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/main
<repo_name>laumaance/Fizzbuzz_game<file_sep>/README.md # Fizzbuzz_draft <file_sep>/scripts/javascripts.js const inputMin = document.getElementById("MinInput"); const inputMax = document.getElementById("MaxInput"); const RefreshBtn = document.getElementById("RefreshBtn"); const ResetBtn = document.getElementById("ResetBtn"); const main = document.getElementById("FizzBuzzContainers"); console.log("Hello world!"); inputMin.value = 1; inputMax.value = 100; const create = function () { //generate 100 divs. while (main.firstChild) { main.removeChild(main.firstChild); }; // for (var i=1; i <= 100; i++) // { // if (i % 15 == 0) // console.log("FizzBuzz"); // else if (i % 3 == 0) // console.log("Fizz"); // else if (i % 5 == 0) // console.log("Buzz"); // else // console.log(i); // } for (let i = 1; i < 101; i++) { let newDiv = document.createElement("div"); let newPar = document.createElement("p"); newDiv.appendChild(newPar); // giving "id" name main.appendChild(newDiv).setAttribute("id", "div#" + i); if (i < inputMin.value || i > inputMax.value) { newDiv.style = "display: none"; } else { if (i % 15 === 0) { newPar.appendChild(document.createTextNode(i + ' = FIZZ BUZZ')); main.appendChild(newDiv).setAttribute("class", "fizbuz"); } else if (i % 3 === 0) { newPar.appendChild(document.createTextNode(i + ' = FIZZ')); main.appendChild(newDiv).setAttribute("class", "fiz"); } else if (i % 5 === 0) { newPar.appendChild(document.createTextNode(i + ' = BUZZ')); main.appendChild(newDiv).setAttribute("class", "buz"); } else { newPar.appendChild(document.createTextNode(i)); main.appendChild(newDiv).setAttribute("class", "num"); } } } }; create(); //set min value inputMin.onkeyup = function (e) { this.value = inputMin.value.replace(/^(0*)/, ""); if (inputMin.value >= 1 && inputMin.value <= 100) { this.value = inputMin.value; } else if (inputMin.value.length === 0) { inputMin.value = null; } else { inputMin.value = null; alert("Incorrect number!"); } if (!((e.keyCode > 95 && e.keyCode < 106) || (e.keyCode > 47 && e.keyCode < 58) || [8, 13, 37, 39].indexOf(e.keyCode) >= 0 )) { return false; } create(); }; //set max value inputMax.onkeyup = function (e) { this.value = inputMax.value.replace(/^(0*)/, ""); if (inputMax.value >= 1 && inputMax.value <= 100) { this.value = inputMax.value; } else if (inputMax.value.length === 0) { inputMax.value = null; } else { inputMax.value = null; alert("Incorrect number!"); } if (!((e.keyCode > 95 && e.keyCode < 106) || (e.keyCode > 47 && e.keyCode < 58) || [8, 13, 37, 39].indexOf(e.keyCode) >= 0 )) { return false; } create(); }; RefreshBtn.onclick = function() { inputMin.value = ""; inputMax.value = ""; create(); }; ResetBtn.onclick = function() { inputMin.value = 1; inputMax.value = 100; create(); }; $(document).ready(function(){ $("#FizzBtn").click(function(){ $(".num, .buz, .fizbuz").toggle(); }); }); $(document).ready(function(){ $("#BuzzBtn").click(function(){ $(".num, .fiz, .fizbuz").toggle(); }); }); $(document).ready(function(){ $("#FizzBuzzBtn").click(function(){ $(".num, .buz, .fiz").toggle(); }); });
7714065419f960b042af601c637f024d3c061738
[ "Markdown", "JavaScript" ]
2
Markdown
laumaance/Fizzbuzz_game
e77818e3db5a1b3f597ae52967f65533d944289a
9d52fbe7f83d668a8a69d0799ed8b1e2cfb0ad85
refs/heads/master
<file_sep>print ("<NAME>") print ("hello") print("Welcome to Gdynia!")
69ee47b1fecbb7599bb4d68e30a6f91d843af916
[ "Python" ]
1
Python
Julkazxcv/projekt-testowy
98e9c7f2ab9ea7c287f1079edc6d8280cd2ea17a
d8cbde35b63df9addbd9fbeef6dad21b8374fd0c
refs/heads/master
<file_sep>#!/bin/bash echo "There are some conventions to follow to ensure that your computer is able to find and execute your Bash scripts." hi="Hello, everyone!" echo $hi. Welcome to our World!
419ab9aa1d714bc8765b606accc4f8b1d6870f44
[ "Shell" ]
1
Shell
7086600/love
110e4fe4d462ad69f81df9e86f14321865914e23
cca2e70d0d681230b04e804d85eb98efa46599a2
refs/heads/master
<repo_name>engKaya/reactnative-train<file_sep>/helloWorldProject/App.js /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from './node_modules/react'; import {Platform, StyleSheet, Text, View, SafeAreaView} from 'react-native'; import axios from 'axios' import FlatListOrnek from "./src/Components/FlatListOrnek"; import PlatformOrnek from './src/Components/PlatformOrnek' export default class App extends Component { state={ name:'', surname:'', loading:true }; componentDidMount(){ axios .get('https://randomuser.me/api/') .then(user => user.data.results[0]) .then(user => { this.setState({ name : user.name.first, surname:user.name.last, loading:false }) }) } render() { const {name,surname,loading} = this.state return ( <View> asfasdasd </View> ); } } //{ loading ? <Text>Loading..</Text>:<Text>{name} {surname}</Text>} const styles = StyleSheet.create({ container:{ backgroundColor:'red', flex:1, alignContent:'center' } }); <file_sep>/loginTrain/App.js import React, { Component } from 'react'; import { View, StyleSheet } from 'react-native'; import LoginPage from './src/Pages/LoginPage'; export default class App extends Component{ render() { return ( <LoginPage/> );} }; const styles = StyleSheet.create({ });<file_sep>/webApi/src/components/Flatlist.js import React, { Component } from 'react'; import {StyleSheet, Text, View, FlatList, Image, TextInput, TouchableHighlight, ActivityIndicator,SafeAreaView} from 'react-native'; import data from '../../data' import axios from 'axios' export default class Flatlist extends Component { state={ backgroundColorOdd: '#ff9292', backgroundColorEven: '#ff6e6e', contacts:[], contactsMain:[], refreshing: false, loading: true, loadMore: true, page:1 } componentDidMount() { this.getContacts() } getContacts = async () => { const {data:{results}} = await axios.get(`https://randomuser.me/api/?results=30&page=${this.state.page}`) const user = [...this.state.contactsMain, ...results] if (this.state.refreshing) user.reverse() this.setState({ contactsMain: user, contacts: user, loading: false, refreshing: false, }); } searchInContacts = (text) => { this.setState({ loading: true, }); const newContacts = this.state.contactsMain.filter(item => { const info = `${item.name.first.toLowerCase()} ${item.name.last.toLowerCase()}` return info.indexOf(text.toLowerCase())>-1 }) this.setState({ contacts: newContacts, loading: false, }); } searchComponent = () => { return( <View style={styles.searchView}> <TextInput placeholder="Ara..." autoCapitalize={'none'} onFocus={()=>{ this.setState({ loadMore:false, }); }} onBlur={()=>{ this.setState({ loadMore:true, }); }} onChangeText={text=>{this.searchInContacts(text)}} style={styles.searchInput} /> </View> ) }; renderFooter = () =>{ if (this.state.loading) { return( <View style={{backgroundColor:'#ffbebe'}}> <ActivityIndicator size="large" color="#3b3b3b"/> </View> ) } return null } onRefresh = () =>{ this.setState({ page:1, refreshing: true }, ()=>{ this.getContacts() }); } loadMore = () =>{ if (this.state.contactsMain != null && this.state.loadMore) { this.setState({ pages:this.state.pages+1, loading:true }, ()=>{ this.getContacts() }) } } renderItem = ({item,index}) => { return( <TouchableHighlight activeOpacity={0.8} underlayColor={index % 2 ===0 ? '#7e4545': '#943d3d'} onPress={ () => {}} > <View style={[styles.touchableObject,{backgroundColor: index % 2 === 0? this.state.backgroundColorEven: this.state.backgroundColorOdd}]}> <View style={styles.imgArea}> <Image style={styles.img} source={{uri:item.picture.medium}}/> </View> <View style={styles.infoArea}> <Text style={styles.nameText}>{item.name.first}</Text> <Text style={styles.nameCorp}>{item.name.last}</Text> </View> </View> </TouchableHighlight> ) } render() { return ( <View> <FlatList ListFooterComponent={this.renderFooter} ListHeaderComponent={this.searchComponent()} data={this.state.contacts} renderItem={this.renderItem} keyExtractor={item=>item.login.uuid} onEndReached={this.loadMore} onEndReachedThreshold={1} refreshing={this.state.refreshing} onRefresh={this.onRefresh} /> </View> ); } }; const styles = StyleSheet.create({ touchableObject:{ padding:10, flex:1, flexDirection:"row", }, imgArea:{ flex: 1.5, }, infoArea:{ flex:5, }, img: { width:75, height:75, borderRadius:37.5 }, nameText:{ color: '#3b3b3b', fontWeight: 'bold', fontSize: 20, textAlign: 'left', }, nameCorp:{ color: '#3b3b3b', fontWeight: 'bold', fontSize: 20, textAlign: 'left', }, searchView:{ paddingVertical: 5, paddingHorizontal: 10, backgroundColor: '#ff9292' }, searchInput:{ backgroundColor: '#faacac', borderWidth:5, borderRadius: 45, borderColor: '#fd6666', paddingHorizontal: 25, }, }); <file_sep>/loginTrain/src/Assets/UI/SignUp.js import React, { Component } from 'react'; import { View, StyleSheet, Text,TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types' export default class SignUp extends Component{ render(){ return( <TouchableOpacity style={[styles.signUpArea,styles.shadow]}> <Text style={styles.signUpText}>Don't you have an Account ?</Text> <Text style={[styles.signUpText,{fontWeight:'bold',}]}>Sign Up</Text> </TouchableOpacity> )}; } const styles = StyleSheet.create({ signUpArea:{ backgroundColor:'#0065e0', marginHorizontal:55, marginBottom:75, justifyContent:'center', alignItems:'center', borderWidth:1.5, borderColor:'#aec0d6', borderRadius:25, padding:10, }, shadow:{ shadowOffset:{width:10,height:25}, shadowColor:'black', shadowOpacity:250, shadowRadius:5, elevation:15, }, signUpText:{ textAlign:'center', fontSize:16, fontWeight:'200', color:'white', } })<file_sep>/helloWorldProject/src/Components/FlatListOrnek.js /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from 'react' import { StyleSheet,Text, View, SafeAreaView,TextInput,TouchableOpacity ,Image, FlatList, TouchableWithoutFeedback} from 'react-native'; import data from '../../data' export default class FlatListOrnek extends Component { state = { text:'', contacts:data, itemTouch:false } renderContactsItem = ({item,index}) =>{ return( <TouchableOpacity style={[styles.itemContainer,{backgroundColor:index % 2 === 1 ? '#f5d7b5' : '#f5e5d3'}]}> <Image style={styles.avatar} source={{uri:item.picture}}/> <View style={styles.textContainer}> <Text style={styles.name}>{item.name}</Text> <Text style={styles.company}>{item.company}</Text> </View> </TouchableOpacity> ) }; searchFilter = text =>{ const newData = data.filter(item=>{ const listItem = `${item.name.toLowerCase()} ${item.company.toLowerCase()}` return listItem.indexOf(text.toLowerCase()) > -1; }) this.setState({ contacts: newData }) } renderHeader = () =>{ const {text} = this.state return( <View style={styles.searchContainer}> <TextInput value={this.text} onChangeText = {text=>{this.setState({ text }); this.searchFilter(text)}} style={styles.searchInput} placeholder='Ara..'/> </View> ) }; render() { return ( <SafeAreaView> <FlatList ListHeaderComponent={this.renderHeader()} renderItem={this.renderContactsItem} //<---ı buraya keyExtractor={(item)=>item._id} // | data={this.state.contacts} ///Buradan --| /> </SafeAreaView> ); } } const styles = StyleSheet.create({ itemContainer:{ flex:1, flexDirection:"row", paddingVertical:10, borderBottomWidth:2, borderBottomColor:"#f7b777" }, avatar:{ width:60, height:60, borderRadius:30, marginHorizontal:10 }, textContainer:{ justifyContent:"space-around", }, name:{ fontSize:20, fontWeight:'bold' }, searchContainer:{ backgroundColor:'#eda24c', padding:5 }, searchInput:{ borderWidth:2, borderColor:'#f5cea2', borderRadius:25, textAlign:'center', paddingHorizontal:35, marginHorizontal:15 } });<file_sep>/loginTrain/src/Components/LoginForm.js import React, { Component } from 'react'; import { View, StyleSheet, Text, ScrollView, KeyboardAvoidingView } from 'react-native'; import TextInputO from '../Assets/UI/TextInputO' import MyButton from '../Assets/UI/MyButton'; export default class LoginPage extends Component{ render() { return ( <View> <Text style={styles.signInText}>Sign In</Text> <TextInputO placeholder='Username' returnKeyType={"next"} onSubmitEditing={()=>this.passwordInput.focus()} /> <TextInputO placeholder='<PASSWORD>' secureTextEntry={true} inputRef={input=>this.passwordInput= input} /> <MyButton bgColor={"#0065e0"} text={"Sign In"} /> </View> )}; } const styles = StyleSheet.create({ signInText:{ marginVertical:10, fontSize:16, color:'#333', fontWeight:"bold" } }) <file_sep>/webApi/App.js import React, {Component} from 'react'; import { StyleSheet, View, Button, Text, SafeAreaView } from 'react-native'; import Flatlist from './src/components/Flatlist'; import RandomUser from './src/components/RandomUser'; import axios from 'axios'; export default class App extends Component { render() { return ( <SafeAreaView style={styles.safeArea}> <Flatlist/> </SafeAreaView> ) } }; const styles = StyleSheet.create({ safeArea:{ backgroundColor: '#ffbebe', flex:1} }); <file_sep>/loginTrain/src/Assets/UI/MyButton.js import React, { Component } from 'react'; import { View, StyleSheet, Text,TouchableOpacity } from 'react-native'; import PropTypes from 'prop-types' export default class MyButton extends Component{ render() { const {bgColor} = this.props return( <View> <TouchableOpacity style={[styles.myButtonStyle,{backgroundColor:bgColor}]}> <Text style={styles.signInStyle}>{this.props.text}</Text> </TouchableOpacity> </View> ) }} MyButton.propTypes = { text: PropTypes.string.isRequired, bgColor : PropTypes.string, } const styles = StyleSheet.create({ myButtonStyle:{ borderColor:'#004aa3', justifyContent:'center', alignItems:'center', borderWidth:2, padding:12.5, marginRight:35, marginVertical:15, marginBottom:25, borderRadius:20, }, signInStyle:{ color:'white', fontWeight:'bold', fontSize:16 } })
8c9293ed79674205837d9a1c8f33d3464c7332c1
[ "JavaScript" ]
8
JavaScript
engKaya/reactnative-train
933cf518d320bc30c08a0d0b80871d093dea673b
fb141b4488dd85238ad1f2ef97aec2447e8606a2
refs/heads/master
<file_sep><!doctype html> <?php /* Template Name: index */ ?> <html lang="pt-Br"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/bootstrap.min.css"> <link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/estilo.css" type="text/css"> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css"/> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css"/> <title>Agencia 947</title> </head> <body data-spy="scroll" data-target="#collapsibleNavbar" date-offset="80" id="page-top"> <div class="row"> <div class="col-sm-12"> <nav class="navbar navbar-expand-sm navbar-dark fixed-top" role="navigation"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class="brand rolagem" href="#page-top"><img src="<?php bloginfo('template_url'); ?>/images/logo.png" alt=""></a> </li> <li class="nav-item"> <a class="nav-link rolagem" href="#page-top"><span>HOME</span></a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#servicos">SERVIÇOS</a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#porque">PORQUÊ</a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#sec2">947?</a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#portifolio">PORTIFÓLIO</a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#clientes">CLIENTES</a> </li> <li class="nav-item active"> <a class="nav-link rolagem" href="#contato">CONTATO</a> </li> </ul> </div> </nav> </div> </div> <section> <div class="row"> <div class="col-sm-12"> <div class="banner1"> <img class="img-fluid" src="<?php bloginfo('template_url'); ?>/images/img1.png" alt=""> </div> </div> </div> </section> <section id="servicos"> <div class="row"> <div class="col-sm-12"> <div class="container"> <h3>Procurando resultados ?</h3> <p class="p1 text-center">Vamos ajudá-lo com isso.</p> <p class="p2 text-center">Dentro da agência desenvolvemos uma série de serviços focados no<br> negócio do cliente. Trabalhamos embasados em 3 principais pilares:<br> Confiança, entrega com responsabilidadee experiência do consumidor.</p> <div class="row icons"> <div class="m-2"> <img class="tamanho" src="<?php bloginfo('template_url'); ?>/images/icon1.png" alt=""> <p class="text-center espaco">Ativação<br> de Marca</p> </div> <div class="m-2"> <img class="tamanho" src="<?php bloginfo('template_url'); ?>/images/icon2.png" alt=""> <p class="text-center espaco">Planejamento<br>criação e execução<br>de ações<br>promocionais</p> </div> <div class="m-2"> <img class="tamanho" src="<?php bloginfo('template_url'); ?>/images/icon3.png" alt=""> <p class="text-center espaco">Eventos<br>corporativos</p> </div> <div class="m-2"> <img class="tamanho" src="<?php bloginfo('template_url'); ?>/images/icon4.png" alt=""> <p class="text-center espaco">Ações de<br>relacionamento</p> </div> <div class="m-2"> <img class="tamanho" src="<?php bloginfo('template_url'); ?>/images/icon5.png" alt=""> <p class="text-center espaco">Gerenciamento de<br>influenciadores</p> </div> </div> </div> </div> </div> </section> <section id="porque"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h3>Nosso foco é solucionar<br>os problemas de posicionamento<br> de marca da sua empresa.</h3> <hr> </div> </div> <div class="row"> <div class="col-sm-6 alinhamentoesquerda"> <p class="p3">Por quê?</p> <img src="<?php bloginfo('template_url'); ?>/images/img2.png" alt=""> <p class="p4"> Uma amizade que virou negócio.<br> No início de 2017. <NAME><br> (DF) convidou seus grandes amigos<br> <NAME> (RJ). <NAME><br> (MG) e <NAME> (AL) para<br> passar um final de semanaem sua<br> casa. O endereço? Brasilia 947. </p> </div> <div class="col-sm-6 alinhamentodireita"> <p class="p5"> A conexão entre todos foi<br> instantânea e a amizade entre<br> os 4 só cresceu. Durante o ano<br> foram diversos encontros que<br> passaram a não ser somente de<br> lazer mas também de negócios<br> e networking.<br><br> Não demorou para perceberem<br> uma oportunidade de mercado<br> que era unânime em suas<br> cidades: Nos 4 cantos do Brasil<br> identificaram carências<br> semelhantes de posicionamento<br> de marca, ativação de consumo<br> e relacionamento. Era<br> necessário maior conexão entre<br> pessoas, marcas e empresas e<br> de conexão eles entendem bem.<br> Nascia assim a Agência 947. </p> </div> </div> </div> </div> </section> <section id="sec2"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>As pessoas por trás<br>de tudo isso:</h2> </div> </div> <div class="row mouseOver"> <div class="col-sm-6 sec2esquerda"> <img class="fotos" src="<?php bloginfo('template_url'); ?>/images/foto1.png" alt=""> <div class="efeito "> <img class="fv" src="<?php bloginfo('template_url'); ?>/images/fv.png" alt=""> <a href="#" target="_blank"><img class="insta" src="<?php bloginfo('template_url'); ?>/images/insta.png" alt=""></a> <a href="#" target="_blank"><img class="face" src="<?php bloginfo('template_url'); ?>/images/face.png" alt=""></a> <a href="#" target="_blank"><img class="twitter" src="<?php bloginfo('template_url'); ?>/images/icontwitter.png" alt=""></a> <a href="#" target="_blank"><img class="linkedin" src="<?php bloginfo('template_url'); ?>/images/iconlinke.png" alt=""></a> <p><NAME></p> </div> </div> <div class="insta"> </div> <div class="col-sm-6 sec2direita"> <img class="fotos" src="<?php bloginfo('template_url'); ?>/images/foto2.png" alt=""> <div class="efeitoLeft"> <img class="fv" src="<?php bloginfo('template_url'); ?>/images/fv.png" alt=""> <a href="#" target="_blank"><img class="insta" src="<?php bloginfo('template_url'); ?>/images/insta.png" alt=""></a> <a href="#" target="_blank"><img class="face" src="<?php bloginfo('template_url'); ?>/images/face.png" alt=""></a> <a href="#" target="_blank"><img class="twitter" src="<?php bloginfo('template_url'); ?>/images/icontwitter.png" alt=""></a> <a href="#" target="_blank"><img class="linkedin" src="<?php bloginfo('template_url'); ?>/images/iconlinke.png" alt=""></a> <p>ANA LADEIRA</p> </div> </div> </div> <div class="row sec2bottom mouseOver"> <div class="col-sm-6 sec2esquerda"> <img class="fotos" src="<?php bloginfo('template_url'); ?>/images/foto3.png" alt=""> <div class="efeito"> <img class="fv" src="<?php bloginfo('template_url'); ?>/images/fv.png" alt=""> <a href="#" target="_blank"><img class="insta" src="<?php bloginfo('template_url'); ?>/images/insta.png" alt=""></a> <a href="#" target="_blank"><img class="face" src="<?php bloginfo('template_url'); ?>/images/face.png" alt=""></a> <a href="#" target="_blank"><img class="twitter" src="<?php bloginfo('template_url'); ?>/images/icontwitter.png" alt=""></a> <a href="#" target="_blank"><img class="linkedin" src="<?php bloginfo('template_url'); ?>/images/iconlinke.png" alt=""></a> <p><NAME></p> </div> </div> <div class="col-sm-3 sec2direita"> <img class="fotos" src="<?php bloginfo('template_url'); ?>/images/foto4.png" alt=""> <div class="efeitoLeft"> <img class="fv" src="<?php bloginfo('template_url'); ?>/images/fv.png" alt=""> <a href="#" target="_blank"><img class="insta" src="<?php bloginfo('template_url'); ?>/images/insta.png" alt=""></a> <a href="#" target="_blank"><img class="face" src="<?php bloginfo('template_url'); ?>/images/face.png" alt=""></a> <a href="#" target="_blank"><img class="twitter" src="<?php bloginfo('template_url'); ?>/images/icontwitter.png" alt=""></a> <a href="#" target="_blank"><img class="linkedin" src="<?php bloginfo('template_url'); ?>/images/iconlinke.png" alt=""></a> <p><NAME></p> </div> </div> </div> </div> </section> <section id="portifolio"> <div class="container"> <div class="row"> <div class="col-sm-12"> <h2>Portifólio</h2> <p class="p6">Trabalhos incríveis focados em resultado</p> </div> </div> <div class="row"> <div class="col-sm-12"> <section class="carousel center slider w-75 h-75"> <?php if( have_rows('carousel') ): // loop through the rows of data while ( have_rows('carousel') ) : the_row(); ?> <div class="mouseOver"> <img src="<?php the_sub_field('imagem'); ?>" alt=""> <div class="efeitoCarousel"> <img src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p><?php the_sub_field('titulo'); ?></p> </div> </div> <?php endwhile; else : // no rows found endif; ?> <!-- <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel1.png"> <div class="efeitoCarousel"> <img src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel2.png"> <div class="efeitoCarousel"> <img class="bg" src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel3.png"> <div class="efeitoCarousel"> <img class="bg" src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel4.png"> <div class="efeitoCarousel"> <img class="bg" src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel5.png"> <div class="efeitoCarousel"> <img class="bg" src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> <div class="mouseOver"> <img src="<?php bloginfo('template_url'); ?>/images/imgcarrousel6.png"> <div class="efeitoCarousel"> <img class="bg" src="<?php bloginfo('template_url'); ?>/images/bgcarrousel.png" alt=""> <p>Campanha<br>Uber Halloween</p> </div> </div> --> </section> </div> </div> </div> </section> <section id="clientes"> <div class="container"> <div class="row"> <div class="col session-cli"> <h3>Nossos clientes</h3> </div> </div> <div class="row justify-content-center"> <div class="col-sm-9"> <?php // loop through the rows of data while ( have_rows('clientes') ) : the_row(); ?> <img class="text-center efeitoClientes" src="<?php the_sub_field('imagem'); ?>" alt=""> <?php endwhile;?> </div> </div> </div> </section> <section id="contato"> <div class="row"> <div class="col verde"> <h3>Fale com a gente:</h3> </div> </div> <div class="container"> <div class="row"> <div class="col-sm-12 contato"> <div class="row pt-4 justify-content-center"> <div class="col-9"> <form> <div class="row"> <div class="col-12 col-sm"> <input type="text" class="form-control" placeholder="Seu nome"> </div> <div class="col-12 col-md mt-4 mt-md-0"> <input type="email" class="form-control" placeholder="Seu email"> </div> <div class="col-12 col-md mt-4 mt-md-0"> <input type="text" class="form-control" placeholder="assunto"> </div> </div> <div class="row mt-4"> <div class="col"> <textarea class="form-control" name="message" rows="4" placeholder="mensagem"></textarea> </div> </div> <div class="row mt-4"> <div class="col text-right"> <button type="submit" class="btn btn-verde">Enviar<span> <img src="<?php bloginfo('template_url'); ?>/images/iconbt.png" alt=""></span></button> </div> </div> </form> </div> </div> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-sm-12"> <div class="row align-items-top text-center text-md-left"> <div class="col-12 col-sm-6 col-md-4 footerEsquerda"> <a href="#" target="_blank"><img class="imgFooter" src="<?php bloginfo('template_url'); ?>/images/img2.png" alt=""></a> </div> <div class="col-12 col-sm-6 col-md-4 mt-4 mt-sm-0 contatoLeft"> <h4><strong>Contato:</strong></h4><br> <p><EMAIL></p><br> <p>21 99565-8585<br>21 99807-7676<br>21 96869-7220</p><br> <p>Rio de Janeiro<br><br>Belo Horizonte<br><br>São Paulo<br><br>Brasília<br><br>Maceió</p> </div> <div class="col-12 col-md-4 mt-5 mt-md-0 iconsLeft"> <h4><strong>Siga-nos:</strong></h4> <div class="iconEspaco"> <a href="#" target="_blank"><span><img src="<?php bloginfo('template_url'); ?>/images/iconface.png" alt=""></span></a> <a href="#" target="_blank"><span><img src="<?php bloginfo('template_url'); ?>/images/iconinsta.png" alt=""></span></a> </div> </div> </div> <div class="row mt-5"> <div class="col text-center text-white"> © 2018 powered by <a href="https://www.peppery.com.br" target="_blank"><span class="span"><img src="<?php bloginfo('template_url'); ?>/images/iconpeppery.png" alt=""></span></a> </div> </div> </div> </div> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="<?php bloginfo('template_url'); ?>/js/bootstrap.min.js"></script> <script src="<?php bloginfo('template_url'); ?>/js/efeitoMouse.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.js"></script> </body> </html><file_sep>/* FUNCTION MOUSEOVER PORTIFÓLIO */ $(document).ready(function(){ $(".efeito, .efeitoLeft").mouseenter(function(){ $(this).css("opacity", "1"); }); $(".efeito, .efeitoLeft").mouseleave(function(){ $(this).css("opacity", "0"); }); }); /* FUNCTION MOUSEOVER PORTIFÓLIO */ /* FUNCTION MOUSEOVER CAROUSEL */ $(document).ready(function(){ $(".efeitoCarousel").mouseenter(function(){ $(this).css("opacity", "1"); }); $(".efeitoCarousel").mouseleave(function(){ $(this).css("opacity", "0"); }); }); /* FUNCTION MOUSEOVER CAROUSEL */ /* FUNCTION CAROUSEL */ $(document).ready(function(){ $('.carousel').slick({ infinite: true, speed: 500, slidesToShow: 3, slidesToScroll: 4, rows: 2, }); }); /* FUNCTION MOUSEOVER CAROUSEL */ /* SCROOL DA PÁGINA */ $(function(){ $(".rolagem").click(function() { var href =$(this).attr("href"); $("body, html").animate({ scrollTop: $(href).offset().top }, 1000) }); }); /* SCROOL DA PÁGINA */ /* EFEITO GRAY CLIENTES */ $(document).ready(function(){ $(".efeitoClientes").mouseenter(function(){ $(this).css("filter", "none"); }); $(".efeitoClientes").mouseleave(function(){ $(this).css("filter", "grayscale(100%)"); }); }); /* EFEITO GRAY CLIENTES */
962861aed8d1f1e78abf25296c8968722f515914
[ "JavaScript", "PHP" ]
2
PHP
renanmurilo/agencia947
71921550b9624fd8df5074a83aec7b04db4fe006
90f493a4b344b16961f5d2a61cabc15bdca96628
refs/heads/master
<file_sep>package com.apap.tugas1.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.apap.tugas1.model.PegawaiModel; import com.apap.tugas1.repository.PegawaiDb; @Service @Transactional public class PegawaiServiceImpl implements PegawaiService { @Autowired private PegawaiDb pegawaiDb; @Override public PegawaiModel getPegawaiDetailByNip(String nip) { return pegawaiDb.findByNip(nip); } @Override public PegawaiModel getOldestPegawai(List<PegawaiModel> listPegawai) { PegawaiModel oldest = null; for(PegawaiModel pegawai: listPegawai) { if(oldest == null) { oldest = pegawai; } else { if(pegawai.getTanggalLahir().compareTo(oldest.getTanggalLahir()) < 0) oldest = pegawai; } } return oldest; } @Override public PegawaiModel getYoungestPegawai(List<PegawaiModel> listPegawai) { PegawaiModel youngest = null; for(PegawaiModel pegawai: listPegawai) { if(youngest == null) { youngest = pegawai; } else { if(pegawai.getTanggalLahir().compareTo(youngest.getTanggalLahir()) > 0) youngest = pegawai; } } return youngest; } @Override public void add(PegawaiModel pegawai) { pegawaiDb.save(pegawai); } @Override public String generateNip(PegawaiModel pegawai) { String kodeInstansi = String.valueOf(pegawai.getInstansi().getId()); String[] dateSplit = String.valueOf(pegawai.getTanggalLahir().toString()).split("-"); String tahun = dateSplit[0]; String bulan = dateSplit[1]; String tanggal = dateSplit[2]; tahun = tahun.substring(2, 4); String tahunMasuk = pegawai.getTahunMasuk(); // generate nomor urut int noUrut; List<PegawaiModel> listPegawai = pegawaiDb.findByInstansiAndTanggalLahirAndTahunMasukOrderByNipAsc(pegawai.getInstansi(), pegawai.getTanggalLahir(), pegawai.getTahunMasuk()); if(listPegawai.size() == 0) { noUrut = 1; } else { PegawaiModel lastPegawai = listPegawai.get(listPegawai.size() - 1); noUrut =Integer.parseInt(lastPegawai.getNip().substring(14, 16)) + 1; } String noUrutStr; if(noUrut == 0) { noUrutStr = "01"; } else if (noUrut < 10) { noUrutStr = "0"; noUrutStr += String.valueOf(noUrut); } else { noUrutStr = String.valueOf(noUrut); } // END generate nomor urut String nip = kodeInstansi + tanggal + bulan + tahun + tahunMasuk + noUrutStr; return nip; } }<file_sep>package com.apap.tugas1.service; import java.util.List; import com.apap.tugas1.model.JabatanModel; public interface JabatanService { List<JabatanModel> getAllJabatan(); void add(JabatanModel jabatan); JabatanModel getJabatanDetailById(long id); void deleteJabatanById(long id); }<file_sep>package com.apap.tugas1.service; import java.util.List; import com.apap.tugas1.model.PegawaiModel; public interface PegawaiService { PegawaiModel getPegawaiDetailByNip(String nip); PegawaiModel getOldestPegawai(List<PegawaiModel> listPegawai); PegawaiModel getYoungestPegawai(List<PegawaiModel> listPegawai); void add(PegawaiModel pegawai); String generateNip(PegawaiModel pegawai); } <file_sep>package com.apap.tugas1.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.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.apap.tugas1.model.JabatanModel; import com.apap.tugas1.service.JabatanService; @Controller public class JabatanController { @Autowired private JabatanService jabatanService; @RequestMapping(value = "/jabatan/tambah", method = RequestMethod.GET) private String addJabatan(Model model) { model.addAttribute("jabatan", new JabatanModel()); model.addAttribute("title", "Tambah Jabatan"); return "add-jabatan"; } @RequestMapping(value = "/jabatan/tambah", method = RequestMethod.POST) private String addJabatan(@ModelAttribute JabatanModel jabatan, Model model) { jabatanService.add(jabatan); model.addAttribute("msg", "Data jabatan berhasil dimasukkan."); model.addAttribute("title", "Sukses"); return "message"; } @RequestMapping(value = "/jabatan/view", method = RequestMethod.GET) private String viewJabatan(@RequestParam(value = "idJabatan") long idJabatan, Model model) { JabatanModel jabatan = jabatanService.getJabatanDetailById(idJabatan); model.addAttribute("jabatan", jabatan); model.addAttribute("jumlahKaryawan", jabatan.getListPegawai().size()); model.addAttribute("title", "Detail Jabatan"); return "detail-jabatan"; } @RequestMapping(value = "/jabatan/viewall", method = RequestMethod.GET) private String viewAllJabatan(Model model) { List<JabatanModel> listJabatan = jabatanService.getAllJabatan(); model.addAttribute("listJabatan", listJabatan); model.addAttribute("title", "Lihat Semua Jabatan"); return "view-all-jabatan"; } @RequestMapping(value = "/jabatan/ubah", method = RequestMethod.GET) private String updateJabatan(@RequestParam(value = "idJabatan") long idJabatan, Model model) { JabatanModel jabatan = jabatanService.getJabatanDetailById(idJabatan); model.addAttribute("jabatan", jabatan); model.addAttribute("title", "Ubah Jabatan"); return "update-Jabatan"; } @RequestMapping(value = "/jabatan/ubah", method = RequestMethod.POST) private String updateJabatan(@ModelAttribute JabatanModel jabatan, Model model) { jabatanService.add(jabatan); model.addAttribute("msg", "Data jabatan telah diubah."); model.addAttribute("title", "Sukses"); return "message"; } @RequestMapping(value = "/jabatan/hapus", method = RequestMethod.POST) private String deleteJabatan(@ModelAttribute JabatanModel jabatan, Model model) { JabatanModel jabatanTemp = jabatanService.getJabatanDetailById(jabatan.getId()); if(jabatanTemp.getListPegawai().isEmpty()) { jabatanService.deleteJabatanById(jabatanTemp.getId()); model.addAttribute("msg", "Data jabatan telah dihapus."); model.addAttribute("title", "Sukses"); } else { model.addAttribute("msg", "Data jabatan gagal diubah."); model.addAttribute("title", "Gagal"); } return "message"; } }
24adcbbbb7fc6d9f5cffc8691915f3418d2b9af8
[ "Java" ]
4
Java
Apap-2018/tugas1_1606917790
f36cbaeb3869dbda18c9369ffa37b22e3a95d954
61e755be14a069cef3bd4e556ae0dab5f257e167
refs/heads/master
<repo_name>milanmilan7711/ITBootcampQAFinalProject<file_sep>/src/tests/DSignInTest.java package tests; import java.util.concurrent.TimeUnit; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import pages.DSignInPage; import pages.ERegistrationPage; import utils.ExcelUtils; public class DSignInTest extends ATestTemplate { @Test public void testingUserSignIn() throws InterruptedException { SoftAssert sa = new SoftAssert(); DSignInPage signInPage = new DSignInPage(driver, locators, waiter); ExcelUtils petStoreData = new ExcelUtils(); petStoreData.setExcell("data/pet-store-data.xlsx"); petStoreData.setWorkSheet(1); for (int i = 1; i < petStoreData.getRowNumber(); i++) { driver.navigate().to(this.locators.getProperty("d_url")); String userID = petStoreData.getDataAt(i, 0); String password = <PASSWORD>.getDataAt(i, 1); signInPage.userLogin(userID, password); sa.assertTrue(signInPage.signInPassed()); } petStoreData.closeExcell(); sa.assertAll(); } } <file_sep>/README.md # ITBootcampQAFinalProject ITBootcampQAFinalProject is used for testing the functionality of the website Target URL: https://petstore.octoperf.com/ Target Browser: Chrome Browser version: 81.0.4044.122 **Used libraries:** * TestNG automation testing framework * Selenium portable framework for testing web applications * Apache POI library for manipulating various file formats **The following website functionalities are tested:** * Enter store * Links validation (left menu, top menu, image menu, sign in) * User registration * User login * Add to cart * Cart validation (all added items are correct) * Cookies ## The project has 3 packages * pages * tests * utils All packages are located in the `src` folder ## Package `pages` contains * APageTemplate * BHomePage * CPetStoreMenuPage * DSignInPage * ERegistrationPage * FStoreItemPage * GCartPage ## Package `tests` contains * ATestTemplate * BEnterStoreTest * CPetStoreMenuTest * DSignInTest * ERegistrationPageTest * GCartTes ## Package `utils` contains * ExcelUtils <file_sep>/src/tests/BEnterStoreTest.java package tests; import org.testng.Assert; import org.testng.annotations.Test; import pages.BHomePage; public class BEnterStoreTest extends ATestTemplate { @Test public void enterStoreTest() throws InterruptedException { driver.navigate().to(this.locators.getProperty("b_url")); BHomePage hp = new BHomePage(driver, locators, waiter); hp.enterStore(); Assert.assertTrue(hp.inStore()); } }
b5acfdc10dc38a814ccb564ccfaea14219221597
[ "Markdown", "Java" ]
3
Java
milanmilan7711/ITBootcampQAFinalProject
4d1148904b1e09be474e56d0f6d841fe9d5b08c1
abdedecd814146bb32cb9ec5d39ce4225eca9365
refs/heads/master
<repo_name>bernardoariel/colegio2021<file_sep>/controladores/caja.controlador.php <?php class ControladorCaja{ /*============================================= MOSTRAR CAJA =============================================*/ static public function ctrMostrarCaja($item, $valor){ $tabla = "caja"; $respuesta = ModeloCaja::mdlMostrarCaja($tabla, $item, $valor); return $respuesta; } /*============================================= INGRESAR CAJA =============================================*/ static public function ctrIngresarCaja($item, $datos){ $tabla = "caja"; $respuesta = ModeloCaja::mdlIngresarCaja($tabla,$datos); return $respuesta; } /*============================================= EDITAR CAJA =============================================*/ static public function ctrEditarCaja($item, $datos){ $tabla = "caja"; $respuesta = ModeloCaja::mdlEditarCaja($tabla,$datos); return $respuesta; } } <file_sep>/controladores/ws.controlador.php <?php class ControladorWs{ /*============================================= MOSTRAR ESCRIBANOS WEBSERVICE =============================================*/ static public function ctrMostrarEscribanosWs($item, $valor){ $tabla = "escribanos"; $respuesta = ModeloWs::mdlMostrarEscribanosWs($tabla, $item, $valor); return $respuesta; } /*============================================= PONER A NULL TODOS LOS ESCRIBANOS DEL WS =============================================*/ static public function ctrNullEscribanosWs(){ $tabla = "escribanos"; $respuesta = ModeloWs::mdlNullEscribanosWs($tabla); return $respuesta; } /*============================================= CAMBIAR EL ESTADO DE LOS ESCRIBANOS =============================================*/ static public function ctrModificarEstadosWs($datos){ $tabla = "escribanos"; $respuesta = ModeloWs::mdlModificarEstadosWs($tabla,$datos); return $respuesta; } } <file_sep>/controladores/modelos.controlador.php <?php class ControladorModelos{ /*============================================= CREAR CATEGORIAS =============================================*/ static public function ctrCrearModelo(){ if(isset($_POST["nuevoModelo"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoModelo"])){ $tabla = "modelo"; $datos = $_POST["nuevoModelo"]; $datos = array("nombre" => strtoupper($_POST["nuevoModelo"]), "detalle" => strtoupper($_POST["nuevoDetalle"])); $respuesta = ModeloModelos::mdlIngresarModelo($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido guardada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "losmodelos"; } }) </script>'; } }else{ echo '<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "losmodelos"; } }) </script>'; } } } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function ctrMostrarModelos($item, $valor){ $tabla = "modelo"; $respuesta = ModeloModelos::mdlMostrarModelos($tabla, $item, $valor); return $respuesta; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function ctrEditarModelo(){ if(isset($_POST["editarModelo"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarModelo"])){ $tabla = "modelos"; $datos = array("modelo"=>$_POST["editarModelo"], "id"=>$_POST["idModelo"]); $respuesta = ModeloModelos::mdlEditarModelos($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido cambiada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } } } /*============================================= BORRAR CATEGORIA =============================================*/ static public function ctrBorrarModelos(){ if(isset($_GET["idModelo"])){ $tabla ="modelos"; $datos = $_GET["idModelo"]; $respuesta = ModeloModelos::mdlBorrarModelo($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } } } } <file_sep>/ajax/ctacorriente.ajax.php <?php require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; require_once "../controladores/cuotas.controlador.php"; require_once "../modelos/cuotas.modelo.php"; class AjaxCtaCorrienteVenta{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxVerVenta(){ $item = "id"; $valor = $_POST["idVenta"]; $respuesta = ControladorVentas::ctrMostrarVentas($item, $valor); echo json_encode($respuesta); } /*============================================= VER CUOTA =============================================*/ public function ajaxVerCuota(){ $item = "id"; $valor = $_POST["idCuota"]; $respuesta = ControladorCuotas::ctrMostrarCuotas($item, $valor); echo json_encode($respuesta); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerEscribano(){ $itemCliente = "id"; $valorCliente = $_POST["idEscribano"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo json_encode($respuestaCliente); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerArt(){ $item = "id"; $valor = $_POST["idVentaArt"]; $respuesta = ControladorVentas::ctrMostrarVentas($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerArtCuota(){ $item = "id"; $valor = $_POST["idCuotaArt"]; $respuesta = ControladorCuotas::ctrMostrarCuotas($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerPagoDerecho(){ $item = "id"; $valor = $_POST["idPagoDerecho"]; $respuesta = ControladorVentas::ctrMostrarVentas($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } } /*============================================= EDITAR CUENTA CORRIENTE =============================================*/ if(isset($_POST["idVenta"])){ $seleccionarFactura = new AjaxCtaCorrienteVenta(); $seleccionarFactura -> ajaxVerVenta(); } /*============================================= EDITAR CUENTA CORRIENTE =============================================*/ if(isset($_POST["idCuota"])){ $seleccionarFactura = new AjaxCtaCorrienteVenta(); $seleccionarFactura -> ajaxVerCuota(); } /*============================================= VER CUENTA CORRIENTE CLIENTE =============================================*/ if(isset($_POST["idEscribano"])){ $verEscribano = new AjaxCtaCorrienteVenta(); $verEscribano -> ajaxVerEscribano(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idVentaArt"])){ $verTabla = new AjaxCtaCorrienteVenta(); $verTabla -> ajaxVerArt(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idCuotaArt"])){ $verTabla = new AjaxCtaCorrienteVenta(); $verTabla -> ajaxVerArtCuota(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idPagoDerecho"])){ $verTabla = new AjaxCtaCorrienteVenta(); $verTabla -> ajaxVerPagoDerecho(); } <file_sep>/vistas/modulos/update.php <?php $desarrollo = 0; if ($desarrollo==1){ ?> <div class="content-wrapper"> <section class="content-header"> <h1> Update <small>Panel de Control</small> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Update</li> </ol> </section> <section class="content"> <h1>esta funcion esta desactivada para el desarrollo</h1> </section> <?php }else{ ?> <div class="content-wrapper"> <section class="content-header"> <h1> Update <small>Panel de Control</small> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Update</li> </ol> </section> <section class="content"> <div class="col-md-4"> <!-- Info Boxes Style 2 --> <div class="info-box bg-yellow"> <span class="info-box-icon"><i class="ion ion-ios-pricetag-outline"></i></span> <?php #ELIMINAR PRODUCTOS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('productos'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $orden = "id"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); $cantidadProductos = count($productos); $cant=0; foreach ($productos as $key => $value) { # code... if($value['ver']==1){ $tabla ="productos"; $datos = array("id" => $value["id"], "nombre" => strtoupper($value["nombre"]), "descripcion" => strtoupper($value["descripcion"]), "codigo" => $value["codigo"], "nrocomprobante" => $value["nrocomprobante"], "cantventa" => $value["cantventa"], "id_rubro" => $value["id_rubro"], "cantminima" => $value["cantminima"], "cuotas" => $value["cuotas"], "importe" => $value["importe"], "obs" => $value["obs"]); $cant ++; } #registramos los productos $respuesta = ModeloEnlace::mdlIngresarProducto($tabla, $datos); } $porcentaje = ($cant * 100) /$cantidadProductos; ?> <div class="info-box-content"> <span class="info-box-text">Productos</span> <span class="info-box-number"><?php echo $cantidadProductos ;?></span> <div class="progress"> <div class="progress-bar" style="width: <?php echo $porcentaje; ?>%"></div> </div> <span class="progress-description"> Se actualizaron <?php echo round($porcentaje,0); ?>% de productos (<?php echo $cant;?>) </span> </div> <!-- /.info-box-content --> </div> <?php #ELIMINAR PRODUCTOS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('escribanos'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $orden = "id"; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor, $orden); $cantidadEscribanos = count($escribanos); $cant=0; foreach ($escribanos as $key => $value) { # code... $tabla = "escribanos"; $datos =array("id"=>$value["id"], "nombre"=>strtoupper($value["nombre"]), "documento"=>$value["documento"], "id_tipo_iva"=>$value["id_tipo_iva"], "tipo"=>$value["tipo"], "facturacion"=>$value["facturacion"], "tipo_factura"=>$value["tipo_factura"], "cuit"=>$value["cuit"], "direccion"=>strtoupper($value["direccion"]), "localidad"=>strtoupper($value["localidad"]), "telefono"=>$value["telefono"], "email"=>strtoupper($value["email"]), "id_categoria"=>$value["id_categoria"], "id_escribano_relacionado"=>$value["id_escribano_relacionado"], "id_osde"=>$value["id_osde"], "ultimolibrocomprado"=>strtoupper($value["ultimolibrocomprado"]), "ultimolibrodevuelto"=>strtoupper($value["ultimolibrodevuelto"])); $cant ++; #registramos los productos $respuesta = ModeloEnlace::mdlIngresarEscribano($tabla, $datos); } $porcentaje = ($cant * 100) /$cantidadEscribanos; ?> <div class="info-box bg-green"> <span class="info-box-icon"><i class="fa fa-users"></i></span> <div class="info-box-content"> <span class="info-box-text">Escribanos</span> <span class="info-box-number"><?php echo $cantidadEscribanos;?></span> <div class="progress"> <div class="progress-bar" style="width: <?php echo $porcentaje; ?>%"></div> </div> <span class="progress-description"> Se actualizaron <?php echo round($porcentaje,0); ?>% de Escribanos (<?php echo $cant;?>) </span> </div> <!-- /.info-box-content --> </div> <?php #ELIMINAR CUOTAS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('cuotas'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $ventas = ControladorVentas::ctrMostrarCuotas($item, $valor); $cantidadVentas = count($ventas); $cant=0; foreach ($ventas as $key => $value) { # code... $tabla = "cuotas"; $datos = array("id"=>$value["id"], "fecha"=>$value["fecha"], "tipo"=>$value["tipo"], "id_cliente"=>$value["id_cliente"], "nombre"=>$value["nombre"], "documento"=>$value["documento"], "productos"=>$value["productos"], "total"=>$value["total"]); $cant ++; #registramos los productos $respuesta = ModeloEnlace::mdlIngresarVenta($tabla, $datos); } $porcentaje = ($cant * 100) /$cantidadVentas; ?> <div class="info-box bg-red"> <span class="info-box-icon"><i class="ion ion-ios-cloud-download-outline"></i></span> <div class="info-box-content"> <span class="info-box-text">DEUDORES</span> <span class="info-box-number"><?php echo $cantidadVentas;?></span> <div class="progress"> <div class="progress-bar" style="width: <?php echo $porcentaje; ?>%"></div> </div> <span class="progress-description"> Se actualizaron <?php echo round($porcentaje,0); ?>% de Ventas (<?php echo $cant+1;?>) </span> </div> <!-- /.info-box-content --> </div> <?php $ventas = ControladorEnlace::ctrMostrarUltimaActualizacion(); echo '<pre>Ultima Actualizacion::: '; print_r($ventas['fechacreacion']); echo '</pre>'; ?> </section> </div> <?php } ?><file_sep>/ajax/imprimiretiqueta.php <?php #FUNCION PARA ÑS Y ACENTOS function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } #LLAMO A LAS LIBRERIAS require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; require_once "../controladores/empresa.controlador.php"; require_once "../modelos/empresa.modelo.php"; require_once "../controladores/clientes.controlador.php"; require_once "../modelos/clientes.modelo.php"; #ITEMS SELECCIONADOS $item = "seleccionado"; $valor = 1; $respuesta = ControladorVentas::ctrMostrarFacturasSeleccionadas($item, $valor); #DATOS DE LA EMPRESA $item = "id"; $valor = 1; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); #PPREPARO EL PDF require('../extensiones/fpdf/fpdf.php'); #INICIO EL PDF $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $pdf->SetAutoPageBreak(true, 20); #INICIO LAS VARIABLES PARA EMPEZAR A CONTAR $altura=0; $contador=1; // Carga de datos foreach ($respuesta as $row => $item) { # TOMAR LOS DATOS DEL CLIENTE $itemCliente = "id"; $valorCliente = $item["id_cliente"]; $cliente = ControladorClientes::ctrMostrarClientes($itemCliente,$valorCliente); # VER TIPO DE CLIENTE $itemTipoCliente = "id"; $valorTipoCliente = $item["id_cliente"]; $tipoCliente = ControladorClientes::ctrMostrarTipoClientes($itemTipoCliente,$valorTipoCliente); if($contador==2){$altura=27;} if($contador==3){$altura=27*2;} if($contador==4){$altura=27*3;} if($contador==5){$altura=27*4;} if($contador==6){$altura=27*5;} if($contador==7){$altura=27*6;} // NOMBRE CLIENTE $pdf->SetFont('Arial','B',7); // $alturaNombre=$altura+10; $altura=$altura+10; $pdf->SetXY(60,$altura+10); $pdf->Write(0,$item['nombre']); //FECHA $pdf->SetX(95); $pdf->Write(0,$item['fecha']); //OBSERVACIONES $pdf->SetXY(60,$altura+15); $pdf->SetFont('Arial','',7); $pdf->Write(0,$item['detalle'].'-'.$item['obs'].' - '.$item['nrofc']); //LADO DERECHO CODIGO $pdf->SetXY(111.2,$altura+13.5); $pdf->SetFont('Arial','',10); $pdf->Write(0,$item['nrofc']); $pdf->SetXY(110,$altura+11); $pdf->Cell(20,16,'',1,1,'C'); //IMAGEN CODIGO DE BARRAS $pdf->Image('codigos/codigodebarras.jpg',113,$altura+15,-900); //NOMBRE if($tipoCliente["nombre"] == 'REVENDEDOR'){ $nombreCliente = $cliente['nombre']; }else{ $nombreCliente = $empresa['empresa']; } $pdf->SetFont('Arial','B',6); if (strlen($nombreCliente)>9){ $pdf->SetXY(109.5,$altura+26); }else{ $pdf->SetXY(113.5,$altura+26); } $pdf->Write(0,$nombreCliente); //SERVICIOS $matrizServicios=json_decode($item['productos'], true); $alturaPromedio =30; $pdf->SetFont('Arial','B',5); // foreach ($matrizServicios as $row => $value) { // switch ($contador) { // case '1': // # code... // $pdf->SetXY(62,$altura+18+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '2': // # code... // $pdf->SetXY(62,$altura+14+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '3': // # code... // $pdf->SetXY(62,$altura+10+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '4': // # code... // $pdf->SetXY(62,$altura+4+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '5': // # code... // $pdf->SetXY(62,$altura+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '6': // # code... // $pdf->SetXY(62,$altura-5+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // case '7': // # code... // $pdf->SetXY(62,$altura-8+$p); // $pdf->Write(0,$value['descripcion']); // $p=$p+2; // break; // } // } if ($cliente['idtipocliente']==1){ $pdf->SetXY(60,$altura+29); $pdf->Write(0,$empresa['web'].' - '.$empresa['telefono']); } $pdf->Line(60, $altura+30, 140, $altura+30); $contador++; } // El documento enviado al navegador $pdf->Output(); ?> <file_sep>/controladores/enlace.controlador.php <?php class ControladorEnlace{ /*============================================= ELIMINAR SEGUN LA TABLA CAJA =============================================*/ static public function ctrEliminarEnlace($tabla){ $respuesta = ModeloEnlace::mdlEliminarEnlace($tabla); return $respuesta; } static public function ctrMostrarVentasColegio(){ $tabla = "cuotas"; $respuesta = ModeloEnlace::mdlMostrarVentasColegio($tabla); return $respuesta; } static public function ctrMostrarVentasClorinda($item,$valor){ $tabla = "clorinda"; $respuesta = ModeloEnlace::mdlMostrarVentasClorinda($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasColorado($item,$valor){ $tabla = "colorado"; $respuesta = ModeloEnlace::mdlMostrarVentasClorinda($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasClorindaCodigoFc($item,$valor){ $tabla = "clorinda"; $respuesta = ModeloEnlace::mdlMostrarVentasClorindaCodigoFc($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasColoradoCodigoFc($item,$valor){ $tabla = "colorado"; $respuesta = ModeloEnlace::mdlMostrarVentasColoradoCodigoFc($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarUltimaActualizacion(){ $tabla = "ventas"; $respuesta = ModeloEnlace::mdlMostrarUltimaActualizacion($tabla); return $respuesta; } static public function ctrMostrarVentasFechaClorinda($item, $valor){ $tabla = "clorinda"; $respuesta = ModeloEnlace::mdlMostrarVentasFechaClorinda($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasFechaColorado($item, $valor){ $tabla = "colorado"; $respuesta = ModeloEnlace::mdlMostrarVentasFechaColorado($tabla, $item, $valor); return $respuesta; } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasEnlace($tabla,$fechaInicial, $fechaFinal){ $respuesta = ModeloEnlace::mdlRangoFechasEnlace($tabla, $fechaInicial, $fechaFinal); return $respuesta; } /*============================================= SUBIR INHABILITADOS =============================================*/ static public function ctrSubirInhabilitado($datos){ $tabla = "inhabilitados"; $respuesta = ModeloEnlace::mdlSubirInhabilitado($tabla, $datos); return $respuesta; } static public function ctrSubirHabilitado($valor){ $tabla = "inhabilitados"; $respuesta = ModeloEnlace::mdlSubirHabilitado($tabla, $valor); return $respuesta; } /*============================================= SUBIR MODIFICACIONES =============================================*/ static public function ctrSubirModificaciones($datos){ $tabla = "modificaciones"; $respuesta = ModeloEnlace::mdlSubirModificaciones($tabla, $datos); return $respuesta; } static public function ctrUpdateModificaciones($datos){ $tabla = "modificaciones"; $respuesta = ModeloEnlace::mdlUpdateModificaciones($tabla, $datos); return $respuesta; } /*============================================= ELIMINAR CUOTA =============================================*/ static public function ctrEliminarCuota($valor){ $tabla = "cuotas"; $respuesta = ModeloEnlace::mdlEliminarCuota($tabla,$valor); return $respuesta; } static public function ctrMostrarUltimaAVenta(){ $tabla = "ventas"; $respuesta = ModeloEnlace::mdlMostrarUltimaVenta($tabla); return $respuesta; } } <file_sep>/ajax/cambioperfil.ajax.php <?php require_once "../controladores/usuarios.controlador.php"; require_once "../modelos/usuarios.modelo.php"; class AjaxPerfil{ /*============================================= CAMBIAR FOTO PERFIL =============================================*/ public $tipo; public $miFotoPerfil; public $idUsuario; public $carpeta; public $foto; public function ajaxCambiarPerfil(){ $item = $this ->tipo; $valor = $this->miFotoPerfil; $idUsuario = $this->idUsuario; $carpeta = $this->carpeta; $foto = $this->foto; $respuesta = ControladorUsuarios::ctrActualizarFoto($item, $valor, $idUsuario,$carpeta,$foto); echo $respuesta; } public $miPass; public $idUsuario2; public function ajaxCambiarPass(){ $idUsuario2 = $this->idUsuario2; $pass = $this->miPass; $respuesta = ControladorUsuarios::ctrActualizarPass($idUsuario2,$pass); echo $respuesta; } } /*============================================= CAMBIAR FOTO PERFIL =============================================*/ if(isset($_FILES["miFotoPerfil"])){ $img = new AjaxPerfil(); $img -> miFotoPerfil = $_FILES["miFotoPerfil"]; $img -> tipo = 'iconochicoblanco'; $img -> idUsuario = $_POST['idUsuario']; $img -> carpeta = $_POST['carpeta']; $img -> foto = $_POST['foto']; $img -> ajaxCambiarPerfil(); } /*============================================= CAMBIAR CONTRASEÑA =============================================*/ if(isset($_POST["miPass"])){ $pass = new AjaxPerfil(); $pass -> idUsuario2 = $_POST['idUsuario2']; $pass -> miPass = $_POST['miPass']; $pass -> ajaxCambiarPass(); }<file_sep>/ajax/crearventa.ajax.php <?php require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; require_once "../controladores/comprobantes.controlador.php"; require_once "../modelos/comprobantes.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; require_once "../controladores/caja.controlador.php"; require_once "../modelos/caja.modelo.php"; require_once "../controladores/articulos.controlador.php"; require_once "../modelos/articulos.modelo.php"; require_once "../controladores/remitos.controlador.php"; require_once "../modelos/remitos.modelo.php"; require_once "../controladores/cuotas.controlador.php"; require_once "../modelos/cuotas.modelo.php"; class AjaxCrearVenta{ /*============================================= CREAR NUEVA VENTA =============================================*/ public function ajaxNuevaVenta(){ if ($_POST["tipoCliente"]=='delegacion'){ $respuesta = ControladorRemitos::ctrCrearRemito(); return $respuesta; }else{ $respuesta = ControladorVentas::ctrCrearVenta(); return $respuesta; } } /*============================================= EDITAR ULTIMA VENTA =============================================*/ public function ajaxEditarCuota(){ $respuesta = ControladorCuotas::ctrEditarCuota(); return $respuesta; } /*============================================= TRAER LA ULTIMA VENTA =============================================*/ public function ajaxUltimaVenta(){ $respuesta = ControladorVentas::ctrUltimoId(); echo json_encode($respuesta); } /*============================================= REMITOS =============================================*/ public function ajaxRemito(){ $respuesta = ControladorRemitos::ctrCrearRemito(); return $respuesta; } /*============================================= FACTURA SIN HOMOLOGACION =============================================*/ public function ajaxSinHomologacion(){ /** * agrego esto para poder realizar la correlatividad... de los eje */ $listaProductos = json_decode($_POST["listaProductos"], true); #creo un array del afip $items=Array(); #recorro $listaproductos para cargarlos en la tabla de comprobantes foreach ($listaProductos as $key => $value) { $tablaComprobantes = "comprobantes"; $valor = $value["idnrocomprobante"]; $datos = $value["folio2"]; $actualizarComprobantes = ModeloComprobantes::mdlUpdateComprobante($tablaComprobantes, $valor,$datos); } $fecha = date("Y-m-d"); if ($_POST["listaMetodoPago"]=="CTA.CORRIENTE"){ $adeuda=$_POST["totalVenta"]; $fechapago="0000-00-00"; }else{ $adeuda=0; $fechapago = $fecha; $caja = ControladorCaja::ctrMostrarCaja($item, $valor); $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVenta"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVenta"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVenta"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVenta"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); } $tabla = 'ventas'; $codigoFactura ="SIN HOMOLOGAR"; $datos = array("id_vendedor"=>$_POST["idVendedor"], "fecha"=>$fecha, "tipo"=>$_POST["tipoFc"], "id_cliente"=>$_POST["seleccionarCliente"], "nombre"=>$_POST['nombreCliente'], "documento"=>$_POST['documentoCliente'], "tabla"=>$_POST['tipoCliente'], "codigo"=>$codigoFactura, "productos"=>$_POST["listaProductos"], "impuesto"=>$_POST["nuevoPrecioImpuesto"], "neto"=>$_POST["nuevoPrecioNeto"], "total"=>$_POST["totalVenta"], "adeuda"=>$adeuda, "obs"=>'', "metodo_pago"=>$_POST["listaMetodoPago"], "referenciapago"=>$_POST["nuevaReferencia"], "cae"=>'', "fecha_cae"=>'', "fechapago"=>$fechapago); $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); // ControladorArticulos::ctrPrepararIngresoArticulo(); if ($_POST["listaMetodoPago"]!='CTA.CORRIENTE'){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVenta"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVenta"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVenta"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVenta"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); } if(isset( $_POST['idVentaNro'])){ ModeloCuotas::mdlEliminarVenta("cuotas", $_POST["idVentaNro"]); // echo '<center><pre>'; print_r($respuesta2 . ' '.$_POST["idVentaNro"]); echo '</pre></center>'; } } /*============================================= FACTURA SIN HOMOLOGACION =============================================*/ public function ajaxEditarVentaSinHomologar(){ $tablaClientes = "escribanos"; $item = "id"; $valor = $_POST["seleccionarCliente"]; $traerCliente = ModeloEscribanos::mdlMostrarEscribanos($tablaClientes, $item, $valor); if($traerCliente['facturacion']=="CUIT"){ $nombre=$traerCliente['nombre']; $documento=$traerCliente['cuit']; }else{ $nombre=$traerCliente['nombre']; $documento=$traerCliente['documento']; } /*============================================= FORMATEO LOS DATOS =============================================*/ $fecha = date("Y-m-d"); if ($_POST["listaMetodoPago"]=="CTA.CORRIENTE"){ $adeuda=$_POST["totalVenta"]; $fechapago="0000-00-00"; }else{ $adeuda=0; $fechapago = $fecha; } $tabla = "ventas"; $datos = array("id_vendedor"=>1, "fecha"=>date('Y-m-d'), "codigo"=>"SIN HOMOLOGAR", "tipo"=>$_POST['tipoCuota'], "id_cliente"=>$_POST['seleccionarCliente'], "nombre"=>$nombre, "documento"=>$documento, "tabla"=>$_POST['tipoCliente'], "productos"=>$_POST['listaProductos'], "impuesto"=>0, "neto"=>0, "total"=>$_POST["totalVenta"], "adeuda"=>'0', "obs"=>'', "cae"=>'', "fecha_cae"=>'', "fechapago"=>$fechapago, "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST['nuevaReferencia'] ); $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); $eliminarCuota = ModeloCuotas::mdlEliminarVenta("cuotas", $_POST["idVentaSinHomologacion"]); } /*============================================= HOLOGOGACION VENTA =============================================*/ public function ajaxHomogacionVenta(){ $respuesta = ControladorVentas::ctrHomologacionVenta(); return $respuesta; } } /*============================================= Traer el ultimo id de factura =============================================*/ if(isset($_POST["ultimaFactura"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxUltimaVenta(); } /*============================================= CREAR NUEVA VENTA CON FACTURA ELECTRONICA SI NO HAY NINGUN ERROR =============================================*/ if(isset($_POST["nuevaVenta"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> nuevaVenta(); } /*============================================= CREAR NUEVA VENTA CON PENDIENTE A FACTURAR PERO SI EXISTE UN ERROR =============================================*/ if(isset($_POST["sinHomologacion"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxSinHomologacion(); } /*============================================= EDITA UNA VENTA CUOTA O REINTEGRO PERO SI NO TIENE ERROR =============================================*/ if(isset($_POST["idVenta"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxEditarCuota(); } /*============================================= EDITA UNA VENTA CUOTA O REINTEGRO PERO SI NO TIENE ERROR =============================================*/ if(isset($_POST["idVentaSinHomologacion"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxEditarVentaSinHomologar(); } // ControladorVentas(); // $realizarHomologacion -> ctrHomologacionVenta(); /*============================================= HOMOLOGA UNA FACTURA SI TIENE LOS DATOS CORRECTOS Y SI HAY INTERNET =============================================*/ if(isset($_POST["idVentaHomologacion"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxHomogacionVenta(); } if(isset($_POST["remito"])){ $nuevaVenta = new AjaxCrearVenta(); $nuevaVenta -> ajaxRemito(); }<file_sep>/extensiones/fpdf/pdf/informe-caja.php <?php require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/remitos.controlador.php"; require_once "../../../modelos/remitos.modelo.php"; require_once "../../../controladores/caja.controlador.php"; require_once "../../../modelos/caja.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; require_once "../../../controladores/clientes.controlador.php"; require_once "../../../modelos/clientes.modelo.php"; require_once "../../../controladores/empresa.controlador.php"; require_once "../../../modelos/empresa.modelo.php"; #FUNCION PARA ÑS Y ACENTOS function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } #NOMBRE DEL INFORME $nombreDePdf="COBRANZAS ". $_GET["tipopago"]; #BUSCO LA FECHA $fecha1=$_GET['fecha1']; if(!isset($_GET['fecha2'])){ $fecha2=$_GET['fecha1']; }else{ $fecha2=$_GET['fecha2']; } #DATOS DE LA EMPRESA $item = "id"; $valor = 1; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); // PAGOS if($_GET["tipopago"]=="CTA.CORRIENTE"){ $item= "fecha"; $valor = $fecha1; }else{ $item= "fechapago"; $valor = $fecha1; } //VENTAS $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); // REMITOS $remitos = ControladorRemitos::ctrMostrarRemitosFecha($item,$valor); switch ($_GET["tipopago"]) { case 'EFECTIVO': # code... $centrarTipoPago = 30; $color1 = 2; $color2 = 117; $color3 = 216; break; case 'TARJETA': # code... $centrarTipoPago = 30; $color1 = 92; $color2 = 184; $color3 = 92; break; case 'CHEQUE': # code... $centrarTipoPago = 29; $color1 = 240; $color2 = 173; $color3 = 78; break; case 'TRANSFERENCIA': # code... $centrarTipoPago = 35; $color1 = 103; $color2 = 58; $color3 = 183; break; case 'CTA.CORRIENTE': # code... $centrarTipoPago = 35; $color1 = 255; $color2 = 163; $color3 = 1; break; default: $centrarTipoPago = 50; $color1 = 240; $color2 = 73; $color3 = 94; break; } #PPREPARO EL PDF require('../fpdf.php'); $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $hoja=1; //CONFIGURACION DEL LA HORA date_default_timezone_set('America/Argentina/Buenos_Aires'); //DATOS DEL MOMENTO $fecha= date("d")."-".date("m")."-".date("Y"); $hora=date("g:i A"); //DATOS QUE RECIBO $fechaInicio=explode ( '-', $fecha1 ); $fechaInicio=$fechaInicio[2].'-'.$fechaInicio[1].'-'.$fechaInicio[0]; $fechaFin=explode ( '-', $fecha2 ); $fechaFin=$fechaFin[2].'-'.$fechaFin[1].'-'.$fechaFin[0]; $pagosRemitos = 0; $cantPagosRemitos = 0; $pagosVentas = 0; $cantPagosVentas = 0; $contador = 0; //COMIENZA ENCABEZADO $pdf->SetFont('Arial','B',9); $pdf->Image('../../../vistas/img/plantilla/logo.jpg' , 5 ,0, 25 , 25,'JPG', 'http://www.bgtoner.com.ar'); $pdf->Text(35, 7,convertirLetras("COLEGIO DE ESCRIBANOS")); $pdf->Text(35, 10,convertirLetras("DE LA PROVINCIA DE FORMOSA")); $pdf->Text(150, 7,convertirLetras($nombreDePdf)); $pdf->SetFont('','',8); $pdf->Text(150, 12,convertirLetras("Fecha: ".$fecha)); $pdf->Text(178, 12,convertirLetras("Hora: ".$hora)); // $pdf->Text(150, 16,convertirLetras("Usuario: ADMIN")); $pdf->SetFont('','',6); $pdf->Text(35, 19,convertirLetras($empresa['direccion']." Tel.: ".$empresa['telefono'])); $pdf->Text(35, 22,convertirLetras("CUIT Nro. ".$empresa['cuit']." Ingresos Brutos 01-".$empresa['cuit'])); $pdf->Text(35, 25,convertirLetras("Inicio Actividades 02-01-1981 IVA Excento")); $pdf->SetFont('','',8); $pdf->Text(100, 27,convertirLetras("Hoja -".$hoja++)); if($fecha1==$fecha2){ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio)); }else{ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio." al ".$fechaFin)); } $pdf->Line(0,28,210, 28); $altura=30; // 3º Una tabla con los articulos comprados $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor($color1,$color2,$color3); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // Los datos (en negro) $pdf->SetTextColor(0,0,0); $pdf->SetFont('Arial','B',10); $altura=$altura+11; foreach($ventasPorFecha as $key=>$rsVentas){ if($rsVentas['metodo_pago']==$_GET["tipopago"]){ if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fecha'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$rsVentas['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } $pagosVentas=$pagosVentas+$importe; $cantPagosVentas++; $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // $pdf->Cell(20,10,"Salida",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); //$cantEfectivo++; $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fecha'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$rsVentas['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } $pagosVentas=$pagosVentas+$importe; $cantPagosVentas++; $altura+=6; $contador++; } } } // $totalRemitos = 0; foreach ($remitos as $key => $valueRemitos) { # code... // $totalRemitos = $totalRemitos + $value['total']; if($valueRemitos['metodo_pago']==$_GET["tipopago"]){ if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); if($valueRemitos['tipo']=='NC'){ $importe=$valueRemitos['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$valueRemitos['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } $pagosRemitos=$pagosRemitos+$importe; $cantPagosRemitos++; $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); if($valueRemitos['tipo']=='NC'){ $importe=$valueRemitos['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$valueRemitos['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } $pagosRemitos=$pagosRemitos+$importe; $cantPagosRemitos++; $altura+=6; $contador++; } } } $altura+=2; $cantTotalPagos = $cantPagosRemitos + $cantPagosVentas; if ($_GET['tipopago']!="CTA.CORRIENTE"){ $pdf->SetFont('Arial','',9); //PRIMER CUADRADO $pdf->SetXY(2,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(15,$altura+3); $pdf->Write(0,'IMPORTE'); #PRIMER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+12); $pdf->Cell($centrarTipoPago,0,"($cantTotalPagos) ".$_GET['tipopago'],0,0,'R');//CANTIDAD $pdf->SetXY(18 ,$altura+25); $pdf->Line(25,$altura+21,44,$altura+21); $pdf->Cell(23,0,$pagosRemitos+$pagosVentas,0,0,'R');//IMPORTE //SEGUNDO CUADRADO $pdf->SetXY(46,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(59,$altura+5); $pdf->Write(0,'PAGOS'); #SEGUNDA RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+11); $pdf->Cell(25,0,"(".$cantPagosVentas.")".' Facturas:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+11); $pdf->Cell(19,0,$pagosVentas,0,0,'R');//IMPORTE #TERCERO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+15); $pdf->Cell(25,0,"(".$cantPagosRemitos.")".' Remitos:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+15); $pdf->Cell(19,0,$pagosRemitos,0,0,'R');//IMPORTE #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(60,$altura+21); // $totales=$cantidadFacturas+$cantidadRemitos; $pdf->Cell(8,0,"(".$cantTotalPagos.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(65 ,$altura+21); $pdf->Line(66,$altura+18,88,$altura+18); $pdf->Cell(19,0,$pagosRemitos+$pagosVentas ,0,0,'R');//IMPORTE }else{ $pdf->SetFont('Arial','',9); //PRIMER CUADRADO $pdf->SetXY(2,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(15,$altura+3); $pdf->Write(0,'IMPORTE'); #PRIMER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+12); $pdf->Cell($centrarTipoPago,0,"($cantTotalPagos) ".$_GET['tipopago'],0,0,'R');//CANTIDAD $pdf->SetXY(18 ,$altura+25); $pdf->Line(25,$altura+21,44,$altura+21); $pdf->Cell(23,0,$pagosRemitos+$pagosVentas,0,0,'R');//IMPORTE //SEGUNDO CUADRADO $pdf->SetXY(46,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(59,$altura+5); $pdf->Write(0,'VENTAS'); #SEGUNDA RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+11); $pdf->Cell(25,0,"(".$cantPagosVentas.")".' Facturas:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+11); $pdf->Cell(19,0,$pagosVentas,0,0,'R');//IMPORTE #TERCERO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+15); $pdf->Cell(25,0,"(".$cantPagosRemitos.")".' Remitos:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+15); $pdf->Cell(19,0,$pagosRemitos,0,0,'R');//IMPORTE #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(60,$altura+21); // $totales=$cantidadFacturas+$cantidadRemitos; $pdf->Cell(8,0,"(".$cantTotalPagos.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(65 ,$altura+21); $pdf->Line(66,$altura+18,88,$altura+18); $pdf->Cell(19,0,$pagosRemitos+$pagosVentas ,0,0,'R');//IMPORTE } // El documento enviado al navegador $pdf->Output(); ?> <file_sep>/vistas/modulos/bibliotecas/paneles-nube.inicio.php <?php //TERMINO EL BUCLE DE LOS ESCRIBANOS /*==================================== = CARGO UN ARRAY DE LOS ESCRIBANOS = =============================================*/ #SE REVISA A LOS DEUDORES $escribanosInabilitados = ControladorEscribanos::ctrMostrarEscribanosInhabilitados(); #TRAER PRODUCTOS DEL COLEGIO $productos = ControladorParametros::ctrCountTablas("productos",null,null); #SE REVISA A LOS DEUDORES $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); ?><file_sep>/vistas/modulos/osde.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar osde </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar osde</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <button class="btn btn-primary" data-toggle="modal" data-target="#modalAgregarOsde"> Agregar osde </button> <button class="btn btn-danger pull-right" id="eliminarOsdes"> Eliminar todos los Osde </button> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Importe</th> <th>Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $osde = ControladorOsde::ctrMostrarOsde($item, $valor); foreach ($osde as $key => $value) { echo ' <tr> <td>'.($key+1).'</td> <td class="text-uppercase">'.$value["nombre"].'</td>'; echo '<td class="text-uppercase">'.$value["importe"].'</td>'; echo '<td> <div class="btn-group"> <button class="btn btn-warning btnEditarOsde" idOsde="'.$value["id"].'" data-toggle="modal" data-target="#modalEditarOsde"><i class="fa fa-pencil"></i></button>'; echo '<button class="btn btn-danger btnEliminarOsde" idOsde="'.$value["id"].'"><i class="fa fa-times"></i></button></div> </td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <!--===================================== MODAL AGREGAR CATEGORÍA ======================================--> <div id="modalAgregarOsde" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar Osde</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <input type="text" class="form-control input-lg" name="nuevoOsde" placeholder="Ingresar osde" required> </div> </div> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <input type="text" class="form-control input-lg" name="nuevoImporte" placeholder="Ingresar Importe" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar osde</button> </div> <?php $crearOsde= new ControladorOsde(); $crearOsde-> ctrCrearOsde(); ?> </form> </div> </div> </div> <!--===================================== MODAL EDITAR CATEGORÍA ======================================--> <div id="modalEditarOsde" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Editar osde</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <input type="text" class="form-control input-lg" name="editarOsde" id="editarOsde" required> <input type="hidden" name="idOsde" id="idOsde" required> </div> </div> <!-- ENTRADA PARA SELECCIONAR EL MOVIMIENTO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <input type="text" class="form-control input-lg" name="editarImporte" id="editarImporte" placeholder="Ingresar Importe" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar cambios</button> </div> <?php $editarOsde = new ControladorOsde(); $editarOsde -> ctrEditarOsde(); ?> </form> </div> </div> </div> <?php $borrarOsde = new ControladorOsde(); $borrarOsde -> ctrBorrarOsde(); ?> <file_sep>/vistas/modulos/bibliotecas/ventas-nube.inicio.php <?php /*========================================== = CANTIDAD DE VENTAS PARA MOSTRAR = ==========================================*/ $item = "fecha"; $valor= date('Y-m-d'); $ventas = ControladorVentas::ctrMostrarVentasFecha($item, $valor); $ventasClorinda = ControladorEnlace::ctrMostrarVentasFechaClorinda($item, $valor); $ventasColorado = ControladorEnlace::ctrMostrarVentasFechaColorado($item, $valor); $item = "tipo"; $valor= "CU"; $cantCuotas = ControladorCuotas::ctrContarCuotayOsde($item,$valor); $item = "tipo"; $valor= "RE"; $cantOsde = ControladorCuotas::ctrContarCuotayOsde($item,$valor); /*========================================== = BUSCAR LA ULTIMA FACTURA = ==========================================*/ $ultimoId = ControladorVentas::ctrUltimoId(); $item = "id"; $valor= $ultimoId["id"]; $ultimaVenta = ControladorVentas::ctrMostrarVentas($item, $valor); ?><file_sep>/ajax/clientes.ajax.php <?php require_once "../controladores/clientes.controlador.php"; require_once "../modelos/clientes.modelo.php"; class AjaxClientes{ // /*============================================= // CREO EL CLIENTE // =============================================*/ public function ajaxCrearClientes(){ #CREO UN NUEVO CLIENTE $datos = array("nombre"=>strtoupper($_POST["nombreAgregarCliente"]), "cuit"=>$_POST["documentoAgregarCliente"], "tipoiva"=>strtoupper($_POST["tipoCuitAgregarCliente"]), "direccion"=>strtoupper($_POST["direccionAgregarCliente"]), "localidad"=>strtoupper($_POST["localidadAgregarCliente"])); ControladorClientes::ctrCrearCliente($datos); #TOMO EL ULTIMO ID PARA COLOCARLO EN EL FORMULARIO $respuesta = ControladorClientes::ctrUltimoCliente(); echo json_encode($respuesta); } public function ajaxBuscarClientes(){ $item = "cuit"; $valor = $_POST["documentoVerificar"]; $respuesta = ControladorClientes::ctrMostrarClientes($item, $valor); echo json_encode($respuesta); } public function ajaMostrarCliente(){ $item = "id"; $valor = $_POST["idCliente"]; $respuesta = ControladorClientes::ctrMostrarClientes($item, $valor); echo json_encode($respuesta); } // /*============================================= // EDITAR CLIENTE // =============================================*/ public function ajaXEditarCliente(){ #CREO UN NUEVO CLIENTE $datos = array("id"=>strtoupper($_POST["idClienteEditar"]), "nombre"=>strtoupper($_POST["nombreEditarCliente"]), "cuit"=>$_POST["documentoEditarCliente"], "tipoiva"=>strtoupper($_POST["tipoCuitEditarCliente"]), "direccion"=>strtoupper($_POST["direccionEditarCliente"]), "localidad"=>strtoupper($_POST["localidadEditarCliente"])); echo '<pre>'; print_r($datos); echo '</pre>'; ControladorClientes::ctrEditarCliente($datos); #TOMO EL ULTIMO ID PARA COLOCARLO EN EL FORMULARIO // $respuesta = ControladorClientes::ctrUltimoCliente(); // echo json_encode($respuesta); } } /*============================================= EDITAR CLIENTES =============================================*/ if(isset($_POST["nombreAgregarCliente"])){ $clientes = new AjaxClientes(); $clientes -> ajaxCrearClientes(); } /*============================================= bUSCAR cLIENTE x cuit =============================================*/ if(isset($_POST["documentoVerificar"])){ $clientes = new AjaxClientes(); $clientes -> ajaxBuscarClientes(); } /*============================================= bUSCAR cLIENTE por id =============================================*/ if(isset($_POST["idCliente"])){ $clientes = new AjaxClientes(); $clientes -> ajaMostrarCliente(); } /*============================================= bUSCAR cLIENTE por id =============================================*/ if(isset($_POST["idClienteEditar"])){ $clientes = new AjaxClientes(); $clientes -> ajaXEditarCliente(); } <file_sep>/extensiones/fpdf/pdf/pagos.php <?php require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/remitos.controlador.php"; require_once "../../../modelos/remitos.modelo.php"; require_once "../../../controladores/caja.controlador.php"; require_once "../../../modelos/caja.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; require_once "../../../controladores/clientes.controlador.php"; require_once "../../../modelos/clientes.modelo.php"; require_once "../../../controladores/empresa.controlador.php"; require_once "../../../modelos/empresa.modelo.php"; #FUNCION PARA ÑS Y ACENTOS function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } #NOMBRE DEL INFORME $nombreDePdf="PAGOS DE CUENTA CORRIENTE"; #BUSCO LA FECHA $fecha1=$_GET['fecha1']; if(!isset($_GET['fecha2'])){ $fecha2=$_GET['fecha1']; }else{ $fecha2=$_GET['fecha2']; } #DATOS DE LA EMPRESA $item = "id"; $valor = 1; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); // VENTAS // $item= "fecha"; // $valor = $fecha1; // $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); // PAGOS $item= "fechapago"; $valor = $fecha1; $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); // REMITOS $item= "fechapago"; $valor = $fecha1; $remitos = ControladorRemitos::ctrMostrarRemitosFecha($item,$valor); #PPREPARO EL PDF require('../fpdf.php'); $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $hoja=1; //CONFIGURACION DEL LA HORA date_default_timezone_set('America/Argentina/Buenos_Aires'); //DATOS DEL MOMENTO $fecha= date("d")."-".date("m")."-".date("Y"); $hora=date("g:i A"); //DATOS QUE RECIBO $fechaInicio=explode ( '-', $fecha1 ); $fechaInicio=$fechaInicio[2].'-'.$fechaInicio[1].'-'.$fechaInicio[0]; $fechaFin=explode ( '-', $fecha2 ); $fechaFin=$fechaFin[2].'-'.$fechaFin[1].'-'.$fechaFin[0]; //COMIENZA ENCABEZADO $pdf->SetFont('Arial','B',9); $pdf->Image('../../../vistas/img/plantilla/logo.jpg' , 5 ,0, 25 , 25,'JPG', 'http://www.bgtoner.com.ar'); $pdf->Text(35, 7,convertirLetras("COLEGIO DE ESCRIBANOS")); $pdf->Text(35, 10,convertirLetras("DE LA PROVINCIA DE FORMOSA")); $pdf->Text(150, 7,convertirLetras($nombreDePdf)); $pdf->SetFont('','',8); $pdf->Text(150, 12,convertirLetras("Fecha: ".$fecha)); $pdf->Text(178, 12,convertirLetras("Hora: ".$hora)); // $pdf->Text(150, 16,convertirLetras("Usuario: ADMIN")); $pdf->SetFont('','',6); $pdf->Text(35, 19,convertirLetras($empresa['direccion']." Tel.: ".$empresa['telefono'])); $pdf->Text(35, 22,convertirLetras("CUIT Nro. ".$empresa['cuit']." Ingresos Brutos 01-".$empresa['cuit'])); $pdf->Text(35, 25,convertirLetras("Inicio Actividades 02-01-1981 IVA Excento")); $pdf->SetFont('','',8); $pdf->Text(100, 27,convertirLetras("Hoja -".$hoja++)); if($fecha1==$fecha2){ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio)); }else{ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio." al ".$fechaFin)); } $pdf->Line(0,28,210, 28); $altura=30; // 3º Una tabla con los articulos comprados $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(52,73,94); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // Los datos (en negro) $pdf->SetTextColor(0,0,0); $pdf->SetFont('Arial','B',10); $altura=$altura+11; #EFECTIVO VARIBLES $efectivoVentas=0; $cantEfectivoVentas=0; $efectivoRemitos=0; $cantEfectivoRemitos=0; #CHEQUE VARIABLES $chequeVentas=0; $cantChequeVentas=0; $chequeRemitos=0; $cantChequeRemitos=0; #Tarjeta VARIABLES $tarjetaVentas=0; $cantTarjetaVentas=0; $tarjetaRemitos=0; $cantTarjetaRemitos=0; #TRANSFERENCIA VARIABLES $transferenciaVentas=0; $cantTransferenciaVentas=0; $transferenciaRemitos=0; $cantTransferenciaRemitos=0; #CTA.CORRIENTE VARIABLES $ctaCorrienteVentas=0; $cantCtaVentas=0; $ctaCorrienteRemitos=0; $cantCtaRemitos=0; // $cheque=0; // $cantCheque=0; // $tarjeta=0; // $cantTarjeta=0; // $transferencia=0; // $cantTransferencia=0; $otros=0; $cantVentas=0; $cuotaSocial=0; $cantCuota=0; $derecho=0; $cantDerecho=0; $cantOsde=0; $osde=0; $otrosRemitos=0; $cantVentasRemitos=0; $cuotaSocialRemitos=0; $cantCuotaRemitos=0; $derechoRemitos=0; $cantDerechoRemitos=0; $cantOsdeRemitos=0; $osdeRemitos=0; $ventasTotal=0; $contador=0; foreach($ventasPorFecha as $key=>$rsVentas){ if($rsVentas['fecha']!=$fecha1){ if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fecha'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); // $listaProductos = json_decode($rsVentas["productos"], true); // foreach ($listaProductos as $key => $value) { // switch ($value['id']) { // case '20': // # cuota... // $cantCuota++; // $cuotaSocial=$value['total']+$cuotaSocial; // break; // case '19': // # derech... // $cantDerecho++; // $derecho=$value['total']+$derecho; // break; // case '22': // # derech... // $cantOsde++; // $osde=$value['total']+$osde; // break; // default: // # venta... // $cantVentas++; // $otros=$value['total']+$otros; // break; // } // } if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$rsVentas['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivoVentas=$efectivoVentas+$importe; $cantEfectivoVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjetaVentas=$tarjetaVentas+$importe; $cantTarjetaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $chequeVentas=$chequeVentas+$importe; $cantChequeVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferenciaVentas=$transferenciaVentas+$importe; $cantTransferenciaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CT'){ $ctaCorrienteVentas=$ctaCorrienteVentas+$importe; $cantCtaVentas++; } $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // $pdf->Cell(20,10,"Salida",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); //$cantEfectivo++; $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fecha'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); if ($rsVentas['tipo']=='FC'){ $pdf->Cell(20,5,$importe,1,0,"C"); $pdf->Cell(20,5,'0',1,0,"C"); if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivoVentas=$efectivoVentas+$importe; $cantEfectivoVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjetaVentas=$tarjetaVentas+$importe; $cantTarjetaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $chequeVentas=$chequeVentas+$importe; $cantChequeVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferenciaVentas=$transferenciaVentas+$importe; $cantTransferenciaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CT'){ $ctaCorrienteVentas=$ctaCorrienteVentas+$importe; $cantCtaVentas++; } } $altura+=6; $contador++; } } } // $totalRemitos = 0; foreach ($remitos as $key => $valueRemitos) { # code... // $totalRemitos = $totalRemitos + $value['total']; if($valueRemitos['fecha']!=$fecha1){ if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); $listaProductos = json_decode($valueRemitos["productos"], true); foreach ($listaProductos as $key => $valueProductos) { switch ($valueProductos['id']) { case '20': # cuota... $cantCuotaRemitos++; $cuotaSocialRemitos=$valueProductos['total']+$cuotaSocialRemitos; break; case '19': # derech... $cantDerechoRemitos++; $derechoRemitos=$valueProductos['total']+$derechoRemitos; break; case '22': # derech... $cantOsdeRemitos++; $osdeRemitos=$valueProductos['total']+$osdeRemitos; break; default: # venta... $cantVentasRemitos++; $otrosRemitos=$valueProductos['total']+$otrosRemitos; break; } } if($valueRemitos['tipo']=='NC'){ $importe=$valueRemitos['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$valueRemitos['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } if (substr($valueRemitos['metodo_pago'],0,2)=='EF'){ $efectivoRemitos=$efectivoRemitos+$importe; $cantEfectivoRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TA'){ $tarjetaRemitos=$tarjetaRemitos+$importe; $cantTarjetaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CH'){ $chequeRemitos=$chequeRemitos+$importe; $cantChequeRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TR'){ $transferenciaRemitos=$transferenciaRemitos+$importe; $cantTransferenciaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CT'){ $ctaCorrienteRemitos=$ctaCorrienteRemitos+$importe; $cantCtaRemitos++; } $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); if ($valueRemitos['tipo']=='FC'){ $pdf->Cell(20,5,$importe,1,0,"C"); $pdf->Cell(20,5,'0',1,0,"C"); if (substr($valueRemitos['metodo_pago'],0,2)=='EF'){ $efectivoRemitos=$efectivoRemitos+$importe; $cantEfectivoRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TA'){ $tarjetaRemitos=$tarjetaRemitos+$importe; $cantTarjetaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CH'){ $chequeRemitos=$chequeRemitos+$importe; $cantChequeRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TR'){ $transferenciaRemitos=$transferenciaRemitos+$importe; $cantTransferenciaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CT'){ $ctaCorrienteRemitos=$ctaCorrienteRemitos+$importe; $cantCtaRemitos++; } } $altura+=6; $contador++; } } } $cantEfectivoPagos = 0; $cantChequePagos =0; $cantTarjetaPagos =0; $cantTransferenciaPagos =0; $efectivoPagos = 0; $chequePagos = 0; $tarjetaPagos =0; $transferenciaPagos=0; foreach ($pagosPorFecha as $key => $valuePagos) { # code... if($valuePagos['tipo']=='NC'){ $importe=$valuePagos['total']*(-1); // $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$valuePagos['total']; // $pdf->Cell(20,5,$importe,1,0,"C"); } if (substr($valuePagos['metodo_pago'],0,2)=='EF'){ $efectivoPagos=$efectivoPagos+$importe; $cantEfectivoPagos++; } if (substr($valuePagos['metodo_pago'],0,2)=='TA'){ $tarjetaPagos=$tarjetaPagos+$importe; $cantTarjetaPagos++; } if (substr($valuePagos['metodo_pago'],0,2)=='CH'){ $chequePagos=$chequePagos+$importe; $cantChequePagos++; } if (substr($valuePagos['metodo_pago'],0,2)=='TR'){ $transferenciaPagos=$transferenciaPagos+$importe; $cantTransferenciaPagos++; } if (substr($valuePagos['metodo_pago'],0,2)=='CT'){ $ctaCorrientePagos=$ctaCorrientePagos+$importe; $cantCtaPagos++; } } $altura+=2; #TOTALES DE LAS CANTIDADES DEL PRIMER RECUADRO $cantidadEfectivoVentas = $cantEfectivoVentas+$cantEfectivoRemitos; $cantidadChequeVentas = $cantChequeVentas+$cantChequeRemitos; $cantidadTarjetaVentas = $cantTarjetaVentas+$cantTarjetaRemitos; $cantidadTrasnferenciaVentas = $cantTransferenciaVentas+$cantTransferenciaRemitos; $cantidadCtaVentas =$cantCtaVentas+$cantCtaRemitos; #TOTALES DE LA SUMA DE TODOS $totalCuadro1 = $efectivoVentas+$efectivoRemitos+$transferenciaVentas+$transferenciaRemitos+$tarjetaRemitos+$tarjetaVentas+$chequeRemitos+$chequeVentas+$ctaCorrienteVentas+$ctaCorrienteRemitos; $totalCantidadesCaja1 = $cantidadEfectivoVentas + $cantidadChequeVentas + $cantidadTarjetaVentas + $cantidadTrasnferenciaVentas + $cantidadCtaVentas; $pdf->SetFont('Arial','',9); //PRIMER CUADRADO $pdf->SetXY(2,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(3,$altura+3); $pdf->Write(0,'PAGOS Cta.C Y REMITOS'); #PRIMER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+7); $pdf->Cell(23,0,"($cantidadEfectivoVentas)".' Efectivo:',0,0,'R');//CANTIDAD $pdf->SetXY(18 ,$altura+7); $pdf->Cell(22,0,$efectivoVentas+$efectivoRemitos,0,0,'R');//IMPORTE #SEGUNDO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+11); $pdf->Cell(23,0,"($cantidadChequeVentas)".' Cheque:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+11); $pdf->Cell(19,0,$chequeVentas+$chequeRemitos,0,0,'R');//IMPORTE #TERCER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+15); $pdf->Cell(23,0,"($cantidadTarjetaVentas)".' Tarjeta:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+15); $pdf->Cell(19,0,$tarjetaVentas+$tarjetaRemitos,0,0,'R');//IMPORTE #CUARTO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+19); $pdf->Cell(23,0,"($cantidadTrasnferenciaVentas)".' Transf.:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+19); $pdf->Cell(19,0,$transferenciaVentas+$transferenciaRemitos,0,0,'R');//IMPORTE #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+24); $totalCantVentas = $cantEfectivo + $cantCheque + $cantTransferencia + $cantTarjeta + $cantOsde; $pdf->Cell(23,0,"(".$totalCantidadesCaja1 .")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+24); $pdf->Line(25,$altura+21 ,44,$altura+21 ); $pdf->Cell(19,0,$totalCuadro1,0,0,'R');//IMPORTE #TOTALES DE LAS CANTIDADES DEL PRIMER RECUADRO $cantidadFacturas = $cantEfectivoVentas + $cantChequeVentas + $cantTarjetaVentas + $cantTransferenciaVentas; $cantidadRemitos = $cantEfectivoRemitos + $cantChequeRemitos + $cantTarjetaRemitos + $cantTransferenciaRemitos; // $cantidadCtaCorriente = $cantCtaVentas+$cantCtaRemitos; $importeFacturas = $efectivoVentas + $transferenciaVentas + $tarjetaVentas + $chequeVentas; $importeRemitos = $efectivoRemitos + $transferenciaRemitos + $tarjetaRemitos + $chequeRemitos; // $importeCta = $ctaCorrienteVentas+$ctaCorrienteRemitos; $totalCuadro4 = $importeFacturas + $importeRemitos;//+ $importeCta; $totalCantPagos = $cantEfectivoPagos + $cantChequePagos + $cantTarjetaPagos + $cantTransferenciaPagos; $totalPagos = $efectivoPagos + $chequePagos + $tarjetaPagos + $transferenciaPagos; //SEGUNDO CUADRADO $pdf->SetXY(46,$altura); $pdf->Cell(42,28,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(59,$altura+5); $pdf->Write(0,'PAGOS'); #SEGUNDA RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+11); $pdf->Cell(25,0,"(".$cantidadFacturas.")".' Facturas:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+11); $pdf->Cell(19,0,$importeFacturas,0,0,'R');//IMPORTE #TERCERO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+15); $pdf->Cell(25,0,"(".$cantidadRemitos.")".' Remitos:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+15); $pdf->Cell(19,0,$importeRemitos,0,0,'R');//IMPORTE #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(60,$altura+21); $totales=$cantidadFacturas+$cantidadRemitos; $pdf->Cell(8,0,"(".$totales.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(65 ,$altura+21); $pdf->Line(66,$altura+18,88,$altura+18); $pdf->Cell(19,0,$importeFacturas+$importeRemitos ,0,0,'R');//IMPORTE // El documento enviado al navegador $pdf->Output(); ?> <file_sep>/extensiones/afip/prueba.php <?php include_once (__DIR__ . '/wsfev1.php'); include_once (__DIR__ . '/wsfexv1.php'); include_once (__DIR__ . '/wsaa.php'); // $CUIT = 30584197680; // $MODO = Wsaa::MODO_PRODUCCION; include ('modo.php'); $PTOVTA = 4; //lo puse acá para pasarlo como parámetro para los certificados por pto de vta //echo "----------Script de prueba de AFIP WSFEV1----------\n"; $afip = new Wsfev1($CUIT,$MODO,$PTOVTA); $result = $afip->init(); if ($result["code"] === Wsfev1::RESULT_OK) { $result = $afip->dummy(); if ($result["code"] === Wsfev1::RESULT_OK) { //$datos = print_r($result["msg"], TRUE); //echo "Resultado: " . $datos . "\n"; //$afip = new Wsfev1($CUIT, Wsaa::MODO_HOMOLOGACION); //$result = $afip->init(); //Crea el cliente SOAP //$ptovta = 2; $tipocbte = 13; //aca va el codigo de NC creo que es 13 $cmp = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,$tipocbte); $ult = $cmp["number"]; $ult = $ult +1; //$ult=3; echo 'Nro. comp. a emitir: ' . $ult; $date_raw=date('Y-m-d'); $desde= date('Ymd', strtotime('-2 day', strtotime($date_raw))); $hasta=date('Ymd', strtotime('-1 day', strtotime($date_raw))); //Si el comprobante es C no debe informarse $detalleiva=Array(); //$detalleiva[0]=array('codigo' => 5,'BaseImp' => 100.55,'importe' => 21.12); //IVA 21% //$detalleiva[1]=array('codigo' => 4,'BaseImp' => 100,'importe' => 10.5); //IVA 10,5% $regcomp['numeroPuntoVenta'] =$PTOVTA; $regcomp['codigoTipoComprobante'] =$tipocbte; $comprob= array(); $regcomp['CbtesAsoc'] = $comprob; $regcomp['codigoConcepto'] = 1; # 1: productos, 2: servicios, 3: ambos $regcomp['codigoTipoDocumento'] = 99; # 80: CUIT, 96: DNI, 99: Consumidor Final $regcomp['numeroDocumento'] = 0; # 0 para Consumidor Final (<$1000) //Ejemplo Factura A con iva discriminado //$regcomp['importeTotal'] = 1.21; # total del comprobante //$regcomp['importeGravado'] = 1; # subtotal neto sujeto a IVA //$regcomp['importeIVA'] = 0.21; //Ejemplo Factura C - Descomentar los siguientes y comentar los anteriores $regcomp['importeTotal'] = 1.00; # total del comprobante $regcomp['importeGravado'] = 1.00; #subtotal neto sujeto a IVA $regcomp['importeIVA'] = 0; $regcomp['importeOtrosTributos'] = 0; $regcomp['importeExento'] = 0.0; $regcomp['numeroComprobante'] = $ult; $regcomp['importeNoGravado'] = 0.00; $regcomp['subtotivas'] = $detalleiva; $regcomp['codigoMoneda'] = 'PES'; $regcomp['cotizacionMoneda'] = 1; $regcomp['fechaComprobante'] = date('Ymd'); $regcomp['fechaDesde'] = $desde; $regcomp['fechaHasta'] = $hasta; $regcomp['fechaVtoPago'] = date('Ymd'); //Ejemplo de otros tributos - Para que los tenga en cuenta deben cargar valor mayores a cero y modificar el total cumandole el $per_ARBA_importe /*$per_ARBA_importe=0; $per_ARBA_imponible=0; $per_ARBA_alic=0; $per_ARBA_importe=0; if($per_ARBA_importe>0){ $regcomp['importeOtrosTributos'] = [per_ARBA_importe]; $detalleTributos=Array(); $detalleTributos[0]=array('Id' => 02 , 'Desc' => 'Perc. ARBA', 'BaseImp' => $per_ARBA_imponible , 'Alic' => $per_ARBA_alic ,'Importe' => $per_ARBA_importe); $regcomp['Tributos'] = $detalleTributos; }else{ $regcomp['importeOtrosTributos'] = 0; } */ /*============================================= ESTE HAY QUE DESTILDAR =============================================*/ $result = $afip->emitirComprobante($regcomp); //$regcomp debe tener la estructura esperada (ver a continuación de la wiki) /*===== End of Section comment block ======*/ // $result = $afip->emitirComprobante($regcomp); //$regcomp debe tener la estructura esperada (ver a continuación de la wiki) if ($result["code"] === Wsfev1::RESULT_OK) { //La facturacion electronica finalizo correctamente //$result["cae"] y $result["fechaVencimientoCAE"] son datos que deberías almacenar //print_r($result); echo ' ** Resultado: OK ** - CAE: ' . $result["cae"]; echo ' - Cae Vto.: ' . $result["fechaVencimientoCAE"] . "\n"; } else { //No pudo emitirse la factura y $result["msg"] contendrá el motivo echo $result["msg"] . "\n"; } } else { echo $result["msg"] . "\n"; } } else { echo $result["msg"] . "\n"; } echo "--------------Ejecución WSFEV1 finalizada-----------------\n"; <file_sep>/ajax/parametros.ajax.php <?php require_once "../controladores/parametros.controlador.php"; require_once "../modelos/parametros.modelo.php"; class AjaxParametros{ /*============================================= VER ATRASO GENERAL =============================================*/ public function ajaxMostrarMaximoAtraso(){ $item = "parametro"; $valor = 'maxAtraso'; $respuesta = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); echo json_encode($respuesta); } public $idParametro; public function ajaxMostrarParametros(){ $item = "id"; $valor = $this->idParametro; $respuesta = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); echo json_encode($respuesta); } public $idbackup; public function ajaxMostrarBackUp(){ $item = "id"; $valor = $this->idbackup; $respuesta = ControladorParametros::ctrMostrarBackUp($item, $valor); echo json_encode($respuesta); } public function ajaxVerArtBackUp(){ $item = "id"; $valor = $_POST["idBackUpArt"]; $respuesta = ControladorParametros::ctrMostrarBackUp($item, $valor); $listaProductos = json_decode($respuesta['datos'], true); echo json_encode($listaProductos); } } /*============================================= VER ATRASO GENERAL =============================================*/ if(isset($_POST["maxAtraso"])){ $cliente = new AjaxParametros(); $cliente -> ajaxMostrarMaximoAtraso(); } if(isset($_POST["idParametro"])){ $parametro = new AjaxParametros(); $parametro -> idParametro = $_POST["idParametro"]; $parametro -> ajaxMostrarParametros(); } if(isset($_POST["idbackup"])){ $parametro = new AjaxParametros(); $parametro -> idbackup = $_POST["idbackup"]; $parametro -> ajaxMostrarBackUp(); } if(isset($_POST["idBackUpArt"])){ $parametro = new AjaxParametros(); $parametro -> idBackUpArt = $_POST["idBackUpArt"]; $parametro -> ajaxVerArtBackUp(); }<file_sep>/vistas/modulos/bibliotecas/servidor.inicio.php <?php /*================================================== = ELIMINAR LOS INHABILITADOS EN EL SERVIDOR = ==================================================*/ #ELIMINAR LOS INHABILITADOS EN EL SERVIDOR $respuesta = ControladorEnlace::ctrEliminarEnlace("inhabilitados"); /*============================================ = HABILITO A TODOS LOS ESCRIBANOS = =============================================*/ #HABILITO A TODOS LOS DEUDORES EN LA TABLA ESCRIBANOS #LOS PONGO A CERO ControladorCuotas::ctrEscribanosHabilitar(); ?><file_sep>/ajax/comprobantes.ajax.php <?php require_once "../controladores/comprobantes.controlador.php"; require_once "../modelos/comprobantes.modelo.php"; require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class AjaxComprobantes{ // /*============================================= // EDITAR COMPROBANTES // =============================================*/ public $idComprobante; public function ajaxEditarComprobante(){ $item = "id"; $valor = $this->idComprobante; $respuesta = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); echo json_encode($respuesta); } /*============================================= EDITAR COMPROBANTES =============================================*/ public function ajaxTodosComprobantes(){ $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); echo json_encode($respuesta); } /*============================================= BORRA LA TABLA tmp_comprobantes =============================================*/ public function iniciarComprobantes(){ $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrIniciarComprobantes($item, $valor); return $respuesta; } /*============================================= INICIAR TABLA =============================================*/ public $idTmp; public $nombreTmp; public $numeroTmp; public function iniciarCargaComprobantes(){ $datos = array("id"=>$this->idTmp, "nombre"=>$this->nombreTmp, "numero"=>$this->numeroTmp); $respuesta = ControladorComprobantes::ctrIniciarCargaTmpComprobantes($datos); return $respuesta; } /*============================================= INICIAR ITEMS =============================================*/ public function borrarItems(){ $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrIniciarItems($item, $valor); } /*============================================= VER ULTIMO COMPROBANTE ID =============================================*/ public $idItem; public function ajaxBorrarItem(){ $item = "id"; $valor = $this->idItem; $respuesta = ControladorComprobantes::ctrBorrarItem($item, $valor); // BORRAR LA TABLA TMP_COMPROBANTES $item = null; $valor = null; $borrarComprobantes = ControladorComprobantes::ctrIniciarComprobantes($item, $valor); // CREAR LA TABLA TMP_COMPROBANTES // 1..cargamos la tabla $item = null; $valor = null; $tablaPrincipalComprobantes = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); foreach ($tablaPrincipalComprobantes as $key => $value) { # code... $datos = array("id"=>$value['id'], "nombre"=>$value['nombre'], "numero"=>$value['numero']); $cargarTmpComprobantes = ControladorComprobantes::ctrIniciarCargaTmpComprobantes($datos); } // MUESTRO TODOS LOS ITEMS DE LA TABLA tmp_items $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrMostrarItemsComprobantes($item, $valor); foreach ($respuesta as $key => $value) { $item = "id"; $valor = $value['idnrocomprobante']; $comprobantes = ControladorComprobantes::ctrMostrarTMPComprobantes($item, $valor); $folio1 = $comprobantes['numero']+1; if ($value['cantidad']==1){ $folio2 =($value['cantventaproducto'] - 1) + ($folio1); }else{ $folio2 =$value['cantventaproducto'] * $value['cantidad']; $folio2 =$folio2 + $folio1; $folio2 = $folio2 - 1; } echo '<tr> <td>'.($key + 1) .'</td> <td> <input type="number" class="form-control nuevaCantidadProducto" name="nuevaCantidadProducto" value="'.$value['cantidad'].'" readonly> </td> <td> <div> <input type="text" class="form-control nuevaDescripcionProducto" idProducto="'.$value['idproducto'].'" idNroComprobante="'.$value['idnrocomprobante'].'" cantVentaProducto="'.$value['cantventaproducto'].'" name="agregarProducto" value="'.$value['nombre'].'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio1" name="folio1" value="'.$folio1.'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio2" name="folio2" value="'.$folio2.'" readonly required> </div> </td> <td> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoPrecioProducto" precioReal="'.$value['precioventa'].'" name="nuevoPrecioProducto" value="'.$value['precioventa'].'" readonly required> </div> </td> <td style="text-align: right;"> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoTotalProducto" precioTotal="'.($value['cantidad']*$value['precioventa']).'" name="nuevoTotalProducto" value="'.($value['cantidad']*$value['precioventa']).'" readonly required> </div> </td> <td> <span class="input-group-addon"><button type="button" class="btn btn-danger btn-xs quitarProducto" idItem="'.$value['id'].'" ><i class="fa fa-times"></i></button></span> </td> </tr>'; // GRABO EL ULTIMO ID $item = "id"; $valor = $value['idnrocomprobante']; $datos = $folio2; $respuesta = ControladorComprobantes::ctrUpdateFolioComprobantes($item, $valor,$datos); // ACTUALIZO EL Folio1 $campo = "folio1"; $id = $value['id']; $numero = $folio1; $folios = ControladorComprobantes::ctrUpdateFolio($campo, $id,$numero); // ACTUALIZO EL Folio1 $campo = "folio2"; $id = $value['id']; $numero = $folio2; $folios = ControladorComprobantes::ctrUpdateFolio($campo, $id,$numero); } } /*============================================= AGREGAR ITEMS =============================================*/ public $idproducto; public $productoNombre; public $idNroComprobante; public $cantidadProducto; public $cantVentaProducto; public $precioVenta; public $idVenta; public function ajaxAgregarItems(){ $idVenta = $this->idVenta; // tomo todos los datos que vienen por el formulario $datos = array("idproducto"=>$this->idproducto, "nombre"=>$this->productoNombre, "idNroComprobante"=>$this->idNroComprobante, "cantidadProducto"=>$this->cantidadProducto, "cantVentaProducto"=>$this->cantVentaProducto, "precioVenta"=>$this->precioVenta, "folio1"=>1, "folio2"=>2); //los agrego en la tabla tmp_items $respuesta = ControladorComprobantes::ctrAgregarItemsComprobantes($datos); // BORRAR LA TABLA TMP_COMPROBANTES $item = null; $valor = null; $borrarComprobantes = ControladorComprobantes::ctrIniciarComprobantes($item, $valor); // CREAR LA TABLA TMP_COMPROBANTES // 1..cargamos la tabla $item = null; $valor = null; $tablaPrincipalComprobantes = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); foreach ($tablaPrincipalComprobantes as $key => $value) { # code... $datos = array("id"=>$value['id'], "nombre"=>$value['nombre'], "numero"=>$value['numero']); $cargarTmpComprobantes = ControladorComprobantes::ctrIniciarCargaTmpComprobantes($datos); } // MUESTRO TODOS LOS ITEMS DE LA TABLA tmp_items $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrMostrarItemsComprobantes($item, $valor); foreach ($respuesta as $key => $value) { $item = "id"; $valor = $value['idnrocomprobante']; $comprobantes = ControladorComprobantes::ctrMostrarTMPComprobantes($item, $valor); $folio1 = $comprobantes['numero']+1; if ($value['cantidad']==1){ $folio2 =($value['cantventaproducto'] - 1) + ($folio1); }else{ $folio2 =$value['cantventaproducto'] * $value['cantidad']; $folio2 =$folio2 + $folio1; $folio2 = $folio2 - 1; } echo '<tr> <td>'.($key + 1) .'</td> <td> <input type="number" class="form-control nuevaCantidadProducto" name="nuevaCantidadProducto" value="'.$value['cantidad'].'" readonly> </td> <td> <div> <input type="text" class="form-control nuevaDescripcionProducto" idProducto="'.$value['idproducto'].'" idNroComprobante="'.$value['idnrocomprobante'].'" cantVentaProducto="'.$value['cantventaproducto'].'" name="agregarProducto" value="'.$value['nombre'].'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio1" name="folio1" value="'.$folio1.'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio2" name="folio2" value="'.$folio2.'" readonly required> </div> </td> <td> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoPrecioProducto" precioReal="'.$value['precioventa'].'" name="nuevoPrecioProducto" value="'.$value['precioventa'].'" readonly required> </div> </td> <td style="text-align: right;"> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoTotalProducto" precioTotal="'.($value['cantidad']*$value['precioventa']).'" name="nuevoTotalProducto" value="'.($value['cantidad']*$value['precioventa']).'" readonly required> </div> </td> <td>'; if ($idVenta == 0){ echo '<span class="input-group-addon"><button type="button" class="btn btn-danger btn-xs quitarProducto" idItem="'.$value['id'].'" ><i class="fa fa-times"></i></button></span> </td>'; } echo ' </tr>'; // GRABO EL ULTIMO ID $item = "id"; $valor = $value['idnrocomprobante']; $datos = $folio2; $respuesta = ControladorComprobantes::ctrUpdateFolioComprobantes($item, $valor,$datos); // ACTUALIZO EL Folio1 $campo = "folio1"; $id = $value['id']; $numero = $folio1; $folios = ControladorComprobantes::ctrUpdateFolio($campo, $id,$numero); // ACTUALIZO EL Folio1 $campo = "folio2"; $id = $value['id']; $numero = $folio2; $folios = ControladorComprobantes::ctrUpdateFolio($campo, $id,$numero); } } // /*============================================= // EDITAR COMPROBANTES // =============================================*/ public $idEscribano; public function ajaxMostrarFc(){ $item = "id_cliente"; $valor = $this->idEscribano; $respuesta = ControladorVentas::ctrMostrarVentasClientes($item, $valor); foreach ($respuesta as $key => $value) { # code... echo '<tr>'. '<td>1</td>'. '<td>'.$respuesta[$key]['fecha'].'</td>'. '<td>'.$respuesta[$key]['tipo'].'</td>'. '<td>'.$respuesta[$key]['codigo'].'</td>'. '<td>ESCRIBANO</td>'. '<td>'.$respuesta[$key]['metodo_pago'].'</td>'. '<td>'.$respuesta[$key]['referenciapago'].'</td>'. '<td>'.$respuesta[$key]['total'].'</td>'. '<td>'.$respuesta[$key]['adeuda'].'</td>'. '</tr>'; } } } /*============================================= EDITAR COMPROBANTES =============================================*/ if(isset($_POST["idComprobante"])){ $categoria = new AjaxComprobantes(); $categoria -> idComprobante = $_POST["idComprobante"]; $categoria -> ajaxEditarComprobante(); } /*============================================= INICIALIZAR COMPROBANTES =============================================*/ if(isset($_POST["iniciar"])){ $comprobantes = new AjaxComprobantes(); $comprobantes -> iniciarComprobantes(); } /*============================================= EDITAR COMPROBANTES todos =============================================*/ if(isset($_POST["todos"])){ $comprobantes = new AjaxComprobantes(); $comprobantes -> idComprobante = $_POST["todos"]; $comprobantes -> ajaxTodosComprobantes(); } /*============================================= INICIALIZAR TABLA TMP =============================================*/ if(isset($_POST["idTmp"])){ $comprobantes = new AjaxComprobantes(); $comprobantes -> idTmp = $_POST["idTmp"]; $comprobantes -> nombreTmp = $_POST["nombreTmp"]; $comprobantes -> numeroTmp = $_POST["numeroTmp"]; $comprobantes -> iniciarCargaComprobantes(); } /*============================================= INICIALIZAR COMPROBANTES =============================================*/ if(isset($_POST["items"])){ $items = new AjaxComprobantes(); $items -> borrarItems(); } /*============================================= AL TOCAR GRABAR ITEM =============================================*/ if(isset($_POST["idNroComprobante"])){ $categoria = new AjaxComprobantes(); $categoria -> cantidadProducto = $_POST["cantidadProducto"]; $categoria -> idproducto = $_POST["idproducto"]; $categoria -> idNroComprobante = $_POST["idNroComprobante"]; $categoria -> cantVentaProducto = $_POST["cantVentaProducto"]; $categoria -> productoNombre = $_POST["productoNombre"]; $categoria -> precioVenta = $_POST["precioVenta"]; $categoria -> idVenta = $_POST['idVenta']; $categoria -> ajaxAgregarItems(); } /*============================================= EDITAR COMPROBANTES =============================================*/ if(isset($_POST["idItem"])){ $categoria = new AjaxComprobantes(); $categoria -> idItem = $_POST["idItem"]; $categoria -> ajaxBorrarItem(); } /*============================================= EDITAR COMPROBANTES =============================================*/ if(isset($_POST["idEscribano"])){ $historico = new AjaxComprobantes(); $historico -> idEscribano = $_POST["idEscribano"]; $historico -> ajaxMostrarFc(); } <file_sep>/modelos/productos.modelo.php <?php require_once "conexion.php"; class ModeloProductos{ /*============================================= MOSTRAR PRODUCTOS =============================================*/ static public function mdlMostrarProductos($tabla, $item, $valor, $orden){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item ORDER BY id DESC"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY nombre DESC"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE PRODUCTO =============================================*/ static public function mdlIngresarProducto($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`nombre`, `descripcion`, `codigo`, `nrocomprobante`, `cantventa`, `id_rubro`, `cantminima`, `cuotas`, `importe`, `obs`) VALUES (:nombre,:descripcion,:codigo,:nrocomprobante,:cantventa,:id_rubro,:cantminima,:cuotas,:importe,:obs)"); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datos["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":nrocomprobante", $datos["nrocomprobante"], PDO::PARAM_INT); $stmt->bindParam(":cantventa", $datos["cantventa"], PDO::PARAM_INT); $stmt->bindParam(":id_rubro", $datos["id_rubro"], PDO::PARAM_INT); $stmt->bindParam(":cantminima", $datos["cantminima"], PDO::PARAM_INT); $stmt->bindParam(":cuotas", $datos["cuotas"], PDO::PARAM_INT); $stmt->bindParam(":importe", $datos["importe"], PDO::PARAM_STR); $stmt->bindParam(":obs", $datos["obs"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } // $stmt->close(); // $stmt = null; } /*============================================= COLOCAR STOCK A CERO =============================================*/ static public function mdlStockNuevo($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET stock = :stock"); $stmt->bindParam(":stock", $datos["stock"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR PRODUCTO =============================================*/ static public function mdlEditarProducto($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre =:nombre, descripcion = :descripcion, codigo = :codigo, nrocomprobante = :nrocomprobante, cantventa = :cantventa , id_rubro = :id_rubro, cantminima = :cantminima, cuotas = :cuotas, importe = :importe, obs = :obs WHERE id = :id"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datos["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":nrocomprobante", $datos["nrocomprobante"], PDO::PARAM_INT); $stmt->bindParam(":cantventa", $datos["cantventa"], PDO::PARAM_INT); $stmt->bindParam(":id_rubro", $datos["id_rubro"], PDO::PARAM_INT); $stmt->bindParam(":cantminima", $datos["cantminima"], PDO::PARAM_INT); $stmt->bindParam(":cuotas", $datos["cuotas"], PDO::PARAM_INT); $stmt->bindParam(":importe", $datos["importe"], PDO::PARAM_STR); $stmt->bindParam(":obs", $datos["obs"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR PRODUCTO =============================================*/ static public function mdlEliminarProducto($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } static public function mdlbKProducto($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } }<file_sep>/modelos/cuotas.modelo.php <?php require_once "conexion.php"; class ModeloCuotas{ /*============================================= MOSTRAR CUOTAS =============================================*/ static public function mdlMostrarCuotas($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } static public function mdlMostrarCuotasEscribano($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= ELIMINAR CUOTA =============================================*/ static public function mdlEliminarVenta($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } // /*============================================= // MOSTRAR OSDE // =============================================*/ // static public function mdlContarOsde($tabla, $item, $valor,$anio){ // $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where tipo ='RE' and MONTH($item)=:valor and YEAR($item)=:anio"); // $stmt->bindParam(":anio", $anio, PDO::PARAM_STR); // $stmt->bindParam(":valor", $valor, PDO::PARAM_STR); // $stmt -> execute(); // return $stmt -> fetchAll(); // $stmt -> close(); // $stmt = null; // } /*============================================= MOSTRAR CUOTAS =============================================*/ // static public function mdlContarCuotas($tabla, $item, $valor,$anio){ // $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where tipo ='CU' and MONTH($item)=:valor and YEAR($item)=:anio"); // $stmt->bindParam(":anio", $anio, PDO::PARAM_STR); // $stmt->bindParam(":valor", $valor, PDO::PARAM_STR); // $stmt -> execute(); // return $stmt -> fetchAll(); // $stmt -> close(); // $stmt = null; // } /*============================================= INGRESO DE CUOTAS =============================================*/ static public function mdlIngresarCuota($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,tipo,id_cliente,nombre,documento,productos,total) VALUES (:fecha,:tipo,:id_cliente,:nombre,:documento, :productos, :total)"); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } static public function mdlChequearGeneracion($tabla, $datos){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where nombre=:tipo and mes =:mes and anio =:anio"); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":mes", $datos["mes"], PDO::PARAM_STR); $stmt->bindParam(":anio", $datos["anio"], PDO::PARAM_INT); $stmt->execute(); return $stmt -> fetch(); $stmt->close(); $stmt = null; } static public function mdlIngresarGeneracionCuota($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`fecha`, `nombre`, `mes`, `anio`, `cantidad`) VALUES (:fecha,:nombre,:mes,:anio, :cantidad)"); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":mes", $datos["mes"], PDO::PARAM_STR); $stmt->bindParam(":anio", $datos["anio"], PDO::PARAM_INT); $stmt->bindParam(":cantidad", $datos["cantidad"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } static public function mdlEscribanosConDeuda($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE id_cliente = :id order by fecha asc"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlEscribanosDeuda($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE id_cliente = :id order by fecha asc limit 1"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= ACTUALIZAR INHABILITADO =============================================*/ static public function mdlEscribanosInhabilitar($tabla, $valor){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET inhabilitado = 1 WHERE id = :id"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= ACTUALIZAR HABILITADO =============================================*/ static public function mdlHabilitarUnEscribano($tabla, $valor){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET inhabilitado = 0 WHERE id = :id"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= ACTUALIZAR HABILITADO =============================================*/ static public function mdlEscribanosHabilitar($tabla){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET inhabilitado = 0"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlContarCuotayOsde($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT count(*) FROM $tabla WHERE $item = :tipo"); $stmt->bindParam(":tipo", $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= ACTUALIZAR INHABILITADO =============================================*/ static public function mdlModificarCuota($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET total =:importe WHERE id = :id"); $stmt->bindParam(":importe", $datos["importe"], PDO::PARAM_STR); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlModificarCuotaProductos($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET productos =:productos WHERE id = :id"); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/vistas/modulos/iniciosinconexion.php <div class="content-wrapper"> <section class="content-header"> <h1> Tablero <small>Panel de Control</small> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Tablero</li> </ol> </section> <section class="content"> <!-- <div class="box box-primary"> --> <div class="box-body"> <?php $cantInhabilitados =0; #SE REVISA A LOS DEUDORES $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanos as $key => $value) { # code... if($value['inhabilitado'] == 1){ $cantInhabilitados++; } } #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $orden ="id"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); /*============================================= = GENERO LA CAJA = =============================================*/ $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); if(count($caja)==0){ $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>0, "tarjeta"=>0, "cheque"=>0, "transferencia"=>0); $insertarCaja = ControladorCaja::ctrIngresarCaja($item, $datos); } ?> <div class="col-md-6"> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-aqua-active"> <h3 class="widget-user-username">ESCRIBANOS</h3> <h5 class="widget-user-desc">Actualizacion en Nube</h5> </div> <a href="escribanos"> <div class="widget-user-image"> <img class="img-circle" src="vistas/img/usuarios/admin/escribanos.jpg" alt="User Avatar"> </div> </a> <div class="box-footer"> <div class="row"> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header" style="color:red;"><button class="btn btn-link" id="btnMostrarInhabilitados"><?php echo $cantInhabilitados;?></button></h5> <span class="description-text" style="color:red;">INHABILITADOS</span> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header"><button class="btn btn-link" id="btnMostrarEscribanos"><?php echo count($escribanos);?></button></h5> <span class="description-text">TODOS</span> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4"> <div class="description-block"> <h5 class="description-header"><button class="btn btn-link" id="btnMostrarProductos"><?php echo count($productos);?></button></h5> <span class="description-text">PRODUCTOS</span> </div> <!-- /.description-block --> </div> <!-- /.col --> </div> <!-- /.row --> </div> </div> <!-- /.widget-user --> </div> <?php /*========================================== = CANTIDAD DE VENTAS = ==========================================*/ $item = "fecha"; $valor= date('Y-m-d'); $ventas = ControladorVentas::ctrMostrarVentasFecha($item, $valor); // /*===== End of CANTIDAD DE VENTAS ======*/ ?> <div class="col-md-3"> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-yellow"> <h3 class="widget-user-username">VENTAS</h3> <h5 class="widget-user-desc">Formosa</h5> </div> <a href="crear-venta"> <div class="widget-user-image"> <img class="img-circle" src="vistas/img/usuarios/admin/colegio.jpg" alt="User Avatar"> </div> </a> <div class="box-footer"> <div class="row"> <!-- /.col --> <div class="col-sm-12"> <div class="description-block"> <h5 class="description-header"><?php echo count($ventas); ?></h5> <span class="description-text">FORMOSA</span> </div> <!-- /.description-block --> </div> <!-- /.col --> <!-- /.col --> </div> <!-- /.row --> </div> </div> <!-- /.widget-user --> </div> <div id="modalLoader" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" id="cabezaLoader" style="background:#3c8dbc;color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Aguarde un instante</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <center> <img src="vistas/img/afip/loader.gif" alt=""> </center> </div> </div> <div class="modal-footer"> <p id="actualizacionparrafo"></p> </div> </div> </div> </div> <div id="modalMostar" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" id="cabezaLoader" style="background:#3c8dbc;color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title" id="titulo"></h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body" id="mostrarBody"> </div> </div> <div class="modal-footer"> <button type="button" id="mostrarSalir" class="btn btn-danger" data-dismiss="modal">Salir</button> </div> </div> </div> </div> </div> </section> </div> <file_sep>/vistas/modulos/crear-venta.php <style> .panel-primary>.panel-heading { color: #fff; background-color: #17a2b8; border-color: #17a2b8; } .box.box-primary { border-top-color: #17a2b8; } .panel-primary{ border-color:#17a2b8; } </style> <?php // FECHA DEL DIA DE HOY $fecha=date('d-m-Y'); $item = "parametro"; $valor = 'maxAtraso'; $atraso = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); $item = "parametro"; $valor = 'maxLibro'; $libro = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); //ULTIMO NUMERO DE VENTAS $item = "nombre"; $valor = "ventas"; $registro = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); $puntoVenta = $registro["cabezacomprobante"]; // FORMATEO EL NUMERO DE COMPROBANTE $ultimoComprobanteAprox=$registro["numero"]+1; $cantRegistro = strlen($ultimoComprobanteAprox); switch ($cantRegistro) { case 1: $ultimoComprobante="0000000".$ultimoComprobanteAprox; break; case 2: $ultimoComprobante="000000".$ultimoComprobanteAprox; break; case 3: $ultimoComprobante="00000".$ultimoComprobanteAprox; break; case 4: $ultimoComprobante="0000".$ultimoComprobanteAprox; break; case 5: $ultimoComprobante="000".$ultimoComprobanteAprox; break; case 6: $ultimoComprobante="00".$ultimoComprobanteAprox; break; case 7: $ultimoComprobante="0".$ultimoComprobanteAprox; break; case 8: $ultimoComprobante=$ultimoComprobanteAprox; break; } $cantCabeza = strlen($puntoVenta); switch ($cantCabeza) { case 1: $ptoVenta="000".$puntoVenta; break; case 2: $ptoVenta="00".$puntoVenta; break; case 3: $ptoVenta="0".$puntoVenta; break; } $codigoFacturaAprox = $ptoVenta .'-'. $ultimoComprobante; ?> <style> #tablaModelo { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } #tablaModelo td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } #tablaModelo tr:nth-child(even) { background-color: #dddddd; } </style> <div class="content-wrapper"> <section class="content"> <form method="post" class="formularioVenta" name="frmVenta" id="frmVenta"> <div class="row" style="background-color: #f8f9fa; color:#343a40"> <!--===================================================== PANEL IZQUIERDO ========================================================--> <div class="col-md-3" style="margin-top: 10px;"> <div class="panel panel-primary"> <div class="panel-heading" id="headPanel"> <h4 style="text-align:center">Datos de la Factura</h4> </div> <div class="panel-body"> <div class="col-xs-12"> <label for="nombre">NRO. FC</label> <input type="text" class="form-control" id='nuevaVenta' name='nuevaVenta' autocomplete="off" value="<?php echo $codigoFacturaAprox;?>" style="text-align: center;" readonly> <input type='hidden' id='idVendedor' name='idVendedor' value='<?php echo $_SESSION["id"];?>'> </div> <div class="col-xs-12 "> <input type='hidden' id='seleccionarCliente' name='seleccionarCliente'> <input type="text" class="form-control" placeholder="NOMBRE...." id='nombreCliente' name='nombreCliente' value='' autocomplete="off" style="margin-top: 5px" readonly> <input type='hidden' id='documentoCliente' name='documentoCliente'> <input type='hidden' id='tipoDocumento' name='tipoDocumento'> <input type='hidden' id='tipoCliente' name='tipoCliente' value="consumidorfinal"> <input type='hidden' id='categoria' name='categoria' value="SinCategoria"> </div> <div class="col-xs-12 text-success" style="text-align: center;font-weight: bold;" id="msgCategoria"></div> <div class="col-xs-12"> <button type="button" id="btnBuscarNombreClienteFc" class="btn btn-primary btn-block btnBuscarCliente" data-toggle="modal" data-target="#myModalClientes" style="margin-top: 5px;" autofocus>Seleccionar Escribano o Cliente</button> </div> <div class="col-xs-12"> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <option value="CTA.CORRIENTE">CTA.CORRIENTE</option> <option value="EFECTIVO" selected>EFECTIVO</option> <option value="TARJETA">TARJETA</option> <option value="CHEQUE">CHEQUE</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> </select> </div> <div class="col-xs-12"> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div> <input type="hidden" id="nuevoPrecioImpuesto" name="nuevoPrecioImpuesto" value="0"> <input type="hidden" id="nuevoPrecioNeto" name="nuevoPrecioNeto" value="0"> <input type="hidden" id="nuevoTotalVentas" name="nuevoTotalVentas" value="0"> <div class="col-xs-12"> <button type="button" class="btn btn-info btn-block" data-toggle="modal" data-target="#myModalProductos" style="margin-top: 5px;"> Articulos </button> </div> </div> </div> </div> <!--===================================================== TABLA DE ARTICULOS ========================================================--> <div class="col-md-9" style="margin-top: 10px;" id="articulosP"> <div class="box box-primary"> <div class="box-header with-border" id="headPanelItems" style="background-color: #17a2b8; color:white"> <h3 class="box-title pull-right">Articulos</h3> <button id="reiniciar" type="button" class="btn bg-navy btn-flat btn-xs pull-left">Actualizar <i class="glyphicon glyphicon-refresh"></i> Reiniciar</button> </div> <!-- /.box-header --> <div class="box-body no-padding" id="datosTabla"> <table class="table table-bordered tablaProductosVendidos"> <thead> <tr> <th style="width: 10px;">#</th> <th style="width: 10px;">Cantidad</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 150px;">Precio</th> <th style="width: 200px;">Total</th> <th style="width: 100px;">Op.</th> </tr> </thead> <tbody class="tablaProductosSeleccionados"></tbody> <tfooter> <tr> <td colspan="8"><div class="col-xs-2">Escribano: </div> <strong> <div class="col-xs-3" id="panel3nombrecliente"> S/REFERENCIA </div> </strong> <div class="col-xs-2">Categoria: </div> <strong> <div class="col-xs-2" id="panel3TipoCLiente"> S/REFERENCIA </div> </strong> </td> </tr> </tfooter> </table> <input type="hidden" id="listaProductos" name="listaProductos"> </div> <div class="box-footer" style="background-color: #FAFAFA"> <div class="col-xs-12"> <input type="hidden" id="totalVenta" name="totalVenta" value="0"> <h1><div id="totalVentasMostrar" class="pull-right">0.00</div></h1> </div> <div class="col-xs-12"> <button type="button" class="btn btn-danger pull-right" id="guardarVenta" style="margin-top: 10px;" disabled>Guardar Venta </button> </div> </div> </div> </div> </div> </form> <?php // $guardarVenta = new ControladorVentas(); // $guardarVenta -> ctrCrearVenta(); ?> </section> </div> <!--===================================== MODAL PARA BUSCAR CLIENTES ======================================--> <div id="myModalClientes" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header " style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Seleccione escribano</h4> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteDni"> x DNI</button> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteCuit"> x CUIT</button> <button class="btn btn-info pull-right" id="consumidorFinal" data-dismiss="modal" idCliente="1" nombreCliente="<NAME>" documentoCliente="0" tipoDocumento="SINCUIT" tipoCLiente="consumidorfinal" >Consumidor Final</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalEscribanos"> Escribanos</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalClientes"> Clientes</button> </div> <div class="modal-body" > <div id="datos_ajax"></div> <table id="buscarclientetabla" class="table table-striped table-condensed table-hover tablaBuscarClientes"> <thead> <tr> <th width="150">nombre</th> <th width="80">documento</th> <th width="80">cuit</th> <th width="10">libros</th> <th width="180">opciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); $item = "parametro"; $valor = "maxLibro"; $parametros = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); foreach ($clientes as $key => $value) { $item = 'id'; $valor = $value["id_categoria"]; $categoria = ControladorCategorias::ctrMostrarCategorias($item, $valor); $cantLibros =$value["ultimolibrocomprado"]-$value["ultimolibrodevuelto"]; echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td>'.$value["documento"].'</td>'; echo '<td>'.$value["cuit"].'</td>'; echo '<td>'.$cantLibros.'</td>'; //CONSULTO SI ESTA ATRASADO O AL DIA 1==NO TIENE DEUDA A FACTURAR if($value["cuit"]!='0'){ if($value["inhabilitado"]==0){ if ($value["facturacion"]=="DNI"){ echo '<td><button class="btn btn-primary btnBuscarCliente" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["documento"].'" tipoDocumento="'.$value["facturacion"].'" categoria="'.$categoria["categoria"].'" tipoCLiente="escribanos" >Seleccionar</button></td>'; }else{ if ($cantLibros<=$parametros["valor"]){ echo '<td><button class="btn btn-primary btnBuscarCliente" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["cuit"].'" tipoDocumento="'.$value["facturacion"].'" categoria="'.$categoria["categoria"].'" tipoCLiente="escribanos" ">Seleccionar</button></td>'; }else{ echo '<td><button class="btn btn-danger" data-dismiss="modal">Inhabilitado (Libros)</button></td>'; } } }else{ echo '<td><button class="btn btn-default btnInhabilitado"><a href="index.php?ruta=historico&idEscribano='.$value["id"].'&tipo=cuotas" style="text-color:white;">Inhabilitado</a></button></td>'; } }else{ if ($value["id"]=='1'){ echo '<td><button class="btn btn-primary btnBuscarCliente" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["cuit"].'" tipoDocumento="'.$value["facturacion"].'" categoria="categoria" tipoCLiente="consumidorfinal" >Seleccionar</button></td>'; }else{ echo '<td><button class="btn btn-danger" data-dismiss="modal">No tiene datos de afip</button></td>'; } } } echo '</tr>'; $item = null; $valor = null; $clientes2 = ControladorClientes::ctrMostrarClientes($item, $valor); foreach ($clientes2 as $key => $value) { echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td> - - </td>'; echo '<td>'.$value["cuit"].'</td>'; echo '<td> - - </td>'; echo '<td><button class="btn btn-primary btnBuscarCliente2" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["cuit"].'" tipoDocumento="CUIT" categoria="categoria" tipoCLiente="clientes">Seleccionar</button></td>'; echo '</tr>'; } $item = null; $valor = null; $delegaciones = ControladorDelegaciones::ctrMostrarDelegaciones($item, $valor); foreach ($delegaciones as $key => $value) { echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td> - - </td>'; echo '<td> - - </td>'; echo '<td> - - </td>'; echo '<td><button class="btn btn-primary btnBuscarDelegacion" data-dismiss="modal" idDelegacion='.$value["id"].' categoria="categoria" nombreDelegacion="'.$value["nombre"].'">Seleccionar</button></td>'; echo '</tr>'; } ?> </tbody> </table> </div><!-- Modal body--> <div class="modal-footer"> <!-- <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarCliente'>Cerrar</button> --> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!-- Modal --> <!-- Modal --> <!--===================================== MODAL SOLO ESCRIBANOS ======================================--> <div id="modalEscribanos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header " style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Solo escribanos Habilitados</h4> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteDni"> x DNI</button> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteCuit"> x CUIT</button> <button class="btn btn-info pull-right" id="consumidorFinal" data-dismiss="modal" idCliente="1" nombreCliente="<NAME>" documentoCliente="0" tipoDocumento="SINCUIT" tipoCLiente="consumidorfinal" >Consumidor Final</button> <button type="button" class="btn btn-info" data-dismiss="modal" data-toggle="modal" data-target="#myModalClientes"> Todos</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalClientes"> Clientes</button> </div> <div class="modal-body"> <div id="datos_ajax"></div> <table id="buscarclientetabla" class="table table-striped table-condensed table-hover tablaBuscarClientes"> <thead> <tr> <th width="150">nombre</th> <th width="80">documento</th> <th width="80">cuit</th> <th width="10">libros</th> <th width="180">opciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); $item = "parametro"; $valor = "maxLibro"; $parametros = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); foreach ($clientes as $key => $value) { if($value["cuit"]!='0' && $value["inhabilitado"]==0){ $item = 'id'; $valor = $value["id_categoria"]; $categoria = ControladorCategorias::ctrMostrarCategorias($item, $valor); $cantLibros =$value["ultimolibrocomprado"]-$value["ultimolibrodevuelto"]; echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td>'.$value["documento"].'</td>'; echo '<td>'.$value["cuit"].'</td>'; echo '<td>'.$cantLibros.'</td>'; echo '<td><button class="btn btn-primary btnBuscarCliente" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["cuit"].'" tipoDocumento="'.$value["facturacion"].'" categoria="'.$categoria["categoria"].'" tipoCLiente="escribanos" >Seleccionar</button></td>'; //CONSULTO SI ESTA ATRASADO O AL DIA 1==NO TIENE DEUDA A FACTURAR } } echo '</tr>'; $item = null; $valor = null; $delegaciones = ControladorDelegaciones::ctrMostrarDelegaciones($item, $valor); foreach ($delegaciones as $key => $value) { echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td> - - </td>'; echo '<td> - - </td>'; echo '<td> - - </td>'; echo '<td><button class="btn btn-primary btnBuscarDelegacion" data-dismiss="modal" idDelegacion='.$value["id"].' categoria="categoria" nombreDelegacion="'.$value["nombre"].'">Seleccionar</button></td>'; echo '</tr>'; } ?> </tbody> </table> </div><!-- Modal body--> <div class="modal-footer"> <!-- <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarCliente'>Cerrar</button> --> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!-- Modal --> <!-- Modal --> <!--===================================== MODAL PARA BUSCAR CLIENTES ======================================--> <div id="modalClientes" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header " style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Solo Clientes</h4> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteDni"> x DNI</button> <button type="button" class="btn btn-warning" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteCuit"> x CUIT</button> <button class="btn btn-info pull-right" id="consumidorFinal" data-dismiss="modal" idCliente="1" nombreCliente="<NAME>" documentoCliente="0" tipoDocumento="SINCUIT" tipoCLiente="consumidorfinal" >Consumidor Final</button> <button type="button" class="btn btn-info" data-dismiss="modal" data-toggle="modal" data-target="#myModalClientes"> Todos</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalEscribanos"> Escribanos</button> </div> <div class="modal-body"> <div id="datos_ajax"></div> <table id="buscarclientetabla" class="table table-striped table-condensed table-hover tablaBuscarClientes"> <thead> <tr> <th width="150">nombre</th> <th width="80">documento</th> <th width="80">cuit</th> <th width="10">libros</th> <th width="180">opciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes2 = ControladorClientes::ctrMostrarClientes($item, $valor); foreach ($clientes2 as $key => $value) { echo '<tr>'; echo '<td>'.$value["nombre"].'</td>'; echo '<td> - - </td>'; echo '<td>'.$value["cuit"].'</td>'; echo '<td> - - </td>'; echo '<td><button class="btn btn-primary btnBuscarCliente2" data-dismiss="modal" idCliente='.$value["id"].' nombreCliente="'.$value["nombre"].'" documentoCliente="'.$value["cuit"].'" tipoDocumento="CUIT" categoria="categoria" tipoCLiente="clientes">Seleccionar</button></td>'; echo '</tr>'; } ?> </tbody> </table> </div><!-- Modal body--> <div class="modal-footer"> <!-- <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarCliente'>Cerrar</button> --> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!-- Modal --> <!-- Modal --> <div id="myModalProductos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Seleccionar articulo</h4> </div> <div class="modal-body" > <div id="datos_ajax_producto"></div> <div id="contenidoSeleccionado" style="display: none"> <div class="row"> <div class="col-xs-2"> <label for="cantidadProducto">CANT.</label> <input type="text" class="form-control" id="cantidadProducto" name="cantidadProducto" autocomplete="off" value="1"> <input type="hidden" class="form-control" id="idproducto" name="idproducto"> <input type="hidden" class="form-control" id="idNroComprobante" name="idNroComprobante"> <input type="hidden" class="form-control" id="cantVentaProducto" name="cantVentaProducto"> <input type="hidden" class="form-control" id="idVenta" name="idVenta" value="0"> </div> <div class="col-xs-5"> <label for="nombreProducto">PRODUCTO</label> <input type="text" class="form-control" id="nombreProducto" name="nombreProducto" disabled> </div> <div class="col-xs-3"> <label for="precioProducto">PRECIO</label> <input type="number" class="form-control" id="precioProducto" name="precioProducto" autocomplete="off" > </div> <div class="col-xs-2"> <button class="btn btn-primary" style="margin-top: 25px" id="grabarItem">Grabar</button> </div> </div> </div> <div id="contenido_producto"> <table id="buscararticulotabla" class="table table-bordered table-striped tablaBuscarProductos" width="100%"> <thead> <tr> <th width="10">id</th> <th>nombre</th> <th>precio</th> <th>opciones</th> </tr> </thead> <tbody> </tbody> </table> </div> </div><!-- Modal body--> <div class="modal-footer"> <!-- <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarProducto'>Cerrar</button> --> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> </div> </div> <div id="modalLoader" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Aguarde un instante</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <center> <img src="vistas/img/afip/loader.gif" alt=""> </center> <center> <img src="vistas/img/afip/afip.jpg" alt=""> </center> </div> </div> <div class="modal-footer"> <p><strong>CONECTANDOSE AL SERVIDOR DE AFIP</strong></p> </div> </div> </div> </div> <div id="modalClienteDni" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Ingrese los Datos del Cliente <button type="button" class="btn btn-warning pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteCuit">cambiar a CUIT </button></h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="nombreClienteEventual" id="nombreClienteEventual" placeholder="Ingresar Nombre" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="number" class="form-control input-lg" name="documentoClienteEventual" id="documentoClienteEventual" placeholder="Ingresar Dni" required> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" id="seleccionarClienteDni">Ingresar Datos</button> </div> </div> </div> </div> <div id="modalClienteCuit" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Ingrese los Datos del Cliente <button type="button" class="btn btn-warning pull-right" data-dismiss="modal" data-toggle="modal" data-target="#modalClienteDni">cambiar a DNI </button></h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="nombreAgregarCliente" id="nombreAgregarCliente" placeholder="Ingresar Nombre" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL CUIT --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="number" class="form-control input-lg" name="documentoAgregarCliente" id="documentoAgregarCliente" placeholder="Ingresar Cuit" required> </div> </div> <!-- ENTRADA PARA SELECCIONAR CATEGORÍA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="tipoCuitAgregarCliente" name="tipoCuitAgregarCliente" required> <option value="">Selecionar categoría</option> <?php $item = null; $valor = null; $categorias = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.$value["nombre"].'">'.$value["nombre"].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA LA DIRECCION --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="text" class="form-control input-lg" name="direccionAgregarCliente" id="direccionAgregarCliente" placeholder="Ingresar Direccion" required> </div> </div> <!-- ENTRADA PARA LA LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="text" class="form-control input-lg" name="localidadAgregarCliente" id="localidadAgregarCliente" placeholder="Ingresar Localidad" required> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" id="seleccionarClientCuit">Ingresar Datos</button> </div> </div> </div> </div><file_sep>/modelos/escribanos.modelo.php <?php require_once "conexion.php"; class ModeloEscribanos{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function mdlMostrarEscribanos($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item and activo = 1"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where activo = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR ESCRIBANOS INHABILITADPS =============================================*/ static public function mdlMostrarEscribanosInhabilitados($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where inhabilitado = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR ESCRIBANOS INHABILITADOS =============================================*/ static public function mdlMostrarInhabilitado($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id,inhabilitado FROM $tabla where activo = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR ESCRIBANOS INHABILITADOS =============================================*/ static public function mdlMostrarEstado($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT id,inhabilitado FROM $tabla WHERE $item = :$item and activo = 1"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT id,inhabilitado FROM $tabla where activo = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR ESCRIBANOS =============================================*/ static public function mdlIngresarEscribano($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`nombre`,`documento`,`id_tipo_iva`,`cuit`, `direccion`,`localidad`, `telefono`,`email` , `id_categoria`,`id_escribano_relacionado`, `id_osde`,matricula_ws) VALUES (:nombre,:documento,:id_iva,:cuit,:direccion,:localidad,:telefono,:email,:id_categoria,:id_escribano_relacionado,:id_osde,:matricula_ws)"); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_INT); $stmt->bindParam(":id_iva", $datos["id_iva"], PDO::PARAM_INT); $stmt->bindParam(":cuit", $datos["cuit"], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); $stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR); $stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR); $stmt->bindParam(":id_categoria", $datos["id_categoria"], PDO::PARAM_INT); $stmt->bindParam(":id_escribano_relacionado", $datos["id_escribano_relacionado"], PDO::PARAM_INT); $stmt->bindParam(":id_osde", $datos["id_osde"], PDO::PARAM_INT); $stmt->bindParam(":matricula_ws", $datos["matricula_ws"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= ELIMINAR ESCRIBANO =============================================*/ static public function mdlEliminarEscribano($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= EDITAR ESCRIBANO =============================================*/ static public function mdlEditarEscribano($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, documento = :documento,id_tipo_iva = :id_tipo_iva,cuit =:cuit,direccion = :direccion ,localidad = :localidad, telefono = :telefono, email = :email, id_categoria = :id_categoria, id_escribano_relacionado =:id_escribano_relacionado,id_osde = :id_osde,matricula_ws=:matricula_ws WHERE id = :id"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_INT); $stmt->bindParam(":id_tipo_iva", $datos["id_tipo_iva"], PDO::PARAM_INT); $stmt->bindParam(":cuit", $datos["cuit"], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); $stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR); $stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR); $stmt->bindParam(":id_categoria", $datos["id_categoria"], PDO::PARAM_INT); $stmt->bindParam(":id_escribano_relacionado", $datos["id_escribano_relacionado"], PDO::PARAM_INT); $stmt->bindParam(":id_osde", $datos["id_osde"], PDO::PARAM_INT); $stmt->bindParam(":matricula_ws", $datos["matricula_ws"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlbKEscribano($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/modelos/osde.modelo.php <?php require_once "conexion.php"; class ModeloOsde{ /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlIngresarOsde($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre,importe) VALUES (:nombre,:importe)"); $stmt -> bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt -> bindParam(":importe", $datos["importe"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function mdlMostrarOsde($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function mdlEditarOsde($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, importe = :importe WHERE id = :id"); $stmt -> bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt -> bindParam(":importe", $datos["importe"], PDO::PARAM_STR); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR OSDE =============================================*/ static public function mdlBorrarOsde($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= BORRAR OSDE =============================================*/ static public function mdlBorrarTodosOsde($tabla){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla"); if($stmt -> execute()){ $stmt = Conexion::conectar()->prepare("UPDATE escribanos set id_osde=0"); if($stmt -> execute()){ return "ok"; }else{ return "error"; } }else{ return "error"; } $stmt -> close(); $stmt = null; } static public function mdlbKOsde($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/ajax/updateProductos.ajax.php <?php require_once "../controladores/productos.controlador.php"; require_once "../modelos/productos.modelo.php"; require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; class AjaxUpdateProductos{ /*============================================= ACTUALIZAR PRODUCTOS =============================================*/ public function ajaxActualizarProductos(){ #ELIMINAR PRODUCTOS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('productos'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $orden = "id"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); // $cantidadProductos = count($productos); $cant=0; foreach ($productos as $key => $value) { # code... if($value['ver']==1){ $tabla ="productos"; $datos = array("id" => $value["id"], "nombre" => strtoupper($value["nombre"]), "descripcion" => strtoupper($value["descripcion"]), "codigo" => $value["codigo"], "nrocomprobante" => $value["nrocomprobante"], "cantventa" => $value["cantventa"], "id_rubro" => $value["id_rubro"], "cantminima" => $value["cantminima"], "cuotas" => $value["cuotas"], "importe" => $value["importe"], "obs" => $value["obs"]); $cant ++; #registramos los productos $respuesta = ModeloEnlace::mdlIngresarProducto($tabla, $datos); } } /*=========================================== = CONSULTAR SI EXISTEN MODIFICACIONES = ===========================================*/ $tabla ="modificaciones"; $datos = array("nombre"=>"productos","fecha"=>date("Y-m-d")); $modificaciones = ModeloEnlace::mdlConsultarModificaciones($tabla,$datos); if(!$modificaciones[0]>=1){ //SI NO EXISTE CREO UNA NUEVA FILA $datos = array("nombre"=>"productos","fecha"=>date("Y-m-d")); ControladorEnlace::ctrSubirModificaciones($datos); }else{ //SI EXISTE ACTUALIZO A CERO $datos = array("nombre"=>"productos","fecha"=>date("Y-m-d")); ControladorEnlace::ctrUpdateModificaciones($datos); } } /*============================================= MOSTRAR PRODUCTOS =============================================*/ public function ajaxMostrarProductos(){ echo '<script>$(".tablaMostrarAjax").DataTable({ "lengthMenu": [[5, 10, 25], [5, 10, 25]], dom: "lBfrtip",buttons: [ { extend: "colvis", columns: ":not(:first-child)", } ], "language": { "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ registros", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_", "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0", "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": Activar para ordenar la columna de manera ascendente", "sSortDescending": ": Activar para ordenar la columna de manera descendente" } } })</script>'; echo '<table class="table table-bordered table-striped dt-responsive tablaMostrarAjax" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Importe</th> </tr> </thead> <tbody>'; $item = null; $valor = null; $orden = "id"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); foreach ($productos as $key => $value) { echo ' <tr> <td>'.($key+1).'</td> <td class="text-uppercase">'.$value["nombre"].'</td> <td class="text-uppercase">'.$value["importe"].'</td> </tr>'; } echo' </tbody> </table>'; } } /*============================================= EDITAR CATEGORÍA =============================================*/ if(isset($_POST["updateProductos"])){ $productos = new AjaxUpdateProductos(); $productos -> ajaxActualizarProductos(); } /*============================================= EDITAR CATEGORÍA =============================================*/ if(isset($_POST["mostrarProductos"])){ $productos = new AjaxUpdateProductos(); $productos -> ajaxMostrarProductos(); }<file_sep>/ajax/delegaciones.ajax.php <?php require_once "../controladores/delegaciones.controlador.php"; require_once "../modelos/delegaciones.modelo.php"; class AjaxDelegaciones{ // /*============================================= // CREO LA NUEVA DELEGACION // =============================================*/ public function ajaxCrearDelegaciones(){ #CREO UN NUEVO CLIENTE $datos = array("nombre"=>strtoupper($_POST["nombreDelegacion"]), "direccion"=>$_POST["direccion"], "localidad"=>strtoupper($_POST["localidad"]), "telefono"=>strtoupper($_POST["telefono"]), "puntodeventa"=>strtoupper($_POST["puntodeventa"]), "idescribano"=>$_POST["idescribano"], "escribano"=>strtoupper($_POST["escribano"])); $respuesta = ControladorDelegaciones::ctrIngresarDelegacion($datos); return $respuesta; } /*============================================= EDITAR DELEGACION =============================================*/ public $idDelegacion; public function ajaxBuscarDelegacion(){ $item = "id"; $valor = $this->idDelegacion; $respuesta = ControladorDelegaciones::ctrMostrarDelegaciones($item, $valor); echo json_encode($respuesta); } // /*============================================= // EDITAR DELEGACION // =============================================*/ public function ajaxEditarDelegacion(){ #CREO UN NUEVO CLIENTE $datos = array("id"=>strtoupper($_POST["idEditar"]), "nombre"=>strtoupper($_POST["nombreDelegacionEditar"]), "direccion"=>$_POST["direccionEditar"], "localidad"=>strtoupper($_POST["localidadEditar"]), "telefono"=>strtoupper($_POST["telefonoEditar"]), "puntodeventa"=>strtoupper($_POST["puntodeventaEditar"]), "idescribano"=>$_POST["idescribanoEditar"], "escribano"=>strtoupper($_POST["escribanoEditar"])); $respuesta = ControladorDelegaciones::ctrEditarDelegacion($datos); // print_r ($datos); } } /*============================================= CREAR NUEVA DELEGACION =============================================*/ if(isset($_POST["nombreDelegacion"])){ $delegaciones = new AjaxDelegaciones(); $delegaciones -> ajaxCrearDelegaciones(); } /*============================================= BUSCAR DELEGACION =============================================*/ if(isset($_POST["idDelegacion"])){ $delegacion = new AjaxDelegaciones(); $delegacion -> idDelegacion = $_POST["idDelegacion"]; $delegacion -> ajaxBuscarDelegacion(); } /*============================================= EDITAR DELEGACION =============================================*/ if(isset($_POST["nombreDelegacionEditar"])){ $delegaciones = new AjaxDelegaciones(); $delegaciones -> ajaxEditarDelegacion(); } <file_sep>/controladores/empresa.controlador.php <?php class ControladorEmpresa{ /*============================================= MOSTRAR USUARIO =============================================*/ static public function ctrMostrarEmpresa($item, $valor){ $tabla = "empresa"; $respuesta = ModeloEmpresa::mdlMostrarEmpresa($tabla, $item, $valor); return $respuesta; } /*============================================= EDITAR EMPRESA DATOS =============================================*/ static public function ctrEditarEmpresa($datos){ $tabla = "empresa"; $respuesta = ModeloEmpresa::mdlEditarEmpresa($tabla, $datos); return $respuesta; } /*============================================= ACTUALIZAR LOGO O ICONO =============================================*/ static public function ctrActualizarImagen($item, $valor){ $tabla = "empresa"; $id = 1; $empresa = ModeloEmpresa::mdlSeleccionarEmpresa($tabla); /*============================================= CAMBIANDO LOGOTIPO O ICONO =============================================*/ if(isset($valor["tmp_name"])){ list($ancho, $alto) = getimagesize($valor["tmp_name"]); /*============================================= CAMBIANDO LOGOTIPO =============================================*/ unlink("../".$empresa[$item]); switch ($item) { case 'backend': $nuevoAncho = 1000; $nuevoAlto = 633; $nombre ="back"; $carpeta="plantilla"; break; case 'iconochicoblanco': $nuevoAncho = 172; $nuevoAlto = 172; $nombre ="icono-blanco"; $carpeta="plantilla"; break; case 'iconochiconegro': $nuevoAncho = 172; $nuevoAlto = 172; $nombre ="icono-negro"; $carpeta="plantilla"; break; case 'logoblancobloque': $nuevoAncho = 500; $nuevoAlto = 183; $nombre ="logo-blanco-bloque"; $carpeta="plantilla"; break; case 'logonegrobloque': $nuevoAncho = 500; $nuevoAlto = 183; $nombre ="logo-negro-bloque"; $carpeta="plantilla"; break; case 'logoblancolineal': $nuevoAncho = 800; $nuevoAlto = 117; $nombre ="logo-blanco-lineal"; $carpeta="plantilla"; break; case 'logonegrolineal': $nuevoAncho = 800; $nuevoAlto = 117; $nombre ="logo-negro-lineal"; $carpeta="plantilla"; break; case 'fotorecibo': $nuevoAncho = 500; $nuevoAlto = 183; $nombre ="logoimpreso"; $carpeta="empresa"; break; default: # code... break; } $destino = imagecreatetruecolor($nuevoAncho, $nuevoAlto); if($valor["type"] == "image/jpeg"){ $ruta = "../vistas/img/".$carpeta."/".$nombre.".jpg"; $origen = imagecreatefromjpeg($valor["tmp_name"]); imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto); imagejpeg($destino, $ruta); $valorNuevo = "vistas/img/".$carpeta."/".$nombre.".jpg"; } if($valor["type"] == "image/png"){ $ruta = "../vistas/img/".$carpeta."/".$nombre.".png"; $origen = imagecreatefrompng($valor["tmp_name"]); imagealphablending($destino, FALSE); imagesavealpha($destino, TRUE); imagecopyresized($destino, $origen, 0, 0, 0, 0, $nuevoAncho, $nuevoAlto, $ancho, $alto); imagepng($destino, $ruta); $valorNuevo = "vistas/img/".$carpeta."/".$nombre.".png"; } } $id = 1; $respuesta = ModeloEmpresa::mdlActualizarLogoIcono($tabla, $id, $item, $valorNuevo); return $respuesta; } } <file_sep>/vistas/js/remitos.js $(".tablas").on("click", ".btnEditarPagoRemito", function(){ let idVenta = $(this).attr("idVenta") let adeuda = $(this).attr("adeuda") $("#idVentaPago").val(idVenta) $("#totalVentaPago").val(adeuda) }) /*============================================= BOTON VER VENTA =============================================*/ $(".tablas").on("click", ".btnVerRemito", function(){ var idVenta = $(this).attr("idVenta"); var codigo = $(this).attr("codigo"); console.log("codigo", codigo); $(".finFactura #imprimirItems").remove(); boton = '<a href="extensiones/tcpdf/pdf/remito.php?id='+idVenta+'" target="_blank" id="imprimirItems"><button type="button" class="btn btn-info pull-left">Imprimir Factura</button></a>'; $(".finFactura").append(boton); $(".tablaArticulosVer").empty(); var datos = new FormData(); datos.append("idVenta", idVenta); $.ajax({ url:"ajax/remitos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ console.log("respuesta", respuesta); $("#verTotalFc").val(respuesta["total"]); $("#verEscribano").val(respuesta["nombre"]); // var datos = new FormData(); datos.append("idVentaArt", idVenta); console.log("idVentaArt", idVenta); $.ajax({ url:"ajax/remitos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta3){ console.log("respuesta3", respuesta3); for (var i = 0; i < respuesta3.length; i++) { // console.log("respuesta3", respuesta3[i]['descripcion']); $(".tablaArticulosVer").append('<tr>'+ '<td>'+respuesta3[i]['cantidad']+'</td>'+ '<td>'+respuesta3[i]['descripcion']+'</td>'+ '<td>'+respuesta3[i]['folio1']+'</td>'+ '<td>'+respuesta3[i]['folio2']+'</td>'+ '<td>'+respuesta3[i]['total']+'</td>'+ '</tr>'); } } }) } }) }) /*============================================= IMPRIMIR FACTURA =============================================*/ $(".tablas").on("click", ".btnImprimirRemito", function(){ var idVenta = $(this).attr("idVenta"); var adeuda = $(this).attr("adeuda"); var total = $(this).attr("total"); window.open("extensiones/tcpdf/pdf/remito.php?id="+idVenta, "_blank"); })<file_sep>/vistas/modulos/afacturar.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar cuotas a facturar </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar cuotas a facturar</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <?php if(isset($_GET["fechaInicial"])){ echo '<a href="vistas/modulos/descargar-reporte.php?reporte=reporte&fechaInicial="'.$_GET["fechaInicial"].'&fechaFinal='.$_GET["fechaFinal"].'">'; }else{ echo '<a href="vistas/modulos/descargar-reporte.php?reporte=reporte">'; } ?> <!-- <button class="btn btn-success" style="margin-top:5px">Descargar reporte en Excel</button> --> </a> <!-- <button type="button" class="btn btn-default pull-right" id="daterange-btn-afacturar"> <span> <i class="fa fa-calendar"></i> Rango de Fecha </span> <i class="fa fa-caret-down"></i> </button> --> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Fecha</th> <th>Tipo</th> <th>Nro.F.</th> <th>Nombre</th> <th>Forma de pago</th> <th>Total</th> <th>Adeuda</th> <th>Acciones</th> </tr> </thead> <tbody> <?php if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } $respuesta = ControladorVentas::ctrRangoFechasaFacturar($fechaInicial, $fechaFinal); foreach ($respuesta as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["fecha"].'</td> <td>'.$value["tipo"].'</td> <td>'.$value["codigo"].'</td>'; $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo '<td>'.$respuestaCliente["nombre"].'</td>'; echo ' <td>'.$value["metodo_pago"].'</td> <td>$ '.number_format($value["total"],2).'</td>'; if ($value["adeuda"]==0){ echo '<td style="color:green">$ '.number_format($value["adeuda"],2).'</td>'; }else{ echo '<td style="color:red">$ '.number_format($value["adeuda"],2).'</td>'; } echo ' <td> <div class="btn-group">'; echo '<button class="btn btn-info btnVerVenta" idVenta="'.$value["id"].'" codigo="'.$value["codigo"].'" title="ver la factura" data-toggle="modal" data-target="#modalVerArticulos" title="Ver articulos de esta Factura"><i class="fa fa-eye"></i></button>'; echo '<button class="btn btn-warning btnEditarVenta" idVenta="'.$value["id"].'" title="ver la factura" idVenta="'.$value["id"].'" title="Editar la Venta"><i class="fa fa-pencil"></i></button>'; // echo '<button class="btn btn-danger btnEliminarVenta" idVenta="'.$value["id"].'"><i class="fa fa-times"></i></button>'; echo '</div> </td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <!--===================================== VER ARTICULOS ======================================--> <div id="modalVerArticulos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Ver Articulos</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="verEscribano" id="verEscribano" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFc" id="verTotalFc" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-info pull-left" data-dismiss="modal">Imprimir Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrRealizarPago("ctacorriente"); ?> </div> </div> </div> <!--===================================== AGREGAR PAGO ======================================--> <div id="modalAgregarPago" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar Pago</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="hidden" class="form-control input-lg" name="idPago" id="idPago" required> <input type="hidden" class="form-control input-lg" name="adeuda" id="adeuda" required> <input type="text" class="form-control input-lg" name="nuevoPago" id="nuevoPago" placeholder="Ingresar Pago" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar pago</button> </div> </form> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrRealizarPago("ctacorriente"); ?> </div> </div> </div> <!--===================================== PAGAR FACTURA ======================================--> <div id="modalRealizarFactura" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#1C2331; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Esta seguro que desea Realizar la Factura de esta Cuota?</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="verEscribano2" id="verEscribano2" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFc2" id="verTotalFc2" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3F729B; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer2"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-danger pull-right" data-dismiss="modal">Sí,realizar Factura</button> <button type="button" class="btn btn-primary pull-left" data-dismiss="modal">Salir</button> </div> </form> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrRealizarPago("ctacorriente"); ?> </div> </div> </div> <!--===================================== AGREGAR DERECHO DE ESCRITURA ======================================--> <div id="modalAgregarDerechoEscritura" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#007E33; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar Derecho de Escritura</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="hidden" class="form-control input-lg" name="idPagoDerecho" id="idPagoDerecho" required> <input type="text" class="form-control input-lg" name="nuevoPagoDerecho" id="nuevoPagoDerecho" placeholder="Ingresar Pago" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Ingresar Importe</button> </div> </form> <?php $ingresarDerechoEscritura = new ControladorVentas(); $ingresarDerechoEscritura -> ctringresarDerechoEscritura(); ?> </div> </div> </div><file_sep>/vistas/js/ctacorriente.js /*============================================= EDITAR FACTURA Y VER ARTICULOS =============================================*/ $(".tablas").on("click", ".btnVerArt", function(){ var idVenta = $(this).attr("idVenta"); // console.log("idVenta", idVenta); $(".tablaArticulosVer").empty(); var datos = new FormData(); datos.append("idVenta", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ $("#verTotalFc").val(respuesta["total"]); //respuesta["id_cliente"] var datos = new FormData(); datos.append("idEscribano", respuesta["id_cliente"]); console.log("respuesta[\"id_cliente\"]", respuesta["id_cliente"]); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta2){ $("#verEscribano").val(respuesta2["nombre"]); // } }) var datos = new FormData(); datos.append("idVentaArt", idVenta); console.log("idVentaArt", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta3){ for (var i = 0; i < respuesta3.length; i++) { // console.log("respuesta3", respuesta3[i]['descripcion']); $(".tablaArticulosVer").append('<tr>'+ '<td>'+respuesta3[i]['cantidad']+'</td>'+ '<td>'+respuesta3[i]['descripcion']+'</td>'+ '<td>'+respuesta3[i]['folio1']+'</td>'+ '<td>'+respuesta3[i]['folio2']+'</td>'+ '<td>'+respuesta3[i]['total']+'</td>'+ '</tr>'); } } }) } }) }) /*============================================= EDITAR FACTURA Y VER ARTICULOS =============================================*/ $(".tablas").on("click", ".btnRealizarFactura", function(){ var idVenta = $(this).attr("idVenta"); console.log("idVenta", idVenta); $(".tablaArticulosVer2").empty(); var datos = new FormData(); datos.append("idVenta", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ $("#verTotalFc2").val(respuesta["total"]); //respuesta["id_cliente"] var datos = new FormData(); datos.append("idEscribano", respuesta["id_cliente"]); console.log("respuesta[\"id_cliente\"]", respuesta["id_cliente"]); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta2){ $("#verEscribano2").val(respuesta2["nombre"]); // } }) var datos = new FormData(); datos.append("idVentaArt", idVenta); console.log("idVentaArt", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta3){ for (var i = 0; i < respuesta3.length; i++) { // console.log("respuesta3", respuesta3[i]['descripcion']); $(".tablaArticulosVer2").append('<tr>'+ '<td>'+respuesta3[i]['cantidad']+'</td>'+ '<td>'+respuesta3[i]['descripcion']+'</td>'+ '<td>'+respuesta3[i]['folio1']+'</td>'+ '<td>'+respuesta3[i]['folio2']+'</td>'+ '<td>'+respuesta3[i]['total']+'</td>'+ '</tr>'); } } }) } }) }) /*============================================= REALIZAR PAGO CTA CORRIENTE =============================================*/ $(".tablas").on("click", ".btnPagarCC", function(){ var idVenta = $(this).attr("idVenta"); console.log("idVenta", idVenta); var datos = new FormData(); datos.append("idVenta", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ console.log("respuesta", respuesta); $("#idPago").val(respuesta["id"]); $("#nuevoPago").val(respuesta["adeuda"]); $("#adeuda").val(respuesta["adeuda"]); } }) }) /*============================================= CUANDO ABRO EL MODAL DE DERECHO DE ESCRITURA =============================================*/ $('#modalAgregarDerechoEscritura').on('shown.bs.modal', function () { $("#nuevoPagoDerecho").focus(); $("#nuevoPagoDerecho").select(); }) /*============================================= REALIZAR PAGO CTA CORRIENTE =============================================*/ $(".tablas").on("click", ".btnDerechoEscritura", function(){ var idVenta = $(this).attr("idVenta"); console.log("idVenta", idVenta); $('#idPagoDerecho').val(idVenta); var datos = new FormData(); datos.append("idPagoDerecho", idVenta); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ console.log("respuesta", respuesta); for (var i = 0; i < respuesta.length; i++) { if (respuesta[i]['id']==19){ $("#nuevoPagoDerecho").val(respuesta[i]['total']); }else{ $("#nuevoPagoDerecho").val(0); } } } }) })<file_sep>/vistas/modulos/ws.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar escribanos WS </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar escribanos WS</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th>Nombre</th> <th>Nombre</th> <th>Apellido</th> <th>matricula</th> <th>email</th> <th>telefono</th> <th>estado</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $escribanos = ControladorWs::ctrMostrarEscribanosWs($item, $valor); foreach ($escribanos as $key => $value) { echo '<tr> <td>'.$value["nombre"].'</td> <td>'.$value["nombre_ws"].'</td> <td>'.$value["apellido_ws"].'</td> <td>'.$value["matricula_ws"].'</td> <td>'.$value["email"].'</td> <td>'.$value["telefono"].'</td> <td>'.$value["inhabilitado"].'</td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <file_sep>/vistas/modulos/afip.php <?php function cvf_convert_object_to_array($data) { if (is_object($data)) { $data = get_object_vars($data); } if (is_array($data)) { return array_map(__FUNCTION__, $data); } else { return $data; } } include('extensiones/afip/consulta.php'); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar Comprobantes Homologados de Afip </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Comprobantes Homolagados</li> </ol> </section> <section class="content"> <div class="box box-danger"> <div class="box-header with-border"> <div class="col-lg-2"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-file"></i></span> <?php $cmp = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,1); if (!isset($_GET['numero'])){ ?> <input type="number" class="form-control input-lg" name="numero" id="numero" value="<?php echo $cmp['number'];?>"> <?php }else{ ?> <input type="number" class="form-control input-lg" name="numero" id="numero" value="<?php echo $_GET['numero'];?>"> <?php }?> </div> </div> </div> <div class="col-lg-3"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-file"></i></span> <select class="form-control input-lg" name="tipoComprobante" id="tipoComprobante"> <?php if (!isset($_GET['comprobante'])){ echo '<option value="11" selected=true>Factura</option> <option value="13">Nota de Credito</option>'; }else{ ?> <option value="11" <?php if ($_GET['comprobante']=="11"){echo "selected=true";}?>>Factura</option> <option value="13" <?php if ($_GET['comprobante']=="13"){echo "selected=true";}?>>Nota de Credito</option> <?php } ?> </select> </div> </div> </div> <div class="col-lg-6"> <div class="form-group"> <div class="input-group"> <button class="btn btn-danger" id="btnAfip">Buscar</button> </div> <?php if(isset($_GET['comprobante'])){ $cmp = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,$_GET['comprobante']); }else{ $cmp = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,11); echo '<pre>'; print_r($cmp); echo '</pre>'; } echo '<h5><strong>Ultimo Nro. de Comprobante: '.$cmp["number"].'</strong></h5>'; ?> </div> </div> </div> <div class="box-body"> <div class="col-lg-6"> <?php $ultimoComprobante = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,11); if(isset($_GET['comprobante'])){ $result = $afip->consultarComprobante($PTOVTA,$_GET['comprobante'],$_GET['numero']); }else{ $result = $afip->consultarComprobante($PTOVTA,1,$ultimoComprobante); } $miObjeto=cvf_convert_object_to_array($result["datos"]); // echo '<pre>'; print_r($miObjeto); echo '</pre>'; ?> <div class="box box-primary"> <div class="box-header with-border"> <h4>DATOS DEL AFIP WEBSERVICE</h4> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;">Cuit</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['DocNro'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;">Fecha</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['CbteFch'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;"> Importe</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['ImpTotal'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;">Nro Comprobante</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['CbteDesde'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;">CAE</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['CodAutorizacion'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;"> Fecha Cae</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['FchVto'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;">Punto Venta</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['PtoVta'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: blue;color:white;"> Tipo Comprobante</span> <input type="text" class="form-control input-lg" value="<?php echo $miObjeto['CbteTipo'];?>"> </div> </div> </div> </div></div> <div class="col-lg-6"> <?php // print_r($miObjeto); if (!empty($miObjeto)){ #BUSCO EL CAE DE LA FACTURA PARA TENER LOS DATOS QUE TENGO GUARDADO EN MI TABLA $item = "cae"; $valor = $miObjeto['CodAutorizacion']; // echo $miObjeto['CodAutorizacion']; $ventas = ControladorVentas::ctrMostrarVentas($item,$valor); // echo '<pre>'; print_r($ventas); echo '</pre>'; echo "<strong>".strtoupper($ventas['tabla'])."</strong>"; $nombre =$ventas['nombre']; $cuit=$ventas['documento']; if($ventas['tabla']=="escribanos"){ $item = "cuit"; $valor = $miObjeto['DocNro']; $respuesta = ControladorEscribanos::ctrMostrarEscribanos($item,$valor); $item = "id"; $valor = $respuesta["id_tipo_iva"]; $tipoIva = ControladorTipoIva::ctrMostrarTipoIva($item,$valor); $tipoIva =$tipoIva['nombre']; } if($ventas['tabla']=="clientes"){ $item = "cuit"; $valor = $miObjeto['DocNro']; $respuesta = ControladorClientes::ctrMostrarClientes($item,$valor); $tipoIva = $respuesta['tipoiva']; } if($ventas['tabla']=="casual"){ $tipoIva = "CONSUMIDOR FINAL"; } if($ventas['tabla']=="consumidor_final"){ $tipoIva = "CONSUMIDOR FINAL"; } ?> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Nombre</span> <input type="text" class="form-control input-lg" value="<?php echo $nombre;?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Cuit</span> <input type="text" class="form-control input-lg" value="<?php echo $cuit;?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Tipo Iva</span> <input type="text" class="form-control input-lg" value="<?php echo $tipoIva;?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Fecha</span> <input type="text" class="form-control input-lg" value="<?php echo $ventas['fecha'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Tipo</span> <input type="text" class="form-control input-lg" value="<?php echo $ventas['tipo'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Comprobante Nro.</span> <input type="text" class="form-control input-lg" value="<?php echo $ventas['codigo'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Fecha Cae</span> <input type="text" class="form-control input-lg" value="<?php echo $ventas['fecha_cae'];?>"> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon" style="background-color: red;color:white;">Total Fc</span> <input type="text" class="form-control input-lg" value="<?php echo $ventas['total'];?>"> </div> </div> </div> <?php }else{ } ?> </section> </div><file_sep>/vistas/js/historico.js $("#selectescribanos").change(function () { // var datos = new FormData(); // datos.append("idEscribano", $(this).val()); var tipo = $("#btnVerCuotas").attr("valor"); window.location = "index.php?ruta=historico&idEscribano="+$(this).val()+"&tipo="+tipo; }); $("#btnVerCuotas").on("click",function(){ var tipo = $("#btnVerCuotas").attr("valor"); var idEsctibano = $("#btnVerCuotas").attr("idEscribano"); window.location = "index.php?ruta=historico&idEscribano="+idEsctibano+"&tipo="+tipo; })<file_sep>/vistas/modulos/cuotas-editar.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar cuotas a facturar </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar cuotas a facturar</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> </div> <div class="box-body"> <form method="POST"> <label for="fechaCUEditar">Fecha</label> <input type="text" name="fechaCUEditar"> <label for="tipoComprobante">Tipo</label> <input type="text" name="tipoComprobante"> <label for="importe1">Importe 1</label> <input type="text" name="importe1"> <label for="importe2">Importe 2</label> <input type="text" name="importe2"> <label for="importe3">Importe 3</label> <input type="text" name="importe3"> <button type="submit">MODIFICAR</button> </form> <?php $modificarCuota = new ControladorCuotas(); $modificarCuota -> ctrModificarImporte(); ?> </div> </div> </section> </div> <file_sep>/ajax/updateInhabilitados.ajax.php <?php require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; require_once "../controladores/cuotas.controlador.php"; require_once "../modelos/cuotas.modelo.php"; require_once "../controladores/parametros.controlador.php"; require_once "../modelos/parametros.modelo.php"; require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; require_once "../controladores/ws.controlador.php"; require_once "../modelos/ws.modelo.php"; class AjaxUpdateInhabilitados{ /*============================================= ACTUALIZAR INHABILITADOS =============================================*/ public function ajaxActualizarInhabilitados(){ #ELIMINAR LOS INHABILITADOS $respuesta = ControladorEnlace::ctrEliminarEnlace("inhabilitados"); $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanos as $key => $value) { if ($value['inhabilitado']==1){ $datos = array("id"=>$value['id'], "nombre"=>$value['nombre']); /*=========================================== = SUBIR INHABILITADOS = ===========================================*/ ControladorEnlace::ctrSubirInhabilitado($datos); /*===== End of SUBIR INHABILITADOS ======*/ } } /*=========================================== = CONSULTAR SI EXISTEN MODIFICACIONES = ===========================================*/ $tabla ="modificaciones"; $datos = array("nombre"=>"inhabilitados","fecha"=>date("Y-m-d")); $modificaciones = ModeloEnlace::mdlConsultarModificaciones($tabla,$datos); if(!$modificaciones[0]>=1){ //SI NO EXISTE CREO UNA NUEVA FILA $datos = array("nombre"=>"inhabilitados","fecha"=>date("Y-m-d")); ControladorEnlace::ctrSubirModificaciones($datos); }else{ //SI EXISTE ACTUALIZO A CERO $datos = array("nombre"=>"inhabilitados","fecha"=>date("Y-m-d")); ControladorEnlace::ctrUpdateModificaciones($datos); } } /*============================================= MOSTRAR INHABILITADOS =============================================*/ public function ajaxMostrarInhabilitados(){ echo '<script>$(".tablaMostrarAjax").DataTable({ "lengthMenu": [[5, 10, 25], [5, 10, 25]], dom: "lBfrtip",buttons: [ { extend: "colvis", columns: ":not(:first-child)", } ], "language": { "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ registros", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_", "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0", "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": Activar para ordenar la columna de manera ascendente", "sSortDescending": ": Activar para ordenar la columna de manera descendente" } } })</script>'; echo '<table class="table table-bordered table-striped dt-responsive tablaMostrarAjax" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th style="width:100px">Nombre</th> <th>Ws</th> </tr> </thead> <tbody>'; $escribanos = ControladorEscribanos::ctrMostrarEscribanosInhabilitados(); foreach ($escribanos as $key => $value) { if ($value["inhabilitado"] ==0){$estado=1;$btnEstado ='<i class="fa fa-info-circle" aria-hidden="true" style="color:green;" ></i>';}//habilitado if ($value["inhabilitado"] ==1){$estado=0;$btnEstado ='<i class="fa fa-info-circle" aria-hidden="true" style="color:red;" ></i>';}//inhabilitado if ($value["inhabilitado"] ==2){$estado=2;}//no consultable $data = '{"nombre":"'.$value["nombre_ws"].'","apellido":"'.$value["apellido_ws"].'","matricula":"'.$value["matricula_ws"].'","email":"'.strtolower($value["email"]).'","telefono":"'.$value["telefono"].'","inhabilitado":"'.$estado.'"}'; $datos = str_replace(' ','',$data); $datos = str_replace('{','',$datos); $datos = str_replace('}','',$datos); $datos = str_replace('"','',$datos); $datos = str_replace(',','\n',$datos); echo ' <tr> <td>'.($key+1).'</td> <td class="text-uppercase" >'.$value["nombre"].'</td> <td class="text-uppercase"><button class="btn btn-danger" onclick=alert("'.$datos.'") >Estado WService</button></td> </tr>'; } echo' </tbody> </table>'; } } /*============================================= ACTUALIZAR INHABILITADOS =============================================*/ if(isset($_POST["upInhabilitados"])){ $inhabilitados = new AjaxUpdateInhabilitados(); $inhabilitados -> ajaxActualizarInhabilitados(); } /*============================================= MOSTRAR INHABILITADOS =============================================*/ if(isset($_POST["mostrarInhabilitados"])){ $inhabilitados = new AjaxUpdateInhabilitados(); $inhabilitados -> ajaxMostrarInhabilitados(); } <file_sep>/vistas/js/nota-credito.js /*============================================= CONSULTAR COMPROBANTE =============================================*/ $("#btnNotaCredito").on("click",function(){ window.location = "extensiones/afip/notacredito.php?cuit="+$('#notaCreditoCuit').val()+'&total='+$('#notaCreditoTotal').val(); }) $('#notaCreditoCuit').focus(); $('#notaCreditoCuit').select();<file_sep>/vistas/modulos/remitos.php <?php // FECHA DEL DIA DE HOY $fecha=date('Y-m-d'); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar remitos </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar remitos</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <a href="crear-venta"> <button class="btn btn-primary"> Agregar remito </button> </a> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th style="width:45px">Fecha</th> <th style="width:30px">Tipo</th> <th style="width:90px">Nro. Factura</th> <th>Nombre</th> <!-- <th>Documento</th> --> <th>Forma de pago</th> <th style="width:50px">Total</th> <th style="width:50px">Adeuda</th> <th style="width:140px">Acciones</th> </tr> </thead> <tbody> <?php if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } $respuesta = ControladorRemitos::ctrMostrarRemitos($fechaInicial, $fechaFinal); foreach ($respuesta as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["fecha"].'</td> <td>'.$value["tipo"].'</td>'; $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo '<td><center>'.$value["codigo"].'</center></td>'; echo '<td>'.$value["nombre"].'</td>'; // echo '<td>'.$value["documento"].'</td>'; echo '<td>'.$value["metodo_pago"].'</td> <td>$ '.number_format($value["total"],2).'</td>'; if ($value["adeuda"]==0){ echo '<td style="color:green">$ '.number_format($value["adeuda"],2).'</td>'; }else{ echo '<td style="color:red">$ '.number_format($value["adeuda"],2).'</td>'; } echo '<td> <div class="btn-group"> <button class="btn btn-info btnVerRemito" idVenta="'.$value["id"].'" codigo="'.$value["codigo"].'" title="ver la factura" data-toggle="modal" data-target="#modalVerArticulos"><i class="fa fa-eye"></i></button>'; echo '<button class="btn btn-danger btnImprimirRemito" idVenta="'.$value["id"].'" total="'.$value["total"].'" adeuda="'.$value["adeuda"].'" codigoVenta="'.$value["codigo"].'"><i class="fa fa-print"></i></button>'; if ($value["adeuda"]==0 && $value["total"]<>0){ // echo '<button class="btn btn-default" title="realizar un pago" ><i class="fa fa-money"></i></button>'; }else{ echo '<button class="btn btn-primary btnEditarPagoRemito" idVenta="'.$value["id"].'" adeuda="'.$value["adeuda"].'" title="realizar un pago" data-toggle="modal" data-target="#modalAgregarPagoRemito"><i class="fa fa-money"></i></button>'; } echo '</div> </td> </tr>'; // } } ?> </tbody> </table> <?php $eliminarVenta = new ControladorVentas(); $eliminarVenta -> ctrEliminarVenta(); $eliminarPago = new ControladorVentas(); $eliminarPago -> ctrEliminarPago(); ?> </div> </div> </section> </div> <!--===================================== VER ARTICULOS ======================================--> <div id="modalVerArticulos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Ver Articulos</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="verEscribano" id="verEscribano" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFc" id="verTotalFc" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer finFactura"> <button type="button" class="btn btn-info pull-left" data-dismiss="modal" id="imprimirItems" codigo="<?php echo $value["id"];?>">aaaa Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> </div> </div> </div> <!--===================================== AGREGAR PAGO ======================================--> <div id="modalAgregarPagoRemito" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <div class="modal-header" style="background:#3E4551; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Metodo Pago</h4> </div> <div class="modal-body"> <input type="hidden" id="idVentaPago" name="idVentaPago" value=""> <input type="hidden" id="totalVentaPago" name="totalVentaPago" value=""> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <option value="EFECTIVO" selected>EFECTIVO</option> <option value="TARJETA">TARJETA</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> <option value="CHEQUE">CHEQUE</option> </select> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div><!-- Modal body--> <div class="modal-footer"> <button type="submit" class="btn btn-danger">Realizar Pago</button> </div> <?php $realizarPagoRemito = new ControladorRemitos(); $realizarPagoRemito -> ctrRealizarPagoRemito(); ?> </form> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!--===================================== VER ARTICULOS ======================================--> <div id="modalEliminar" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#ff4444; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Factura para Eliminar</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="col-lg-3"> <img src="vistas/img/usuarios/default/admin.jpg" class="user-image" width="100px"> </div> <!-- ENTRADA PARA EL NOMBRE --> <div class="col-lg-9"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="usuario" id="usuario" value="ADMIN" readonly> <input type="hidden" name="pagina" value="ventas"> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="password" class="form-control input-lg" name="password" id="password" placeholder="<PASSWORD>" required> </div> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer finFactura"> <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="eliminarFactura" codigo="<?php echo $value["codigo"];?>">Eliminar Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrEliminarVenta(); ?> </div> </div> </div> <div id="modalLoader" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Aguarde un instante</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <center> <img src="vistas/img/afip/loader.gif" alt=""> </center> <center> <img src="vistas/img/afip/afip.jpg" alt=""> </center> </div> </div> <div class="modal-footer"> <p><strong>CONECTANDOSE AL SERVIDOR DE AFIP</strong></p> </div> </div> </div> </div> <!--===================================== PREPARAR AFIP ======================================--> <div id="modalPrepararAfip" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post" name="frmHomologacionlogacion"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#ff4444; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Preparar Homologacion Afip</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="hidden" id="idVentaHomologacion" name="idVentaHomologacion"> <input type="hidden" id="idDocumentoHomologacion" name="idDocumentoHomologacion"> <input type="hidden" id="idClienteHomologacion" name="idClienteHomologacion"> <input type="text" class="form-control input-lg" name="verEscribanoHomologacion" id="verEscribanoHomologacion" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFcHomologacion" id="verTotalFcHomologacion" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#ef5350; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVerHomologacion"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-danger" id="btnHomologacion" data-dismiss="modal">Confirmar Homologacion</button> </div> </form> </div> </div> </div> <!--===================================== HACER UNA NOTA DE CREDITO ======================================--> <div id="modalVerNotaCredito" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <div class="modal-header" style="background:#FF8800; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Hacer nota de Credito</h4> </div> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <!-- ENTRADA PARA EL NOMBRE --> <input type="hidden" id="idClienteNc" name="idClienteNc"> <input type="text" class="form-control input-lg" name="nombreClienteNc" id="nombreClienteNc" placeholder="Ingresar Nombre" style="text-transform:uppercase; " readonly> </div> </div> <!-- ENTRADA PARA EL DOCUMENTO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="hidden" id="tablaNc" name="tablaNc"> <input type="hidden" id="productosNc" name="productosNc"> <input type="number" class="form-control input-lg" name="documentoNc" id="documentoNc" placeholder="Ingresar Documento" readonly> </div> </div> <!-- ENTRADA PARA EL TOTAL --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="totalNc" id="totalNc" placeholder="Ingresar Total NC" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidosNc"> <thead style="background:#ffbb33; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVerNc"></tbody> </table> </div> </div> </div> </div><!-- Modal body--> <div class="modal-footer"> <button type="button" id="realizarNc" class="btn btn-danger" data-dismiss="modal">Realizar NC</button> </div> </form> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--><file_sep>/vistas/modulos/bibliotecas/parametros.inicio.php <?php /*========================================== PARAMETROS =============================================*/ #DIAS DE ATRASO $item = "parametro"; $valor = 'maxAtraso'; $atraso = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); #CANTIDAD DE LIBROS $item = "parametro"; $valor = 'maxLibro'; $libro = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); $maxLibros=$libro['valor']+1; ?><file_sep>/vistas/js/clientes.js /*============================================= EDITAR CLIENTE =============================================*/ $(".tablas").on("click", ".btnEditarCliente", function(){ var idCliente = $(this).attr("idCliente"); console.log("idCliente", idCliente); var datos = new FormData(); datos.append("idCliente", idCliente); $.ajax({ url:"ajax/clientes.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ tipoCuit = '#tipoCuitEditarCliente option[value="'+ respuesta['tipocuit'] +'"]'; $("#nombreEditarCliente").val(respuesta["nombre"]); $("#documentoEditarCliente").val(respuesta["cuit"]); $("#direccionEditarCliente").val(respuesta["direccion"]); $("#localidadEditarCliente").val(respuesta["localidad"]); $("#idClienteEditar").val(respuesta["id"]); // $("#tipoCuitEditarCliente option:contains('"+ respuesta["tipoiva"] +"')").attr('selected', true); // console.log("respuesta[\"tipoiva\"]", respuesta["tipoiva"]); $("#tipoCuitEditarCliente option[value='"+ respuesta["tipoiva"] +"']").attr("selected",true); // $("#editarCategoriaOsde option[value="+ respuesta["id_osde"] +"]").attr("selected",true); // $("#editarTipoIva option[value="+ respuesta["id_tipo_iva"] +"]").attr("selected",true); } }) }) /*============================================= ELIMINAR CLIENTE =============================================*/ $(".tablas").on("click", ".btnEliminarCliente", function(){ var idCliente = $(this).attr("idCliente"); console.log("idCliente", idCliente); swal({ title: '¿Está seguro de borrar este Cliente?', text: "¡Si no lo está puede cancelar la acción!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText: 'Cancelar', confirmButtonText: 'Si, borrar cliente!' }).then(function(result){ if (result.value) { window.location = "index.php?ruta=clientes&idCliente="+idCliente; } }) }) /*============================================= HACER FOCO EN EL BUSCADOR CLIENTES =============================================*/ $('#modalAgregarCliente').on('shown.bs.modal', function () { $('#nuevoCliente').focus(); }) /*============================================= FACTURA ELECTRONICA =============================================*/ $("#btnIngresarClienteNuevo").on("click",function(){ var datos = new FormData(); datos.append("idClienteEditar", $("#idClienteEditar").val()); datos.append("nombreEditarCliente", $("#nombreEditarCliente").val()); datos.append("documentoEditarCliente", $("#documentoEditarCliente").val()); datos.append("tipoCuitEditarCliente", $("#tipoCuitEditarCliente").val()); datos.append("direccionEditarCliente", $("#direccionEditarCliente").val()); datos.append("localidadEditarCliente", $("#localidadEditarCliente").val()); $.ajax({ url:"ajax/clientes.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuesta){ } }) }) /*============================================= GUARDAR CAMBIOS DE LOS CLIENTES =============================================*/ $("#btnGuardarCambios").on("click",function(){ if (validarCuit($('#documentoEditarCliente').val())){ var datos = new FormData(); datos.append("idClienteEditar", $("#idClienteEditar").val()); datos.append("nombreEditarCliente", $("#nombreEditarCliente").val()); datos.append("documentoEditarCliente", $("#documentoEditarCliente").val()); datos.append("tipoCuitEditarCliente", $("#tipoCuitEditarCliente").val()); datos.append("direccionEditarCliente", $("#direccionEditarCliente").val()); datos.append("localidadEditarCliente", $("#localidadEditarCliente").val()); $.ajax({ url:"ajax/clientes.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuesta){ // console.log("respuesta", respuesta); window.location = "clientes"; } }) }else{ swal("Este cuit no es correcto "+$('#documentoEditarCliente').val(), "Verifique los datos", "warning"); } }) <file_sep>/ajax/escribanos.ajax.php <?php require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; class AjaxEscribano{ /*============================================= EDITAR ESCRIBANO =============================================*/ public $idEscribano; public function ajaxEditarEscribano(){ $item = "id"; $valor = $this->idEscribano; $respuesta = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); echo json_encode($respuesta); } } /*============================================= EDITAR ESCRIBANO =============================================*/ if(isset($_POST["idEscribano"])){ $escribano = new AjaxEscribano(); $escribano -> idEscribano = $_POST["idEscribano"]; $escribano -> ajaxEditarEscribano(); }<file_sep>/vistas/modulos/menu.php <aside class="main-sidebar"> <section class="sidebar"> <ul class="sidebar-menu"> <!-- inicio --> <li class="active"> <a href="inicio"> <i class="fa fa-home"></i> <span>Inicio</span> </a> </li> <!--===================================== = ADMINISTRADOR = ======================================--> <?php if($_SESSION['perfil']=="Administrador"){ echo '<li class="treeview"> <a href="#"> <i class="fa fa-address-card"></i> <span>Admin</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li> <a href="usuarios"> <i class="fa fa-user"></i> <span>Usuarios</span> </a> </li> <li> <a href="miempresa"> <i class="fa fa-university"></i> <span>Empresa</span> </a> </li> </ul> </li>'; echo '<li class="treeview"> <a href="#"> <i class="fa fa-braille"></i> <span>Datos</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li> <a href="escribanos"> <i class="fa fa-user"></i> <span>Escribanos</span> </a> </li> <li> <a href="categorias"> <i class="fa fa-users"></i> <span>Categorías Escribanos</span> </a> </li> <li> <a href="rubros"> <i class="fa fa-linode"></i> <span>Rubros</span> </a> </li> <li> <a href="comprobantes"> <i class="fa fa-files-o"></i> <span>Comprobantes</span> </a> </li> <li> <a href="osde"> <i class="fa fa-heartbeat"></i> <span>Osde</span> </a> </li> <li> <a href="productos"> <i class="fa fa-product-hunt"></i> <span>Productos</span> </a> </li> <li> <a href="parametros"> <i class="fa fa-wrench"></i> <span>Parametros</span> </a> </li> </ul> </li>'; } ?> <!--===================================== = VENDEDOR = ======================================--> <?php if($_SESSION['perfil']=="Administrativo"||$_SESSION['perfil']=="SuperAdmin"){ echo'<li> <a href="caja2"> <i class="fa fa-money"></i> <span>Caja</span> </a> </li>'; echo'<li> <a href="libros"> <i class="fa fa-book"></i> <span>Libros</span> </a> </li>'; echo'<li> <a href="clientes"> <i class="fa fa-user"></i> <span>Clientes</span> </a> </li>'; echo '<li class="treeview"> <a href="#"> <i class="fa fa-list-ul"></i> <span>Ventas</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> <ul class="treeview-menu"> <li> <a href="ventas"> <i class="fa fa-table"></i> <span>Administrar ventas</span> </a> </li> <li> <a href="crear-venta"> <i class="fa fa-file"></i> <span>Crear venta</span> </a> </li> <li> <a href="ctacorriente"> <i class="fa fa-spinner"></i> <span>Cta Corriente</span> </a> </li> <li> <a href="cuotas"> <i class="fa fa-file-text-o"></i> <span>Cuotas</span> </a> </li> <li> <a href="remitos"> <i class="fa fa-table"></i> <span>Administrar remitos</span> </a> </li> <li> <a href="afip"> <i class="fa fa-asterisk"></i> <span>Afip</span> </a> </li> <li> <a href="historico"> <i class="fa fa-database"></i> <span>Historico</span> </a> </li>'; // <li> // <a href="tmpcuotas"> // <i class="fa fa-database"></i> // <span>tmpCUOTAS</span> // </a> // </li> // </ul> // </li> } ?> </ul> </section> </aside><file_sep>/modelos/enlace.modelo.php <?php require_once "conexion.php"; class ModeloEnlace{ /*============================================= ELIMINAR DATOS DE LA TABLA ENLACE =============================================*/ static public function mdlEliminarEnlace($tabla){ $stmt = Conexion::conectarEnlace()->prepare("DELETE FROM $tabla"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= INGRESAR PRODUCTOS A ENLACE =============================================*/ static public function mdlIngresarProducto($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(`id`,`nombre`, `descripcion`, `codigo`, `nrocomprobante`, `cantventa`, `id_rubro`, `cantminima`, `cuotas`, `importe`, `obs`) VALUES (:id,:nombre,:descripcion,:codigo,:nrocomprobante,:cantventa,:id_rubro,:cantminima,:cuotas,:importe,:obs)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datos["descripcion"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":nrocomprobante", $datos["nrocomprobante"], PDO::PARAM_INT); $stmt->bindParam(":cantventa", $datos["cantventa"], PDO::PARAM_INT); $stmt->bindParam(":id_rubro", $datos["id_rubro"], PDO::PARAM_INT); $stmt->bindParam(":cantminima", $datos["cantminima"], PDO::PARAM_INT); $stmt->bindParam(":cuotas", $datos["cuotas"], PDO::PARAM_INT); $stmt->bindParam(":importe", $datos["importe"], PDO::PARAM_STR); $stmt->bindParam(":obs", $datos["obs"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } // $stmt->close(); // $stmt = null; } /*============================================= INTRODUCIR ESCRIBANOS AL ENLACE =============================================*/ static public function mdlIngresarEscribano($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(`id`,`nombre`,`documento`,id_tipo_iva,tipo,facturacion,tipo_factura,`cuit`, `direccion`,`localidad`, `telefono`,`email` , `id_categoria`,`id_escribano_relacionado`, `id_osde`,`ultimolibrocomprado`,`ultimolibrodevuelto`,`apellido_ws`,`nombre_ws`,`matricula_ws`) VALUES (:id,:nombre,:documento,:id_tipo_iva,:tipo,:facturacion,:tipo_factura,:cuit,:direccion,:localidad,:telefono,:email,:id_categoria,:id_escribano_relacionado,:id_osde,:ultimolibrocomprado,:ultimolibrodevuelto,:apellido_ws,:nombre_ws,:matricula_ws)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_INT); $stmt->bindParam(":id_tipo_iva", $datos["id_tipo_iva"], PDO::PARAM_INT); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":facturacion", $datos["facturacion"], PDO::PARAM_STR); $stmt->bindParam(":tipo_factura", $datos["tipo_factura"], PDO::PARAM_STR); $stmt->bindParam(":cuit", $datos["cuit"], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); $stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR); $stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR); $stmt->bindParam(":id_categoria", $datos["id_categoria"], PDO::PARAM_INT); $stmt->bindParam(":id_escribano_relacionado", $datos["id_escribano_relacionado"], PDO::PARAM_INT); $stmt->bindParam(":id_osde", $datos["id_osde"], PDO::PARAM_INT); $stmt->bindParam(":ultimolibrocomprado", $datos["ultimolibrocomprado"], PDO::PARAM_INT); $stmt->bindParam(":ultimolibrodevuelto", $datos["ultimolibrodevuelto"], PDO::PARAM_INT); $stmt->bindParam(":apellido_ws", $datos["apellido_ws"], PDO::PARAM_STR); $stmt->bindParam(":nombre_ws", $datos["nombre_ws"], PDO::PARAM_STR); $stmt->bindParam(":matricula_ws", $datos["matricula_ws"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlMostrarVentasColegio($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE codigo LIKE 1"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE VENTA =============================================*/ static public function mdlIngresarVenta($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(id,fecha,tipo,id_cliente,nombre,documento, productos,total)VALUES (:id,:fecha,:tipo,:id_cliente,:nombre,:documento,:productos,:total)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= INGRESO DE CUOTAS =============================================*/ static public function mdlIngresarCuota($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(id,fecha,tipo,id_cliente,nombre,documento, productos,total)VALUES (:id,:fecha,:tipo,:id_cliente,:nombre,:documento,:productos,:total)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlMostrarUltimaActualizacion($tabla){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla limit 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarUltimaActualizacionModificaciones($tabla,$valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla where nombre = :nombre ORDER BY id DESC LIMIT 1"); $stmt->bindParam(":nombre", $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasFechaClorinda($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE $item = '".$valor."' ORDER BY codigo ASC"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasFechaColorado($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE $item = '".$valor."' ORDER BY codigo ASC"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasClorinda($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE $item = $valor"); // $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasClorindaCodigoFc($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE $item = '$valor'"); // $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasColorado($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE $item = $valor"); // $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasColoradoCodigoFc($tabla, $item, $valor){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE codigo = '".$valor."'"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= RANGO FECHAS =============================================*/ static public function mdlRangoFechasEnlace($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ // $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla ORDER BY codigo asc limit 60"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ // $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' ORDER BY codigo DESC "); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ // $fechaFinal = new DateTime(); // $fechaFinal->add(new DateInterval('P1D')); // $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal' ORDER BY codigo asc"); $stmt -> execute(); return $stmt -> fetchAll(); } } /*============================================= INGRESAR HABILITADOS A ENLACE =============================================*/ static public function mdlSubirInhabilitado($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO `inhabilitados`(`id_cliente`, `nombre`) VALUES (:id_cliente,:nombre)"); $stmt->bindParam(":id_cliente", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= INGRESAR HABILITADOS A ENLACE =============================================*/ static public function mdlSubirHabilitado($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("DELETE FROM $tabla where id_cliente=:id_cliente"); $stmt->bindParam(":id_cliente", $valor, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= REGISTRAR MODIFICACIONES =============================================*/ static public function mdlSubirModificaciones($tabla,$datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(`fecha`,`nombre`,`colegio`) VALUES (:fecha,:nombre,1)"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlUpdateModificaciones($tabla,$datos){ $stmt = Conexion::conectarEnlace()->prepare("UPDATE $tabla SET colorado = 0 , clorinda = 0 WHERE fecha =:fecha and nombre =:nombre"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= VER REGISTROS DE MODIFICACIONES =============================================*/ static public function mdlVerModificaciones($tabla,$datos){ $stmt = Conexion::conectarEnlace()->prepare("SELECT *From $tabla where fecha=:fecha,nombre=:nombre"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= CONSULTAR MODIFICACIONES =============================================*/ static public function mdlConsultarModificaciones($tabla,$datos){ $stmt = Conexion::conectarEnlace()->prepare("SELECT COUNT(nombre)FROM $tabla WHERE nombre =:nombre AND fecha =:fecha"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE VENTA =============================================*/ static public function mdlIngresarVentaEnlace($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(id,fecha,tipo,codigo, id_cliente,nombre,documento,tabla, id_vendedor, productos, impuesto, neto, total,adeuda,observaciones,metodo_pago,referenciapago,fechapago,cae,fecha_cae) VALUES (:id,:fecha,:tipo,:codigo, :id_cliente,:nombre,:documento,:tabla, :id_vendedor, :productos, :impuesto, :neto, :total,:adeuda,:obs, :metodo_pago,:referenciapago,:fechapago,:cae,:fecha_cae)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":id_vendedor", $datos["id_vendedor"], PDO::PARAM_INT); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":impuesto", $datos["impuesto"], PDO::PARAM_STR); $stmt->bindParam(":neto", $datos["neto"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); $stmt->bindParam(":obs",$datos["obs"], PDO::PARAM_STR); $stmt->bindParam(":metodo_pago", $datos["metodo_pago"], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos["referenciapago"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return " error"; } $stmt->close(); $stmt = null; } /*============================================= ELIMINAR CUOTA =============================================*/ static public function mdlEliminarCuota($tabla, $valor){ $stmt = Conexion::conectarEnlace()->prepare("DELETE FROM $tabla where id=:id"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlMostrarUltimaVenta($tabla){ $stmt = Conexion::conectarEnlace()->prepare("SELECT * FROM $tabla order by id desc limit 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE VENTA =============================================*/ static public function mdlIngresarVentaEnlace2($tabla, $datos){ $stmt = Conexion::conectarEnlace()->prepare("INSERT INTO $tabla(id,fecha,codigo,tipo,id_cliente,nombre,documento,tabla, id_vendedor, productos,impuesto,neto,total,adeuda,cae,fecha_cae,metodo_pago,fechapago,referenciapago,observaciones) VALUES (:id,:fecha,:codigo,:tipo, :id_cliente,:nombre,:documento,:tabla, :id_vendedor, :productos, :impuesto, :neto, :total,:adeuda,:cae,:fecha_cae,:metodo_pago,:fechapago,:referenciapago,:observaciones)"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":id_vendedor", $datos["id_vendedor"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":impuesto", $datos["impuesto"], PDO::PARAM_STR); $stmt->bindParam(":neto", $datos["neto"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); $stmt->bindParam(":metodo_pago", $datos["metodo_pago"], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos["referenciapago"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); $stmt->bindParam(":observaciones", $datos["observaciones"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/vistas/modulos/clorinda.php <?php $botonDescarga = ''; // FECHA DEL DIA DE HOY $fecha=date('Y-m-d'); $item = "fecha"; if (isset($_GET['fecha'])){ $fechaMueva = explode("-", $_GET['fecha']); $valor = $fechaMueva[2]."-".$fechaMueva[1]."-".$fechaMueva[0]; $ventasClorinda = ControladorEnlace::ctrMostrarVentasFechaClorinda($item, $valor); }else if(isset($_GET['fechaInicial'])){ // $fechaMueva1 = explode("-",$_GET['fechaInicial']); $fechaInicial =$_GET['fechaInicial'];//$fechaMueva1[2]."-".$fechaMueva1[1]."-".$fechaMueva1[0]; // $fechaMueva2 = explode("-",$_GET['fechaFinal']); $fechaFinal = $_GET['fechaFinal'];//$fechaMueva2[2]."-".$fechaMueva2[1]."-".$fechaMueva2[0]; $ventasClorinda = ControladorEnlace::ctrRangoFechasEnlace("clorinda",$fechaInicial, $fechaFinal); $botonDescarga = '<a href="vistas/modulos/descargar-reporte.php?reporte=reporte&fechaInicial='.$_GET["fechaInicial"].'&fechaFinal='.$_GET["fechaFinal"].'&ruta='.$_GET["ruta"].'"><button class="btn btn-success" style="margin-top:5px">Descargar reporte en Excel</button></a>'; }else{ $valor= date('Y-m-d'); $ventasClorinda = ControladorEnlace::ctrMostrarVentasFechaClorinda($item, $valor); } ?> <div class="content-wrapper"> <section class="content-header"> <h1 style="color:red;"> Ventas de Clorinda de <?php echo $valor;?> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar ventas</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <div class="col-lg-2"> <div class="input-group date"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="text" class="form-control pull-right" id="datapicker" name="fecha" data-date-format="dd-mm-yyyy" value="<?php echo $valor; ?>"> </div> </div> <div class="col-lg-1"> <button class="btn btn-primary" id="bsqlClorinda">Buscar</button> </div> <div class="col-lg-1 pull-left"> <button class="btn btn-info" id="imprimirClorinda" fecha="<?php echo $valor; ?>"><i class="fa fa-print"></i></button> </div> <?php echo $botonDescarga; ?> <button type="button" class="btn btn-default pull-right" id="daterange-btn-clorinda"> <span> <i class="fa fa-calendar"></i> Rango de Fecha </span> <i class="fa fa-caret-down"></i> </button> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th style="width:45px">Fecha</th> <th style="width:35px">Tipo</th> <th>Nro. Factura</th> <th>Escribano</th> <!-- <th>Vendedor</th> --> <th>Forma de pago</th> <th style="width:50px">Total</th> <th style="width:50px">Adeuda</th> <th style="width:140px">Acciones</th> </tr> </thead> <tbody> <?php foreach ($ventasClorinda as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["fecha"].'</td> <td>'.$value["tipo"].'</td> <td>'.$value["codigo"].'</td>'; // $itemCliente = "id"; // $valorCliente = $value["id_cliente"]; // $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo '<td>'.$value["nombre"].'</td>'; echo '<td>'.$value["metodo_pago"].'</td> <td>$ '.number_format($value["total"],2).'</td>'; if ($value["adeuda"]==0){ echo '<td style="color:green">$ '.number_format($value["adeuda"],2).'</td>'; }else{ echo '<td style="color:red">$ '.number_format($value["adeuda"],2).'</td>'; } echo ' <td> <div class="btn-group"> <button class="btn btn-info btnVerVentaClorinda" idVenta="'.$value["id"].'" codigo="'.$value["codigo"].'" title="ver la factura" data-toggle="modal" data-target="#modalVerArticulos"><i class="fa fa-eye"></i></button>'; // if ($value["adeuda"]==0 && $value["total"]<>0){ // echo '<button class="btn btn-default"><i class="fa fa-money"></i></button>'; // }else{ // echo '<button class="btn btn-danger btnEditarPago" idVenta="'.$value["id"].'" data-toggle="modal" data-target="#modalAgregarPago"><i class="fa fa-money"></i></button>'; // } // echo ' <button class="btn btn-danger btnVerVenta-Eliminar" idVenta="'.$value["id"].'" data-toggle="modal" data-target="#modalEliminar"><i class="fa fa-times"></i></button>'; // btnEliminarVenta echo '</div> </td> </tr>'; // } } ?> </tbody> </table> <?php $eliminarVenta = new ControladorVentas(); $eliminarVenta -> ctrEliminarVenta(); $eliminarPago = new ControladorVentas(); $eliminarPago -> ctrEliminarPago(); ?> </div> </div> </section> </div> <!--===================================== VER ARTICULOS ======================================--> <div id="modalVerArticulos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Ver Articulos</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="verEscribano" id="verEscribano" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFc" id="verTotalFc" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer finFactura"> <button type="button" class="btn btn-info pull-left" data-dismiss="modal" id="imprimirItems" codigo="<?php echo $value["codigo"];?>">Imprimir Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> </div> </div> </div> <!--===================================== AGREGAR PAGO ======================================--> <div id="modalAgregarPago" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <div class="modal-header" style="background:#3E4551; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Metodo Pago</h4> </div> <div class="modal-body"> <input type="hidden" id="idVentaPago" name="idVentaPago" value="13"> <input type="hidden" id="totalVentaPago" name="totalVentaPago" value="13"> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <option value="EFECTIVO" selected>EFECTIVO</option> <option value="TARJETA">TARJETA</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> <option value="CHEQUE">CHEQUE</option> </select> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div><!-- Modal body--> <div class="modal-footer"> <button type="submit" class="btn btn-danger">Realizar Pago</button> </div> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrRealizarPagoVenta(); ?> </form> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!--===================================== VER ARTICULOS ======================================--> <div id="modalEliminar" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#ff4444; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Factura para Eliminar</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="col-lg-3"> <img src="vistas/img/usuarios/default/admin.jpg" class="user-image" width="100px"> </div> <!-- ENTRADA PARA EL NOMBRE --> <div class="col-lg-9"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="usuario" id="usuario" value="ADMIN" readonly> <input type="hidden" name="pagina" value="ventas"> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="password" class="form-control input-lg" name="password" id="password" placeholder="<PASSWORD>" required> </div> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer finFactura"> <button type="button" class="btn btn-danger pull-left" data-dismiss="modal" id="eliminarFactura" codigo="<?php echo $value["codigo"];?>">Eliminar Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrEliminarVenta(); ?> </div> </div> </div> <file_sep>/modificacion-items.sql CREATE TABLE `items` ( `id` int(11) NOT NULL, `idVenta` int(11) NOT NULL, `idCodigoFc` int(11) NOT NULL, `fecha` date NOT NULL, `nombreEscribano` text COLLATE utf8_spanish_ci NOT NULL, `nroComprobante` text COLLATE utf8_spanish_ci NOT NULL, `descripcionComprobante` text COLLATE utf8_spanish_ci NOT NULL, `folio1` text COLLATE utf8_spanish_ci NOT NULL, `folio2` text COLLATE utf8_spanish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci; ALTER TABLE `items` ADD PRIMARY KEY (`id`); ALTER TABLE `items` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26690;<file_sep>/modelos/modelos.modelo.php <?php require_once "conexion.php"; class ModeloModelos{ /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlIngresarModelo($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre,detalle) VALUES (:nombre,:detalle)"); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":detalle", $datos['detalle'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function mdlMostrarModelos($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function mdlEditarCategoria($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET categoria = :categoria WHERE id = :id"); $stmt -> bindParam(":categoria", $datos["categoria"], PDO::PARAM_STR); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR CATEGORIA =============================================*/ static public function mdlBorrarCategoria($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } static public function mdlBuscarModelos($item){ $stmt = Conexion::conectar()->prepare("SELECT * FROM modelo WHERE nombre COLLATE UTF8_SPANISH_CI LIKE '%$item%' OR detalle COLLATE UTF8_SPANISH_CI LIKE '%$item%' OR CONCAT(nombre,' ',detalle) COLLATE UTF8_SPANISH_CI LIKE '%$item%' "); $stmt -> execute(); return $stmt -> fetchAll(); } } <file_sep>/vistas/modulos/bibliotecas/fechas-cuotas.inicio.php <?php #VEO QUE CANTIDAD DE CUOTAS $cuotas = ControladorCuotas::ctrMostrarGeneracion("CUOTA"); $osde = ControladorCuotas::ctrMostrarGeneracion("OSDE"); $tabla ="modificaciones"; $valor = "cuotas"; $modificacionesCuota = ModeloEnlace::mdlMostrarUltimaActualizacionModificaciones($tabla,$valor); $tabla ="modificaciones"; $valor = "ventas"; $modificacionesFc = ModeloEnlace::mdlMostrarUltimaActualizacionModificaciones($tabla,$valor); ?><file_sep>/extensiones/qr/index.php <?php require '../extensiones/qr/phpqrcode/qrlib.php'; $dir = '../extensiones/qr/temp/'; if(!file_exists($dir)){ mkdir($dir); } $filename = $dir.$result["cae"].'.png'; $url = 'https://www.afip.gob.ar/fe/qr/'; // URL que pide AFIP que se ponga en el QR. $datos_cmp_base_64 = json_encode([ "ver" => 1, // Numérico 1 digito - OBLIGATORIO – versión del formato de los datos del comprobante 1 "fecha" => date('Y-m-d'), // full-date (RFC3339) - OBLIGATORIO – Fecha de emisión del comprobante "cuit" => (int) 30584197680, // Numérico 11 dígitos - OBLIGATORIO – Cuit del Emisor del comprobante "ptoVta" => (int) $PTOVTA, // Numérico hasta 5 digitos - OBLIGATORIO – Punto de venta utilizado para emitir el comprobante "tipoCmp" => (int) $tipocbte, // Numérico hasta 3 dígitos - OBLIGATORIO – tipo de comprobante (según Tablas del sistema. Ver abajo ) "nroCmp" => (int) $ultimoComprobante, // Numérico hasta 8 dígitos - OBLIGATORIO – Número del comprobante "importe" => (float) $totalVenta, // Decimal hasta 13 enteros y 2 decimales - OBLIGATORIO – Importe Total del comprobante (en la moneda en la que fue emitido) "moneda" => "PES", // 3 caracteres - OBLIGATORIO – Moneda del comprobante (según Tablas del sistema. Ver Abajo ) "ctz" => (float) 1, // Decimal hasta 13 enteros y 6 decimales - OBLIGATORIO – Cotización en pesos argentinos de la moneda utilizada (1 cuando la moneda sea pesos) "tipoDocRec" => $codigoTipoDoc , // Numérico hasta 2 dígitos - DE CORRESPONDER – Código del Tipo de documento del receptor (según Tablas del sistema ) "nroDocRec" => $numeroDoc, // Numérico hasta 20 dígitos - DE CORRESPONDER – Número de documento del receptor correspondiente al tipo de documento indicado "tipoCodAut" => "E", // string - OBLIGATORIO – “A” para comprobante autorizado por CAEA, “E” para comprobante autorizado por CAE "codAut" => (int) $result["cae"] // Numérico 14 dígitos - OBLIGATORIO – Código de autorización otorgado por AFIP para el comprobante ]); $datos_cmp_base_64 = base64_encode($datos_cmp_base_64); $url = 'https://www.afip.gob.ar/fe/qr/'; $to_qr = $url.'?p='.$datos_cmp_base_64; $tamanio = 10; $level = 'M'; $frameSize = 3; $contenido = $datos_cmp_base_64;//'Hola mundo'; QRcode::png($to_qr,$filename,$level,$tamanio,$frameSize); // echo '<img src="'.$filename.'" />'; ?><file_sep>/modelos/caja.modelo.php <?php require_once "conexion.php"; class ModeloCaja{ /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function mdlMostrarCaja($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM caja WHERE fecha like '%$valor%' order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc limit 15"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlIngresarCaja($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,efectivo,tarjeta,cheque,transferencia) VALUES (:fecha,:efectivo,:tarjeta,:cheque,:transferencia)"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":efectivo", $datos['efectivo'], PDO::PARAM_STR); $stmt->bindParam(":tarjeta", $datos['tarjeta'], PDO::PARAM_STR); $stmt->bindParam(":cheque", $datos['cheque'], PDO::PARAM_STR); $stmt->bindParam(":transferencia", $datos['transferencia'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDiTAR CATEGORIA =============================================*/ static public function mdlEditarCaja($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET efectivo = :efectivo,tarjeta = :tarjeta, cheque = :cheque,transferencia = :transferencia WHERE fecha = :fecha"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":efectivo", $datos['efectivo'], PDO::PARAM_STR); $stmt->bindParam(":tarjeta", $datos['tarjeta'], PDO::PARAM_STR); $stmt->bindParam(":cheque", $datos['cheque'], PDO::PARAM_STR); $stmt->bindParam(":transferencia", $datos['transferencia'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/modelos/conexion.php <?php class Conexion{ static public function conectar(){ //CONEXION LOCAL $link = new PDO("mysql:host=localhost;dbname=colegio", "root",""); $link->exec("set names utf8"); return $link; } static public function conectarEnlace(){ try { //CONEXION DE BACKUP EN LA WEB --ORIGINAL-- // $link = new PDO("mysql:host=192.168.3.11;dbname=colegioe_enlace01", // "root", // "Bgtoner123456"); //CONEXION DE BACKUP EN LA WEB --PRUEBA-- $link = new PDO("mysql:host=192.168.3.11;dbname=colegioe_enlace01prueba", "root", "Bgtoner123456"); $link->exec("set names utf8"); $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $link; } catch (PDOException $e) { echo '<script>window.location = "iniciosinconexion";</script>'; } } static public function conectarWs(){ //CONEXION DE BACKUP EN LA WEB --ORIGINAL-- // $link = new PDO("mysql:host=192.168.3.11;dbname=webservice", // "root", // "Bgtoner123456"); //CONEXION PARA WEBSERVICE --PRUEBA-- $link = new PDO("mysql:host=192.168.3.11;dbname=webservice_prueba", "root", "Bgtoner123456"); $link->exec("set names utf8"); $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $link; } } <file_sep>/vistas/modulos/bibliotecas/fechas.inicio.php <?php $mesEnLetras = date("F"); switch (date("F")) { case 'January': # code... $mesNombre="Enero"; break; case 'February': # code... $mesNombre="Febrero"; break; case 'March': # code... $mesNombre="Marzo"; break; case 'April': # code... $mesNombre="Abril"; break; case 'May': # code... $mesNombre="Mayo"; break; case 'June': # code... $mesNombre="Junio"; break; case 'July': # code... $mesNombre="Julio"; break; case 'August': # code... $mesNombre="Agosto"; break; case 'September': # code... $mesNombre="Septiembre"; break; case 'October': # code... $mesNombre="Octubre"; break; case 'November': # code... $mesNombre="Noviembre"; break; case 'December': # code... $mesNombre="Diciembre"; break; } ?><file_sep>/extensiones/afip/wsfexv1.php <?php include_once (__DIR__ . '/wsaa.php'); /** * Clase para emitir facturas de exportación electronicas online con AFIP * con el webservice wsfexv1 * */ class Wsfexv1 { //************* CONSTANTES ***************************** const MSG_AFIP_CONNECTION = "No pudimos comunicarnos con AFIP: "; const MSG_BAD_RESPONSE = "Respuesta mal formada"; const RESULT_ERROR = 1; const RESULT_OK = 0; const TA = "/token/TA.xml"; # Ticket de Acceso, from WSAA const WSDL_PRODUCCION = "/wsdl/produccion/wsfexv1.wsdl"; const URL_PRODUCCION = "https://servicios1.afip.gov.ar/wsfexv1/service.asmx"; const WSDL_HOMOLOGACION = "/wsdl/homologacion/wsfexv1.wsdl"; const URL_HOMOLOGACION = "https://wswhomo.afip.gov.ar/wsfexv1/service.asmx"; const PROXY_HOST = ""; # Proxy IP, to reach the Internet const PROXY_PORT = ""; # Proxy TCP port const SERVICE_NAME = "wsfex"; //************* VARIABLES ***************************** var $log_xmls = TRUE; # Logs de las llamadas var $modo = 0; # Homologacion "0" o produccion "1" var $cuit = 0; # CUIT del emisor de las FC/NC/ND var $client = NULL; var $token = NULL; var $sign = NULL; var $base_dir = __DIR__; var $wsdl = ""; var $url = ""; function __construct($cuit, $modo_afip) { // Llamar a init luego de construir la instancia de clase $this->cuit = (float) $cuit; // Si no casteamos a float, lo toma como long y el soap client // de windows no lo soporta - > lo transformaba en 2147483647 $this->modo = intval($modo_afip); if ($this->modo === Wsaa::MODO_PRODUCCION) { $this->wsdl = Wsfexv1::WSDL_PRODUCCION; $this->url = Wsfexv1::URL_PRODUCCION; } else { $this->wsdl = Wsfexv1::WSDL_HOMOLOGACION; $this->url = Wsfexv1::URL_HOMOLOGACION; } } /** * Crea el cliente de conexión para el protocolo SOAP y carga el token actual */ function init() { try { ini_set("soap.wsdl_cache_enabled", 0); ini_set('soap.wsdl_cache_ttl', 0); if (!file_exists($this->base_dir . $this->wsdl)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "No existe el archivo de configuración de AFIP: " . $this->base_dir . $this->wsdl); } $context = stream_context_create(array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) )); $this->client = new soapClient($this->base_dir . $this->wsdl, array('soap_version' => SOAP_1_2, 'location' => $this->url, # 'proxy_host' => PROXY_HOST, # 'proxy_port' => PROXY_PORT, #'verifypeer' => false, 'verifyhost' => false, 'exceptions' => 1, 'encoding' => 'ISO-8859-1', 'features' => SOAP_USE_XSI_ARRAY_TYPE + SOAP_SINGLE_ELEMENT_ARRAYS, 'trace' => 1, 'stream_context' => $context )); # needed by getLastRequestHeaders and others $this->checkToken(); if ($this->log_xmls) { file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/functions.txt", print_r($this->client->__getFunctions(), TRUE)); file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/types.txt", print_r($this->client->__getTypes(), TRUE)); } } catch (Exception $exc) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "Error: " . $exc->getTraceAsString()); } return array("code" => Wsfexv1::RESULT_OK, "msg" => "Inicio correcto"); } /** * Si el loggueo de errores esta habilitado graba en archivos xml y txt las solicitudes y respuestas * * @param: $method - String: Metodo consultado * */ function checkErrors($method) { if ($this->log_xmls) { file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/request-" . $method . ".xml", $this->client->__getLastRequest()); file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/hdr-request-" . $method . ".txt", $this->client-> __getLastRequestHeaders()); file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/response-" . $method . ".xml", $this->client->__getLastResponse()); file_put_contents($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . "/tmp/hdr-response-" . $method . ".txt", $this->client-> __getLastResponseHeaders()); } } /** * Si el token actual está vencido solicita uno nuevo * */ function checkToken() { if (!file_exists($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . Wsfexv1::TA)) { $not_exist = TRUE; } else { $not_exist = FALSE; $TA = simplexml_load_file($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . Wsfexv1::TA); $expirationTime = date('c', strtotime($TA->header->expirationTime)); $actualTime = date('c', date('U')); } if ($not_exist || $actualTime >= $expirationTime) { //renovamos el token $wsaa_client = new Wsaa("wsfex", $this->modo, $this->cuit, $this->log_xmls); $result = $wsaa_client->generateToken(); if ($result["code"] == wsaa::RESULT_OK) { //Recargamos con el nuevo token $TA = simplexml_load_file($this->base_dir . "/" . $this->cuit . "/" . $this::SERVICE_NAME . Wsfexv1::TA); } else { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $result["msg"]); } } $this->token = $TA->credentials->token; $this->sign = $TA->credentials->sign; return array("code" => Wsfexv1::RESULT_OK, "msg" => "Ok, token valido"); } /** * Consulta dummy para verificar funcionamiento del servicio * */ function dummy() { $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); try { $results = $this->client->FEXDummy($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "No pudimos comunicarnos con AFIP: " . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXDummy'); if (!isset($results->FEXDummyResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXDummyResult->Errors)) { $error_str = "Error al realizar consulta de puntos de venta: \n"; foreach ($results->FEXDummyResult->Errors->Err as $e) { $error_str .= "$e->Code - $e->Msg"; } return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring"); } else { return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK"); } } else { return $result; } } /** * Metodo privado que arma los parametros que pide el WSDL * * @param type $voucher * @return \stdClass * */ function _comprobante($voucher) { $params = new stdClass(); //Token************************************************ $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; //Enbezado ********************************************* $params->Cmp = new stdClass(); $params->Cmp->Id = floatVal($voucher["numeroPuntoVenta"] . $voucher["numeroComprobante"]); $params->Cmp->Fecha_cbte = $voucher["fechaComprobante"]; // [N] $params->Cmp->Cbte_Tipo = $voucher["codigoTipoComprobante"]; // FEXGetPARAM_Cbte_Tipo $params->Cmp->Punto_vta = $voucher["numeroPuntoVenta"]; $params->Cmp->Cbte_nro = $voucher["numeroComprobante"]; $params->Cmp->Tipo_expo = $voucher["codigoConcepto"]; // FEXGetPARAM_Tipo_Expo $params->Cmp->Permiso_existente = ""; // Permiso de embarque - S, N, NULL (vacío) //$params->Cmp->Permisos = array(); // [N] $params->Cmp->Dst_cmp = $voucher["codigoPais"]; // FEXGetPARAM_DST_pais $params->Cmp->Cliente = $voucher["nombreCliente"]; $params->Cmp->Cuit_pais_cliente = ""; // FEXGetPARAM_DST_CUIT (No es necesario si se ingresa ID_impositivo) $params->Cmp->Domicilio_cliente = $voucher["domicilioCliente"]; $params->Cmp->Id_impositivo = $voucher["numeroDocumento"]; $params->Cmp->Moneda_Id = $voucher["codigoMoneda"]; // FEXGetPARAM_MON $params->Cmp->Moneda_ctz = $voucher["cotizacionMoneda"]; // FEXGetPARAM_Ctz //$params->Cmp->Obs_comerciales = ""; // [N] $params->Cmp->Imp_total = $voucher["importeTotal"]; //$params->Cmp->Obs = ""; // [N] //$params->Cmp->Cmps_asoc = array(); // [N] //$params->Cmp->Forma_pago = $voucher["CondicionVenta"]; // [N] //$params->Cmp->Incoterms = ""; // Cláusula de venta - FEXGetPARAM_Incoterms [N] //$params->Cmp->Incoterms_Ds = ""; // [N] $params->Cmp->Idioma_cbte = $voucher["idiomaComprobante"]; // 2:Ingles - FEXGET_PARAM_IDIOMAS //$params->Cmp->Opcionales = array(); // [N] // Items if (array_key_exists("items", $voucher) && count($voucher["items"]) > 0) { $params->Cmp->Items = array(); foreach ($voucher["items"] as $value) { $item = new stdClass(); $item->Pro_codigo = $value["codigo"]; $item->Pro_ds = $value["descripcion"]; $item->Pro_qty = $value["cantidad"]; $item->Pro_umed = $value["codigoUnidadMedida"]; // FEXGetPARAM_UMed $item->Pro_precio_uni = $value["precioUnitario"]; $item->Pro_bonificacion = $value["impBonif"]; $item->Pro_total_item = $value["importeItem"]; $params->Cmp->Items[] = $item; } } //print_r($params); return $params; } /** * Emite un comprobante electrónico de exportación con el web service de afip * A partir de un arreglo asociativo con los datos necesarios * * @param: $voucher - Array: Datos del comprobante a emitir * */ function emitirComprobante($voucher) { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = $this->_comprobante($voucher); try { $results = $this->client->FEXAuthorize($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXAuthorize'); if (!isset($results->FEXAuthorizeResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXAuthorizeResult->FEXErr) && $results->FEXAuthorizeResult->FEXErr->ErrCode !== 0) { $error_str = "Error al emitir comprobante de exportación: \n"; $e = $results->FEXAuthorizeResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $response =$results->FEXAuthorizeResult->FEXResultAuth; $cae = $response->Cae; $fecha_vencimiento = $response->Fch_venc_Cae; return array("code" => Wsfev1::RESULT_OK, "msg" => "OK", "cae" => $cae, "fechaVencimientoCAE" => $fecha_vencimiento); } } else { return $result; } } /** * Consulta un comprobante de exportación en AFIP y devuelve el XML correspondiente * * @param: $PV - Integer: Punto de venta * @param: $TC - Integer: Tipo de comprobante * */ function consultarComprobante($PV, $TC, $NRO) { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $<PASSWORD>; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; $params->Cmp = new stdClass(); $params->Cmp->Cbte_tipo = $TC; $params->Cmp->Punto_vta = $PV; $params->Cmp->Cbte_nro = $NRO; try { $results = $this->client->FEXGetCMP($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetCMP'); if (!isset($results->FEXGetCMPResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetCMPResult->FEXErr) && $results->FEXGetCMPResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de comprobante: \n"; $e = $results->FEXGetCMPResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $datos = $results->FEXGetCMPResult->FEXResultGet; return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta el numero de comprobante del último autorizado por AFIP * * @param: $PV - Integer: Punto de venta * @param: $TC - Integer: Tipo de comprobante * */ function consultarUltimoComprobanteAutorizado($PV, $TC) { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; $params->Auth->Cbte_Tipo = $TC; $params->Auth->Pto_venta = $PV; try { $results = $this->client->FEXGetLast_CMP($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetLast_CMP'); if (!isset($results->FEXGetLast_CMPResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetLast_CMPResult->FEXErr) && $results->FEXGetLast_CMPResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de ultimo comprobante autorizado: \n"; $e = $results->FEXGetLast_CMPResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $number = $results->FEXGetLast_CMPResult->FEXResult_LastCMP->Cbte_nro; return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "number" => $number); } } else { return $result; } } /** * Recuperador de valores referenciales de CUITs de Países * */ function consultarCuitsPaises() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_DST_CUIT($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_DST_CUIT'); if (!isset($results->FEXGetPARAM_DST_CUITResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_DST_CUITResult->FEXErr) && $results->FEXGetPARAM_DST_CUITResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de CUITs paises: \n"; $e = $results->FEXGetPARAM_DST_CUITResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_DST_CUITResult->FEXResultGet; foreach ($X->ClsFEXResponse_DST_cuit as $Y) { $datos[$Y->DST_CUIT] = $Y->DST_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta los tipos de moneda disponibles * */ function consultarMonedas() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_MON($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_MON'); if (!isset($results->FEXGetPARAM_MONResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_MONResult->FEXErr) && $results->FEXGetPARAM_MONResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de CUITs paises: \n"; $e = $results->FEXGetPARAM_MONResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_MONResult->FEXResultGet; foreach ($X->ClsFEXResponse_Mon as $Y) { $datos[$Y->Mon_Id] = $Y->Mon_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta tipos de comprobantes * */ function consultarTiposComprobante() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_Cbte_Tipo($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_Cbte_Tipo'); if (!isset($results->FEXGetPARAM_Cbte_TipoResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_Cbte_TipoResult->FEXErr) && $results->FEXGetPARAM_Cbte_TipoResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de tipos de comprobantes: \n"; $e = $results->FEXGetPARAM_Cbte_TipoResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_Cbte_TipoResult->FEXResultGet; foreach ($X->ClsFEXResponse_Cbte_Tipo as $Y) { $datos[$Y->Cbte_Id] = $Y->Cbte_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta tipos de exportación * */ function consultarTiposExportacion() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_Tipo_Expo($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_Tipo_Expo'); if (!isset($results->FEXGetPARAM_Tipo_ExpoResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_Tipo_ExpoResult->FEXErr) && $results->FEXGetPARAM_Tipo_ExpoResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de tipos de exportación: \n"; $e = $results->FEXGetPARAM_Tipo_ExpoResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_Tipo_ExpoResult->FEXResultGet; foreach ($X->ClsFEXResponse_Tex as $Y) { $datos[$Y->Tex_Id] = $Y->Tex_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta las unidades de medida disponibles * */ function consultarUnidadesMedida() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = <PASSWORD>; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_Umed($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_Umed'); if (!isset($results->FEXGetPARAM_UMedResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_UMedResult->FEXErr) && $results->FEXGetPARAM_UMedResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de unidades de medida: \n"; $e = $results->FEXGetPARAM_UMedResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_UMedResult->FEXResultGet; foreach ($X->ClsFEXResponse_UMed as $Y) { $datos[$Y->Umed_Id] = $Y->Umed_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta de idiomas * */ function consultarIdiomas() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_Idiomas($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_Idiomas'); if (!isset($results->FEXGetPARAM_IdiomasResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_IdiomasResult->FEXErr) && $results->FEXGetPARAM_IdiomasResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de idiomas: \n"; $e = $results->FEXGetPARAM_IdiomasResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_IdiomasResult->FEXResultGet; foreach ($X->ClsFEXResponse_Idi as $Y) { $datos[$Y->Idi_Id] = $Y->Idi_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta de paises * */ function consultarPaises() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_DST_Pais($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_DST_Pais'); if (!isset($results->FEXGetPARAM_DST_paisResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_DST_paisResult->FEXErr) && $results->FEXGetPARAM_DST_paisResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de paises: \n"; $e = $results->FEXGetPARAM_DST_paisResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_DST_paisResult->FEXResultGet; foreach ($X->ClsFEXResponse_DST_pais as $Y) { $datos[$Y->DST_Codigo] = $Y->DST_Ds; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } /** * Consulta de cotización de moneda * */ function consultarCotizacion($Mon_id) { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; $params->Mon_id = $Mon_id; try { $results = $this->client->FEXGetPARAM_Ctz($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_Ctz'); if (!isset($results->FEXGetPARAM_CtzResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_CtzResult->FEXErr) && $results->FEXGetPARAM_CtzResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de cotización de moneda: \n"; $e = $results->FEXGetPARAM_CtzResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_CtzResult->FEXResultGet; return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $X->Mon_ctz); } } else { return $result; } } /** * Consulta de puntos de venta habilitados para facturas de exportación * */ function consultarPuntosVenta() { $datos = array(); $result = $this->checkToken(); if ($result["code"] == Wsfexv1::RESULT_OK) { $params = new stdClass(); $params->Auth = new stdClass(); $params->Auth->Token = $this->token; $params->Auth->Sign = $this->sign; $params->Auth->Cuit = $this->cuit; try { $results = $this->client->FEXGetPARAM_PtoVenta($params); } catch (Exception $e) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_AFIP_CONNECTION . $e->getMessage(), "datos" => NULL); } $this->checkErrors('FEXGetPARAM_PtoVenta'); if (!isset($results->FEXGetPARAM_PtoVentaResult)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => Wsfexv1::MSG_BAD_RESPONSE, "datos" => NULL); } else if (isset($results->FEXGetPARAM_PtoVentaResult->FEXErr) && $results->FEXGetPARAM_PtoVentaResult->FEXErr->ErrCode !== 0) { $error_str = "Error al realizar consulta de puntos de venta: \n"; $e = $results->FEXGetPARAM_PtoVentaResult->FEXErr; $error_str .= "$e->ErrCode - $e->ErrMsg"; return array("code" => Wsfexv1::RESULT_ERROR, "msg" => $error_str, "datos" => NULL); } else if (is_soap_fault($results)) { return array("code" => Wsfexv1::RESULT_ERROR, "msg" => "$results->faultcode - $results->faultstring", "datos" => NULL); } else { $X = $results->FEXGetPARAM_PtoVentaResult->FEXResultGet; //TODO Ver cuando viene un resultado foreach ($X->ClsFEXResponse_PtoVenta as $Y) { $datos[$Y->PVE_Nro] = $Y->$Y->PVE_Bloqueado; } return array("code" => Wsfexv1::RESULT_OK, "msg" => "OK", "datos" => $datos); } } else { return $result; } } }<file_sep>/vistas/modulos/productos.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar productos </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar productos</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <button class="btn btn-primary" data-toggle="modal" data-target="#modalAgregarProducto"> Agregar producto </button> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablaProductos" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Descripcion</th> <th>Código</th> <th>Rubros</th> <th>Cant. Venta</th> <th>Importe</th> <th>Observaciones</th> <th>Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $orden = "id"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); foreach ($productos as $key => $value){ $item = "id"; $valor = $value["id_rubro"]; $rubros = ControladorRubros::ctrMostrarRubros($item, $valor); echo ' <tr> <td>'.($key+1).'</td> <td>'.$value["nombre"].'</td> <td>'.$value["descripcion"].'</td> <td>'.$value["codigo"].'</td> <td>'.$rubros["nombre"].'</td> <td>'.$value["cantventa"].'</td> <td>'.$value["importe"].'</td> <td>'.$value["obs"].'</td>'; echo '<td> <div class="btn-group"> <button class="btn btn-warning btnEditarProducto" idProducto="'.$value["id"].'" data-toggle="modal" data-target="#modalEditarProducto"><i class="fa fa-pencil"></i></button> <button class="btn btn-danger btnEliminarProducto" idProducto="'.$value["id"].'"><i class="fa fa-times"></i></button> </div> </td> </tr>'; } ?> </tbody> </table> <input type="hidden" value="<?php echo $_SESSION['perfil']; ?>" class="perfilUsuario"> </div> </div> </section> </div> <!--===================================== MODAL AGREGAR PRODUCTO ======================================--> <div id="modalAgregarProducto" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar producto</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA SELECCIONAR RUBROS --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="nuevoRubro" name="nuevoRubro" required> <option value="">Selecionar rubro</option> <?php $item = null; $valor = null; $categorias = ControladorRubros::ctrMostrarRubros($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["nombre"].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA EL CÓDIGO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-code"></i></span> <input type="text" class="form-control input-lg" id="nuevoCodigo" name="nuevoCodigo" placeholder="Ingresar código" readonly required> </div> </div> <!-- ENTRADA PARA LA nOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" id="nuevoNombre" name="nuevoNombre" placeholder="Ingresar nombre" required> </div> </div> <!-- ENTRADA PARA LA DESCRIPCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" name="nuevaDescripcion" placeholder="Ingresar descripción" required> </div> </div> <!-- ENTRADA PARA SELECCIONAR RUBROS --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="nuevoComprobante" name="nuevoComprobante" required> <option value="">Tipo Comprobante</option> <?php $item = null; $valor = null; $comprobantes = Controladorcomprobantes::ctrMostrarComprobantes($item, $valor); foreach ($comprobantes as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["nombre"].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA PRECIO COMPRA --> <div class="form-group row"> <div class="col-xs-6"> <label for="">Cantidad de Venta</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-up"></i></span> <input type="number" class="form-control input-lg" id="nuevaCantidadVenta" name="nuevaCantidadVenta" min="1" placeholder="(lega=1;libro=200)" required> </div> </div> <!-- ENTRADA PARA PRECIO VENTA --> <div class="col-xs-6"> <label for="">Cantidad Minima</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-down"></i></span> <input type="number" class="form-control input-lg" id="nuevaCantidadMinima" name="nuevaCantidadMinima" min="1" placeholder="Cantidad Minima" required> </div> </div> </div> <!-- ENTRADA PARA PRECIO COMPRA --> <div class="form-group row"> <div class="col-xs-6"> <label for="">Cuotas</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-up"></i></span> <input type="number" class="form-control input-lg" id="nuevaCuota" name="nuevaCuota" min="0" placeholder="Cursos:12 NoCurso:0" required> </div> </div> <!-- ENTRADA PARA PRECIO VENTA --> <div class="col-xs-6"> <label for="">Importe</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-down"></i></span> <input type="number" class="form-control input-lg" id="nuevoImporte" name="nuevoImporte" placeholder="Importe" required> </div> </div> </div> <!-- ENTRADA PARA LA DESCRIPCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" name="nuevaObs" placeholder="Ingresar Observaciones" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar producto</button> </div> </form> <?php $crearProducto = new ControladorProductos(); $crearProducto -> ctrCrearProducto(); ?> </div> </div> </div> <!--===================================== MODAL EDITAR PRODUCTO ======================================--> <div id="modalEditarProducto" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar producto</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA SELECCIONAR RUBROS --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="editarRubro" name="editarRubro" required> <option value="">Selecionar rubro</option> <?php $item = null; $valor = null; $categorias = ControladorRubros::ctrMostrarRubros($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["nombre"].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA EL CÓDIGO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-code"></i></span> <input type="hidden" name="idProducto" id="idProductoEditar"> <input type="text" class="form-control input-lg" id="editarCodigo" name="editarCodigo" placeholder="Ingresar código" readonly required> </div> </div> <!-- ENTRADA PARA LA nOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" id="editarNombre" name="editarNombre" placeholder="Ingresar nombre" required> </div> </div> <!-- ENTRADA PARA LA DESCRIPCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" name="editarDescripcion" id="editarDescripcion" placeholder="Ingresar descripción" required> </div> </div> <!-- ENTRADA PARA SELECCIONAR RUBROS --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="editarComprobante" name="editarComprobante" required> <option value="">Tipo Comprobante</option> <?php $item = null; $valor = null; $comprobantes = Controladorcomprobantes::ctrMostrarComprobantes($item, $valor); foreach ($comprobantes as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["nombre"].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA PRECIO COMPRA --> <div class="form-group row"> <div class="col-xs-6"> <label for="">Cantidad de Venta</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-up"></i></span> <input type="number" class="form-control input-lg" id="editarCantidadVenta" name="editarCantidadVenta" min="1" placeholder="(lega=1;libro=200)" required> </div> </div> <!-- ENTRADA PARA PRECIO VENTA --> <div class="col-xs-6"> <label for="">Cantidad Minima</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-down"></i></span> <input type="number" class="form-control input-lg" id="editarCantidadMinima" name="editarCantidadMinima" min="1" placeholder="Cantidad Minima" required> </div> </div> </div> <!-- ENTRADA PARA PRECIO COMPRA --> <div class="form-group row"> <div class="col-xs-6"> <label for="">Cuotas</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-up"></i></span> <input type="number" class="form-control input-lg" id="editarCuota" name="editarCuota" min="0" placeholder="Cursos:12 NoCurso:0" required> </div> </div> <!-- ENTRADA PARA PRECIO VENTA --> <div class="col-xs-6"> <label for="">Importe</label> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-arrow-down"></i></span> <input type="number" class="form-control input-lg" id="editarImporte" name="editarImporte" placeholder="Importe" required> </div> </div> </div> <!-- ENTRADA PARA LA DESCRIPCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-product-hunt"></i></span> <input type="text" class="form-control input-lg" name="editarObs" id="editarObs" placeholder="Ingresar Observaciones" required> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar producto</button> </div> </form> <?php $editarProducto = new ControladorProductos(); $editarProducto -> ctrEditarProducto(); ?> </div> </div> </div> <?php $eliminarProducto = new ControladorProductos(); $eliminarProducto -> ctrEliminarProducto(); ?> <file_sep>/vistas/modulos/descargar-reporte.php <?php require_once "../../controladores/ventas.controlador.php"; require_once "../../modelos/ventas.modelo.php"; require_once "../../controladores/escribanos.controlador.php"; require_once "../../modelos/escribanos.modelo.php"; require_once "../../controladores/enlace.controlador.php"; require_once "../../modelos/enlace.modelo.php"; require_once "../../controladores/usuarios.controlador.php"; require_once "../../modelos/usuarios.modelo.php"; $reporte = new ControladorVentas(); $reporte -> ctrDescargarReporte();<file_sep>/vistas/modulos/editar-venta.php <?php #ELIMINO TODA LA TABLA $item = null; $valor = null; $respuesta = ControladorComprobantes::ctrIniciarItems($item, $valor); $item= "id"; $valor = $_GET["idVenta"]; $venta = ControladorCuotas::ctrMostrarCuotas($item,$valor); // $itemUsuario = "id"; // $valorUsuario = $venta["id_vendedor"]; // $vendedor = ControladorUsuarios::ctrMostrarUsuarios($itemUsuario,$valorUsuario); $itemCliente = "id"; $valorCliente = $venta["id_cliente"]; $cliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente,$valorCliente); $itemTipoCliente = "id"; $valorTipoCliente = $cliente["id_categoria"]; $tipoCliente = ControladorCategorias::ctrMostrarCategorias($itemTipoCliente,$valorTipoCliente); //ULTIMO NUMERO DE VENTAS $item = "nombre"; $valor = "ventas"; $registro = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); $puntoVenta = $registro["cabezacomprobante"]; // FORMATEO EL NUMERO DE COMPROBANTE $ultimoComprobanteAprox=$registro["numero"]+1; $cantRegistro = strlen($ultimoComprobanteAprox); switch ($cantRegistro) { case 1: $ultimoComprobante="0000000".$ultimoComprobanteAprox; break; case 2: $ultimoComprobante="000000".$ultimoComprobanteAprox; break; case 3: $ultimoComprobante="00000".$ultimoComprobanteAprox; break; case 4: $ultimoComprobante="0000".$ultimoComprobanteAprox; break; case 5: $ultimoComprobante="000".$ultimoComprobanteAprox; break; case 6: $ultimoComprobante="00".$ultimoComprobanteAprox; break; case 7: $ultimoComprobante="0".$ultimoComprobanteAprox; break; case 8: $ultimoComprobante=$ultimoComprobanteAprox; break; } $cantCabeza = strlen($puntoVenta); switch ($cantCabeza) { case 1: $ptoVenta="000".$puntoVenta; break; case 2: $ptoVenta="00".$puntoVenta; break; case 3: $ptoVenta="0".$puntoVenta; break; } $codigoFacturaAprox = $ptoVenta .'-'. $ultimoComprobante; ?> <div class="content-wrapper"> <section class="content"> <form method="post" class="formularioVenta" name="frmVentaEditada" id="frmVentaEditada"> <div class="row"> <!--===================================================== PANEL IZQUIERDO ========================================================--> <div class="col-md-3" style="margin-top: 10px;"> <div class="panel " > <div class="panel-heading" style="background-color: #212121;color:white"> <h4>Datos del Escribano</h4> </div> <div class="panel-body" style="background-color: #37474F;color:white"> <div class="col-xs-12"> <label for="nombre">NRO. FC</label> <?php $registro=$registro; ?> <input type="text" class="form-control" id='editarVenta' name='editarVenta' autocomplete="off" value="<?php echo $codigoFacturaAprox;?>" style="text-align: center;" readonly> <input type='hidden' id='idVendedor' name='idVendedor' value='1'> <input type='hidden' id='idVenta' name='idVenta' value='<?php echo $_GET["idVenta"];?>'> <input type='hidden' id='tipoFc' name='tipoFc' value='<?php echo $venta["tipo"];?>'> </div> <div class="col-xs-12 "> <!-- <label for="nombre">NOMBRE</label> --> <input type='hidden' id='seleccionarCliente' name='seleccionarCliente' value="<?php echo $cliente['id'];?>"> <input type="text" class="form-control" placeholder="NOMBRE...." id='nombrecliente' name='nombreCliente' value="<?php echo $cliente['nombre'];?>" autocomplete="off" readonly style="margin-top: 5px"> <input type='hidden' id='categoria' name='categoria' value="SinCategoria"> <?php if($cliente['facturacion']=="CUIT"){ echo "<input type='hidden' id='documentoCliente' name='documentoCliente' value=".$cliente['cuit'].">"; echo "<input type='hidden' id='tipoDocumento' name='tipoDocumento' value='CUIT'>"; }else{ echo "<input type='hidden' id='documentoCliente' name='documentoCliente' value=". $cliente['documento'].">"; echo "<input type='hidden' id='tipoDocumento' name='tipoDocumento' value='DNI'>"; } ?> <input type='hidden' id='tipoCliente' name='tipoCliente' value="escribanos"> <input type='hidden' id='tipoCuota' name='tipoCuota' value="<?php echo $venta['tipo'];?>"> </div> <!-- <div class="col-xs-12"> <button type="button" class="btn btn-primary btn-block btnBuscarCliente" data-toggle="modal" data-target="#myModalClientes" style="margin-top: 5px;" autofocus>Buscar Cliente</button> </div> --> <div class="col-xs-12"> <div class="form-group"> <label>FECHA:</label> <div class="input-group date"> <div class="input-group-addon"> <i class="fa fa-calendar"></i> </div> <input type="text" class="form-control pull-right" id="datepicker" name="fecha" data-date-format="dd-mm-yyyy" value="<?php echo $venta["fecha"];?>"> </div> </div> </div> <!-- <div class="col-xs-12"> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <?php echo '<option value="'.$venta['metodo_pago'].'">'.$venta['metodo_pago'].'</option>'; ?> <option value="CTA.CORRIENTE">CTA.CORRIENTE</option> <option value="EFECTIVO">EFECTIVO</option> <option value="TARJETA">TARJETA</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> </select> </div> --> <!-- <div class="col-xs-12 "> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div> --> <input type="hidden" id="nuevoPrecioImpuesto" name="nuevoPrecioImpuesto" value="0"> <input type="hidden" id="nuevoPrecioNeto" name="nuevoPrecioNeto" value="0"> <input type="hidden" id="nuevoTotalVentas" name="nuevoTotalVentas" value="0"> <div class="col-xs-12"> <button type="button" class="btn btn-info btn-block" data-toggle="modal" data-target="#myModalProductos" style="margin-top: 5px;"> Articulos </button> </div> </div> </div> </div> <!--===================================================== TABLA DE ARTICULOS ========================================================--> <div class="col-md-9" style="margin-top: 10px;" id="articulosP"> <div class="box box-primary"> <div class="box-header box-info"style="background-color: #212121;color:white"> <h3 class="box-title">Articulos</h3> </div> <!-- /.box-header --> <div class="box-body no-padding" id="datosTabla"> <table class="table table-bordered tablaProductosVendidos"> <thead> <tr> <th style="width: 10px;">#</th> <th style="width: 10px;">Cantidad</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 150px;">Precio</th> <th style="width: 200px;">Total</th> <th style="width: 100px;">Op.</th> </tr> </thead> <tbody class="tablaProductosSeleccionados"> <?php $listaProducto= json_decode($venta["productos"],true); foreach ($listaProducto as $key => $value) { echo '<tr> <td>'.($key + 1) .'</td> <td> <input type="number" class="form-control nuevaCantidadProducto" name="nuevaCantidadProducto" value="'.$value['cantidad'].'" readonly> </td> <td> <div> <input type="text" class="form-control nuevaDescripcionProducto" idProducto="'.$value['id'].'" idNroComprobante="'.$value['idnrocomprobante'].'" cantVentaProducto="'.$value['cantventaproducto'].'" name="agregarProducto" value="'.$value['descripcion'].'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio1" name="folio1" value="'.$value['folio1'].'" readonly required> </div> </td> <td> <div class="input-group"> <input type="text" class="form-control nuevoFolio2" name="folio2" value="'.$value['folio2'].'" readonly required> </div> </td> <td> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoPrecioProducto" precioReal="'.$value['precio'].'" name="nuevoPrecioProducto" value="'.$value['precio'].'" readonly required> </div> </td> <td style="text-align: right;"> <div class="input-group"> <span class="input-group-addon"><i class="ion ion-social-usd"></i></span> <input type="text" class="form-control nuevoTotalProducto" precioTotal="'.($value['cantidad']*$value['precio']).'" name="nuevoTotalProducto" value="'.($value['cantidad']*$value['precio']).'" readonly required> </div> </td> <td> </td> </tr>'; } ?> </tbody> <tfooter> <tr> <td colspan="8"><div class="col-xs-2">Escribano: </div> <strong> <div class="col-xs-3" id="panel3nombrecliente"> <?php echo $cliente['nombre']; ?> </div> </strong> <div class="col-xs-2">Categoria: </div> <strong> <div class="col-xs-2" id="panel3TipoCLiente"> <?php echo $tipoCliente['categoria'];?> </div> </strong> </td> </tr> </tfooter> </table> <input type="hidden" id="listaProductos" name="listaProductos" value='<?php echo $venta["productos"];?>'> </div> <div class="box-footer" style="background-color: #FAFAFA"> <div class="col-xs-12"> <input type="hidden" id="totalVenta" name="totalVenta" value="<?php echo $venta['total']; ?>"> <h1><div id="totalVentasMostrar" class="pull-right"><?php echo '$ '.$venta['total'].'.00'; ?></div></h1> </div> <div class="col-xs-12"> <button type="button" class="btn btn-danger pull-right" data-toggle="modal" data-target="#myModalPago" style="margin-top: 10px;" id="btn-editarVenta">Guardar Venta </button> </div> </div> </div> </div> </div> <!--===================================== MODAL PARA ELEGIR PAGO ======================================--> <div id="myModalPago" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" style="background:#3E4551; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Metodo Pago</h4> </div> <div class="modal-body"> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <option value="EFECTIVO" selected>EFECTIVO</option> <option value="CTA.CORRIENTE">CTA.CORRIENTE</option> <option value="TARJETA">TARJETA</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> <option value="CHEQUE">CHEQUE</option> </select> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div><!-- Modal body--> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" id="guardarEditarVenta">Guardar Venta</button> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> </form> <?php foreach ($listaProducto as $key => $value) { // tomo todos los datos que vienen por el formulario $datos = array("idproducto"=>$value['id'], "nombre"=>$value['descripcion'], "idNroComprobante"=>$value['idnrocomprobante'], "cantidadProducto"=>$value['cantidad'], "cantVentaProducto"=>$value['cantventaproducto'], "precioVenta"=>$value['precio'], "folio1"=>$value['folio1'], "folio2"=>$value['folio2']); //los agrego en la tabla tmp_items $respuesta = ControladorComprobantes::ctrAgregarItemsComprobantes($datos); } $editarVenta = new ControladorCuotas(); $editarVenta -> ctrEditarCuota(); ?> </section> </div> <!--===================================== MODAL PARA BUSCAR CLIENTES ======================================--> <div id="myModalClientes" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button">&times;</button> <h4 class="modal-title">Seleccione cliente</h4> <button class="btn btn-primary" data-toggle="modal" data-dismiss="modal" data-target="#modalAgregarCliente"> Agregar cliente </button> </div> <div class="modal-body" > <div id="datos_ajax"></div> <table id="buscarclientetabla" class="table table-striped table-condensed table-hover tablaBuscarClientes"> <thead> <tr> <th width="150">nombre</th> <th width="80">documento</th> <th width="80">cuit</th> <th width="150">opciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($clientes as $key => $value) { echo '<tr>'; echo '<td>'.$clientes[$key]["nombre"].'</td>'; echo '<td>'.$clientes[$key]["documento"].'</td>'; echo '<td>'.$clientes[$key]["cuit"].'</td>'; echo '<td><button class="btn btn-primary btnBuscarCliente" data-dismiss="modal" idCliente='.$clientes[$key]["id"].' nombreCliente="'.$clientes[$key]["nombre"].'">Seleccionar</button></td>'; echo '</tr>'; } ?> </tbody> </table> </div><!-- Modal body--> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarCliente'>Cerrar</button> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <!-- Modal --> <!-- Modal --> <div id="myModalProductos" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" style="background:#3E4551; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Seleccionar articulo</h4> </div> <div class="modal-body" > <div id="datos_ajax_producto"></div> <div id="contenidoSeleccionado" style="display: none"> <div class="row"> <div class="col-xs-2"> <label for="cantidadProducto">CANT.</label> <input type="text" class="form-control" id="cantidadProducto" name="cantidadProducto" autocomplete="off" value="1"> <input type="hidden" class="form-control" id="idproducto" name="idproducto"> <input type="hidden" class="form-control" id="idVenta" name="idVenta" value="<?php echo $_GET["idVenta"];?>"> <input type="hidden" class="form-control" id="idNroComprobante" name="idNroComprobante"> <input type="hidden" class="form-control" id="cantVentaProducto" name="cantVentaProducto"> </div> <div class="col-xs-5"> <label for="nombreProducto">PRODUCTO</label> <input type="text" class="form-control" id="nombreProducto" name="nombreProducto" disabled> </div> <div class="col-xs-3"> <label for="precioProducto">PRECIO</label> <input type="text" class="form-control" id="precioProducto" name="precioProducto" autocomplete="off" > </div> <div class="col-xs-2"> <button class="btn btn-primary" style="margin-top: 25px" id="grabarItem">Grabar</button> </div> </div> </div> <div id="contenido_producto"> <table id="buscararticulotabla" class="table table-bordered table-striped tablaBuscarProductos"> <thead> <tr> <th width="10">id</th> <th>nombre</th> <th>precio</th> <th>opciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $orden = "nombre"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); foreach ($productos as $key => $value){ if ($value['id']>=19 && $value['id']<=22){ echo ' <tr> <td>'.($key+1).'</td> <td>'.$value["nombre"].'</td>'; echo '<td>'.$value["importe"].'</td>'; echo '<td> <button class="btn btn-primary btnSeleccionarProducto" idProducto="'.$value["id"].'" idNroComprobante="'.$value["nrocomprobante"].'" cantVentaProducto="'.$value["cantventa"].'" productoNombre="'.$value["nombre"].'" precioVenta="'.$value["importe"].'">Seleccionar</button> </td> </tr>'; } } ?> </tbody> </table> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" id='cerrarProducto'>Cerrar</button> </div> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> </div> </div> <div id="modalLoader" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Aguarde un instante</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <center> <img src="vistas/img/afip/loader.gif" alt=""> </center> <center> <img src="vistas/img/afip/afip.jpg" alt=""> </center> </div> </div> <div class="modal-footer"> <p><strong>CONECTANDOSE AL SERVIDOR DE AFIP</strong></p> </div> </div> </div> </div><file_sep>/vistas/js/inicio.js $(document).ready(function() { // INICIO LOS COMPROBANTES var pathname = window.location.pathname; if(pathname =="/colegio/iniciosinconexion"){ if(navigator.onLine) { // el navegador está conectado a la red window.location = "inicio"; } else { // el navegador NO está conectado a la red $('#modalMostar #titulo').html("ERROR DE CONEXION"); $('#modalMostar #mostrarBody').html("<center><img src='vistas/img/plantilla/desconectado.jpg'><h3>SIN CONEXION</h3><h4>Funciones reducidas</h4></center>"); $("#modalMostar #cabezaLoader").css("background", "#ffbb33"); $("#mostrarSalir").removeClass("btn-danger"); $("#mostrarSalir").addClass("btn-warning"); $('#modalMostar').modal('show'); } } }) /*============================================= CARGAR LA TABLA =============================================*/ $("#upInhabilitados").click(function() { var datos = new FormData(); datos.append("upInhabilitados", "1"); $.ajax({ url:"ajax/updateInhabilitados.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, beforeSend: function(){ $("#cabezaLoader").css("background", "#ffbb33"); $('#actualizacionparrafo').html("<strong>ACTUALIZANDO LOS INHABILITADOS</strong>"); $('#modalLoader').modal('show'); }, success:function(respuesta){ $('#modalLoader').modal('hide'); } }) }) $("#btnMostrarInhabilitados").click(function() { var datos = new FormData(); datos.append("mostrarInhabilitados", "1"); $.ajax({ url:"ajax/updateInhabilitados.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuesta){ $('#modalMostar #titulo').html("ESCRIBANOS INHABILITADOS"); $('#modalMostar #mostrarBody').html(respuesta); $("#modalMostar #cabezaLoader").css("background", "#ffbb33"); $("#mostrarSalir").removeClass("btn-danger"); $("#mostrarSalir").addClass("btn-warning"); $('#modalMostar').modal('show'); } }) }) $("#upProductos").click(function() { var datos = new FormData(); datos.append("updateProductos", "1"); $.ajax({ url:"ajax/updateProductos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, beforeSend: function(){ $("#cabezaLoader").css("background", "#ff4444"); $('#actualizacionparrafo').html("<strong>ACTUALIZANDO LOS PRODUCTOS</strong>"); $('#modalLoader').modal('show'); }, success:function(respuesta){ $('#modalLoader').modal('hide'); } }) }) $("#btnMostrarProductos").click(function() { var datos = new FormData(); datos.append("mostrarProductos", "1"); $.ajax({ url:"ajax/updateProductos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuesta){ $('#modalMostar #titulo').html("PRODUCTOS"); $('#modalMostar #mostrarBody').html(respuesta); $("#modalMostar #cabezaLoader").css("background", "#ff4444"); $("#mostrarSalir").removeClass("btn-danger"); $("#mostrarSalir").addClass("btn-danger"); $('#modalMostar').modal('show'); } }) }) $("#upEscribanos").click(function() { var datos = new FormData(); datos.append("upEscribanos", "1"); $.ajax({ url:"ajax/updateEscribanos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, beforeSend: function(){ $("#cabezaLoader").css("background", "#00C851"); $('#actualizacionparrafo').html("<strong>ACTUALIZANDO LOS ESCRIBANOS</strong>"); $('#modalLoader').modal('show'); }, success:function(respuesta){ $('#modalLoader').modal('hide'); } }) }) $("#btnMostrarEscribanos").click(function() { var datos = new FormData(); datos.append("mostrarEscribanos", "1"); $.ajax({ url:"ajax/updateEscribanos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuesta){ $('#modalMostar #titulo').html("ESCRIBANOS"); $('#modalMostar #mostrarBody').html(respuesta); $("#modalMostar #cabezaLoader").css("background", "#00C851"); $("#mostrarSalir").removeClass("btn-danger"); $("#mostrarSalir").addClass("btn-success"); $('#modalMostar').modal('show'); } }) }) $("#actualizarCuota").click(function() { var datos = new FormData(); datos.append("actualizarCuota", "1"); $.ajax({ url:"ajax/updateTodo.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, beforeSend: function(){ $("#cabezaLoader").css("background", "#ffbb33"); $('#actualizacionparrafo').html("<strong>ACTUALIZANDO TODAS LAS CUOTAS</strong>"); $('#modalLoader').modal('show'); }, success:function(respuesta){ console.log("respuesta", respuesta); $('#modalLoader').modal('hide'); } }) }) $("#actualizarFc").click(function() { var datos = new FormData(); datos.append("actualizarFc", "1"); $.ajax({ url:"ajax/updateTodo.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, beforeSend: function(){ $("#cabezaLoader").css("background", "#ffbb33"); $('#actualizacionparrafo').html("<strong>ACTUALIZANDO TODAS LAS CUOTAS</strong>"); $('#modalLoader').modal('show'); }, success:function(respuesta){ console.log("respuesta", respuesta); $('#modalLoader').modal('hide'); } }) }) $("#revisarInabilitados").click(function() { window.location = "index.php?ruta=inicio&tipo=revisar"; }) <file_sep>/controladores/parametros.controlador.php <?php class ControladorParametros{ /*============================================= MOSTRAR PARAMETROS DE FACTURACION =============================================*/ static public function ctrMostrarParametros($item, $valor){ $tabla = "facturaconfig"; $respuesta = ModeloParametros::mdlMostrarParametros($tabla, $item, $valor); return $respuesta; } /*============================================= MOSTRAR PARAMETROS DE VENTAS =============================================*/ static public function ctrMostrarParametroAtraso($item, $valor){ $tabla = "parametros"; $respuesta = ModeloParametros::mdlMostrarParametros($tabla, $item, $valor); return $respuesta; } static public function ctrEditarParametros(){ if (isset($_POST["editarId"])){ $tabla = "parametros"; $datos = array("id" => $_POST["editarId"], "valor" => $_POST["editarValor"]); $respuesta =ControladorParametros::ctrbKParametros($tabla, "id", $_POST["editarId"], "UPDATE"); $respuesta = ModeloParametros::mdlEditarParametros($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "Ha sido editado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "parametros"; } }) </script>'; } } } static public function ctrEditarLibro(){ if(isset($_POST['editarIdEscribano'])){ $tabla = "escribanos"; $datos = array("ultimolibrocomprado"=>$_POST["editarUltimoLibroComprado"], "ultimolibrodevuelto"=>$_POST["editarUltimoLibroDevuelto"], "id"=>$_POST["editarIdEscribano"]); $respuesta = ModeloParametros::mdlEditarLibro($tabla, $datos); if($respuesta == "ok"){ echo'<script> window.location = "index.php?ruta=inicio&tipo=revisar"; </script>'; } } } static public function ctrbKParametros($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorParametros::ctrMostrarParametroAtraso($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "parametro":"'.$respuesta[1].'", "valor":"'.$respuesta[2].'"}]'; $datos = array("tabla"=>"parametros", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloParametros::mdlbKParametro($tabla, $datos); } /*============================================= MOSTRAR DATOS ELIMINADOs =============================================*/ static public function ctrMostrarBackUp($item, $valor){ $tabla = "backup"; $respuesta = ModeloParametros::mdlMostrarBackUp($tabla, $item, $valor); return $respuesta; } /*============================================= ELIMINAR DATOS =============================================*/ static public function ctrEliminarBackup(){ if (isset($_GET['idBackUpEliminar'])){ $datos = $_GET['idBackUpEliminar']; $tabla = "backup"; $respuesta = ModeloParametros::mdlEliminarBackup($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "Ha sido editado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "restaurar"; } }) </script>'; } } } /*============================================= ELIMINAR DATOS =============================================*/ static public function ctrRestaurarBackup(){ if (isset($_GET['idBackUpRestaurar'])){ $datos = $_GET['idBackUpRestaurar']; $tabla = "backup"; $respuesta = ModeloParametros::mdlMostrarBackup($tabla,"id", $datos); echo '<pre>'; print_r($respuesta); echo '</pre>'; } } static public function ctrCountTablas($tabla,$item,$valor){ $respuesta = ModeloParametros::mdlCountTablas($tabla,$item,$valor); return $respuesta; } } <file_sep>/controladores/articulos.controlador.php <?php class ControladorArticulos{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function ctrMostrarArticulos($item, $valor){ $tabla = "articulos"; $respuesta = ModeloArticulos::mdlMostrarArticulos($tabla, $item, $valor); return $respuesta; } /*============================================= CREAR ESCRIBANOS =============================================*/ static public function ctrCrearArticulo($datos){ $tabla="articulos"; $respuesta = ModeloArticulos::mdlIngresarArticulo($tabla, $datos); } /*============================================= CREAR PREPARAR ARTICULOS PARA INGRESAR =============================================*/ static public function ctrPrepararIngresoArticulo(){ #tomo los productos $listarProductos = json_decode($_POST["listaProductos"], true); #creo un array del afip $items=Array(); foreach ($listarProductos as $key => $value) { if ($value['folio1']!=1){ $respuesta = ControladorVentas::ctrUltimoId(); $i = $value['folio1']; for ($i; $i <= $value['folio2'] ; $i++) { # code... $datos = array("folio"=>$i, "nrocomprobante"=>$value["idnrocomprobante"], "nombre"=>$value["descripcion"], "idfactura"=>$respuesta[0], "fecha"=>"10/10/10", "nrofactura"=>$respuesta['codigo'], "nombrecliente"=>$_POST['nombreCliente']); print_r($_POST); $registro = ControladorArticulos::ctrCrearArticulo($datos); } } } } }<file_sep>/ajax/empresa.fotos.ajax.php <?php require_once "../controladores/empresa.controlador.php"; require_once "../modelos/empresa.modelo.php"; class AjaxEmpresa{ /*============================================= CAMBIAR BACKEND =============================================*/ public $tipo; public $imagen; public function ajaxCambiarImagen(){ $item = $this ->tipo; $valor = $this->imagen; $respuesta = ControladorEmpresa::ctrActualizarImagen($item, $valor); echo $respuesta; } } /*============================================= CAMBIAR ICONO CHICO BLANCO =============================================*/ if(isset($_FILES["iconochicoblanco"])){ $img = new AjaxEmpresa(); $img -> imagen = $_FILES["iconochicoblanco"]; $img -> tipo = 'iconochicoblanco'; $img -> ajaxCambiarImagen(); } /*============================================= CAMBIAR ICONO CHICO NEGRO =============================================*/ if(isset($_FILES["iconochiconegro"])){ $img = new AjaxEmpresa(); $img -> imagen = $_FILES["iconochiconegro"]; $img -> tipo = 'iconochiconegro'; $img -> ajaxCambiarImagen(); } /*============================================= CAMBIAR BLOQUE BLANCO =============================================*/ if(isset($_FILES["logoblancobloque"])){ $img = new AjaxEmpresa(); $img -> imagen = $_FILES["logoblancobloque"]; $img -> tipo = 'logoblancobloque'; $img -> ajaxCambiarImagen(); } /*============================================= CAMBIAR BLOQUE LINEAL BLANCO =============================================*/ if(isset($_FILES["logoblancolineal"])){ $img = new AjaxEmpresa(); $img -> imagen = $_FILES["logoblancolineal"]; $img -> tipo = 'logoblancolineal'; $img -> ajaxCambiarImagen(); } /*============================================= CAMBIAR RECIBO FOTO =============================================*/ if(isset($_FILES["fotorecibo"])){ $img = new AjaxEmpresa(); $img -> imagen = $_FILES["fotorecibo"]; $img -> tipo = 'fotorecibo'; $img -> ajaxCambiarImagen(); }<file_sep>/vistas/modulos/bibliotecas/cuotas.inicio.php <?php /*============================================= = GENERO LAS CUOTAS = =============================================*/ #CHEQUEO SI SE GENERARON Y SI NO SE GENERARON GENERARLA $GenerarCuota = ControladorCuotas::ctrChequearGeneracion("CUOTA"); $GenerarOsde = ControladorCuotas::ctrChequearGeneracion("OSDE"); ?><file_sep>/controladores/delegaciones.controlador.php <?php class ControladorDelegaciones{ /*============================================= MOSTRAR DELEGACIONES =============================================*/ static public function ctrMostrarDelegaciones($item, $valor){ $tabla = "delegaciones"; $respuesta = ModeloDelegaciones::mdlMostrarDelegaciones($tabla, $item, $valor); return $respuesta; } /*============================================= AGREGAR DELEGACIONES =============================================*/ static public function ctrIngresarDelegacion($datos){ $tabla = "delegaciones"; $respuesta = ModeloDelegaciones::mdlIngresarDelegacion($tabla, $datos); return $respuesta; } /*============================================= AGREGAR DELEGACIONES =============================================*/ static public function ctrEditarDelegacion($datos){ // print_r($datos); $tabla = "delegaciones"; $respuesta = ModeloDelegaciones::mdlEditarDelegacion($tabla, $datos); return $respuesta; } /*============================================= BORRAR DELEGACIONES =============================================*/ static public function ctrEliminarDelegacion(){ if(isset($_GET["idDelegacion"])){ $tabla ="delegaciones"; $datos = $_GET["idDelegacion"]; #ENVIAMOS LOS DATOS // ControladorCategorias::ctrbKCategorias($tabla, "id", $_GET["idCategoria"], "ELIMINAR"); $respuesta = ModeloDelegaciones::mdlBorrarDelegacion($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La delegacion ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "delegaciones"; } }) </script>'; } } } } <file_sep>/vistas/modulos/ctacorriente.php <?php // FECHA DEL DIA DE HOY $fecha=date('Y-m-d'); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar cta. corriente </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar cta. corriente</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <a href="crear-venta"> <button class="btn btn-primary"> Agregar venta </button> </a> <!-- <button type="button" class="btn btn-default pull-right" id="daterange-btn"> <span> <i class="fa fa-calendar"></i> Rango de Fecha </span> <i class="fa fa-caret-down"></i> </button> --> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th style="width:45px">Fecha</th> <th style="width:35px">Tipo</th> <th>Nro. Factura</th> <th>Escribano</th> <!-- <th>Vendedor</th> --> <th>Forma de pago</th> <th style="width:50px">Total</th> <th style="width:50px">Adeuda</th> <th style="width:140px">Acciones</th> </tr> </thead> <tbody> <?php if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } $respuesta = ControladorVentas::ctrRangoFechasCtaCorriente($fechaInicial, $fechaFinal); foreach ($respuesta as $key => $value) { // if(strlen($value["codigo"])==13 && $value["metodo_pago"]=="CTA.CORRIENTE"){ echo '<tr> <td>'.($key+1).'</td> <td>'.$value["fecha"].'</td> <td>'.$value["tipo"].'</td> <td>'.$value["codigo"].'</td>'; $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo '<td>'.$respuestaCliente["nombre"].'</td>'; echo '<td>'.$value["metodo_pago"].'</td> <td>$ '.number_format($value["total"],2).'</td>'; if ($value["adeuda"]==0){ echo '<td style="color:green">$ '.number_format($value["adeuda"],2).'</td>'; }else{ echo '<td style="color:red">$ '.number_format($value["adeuda"],2).'</td>'; } echo ' <td> <div class="btn-group"> <button class="btn btn-info btnVerVenta" idVenta="'.$value["id"].'" codigo="'.$value["codigo"].'" title="ver la factura" data-toggle="modal" data-target="#modalVerArticulos"><i class="fa fa-eye"></i></button> <button class="btn btn-success btnImprimirFactura" total="'.$value["total"].'" adeuda="'.$value["adeuda"].'" codigoVenta="'.$value["codigo"].'"> <i class="fa fa-file-pdf-o"></i> </button>'; if ($value["adeuda"]==0 && $value["total"]<>0){ echo '<button class="btn btn-default"><i class="fa fa-money"></i></button>'; }else{ echo '<button class="btn btn-danger btnEditarPago" idVenta="'.$value["id"].'" data-toggle="modal" data-target="#modalAgregarPago"><i class="fa fa-money"></i></button>'; } // echo ' <button class="btn btn-danger btnEliminarVenta" idVenta="'.$value["id"].'"><i class="fa fa-times"></i></button>'; echo '</div> </td> </tr>'; // } } ?> </tbody> </table> <?php $eliminarVenta = new ControladorVentas(); $eliminarVenta -> ctrEliminarVenta(); $eliminarPago = new ControladorVentas(); $eliminarPago -> ctrEliminarPago(); ?> </div> </div> </section> </div> <!--===================================== VER ARTICULOS ======================================--> <div id="modalVerArticulos" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Ver Articulos</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="verEscribano" id="verEscribano" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-usd"></i></span> <input type="text" class="form-control input-lg" name="verTotalFc" id="verTotalFc" placeholder="Ingresar Pago" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th style="width: 10px;">Cant.</th> <th style="width: 500px;">Articulo</th> <th style="width: 150px;">Folio 1</th> <th style="width: 150px;">Folio 2</th> <th style="width: 200px;">Total</th> </tr> </thead> <tbody class="tablaArticulosVer"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer finFactura"> <button type="button" class="btn btn-info pull-left" data-dismiss="modal" id="imprimirItems" codigo="<?php echo $value["codigo"];?>">Imprimir Factura</button> <button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Salir</button> </div> </form> </div> </div> </div> <!--===================================== AGREGAR PAGO ======================================--> <div id="modalAgregarPago" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" method="post"> <div class="modal-header" style="background:#3E4551; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Metodo Pago</h4> </div> <div class="modal-body"> <input type="hidden" id="idVentaPago" name="idVentaPago" value="13"> <input type="hidden" id="totalVentaPago" name="totalVentaPago" value="13"> <label for="pago">PAGO</label> <select class="form-control" id='listaMetodoPago' name='listaMetodoPago'> <option value="EFECTIVO" selected>EFECTIVO</option> <option value="TARJETA">TARJETA</option> <option value="TRANSFERENCIA">TRANSFERENCIA</option> <option value="CHEQUE">CHEQUE</option> </select> <label for="nuevaReferencia">REFERENCIA</label> <input type="text" class="form-control" placeholder="REFERENCIA...." id='nuevaReferencia' name='nuevaReferencia' value='EFECTIVO' autocomplete="off"> </div><!-- Modal body--> <div class="modal-footer"> <button type="submit" class="btn btn-danger">Realizar Pago</button> </div> <?php $realizarPago = new ControladorVentas(); $realizarPago -> ctrRealizarPagoVenta(); ?> </form> </div><!-- Modal content--> </div><!-- Modal dialog--> </div><!-- Modal face--> <file_sep>/vistas/modulos/buscaritem.php <!-- {"id":"12","descripcion":"PROTOCOLO","idnrocomprobante":"56","cantventaproducto":"10", "folio1":"368451","folio2":"368470","cantidad":"2","precio":"1000","total":"2000"}, {"id":"10","descripcion":"CONCUERDAS","idnrocomprobante":"54","cantventaproducto":"1", "folio1":"196925","folio2":"196944","cantidad":"20","precio":"100","total":"2000"}, {"id":"8","descripcion":"CERTIFICACION DE FIRMAS","idnrocomprobante":"52","cantventaproducto":"1", "folio1":"670565","folio2":"670584","cantidad":"20","precio":"100","total":"2000"}] --> <div class="content-wrapper"> <section class="content-header"> <h1> BUSCAR ITEMS </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Buscar items</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-body"> <?php //2018 //2019 // $fechaInicial='2019-01-01'; // $fechaFinal='2019-12-31'; //2020 // $fechaInicial='2020-01-01'; // $fechaFinal='2020-12-31'; //2021 // $fechaInicial='2021-01-01'; // $fechaFinal='2021-12-31'; function copiarVentas($fechaInicial, $fechaFinal){ //DATOS DE TODAS LAS VENTAS DEL MES $respuesta = ControladorVentas::ctrRangoFechasVentasNuevo($fechaInicial,$fechaFinal); foreach ($respuesta as $key => $value) { #tomo los productos $datos = array(); $listaProductos = json_decode($value["productos"], true); #recorro $listaproductos para cargarlos en la tabla de comprobantes foreach ($listaProductos as $key => $value2) { $tablaComprobantes = "comprobantes"; $idVenta = $value['id']; $idCodigoFc = $value['codigo']; $fecha = $value['fecha']; $nombreEscribano = $value['nombre']; $nroComprobante = $value2["idnrocomprobante"]; $descripcionComprobante = $value2["descripcion"]; $folio1 = $value2["folio1"]; $folio2 = $value2["folio2"]; if($folio1 == $folio2){ $datos = array( "idVenta"=>$idVenta, "idCodigoFc"=>$idCodigoFc, "fecha"=>$fecha, "nombreEscribano"=>$nombreEscribano, "nroComprobante"=>$nroComprobante, "descripcionComprobante"=>$descripcionComprobante, "folio1"=>$folio1, "folio2"=>$folio2 ); // echo '<h2>MISMO FOLIO</h2>'; echo '<pre>'.$fechaInicial.' '.$fechaFinal.'</pre>'; $respuesta = ControladorVentas::ctrGuardarItem($datos); echo '<pre>'; print_r($respuesta); echo '</pre>'; }else{ for ($i=$folio1; $i < $folio2 ; $i++) { # code... $datos = array( "idVenta"=>$idVenta, "idCodigoFc"=>$idCodigoFc, "fecha"=>$fecha, "nombreEscribano"=>$nombreEscribano, "nroComprobante"=>$nroComprobante, "descripcionComprobante"=>$descripcionComprobante, "folio1"=>$folio1, "folio2"=>$i ); // echo '<h2>DISTINTO FOLIO</h2>'; // echo '<pre>'; print_r($datos); echo '</pre>'; echo '<pre>'.$fechaInicial.' '.$fechaFinal.'</pre>'; $respuesta = ControladorVentas::ctrGuardarItem($datos); echo '<pre>'; print_r($respuesta); echo '</pre>'; } } } } echo '<h1 class="text-danger">TERMINADO '.$fechaFinal.'</h1>'; } // copiarVentas('2018-01-01','2018-01-14'); // copiarVentas('2018-01-15','2018-01-31'); // copiarVentas('2018-02-01','2018-02-14'); // copiarVentas('2018-02-15','2018-02-28'); // copiarVentas('2018-03-01','2018-03-14'); // copiarVentas('2018-03-15','2018-03-31'); // copiarVentas('2018-04-01','2018-04-14'); // copiarVentas('2018-04-15','2018-04-30'); // copiarVentas('2018-05-01','2018-05-14'); // copiarVentas('2018-05-15','2018-05-31'); // copiarVentas('2018-06-01','2018-06-14'); // copiarVentas('2018-06-15','2018-06-30'); // copiarVentas('2018-07-01','2018-07-14'); // copiarVentas('2018-07-15','2018-07-31'); // copiarVentas('2018-08-01','2018-08-14'); // copiarVentas('2018-08-15','2018-08-31'); // copiarVentas('2018-09-01','2018-09-14'); // copiarVentas('2018-09-15','2018-09-30'); // copiarVentas('2018-10-01','2018-10-14'); copiarVentas('2018-10-15','2018-10-31'); // copiarVentas('2018-11-01','2018-11-14'); // copiarVentas('2018-11-15','2018-11-30'); // copiarVentas('2018-12-01','2018-12-14'); // copiarVentas('2018-12-15','2018-12-31'); // copiarVentas('2019-01-01','2019-01-14'); // copiarVentas('2019-01-15','2019-01-31'); // copiarVentas('2019-02-01','2019-02-14'); // copiarVentas('2019-02-15','2019-02-28'); // copiarVentas('2019-03-01','2019-03-14'); // copiarVentas('2019-03-15','2019-03-31'); // copiarVentas('2019-04-01','2019-04-14'); // copiarVentas('2019-04-15','2019-04-30'); // copiarVentas('2019-05-01','2019-05-14'); // copiarVentas('2019-05-15','2019-05-31'); // copiarVentas('2019-06-01','2019-06-14'); // copiarVentas('2019-06-15','2019-06-30'); // copiarVentas('2019-07-01','2019-07-14'); // copiarVentas('2019-07-15','2019-07-31'); // copiarVentas('2019-08-01','2019-08-14'); // copiarVentas('2019-08-15','2019-08-31'); // copiarVentas('2019-09-01','2019-09-14'); // copiarVentas('2019-09-15','2019-09-30'); // copiarVentas('2019-10-01','2019-10-14'); // copiarVentas('2019-10-15','2019-10-31'); // copiarVentas('2019-11-01','2019-11-14'); // copiarVentas('2019-11-15','2019-11-30'); // copiarVentas('2019-12-01','2019-12-14'); // copiarVentas('2019-12-15','2019-12-31'); // copiarVentas('2020-01-01','2020-01-14'); // copiarVentas('2020-01-15','2020-01-31'); // copiarVentas('2020-02-01','2020-02-14'); // copiarVentas('2020-02-15','2020-02-29'); // copiarVentas('2020-03-01','2020-03-14'); // copiarVentas('2020-03-15','2020-03-31'); // copiarVentas('2020-04-01','2020-04-14'); // copiarVentas('2020-04-15','2020-04-30'); // copiarVentas('2020-05-01','2020-05-14'); // copiarVentas('2020-05-15','2020-05-31'); // copiarVentas('2020-06-01','2020-06-14'); // copiarVentas('2020-06-15','2020-06-30'); // copiarVentas('2020-07-01','2020-07-14'); // copiarVentas('2020-07-15','2020-07-31'); // copiarVentas('2020-08-01','2020-08-14'); // copiarVentas('2020-08-15','2020-08-31'); // copiarVentas('2020-09-01','2020-09-14'); // copiarVentas('2020-09-15','2020-09-30'); // copiarVentas('2020-10-01','2020-10-14'); // copiarVentas('2020-10-15','2020-10-31'); // copiarVentas('2020-11-01','2020-11-14'); // copiarVentas('2020-11-15','2020-11-30'); // copiarVentas('2020-12-01','2020-12-14'); // copiarVentas('2020-12-15','2020-12-31'); // copiarVentas('2021-01-01','2021-01-14'); // copiarVentas('2021-01-15','2021-01-31'); // copiarVentas('2021-02-01','2021-02-14'); // copiarVentas('2021-02-15','2021-02-28'); // copiarVentas('2021-03-01','2021-03-14'); // copiarVentas('2021-03-15','2021-03-31'); // copiarVentas('2021-04-01','2021-04-14'); // copiarVentas('2021-04-15','2021-04-30'); // copiarVentas('2021-05-01','2021-05-14'); // copiarVentas('2021-05-15','2021-05-31'); // copiarVentas('2021-06-01','2021-06-14'); // copiarVentas('2021-06-15','2021-06-30'); // copiarVentas('2021-07-01','2021-07-14'); // copiarVentas('2021-07-15','2021-07-31'); // copiarVentas('2021-08-01','2021-08-14'); // copiarVentas('2021-08-15','2021-08-31'); // copiarVentas('2021-09-01','2021-09-14'); // copiarVentas('2021-09-15','2021-09-30'); // copiarVentas('2021-10-01','2021-10-14'); // copiarVentas('2021-10-15','2021-10-31'); // copiarVentas('2021-11-01','2021-11-14'); // copiarVentas('2021-11-15','2021-11-30'); // copiarVentas('2021-12-01','2021-12-14'); // copiarVentas('2021-12-15','2021-12-31'); ?> </div> </div> </section> </div><file_sep>/ajax/buscar.modelos.ajax.php <?php /*============================================= EDITAR CLIENTE =============================================*/ require_once "../modelos/modelos.modelo.php"; // $connection = mysqli_connect('localhost','root','','bgtoner2'); // // Si la conexión falla, aparece el error // if($connection === false) { // echo 'Ha habido un error <br>'.mysqli_connect_error(); // } else { // echo 'Conectado a la base de datos'; // } //Variable de búsqueda $consultaBusqueda = $_POST['valorBusqueda']; //Filtro anti-XSS $caracteres_malos = array("<", ">", "\"", "'", "/", "<", ">", "'", "/"); $caracteres_buenos = array("& lt;", "& gt;", "& quot;", "& #x27;", "& #x2F;", "& #060;", "& #062;", "& #039;", "& #047;"); $consultaBusqueda = str_replace($caracteres_malos, $caracteres_buenos, $consultaBusqueda); //Variable vacía (para evitar los E_NOTICE) $mensaje = ""; //Comprueba si $consultaBusqueda está seteado if (isset($consultaBusqueda)) { //Selecciona todo de la tabla mmv001 //donde el nombre sea igual a $consultaBusqueda, //o el apellido sea igual a $consultaBusqueda, //o $consultaBusqueda sea igual a nombre + (espacio) + apellido $respuesta=ModeloModelos::mdlBuscarModelos($consultaBusqueda); // $consulta = mysqli_query($connection, "SELECT * FROM modelo // WHERE nombre COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%' // OR detalle COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%' // OR CONCAT(nombre,' ',detalle) COLLATE UTF8_SPANISH_CI LIKE '%$consultaBusqueda%' // "); // //Obtiene la cantidad de filas que hay en la consulta // $filas = mysqli_num_rows($consulta); //Si existe alguna fila que sea igual a $consultaBusqueda, entonces mostramos el siguiente mensaje //La variable $resultado contiene el array que se genera en la consulta, así que obtenemos los datos y los mostramos en un bucle foreach ($respuesta as $key => $value) { //Output $mensaje .= ' <tr> <td>' . $value['nombre'] . '</td> <td><button type="button" class="btn btn-link btnSeleccionarModelo" nombreModelo="'.$value['nombre'].'" idModelo='.$value['id'] .'>Seleccionar</button></td> </tr> '; };//Fin while $resultados };//Fin isset $consultaBusqueda //Devolvemos el mensaje que tomará jQuery echo '<table id="tablaModelo">'.$mensaje.'</table>'; <file_sep>/ajax/updateEscribanos.ajax.php <?php require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; class AjaxUpdateEscribanos{ /*============================================= ACTUALIZAR PRODUCTOS =============================================*/ public function ajaxActualizarEscribanos(){ #ELIMINAR PRODUCTOS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('escribanos'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $orden = "id"; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor, $orden); $cantidadEscribanos = count($escribanos); $cant=0; foreach ($escribanos as $key => $value) { # code... $tabla = "escribanos"; $datos =array("id"=>$value["id"], "nombre"=>strtoupper($value["nombre"]), "documento"=>$value["documento"], "id_tipo_iva"=>$value["id_tipo_iva"], "tipo"=>$value["tipo"], "facturacion"=>$value["facturacion"], "tipo_factura"=>$value["tipo_factura"], "cuit"=>$value["cuit"], "direccion"=>strtoupper($value["direccion"]), "localidad"=>strtoupper($value["localidad"]), "telefono"=>$value["telefono"], "email"=>strtoupper($value["email"]), "id_categoria"=>$value["id_categoria"], "id_escribano_relacionado"=>$value["id_escribano_relacionado"], "id_osde"=>$value["id_osde"], "ultimolibrocomprado"=>strtoupper($value["ultimolibrocomprado"]), "ultimolibrodevuelto"=>strtoupper($value["ultimolibrodevuelto"]), "apellido_ws"=>$value["apellido_ws"], "nombre_ws"=>$value["nombre_ws"], "matricula_ws"=>$value["matricula_ws"], "inhabilitado"=>$value["inhabilitado"]); $cant ++; #registramos los productos $respuesta = ModeloEnlace::mdlIngresarEscribano($tabla, $datos); } /*=========================================== = CONSULTAR SI EXISTEN MODIFICACIONES = ===========================================*/ $tabla ="modificaciones"; $datos = array("nombre"=>"escribanos","fecha"=>date("Y-m-d")); $modificaciones = ModeloEnlace::mdlConsultarModificaciones($tabla,$datos); if(!$modificaciones[0]>=1){ //SI NO EXISTE CREO UNA NUEVA FILA $datos = array("nombre"=>"escribanos","fecha"=>date("Y-m-d")); ControladorEnlace::ctrSubirModificaciones($datos); }else{ //SI EXISTE ACTUALIZO A CERO $datos = array("nombre"=>"escribanos","fecha"=>date("Y-m-d")); ControladorEnlace::ctrUpdateModificaciones($datos); } } /*============================================= MOSTRAR ESCRIBANOS =============================================*/ public function ajaxMostrarEscribanos(){ echo '<script>$(".tablaMostrarAjax").DataTable({ "lengthMenu": [[5, 10, 25], [5, 10, 25]], dom: "lBfrtip",buttons: [ { extend: "colvis", columns: ":not(:first-child)", } ], "language": { "sProcessing": "Procesando...", "sLengthMenu": "Mostrar _MENU_ registros", "sZeroRecords": "No se encontraron resultados", "sEmptyTable": "Ningún dato disponible en esta tabla", "sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_", "sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0", "sInfoFiltered": "(filtrado de un total de _MAX_ registros)", "sInfoPostFix": "", "sSearch": "Buscar:", "sUrl": "", "sInfoThousands": ",", "sLoadingRecords": "Cargando...", "oPaginate": { "sFirst": "Primero", "sLast": "Último", "sNext": "Siguiente", "sPrevious": "Anterior" }, "oAria": { "sSortAscending": ": Activar para ordenar la columna de manera ascendente", "sSortDescending": ": Activar para ordenar la columna de manera descendente" } } })</script>'; echo '<table class="table table-bordered table-striped dt-responsive tablaMostrarAjax" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Telefono</th> <th>Estado</th> <th>WService</th> </tr> </thead> <tbody>'; $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanos as $key => $value) { if ($value["inhabilitado"] ==0){$estado=1;$btnEstado ='<i class="fa fa-info-circle" aria-hidden="true" style="color:green;" ></i>';}//habilitado if ($value["inhabilitado"] ==1){$estado=0;$btnEstado ='<i class="fa fa-info-circle" aria-hidden="true" style="color:red;" ></i>';}//inhabilitado if ($value["inhabilitado"] ==2){$estado=2;}//no consultable $data = '{"nombre":"'.$value["nombre_ws"].'","apellido":"'.$value["apellido_ws"].'","matricula":"'.$value["matricula_ws"].'","email":"'.strtolower($value["email"]).'","telefono":"'.$value["telefono"].'","inhabilitado":"'.$estado.'"}'; $datos = str_replace(' ','',$data); $datos = str_replace('{','',$datos); $datos = str_replace('}','',$datos); $datos = str_replace('"','',$datos); $datos = str_replace(',','\n',$datos); echo ' <tr> <td>'.($key+1).'</td> <td class="text-uppercase">'.$value["nombre"].'</td> <td class="text-uppercase">'.$value["telefono"].'</td>'; if($value["inhabilitado"]==0){ echo '<td class="text-uppercase">HABILITADO</td>'; }else{ echo '<td class="text-uppercase">INHABILITADO</td>'; } if ($value["inhabilitado"] ==0){ echo '<td class="text-uppercase"><button class="btn btn-success" onclick=alert("'.$datos.'") >Estado WService</button></td>'; }else{ echo '<td class="text-uppercase"><button class="btn btn-danger" onclick=alert("'.$datos.'") >Estado WService</button></td>'; } echo '</tr>'; } echo' </tbody> </table>'; } } /*============================================= EDITAR CATEGORÍA =============================================*/ if(isset($_POST["upEscribanos"])){ $productos = new AjaxUpdateEscribanos(); $productos -> ajaxActualizarEscribanos(); } if(isset($_POST["mostrarEscribanos"])){ $productos = new AjaxUpdateEscribanos(); $productos -> ajaxMostrarEscribanos(); } <file_sep>/controladores/cuotas.controlador - copia.php <?php class ControladorCuotas{ /*============================================= MOSTRAR CUOTAS =============================================*/ static public function ctrMostrarCuotas($item, $valor){ $tabla = "cuotas"; $respuesta = ModeloCuotas::mdlMostrarCuotas($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarCuotasEscribano($item, $valor){ $tabla = "cuotas"; $respuesta = ModeloCuotas::mdlMostrarCuotasEscribano($tabla, $item, $valor); return $respuesta; } /*============================================= EDITAR CUOTAS =============================================*/ static public function ctrEditarCuota(){ if(isset($_POST["idVenta"])){ $listaProductos = json_decode($_POST["listaProductos"], true); $items=Array();//del afip foreach ($listaProductos as $key => $value) { $items[$key]=array('codigo' => $value["id"],'descripcion' => $value["descripcion"],'cantidad' => $value["cantidad"],'codigoUnidadMedida'=>7,'precioUnitario'=>$value["precio"],'importeItem'=>$value["total"],'impBonif'=>0); } $codigoFactura=1; include('../extensiones/afip/afip.php'); /*============================================= GUARDAR LA VENTA =============================================*/ $result = $afip->emitirComprobante($regcomp); //$regcomp debe tener la estructura esperada (ver a continuación de la wiki) if ($result["code"] === Wsfev1::RESULT_OK) { $tablaClientes = "escribanos"; $item = "id"; $valor = $_POST["seleccionarCliente"]; $traerCliente = ModeloEscribanos::mdlMostrarEscribanos($tablaClientes, $item, $valor); if($traerCliente['facturacion']=="CUIT"){ $nombre=$traerCliente['nombre']; $documento=$traerCliente['cuit']; }else{ $nombre=$traerCliente['nombre']; $documento=$traerCliente['documento']; } // $nombre=$_POST['seleccionarCliente']; // $documento=$_POST['documentoCliente']; // $tabla=$_POST['tipoCliente']; /*============================================= FORMATEO LOS DATOS =============================================*/ $fecha = date("Y-m-d"); if ($_POST["listaMetodoPago"]=="CTA.CORRIENTE"){ $adeuda=$_POST["totalVenta"]; $fechapago="0000-00-00"; }else{ $adeuda=0; $fechapago = $fecha; } $cantCabeza = strlen($PTOVTA); switch ($cantCabeza) { case 1: $ptoVenta="000".$PTOVTA; break; case 2: $ptoVenta="00".$PTOVTA; break; case 3: $ptoVenta="0".$PTOVTA; break; } $codigoFactura = $ptoVenta .'-'. $ultimoComprobante; $tabla = "ventas"; $fechaCaeDia = substr($result["fechaVencimientoCAE"],-2); $fechaCaeMes = substr($result["fechaVencimientoCAE"],4,-2); $fechaCaeAno = substr($result["fechaVencimientoCAE"],0,4); $afip=1; //La facturacion electronica finalizo correctamente $datos = array("fecha"=>date('Y-m-d'), "tipo"=>$_POST['tipoCuota'], "codigo"=>$codigoFactura, "id_cliente"=>$_POST['seleccionarCliente'], "nombre"=>$nombre, "documento"=>$documento, "tabla"=>$_POST['tipoCliente'], "id_vendedor"=>1, "productos"=>$_POST['listaProductos'], "impuesto"=>0, "neto"=>0, "total"=>$_POST["totalVenta"], "adeuda"=>'0', "obs"=>'', "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST['nuevaReferencia'], "fechapago"=>$fechapago, "cae"=>$result["cae"], "fecha_cae"=>$fechaCaeDia.'/'.$fechaCaeMes.'/'.$fechaCaeAno); $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); $eliminarCuota = ModeloCuotas::mdlEliminarVenta("cuotas", $_POST["idVenta"]); } else{ echo $result["code"]; } if(isset($respuesta)){ if($respuesta == "ok"){ if($afip==1){ /*============================================= AGREGAR EL NUMERO DE COMPROBANTE =============================================*/ $tabla = "comprobantes"; $datos = $ult; ModeloVentas::mdlAgregarNroComprobante($tabla, $datos); $nroComprobante = substr($codigoFactura,8); //ULTIMO NUMERO DE COMPROBANTE $item = "nombre"; $valor = "FC"; $registro = ControladorVentas::ctrUltimoComprobante($item, $valor); } if ($_POST["listaMetodoPago"]!='CTA.CORRIENTE'){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVenta"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVenta"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVenta"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVenta"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); } } if($afip==1){ echo 'FE'; } } } } static public function ctrContarCuotayOsde($item, $valor){ $tabla = "cuotas"; $respuesta = ModeloCuotas::mdlContarCuotayOsde($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarGeneracion($tipo){ $tabla = "generacion"; # code... $mimes=date("m")-1; $mes=ControladorVentas::ctrNombreMes($mimes); $datos = array("tipo"=>$tipo, "mes"=>$mes, "anio"=>date("Y")); $respuesta = ModeloCuotas::mdlChequearGeneracion($tabla, $datos); return $respuesta; } static public function ctrChequearGeneracion($tipo){ /* $tabla = "generacion"; # code... $mimes=date("m")-1; $mes=ControladorVentas::ctrNombreMes($mimes); $datos = array("tipo"=>$tipo, "mes"=>$mes, "anio"=>date("Y")); $respuesta = ModeloCuotas::mdlChequearGeneracion($tabla, $datos); if(empty($respuesta)){ if($tipo=="CUOTA"){ $GenerarCuota = ControladorCuotas::ctrgeneraCuota(); } if($tipo=="OSDE"){ $GenerarCuota = ControladorCuotas::ctrGeneraOsde(); } }*/ /*============================================= BUSCO UNA COINCIDENCIA EN GENERACIÓN =============================================*/ $tabla = "generacion"; $mimes=date("m")-1; // echo '<pre>'; print_r($mimes); echo '</pre>'; if($mimes==0){ $mes=ControladorVentas::ctrNombreMes(12); $anio = date("Y")-1; }else{ $anio = date("Y"); $mes=ControladorVentas::ctrNombreMes($mimes); } $datos = array("tipo"=>$tipo, "mes"=>$mes, "anio"=>$anio); $respuesta = ModeloCuotas::mdlChequearGeneracion($tabla, $datos); if(empty($respuesta)){ if($tipo=="CUOTA"){ // echo "entra en cuota"; $GenerarCuota = ControladorCuotas::ctrgeneraCuota(); } if($tipo=="OSDE"){ // echo "entra en osde"; $GenerarCuota = ControladorCuotas::ctrGeneraOsde(); } } } /*============================================= SE GENERAN LAS FACTURAS AUTOMATICAMENTE =============================================*/ static public function ctrgeneraCuota(){ $fechaactual = date('Y-m-d'); // 2016-12-29 $nuevafecha = strtotime ('-1 year' , strtotime($fechaactual)); //Se añade un año mas $nuevafecha = date ('Y-m-d',$nuevafecha); $nuevafecha = explode("-", $nuevafecha ); $nuevafecha=$nuevafecha[0]; if(date("m")=='01'||date("m")=='1'){ $anio=$nuevafecha; }else{ $anio=date("Y"); } //PRIMERO CONTAMOS CUANTOS ESCRIBANOS EXISTEN $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); $cantidadCuotas = 0; foreach ($escribanos as $key => $value) { # code... $mimes=date("m")-1; $mes=ControladorVentas::ctrNombreMes($mimes); $item = "id"; $valor = $value['id_categoria']; $categoria = ControladorCategorias::ctrMostrarCategorias($item, $valor); $importe = $categoria["importe"]; $productos = '[{"id":"20","descripcion":"CUOTA MENSUAL '.strtoupper($mes).'/'.$anio.'","idnrocomprobante":"100","cantventaproducto":"1","folio1":"1","folio2":"1","cantidad":"1","precio":"'.$categoria["importe"].'","total":"'.$categoria["importe"].'"}]'; $tabla = "cuotas"; $datos = array("fecha"=>date('Y-m-d'), "tipo"=>'CU', "id_cliente"=>$value['id'], "nombre"=>$value['nombre'], "documento"=>$value['cuit'], "productos"=>$productos, "total"=>$importe); $respuesta = ModeloCuotas::mdlIngresarCuota($tabla, $datos); $cantidadCuotas++; } $tabla ='generacion'; $datos = array("fecha"=>date('Y-m-d'), "nombre"=>'CUOTA', "mes"=>strtoupper($mes), "anio"=>$anio, "cantidad"=>$cantidadCuotas); ModeloCuotas::mdlIngresarGeneracionCuota($tabla, $datos); } /*============================================= SE GENERAN LOS REINTEGROS OSDE =============================================*/ static public function ctrGeneraOsde(){ $fechaactual = date('Y-m-d'); // 2016-12-29 $nuevafecha = strtotime ('-1 year' , strtotime($fechaactual)); //Se añade un año mas $nuevafecha = date ('Y-m-d',$nuevafecha); $nuevafecha = explode("-", $nuevafecha ); $nuevafecha=$nuevafecha[0]; if(date("m")=='01'||date("m")=='1'){ $anio=$nuevafecha; }else{ $anio=date("Y"); } $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); $cantidadCuotas = 0; foreach ($escribanos as $key => $value) { # code... $mimes=date("m")-1; $mes=ControladorVentas::ctrNombreMes($mimes); if(date("m")-1==0){ $anio =date("Y")-1; } if($value['id_osde']!=0){ $item = "id"; $valor = $value['id_osde']; $osde = ControladorOsde::ctrMostrarOsde($item, $valor); $productos = '[{"id":"22","descripcion":"REINTEGRO OSDE '.strtoupper($mes).'/'.$anio.'","idnrocomprobante":"12000","cantventaproducto":"1","folio1":"1","folio2":"1","cantidad":"1","precio":"'.$osde["importe"].'","total":"'.$osde["importe"].'"}]'; $tabla = "cuotas"; $datos = array("fecha"=>$fechaactual, "tipo"=>'RE', "id_cliente"=>$value['id'], "nombre"=>$value['nombre'], "documento"=>$value['cuit'], "productos"=>$productos, "total"=>$osde["importe"] ); $respuesta = ModeloCuotas::mdlIngresarCuota($tabla, $datos); $cantidadCuotas++; } } $tabla ='generacion'; $datos = array("fecha"=>date('Y-m-d'), "nombre"=>'OSDE', "mes"=>strtoupper($mes), "anio"=>$anio, "cantidad"=>$cantidadCuotas); ModeloCuotas::mdlIngresarGeneracionCuota($tabla, $datos); } // static public function ctrEscribanosConDeuda($item, $valor,$tipo){ // $tabla = "cuotas"; // $respuesta = ModeloCuotas::mdlEscribanosConDeuda($tabla, $item, $valor); // if ($tipo=='contar'){ // return count($respuesta); // }else{ // return $respuesta; // } // } static public function ctrEscribanosDeuda($item, $valor){ $tabla = "cuotas"; $respuesta = ModeloCuotas::mdlEscribanosDeuda($tabla, $item, $valor); return $respuesta; } /*============================================= ACTUALIZAR INHABILITADO =============================================*/ static public function ctrEscribanosInhabilitar($valor){ $tabla ="escribanos"; $respuesta = ModeloCuotas::mdlEscribanosInhabilitar($tabla, $valor); } /*============================================= ACTUALIZAR HABILITADO =============================================*/ static public function ctrHabilitarUnEscribano($valor){ $tabla ="escribanos"; $respuesta = ModeloCuotas::mdlHabilitarUnEscribano($tabla, $valor); } /*============================================= ACTUALIZAR HABILITADO =============================================*/ static public function ctrEscribanosHabilitar(){ $tabla ="escribanos"; $respuesta = ModeloCuotas::mdlEscribanosHabilitar($tabla); } /*============================================= DESCARGAR EXCEL =============================================*/ public function ctrDescargarCuotas(){ if(isset($_GET["descargar_cuota"])){ $tabla = "cuotas"; $cuotas = ModeloCuotas::mdlMostrarCuotas($tabla, null, null); /*============================================= CREAMOS EL ARCHIVO DE EXCEL =============================================*/ $Name = $tabla.'.xls'; header('Expires: 0'); header('Cache-control: private'); header("Content-type: application/vnd.ms-excel"); // Archivo de Excel header("Cache-Control: cache, must-revalidate"); header('Content-Description: File Transfer'); header('Last-Modified: '.date('D, d M Y H:i:s')); header("Pragma: public"); header('Content-Disposition:; filename="'.$Name.'"'); header("Content-Transfer-Encoding: binary"); echo utf8_decode("<table border='0'> <tr> <td style='font-weight:bold; border:1px solid #eee;'>FECHA</td> <td style='font-weight:bold; border:1px solid #eee;'>TIPO</td> <td style='font-weight:bold; border:1px solid #eee;'>NOMBRE</td> <td style='font-weight:bold; border:1px solid #eee;'>DOCUMENTO</td> <td style='font-weight:bold; border:1px solid #eee;'>PRODUCTOS</td> <td style='font-weight:bold; border:1px solid #eee;'>TOTAL</td> </tr>"); foreach ($cuotas as $row => $item){ echo utf8_decode("<tr> <td style='border:1px solid #eee;'>".$item["fecha"]."</td> <td style='border:1px solid #eee;'>".$item["tipo"]."</td> <td style='border:1px solid #eee;'>".$item["nombre"]."</td> <td style='border:1px solid #eee;'>".$item["documento"]."</td> "); $productos = json_decode($item["productos"], true); echo utf8_decode("<td style='border:1px solid #eee;'>"); foreach ($productos as $key => $valueProductos) { echo utf8_decode($valueProductos["descripcion"]." ".$valueProductos["folio1"]."-".$valueProductos["folio2"]."<br>"); } echo utf8_decode("</td> <td style='border:1px solid #eee;'>$ ".number_format($item["total"],2)."</td> </tr>"); } echo "</table>"; } } } <file_sep>/vistas/js/libros.js /*============================================= EDITAR LIBRO =============================================*/ $(".tablas").on("click", ".btnEditarLibro", function(){ var idEscribano = $(this).attr("idEscribano"); console.log("idEscribano", idEscribano); var datos = new FormData(); datos.append("idEscribano", idEscribano); $.ajax({ url: "ajax/escribanos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success: function(respuesta){ console.log("respuesta", respuesta); $("#editarIdEscribano").val(respuesta["id"]); $("#editarNombreEscribano").val(respuesta["nombre"]); $("#editarUltimoLibroComprado").val(respuesta["ultimolibrocomprado"]); $("#editarUltimoLibroDevuelto").val(respuesta["ultimolibrodevuelto"]); } }) }) /*============================================= HACER FOCO EN EL NOMBRE DEL COMPROBANTE =============================================*/ $('#modalEditarLibros').on('shown.bs.modal', function () { $('#editarUltimoLibroComprado').focus(); $('#editarUltimoLibroComprado').select(); }) <file_sep>/ajax/datatable-ventas.ajax.php <?php require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class TablaProductos{ /*============================================= MOSTRAR LA TABLA DE PRODUCTO =============================================*/ public function mostrarTabla(){ if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } $respuesta = ControladorVentas::ctrRangoFechasVentas($fechaInicial, $fechaFinal); echo '{ "data": ['; for($i = 0; $i < count($productos)-1; $i++){ echo '[ "'.($i+1).'", "'.$respuesta[$i]["fecha"].'", "'.$respuesta[$i]["codigo"].'", "'.$respuesta[$i]["nrofc"].'", "'.$respuesta[$i]["id_cliente"].'", "'.$respuesta[$i]["metodo_pago"].'", "'.$respuesta[$i]["detalle"].'", "'.$respuesta[$i]["total"].'", "'.$respuesta[$i]["adeuda"].'", "'.$respuesta[$i]["observaciones"].'" ],'; } echo'[ "'.count($respuesta).'", "'.$respuesta[count($respuesta)-1]["fecha"].'", "'.$respuesta[count($respuesta)-1]["codigo"].'", "'.$respuesta[count($respuesta)-1]["nrofc"].'", "'.$respuesta[count($respuesta)-1]["id_cliente"].'", "'.$respuesta[count($respuesta)-1]["metodo_pago"].'", "'.$respuesta[count($respuesta)-1]["detalle"].'", "'.$respuesta[count($respuesta)-1]["total"].'", "'.$respuesta[count($respuesta)-1]["adeuda"].'", "'.$respuesta[count($respuesta)-1]["observaciones"].'" ] ] }'; } } /*============================================= ACTIVAR TABLA DE PRODUCTOS =============================================*/ $activar = new TablaProductos(); $activar -> mostrarTabla();<file_sep>/vistas/modulos/escribanos.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar escribanos </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar escribanos</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <button class="btn btn-primary" data-toggle="modal" data-target="#modalAgregarEscribano"> Agregar escribano </button> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Direccion</th> <th>Localidad</th> <th>Telefono</th> <th>Documento</th> <th>T.Iva</th> <th>Cuit</th> <th>Caracter</th> <th>Osde</th> <th>Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanos as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["nombre"].'</td> <td>'.$value["direccion"].'</td> <td>'.$value["localidad"].'</td> <td>'.$value["telefono"].'</td> <td>'.$value["documento"].'</td>'; $item = "id"; $valor = $value["id_tipo_iva"]; $tipoIva = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); echo '<td>'.$tipoIva["nombre"].'</td>'; echo '<td>'.$value["cuit"].'</td>'; $item = "id"; $valor = $value["id_categoria"]; $categorias = ControladorCategorias::ctrMostrarCategorias($item, $valor); echo '<td>'.$categorias["categoria"].'</td>'; $item = "id"; $valor = $value["id_osde"]; $osde = ControladorOsde::ctrMostrarOsde($item, $valor); if($osde){ echo '<td>'.$osde["nombre"].' - $'.$osde["importe"].'</td>'; }else{ echo '<td>Sin Osde</td>'; } // if($osde["importe"]==0){ // echo '<td>Sin Osde</td>'; // }else{ // echo '<td>'.$osde["nombre"].' - $'.$osde["importe"].'</td>';} echo '<td> <div class="btn-group"> <button class="btn btn-warning btnEditarEscribano" data-toggle="modal" data-target="#modalEditarEscribano" idEscribano="'.$value["id"].'"><i class="fa fa-pencil"></i></button>'; // if($_SESSION["perfil"] == "Administrador"){ echo '<button class="btn btn-danger btnEliminarEscribano" idEscribano="'.$value["id"].'"><i class="fa fa-times"></i></button>'; // } echo '</div> </td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <!--===================================== AGREGAR ESCRIBANO ======================================--> <div id="modalAgregarEscribano" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar escribano</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="nuevoEscribano" id="nuevoEscribano" placeholder="Ingresar nombre" required> </div> </div> <!-- ENTRADA PARA EL DOCUMENTO ID --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="number" min="0" class="form-control input-lg" name="nuevoDocumento" placeholder="Ingresar documento" required> </div> </div> <!-- ENTRADA CATEGORIA DE ESCRIBANO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="nuevaIdIva"> <option value="">SELECCIONAR TIPO IVA</option> <?php $item = null; $valor = null; $tipoIva = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); foreach ($tipoIva as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA EL CUIT --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="text" class="form-control input-lg" name="nuevoCuit" placeholder="Ingresar Cuit" data-inputmask="'mask':'99-99999999-9'" data-mask required> </div> </div> <!-- ENTRADA PARA LA DIRECCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="nuevaDireccion" placeholder="Ingresar dirección" required> </div> </div> <!-- ENTRADA PARA LA LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="nuevaLocalidad" placeholder="Ingresar localidad" required> </div> </div> <div class="form-group"> <div class="input-group"> <!-- ENTRADA PARA EL TELÉFONO --> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input type="text" class="form-control input-lg" name="nuevoTelefono" placeholder="Ingresar teléfono" data-inputmask="'mask':'(999) 999-9999'" data-mask required> </div> </div> <!-- ENTRADA PARA EL EMAIL --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input type="email" class="form-control input-lg" name="nuevoEmail" placeholder="Ingresar email" required> </div> </div> <!-- ENTRADA CATEGORIA DE ESCRIBANO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="nuevaCategoriaEscribano"> <option value="">SELECCIONAR CATEGORIA ESCRIBANO</option> <?php $item = null; $valor = null; $categorias = ControladorCategorias::ctrMostrarCategorias($item, $valor); foreach ($categorias as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['categoria'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA ESCRIBANO RELACIONADO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="nuevoEscribanoRelacionado"> <option value="">SELECCIONAR ESCRIBANO RELACIONADO</option> <?php echo '<option value="0">SIN RELACION</option>'; $item = null; $valor = null; $escribanosRelacionado = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanosRelacionado as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA CATEGORIA OSDE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="nuevoCategoriaOsde"> <option value="">SELECCIONAR OSDE</option> <?php echo '<option value="0">SIN OSDE</option>'; $item = null; $valor = null; $osde = ControladorOsde::ctrMostrarOsde($item, $valor); foreach ($osde as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].' - $ '.$value['importe'].'</option>'; } ?> </select> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar ESCRIBANO</button> </div> </form> <?php $crearEscribano = new ControladorEscribanos(); $crearEscribano -> ctrCrearEscribano(); ?> </div> </div> </div> <!--===================================== AGREGAR ESCRIBANO ======================================--> <div id="modalEditarEscribano" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar escribano</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="editarEscribano" id="editarEscribano" placeholder="Ingresar nombre" required> <input type="hidden" id="idEscribano" name="idEscribano"> </div> </div> <!-- ENTRADA PARA EL DOCUMENTO ID --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="number" min="0" class="form-control input-lg" name="editarDocumento" id="editarDocumento" placeholder="Ingresar documento" required> </div> </div> <!-- ENTRADA CATEGORIA OSDE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="editarTipoIva" id="editarTipoIva"> <option value="">SELECCIONAR TIPO IVA</option> <?php $item = null; $valor = null; $tipoIva = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); foreach ($tipoIva as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA EL CUIT --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-key"></i></span> <input type="text" class="form-control input-lg" name="editarCuit" id="editarCuit" placeholder="Ingresar Cuit" data-inputmask="'mask':'99-99999999-9'" data-mask required> </div> </div> <!-- ENTRADA PARA LA DIRECCIÓN --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="editarDireccion" id="editarDireccion" placeholder="Ingresar dirección" required> </div> </div> <!-- ENTRADA PARA LA LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="editarLocalidad" id="editarLocalidad" placeholder="Ingresar localidad" required> </div> </div> <div class="form-group"> <div class="input-group"> <!-- ENTRADA PARA EL TELÉFONO --> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input type="text" class="form-control input-lg" name="editarTelefono" id="editarTelefono" placeholder="Ingresar teléfono" data-inputmask="'mask':'(999) 999-9999'" data-mask required> </div> </div> <!-- ENTRADA PARA EL EMAIL --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input type="email" class="form-control input-lg" name="editarEmail" id="editarEmail" placeholder="Ingresar email" required> </div> </div> <!-- ENTRADA CATEGORIA DE ESCRIBANO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="editarCategoriaEscribano" id="editarCategoriaEscribano"> <option value="">SELECCIONAR CATEGORIA ESCRIBANO</option> <?php $item = null; $valor = null; $categorias = ControladorCategorias::ctrMostrarCategorias($item, $valor); foreach ($categorias as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['categoria'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA ESCRIBANO RELACIONADO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="editarEscribanoRelacionado" id="editarEscribanoRelacionado"> <option value="">SELECCIONAR ESCRIBANO RELACIONADO</option> <?php echo '<option value="0">SIN RELACION</option>'; $item = null; $valor = null; $escribanosRelacionado = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($escribanosRelacionado as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].'</option>'; } ?> </select> </div> </div> <!-- ENTRADA CATEGORIA OSDE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-info"></i></span> <select class="form-control input-lg" name="editarCategoriaOsde" id="editarCategoriaOsde"> <option value="">SELECCIONAR OSDE</option> <?php echo '<option value="0">SIN OSDE</option>'; $item = null; $valor = null; $osde = ControladorOsde::ctrMostrarOsde($item, $valor); foreach ($osde as $key => $value) { # code... echo '<option value="'.$value['id'].'">'.$value['nombre'].' - $ '.$value['importe'].'</option>'; } ?> </select> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Salir</button> <button type="submit" class="btn btn-primary">Guardar ESCRIBANO</button> </div> </form> <?php $editarEscribano = new ControladorEscribanos(); $editarEscribano -> ctrEditarEscribano(); ?> </div> </div> </div> <?php $eliminarEscribano = new ControladorEscribanos(); $eliminarEscribano -> ctrEliminarEscribano(); ?> <file_sep>/modelos/programaviejo.modelo.php <?php require_once "conexion.php"; class ModeloProgramaViejo{ static public function mdlEliminarEscribanos(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `escribanos`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlEscribanos($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id,nombre,direccion,localidad,telefono,documento,cuit,email,id_categoria,id_escribano_relacionado,id_osde,ultimolibrocomprado,ultimolibrodevuelto) VALUES (:id,:nombre,:direccion,:localidad,:telefono,:documento,:cuit,:email,:id_categoria,:id_escribano_relacionado,:id_osde,:ultimolibrocomprado ,:ultimolibrodevuelto)"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos['direccion'], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos['localidad'], PDO::PARAM_STR); $stmt->bindParam(":telefono", $datos['telefono'], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos['documento'], PDO::PARAM_STR); $stmt->bindParam(":cuit", $datos['cuit'], PDO::PARAM_STR); $stmt->bindParam(":email", $datos['email'], PDO::PARAM_STR); $stmt->bindParam(":id_categoria", $datos['id_categoria'], PDO::PARAM_INT); $stmt->bindParam(":id_escribano_relacionado", $datos['id_escribano_relacionado'], PDO::PARAM_INT); $stmt->bindParam(":id_osde", $datos['id_osde'], PDO::PARAM_INT); $stmt->bindParam(":ultimolibrocomprado", $datos['ultimolibrocomprado'], PDO::PARAM_INT); $stmt->bindParam(":ultimolibrodevuelto", $datos['ultimolibrodevuelto'], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEliminarComprobantes(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `comprobantes`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlComprobantes($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(id,nombre,cabezacomprobante,numero) VALUES (:id,:nombre,:cabezacomprobante,:numero)"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":cabezacomprobante", $datos['cabezacomprobante'], PDO::PARAM_STR); $stmt->bindParam(":numero", $datos['numero'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEliminarOsde(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `osde`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlOsde($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(id,nombre,importe) VALUES (:id,:nombre,:importe)"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":importe", $datos['importe'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEliminarRubros(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `rubros`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlRubros($tabla, $datos){ $ssql ="INSERT INTO $tabla(id,nombre,movimiento,mensual,obs,activo,obsdel) VALUES (".$datos['id'].",'".$datos['nombre']."',".$datos['movimiento'].",'".$datos['mensual']."','".$datos['obs']."',".$datos['activo'].",'".$datos['obsdel']."')"; // echo $ssql; $stmt = Conexion::conectar()->prepare($ssql); // $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); // $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); // $stmt->bindParam(":movimiento", $datos['movimiento'], PDO::PARAM_INT); // $stmt->bindParam(":mensual", $datos['mensual'], PDO::PARAM_INT); // $stmt->bindParam(":obs", $datos['obs'], PDO::PARAM_STR); // $stmt->bindParam(":activo", $datos['activo'], PDO::PARAM_INT); // $stmt->bindParam(":obsdel", $datos['obsdel'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEliminarProductos(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `productos`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlProductos($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id,nombre,descripcion,codigo,nrocomprobante,cantventa,id_rubro,cantminima,cuotas,importe,ultimonrocompra) VALUES (:id,:nombre,:descripcion,:codigo,:nrocomprobante,:cantventa,:idrubro,:cantminima,:cuotas,:importe,:ultimonrocompra)"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":descripcion", $datos['descripcion'], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos['codigo'], PDO::PARAM_STR); $stmt->bindParam(":nrocomprobante", $datos['nrocomprobante'], PDO::PARAM_INT); $stmt->bindParam(":cantventa", $datos['cantventa'], PDO::PARAM_INT); $stmt->bindParam(":idrubro", $datos['idrubro'], PDO::PARAM_INT); $stmt->bindParam(":cantminima", $datos['cantminima'], PDO::PARAM_INT); $stmt->bindParam(":cuotas", $datos['cuotas'], PDO::PARAM_INT); $stmt->bindParam(":importe", $datos['importe'], PDO::PARAM_STR); $stmt->bindParam(":ultimonrocompra", $datos['ultimonrocompra'], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEliminarVentas(){ $stmt = Conexion::conectar()->prepare("DELETE FROM `ventas`"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlVentas($tabla, $datos){ $stmt = Conexion::conectar()->prepare("ALTER TABLE ventas AUTO_INCREMENT = 1"); $stmt->execute(); $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,tipo,id_cliente,codigo,id_vendedor,productos,total,adeuda,metodo_pago,referenciapago) VALUES (:fecha,:tipo,:idescribano,1,1,:productos,:total,:adeuda,'CTA.CORRIENTE','CTA.CORRIENTE')"); // $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos['tipo'], PDO::PARAM_STR); $stmt->bindParam(":idescribano", $datos['idescribano'], PDO::PARAM_STR); $stmt->bindParam(":productos", $datos['productos'], PDO::PARAM_STR); // $stmt->bindParam(":nrofc", $datos['nrofc'], PDO::PARAM_STR); $stmt->bindParam(":total", $datos['adeuda'], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos['adeuda'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/extensiones/fpdf/pdf/factura.php <?php session_start(); include('../fpdf.php'); require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/parametros.controlador.php"; require_once "../../../modelos/parametros.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; class PDF_JavaScript extends FPDF { protected $javascript; protected $n_js; function IncludeJS($script, $isUTF8=false) { if(!$isUTF8) $script=utf8_encode($script); $this->javascript=$script; } function _putjavascript() { $this->_newobj(); $this->n_js=$this->n; $this->_put('<<'); $this->_put('/Names [(EmbeddedJS) '.($this->n+1).' 0 R]'); $this->_put('>>'); $this->_put('endobj'); $this->_newobj(); $this->_put('<<'); $this->_put('/S /JavaScript'); $this->_put('/JS '.$this->_textstring($this->javascript)); $this->_put('>>'); $this->_put('endobj'); } function _putresources() { parent::_putresources(); if (!empty($this->javascript)) { $this->_putjavascript(); } } function _putcatalog() { parent::_putcatalog(); if (!empty($this->javascript)) { $this->_put('/Names <</JavaScript '.($this->n_js).' 0 R>>'); } } } class PDF_AutoPrint extends PDF_JavaScript { function AutoPrint($printer='') { // Open the print dialog if($printer) { $printer = str_replace('\\', '\\\\', $printer); $script = "var pp = getPrintParams();"; $script .= "pp.interactive = pp.constants.interactionLevel.full;"; $script .= "pp.printerName = '$printer'"; $script .= "print(pp);"; } else $script = 'print(true);'; $this->IncludeJS($script); } } function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } require_once('../../../modelos/conexion.php'); // PARAMETROS $item= "id"; $valor = 1; $parametros = ControladorParametros::ctrMostrarParametros($item,$valor); // VENTA $item= "codigo"; $valor = $_GET['codigo']; $ventas = ControladorVentas::ctrMostrarVentas($item,$valor); // ESCRIBANO $item= "id"; $valor = $ventas['id_cliente']; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item,$valor); $fechaNueva = explode("-", $ventas['fecha']); $anio = substr($fechaNueva[0], -2); //$pdf = new FPDF('P','mm','A4'); $pdf = new PDF_AutoPrint($parametros['formatopagina1'],$parametros['formatopagina2'],$parametros['formatopagina3']); $pdf->AddPage(); //$pdf -> SetFont('Arial', 'I', 8); // set the font $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], $parametros['formatofuente3']); // set the font //ENCABEZADO FACTURA 1 //primera linea fecha //$pdf -> SetY(25); // set the cursor at Y position 5 $pdf -> SetY($parametros['fecha1posY']); // set the cursor at Y position 5 //$pdf -> SetX(170); $pdf -> SetX($parametros['fecha1posXdia']); $pdf->Cell(0,0,$fechaNueva[2]); //$pdf -> SetX(180); $pdf -> SetX($parametros['fecha1posXmes']); $pdf->Cell(0,0,$fechaNueva[1]); //$pdf -> SetX(192); $pdf -> SetX($parametros['fecha1posXanio']); $pdf->Cell(0,0,$anio); //Carga cliente y condiciones //$pdf -> SetY(40); // set the cursor at Y position 5 //$pdf -> SetX(50); $pdf -> SetY($parametros['formatocabecera1posY1']); // set the cursor at Y position 5 $pdf -> SetX($parametros['formatocabecera1posX1']); //convertir en castellano ÑÑÑ //$str = iconv('UTF-8', 'windows-1252', $rsCta['nombreescribano']); $pdf->Cell(0,0,convertirLetras($escribanos['nombre'])); //$pdf -> SetY(44); //$pdf -> SetX(50); $pdf -> SetY($parametros['formatocabecera1posY2']); $pdf -> SetX($parametros['formatocabecera1posX2']); $pdf->Cell(0,0,'s/iva'); //$pdf -> SetY(50); //$pdf -> SetX(70); $pdf -> SetY($parametros['formatocabecera1posY3']); $pdf -> SetX($parametros['formatocabecera1posX3']); if($ventas['metodo_pago']==$ventas['referenciapago']){ $metodoDePago = $ventas['metodo_pago']; }else{ $metodoDePago = $ventas['metodo_pago']==$ventas['referenciapago']; } $pdf->Cell(0,0,$metodoDePago); //Items $renglon1=$parametros['formatoitem1posY']; $espaciorenglon=0; $veces=0; $productosVentas = json_decode($ventas["productos"], true); foreach ($productosVentas as $key => $rsCtaART) { $pdf -> SetY($renglon1+($espaciorenglon*$veces)); // set the cursor at Y position 5 $pdf -> SetX($parametros['formatoitem1posXcant']); $pdf->Cell(0,0,$rsCtaART['cantidad']); //$pdf -> SetX(53); $pdf -> SetX($parametros['formatoitem1posXart']); $miItem=convertirLetras($rsCtaART['descripcion']); $cantidaddeLetras=strlen($miItem); if($cantidaddeLetras<=27) { $pdf->Cell(0,0,$miItem); }else{ $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], 6); // set the font $pdf->Cell(0,0,$miItem); $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], $parametros['formatofuente3']); // set the font } //$pdf -> SetX(100); $pdf -> SetX($parametros['formatoitem1posXfolio1']); $pdf->Cell(0,0,$rsCtaART['folio1']); //$pdf -> SetX(126); $pdf -> SetX($parametros['formatoitem1posXfolio2']); $pdf->Cell(0,0,$rsCtaART['folio2']); //$pdf -> SetX(157); $pdf -> SetX($parametros['formatoitem1posXunitario']); $pdf->Cell(0,0,$rsCtaART['precio']); $subtotal=$rsCtaART['precio']*$rsCtaART['cantidad']; //$pdf -> SetX(185); $pdf -> SetX($parametros['formatoitem1posXtotal']); $pdf->Cell(0,0,$subtotal); $espaciorenglon=$parametros['formatoitem1posY2']; $veces++; } $pdf->SetY($parametros['formatoobsposY']); $pdf -> SetX($parametros['formatoobsposX']); $pdf->Cell(0,0,date("d/m/Y").' :--: '. date("G:H:s").' - '.$_SESSION['perfil']); $pdf -> SetY($parametros['formatoobsposY']+5); $pdf -> SetX($parametros['formatoobsposX']); $pdf->Cell(0,0,'Nro. Fac. '.$ventas['codigo']); //$pdf -> SetX(185); $pdf->SetFont('Arial','B',10); $pdf->SetY($parametros['formatototalposY']); $pdf -> SetX($parametros['formatototalposX']); $pdf->Cell(0,0,$ventas['total']); $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], $parametros['formatofuente3']); //$pdf -> SetY(25); // set the cursor at Y position 5 $pdf -> SetY($parametros['fecha1posY']+$parametros['posYfactura2']); // set the cursor at Y position 5 //$pdf -> SetX(170); $pdf -> SetX($parametros['fecha1posXdia']); $pdf->Cell(0,0,$fechaNueva[2]); //$pdf -> SetX(180); $pdf -> SetX($parametros['fecha1posXmes']); $pdf->Cell(0,0,$fechaNueva[1]); //$pdf -> SetX(192); $pdf -> SetX($parametros['fecha1posXanio']); $pdf->Cell(0,0,$anio); //Carga cliente y condiciones //$pdf -> SetY(40); // set the cursor at Y position 5 //$pdf -> SetX(50); $pdf -> SetY($parametros['formatocabecera1posY1']+$parametros['posYfactura2']); // set the cursor at Y position 5 $pdf -> SetX($parametros['formatocabecera1posX1']); $pdf->Cell(0,0,convertirLetras($escribanos['nombre'])); //$pdf -> SetY(44); //$pdf -> SetX(50); $pdf -> SetY($parametros['formatocabecera1posY2']+$parametros['posYfactura2']); $pdf -> SetX($parametros['formatocabecera1posX2']); $pdf->Cell(0,0,'s/iva'); //$pdf -> SetY(50); //$pdf -> SetX(70); $pdf -> SetY($parametros['formatocabecera1posY3']+$parametros['posYfactura2']); $pdf -> SetX($parametros['formatocabecera1posX3']); $pdf->Cell(0,0,$metodoDePago); $renglon1=$parametros['formatoitem1posY']+$parametros['posYfactura2']; $espaciorenglon=0; $veces=0; $productosVentas = json_decode($ventas["productos"], true); foreach ($productosVentas as $key => $rsCtaART) { $pdf -> SetY($renglon1+($espaciorenglon*$veces)); // set the cursor at Y position 5 $pdf -> SetX($parametros['formatoitem1posXcant']); $pdf->Cell(0,0,$rsCtaART['cantidad']); //$pdf -> SetX(53); $pdf -> SetX($parametros['formatoitem1posXart']); $miItem=convertirLetras($rsCtaART['descripcion']); $cantidaddeLetras=strlen($miItem); if($cantidaddeLetras<=27) { $pdf->Cell(0,0,$miItem); }else{ $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], 6); // set the font $pdf->Cell(0,0,$miItem); $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], $parametros['formatofuente3']); // set the font } //$pdf -> SetX(100); $pdf -> SetX($parametros['formatoitem1posXfolio1']); $pdf->Cell(0,0,$rsCtaART['folio1']); //$pdf -> SetX(126); $pdf -> SetX($parametros['formatoitem1posXfolio2']); $pdf->Cell(0,0,$rsCtaART['folio2']); //$pdf -> SetX(157); $pdf -> SetX($parametros['formatoitem1posXunitario']); $pdf->Cell(0,0,$rsCtaART['precio']); $subtotal=$rsCtaART['precio']*$rsCtaART['cantidad']; //$pdf -> SetX(185); $pdf -> SetX($parametros['formatoitem1posXtotal']); $pdf->Cell(0,0,$subtotal); $espaciorenglon=$parametros['formatoitem1posY2']; $veces++; } $pdf->SetY($parametros['formatoobsposY']+$parametros['posYfactura2']); $pdf -> SetX($parametros['formatoobsposX']); $pdf->Cell(0,0,date("d/m/Y").' :--: '. date("G:H:s").' - '.$_SESSION['perfil']); $pdf -> SetY($parametros['formatoobsposY']+$parametros['posYfactura2']+5); $pdf -> SetX($parametros['formatoobsposX']); $pdf->Cell(0,0,'Nro. Fac. '.$ventas['codigo']); //$pdf -> SetX(185); $pdf->SetFont('Arial','B',10); $pdf->SetY($parametros['formatototalposY']+$parametros['posYfactura2']); $pdf -> SetX($parametros['formatototalposX']); $pdf->Cell(0,0,$ventas['total']); $pdf->AutoPrint(); $pdf->Output(); ?><file_sep>/ajax/cuotas.ajax.php <?php require_once "../controladores/cuotas.controlador.php"; require_once "../modelos/cuotas.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; require_once "../controladores/categorias.controlador.php"; require_once "../modelos/categorias.modelo.php"; require_once "../controladores/osde.controlador.php"; require_once "../modelos/osde.modelo.php"; class AjaxCuota{ /*============================================= EDITAR CUOTAS =============================================*/ public function ajaxGenerarCuota(){ /*============================================= = GENERO LAS CUOTAS = =============================================*/ $item = null; $valor = null; $GenerarCuota = ControladorCuotas::ctrGeneraCuota($item, $valor); echo '<pre>'; print_r($GenerarCuota); echo '</pre>'; } /*============================================= EDITAR OSDE =============================================*/ public function ajaxGenerarOsde(){ /*============================================= = GENERO LAS CUOTAS = =============================================*/ $item = null; $valor = null; $GenerarOsde = ControladorCuotas::ctrGeneraOsde($item, $valor); echo '<pre>'; print_r($GenerarOsde); echo '</pre>'; } } /*============================================= EDITAR CUOTAS =============================================*/ if(isset($_POST["cuotas"])){ $cuotas = new AjaxCuota(); $cuotas -> ajaxGenerarCuota(); } /*============================================= EDITAR CUOTAS =============================================*/ if(isset($_POST["osde"])){ $cuotas = new AjaxCuota(); $cuotas -> ajaxGenerarOsde(); }<file_sep>/extensiones/fpdf/pdf/ventas.php <?php require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/remitos.controlador.php"; require_once "../../../modelos/remitos.modelo.php"; require_once "../../../controladores/caja.controlador.php"; require_once "../../../modelos/caja.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; require_once "../../../controladores/clientes.controlador.php"; require_once "../../../modelos/clientes.modelo.php"; require_once "../../../controladores/empresa.controlador.php"; require_once "../../../modelos/empresa.modelo.php"; #FUNCION PARA ÑS Y ACENTOS function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } #NOMBRE DEL INFORME $nombreDePdf="VENTAS DEL DIA"; #BUSCO LA FECHA $fecha1=$_GET['fecha1']; if(!isset($_GET['fecha2'])){ $fecha2=$_GET['fecha1']; }else{ $fecha2=$_GET['fecha2']; } $tipoVenta = $_GET['tipoventa']; #DATOS DE LA EMPRESA $item = "id"; $valor = 1; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); // VENTAS $item= "fecha"; $valor = $fecha1; $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); // REMITOS $item= "fecha"; $valor = $fecha1; $remitos = ControladorRemitos::ctrMostrarRemitosFecha($item,$valor); #PPREPARO EL PDF require('../fpdf.php'); $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $hoja=1; //CONFIGURACION DEL LA HORA date_default_timezone_set('America/Argentina/Buenos_Aires'); //DATOS DEL MOMENTO $fecha= date("d")."-".date("m")."-".date("Y"); $hora=date("g:i A"); //DATOS QUE RECIBO $fechaInicio=explode ( '-', $fecha1 ); $fechaInicio=$fechaInicio[2].'-'.$fechaInicio[1].'-'.$fechaInicio[0]; $fechaFin=explode ( '-', $fecha2 ); $fechaFin=$fechaFin[2].'-'.$fechaFin[1].'-'.$fechaFin[0]; //COMIENZA ENCABEZADO $pdf->SetFont('Arial','B',9); $pdf->Image('../../../vistas/img/plantilla/logo.jpg' , 5 ,0, 25 , 25,'JPG', 'http://www.bgtoner.com.ar'); $pdf->Text(35, 7,convertirLetras("COLEGIO DE ESCRIBANOS")); $pdf->Text(35, 10,convertirLetras("DE LA PROVINCIA DE FORMOSA")); $pdf->Text(150, 7,convertirLetras($nombreDePdf)); $pdf->SetFont('','',8); $pdf->Text(150, 12,convertirLetras("Fecha: ".$fecha)); $pdf->Text(178, 12,convertirLetras("Hora: ".$hora)); // $pdf->Text(150, 16,convertirLetras("Usuario: ADMIN")); $pdf->SetFont('','',6); $pdf->Text(35, 19,convertirLetras($empresa['direccion']." Tel.: ".$empresa['telefono'])); $pdf->Text(35, 22,convertirLetras("CUIT Nro. ".$empresa['cuit']." Ingresos Brutos 01-".$empresa['cuit'])); $pdf->Text(35, 25,convertirLetras("Inicio Actividades 02-01-1981 IVA Excento")); $pdf->SetFont('','',8); $pdf->Text(100, 27,convertirLetras("Hoja -".$hoja++)); if($fecha1==$fecha2){ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio)); }else{ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio." al ".$fechaFin)); } $pdf->Line(0,28,210, 28); $altura=30; // 3º Una tabla con los articulos comprados $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(26,188,156); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // Los datos (en negro) $pdf->SetTextColor(0,0,0); $pdf->SetFont('Arial','B',10); $altura=$altura+11; #EFECTIVO VARIBLES $efectivoVentas=0; $cantEfectivoVentas=0; $efectivoRemitos=0; $cantEfectivoRemitos=0; #CHEQUE VARIABLES $chequeVentas=0; $cantChequeVentas=0; $chequeRemitos=0; $cantChequeRemitos=0; #Tarjeta VARIABLES $tarjetaVentas=0; $cantTarjetaVentas=0; $tarjetaRemitos=0; $cantTarjetaRemitos=0; #TRANSFERENCIA VARIABLES $transferenciaVentas=0; $cantTransferenciaVentas=0; $transferenciaRemitos=0; $cantTransferenciaRemitos=0; #CTA.CORRIENTE VARIABLES $ctaCorrienteVentas=0; $cantCtaVentas=0; $ctaCorrienteRemitos=0; $cantCtaRemitos=0; // $cheque=0; // $cantCheque=0; // $tarjeta=0; // $cantTarjeta=0; // $transferencia=0; // $cantTransferencia=0; $otros=0; $cantVentas=0; $cuotaSocial=0; $cantCuota=0; $derecho=0; $cantDerecho=0; $cantOsde=0; $osde=0; $otrosRemitos=0; $cantVentasRemitos=0; $cuotaSocialRemitos=0; $cantCuotaRemitos=0; $derechoRemitos=0; $cantDerechoRemitos=0; $cantOsdeRemitos=0; $osdeRemitos=0; $ventasTotal=0; $contador=0; if($tipoVenta != "REMITO"){ foreach($ventasPorFecha as $key=>$rsVentas){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fecha'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$rsVentas['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } if($contador<=33){ $listaProductos = json_decode($rsVentas["productos"], true); foreach ($listaProductos as $key => $value) { switch ($value['id']) { case '20': # cuota... $cantCuota++; $cuotaSocial=$value['total']+$cuotaSocial; break; case '19': # derech... $cantDerecho++; $derecho=$value['total']+$derecho; break; case '22': # derech... $cantOsde++; $osde=$value['total']+$osde; break; default: # venta... $cantVentas++; $otros=$value['total']+$otros; break; } } if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivoVentas=$efectivoVentas+$importe; $cantEfectivoVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjetaVentas=$tarjetaVentas+$importe; $cantTarjetaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $chequeVentas=$chequeVentas+$importe; $cantChequeVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferenciaVentas=$transferenciaVentas+$importe; $cantTransferenciaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CT'){ $ctaCorrienteVentas=$ctaCorrienteVentas+$importe; $cantCtaVentas++; } $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(26,188,156); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); // $pdf->Cell(20,10,"Salida",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); //$cantEfectivo++; if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ // $importe=$rsVentas['total']; // $pdf->Cell(20,5,$importe,1,0,"C"); if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivoVentas=$efectivoVentas+$importe; $cantEfectivoVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjetaVentas=$tarjetaVentas+$importe; $cantTarjetaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $chequeVentas=$chequeVentas+$importe; $cantChequeVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferenciaVentas=$transferenciaVentas+$importe; $cantTransferenciaVentas++; } if (substr($rsVentas['metodo_pago'],0,2)=='CT'){ $ctaCorrienteVentas=$ctaCorrienteVentas+$importe; $cantCtaVentas++; } } $altura+=6; $contador++; } } } if($tipoVenta != "VENTA"){ // $totalRemitos = 0; foreach ($remitos as $key => $valueRemitos) { # code... // $totalRemitos = $totalRemitos + $value['total']; if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); $listaProductos = json_decode($valueRemitos["productos"], true); foreach ($listaProductos as $key => $valueProductos) { switch ($valueProductos['id']) { case '20': # cuota... $cantCuotaRemitos++; $cuotaSocialRemitos=$valueProductos['total']+$cuotaSocialRemitos; break; case '19': # derech... $cantDerechoRemitos++; $derechoRemitos=$valueProductos['total']+$derechoRemitos; break; case '22': # derech... $cantOsdeRemitos++; $osdeRemitos=$valueProductos['total']+$osdeRemitos; break; default: # venta... $cantVentasRemitos++; $otrosRemitos=$valueProductos['total']+$otrosRemitos; break; } } if($valueRemitos['tipo']=='NC'){ $importe=$valueRemitos['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$valueRemitos['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } if (substr($valueRemitos['metodo_pago'],0,2)=='EF'){ $efectivoRemitos=$efectivoRemitos+$importe; $cantEfectivoRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TA'){ $tarjetaRemitos=$tarjetaRemitos+$importe; $cantTarjetaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CH'){ $chequeRemitos=$chequeRemitos+$importe; $cantChequeRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TR'){ $transferenciaRemitos=$transferenciaRemitos+$importe; $cantTransferenciaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CT'){ $ctaCorrienteRemitos=$ctaCorrienteRemitos+$importe; $cantCtaRemitos++; } $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$valueRemitos['fecha'],1,0,"C"); $pdf->Cell(9,5,$valueRemitos['tipo'],1,0,"C"); $pdf->Cell(31,5,$valueRemitos['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$valueRemitos['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras($valueRemitos['nombre']),1,0,"L"); if ($valueRemitos['tipo']=='FC'){ $pdf->Cell(20,5,$importe,1,0,"C"); $pdf->Cell(20,5,'0',1,0,"C"); if (substr($valueRemitos['metodo_pago'],0,2)=='EF'){ $efectivoRemitos=$efectivoRemitos+$importe; $cantEfectivoRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TA'){ $tarjetaRemitos=$tarjetaRemitos+$importe; $cantTarjetaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CH'){ $chequeRemitos=$chequeRemitos+$importe; $cantChequeRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='TR'){ $transferenciaRemitos=$transferenciaRemitos+$importe; $cantTransferenciaRemitos++; } if (substr($valueRemitos['metodo_pago'],0,2)=='CT'){ $ctaCorrienteRemitos=$ctaCorrienteRemitos+$importe; $cantCtaRemitos++; } } $altura+=6; $contador++; } } } $altura+=2; #TOTALES DE LAS CANTIDADES DEL PRIMER RECUADRO $cantidadEfectivoVentas = $cantEfectivoVentas+$cantEfectivoRemitos; $cantidadChequeVentas = $cantChequeVentas+$cantChequeRemitos; $cantidadTarjetaVentas = $cantTarjetaVentas+$cantTarjetaRemitos; $cantidadTrasnferenciaVentas = $cantTransferenciaVentas+$cantTransferenciaRemitos; $cantidadCtaVentas =$cantCtaVentas+$cantCtaRemitos; #TOTALES DE LA SUMA DE TODOS $totalCuadro1 = $efectivoVentas+$efectivoRemitos+$transferenciaVentas+$transferenciaRemitos+$tarjetaRemitos+$tarjetaVentas+$chequeRemitos+$chequeVentas+$ctaCorrienteVentas+$ctaCorrienteRemitos; $totalCantidadesCaja1 = $cantidadEfectivoVentas + $cantidadChequeVentas + $cantidadTarjetaVentas + $cantidadTrasnferenciaVentas + $cantidadCtaVentas; $pdf->SetFont('Arial','',9); //PRIMER CUADRADO $pdf->SetXY(2,$altura); $pdf->Cell(42,34,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(16,$altura+3); $pdf->Write(0,$_GET['tipoventa']); #PRIMER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+7); $pdf->Cell(23,0,"($cantidadEfectivoVentas)".' Efectivo:',0,0,'R');//CANTIDAD $pdf->SetXY(18 ,$altura+7); $pdf->Cell(21,0,$efectivoVentas+$efectivoRemitos,0,0,'R');//IMPORTE #SEGUNDO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+11); $pdf->Cell(23,0,"($cantidadChequeVentas)".' Cheque:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+11); $pdf->Cell(19,0,$chequeVentas+$chequeRemitos,0,0,'R');//IMPORTE #TERCER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+15); $pdf->Cell(23,0,"($cantidadTarjetaVentas)".' Tarjeta:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+15); $pdf->Cell(19,0,$tarjetaVentas+$tarjetaRemitos,0,0,'R');//IMPORTE #CUARTO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+19); $pdf->Cell(23,0,"($cantidadTrasnferenciaVentas)".' Transf.:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+19); $pdf->Cell(19,0,$transferenciaVentas+$transferenciaRemitos,0,0,'R');//IMPORTE #QUINTO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+23); $pdf->Cell(23,0,"($cantidadCtaVentas)".' Cta.Corr.:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+23); $pdf->Cell(19,0,$ctaCorrienteVentas+$ctaCorrienteRemitos,0,0,'R');//IMPORTE #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(4,$altura+30); $totalCantVentas = $cantEfectivo + $cantCheque + $cantTransferencia + $cantTarjeta + $cantOsde; $pdf->Cell(23,0,"(".$totalCantidadesCaja1 .")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(20 ,$altura+30); $pdf->Line(25,$altura+26 ,44,$altura+26 ); $pdf->Cell(19,0,$totalCuadro1,0,0,'R');//IMPORTE if($_GET['tipoventa']=="VENTA"){ //SEGUNDO CUADRADO $pdf->SetXY(46,$altura); $pdf->Cell(42,34,'',1,0,"C"); #TITULO $pdf->SetFont('','U'); $pdf->SetXY(49,$altura+3); $pdf->Write(0,'VENTAS EN INSUMOS'); #PRIMER RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+7); $pdf->Cell(25,0,"(".$cantVentas.")".' Ventas:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+7); $pdf->Cell(19,0,$otros,0,0,'R');//IMPORTE #SEGUNDA RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+11); $pdf->Cell(25,0,"(".$cantCuota.")".' C. Social:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+11); $pdf->Cell(19,0,$cuotaSocial,0,0,'R');//IMPORTE #TERCERO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+15); $pdf->Cell(25,0,"(".$cantDerecho.")".' Derecho:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+15); $pdf->Cell(19,0,$derecho,0,0,'R');//IMPORTE #CUARTO RENGLON $pdf->SetFont('','B'); $pdf->SetXY(43,$altura+19); $pdf->Cell(25,0,"(".$cantOsde.")".' Osde:',0,0,'R');//CANTIDAD $pdf->SetXY(65,$altura+19); $pdf->Cell(19,0,$osde,0,0,'R');//IMPORTE #QUINTO RENGLON // $pdf->SetFont('','B'); // $pdf->SetXY(43,$altura+23); // $totalesCantRemitos = $cantCuotaRemitos+$cantDerechoRemitos+$cantOsdeRemitos+$cantVentasRemitos; // $pdf->Cell(25,0,"($totalesCantRemitos)".' Remitos:',0,0,'R');//CANTIDAD // $pdf->SetXY(65 ,$altura+23); // $pdf->Cell(19,0,$ctaCorrienteVentas+$ctaCorrienteRemitos,0,0,'R');//IMPORTE // $totalRemitos = $otrosRemitos+$cuotaSocialRemitos+$derechoRemitos+$osdeRemitos; #TOTALES $pdf->SetFont('','B'); $pdf->SetXY(60,$altura+30); $totales=$cantDerecho+$cantCuota+$cantVentas+$cantOsde+$totalesCantRemitos; $pdf->Cell(8,0,"(".$totales.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(65 ,$altura+30); $pdf->Line(66,$altura+26,88,$altura+26); $pdf->Cell(19,0,$otros+$cuotaSocial+$derecho+$osde+$totalRemitos ,0,0,'R');//IMPORTE } // El documento enviado al navegador $pdf->Output(); ?> <file_sep>/vistas/modulos/reportes/grafico-ventas.php <?php function cargarGrafico($fechaInicial,$fechaFinal){ //DATOS DE TODAS LAS VENTAS DEL MES $respuesta = ControladorVentas::ctrRangoFechasVentas($fechaInicial, $fechaFinal); $totalFacturado = 0; $repuestosVendidos = 0; $gananciaTotal = 0; $serviciosTerceros = 0; $cantidadSericiosTerceros =0; $tablaVendido=""; // inicio el recorrido foreach ($respuesta as $key => $value) { // tomo los valores $fecha = $value["fecha"]; $nrofc = $value["nrofc"]; // valores para MostrarClientes $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorClientes::ctrMostrarClientes($itemCliente, $valorCliente); // nombre del cliente $cliente = $respuestaCliente["nombre"]; //tomo los datos de los items $listaProducto= json_decode($value["productos"],true); foreach ($listaProducto as $key => $value2) { // TRAER EL STOCK $tablaProductos = "productos"; $item = "id"; $valor = $value2["id"]; $orden = "id"; $stock = ModeloProductos::mdlMostrarProductos($tablaProductos, $item, $valor, $orden); // VER QUE TIPO DE STOCK TIENE $item = "id"; $valor = $stock["id_categoria"]; $categorias = ControladorCategorias::ctrMostrarCategorias($item, $valor); $totalFacturado = $value2['total']+$totalFacturado; if($categorias["movimiento"]=="SI"){ //ESTE ES EL TOTAL DE LOS REPUESTOS $repuestosVendidos = $value2['total']+$repuestosVendidos; }else{ if ($stock['codigo']==302){ $serviciosTerceros= $value2['total']+$serviciosTerceros; $cantidadSericiosTerceros++; }else{ $gananciaTotal = $value2['total']+$gananciaTotal; } } } } $datos =array("repuestos"=>$repuestosVendidos,"ganancia"=>$gananciaTotal); return $datos; } // los diez ultimos meses $mes0= Date("Y-m"); $fechaInicial = $mes0.'-01'; $fechaFinal = $mes0.'-'.getUltimoDiaMes($mes0); $respuestaMes0 = cargarGrafico($fechaInicial, $fechaFinal); // --------------------------------------------------------------------------------------------------- $mes1 = strtotime ( '-1 month' , strtotime ( $mes0 ) ) ; $mes1 = date ( 'Y-m' , $mes1 ); $fechaInicial = $mes1.'-01'; $fechaFinal =$mes1.'-'.getUltimoDiaMes($mes1); $respuestaMes01 = cargarGrafico($fechaInicial, $fechaFinal); // --------------------------------------------------------------------------------------------------- $mes2 = strtotime ( '-1 month' , strtotime ( $mes1 ) ) ; $mes2 = date ( 'Y-m' , $mes2 ); $fechaInicial = $mes2.'-01'; $fechaFinal =$mes2.'-'.getUltimoDiaMes($mes2); $respuestaMes02 = cargarGrafico($fechaInicial, $fechaFinal); // --------------------------------------------------------------------------------------------------- ?> <!--===================================== GRÁFICO DE VENTAS ======================================--> <div class="box box-solid bg-teal-gradient"> <div class="nav-tabs-custom"> <!-- Tabs within a box --> <ul class="nav nav-tabs pull-right"> <li class="active"><a href="#revenue-chart" data-toggle="tab">Area</a></li> <li class="pull-left header"><i class="fa fa-inbox"></i> Ganancia y Repuestos</li> </ul> <div class="tab-content no-padding"> <!-- Morris chart - Sales --> <div class="chart tab-pane active" id="revenue-chart" style="position: relative; height: 300px;"></div> <div class="chart tab-pane" id="sales-chart" style="position: relative; height: 300px;"></div> </div> </div> </div> <script> /* Morris.js Charts */ // Sales chart var area = new Morris.Area({ element : 'revenue-chart', resize : true, data : [ { y: '<?php echo $mes2;?>', item1: <?php echo $respuestaMes02['repuestos'];?>, item2: <?php echo $respuestaMes02['ganancia'];?> }, { y: '<?php echo $mes1;?>', item1: <?php echo $respuestaMes01['repuestos'];?>, item2: <?php echo $respuestaMes01['ganancia'];?> }, { y: '<?php echo $mes0;?>', item1: <?php echo $respuestaMes0['repuestos'];?>, item2: <?php echo $respuestaMes0['ganancia'];?>} ], xkey : 'y', ykeys : ['item1', 'item2'], labels : ['Ganancia', 'Repuestos'], lineColors: ['#a0d0e0', '#3c8dbc'], hideHover : 'auto' }); </script><file_sep>/modelos/clientes.modelo.php <?php require_once "conexion.php"; class ModeloClientes{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function mdlMostrarClientes($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR CLIENTES =============================================*/ static public function mdlCrearCliente($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`nombre`,`cuit`,`tipoiva`,`direccion`, `localidad`) VALUES (:nombre,:cuit,:tipoiva,:direccion,:localidad)"); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":cuit", $datos["cuit"], PDO::PARAM_INT); $stmt->bindParam(":tipoiva", $datos["tipoiva"], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function mdlUltimoCliente($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc limit 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= CREAR CLIENTES =============================================*/ static public function mdlEditarCliente($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET `nombre`=:nombre,`cuit`=:cuit,`tipoiva`=:tipoiva,`direccion`=:direccion,`localidad`=:localidad WHERE id= :id "); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":cuit", $datos["cuit"], PDO::PARAM_STR); $stmt->bindParam(":tipoiva", $datos["tipoiva"], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlbKCliente($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= ELIMINAR ESCRIBANO =============================================*/ static public function mdlEliminarCliente($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } } <file_sep>/controladores/clientes.controlador.php <?php class ControladorClientes{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function ctrMostrarClientes($item, $valor){ $tabla = "clientes"; $respuesta = ModeloClientes::mdlMostrarClientes($tabla, $item, $valor); return $respuesta; } /*============================================= CREAR CLIENTE =============================================*/ static public function ctrCrearCliente($datos){ $tabla = "clientes"; $respuesta = ModeloCLientes::mdlCrearCliente($tabla, $datos); } /*============================================= MOSTRAR ULTIMO CLIENTE =============================================*/ static public function ctrUltimoCliente(){ $tabla = "clientes"; $respuesta = ModeloClientes::mdlUltimoCliente($tabla); return $respuesta; } /*============================================= EDITAR CLIENTE =============================================*/ static public function ctrEditarCliente($datos){ $tabla = "clientes"; $respuesta = ModeloCLientes::mdlEditarCliente($tabla, $datos); } /*============================================= ELIMINAR CLIENTE =============================================*/ static public function ctrEliminarCliente(){ if(isset($_GET["idCliente"])){ $tabla ="clientes"; $datos = $_GET["idCliente"]; $valor = $_GET["idCliente"]; #ENVIAMOS LOS DATOS ControladorClientes::ctrbKCliente($tabla, "id", $valor, "ELIMINAR"); $respuesta = ModeloClientes::mdlEliminarCliente($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Escribano ha sido borrado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar", closeOnConfirm: false }).then(function(result){ if (result.value) { window.location = "clientes"; } }) </script>'; } } } static public function ctrbKCliente($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO echo $item. " ". $valor; $respuesta = ControladorClientes::ctrMostrarClientes($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "direccion":"'.$respuesta[2].'", "localidad":"'.$respuesta[3].'", "telefono":"'.$respuesta[4].'", "tipoiva":"'.$respuesta[3].'", "cuit":"'.$respuesta[2].'"}]'; $datos = array("tabla"=>$tabla, "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloClientes::mdlbKCliente($tabla, $datos); } }<file_sep>/extensiones/afip/consulta.php <?php date_default_timezone_set('America/Argentina/Buenos_Aires'); include_once (__DIR__ . '/wsfev1.php'); include_once (__DIR__ . '/wsfexv1.php'); include_once (__DIR__ . '/wsaa.php'); include ('modo.php'); // $CUIT = 30584197680; // $MODO = Wsaa::MODO_PRODUCCION; $PTOVTA = 4; //lo puse acá para pasarlo como parámetro para los certificados por pto de vta $afip = new Wsfev1($CUIT,$MODO,$PTOVTA); $result = $afip->init(); if ($result["code"] === Wsfev1::RESULT_OK) { $result = $afip->dummy(); if ($result["code"] === Wsfev1::RESULT_OK) { $tipocbte = 11; } else { echo $result["msg"] . "\n"; } } else { echo $result["msg"] . "\n"; }<file_sep>/ajax/osde.ajax.php <?php require_once "../controladores/osde.controlador.php"; require_once "../modelos/osde.modelo.php"; class AjaxOsde{ /*============================================= EDITAR OSDE =============================================*/ public $idOsde; public function ajaxEditarOsde(){ $item = "id"; $valor = $this->idOsde; $respuesta = ControladorOsde::ctrMostrarOsde($item, $valor); echo json_encode($respuesta); } } /*============================================= EDITAR CATEGORÍA =============================================*/ if(isset($_POST["idOsde"])){ $categoria = new AjaxOsde(); $categoria -> idOsde = $_POST["idOsde"]; $categoria -> ajaxEditarOsde(); } <file_sep>/vistas/modulos/editar-perfil.php <?php $item = 'id'; $valor = $_SESSION['id']; $usuarios = ControladorUsuarios::ctrMostrarUsuarios($item, $valor); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar MI Perfil <?php echo "[".strtoupper($_SESSION['usuario'])."]"; ?> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar MI Perfil </li> </ol> </section> <section class="content"> <div class="row"> <div class="col-md-6 col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">Mi FOTO</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar mi Foto</label> <p class="pull-right"> <img src="<?php echo $_SESSION["foto"]; ?>" class="img-thumbnail previsualizarMiFoto" width="100px"> </p> <input type="hidden" id="idUsuario" value="<?php echo $_SESSION["id"]; ?>"> <input type="hidden" id="carpeta" value="<?php echo $_SESSION["usuario"]; ?>"> <input type="hidden" id="foto" value="<?php echo $_SESSION["foto"]; ?>"> <input type="file" id="subirMiFoto"> <p class="help-block">Tamaño recomendado 172px * 172px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarMiFoto" class="btn btn-primary pull-right">Guardar Mi Foto</button> </div> </div> </div> <!--===================================== FOTO RECIBO ======================================--> <div class="col-md-6 col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">MI CONTRASEÑA</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar mi Contraseña</label> <input type="<PASSWORD>" class="form-control input-lg" name="<PASSWORD>Password" id="<PASSWORD>" placeholder="<PASSWORD>" required> </div> </div> <div class="box-footer"> <button type="button" id="guardarMiPass" class="btn btn-primary pull-right">Guardar mi Contraseña</button> </div> </div> </div> </div> </section> </div> <file_sep>/modelos/empresa.modelo.php <?php require_once "conexion.php"; class ModeloEmpresa{ /*============================================= MOSTRAR EMPRESA =============================================*/ static public function mdlMostrarEmpresa($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= EDITAR EMPRESA =============================================*/ static public function mdlEditarEmpresa($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET empresa = :empresa, direccion = :direccion, telefono = :telefono,cuit = :cuit, email = :email, web = :web, detalle1 = :detalle1, detalle2 =:detalle2 WHERE id = 1"); $stmt -> bindParam(":empresa",strtoupper($datos["empresa"]), PDO::PARAM_STR); $stmt -> bindParam(":direccion",strtoupper($datos["direccion"]), PDO::PARAM_STR); $stmt -> bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR); $stmt -> bindParam(":cuit", $datos["cuit"], PDO::PARAM_STR); $stmt -> bindParam(":web",strtoupper($datos["web"]), PDO::PARAM_STR); $stmt -> bindParam(":email",strtoupper($datos["email"]), PDO::PARAM_STR); $stmt -> bindParam(":detalle1",strtoupper($datos["detalle1"]), PDO::PARAM_STR); $stmt -> bindParam(":detalle2",strtoupper($datos["detalle2"]), PDO::PARAM_STR); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= SELECCIONAR EMPRESA =============================================*/ static public function mdlSeleccionarEmpresa($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= ACTUALIZAR LOGO O ICONO =============================================*/ static public function mdlActualizarLogoIcono($tabla, $id, $item, $valor){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET $item = :$item WHERE id = :id"); $stmt->bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt->bindParam(":id", $id, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } }<file_sep>/vistas/modulos/restaurar.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar ventas </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar ventas</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal box-danger"> <div class="box-header with-border"> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>id</th> <th>tabla</th> <th>tipo</th> <th>fecha</th> <th>Usuario</th> <th style="width:140px">Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $respuesta = ControladorParametros::ctrMostrarBackUp($item, $valor); foreach ($respuesta as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value['id'].'</td> <td>'.$value['tabla'].'</td> <td>'.$value['tipo'].'</td> <td>'.$value['fechacreacion'].'</td> <td>'.$value['usuario'].'</td> <td> <div class="btn-group"> <button class="btn btn-info btnVerBackupEliminacion" idbackup="'.$value["id"].'" title="ver detalle" data-toggle="modal" data-target="#modalVerBackUp"><i class="fa fa-eye"></i></button> </button> </div> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <!--===================================== VER ARTICULOS ======================================--> <div id="modalVerBackUp" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <form role="form" method="post"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Ver Articulos</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <!-- ENTRADA PARA EL NOMBRE --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-calendar"></i></span> <input type="text" class="form-control input-lg" name="bkFecha" id="bkFecha"readonly> <input type="hidden" id="idBackUp" name="idBackUp"> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-database"></i></span> <input type="text" class="form-control input-lg" name="bkTabla" id="bkTabla" readonly> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-code"></i></span> <input type="text" class="form-control input-lg" name="bkTipo" id="bkTipo" readonly> </div> </div> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="text" class="form-control input-lg" name="bkUsuario" id="bkUsuario" readonly> </div> </div> <!-- ENTRADA PARA EL IMPORTE FACTURA --> <div class="form-group" > <div class="input-group"> <table class="table table-bordered tablaProductosVendidos"> <thead style="background:#3c8dbc; color:white"> <tr> <th>Campo</th> <th>Valor</th> </tr> </thead> <tbody id="verItems"></tbody> </table> </div> </div> </div> </div> <!--===================================== PIE DEL MODAL ======================================--> <div class="modal-footer" id="finalFooterRestaurar"> <!-- --> <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Salir</button> </div> </form> <?php $restaurarBackup = new ControladorParametros(); $restaurarBackup -> ctrRestaurarBackup(); ?> </div> </div> </div> <?php $eliminarBackup = new ControladorParametros(); $eliminarBackup -> ctrEliminarBackup(); ?><file_sep>/vistas/modulos/bibliotecas/inhabilitados.inicio.php <?php /*============================================= = CARGO UN ARRAY DE LOS ESCRIBANOS = =============================================*/ #SE REVISA A LOS DEUDORES $item = null; $valor = null; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); #CANTIDAD DE INHABILITADOS $cantInhabilitados = 0; #CANTIDAD DE INHABILITADOS $cantEscribanos = 0; #HAGO UN FOREACH PARA EVALUAR CUANTOS LIBROS DEBE foreach ($escribanos as $key => $value) { $cantEscribanos++; #INHABILITADOS $inhabilitado = 0; /*============================================= INHABILITACION POR LIBROS =============================================*/ #OBTENGO CUANTOS LIBROS... DEBE $cantLibros = $value["ultimolibrocomprado"]-$value["ultimolibrodevuelto"]; if ($cantLibros>=$maxLibros){ $inhabilitado++;//LO SACO DE CERO AL INHABILITADO } /*============================================= INHABILITACION POR DEUDA =============================================*/ //ACA ENTRAN TODOS LOS ATRASADOS $item= "id"; $valor = $value["id"]; // //VER LA DEUDA DE CADA ESCRIBANO $escribanosConDeudaTodos = ControladorCuotas::ctrEscribanosDeuda($item,$valor); if(!empty($escribanosConDeudaTodos)){ $fecha2=date("Y-m-j"); $dias = (strtotime($escribanosConDeudaTodos["fecha"])-strtotime($fecha2))/86400; $dias = abs($dias); $dias = floor($dias); if($dias>=$atraso['valor']) { if ($value['id']<>1){ $inhabilitado++; // echo '<pre>'; print_r($value["nombre"]); echo ' - ('.$dias.'-'.$inhabilitado. ')</pre>'; } } } /*============================================= GUARDO LOS INHABILITADOS EN LA BD LOCAL =============================================*/ if($inhabilitado>=1){ $valor=$value['id']; $respuesta = ControladorCuotas::ctrEscribanosInhabilitar($valor); $cantInhabilitados ++; /*=========================================== = SUBIR INHABILITADOS A LA TABLA INABILITADOS DEL = ===========================================*/ $datos = array("id"=>$value['id'], "nombre"=>$value['nombre']); ControladorEnlace::ctrSubirInhabilitado($datos); } }//foreach ?><file_sep>/vistas/js/cuotas.js /*============================================= BOTON VER CUOTA =============================================*/ $(".tablas").on("click", ".btnVerCuota", function(){ var idCuota = $(this).attr("idCuota"); var codigo = $(this).attr("codigo"); $(".tablaArticulosVer").empty(); var datos = new FormData(); datos.append("idCuota", idCuota); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ $("#verTotalFc").val(respuesta["total"]); $("#verEscribano").val(respuesta["nombre"]); // var datos = new FormData(); datos.append("idCuotaArt", idCuota); $.ajax({ url:"ajax/ctacorriente.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta3){ console.log("respuesta3", respuesta3); for (var i = 0; i < respuesta3.length; i++) { // console.log("respuesta3", respuesta3[i]['descripcion']); $(".tablaArticulosVer").append('<tr>'+ '<td>'+respuesta3[i]['cantidad']+'</td>'+ '<td>'+respuesta3[i]['descripcion']+'</td>'+ '<td>'+respuesta3[i]['folio1']+'</td>'+ '<td>'+respuesta3[i]['folio2']+'</td>'+ '<td>'+respuesta3[i]['total']+'</td>'+ '</tr>'); } } }) } }) })<file_sep>/vistas/modulos/descargar-reporte-cuotas.php <?php require_once "../../controladores/ventas.controlador.php"; require_once "../../modelos/ventas.modelo.php"; require_once "../../controladores/escribanos.controlador.php"; require_once "../../modelos/escribanos.modelo.php"; require_once "../../controladores/enlace.controlador.php"; require_once "../../modelos/enlace.modelo.php"; require_once "../../controladores/usuarios.controlador.php"; require_once "../../modelos/usuarios.modelo.php"; require_once "../../controladores/cuotas.controlador.php"; require_once "../../modelos/cuotas.modelo.php"; $reporte = new ControladorCuotas(); $reporte -> ctrDescargarCuotas();<file_sep>/modelos/remitos.modelo.php <?php require_once "conexion.php"; class ModeloRemitos{ /*============================================= MOSTRAR DELEGACIONES =============================================*/ static public function mdlMostrarRemitos($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR DELEGACIONES =============================================*/ static public function mdlMostrarRemitosFecha($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= CREAR DELEGACION =============================================*/ static public function mdlIngresarRemito($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre,direccion,localidad,telefono,puntodeventa,idescribano,escribano) VALUES (:nombre,:direccion,:localidad,:telefono,:puntodeventa,:idescribano,:escribano)"); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":direccion", $datos['direccion'], PDO::PARAM_STR); $stmt->bindParam(":localidad", $datos['localidad'], PDO::PARAM_STR); $stmt->bindParam(":telefono", $datos['telefono'], PDO::PARAM_STR); $stmt->bindParam(":puntodeventa", $datos['puntodeventa'], PDO::PARAM_STR); $stmt->bindParam(":idescribano", $datos['idescribano'], PDO::PARAM_INT); $stmt->bindParam(":escribano", $datos['escribano'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function mdlEditarRemito($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre,direccion = :direccion, localidad = :localidad, telefono = :telefono, puntodeventa = :puntodeventa, idescribano = :idescribano,escribano = :escribano WHERE id = :id"); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt -> bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt -> bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR); $stmt -> bindParam(":localidad", $datos["localidad"], PDO::PARAM_STR); $stmt -> bindParam(":telefono", $datos["telefono"], PDO::PARAM_STR); $stmt -> bindParam(":puntodeventa", $datos["puntodeventa"], PDO::PARAM_STR); $stmt -> bindParam(":idescribano", $datos["idescribano"], PDO::PARAM_INT); $stmt -> bindParam(":escribano", $datos["escribano"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR DELEGACION =============================================*/ static public function mdlBorrarRemito($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= OBTENER EL ULTIMO ID =============================================*/ static public function mdlUltimoIdRemito($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id,codigo FROM `remitos` ORDER BY id DESC LIMIT 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE VENTA =============================================*/ static public function mdlIngresarVentaRemito($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,tipo,codigo, id_cliente,nombre,documento,tabla, id_vendedor, productos, impuesto, neto, total,adeuda,observaciones,metodo_pago,referenciapago,fechapago,cae,fecha_cae) VALUES (:fecha,:tipo,:codigo, :id_cliente,:nombre,:documento,:tabla, :id_vendedor, :productos, :impuesto, :neto, :total,:adeuda,:obs, :metodo_pago,:referenciapago,:fechapago,:cae,:fecha_cae)"); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":id_vendedor", $datos["id_vendedor"], PDO::PARAM_INT); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":impuesto", $datos["impuesto"], PDO::PARAM_STR); $stmt->bindParam(":neto", $datos["neto"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); $stmt->bindParam(":obs",$datos["obs"], PDO::PARAM_STR); $stmt->bindParam(":metodo_pago", $datos["metodo_pago"], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos["referenciapago"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } } <file_sep>/vistas/modulos/bibliotecas/con-caja.incio.php <?php #CREO UN NUEVO REGISTRO DE LA CAJA CON LA FECHA DEL DIA $datos=array("fecha"=>date('Y-m-d'), "efectivo"=>0, "tarjeta"=>0, "cheque"=>0, "transferencia"=>0); $insertarCaja = ControladorCaja::ctrIngresarCaja($item, $datos); include("cuotas.inicio.php");#CHEQUEO SI SE GENERARON Y SI NO SE GENERARON GENERARLA include("servidor.inicio.php");#ELIMINAR LOS INHABILITADOS EN EL SERVIDOR y habilito include("inhabilitados.inicio.php");#INABILITO A QUIEN CORRESPONDA include("ws.inicio.php");#LO SUBO EN LA WS ?><file_sep>/ajax/rubros.ajax.php <?php require_once "../controladores/rubros.controlador.php"; require_once "../modelos/rubros.modelo.php"; class AjaxRubros{ /*============================================= EDITAR RUBRO =============================================*/ public $idRubro; public function ajaxEditarRubro(){ $item = "id"; $valor = $this->idRubro; $respuesta = ControladorRubros::ctrMostrarRubros($item, $valor); echo json_encode($respuesta); } } /*============================================= EDITAR RUBRO =============================================*/ if(isset($_POST["idRubro"])){ $categoria = new AjaxRubros(); $categoria -> idRubro = $_POST["idRubro"]; $categoria -> ajaxEditarRubro(); } <file_sep>/vistas/modulos/miempresa.php <?php $item = null; $valor = null; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar empresa </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar empresa</li> </ol> </section> <section class="content"> <div class="box box-danger"> <div class="box-body"> <div class="row"> <div class="col-lg-8"> <!-- ENTRADA PARA LA EMPRESA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-university"></i></span> <input type="text" class="form-control input-lg" id="editarEmpresa" name="editarEmpresa" value="<?php echo $empresa[0]['empresa']; ?>" required> </div> </div> <!-- ENTRADA PARA LA DIRECCION --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" id="editarDireccion" name="editarDireccion" value="<?php echo $empresa[0]['direccion']; ?>" required> </div> </div> <!-- ENTRADA PARA EL TELEFONO --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input type="text" class="form-control input-lg" name="editarTelefono" id="editarTelefono" value="<?php echo $empresa[0]['telefono']; ?>" required > </div> </div> <!-- ENTRADA PARA EL EMAIL --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-at"></i></span> <input type="text" class="form-control input-lg" name="editarEmail" id="editarEmail" value="<?php echo $empresa[0]['email']; ?>" required > </div> </div> <!-- ENTRADA PARA EL CUIT --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-hashtag"></i></span> <input type="text" class="form-control input-lg" name="editarCuit" id="editarCuit" value="<?php echo $empresa[0]['cuit']; ?>"> </div> </div> <!-- ENTRADA PARA EL WEB --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-chrome"></i></span> <input type="text" class="form-control input-lg" name="editarWeb" id="editarWeb" value="<?php echo $empresa[0]['web']; ?>"> </div> </div> </div> <div class="col-lg-3"> <div class="form-group"> <div class="input-group"> <label for="editarDetalle1">NOTA RECIBO CLIENTE</label> <textarea name="editarDetalle1" id="editarDetalle1" cols="50" rows="5"><?php echo $empresa[0]['detalle1']; ?></textarea> </div> </div> <div class="form-group"> <div class="input-group"> <label for="editarDetalle2">NOTA ACEPTACION CLIENTE</label> <textarea name="editarDetalle2" id="editarDetalle2" cols="50" rows="5"><?php echo $empresa[0]['detalle2']; ?></textarea> </div> </div> <div class="box-footer"> <button type="button" id="guardarDatosEmpresa" class="btn btn-primary pull-right">Guardar Datos de Empresa</button> </div> </div> </div> <div class="row"> <div class="col-md-6 col-xs-12"> <div class="box box-primary"> <div class="box-header with-border"> <h3 class="box-title">ICONO DEL MENU</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar icono del Menu</label> <p class="pull-right"> <img src="<?php echo $empresa[0]["iconochicoblanco"]; ?>" class="img-thumbnail previsualizarIconoBlanco" width="50px"> </p> <input type="file" id="subirIconoBlanco"> <p class="help-block">Tamaño recomendado 172px * 172px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarIconoBlanco" class="btn btn-primary pull-right">Guardar Icono Menu</button> </div> <!--===================================== ICONO NEGRO ======================================--> <div class="box-header with-border"> <h3 class="box-title">ICONO DEL NAVEGADOR</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar el icono del Navegador</label> <p class="pull-right"> <img src="<?php echo $empresa[0]["iconochiconegro"]; ?>" class="img-thumbnail previsualizarIconoNegro" width="50px"> </p> <input type="file" id="subirIconoNegro"> <p class="help-block">Tamaño recomendado 172px * 172px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarIconoNegro" class="btn btn-primary pull-right">Guardar Icono Navegador</button> </div> <!--===================================== LOGO BLANCO BLOQUE ======================================--> <div class="box-header with-border"> <h3 class="box-title">LOGO PARA EL BACKEND</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar Logo para el Backend</label> <p class="pull-right"> <img src="<?php echo $empresa[0]["logoblancobloque"]; ?>" class="img-thumbnail previsualizarLogoBlancoBloque" width="100px"> </p> <input type="file" id="subirLogoBlancoBloque"> <p class="help-block">Tamaño recomendado 500px * 183px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarLogoBlancoBloque" class="btn btn-primary pull-right">Guardar Logo para Backend</button> </div> </div><!-- box box-primary --> </div><!-- col-md-6 col-xs-12 --> <div class="col-md-6 col-xs-12"> <div class="box box-primary"> <!--===================================== LOGO BLANCO LINEAL ======================================--> <div class="box-header with-border"> <h3 class="box-title">LOGO LINEAL MENU</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar Lineal Menu</label> <p class="pull-right"> <img src="<?php echo $empresa[0]["logoblancolineal"]; ?>" class="img-thumbnail previsualizarBlancoLineal" width="150px"> </p> <input type="file" id="subirBlancoLineal"> <p class="help-block">Tamaño recomendado 800px * 117px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarBlancoLineal" class="btn btn-primary pull-right">Guardar Lineal Menu</button> </div> <!--===================================== FOTO RECIBO ======================================--> <div class="box-header with-border"> <h3 class="box-title">RECIBO</h3> </div> <div class="box-body"> <div class="form-group"> <label>Cambiar Recibo</label> <p class="pull-right"> <img src="<?php echo $empresa[0]["fotorecibo"]; ?>" class="img-thumbnail previsualizarFotoRecibo" width="100px"> </p> <input type="file" id="subirFotoRecibo"> <p class="help-block">Tamaño recomendado 500px * 183px</p> </div> </div> <div class="box-footer"> <button type="button" id="guardarFotoRecibo" class="btn btn-primary pull-right">Guardar Foto Recibo</button> </div> </div><!-- box box-primary --> </div><!-- col-md-6 col-xs-12 --> </div><!-- ROW--> </section> </div> <file_sep>/extensiones/fpdf/pdf/caja - copia.php <?php require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/caja.controlador.php"; require_once "../../../modelos/caja.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; require_once "../../../controladores/empresa.controlador.php"; require_once "../../../modelos/empresa.modelo.php"; #FUNCION PARA ÑS Y ACENTOS function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } #NOMBRE DEL INFORME $nombreDePdf="CAJA DEL DIA"; #BUSCO LA FECHA $fecha1=$_GET['fecha1']; if(!isset($_GET['fecha2'])){ $fecha2=$_GET['fecha1']; }else{ $fecha2=$_GET['fecha2']; } // VENTA $item= "fechapago"; $valor = $fecha1; $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); #DATOS DE LA EMPRESA $item = "id"; $valor = 1; $empresa = ControladorEmpresa::ctrMostrarEmpresa($item, $valor); #PPREPARO EL PDF require('../fpdf.php'); $pdf = new FPDF('P','mm','A4'); $pdf->AddPage(); $hoja=1; //CONFIGURACION DEL LA HORA date_default_timezone_set('America/Argentina/Buenos_Aires'); //DATOS DEL MOMENTO $fecha= date("d")."-".date("m")."-".date("Y"); $hora=date("g:i A"); //DATOS QUE RECIBO $fechaInicio=explode ( '-', $fecha1 ); $fechaInicio=$fechaInicio[2].'-'.$fechaInicio[1].'-'.$fechaInicio[0]; $fechaFin=explode ( '-', $fecha2 ); $fechaFin=$fechaFin[2].'-'.$fechaFin[1].'-'.$fechaFin[0]; //COMIENZA ENCABEZADO $pdf->SetFont('Arial','B',9); $pdf->Image('../../../vistas/img/plantilla/logo.jpg' , 5 ,0, 25 , 25,'JPG', 'http://www.bgtoner.com.ar'); $pdf->Text(35, 7,convertirLetras("COLEGIO DE ESCRIBANOS")); $pdf->Text(35, 10,convertirLetras("DE LA PROVINCIA DE FORMOSA")); $pdf->Text(150, 7,convertirLetras($nombreDePdf)); $pdf->SetFont('','',8); $pdf->Text(150, 12,convertirLetras("Fecha: ".$fecha)); $pdf->Text(178, 12,convertirLetras("Hora: ".$hora)); // $pdf->Text(150, 16,convertirLetras("Usuario: ADMIN")); $pdf->SetFont('','',6); $pdf->Text(35, 19,convertirLetras($empresa['direccion']." Tel.: ".$empresa['telefono'])); $pdf->Text(35, 22,convertirLetras("CUIT Nro. ".$empresa['cuit']." Ingresos Brutos 01-".$empresa['cuit'])); $pdf->Text(35, 25,convertirLetras("Inicio Actividades 02-01-1981 IVA Excento")); $pdf->SetFont('','',8); $pdf->Text(100, 27,convertirLetras("Hoja -".$hoja++)); if($fecha1==$fecha2){ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio)); }else{ $pdf->Text(135, 25,convertirLetras("FECHA DE CONSULTA: Del ".$fechaInicio." al ".$fechaFin)); } $pdf->Line(0,28,210, 28); $altura=30; // 3º Una tabla con los articulos comprados $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(9,10,"Tipo",1,0,"C",true); $pdf->Cell(31,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); $total=0; // Los datos (en negro) $pdf->SetTextColor(0,0,0); $pdf->SetFont('Arial','B',10); $altura=$altura+11; $efectivo=0; $cantEfectivo=0; $cheque=0; $cantCheque=0; $tarjeta=0; $cantTarjeta=0; $transferencia=0; $cantTransferencia=0; $otros=0; $cantVentas=0; $cuotaSocial=0; $cantCuota=0; $derecho=0; $cantDerecho=0; $cantOsde=0; $osde=0; $ventasTotal=0; $contador=0; foreach($ventasPorFecha as $key=>$rsVentas){ if($contador<=33){ $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fechapago'],1,0,"C"); $pdf->Cell(9,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(31,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); // ESCRIBANO if ($rsVentas['id_cliente']!=0){ $item= "id"; $valor = $rsVentas['id_cliente']; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item,$valor); $pdf->Cell(95,5,convertirLetras($escribanos['nombre']),1,0,"L"); }else{ $pdf->Cell(95,5,convertirLetras($rsVentas['nombre']),1,0,"L"); } $listaProductos = json_decode($rsVentas["productos"], true); foreach ($listaProductos as $key => $value) { switch ($value['id']) { case '20': # cuota... $cantCuota++; $cuotaSocial=$value['total']+$cuotaSocial; break; case '19': # derech... $cantDerecho++; $derecho=$value['total']+$derecho; break; case '22': # derech... $cantOsde++; $osde=$value['total']+$osde; break; default: # venta... $cantVentas++; $otros=$value['total']+$otros; break; } } if($rsVentas['tipo']=='NC'){ $importe=$rsVentas['total']*(-1); $pdf->Cell(20,5,$importe,1,0,"C"); }else{ $importe=$rsVentas['total']; $pdf->Cell(20,5,$importe,1,0,"C"); } if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivo=$efectivo+$importe; $cantEfectivo++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjeta=$tarjeta+$importe; $cantTarjeta++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $cheque=$cheque+$importe; $cantCheque++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferencia=$transferencia+$importe; $cantTransferencia++; $ventasTotal+=$importe; $cantVentasTotal++; } $altura+=6; $contador++; }else{ $contador=0; $pdf->AddPage(); //ENCAABREZADO $altura=30; $pdf->SetFont('Arial','B',11); // La cabecera de la tabla (en azulito sobre fondo rojo) $pdf->SetXY(3,$altura); $pdf->SetFillColor(255,0,0); $pdf->SetTextColor(255,255,255); $pdf->Cell(20,10,"Fecha",1,0,"C",true); $pdf->Cell(10,10,"Tipo",1,0,"C",true); $pdf->Cell(10,10,"Pago",1,0,"C",true); $pdf->Cell(30,10,"Nro. Factura",1,0,"C",true); $pdf->Cell(95,10,"Nombre",1,0,"C",true); $pdf->Cell(20,10,"Entrada",1,0,"C",true); $pdf->Cell(20,10,"Salida",1,0,"C",true); $pdf->SetFont('Arial','B',10); $pdf->SetXY(5,$altura); $altura=$altura+11; $pdf->SetTextColor(0,0,0); //$cantEfectivo++; $pdf->SetXY(3,$altura); $pdf->Cell(20,5,$rsVentas['fechapago'],1,0,"C"); $pdf->Cell(10,5,$rsVentas['tipo'],1,0,"C"); $pdf->Cell(10,5,$rsVentas['metodo_pago'],1,0,"C"); $pdf->Cell(30,5,$rsVentas['codigo'],1,0,"C"); $pdf->Cell(95,5,convertirLetras('<NAME>'),1,0,"L"); if ($rsVentas['tipo']=='FC'){ $pdf->Cell(20,5,$importe,1,0,"C"); $pdf->Cell(20,5,'0',1,0,"C"); if (substr($rsVentas['metodo_pago'],0,2)=='EF'){ $efectivo=$efectivo+$importe; $cantEfectivo++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='TA'){ $tarjeta=$tarjeta+$importe; $cantTarjeta++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='CH'){ $cheque=$cheque+$importe; $cantCheque++; $ventasTotal+=$importe; $cantVentasTotal++; } if (substr($rsVentas['metodo_pago'],0,2)=='TR'){ $transferencia=$transferencia+$importe; $cantTransferencia++; $ventasTotal+=$importe; $cantVentasTotal++; } } $altura+=6; $contador++; } } $altura+=2; $pdf->SetFont('Arial','',9); //PRIMER CUADRADO $pdf->SetXY(39,$altura); $pdf->Cell(42,28,'',1,0,"C"); $pdf->SetFont('','U'); $pdf->SetXY(48,$altura+3); $pdf->Write(0,'RECAUDACION'); $pdf->SetFont('','B'); $pdf->SetXY(38,$altura+7); $pdf->Cell(23,0,"($cantEfectivo)".' Efectivo:',0,0,'R');//CANTIDAD $pdf->SetXY(60 ,$altura+7); $pdf->Cell(19,0,$efectivo,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(38,$altura+11); $pdf->Cell(23,0,"($cantCheque)".' Cheque:',0,0,'R');//CANTIDAD $pdf->SetXY(60 ,$altura+11); $pdf->Cell(19,0,$cheque,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(38,$altura+15); $pdf->Cell(23,0,"($cantTarjeta)".' Tarjeta:',0,0,'R');//CANTIDAD $pdf->SetXY(60 ,$altura+15); $pdf->Cell(19,0,$tarjeta,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(38,$altura+19); $pdf->Cell(23,0,"($cantTransferencia)".' Transf.:',0,0,'R');//CANTIDAD $pdf->SetXY(60 ,$altura+19); $pdf->Cell(19,0,$tarjeta,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(38,$altura+25); $totalCantVentas = $cantEfectivo + $cantCheque + $cantTransferencia + $cantTarjeta + $cantOsde; $pdf->Cell(23,0,"(".$totalCantVentas.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(60 ,$altura+25); $pdf->Line(45,$altura+22,79,$altura+22); $pdf->Cell(19,0,$ventasTotal,0,0,'R');//IMPORTE //SEGUNDO CUADRADO $pdf->SetXY(85,$altura); $pdf->Cell(42,28,'',1,0,"C"); $pdf->SetFont('','U'); $pdf->SetXY(97,$altura+3); $pdf->Write(0,'VENTAS'); $pdf->SetFont('','B'); $pdf->SetXY(83,$altura+7); $pdf->Cell(25,0,"(".$cantVentas.")".' Ventas:',0,0,'R');//CANTIDAD $pdf->SetXY(103,$altura+7); $pdf->Cell(19,0,$otros,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(83,$altura+11); $pdf->Cell(25,0,"(".$cantCuota.")".' C. Social:',0,0,'R');//CANTIDAD $pdf->SetXY(103,$altura+11); $pdf->Cell(19,0,$cuotaSocial,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(83,$altura+15); $pdf->Cell(25,0,"(".$cantDerecho.")".' Derecho:',0,0,'R');//CANTIDAD $pdf->SetXY(103,$altura+15); $pdf->Cell(19,0,$derecho,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(83,$altura+19); $pdf->Cell(25,0,"(".$cantOsde.")".' Osde:',0,0,'R');//CANTIDAD $pdf->SetXY(103,$altura+19); $pdf->Cell(19,0,$osde,0,0,'R');//IMPORTE $pdf->SetFont('','B'); $pdf->SetXY(100,$altura+25); $totales=$cantDerecho+$cantCuota+$cantVentas+$cantOsde; $pdf->Cell(8,0,"(".$totales.")".' Total:',0,0,'R');//CANTIDAD $pdf->SetXY(103 ,$altura+20); $pdf->Line(90,$altura+22,122,$altura+22); $pdf->Cell(19,10,$otros+$cuotaSocial+$derecho+$osde,0,0,'R');//IMPORTE //TERCER CUADRADO $pdf->SetXY(135,$altura); $pdf->Cell(42,28,'',1,0,"C"); $pdf->SetFont('','U'); $pdf->SetXY(146,$altura+3); $pdf->Write(0,'EFECTIVO'); // $pdf->SetFont('','B'); $pdf->SetFont('Arial','B',12); $pdf->SetXY(80,$altura+14); $pdf->Cell(85,0,"$ ".$efectivo.".-",0,0,'R');//CANTIDAD $pdf->SetXY(142,$altura+14); // El documento enviado al navegador $pdf->Output(); ?> <file_sep>/ajax/updateTodo.ajax.php <?php require_once "../controladores/cuotas.controlador.php"; require_once "../modelos/cuotas.modelo.php"; require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class AjaxUpdateTodos{ /*============================================= ACTUALIZAR CUOTAS =============================================*/ public function ajaxActualizarCuotas(){ #ELIMINAR CUOTAS DEL ENLACE ControladorEnlace::ctrEliminarEnlace('cuotas'); #TRAER PRODUCTOS DEL COLEGIO $item = null; $valor = null; $cuotas = ControladorCuotas::ctrMostrarCuotas($item, $valor); $cant=0; foreach ($cuotas as $key => $value) { # code... $tabla = "cuotas"; $datos = array( "id"=>$value['id'], "fecha"=>$value['fecha'], "tipo"=>$value['tipo'], "id_cliente"=>$value['id_cliente'], "nombre"=>$value['nombre'], "documento"=>$value['documento'], "productos"=>$value['productos'], "total"=>$value['total']); #registramos los productos $respuesta = ModeloEnlace::mdlIngresarCuota($tabla, $datos); } /*=========================================== = CONSULTAR SI EXISTEN MODIFICACIONES = ===========================================*/ $tabla ="modificaciones"; $datos = array("nombre"=>"cuotas","fecha"=>date("Y-m-d")); $modificaciones = ModeloEnlace::mdlConsultarModificaciones($tabla,$datos); if(!$modificaciones[0]>=1){ $datos = array("nombre"=>"cuotas","fecha"=>date("Y-m-d")); ControladorEnlace::ctrSubirModificaciones($datos); } } /*============================================= ACTUALIZAR FACTURAS =============================================*/ public function ajaxActualizarFacturas(){ $ventasEnlace =ControladorEnlace::ctrMostrarUltimaAVenta(); $ultimoIdServidor = $ventasEnlace['id']; $ventasLocal = ControladorVentas::ctrMostrarUltimaAVenta(); $ultimoIdLocal = $ventasLocal['id']; if ($ultimoIdServidor < $ultimoIdLocal){ #CONSULTA DE VENTAS MAYORES AL ULTIMO ID DEL SERVIDOR $item = "id"; $valor = $ultimoIdServidor; $ventasUltimasVentas = ControladorVentas::ctrMostrarUltimasVentas($item, $valor); foreach ($ventasUltimasVentas as $key => $value) { # code... $tabla = "ventas"; $datos = array("id"=>$value["id"], "fecha"=>$value["fecha"], "codigo"=>$value["codigo"], "tipo"=>$value["tipo"], "id_cliente"=>$value["id_cliente"], "nombre"=>$value["nombre"], "documento"=>$value["documento"], "tabla"=>$value["tabla"], "id_vendedor"=>$value["id_vendedor"], "productos"=>$value["productos"], "impuesto"=>$value["impuesto"], "neto"=>$value["neto"], "total"=>$value["total"], "adeuda"=>$value["adeuda"], "metodo_pago"=>$value["metodo_pago"], "fechapago"=>$value["fechapago"], "cae"=>$value["cae"], "fecha_cae"=>$value["fecha_cae"], "referenciapago"=>$value["referenciapago"], "observaciones"=>$value["observaciones"]); #registramos los productos $respuesta = ModeloEnlace::mdlIngresarVentaEnlace2($tabla, $datos); } } /*=========================================== = CONSULTAR SI EXISTEN MODIFICACIONES = ===========================================*/ $tabla ="modificaciones"; $datos = array("nombre"=>"ventas","fecha"=>date("Y-m-d")); $modificaciones = ModeloEnlace::mdlConsultarModificaciones($tabla,$datos); if(!$modificaciones[0]>=1){ $datos = array("nombre"=>"ventas","fecha"=>date("Y-m-d")); ControladorEnlace::ctrSubirModificaciones($datos); } } } /*============================================= ACTUALIZAR TODO =============================================*/ if(isset($_POST["actualizarCuota"])){ $productos = new AjaxUpdateTodos(); $productos -> ajaxActualizarCuotas(); } if(isset($_POST["actualizarFc"])){ $productos = new AjaxUpdateTodos(); $productos -> ajaxActualizarFacturas(); }<file_sep>/vistas/modulos/reportes/caja-tecnico.php <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <button type="button" class="btn btn-default pull-right" id="daterange-btn-repuestos-tecnico"> <span> <i class="fa fa-calendar"></i> Rango de Fecha </span> <i class="fa fa-caret-down"></i> </button> </div> <?php if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } //DATOS DE TODAS LAS VENTAS DEL MES $respuesta = ControladorVentas::ctrRangoFechasVentas($fechaInicial, $fechaFinal); $totalFacturado = 0; $repuestosVendidos = 0; $gananciaTotal = 0; $serviciosTerceros = 0; $cantidadSericiosTerceros =0; $tablaVendido=""; // inicio el recorrido foreach ($respuesta as $key => $value) { // tomo los valores $fecha = $value["fecha"]; $nrofc = $value["nrofc"]; $detalle =$value['detalle']; // valores para MostrarClientes $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorClientes::ctrMostrarClientes($itemCliente, $valorCliente); // nombre del cliente $cliente = $respuestaCliente["nombre"]; //tomo los datos de los items $listaProducto= json_decode($value["productos"],true); foreach ($listaProducto as $key => $value2) { // TRAER EL STOCK $tablaProductos = "productos"; $item = "id"; $valor = $value2["id"]; $orden = "id"; $stock = ModeloProductos::mdlMostrarProductos($tablaProductos, $item, $valor, $orden); // VER QUE TIPO DE STOCK TIENE $item = "id"; $valor = $stock["id_categoria"]; $categorias = ControladorCategorias::ctrMostrarCategorias($item, $valor); $totalFacturado = $value2['total']+$totalFacturado; if($categorias["movimiento"]=="SI"){ //ESTE ES EL TOTAL DE LOS REPUESTOS $repuestosVendidos = $value2['total']+$repuestosVendidos; }else{ if ($stock['codigo']==302){ $serviciosTerceros= $value2['total']+$serviciosTerceros; $cantidadSericiosTerceros++; $tablaCobrada = $tablaCobrada . '<tr> <td>'.$cantidadSericiosTerceros.'</td> <td>'.$fecha.'</td> <td>'.$nrofc.'</td> <td>'.$cliente.'</td> <td>'.$detalle.'</td> <td>'.$value2['descripcion'].'</td> <td>'.$value2['total'].'</td> </tr>'; }else{ $gananciaTotal = $value2['total']+$gananciaTotal; } } } } ?> <div class="box-header with-border"> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="fa fa-wrench"></i></span> <div class="info-box-content"> <span class="info-box-text">MI TRABAJO</span> <span class="info-box-number"><center>$ <?php if(isset($_GET["fechaInicial"])){ echo $serviciosTerceros; }else{ echo "0.00"; } ?></center></span> <span class="info-box-number"> <center><small><?php if(isset($_GET["fechaInicial"])){ echo $cantidadSericiosTerceros; }else{ echo "0"; }?> Uni.</small></center></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <!-- /.col --> </div> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th>#</th> <th>Fecha</th> <th>Codigo</th> <th>Cliente</th> <th>Modelo</th> <th>Detalle</th> <th>Importe</th> </tr> </thead> <tbody> <?php if(isset($_GET["fechaInicial"])){ echo $tablaCobrada; } ?> </tbody> </table> </div> </section> </div> <file_sep>/index.php <?php date_default_timezone_set('America/Argentina/Buenos_Aires'); #CONTROLADORES QUE SE USAN::::::::::::::::::::::::::::: require_once "controladores/plantilla.controlador.php"; require_once "controladores/escribanos.controlador.php"; require_once "controladores/usuarios.controlador.php"; require_once "controladores/empresa.controlador.php"; require_once "controladores/categorias.controlador.php"; require_once "controladores/osde.controlador.php"; require_once "controladores/rubros.controlador.php"; require_once "controladores/comprobantes.controlador.php"; require_once "controladores/productos.controlador.php"; require_once "controladores/ventas.controlador.php"; require_once "controladores/parametros.controlador.php"; require_once "controladores/caja.controlador.php"; require_once "controladores/tipoiva.controlador.php"; require_once "controladores/enlace.controlador.php"; require_once "controladores/clientes.controlador.php"; require_once "controladores/articulos.controlador.php"; require_once "controladores/delegaciones.controlador.php"; require_once "controladores/remitos.controlador.php"; require_once "controladores/cuotas.controlador.php"; require_once "controladores/ws.controlador.php"; #MODELOS QUE SE USAN:::::::::::::::::::::::::::::::::::: require_once "modelos/escribanos.modelo.php"; require_once "modelos/empresa.modelo.php"; require_once "modelos/usuarios.modelo.php"; require_once "modelos/categorias.modelo.php"; require_once "modelos/osde.modelo.php"; require_once "modelos/rubros.modelo.php"; require_once "modelos/comprobantes.modelo.php"; require_once "modelos/productos.modelo.php"; require_once "modelos/ventas.modelo.php"; require_once "modelos/parametros.modelo.php"; require_once "modelos/caja.modelo.php"; require_once "modelos/programaviejo.modelo.php"; require_once "modelos/tipoiva.modelo.php"; require_once "modelos/enlace.modelo.php"; require_once "modelos/clientes.modelo.php"; require_once "modelos/articulos.modelo.php"; require_once "modelos/delegaciones.modelo.php"; require_once "modelos/remitos.modelo.php"; require_once "modelos/cuotas.modelo.php"; require_once "modelos/ws.modelo.php"; $plantilla = new ControladorPlantilla(); $plantilla -> ctrPlantilla(); <file_sep>/vistas/modulos/clientes.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar clientes </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar clientes</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <!-- <button class="btn btn-primary" data-toggle="modal" data-target="#modalAgregarEscribano"> Agregar clientes </button> --> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Cuit</th> <th>T.Iva</th> <th>Direccion</th> <th>Localidad</th> <th>Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes = ControladorClientes::ctrMostrarClientes($item, $valor); foreach ($clientes as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["nombre"].'</td> <td>'.$value["cuit"].'</td> <td>'.$value["tipoiva"].'</td> <td>'.$value["direccion"].'</td> <td>'.$value["localidad"].'</td>'; echo '<td> <div class="btn-group"> <button class="btn btn-warning btnEditarCliente" data-toggle="modal" data-target="#modalEditarCliente" idCliente="'.$value["id"].'"><i class="fa fa-pencil"></i></button>'; // if($_SESSION["perfil"] == "Administrador"){ echo '<button class="btn btn-danger btnEliminarCliente" idCliente="'.$value["id"].'"><i class="fa fa-times"></i></button>'; // } echo '</div> </td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <div id="modalEditarCliente" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Editar los Datos del Cliente</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-user"></i></span> <input type="hidden" id="idClienteEditar" name="idClienteEditar"> <input type="text" class="form-control input-lg" name="nombreEditarCliente" id="nombreEditarCliente" placeholder="Ingresar Nombre" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL CUIT --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="number" class="form-control input-lg" name="documentoEditarCliente" id="documentoEditarCliente" placeholder="Ingresar Cuit" required> </div> </div> <!-- ENTRADA PARA SELECCIONAR CATEGORÍA --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-th"></i></span> <select class="form-control input-lg" id="tipoCuitEditarCliente" name="tipoCuitEditarCliente" required> <option value="">Selecionar categoría</option> <?php $item = null; $valor = null; $categorias = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.strtoupper($value["nombre"]).'">'.strtoupper($value["nombre"]).'</option>'; } ?> </select> </div> </div> <!-- ENTRADA PARA LA DIRECCION --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="text" class="form-control input-lg" name="direccionEditarCliente" id="direccionEditarCliente" placeholder="Ingresar Direccion" required> </div> </div> <!-- ENTRADA PARA LA LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-id-card"></i></span> <input type="text" class="form-control input-lg" name="localidadEditarCliente" id="localidadEditarCliente" placeholder="Ingresar Localidad" required> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" id="btnGuardarCambios">Guardar Cambios</button> </div> </div> </div> </div> <?php $eliminarCliente = new ControladorClientes(); $eliminarCliente -> ctrEliminarCliente(); ?> <file_sep>/vistas/modulos/bibliotecas/ws.inicio.php <?php /*=================================================== = INHABILITO A LOS ESCRIBANOS QUE ESTEN ATRASADOS O DEBAN LIBROS = los paso al nro 2 EN EL WEBSERVICE ===================================================*/ ControladorWs::ctrNullEscribanosWs(); /*============================================= GUARDO LOS INHABILITADOS EN LA BD LOCAL =============================================*/ $verEscribanos = ControladorEscribanos::ctrMostrarInhabilitado(); foreach ($verEscribanos as $key => $value) { $datos = array("idcliente"=>$value['id'], "inhabilitado"=>$value['inhabilitado']); ControladorWs::ctrModificarEstadosWs($datos); } ?><file_sep>/ajax/nota_credito.ajax.php <?php #escribanos require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; #clientes require_once "../controladores/clientes.controlador.php"; require_once "../modelos/clientes.modelo.php"; #grabar require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class AjaxNotaCredito{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxNotadeCredito(){ $datos = array("idVenta"=>$_POST['idVenta'], "idcliente"=>$_POST['idClienteNc'], "nombre"=>$_POST['nombreClienteNc'], "documento"=>$_POST['documentoNc'], "tabla"=>$_POST['tablaNc'], "productos"=>$_POST['productosNc'], "total"=>$_POST['totalNc'], "nroFactura"=>$_POST['nroFactura']); $respuesta = ControladorVentas::ctrCrearNc($datos); } } /*============================================= REALIZAR NOTA DE CREDITO =============================================*/ if(isset($_POST["idClienteNc"])){ $verTabla = new AjaxNotaCredito(); $verTabla -> ajaxNotadeCredito(); } <file_sep>/vistas/js/editar-venta.js $("#guardarEditarVenta").on("click",function(){ $("#btn-editarVenta").attr('disabled','disabled'); var idUltimaFactura=0; var codigoUltimaFactura=0; var datos = new FormData(); datos.append("sinHomologacion",1 ); datos.append("listaProductos", $('#listaProductos').val()); console.log('listaProductos ', $('#listaProductos').val()); datos.append("idVendedor", $('#idVendedor').val()); console.log('idVendedor: ', $('#idVendedor').val()); datos.append("seleccionarCliente", $('#seleccionarCliente').val()); console.log('seleccionarCliente: ', $('#seleccionarCliente').val()); datos.append("documentoCliente", $('#documentoCliente').val()); console.log('documentoCliente: ', $('#documentoCliente').val()); datos.append("tipoCliente", $('#tipoCliente').val()); console.log('tipoCliente: ', $('#tipoCliente').val()); datos.append("tipoDocumento", $('#tipoDocumento').val()); console.log('tipoDocumento: ', $('#tipoDocumento').val()); datos.append("nombreCliente",$("#nombrecliente").val()); console.log('nombreCliente: ', $("#nombrecliente").val()); datos.append("listaMetodoPago", $('#listaMetodoPago').val()); console.log('listaMetodoPago: ', $('#listaMetodoPago').val()); datos.append("nuevaReferencia", $('#nuevaReferencia').val()); console.log('nuevaReferencia: ', $('#nuevaReferencia').val()); datos.append("totalVenta", $('#totalVenta').val()); console.log('totalVenta: ', $('#totalVenta').val()); datos.append("nuevoPrecioImpuesto", $('#nuevoPrecioImpuesto').val()); console.log('nuevoPrecioImpuesto: ', $('#nuevoPrecioImpuesto').val()); datos.append("nuevoPrecioNeto", $('#nuevoPrecioNeto').val()); console.log('nuevoPrecioNeto: ', $('#nuevoPrecioNeto').val()); datos.append("nuevoTotalVentas", $('#nuevoTotalVentas').val()); console.log('nuevoTotalVentas: ', $('#nuevoTotalVentas').val()); datos.append("tipoCuota", $('#tipoCuota').val()); console.log('tipoCuota: ', $('#tipoCuota').val()); datos.append("idVentaNro", $('#idVenta').val()); console.log('idVentaNro: ', $('#idVenta').val()); datos.append("tipoFc", $('#tipoFc').val()); console.log('idVentaNro: ', $('#idVenta').val()); //CREAMOS LA FACTURA $.ajax({ url:"ajax/crearventa.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, success:function(respuestaSinHomologacion){ console.log("respuestaSinHomologacion", respuestaSinHomologacion); ultimaFactura = 'ultimaFactura'; var datos = new FormData(); datos.append("ultimaFactura",ultimaFactura); $.ajax({ url:"ajax/crearventa.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuestaUltimaFactura){ console.log('respuestaUltimaFactura: ', respuestaUltimaFactura); idUltimaFactura=respuestaUltimaFactura["id"]; codigoUltimaFactura=respuestaUltimaFactura["codigo"]; window.location = "index.php?ruta=ventas&id="+idUltimaFactura+"&tipo=cuota"; } }) } }) }) <file_sep>/modelos/articulos.modelo.php <?php require_once "conexion.php"; class ModeloArticulos{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function mdlMostrarArticulos($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item and activo = 1"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where activo = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR ESCRIBANOS =============================================*/ static public function mdlIngresarArticulo($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`folio`,`nrocomprobante`,`nombre`,`idfactura`, `fecha`,`nrofactura`, `nombrecliente`) VALUES (:folio,:nrocomprobante,:nombre,:idfactura,:fecha,:nrofactura,:nombrecliente)"); $stmt->bindParam(":folio", $datos["folio"], PDO::PARAM_STR); $stmt->bindParam(":nrocomprobante", $datos["nrocomprobante"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":idfactura", $datos["idfactura"], PDO::PARAM_STR); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":nrofactura", $datos["nrofactura"], PDO::PARAM_STR); $stmt->bindParam(":nombrecliente", $datos["nombrecliente"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/ajax/ventaSeleccionada.ajax.php <?php require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class AjaxSeleccionarVenta{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxSeleccionoVenta(){ $item = "id"; $valor = $_POST["idVenta"]; $respuesta = ControladorVentas::ctrSeleccionarVenta($item, $valor); } } /*============================================= EDITAR VENTA =============================================*/ if(isset($_POST["idVenta"])){ $seleccionarFactura = new AjaxSeleccionarVenta(); $seleccionarFactura -> ajaxSeleccionoVenta(); } <file_sep>/ajax/ultimoIdVentas.ajax.php <?php require_once "../modelos/ventas.modelo.php"; class AjaxUltimoId{ /*============================================= EDITAR CATEGORÍA =============================================*/ public function ajaxUltimoIdBsq(){ $respuesta = ModeloVentas::mdlUltimoId("ventas"); echo $respuesta['id']; } } /*============================================= EDITAR CATEGORÍA =============================================*/ if(isset($_POST["ultimoId"])){ $ultimoId = new AjaxUltimoId(); $ultimoId -> ajaxUltimoIdBsq(); } <file_sep>/controladores/categorias.controlador.php <?php class ControladorCategorias{ /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function ctrMostrarCategorias($item, $valor){ $tabla = "categorias"; $respuesta = ModeloCategorias::mdlMostrarCategorias($tabla, $item, $valor); return $respuesta; } static public function ctrbKCategorias($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorCategorias::ctrMostrarCategorias($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "categoria":"'.$respuesta[1].'", "importe":"'.$respuesta[2].'", "activo":"'.$respuesta[3].'", "osbdel":"'.$respuesta[4].'", "fecha":"'.$respuesta[5].'"}]'; $datos = array("tabla"=>"categorias", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloCategorias::mdlbKCategoria($tabla, $datos); } /*============================================= CREAR CATEGORIAS =============================================*/ static public function ctrCrearCategoria(){ if(isset($_POST["nuevaCategoria"])){ if ($_POST["nuevoImporte"]<>null){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevaCategoria"])){ $tabla = "categorias"; $datos = $_POST["nuevaCategoria"]; $datos = array("categoria" => $_POST["nuevaCategoria"], "importe" => $_POST["nuevoImporte"]); $respuesta = ModeloCategorias::mdlIngresarCategoria($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido guardada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } } } } /*============================================= EDITAR CATEGORIAS =============================================*/ static public function ctrEditarCategoria(){ if(isset($_POST["editarCategoria"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarCategoria"])){ $tabla = "categorias"; $datos = array("categoria"=>$_POST["editarCategoria"], "importe"=>$_POST["editarImporte"], "id"=>$_POST["idCategoria"]); ControladorCategorias::ctrbKCategorias($tabla, "id", $_POST["idCategoria"], "UPDATE"); $respuesta = ModeloCategorias::mdlEditarCategoria($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido cambiada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } } } /*============================================= BORRAR CATEGORIAS =============================================*/ static public function ctrBorrarCategoria(){ if(isset($_GET["idCategoria"])){ $tabla ="categorias"; $datos = $_GET["idCategoria"]; #ENVIAMOS LOS DATOS ControladorCategorias::ctrbKCategorias($tabla, "id", $_GET["idCategoria"], "ELIMINAR"); $respuesta = ModeloCategorias::mdlBorrarCategoria($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La categoría ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "categorias"; } }) </script>'; } } } } <file_sep>/controladores/tipoiva.controlador.php <?php class ControladorTipoIva{ /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function ctrMostrarTipoIva($item, $valor){ $tabla = "tipo_iva"; $respuesta = ModeloTipoIva::mdlMostrarTipoIva($tabla, $item, $valor); return $respuesta; } } <file_sep>/extensiones/fpdf/pdf/facturaElectronica2.php <?php session_start(); include('../fpdf.php'); include ('../../barcode.php'); require_once "../../../controladores/ventas.controlador.php"; require_once "../../../modelos/ventas.modelo.php"; require_once "../../../controladores/parametros.controlador.php"; require_once "../../../modelos/parametros.modelo.php"; require_once "../../../controladores/escribanos.controlador.php"; require_once "../../../modelos/escribanos.modelo.php"; require_once "../../../controladores/clientes.controlador.php"; require_once "../../../modelos/clientes.modelo.php"; require_once "../../../controladores/tipoiva.controlador.php"; require_once "../../../modelos/tipoiva.modelo.php"; class PDF_JavaScript extends FPDF { protected $javascript; protected $n_js; function IncludeJS($script, $isUTF8=false) { if(!$isUTF8) $script=utf8_encode($script); $this->javascript=$script; } function _putjavascript() { $this->_newobj(); $this->n_js=$this->n; $this->_put('<<'); $this->_put('/Names [(EmbeddedJS) '.($this->n+1).' 0 R]'); $this->_put('>>'); $this->_put('endobj'); $this->_newobj(); $this->_put('<<'); $this->_put('/S /JavaScript'); $this->_put('/JS '.$this->_textstring($this->javascript)); $this->_put('>>'); $this->_put('endobj'); } function _putresources() { parent::_putresources(); if (!empty($this->javascript)) { $this->_putjavascript(); } } function _putcatalog() { parent::_putcatalog(); if (!empty($this->javascript)) { $this->_put('/Names <</JavaScript '.($this->n_js).' 0 R>>'); } } } class PDF_AutoPrint extends PDF_JavaScript { function AutoPrint($printer='') { // Open the print dialog if($printer) { $printer = str_replace('\\', '\\\\', $printer); $script = "var pp = getPrintParams();"; $script .= "pp.interactive = pp.constants.interactionLevel.full;"; $script .= "pp.printerName = '$printer'"; $script .= "print(pp);"; } else $script = 'print(true);'; $this->IncludeJS($script); } } function convertirLetras($texto){ $texto = iconv('UTF-8', 'windows-1252', $texto); return $texto; } require_once('../../../modelos/conexion.php'); // PARAMETROS $item= "id"; $valor = 1; $parametros = ControladorParametros::ctrMostrarParametros($item,$valor); // VENTA $item= "id"; $valor = $_GET['id']; $ventas = ControladorVentas::ctrMostrarVentas($item,$valor); if($ventas['tipo']=='NC'){ $codFactura = 'COD. 13'; $tituloFactura ="NOTA DE CREDITO"; }else{ $codFactura = 'COD. 11'; $tituloFactura ="FACTURA"; } // ESCRIBANO if($ventas['id_cliente']==0){ $item= "id"; $valor = 5; $descripcionTipoDoc ="DNI:"; }else{ if ($ventas['tabla']=='escribanos') { #SI ES UN ESCRIBANO $descripcionTipoDoc ="CUIT:"; $item= "id"; $valor = $ventas['id_cliente']; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item,$valor); #BUSCAR EL TIPO DE IVA $item = "id"; $valor = $escribanos["id_tipo_iva"]; $tipo_Iva = ControladorTipoIva::ctrMostrarTipoIva($item, $valor); $tipoIva = $tipo_Iva["nombre"]; }elseif($ventas['id_cliente']==1) { $descripcionTipoDoc ="CUIT:"; $tipoIva ="Consumidor Final"; } else{ $descripcionTipoDoc ="CUIT:"; $item= "id"; $valor = $ventas['id_cliente']; $escribanos = ControladorClientes::ctrMostrarClientes($item,$valor); $tipoIva = $escribanos['tipoiva']; } } $fechaNueva = explode("-", $ventas['fecha']); $anio = substr($fechaNueva[0], -2); //PUNTO DE VENTAS $codigo = explode("-", $ventas['codigo']); //FECHA $fecha = explode("-", $ventas['fecha']); $fecha = $fecha[2]."/".$fecha[1]."/".$fecha[0]; //CODIGO DE BARRA $tipocbte = 11; $fechaCae = explode("/", $ventas['fecha_cae']); $codigodeBarra = '30584197680'.$tipocbte.$codigo[0].$ventas['cae'].$fechaCae[2].$fechaCae[1].$fechaCae[0]; $cantCodigodeBarra =strlen($codigodeBarra); $impares = 0; $pares = 0; for ($i=0; $i <= $cantCodigodeBarra ; $i+=2) { # code... $impares=$impares+$codigodeBarra[$i]; } for ($i=1; $i <= $cantCodigodeBarra ; $i+=2) { # code... $pares=$pares+$codigodeBarra[$i]; } $impares = $impares * 3; $resultadoCodigo = $pares + $impares; $resultadoCodigo2 =$resultadoCodigo; $ultimoDigito = 0; for ($j=0; $j <= 10 ; $j++) { if(substr($resultadoCodigo2,-1,1)=='0'){ $ultimoDigito = $j; break; }else{ $resultadoCodigo2=$resultadoCodigo2+1; } $i++; } $pdf = new PDF_AutoPrint($parametros['formatopagina1'],$parametros['formatopagina2'],$parametros['formatopagina3']); $pdf->AddPage('P','A4'); $pdf -> SetFont($parametros['formatofuente1'], $parametros['formatofuente2'], $parametros['formatofuente3']); $pdf->Image('../../../vistas/img/afip/factura.jpg' , 5 ,5, 200 , 245,'JPG', ''); //ENCABEZADO FACTURA /*============================================= CENTRO DE LA FACTURA =============================================*/ //POSICION ORIGINAL DUPLICADO TRIPLICADO $pdf -> SetY(11); $pdf -> SetX(90); $pdf -> SetFont('Arial','B',16); $pdf->Cell(0,0,'ORIGINAL'); //POSICION DEL TIPO DE FACTURA $pdf -> SetY(26); $pdf -> SetX(98); $pdf -> SetFont('Arial','B',35); $pdf->Cell(0,0,'C'); //POSICION DEL NRO COMPROBANTE $pdf -> SetY(35); $pdf -> SetX(96); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,$codFactura); /*============================================= IZQUIERDA DE LA FACTURA =============================================*/ //POSICION DEL NOMBRE FICTICIO $pdf -> SetY(22); $pdf -> SetX(12); $pdf -> SetFont('Arial','B',16); $pdf->Cell(0,0,'COLEGIO DE ESCRIBANOS'); $pdf -> SetY(28); $pdf -> SetX(24); $pdf->Cell(0,0,'DE LA PROVINCIA'); $pdf -> SetY(34); $pdf -> SetX(32); $pdf->Cell(0,0,'DE FORMOSA'); //RAZON SOCIAL $pdf -> SetY(45); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Razón Social:')); $pdf -> SetX(27); $pdf -> SetFont('Arial','',7); $pdf->Cell(0,0,convertirLetras('COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA')); //DOMICILIO COMERCIAL $pdf -> SetY(49); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Domicilio Comercial:')); $pdf -> SetX(35); $pdf -> SetFont('Arial','',7); $pdf->Cell(0,0,convertirLetras('PADRE PATINO 812 - FORMOSA ')); //TELEFONO $pdf -> SetY(53); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Telefono:')); $pdf -> SetX(22); $pdf -> SetFont('Arial','',8); $pdf->Cell(0,0,convertirLetras('3704-429330 // 3704-431837')); //CONDICION FRENTE AL IVA $pdf -> SetY(57); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); $pdf -> SetX(40); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Iva Exento')); /*============================================= DERECHA DE LA FACTURA =============================================*/ //POSICION DE LA PALABRA FACTURA $pdf -> SetY(22); $pdf -> SetX(122); $pdf -> SetFont('Arial','B',18); $pdf->Cell(0,0,$tituloFactura); //POSICION DE PUNTO DE VENTA Y NRO DE COMPROBANTE $pdf -> SetY(33); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Punto de Venta:')); $pdf -> SetY(33); $pdf -> SetX(145); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($codigo[0])); $pdf -> SetY(33); $pdf -> SetX(160); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Comp. Nro: ')); $pdf -> SetY(33); $pdf -> SetX(180); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($codigo[1])); //FECHA DE EMISION $pdf -> SetY(38); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Fecha de Emisión:')); $pdf -> SetY(38); $pdf -> SetX(148); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($fecha)); //CUIT $pdf -> SetY(46); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('CUIT:')); $pdf -> SetY(46); $pdf -> SetX(130); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('30584197680')); //INGRESOS BRUTOS $pdf -> SetY(50); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Ingresos Brutos:')); $pdf -> SetY(50); $pdf -> SetX(146); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('30584197680')); //INICIO DE ACTIVIDADES $pdf -> SetY(54); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Fecha de Inicio de Actividades:')); $pdf -> SetY(54); $pdf -> SetX(165); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('07/10/1979')); /*============================================= CAJA CLIENTE =============================================*/ //CUIT $pdf -> SetY(68); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras($descripcionTipoDoc)); $pdf -> SetY(68); $pdf -> SetX(18); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,$ventas["documento"]); //POSICION DEL NOMBRE DEL CLIENTE $pdf -> SetY(68); $pdf -> SetX(50); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Apellido y Nombre / Razón Social:')); $pdf -> SetY(68); $pdf -> SetX(110); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($ventas["nombre"])); //TIPO DE IVA $pdf -> SetY(76); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); //primera linea if ($ventas["id_cliente"]!=0){ if(strlen($tipoIva)<=37){ $pdf -> SetY(76); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($tipoIva)); }else{ $dividirPalabra =explode('-',$tipoIva); $pdf -> SetY(76); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($dividirPalabra[0])); $pdf -> SetY(80); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($dividirPalabra[1])); } }else{ $pdf -> SetY(76); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras("CONSUMIDOR FINAL")); } //CONDICION DE VENTA $pdf -> SetY(84); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Condición de Venta:')); $pdf -> SetY(84); $pdf -> SetX(45); $pdf -> SetFont('Arial','',10); if ($ventas['referenciapago']=="EFECTIVO"){ $pdf->Cell(0,0,'Contado'); }else{ $pdf->Cell(0,0,$ventas['metodo_pago']); } //DOMICILIO $pdf -> SetY(76); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Domicilio:')); $pdf -> SetY(76); $pdf -> SetX(138); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($escribanos['direccion'])); $pdf -> SetY(80); $pdf -> SetX(138); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($escribanos['localidad'])); /*============================================= ENCABEZADO =============================================*/ //PRODUCTO $pdf -> SetY(93); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Producto / Servicio')); //CANTIDAD $pdf -> SetY(93); $pdf -> SetX(121); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Cantidad')); //PRECIO UNITARIO $pdf -> SetY(93); $pdf -> SetX(143); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Precio Unit.')); //PRECIO TOTAL $pdf -> SetY(93); $pdf -> SetX(176); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Subtotal')); /*============================================= PRODUCTOS =============================================*/ $renglon1=101; $espaciorenglon=0; $veces=0; //TOMO LOS PRODUCTOS EN UN ARRAY $productosVentas = json_decode($ventas["productos"], true); foreach ($productosVentas as $key => $rsCtaART) { $pdf -> SetFont('Arial','',10); $pdf -> SetY($renglon1+($espaciorenglon*$veces)); $pdf -> SetX(8); $miItem=convertirLetras($rsCtaART['descripcion']); if($ventas["tipo"]=="FC"){ if ($rsCtaART['folio1']!=1){ $miItem.=' del '.$rsCtaART['folio1'].' al '.$rsCtaART['folio2']; } } $pdf->Cell(0,0,$miItem,0,0,'L'); $pdf -> SetX(110); $pdf->Cell(28,0,$rsCtaART['cantidad'],0,0,'R'); $pdf -> SetX(147); $pdf->Cell(16,0,$rsCtaART['precio'],0,0,'R'); $subtotal=$rsCtaART['precio']*$rsCtaART['cantidad']; $pdf -> SetX($parametros['formatoitem1posXtotal']); $pdf->Cell(0,0,$subtotal,0,0,'R'); $espaciorenglon=$parametros['formatoitem1posY2']; $veces++; } /*============================================= CAJA DE SUBTOTALES =============================================*/ //SUBTOTAL $pdf -> SetY(207); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Subtotal: $'),0,0,'R'); $pdf -> SetY(207); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); //OTROS ATRIBUTOS $pdf -> SetY(217); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Importe Otros Tributos: $'),0,0,'R'); $pdf -> SetY(217); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,convertirLetras('0,00'),0,0,'R'); //OTROS ATRIBUTOS $pdf -> SetY(227); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Importe Total: $'),0,0,'R'); $pdf -> SetY(227); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); /*============================================= CAJA DEL NOMBRE =============================================*/ //NOMBRE $pdf -> SetY(245); $pdf -> SetX(10); $pdf -> SetFont('Arial','BI',8); $pdf->Cell(0,0,convertirLetras('"COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA."')); $pdf -> SetX(100); $pdf->Cell(0,0,convertirLetras('"Los trámites de apostilla tienen una demora de 24 a 48 hs. como mínimo."')); /*============================================= PIE DE PAGINA =============================================*/ //PAGINACION $pdf -> SetY(255); $pdf -> SetX(90); $pdf -> SetFont('Arial','B',12); $pdf->Cell(0,0,convertirLetras('Pág. 1/3')); //CAE $pdf -> SetY(255); $pdf -> SetX(155); $pdf -> SetFont('Arial','B',12); $pdf->Cell(15,0,convertirLetras('CAE Nro.:'),0,0,'R'); $pdf -> SetY(255); $pdf -> SetX(170); $pdf -> SetFont('Arial','',12); $pdf->Cell(15,0,convertirLetras($ventas['cae']),0,0,'L'); //FECHA CAE $pdf -> SetY(260); $pdf -> SetX(155); $pdf -> SetFont('Arial','B',12); $pdf->Cell(15,0,convertirLetras('Fecha de Vto. de CAE:'),0,0,'R'); $pdf -> SetY(260); $pdf -> SetX(170); $pdf -> SetFont('Arial','',12); $pdf->Cell(15,0,convertirLetras($ventas['fecha_cae']),0,0,'L'); //IMAGEN $pdf->Image('../../../vistas/img/afip/afip.jpg' , 5 ,252, 45 , 17,'JPG', ''); $pdf -> SetY(270); $pdf -> SetX(6); $pdf -> SetFont('Arial','BI',5); $pdf->Cell(15,0,convertirLetras('Esta Administración Federal no se responsabiliza por los datos ingresados en el detalle de la operación'),0,0,'L'); //IMAGEN barcode('../../codigos/'.$codigodeBarra.$ultimoDigito.'.png', $codigodeBarra.$ultimoDigito, 50, 'horizontal', 'code128', true); $pdf->Image('../../codigos/'.$codigodeBarra.$ultimoDigito.'.png', 12 ,273, 70 , 14,'PNG', ''); // $pdf -> SetY(272); // $pdf -> SetX(18); // $pdf -> SetFont('Arial','',7); // $pdf->Cell(15,0,convertirLetras($codigodeBarra.$ultimoDigito)); /*================================ = PAGINA 2 = ================================*/ $pdf->Image('../../../vistas/img/afip/factura.jpg' , 5,NULL, 200 , 245,'JPG', ''); $pagina2=5; //ENCABEZADO FACTURA /*============================================= CENTRO DE LA FACTURA =============================================*/ //POSICION ORIGINAL DUPLICADO TRIPLICADO $pdf -> SetY(11+$pagina2); $pdf -> SetX(87); $pdf -> SetFont('Arial','B',16); $pdf->Cell(0,0,'DUPLICADO'); //POSICION DEL TIPO DE FACTURA $pdf -> SetY(26+$pagina2); $pdf -> SetX(98); $pdf -> SetFont('Arial','B',35); $pdf->Cell(0,0,'C'); //POSICION DEL NRO COMPROBANTE $pdf -> SetY(35+$pagina2); $pdf -> SetX(96); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,$codFactura); /*============================================= IZQUIERDA DE LA FACTURA =============================================*/ //POSICION DEL NOMBRE FICTICIO $pdf -> SetY(22+$pagina2); $pdf -> SetX(12); $pdf -> SetFont('Arial','B',16); $pdf->Cell(0,0,'COLEGIO DE ESCRIBANOS'); $pdf -> SetY(28+$pagina2); $pdf -> SetX(24); $pdf->Cell(0,0,'DE LA PROVINCIA'); $pdf -> SetY(34+$pagina2); $pdf -> SetX(32); $pdf->Cell(0,0,'DE FORMOSA'); //RAZON SOCIAL $pdf -> SetY(45+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Razón Social:')); $pdf -> SetX(27); $pdf -> SetFont('Arial','',7); $pdf->Cell(0,0,convertirLetras('COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA')); //DOMICILIO COMERCIAL $pdf -> SetY(49+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Domicilio Comercial:')); $pdf -> SetX(35); $pdf -> SetFont('Arial','',7); $pdf->Cell(0,0,convertirLetras('PADRE PATINO 812 - FORMOSA ')); //TELEFONO $pdf -> SetY(53+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Telefono:')); $pdf -> SetX(22); $pdf -> SetFont('Arial','',8); $pdf->Cell(0,0,convertirLetras('3704-429330 // 3704-431837')); //CONDICION FRENTE AL IVA $pdf -> SetY(57+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); $pdf -> SetX(40); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Iva Exento')); /*============================================= DERECHA DE LA FACTURA =============================================*/ //POSICION DE LA PALABRA FACTURA $pdf -> SetY(22+$pagina2); $pdf -> SetX(122); $pdf -> SetFont('Arial','B',18); $pdf->Cell(0,0,$tituloFactura); //POSICION DE PUNTO DE VENTA Y NRO DE COMPROBANTE $pdf -> SetY(33+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Punto de Venta:')); $pdf -> SetY(33+$pagina2); $pdf -> SetX(145); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($codigo[0])); $pdf -> SetY(33+$pagina2); $pdf -> SetX(160); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Comp. Nro: ')); $pdf -> SetY(33+$pagina2); $pdf -> SetX(180); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($codigo[1])); //FECHA DE EMISION $pdf -> SetY(38+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Fecha de Emisión:')); $pdf -> SetY(38+$pagina2); $pdf -> SetX(148); $pdf -> SetFont('Arial','B',9); $pdf->Cell(0,0,convertirLetras($fecha)); //CUIT $pdf -> SetY(46+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras($descripcionTipoDoc)); $pdf -> SetY(46+$pagina2); $pdf -> SetX(130); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('30584197680')); //INGRESOS BRUTOS $pdf -> SetY(50+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Ingresos Brutos:')); $pdf -> SetY(50+$pagina2); $pdf -> SetX(146); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('30584197680')); //INICIO DE ACTIVIDADES $pdf -> SetY(54+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',8); $pdf->Cell(0,0,convertirLetras('Fecha de Inicio de Actividades:')); $pdf -> SetY(54+$pagina2); $pdf -> SetX(165); $pdf -> SetFont('Arial','',9); $pdf->Cell(0,0,convertirLetras('07/10/1979')); /*============================================= CAJA CLIENTE =============================================*/ //CUIT $pdf -> SetY(68+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras($descripcionTipoDoc)); $pdf -> SetY(68+$pagina2); $pdf -> SetX(18); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,$ventas["documento"]); //POSICION DEL NOMBRE DEL CLIENTE $pdf -> SetY(68+$pagina2); $pdf -> SetX(50); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Apellido y Nombre / Razón Social:')); $pdf -> SetY(68+$pagina2); $pdf -> SetX(110); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($ventas["nombre"])); //TIPO DE IVA $pdf -> SetY(76+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); //primera linea if ($ventas["id_cliente"]!=0){ if(strlen($tipoIva)<=37){ $pdf -> SetY(81); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($tipoIva)); }else{ $dividirPalabra =explode('-',$tipoIva); $pdf -> SetY(81); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($dividirPalabra[0])); $pdf -> SetY(85); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($dividirPalabra[1])); } }else{ $pdf -> SetY(81); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras("CONSUMIDOR FINAL")); } //CONDICION DE VENTA $pdf -> SetY(84+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Condición de Venta:')); $pdf -> SetY(84+$pagina2); $pdf -> SetX(45); $pdf -> SetFont('Arial','',10); if ($ventas['referenciapago']=="EFECTIVO"){ $pdf->Cell(0,0,'Contado'); }else{ $pdf->Cell(0,0,$ventas['metodo_pago']); } //DOMICILIO $pdf -> SetY(76+$pagina2); $pdf -> SetX(120); $pdf -> SetFont('Arial','B',10); $pdf->Cell(0,0,convertirLetras('Domicilio:')); $pdf -> SetY(76+$pagina2); $pdf -> SetX(138); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($escribanos['direccion'])); $pdf -> SetY(80+$pagina2); $pdf -> SetX(138); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras($escribanos['localidad'])); /*============================================= ENCABEZADO =============================================*/ //PRODUCTO $pdf -> SetY(93+$pagina2); $pdf -> SetX(50); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Producto / Servicio')); //CANTIDAD $pdf -> SetY(93+$pagina2); $pdf -> SetX(121); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Cantidad')); //PRECIO UNITARIO $pdf -> SetY(93+$pagina2); $pdf -> SetX(143); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Precio Unit.')); //PRECIO TOTAL $pdf -> SetY(93+$pagina2); $pdf -> SetX(176); $pdf -> SetFont('Arial','',10); $pdf->Cell(0,0,convertirLetras('Subtotal')); /*============================================= PRODUCTOS =============================================*/ $renglon1=101; $espaciorenglon=0; $veces=0; //TOMO LOS PRODUCTOS EN UN ARRAY $productosVentas = json_decode($ventas["productos"], true); foreach ($productosVentas as $key => $rsCtaART) { $pdf -> SetFont('Arial','',10); $pdf -> SetY($renglon1+($espaciorenglon*$veces)+$pagina2); $pdf -> SetX(8); $miItem=convertirLetras($rsCtaART['descripcion']); if ($rsCtaART['folio1']!=1){ $miItem.=' del '.$rsCtaART['folio1'].' al '.$rsCtaART['folio2']; } $pdf->Cell(0,0,$miItem,0,0,'L'); $pdf -> SetX(110); $pdf->Cell(28,0,$rsCtaART['cantidad'],0,0,'R'); $pdf -> SetX(147+$pagina2); $pdf->Cell(12,0,$rsCtaART['precio'],0,0,'R'); $subtotal=$rsCtaART['precio']*$rsCtaART['cantidad']; $pdf -> SetX($parametros['formatoitem1posXtotal']); $pdf->Cell(0,0,$subtotal,0,0,'R'); $espaciorenglon=$parametros['formatoitem1posY2']; $veces++; } /*============================================= CAJA DE SUBTOTALES =============================================*/ //SUBTOTAL $pdf -> SetY(207+$pagina2); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Subtotal: $'),0,0,'R'); $pdf -> SetY(207+$pagina2); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); //OTROS ATRIBUTOS $pdf -> SetY(217+$pagina2); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Importe Otros Tributos: $'),0,0,'R'); $pdf -> SetY(217+$pagina2); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,convertirLetras('0,00'),0,0,'R'); //OTROS ATRIBUTOS $pdf -> SetY(227+$pagina2); $pdf -> SetX(150); $pdf -> SetFont('Arial','B',10); $pdf->Cell(10,0,convertirLetras('Importe Total: $'),0,0,'R'); $pdf -> SetY(227+$pagina2); $pdf -> SetX(190); $pdf -> SetFont('Arial','B',10); $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); /*============================================= CAJA DEL NOMBRE =============================================*/ //NOMBRE $pdf -> SetY(245+$pagina2); $pdf -> SetX(10); $pdf -> SetFont('Arial','BI',8); $pdf->Cell(0,0,convertirLetras('"COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA."')); $pdf -> SetX(100); $pdf->Cell(0,0,convertirLetras('"Los trámites de apostilla tienen una demora de 24 a 48 hs. como mínimo."')); /*============================================= PIE DE PAGINA =============================================*/ //PAGINACION $pdf -> SetY(255+$pagina2); $pdf -> SetX(90); $pdf -> SetFont('Arial','B',12); $pdf->Cell(0,0,convertirLetras('Pág. 2/3')); //CAE $pdf -> SetY(255+$pagina2); $pdf -> SetX(155); $pdf -> SetFont('Arial','B',12); $pdf->Cell(15,0,convertirLetras('CAE Nro.:'),0,0,'R'); $pdf -> SetY(255+$pagina2); $pdf -> SetX(170); $pdf -> SetFont('Arial','',12); $pdf->Cell(15,0,convertirLetras($ventas['cae']),0,0,'L'); //FECHA CAE $pdf -> SetY(260+$pagina2); $pdf -> SetX(155); $pdf -> SetFont('Arial','B',12); $pdf->Cell(15,0,convertirLetras('Fecha de Vto. de CAE:'),0,0,'R'); $pdf -> SetY(260+$pagina2); $pdf -> SetX(170); $pdf -> SetFont('Arial','',12); $pdf->Cell(15,0,convertirLetras($ventas['fecha_cae']),0,0,'L'); //IMAGEN $pdf->Image('../../../vistas/img/afip/afip.jpg' , 5 ,252+$pagina2, 45 , 17,'JPG', ''); $pdf -> SetY(270+$pagina2); $pdf -> SetX(6); $pdf -> SetFont('Arial','BI',5); $pdf->Cell(15,0,convertirLetras('Esta Administración Federal no se responsabiliza por los datos ingresados en el detalle de la operación'),0,0,'L'); //IMAGEN // $pdf->Image('../../../vistas/img/afip/codigobarra.jpg' , 12 ,273+$pagina2, 70 , 14,'JPG', ''); $pdf->Image('../../codigos/'.$codigodeBarra.$ultimoDigito.'.png', 12 ,273+$pagina2, 70 , 14,'PNG', ''); /*===== End of PAGINA 2 ======*/ /*================================ = PAGINA 3 = ================================*/ // $pdf->Image('../../../vistas/img/afip/factura.jpg' , 5,NULL, 200 , 245,'JPG', ''); // $pagina2=5; // //ENCABEZADO FACTURA // /*============================================= // CENTRO DE LA FACTURA // =============================================*/ // //POSICION ORIGINAL DUPLICADO TRIPLICADO // $pdf -> SetY(11+$pagina2); // $pdf -> SetX(87); // $pdf -> SetFont('Arial','B',16); // $pdf->Cell(0,0,'TRIPLICADO'); // //POSICION DEL TIPO DE FACTURA // $pdf -> SetY(26+$pagina2); // $pdf -> SetX(98); // $pdf -> SetFont('Arial','B',35); // $pdf->Cell(0,0,'C'); // //POSICION DEL NRO COMPROBANTE // $pdf -> SetY(35+$pagina2); // $pdf -> SetX(96); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,$codFactura); // /*============================================= // IZQUIERDA DE LA FACTURA // =============================================*/ // //POSICION DEL NOMBRE FICTICIO // $pdf -> SetY(22+$pagina2); // $pdf -> SetX(12); // $pdf -> SetFont('Arial','B',16); // $pdf->Cell(0,0,'COLEGIO DE ESCRIBANOS'); // $pdf -> SetY(28+$pagina2); // $pdf -> SetX(24); // $pdf->Cell(0,0,'DE LA PROVINCIA'); // $pdf -> SetY(34+$pagina2); // $pdf -> SetX(32); // $pdf->Cell(0,0,'DE FORMOSA'); // //RAZON SOCIAL // $pdf -> SetY(45+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Razón Social:')); // $pdf -> SetX(27); // $pdf -> SetFont('Arial','',7); // $pdf->Cell(0,0,convertirLetras('COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA')); // //DOMICILIO COMERCIAL // $pdf -> SetY(49+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Domicilio Comercial:')); // $pdf -> SetX(35); // $pdf -> SetFont('Arial','',7); // $pdf->Cell(0,0,convertirLetras('PADRE PATINO 812 - FORMOSA ')); // //CONDICION FRENTE AL IVA // $pdf -> SetY(53+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); // $pdf -> SetX(40); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Iva Exento')); // /*============================================= // DERECHA DE LA FACTURA // =============================================*/ // //POSICION DE LA PALABRA FACTURA // $pdf -> SetY(22+$pagina2); // $pdf -> SetX(122); // $pdf -> SetFont('Arial','B',18); // $pdf->Cell(0,0,$tituloFactura); // //POSICION DE PUNTO DE VENTA Y NRO DE COMPROBANTE // $pdf -> SetY(33+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Punto de Venta:')); // $pdf -> SetY(33+$pagina2); // $pdf -> SetX(145); // $pdf -> SetFont('Arial','B',9); // $pdf->Cell(0,0,convertirLetras($codigo[0])); // $pdf -> SetY(33+$pagina2); // $pdf -> SetX(160); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Comp. Nro: ')); // $pdf -> SetY(33+$pagina2); // $pdf -> SetX(180); // $pdf -> SetFont('Arial','B',9); // $pdf->Cell(0,0,convertirLetras($codigo[1])); // //FECHA DE EMISION // $pdf -> SetY(38+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Fecha de Emisión:')); // $pdf -> SetY(38+$pagina2); // $pdf -> SetX(148); // $pdf -> SetFont('Arial','B',9); // $pdf->Cell(0,0,convertirLetras($fecha)); // //CUIT // $pdf -> SetY(46+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('CUIT:')); // $pdf -> SetY(46+$pagina2); // $pdf -> SetX(130); // $pdf -> SetFont('Arial','',9); // $pdf->Cell(0,0,convertirLetras('30584197680')); // //INGRESOS BRUTOS // $pdf -> SetY(50+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Ingresos Brutos:')); // $pdf -> SetY(50+$pagina2); // $pdf -> SetX(146); // $pdf -> SetFont('Arial','',9); // $pdf->Cell(0,0,convertirLetras('30584197680')); // //INICIO DE ACTIVIDADES // $pdf -> SetY(54+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',8); // $pdf->Cell(0,0,convertirLetras('Fecha de Inicio de Actividades:')); // $pdf -> SetY(54+$pagina2); // $pdf -> SetX(165); // $pdf -> SetFont('Arial','',9); // $pdf->Cell(0,0,convertirLetras('07/10/1979')); // /*============================================= // CAJA CLIENTE // =============================================*/ // //CUIT // $pdf -> SetY(68+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(0,0,convertirLetras('CUIT:')); // $pdf -> SetY(68+$pagina2); // $pdf -> SetX(18); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,$ventas["documento"]); // //POSICION DEL NOMBRE DEL CLIENTE // $pdf -> SetY(68+$pagina2); // $pdf -> SetX(50); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(0,0,convertirLetras('Apellido y Nombre / Razón Social:')); // $pdf -> SetY(68+$pagina2); // $pdf -> SetX(110); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($ventas["nombre"])); // //TIPO DE IVA // $pdf -> SetY(76+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(0,0,convertirLetras('Condición frente al IVA:')); // //primera linea // if(strlen($tipoIva)<=37){ // $pdf -> SetY(76+$pagina2); // $pdf -> SetX(50); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($tipoIva)); // }else{ // $dividirPalabra =explode('-',$tipoIva); // $pdf -> SetY(76+$pagina2); // $pdf -> SetX(50); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($dividirPalabra[0])); // $pdf -> SetY(80+$pagina2); // $pdf -> SetX(50); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($dividirPalabra[1])); // } // //CONDICION DE VENTA // $pdf -> SetY(84+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(0,0,convertirLetras('Condición de Venta:')); // $pdf -> SetY(84+$pagina2); // $pdf -> SetX(45); // $pdf -> SetFont('Arial','',10); // if ($ventas['referenciapago']=="EFECTIVO"){ // $pdf->Cell(0,0,'Contado'); // }else{ // $pdf->Cell(0,0,$ventas['metodo_pago']); // } // //DOMICILIO // $pdf -> SetY(76+$pagina2); // $pdf -> SetX(120); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(0,0,convertirLetras('Domicilio:')); // $pdf -> SetY(76+$pagina2); // $pdf -> SetX(138); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($escribanos['direccion'])); // $pdf -> SetY(80+$pagina2); // $pdf -> SetX(138); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras($escribanos['localidad'])); // /*============================================= // ENCABEZADO // =============================================*/ // //PRODUCTO // $pdf -> SetY(93+$pagina2); // $pdf -> SetX(50); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras('Producto / Servicio')); // //CANTIDAD // $pdf -> SetY(93+$pagina2); // $pdf -> SetX(121); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras('Cantidad')); // //PRECIO UNITARIO // $pdf -> SetY(93+$pagina2); // $pdf -> SetX(143); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras('Precio Unit.')); // //PRECIO TOTAL // $pdf -> SetY(93+$pagina2); // $pdf -> SetX(176); // $pdf -> SetFont('Arial','',10); // $pdf->Cell(0,0,convertirLetras('Subtotal')); // /*============================================= // PRODUCTOS // =============================================*/ // $renglon1=101; // $espaciorenglon=0; // $veces=0; // //TOMO LOS PRODUCTOS EN UN ARRAY // $productosVentas = json_decode($ventas["productos"], true); // foreach ($productosVentas as $key => $rsCtaART) { // $pdf -> SetFont('Arial','',10); // $pdf -> SetY($renglon1+($espaciorenglon*$veces)+$pagina2); // $pdf -> SetX(8); // $miItem=convertirLetras($rsCtaART['descripcion']); // if ($rsCtaART['folio1']!=1){ // $miItem.=' del '.$rsCtaART['folio1'].' al '.$rsCtaART['folio2']; // } // $pdf->Cell(0,0,$miItem,0,0,'L'); // $pdf -> SetX(110); // $pdf->Cell(28,0,$rsCtaART['cantidad'],0,0,'R'); // $pdf -> SetX(147+$pagina2); // $pdf->Cell(12,0,$rsCtaART['precio'],0,0,'R'); // $subtotal=$rsCtaART['precio']*$rsCtaART['cantidad']; // $pdf -> SetX($parametros['formatoitem1posXtotal']); // $pdf->Cell(0,0,$subtotal,0,0,'R'); // $espaciorenglon=$parametros['formatoitem1posY2']; // $veces++; // } // /*============================================= // CAJA DE SUBTOTALES // =============================================*/ // //SUBTOTAL // $pdf -> SetY(207+$pagina2); // $pdf -> SetX(150); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(10,0,convertirLetras('Subtotal: $'),0,0,'R'); // $pdf -> SetY(207+$pagina2); // $pdf -> SetX(190); // $pdf -> SetFont('Arial','B',10); // $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); // //OTROS ATRIBUTOS // $pdf -> SetY(217+$pagina2); // $pdf -> SetX(150); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(10,0,convertirLetras('Importe Otros Tributos: $'),0,0,'R'); // $pdf -> SetY(217+$pagina2); // $pdf -> SetX(190); // $pdf -> SetFont('Arial','B',10); // $pdf -> Cell(10,0,convertirLetras('0,00'),0,0,'R'); // //OTROS ATRIBUTOS // $pdf -> SetY(227+$pagina2); // $pdf -> SetX(150); // $pdf -> SetFont('Arial','B',10); // $pdf->Cell(10,0,convertirLetras('Importe Total: $'),0,0,'R'); // $pdf -> SetY(227+$pagina2); // $pdf -> SetX(190); // $pdf -> SetFont('Arial','B',10); // $pdf -> Cell(10,0,number_format($ventas['total'], 2, ',', ''),0,0,'R'); // /*============================================= // CAJA DEL NOMBRE // =============================================*/ // //NOMBRE // $pdf -> SetY(245+$pagina2); // $pdf -> SetX(35); // $pdf -> SetFont('Arial','I',14); // $pdf->Cell(0,0,convertirLetras('"COLEGIO DE ESCRIBANOS DE LA PROVINCIA DE FORMOSA"')); // /*============================================= // PIE DE PAGINA // =============================================*/ // //PAGINACION // $pdf -> SetY(255+$pagina2); // $pdf -> SetX(90); // $pdf -> SetFont('Arial','B',12); // $pdf->Cell(0,0,convertirLetras('Pág. 3/3')); // //CAE // $pdf -> SetY(255+$pagina2); // $pdf -> SetX(155); // $pdf -> SetFont('Arial','B',12); // $pdf->Cell(15,0,convertirLetras('CAE Nro.:'),0,0,'R'); // $pdf -> SetY(255+$pagina2); // $pdf -> SetX(170); // $pdf -> SetFont('Arial','',12); // $pdf->Cell(15,0,convertirLetras($ventas['cae']),0,0,'L'); // //FECHA CAE // $pdf -> SetY(260+$pagina2); // $pdf -> SetX(155); // $pdf -> SetFont('Arial','B',12); // $pdf->Cell(15,0,convertirLetras('Fecha de Vto. de CAE:'),0,0,'R'); // $pdf -> SetY(260+$pagina2); // $pdf -> SetX(170); // $pdf -> SetFont('Arial','',12); // $pdf->Cell(15,0,convertirLetras($ventas['fecha_cae']),0,0,'L'); // //IMAGEN // $pdf->Image('../../../vistas/img/afip/afip.jpg' , 5 ,252+$pagina2, 45 , 17,'JPG', ''); // $pdf -> SetY(270+$pagina2); // $pdf -> SetX(6); // $pdf -> SetFont('Arial','BI',5); // $pdf->Cell(15,0,convertirLetras('Esta Administración Federal no se responsabiliza por los datos ingresados en el detalle de la operación'),0,0,'L'); // //IMAGEN // $pdf->Image('../../../vistas/img/afip/codigobarra.jpg' , 12 ,273+$pagina2, 70 , 14,'JPG', ''); // $pdf->Image('../../codigos/'.$codigodeBarra.$ultimoDigito.'.png', 12 ,273+$pagina2, 70 , 14,'PNG', ''); // $pdf -> SetY(272+4.5); // $pdf -> SetX(18); // $pdf -> SetFont('Arial','',7); // $pdf->Cell(15,0,convertirLetras($codigodeBarra.$ultimoDigito)); /*===== End of PAGINA 2 ======*/ $pdf->AutoPrint(); $pdf->Output(); ?><file_sep>/controladores/escribanos.controlador.php <?php class ControladorEscribanos{ /*============================================= MOSTRAR ESCRIBANOS =============================================*/ static public function ctrMostrarEscribanos($item, $valor){ $tabla = "escribanos"; $respuesta = ModeloEscribanos::mdlMostrarEscribanos($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarEscribanosInhabilitados(){ $tabla = "escribanos"; $respuesta = ModeloEscribanos::mdlMostrarEscribanosInhabilitados($tabla); return $respuesta; } static public function ctrMostrarInhabilitado(){ $tabla = "escribanos"; $respuesta = ModeloEscribanos::mdlMostrarInhabilitado($tabla); return $respuesta; } static public function ctrMostrarEstado($item,$valor){ $tabla = "escribanos"; $respuesta = ModeloEscribanos::mdlMostrarEstado($tabla,$item,$valor); return $respuesta; } /*============================================= CREAR ESCRIBANOS =============================================*/ static public function ctrCrearEscribano(){ if(isset($_POST["nuevoEscribano"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoEscribano"]) && preg_match('/^[0-9]+$/', $_POST["nuevoDocumento"]) && preg_match('/^[#\.\-a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevaDireccion"])){ $cuit = explode("-",$_POST["nuevoCuit"]); $tabla = "escribanos"; $datos = array("nombre"=>strtoupper($_POST["nuevoEscribano"]), "documento"=>$_POST["nuevoDocumento"], "id_iva"=>$_POST["nuevaIdIva"], "cuit"=>$cuit[0].$cuit[1].$cuit[2], "direccion"=>strtoupper($_POST["nuevaDireccion"]), "localidad"=>strtoupper($_POST["nuevaLocalidad"]), "telefono"=>$_POST["nuevoTelefono"], "email"=>strtoupper($_POST["nuevoEmail"]), "id_categoria"=>$_POST["nuevaCategoriaEscribano"], "id_escribano_relacionado"=>$_POST["nuevoEscribanoRelacionado"], "id_osde"=>$_POST["nuevoCategoriaOsde"]); $respuesta = ModeloEscribanos::mdlIngresarEscribano($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El escribano ha sido guardado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "escribanos"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡El escribano no puede ir vacío o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "escribanos"; } }) </script>'; } } } static public function ctrbKEscribano($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "direccion":"'.$respuesta[2].'", "localidad":"'.$respuesta[3].'", "telefono":"'.$respuesta[4].'", "documento":"'.$respuesta[5].'", "cuit":"'.$respuesta[6].'", "email":"'.$respuesta[7].'", "id_categoria":"'.$respuesta[8].'", "id_escribano_relacionado":"'.$respuesta[9].'", "id_osde":"'.$respuesta[10].'", "ultimolibrocomprado":"'.$respuesta[11].'", "ultimolibrodevuelto":"'.$respuesta[12].'", "obs":"'.$respuesta[13].'", "activo":"'.$respuesta[14].'", "obsdel":"'.$respuesta[15].'", "fechacreacion":"'.$respuesta[16].'"}]'; $datos = array("tabla"=>"escribanos", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloEscribanos::mdlbKEscribano($tabla, $datos); } /*============================================= ELIMINAR ESCRIBANO =============================================*/ static public function ctrEliminarEscribano(){ if(isset($_GET["idEscribano"])){ $tabla ="escribanos"; $datos = $_GET["idEscribano"]; $valor = $_GET["idEscribano"]; #ENVIAMOS LOS DATOS ControladorEscribanos::ctrbKEscribano($tabla, "id", $valor, "ELIMINAR"); $respuesta = ModeloEscribanos::mdlEliminarEscribano($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Escribano ha sido borrado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar", closeOnConfirm: false }).then(function(result){ if (result.value) { window.location = "escribanos"; } }) </script>'; } } } /*============================================= EDITAR CLIENTE =============================================*/ static public function ctrEditarEscribano(){ if(isset($_POST["editarEscribano"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarEscribano"]) && preg_match('/^[0-9 ]+$/', $_POST["editarDocumento"]) && preg_match('/^[^0-9][a-zA-Z0-9_-]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $_POST["editarEmail"])){ $tabla = "escribanos"; $cuit = explode("-",$_POST["editarCuit"]); #ENVIAMOS LOS DATOS ControladorEscribanos::ctrbKEscribano($tabla, "id", $_POST["idEscribano"], "UPDATE"); $datos = array( "id"=>$_POST["idEscribano"], "nombre"=>strtoupper($_POST["editarEscribano"]), "documento"=>$_POST["editarDocumento"], "id_tipo_iva"=>$_POST["editarTipoIva"], "cuit"=>$cuit[0].$cuit[1].$cuit[2], "direccion"=>strtoupper($_POST["editarDireccion"]), "localidad"=>strtoupper($_POST["editarLocalidad"]), "telefono"=>$_POST["editarTelefono"], "email"=>strtoupper($_POST["editarEmail"]), "id_categoria"=>$_POST["editarCategoriaEscribano"], "id_escribano_relacionado"=>$_POST["editarEscribanoRelacionado"], "id_osde"=>$_POST["editarCategoriaOsde"], "matricula_ws"=>$_POST["editarMatricula"]); $respuesta = ModeloEscribanos::mdlEditarEscribano($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Escribano ha sido cambiado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "escribanos"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡El cliente no puede ir vacío o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "escribanos"; } }) </script>'; } } } }<file_sep>/modelos/rubros.modelo.php <?php require_once "conexion.php"; class ModeloRubros{ /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlIngresarRubro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre,movimiento,mensual,obs) VALUES (:nombre,:movimiento,:mensual,:obs)"); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":movimiento", $datos['movimiento'], PDO::PARAM_INT); $stmt->bindParam(":mensual", $datos['mensual'], PDO::PARAM_INT); $stmt->bindParam(":obs", $datos['obs'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function mdlMostrarRubros($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= EDITAR RUBRO =============================================*/ static public function mdlEditarRubro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, movimiento = :movimiento,mensual =:mensual,obs = :obs WHERE id = :id"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":movimiento", $datos['movimiento'], PDO::PARAM_INT); $stmt->bindParam(":mensual", $datos['mensual'], PDO::PARAM_INT); $stmt->bindParam(":obs", $datos['obs'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR CATEGORIA =============================================*/ static public function mdlBorrarRubro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } static public function mdlbKRubro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/vistas/modulos/buscar-venta-repuestos.php <div class="content-wrapper"> <section class="content-header"> <h1> Buscar x Articulo </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Buscar x Articulo</li> </ol> </section> <section class="content"> <div class="box cajaPrincipal"> <div class="box-header with-border"> <div class="col-lg-1"> <strong> <p style="font-size: 22px">Producto:</p> </strong> </div> <div class="col-lg-3"> <?php $item = null; $valor = null; $order ="nombre"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor,$order); ?> <select name="productos" id="productos" class="form-control input-lg" > <option value="1">SIN REFERENCIA</option> <?php foreach ($productos as $key => $value) { echo '<option value="'.$value['id'].'">'.$value['nombre'].'</option>'; } ?> </select> </div> <div class="col-lg-3"> <button type="button" class="btn btn-primary" id="btn-bsqVentaProducto">Buscar</button> </div> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th>#</th> <th>Fecha</th> <th>Codigo</th> <th>Cliente</th> <th>Id</th> <th>Detalle</th> <th>Importe</th> </tr> </thead> <tbody> <?php if(isset($_GET["fechaInicial"])){ $fechaInicial = $_GET["fechaInicial"]; $fechaFinal = $_GET["fechaFinal"]; }else{ $fechaInicial = null; $fechaFinal = null; } //DATOS DE TODAS LAS VENTAS DEL MES $respuesta = ControladorVentas::ctrRangoFechasVentas($fechaInicial, $fechaFinal); $tablaVendido=''; $contadorTabla=1; // inicio el recorrido foreach ($respuesta as $key => $value) { $fecha = $value["fecha"]; $nrofc = $value["nrofc"]; $detalle =$value['detalle']; // valores para MostrarClientes $itemCliente = "id"; $valorCliente = $value["id_cliente"]; $respuestaCliente = ControladorClientes::ctrMostrarClientes($itemCliente, $valorCliente); // nombre del cliente $cliente = $respuestaCliente["nombre"]; //tomo los datos de los items $listaProducto= json_decode($value["productos"],true); foreach ($listaProducto as $key2 => $value2) { // TRAER EL STOCK $tablaProductos = "productos"; if(isset($_GET["idProducto"])){ if($_GET["idProducto"]==$value2["id"]){ $tablaVendido = $tablaVendido . '<tr> <td>'.$contadorTabla.'</td> <td>'.$fecha.'</td> <td>'.$nrofc.'</td> <td>'.$cliente.'</td> <td>'.$value2['id'].'</td> <td>'.$value2['descripcion'].'</td> <td>'.$value2['total'].'</td> </tr>'; $contadorTabla++; } } } } echo $tablaVendido; ?> </tbody> </table> </div> </div> </section> </div> <file_sep>/ajax/tablaProductos.ajax.php <?php require_once "../controladores/productos.controlador.php"; require_once "../modelos/productos.modelo.php"; require_once "../controladores/comprobantes.controlador.php"; require_once "../modelos/comprobantes.modelo.php"; class TablaProductos{ /*============================================= MOSTRAR LA TABLA DE PRODUCTOS =============================================*/ public $tipoCliente; public $categoria; public function mostrarTablaProductos(){ $valorTipoCliente = $this->tipoCliente; $item = null; $valor = null; $orden = "nombre"; $productos = ControladorProductos::ctrMostrarProductos($item, $valor, $orden); $datosJson = '{ "data": ['; for($i = 0; $i < count($productos); $i++){ switch ($valorTipoCliente) { case 'casual': if($productos[$i]["vista_consumidor_final"]==1){ $botones = "<button class='btn btn-primary btnSeleccionarProducto' idProducto='".$productos[$i]["id"]."' idNroComprobante='".$productos[$i]["nrocomprobante"]."' cantVentaProducto='".$productos[$i]["cantventa"]."' productoNombre='".$productos[$i]["nombre"]."' precioVenta='".$productos[$i]["importe"]."'>Seleccionar</button>"; $datosJson .='[ "'.($i+1).'", "'.$productos[$i]['nombre'].'", "'.$productos[$i]['importe'].'", "'.$botones.'" ],'; } break; case 'consumidorfinal': if($productos[$i]["vista_consumidor_final"]==1){ $botones = "<button class='btn btn-primary btnSeleccionarProducto' idProducto='".$productos[$i]["id"]."' idNroComprobante='".$productos[$i]["nrocomprobante"]."' cantVentaProducto='".$productos[$i]["cantventa"]."' productoNombre='".$productos[$i]["nombre"]."' precioVenta='".$productos[$i]["importe"]."'>Seleccionar</button>"; $datosJson .='[ "'.($i+1).'", "'.$productos[$i]['nombre'].'", "'.$productos[$i]['importe'].'", "'.$botones.'" ],'; } break; case 'clientes': if($productos[$i]["vista_clientes"]==1){ $botones = "<button class='btn btn-primary btnSeleccionarProducto' idProducto='".$productos[$i]["id"]."' idNroComprobante='".$productos[$i]["nrocomprobante"]."' cantVentaProducto='".$productos[$i]["cantventa"]."' productoNombre='".$productos[$i]["nombre"]."' precioVenta='".$productos[$i]["importe"]."'>Seleccionar</button>"; $datosJson .='[ "'.($i+1).'", "'.$productos[$i]['nombre'].'", "'.$productos[$i]['importe'].'", "'.$botones.'" ],'; } break; case 'delegacion': $botones = "<button class='btn btn-primary btnSeleccionarProducto' idProducto='".$productos[$i]["id"]."' idNroComprobante='".$productos[$i]["nrocomprobante"]."' cantVentaProducto='".$productos[$i]["cantventa"]."' productoNombre='".$productos[$i]["nombre"]."' precioVenta='".$productos[$i]["importe"]."'>Seleccionar</button>"; $datosJson .='[ "'.($i+1).'", "'.$productos[$i]['nombre'].'", "'.$productos[$i]['importe'].'", "'.$botones.'" ],'; break; case 'escribanos': if($productos[$i]["vista_escribanos"]==1){ //si la vista esta aprobada para todos los escribanos if($productos[$i]["vista_categoria"]!=$this->categoria){ $botones = "<button class='btn btn-primary btnSeleccionarProducto' idProducto='".$productos[$i]["id"]."' idNroComprobante='".$productos[$i]["nrocomprobante"]."' cantVentaProducto='".$productos[$i]["cantventa"]."' productoNombre='".$productos[$i]["nombre"]."' precioVenta='".$productos[$i]["importe"]."'>Seleccionar</button>"; $datosJson .='[ "'.($i+1).'", "'.$productos[$i]['nombre'].'", "'.$productos[$i]['importe'].'", "'.$botones.'" ],'; } } break; } } $datosJson = substr($datosJson, 0, -1); $datosJson .= '] }'; echo $datosJson; } } /*============================================= ACTIVAR LA TABLA DE PRODUCTOS =============================================*/ $activarProductos = new TablaProductos(); $activarProductos -> tipoCliente = $_POST["tipoCliente"]; $activarProductos -> categoria = $_POST["categoria"]; $activarProductos -> mostrarTablaProductos(); <file_sep>/modelos/modificaciones.modelo.php <?php require_once "conexion.php"; class ModeloModificaciones{ /*============================================= MOSTRAR MODIFICACIONES =============================================*/ static public function mdlMostrarCategorias($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR MODIFICACION =============================================*/ static public function mdlIngresarModificaciones($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,nombre) VALUES (:fecha,:nombre)"); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/ajax/remitos.ajax.php <?php require_once "../controladores/remitos.controlador.php"; require_once "../modelos/remitos.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; class AjaxRemito{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxVerVenta(){ $item = "id"; $valor = $_POST["idVenta"]; $respuesta = ControladorRemitos::ctrMostrarRemitos($item, $valor); echo json_encode($respuesta); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerArt(){ $item = "id"; $valor = $_POST["idVentaArt"]; $respuesta = ControladorRemitos::ctrMostrarRemitos($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } /*============================================= TRAER LA ULTIMA VENTA =============================================*/ public function ajaxUltimoRemito(){ $respuesta = ControladorRemitos::ctrUltimoIdRemito(); echo json_encode($respuesta); } /*============================================= TRAER LA ULTIMA VENTA =============================================*/ public function ultimoRemito(){ $respuesta = ControladorRemitos::ctrUltimoIdRemito(); echo json_encode($respuesta); } } /*============================================= EDITAR CUENTA CORRIENTE =============================================*/ if(isset($_POST["idVenta"])){ $seleccionarFactura = new AjaxRemito(); $seleccionarFactura -> ajaxVerVenta(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idVentaArt"])){ $verTabla = new AjaxRemito(); $verTabla -> ajaxVerArt(); } if(isset($_POST["ultimoRemito"])){ $nuevaVenta = new AjaxRemito(); $nuevaVenta -> ajaxUltimoRemito(); } <file_sep>/ajax/ctacorriente.colorado.ajax.php <?php require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; class AjaxCtaCorrienteVentaColorado{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxVerVentaColorado(){ $item = "id"; $valor = $_POST["idVenta"]; $respuesta = ControladorEnlace::ctrMostrarVentasColorado($item, $valor); echo json_encode($respuesta); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerEscribano(){ $itemCliente = "id"; $valorCliente = $_POST["idEscribano"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo json_encode($respuestaCliente); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerArtColorado(){ $item = "id"; $valor = $_POST["idVentaArt"]; $respuesta = ControladorEnlace::ctrMostrarVentasColorado($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerPagoDerechoColorado(){ $item = "id"; $valor = $_POST["idPagoDerecho"]; $respuesta = ControladorEnlace::ctrMostrarVentasColorado($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } } /*============================================= EDITAR CUENTA CORRIENTE =============================================*/ if(isset($_POST["idVenta"])){ $seleccionarFactura = new AjaxCtaCorrienteVentaColorado(); $seleccionarFactura -> ajaxVerVentaColorado(); } /*============================================= VER CUENTA CORRIENTE CLIENTE =============================================*/ if(isset($_POST["idEscribano"])){ $verEscribano = new AjaxCtaCorrienteVentaColorado(); $verEscribano -> ajaxVerEscribano(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idVentaArt"])){ $verTabla = new AjaxCtaCorrienteVentaColorado(); $verTabla -> ajaxVerArtColorado(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idPagoDerecho"])){ $verTabla = new AjaxCtaCorrienteVentaColorado(); $verTabla -> ajaxVerPagoDerechoColorado(); } <file_sep>/vistas/modulos/programaviejo.php <?php function conectar_db1(){ //funcion conectar con la base de datos - funcion mas sencilla posible $servidor = 'localhost'; $user='root'; $pass = ''; $db = 'escribano'; // realice todos las variables en una misma funcion para evitar cambios $con = @mysql_connect($servidor,$user,$pass); mysql_set_charset('utf8',$con); @mysql_select_db($db,$con); } function conectar_db2(){ //funcion conectar con la base de datos - funcion mas sencilla posible $servidor = 'localhost'; $user='root'; $pass = ''; $db = 'colorado'; // realice todos las variables en una misma funcion para evitar cambios $con = @mysql_connect($servidor,$user,$pass); mysql_set_charset('utf8',$con); @mysql_select_db($db,$con); } function desconectar(){ @mysql_close(); } ?> <div class="content-wrapper"> <section class="content-header"> <h1> Realizar Copia de Datos </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar Copia de Datos</li> </ol> </section> <section class="content"> <div class="callout callout-info"> <h1>Copiar la tabla de escribanos</h1> <?php conectar_db1(); $ssql ="select * from escribanos where activo=1 order by apellido"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayEscribano[$contador]['idescribano']=$line['idescribano']; $arrayEscribano[$contador]['apellido']=$line['apellido']; $arrayEscribano[$contador]['nombre']=$line['nombre']; $arrayEscribano[$contador]['direccion']=$line['direccion']; $arrayEscribano[$contador]['ciudad']=$line['ciudad']; $arrayEscribano[$contador]['telefono1']=$line['telefono1']; $arrayEscribano[$contador]['dni']=$line['dni']; $arrayEscribano[$contador]['cuit']=$line['cuit']; $arrayEscribano[$contador]['email']=$line['email']; $arrayEscribano[$contador]['categoriaescribano']=$line['categoriaescribano']; $arrayEscribano[$contador]['escribanorelacionado']=$line['escribanorelacionado']; $arrayEscribano[$contador]['categoriaosde']=$line['categoriaosde']; $arrayEscribano[$contador]['ultimolibrocomprado']=$line['ultimolibrocomprado']; $arrayEscribano[$contador]['ultimolibrodevuelto']=$line['ultimolibrodevuelto']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarEscribanos(); $tabla = "escribanos"; foreach($arrayEscribano as $rsEscribano){ # code... $datos = array("id"=>$rsEscribano["idescribano"], // "apellido"=>$rsEscribano["apellido"], "nombre"=>$rsEscribano["apellido"].' '.$rsEscribano["nombre"], "direccion"=>$rsEscribano["direccion"], "localidad"=>$rsEscribano["ciudad"], "telefono"=>$rsEscribano["telefono1"], "documento"=>$rsEscribano["dni"], "cuit"=>$rsEscribano["cuit"], "email"=>$rsEscribano["email"], "id_categoria"=>$rsEscribano["categoriaescribano"], "id_escribano_relacionado"=>$rsEscribano["escribanorelacionado"], "id_osde"=>$rsEscribano["categoriaosde"], "ultimolibrocomprado"=>$rsEscribano["ultimolibrocomprado"], "ultimolibrodevuelto"=>$rsEscribano["ultimolibrodevuelto"]); $respuesta = ModeloProgramaViejo::mdlEscribanos($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsEscribano["apellido"].' '.$rsEscribano["nombre"].'<i class="fa fa-check"></i>'; }else{ echo 'no'; } } desconectar(); ?> </div> <div class="callout callout-warning"> <h1>Copiar la tabla de comprobantes</h1> <?php conectar_db1(); $ssql ="select * from nrocomprobante"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayComprobantes[$contador]['idnrocomprobante']=$line['idnrocomprobante']; $arrayComprobantes[$contador]['nombre']=$line['nombre']; $arrayComprobantes[$contador]['cabezacomprobante']=$line['cabezacomprobante']; $arrayComprobantes[$contador]['nrocomprobante']=$line['nrocomprobante']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarComprobantes(); $tabla = "comprobantes"; foreach($arrayComprobantes as $rsComprobantes){ # code... $datos = array("id"=>$rsComprobantes["idnrocomprobante"], "nombre"=>$rsComprobantes["nombre"], "cabezacomprobante"=>$rsComprobantes["cabezacomprobante"], "numero"=>$rsComprobantes["nrocomprobante"]); $respuesta = ModeloProgramaViejo::mdlComprobantes($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsComprobantes["nombre"].'<i class="fa fa-check"></i>'; }else{ echo 'no'; } } desconectar(); ?> </div> <div class="callout callout-success"> <h1>Copiar la tabla de osde</h1> <?php conectar_db1(); $ssql ="select * from l_osde"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayOsde[$contador]['idosde']=$line['idosde']; $arrayOsde[$contador]['nombre']=$line['nombre']; $arrayOsde[$contador]['importe']=$line['importe']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarOsde(); $tabla = "osde"; foreach($arrayOsde as $rsOsde){ # code... $datos = array("id"=>$rsOsde["idosde"], "nombre"=>$rsOsde["nombre"], "importe"=>$rsOsde["importe"]); $respuesta = ModeloProgramaViejo::mdlOsde($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsOsde["nombre"].'<i class="fa fa-check"></i>'; }else{ echo 'no'; } } desconectar(); ?> </div> <div class="callout callout-danger"> <h1>Copiar la tabla de rubros</h1> <?php conectar_db1(); $ssql ="select * from rubros"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayRubros[$contador]['idrubro']=$line['idrubro']; $arrayRubros[$contador]['nombre']=$line['nombre']; $arrayRubros[$contador]['movimiento']=$line['movimiento']; $arrayRubros[$contador]['mensual']=$line['mensual']; $arrayRubros[$contador]['obs']=$line['obs']; $arrayRubros[$contador]['activo']=$line['activo']; $arrayRubros[$contador]['obsdel']=$line['obsdel']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarRubros(); $tabla = "rubros"; foreach($arrayRubros as $rsRubros){ # code... $datos = array("id"=>$rsRubros["idrubro"], "nombre"=>$rsRubros["nombre"], "movimiento"=>$rsRubros["movimiento"], "mensual"=>$rsRubros["mensual"], "obs"=>$rsRubros["obs"], "activo"=>$rsRubros["activo"], "obsdel"=>$rsRubros["obsdel"]); $respuesta = ModeloProgramaViejo::mdlRubros($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsRubros["nombre"].'<i class="fa fa-check"></i>'; }else{ echo 'no'; } } desconectar(); ?> </div> <div class="callout callout-info"> <h1>Copiar la tabla de productos</h1> <?php conectar_db1(); $ssql ="select * from productos"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayProductos[$contador]['idproducto']=$line['idproducto']; $arrayProductos[$contador]['nombre']=$line['nombre']; $arrayProductos[$contador]['descripcion']=$line['descripcion']; $arrayProductos[$contador]['codigo']=$line['codigo']; $arrayProductos[$contador]['nrocomprobante']=$line['nrocomprobante']; $arrayProductos[$contador]['cantventa']=$line['cantventa']; $arrayProductos[$contador]['idrubro']=$line['idrubro']; $arrayProductos[$contador]['cantminima']=$line['cantminima']; $arrayProductos[$contador]['cuotas']=$line['cuotas']; $arrayProductos[$contador]['importe']=$line['importe']; $arrayProductos[$contador]['ultimonrocompra']=$line['ultimonrocompra']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarProductos(); $tabla = "productos"; foreach($arrayProductos as $rsProductos){ # code... $datos = array("id"=>$rsProductos["idproducto"], "nombre"=>$rsProductos["nombre"], "descripcion"=>$rsProductos["descripcion"], "codigo"=>$rsProductos["codigo"], "nrocomprobante"=>$rsProductos["nrocomprobante"], "cantventa"=>$rsProductos["cantventa"], "idrubro"=>$rsProductos["idrubro"], "cantminima"=>$rsProductos["cantminima"], "cuotas"=>$rsProductos["cuotas"], "importe"=>$rsProductos["importe"], "ultimonrocompra"=>$rsProductos["ultimonrocompra"]); $respuesta = ModeloProgramaViejo::mdlProductos($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsProductos["nombre"].'<i class="fa fa-check"></i>'; }else{ echo 'noa'; } } desconectar(); ?> </div> <div class="callout callout-info"> <h1>Copiar la tabla de VENTAS</h1> <?php conectar_db1(); $ssql ="select * from cta where adeuda >0"; $result=mysql_query($ssql); $numero = mysql_num_rows($result); $contador=0; while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { $arrayCta[$contador]['idcta']=$line['idcta']; $arrayCta[$contador]['fecha']=$line['fecha']; $arrayCta[$contador]['tipo']=$line['tipo']; $arrayCta[$contador]['idescribano']=$line['idescribano']; $arrayCta[$contador]['nrofc']=$line['nrofc']; $arrayCta[$contador]['total']=$line['total']; $arrayCta[$contador]['adeuda']=$line['adeuda']; $contador++; } $respuesta = ModeloProgramaViejo::mdlEliminarVentas(); $tabla = "ventas"; foreach($arrayCta as $rsCta){ # code... // $ssql ="select * from cta_art where idcta =".$rsCta["idcta"]; // $result=mysql_query($ssql); // $numero = mysql_num_rows($result); // $contador=0; // while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { // $arrayCta_art[$contador]['idctaart']=$line['idctaart']; // $arrayCta_art[$contador]['idcta']=$line['idcta']; // $arrayCta_art[$contador]['idproducto']=$line['idproducto']; // $arrayCta_art[$contador]['nombre']=$line['nombre']; // $arrayCta_art[$contador]['cantidad']=$line['cantidad']; // $arrayCta_art[$contador]['importe']=$line['importe']; // $arrayCta_art[$contador]['folio1']=$line['folio1']; // $arrayCta_art[$contador]['folio2']=$line['folio2']; // $contador++; // } $datos = array("fecha"=>$rsCta["fecha"], "tipo"=>$rsCta["tipo"], "productos"=>"", "idescribano"=>$rsCta["idescribano"], "total"=>$rsCta["total"], "adeuda"=>$rsCta["adeuda"]); // [{"id":"20","descripcion":"CUOTA MENSUAL JULIO/2018","idnrocomprobante":"100","cantventaproducto":"1","folio1":"1","folio2":"1","cantidad":"1","precio":"100","total":"100"}] $respuesta = ModeloProgramaViejo::mdlVentas($tabla, $datos); if($respuesta=="ok"){ echo '<br>'.$rsCta["idcta"].' '.$rsCta["adeuda"].'<i class="fa fa-check"></i>'; }else{ echo 'noa'; } } desconectar(); ?> </div> </section> </div> <file_sep>/vistas/modulos/bibliotecas/caja.inicio.php <?php /*============================================ = GENERO LA CAJA = =============================================*/ $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); if(count($caja)==0){ //SI NO EXISTE LA CAJA CREO UNA include("con-caja.incio.php"); } /*=========================================== = SI VIENE DE UN PAGO DE UNA CUOTA = ===========================================*/ $cantHabilitados = 0; if(isset($_GET['tipo'])){ if($_GET['tipo']=="cuota"){ /*============================================= VEO SI SE ENCUENTRA INHABILITADO =============================================*/ $item = "id"; $valor = $_GET['idescribano']; $respuesta = ControladorEscribanos::ctrMostrarEstado($item, $valor); if($respuesta["inhabilitado"]!=0){//SI SE ENCUENTRA HABILITADO 0//QUE NO HAGA NADA include("servidor.inicio.php");#ELIMINAR LOS INHABILITADOS EN EL SERVIDOR y habilito include("inhabilitados.inicio.php");#INABILITO A QUIEN CORRESPONDA include("ws.inicio.php");#LO SUBO EN LA WS } } if($_GET['tipo']=="revisar"){ include("cuotas.inicio.php");#CHEQUEO SI SE GENERARON Y SI NO SE GENERARON GENERARLA include("servidor.inicio.php");#ELIMINAR LOS INHABILITADOS EN EL SERVIDOR y habilito include("inhabilitados.inicio.php");#INABILITO A QUIEN CORRESPONDA include("ws.inicio.php");#LO SUBO EN LA WS } echo '<script>window.location = "inicio"</script>'; }<file_sep>/extensiones/afip/README.md Implementación simple para interactuar con WebService de AFIP y realizar Factura Electrónica Argentina en PHP. Permite realizar Facturas, Notas de Crédito y Débito: A, B, C M y E con webservice wsfev1 y wsfexv1. Pasos: 1. copiar carpeta FE 2. Crear una carpeta dentro del mismo con el [cuit] de la persona autorizada en AFIP 3. Crear dos carpetas dentro de la anterior: ./[cuit]/wsfe y ./[cuit]/wsfex 3. Dentro de dichas carpetas crear tres carpetas más: ./[cuit]./[serviceName]/tmp ./[cuit]./[serviceName]/token y ./[cuit]./[serviceName]/key 4. Dentro de .key crear dos carpetas ./key/homologacion y ./key/produccion. Colocar los certificados generados en afip junto con las claves privadas. con el número de cuit y la extension .pem para el certificado y sin extension para arcrivo clave (Ej. 2015065930.pem y 2015065930) Ejemplo estructura de archivos FE 20150659303 wsfe key homologacion 2015065930 (archivo key) 2015065930.pem produccion tmp token wsfex key homologacion 2015065930 (archivo key) 2015065930.pem produccion tmp token wsdl Test: 1. Editar el archivo prueba.php y modificar el valor de la variable $CUIT por el de la persona autorizada en AFIP. <file_sep>/ajax/mostrarVentasSeleccionada.ajax.php <?php require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; class AjaxSeleccionarVenta{ /*============================================= MOSTRAR FACTURAS SELECCIONADAS =============================================*/ public function ajaxMostrarFacturas(){ $item = "seleccionado"; $valor = $_POST["mostrarSeleccion"]; $respuesta = ControladorVentas::ctrMostrarFacturasSeleccionadas($item, $valor); echo json_encode($respuesta); } } /*============================================= MOSTRAR SELECCION =============================================*/ if(isset($_POST["mostrarSeleccion"])){ $mostrarFacturasSeleccionadas = new AjaxSeleccionarVenta(); $mostrarFacturasSeleccionadas -> ajaxMostrarFacturas(); } <file_sep>/extensiones/afip/notacredito.php <?php date_default_timezone_set('America/Argentina/Buenos_Aires'); include_once (__DIR__ . '/wsfev1.php'); include_once (__DIR__ . '/wsfexv1.php'); include_once (__DIR__ . '/wsaa.php'); require_once "../modelos/clientes.modelo.php"; // require_once "../controladores/comprobantes.controladores.php"; // require_once "../modelo/comprobantes.modelo.php"; //PUNTO DE VENTAS $item = "nombre"; $valor = "ventas"; $registro = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); $puntoVenta = $registro["cabezacomprobante"]; include ('modo.php'); // $CUIT = 30584197680; // $MODO = Wsaa::MODO_PRODUCCION; $PTOVTA = intval($puntoVenta); //echo "----------Script de prueba de AFIP WSFEV1----------\n"; $afip = new Wsfev1($CUIT,$MODO,$PTOVTA); $result = $afip->init(); $ERRORAFIP = 0; if ($result["code"] === Wsfev1::RESULT_OK) { $result = $afip->dummy(); if ($result["code"] === Wsfev1::RESULT_OK) { // $ptovta = intval($puntoVenta); #COMPROBANTE NOTA DE CREDITO $tipocbte = 13; //ULTIMO NRO DE COMPROBANTE $cmp = $afip->consultarUltimoComprobanteAutorizado($PTOVTA,$tipocbte); $ult = $cmp["number"]; $ult = $ult +1; $cantRegistro = strlen($ult); switch ($cantRegistro) { case 1: $ultimoComprobante="0000000".$ult; break; case 2: $ultimoComprobante="000000".$ult; break; case 3: $ultimoComprobante="00000".$ult; break; case 4: $ultimoComprobante="0000".$ult; break; case 5: $ultimoComprobante="000".$ult; break; case 6: $ultimoComprobante="00".$ult; break; case 7: $ultimoComprobante="0".$ult; break; case 8: $ultimoComprobante=$ult; break; } //$ult=3; // echo 'Nro. comp. a emitir: ' . $ult; $date_raw=date('Y-m-d'); $desde= date('Ymd', strtotime('-2 day', strtotime($date_raw))); $hasta=date('Ymd', strtotime('-1 day', strtotime($date_raw))); //Si el comprobante es C no debe informarse $detalleiva=Array(); //$detalleiva[0]=array('codigo' => 5,'BaseImp' => 100.55,'importe' => 21.12); //IVA 21% //$detalleiva[1]=array('codigo' => 4,'BaseImp' => 100,'importe' => 10.5); //IVA 10,5% $regcomp['numeroPuntoVenta'] =$PTOVTA; $regcomp['codigoTipoComprobante'] =$tipocbte; $comprob= array(); //$regcomp['CbtesAsoc'] = $comprob; $regcomp['codigoConcepto'] = 1; # 1: productos, 2: servicios, 3: ambos #TIPO DE CLIENTE....SON 3 //print_r ($datos); switch ($datos["tabla"]) { case 'escribanos': $item = "id"; $valor = $datos["idcliente"]; $traerCliente = ModeloEscribanos::mdlMostrarEscribanos('escribanos', $item, $valor); if($traerCliente['facturacion']=="CUIT"){ # code... $codigoTipoDoc = 80; $numeroDoc=$traerCliente['cuit']; break; }else{ $codigoTipoDoc = 96; $numeroDoc=$traerCliente['documento']; } case 'casual': # code... // print_r ($_POST); $codigoTipoDoc = 96; $numeroDoc=$datos["documento"]; break; case 'clientes': // $item = "id"; // $valor = $_POST["seleccionarCliente"]; // $tabla = "clientes"; // $traerCliente = ModeloClientes::mdlMostrarClientes($tabla, $item, $valor); $codigoTipoDoc = 80; $numeroDoc=$datos["documento"]; break; default: # consumidor final // $item = "id"; // $valor = $_POST["seleccionarCliente"]; // $traerCliente = ModeloEscribanos::mdlMostrarEscribanos('escribanos', $item, $valor); $codigoTipoDoc = 99; $numeroDoc=$datos["documento"]; break; } $wcompasoc = Array(); $wnrofact = $facturaOriginal; //Nro de factura a la que hace referencia la Nota de credito $wfecha = date('Ymd'); //Fecha de la factura $wcompasoc [0] = array('Tipo' => $tipocbte , 'PtoVta' => $PTOVTA, 'Nro' => $wnrofact, 'Cuit' => $numeroDoc, 'Fecha' => $wfecha ); // echo $codigoTipoDoc." ".$numeroDoc; $regcomp['codigoTipoDocumento'] = $codigoTipoDoc; # 80: CUIT, 96: DNI, 99: Consumidor Final $regcomp['numeroDocumento'] = $numeroDoc;//$traerCliente['cuit']; # 0 para Consumidor Final (<$1000) $regcomp['importeTotal'] = $datos["total"];//121.00; # total del comprobante $regcomp['importeGravado'] = $datos["total"]; #subtotal neto sujeto a IVA $regcomp['importeIVA'] = 0; $regcomp['importeOtrosTributos'] = 0; $regcomp['importeExento'] = 0.0; $regcomp['numeroComprobante'] = $ult; $regcomp['importeNoGravado'] = 0.00; $regcomp['subtotivas'] = $detalleiva; $regcomp['codigoMoneda'] = 'PES'; $regcomp['cotizacionMoneda'] = 1; $regcomp['fechaComprobante'] = date('Ymd'); $regcomp['fechaDesde'] = $desde; $regcomp['fechaHasta'] = $hasta; $regcomp['fechaVtoPago'] = date('Ymd'); $regcomp['CbtesAsoc'] = $wcompasoc; //ITEMS COMPROBANTE } else { $ERRORAFIP=1; echo "ER.si no hace el dummy".$result["msg"] ." ".$result["code"]."\n"; } } else { $ERRORAFIP=1; echo "ER.si no inicia de primnera".$result["msg"] ." ".$result["code"]."\n"; } // echo "--------------Ejecución WSFEV1 finalizada-----------------\n"; <file_sep>/vistas/modulos/cargarcuotas.php <?php $item = null; $valor = null; $respuesta = ControladorVentas::ctrMostrarVentas($item, $valor); foreach ($respuesta as $key => $value) { # code... $fecha = explode("-",$value["fecha"]); // $fecha = $fecha[2]."-".$fecha[1]."-".$fecha[0]; $mimes=$fecha[1]-1; $mimes = ControladorVentas::ctrNombreMes($mimes); if($mimes=='diciembre'){ $anio=$fecha[0]-1; }else{ $anio = $fecha[0]; } $productos = '[{"id":"20","descripcion":"CUOTA MENSUAL '.strtoupper($mimes).'/'.$anio.'","idnrocomprobante":"100","cantventaproducto":"1","folio1":"1","folio2":"1","cantidad":"1","precio":"'.$value['adeuda'].'","total":"'.$value['adeuda'].'"}]'; $datos = array("id"=>$value["id"], "productos"=>$productos); $tabla = 'ventas'; ModeloVentas::mdlUpdateProductos($tabla,$datos); }<file_sep>/modelos/ventas.modelo.php <?php require_once "conexion.php"; class ModeloVentas{ /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlMostrarVentas($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item ORDER BY codigo DESC"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY codigo DESC"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR VENTAS porFECHA =============================================*/ static public function mdlMostrarVentasFecha($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = '".$valor."' ORDER BY codigo ASC"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasClientes($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item ORDER BY id ASC"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY codigo ASC"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } static public function mdlMostrarVentasEscribanos($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item and tabla='escribanos' ORDER BY id ASC"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE tabla='escribanos' ORDER BY codigo ASC"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= REGISTRO DE VENTA =============================================*/ static public function mdlIngresarVenta($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(fecha,tipo,codigo, id_cliente,nombre,documento,tabla, id_vendedor, productos, impuesto, neto, total,adeuda,observaciones,metodo_pago,referenciapago,fechapago,cae,fecha_cae,qr) VALUES (:fecha,:tipo,:codigo, :id_cliente,:nombre,:documento,:tabla, :id_vendedor, :productos, :impuesto, :neto, :total,:adeuda,:obs, :metodo_pago,:referenciapago,:fechapago,:cae,:fecha_cae,:qr)"); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":id_vendedor", $datos["id_vendedor"], PDO::PARAM_INT); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":impuesto", $datos["impuesto"], PDO::PARAM_STR); $stmt->bindParam(":neto", $datos["neto"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); $stmt->bindParam(":obs",$datos["obs"], PDO::PARAM_STR); $stmt->bindParam(":metodo_pago", $datos["metodo_pago"], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos["referenciapago"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); $stmt->bindParam(":qr", $datos["qr"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } /*============================================= EDITAR VENTA =============================================*/ static public function mdlEditarVenta($tabla, $datos){ $mifecha ='0000-00-00'; $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET fecha = :fecha, codigo = :codigo,id_cliente = :id_cliente,nombre=:nombre,documento=:documento, id_vendedor = :id_vendedor,productos = :productos, impuesto = :impuesto, neto = :neto, total= :total,adeuda =:adeuda, metodo_pago = :metodo_pago,fechapago = :fechapago,referenciapago =:referenciapago, cae =:cae, fecha_cae =:fecha_cae WHERE id = :id"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":id_cliente", $datos["id_cliente"], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":id_vendedor", $datos["id_vendedor"], PDO::PARAM_INT); $stmt->bindParam(":productos", $datos["productos"], PDO::PARAM_STR); $stmt->bindParam(":impuesto", $datos["impuesto"], PDO::PARAM_STR); $stmt->bindParam(":neto", $datos["neto"], PDO::PARAM_STR); $stmt->bindParam(":total", $datos["total"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); if($datos["metodo_pago"]=="CTA.CORRIENTE"){ $stmt->bindParam(":fechapago", $mifecha , PDO::PARAM_STR); }else{ $stmt->bindParam(":fechapago", $datos["fechapago"], PDO::PARAM_STR); } $stmt->bindParam(":metodo_pago", $datos["metodo_pago"], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos["referenciapago"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ echo "\nPDO::errorInfo():\n"; print_r($stmt->errorInfo()); } $stmt->close(); $stmt = null; } /*============================================= SELECCIONAR VENTA =============================================*/ static public function mdlSeleccionarVenta($tabla,$item, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET seleccionado = 1 WHERE id =:id"); $stmt->bindParam(":id", $datos, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlAgregarNroNotadeCredito($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET observaciones = :obs WHERE id =:id"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":obs", $datos["obs"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= HOMOLOGAR VENTA =============================================*/ static public function mdlHomologacionVenta($tabla,$datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET fecha = :fecha,codigo = :codigo,cae =:cae,fecha_cae=:fecha_cae,nombre=:nombre,documento=:documento,qr=:qr WHERE id =:id"); $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos["fecha"], PDO::PARAM_STR); $stmt->bindParam(":codigo", $datos["codigo"], PDO::PARAM_STR); $stmt->bindParam(":cae", $datos["cae"], PDO::PARAM_STR); $stmt->bindParam(":fecha_cae", $datos["fecha_cae"], PDO::PARAM_STR); $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); $stmt->bindParam(":qr", $datos["qr"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlMostrarFacturasSeleccionadas($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT ventas.id as id,ventas.nrofc as nrofc,ventas.detalle as detalle,ventas.observaciones as obs,ventas.productos as productos,ventas.fecha as fecha,clientes.nombre as nombre,clientes.id as id_cliente FROM ventas,clientes WHERE seleccionado = 1 and clientes.id = ventas.id_cliente ORDER BY ventas.id ASC"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlBorrarFacturasSeleccionadas($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET seleccionado = 0 "); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= RANGO FECHAS =============================================*/ static public function mdlRangoFechasVentas($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY codigo asc limit 60"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' ORDER BY codigo DESC "); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' ORDER BY codigo asc"); $stmt -> execute(); return $stmt -> fetchAll(); } } static public function mdlRangoFechasVentas2($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE codigo<> '1' ORDER BY fecha desc,codigo DESC,tipo asc limit 150"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' and codigo<> '1' ORDER BY fecha desc,codigo DESC,tipo asc"); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' and codigo<> '1' ORDER BY codigo desc"); $stmt -> execute(); return $stmt -> fetchAll(); } } static public function mdlRangoFechasVentasNuevo($tabla, $fechaInicial, $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal' and codigo<> '1' ORDER BY codigo desc"); $stmt -> execute(); return $stmt -> fetchAll(); } static public function mdlRangoFechasCtaCorriente($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE adeuda >0 and codigo <> '1' ORDER BY id desc limit 150"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' and adeuda >0 and codigo <> '1' ORDER BY id DESC "); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' and adeuda >0 and codigo <> '1' ORDER BY id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } } static public function mdlRangoFechasaFacturar($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY id desc limit 150"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' ORDER BY id DESC "); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal2'ORDER BY id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } } static public function mdlRangoFechasVentasCobrados($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY codigo asc limit 60"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fechapago like '%$fechaFinal%' ORDER BY codigo asc limit 60"); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fechapago BETWEEN '$fechaInicial' AND '$fechaFinal2' ORDER BY codigo asc"); $stmt -> execute(); return $stmt -> fetchAll(); } } /*============================================= RANGO FECHAS =============================================*/ static public function mdlRangoFechasVentasNroFc($tabla, $fechaInicial, $fechaFinal, $nrofc){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where nrofc='".$nrofc."' ORDER BY id DESC"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha like '%$fechaFinal%' and $nrofc ='".$nrofc."' ORDER BY id DESC"); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' and $nrofc ='".$nrofc."' ORDER BY id DESC"); $stmt -> execute(); return $stmt -> fetchAll(); } } /*============================================= RANGO FECHAS clientes que deben =============================================*/ static public function RangoFechasVentasCtaCorriente($tabla, $fechaInicial, $fechaFinal){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where adeuda > 0 and codigo = 1 ORDER BY id DESC"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE adeuda > 0 and fecha like '%$fechaFinal%' and codigo = 1 ORDER BY id DESC"); $stmt -> bindParam(":fecha", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE adeuda > 0 AND fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' ORDER BY id DESC "); $stmt -> execute(); return $stmt -> fetchAll(); } } /*============================================= RANGO FECHAS =============================================*/ static public function mdlRangoFechasVentasMetodoPago($tabla, $fechaInicial, $fechaFinal,$metodoPago){ if($fechaInicial == null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM ventas WHERE metodo_pago ='".$metodoPago."' and fechapago like '%".date('Y-m-d')."%' ORDER BY id DESC limit 60"); $stmt -> execute(); return $stmt -> fetchAll(); }else if($fechaInicial == $fechaFinal){ $stmt = Conexion::conectar()->prepare("SELECT * FROM ventas WHERE metodo_pago ='".$metodoPago."' and fechapago like '%$fechaFinal%' ORDER BY id DESC limit 60"); $stmt -> bindParam(":fechapago", $fechaFinal, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); }else{ $fechaFinal = new DateTime(); $fechaFinal->add(new DateInterval('P1D')); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT * FROM ventas WHERE metodo_pago ='".$metodoPago."' and fecha BETWEEN '$fechaInicial' AND '$fechaFinal2' ORDER BY id DESC"); $stmt -> execute(); return $stmt -> fetchAll(); } } /*============================================= LISTADO DE ETIQUETAS =============================================*/ static public function mdlEtiquetasVentas($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla ORDER BY fecha DESC limit 30"); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } static public function mdlTmpVentasCopia($tabla, $tipo){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where tipo =:tipo and adeuda > 0"); $stmt->bindParam(":tipo", $tipo, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= SUMAR EL TOTAL DE VENTAS =============================================*/ static public function mdlSumaTotalVentas($tabla){ // VENTAS DEL DIA $fechaFinal = new DateTime(); $fechaFinal2 = $fechaFinal->format('Y-m-d'); $stmt = Conexion::conectar()->prepare("SELECT SUM(total) as total FROM $tabla where fecha='".$fechaFinal2."'"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } /*============================================= SUMAR EL TOTAL DE VENTAS =============================================*/ static public function mdlSumaTotalVentasEntreFechas($tabla,$fechaInicial,$fechaFinal){ // VENTAS DEL DIA $stmt = Conexion::conectar()->prepare("SELECT SUM(total) as total FROM $tabla where fecha BETWEEN '".$fechaInicial."' and '".$fechaFinal."'"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } public function mdlUltimoComprobante($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); $stmt->close(); } /*============================================= EDITAR VENTA =============================================*/ static public function mdlAgregarNroComprobante($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET numero = :numero WHERE id=1"); $stmt->bindParam(":numero", $datos, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR VENTA =============================================*/ static public function mdlRealizarPago($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE ventas SET adeuda = ".$datos["adeuda"].", fechapago='".$datos["fecha"]."' WHERE id = ".$datos["id"]); // $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); // $stmt->bindParam(":adeuda", $datos["adeuda"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= RANGO FECHAS =============================================*/ static public function mdlHistorial($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where tipo='FC' "); $stmt -> execute(); return $stmt -> fetchAll(); } /*============================================= MOSTRAR VENTAS =============================================*/ static public function mdlHistorialCta_art($tabla, $idcta){ // echo "SELECT * FROM $tabla where idcta=".$idcta; $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla where idcta=".$idcta); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } /*============================================= ELIMINAR PAGO =============================================*/ static public function mdlEliminarPago($tabla, $valor){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET fechapago = '0000-00-00', adeuda = total WHERE id = :id"); $stmt->bindParam(":id", $valor, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR DERECHO DE ESCRITURA =============================================*/ static public function mdlDerechoEscrituraVenta($tabla, $datos,$total){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET productos = :productos,total = :total, adeuda = :adeuda WHERE id = :id"); $stmt->bindParam(":id",$valor, PDO::PARAM_INT); $stmt->bindParam(":productos", $datos, PDO::PARAM_STR); $stmt->bindParam(":total", $total, PDO::PARAM_STR); $stmt->bindParam(":adeuda", $total, PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= SELECCIONAR VENTA =============================================*/ static public function mdlRealizarPagoVenta($tabla,$datos){ echo '<center><pre>'; print_r($datos); echo '</pre></center>'; $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET metodo_pago = :metodo_pago,referenciapago =:referenciapago,fechapago =:fechapago, adeuda =:adeuda WHERE id =:id"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":metodo_pago", $datos['metodo_pago'], PDO::PARAM_STR); $stmt->bindParam(":referenciapago", $datos['referenciapago'], PDO::PARAM_STR); $stmt->bindParam(":fechapago", $datos['fechapago'], PDO::PARAM_STR); $stmt->bindParam(":adeuda", $datos['adeuda'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlUpdateProductos($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET productos = :productos WHERE id =:id"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":productos", $datos['productos'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= OBTENER EL ULTIMO ID =============================================*/ static public function mdlUltimoId($tabla){ $stmt = Conexion::conectar()->prepare("SELECT id,codigo FROM `ventas` ORDER BY id DESC LIMIT 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } // static public function mdlCorregirNombres($tabla, $datos){ // $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre, documento = :documento WHERE id = :id"); // $stmt->bindParam(":id", $datos["id"], PDO::PARAM_INT); // $stmt->bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); // $stmt->bindParam(":documento", $datos["documento"], PDO::PARAM_STR); // if($stmt->execute()){ // return "ok"; // }else{ // echo "\nPDO::errorInfo():\n"; // print_r($stmt->errorInfo()); // } // $stmt->close(); // $stmt = null; // } static public function mdlMostrarUltimaVenta($tabla){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc limit 1"); $stmt -> execute(); return $stmt -> fetch(); $stmt -> close(); $stmt = null; } static public function mdlMostrarUltimasVentas($tabla, $item, $valor){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item > :$item ORDER BY id"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_INT); $stmt -> execute(); return $stmt -> fetchAll(); $stmt -> close(); $stmt = null; } static public function mdlGuardarItem($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO items (idVenta,idCodigoFc,fecha,nombreEscribano,nroComprobante, descripcionComprobante,folio1,folio2) VALUES (:idVenta,:idCodigoFc,:fecha,:nombreEscribano,:nroComprobante, :descripcionComprobante,:folio1,:folio2)"); $stmt->bindParam(":idVenta", $datos['idVenta'], PDO::PARAM_INT); $stmt->bindParam(":idCodigoFc", $datos['idCodigoFc'], PDO::PARAM_INT); $stmt->bindParam(":fecha", $datos['fecha'], PDO::PARAM_INT); $stmt->bindParam(":nombreEscribano", $datos['nombreEscribano'], PDO::PARAM_STR); $stmt->bindParam(":nroComprobante", $datos['nroComprobante'], PDO::PARAM_STR); $stmt->bindParam(":descripcionComprobante", $datos['descripcionComprobante'], PDO::PARAM_STR); $stmt->bindParam(":folio1", $datos['folio1'], PDO::PARAM_STR); $stmt->bindParam(":folio2", $datos['folio2'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return $stmt->errorInfo(); } $stmt->close(); $stmt = null; } }<file_sep>/vistas/modulos/delegaciones.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar Delegaciones </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar delegaciones</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <button class="btn btn-primary" data-toggle="modal" data-target="#modalAgregarDelegacion"> Agregar Delegacion </button> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Nombre</th> <th>Direccion</th> <th>Localidad</th> <th>P.Venta</th> <th>Titular</th> <th>Acciones</th> </tr> </thead> <tbody> <?php $item = null; $valor = null; $clientes = ControladorDelegaciones::ctrMostrarDelegaciones($item, $valor); foreach ($clientes as $key => $value) { echo '<tr> <td>'.($key+1).'</td> <td>'.$value["nombre"].'</td> <td>'.$value["direccion"].'</td> <td>'.$value["localidad"].'</td> <td>'.$value["puntodeventa"].'</td> <td>'.$value["escribano"].'</td>'; echo '<td> <div class="btn-group"> <button class="btn btn-warning btnEditarDelgacion" data-toggle="modal" data-target="#modalEditarDelegacion" idDelegacion="'.$value["id"].'"><i class="fa fa-pencil"></i></button>'; echo '<button class="btn btn-danger btnEliminarDelegacion" idDelegacion="'.$value["id"].'"><i class="fa fa-times"></i></button>'; echo '</div> </td> </tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <div id="modalAgregarDelegacion" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Editar los Datos de la Delegacion</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-university"></i></span> <input type="text" class="form-control input-lg" name="nombreNuevoDelegacion" id="nombreNuevoDelegacion" placeholder="Ingresar Delegacion" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL DIRECCION --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="direccionNuevoDelegacion" id="direccionNuevoDelegacion" placeholder="Ingresar Direccion" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="localidadNuevoDelegacion" id="localidadNuevoDelegacion" placeholder="Ingresar Localidad" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL Telefono --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input type="text" class="form-control input-lg" name="telefonoNuevoDelegacion" id="telefonoNuevoDelegacion" placeholder="Ingresar Telefono" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL Punto de venta --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-qrcode"></i></span> <input type="text" class="form-control input-lg" name="puntoVentaNuevoDelegacion" id="puntoVentaNuevoDelegacion" placeholder="Ingresar Punto de Venta" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA SELECCIONAR Escribano --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-male"></i></span> <select class="form-control input-lg" id="escribanoNuevoDelegacion" name="escribanoNuevoDelegacion" style="text-transform:uppercase; " required> <option value="0">Seleccionar Escribano</option> <?php $item = null; $valor = null; $categorias = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.strtoupper($value["id"]).'">'.strtoupper($value["nombre"]).'</option>'; } ?> </select> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" id="btnDelegacionAgregar">Guardar Cambios</button> </div> </div> </div> </div> <div id="modalEditarDelegacion" class="modal fade" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" style="background:#3c8dbc; color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Agregar los Datos de la Delegacion</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-university"></i></span> <input type="hidden" name="idEditar" id="idEditar"> <input type="text" class="form-control input-lg" name="nombreEditarDelegacion" id="nombreEditarDelegacion" placeholder="Ingresar Delegacion" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL DIRECCION --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="direccionEditarDelegacion" id="direccionEditarDelegacion" placeholder="Ingresar Direccion" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL LOCALIDAD --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-map-marker"></i></span> <input type="text" class="form-control input-lg" name="localidadEditarDelegacion" id="localidadEditarDelegacion" placeholder="Ingresar Localidad" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL Telefono --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-phone"></i></span> <input type="text" class="form-control input-lg" name="telefonoEditarDelegacion" id="telefonoEditarDelegacion" placeholder="Ingresar Telefono" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA EL Punto de venta --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-qrcode"></i></span> <input type="text" class="form-control input-lg" name="puntoVentaEditarDelegacion" id="puntoVentaEditarDelegacion" placeholder="Ingresar Punto de Venta" style="text-transform:uppercase; " required> </div> </div> <!-- ENTRADA PARA SELECCIONAR Escribano --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-male"></i></span> <select class="form-control input-lg" id="escribanoEditarDelegacion" name="escribanoEditarDelegacion" style="text-transform:uppercase; " required> <option value="0">Seleccionar Escribano</option> <?php $item = null; $valor = null; $categorias = ControladorEscribanos::ctrMostrarEscribanos($item, $valor); foreach ($categorias as $key => $value) { echo '<option value="'.strtoupper($value["id"]).'">'.strtoupper($value["nombre"]).'</option>'; } ?> </select> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal" id="btnDelegacionEditar">Guardar Cambios</button> </div> </div> </div> </div> <?php $eliminarDelegacion = new ControladorDelegaciones(); $eliminarDelegacion -> ctrEliminarDelegacion(); ?> <file_sep>/vistas/modulos/caja2.php <?php /*============================================= CHEQUEO LAS RESTRICCIONES DE LOS USUARIOS =============================================*/ // include('restricciones.php'); /*===== End of Section comment block ======*/ ?> <?php if(isset($_GET['fecha1'])){ $fecha1 = $_GET['fecha1']; }else{ $fecha1 =date('Y-m-d'); } /*============================================= LOS IMPORTES DE CAJA =============================================*/ $item = "fecha"; $valor = $fecha1; $caja = ControladorCaja::ctrMostrarCaja($item, $valor); /*===== End of Section comment block ======*/ /*============================================= VENTAS =============================================*/ $item= "fecha"; $valor = $fecha1; $ventasPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); $totalventas = 0; $cuentaCorrienteVenta = 0; foreach ($ventasPorFecha as $key => $value) { # code... if($value['metodo_pago']=="CTA.CORRIENTE"){ $cuentaCorrienteVenta+=$value['total']; } $totalventas += $value['total']; } /*============================================= REMITOS =============================================*/ $item= "fecha"; $valor = $fecha1; $remitos = ControladorRemitos::ctrMostrarRemitosFecha($item,$valor); $totalRemitos = 0; $cuentaCorrienteRemito = 0; foreach ($remitos as $key => $value) { # code... if($value['metodo_pago']=="CTA.CORRIENTE"){ $cuentaCorrienteRemito+=$value['total']; } $totalRemitos += $value['total']; } // PAGOS $item= "fechapago"; $valor = $fecha1; $pagosPorFecha = ControladorVentas::ctrMostrarVentasFecha($item,$valor); $pagosVenta = 0; $pagoVentaTotal = 0; foreach ($pagosPorFecha as $key => $value) { # code... if($value['fecha']!=$fecha1){ $pagosVenta += $value['total']; } $pagoVentaTotal+=$value['total']; } // REMITOS $item= "fechapago"; $valor = $fecha1; $pagosPorFechaRemitos = ControladorRemitos::ctrMostrarRemitosFecha($item,$valor); $pagosRemito = 0; $pagoRemitoTotal = 0; foreach ($pagosPorFechaRemitos as $key => $value) { # code... if($value['fecha']!=$fecha1){ $pagosRemito += $value['total']; } $pagoRemitoTotal+=$value['total']; } //FORMATEAR FECHA $fechaFormateada = explode("-", $fecha1); switch (intval($fechaFormateada[1])) { case 1: $mes ="ENERO"; break; case 2: $mes= "FEBRERO"; break; case 3: $mes= "MARZO"; break; case 4: $mes= "ABRIL"; break; case 5: $mes= "MAYO"; break; case 6: $mes= "JUNIO"; break; case 7: $mes= "JULIO"; break; case 8: $mes= "AGOSTO"; break; case 9: $mes= "SEPTIEMBRE"; break; case 10: $mes= "OCTUBRE"; break; case 11: $mes= "NOVIEMBRE"; break; case 12: $mes= "DICIEMBRE"; break; // default: // # code... // echo "aaaaaaaaaaaaaaaaaa---------".$fecha1[1]; // break; } ?> <div class="content-wrapper"> <section class="content-header"> <h1> Administrar caja del día <?php echo $fechaFormateada[2]. " de ".$mes." ".$fechaFormateada[0]; ?> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar caja</li> </ol> </section> <section class="content"> <div class="row"> <!-- /.col --> <div class="col-md-2 col-sm-3 col-xs-12"> <div class="info-box" title="Son Todas las Cobranzas en EFECTIVO"> <span class="info-box-icon bg-blue"><i class="fa fa fa-usd"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Efectivo <a href="http://localhost/colegio/extensiones/fpdf/pdf/informe-caja.php?fecha1=<?php echo $fecha1;?>&tipopago=EFECTIVO" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number" style="font-size: 15px">$<?php echo number_format($caja[0]['efectivo'],2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-2 col-sm-3 col-xs-12"> <div class="info-box" title="Son Todas las Cobranzas con TARJETA"> <span class="info-box-icon bg-green"><i class="fa fa-credit-card"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Tarjeta <a href="http://localhost/colegio/extensiones/fpdf/pdf/informe-caja.php?fecha1=<?php echo $fecha1;?>&tipopago=TARJETA" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number" style="font-size: 15px">$<?php echo number_format($caja[0]['tarjeta'],2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <!-- /.col --> <div class="col-md-2 col-sm-6 col-xs-12"> <div class="info-box" title="Son Todas las Cobranzas con CHEQUE"> <span class="info-box-icon bg-orange"><i class="fa fa-university"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Cheque <a href="http://localhost/colegio/extensiones/fpdf/pdf/informe-caja.php?fecha1=<?php echo $fecha1;?>&tipopago=CHEQUE" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number" style="font-size: 15px">$<?php echo number_format($caja[0]['cheque'],2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="info-box" title="Son Todas las Cobranzas con TRANSFERENCIAS BANCARIAS"> <span class="info-box-icon bg-purple"><i class="fa fa-bookmark"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Transferencias <a href="http://localhost/colegio/extensiones/fpdf/pdf/informe-caja.php?fecha1=<?php echo $fecha1;?>&tipopago=TRANSFERENCIA" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number" style="font-size: 15px">$<?php echo number_format($caja[0]['transferencia'],2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-3 col-xs-12"> <div class="info-box" title="Aqui estan acentados toda VENTA (incluida las delegaciones) que no fue cobrada "> <span class="info-box-icon bg-yellow"><i class="fa fa fa-users"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Cuenta Corriente <a href="http://localhost/colegio/extensiones/fpdf/pdf/informe-caja.php?fecha1=<?php echo $fecha1;?>&tipopago=CTA.CORRIENTE" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number" style="font-size: 15px">$<?php echo number_format($cuentaCorrienteVenta+$cuentaCorrienteRemito,2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-4 col-xs-12"> <div class="info-box" title="Son Todas LAS VENTAS DEL DIA"> <span class="info-box-icon bg-red"><i class="fa fa-line-chart"></i></span> <div class="info-box-content"> <h5></h5> <span class="info-box-text"><strong>Ventas <a href="http://localhost/colegio/extensiones/fpdf/pdf/ventas.php?fecha1=<?php echo $fecha1;?>&tipoventa=VENTA" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number">Total $<?php echo number_format($totalventas,2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-4 col-xs-12"> <div class="info-box" title="Son Todas LAS VENTAS DEL DIA A LAS DELEGACIONES"> <span class="info-box-icon bg-blue"><i class="fa fa-line-chart"></i></span> <div class="info-box-content"> <h5></h5> <span class="info-box-text"><strong>Remitos <a href="http://localhost/colegio/extensiones/fpdf/pdf/ventas.php?fecha1=<?php echo $fecha1;?>&tipoventa=REMITO" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number">Total $<?php echo number_format($totalRemitos,2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-3 col-xs-12"> <div class="info-box" title="Son Todos los pagos de aquellos que tenian deuda de escribanos/particulares y/o delegaciones"> <span class="info-box-icon bg-pink"><i class="fa fa-building"></i></span> <div class="info-box-content"> <span class="info-box-text"><strong>Pagos de Cta.Corriente <a href="http://localhost/colegio/extensiones/fpdf/pdf/pagos.php?fecha1=<?php echo $fecha1;?>" target="_blank"></strong><i class="fa fa-external-link-square" aria-hidden="true"></i></a></span> <span class="info-box-number">$<?php echo number_format($pagosVenta+$pagosRemito,2); ?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <div class="col-md-3 col-sm-4 col-xs-12"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="fa fa-line-chart"></i></span> <div class="info-box-content"> <h5></h5> <!-- <span class="info-box-text"><strong>Ventas </strong></span> --> <span class="info-box-number">Total $<?php echo number_format($pagoVentaTotal+ $pagoRemitoTotal,2); ?></span> <h6>(Ventas + Remitos + Pagos)</h6> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> </div> <div class="box"> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Fecha</th> <th>Efectivo</th> <th>Tarjeta</th> <th>Cheque</th> <th>Transferencia</th> <th>Acciones</th> </tr> </thead> <tbody> <?php // $item = "fecha"; // $valor = date('Y-m-d'); $item = null; $valor = null; $caja = ControladorCaja::ctrMostrarCaja($item, $valor); foreach ($caja as $key => $value) { echo '<tr> <td>'.($key+1).'</td>'; echo '<td class="text-uppercase">'.$value["fecha"].'</td>'; echo '<td class="text-uppercase">'.$value["efectivo"].'</td>'; echo '<td class="text-uppercase">'.$value["tarjeta"].'</td>'; echo '<td class="text-uppercase">'.$value["cheque"].'</td>'; echo '<td class="text-uppercase">'.$value["transferencia"].'</td>'; echo '<td><div class="btn-group"> <button class="btn btn-primary btnImprimirCaja" fecha="'.$value["fecha"].'" title="Imprimir caja"><i class="fa fa-print"></i></button> <button class="btn btn-danger btnSeleccionarCaja" fecha="'.$value["fecha"].'" title="caja del dia '.$value["fecha"].'" ><i class="fa fa-calendar"></a></i></button> '; echo '</div></td>'; echo '</tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <file_sep>/vistas/modulos/tmpcuotas.php <?php $respuesta = ControladorVentas::ctrTmpVentasCopia("CU"); foreach ($respuesta as $key => $value) { $tabla = "cuotas"; $datos = array("id"=>$value["id"], "fecha"=>$value["fecha"], "tipo"=>$value["tipo"], "id_cliente"=>$value["id_cliente"], "nombre"=>$value["nombre"], "documento"=>$value["documento"], "productos"=>$value["productos"], "total"=>$value["total"]); #registramos los productos $respuesta = ModeloCuotas::mdlIngresarCuota($tabla, $datos); } $respuesta = ControladorVentas::ctrTmpVentasCopia("RE"); foreach ($respuesta as $key => $value2) { $tabla = "cuotas"; $datos = array("id"=>$value2["id"], "fecha"=>$value2["fecha"], "tipo"=>$value2["tipo"], "id_cliente"=>$value2["id_cliente"], "nombre"=>$value2["nombre"], "documento"=>$value2["documento"], "productos"=>$value2["productos"], "total"=>$value2["total"]); #registramos los productos $respuesta = ModeloCuotas::mdlIngresarCuota($tabla, $datos); } ?><file_sep>/ajax/ctacorriente.clorinda.ajax.php <?php require_once "../controladores/enlace.controlador.php"; require_once "../modelos/enlace.modelo.php"; require_once "../controladores/escribanos.controlador.php"; require_once "../modelos/escribanos.modelo.php"; class AjaxCtaCorrienteVentaClorinda{ /*============================================= UPDATE SELECCIONAR VENTA =============================================*/ public function ajaxVerVentaClorinda(){ $item = "id"; $valor = $_POST["idVenta"]; $respuesta = ControladorEnlace::ctrMostrarVentasClorinda($item, $valor); echo json_encode($respuesta); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerEscribano(){ $itemCliente = "id"; $valorCliente = $_POST["idEscribano"]; $respuestaCliente = ControladorEscribanos::ctrMostrarEscribanos($itemCliente, $valorCliente); echo json_encode($respuestaCliente); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerArtClorinda(){ $item = "id"; $valor = $_POST["idVentaArt"]; $respuesta = ControladorEnlace::ctrMostrarVentasClorinda($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } /*============================================= VER ESCRIBANO =============================================*/ public function ajaxVerPagoDerechoClorinda(){ $item = "id"; $valor = $_POST["idPagoDerecho"]; $respuesta = ControladorEnlace::ctrMostrarVentasClorinda($item, $valor); $listaProductos = json_decode($respuesta['productos'], true); echo json_encode($listaProductos); } } /*============================================= EDITAR CUENTA CORRIENTE =============================================*/ if(isset($_POST["idVenta"])){ $seleccionarFactura = new AjaxCtaCorrienteVentaClorinda(); $seleccionarFactura -> ajaxVerVentaClorinda(); } /*============================================= VER CUENTA CORRIENTE CLIENTE =============================================*/ if(isset($_POST["idEscribano"])){ $verEscribano = new AjaxCtaCorrienteVentaClorinda(); $verEscribano -> ajaxVerEscribano(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idVentaArt"])){ $verTabla = new AjaxCtaCorrienteVentaClorinda(); $verTabla -> ajaxVerArtClorinda(); } /*============================================= VER ARTICULOS CORRIENTE =============================================*/ if(isset($_POST["idPagoDerecho"])){ $verTabla = new AjaxCtaCorrienteVentaClorinda(); $verTabla -> ajaxVerPagoDerechoClorinda(); } <file_sep>/controladores/osde.controlador.php <?php class ControladorOsde{ /*============================================= CREAR CATEGORIAS =============================================*/ static public function ctrCrearOsde(){ if(isset($_POST["nuevoOsde"])){ if ($_POST["nuevoImporte"]<>null){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoOsde"])){ $tabla = "osde"; $datos = array("nombre" => $_POST["nuevoOsde"], "importe" => $_POST["nuevoImporte"]); echo '<pre>'; print_r($datos); echo '</pre>'; $respuesta = ModeloOsde::mdlIngresarOsde($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Nuevo Osde ha sido guardado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "osde"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "osde"; } }) </script>'; } } } } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function ctrMostrarOsde($item, $valor){ $tabla = "osde"; $respuesta = ModeloOsde::mdlMostrarOsde($tabla, $item, $valor); return $respuesta; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function ctrEditarOsde(){ if(isset($_POST["editarOsde"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarOsde"])){ $tabla = "osde"; $datos = array("nombre"=>$_POST["editarOsde"], "importe"=>$_POST["editarImporte"], "id"=>$_POST["idOsde"]); ControladorOsde::ctrbKOsde($tabla, "id", $_POST["idOsde"], "UPDATE"); $respuesta = ModeloOsde::mdlEditarOsde($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Plan Osde ha sido cambiado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "osde"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "osde"; } }) </script>'; } } } /*============================================= BORRAR CATEGORIA =============================================*/ static public function ctrBorrarOsde(){ if(isset($_GET["idOsde"])){ $tabla ="osde"; $datos = $_GET["idOsde"]; ControladorOsde::ctrbKOsde($tabla, "id", $_GET["idOsde"], "ELIMINAR"); $respuesta = ModeloOsde::mdlBorrarOsde($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El PLan Osde ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "osde"; } }) </script>'; } } if(isset($_GET["todos"])){ $tabla ="osde"; $respuesta = ModeloOsde::mdlBorrarTodosOsde($tabla); } } static public function ctrbKOsde($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorOsde::ctrMostrarOsde($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "importe":"'.$respuesta[2].'"}]'; $datos = array("tabla"=>"osde", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloOsde::mdlbKOsde($tabla, $datos); } } <file_sep>/controladores/remitos.controlador.php <?php class ControladorRemitos{ /*============================================= MOSTRAR DELEGACIONES =============================================*/ static public function ctrMostrarRemitos($item, $valor){ $tabla = "remitos"; $respuesta = ModeloRemitos::mdlMostrarRemitos($tabla, $item, $valor); return $respuesta; } /*============================================= MOSTRAR REMITOS POR FECHA =============================================*/ static public function ctrMostrarRemitosFecha($item, $valor){ $tabla = "remitos"; $respuesta = ModeloRemitos::mdlMostrarRemitosFecha($tabla, $item, $valor); return $respuesta; } /*============================================= AGREGAR DELEGACIONES =============================================*/ static public function ctrEditarDelegacion($datos){ $tabla = "remitos"; $respuesta = ModeloRemitos::mdlEditarDelegacion($tabla, $datos); return $respuesta; } /*============================================= BORRAR DELEGACIONES =============================================*/ static public function ctrEliminarDelegacion(){ if(isset($_GET["idDelegacion"])){ $tabla ="delegaciones"; $datos = $_GET["idDelegacion"]; #ENVIAMOS LOS DATOS // ControladorCategorias::ctrbKCategorias($tabla, "id", $_GET["idCategoria"], "ELIMINAR"); $respuesta = ModeloRemitos::mdlBorrarDelegacion($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La delegacion ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "delegaciones"; } }) </script>'; } } } static public function ctrUltimoIdRemito(){ $tabla = "remitos"; $respuesta = ModeloRemitos::mdlUltimoIdRemito($tabla); return $respuesta; } /*============================================= CREAR REMITO =============================================*/ static public function ctrCrearRemito(){ #tomo los productos $listaProductos = json_decode($_POST["listaProductos"], true); #creo un array del afip $items=Array(); #recorro $listaproductos para cargarlos en la tabla de comprobantes foreach ($listaProductos as $key => $value) { $tablaComprobantes = "comprobantes"; $valor = $value["idnrocomprobante"]; $datos = $value["folio2"]; $actualizarComprobantes = ModeloComprobantes::mdlUpdateComprobante($tablaComprobantes, $valor,$datos); $miItem=$value["descripcion"]; if ($value['folio1']!=1){ $miItem.=' del '.$value['folio1'].' al '.$value['folio2']; } $items[$key]=array('codigo' => $value["id"],'descripcion' => $miItem,'cantidad' => $value["cantidad"],'codigoUnidadMedida'=>7,'precioUnitario'=>$value["precio"],'importeItem'=>$value["total"],'impBonif'=>0 ); } $fecha = date("Y-m-d"); if ($_POST["listaMetodoPago"]=="CTA.CORRIENTE"){ $adeuda=$_POST["totalVenta"]; $fechapago="0000-00-00"; }else{ $adeuda=0; $fechapago = $fecha; } $ptoVenta="0004"; //ULTIMO NUMERO DE COMPROBANTE Y LO FORMATERO PARA LOGRAR EL CODIGO $item = "nombre"; $valor = "remitos"; $ultimoComprobante = ControladorVentas::ctrUltimoComprobante($item, $valor); $cantDigitosRemito = strlen($ultimoComprobante['numero']); // echo '<pre>'; print_r($ultimoComprobante); echo '</pre>'; switch ($cantDigitosRemito) { case 1: $ultimoComprobante="0000000".$ultimoComprobante['numero']; break; case 2: $ultimoComprobante="000000".$ultimoComprobante['numero']; break; case 3: $ultimoComprobante="00000".$ultimoComprobante['numero']; break; case 4: $ultimoComprobante="0000".$ultimoComprobante['numero']; break; case 5: $ultimoComprobante="000".$ultimoComprobante['numero']; break; case 6: $ultimoComprobante="00".$ultimoComprobante['numero']; break; case 7: $ultimoComprobante="0".$ultimoComprobante['numero']; break; case 8: $ultimoComprobante=$ultimoComprobante['numero']; break; } $codigoFactura = $ptoVenta .'-'. $ultimoComprobante; $datos = array( "id_vendedor"=>1, "fecha"=>date('Y-m-d'), "codigo"=>$codigoFactura, "tipo"=>'REM', "id_cliente"=>$_POST['seleccionarCliente'], "nombre"=>$_POST['nombreCliente'], "documento"=>$_POST['documentoCliente'], "tabla"=>$_POST['tipoCliente'], "productos"=>$_POST['listaProductos'], "impuesto"=>0, "neto"=>0, "total"=>$_POST["totalVenta"], "adeuda"=>$adeuda, "obs"=>'', "cae"=>'0', "fecha_cae"=>date('Y-m-d'), "fechapago"=>$fechapago, "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST['nuevaReferencia'] ); $tabla = "remitos"; $respuesta = ModeloRemitos::mdlIngresarVentaRemito($tabla, $datos); $codigocomprobante = 3; $ultimoRemito =$ultimoComprobante+1; ModeloComprobantes::mdlUpdateComprobante("comprobantes",$codigocomprobante,$ultimoRemito); if ($_POST["listaMetodoPago"]!='CTA.CORRIENTE'){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVenta"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVenta"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVenta"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVenta"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); } echo 'REM'; } static public function ctrRealizarPagoRemito(){ if(isset($_POST["idVentaPago"])){ // echo '<center><pre>'; print_r($_POST); echo '</pre></center>'; $tabla = "remitos"; $datos = array("id"=>$_POST['idVentaPago'], "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST["nuevaReferencia"], "fechapago"=>date('Y-m-d'), "adeuda"=>0); $respuesta = ModeloVentas::mdlRealizarPagoVenta($tabla, $datos);//REUTILIZO EL CODIGO DE VENTAS PERO CON LA TABLA REMITO // echo '<center><pre>'; print_r($respuesta); echo '</pre></center>'; if($respuesta == "ok"){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); // echo '<pre>'; print_r($caja); echo '</pre>'; $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVentaPago"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVentaPago"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVentaPago"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVentaPago"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); echo '<script> window.location = "remitos"; </script>'; } } } } <file_sep>/vistas/js/escribanos.js /*============================================= EDITAR CLIENTE =============================================*/ $(".tablas").on("click", ".btnEditarEscribano", function(){ var idEscribano = $(this).attr("idEscribano"); console.log("idEscribano", idEscribano); var datos = new FormData(); datos.append("idEscribano", idEscribano); $.ajax({ url:"ajax/escribanos.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success:function(respuesta){ console.log("respuesta", respuesta); $("#idEscribano").val(respuesta["id"]); $("#editarEscribano").val(respuesta["nombre"]); $("#editarDocumento").val(respuesta["documento"]); $("#editarCuit").val(respuesta["cuit"]); $("#editarLocalidad").val(respuesta["localidad"]); $("#editarDireccion").val(respuesta["direccion"]); $("#editarTelefono").val(respuesta["telefono"]); $("#editarEmail").val(respuesta["email"]); $("#editarCategoriaEscribano option[value="+ respuesta["id_categoria"] +"]").attr("selected",true); $("#editarEscribanoRelacionado option[value="+ respuesta["id_escribano_relacionado"] +"]").attr("selected",true); $("#editarCategoriaOsde option[value="+ respuesta["id_osde"] +"]").attr("selected",true); $("#editarTipoIva option[value="+ respuesta["id_tipo_iva"] +"]").attr("selected",true); } }) }) /*============================================= ELIMINAR CLIENTE =============================================*/ $(".tablas").on("click", ".btnEliminarEscribano", function(){ var idEscribano = $(this).attr("idEscribano"); console.log("idEscribano", idEscribano); swal({ title: '¿Está seguro de borrar el Escribano?', text: "¡Si no lo está puede cancelar la acción!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText: 'Cancelar', confirmButtonText: 'Si, borrar escribano!' }).then(function(result){ if (result.value) { window.location = "index.php?ruta=escribanos&idEscribano="+idEscribano; } }) }) /*============================================= HACER FOCO EN EL BUSCADOR CLIENTES =============================================*/ $('#modalAgregarEscribano').on('shown.bs.modal', function () { $('#nuevoEscribano').focus(); })<file_sep>/vistas/modulos/caja.php <div class="content-wrapper"> <section class="content-header"> <h1> Administrar caja </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Administrar caja</li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> </div> <div class="box-body"> <table class="table table-bordered table-striped dt-responsive tablas" width="100%"> <thead> <tr> <th style="width:10px">#</th> <th>Fecha</th> <th>Efectivo</th> <th>Tarjeta</th> <th>Cheque</th> <th>Transferencia</th> <th>Acciones</th> </tr> </thead> <tbody> <?php // $item = "fecha"; // $valor = date('Y-m-d'); $item = null; $valor = null; $caja = ControladorCaja::ctrMostrarCaja($item, $valor); foreach ($caja as $key => $value) { echo '<tr> <td>'.($key+1).'</td>'; echo '<td class="text-uppercase">'.$value["fecha"].'</td>'; echo '<td class="text-uppercase">'.$value["efectivo"].'</td>'; echo '<td class="text-uppercase">'.$value["tarjeta"].'</td>'; echo '<td class="text-uppercase">'.$value["cheque"].'</td>'; echo '<td class="text-uppercase">'.$value["transferencia"].'</td>'; echo '<td> <button class="btn btn-primary btnImprimirCaja" fecha="'.$value["fecha"].'" title="Imprimir caja"><i class="fa fa-print"></i></button>'; echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div> </div> </section> </div> <file_sep>/vistas/modulos/corregir.php <?php $item = null; $valor = null; $ventas = ControladorVentas::ctrMostrarVentas($item, $valor); foreach ($ventas as $key => $value) { # code... $item = "id"; $valor = $value['id_cliente']; $orden ='id'; $escribanos = ControladorEscribanos::ctrMostrarEscribanos($item, $valor, $orden); $datos = array("id"=>$value['id'], "nombre"=>$escribanos['nombre'], "documento"=>$escribanos['documento']); $tabla="ventas"; $respuesta = ModeloVentas::mdlCorregirNombres($tabla,$datos); if($respuesta=="ok"){ echo 'ok'; }else{ echo $value['id']; echo $respuesta; } } ?><file_sep>/controladores/ventas.controlador.php <?php date_default_timezone_set('America/Argentina/Buenos_Aires'); class ControladorVentas{ /*============================================= MOSTRAR VENTAS =============================================*/ static public function ctrMostrarVentas($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarVentas($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarCuotas($item, $valor){ $tabla = "cuotas"; $respuesta = ModeloVentas::mdlMostrarCuotas($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasFecha($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarVentasFecha($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasClientes($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarVentasClientes($tabla, $item, $valor); return $respuesta; } static public function ctrMostrarVentasEscribanos($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarVentasEscribanos($tabla, $item, $valor); return $respuesta; } /*============================================= CREAR VENTA =============================================*/ static public function ctrCrearVenta(){ #tomo los productos $listaProductos = json_decode($_POST["listaProductos"], true); #creo un array del afip $items=Array(); #recorro $listaproductos para cargarlos en la tabla de comprobantes foreach ($listaProductos as $key => $value) { $tablaComprobantes = "comprobantes"; $valor = $value["idnrocomprobante"]; $datos = $value["folio2"]; $actualizarComprobantes = ModeloComprobantes::mdlUpdateComprobante($tablaComprobantes, $valor,$datos); $miItem=$value["descripcion"]; if ($value['folio1']!=1){ $miItem.=' del '.$value['folio1'].' al '.$value['folio2']; } $items[$key]=array('codigo' => $value["id"],'descripcion' => $miItem,'cantidad' => $value["cantidad"],'codigoUnidadMedida'=>7,'precioUnitario'=>$value["precio"],'importeItem'=>$value["total"],'impBonif'=>0 ); } include('../extensiones/afip/afip.php'); /*============================================= GUARDAR LA VENTA =============================================*/ $tabla = "ventas"; $fecha = date("Y-m-d"); if ($_POST["listaMetodoPago"]=="CTA.CORRIENTE"){ $adeuda=$_POST["totalVenta"]; $fechapago="0000-00-00"; }else{ $adeuda = 0; $fechapago = $fecha; } if($ERRORAFIP==0){ $result = $afip->emitirComprobante($regcomp); //$regcomp debe tener la estructura esperada (ver a continuación de la wiki) if ($result["code"] === Wsfev1::RESULT_OK) { /*============================================= FORMATEO LOS DATOS =============================================*/ $cantCabeza = strlen($PTOVTA); switch ($cantCabeza) { case 1: $ptoVenta="000".$PTOVTA; break; case 2: $ptoVenta="00".$PTOVTA; break; case 3: $ptoVenta="0".$PTOVTA; break; } $codigoFactura = $ptoVenta .'-'. $ultimoComprobante; $fechaCaeDia = substr($result["fechaVencimientoCAE"],-2); $fechaCaeMes = substr($result["fechaVencimientoCAE"],4,-2); $fechaCaeAno = substr($result["fechaVencimientoCAE"],0,4); $afip=1; if($_POST['listaMetodoPago']=="CTA.CORRIENTE"){ $adeuda = $_POST['totalVenta']; }else{ $adeuda = 0; } $totalVenta = $_POST["totalVenta"]; include('../extensiones/qr/index.php'); $datos = array( "id_vendedor"=>1, "fecha"=>date('Y-m-d'), "codigo"=>$codigoFactura, "tipo"=>'FC', "id_cliente"=>$_POST['seleccionarCliente'], "nombre"=>$_POST['nombreCliente'], "documento"=>$_POST['documentoCliente'], "tabla"=>$_POST['tipoCliente'], "productos"=>$_POST['listaProductos'], "impuesto"=>0, "neto"=>0, "total"=>$_POST["totalVenta"], "adeuda"=>$adeuda, "obs"=>'', "cae"=>$result["cae"], "fecha_cae"=>$fechaCaeDia.'/'.$fechaCaeMes.'/'.$fechaCaeAno, "fechapago"=>$fechapago, "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST['nuevaReferencia'], "qr"=>$datos_cmp_base_64."=" ); $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); } } if(isset($respuesta)){ if($respuesta == "ok"){ if($afip==1){ /*============================================= AGREGAR EL NUMERO DE COMPROBANTE =============================================*/ $tabla = "comprobantes"; $datos = $ult; ModeloVentas::mdlAgregarNroComprobante($tabla, $datos); $nroComprobante = substr($_POST["nuevaVenta"],8); //ULTIMO NUMERO DE COMPROBANTE $item = "nombre"; $valor = "FC"; $registro = ControladorVentas::ctrUltimoComprobante($item, $valor); } if ($_POST["listaMetodoPago"]!='CTA.CORRIENTE'){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVenta"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVenta"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVenta"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVenta"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); } } if($afip==1){ echo 'FE'; }else{ echo "ER"; } } } static public function ctrHomologacionVenta(){ if(isset($_POST["idVentaHomologacion"])){ $item="id"; $valor=$_POST["idVentaHomologacion"]; $ventas=ControladorVentas::ctrMostrarVentas($item,$valor); $listaProductos = json_decode($ventas["productos"], true); $items=Array();//del afip foreach ($listaProductos as $key => $value) { $items[$key]=array('codigo' => $value["id"],'descripcion' => $value["descripcion"],'cantidad' => $value["cantidad"],'codigoUnidadMedida'=>7,'precioUnitario'=>$value["precio"],'importeItem'=>$value["total"],'impBonif'=>0); } $nombre=$ventas['nombre']; $documento=$ventas['documento']; $tabla=$ventas['tabla']; include('../extensiones/afip/homologacion.php'); /*============================================= GUARDAR LA VENTA =============================================*/ if($ERRORAFIP==0){ $result = $afip->emitirComprobante($regcomp); //$regcomp debe tener la estructura esperada (ver a continuación de la wiki) if ($result["code"] === Wsfev1::RESULT_OK) { $cantCabeza = strlen($PTOVTA); switch ($cantCabeza) { case 1: $ptoVenta="000".$PTOVTA; break; case 2: $ptoVenta="00".$PTOVTA; break; case 3: $ptoVenta="0".$PTOVTA; break; } $codigoFactura = $ptoVenta .'-'. $ultimoComprobante; $fechaCaeDia = substr($result["fechaVencimientoCAE"],-2); $fechaCaeMes = substr($result["fechaVencimientoCAE"],4,-2); $fechaCaeAno = substr($result["fechaVencimientoCAE"],0,4); $tabla = "comprobantes"; $datos = $ult; ModeloVentas::mdlAgregarNroComprobante($tabla, $datos); $numeroDoc=$documento; $totalVenta=$ventas["total"]; include('../extensiones/qr/index.php'); $datos = array("id"=>$_POST["idVentaHomologacion"], "fecha" => date('Y-m-d'), "codigo"=>$codigoFactura, "nombre"=>$nombre, "documento"=>$documento, "cae"=>$result["cae"], "fecha_cae"=>$fechaCaeDia.'/'.$fechaCaeMes.'/'.$fechaCaeAno,"qr"=>$datos_cmp_base_64."="); $tabla="ventas"; $respuesta = ModeloVentas::mdlHomologacionVenta($tabla,$datos); echo 'FE'; } }else{ echo "ER"; } } } /*============================================= ELIMINAR VENTA =============================================*/ static public function ctrEliminarVenta(){ if(isset($_GET["idVenta"])){ if(isset($_GET["password"])){ $tabla = "ventas"; $item = "id"; $valor = $_GET["idVenta"]; $traerVenta = ModeloVentas::mdlMostrarVentas($tabla, $item, $valor); echo '<pre>'; print_r($traerVenta); echo '</pre>'; /*============================================= ELIMINAR VENTA =============================================*/ //AGREGAR A LA CAJA $item = "fecha"; $valor = $traerVenta['fechapago']; $caja = ControladorCaja::ctrMostrarCaja($item, $valor); echo '<pre>'; print_r($caja); echo '</pre>'; $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($traerVenta['metodo_pago']){ case 'EFECTIVO': # code... $efectivo = $efectivo - $traerVenta["total"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta - $traerVenta["total"]; break; case 'CHEQUE': # code... $cheque = $cheque - $traerVenta["total"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia - $traerVenta["total"]; break; } $datos = array("fecha"=>$traerVenta['fechapago'], "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); $respuesta = ModeloVentas::mdlEliminarVenta($tabla, $_GET["idVenta"]); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La venta ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "ventas"; } }) </script>'; } }else{ echo'<script> swal({ type: "warning", title: "La autenticacion es incorrecta", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "ventas"; } }) </script>'; } } } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasVentas($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentas($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrRangoFechasVentas2($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentas2($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrRangoFechasVentasNuevo($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentasNuevo($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrRangoFechasCtaCorriente($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasCtaCorriente($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrRangoFechasaFacturar($fechaInicial, $fechaFinal){ $tabla = "cuotas"; $respuesta = ModeloVentas::mdlRangoFechasaFacturar($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrRangoFechasaFacturarVentas($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasaFacturar($tabla, $fechaInicial, $fechaFinal); return $respuesta; } static public function ctrTmpVentasCopia($tipo){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlTmpVentasCopia($tabla, $tipo); return $respuesta; } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasVentasCobrados($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentasCobrados($tabla, $fechaInicial, $fechaFinal); return $respuesta; } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasVentasNroFc($fechaInicial, $fechaFinal, $nrofc){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentasNroFc($tabla, $fechaInicial, $fechaFinal, $nrofc); return $respuesta; } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasVentasMetodoPago($fechaInicial, $fechaFinal, $metodoPago){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlRangoFechasVentasMetodoPago($tabla, $fechaInicial, $fechaFinal, $metodoPago); return $respuesta; } /*============================================= LISTADO DE ETIQUETAS =============================================*/ static public function ctrEtiquetasVentas(){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlEtiquetasVentas($tabla); return $respuesta; } /*============================================= RANGO FECHAS =============================================*/ static public function ctrRangoFechasVentasCtaCorriente($fechaInicial, $fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::RangoFechasVentasCtaCorriente($tabla, $fechaInicial, $fechaFinal); return $respuesta; } /*============================================= SELECCIONO UNA FACTURA PARA LA ETIQUETA =============================================*/ static public function ctrSeleccionarVenta($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlSeleccionarVenta($tabla, $item, $valor); return $respuesta; } /*============================================= MUESTRO LAS FACTURAS SELECCIONADAS =============================================*/ static public function ctrMostrarFacturasSeleccionadas($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarFacturasSeleccionadas($tabla, $item, $valor); return $respuesta; } /*============================================= BORRAR LAS FACTURAS SELECCIONADAS =============================================*/ static public function ctrBorrarFacturasSeleccionadas($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlBorrarFacturasSeleccionadas($tabla, $item, $valor); return $respuesta; } /*============================================= BORRAR PAGO DE LAS FACTURAS =============================================*/ static public function ctrEliminarPago(){ if(isset($_GET["idPago"])){ $tabla = "ventas"; $valor =$_GET["idPago"]; $respuesta = ModeloVentas::mdlEliminarPago($tabla,$valor); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El pago ha sido borrado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "ventas"; } }) </script>'; } } } /*============================================= DESCARGAR EXCEL =============================================*/ public function ctrDescargarReporte(){ if(isset($_GET["reporte"])){ $tabla = $_GET["ruta"]; if(isset($_GET["fechaInicial"]) && isset($_GET["fechaFinal"])){ $ventas = ControladorEnlace::ctrRangoFechasEnlace($tabla, $_GET["fechaInicial"], $_GET["fechaFinal"]); } // else{ // $item = null; // $valor = null; // $ventas = ModeloVentas::mdlMostrarVentas($tabla, $item, $valor); // } /*============================================= CREAMOS EL ARCHIVO DE EXCEL =============================================*/ $Name = $_GET["ruta"].'.xls'; header('Expires: 0'); header('Cache-control: private'); header("Content-type: application/vnd.ms-excel"); // Archivo de Excel header("Cache-Control: cache, must-revalidate"); header('Content-Description: File Transfer'); header('Last-Modified: '.date('D, d M Y H:i:s')); header("Pragma: public"); header('Content-Disposition:; filename="'.$Name.'"'); header("Content-Transfer-Encoding: binary"); echo utf8_decode("<table border='0'> <tr> <td style='font-weight:bold; border:1px solid #eee;'>FECHA</td> <td style='font-weight:bold; border:1px solid #eee;'>TIPO</td> <td style='font-weight:bold; border:1px solid #eee;'>CÓDIGO</td> <td style='font-weight:bold; border:1px solid #eee;'>NOMBRE</td> <td style='font-weight:bold; border:1px solid #eee;'>DOCUMENTO</td> <td style='font-weight:bold; border:1px solid #eee;'>PRODUCTOS</td> <td style='font-weight:bold; border:1px solid #eee;'>TOTAL</td> </tr>"); foreach ($ventas as $row => $item){ echo utf8_decode("<tr> <td style='border:1px solid #eee;'>".$item["fecha"]."</td> <td style='border:1px solid #eee;'>".$item["tipo"]."</td> <td style='border:1px solid #eee;'>".$item["codigo"]."</td> <td style='border:1px solid #eee;'>".$item["nombre"]."</td> <td style='border:1px solid #eee;'>".$item["documento"]."</td> "); $productos = json_decode($item["productos"], true); echo utf8_decode("<td style='border:1px solid #eee;'>"); foreach ($productos as $key => $valueProductos) { echo utf8_decode($valueProductos["descripcion"]." ".$valueProductos["folio1"]."-".$valueProductos["folio2"]."<br>"); } echo utf8_decode("</td> <td style='border:1px solid #eee;'>$ ".number_format($item["total"],2)."</td> </tr>"); } echo "</table>"; } } /*============================================= SUMA TOTAL VENTAS =============================================*/ public function ctrSumaTotalVentas(){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlSumaTotalVentas($tabla); return $respuesta; } /*============================================= SUMA TOTAL VENTAS =============================================*/ public function ctrSumaTotalVentasEntreFechas($fechaInicial,$fechaFinal){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlSumaTotalVentasEntreFechas($tabla,$fechaInicial,$fechaFinal); return $respuesta; } public function ctrUltimoComprobante($item,$valor){ $tabla = "comprobantes"; $respuesta = ModeloVentas::mdlUltimoComprobante($tabla, $item, $valor); return $respuesta; } #ACTUALIZAR PRODUCTO EN CTA_ART_TMP #--------------------------------- public function ctrAgregarTabla($datos){ echo '<table class="table table-bordered"> <tbody> <tr> <th style="width: 10px;">#</th> <th style="width: 10px;">Cantidad</th> <th style="width: 400px;">Articulo</th> <th style="width: 70px;">Precio</th> <th style="width: 70px;">Total</th> <th style="width: 10px;">Opciones</th> </tr>'; echo "<tr> <td>1.</td> <td><span class='badge bg-red'>".$datos['cantidadProducto']."</span></td> <td>".$datos['productoNombre']."</td> <td style='text-align: right;'>$ ".$datos['precioVenta'].".-</td> <td style='text-align: right;'>$ ".$datos['cantidadProducto']*$datos['precioVenta'].".-</td> <td><button class='btn btn-link btn-xs' data-toggle='modal' data-target='#myModalEliminarItemVenta'><span class='glyphicon glyphicon-trash'></span></button></td> </tr>"; echo '</tbody></table>'; } /*============================================= REALIZAR Pago =============================================*/ static public function ctrRealizarPago($redireccion){ if(isset($_POST["nuevoPago"])){ $adeuda = $_POST["adeuda"]-$_POST["nuevoPago"]; $tabla = "ventas"; $fechaPago = explode("-",$_POST["fechaPago"]); //15-05-2018 $fechaPago = $fecha[2]."-".$fecha[1]."-".$fecha[0]; $datos = array("id"=>$_POST["idPago"], "adeuda"=>$adeuda, "fecha"=>$_POST["fechaPago"]); $respuesta = ModeloVentas::mdlRealizarPago($tabla, $datos); if($respuesta == "ok"){ echo'<script> localStorage.removeItem("rango"); swal({ type: "success", title: "La venta ha sido editada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "'.$redireccion.'"; } }) </script>'; } } } /*============================================= RANGO FECHAS =============================================*/ static public function ctrHistorial(){ // FACTURAS $tabla = "cta"; $respuesta = ModeloVentas::mdlHistorial($tabla); foreach ($respuesta as $key => $value) { // veo los items de la factura $tabla = "ctaart"; $repuestos = ModeloVentas::mdlHistorialCta_art($tabla,$value['idcta']); $productos=''; for($i = 0; $i < count($repuestos)-1; $i++){ $productos = '{"id":"'.$repuestos[$i]["idarticulo"].'", "descripcion":"'.$repuestos[$i]["nombre"].'", "cantidad":"'.$repuestos[$i]["cantidad"].'", "precio":"'.$repuestos[$i]["precio"].'", "total":"'.$repuestos[$i]["precio"].'"},'; } $productos = $productos . '{"id":"'.$repuestos[count($repuestos)-1]["idarticulo"].'", "descripcion":"'.$repuestos[count($repuestos)-1]["nombre"].'", "cantidad":"'.$repuestos[count($repuestos)-1]["cantidad"].'", "precio":"'.$repuestos[count($repuestos)-1]["precio"].'", "total":"'.$repuestos[count($repuestos)-1]["precio"].'"}'; $productos ="[".$productos."]"; echo '<pre>'; print_r($productos); echo '</pre>'; // datos para cargar la factura $tabla = "ventas"; $datos = array("id_vendedor"=>1, "fecha"=>$value['fecha'], "id_cliente"=>$value["idcliente"], "codigo"=>$key, "nrofc"=>$value["nrofc"], "detalle"=>strtoupper($value["obs"]), "productos"=>$productos, "impuesto"=>0, "neto"=>0, "total"=>$value["importe"], "adeuda"=>$value["adeuda"], "obs"=>"", "metodo_pago"=>$value["detallepago"], "fechapago"=>$value['fecha']); $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); } return $respuesta; } /*============================================= INGRESAR DERECHO DE ESCRITURA =============================================*/ static public function ctringresarDerechoEscritura(){ if(isset($_POST["nuevoPagoDerecho"])){ $tabla = "ventas"; $item = "id"; $valor =$_POST["idPagoDerecho"]; $respuesta = ModeloVentas::mdlMostrarVentas($tabla, $item, $valor); /*============================================= REVISO LOS PRODUCTOS =============================================*/ $listaProductos = json_decode($respuesta['productos'], true); $totalFactura = 0; foreach ($listaProductos as $key => $value) { if($value['id']==19){ //ELIMINO EL ID 19 QUE ES DEL TESTIMONIO unset($listaProductos[$key]); }else{ // SUMO EL TOTAL DE LA FACTURA $totalFactura = $totalFactura +$value['total']; } } echo '<pre>'; print_r(count($listaProductos)); echo '</pre>'; $productosNuevosInicio = '['; for($i = 0; $i <= count($listaProductos); $i++){ $productosNuevosMedio = '{ "id":"'.$listaProductos[0]["id"].'", "descripcion":"'.$listaProductos[0]["descripcion"].'", "idnrocomprobante":"'.$listaProductos[0]["idnrocomprobante"].'", "cantventaproducto":"'.$listaProductos[0]["cantventaproducto"].'", "folio1":"'.$listaProductos[0]["folio1"].'", "folio2":"'.$listaProductos[0]["folio2"].'", "cantidad":"'.$listaProductos[0]["cantidad"].'", "precio":"'.$listaProductos[0]["precio"].'", "total":"'.$listaProductos[0]["total"].'" },'; } $productosNuevosFinal = '{ "id":"19", "descripcion":"DERECHO DE ESCRITURA", "idnrocomprobante":"100", "cantventaproducto":"1", "folio1":"1", "folio2":"1", "cantidad":"1", "precio":"'.$_POST["nuevoPagoDerecho"].'", "total":"'.$_POST["nuevoPagoDerecho"].'" }]'; echo $productosNuevosInicio . $productosNuevosMedio . $productosNuevosFinal; } } static public function ctrNombreMes($mes){ setlocale(LC_TIME, 'spanish'); $nombre=strftime("%B",mktime(0, 0, 0, $mes, 1, 2000)); return $nombre; } static public function ctrRealizarPagoVenta(){ if(isset($_POST["idVentaPago"])){ $tabla = "ventas"; $datos = array("id"=>$_POST['idVentaPago'], "metodo_pago"=>$_POST['listaMetodoPago'], "referenciapago"=>$_POST["nuevaReferencia"], "fechapago"=>date('Y-m-d'), "adeuda"=>0); $respuesta = ModeloVentas::mdlRealizarPagoVenta($tabla, $datos); if($respuesta == "ok"){ //AGREGAR A LA CAJA $item = "fecha"; $valor = date('Y-m-d'); $caja = ControladorCaja::ctrMostrarCaja($item, $valor); echo '<pre>'; print_r($caja); echo '</pre>'; $efectivo = $caja[0]['efectivo']; $tarjeta = $caja[0]['tarjeta']; $cheque = $caja[0]['cheque']; $transferencia = $caja[0]['transferencia']; switch ($_POST["listaMetodoPago"]) { case 'EFECTIVO': # code... $efectivo = $efectivo + $_POST["totalVentaPago"]; break; case 'TARJETA': # code... $tarjeta = $tarjeta + $_POST["totalVentaPago"]; break; case 'CHEQUE': # code... $cheque = $cheque + $_POST["totalVentaPago"]; break; case 'TRANSFERENCIA': # code... $transferencia = $transferencia + $_POST["totalVentaPago"]; break; } $datos = array("fecha"=>date('Y-m-d'), "efectivo"=>$efectivo, "tarjeta"=>$tarjeta, "cheque"=>$cheque, "transferencia"=>$transferencia); $caja = ControladorCaja::ctrEditarCaja($item, $datos); echo '<script> window.location = "ventas"; </script>'; } } } static public function ctrUltimoId(){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlUltimoId($tabla); return $respuesta; } /*============================================= CREAR NC =============================================*/ static public function ctrCrearNc($datos){ $facturaOriginal = explode("-",$datos["nroFactura"]); $facturaOriginal = intval($facturaOriginal[1]); $item="id"; $valor=$datos['idVenta']; $ventas=ControladorVentas::ctrMostrarVentas($item,$valor); #creo un array del afip $items=json_decode($datos["productos"], true); #paso los datos al archivo de conexnion de afip include('../extensiones/afip/notacredito.php'); if($ERRORAFIP==0){ /*============================================= GUARDAR LA VENTA =============================================*/ $tabla = "ventas"; $result = $afip->emitirComprobante($regcomp); if ($result["code"] === Wsfev1::RESULT_OK) { /*============================================= FORMATEO LOS DATOS =============================================*/ $fecha = date("Y-m-d"); $adeuda=0; $fechapago = $fecha; $cantCabeza = strlen($PTOVTA); switch ($cantCabeza) { case 1: $ptoVenta="000".$PTOVTA; break; case 2: $ptoVenta="00".$PTOVTA; break; case 3: $ptoVenta="0".$PTOVTA; break; } $codigoFactura = $ptoVenta .'-'. $ultimoComprobante; $fechaCaeDia = substr($result["fechaVencimientoCAE"],-2); $fechaCaeMes = substr($result["fechaVencimientoCAE"],4,-2); $fechaCaeAno = substr($result["fechaVencimientoCAE"],0,4); $totalVenta = $datos["total"]; include('../extensiones/qr/index.php'); $datos = array( "id_vendedor"=>1, "fecha"=>date('Y-m-d'), "codigo"=>$codigoFactura, "tipo"=>'NC', "id_cliente"=>$datos['idcliente'], "nombre"=>$datos['nombre'], "documento"=>$datos['documento'], "tabla"=>$datos['tabla'], "productos"=>$datos['productos'], "impuesto"=>0, "neto"=>0, "total"=>$datos["total"], "adeuda"=>'0', "obs"=>'FC-'.$ventas['codigo'], "cae"=>$result["cae"], "fecha_cae"=>$fechaCaeDia.'/'.$fechaCaeMes.'/'.$fechaCaeAno, "fechapago"=>$fechapago, "metodo_pago"=>"EFECTIVO", "referenciapago"=>"EFECTIVO", "qr"=>$datos_cmp_base_64."=" ); #grabo la nota de credito $respuesta = ModeloVentas::mdlIngresarVenta($tabla, $datos); #resto de la caja $item = "id"; $datos = array( "id"=>$ventas['id'], "obs"=>'NC-'.$codigoFactura); $respuesta = ModeloVentas::mdlAgregarNroNotadeCredito($tabla,$datos); echo 'FE'; } } } static public function ctrMostrarUltimaAVenta(){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarUltimaVenta($tabla); return $respuesta; } static public function ctrMostrarUltimasVentas($item, $valor){ $tabla = "ventas"; $respuesta = ModeloVentas::mdlMostrarUltimasVentas($tabla, $item, $valor); return $respuesta; } static public function ctrGuardarItem($datos){ $tabla = "items"; $respuesta = ModeloVentas::mdlGuardarItem($tabla, $datos); return $respuesta; } } <file_sep>/ajax/agregarProductos.ajax.php <?php #CONTROLADORES #----------------------------------------------89 require_once "../controladores/ventas.controlador.php"; require_once "../modelos/ventas.modelo.php"; $datos = array("idProducto"=>$_POST["idProducto"],"cantidadProducto"=>$_POST["cantidadProducto"],"productoNombre"=>$_POST["productoNombre"],"precioVenta"=>$_POST["precioVenta"]); $agregarProductos = new ControladorVentas(); $agregarProductos ->ctrAgregarTabla($datos); // var_dump($datos); ?> <file_sep>/vistas/js/osde.js /*============================================= EDITAR CATEGORIA =============================================*/ $(".tablas").on("click", ".btnEditarOsde", function(){ var idOsde = $(this).attr("idOsde"); var datos = new FormData(); datos.append("idOsde", idOsde); $.ajax({ url: "ajax/osde.ajax.php", method: "POST", data: datos, cache: false, contentType: false, processData: false, dataType:"json", success: function(respuesta){ console.log("respuesta", respuesta); $("#editarOsde").val(respuesta["nombre"]); $("#idOsde").val(respuesta["id"]); $("#editarImporte").val(respuesta["importe"]); } }) }) /*============================================= ELIMINAR OSDE =============================================*/ $(".tablas").on("click", ".btnEliminarOsde", function(){ var idOsde = $(this).attr("idOsde"); console.log("idOsde", idOsde); swal({ title: '¿Está seguro de borrar el Plan de Osde?', text: "¡Si no lo está puede cancelar la acción!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText: 'Cancelar', confirmButtonText: 'Si, borrar Osde!' }).then(function(result){ if(result.value){ window.location = "index.php?ruta=osde&idOsde="+idOsde; } }) }) /*============================================= ELIMINAR OSDE =============================================*/ $("#eliminarOsdes").on("click", function(){ swal({ title: '¿Está seguro de borrar Todos los Planes Osde?', text: "¡Si no lo está puede cancelar la acción!", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText: 'Cancelar', confirmButtonText: 'Si, borrar Osde!' }).then(function(result){ if(result.value){ window.location = "index.php?ruta=osde&todos=si"; } }) })<file_sep>/modelos/parametros.modelo.php <?php require_once "conexion.php"; class ModeloParametros{ /*============================================= MOSTRAR PARAMETEROS =============================================*/ static public function mdlMostrarParametros($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt->fetchAll(PDO::FETCH_CLASS); } $stmt -> close(); $stmt = null; } /*============================================= EDITAR LIBROS =============================================*/ static public function mdlEditarLibro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET ultimolibrocomprado = :ultimolibrocomprado,ultimolibrodevuelto = :ultimolibrodevuelto WHERE id = :id"); $stmt -> bindParam(":ultimolibrocomprado", $datos["ultimolibrocomprado"], PDO::PARAM_STR); $stmt -> bindParam(":ultimolibrodevuelto", $datos["ultimolibrodevuelto"], PDO::PARAM_STR); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlEditarParametros($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET valor = :valor WHERE id = :id"); $stmt -> bindParam(":valor", $datos["valor"], PDO::PARAM_STR); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlbKParametro($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= MOSTRAR PARAMETEROS =============================================*/ static public function mdlMostrarBackUp($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item order by id desc"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla order by id desc"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= ELIMINAR ESCRIBANO =============================================*/ static public function mdlEliminarBackup($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= CONTAR TABLAS =============================================*/ static public function mdlCountTablas($tabla,$item,$valor){ if ($item ==null){ $stmt = Conexion::conectar()->prepare("SELECT count(*) FROM $tabla"); }else{ $stmt = Conexion::conectarEnlace()->prepare("SELECT count(*) FROM $tabla WHERE $item = :valor"); $stmt -> bindParam(":valor", $valor, PDO::PARAM_STR); } $stmt -> execute(); return $stmt -> fetch(); } } <file_sep>/modelos/comprobantes.modelo.php <?php require_once "conexion.php"; class ModeloComprobantes{ /*============================================= MOSTRAR COMPROBANTES =============================================*/ static public function mdlMostrarComprobantes($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE $item = :$item"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= CREAR CATEGORIA =============================================*/ static public function mdlIngresarComprobante($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(nombre,numero) VALUES (:nombre,:numero)"); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":numero", $datos['numero'], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function mdlEditarComprobante($tabla, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET nombre = :nombre,numero = :numero WHERE id = :id"); $stmt -> bindParam(":id", $datos["id"], PDO::PARAM_INT); $stmt -> bindParam(":nombre", $datos["nombre"], PDO::PARAM_STR); $stmt -> bindParam(":numero", $datos["numero"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= BORRAR CATEGORIA =============================================*/ static public function mdlBorrarComprobante($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE id = :id"); $stmt -> bindParam(":id", $datos, PDO::PARAM_INT); if($stmt -> execute()){ return "ok"; }else{ return "error"; } $stmt -> close(); $stmt = null; } /*============================================= BORRAR TODOS LOS COMPROBANTES =============================================*/ static public function mdlIniciarTabla($tabla, $datos){ $stmt = Conexion::conectar()->prepare("DELETE FROM $tabla"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= INSERTAR DATOS A LA TABLA =============================================*/ static public function mdlIniciarCargaTmpComprobantes($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(id,nombre,numero) VALUES (:id,:nombre,:numero)"); $stmt->bindParam(":id", $datos['id'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":numero", $datos['numero'], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= AGREGAR ULTIMO ID CATEGORIA =============================================*/ static public function mdlAgregarItemsComprobantes($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (idproducto, cantidad, nombre, idnrocomprobante, cantventaproducto, precioventa, folio1, folio2) VALUES ( :idproducto,:cantidad,:nombre,:idnrocomprobante,:cantventaproducto,:precioventa,:folio1,:folio2)"); $stmt->bindParam(":idproducto", $datos['idproducto'], PDO::PARAM_INT); $stmt->bindParam(":cantidad", $datos['cantidadProducto'], PDO::PARAM_INT); $stmt->bindParam(":nombre", $datos['nombre'], PDO::PARAM_STR); $stmt->bindParam(":idnrocomprobante", $datos['idNroComprobante'], PDO::PARAM_INT); $stmt->bindParam(":cantventaproducto", $datos['cantVentaProducto'], PDO::PARAM_INT); $stmt->bindParam(":precioventa", $datos['precioVenta'], PDO::PARAM_INT); $stmt->bindParam(":folio1", $datos['folio1'], PDO::PARAM_INT); $stmt->bindParam(":folio2", $datos['folio2'], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function mdlUpdateFolioComprobantes($tabla, $item, $valor, $datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET numero = $datos WHERE id = $valor"); // $stmt -> bindParam(":id", $valor, PDO::PARAM_INT); // $stmt -> bindParam(":numero", $datos, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= UPDATE FOLIOS =============================================*/ static public function mdlUpdateFolio($tabla,$campo, $id,$numero){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET $campo = $numero WHERE id = $id"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= ACTUALIZAR NURO COMPROBANTES CATEGORIA =============================================*/ static public function mdlUpdateComprobante($tabla, $valor,$datos){ $stmt = Conexion::conectar()->prepare("UPDATE $tabla SET numero = :numero WHERE id = :id"); $stmt -> bindParam(":id", $valor, PDO::PARAM_INT); $stmt -> bindParam(":numero", $datos, PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } static public function mdlbKComprobante($tabla, $datos){ $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(`tabla`,`tipo`,`datos`,`usuario`) VALUES (:tabla,:tipo,:datos,:usuario)"); $stmt->bindParam(":tabla", $datos["tabla"], PDO::PARAM_STR); $stmt->bindParam(":tipo", $datos["tipo"], PDO::PARAM_STR); $stmt->bindParam(":datos", $datos["datos"], PDO::PARAM_STR); $stmt->bindParam(":usuario", $datos["usuario"], PDO::PARAM_STR); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/vistas/js/afip.js /*============================================= CONSULTAR COMPROBANTE =============================================*/ $("#btnAfip").on("click",function(){ window.location = "index.php?ruta=afip&numero="+$('#numero').val()+"&comprobante="+$('#tipoComprobante').val(); }) $('#numero').focus(); $('#numero').select();<file_sep>/controladores/rubros.controlador.php <?php class ControladorRubros{ /*============================================= CREAR CATEGORIAS =============================================*/ static public function ctrCrearRubro(){ if(isset($_POST["nuevoRubro"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoRubro"]) && ($_POST["nuevoMovimiento"]!=null)&& ($_POST["nuevoMensual"]!=null)){ $tabla = "rubros"; $datos = $_POST["nuevoRubro"]; $datos = array("nombre" => $_POST["nuevoRubro"], "movimiento" => $_POST["nuevoMovimiento"], "mensual" => $_POST["nuevoMensual"], "obs" => $_POST["nuevoObs"]); $respuesta = ModeloRubros::mdlIngresarRubro($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Rubro ha sido guardado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "rubros"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡El rubro no puede ir vacía o llevar caracteres especiales! o faltan algunos datos", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "rubros"; } }) </script>'; } } } /*============================================= MOSTRAR CATEGORIAS =============================================*/ static public function ctrMostrarRubros($item, $valor){ $tabla = "rubros"; $respuesta = ModeloRubros::mdlMostrarRubros($tabla, $item, $valor); return $respuesta; } /*============================================= EDITAR CATEGORIA =============================================*/ static public function ctrEditarRubro(){ if(isset($_POST["editarRubro"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarRubro"]) ){ $tabla = "rubros"; $datos = array("id"=>$_POST["idRubro"], "nombre"=>$_POST["editarRubro"], "movimiento"=>$_POST["editarMovimiento"], "mensual"=>$_POST["editarMensual"], "obs"=>$_POST["editarObs"], ); ControladorRubros::ctrbKRubros($tabla, "id", $_POST["idRubro"], "UPDATE"); $respuesta = ModeloRubros::mdlEditarRubro($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El Rubro ha sido actualizado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "rubros"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!, o faltan algunos datos", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "rubros"; } }) </script>'; } } } /*============================================= BORRAR RUBRO =============================================*/ static public function ctrBorrarRubro(){ if(isset($_GET["idRubro"])){ $tabla ="rubros"; $datos = $_GET["idRubro"]; ControladorRubros::ctrbKRubros($tabla, "id", $_GET["idRubro"], "ELIMINAR"); $respuesta = ModeloRubros::mdlBorrarRubro($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El rubro ha sido borrada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "rubros"; } }) </script>'; } } } static public function ctrbKRubros($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorRubros::ctrMostrarRubros($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "movimiento":"'.$respuesta[2].'", "mensual":"'.$respuesta[3].'", "activo":"'.$respuesta[4].'", "osbdel":"'.$respuesta[5].'", "fecha":"'.$respuesta[6].'"}]'; $datos = array("tabla"=>"rubros", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloRubros::mdlbKRubro($tabla, $datos); } } <file_sep>/controladores/comprobantes.controlador.php <?php class ControladorComprobantes{ /*============================================= MOSTRAR COMPROBANTES =============================================*/ static public function ctrMostrarComprobantes($item, $valor){ $tabla = "comprobantes"; $respuesta = ModeloComprobantes::mdlMostrarComprobantes($tabla, $item, $valor); return $respuesta; } /*============================================= CREAR COMPROBANTES =============================================*/ static public function ctrCrearComprobante(){ if(isset($_POST["nuevoComprobante"])){ if ($_POST["nuevoNumeroComprobante"]<>null){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoComprobante"])){ $tabla = "comprobantes"; $datos = $_POST["nuevoComprobante"]; $datos = array("nombre" => $_POST["nuevoComprobante"], "numero" => $_POST["nuevoNumeroComprobante"]); $respuesta = ModeloComprobantes::mdlIngresarComprobante($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El comprobante ha sido guardado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "comprobantes"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡La categoría no puede ir vacía o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "comprobantes"; } }) </script>'; } } } } /*============================================= EDITAR Comprobantes =============================================*/ static public function ctrEditarComprobante(){ if(isset($_POST["editarComprobante"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarComprobante"])){ $tabla = "comprobantes"; $datos = array("id"=>$_POST["idComprobante"], "nombre"=>$_POST["editarComprobante"], "numero"=>$_POST["editarNumeroComprobante"]); ControladorComprobantes::ctrbKComprobantes($tabla, "id", $_POST["idComprobante"], "UPDATE"); $respuesta = ModeloComprobantes::mdlEditarComprobante($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "La edicion ha sido guardada correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "comprobantes"; } }) </script>'; } } } } /*============================================= BORRAR COMPROBANTE =============================================*/ static public function ctrBorrarComprobante(){ if(isset($_GET["idComprobante"])){ $tabla ="comprobantes"; $datos = $_GET["idComprobante"]; ControladorComprobantes::ctrbKComprobantes($tabla, "id", $_GET["idComprobante"], "ELIMINAR"); // $respuesta = ModeloComprobantes::mdlBorrarComprobante($tabla, $datos); // if($respuesta == "ok"){ // echo'<script> // swal({ // type: "success", // title: "El comprobante ha sido borrado correctamente", // showConfirmButton: true, // confirmButtonText: "Cerrar" // }).then(function(result){ // if (result.value) { // window.location = "comprobantes"; // } // }) // </script>'; // } } } /*============================================= INICIALIZAR COMPROBANTES =============================================*/ static public function ctrIniciarComprobantes($item, $valor){ $tabla = "tmp_comprobantes"; $respuesta = ModeloComprobantes::mdlIniciarTabla($tabla, $item, $valor); return $respuesta; } /*============================================= INICIAR COMPROBANTES =============================================*/ static public function ctrIniciarCargaTmpComprobantes($datos){ $tabla = "tmp_comprobantes"; $respuesta = ModeloComprobantes::mdlIniciarCargaTmpComprobantes($tabla, $datos); return $respuesta; } /*============================================= AGREGAR ULTIMO ID COMPROBANTES =============================================*/ static public function ctrAgregarItemsComprobantes($datos){ $tabla = "tmp_items"; $respuesta = ModeloComprobantes::mdlAgregarItemsComprobantes($tabla, $datos); return $respuesta; } /*============================================= MOSTRAR ITEMS COMPROBANTES =============================================*/ static public function ctrMostrarItemsComprobantes($item, $valor){ $tabla = "tmp_items"; $respuesta = ModeloComprobantes::mdlMostrarComprobantes($tabla, $item, $valor); return $respuesta; } /*============================================= ACTUALIZAR FOLIO DE COMPROBANTES =============================================*/ static public function ctrUpdateFolioComprobantes($item, $valor,$datos){ $tabla = "tmp_comprobantes"; $respuesta = ModeloComprobantes::mdlUpdateFolioComprobantes($tabla, $item, $valor, $datos); return $respuesta; } /*============================================= INICIALIZAR COMPROBANTES =============================================*/ static public function ctrIniciarItems($item, $valor){ $tabla = "tmp_items"; $respuesta = ModeloComprobantes::mdlIniciarTabla($tabla, $item, $valor); return $respuesta; } /*============================================= MOSTRAR COMPROBANTES =============================================*/ static public function ctrMostrarTMPComprobantes($item, $valor){ $tabla = "tmp_comprobantes"; $respuesta = ModeloComprobantes::mdlMostrarComprobantes($tabla, $item, $valor); return $respuesta; } /*============================================= UPDATE FOLIOS =============================================*/ static public function ctrUpdateFolio($campo, $id,$numero){ $tabla = "tmp_items"; $respuesta = ModeloComprobantes::mdlUpdateFolio($tabla,$campo, $id,$numero); return $respuesta; } /*============================================= BORRAR ITEM TMP_ITEMS =============================================*/ static public function ctrBorrarItem($item, $valor){ $tabla = "tmp_items"; $datos = $valor; //uso la misma funcion de modelos con otros parametros $respuesta = ModeloComprobantes::mdlBorrarComprobante($tabla, $datos); return $respuesta; } static public function ctrbKComprobantes($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorComprobantes::ctrMostrarComprobantes($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "cabezacomprobante":"'.$respuesta[2].'", "numero":"'.$respuesta[3].'"}]'; $datos = array("tabla"=>"comprobantes", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloComprobantes::mdlbKComprobante($tabla, $datos); } } <file_sep>/vistas/modulos/inicio.php <?php include("bibliotecas/fechas.inicio.php"); include("bibliotecas/parametros.inicio.php"); include("bibliotecas/caja.inicio.php"); include("bibliotecas/paneles-nube.inicio.php"); include("bibliotecas/ventas-nube.inicio.php"); include("bibliotecas/fechas-cuotas.inicio.php"); ?> <div class="content-wrapper"> <section class="content-header"> <h1> Tablero <?php echo $mesNombre;?> <small>Panel de Control </small> </h1> <ol class="breadcrumb"> <li><a href="inicio"><i class="fa fa-dashboard"></i> Inicio</a></li> <li class="active">Escritorio</li> </ol> </section> <section class="content"> <div class="box-body"> <div class="col-md-4"> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-aqua-active"> <h3 class="widget-user-username">ESCRIBANOS</h3> <h5 class="widget-user-desc">Actualizacion en Nube</h5> </div> <a href="escribanos"> <div class="widget-user-image"> <img class="img-circle" src="vistas/img/usuarios/admin/escribanos.jpg" alt="User Avatar"> </div> </a> <div class="box-footer"> <div class="row"> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header" style="color:red;"><button class="btn btn-link" id="btnMostrarInhabilitados"><?php echo count($escribanosInabilitados);?></button></h5> <span class="description-text" style="color:red;">INHABILITADOS</span> <h3 class="description-header"><button class="btn btn-warning"id="upInhabilitados"><i class="fa fa-cloud-upload" aria-hidden="true"></i></button></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header"><button class="btn btn-link" id="btnMostrarEscribanos"><?php echo count($escribanos);?></button></h5> <span class="description-text">TODOS</span> <h3 class="description-header"><button class="btn btn-success"id="upEscribanos"><i class="fa fa-cloud-upload" aria-hidden="true"></i></button></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4"> <div class="description-block"> <h5 class="description-header"><button class="btn btn-link" id="btnMostrarProductos"><?php echo $productos[0];?></button></h5> <span class="description-text">PRODUCTOS</span> <h3 class="description-header"><button class="btn btn-danger"id="upProductos"><i class="fa fa-cloud-upload" aria-hidden="true"></i></button></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> </div> <!-- /.row --> </div> </div> <!-- /.widget-user --> </div> <div class="col-md-5"> <!-- Widget: user widget style 1 --> <div class="box box-widget widget-user"> <!-- Add the bg color to the header using any of the bg-* classes --> <div class="widget-user-header bg-yellow"> <h3 class="widget-user-username">VENTAS</h3> <h5 class="widget-user-desc">En las delegaciones</h5> </div> <a href="crear-venta"> <div class="widget-user-image"> <img class="img-circle" src="vistas/img/usuarios/admin/colegio.jpg" alt="User Avatar"> </div> </a> <div class="box-footer"> <div class="row"> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header"><?php echo count ($ventasColorado); ?></h5> <h6> - </h6> <span class="description-text">COLORADO</span> <h3 class="description-header"><a href="colorado"><button class="btn btn-success"><i class="fa fa-file-text-o" aria-hidden="true"></i></button></a></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4 border-right"> <div class="description-block"> <h5 class="description-header"><?php echo count($ventas); ?></h5> <h6> - </h6> <span class="description-text">FORMOSA</span> <h3 class="description-header"><a href="ventas"><button class="btn btn-warning"><i class="fa fa-file" aria-hidden="true"></i></button></a></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> <div class="col-sm-4"> <div class="description-block"> <h5 class="description-header"><?php echo count($ventasClorinda); ?></h5> <h6> - </h6> <span class="description-text">CLORINDA</span> <h3 class="description-header"><a href="clorinda"><button class="btn btn-success"><i class="fa fa-file-text-o" aria-hidden="true"></i></button></a></h3> </div> <!-- /.description-block --> </div> <!-- /.col --> </div> <!-- /.row --> </div> </div> <!-- /.widget-user --> </div> <div class="col-md-3"> <div class="row"> <div class="info-box"> <span class="info-box-icon bg-orange"><i class="fa fa-book"></i></span> <div class="info-box-content"> <span class="info-box-text">Máximo de libros </span> <span class="info-box-number"><?php echo $libro["valor"]; ?> Libros</span> </div> </div> </div> <div class="row"> <div class="info-box"> <span class="info-box-icon bg-red"><i class="fa fa-calendar"></i></span> <div class="info-box-content"> <span class="info-box-text">Máximo de Dias</span> <span class="info-box-number"><?php echo $atraso["valor"]; ?> Días</span> </div> </div> </div> <div class="row"> <div class="info-box"> <span class="info-box-icon bg-blue"><i class="fa fa-file-pdf-o"></i></span> <div class="info-box-content"> <span class="info-box-text">Última Factura</span> <span class="info-box-number"><small><?php echo $ultimaVenta["codigo"]." $ ".$ultimaVenta["total"]; ?></small></span> <span class="info-box-number"><small><?php echo $ultimaVenta["nombre"]; ?></small></span> </div> </div> </div> </div> <div class="col-md-3"> <div class="info-box"><a href="cuotas"> <span class="info-box-icon bg-green"><i class="fa fa-flag-o"></i></span></a> <div class="info-box-content"> <span class="info-box-text"><strong>CUOTAS/OSDE</strong></span> <span class="info-box-number"><?php echo $cantCuotas[0]."/".$cantOsde[0];?></span> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> <!-- /.col --> <div class="col-md-4"> <div class="box box-danger"> <!-- /.box-header --> <div class="box-body"> <p>Se generaron las <strong>CUOTAS</strong> del mes de <strong><?php echo $cuotas['mes']."/".$cuotas['anio'];?></strong> en la fecha <?php echo $cuotas['fecha'];?></p> <p>Se generaron los <strong>REINTEGROS de OSDE</strong> del mes de <strong><?php echo $osde['mes']."/".$osde['anio'];?></strong> en la fecha <?php echo $osde['fecha'];?></p> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <div class="col-md-2"> <div class="box box-warning"> <!-- /.box-header --> <div class="box-body"> <span class="info-box-text"><strong>Inhabilitados</strong></span> <button class="btn btn-success" id="revisarInabilitados"> REVISAR </button> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <div class="col-md-3"> <div class="info-box pull-right"> <span class="info-box-icon bg-purple"><i class="fa fa-cloud"></i></span> <div class="info-box-content"> <div style="font-size: x-small;"><strong>Facturas Actualizacion: <?php if(!empty($modificacionesFc)){echo $modificacionesFc['fecha'];}else{echo "NULL";} ?></strong></div> <div style="font-size: x-small;"><strong>Cuotas Actualizacion: <?php if(!empty($modificacionesCuota)){echo $modificacionesCuota['fecha'];}else{echo "NULL";} ?></strong></div> <br> <button class="btn btn-success" id="actualizarCuota"> <i class="fa fa-cloud-upload" aria-hidden="true"> Cuota</i> </button> <button class="btn btn-warning"id="actualizarFc"> <i class="fa fa-cloud-upload" aria-hidden="true"> Factura</i> </button> </div> <!-- /.info-box-content --> </div> <!-- /.info-box --> </div> </div> </section> </div> <div id="modalLoader" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" id="cabezaLoader" style="background:#3c8dbc;color:white"> <!-- <button type="button" class="close" data-dismiss="modal">&times;</button> --> <h4 class="modal-title">Aguarde un instante</h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body"> <center> <img src="vistas/img/afip/loader.gif" alt=""> </center> </div> </div> <div class="modal-footer"> <p id="actualizacionparrafo"></p> </div> </div> </div> </div> <div id="modalMostar" class="modal fade" role="dialog" data-keyboard="false" data-backdrop="static"> <div class="modal-dialog"> <div class="modal-content"> <!--===================================== CABEZA DEL MODAL ======================================--> <div class="modal-header" id="cabezaLoader" style="background:#3c8dbc;color:white"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title" id="titulo"></h4> </div> <!--===================================== CUERPO DEL MODAL ======================================--> <div class="modal-body"> <div class="box-body" id="mostrarBody"> </div> </div> <div class="modal-footer"> <button type="button" id="mostrarSalir" class="btn btn-danger" data-dismiss="modal">Salir</button> </div> </div> </div> </div><file_sep>/modelos/ws.modelo.php <?php require_once "conexion.php"; class ModeloWs{ /*============================================= MOSTRAR ESCRIBANOS WEBSERVICE =============================================*/ static public function mdlMostrarEscribanosWs($tabla, $item, $valor){ if($item != null){ $stmt = Conexion::conectarWs()->prepare("SELECT * FROM $tabla WHERE $item = :$item and activo = 1"); $stmt -> bindParam(":".$item, $valor, PDO::PARAM_STR); $stmt -> execute(); return $stmt -> fetch(); }else{ $stmt = Conexion::conectarWs()->prepare("SELECT * FROM $tabla where activo = 1 order by nombre"); $stmt -> execute(); return $stmt -> fetchAll(); } $stmt -> close(); $stmt = null; } /*============================================= PONER A NULL TODOS LOS ESCRIBANOS DEL WS =============================================*/ static public function mdlNullEscribanosWs($tabla){ $stmt = Conexion::conectarWs()->prepare("UPDATE $tabla SET inhabilitado = 2"); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } /*============================================= CAMBIAR EL ESTADO DE LOS ESCRIBANOS =============================================*/ static public function mdlModificarEstadosWs($tabla, $datos){ $stmt = Conexion::conectarWs()->prepare("UPDATE $tabla SET inhabilitado =:inhabilitado where id=:idcliente"); $stmt->bindParam(":idcliente", $datos['idcliente'], PDO::PARAM_INT); $stmt->bindParam(":inhabilitado", $datos['inhabilitado'], PDO::PARAM_INT); if($stmt->execute()){ return "ok"; }else{ return "error"; } $stmt->close(); $stmt = null; } } <file_sep>/controladores/productos.controlador.php <?php class ControladorProductos{ /*============================================= MOSTRAR PRODUCTOS =============================================*/ static public function ctrMostrarProductos($item, $valor, $orden){ $tabla = "productos"; $respuesta = ModeloProductos::mdlMostrarProductos($tabla, $item, $valor, $orden); return $respuesta; } /*============================================= CREAR PRODUCTO =============================================*/ static public function ctrCrearProducto(){ if(isset($_POST["nuevaDescripcion"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevaDescripcion"]) && preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["nuevoNombre"])){ $tabla = "productos"; $datos = array("id_rubro" => $_POST["nuevoRubro"], "codigo" => $_POST["nuevoCodigo"], "nombre" => strtoupper($_POST["nuevoNombre"]), "descripcion" => strtoupper($_POST["nuevaDescripcion"]), "nrocomprobante" => $_POST["nuevoComprobante"], "cantventa" => $_POST["nuevaCantidadVenta"], "cantminima" => $_POST["nuevaCantidadMinima"], "cuotas" => $_POST["nuevaCuota"], "importe" => $_POST["nuevoImporte"], "obs" => $_POST["nuevaObs"]); $respuesta = ModeloProductos::mdlIngresarProducto($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El producto ha sido guardado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "productos"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡El producto no puede ir con los campos vacíos o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "productos"; } }) </script>'; } } } /*============================================= EDITAR PRODUCTO =============================================*/ static public function ctrEditarProducto(){ if(isset($_POST["editarDescripcion"])){ if(preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarDescripcion"]) && preg_match('/^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]+$/', $_POST["editarNombre"])){ $tabla = "productos"; $datos = array("id" => $_POST["idProducto"], "id_rubro" => $_POST["editarRubro"], "codigo" => $_POST["editarCodigo"], "nombre" => strtoupper($_POST["editarNombre"]), "descripcion" => strtoupper($_POST["editarDescripcion"]), "nrocomprobante" => $_POST["editarComprobante"], "cantventa" => $_POST["editarCantidadVenta"], "cantminima" => $_POST["editarCantidadMinima"], "cuotas" => $_POST["editarCuota"], "importe" => $_POST["editarImporte"], "obs" => $_POST["editarObs"]); // ControladorProductos::ctrbKProductos($tabla, "id", $_POST["idProducto"], "UPDATE"); $respuesta = ModeloProductos::mdlEditarProducto($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El producto ha sido editado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "productos"; } }) </script>'; } }else{ echo'<script> swal({ type: "error", title: "¡El producto no puede ir con los campos vacíos o llevar caracteres especiales!", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "productos"; } }) </script>'; } } } /*============================================= BORRAR PRODUCTO =============================================*/ static public function ctrEliminarProducto(){ if(isset($_GET["idProducto"])){ $tabla ="productos"; $datos = $_GET["idProducto"]; if($_GET["imagen"] != "" && $_GET["imagen"] != "vistas/img/productos/default/anonymous.png"){ unlink($_GET["imagen"]); rmdir('vistas/img/productos/'.$_GET["codigo"]); } ControladorProductos::ctrbKProductos($tabla, "id", $_GET["idProducto"], "ELIMINAR"); $respuesta = ModeloProductos::mdlEliminarProducto($tabla, $datos); if($respuesta == "ok"){ echo'<script> swal({ type: "success", title: "El producto ha sido borrado correctamente", showConfirmButton: true, confirmButtonText: "Cerrar" }).then(function(result){ if (result.value) { window.location = "productos"; } }) </script>'; } } } static public function ctrbKProductos($tabla, $item, $valor,$tipo){ #TRAEMOS LOS DATOS DE IDESCRIBANO $respuesta = ControladorProductos::ctrMostrarProductos($item, $valor); $valor='[{"id":"'.$respuesta[0].'", "nombre":"'.$respuesta[1].'", "descripcion":"'.$respuesta[2].'", "codigo":"'.$respuesta[3].'", "nrocomprobante":"'.$respuesta[4].'", "cantventa":"'.$respuesta[5].'", "id_rubro":"'.$respuesta[6].'", "cantminima":"'.$respuesta[7].'", "cuotas":"'.$respuesta[8].'", "importe":"'.$respuesta[9].'", "ultimonrocompra":"'.$respuesta[10].'", "obs":"'.$respuesta[11].'", "activo":"'.$respuesta[12].'", "obsdel":"'.$respuesta[13].'"}]'; $datos = array("tabla"=>"productos", "tipo"=>$tipo, "datos"=>$valor, "usuario"=>$_SESSION['nombre']); $tabla = "backup"; $respuesta = ModeloProductos::mdlbKProducto($tabla, $datos); } }<file_sep>/ajax/empresa.datos.ajax.php <?php require_once "../controladores/empresa.controlador.php"; require_once "../modelos/empresa.modelo.php"; class AjaxEmpresa{ /*============================================= CAMBIAR DATOS =============================================*/ public $editarEmpresa; public $editarDireccion; public $editarTelefono; public $editarEmail; public $editarCuit; public $editarWeb; public $editarDetalle1; public $editarDetalle2; public function ajaxCambiarDatos(){ $empresa = $this->editarEmpresa; $direccion = $this->editarDireccion; $telefono = $this->editarTelefono; $email = $this->editarEmail; $cuit = $this->editarCuit; $web = $this->editarWeb; $detalle1 = $this->editarDetalle1; $detalle2 = $this->editarDetalle2; $datos = array("empresa" => $empresa , "direccion" => $direccion, "telefono" => $telefono, "email" => $email, "cuit" => $cuit, "web" => $web, "detalle1" => $detalle1, "detalle2" => $detalle2); $respuesta = ControladorEmpresa::ctrEditarEmpresa($datos); echo $respuesta; } } /*============================================= CAMBIAR DATOS =============================================*/ $empresaDatos = new AjaxEmpresa(); $empresaDatos -> editarEmpresa = $_POST["editarEmpresa"]; $empresaDatos -> editarDireccion = $_POST["editarDireccion"]; $empresaDatos -> editarTelefono = $_POST["editarTelefono"]; $empresaDatos -> editarEmail = $_POST["editarEmail"]; $empresaDatos -> editarCuit = $_POST["editarCuit"]; $empresaDatos -> editarWeb = $_POST["editarWeb"]; $empresaDatos -> editarDetalle1 = $_POST["editarDetalle1"]; $empresaDatos -> editarDetalle2 = $_POST["editarDetalle2"]; $empresaDatos -> ajaxCambiarDatos();
bfbcd42574bb5ffaf4a41d2ad3356c424c0b3dcb
[ "JavaScript", "SQL", "Markdown", "PHP" ]
137
PHP
bernardoariel/colegio2021
d5d26cf51590d97eea9ff224c2afc2d07c2dfbae
cb795c89fff95f9c7e9cfca2554f50887910b081
refs/heads/master
<repo_name>polinetuch/giphy-api<file_sep>/assets/javascript/app.js $(document).ready(function() { var gif = ["unicorn", "roses", "shooting stars"]; // displayGifs function re-renders the HTML to display the appropriate content function displayGif() { event.preventDefault(); var gifImage = $(this).attr("data-name"); var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + gifImage + "&api_key=<KEY>&limit=10"; // create an AJAX call for specific gifImage button being clicked $.ajax({ url: queryURL, method: "GET" }).then(function(response) { console.log(queryURL); console.log(response); var results = response.data; // looping over every result item for (var i = 0; i < results.length; i++) { // create a div to hold the gif images var newDiv = $("<div class='gif'>"); console.log(results.length); // create an element to have the rating displayed in browser var rating = results[i].rating; // create a paragraph tag with the result item's rating var pRating = $("<p>").text("Rating: " + rating); // create an image tag to hold all the gifs response from data var gifImage = $("<img>"); // giving the image tag an src attribute of // a property pulled off the result item gifImage.attr("src", results[i].images.fixed_height.url); // append the pRating and gifImage newDiv.append(pRating); newDiv.append(gifImage); // prepending the newDiv to the #displayGifHere $("#displayGifHere").prepend(newDiv); } }); } function renderButtons() { $("#arrayBtn").empty(); // loop through the array of movies for (var i = 0; i < gif.length; i++) { // create a new button var inputButton = $("<button class='gif-button' data-name=>"); // add class named newBtn to the button variable inputButton.addClass("newBtn"); // add data-attribute inputButton.attr("data-name", gif[i]); // provide initial button text inputButton.text(gif[i]); // add the button to the #arrayBtn div $("#arrayBtn").append(inputButton); } displayGif(); } $("#add-gif").on("click", function(event) { event.preventDefault(); // grab the user's search input from text box var moreGifBtn = $("#buttonInput") .val() .trim(); // add the input from the textbox to the array gif.push(moreGifBtn); // calling renderButtons, which handles the processing of the gif array renderButtons(); }); // // add a click event listent to all elements with class of gif-button $(document).on("click", ".gif-button", displayGif); // // calling the renderButtons function to display the initial buttons renderButtons(); }); <file_sep>/README.md Giphy API Visit the app here: https://polinetuch.github.io/giphy-api/ This app allows user to find their favourite gif images through a search bar The search input will be rendered as a button then get a response from api call back function
02b0ac50d7a7a02c5bf07c22336a7474ae2e92a4
[ "JavaScript", "Markdown" ]
2
JavaScript
polinetuch/giphy-api
53a955c844f63d01136db5a9f9544687162dd405
84e7f29f33229b2ed2c268208960e3cf699e1f23
refs/heads/master
<file_sep>// pages/net/index.js Page({ data:{ songs:'',//结果集合 song:'',//搜索的信息 num:0, count:0//为了分页时能躲开第一次空白的缺陷 }, //输入框赋值 binput: function(e){ this.setData({ song: e.detail.value }) }, //点击搜索后的网络请求 search: function(e){ count: 0 var that = this console.log(this.data.song) wx.request({ url: "https://api.imjad.cn/cloudmusic/?", data:{ type: 'search', s: this.data.song, limit: 10, offset: this.data.num }, header: { //"Content-Type":"application/json" }, success: function (res) { console.log(res.data.result.songs) if(that.data.count==0){ that.setData({ songs: res.data.result.songs }) }else{ that.setData({ songs: that.data.songs.concat(res.data.result.songs) }) } }, fail: function (err) { console.log(err) } }) }, //滚动到底部触发事件 searchScrollLower: function () { let that = this; that.data.count = 1; that.data.num = that.data.num +10; that.search(); wx.showToast({ title: '加载中。。。', icon: 'loading', duration: 1000 }) } })<file_sep># 天气微信小程序 - 调用微信小程序定位API - 调用第三方天气接口 - 调用一言 API 获取每日一段话 - 调用一图 API 获取每日一张图<file_sep>//index.js //获取应用实例 var app = getApp() Page({ data: { //加载状态 loadingHidden: false, height: '', //纬度 latitude: '', //经度 longitude: '', //当前城市 city: '', //pm 2.5 pm: '', //当前时间 date: '', //天气数据共四天,今天和之后三天的) weather_data: '' }, onShow: function () { console.log('onShow') var that = this //100%好像不好使 可以获取设备高度 wx.getSystemInfo({ success: function (res) { console.log(res) that.data.height = res.windowHeight; } }) wx.getLocation({ type: 'wgs84', //返回经纬度 success: function (res) { console.log(res) that.data.latitude = res.latitude that.data.longitude = res.longitude //通过经纬度请求数据 wx.request({ //百度天气的api url: 'http://api.map.baidu.com/telematics/v3/weather', data: { //位置 'location': that.data.longitude + ',' + that.data.latitude, //自己的百度ak 'ak':'8<KEY>', //结果输出方式 'output':'json' }, success: function (res) { console.log(res.data) that.setData({ loadingHidden: true, date: res.data.date, city: res.data.results[0].currentCity, pm: res.data.results[0].pm25, weather_data: res.data.results[0].weather_data }) wx.setNavigationBarTitle({ title: that.data.date }) }, fail: function (res){ console.log(res.data) } }) } }) } }) <file_sep>//index.js //获取应用实例 const app = getApp() Page({ data: { date:'', image_url:'', image_author:'', word:'', word_from:'' }, //页面初次渲染完成 onReady: function (e) { var that = this; wx.request({ url: 'https://api.hibai.cn/api/index/index', data: { "TransCode": "030111", "OpenId": "Test" }, method: 'post', header: { 'content-type': 'application/json' }, success: function (res) { console.log(res.data) that.setData({ date: res.data.Body.date, image_url: res.data.Body.img_url, image_author: res.data.Body.img_author, word: res.data.Body.word, word_from: res.data.Body.word_from.concat('<--') }) } }) } })
861d8732b42141e58b7b88e0d32e5c97c623e57e
[ "JavaScript", "Markdown" ]
4
JavaScript
feynman7355608/Small-program-test
c23e09440110d90879cb11644ddc37f39f9341e0
2f8fdfcd9ad95dc5c01c35ab8b54c4791d113edf
refs/heads/main
<repo_name>LanceDrolet/FPSTutorial<file_sep>/Scripts/Weapon.cs using Godot; using System; public class Weapon : Node { [Export] protected float fireRate {get; set;} = (float)0.5; [Export] protected int clipSize {get; set;} = 5; [Export] protected float reloadRate {get; set;} = (float)1.0; int currentAmmo; bool reloading = false; protected RayCast rayCast; protected Label ammoLabel; bool canFire = true; public override void _Ready() { ammoLabel = GetNode<Label>("/root/World/UI/Label"); currentAmmo = clipSize; rayCast = GetNode<RayCast>("../Head/Camera/RayCast"); } public override void _Process(float delta) { if(reloading) ammoLabel.Text = "Reloading..."; else ammoLabel.Text = currentAmmo.ToString() + " / " + clipSize.ToString(); if(Input.IsActionJustPressed("primaryFire") && canFire) { if (currentAmmo > 0 && !reloading) Shoot(); else if(!reloading) Reload(); } if(Input.IsActionJustPressed("Reload") && !reloading) Reload(); } private async void Shoot() { GD.Print("Fired Weapon"); canFire = false; currentAmmo -= 1; CheckCollision(); await ToSignal(GetTree().CreateTimer(fireRate), "timeout"); canFire = true; } private async void Reload() { reloading = true; GD.Print("Reloading!"); await ToSignal(GetTree().CreateTimer(reloadRate), "timeout"); currentAmmo = clipSize; reloading = false; GD.Print("Reload Complete."); } public void CheckCollision() { if(rayCast.IsColliding()) { GD.Print("colliding"); Node collider = (Node)rayCast.GetCollider(); if(collider.IsInGroup("Enemies")) { collider.QueueFree(); GD.Print($"Killed ", collider.Name); } } } } <file_sep>/Scripts/Shotgun.cs using Godot; using System; public class Shotgun : Weapon { [Export] public float fireRange { get; set; } = (float)10; public override void _Ready() { base._Ready(); rayCast.CastTo = new Vector3(0, 0, -fireRange); } } <file_sep>/Scripts/Player.cs using Godot; using System; public class Player : KinematicBody { #region properties [Export] int speed = 10; [Export] int acceleration = 5; [Export] double gravity = 40; [Export] float jump_power = 30; [Export] float mouse_sensitivity = (float)0.3; Vector3 velocity; private Spatial head; private Camera camera; private double cameraXRotation = 0; #endregion public override void _Ready() { velocity = new Vector3(); head = GetNode<Spatial>("Head"); camera = GetNode<Camera>("Head/Camera"); Input.SetMouseMode(Input.MouseMode.Captured); } public override void _Input(InputEvent @event) { if(@event is InputEventMouseMotion eventMouseMotion) { head.RotateY(deg2rad(-eventMouseMotion.Relative.x) * mouse_sensitivity); var x_delta = eventMouseMotion.Relative.y * mouse_sensitivity; if(cameraXRotation + x_delta > -90 && cameraXRotation + x_delta < 90) { camera.RotateX(deg2rad(-x_delta)); cameraXRotation += x_delta; } } base._Input(@event); } public override void _PhysicsProcess(float delta) { var headBasis = head.GlobalTransform.basis; base._PhysicsProcess(delta); var direction = new Vector3(); if(Input.IsActionPressed("Move_Forward")) direction -= headBasis.z; else if(Input.IsActionPressed("Move_Backward")) direction += headBasis.z; if(Input.IsActionPressed("Move_Left")) direction -= headBasis.x; else if(Input.IsActionPressed("Move_Right")) direction += headBasis.x; direction = direction.Normalized(); velocity = velocity.LinearInterpolate(direction * speed, acceleration * delta); velocity.y -= (float)gravity * delta; if(Input.IsActionJustPressed("Jump") && IsOnFloor()) velocity.y += jump_power; velocity = MoveAndSlide(velocity, Vector3.Up); } public override void _Process(float delta) { if (Input.IsActionJustPressed("ui_cancel")) Input.SetMouseMode(Input.MouseMode.Visible); base._Process(delta); } private float deg2rad(double angle) { return (float)((Math.PI / 180) * angle); } } <file_sep>/README.md # FPSTutorial This is the result of a first person shooter tutorial on the Godot game engine. I converted the initial "godotscript" code to C# as a personal project.
7f86251b0098543e17627fb1f0e97e2e6487e12a
[ "Markdown", "C#" ]
4
C#
LanceDrolet/FPSTutorial
26c4ce538aed8235810acb6b7100bbbc63d7b711
b1f90b17aae2386c2b38c3f65244139a3c8233f0
refs/heads/master
<file_sep># MiNETEssentials-MiNET Port of the Bukkit plugin Essentials <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MiNETEssentials.Chat { public static class MCPEColor { public static string COLOR_BLACK = "§0"; public static string COLOR_DBLUE = "§1"; public static string COLOR_DGREEN = "§2"; public static string COLOR_DCYAN = "§3"; public static string COLOR_DRED = "§4"; public static string COLOR_PURPLE = "§5"; public static string COLOR_GOLD = "§6"; public static string COLOR_GRAY = "§7"; public static string COLOR_DGRAY = "§8"; public static string COLOR_BLUE = "§9"; public static string COLOR_BGREEN = "§a"; public static string COLOR_TEAL = "§b"; public static string COLOR_RED = "§c"; public static string COLOR_PINK = "§d"; public static string COLOR_YELLOW = "§e"; public static string COLOR_WHITE = "§f"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using MiNET.Plugins; using MiNET.Plugins.Attributes; namespace MiNETEssentials.Group { [Plugin(PluginName = "MiNETEssentialsGroup", Description = "MiNETEssentials Group Part", PluginVersion = "0.0.1", Author = "FDKPIBC")] public class MiNETEssentialsGroup : Plugin { static ILog Log = LogManager.GetLogger(typeof(MiNETEssentialsGroup)); public override void OnDisable() { Log.Info("MiNETEssentialsChat Disable"); } protected override void OnEnable() { Log.Info("MiNETEssentialsChat Enable"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using MiNET; using MiNET.Plugins; using MiNET.Plugins.Attributes; using MiNET.Utils; using MiNET.Worlds; namespace MiNETEssentials.Spawn { [Plugin(PluginName = "MiNETEssentialsSpawn", Description = "MiNETEssentials Spawn Part", PluginVersion = "0.0.1", Author = "FDKPIBC")] public class MiNETEssentialsSpawn : Plugin, IMiNETEssentialsSpawn { protected static ILog Log = LogManager.GetLogger(typeof(MiNETEssentialsSpawn)); protected override void OnEnable() { Log.Info("MiNETEssentialsChat Enable"); } public override void OnDisable() { Log.Info("MiNETEssentialsChat Disable"); } [Command(Command = "worldspawn")] public void SetWorldSpawnPoint(Player player) { SetWorldSpawnPoint(player, player.KnownPosition.X, player.KnownPosition.Y, player.KnownPosition.Z); } [Command(Command = "worldspawn")] public void SetWorldSpawnPoint(Player player, float x, float y, float z) { if (player.Permissions.IsInGroup(UserGroup.Operator)) { SetWorldSpawn(GetLevelIndex(player.Level.LevelId), new PlayerLocation(x, y, z)); player.Level.BroadcastMessage(string.Format("Player {0} Set World {1} SpawnPoint in x:{2} y:{3} z:{4} ", player.Username, player.Level.LevelId, x, y, z)); } else { player.SendMessage("You have no permission to do this!"); } } [Command(Command = "spawnpoint")] public void SetPlayerSpawnPoint(Player player) { SetPlayerSpawnPoint(player, player.KnownPosition.X, player.KnownPosition.Y, player.KnownPosition.Z); } [Command(Command = "spawnpoint")] public void SetPlayerSpawnPoint(Player player, float x, float y, float z) { SetPlayerSpawn(player, new PlayerLocation(x, y, z)); player.SendMessage(string.Format("Set Home in x:{0} y:{1} z:{2} ", x, y, z)); } private int GetLevelIndex(string Level) { return Context.LevelManager.Levels.FindIndex(t => t.LevelId == Level); } public void SetWorldSpawn(int LevelIndex, PlayerLocation SpawnPoint) { if (SpawnPoint == null) return; Context.LevelManager.Levels[LevelIndex].SpawnPoint = SpawnPoint; } public void SetPlayerSpawn(Player player, PlayerLocation SpawnPoint) { if (SpawnPoint == null) return; player.SpawnPosition = SpawnPoint; } public BlockCoordinates GetSpawn(int LevelIndex) { return new BlockCoordinates(Context.LevelManager.Levels[LevelIndex].SpawnPoint); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MiNET; using MiNET.Utils; namespace MiNETEssentials.Spawn { public interface IMiNETEssentialsSpawn { void SetWorldSpawn(int LevelIndex,PlayerLocation SpawnPoint); void SetPlayerSpawn(Player player, PlayerLocation SpawnPoint); BlockCoordinates GetSpawn(int LevelIndex); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MiNET.Plugins; using MiNET.Plugins.Attributes; using log4net; namespace MiNETEssentials { [Plugin(PluginName = "MiNETEssentials", Description = "MiNET Essentials Plugin", PluginVersion = "0.0.1", Author = "FDKPIBC")] public class MiNETEssentials : Plugin { protected static ILog Log = LogManager.GetLogger(typeof(MiNETEssentials)); public override void OnDisable() { Log.Info("MiNETEssentials Disable"); } protected override void OnEnable() { Log.Info("MiNETEssentials Enable"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using MiNET; using MiNET.Plugins; using MiNET.Plugins.Attributes; namespace MiNETEssentials.Chat { [Plugin(PluginName = "MiNETEssentialsChat", Description = "MiNETEssentials Chat Part", PluginVersion = "0.0.1", Author = "FDKPIBC")] public class MiNETEssentialsChat : Plugin { static ILog Log = LogManager.GetLogger(typeof(MiNETEssentialsChat)); public override void OnDisable() { Log.Info("MiNETEssentialsChat Disable"); } protected override void OnEnable() { Log.Info("MiNETEssentialsChat Enable"); } } }
d46ed1e434757343ccf0414303408fd36171b4b1
[ "Markdown", "C#" ]
7
Markdown
BukkitPluginPort/MiNETEssentials-MiNET
a91f6b874f7bdec346dc3357f787bd1559b8956c
38d77546db0867594675091e6c4acd1194a3a63c
refs/heads/master
<file_sep>$(document).ready(function() { // VARIABLES ========================================================== var triviaQuizList = [ { question : "Who was the voice of Simba in the Lion King 2019?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/simba-bug.webp" }, { question : "Who was the voice of Sarabi in the Lion King 1994?", answers : ["<NAME>", "<NAME>", "<NAME>","<NAME>"], correct : "<NAME>", gif: "assets/images/animated_gif_014_sarabi_baby_simba.gif" }, { question : "Who was the voice of Zazu in the Lion King 1994?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/zazu.webp" }, { question : "Who was the voice of Scar in in the Lion King 2019?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/scar.webp" }, { question : "Who was the voice of Rafiki in Lion King 2019?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/animated_gif_038_rafiki_talking.gif" }, { question : "Who wrote the music score for the Lion King?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/cute-simba.webp" }, { question : "Who directed the Lion King 2019?", answers : ["<NAME>", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/rafiki-painting.webp" }, { question : "Who was the voice of Nala in Lion King 1994?", answers : ["Beyonce", "<NAME>", "<NAME>", "<NAME>"], correct : "<NAME>", gif : "assets/images/nala.webp" }, { question : "Who was the voice of Timon in Lion King 1994?", answers : ["<NAME>", "<NAME>", "<NAME>","<NAME>"], correct : "<NAME>", gif: "assets/images/timon.webp" } ]; // VARS =================================================== var countdown = 10; var intervalId = 0; var index = 0; var questions = triviaQuizList.length; var correct = 0; var wrong = 0; var timeouts = 0; var start; var summaryMessageDiv = "<div id='summary-message'>"; var tryAgainHTML = '<button type="button" id="try-again" onclick="tryAgain()" class="btn btn-info">Try Again</button>'; // hide scores when loading page $("#scores").hide(); // start countdown and show question ========================== function startCountdown() { // test if game is over, if true show summary if (index >= questions) { clearInterval(intervalId); // show summary message $("#summary-section").empty(); showSummary(); } else { // hide/show elements $("#run").empty(); $("#time-section").show(); $("#scores").show(); $("#giphy").hide(); $("#time-message").text("Time Remaining:"); $("#summary-section").empty(); // empty summary-section // display a question and its answers showQuestion(index); // set countdown countdown = 10; // start decrementing the clock intervalId = setInterval(decrement, 1000); } // end else }; // end startCountdown function tryAgain() { countdown = 10; intervalId = 0; index = 0; correct = 0; wrong = 0; timeouts = 0; $("#timeout").text(timeouts); $("#wrong").text(wrong); $("#correct").text(correct); startCountdown(); }; // end tryAgain // decrement the stopwatch and show in html ==================== function decrement() { countdown--; $("#time-number").text(countdown); // what to do when time is up if (countdown === 0 ) { // clearInterval and remove number from countdown clearInterval(intervalId); $("#time-number").html("&nbsp;"); // increment the timeout and update html timeouts++; $("#timeout").text(timeouts); // hide the time section $("#time-section").hide(); // empty the question and answer-list sections $("#question").empty(); $("#answer-list").empty(); // create a message and display it var correctAns = triviaQuizList[index].correct; var timeoutAlert = "Time's up! The correct answer is " + correctAns + "."; // make summary message div $("#summary-section").append(summaryMessageDiv); // append message $("#summary-message").html("<h5>" + timeoutAlert + "</h5>"); $("#summary-message").show(); // show the gif assigned in the question function $("#giphy").fadeIn(2000); // set index to next question index++; // wait 4 seconds before startCountDown function waitForIt(); } // end if }; // end decrement // display question answer set ================================= function showQuestion (i) { // empty current html question first $("#question").empty(); var trivia = triviaQuizList[i]; var question = trivia.question; $("#question").html("<h5>" + question + "</h5>"); // empty current html answer list first $("#answer-list").empty(); // display all the answers for ( var j = 0 ; j <= 3 ; j++ ) { var answer = trivia.answers[j]; var truth = trivia.correct; var answerHTML = '<li class="list-group-item" id="answer" value="' + truth + '">' + answer + '</li>'; $("#question").append(answerHTML); } // end for // insert image object (not displayed) var image = "<img src=" + trivia.gif + " width='300px'>"; $("#giphy").html(image); } // end function // give a summary after the last question ========================= function showSummary() { $("#run").append(tryAgainHTML); $("#time-section").hide(); $("#question").empty(); $("#answer-list").empty(); $("#summary-section").show(); // make summary message div $("#summary-section").append(summaryMessageDiv); // append message var summaryMessage = "<h5>Here's how you did:</h5>"; $("#summary-section").append(summaryMessage); // make html var totalCorrect = "<h6 id='total-correct'>"; var totalWrong = "<h6 id='total-wrong'>"; var totalTimeout = "<h6 id='total-timeout'>"; // append html $("#summary-section").append(totalCorrect).append(totalWrong).append(totalTimeout); // insert text $("#total-correct").text("Correct answers: " + correct); $("#total-wrong").text("Wrong answers: " + wrong); $("#total-timeout").text("Timeouts: " + timeouts); } // end showSummary // 5-second pause to read the answer result ====================== function waitForIt() { setTimeout(function(){ startCountdown() }, 4000); } // end waitForIt // ON CLICK EVENT ===================================================== // compare item selected value to trivia array correct answer $(document).on("click", "li", function () { // capture selection and correct values var selection = $(this).text(); var correctAnswer = $(this).attr("value"); // stop the clock and hide time section clearInterval(intervalId); $("#time-number").html("&nbsp;"); $("#time-section").hide(); // empty the question and answer-list sections $("#question").empty(); $("#answer-list").empty(); // append the summary message div $("#summary-section").append(summaryMessageDiv); // append message $("#summary-section").show(); // show gif $("#giphy").fadeIn(2000); // if no more questions to ask... if (index >= questions) { clearInterval(intervalId); // show summary message showSummary(); } else { // increment the question index index++; // if there is a match ------------------------------- if ( selection === correctAnswer ) { // increment the correct counter and assign to html element correct++; $("#correct").text(correct); // create a message and display it var message = "Yes! " + correctAnswer + " is correct!"; $("#summary-message").html("<h5>" + message + "</h5>"); // wait 4 seconds before startCountDown function waitForIt(); } // end if else { // else must be a mismatch --------------------------- // increment the correct counter and assign to html element wrong++; $("#wrong").text(wrong); // create a message and display it var message = "Sorry! The correct answer is " + correctAnswer + "."; $("#summary-message").html("<h5>" + message + "</h5>"); // wait 4 seconds before startCountDown function waitForIt(); } // end else } // end else }); // end click on list item }); // document ready end <file_sep># TriviaGame Game of trivia with timer on answer responses. This game is focused on animated movie voices and composers, largely on the Lion King movies. It posed a challenge handling the clock functions such as setInterval and setTimeout, learning that js "on" functions may fire when the page is loaded, and why a function is not recognized by a new button. Game starts with a Start button. When activated a series of questions with dropdown answers appear. Each question has a 10-second timer. When a selection is made, a message indicates if the question was right or wrong. Once all the questions have been displayed, a game summary appears with the option to try again. The link is: https://alanleverenz.github.io/TriviaGame/
0f4b06b13b4e214b11df5dfaeff1017d050d7e70
[ "JavaScript", "Markdown" ]
2
JavaScript
dzapps/TriviaGame
cc5962fc8467bdd951fa7c0803ce8bf813d80b3c
fdb2dacdb58699c7cd90407622ab9c278e096e43
refs/heads/master
<file_sep>//var offerOptions = { // offerToReceiveAudio: 1, // offerToReceiveVideo: 1, // iceRestart:true //}; //example: pc.createOffer(offerOptions).then(.... //todo: add a pc.createOffer({iceRestart:true})... in the onicecandidate event while icestatus is failed var NetConnector = {socket:null}; var userProfiles = {}; var self = {}; var cfg = {"iceServers":[{"url":"stun:stun.voipbuster.com"}, {"url": "turn:benusying.6655.la?transport=tcp", "username": "benus", "credential": "<PASSWORD>"} ]}; function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x3|0x8)).toString(16); }); return uuid; }; function writeToChatArea(message) { output("chat",message); }; function writeToMsgArea(message) { output("msg",message); }; function output(type,message) { //document.getElementById(type + "Area").innerHTML += "<p>" + message + "</p>"; }; function login() { var userName = document.getElementById("userName").value; if(userName) { self.userName = userName; NetConnector.login(userName); } else { console.log("No user name"); } }; NetConnector.newPeerConnectionAndOffer = function(userList) { //var offers = {}; for(var key in userList) { if(self.peerId != userList[key]) { userProfiles[userList[key]] = {}; var pc = new RTCPeerConnection(cfg); pc.remotePeerId = userList[key];console.log("new pc.remotePeerId="+pc.remotePeerId); pc.onicecandidate = function(e){NetConnector.onicecandidate(e,userList[key],'offer')}; pc.onconnecting = NetConnector.handleOnPeerConnecting; pc.onconnection = NetConnector.handleOnPeerConnection; pc.onsignalingstatechange = NetConnector.handleOnSignalingStateChange; pc.oniceconnectionstatechange = function(e){NetConnector.handleOnIceConnectionStateChange(e,pc,userList[key])}; pc.onicegatheringstatechange = NetConnector.handleOnIceGatheringStateChange; NetConnector.createDataChannel(pc,userList[key]); (function(pc,key){NetConnector.createOffer(pc,userList[key],{})})(pc,key); /*(function(pc,key){pc.createOffer({iceRestart:true}).then(function (desc) { console.log("In offer, pc.remotePeerId=", pc.remotePeerId); pc.setLocalDescription(desc); console.log("Created local offer", desc); writeToMsgArea("Created local offer"); //offers[userList[key]] = JSON.stringify({ "sdp": desc }); var offer = {}; offer[userList[key]] = JSON.stringify(desc); NetConnector.socket.emit("offer",offer); }, function () {console.warn("Couldn't create offer");writeToMsgArea("Couldn't create offer");})})(pc,key);*/ userProfiles[userList[key]].pc = pc; console.log("Created peer connection to user(" + userList[key] + ")"); } } //return offers; }; NetConnector.createOffer = function(pc,remotePeerId,offerOption) { pc.createOffer(offerOption).then(function (desc) { console.log("In offer, pc.remotePeerId=", remotePeerId); pc.setLocalDescription(desc); console.log("Created local offer", desc); writeToMsgArea("Created local offer"); //offers[userList[key]] = JSON.stringify({ "sdp": desc }); var offer = {}; offer[remotePeerId] = JSON.stringify(desc); NetConnector.socket.emit("offer",offer); }, function () {console.warn("Couldn't create offer");writeToMsgArea("Couldn't create offer");}) }; NetConnector.newPeerConnectionAndAnswer = function(info) { var pc = userProfiles[info.peerId].pc; if(!pc) { pc = new RTCPeerConnection(cfg); pc.onicecandidate = function(e){NetConnector.onicecandidate(e,info.peerId,'answer')}; pc.ondatachannel = function(e){NetConnector.ondatachannel(e,info.peerId)}; pc.onconnecting = NetConnector.handleOnPeerConnecting; pc.onconnection = NetConnector.handleOnPeerConnection; pc.onsignalingstatechange = NetConnector.handleOnSignalingStateChange; pc.oniceconnectionstatechange = NetConnector.handleOnIceConnectionStateChange; pc.onicegatheringstatechange = NetConnector.handleOnIceGatheringStateChange; // once remote stream arrives, show it in the remote video element pc.onaddstream = function (evt) { document.getElementById("audio").src = URL.createObjectURL(evt.stream); }; userProfiles[info.peerId].pc = pc; } var offerDesc = new RTCSessionDescription(JSON.parse(info.offer)); //var toRemoteAnswerDesc = null; pc.setRemoteDescription(offerDesc); pc.createAnswer(function (answerDesc) { console.log("Created local answer for user(" + info.peerId + ")",answerDesc); writeToMsgArea("Created local answer for user(" + info.peerId + ")"); pc.setLocalDescription(answerDesc); //toRemoteAnswerDesc = answerDesc; var answer = {}; answer[info.peerId] = JSON.stringify(answerDesc); NetConnector.socket.emit("answer",answer); //document.getElementById(localAnswerDivId).innerHTML = JSON.stringify(answerDesc); },function() {console.warn("Couldn't create answer");writeToMsgArea("Couldn't create answer");}); //return toRemoteAnswerDesc; }; NetConnector.startConnectionWithAnswer = function(info) { if(userProfiles[info.peerId]) { var answerDesc = new RTCSessionDescription(JSON.parse(info.answer)); userProfiles[info.peerId].pc.setRemoteDescription(answerDesc); console.log("Start a peer connection with user(" + info.peerId + ")"); writeToMsgArea("Start a peer connection with user(" + info.peerId + ")"); } }; NetConnector.createDataChannel = function(pc,remotePeerId) { try { var dc = pc.createDataChannel("dc from " + self.peerId + " to " + remotePeerId,{reliable:false}); console.log("Created data channel"); writeToMsgArea("Created data channel"); dc.onopen = function(e) { console.log('Data channel connected'); writeToMsgArea('Data channel connected'); NetConnector.synOnConnection(); }; dc.onmessage = function(e){NetConnector.handleOnMessage(e,remotePeerId)}; dc.onerror = function(e) { console.warn('Error happened on Data channel:' + e); writeToMsgArea('Error happened on Data channel:' + e); }; userProfiles[remotePeerId].dc = dc; } catch(e) { console.warn("no data"); } }; NetConnector.getPeerId = function() { var peerId = localStorage.getItem(appName + '.peerId'); if(!peerId) { peerId = generateUUID(); localStorage.setItem(appName + '.peerId',peerId); } return peerId; }; NetConnector.init = function() { console.log("Init the network"); this.socket = io.connect("ws://ADMINIB-G0GH1QP:9000");//benusying.6655.la self.peerId = NetConnector.getPeerId(); console.log("peerId: " + self.peerId); this.socket.emit("online",{peerId:self.peerId}); this.socket.on("online",function(info) { if(info.peerId != self.peerId) { userProfiles[info.peerId] = {}; console.log("User " + info.peerId + " is online"); writeToMsgArea("User " + info.peerId + " is online"); } }); this.socket.on("login",function(info) { if(info.peerId != self.peerId) { if(info.userName.substring(0,5) == 'Robot') { userProfiles[info.peerId][info.userName] = {homeIndex:info.homeIndex}; writeToMsgArea("Robot " + info.userName + "login"); console.log("Robot " + info.userName + " login"); } else { userProfiles[info.peerId].userName = info.userName; userProfiles[info.peerId].homeIndex = info.homeIndex; writeToMsgArea("User " + info.userName + "login"); console.log("User " + info.userName + " login"); } NetConnector.getApp().newRemoteAgent(info.userName,info.homeIndex);//the userName including peerId } }); this.socket.on("logout",function(info) { if(info.peerId != self.peerId) { writeToMsgArea("User " + userProfiles[info.peerId].userName + "logout"); if(userProfiles[info.peerId]) { NetConnector.getApp().destoryRemoteAgent(info.userName); if(info.userName.substring(0,5) == 'Robot') { delete userProfiles[info.peerId][info.userName]; } else { delete userProfiles[info.peerId]; } } } }); this.socket.on("env",function(info) { console.log("Get Env"); if(info.peerIdList && info.peerIdList.length > 0) { console.log("Totally, " + info.peerIdList.length + " users are online"); console.log("Online user list: " + info.peerIdList); //preset user profiles var userName; var homeIndex; for(var key in info.peerIdList) { if(info.peerIdList[key] != self.peerId) { userProfiles[info.peerIdList[key]] = {}; if(info.loginedUserNameList[info.peerIdList[key]]) { userName = info.loginedUserNameList[info.peerIdList[key]].userName; homeIndex = info.loginedUserNameList[info.peerIdList[key]].homeIndex; if(userName && homeIndex) { userProfiles[info.peerIdList[key]].userName = userName; console.log("User " + userName + " existed"); NetConnector.getApp().newRemoteAgent(userName,homeIndex); } for(var name in info.loginedUserNameList[info.peerIdList[key]]) { if(name.substring(0,5) == 'Robot') { console.log("Robot " + name + " existed"); NetConnector.getApp().newRemoteAgent(name + '_' + info.peerIdList[key],info.loginedUserNameList[info.peerIdList[key]][name].homeIndex); } } } } } NetConnector.newPeerConnectionAndOffer(info.peerIdList); //console.log("Offer created for Users: " + Object.keys(offers)); //NetConnector.socket.emit("offer",offers); } else { writeToMsgArea("I am the first one"); } NetConnector.getApp().go(); }); this.socket.on("offer",function(info) { if(userProfiles[info.peerId]) { writeToMsgArea("Get offer from " + info.peerId); NetConnector.newPeerConnectionAndAnswer(info); } }); this.socket.on("answer",function(info) { if(userProfiles[info.peerId]) { writeToMsgArea("Get answer from " + info.peerId); NetConnector.startConnectionWithAnswer(info); } }); this.socket.on("ice",function(info) { if(userProfiles[info.peerId]) { writeToMsgArea("Get ice from " + info.peerId); console.log("Get ice from " + info.peerId + ":" + info.candidate); userProfiles[info.peerId].pc.addIceCandidate(new RTCIceCandidate(JSON.parse(info.candidate))); } }); this.socket.on("message",function(msg) { console.log("Get a msg: " + msg); output(msg.type,msg.content); }); }; NetConnector.close = function() { if(userProfiles) { console.log("Ready to close RTC connection"); for(var peerId in userProfiles) { if(userProfiles[peerId].dc) { userProfiles[peerId].dc.close(); console.log("Closed dc(" + userProfiles[peerId].dc.label+ ")"); } if(userProfiles[peerId].pc) { userProfiles[peerId].pc.close(); console.log("Closed pc"); } } } }; NetConnector.login = function(userName,homeNodeIndex) { if(NetConnector.socket) { NetConnector.socket.emit("login",{peerId:self.peerId,userName:userName,homeIndex:{x:homeNodeIndex.x,y:homeNodeIndex.y}}); } }; NetConnector.logout = function(userName) { if(NetConnector.socket) { NetConnector.socket.emit("logout",{peerId:self.peerId,userName:userName}); } }; NetConnector.sendToServer = function(type,info) { if(NetConnector.socket) { NetConnector.socket.emit(type,info); } }; NetConnector.synValue = function(index,value) {//for Cube game console.log("syn value" + index + "," + value); NetConnector.syn({index:index,value:value}); }; NetConnector.syn = function(data) {console.log("in syn" + data); var timestamp = new Date().getTime(); for(var remotePeerId in userProfiles) { if(userProfiles[remotePeerId].dc) { if(userProfiles[remotePeerId].dc.readyState == 'open') { var synData; if(!data) {//if there is no data, just syn timestamp synData = JSON.stringify({syn:{timestamp:timestamp}}); } else if(data.echo) { synData = JSON.stringify({syn:{echo:data.echo}}); } else if(data.values) {//for Cube game synData = JSON.stringify({syn:{values:data.values}}); } else if(data.value) {//for Cube game synData = JSON.stringify({syn:{index:data.index,value:data.value}}); } else { var latency = NetConnector.getApp().getLatency(remotePeerId); synData = JSON.stringify({syn:{latency:latency,timestamp:timestamp,objectName:data.objectName,movement:data.movement,status:data.status,cellIndex:{x:data.cellIndex.x,y:data.cellIndex.y,z:data.cellIndex.z}}}); } console.log("syn: " + synData); userProfiles[remotePeerId].dc.send(synData); } else { console.warn("Fail to syn data to user(" + remotePeerId + ") as dc is no open"); } } } }; NetConnector.sendToPeers = function() { var input = document.getElementById("myWords").value; if(input) { for(var remotePeerId in userProfiles) { if(userProfiles[remotePeerId].dc) { if(userProfiles[remotePeerId].dc.readyState == 'open') { userProfiles[remotePeerId].dc.send(JSON.stringify({message:input})); console.log("Sent msg to user(" + remotePeerId + ")"); } else { console.warn("Fail to send msg to user(" + remotePeerId + ") as dc is not open"); writeToMsgArea("Fail to send msg to user(" + remotePeerId + ") as dc is not open"); } } else { console.warn("Fail to send msg to user(" + remotePeerId + ") as dc is not received"); writeToMsgArea("Fail to send msg to user(" + remotePeerId + ") as dc is not received"); } } writeToChatArea(input); document.getElementById("myWords").value = ""; } }; NetConnector.ondatachannel = function (e,remotePeerId) { var dataChannel = e.channel || e; console.log("Received data channel",arguments); writeToMsgArea("Received data channel"); dataChannel.onmessage = function(e){NetConnector.handleOnMessage(e,remotePeerId)}; userProfiles[remotePeerId].dc = dataChannel; NetConnector.synOnConnection(); }; NetConnector.getDataConnectionNum = function() { var count = 0; for(var remotePeerId in userProfiles) { if(userProfiles[remotePeerId].dc) { count++; } } return count; } NetConnector.synOnConnection = function() { if(NetConnector.getApp().getLocalGameCellValues) {//for Cube game var count = NetConnector.getDataConnectionNum(); NetConnector.getApp().updateNetConnectionNum(count); //NetConnector.updateNetConnectionNum(count); var values = NetConnector.getApp().getLocalGameCellValues(); NetConnector.syn({values:values}); } else { NetConnector.syn();//syn timestamp to all others??? } }; NetConnector.handleOnPeerConnecting = function() { console.log("data channel connecting"); }; NetConnector.handleOnPeerConnection = function() { console.log("data channel connected"); }; NetConnector.handleOnSignalingStateChange = function(state) { console.log('signaling state change:', state); }; NetConnector.handleOnIceConnectionStateChange = function(state,pc,remotePeerId) { console.log('ice connection state changed to ' + state.currentTarget.iceConnectionState, state); if(state.currentTarget.iceConnectionState == "failed" && pc && remotePeerId) { console.log('ice restart'); NetConnector.createOffer(pc,remotePeerId,{iceRestart:true}); } }; NetConnector.handleOnIceGatheringStateChange = function(state) { console.log('ice gathering state changed to ' + state.currentTarget.iceGatheringState, state); }; NetConnector.handleOnMessage = function(e,remotePeerId) { var data = JSON.parse(e.data); if(data.syn) {console.log(data); if(data.syn.timestamp) { NetConnector.syn({echo:data.syn.timestamp});//echo the timestamp for calc network delay } else if(data.syn.echo) { var latency = new Date().getTime() - Number(data.syn.echo); NetConnector.getApp().setLatency(remotePeerId,latency); } else if(data.syn.values) {//for Cube game NetConnector.getApp().initRemoteGame(remotePeerId,data.syn.values) } else if(data.syn.value) {//for Cube game NetConnector.getApp().updateRemoteGameCellValue(remotePeerId,data.syn.index,data.syn.value) } if(data.syn.objectName) { //console.log("Got a message: " + e.data); NetConnector.getApp().setSynData(data.syn.objectName,data.syn); } } else if(data.message) { writeToChatArea(data.message,"text-info"); } }; NetConnector.onicecandidate = function(e,remotePeerId,type) { if(e.candidate) { writeToMsgArea("Sent ice to user(" + remotePeerId + ")"); NetConnector.sendToServer("ice",{peerId:remotePeerId, candidate:JSON.stringify( e.candidate )}); } /*else { //The idea of this code block is to send offer/answer with icd candidate, which is referenced from serverless-webrtc.js console.log("Get latest desc with ice candidate and send to user(" + remotePeerId + ")"); var desc = {}; desc[remotePeerId] = JSON.stringify(userProfiles[remotePeerId].pc.localDescription); NetConnector.socket.emit(type,desc); }*/ }; NetConnector.getApp = function() { return Processing.getInstanceById(appName); } //it is a temp function NetConnector.updateNetConnectionNum = function(count) { var context = NetConnector.getApp.externals.context; if(context) { context.fillStyle = "blue"; context.fillText("peers: " + count,5,5); } }; window.onload = function() { //NetConnector.init(); /* document.getElementById("userName").onkeydown = function(e) { e = e || event; if (e.keyCode === 13) { login(); } }; document.getElementById("myWords").onkeydown = function(e) { e = e || event; if (e.keyCode === 13) { NetConnector.sendToPeers(); } };*/ } window.onunload = function() { NetConnector.close(); return "Close"; };<file_sep># Cube It is a small game running on mobile browsers. Allow at most 5 peers to play game together.
8424f6e4548597a15ec9a625cacedf15349f9102
[ "JavaScript", "Markdown" ]
2
JavaScript
benus/Cube
869c6c2b4c8939a7587c4cc3085ccbb8621425ad
c89cfcf8441bd3a6a2ce5bdd1bfc263367df3457
refs/heads/master
<file_sep>using System.ComponentModel.DataAnnotations; using LinqToTwitter; namespace SociOLRoom.Analytics.Models { public class Tag { public string Name { get; set; } public double Confidence { get; set; } } }<file_sep>using System; using SociOLRoom.Analytics.Core; namespace SociOLRoom.Analytics.Models { public class Statistics { public int Women { get; set; } public int Men { get; set; } public int Age { get; set; } public NamePercent Emotion { get; set; } public int Children { get; set; } public DateTime? From { get; set; } public NamePercent Category { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace SociOLRoom.Analytics.Core { public class TranslatorService { public class AdmAccessToken { public string access_token { get; set; } public string token_type { get; set; } public string expires_in { get; set; } public string scope { get; set; } } public static async Task<string> Translate(string str, string from, string to) { var bearer = await Auth(); string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(str) + "&from=" + from + "&to=" + to; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", bearer); var xml = await client.GetStringAsync(uri); return XDocument.Parse(xml).Root.Value; } } public static async Task<string> Auth() { string clientID = Config.Bing.TranslatorClientID; string clientSecret = Config.Bing.TranslatorClientSecret; using (var httpClient = new HttpClient()) { var response = await httpClient.PostAsync("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13", new FormUrlEncodedContent( new KeyValuePair<string, string>[] { new KeyValuePair<string,string>("grant_type", "client_credentials"), new KeyValuePair<string,string>("client_id", clientID), new KeyValuePair<string,string>("client_secret", clientSecret), new KeyValuePair<string,string>("scope", "http://api.microsofttranslator.com"), })); response.EnsureSuccessStatusCode(); var json = await response.Content.ReadAsStringAsync(); dynamic admAccessToken = JObject.Parse(json); return "Bearer " + admAccessToken.access_token; } } } }<file_sep>namespace SociOLRoom.Analytics.Models { public class NamePercent { public int Percent { get; set; } public string Name { get; set; } } }<file_sep>using System; using Microsoft.ProjectOxford.Emotion.Contract; using Microsoft.ProjectOxford.Vision.Contract; using Newtonsoft.Json; using Face = Microsoft.ProjectOxford.Face.Contract.Face; namespace SociOLRoom.Analytics.Core { public class SocialAnalytics { [JsonProperty(PropertyName = "id")] public string Id { get; set; } public ulong TweetID { get; set; } public SocialNetwork SocialNetwork { get; set; } public AnalysisResult AnalysisResult { get; set; } public string ImageUrl { get; set; } public DateTime CreatedAt { get; set; } public Emotion[] EmotionResult { get; set; } public Face[] FaceResult { get; set; } public string From { get; set; } public string Tags { get; set; } public long CreatedAtTimeStamp { get; set; } } }<file_sep>using System; namespace SociOLRoom.Analytics.Core { public class Instagram { public string ImageUrl { get; set; } public string Id { get; set; } public string Tags { get; set; } public DateTime CreatedAt { get; set; } public string User { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Http; using Microsoft.Azure.Documents.Client; using SociOLRoom.Analytics.Core; using SociOLRoom.Analytics.Models; namespace SociOLRoom.Analytics.Controllers { public class DataController : ApiController { private readonly DocumentClient _client; public DataController() { this._client = new DocumentClient(new Uri(Config.EndpointUri), Config.PrimaryKey); } [HttpGet] public Statistics Statistics() { Statistics statistics = new Statistics(); statistics.Men = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .SelectMany(s => s.FaceResult).Where(s => s.FaceAttributes.Gender == "male").ToList().Count; statistics.Women = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .SelectMany(s => s.FaceResult).Where(s => s.FaceAttributes.Gender == "female").ToList().Count; var ages = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .SelectMany(s => s.FaceResult).Select(s => s.FaceAttributes.Age).ToList(); statistics.Children = ages.Count(a => a < 18); statistics.Age = (int)ages.Average(); var lastItem = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .OrderByDescending(c => c.CreatedAtTimeStamp).Take(1).ToList(); statistics.From = lastItem.FirstOrDefault()?.CreatedAt; var emotions = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .SelectMany(s => s.EmotionResult).Select(s => s.Scores).ToList(); var emotionStat = new[] { new {Name = "Anger", Value = emotions.Sum(t => t.Anger)}, new {Name = "Contempt", Value = emotions.Sum(t => t.Contempt)}, new {Name = "Disgust", Value = emotions.Sum(t => t.Disgust)}, new {Name = "Fear", Value = emotions.Sum(t => t.Fear)}, new {Name = "Happiness", Value = emotions.Sum(t => t.Happiness)}, new {Name = "Neutral", Value = emotions.Sum(t => t.Neutral)}, new {Name = "Sadness", Value = emotions.Sum(t => t.Sadness)}, new {Name = "Surprise", Value = emotions.Sum(t => t.Surprise)} }; var topEmotion = emotionStat.OrderByDescending(e => e.Value).FirstOrDefault(); if (topEmotion != null) statistics.Emotion = new NamePercent { Name = topEmotion.Name, Percent = (int)Math.Round(topEmotion.Value / emotionStat.Sum(t => t.Value) * 100) }; var categories = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName)) .SelectMany(s => s.AnalysisResult.Categories).ToList(); var predicateCat = categories.GroupBy(s => s.Name).Select(s => new { Name = s.Key, Value = s.Sum(g => g.Score) }); var cat = predicateCat.OrderByDescending(s => s.Value).FirstOrDefault(); statistics.Category = new NamePercent { Name = cat.Name, Percent = (int)Math.Round(cat.Value / predicateCat.Sum(s => s.Value) * 100) }; return statistics; } [HttpGet] public List<SocialAnalytics> Wall() { FeedOptions queryOptions = new FeedOptions { MaxItemCount = -1 }; var items = this._client.CreateDocumentQuery<SocialAnalytics>( UriFactory.CreateDocumentCollectionUri(Config.DataBaseId, Config.DatabaseCollectionName), queryOptions) .OrderByDescending(c => c.CreatedAtTimeStamp).Take(52).ToList(); foreach (var item in items) { var culture = HttpContext.Current.Request.UserLanguages[0]; if (culture.StartsWith("en", StringComparison.InvariantCultureIgnoreCase)) item.AnalysisResult.Description.Captions[0] = item.AnalysisResult.Description.Captions[1]; else if (culture.StartsWith("fr", StringComparison.InvariantCultureIgnoreCase)) item.AnalysisResult.Description.Captions[0] = item.AnalysisResult.Description.Captions[0]; else if (culture.StartsWith("es", StringComparison.InvariantCultureIgnoreCase)) item.AnalysisResult.Description.Captions[0] = item.AnalysisResult.Description.Captions[2]; } return items; } } } <file_sep>using System; using System.Drawing; using System.Drawing.Imaging; namespace SociOLRoom.Analytics.Core { public static class PictureHelper { public static Image AutoCrop(this Bitmap bmp) { if (Image.GetPixelFormatSize(bmp.PixelFormat) != 32) throw new InvalidOperationException("Autocrop currently only supports 32 bits per pixel images."); // Initialize variables var cropColor = Color.White; var bottom = 0; var left = bmp.Width; // Set the left crop point to the width so that the logic below will set the left value to the first non crop color pixel it comes across. var right = 0; var top = bmp.Height; // Set the top crop point to the height so that the logic below will set the top value to the first non crop color pixel it comes across. var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat); unsafe { var dataPtr = (byte*)bmpData.Scan0; for (var y = 0; y < bmp.Height; y++) { for (var x = 0; x < bmp.Width; x++) { var rgbPtr = dataPtr + (x * 4); var b = rgbPtr[0]; var g = rgbPtr[1]; var r = rgbPtr[2]; var a = rgbPtr[3]; // If any of the pixel RGBA values don't match and the crop color is not transparent, or if the crop color is transparent and the pixel A value is not transparent if ((cropColor.A > 0 && (b != cropColor.B || g != cropColor.G || r != cropColor.R || a != cropColor.A)) || (cropColor.A == 0 && a != 0)) { if (x < left) left = x; if (x >= right) right = x + 1; if (y < top) top = y; if (y >= bottom) bottom = y + 1; } } dataPtr += bmpData.Stride; } } bmp.UnlockBits(bmpData); if (left < right && top < bottom) return bmp.Clone(new Rectangle(left, top, right - left, bottom - top), bmp.PixelFormat); return null; // Entire image should be cropped, so just return null } } }<file_sep>using System; using System.Net; using System.Threading.Tasks; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; namespace SociOLRoom.Analytics.Core { public static class DocDBExtension { public static async Task CreateDatabaseIfNotExists(this DocumentClient client, string databaseName) { // Check to verify a database with the id=FamilyDB does not exist try { await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName)); } catch (DocumentClientException de) { // If the database does not exist, create a new database if (de.StatusCode == HttpStatusCode.NotFound) { await client.CreateDatabaseAsync(new Database { Id = databaseName }); } else { throw; } } } public static async Task CreateDocumentCollectionIfNotExists(this DocumentClient client, string databaseName, string collectionName) { try { await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName)); } catch (DocumentClientException de) { // If the document collection does not exist, create a new collection if (de.StatusCode == HttpStatusCode.NotFound) { DocumentCollection collectionInfo = new DocumentCollection(); collectionInfo.Id = collectionName; // Configure collections for maximum query flexibility including string range queries. collectionInfo.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 }); // Here we create a collection with 400 RU/s. await client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri(databaseName),new DocumentCollection { Id = collectionName },new RequestOptions { OfferThroughput = 400 }); } else { throw; } } } public static async Task CreateDocumentIfNotExists<T>(this DocumentClient client, string databaseName, string collectionName, T document, Func<T, string> getIdFunc) { try { await client.ReadDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, getIdFunc(document))); } catch (DocumentClientException de) { if (de.StatusCode == HttpStatusCode.NotFound) { await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), document); } else { throw; } } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.WebJobs; using Microsoft.ProjectOxford.Emotion; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Vision; using Microsoft.ServiceBus.Messaging; using SociOLRoom.Analytics.Core; namespace SociOLRoom.Analytics.ProcessImages { public class Functions { public static async Task ProcessQueueMessage(TextWriter log, [ServiceBusTrigger("sociolroom", AccessRights.Listen)] SocialAnalytics socialAnalytics, [ServiceBus("sociolroom")] IAsyncCollector<SocialAnalytics> output) { var client = new DocumentClient(new Uri(Config.EndpointUri), Config.PrimaryKey); try { if (string.IsNullOrWhiteSpace(socialAnalytics.Id)) { log.WriteLine(DateTime.UtcNow + " -- ProcessImage: id is null"); return; } using (ImageProcessor processor = new ImageProcessor()) { var result = await processor.ProcessImage(socialAnalytics.ImageUrl); socialAnalytics.AnalysisResult = result.VisionTask.Result; socialAnalytics.EmotionResult = result.EmotionTask.Result; socialAnalytics.FaceResult = result.FaceTask.Result; await client.CreateDocumentIfNotExists(Config.DataBaseId, Config.DatabaseCollectionName, socialAnalytics, (t) => t.Id.ToString()); } } catch (ClientException ex) { if (ex.Error.Code != "InvalidImageUrl") { log.WriteLine(DateTime.UtcNow + " -- ProcessImage: " + ex.Message); await output.AddAsync(socialAnalytics); } } catch (Exception ex) { log.WriteLine(DateTime.UtcNow + " -- ProcessImage: " + ex.Message); await output.AddAsync(socialAnalytics); } await Task.Delay(TimeSpan.FromSeconds(30)); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.WebJobs; using Microsoft.ServiceBus.Messaging; using SociOLRoom.Analytics.Core; namespace SociOLRoom.Analytics.InstagramListener { public class Functions { // This function will get triggered/executed when a new message is written // on an Azure Queue called queue. [NoAutomaticTriggerAttribute] public static async Task ProcessMethod(TextWriter log) { string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "sociolroom"); DateTime createdDateTime = DateTime.MinValue; while (true) { try { var grams = await InstagramService.GetPhoto(Config.Tag); grams = grams.OrderBy(c => c.CreatedAt).ToList(); List<BrokeredMessage> toSend = new List<BrokeredMessage>(); foreach (var gram in grams) { if (gram.CreatedAt > createdDateTime) { SocialAnalytics analytics = new SocialAnalytics { SocialNetwork = SocialNetwork.Instagram, Id = gram.Id, CreatedAt = gram.CreatedAt, CreatedAtTimeStamp = gram.CreatedAt.Ticks, From = gram.User, Tags = gram.Tags, ImageUrl = gram.ImageUrl }; toSend.Add(new BrokeredMessage(analytics)); createdDateTime = gram.CreatedAt; } } await client.SendBatchAsync(toSend); } catch (Exception ex) { log.WriteLine(DateTime.UtcNow + " -- InstagramListener: " + ex.Message); } await Task.Delay(TimeSpan.FromMinutes(3)); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using LinqToTwitter; using SociOLRoom.Analytics.Core; namespace TwitterListener { public class TwitterService { private TwitterContext _twitterCtx; public event EventHandler<GenericEventArgs<Status>> OnNewMessage; static IAuthorizer DoApplicationOnlyAuth() { var auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = Config.Twitter.ConsumerKey, ConsumerSecret = Config.Twitter.ConsumerSecret, AccessToken = Config.Twitter.AccessToken, AccessTokenSecret = Config.Twitter.AccessTokenSecret } }; return auth; } public async Task Authenticate() { var auth = DoApplicationOnlyAuth(); await auth.AuthorizeAsync(); _twitterCtx = new TwitterContext(auth); } public async Task GetStreamTweets(string tag) { await (from strm in _twitterCtx.Streaming where strm.Type == StreamingType.Filter && strm.Track == tag select strm) .StartAsync(strm => { if (strm.EntityType == StreamEntityType.Status) { var status = strm.Entity as Status; if (status.Entities != null) { if (status.Entities.MediaEntities != null && status.Entities.MediaEntities.Count > 0 && status.RetweetedStatus.CreatedAt == DateTime.MinValue) { OnNewMessage?.Invoke(this, new GenericEventArgs<Status> { Data = status }); } } } return Task.FromResult(0); }); } public async Task<List<Status>> GetTweets(string tag, ulong sinceId = 0) { var auth = DoApplicationOnlyAuth(); await auth.AuthorizeAsync(); List<Status> tweets = new List<Status>(); using (var twitterCtx = new TwitterContext(auth)) { Search searchResponse = await (twitterCtx.Search.Where(search => search.Type == SearchType.Search && search.Query == "#" + tag + " -filter:retweets" && search.ResultType == ResultType.Recent && search.SinceID == sinceId && search.IncludeEntities == true)).SingleOrDefaultAsync(); if (searchResponse != null && searchResponse.Statuses != null) //searchResponse.Statuses.ForEach(tweet => tweet.Entities. { foreach (var tweet in searchResponse.Statuses) { if (tweet.Entities != null) { if (tweet.Entities.MediaEntities != null && tweet.Entities.MediaEntities.Count > 0 && tweet.RetweetedStatus.CreatedAt == DateTime.MinValue) { tweets.Add(tweet); } } } } } return tweets; } } }<file_sep>using System; using System.Threading.Tasks; using Microsoft.ProjectOxford.Emotion; using Microsoft.ProjectOxford.Face; using Microsoft.ProjectOxford.Vision; using Microsoft.ProjectOxford.Vision.Contract; namespace SociOLRoom.Analytics.Core { public class ImageProcessor : IDisposable { private readonly VisionServiceClient _visionServiceClient; private readonly EmotionServiceClient _emotionServiceClient; private readonly FaceServiceClient _faceServiceClient; public ImageProcessor() { _visionServiceClient = new VisionServiceClient(Config.Cognitive.VisionAPIKey); _emotionServiceClient = new EmotionServiceClient(Config.Cognitive.EmotionAPIKey); _faceServiceClient = new FaceServiceClient(Config.Cognitive.FaceAPIKey); } public async Task<CogniviteResult> ProcessImage(string url) { VisualFeature[] visualFeatures = { VisualFeature.Adult, VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description, VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags }; CogniviteResult result = new CogniviteResult(); result.VisionTask = _visionServiceClient.AnalyzeImageAsync(url, visualFeatures); result.EmotionTask = _emotionServiceClient.RecognizeAsync(url); result.FaceTask = _faceServiceClient.DetectAsync(url, false, true,new[] {FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses}); await Task.WhenAll(result.VisionTask, result.EmotionTask, result.FaceTask); var enTxt = result.VisionTask.Result.Description.Captions[0].Text; var frTxt = await TranslatorService.Translate(enTxt, "en", "fr"); var esTxt = await TranslatorService.Translate(enTxt, "en", "es"); result.VisionTask.Result.Description.Captions = new[] { new Caption { Text = frTxt }, result.VisionTask.Result.Description.Captions[0], new Caption { Text = esTxt }, }; return result; } public void Dispose() { if (_faceServiceClient != null) _faceServiceClient.Dispose(); } } }<file_sep># SociolRoom Analytics Sociol Room is a webiste displaying in a wall the cognitive analysis results of pictures posted in Twitter and Instagram with a specific hashtag. You can have a demo: http://sociolroom-analytics.azurewebsites.net #Before starting The website is designed to run on Microsoft Azure. The steps to run the app are: ##Azure provisionning * Open an Azure account * Create cognitive service for Vision, Emotion, Face https://www.microsoft.com/cognitive-services/en-us/apis * Create an Bing Translator app https://www.microsoft.com/en-us/translator/getstarted.aspx * Create a Document DB database * Create an Azure service bus * Create a storage * Create an app service and a web site * Enable Always On https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure/ * Create a Twitter app https://dev.twitter.com/ ##Configuration * Clone the repository * Create a folder named .config on the root folder with 2 files: secretAppSettings.config and secretConnectionStrings.config * Replace with your keys * secretAppSettings.config <pre> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;appSettings&gt; &lt;add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[ENDPOINT];SharedAccessKeyName=[KeyName];SharedAccessKey=[Key]"/&gt; &lt;add key="DocumentDBUrl" value="" /&gt; &lt;add key="DocumentDBPrimaryKey" value="" /&gt; &lt;add key="Cognitive:VisionAPIKey" value="" /&gt; &lt;add key="Cognitive:EmotionAPIKey" value="" /&gt; &lt;add key="Cognitive:FaceAPIKey" value="" /&gt; &lt;add key="Bing:TranslatorClientID" value="" /&gt; &lt;add key="Bing:TranslatorClientSecret" value="" /&gt; &lt;add key="Twitter:ConsumerKey" value="" /&gt; &lt;add key="Twitter:ConsumerSecret" value="" /&gt; &lt;add key="Twitter:AccessToken" value="" /&gt; &lt;add key="Twitter:AccessTokenSecret" value="" /&gt; &lt;/appSettings&gt; </pre> secretConnectionStrings.config <pre> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;connectionStrings&gt; &lt;add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=[Account];AccountKey=[Key]" /&gt; &lt;add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=[Account]AccountKey=[Key]" /&gt; &lt;add name="AzureWebJobsServiceBus" connectionString="Endpoint=sb://[ENDPOINT];SharedAccessKeyName=[KeyName];SharedAccessKey=[Key]" /&gt; &lt;/connectionStrings&gt; </pre> Enjoy ! <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.UI; using LinqToTwitter; using Microsoft.ProjectOxford.Vision.Contract; using SociOLRoom.Analytics.Core; using SociOLRoom.Analytics.Models; using Rectangle = System.Drawing.Rectangle; namespace SociOLRoom.Analytics.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } [OutputCache(Duration = 84600, Location = OutputCacheLocation.Any)] public async Task<FileResult> Picture(string url) { try { using (HttpClient client = new HttpClient()) { var stream = await client.GetStreamAsync(url); Bitmap bitmap = (Bitmap)Image.FromStream(stream); Bitmap clone = new Bitmap(bitmap.Width, bitmap.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); using (Graphics gr = Graphics.FromImage(clone)) { gr.DrawImage(bitmap, new Rectangle(0, 0, clone.Width, clone.Height)); } var img = clone.AutoCrop(); FileContentResult result; using (var memStream = new System.IO.MemoryStream()) { img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg); result = this.File(memStream.GetBuffer(), "image/jpeg"); } return result; } } catch (Exception) { return new FileContentResult(null, "image/jpeg"); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; using Newtonsoft.Json.Serialization; namespace SociOLRoom.Analytics { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); JsonMediaTypeFormatter jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter; //jsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } } <file_sep>using Microsoft.Azure; namespace SociOLRoom.Analytics.Core { public class Config { public const string Tag = "parcol"; public static string EndpointUri = CloudConfigurationManager.GetSetting("DocumentDBUrl"); public static string PrimaryKey = CloudConfigurationManager.GetSetting("DocumentDBPrimaryKey"); public const string DatabaseCollectionName = "SocialAnalyticsV3"; public const string DataBaseId = "SociOLRoom"; public class Cognitive { public static string VisionAPIKey = CloudConfigurationManager.GetSetting("Cognitive:VisionAPIKey"); public static string EmotionAPIKey = CloudConfigurationManager.GetSetting("Cognitive:EmotionAPIKey"); public static string FaceAPIKey = CloudConfigurationManager.GetSetting("Cognitive:FaceAPIKey"); } public class Bing { public static string TranslatorClientID = CloudConfigurationManager.GetSetting("Bing:TranslatorClientID"); public static string TranslatorClientSecret = CloudConfigurationManager.GetSetting("Bing:TranslatorClientSecret"); } public class Twitter { public static string ConsumerKey = CloudConfigurationManager.GetSetting("Twitter:ConsumerKey"); public static string ConsumerSecret = CloudConfigurationManager.GetSetting("Twitter:ConsumerSecret"); public static string AccessToken = CloudConfigurationManager.GetSetting("Twitter:AccessToken"); public static string AccessTokenSecret = CloudConfigurationManager.GetSetting("Twitter:AccessTokenSecret"); } } }<file_sep>using System; namespace TwitterListener { public class GenericEventArgs<T>:EventArgs { public T Data { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace SociOLRoom.Analytics.Core { public class InstagramService { public static async Task<List<Instagram>> GetPhoto(string tag) { List<Instagram> instagrams = new List<Instagram>(); using (HttpClient client = new HttpClient()) { var json = await client.GetStringAsync("https://api.instagram.com/v1/tags/" + tag + "/media/recent?access_token=2070635583.5b<PASSWORD>.7c<PASSWORD>a6c94fcdbcde343<PASSWORD>"); dynamic jsonObject = JObject.Parse(json); JArray dataArray = jsonObject.data as JArray; foreach (dynamic data in dataArray) { if (data.type == "image") { Instagram instagram = new Instagram(); instagram.ImageUrl = data.images.standard_resolution.url; instagram.Id = data.id; instagram.Tags = String.Join(", ", ((JArray)data.tags).Select(s => "#" + s)); DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dt = dt.AddSeconds(int.Parse((string)data.created_time)).ToLocalTime(); instagram.CreatedAt = dt; instagram.User = data.user.username; instagrams.Add(instagram); } } } return instagrams; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using LinqToTwitter; using Microsoft.Azure; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.WebJobs; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using SociOLRoom.Analytics.Core; namespace TwitterListener { public class Functions { // This function will get triggered/executed when a new message is written // on an Azure Queue called queue. [NoAutomaticTriggerAttribute] public static async Task ProcessMethod(TextWriter log) { string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString"); QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "sociolroom"); while (true) { try { TwitterService service = new TwitterService(); await service.Authenticate(); service.OnNewMessage += async (s, e) => { SocialAnalytics analytics = new SocialAnalytics { TweetID = e.Data.StatusID, SocialNetwork = SocialNetwork.Twitter, Id = e.Data.StatusID.ToString(), CreatedAt = e.Data.CreatedAt, CreatedAtTimeStamp = e.Data.CreatedAt.Ticks, From = e.Data.User.Name, Tags = string.Join(", ", e.Data.Entities.HashTagEntities.Select(t => "#" + t.Tag)), ImageUrl = e.Data.Entities.MediaEntities[0].MediaUrl + ":large" }; await client.SendAsync(new BrokeredMessage(analytics)); }; await service.GetStreamTweets(Config.Tag); } catch (Exception ex) { log.WriteLine(DateTime.UtcNow + " -- TwitterListener: "+ex.Message); } await Task.Delay(TimeSpan.FromSeconds(5)); } } } } <file_sep>using System.Threading.Tasks; using Microsoft.ProjectOxford.Emotion.Contract; using Microsoft.ProjectOxford.Vision.Contract; using Face = Microsoft.ProjectOxford.Face.Contract.Face; namespace SociOLRoom.Analytics.Core { public class CogniviteResult { public Task<AnalysisResult> VisionTask { get; set; } public Task<Emotion[]> EmotionTask { get; set; } public Task<Face[]> FaceTask { get; set; } } }
578fc6c4603fbbe905ecebe2aa8061ba40e67e26
[ "Markdown", "C#" ]
21
C#
Exakis/sociolRoom
35c5b151ea6ed0135256aa47c186bd3873a5140b
1f54fe57f38b00459a79d7292d96b61fb762d4ba
refs/heads/main
<repo_name>rudhan/calc<file_sep>/README.md # calc scientific calculator scientific calculator with shunting yard algorithm <file_sep>/calc/deneme.js $(document).ready(function() { // A database of the symbols and functions of every operand. Order of operators determines precedence. var operators = [ { id: "op-power", numOperands: 2, symbol: " ^ ", calc: function(a, b) { return Math.pow(a, b); } }, { id: "op-negate", numOperands: 1, symbol: " -", calc: function(a) { return -a; } }, { id: "op-square-root", numOperands: 1, symbol: " √", calc: function(a) { return Math.sqrt(a); } }, { id: "op-log", numOperands: 1, symbol: " log ", calc: function(a) { return Math.log10(a); } }, { id: "op-natural-log", numOperands: 1, symbol: " ln ", calc: function(a) { return Math.log(a); } }, { id: "op-sin", numOperands: 1, symbol: " sin ", calc: function(a) { return Math.sin(a); } }, { id: "op-cos", numOperands: 1, symbol: " cos ", calc: function(a) { return Math.cos(a); } }, { id: "op-tan", numOperands: 1, symbol: " tan ", calc: function(a) { return Math.tan(a); } }, { id: "op-inverse-sin", numOperands: 1, symbol: " sin-1 ", calc: function(a) { return Math.asin(a); } }, { id: "op-inverse-cos", numOperands: 1, symbol: " cos-1 ", calc: function(a) { return Math.acos(a); } }, { id: "op-inverse-tan", numOperands: 1, symbol: " tan-1 ", calc: function(a) { return Math.atan(a); } }, { id: "op-e", numOperands: 1, symbol: " e ^ ", calc: function(a) { return Math.exp(a); } }, { id: "op-nth-root", numOperands: 2, symbol: "*√", calc: function(a, b) { return Math.pow(b, 1/a); } }, { id: "op-multiply", numOperands: 2, symbol: " x ", calc: function(a, b) { return a * b; } }, { id: "op-divide", numOperands: 2, symbol: " ÷ ", calc: function(a, b) { return a / b; } }, { id: "op-add", numOperands: 2, symbol: " + ", calc: function(a, b) { return a + b; } }, { id: "op-subtract", numOperands: 2, symbol: " - ", calc: function(a, b) { return a - b; } } ]; // The number of places to round to const roundPlaces = 15; // Get the operator object for a given operator ID function getOperator(opID) { for(var i = 0; i < operators.length; i++) { if(operators[i].id === opID) { return operators[i]; } } return undefined; } // Get the precedence of an operator given its ID function getOpPrecedence(opID) { for(var i = 0; i < operators.length; i++) { if(operators[i].id === opID) { return i; } } // If the given ID does not return an operator, then return a large value that will always lose in precedence return 1000; } // Returns true if op1 ID has equal or higher precedence than op2 ID, false otherwise function hasPrecedence(op1, op2) { if(getOperator(op1) != undefined) { return getOpPrecedence(op1) <= getOpPrecedence(op2); } } // Converts the given radian value to degrees function toDegrees(radians) { return radians * (180 / Math.PI); } // Converts the given degrees value to radians function toRadians(degrees) { return degrees * (Math.PI / 180); } // A list of every token (number or operator) currently in the expression var tokenList = []; // A list of previous results and expressions in the form {out: output, expression: expression string, tokens: list of tokens in the expression} var calcHistory = []; // Evaluates the expression and outputs the result function calculate() { // Check if brackets are balanced var count = 0; for(var i = 0; i < tokenList.length; i++) { if(tokenList[i] === "bracket-left") { count++; } else if(tokenList[i] === "bracket-right") { count--; } } if(count != 0) { output("Error: unbalanced brackets"); return; } // Evaluate the expression using a modified version of the shunting yard algorithm var valStack = []; var opStack = []; for(var i = 0; i < tokenList.length; i++) { if(!isNaN(tokenList[i])) { valStack.push(tokenList[i]); } else if(tokenList[i] === "num-pi") { valStack.push(Math.PI); } else if(tokenList[i] === "bracket-left") { opStack.push(tokenList[i]); } else if(tokenList[i] === "bracket-right") { while(opStack[opStack.length - 1] !== "bracket-left") { var operator = getOperator(opStack.pop()); if(operator.numOperands === 1) valStack.push(applyOperator(operator, [valStack.pop()])); else valStack.push(applyOperator(operator, [valStack.pop(), valStack.pop()])); } opStack.pop(); } else { while(opStack.length > 0 && hasPrecedence(opStack[opStack.length - 1], tokenList[i])) { var operator = getOperator(opStack.pop()); if(operator.numOperands === 1) valStack.push(applyOperator(operator, [valStack.pop()])); else valStack.push(applyOperator(operator, [valStack.pop(), valStack.pop()])); } opStack.push(tokenList[i]); } } while(opStack.length > 0) { var operator = getOperator(opStack.pop()); if(operator.numOperands === 1) valStack.push(applyOperator(operator, [valStack.pop()])); else valStack.push(applyOperator(operator, [valStack.pop(), valStack.pop()])); } // Output the calculated result and the original expression output(valStack[0], $("#expression").html(), tokenList); } // Returns the result of applying the given unary or binary operator on the top values of the value stack function applyOperator(operator, vals) { var valA = vals[0]; var result; if(vals.length === 1) { result = operator.calc(parseFloat(valA)); } else { var valB = vals[1]; result = operator.calc(parseFloat(valB), parseFloat(valA)); } return result; } // Updates the equation and calc history with the given output function output(out, expression, tokens) { out = +out.toFixed(roundPlaces); $("#expression").html(out.toString()); calcHistory.push({out: out, expression: expression, tokens: tokens}); $("#calc-history-box").html(""); for(var i = calcHistory.length - 1; i >= 0; i--) { $("#calc-history-box").append("<p style='color: #B0B0B0; ' class='calc-history-eq' id='eq" + i + "'>" + calcHistory[i].expression + "</p><p style='text-align: right; margin-top: -10px;'>= " + calcHistory[i].out + "</p>"); } } // Adds a token to the token list and updates the display function addToken(token) { if(isNaN(token)) { if((token === "bracket-left" || token === "num-pi") && !isNaN(tokenList[tokenList.length - 1])) { tokenList.push("op-multiply"); } tokenList.push(token); } else { if(!isNaN(tokenList[tokenList.length - 1])) { tokenList[tokenList.length - 1] = tokenList[tokenList.length - 1] + token; } else { if(!isNaN(token) && (tokenList[tokenList.length - 1] === "bracket-right" || tokenList[tokenList.length - 1] === "num-pi")) { tokenList.push("op-multiply"); } tokenList.push(token); } } displayEquation(); } // Updates the expression display's HTML function displayEquation() { var htmlString = ""; for(var i = 0; i < tokenList.length; i++) { if(isNaN(tokenList[i])) { if(tokenList[i] === "bracket-left") { htmlString += " ("; } else if(tokenList[i] === "bracket-right") { htmlString += ") "; } else if(tokenList[i] === "num-pi") { htmlString += " π "; } else { htmlString += getOperator(tokenList[i]).symbol; } } else { htmlString += tokenList[i]; } } $("#expression").html(htmlString); } // Deletes the last entered token function deleteLast() { if(isNaN(tokenList[tokenList.length - 1])) { tokenList.pop(); } else { tokenList[tokenList.length - 1] = tokenList[tokenList.length - 1].slice(0, -1); if(tokenList[tokenList.length -1].length === 0) { tokenList.pop(); } } displayEquation(); } // Shows/hides the advanced operators panel function toggleAdvanced() { $("#advanced-buttons").toggle(); if($("#advanced-buttons").is(":visible")) { $("#toggle-advanced").removeClass("button-off"); $("#toggle-advanced span").removeClass("glyphicon-triangle-bottom").addClass("glyphicon-triangle-top"); } else { $("#toggle-advanced").addClass("button-off"); $("#toggle-advanced span").removeClass("glyphicon-triangle-top").addClass("glyphicon-triangle-bottom"); } } // Triggers the appropriate action for each button that can be pressed function processButton(button) { switch($(button).attr("id")) { case "delete": deleteLast(); break; case "clear": if(tokenList.length === 0) { calcHistory.length = 0; $("#calc-history-box").html(""); } else { tokenList.length = 0; displayEquation(); } break; case "period": if(isNaN(tokenList[tokenList.length - 1])) { addToken("0."); } else { if(tokenList[tokenList.length - 1].indexOf(".") === -1) { tokenList[tokenList.length - 1] += "."; } } displayEquation(); break; case "equals": calculate(); break; case "toggle-advanced": toggleAdvanced(); break; case "num-pi": addToken("num-pi"); break; default: if($(button).hasClass("num")) { addToken($(button).html()); } else { addToken($(button).attr("id")); } } } // Catches all button clicks on the page $(".btn").click(function(event) { $(event.target).blur(); processButton(event.target); }); $(document).on("click", ".calc-history-eq", function(event) { var tokens = calcHistory[parseInt($(event.target).attr("id").substring(2))].tokens; console.log(parseInt($(event.target).attr("id").substring(2))); console.log(calcHistory); console.log(tokens); tokenList = tokens; displayEquation(); }); });<file_sep>/calc/script.js class Calculator { constructor(previousOperandTextElement, currentOperandTextElement) { this.previousOperandTextElement = previousOperandTextElement this.currentOperandTextElement = currentOperandTextElement this.silFunciton() } silFunciton() { this.currentOperand = '' this.previousOperand = '' this.operation = undefined } delete() { this.currentOperand = this.currentOperand.toString().slice(0, -1) } /*sin(number){ Math.sin(number) }*/ recursiveAdd(number) { if (number === '.' && this.currentOperand.includes('.')) return this.currentOperand = this.currentOperand.toString() + number.toString() } // her operator eklendiğinde current operand ı alıp tokenlist e pushluyoruz chooseOperation(operation) { if (this.currentOperand === '') return tokenList.push(this.currentOperand) tokenList.push(operation) this.operation = operation this.previousOperand = this.currentOperand this.previousOperand = this.operation this.currentOperand = '' } getOperator(operation){ var precendenceID switch(this.operation){ case '+': precendenceID = 0 ; break case '-': precendenceID = 0 ; break case '/': precendenceID = 1 ; break case '*': precendenceID = 1 ; break default: return } this.operation=precendenceID } //precedence = öncelik //öncelik sırası var mı kontrol edilecek //eğer precedenceID düşükse öncelikği daha azdır //yüksek değer = yüksek öncelik hasPrecedence(operation1,operation2){ if(getOperator(operation1) != undefined) // daha sonra sadece tek eleman alan fonksiyonlar eklenirse return this.getOperator(this.operation1)>=this.getOperator(this.operation2) } shuntingYard (){ for(var i = 0; i < tokenList.length; i++) { if(!isNaN(tokenList[i])) { valStack.push(tokenList[i]); } else if(tokenList[i] === leftParenthesis) { opStack.push(tokenList[i]); } else if(tokenList[i] === rightParenthesis) { while(opStack[opStack.length - 1] !== leftParenthesis) { var operator = getOperator(opStack.pop()); if(operator.numOperands === 1) valStack.push(applyOperator(operator, [valStack.pop()])); else valStack.push(applyOperator(operator, [valStack.pop(), valStack.pop()])); } opStack.pop(); } else { while(opStack.length > 0 && hasPrecedence(opStack[opStack.length - 1], tokenList[i])) { var operator = getOperator(opStack.pop()); valStack.push(hesap(operator, [valStack.pop(), valStack.pop()])); } opStack.push(tokenList[i]); } } while(opStack.length > 0) { var operator = getOperator(opStack.pop()); valStack.push(hesap(operator, [valStack.pop(), valStack.pop()])); } } // son iki değeri ve operatoru alarak hesap hesap(operator,valS) { var finalize ='' var prev = parseFloat(vals[0]) var current = parseFloat(vals[1]) if (isNaN(prev) || isNaN(current)) return // hata gönderiyor mu switch (this.operation) { case '+': finalize = prev + current break case '-': finalize = prev - current break case '*': finalize = prev * current break case '÷': finalize = prev / current break default: return } this.operation = undefined this.previousOperand = '' return finalize } getDisplayNumber(character) { const stringNumber = character.toString() const integerDigits = parseFloat(stringNumber.split('.')[0]) const decimalDigits = stringNumber.split('.')[1] let integerDisplay if (isNaN(integerDigits)) { integerDisplay = '' } else { integerDisplay = integerDigits.toLocaleString('en', { maximumFractionDigits: 0 }) } if (decimalDigits != null) { return `${integerDisplay}.${decimalDigits}` } else { return integerDisplay } } //sıfırıncı elemanı al ve görüntüle updateDisplay() { this.currentOperandTextElement.innerText =this.getDisplayNumber(valStack[0]) if (this.operation != null) { this.previousOperandTextElement.innerText =`${this.getDisplayNumber(this.previousOperand)} ${this.operation}` } else { this.previousOperandTextElement.innerText = '' } } } const numberButtons = document.querySelectorAll('[data-numbers]') const operationButtons = document.querySelectorAll('[data-operation]') const equalsButton = document.querySelector('[data-equals]') const deleteButton = document.querySelector('[data-delete]') const allClearButton = document.querySelector('[data-AC]') const leftParenthesis = document.querySelector('[data-left-parenthesis]') const rightParenthesis = document.querySelector('[data-right-parenthesis]') const previousOperandTextElement = document.querySelector('[data-previous-operand]') const currentOperandTextElement = document.querySelector('[data-current-operand]') const calculator = new Calculator(previousOperandTextElement, currentOperandTextElement) var tokenList= [] //tüm elemanların listesi var valStack = [] //rakamların sadizisi var opStack = [] //işlemlerin dizisi numberButtons.forEach(button => { button.addEventListener('click', () => { calculator.recursiveAdd(button.innerText) calculator.updateDisplay() }) }) operationButtons.forEach(button => { button.addEventListener('click', () => { calculator.chooseOperation(button.innerText) calculator.updateDisplay() }) }) equalsButton.addEventListener('click', button => { calculator.shuntingYard() calculator.updateDisplay() }) allClearButton.addEventListener('click', button => { calculator.silFunciton() calculator.updateDisplay() }) deleteButton.addEventListener('click', button => { calculator.delete() calculator.updateDisplay() }) leftParenthesis.addEventListener('click', button => { calculator.recursiveAdd(button.innerText) calculator.updateDisplay() }) rightParenthesis.addEventListener('click', button => { calculator.recursiveAdd(button.innerText) calculator.updateDisplay() })
92394fe573bbecefecb5e4d9ee519b36bb405995
[ "Markdown", "JavaScript" ]
3
Markdown
rudhan/calc
1f376993a283fcf1275acdfcc091540686cdc93a
21972d057e84f63131637d98e729665644f53b9e
refs/heads/master
<repo_name>suna4it/elastic<file_sep>/logstash/Dockerfile FROM logstash:2 ADD logstash-beats.key /etc/pki/tls/private/logstash-beats.key ADD logstash-beats.crt /etc/pki/tls/certs/logstash-beats.crt ADD config/logstash.conf /logstash.conf # Add your logstash plugins setup here #RUN logstash-plugin install logstash-output-amazon_es <file_sep>/metrics/Dockerfile FROM webwurst/go-cron RUN apk add --update coreutils groff less python py-pip && rm -rf /var/cache/apk/* RUN pip install awscli ADD start.sh /start.sh <file_sep>/elasticsearch_cleanup/start.sh #!/bin/sh DATE=`date -d '1 days ago' '+%Y.%m.%d'` curl -XDELETE elasticsearch:9200/filebeat-$DATE <file_sep>/metrics/start.sh #!/bin/sh COUNT=`ls -1 /data/inbox | wc -l` aws cloudwatch put-metric-data --metric-name InboxFiles --namespace ELK --value $COUNT<file_sep>/elasticsearch_cleanup/Dockerfile FROM webwurst/go-cron RUN apk add --update coreutils && rm -rf /var/cache/apk/* ADD start.sh /start.sh<file_sep>/readme.md # Elk stack Bestaat uit * sebp/elk (dockerhub) (zie https://elk-docker.readthedocs.io/) * filebeat (zelf gebouwd; zie https://elk-docker.readthedocs.io/) ## gebruik docker-compose up MERK OP dat de filebeat container refereert naar een extern volume: ~~~yaml volumes: wpcs-logs: external: name: pcsdockercompose_wpcs-logs ~~~ Ik heb dat zo gedaan dat in pcs-docker-compose een volume wpcs-logs is gedefinieerd: ~~~yaml volumes: wpcs-logs: driver: local ~~~ en wpcs/docker-wpcs/docker-compse.yml ook refereerd naar die volume. ~~~yaml volumes: wpcs-logs: external: name: pcsdockercompose_wpcs-logs ~~~ <file_sep>/inbox_processor/start.sh #!/bin/sh LOGGING_ENABLED=${LOGGING_ENABLED:-false} INBOX=${INBOX:-/data/inbox} FILEBEAT_REGISTRY_LOCATION=${FILEBEAT_REGISTRY_LOCATION:-/data/filebeat-registry} FILEBEAT_REGISTRY=${FILEBEAT_REGISTRY_LOCATION}/registry FILEBEAT_INBOX=${FILEBEAT_INBOX:-/data/filebeat-inbox} FILE_SIZE_BOUNDARY=${FILE_SIZE_BOUNDARY:-100000} INTERVAL=$((30)) log_message() { if [ $LOGGING_ENABLED == "true" ] then echo $@ fi } run() { log_message $@ $@ } filebeat_inbox() { local name=$1 echo ${FILEBEAT_INBOX}/$name } file_processed() { local filepath=$1 local filesize=$2 [ -e ${FILEBEAT_REGISTRY} ] || return 0 local processed_bytes=$(cat ${FILEBEAT_REGISTRY} | jq ".[] | select(.source==\"${filepath}\") | .offset") [ "${processed_bytes}" == "" ] || [ ${processed_bytes} -ge ${filesize} ] } wait_for_filebeat_to_finish_files() { local inbox_name=$1 for filepath in $(ls $(filebeat_inbox ${inbox_name})/*.log 2> /dev/null ); do local filesize=$(wc -c <${filepath}) until file_processed ${filepath} ${filesize}; do log_message waiting for ${filepath} to finish sleep 5 done rm ${filepath} done } send_file_to_inbox() { local filebeat_inbox_path=$(filebeat_inbox $1) local file=$2 local basename=$(echo ${file} | sed -e "s,\.gz,,") run gunzip -c ${INBOX}/${file} > ${filebeat_inbox_path}/.${basename}.tmp run rm -f ${INBOX}/${file} run mv ${filebeat_inbox_path}/.${basename}.tmp ${filebeat_inbox_path}/${basename}.log } send_file_list() { local file_list_name=$1 shift local file_list=$@ for file in $file_list; do send_file_to_inbox ${file_list_name} ${file} sleep 35 wait_for_filebeat_to_finish_files ${file_list_name} done log_message cleaning up $(filebeat_inbox ${file_list_name}) find $(filebeat_inbox ${file_list_name}) -type f -mtime +2 | xargs rm -f } process_inbox() { ( wait_for_filebeat_to_finish_files small )& ( wait_for_filebeat_to_finish_files large )& wait local large_list="" local small_list="" for file in $(ls -rt ${INBOX}); do if [ $(wc -c <${INBOX}/${file}) -gt ${FILE_SIZE_BOUNDARY} ]; then large_list="${large_list} ${file}" else small_list="${small_list} ${file}" fi done ( send_file_list small $small_list )& ( send_file_list large $large_list )& wait } create_filebeat_inboxes() { [ -e $(filebeat_inbox small) ] || mkdir $(filebeat_inbox small) [ -e $(filebeat_inbox large) ] || mkdir $(filebeat_inbox large) } until nc -z logstash 5000 ; do echo waiting for logstash; sleep 2; done while true do create_filebeat_inboxes process_inbox log_message going to sleep for ${INTERVAL} seconds sleep ${INTERVAL} done <file_sep>/expvar.py import requests import argparse import time import curses def main(): parser = argparse.ArgumentParser( description="Print per second stats from expvars") parser.add_argument("url", help="The URL from where to read the values") args = parser.parse_args() stdscr = curses.initscr() curses.noecho() curses.cbreak() last_vals = {} # running average for last 30 measurements N = 30 avg_vals = {} now = time.time() while True: try: time.sleep(1.0) stdscr.erase() r = requests.get(args.url) json = r.json() last = now now = time.time() dt = now - last total=json['libbeat.publisher.published_events'] key='published_events' if isinstance(total, (int, long, float)): if key in last_vals: per_sec = (total - last_vals[key])/dt if key not in avg_vals: avg_vals[key] = [] avg_vals[key].append(per_sec) if len(avg_vals[key]) > N: avg_vals[key] = avg_vals[key][1:] avg_sec = sum(avg_vals[key])/len(avg_vals[key]) else: per_sec = "na" avg_sec = "na" last_vals[key] = total stdscr.addstr("{}: {}/s (avg: {}/s) (total: {})\n" .format(key, per_sec, avg_sec, total)) stdscr.refresh() except requests.ConnectionError: stdscr.addstr("Waiting for connection...\n") stdscr.refresh() last_vals = {} avg_vals = {} if __name__ == "__main__": main() <file_sep>/inbox_processor/Dockerfile FROM alpine:3.4 WORKDIR /opt RUN apk update && \ apk add --update python curl jq ADD start.sh /opt/ WORKDIR /opt CMD ["./start.sh"] <file_sep>/filebeat/Dockerfile FROM jeanblanchard/alpine-glibc:3.4_2.23-r3 ENV FILEBEAT_VERSION 5.0.0-beta1 ENV FILEBEAT_FILE filebeat-${FILEBEAT_VERSION}-linux-x86_64 ENV FILEBEAT_URL https://artifacts.elastic.co/downloads/beats/filebeat/${FILEBEAT_FILE}.tar.gz ENV FILEBEAT_HOME /opt/filebeat ENV PATH $PATH:${FILEBEAT_HOME} WORKDIR /opt RUN apk update && \ apk add --update python curl RUN curl -sL ${FILEBEAT_URL} | tar xz -C . && mv /opt/${FILEBEAT_FILE} ${FILEBEAT_HOME} && echo ${FILEBEAT_VERSION} >> ${FILEBEAT_HOME}/version.txt ADD start.sh ${FILEBEAT_HOME}/ ADD config ${FILEBEAT_HOME}/config RUN mkdir -p /etc/pki/tls/certs ADD logstash-beats.crt /etc/pki/tls/certs/logstash-beats.crt WORKDIR ${FILEBEAT_HOME} CMD ["./start.sh"] <file_sep>/elasticsearch/Dockerfile FROM elasticsearch:2.4 ADD config /usr/share/elasticsearch/config <file_sep>/filebeat/start.sh #!/bin/sh until nc -z logstash 5000 ; do echo waiting for logstash; sleep 2; done curl -XPUT "http://${ELASTIC_HOST}:9200/_template/filebeat?pretty" -d@filebeat.template-es2x.json ./filebeat -c ${FILEBEAT_HOME}/config/filebeat.yml -e ${FILEBEAT_OPTIONS} -httpprof :6060 > /dev/null
63bfd0b67df2d52a3da76ff6cbf4ae46f76b6cad
[ "Markdown", "Python", "Dockerfile", "Shell" ]
12
Dockerfile
suna4it/elastic
50df69fad5fd238f7ca6606a59a9bf532b85d8f9
1fbd3c7b349562293264e2c5284d8066ca042721
refs/heads/master
<file_sep>/* ========================================================================== * codeEditors.js * * Creates a 'CodeMirror' code editor and defines the syntax highlighting for * the 'Fun' programming language. * * Creates read-only code snippets to be used to display information within the * specification section. * ========================================================================== */ // Import CodeMirror node module var CodeMirror = require('codemirror'); // Import the CodeMirror 'simple-mode' addon require('codemirror/addon/mode/simple.js'); // Import the CodeMirror 'active-line' addon require('codemirror/addon/selection/active-line.js'); // Import the CodeSnippets module var CodeSnippets = require('./codeSnippets.js') // Bind a 'click' event listener to all links with the class 'code-example' $(".code-example").on("click", function() { // Get the example name from the 'example' data-attribute and update code_editor.setValue(CodeSnippets.getSnippet($(this).data("example"))); }); // Event listener to trigger when a specification tab is shown $('.nav-tabs a').on('shown.bs.tab', function() { // Refresh (reload) the specified CodeMirror objects overview_snippet.refresh(); predefined_snippet.refresh(); }); // Define a 'mode' for the Fun programming language, i.e., syntax highlighting CodeMirror.defineSimpleMode("fun", { start: [ {regex: /(?:func|proc|return|if|while|else|not)\b/, token: "keyword"}, {regex: /true|false/, token: "atom"}, {regex: /int|bool/, token: "type"}, {regex: /0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i, token: "number"}, {regex: /#.*/, token: "comment"}, {regex: /[-+\/*=<>]+/, token: "operator"}, {regex: /[\:]/, indent: true}, {regex: /[\.]/, dedent: true}, {regex: /[a-z$][\w$]*/, token: "variable"}, ], comment: [] }); // Create a CodeMirror object from a text area var code_editor = CodeMirror.fromTextArea( document.getElementById("code-editor"), { lineNumbers: true, tabSize: 2, lineWrapping: true, styleActiveLine: true, mode: "fun", theme: "dracula" } ); // Set the default value of the code mirror code_editor.setValue(CodeSnippets.getSnippet("DEFAULT")); // Below are read-only code snippets used within the specification var overview_snippet = CodeMirror(document.getElementById("overview") .getElementsByClassName("code-snippet")[0], { lineNumbers: true, tabSize: 2, lineWrapping: true, mode: "fun", theme: "dracula", readOnly: "nocursor", value: CodeSnippets.getSnippet("OVERVIEW") }); var predefined_snippet = CodeMirror(document.getElementById("predefined") .getElementsByClassName("code-snippet")[0], { lineNumbers: true, tabSize: 2, lineWrapping: true, mode: "fun", theme: "dracula", readOnly: "nocursor", value: CodeSnippets.getSnippet("PREDEFINED") }); <file_sep><?xml version="1.0" encoding="UTF-8"?> <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>api</groupId> <artifactId>api</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.antlr</groupId> <artifactId>antlr4-runtime</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <finalName>api</finalName> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>api.Api</mainClass> <classpathPrefix>dependency-jars/</classpathPrefix> </manifest> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <goals> <goal>attached</goal> </goals> <phase>package</phase> <configuration> <finalName>api</finalName> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>api.Api</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.antlr</groupId> <artifactId>antlr4-maven-plugin</artifactId> <version>4.5.3</version> <executions> <execution> <goals> <goal>antlr4</goal> </goals> <configuration> <sourceDirectory>${basedir}/src/main/antlr4/api</sourceDirectory> <listener>false</listener> <visitor>true</visitor> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>try { // Import JQuery module, globally available with '$' and 'jQuery' window.$ = window.jQuery = require('jquery'); // Import Bootstrap module require('bootstrap-sass'); // Import CodeEditors module require("./codeEditors.js"); // Import CodeSubmit module require("./codeSubmit.js"); } catch (e) {} <file_sep>/* ========================================================================== * codeSnippets.js * * Defines a list of pre-defined Fun program which can be selected and * auto-loaded into the code editor. * * Exposes a method to retrieve each snippet by name. * ========================================================================== */ var CodeSnippets = module.exports = { // Retrieve a code snippet by name getSnippet: function(snippetName) { return snippets[snippetName]; } } // Defines a list of pre-defined Fun programs var snippets = { ASSIGN: "proc main():\n\tint g = 7\n\tg = g + 1\n\t" + "g = 1 + 2 * g\n\tg = (1 + 2) * g\n\twrite(g)\n.", DEFAULT: "int n = 15\nproc main():\n\twhile n > 1:\n\t\t" + "n = n/2\n\t.\n.", FACTORIAL: "func int fac(int n):\n\tint f = 1\n\twhile n > 1:\n\t\t" + "f = f * n\n\t\tn = n - 1\n\t.\n\treturn f\n.\n\n" + "proc main():\n\twrite(fac(10))\n.", FUNCTION: "func int test(int n):\n\tint r = 10\n\tint s = 20\n\t" + "int t = 30\n\twrite(s)\n\treturn r\n.\n\n" + "proc main():\n\twrite(test(5))\n.", IF: "proc main():\n\tint m = 7\n\tint n = 3\n\t" + "if m < n:\n\t\t" + "m = m + 1\n\t\twrite(m)\n\telse:\n\t\tn = n + 1\n\t\t" + "write(n)\n\t.\n.", IO: "int p = read()\n\nproc main():\n\tint q = read()\n\t" + "write(p)\n\twrite(q + 2/5)\n.", OCTAL: "proc writeoctal(int n):\n\tif n < 8:\n\t\twrite(n)\n\t" + "else:\n\t\twriteoctal(n/8)\n\t\t" + "write(n-((n/8)*8))\n\t.\n.\n\nproc main():\n\t" + "writeoctal(8)\n.", OVERVIEW: "bool verbose = true\n\n" + "func int fac(int n): # Returns n\n\tint f = 1\n\t" + "while n > 1:\n\t\tf = f * n\n\t\tn = n - 1\n\t" + "return f\n.\n\nproc main():\n\tint num = read()\n\t" + "while not (num == 0):\n\t\t" + "if verbose: write(num) .\n\t\twrite(fac(num))\n\t\t" + "num = read()\n\t.\n.", PREDEFINED: "func int read():\t\t# Inputs and returns an integer\n\t" + "...\nproc write(int n):\t\t# Outputs the integer n\n\t...", PROC: "int total = 0\n\nproc add(int inc):\n\t" + "total = total + inc\n.\n\n" + "proc main():\n\tint i = read()\n\twhile i > 0:\n\t\t" + "add(i)\n\t\ti = read()\n\t.\n\twrite(total)\n.", SCOPE_CHECKING: "int y = x # Error\nbool x = true\n\n" + "proc main():\n\tint n = 0\n\t" + "int n = 1 #Error\n\tx = x + y # Error\n\tp() # Error\n.", TYPE_CHECKING: "int n = true # Error\nbool c = 1 # Error\n\n" + "func bool pos(int n):\n\treturn n # Error\n.\n\n" + "proc main():\n\tint i = 3\n\tbool b = true\n\t" + "i = i + 1\n\ti = b # Error\n\ti = b * 2 # Error\n\t" + "b = i > 0\n\tif b: write(i) .\n\t" + "if i: write(i) . # Error\n\tb = pos(true) # Error\n\t" + "while pos(7):\n\t\ti = i + 1\n\t.\n.", WHILE: "proc main():\n\tint m = read()\n\tint n = 1\n\t" + "while n * n < m + 1:\n\t\twrite(n * n)\n\t\t" + "n = n + 1\n\t.\n." } <file_sep>package api; ////////////////////////////////////////////////////////////// // // A visitor to build an AST over the parse tree. // // Builds a JSON array to be eventually stored in the FunResponse. // // Developed September 2017 - March 2018 by <NAME>. // ////////////////////////////////////////////////////////////// import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import org.antlr.v4.runtime.misc.*; import java.util.Stack; import java.util.List; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class FunASTVisitor extends AbstractParseTreeVisitor<Void> implements FunVisitor<Void> { private Parser parser; // Stores the AST as flat JSON data private JsonArray treeNodes = new JsonArray(); // Stores a stack of parent node ids private Stack<Integer> parentNodes = new Stack<Integer>(); public FunASTVisitor(Parser parser) { this.parser = parser; } public JsonArray getTreeNodes() { return treeNodes; } /** * Overloaded version of the createJSONObject method, which creates a JSON * object with the same nodeName and nodeValue. * @param ctx the parse tree * @param nodeName the name of the node */ private void createJsonObject(Object ctx, String nodeName) { createJsonObject(ctx, nodeName, nodeName); } /** * Creates a new JSON object. Uses the node on top of the parentNodes stack * to determine who the parent is. Adds the newly created JSON object to an * ordered JSON array. * @param ctx the parse tree * @param nodeName the name of the node * @param nodeValue the value stored in the node (if token) */ private void createJsonObject(Object ctx, String nodeName, String nodeValue) { JsonObject data_object = new JsonObject(); // use the object's hash as an id int id = ctx.hashCode(); // parent is -1 if at the root, top of the stack otherwise int parent_id = (parentNodes.empty() ? -1 : parentNodes.peek()); data_object.addProperty("id", id); data_object.addProperty("nodeName", nodeName); data_object.addProperty("nodeValue", nodeValue); data_object.addProperty("parent_id", parent_id); // add the newly created JSON object to JSON array treeNodes.add(data_object); } /*============================== VISITORS ==============================*/ /** * Visit a parse tree produced by the {@code prog} * labeled alternative in {@link FunParser#program}. * @param ctx the parse tree * @return the visitor result */ public Void visitProg(FunParser.ProgContext ctx) { createJsonObject(ctx, "PROG"); parentNodes.push(ctx.hashCode()); visitChildren(ctx); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code proc} * labeled alternative in {@link FunParser#proc_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitProc(FunParser.ProcContext ctx) { createJsonObject(ctx, "PROC"); parentNodes.push(ctx.hashCode()); createJsonObject(ctx.ID(), ctx.ID().getText()); FunParser.Formal_declContext fd = ctx.formal_decl(); visit(ctx.formal_decl()); List<FunParser.Var_declContext> var_decl = ctx.var_decl(); for (FunParser.Var_declContext vd : var_decl) visit(vd); visit(ctx.seq_com()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code func} * labeled alternative in {@link FunParser#proc_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitFunc(FunParser.FuncContext ctx) { createJsonObject(ctx, "FUNC"); parentNodes.push(ctx.hashCode()); visit(ctx.type()); createJsonObject(ctx.ID(), ctx.ID().getText()); FunParser.Formal_declContext fd = ctx.formal_decl(); visit(ctx.formal_decl()); List<FunParser.Var_declContext> var_decl = ctx.var_decl(); for (FunParser.Var_declContext vd : var_decl) visit(vd); visit(ctx.seq_com()); visit(ctx.expr()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code formal} * labeled alternative in {@link FunParser#formal_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitFormal(FunParser.FormalContext ctx) { FunParser.TypeContext tc = ctx.type(); if (tc != null) { createJsonObject(ctx, "FORMAL"); parentNodes.push(ctx.hashCode()); visit(tc); createJsonObject(ctx.ID(), "ID", ctx.ID().getText()); parentNodes.pop(); } else { createJsonObject(ctx, "NOFORMAL"); } return null; } /** * Visit a parse tree produced by the {@code var} * labeled alternative in {@link FunParser#var_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitVar(FunParser.VarContext ctx) { createJsonObject(ctx, "VAR"); parentNodes.push(ctx.hashCode()); visit(ctx.type()); createJsonObject(ctx.ID(), "ID", ctx.ID().getText()); visit(ctx.expr()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code bool} * labeled alternative in {@link FunParser#type}. * @param ctx the parse tree * @return the visitor result */ public Void visitBool(FunParser.BoolContext ctx) { createJsonObject(ctx, "BOOL"); return null; } /** * Visit a parse tree produced by the {@code int} * labeled alternative in {@link FunParser#type}. * @param ctx the parse tree * @return the visitor result */ public Void visitInt(FunParser.IntContext ctx) { createJsonObject(ctx, "INT"); return null; } /** * Visit a parse tree produced by the {@code assn} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitAssn(FunParser.AssnContext ctx) { createJsonObject(ctx, "ASSN"); parentNodes.push(ctx.hashCode()); createJsonObject(ctx.ID(), "ID", ctx.ID().getText()); visit(ctx.expr()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code proccall} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitProccall(FunParser.ProccallContext ctx) { createJsonObject(ctx, "PROCCALL"); parentNodes.push(ctx.hashCode()); createJsonObject(ctx.ID(), "ID", ctx.ID().getText()); visit(ctx.actual()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code if} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitIf(FunParser.IfContext ctx) { if (ctx.c2 != null) { createJsonObject(ctx, "IFELSE"); parentNodes.push(ctx.hashCode()); visit(ctx.expr()); visit(ctx.c1); visit(ctx.c2); } else { createJsonObject(ctx, "IF"); parentNodes.push(ctx.hashCode()); visit(ctx.expr()); visit(ctx.c1); } parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code while} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitWhile(FunParser.WhileContext ctx) { createJsonObject(ctx, "WHILE"); parentNodes.push(ctx.hashCode()); visit(ctx.expr()); visit(ctx.seq_com()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code seq} * labeled alternative in {@link FunParser#seq_com}. * @param ctx the parse tree * @return the visitor result */ public Void visitSeq(FunParser.SeqContext ctx) { createJsonObject(ctx, "SEQ"); parentNodes.push(ctx.hashCode()); visitChildren(ctx); parentNodes.pop(); return null; } /** * Visit a parse tree produced by {@link FunParser#expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitExpr(FunParser.ExprContext ctx) { if (ctx.e2 != null) { createJsonObject(ctx.op, parser.getVocabulary().getSymbolicName(ctx.op.getType())); parentNodes.push(ctx.op.hashCode()); visit(ctx.e1); visit(ctx.e2); parentNodes.pop(); } else { visit(ctx.e1); } return null; } /** * Visit a parse tree produced by {@link FunParser#sec_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitSec_expr(FunParser.Sec_exprContext ctx) { if (ctx.e2 != null) { createJsonObject(ctx.op, parser.getVocabulary().getSymbolicName(ctx.op.getType())); parentNodes.push(ctx.op.hashCode()); visit(ctx.e1); visit(ctx.e2); parentNodes.pop(); } else { visit(ctx.e1); } return null; } /** * Visit a parse tree produced by the {@code false} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitFalse(FunParser.FalseContext ctx) { createJsonObject(ctx, "FALSE"); return null; } /** * Visit a parse tree produced by the {@code true} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitTrue(FunParser.TrueContext ctx) { createJsonObject(ctx, "TRUE"); return null; } /** * Visit a parse tree produced by the {@code num} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitNum(FunParser.NumContext ctx) { createJsonObject(ctx, "NUM", ctx.getText()); return null; } /** * Visit a parse tree produced by the {@code id} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitId(FunParser.IdContext ctx) { createJsonObject(ctx, "ID", ctx.getText()); return null; } /** * Visit a parse tree produced by the {@code funccall} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitFunccall(FunParser.FunccallContext ctx) { createJsonObject(ctx, "FUNCCALL"); parentNodes.push(ctx.hashCode()); createJsonObject(ctx.ID(), "ID", ctx.ID().getText()); visit(ctx.actual()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code not} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitNot(FunParser.NotContext ctx) { createJsonObject(ctx, "NOT"); parentNodes.push(ctx.hashCode()); visitChildren(ctx.prim_expr()); parentNodes.pop(); return null; } /** * Visit a parse tree produced by the {@code parens} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitParens(FunParser.ParensContext ctx) { return visit(ctx.expr()); } /** * Visit a parse tree produced by {@link FunParser#actual}. * @param ctx the parse tree * @return the visitor result */ public Void visitActual(FunParser.ActualContext ctx) { FunParser.ExprContext ec = ctx.expr(); if (ec != null) { visit(ec); } return null; } } <file_sep>package api; ////////////////////////////////////////////////////////////// // // Creates an API to compile received Fun programs. // // Developed September 2017 - March 2018 by <NAME>. // ////////////////////////////////////////////////////////////// import static spark.Spark.*; import java.io.*; import com.google.gson.Gson; public class Api { public static void main(String[] args) { // Create a GSON object, used to convert objects to JSON Gson gson = new Gson(); // Post request at route '/', convert output to JSON post("/", (req, res) -> { // Set the content-type of the response to JSON res.type("application/json"); // Get the input program sent from the web app String program = req.queryParams("program"); // Get the execution type sent from the web app String type = req.queryParams("type"); // Convert the input String to an InputStream InputStream programInputStream = new ByteArrayInputStream(program.getBytes()); // Pass the InputStream to the Fun compiler return FunRun.execute(programInputStream, type); }, gson::toJson); } } <file_sep>/* ========================================================================== * codeHelpers.js * * Provides helper methods used to manipulate the response returned from the * API to build a data structure in which D3 can form a tree. * ========================================================================== */ var CodeHelpers = module.exports = { // Converts a flat data structure into a parent-child tree buildTree: function(data) { var dataMap = CodeHelpers.mapData(data); var treeData = []; data.forEach(function(node) { var parent = dataMap[node.parent_id]; if (parent) { (parent.children || (parent.children = [])).push(node); } else { treeData.push(node); } }); return treeData; }, // Modifies the array index to be the ID of the node mapData: function(data) { var dataMap = data.reduce(function(map, node) { map[node.id] = node; return map; }, {}); return dataMap; } } <file_sep>/* ========================================================================== * codeSubmit.js * * Submits the input program to the compiler API. Retrieves the response and if * successful, triggers the methods to build the AST. * ========================================================================== */ // Import Code Animation module var CodeAnimation = require("./codeAnimation.js"); // Indicates which button was pressed, contextual analysis or code generation var executionType; // Event listener to trigger when either submit button is pressed $("button[type='submit']").click(function() { // Contextual analysis or code generation executionType = $(this).val(); // Modify background-ground to show active $(this).siblings().css("background-color", "#333545") $(this).css("background-color", "#035a80"); }); // Event listener to trigger when form is submitted $("#execute-form").submit(function(e) { // Get the form that was submitted var $form = $(this); // Stop the form submitting normally (i.e., don't route to action parameter) e.preventDefault(); // Get csrf token from page meta-data var AUTH_TOKEN = $("meta[name='csrf-token']").attr("content"); // Create the url to use within the post request var url = "/" + executionType; // Serialise the form inputs, add csrf token var data = $form.serialize() + "&_token=" + AUTH_TOKEN; // Post to the controller and execute body upon success $.post(url, data, function(responseData) { // Collect all response data var response = responseData.response; var numSyntaxErrors = response.numSyntaxErrors; var syntaxErrors = response.syntaxErrors; var numContextualErrors = response.numContextualErrors; var contextualErrors = response.contextualErrors; var treeNodes = response.treeNodes; var objectCode = response.objectCode; var nodeOrder = response.nodeOrder; // If there was syntax errors... if (numSyntaxErrors > 0) { // Build an error message and insert into an alert var syntaxErrorMessage = "Number of syntax errors: " + numSyntaxErrors; $.each(syntaxErrors, function(index, syntaxError) { syntaxErrorMessage += ("\n" + syntaxError); }); alert(syntaxErrorMessage); // If the program has contextual errors and the user is trying to do cg... } else if (executionType === "cg" && numContextualErrors > 0) { // Build an error message and insert into an alert var contextualErrorMessage = "Number of contextual errors: " + numContextualErrors; $.each(contextualErrors, function(index, contextualError) { contextualErrorMessage += ("\n" + contextualError); }); alert(contextualErrorMessage); // Otherwise... } else { // Hide the specification section $("#display-specification").hide(); // Display the AST section $("#display-program-tree").show(); // Remove the active class from the 'Home' button $("#navbar .active").removeClass("active"); // Display the correct containers depending on the execution type CodeAnimation.initialise(executionType, nodeOrder); // Draw the AST CodeAnimation.drawTree(treeNodes); // 'Animate' the first node in the tree CodeAnimation.highlightFirstNode(); } // If post request return a failure... }).fail(function(responseData) { // Insert errors into an alert alert(responseData.responseJSON.errors.program); }); }); <file_sep>/* ========================================================================== * codeTemplates.js * * Defines a list of code templates that are displayed during code-generation * when traversing the AST * * Exposes a method to retrieve each template by name. * ========================================================================== */ var CodeTemplates = module.exports = { // Retrieve a code template by name getTemplate: function(templateName) { return templates[templateName]; } } // Defines a list of pre-defined code templates var templates = { ASSN: [ "Code to evaluate expr", "STOREG d or STOREL d" ], CMPEQ: [ "Code to evaluate expr1", "Code to evaluate expr2", "CMPEQ" ], DIV: [ "Code to evaluate expr1", "Code to evaluate expr2", "DIV" ], FALSE: [ "LOADC" ], FORMAL: [ "COPYARG" ], FUNC: [ "Code to evaluate formal declarations", "Code to evaluate variable declarations", "Code to execute com", "Code to evaluate return expr", "RETURN" ], FUNCCALL: [ "Code to evaluate expr", "CALL d" ], GT: [ "Code to evaluate expr1", "Code to evaluate expr2", "GT" ], ID: [ "LOADG d or LOADC d" ], IF: [ "Code to evaluate expr", "JUMPF 'exit_address'", "Code to evaluate com", "Label: 'exit_address'" ], IFELSE: [ "Code to evaluate expr", "JUMPF 'else_address'", "Code to evaluate com1", "JUMP 'exit_address'", "Label: 'else_address'", "Code to evaluate com 2", "Label: 'exit_address'" ], LT: [ "Code to evaluate expr1", "Code to evaluate expr2", "LT" ], MINUS: [ "Code to evaluate expr1", "Code to evaluate expr2", "SUB" ], NOFORMAL: [ "COPYARG" ], NOT: [ "Code to evaluate expr", "INV" ], NUM: [ "LOADC" ], PLUS: [ "Code to evaluate expr1", "Code to evaluate expr2", "ADD" ], PROC: [ "Code to evaluate formal declarations", "Code to evaluate variable declarations", "Code to execute com", "RETURN" ], PROCCALL: [ "Code to evaluate expr", "CALL d" ], PROG: [ "Code to evaluate variable declarations", "CALL", "HALT", "Code to evaluate procedure declarations" ], SEQ: [ "Code to execute com" ], MUL: [ "Code to evaluate expr1", "Code to evaluate expr2", "TIMES" ], TRUE: [ "LOADC" ], VAR: [ "Code to evaluate expr" ], WHILE: [ "Label: 'start_address'", "Code to evaluate expr", "JUMPF exit_address", "Code to execute com", "JUMP start_address", "Label: 'exit_address'" ] } <file_sep><?php namespace Tests\Feature; use Tests\TestCase; class HttpTest extends TestCase { /** * Ensure the 'index' view is rendered when navigating to '/'. * * @return void */ public function testIndexView() { $response = $this->get('/'); $response->assertViewIs('index'); } /** * Make a post request for a contextual analysis result with a correct * program and ensure only the correct fragments are returned. * * @return void */ public function testSuccessfulAndValidCARequest() { $response = $this->json('POST', route('execute', [ 'type' => 'ca', 'program' => 'int n = 15 proc main(): while n > 1: n = n/2 . .' ])); $response->assertSuccessful() ->assertJsonFragment([ 'redirect_url' => '/', 'numSyntaxErrors' => 0, 'numContextualErrors' => 0, 'syntaxErrors' => [], 'contextualErrors' => [] ]) ->assertSeeText('nodeOrder') ->assertSeeText('treeNodes') ->assertDontSeeText('objectCode'); } /** * Make a post request for a contextual analysis result with an incorrect * program and ensure only the correct fragments are returned. * * @return void */ public function testSuccessfulAndInvalidCARequest() { $response = $this->json('POST', route('execute', [ 'type' => 'ca', 'program' => 'int n = 15 proc main(): while n > 1 n = n/2 . .' ])); $response->assertSuccessful() ->assertJsonFragment([ 'redirect_url' => '/', 'numSyntaxErrors' => 1, 'numContextualErrors' => 0, 'syntaxErrors' => ['line 1:36 missing \':\' at \'n\''], ]) ->assertDontSeeText('nodeOrder') ->assertDontSeeText('treeNodes'); } /** * Make a post request for a contextual analysis result with an empty * and ensure a 422 'Unprocessable Entity' status code is returned. * * @return void */ public function testUnsuccessfulCARequest() { $response = $this->json('POST', route('execute', [ 'type' => 'ca', 'program' => '' ])); $response->assertStatus(422) ->assertSeeText('The program field is required.'); } /** * Make a post request for a code generation result and ensure only * the correct fragments are returned. * * @return void */ public function testSuccessfulAndValidCGRequest() { $response = $this->json('POST', route('execute', [ 'type' => 'cg', 'program' => 'int n = 15 proc main(): while n > 1: n = n/2 . .' ])); $response->assertSuccessful() ->assertJsonFragment([ 'redirect_url' => '/', 'numSyntaxErrors' => 0, 'numContextualErrors' => 0, 'syntaxErrors' => [], 'contextualErrors' => [] ]) ->assertSeeText('nodeOrder') ->assertSeeText('treeNodes') ->assertSeeText('objectCode'); } /** * Make a post request for a code generation result with an incorrect * program and ensure only the correct fragments are returned. * * @return void */ public function testSuccessfulAndInvalidCGRequest() { $response = $this->json('POST', route('execute', [ 'type' => 'cg', 'program' => 'int n = 15 proc main(): while n > 1 n = n/2 . .' ])); $response->assertSuccessful() ->assertJsonFragment([ 'redirect_url' => '/', 'numSyntaxErrors' => 1, 'numContextualErrors' => 0, 'syntaxErrors' => ['line 1:36 missing \':\' at \'n\''], ]) ->assertDontSeeText('nodeOrder') ->assertDontSeeText('treeNodes'); } /** * Make a post request for a code generation result with an empty * and ensure a 422 'Unprocessable Entity' status code is returned. * * @return void */ public function testUnsuccessfulCGRequest() { $response = $this->json('POST', route('execute', [ 'type' => 'cg', 'program' => '' ])); $response->assertStatus(422) ->assertSeeText('The program field is required.'); } } <file_sep># Use an OpenJDK8 image to run and compile Java files FROM openjdk:8 # Install Maven in the container RUN apt-get update RUN apt-get install -y maven # Create the 'compiler' directory and set to be the working directory of the container WORKDIR /compiler # Add 'pom.xml' to the container ADD pom.xml /compiler/pom.xml # Download maven dependencies (e.g., Antlr and Spark) RUN ["mvn", "dependency:resolve"] RUN ["mvn", "verify"] # Add the source directory ADD src /compiler/src # Compile and package into a fat jar RUN ["mvn", "package"] <file_sep><?php Route::get('/', 'IndexController@index')->name('index'); Route::post('/{type}', 'IndexController@execute')->name('execute'); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class IndexController extends Controller { /** * Display the home page with no currently executed program, i.e., display * the Fun specification. * * @return \Illuminate\View\View */ public function index() { return view('index'); } /** * Makes an API request to the Fun compiler, passing the input program and * the compilation type (contextual analysis or code generation) as * parameters. Retrieves the JSON response and returns this along with * a redirect URL (the home page) to the AJAX request that initially * triggered this method. * * @return \Illuminate\Http\JsonResponse */ public function execute() { // An empty program cannot be submitted request()->validate([ 'program' => 'required' ]); // Create a new Guzzle client $client = new \GuzzleHttp\Client(); // Send a post request to the compiler container $res = $client->request('POST', 'http://compiler:4567', [ 'form_params' => [ // Pass the input program as a parameter 'program' => request()->program, // Pass the execution type as a parameter 'type' => request()->type ] ]); // Convert the body of the response to an associative array $response = json_decode($res->getBody(), true); // Render the index view, passing along the response array return response()->json(['redirect_url' => '/', 'response' => $response]); } } <file_sep>[![Build Status](https://travis-ci.org/DavidR95/FunCompiler.svg?branch=master)](https://travis-ci.org/DavidR95/FunCompiler) # FunCompiler ### Abstract The goal of this project is to create an application that provides concrete, visual representations of the abstract, conceptual notions characterised by compilation theory. The application, named the FunCompiler, is to be distributed as an additional educational resource during the delivery of the University of Glasgow's computer science course, Programming Languages. The FunCompiler enables its users to animate the compilation of any program written in the Fun language, including building visualisations of the key data structures involved and augmenting each step of the animation with additional, explanatory details. We also consider the claims that have been made in regards to the effectiveness of animations used to teach computational algorithms and investigate whether the FunCompiler can be used to support or discredit these theories. ## Getting started To get started with the app, navigate to the top-level directory (containing docker-compose.yml) and simply run: ``` $ docker-compose -f docker-compose.production.yml up --build ``` You should now be able to find the web app at [localhost:8000](http://localhost:8000). <file_sep>package api; //////////////////////////////////////////////////////////////// // // Representation of types. // // Developed June 2012 by <NAME> (University of Glasgow). // // Sequence types added by <NAME>, September 2016. // // Extended September 2017 - March 2018 by <NAME>. // //////////////////////////////////////////////////////////////// import java.util.ArrayList; public abstract class Type { // An object of class Type represents a type, which may // be a primitive type, a pair type, or a mapping type, public static final Primitive VOID = new Primitive(0), BOOL = new Primitive(1), INT = new Primitive(2); public static final Error ERROR = new Error(); public static final Sequence EMPTY = new Sequence(new ArrayList<Type>()); public abstract boolean equiv (Type that); // Return true if and only if this type is equivalent // to that. public abstract String toString (); // Return a textual reporesentation of this type. //////////////////////////////////////////////////////// public static class Primitive extends Type { public int which; public Primitive (int w) { which = w; } public boolean equiv (Type that) { return (that instanceof Primitive && this.which == ((Primitive)that).which); } public String toString () { switch (which) { case 0: return "void"; case 1: return "bool"; case 2: return "int"; } return "???"; } } //////////////////////////////////////////////////////// public static class Pair extends Type { public Type first, second; public Pair (Type fst, Type snd) { first = fst; second = snd; } public boolean equiv (Type that) { if (that instanceof Pair) { Pair thatPair = (Pair)that; return this.first.equiv(thatPair.first) && this.second.equiv(thatPair.second); } else return false; } public String toString () { return first + " x " + second; } } //////////////////////////////////////////////////////////// public static class Sequence extends Type { public ArrayList<Type> sequence; public Sequence(ArrayList<Type> seq) { sequence = seq; } public boolean equiv(Type that) { if (that instanceof Sequence) { ArrayList<Type> thatSequence = ((Sequence)that).sequence; if (thatSequence.size() != sequence.size()) return false; for (int i = 0; i < thatSequence.size(); i++) if (!(thatSequence.get(i).equiv(sequence.get(i)))) return false; return true; } else return false; } public String toString() { String s = "["; if (sequence.size() > 0) { s = s + sequence.get(0); for (int i = 1; i < sequence.size(); i++) s = s + "," + sequence.get(i); } s = s + "]"; return s; } } //////////////////////////////////////////////////////// public static class Mapping extends Type { public Type domain, range; public Mapping (Type d, Type r) { domain = d; range = r; } public boolean equiv (Type that) { if (that instanceof Mapping) { Mapping thatMapping = (Mapping)that; return this.domain.equiv( thatMapping.domain) && this.range.equiv( thatMapping.range); } else return false; } public String toString () { return domain + " -> " + range; } } //////////////////////////////////////////////////////// public static class Error extends Type { public Error () { } public boolean equiv (Type that) { return true; } public String toString () { return "error"; } } } <file_sep>package api; ////////////////////////////////////////////////////////////// // // Representation of FunVM code, global, and local addresses. // // Developed June 2012 by <NAME> (University of Glasgow). // // Extended September 2017 - March 2018 by <NAME>. // ////////////////////////////////////////////////////////////// public class Address { public static final int CODE = 0, GLOBAL = 1, LOCAL = 2; public int offset; public int locale; // CODE, GLOBAL, or LOCAL public Address (int off, int loc) { offset = off; locale = loc; } } <file_sep># Use a PHP7.0 image that is packaged with the Apache web server FROM php:7.0-apache # Download composer and install composer.phar in /usr/local/bin RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer # Create the 'app' directory and set to be the working directory of the container WORKDIR /app # Copy all files in current directory to the working directory of the container COPY . /app # Update packages and install composer and PHP dependencies. RUN apt-get update -yqq RUN apt-get install git zlib1g-dev -yqq RUN pecl install xdebug # Compile PHP, include these extensions. RUN docker-php-ext-install zip RUN docker-php-ext-enable xdebug # Use the 'composer.json' file to download any PHP dependencies (including Laravel) RUN composer install RUN cp .env.example .env RUN php artisan key:generate <file_sep>package api; ////////////////////////////////////////////////////////////// // // A visitor for code generation for Fun. // // Developed August 2015 by <NAME> (University of Glasgow). // // Based on a previous version by <NAME>. // // Extended September 2017 - March 2018 by <NAME>. // ////////////////////////////////////////////////////////////// import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import org.antlr.v4.runtime.misc.*; import java.util.List; import java.util.Map; import java.util.HashMap; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class FunEncoderVisitor extends AbstractParseTreeVisitor<Void> implements FunVisitor<Void> { private SVM obj = new SVM(); private SymbolTable<Address> addrTable = new SymbolTable<Address>(); // Defines the augmentations and the order in which the AST nodes should be visited private JsonArray nodeOrder = new JsonArray(); // A map of nodes to explanatory messages private Map<Integer,JsonArray> nodeExplanations = new HashMap<Integer,JsonArray>(); private int globalvaraddr = 0; private int localvaraddr = 0; private int currentLocale = Address.GLOBAL; public JsonArray getNodeOrder() { return nodeOrder; } private void predefine () { addrTable.put("read", new Address(SVM.READOFFSET, Address.CODE)); addrTable.put("write", new Address(SVM.WRITEOFFSET, Address.CODE)); } private String convertLocale(int locale) { switch(locale) { case 0: return "code"; case 1: return "global"; case 2: return "local"; } return "Unrecognised locale"; } /** * Create a node containing all augmentation information. * @param ctx the parse tree * @param explanation the explanatory message */ private void addNode(Object ctx, String explanation) { int contextHash = ctx.hashCode(); JsonObject nodeObject = new JsonObject(); JsonArray currentExplanationArray = new JsonArray(); JsonArray previousExplanationArray = nodeExplanations.get(contextHash); if (previousExplanationArray != null) { currentExplanationArray.addAll(previousExplanationArray); currentExplanationArray.add(explanation); } else { currentExplanationArray.add(explanation); } nodeExplanations.put(contextHash, currentExplanationArray); JsonArray addrTableArray = new JsonArray(); addrTable.getGlobals().forEach((id,addr) -> { JsonObject addrTableObject = new JsonObject(); addrTableObject.addProperty("scope", convertLocale(addr.locale)); addrTableObject.addProperty("id", id); addrTableObject.addProperty("type_address", Integer.toString(addr.offset)); addrTableArray.add(addrTableObject); }); addrTable.getLocals().forEach((id,addr) -> { JsonObject addrTableObject = new JsonObject(); addrTableObject.addProperty("scope", convertLocale(addr.locale)); addrTableObject.addProperty("id", id); addrTableObject.addProperty("type_address", Integer.toString(addr.offset)); addrTableArray.add(addrTableObject); }); nodeObject.addProperty("id", contextHash); nodeObject.add("explanations", currentExplanationArray); nodeObject.add("objectCode", obj.getObjectCode()); nodeObject.add("table", addrTableArray); nodeOrder.add(nodeObject); } /*============================== VISITORS ==============================*/ /** * Visit a parse tree produced by the {@code prog} * labeled alternative in {@link FunParser#program}. * @param ctx the parse tree * @return the visitor result */ public Void visitProg(FunParser.ProgContext ctx) { predefine(); addNode(ctx, "Predefine the read and write procedures"); List<FunParser.Var_declContext> var_decl = ctx.var_decl(); if (!var_decl.isEmpty()) { addNode(ctx, "Walk var-decl, generating code"); for (FunParser.Var_declContext vd : var_decl) visit(vd); } int calladdr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c1 (" + calladdr + ")"); obj.emit12(SVM.CALL, 0); addNode(ctx, "Emit 'CALL 0'"); obj.emit1(SVM.HALT); addNode(ctx, "Emit 'HALT'"); List<FunParser.Proc_declContext> proc_decl = ctx.proc_decl(); if (!proc_decl.isEmpty()) { addNode(ctx, "Walk proc-decl, generating code"); for (FunParser.Proc_declContext pd : proc_decl) visit(pd); } int mainaddr = addrTable.get("main").offset; addNode(ctx, "Lookup 'main' and retrieve its address, " + mainaddr); obj.patch12(calladdr, mainaddr); addNode(ctx, "Patch address of 'main' (" + mainaddr + ") into the call at c1 (" + calladdr + ")"); return null; } /** * Visit a parse tree produced by the {@code proc} * labeled alternative in {@link FunParser#proc_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitProc(FunParser.ProcContext ctx) { String id = ctx.ID().getText(); Address procaddr = new Address( obj.currentOffset(), Address.CODE); addNode(ctx, "Insert '" + id + "' into the address table at address " + obj.currentOffset() + " (scope: code)"); addrTable.put(id, procaddr); addrTable.enterLocalScope(); addNode(ctx, "Enter local scope"); currentLocale = Address.LOCAL; localvaraddr = 2; // ... allows 2 words for link data FunParser.Formal_declContext fd = ctx.formal_decl(); addNode(ctx, "Walk formal-decl, generating code"); visit(fd); List<FunParser.Var_declContext> var_decl = ctx.var_decl(); if(!var_decl.isEmpty()) { addNode(ctx, "Walk var-decl, generating code"); for (FunParser.Var_declContext vd : var_decl) visit(vd); } addNode(ctx, "Walk com, generating code"); visit(ctx.seq_com()); obj.emit11(SVM.RETURN, 0); addNode(ctx, "Emit 'RETURN 0'"); addrTable.exitLocalScope(); addNode(ctx, "Exit local scope"); currentLocale = Address.GLOBAL; return null; } /** * Visit a parse tree produced by the {@code func} * labeled alternative in {@link FunParser#proc_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitFunc(FunParser.FuncContext ctx) { String id = ctx.ID().getText(); Address procaddr = new Address(obj.currentOffset(), Address.CODE); addNode(ctx, "Insert '" + id + "' into the address table at address " + obj.currentOffset() + " (scope: code)"); addrTable.put(id, procaddr); addrTable.enterLocalScope(); addNode(ctx, "Enter local scope"); currentLocale = Address.LOCAL; localvaraddr = 2; // ... allows 2 words for link data FunParser.Formal_declContext fd = ctx.formal_decl(); addNode(ctx, "Walk formal-decl, generating code"); visit(fd); List<FunParser.Var_declContext> var_decl = ctx.var_decl(); if (!var_decl.isEmpty()) { addNode(ctx, "Walk var-decl, generating code"); for (FunParser.Var_declContext vd : var_decl) visit(vd); } addNode(ctx, "Walk com, generating code"); visit(ctx.seq_com()); addNode(ctx, "Walk return expr, generating code"); visit(ctx.expr()); obj.emit11(SVM.RETURN, 1); addNode(ctx, "Emit 'RETURN 1'"); addrTable.exitLocalScope(); addNode(ctx, "Exit local scope"); currentLocale = Address.GLOBAL; return null; } /** * Visit a parse tree produced by the {@code formal} * labeled alternative in {@link FunParser#formal_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitFormal(FunParser.FormalContext ctx) { FunParser.TypeContext tc = ctx.type(); if (tc != null) { String id = ctx.ID().getText(); addNode(ctx, "Insert '" + id + "' into the address table at address " + localvaraddr + " (scope: local)"); addrTable.put(id, new Address(localvaraddr++, Address.LOCAL)); obj.emit11(SVM.COPYARG, 1); addNode(ctx, "Emit 'COPYARG 1'"); } else { addNode(ctx, "Note: no formal parameters"); } return null; } /** * Visit a parse tree produced by the {@code var} * labeled alternative in {@link FunParser#var_decl}. * @param ctx the parse tree * @return the visitor result */ public Void visitVar(FunParser.VarContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.expr()); String id = ctx.ID().getText(); switch (currentLocale) { case Address.LOCAL: addNode(ctx, "Insert '" + id + "' into the address table at address " + localvaraddr + " (scope: local)"); addrTable.put(id, new Address(localvaraddr++, Address.LOCAL)); break; case Address.GLOBAL: addNode(ctx, "Insert '" + id + "' into the address table at address " + globalvaraddr + " (scope: global)"); addrTable.put(id, new Address(globalvaraddr++, Address.GLOBAL)); break; } return null; } /** * Visit a parse tree produced by the {@code bool} * labeled alternative in {@link FunParser#type}. * @param ctx the parse tree * @return the visitor result */ public Void visitBool(FunParser.BoolContext ctx) { return null; } /** * Visit a parse tree produced by the {@code int} * labeled alternative in {@link FunParser#type}. * @param ctx the parse tree * @return the visitor result */ public Void visitInt(FunParser.IntContext ctx) { return null; } /** * Visit a parse tree produced by the {@code assn} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitAssn(FunParser.AssnContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.expr()); String id = ctx.ID().getText(); Address varaddr = addrTable.get(id); addNode(ctx, "Lookup '" + id + "' and retrieve its address, " + varaddr.offset); switch (varaddr.locale) { case Address.GLOBAL: obj.emit12(SVM.STOREG, varaddr.offset); addNode(ctx, "Emit STOREG " + varaddr.offset); break; case Address.LOCAL: obj.emit12(SVM.STOREL, varaddr.offset); addNode(ctx, "Emit STOREL " + varaddr.offset); break; } return null; } /** * Visit a parse tree produced by the {@code proccall} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitProccall(FunParser.ProccallContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.actual()); String id = ctx.ID().getText(); Address procaddr = addrTable.get(id); addNode(ctx, "Lookup '" + id + "' and retrieve its address, " + procaddr.offset); // Assume procaddr.locale == CODE. obj.emit12(SVM.CALL, procaddr.offset); addNode(ctx, "Emit 'CALL " + procaddr.offset + "'"); return null; } /** * Visit a parse tree produced by the {@code if} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitIf(FunParser.IfContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.expr()); int condaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c1 (" + condaddr + ")"); obj.emit12(SVM.JUMPF, 0); addNode(ctx, "Emit 'JUMPF 0'"); if (ctx.c2 == null) { addNode(ctx, "Walk com, generating code"); visit(ctx.c1); int exitaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c2 (" + exitaddr + ")"); obj.patch12(condaddr, exitaddr); addNode(ctx, "Patch c2 (" + exitaddr + ") into the jump at c1 (" + condaddr + ")"); } else { addNode(ctx, "Walk com1, generating code"); visit(ctx.c1); int jumpaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c2 (" + jumpaddr + ")"); obj.emit12(SVM.JUMP, 0); addNode(ctx, "Emit 'JUMP 0'"); int elseaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c3 (" + elseaddr + ")"); obj.patch12(condaddr, elseaddr); addNode(ctx, "Patch c3 (" + elseaddr + ") into the jump at c1 (" + condaddr + ")"); addNode(ctx, "Walk com2, generating code"); visit(ctx.c2); int exitaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c4 (" + exitaddr + ")"); obj.patch12(jumpaddr, exitaddr); addNode(ctx, "Patch c4 (" + exitaddr + ") into the jump at c2 (" + jumpaddr + ")"); } return null; } /** * Visit a parse tree produced by the {@code while} * labeled alternative in {@link FunParser#com}. * @param ctx the parse tree * @return the visitor result */ public Void visitWhile(FunParser.WhileContext ctx) { int startaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c1 (" + startaddr + ")"); addNode(ctx, "Walk expr, generating code"); visit(ctx.expr()); int condaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c2 (" + condaddr + ")"); obj.emit12(SVM.JUMPF, 0); addNode(ctx, "Emit 'JUMPF 0'"); addNode(ctx, "Walk com, generating code"); visit(ctx.seq_com()); obj.emit12(SVM.JUMP, startaddr); addNode(ctx, "Emit 'JUMP c1 (" + startaddr + ")'"); int exitaddr = obj.currentOffset(); addNode(ctx, "Note the current instruction address, c3 (" + exitaddr + ")"); obj.patch12(condaddr, exitaddr); addNode(ctx, "Patch c3 (" + exitaddr + ") into the jump at c2 (" + condaddr + ")"); return null; } /** * Visit a parse tree produced by the {@code seq} * labeled alternative in {@link FunParser#seq_com}. * @param ctx the parse tree * @return the visitor result */ public Void visitSeq(FunParser.SeqContext ctx) { addNode(ctx, "Walk com, generating code"); visitChildren(ctx); return null; } /** * Visit a parse tree produced by {@link FunParser#expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitExpr(FunParser.ExprContext ctx) { if (ctx.e2 != null) { addNode(ctx.op, "Walk expr1, generating code"); visit(ctx.e1); addNode(ctx.op, "Walk expr2, generating code"); visit(ctx.e2); switch (ctx.op.getType()) { case FunParser.EQ: obj.emit1(SVM.CMPLT); addNode(ctx.op, "Emit 'CMPEQ'"); break; case FunParser.LT: obj.emit1(SVM.CMPLT); addNode(ctx.op, "Emit 'CMPLT'"); break; case FunParser.GT: obj.emit1(SVM.CMPGT); addNode(ctx.op, "Emit 'CMPGT'"); break; } } else { visit(ctx.e1); } return null; } /** * Visit a parse tree produced by {@link FunParser#sec_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitSec_expr(FunParser.Sec_exprContext ctx) { if (ctx.e2 != null) { addNode(ctx.op, "Walk expr1, generating code"); visit(ctx.e1); addNode(ctx.op, "Walk expr2, generating code"); visit(ctx.e2); switch (ctx.op.getType()) { case FunParser.PLUS: obj.emit1(SVM.ADD); addNode(ctx.op, "Emit 'ADD'"); break; case FunParser.MINUS: obj.emit1(SVM.SUB); addNode(ctx.op, "Emit 'SUB'"); break; case FunParser.TIMES: obj.emit1(SVM.MUL); addNode(ctx.op, "Emit 'MUL'"); break; case FunParser.DIV: obj.emit1(SVM.DIV); addNode(ctx.op, "Emit 'DIV'"); break; } } else { visit(ctx.e1); } return null; } /** * Visit a parse tree produced by the {@code false} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitFalse(FunParser.FalseContext ctx) { obj.emit12(SVM.LOADC, 0); addNode(ctx, "Emit 'LOADC 0'"); return null; } /** * Visit a parse tree produced by the {@code true} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitTrue(FunParser.TrueContext ctx) { obj.emit12(SVM.LOADC, 1); addNode(ctx, "Emit 'LOADC 1'"); return null; } /** * Visit a parse tree produced by the {@code num} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitNum(FunParser.NumContext ctx) { int value = Integer.parseInt(ctx.NUM().getText()); obj.emit12(SVM.LOADC, value); addNode(ctx, "Emit 'LOADC " + value + "'"); return null; } /** * Visit a parse tree produced by the {@code id} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitId(FunParser.IdContext ctx) { String id = ctx.ID().getText(); Address varaddr = addrTable.get(id); addNode(ctx, "Lookup '" + id + "' and retrieve its address, " + varaddr.offset); switch (varaddr.locale) { case Address.GLOBAL: obj.emit12(SVM.LOADG, varaddr.offset); addNode(ctx, "Emit 'LOADG " + varaddr.offset + "'"); break; case Address.LOCAL: obj.emit12(SVM.LOADC, varaddr.offset); addNode(ctx, "Emit 'LOADC " + varaddr.offset + "'"); break; } return null; } /** * Visit a parse tree produced by the {@code funccall} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitFunccall(FunParser.FunccallContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.actual()); String id = ctx.ID().getText(); Address funcaddr = addrTable.get(id); addNode(ctx, "Lookup '" + id + "' and retrieve its address, " + funcaddr.offset); // Assume funcaddr.locale == CODE. obj.emit12(SVM.CALL, funcaddr.offset); addNode(ctx, "Emit 'CALL " + funcaddr.offset + "'"); return null; } /** * Visit a parse tree produced by the {@code not} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitNot(FunParser.NotContext ctx) { addNode(ctx, "Walk expr, generating code"); visit(ctx.prim_expr()); obj.emit1(SVM.INV); addNode(ctx, "Emit 'INV'"); return null; } /** * Visit a parse tree produced by the {@code parens} * labeled alternative in {@link FunParser#prim_expr}. * @param ctx the parse tree * @return the visitor result */ public Void visitParens(FunParser.ParensContext ctx) { visit(ctx.expr()); return null; } /** * Visit a parse tree produced by {@link FunParser#actual}. * @param ctx the parse tree * @return the visitor result */ public Void visitActual(FunParser.ActualContext ctx) { FunParser.ExprContext ec = ctx.expr(); if (ec != null) { visit(ec); } return null; } } <file_sep>/* ========================================================================== * codeAnimation.js * * Build and draw the AST using the D3 library. * * Define the logic used to traverse/animate the resulting AST. * ========================================================================== */ // Import the D3 node module var d3 = require('d3'); // Import CodeTemplates module var CodeTemplates = require('./codeTemplates.js'); // Import CodeHelpers module var CodeHelpers = require('./codeHelpers.js'); var CodeAnimation = module.exports = { // Draw the AST gives the tree nodes drawTree: function(data) { var treeData = CodeHelpers.buildTree(data); var marginLeft = 10; var marginTop = 35 var width = 800 - (marginLeft * 2); var height = 650 - (marginTop * 2); var treemap = d3.tree().size([width, height]); var nodes = d3.hierarchy(treeData[0]); nodes = treemap(nodes); var svg = d3.select(".program-tree-container") .html("") .append("div") .classed("svg-container", true) .append("svg") .attr("preserveAspectRatio", "none") .attr("viewBox", "0 0 800 650") var g = svg.append("g") .attr( "transform", "translate(" + marginLeft + "," + marginTop + ")" ); g.selectAll(".link") .data(nodes.descendants().slice(1)).enter().append("path") .attr("class", "link").attr("d", function(d) { return "M" + d.x + "," + d.y + "C" + d.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + d.parent.y; }); var node = g.selectAll(".node") .data(nodes.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ( d.children ? " node--internal" : " node--leaf" ); }).attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }).attr("id", function(d) { return "node-" + d.data.id; }).attr("data-node-name", function(d) { return d.data.nodeName; }).attr("data-node-value", function(d) { return d.data.nodeValue; }); node.append("text") .attr("dy", ".35em") .style("text-anchor", "middle") .style("font-size", "0.75em") .text(function(d) { var name = d.data.nodeValue; if (name.length <= 5) return name; else return name.substring(0, 5) + "..."; }); node.each(function(){ var node = d3.select(this); var bBox = node.select("text").node().getBBox(); node.insert("rect", ":first-child") .attr("x", bBox.x - 3) .attr("y", bBox.y - 3) .attr("height", bBox.height + 6) .attr("width", bBox.width + 6); }); }, // Stop any currently running animation and show the correct containers initialise: function(executionType, executionNodeOrder) { pause(); previousNode = null; currentNodeIndex = -1; showGenerationAnimation = (executionType === "cg") ? true : false; if (showGenerationAnimation) { $(".controls-container span").html("Code Generation"); $("#display-contextual-container").hide(); $("#display-generation-container").show(); } else { $(".controls-container span").html("Contextual Analysis"); $("#display-generation-container").hide(); $("#display-contextual-container").show(); } nodeOrder = executionNodeOrder }, // 'Animate' the first node in the tree highlightFirstNode: function() { var node = nodeOrder[currentNodeIndex+1]; animateNode(node, true, 0); } } var nodeOrder; var currentNodeIndex; var is_playing; var showGenerationAnimation; var previousNode; $("#play-button").on("click", function() { play(); }); $("#pause-button").on("click", function() { pause(); }); $("#forward-button").on("click", function() { forward(); }); $("#reverse-button").on("click", function() { reverse(); }); // Increases the size and boldness of the current node text function increaseFontSize(transition) { transition .style("font-weight", "900") .style("font-size", "1em"); } // Increase the rectangle size based on the increased text size function highlightCurrentRectangle(currentNode, bBox) { currentNode.select("rect") .style("fill", "#035a80") .attr("x", bBox.x - 10) .attr("y", bBox.y - 10) .attr("width", bBox.width + 20) .attr("height", bBox.height + 20) currentNode.raise(); } // Decrease the previous rectangle back to its previous size and colour function unhighlightCurrentRectangle(previousNode, bBox) { $(previousNode).prev("rect") .css("fill", "#3e4153") .attr("x", bBox.x - 3) .attr("y", bBox.y - 3) .attr("width", bBox.width + 6) .attr("height", bBox.height + 6) } // Highlights a single node and displays any corresponding information function animateNode(node, isPlayingForward, delayOffset) { if (showGenerationAnimation) { var explanationsText = $(".generation-explanations ul"); var objectCodeText = $(".object-code ul"); var tableBody = $(".address-table tbody"); var tableWrapper = $(".address-table").parent(); var codeTemplateText = $(".code-template ul"); } else { var explanationsText = $(".contextual-explanations ul"); var tableBody = $(".type-table tbody"); var tableWrapper = $(".type-table").parent(); } var currentNode = d3.select("#node-" + node.id); currentNode.select("text").transition().duration(0) .delay(delayOffset * 1000).call(increaseFontSize) .on("start", function() { if (previousNode != null && previousNode !== this) { $(previousNode).css({ "font-weight": "normal", "font-size": "0.75em" }); var bBox = d3.select(previousNode).node().getBBox(); unhighlightCurrentRectangle(previousNode, bBox); } isPlayingForward ? currentNodeIndex++ : currentNodeIndex--; var nodeName = $("#node-"+node.id).data("node-name"); $(".data-heading-container span").html(nodeName); var tableEntries = ""; $.each(node.table, function(index, tableEntry) { tableEntries += "<tr><td>" + tableEntry.scope + "</td><td>" + tableEntry.id + "</td><td>" + tableEntry.type_address + "</td></tr>"; }); tableBody.html(tableEntries); tableWrapper.scrollTop(tableWrapper.prop("scrollHeight")); var explanations = ""; $.each(node.explanations, function(index, explanation) { explanations += "<li>> " + explanation + "</li>"; }); explanationsText.html(explanations); explanationsText.scrollTop(explanationsText.prop("scrollHeight")); if (showGenerationAnimation) { var objectCodeInstructions = ""; $.each(node.objectCode, function(index, objectCode) { objectCodeInstructions += "<li>" + objectCode + "</li>"; }); objectCodeText.html(objectCodeInstructions); objectCodeText.scrollTop(objectCodeText.prop("scrollHeight")); var codeTemplateInstructions = ""; var codeTemplate = CodeTemplates.getTemplate(nodeName); $.each(codeTemplate, function(index, codeTemplateInstruction) { codeTemplateInstructions += "<li>> " + codeTemplateInstruction + "</li>"; }) codeTemplateText.html(codeTemplateInstructions); } }).on("end", function() { var bBox = d3.select(this).node().getBBox(); highlightCurrentRectangle(currentNode, bBox); previousNode = this; if (hasAnimationFinished() && is_playing) { is_playing = false; enablePlayButton(); } }); } // Animates each node sequentially function animateTree() { for (var i = currentNodeIndex, j = 0; i < nodeOrder.length-1; i++, j++) { var node = nodeOrder[i+1]; animateNode(node, true, j); } } // Start playing the animation, restart if already at the end function play() { is_playing = true; enablePauseButton(); if (hasAnimationFinished()) currentNodeIndex = -1; animateTree(); } // Pause the animation, interrupt all current animations function pause() { is_playing = false; enablePlayButton(); d3.selectAll("text").interrupt(); } // Move one node forward function forward() { if (is_playing) pause(); if (!hasAnimationFinished()) { var node = nodeOrder[currentNodeIndex+1]; animateNode(node, true, 0); } } // Move one node backward function reverse() { if (is_playing) pause(); if (hasAnimationStarted()) { var node = nodeOrder[currentNodeIndex-1]; animateNode(node, false, 0); } } // Show the play button, hide the pause button function enablePlayButton() { $("#play-button").show(); $("#pause-button").hide(); } // Show the pause button, hide the play button function enablePauseButton() { $("#play-button").hide(); $("#pause-button").show(); } // Check if the animation has reached the last node function hasAnimationFinished() { return currentNodeIndex === nodeOrder.length-1; } // Check if the animation has moved beyond the first node function hasAnimationStarted() { return currentNodeIndex > 0; }
cc0fb8d4889da3cebcb4d0c561f94534c6f0b646
[ "JavaScript", "Markdown", "Maven POM", "Java", "PHP", "Dockerfile" ]
19
JavaScript
DavidR95/FunCompiler
ac74886bd5be41633ddd961fffafc6d7bf0148bc
655e716e23cb61171b33d306591b0060101880dc
refs/heads/master
<file_sep># Change Log ## [Unreleased](https://github.com/vanyaland/IMNetworkReachability/tree/HEAD) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.2.1...HEAD) **Closed issues:** - Problem when compile Xcode 9 [\#2](https://github.com/vanyaland/IMNetworkReachability/issues/2) ## [0.2.1](https://github.com/vanyaland/IMNetworkReachability/tree/0.2.1) (2017-12-19) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.2.0...0.2.1) **Merged pull requests:** - change the access qualifier from private to fileprivate [\#3](https://github.com/vanyaland/IMNetworkReachability/pull/3) ([frelei](https://github.com/frelei)) ## [0.2.0](https://github.com/vanyaland/IMNetworkReachability/tree/0.2.0) (2017-07-08) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.2...0.2.0) ## [0.2](https://github.com/vanyaland/IMNetworkReachability/tree/0.2) (2017-07-08) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.1.2...0.2) ## [0.1.2](https://github.com/vanyaland/IMNetworkReachability/tree/0.1.2) (2017-07-05) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.1.1...0.1.2) ## [0.1.1](https://github.com/vanyaland/IMNetworkReachability/tree/0.1.1) (2017-07-05) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.1...0.1.1) ## [0.1](https://github.com/vanyaland/IMNetworkReachability/tree/0.1) (2017-07-05) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.0.4...0.1) ## [0.0.4](https://github.com/vanyaland/IMNetworkReachability/tree/0.0.4) (2017-07-04) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.0.3...0.0.4) ## [0.0.3](https://github.com/vanyaland/IMNetworkReachability/tree/0.0.3) (2017-07-04) [Full Changelog](https://github.com/vanyaland/IMNetworkReachability/compare/0.0.2...0.0.3) ## [0.0.2](https://github.com/vanyaland/IMNetworkReachability/tree/0.0.2) (2017-07-04) \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*<file_sep>/** * 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. */ import Foundation import SystemConfiguration // MARK: AsyncHandler class AsyncHandler { private let hostName: String private let reachability: SCNetworkReachability? /// Queue where the `SCNetworkReachability` callbacks run private let queue = DispatchQueue.main /// Keeps track of a backup of the last flags read private var currentReachabilityFlags: SCNetworkReachabilityFlags? private var isListening = false private var callback: IMNetworkCallback = { _ in } init(_ host: String) { hostName = host reachability = SCNetworkReachabilityCreateWithName(nil, host) } func start(_ callback: IMNetworkCallback?) { guard !isListening else { return } guard let reachability = reachability else { return self.callback(.error(.canNotInstantiateReachability)) } if let callback = callback { self.callback = callback } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<AsyncHandler>.passUnretained(self).toOpaque()) let callbackClosure = buildCallbackClosure() if !SCNetworkReachabilitySetCallback(reachability, callbackClosure, &context) { return self.callback(.error(.notAbleSetCallback)) } if !SCNetworkReachabilitySetDispatchQueue(reachability, queue) { return self.callback(.error(.notAbleSetQueue)) } queue.async { self.currentReachabilityFlags = nil var flags = SCNetworkReachabilityFlags() SCNetworkReachabilityGetFlags(reachability, &flags) self.checkReachability(flags: flags) } isListening = true } /// Stops listening func stop() { guard isListening, let reachability = reachability else { return } SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) isListening = false } // MARK: Private private func buildCallbackClosure() -> SCNetworkReachabilityCallBack? { let callbackClosure: SCNetworkReachabilityCallBack? = { (reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in guard let info = info else { return } let handler = Unmanaged<AsyncHandler>.fromOpaque(info).takeUnretainedValue() DispatchQueue.main.async { handler.checkReachability(flags: flags) } } return callbackClosure } private func checkReachability(flags: SCNetworkReachabilityFlags) { if currentReachabilityFlags != flags { currentReachabilityFlags = flags let result: IMReachabilityResult = SyncEvaluator .isNetworkReachable(with: flags) ? .reachable : .offline self.callback(result) } } } <file_sep># IMNetworkReachability [![codebeat badge](https://codebeat.co/badges/443cdf3e-63c0-458c-bb83-611b1fe700c6)](https://codebeat.co/projects/github-com-vanyaland-imnetworkreachability-master) [![Swift Package Manager compatible](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![CocoaPods](https://img.shields.io/cocoapods/v/IMNetworkReachability.svg) ![Platforms](https://img.shields.io/cocoapods/p/IMNetworkReachability.svg) ![License](https://img.shields.io/npm/l/express.svg) IMNetworkReachability is a reachability framework. It is designed to help you interface with network activity events. It allows you to monitor network state synchronously and asynchronously. - [Requirements](#requirements) - [Installation](#installation) - [Usage](#usage) ## Requirements - iOS 8.0+ / macOS 10.9+ / tvOS 9.0+ - Xcode 9.0 - Swift 4.0 ## Installation IMNetworkReachability supports multiple methods for installing the library in a project. ## Installation with CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like IMNetworkReachability in your projects. See the ["Getting Started" guide for more information](https://guides.cocoapods.org/using/getting-started.html). You can install it with the following command: ```bash $ gem install cocoapods ``` #### Podfile To integrate IMNetworkReachability into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' target 'iOS' do platform :ios, '8.0' use_frameworks! pod 'IMNetworkReachability', '~> 0.2.0' end target 'macOS' do platform :osx, '10.9' use_frameworks! pod 'IMNetworkReachability', '~> 0.2.0' end target 'tvOS' do platform :tvos, '9.0' use_frameworks! pod 'IMNetworkReachability', '~> 0.2.0' end ``` Then, run the following command: ```bash $ pod install ``` ### Installation with Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with [Homebrew](http://brew.sh/) using the following command: ```bash $ brew update $ brew install carthage ``` To integrate IMNetworkReachability into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "vanyaland/IMNetworkReachability" ~> 0.2.0 ``` Run `carthage` to build the framework and drag the built `IMNetworkReachability.framework` into your Xcode project. ### Swift Package Manager The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but IMNetworkReachability does support its use on supported platforms. Once you have your Swift package set up, adding IMNetworkReachability as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. ```swift dependencies: [ .package(url: "https://github.com/vanyaland/IMNetworkReachability.git", from: "0.2.0"), ] ``` ### Manually If you prefer not to use any of the aforementioned dependency managers, you can integrate IMNetworkReachability into your project manually. #### Embedded Framework - Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: ```bash $ git init ``` - Add IMNetworkReachability as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/vanyaland/IMNetworkReachability.git ``` - Open the new `IMNetworkReachability` folder, and drag the `IMNetworkReachability.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `IMNetworkReachability.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `IMNetworkReachability.xcodeproj` folders each with two different versions of the `IMNetworkReachability.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `IMNetworkReachability.framework`. - Select the top `IMNetworkReachability.framework` for iOS and the bottom one for OS X. > You can verify which one you selected by inspecting the build log for your project. The build target for `IMNetworkReachability` will be listed as either `IMNetworkReachability_iOS`, `IMNetworkReachability_macOS` or `IMNetworkReachability_tvOS`. - And that's it! > The `IMNetworkReachability.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. ## Usage #### Synchronously ```swift let reachability = IMNetworkReachability("www.google.com") switch reachability.isReachable() { case .reachable: print("Reachable") case .offline: print("Offline") case .error(let error): print("Failed to check for a network reachability, error: \(error)") } ``` #### Closures ```swift // Declare this property where it won't go out of scope relative to your listener let reachability = IMNetworkReachability("www.google.com") reachability.startListening { (result) in // this is called on a main thread switch result { case .reachable: print("Reachable") case .offline: print("Offline") case .error(let error): print("Failed to check for a network reachability, error: \(error)") } } ``` and for stopping notifications ```swift reachability.stopListening() ``` Also, don't forget to [enable network access](https://developer.apple.com/library/content/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/uid/TP40011195-CH4-SW9) on macOS. ## Author I'm [<NAME>](https://www.facebook.com/ivan.magda). Email: [<EMAIL>](mailto:<EMAIL>). Twitter: [@magda_ivan](https://twitter.com/magda_ivan). ## LICENSE This project is open-sourced software licensed under the MIT License. See the LICENSE file for more information.
8c4ce854cb420fa4f1351abc22cc6b92f722c007
[ "Markdown", "Swift" ]
3
Markdown
ivan-magda/IMNetworkReachability
09a359c0c1ce821f7b03dfa7e9a6a01c7cc50e4d
79343f0fdd7b1fe51b17e545973897d9107ed270
refs/heads/master
<repo_name>xiongxiong666-C/xxstore<file_sep>/goodIt.php <?php echo "This is a PHP code";//注释 echo "I am in hot_fic branch"; echo "Master branch doing"; echo "ssh push"; ?>
39bf8cc9288da15a99b3110baa8b93df5777eb5b
[ "PHP" ]
1
PHP
xiongxiong666-C/xxstore
abf4b308af80268147b0ffd52c088e22695365ad
cce40e2d6f5acda7a1c1cb58a94ecad6b70bad07
refs/heads/master
<repo_name>spaul13/TCPClient-C-Sharp<file_sep>/Assets/CallPrefetch.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CallPrefetch : MonoBehaviour { public TCPTestClient ttc; public int fid = 7; int count = 0; // Use this for initialization void Start () { ttc = GameObject.Find ("udpclient").GetComponent<TCPTestClient> (); ttc.ConnectToTcpServer(); } // Update is called once per frame void Update () { //StartCoroutine("Send"); if (Input.GetMouseButtonDown(0)) { List<int> fid_list = new List<int>(); fid_list.Add(fid); //fid_list.Add(fid + 161); //fid_list.Add(fid + 1); //before sending the request for fids we need to check whether those fids already existed or not then pass to network thread Send(fid_list); StartCoroutine(ttc.ListenForData()); count++; } /*if (fid < 200) fid++; else fid = 0; ttc.Sendfid(fid);*/ } //IEnumerator Send() void Send(List<int> fid_list) { //else fid = 0; //fid++; ttc.Sendfid(fid_list); //if (fid < 2) //yield return new WaitForSeconds(2f); } } <file_sep>/Assets/UDPClient.cs using UnityEngine; using System.Collections; using System; using System.Text; using System.Net; using System.Net.Sockets; public class UDPClient : MonoBehaviour { public UdpClient client; public IPAddress serverIp; public string hostIp = "192.168.1.131"; public int hostPort = 4544; public IPEndPoint hostEndPoint; //string prefetch_fn; byte[] prefetch_fn; int fid = 0; //initial frameid int fid_max = 25000; void Start(){ serverIp = IPAddress.Parse(hostIp); hostEndPoint = new IPEndPoint(serverIp,hostPort); client = new UdpClient(); client.Connect(hostEndPoint); client.Client.Blocking = false; prefetch_fn = new byte[20]; } //public void SendDgram(string evento,string msg) public void SendDgram(int fid){ int _fid = fid; /* for (int i = 9; i >= 0; i--) { string mys = (_fid % 10).ToString(); //prefetch_fn = prefetch_fn + mys; prefetch_fn = prefetch_fn + "0" + mys; _fid /= 10; } */ for (int i = 9; i >= 0; i--) { prefetch_fn [i] = Convert.ToByte((char)(_fid % 10 + 48)); _fid /= 10; } prefetch_fn [10] = 0; //Debug.Log (prefetch_fn); //byte[] dgram = Encoding.UTF8.GetBytes(prefetch_fn); //client.Send(dgram,dgram.Length); //client.BeginReceive(new AsyncCallback(processDgram),client); client.Send(prefetch_fn, 10); } public void processDgram(IAsyncResult res){ try { byte[] recieved = client.EndReceive(res,ref hostEndPoint); Debug.Log(Encoding.UTF8.GetString(recieved)); } catch (Exception ex) { throw ex; } } /* void OnGUI() { if(GUI.Button (new Rect (10,10,100,40), "Send")) { DynamicObject d = new DynamicObject(); SendDgram("JSON",JsonUtility.ToJson(d).ToString()); } } */ void Update() { SendDgram (fid); if (fid < fid_max) fid = fid + 1; else fid = 0; } }
daecc8ab5c87c0f1b5150019b9dff5b8b0cd85c0
[ "C#" ]
2
C#
spaul13/TCPClient-C-Sharp
257fc4e74b7bb14b2998379f97a1d48ca5745dcf
c387b8d95dfde2ffcc4f76bb64ba049c72e8a875
refs/heads/master
<file_sep>package com.game.desktop; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; public class ProcessSongData { public static final String ONSET_FILE = "onset.txt"; public static final String PITCH_FILE = "pitch.txt"; public static final String EXPORT_FILE = "songData.dat"; public static final String SONG_FILE = "chime_phototropic.wav"; public static final String PATH = "assets-raw/music"; public static final String EXPORT_PATH = "game_data"; public static final int THRESHOLD = 5; public static double[] loadOnsetData() throws FileNotFoundException { File file = new File(PATH+"/"+ONSET_FILE); ArrayList<String> data = new ArrayList<String>(); Scanner scan = new Scanner(file); while (scan.hasNext()) { data.add(scan.nextLine()); } double[] onsetData = new double[data.size()]; for (int x=0;x<onsetData.length;x++) { onsetData[x] = Double.parseDouble(data.get(x)); } return onsetData; } public static double[][] loadPitchData() throws FileNotFoundException { File file = new File(PATH+"/"+PITCH_FILE); ArrayList<String> data = new ArrayList<String>(); Scanner scan = new Scanner(file); while (scan.hasNext()) { data.add(scan.nextLine()); } double[][] pitchData = new double[2][data.size()]; for (int x=0;x<pitchData[0].length;x++) { String[] values = data.get(x).split(" "); pitchData[0][x] = Double.parseDouble(values[0]); pitchData[1][x] = Double.parseDouble(values[1]); } return pitchData; } public static int[] computePitchAtOnset(double[] onset, double[][]pitch) { int[] result = new int[onset.length]; int pitchLoc = 0; for (int x=0;x<onset.length;x++) { while (pitch[0][pitchLoc] < onset[x]) { pitchLoc++; } result[x] = (int)((pitch[1][pitchLoc-1]+pitch[1][pitchLoc])/2); } return result; } /** * Very simple clustering algorithm. * @param rawTypes * @return */ public static int[] setTypes(int[] rawTypes) { int[] types = new int[rawTypes.length]; int nextType = 1; HashMap<Integer,Integer> baseTypes = new HashMap<Integer,Integer>(); types[0] = 1; baseTypes.put(1, rawTypes[0]); for (int x=1;x<types.length;x++) { types[x] = -1; for(Integer key : baseTypes.keySet()) { int value = baseTypes.get(key); if ((rawTypes[x] > value - 5) && (rawTypes[x] < value + 5)) { types[x] = key; break; } } if (types[x] == -1) { types[x] = nextType; baseTypes.put(nextType, rawTypes[x]); nextType++; } } return types; } /** * Looks for beat types that occur in close succession. * @param onset * @param types */ public static ArrayList<double[]> findRuns(double[] onset, int[] types) { ArrayList<double[]> data = new ArrayList<double[]>(); int lastType = types[0]; boolean run = false; int start = -1; int end = -1; for (int x=1;x<types.length;x++) { if ((lastType == types[x]) && (onset[x-1] + 0.4 > onset[x])) { if (!run) { start = x-1; } run = true; } else if (run) { end = x-1; double[] runData = new double[end - start + 2]; for (int y=0;y<runData.length-1;y++) { runData[y] = onset[start+y]; } runData[runData.length-1] = types[x-1]; data.add(runData); for (int y=start; y<=end;y++) { onset[y] = -1; types[y] = -1; } end = -1; start = -1; run = false; } lastType = types[x]; } return data; } /** * Create the JSON file for the game. * @param onset * @param types * @throws FileNotFoundException */ public static void exportData(double[] onset, int[] types, ArrayList<double[]> runData) throws FileNotFoundException { File file = new File(EXPORT_PATH+"/"+EXPORT_FILE); PrintWriter pw = new PrintWriter(file); pw.print("{\n"); pw.print("song: "+SONG_FILE+"\n"); pw.print("onset: [\n"); for (int x=0;x<onset.length-1;x++) { if (onset[x] != -1) pw.print(onset[x]+", \n"); } pw.print(onset[onset.length-1]+" ],\n"); pw.print("types: [\n"); for (int x=0;x<types.length-1;x++) { if (types[x] != -1) pw.print(types[x]+", \n"); } pw.print(types[types.length-1]+" ],\n"); pw.print("runs: [\n"); for (double[] run: runData) { pw.print("[ "); for (int x=0;x<run.length-1;x++) { pw.print(run[x]+", "); } pw.print(run[run.length-1]+" ]\n"); } pw.print(" ]\n"); pw.print("}"); pw.flush(); pw.close(); } public static void main(String[] args) { try { double[] onsetData = loadOnsetData(); double[][] pitchData = loadPitchData(); int[] pitchAtOnsetData = computePitchAtOnset(onsetData,pitchData); int[] typeData = setTypes(pitchAtOnsetData); ArrayList<double[]> runData = findRuns(onsetData,typeData); exportData(onsetData,typeData,runData); System.out.println("Here"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package com.game.obj; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; public abstract class AbstractGameObject extends SimpleAbstractGameObject { // Non-Box2D Physics public Vector2 velocity; public Vector2 terminalVelocity; public Vector2 friction; public Vector2 acceleration; public Rectangle bounds; // Box2D Physics public Body body; // Animation public float stateTime; public Animation animation; public AbstractGameObject() { velocity = new Vector2(); terminalVelocity = new Vector2(1, 1); friction = new Vector2(); acceleration = new Vector2(); bounds = new Rectangle(); } protected void updateMotionX(float deltaTime) { if (velocity.x != 0) { if (velocity.x > 0) { velocity.x = Math.max(velocity.x - friction.x * deltaTime, 0); } else { velocity.x = Math.min(velocity.x + friction.x * deltaTime, 0); } } velocity.x += acceleration.x * deltaTime; velocity.x = MathUtils.clamp(velocity.x, -terminalVelocity.x, terminalVelocity.x); } protected void updateMotionY(float deltaTime) { if (velocity.y != 0) { if (velocity.y > 0) { velocity.y = Math.max(velocity.y - friction.y * deltaTime, 0); } else { velocity.y = Math.min(velocity.y + friction.y * deltaTime, 0); } } velocity.y += acceleration.y * deltaTime; velocity.y = MathUtils.clamp(velocity.y, -terminalVelocity.y, terminalVelocity.y); } // TODO: Should this method be made final so we can't override it? public void update(float deltaTime) { stateTime += deltaTime; if (body == null) { updateMotionX(deltaTime); updateMotionY(deltaTime); m_position.x += velocity.x * deltaTime; m_position.y += velocity.y * deltaTime; } else { m_position.set(body.getPosition()); rotation = body.getAngle() * MathUtils.radiansToDegrees; } } public void setAnimation(Animation anim) { animation = anim; stateTime = 0; } }
c1b40c223a904d7e8a41d6261783670ec6d7023f
[ "Java" ]
2
Java
cdgirard/ShinxDefends
cfde3a942efccce2ff3009b9ee383ae2ce5b93ae
c3d195f648bc8f305d2d82c78d8f9fb1022248a2
refs/heads/master
<repo_name>suenot/gulp-sass-example<file_sep>/gulpfile.js var gulp = require('gulp'), $ = require('gulp-load-plugins')(); gulp.task('sass', function () { return gulp.src(['./sass/**/*.sass']) .pipe($.sourcemaps.init()) .pipe($.sass({ indentedSyntax: true, errLogToConsole: true, outputStyle: 'compressed' })) // .pipe($.autoprefixer('last 3 version')) .pipe($.sourcemaps.write('.')) .pipe(gulp.dest('css')); }); gulp.task('watch', function () { gulp.watch(['./sass/**/*.sass'], ['sass']); }); gulp.task('default', ['sass', 'watch']);
4f9c85e4a47c71f5444b4885194e4e20d7e4a803
[ "JavaScript" ]
1
JavaScript
suenot/gulp-sass-example
7c6071e46e31639795cfe1e9b1e3693a1c62d244
8afd5914c8eaf961f2a7536dbf605302bca589a2
refs/heads/main
<repo_name>venkii04/Tusk<file_sep>/bike.java package test; public class Bikes extends Vehicle{ void print() { System.out.println("Bike is Running"); } }<file_sep>/Withdraw.java package Test; public class Withdraw extends BankDB{ int amount; public void setValue(int amt) { this.amount = amt; } public int getValue(int bal) { return bal - amount; } }<file_sep>/deposite.java package Test; public class Deposit extends BankDB{ int amount; public void setValue(int amt) { this.amount = amt; } public int getBal(int bal) { return bal + amount; } }<file_sep>/cars.java package test; public class Cars extends Vehicle{ void print() { System.out.println("Car is Running"); } }<file_sep>/DemoAccess.java package Test; public class DemoAccess { int i = 1; public int j = 2; protected int k = 3; private int m = 4; }
d0e018ea9d507ae88d20f26823e278974e8bb150
[ "Java" ]
5
Java
venkii04/Tusk
a5b97a815f44a807a15e9f16eebaf3dd5e439c23
c0b640b1f29eba93b0aac268a182aec0497db17c
refs/heads/master
<file_sep>package externaldns import ( "fmt" "reflect" "time" "github.com/alecthomas/kingpin" "github.com/sirupsen/logrus" "github.com/yangkailc/bigtree-dns/source" ) const ( passwordMask = "******" ) var ( // Version is the current version of the app, generated at build time Version = "unknown" ) // Config is a project-wide configuration type Config struct { APIServerURL string KubeConfig string RequestTimeout time.Duration ContourLoadBalancerService string SkipperRouteGroupVersion string Sources []string Namespace string AnnotationFilter string FQDNTemplate string CombineFQDNAndAnnotation bool IgnoreHostnameAnnotation bool Compatibility string PublishInternal bool PublishHostIP bool AlwaysPublishNotReadyAddresses bool ConnectorSourceServer string Provider string GoogleProject string GoogleBatchChangeSize int GoogleBatchChangeInterval time.Duration DomainFilter []string ExcludeDomains []string ZoneIDFilter []string AlibabaCloudConfigFile string AlibabaCloudZoneType string AWSZoneType string AWSZoneTagFilter []string AWSAssumeRole string AWSBatchChangeSize int AWSBatchChangeInterval time.Duration AWSEvaluateTargetHealth bool AWSAPIRetries int AWSPreferCNAME bool AzureConfigFile string AzureResourceGroup string AzureSubscriptionID string AzureUserAssignedIdentityClientID string CloudflareProxied bool CloudflareZonesPerPage int CoreDNSPrefix string RcodezeroTXTEncrypt bool AkamaiServiceConsumerDomain string AkamaiClientToken string AkamaiClientSecret string AkamaiAccessToken string InfobloxGridHost string InfobloxWapiPort int InfobloxWapiUsername string InfobloxWapiPassword string `secure:"yes"` InfobloxWapiVersion string InfobloxSSLVerify bool InfobloxView string InfobloxMaxResults int DynCustomerName string DynUsername string DynPassword string `secure:"yes"` DynMinTTLSeconds int OCIConfigFile string InMemoryZones []string OVHEndpoint string OVHApiRateLimit int PDNSServer string PDNSAPIKey string `secure:"yes"` PDNSTLSEnabled bool TLSCA string TLSClientCert string TLSClientCertKey string Policy string Registry string TXTOwnerID string TXTPrefix string TXTSuffix string Interval time.Duration Once bool DryRun bool UpdateEvents bool LogFormat string MetricsAddress string LogLevel string TXTCacheInterval time.Duration ExoscaleEndpoint string ExoscaleAPIKey string `secure:"yes"` ExoscaleAPISecret string `secure:"yes"` CRDSourceAPIVersion string CRDSourceKind string ServiceTypeFilter []string CFAPIEndpoint string CFUsername string CFPassword string RFC2136Host string RFC2136Port int RFC2136Zone string RFC2136Insecure bool RFC2136TSIGKeyName string RFC2136TSIGSecret string `secure:"yes"` RFC2136TSIGSecretAlg string RFC2136TAXFR bool RFC2136MinTTL time.Duration NS1Endpoint string NS1IgnoreSSL bool TransIPAccountName string TransIPPrivateKeyFile string DigitalOceanAPIPageSize int } var defaultConfig = &Config{ APIServerURL: "", KubeConfig: "", RequestTimeout: time.Second * 30, ContourLoadBalancerService: "heptio-contour/contour", SkipperRouteGroupVersion: "zalando.org/v1", Sources: nil, Namespace: "", AnnotationFilter: "", FQDNTemplate: "", CombineFQDNAndAnnotation: false, IgnoreHostnameAnnotation: false, Compatibility: "", PublishInternal: false, PublishHostIP: false, ConnectorSourceServer: "localhost:8080", Provider: "", GoogleProject: "", GoogleBatchChangeSize: 1000, GoogleBatchChangeInterval: time.Second, DomainFilter: []string{}, ExcludeDomains: []string{}, AlibabaCloudConfigFile: "/etc/kubernetes/alibaba-cloud.json", AWSZoneType: "", AWSZoneTagFilter: []string{}, AWSAssumeRole: "", AWSBatchChangeSize: 1000, AWSBatchChangeInterval: time.Second, AWSEvaluateTargetHealth: true, AWSAPIRetries: 3, AWSPreferCNAME: false, AzureConfigFile: "/etc/kubernetes/azure.json", AzureResourceGroup: "", AzureSubscriptionID: "", CloudflareProxied: false, CloudflareZonesPerPage: 50, CoreDNSPrefix: "/skydns/", RcodezeroTXTEncrypt: false, AkamaiServiceConsumerDomain: "", AkamaiClientToken: "", AkamaiClientSecret: "", AkamaiAccessToken: "", InfobloxGridHost: "", InfobloxWapiPort: 443, InfobloxWapiUsername: "admin", InfobloxWapiPassword: "", InfobloxWapiVersion: "2.3.1", InfobloxSSLVerify: true, InfobloxView: "", InfobloxMaxResults: 0, OCIConfigFile: "/etc/kubernetes/oci.yaml", InMemoryZones: []string{}, OVHEndpoint: "ovh-eu", OVHApiRateLimit: 20, PDNSServer: "http://localhost:8081", PDNSAPIKey: "", PDNSTLSEnabled: false, TLSCA: "", TLSClientCert: "", TLSClientCertKey: "", Policy: "sync", Registry: "txt", TXTOwnerID: "default", TXTPrefix: "", TXTSuffix: "", TXTCacheInterval: 0, Interval: time.Minute, Once: false, DryRun: false, UpdateEvents: false, LogFormat: "text", MetricsAddress: ":7979", LogLevel: logrus.InfoLevel.String(), ExoscaleEndpoint: "https://api.exoscale.ch/dns", ExoscaleAPIKey: "", ExoscaleAPISecret: "", CRDSourceAPIVersion: "externaldns.k8s.io/v1alpha1", CRDSourceKind: "DNSEndpoint", ServiceTypeFilter: []string{}, CFAPIEndpoint: "", CFUsername: "", CFPassword: "", RFC2136Host: "", RFC2136Port: 0, RFC2136Zone: "", RFC2136Insecure: false, RFC2136TSIGKeyName: "", RFC2136TSIGSecret: "", RFC2136TSIGSecretAlg: "", RFC2136TAXFR: true, RFC2136MinTTL: 0, NS1Endpoint: "", NS1IgnoreSSL: false, TransIPAccountName: "", TransIPPrivateKeyFile: "", DigitalOceanAPIPageSize: 50, } // NewConfig returns new Config object func NewConfig() *Config { return &Config{} } func (cfg *Config) String() string { // prevent logging of sensitive information temp := *cfg t := reflect.TypeOf(temp) for i := 0; i < t.NumField(); i++ { f := t.Field(i) if val, ok := f.Tag.Lookup("secure"); ok && val == "yes" { if f.Type.Kind() != reflect.String { continue } v := reflect.ValueOf(&temp).Elem().Field(i) if v.String() != "" { v.SetString(passwordMask) } } } return fmt.Sprintf("%+v", temp) } // allLogLevelsAsStrings returns all logrus levels as a list of strings func allLogLevelsAsStrings() []string { var levels []string for _, level := range logrus.AllLevels { levels = append(levels, level.String()) } return levels } // ParseFlags adds and parses flags from command line func (cfg *Config) ParseFlags(args []string) error { app := kingpin.New("bigtree-dns", "BigtreeDNS synchronizes exposed Kubernetes Services and Ingresses with DNS \n") app.Version(Version) app.DefaultEnvars() // Flags related to Kubernetes app.Flag("server", "The Kubernetes API server to connect to (default: auto-detect)").Default(defaultConfig.APIServerURL).StringVar(&cfg.APIServerURL) app.Flag("kubeconfig", "Retrieve target cluster configuration from a Kubernetes configuration file (default: auto-detect)").Default(defaultConfig.KubeConfig).StringVar(&cfg.KubeConfig) app.Flag("request-timeout", "Request timeout when calling Kubernetes APIs. 0s means no timeout").Default(defaultConfig.RequestTimeout.String()).DurationVar(&cfg.RequestTimeout) app.Flag("skipper-routegroup-groupversion", "The resource version for skipper routegroup").Default(source.DefaultRoutegroupVersion).StringVar(&cfg.SkipperRouteGroupVersion) // Flags related to processing sources app.Flag("source", "The resource types that are queried for endpoints; specify multiple times for multiple sources (required, options: service, ingress, node, fake)").Required().PlaceHolder("source").EnumsVar(&cfg.Sources, "service", "ingress", "node", "fake") app.Flag("namespace", "Limit sources of endpoints to a specific namespace (default: all namespaces)").Default(defaultConfig.Namespace).StringVar(&cfg.Namespace) app.Flag("annotation-filter", "Filter sources managed by external-dns via annotation using label selector semantics (default: all sources)").Default(defaultConfig.AnnotationFilter).StringVar(&cfg.AnnotationFilter) app.Flag("fqdn-template", "A templated string that's used to generate DNS names from sources that don't define a hostname themselves, or to add a hostname suffix when paired with the fake source (optional). Accepts comma separated list for multiple global FQDN.").Default(defaultConfig.FQDNTemplate).StringVar(&cfg.FQDNTemplate) app.Flag("combine-fqdn-annotation", "Combine FQDN template and Annotations instead of overwriting").BoolVar(&cfg.CombineFQDNAndAnnotation) app.Flag("ignore-hostname-annotation", "Ignore hostname annotation when generating DNS names, valid only when using fqdn-template is set (optional, default: false)").BoolVar(&cfg.IgnoreHostnameAnnotation) app.Flag("compatibility", "Process annotation semantics from legacy implementations (optional, options: mate, molecule)").Default(defaultConfig.Compatibility).EnumVar(&cfg.Compatibility, "", "mate", "molecule") app.Flag("publish-internal-services", "Allow external-dns to publish DNS records for ClusterIP services (optional)").BoolVar(&cfg.PublishInternal) app.Flag("publish-host-ip", "Allow external-dns to publish host-ip for headless services (optional)").BoolVar(&cfg.PublishHostIP) app.Flag("always-publish-not-ready-addresses", "Always publish also not ready addresses for headless services (optional)").BoolVar(&cfg.AlwaysPublishNotReadyAddresses) app.Flag("connector-source-server", "The server to connect for connector source, valid only when using connector source").Default(defaultConfig.ConnectorSourceServer).StringVar(&cfg.ConnectorSourceServer) app.Flag("crd-source-apiversion", "API version of the CRD for crd source, e.g. `externaldns.k8s.io/v1alpha1`, valid only when using crd source").Default(defaultConfig.CRDSourceAPIVersion).StringVar(&cfg.CRDSourceAPIVersion) app.Flag("crd-source-kind", "Kind of the CRD for the crd source in API group and version specified by crd-source-apiversion").Default(defaultConfig.CRDSourceKind).StringVar(&cfg.CRDSourceKind) app.Flag("service-type-filter", "The service types to take care about (default: all, expected: ClusterIP, NodePort, LoadBalancer or ExternalName)").StringsVar(&cfg.ServiceTypeFilter) // Flags related to providers app.Flag("provider", "The DNS provider where the DNS records will be created (required, options: coredns, skydns, inmemory)").Required().PlaceHolder("provider").EnumVar(&cfg.Provider, "coredns", "skydns", "inmemory") app.Flag("domain-filter", "Limit possible target zones by a domain suffix; specify multiple times for multiple domains (optional)").Default("").StringsVar(&cfg.DomainFilter) app.Flag("exclude-domains", "Exclude subdomains (optional)").Default("").StringsVar(&cfg.ExcludeDomains) app.Flag("zone-id-filter", "Filter target zones by hosted zone id; specify multiple times for multiple zones (optional)").Default("").StringsVar(&cfg.ZoneIDFilter) app.Flag("coredns-prefix", "When using the CoreDNS provider, specify the prefix name").Default(defaultConfig.CoreDNSPrefix).StringVar(&cfg.CoreDNSPrefix) app.Flag("inmemory-zone", "Provide a list of pre-configured zones for the inmemory provider; specify multiple times for multiple zones (optional)").Default("").StringsVar(&cfg.InMemoryZones) // Flags related to policies app.Flag("policy", "Modify how DNS records are synchronized between sources and providers (default: sync, options: sync, upsert-only, create-only)").Default(defaultConfig.Policy).EnumVar(&cfg.Policy, "sync", "upsert-only", "create-only") // Flags related to the registry app.Flag("registry", "The registry implementation to use to keep track of DNS record ownership (default: txt, options: txt, noop, aws-sd)").Default(defaultConfig.Registry).EnumVar(&cfg.Registry, "txt", "noop", "aws-sd") app.Flag("txt-owner-id", "When using the TXT registry, a name that identifies this instance of ExternalDNS (default: default)").Default(defaultConfig.TXTOwnerID).StringVar(&cfg.TXTOwnerID) app.Flag("txt-prefix", "When using the TXT registry, a custom string that's prefixed to each ownership DNS record (optional). Mutual exclusive with txt-suffix!").Default(defaultConfig.TXTPrefix).StringVar(&cfg.TXTPrefix) app.Flag("txt-suffix", "When using the TXT registry, a custom string that's suffixed to the host portion of each ownership DNS record (optional). Mutual exclusive with txt-prefix!").Default(defaultConfig.TXTSuffix).StringVar(&cfg.TXTSuffix) // Flags related to the main control loop app.Flag("txt-cache-interval", "The interval between cache synchronizations in duration format (default: disabled)").Default(defaultConfig.TXTCacheInterval.String()).DurationVar(&cfg.TXTCacheInterval) app.Flag("interval", "The interval between two consecutive synchronizations in duration format (default: 1m)").Default(defaultConfig.Interval.String()).DurationVar(&cfg.Interval) app.Flag("once", "When enabled, exits the synchronization loop after the first iteration (default: disabled)").BoolVar(&cfg.Once) app.Flag("dry-run", "When enabled, prints DNS record changes rather than actually performing them (default: disabled)").BoolVar(&cfg.DryRun) app.Flag("events", "When enabled, in addition to running every interval, the reconciliation loop will get triggered when supported sources change (default: disabled)").BoolVar(&cfg.UpdateEvents) // Miscellaneous flags app.Flag("log-format", "The format in which log messages are printed (default: text, options: text, json)").Default(defaultConfig.LogFormat).EnumVar(&cfg.LogFormat, "text", "json") app.Flag("metrics-address", "Specify where to serve the metrics and health check endpoint (default: :7979)").Default(defaultConfig.MetricsAddress).StringVar(&cfg.MetricsAddress) app.Flag("log-level", "Set the level of logging. (default: info, options: panic, debug, info, warning, error, fatal").Default(defaultConfig.LogLevel).EnumVar(&cfg.LogLevel, allLogLevelsAsStrings()...) _, err := app.Parse(args) if err != nil { return err } return nil }
c3c31ba60a255392c7b63728e580563816c44416
[ "Go" ]
1
Go
yangkailc/bigtree-dns
68a8344d7be39e8ed3d427467893f7ccd35a4406
cbe6c348a2c4fd5347394d46235e1775c37a6426
refs/heads/master
<file_sep>apply plugin: 'java' apply plugin: 'scala' apply plugin: 'eclipse' apply plugin: 'application' repositories { mavenCentral() } dependencies { compile 'org.scala-lang:scala-library:2.10.4' } tasks.withType(ScalaCompile) { scalaCompileOptions.useAnt = false } dependencies { compile group: 'com.typesafe.akka', name: 'akka-actor_2.10', version: '2.3.9' compile group: 'org.scala-lang', name: 'scala-library', version: '2.10.4' testCompile "junit:junit:4.11" } task executeMain(dependsOn:'build', type:JavaExec) { main = 'org.vramachandran.akkademo.helloworld.main.Main' classpath = sourceSets.main.runtimeClasspath } <file_sep>package org.vramachandran.akkademo.helloworld.actor; import org.vramachandran.akkademo.helloworld.model.Message; import akka.actor.UntypedActor; public class HelloWorldActor extends UntypedActor { private void handleMessage(final Message message) throws Exception { final String outputMessage = String.format("Hello world! Look what I got: %s!", message); System.out.println(outputMessage); } /** * (non-Javadoc) * @see akka.actor.UntypedActor#onReceive(java.lang.Object) */ @Override public void onReceive(Object message) throws Exception { if (message instanceof Message) { handleMessage((Message) message); } else { unhandled(message); } } } <file_sep># Akka Demo This package contains examples of working with the Akka framework in Java as a means to understand and become familiarized with the framework. The actual example scenarios created in this package are described below. All code is built with Gradle. ## Hello World A simple setup getting a "Hello World" message creating an Akka application and getting it running. <file_sep>apply plugin: 'java' apply plugin: 'scala' repositories { mavenCentral() } dependencies { compile 'org.scala-lang:scala-library:2.10.4' } tasks.withType(ScalaCompile) { scalaCompileOptions.useAnt = false } dependencies { compile group: 'com.typesafe.akka', name: 'akka-actor_2.10', version: '2.3.9' compile group: 'org.scala-lang', name: 'scala-library', version: '2.10.4' testCompile "junit:junit:4.11" }
d1fbf4f953119207323f2b3a6629d0e1c0424171
[ "Markdown", "Java", "Gradle" ]
4
Gradle
v-ramachandran/akka-demo
ecc2688e97275e6db2c93e0d5d50657b52eb62da
d72b878a844d2794c4f2b291fa286f81053e7e62
refs/heads/master
<file_sep>angular.module('zulip').service('ConnectionService', ['$http', '$rootScope', 'serverConfig', 'Base64', function($http, $rootScope, serverConfig, Base64) { var self = this; this.login = function(email, password, remember) { $http.post('v1/fetch_api_key', { username: email, password: <PASSWORD> }) .success(function(data) { if (data.result === 'success') { if (remember) { localStorage.setItem('username', email); localStorage.setItem('password', <PASSWORD>); } console.log(data); $rootScope.user.api_key = data['api_key']; $rootScope.user.email = data['email']; $rootScope.user.username = email; $rootScope.isAuth = true; self.registerCommand(); } }) .error(function(data, status) { console.log(status); console.log(data); }); }; this.registerCommand = function() { if (!$rootScope.isAuth) { return; } var authdata = Base64.encode($rootScope.user.email + ':' + $rootScope.user.api_key); $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; $http.post('v1/register') .success(function(data){ console.log(data); }); } }]); <file_sep>angular.module('zulip').controller('LoginController', ['$rootScope', '$scope', 'ConnectionService', function($rootScope, $scope, ConnectionService) { $rootScope.$broadcast('page-change', { title: 'Вход' }); $scope.user = { email: '', password: '', remember: true }; $scope.login = function() { ConnectionService.login($scope.user.email, $scope.user.password, $scope.user.remember); } }]); <file_sep>app.factory('HttpInspector', ['$rootScope', 'serverConfig', function($rootScope, serverConfig){ return { request: function(config){ $('#loading-progress').show(); if (config.method === 'POST') { config.url = serverConfig.serverURI + config.url; } return config; }, response: function(response){ $('#loading-progress').hide(); return response; }, requestError: function(data){ //$mdToast.show($mdToast.simple().textContent('Произошла ошибка при запросе')); $('#loading-progress').hide(); return data; }, responseError: function(data){ $('#loading-progress').hide(); return data; } }; }]);<file_sep>app.constant('serverConfig',{ serverURI: 'https://zulip.beget.ru/api/' }); <file_sep>angular.module('zulip').controller('ToolbarController',['$scope', '$mdSidenav', '$rootScope', function($scope, $mdSidenav, $rootScope) { $scope.title = 'Zulip'; $scope.toggleRight = function() { $mdSidenav('left').toggle(); }; $scope.$on('page-change', function(event, params) { $scope.title = params.title; }); }]);
0fc69f68cac30f030ac13810cedeba5ef76200ff
[ "JavaScript" ]
5
JavaScript
goodwin331/Zulip-angular
bf54fd604d686493540e7161333ac6a4ba4e57ee
eea640e546a61e16757a155ecc0de22e3accb449
refs/heads/master
<file_sep>const mongoose = require('mongoose'); const express = require('express'); const Conversation = require('../models/conversation'); var app = express(); app.use(express.json()); app.post('/', function(req, res){ let conversation = new Conversation({ _id: new mongoose.Types.ObjectId, from: req.body.from, message: req.body.message, to: req.body.to }) conversation .save() .then(function(response){ console.log(response); res.status(200).json({ response }) }) .catch(function(error){ console.log(error); res.status(500).json({ error }) }) }) app.get('/:conversationId', function(req, res){ Conversation.findById({ _id: req.params.conversationId }).then(function(response){ res.status(200).json({ response: response }) }).catch(function(error){ res.status(500).json({ err: error }) }); }) app.get('/:userId',function(req, res){ let userId = req.params.userId; Conversation.find().then(function(response){ res.status(200).json({ response }) }).catch(function(err){ res.status(500).json({ err }) }) }) app.get('/findFriends/:userId', function(req, res){ let userId = req.params.userId; Conversation .find({from: userId}) .populate('to') .sort({added_date: -1}) .select('-_id -from') .exec() .then(function(response){ let set = new Set(); let result = []; response.forEach(function(data){ let to = JSON.stringify(data.to); console.log(typeof to); if(!set.has(to)){ set.add(to); result.push(data); } }) console.log(result); res.status(200).json({ result }); }).catch(function(err){ res.status(500).json({err}); }) }) app.get('/:sourceId/:destinationId', function(req, res){ let sourceId = req.params.sourceId; let destinationId = req.params.destinationId; console.log(sourceId + " " + destinationId); Conversation .find({ $or: [ { from: sourceId, to: destinationId }, { from: destinationId, to: sourceId } ] }) .exec() .then(function(response){ console.log() res.status(200).json({ response }) }) .catch(function(err){ res.send(500).json({ err }) }) }) module.exports = app; <file_sep>require('dotenv').config(); const express = require('express'); const app = express(); const mongoose = require('mongoose'); const userRoute = require('./server-side/src/routes/user'); const conversationRoute = require('./server-side/src/routes/conversation'); const friendlistRoute = require('./server-side/src/routes/friendlist'); app.use('/user', userRoute); app.use('/conversation', conversationRoute); app.use('/friendlist', friendlistRoute); app.get('/', function(req, res){ res.send('HEllow World'); }) mongoose .connect('mongodb+srv://subarsh:' + process.env.MONGO_ATLAS_PWD + '@chat-db-sefmf.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true }) .catch(function(err){ console.log(err); }) app.listen(process.env.PORT, function(){ console.log(`Listening on 127.0.0.1:${process.env.PORT}`); })
2604ee67f78cd6896644032ef841c8cd28c1e156
[ "JavaScript" ]
2
JavaScript
Subarsh/JWTAuth
a76f5dbbedc51718f525c7d3e3b633790013ccd3
b14c6880d59e849799e3a61f8cfe17e7c1ffc03d
refs/heads/master
<repo_name>FraMecca/urllib<file_sep>/README.md urllib ==== Web URL handling for D Motivation ---------- [dhasenan's url library](https://github.com/dhasenan/urld) is great but I needed something more specific for web urls. In particular, this library handles subdomains and tld. Also, no implicit conversion to strings. Usage ----- Parse a URL: ```D auto url = "ircs://irc.freenode.com/#d".parseURL; ``` Construct one from scratch, laboriously: ```D URL url; with (url) { scheme = "soap.beep"; host = "example"; tld = "org"; subdomain = "beep"; port = 1772; path = "/serverinfo/info"; queryParams.add("token", "<PASSWORD>"); } curl.get(url.toString); ``` Unicode domain names: ```D auto url = "http://☃.com/".parseURL; writeln(url.toString); // http://xn--n3h.com/ writeln(url.toHumanReadableString); // http://☃.com/ ``` Autodetect ports: ```D assert(parseURL("http://example.org").port == 80); assert(parseURL("http://example.org:5326").port == 5326); ``` URLs of maximum complexity: ```D auto url = parseURL("redis://admin:password@redisbox.local:2201/path?query=value#fragment"); assert(url.scheme == "redis"); assert(url.user == "admin"); assert(url.pass == "<PASSWORD>"); // etc ``` URLs of minimum complexity: ```D assert(parseURL("example.org").toString == "http://example.org/"); ``` Canonicalization: ```D assert(parseURL("http://example.org:80").toString == "http://example.org/"); ``` <file_sep>/generate_tld_dat.bash #!/bin/bash echo 'enum byte[string] tlds = [' > source/tlds.d curl https://raw.githubusercontent.com/pauldix/domainatrix/master/lib/effective_tld_names.dat \ | sed 's/\/\/.*//g' | sed '/^$/d' | sed 's/\!//g'| sed 's/\*\.//g' | \ sed 's/^/"/g' | sed 's/$/":0,/g' >> source/tlds.d echo '];' >> source/tlds.d
68f68a70fcc57e85971f3401e9f5108d512bdcf2
[ "Markdown", "Shell" ]
2
Markdown
FraMecca/urllib
85e8f92598b13878d9a1bf961150a5b26ae71551
09e18213671b48e406ac579330fdf5a31fc95f44
refs/heads/master
<repo_name>crosspant/shell_yin<file_sep>/logrota.sh #! /bin/bash cd /var/log/rsyslog/httpd find -mtime +90 -delete find -mtime -89 -mmin +360 -name "*_log" -exec gzip {} \; <file_sep>/check-ping.sh #!/bin/bash # Updated 20180723 # Shrew IKE VPN Connection Check file date >> /var/log/ping-check.log PING=`ping -c 1 -i 1 192.168.1.1|tee -a /var/log/ping-check.log |grep "100% packet loss"` CHECK=`tail -1 /var/log/shrew-check.log|grep OK` CHECKRT=`tail -1 /var/log/shrew-check.log|grep Reconnect` if [ -z "$PING" ] ; then # if [ -z "$CHECK" ]; then if [ -n "$CHECKRT" ]; then /usr/sbin/sendmail -t -i '-<EMAIL>' < /root/recover.txt fi echo "[Ping OK] : "`date` >> /var/log/shrew-check.log 2>&1 else if [ -n "$CHECK" ]; then /usr/sbin/sendmail -t -i '-<EMAIL>' < /root/alert.txt fi echo "[Ping NG] : "`date` >> /var/log/shrew-check.log 2>&1 echo "Challenge Reconnect" >> /var/log/shrew-check.log 2>&1 service shrew-connect stop service iked stop sleep 3 service iked start service shrew-connect start fi <file_sep>/nslookup.sh #! /bin/bash # nslookupコマンドを実行し、IPアドレス表示 nslookup www.yahoo.co.jp |grep "Address" |grep -v "#53" |cut -d" " -f2 |sort <file_sep>/ssl_chk.sh #! /bin/bash UserParameter=ssl_chk[*],/usr/lib/zabbix/externalscripts/ssl_check.sh $1 SSL_LIMIT=`openssl s_client -connect $1:443 2>&1 < /dev/null |openssl x509 -enddate | grep ^notAfter | cut -c 10-33` expr \( `date -d "$SSL_LIMIT" +%s` - `date +%s` \)
82f62974764bb8be03951b881d8b45a917522b81
[ "Shell" ]
4
Shell
crosspant/shell_yin
6c716188f02d3f0ad7649d8d5e65d657b3a27a4c
c503e36eb6666d0d152fd4a32a2c73a92643e04a
refs/heads/master
<repo_name>zclyne/Goblog<file_sep>/main.go package main import "goblog/router" func main() { router.InitRouter() } <file_sep>/model/page_options.go package model import ( "strconv" ) type PageOptions struct { Offset int `json:"offset"` Limit int `json:"limit"` } func ParsePageOptions(limitStr string, offsetStr string, defaultLimit int, defaultOffset int) PageOptions { pageOptions := PageOptions{} if offsetStr == "" { pageOptions.Offset = defaultOffset } else { offset, err := strconv.Atoi(offsetStr) if err != nil { panic(err) } pageOptions.Offset = offset } if limitStr == "" { pageOptions.Limit = defaultLimit } else { limit, err := strconv.Atoi(limitStr) if err != nil { panic(err) } pageOptions.Limit = limit } return pageOptions } <file_sep>/model/user.go package model import ( "time" "github.com/google/uuid" "github.com/jinzhu/gorm" ) type User struct { UserId string `json:"user_id" gorm:"column:user_id;type:varchar(50);PRIMARY_KEY"` Username string `json:"username" gorm:"column:username;type:varchar(50)"` Password string `json:"<PASSWORD>" gorm:"column:password;type:varchar(50)"` Email string `json:"email" gorm:"column:email;type:varchar(50)"` AvatarUrl string `json:"avatar_url" gorm:"column:avatar_url;type:varchar(1000)"` // type 1 for admin and 2 for normal user Type int `json:"type" gorm:"column:type;type:tinyint"` CreateAt time.Time `json:"create_at" gorm:"column:create_at;type:timestamp"` UpdateAt time.Time `json:"update_at" gorm:"column:update_at;type:timestamp"` } func (User) TableName() string { return "user" } func (user *User) BeforeCreate(scope *gorm.Scope) error { user.UserId = uuid.New().String() user.CreateAt = time.Now() user.UpdateAt = time.Now() // TODO: encrypt the password return nil } <file_sep>/service/blog_service.go package service import ( "goblog/model" "log" "github.com/google/uuid" ) func ListBlogs(pageOptions model.PageOptions) []model.Blog { limit, offset := pageOptions.Limit, pageOptions.Offset var blogs []model.Blog db.Limit(limit).Offset(offset).Order("create_at desc").Find(&blogs) return blogs } func GetBlogsCount() int { var count int db.Model(&model.Blog{}).Count(&count) return count } func ListBlogsByTypeId(pageOptions model.PageOptions, typeId string) []model.Blog { limit, offset := pageOptions.Limit, pageOptions.Offset var blogs []model.Blog db.Limit(limit).Offset(offset).Where("type_id = ?", typeId).Find(&blogs) return blogs } func ListBlogsByTagId(pageOptions model.PageOptions, tagId string) []model.Blog { limit, offset := pageOptions.Limit, pageOptions.Offset var blogs []model.Blog rows, err := db.Table("blog_tag").Limit(limit).Offset(offset).Where("tag_id = ?", tagId).Select("blog_id").Rows() if err != nil { log.Printf("error occurred while listing blogs by tag id, err is %s\n", err) } for rows.Next() { var blogId string rows.Scan(&blogId) blog := GetBlogById(blogId) blogs = append(blogs, blog) } return blogs } func GetBlogById(blogId string) model.Blog { blog := model.Blog{} db.Where("blog_id = ?", blogId).First(&blog) return blog } func CreateBlog(blog *model.Blog) { db.Create(blog) } func UpdateBlog(blog *model.Blog) error { if err := db.Save(blog).Error; err != nil { log.Printf("error occurred while updating blog: %s\n", err) return err } return nil } func DeleteBlog(blogId string) error { db.Exec("DELETE FROM blog_tag where blog_id = ?", blogId) if err := db.Where("blog_id = ?", blogId).Delete(model.Blog{}).Error; err != nil { log.Printf("error occurred while deleting blog err is: %s\n", err) return err } // TODO: delete association between this blog and the tags db.Exec("DELETE FROM blog_tag WHERE blog_id = ?", blogId) return nil } func SaveAssociationBetweenBlogAndTags(blogId string, tags []model.Tag) { oldTags := ListTagsByBlogId(blogId) newTagIds := make(map[string]bool) for _, tag := range tags { newTagIds[tag.TagId] = true } for _, oldTag := range oldTags { oldTagId := oldTag.TagId if !newTagIds[oldTagId] { // the tag is removed db.Exec("DELETE FROM blog_tag where tag_id = ?", oldTagId) } else { // the tag is still attached to the blog, remove it from newTagIds delete(newTagIds, oldTagId) } } for newTagId := range newTagIds { id := uuid.New().String() db.Exec("INSERT INTO blog_tag(id, blog_id, tag_id) VALUES(?, ?, ?)", id, blogId, newTagId) } } func ListBlogsGroupedByYear() map[string][]model.Blog { blogsGroupedByYear := make(map[string][]model.Blog) // list all the years rows, err := db.Raw("SELECT DISTINCT YEAR(create_at) FROM blog").Rows() if err != nil { log.Printf("error occurred while listing years of blogs, err is %s\n", err) return nil } var years []string for rows.Next() { var year string rows.Scan(&year) years = append(years, year) } // select blogs by year for _, year := range years { var blogsOfThisYear []model.Blog db.Where("YEAR(create_at) = ?", year).Find(&blogsOfThisYear) blogsGroupedByYear[year] = blogsOfThisYear } return blogsGroupedByYear } <file_sep>/model/blog.go package model import ( "time" "github.com/google/uuid" "github.com/jinzhu/gorm" ) type Blog struct { BlogId string `json:"blog_id" gorm:"column:blog_id;type:varchar(50);PRIMARY_KEY"` Title string `json:"title" gorm:"column:title;type:varchar(50)"` Content string `json:"content" gorm:"column:content;type:varchar(20000)"` ImageUrl string `json:"image_url" gorm:"column:image_url;type:varchar(1000)"` Published bool `json:"published" gorm:"column:published;type:boolean"` TypeId string `json:"type_id" gorm:"column:type_id;type:varchar(50);"` CreateAt time.Time `json:"create_at" gorm:"column:create_at;type:timestamp"` UpdateAt time.Time `json:"update_at" gorm:"column:update_at;type:timestamp"` } func (Blog) TableName() string { return "blog" } func (blog *Blog) BeforeCreate(scope *gorm.Scope) error { blog.BlogId = uuid.New().String() blog.CreateAt = time.Now() blog.UpdateAt = time.Now() return nil } <file_sep>/model_view/blog_view.go package model_view import "goblog/model" // BlogView parses a create or update blog request // it consists of a blog and a list of tags type BlogView struct { Blog model.Blog `json:"blog"` Type model.Type `json:"type"` Tags []model.Tag `json:"tags"` }<file_sep>/model/comment.go package model import ( "github.com/google/uuid" "github.com/jinzhu/gorm" "time" ) type Comment struct { CommentId string `json:"comment_id" gorm:"column:comment_id;type:varchar(50);PRIMARY_KEY"` Nickname string `json:"nickname" gorm:"column:nickname;type:varchar(50)"` Email string `json:"email" gorm:"column:email;type:varchar(50)"` BlogId string `json:"blog_id" gorm:"column:blog_id;type:varchar(50)"` Content string `json:"content" gorm:"column:content;type:varchar(2000)"` AvatarUrl string `json:"avatar_url" gorm:"column:avatar_url;type:varchar(1000)"` CreateAt time.Time `json:"create_at" gorm:"column:create_at;type:timestamp"` } func (Comment) TableName() string { return "comment" } func (c *Comment) BeforeCreate(scope *gorm.Scope) error { c.CommentId = uuid.New().String() c.CreateAt = time.Now() return nil }<file_sep>/router/type_router.go package router import ( "goblog/model" "goblog/service" "log" "net/http" "github.com/gin-gonic/gin" ) func ListTypes(c *gin.Context) { types := service.ListTypes() c.JSON(http.StatusOK, types) } func GetType(c *gin.Context) { typeId := c.Param("type_id") blogType := service.GetTypeById(typeId) c.JSON(http.StatusOK, blogType) } func CreateType(c *gin.Context) { t := model.Type{} if err := c.ShouldBind(&t); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing type, please check the input again") } service.CreateType(&t) c.JSON(http.StatusCreated, nil) } func DeleteType(c *gin.Context) { typeId := c.Param("type_id") if err := service.DeleteType(typeId); err != nil { c.JSON(http.StatusBadRequest, err) } c.JSON(http.StatusAccepted, nil) } func UpdateType(c *gin.Context) { t := model.Type{} if err := c.ShouldBind(&t); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing type, please check the input again") } if err := service.UpdateType(&t); err != nil { c.JSON(http.StatusBadRequest, err) } c.JSON(http.StatusAccepted, nil) } <file_sep>/frontend/goblog-frontend/src/store/user/mutations.js export function saveUserToken (state, userToken) { state.userToken = userToken } export function deleteUserToken (state) { state.userToken = '' } <file_sep>/router/user_router.go package router import ( "goblog/model" "goblog/service" "log" "net/http" "github.com/gin-gonic/gin" ) func UserRegister(c *gin.Context) { user := model.User{} if err := c.ShouldBind(&user); err != nil { log.Printf("Error parsing the request body to model.User, err is %s\n", err) c.JSON(http.StatusNotAcceptable, map[string]string{ "msg": "There is some error with the uploaded request body, please check the input again", }) } service.Register(&user) } <file_sep>/frontend/goblog-frontend/src/router/routes.js import MainLayout from 'layouts/MainLayout' import AdminLayout from 'layouts/AdminLayout' import Index from 'pages/Index' import Blogs from 'pages/blog/Blogs' import BlogDetail from 'pages/blog/BlogDetail' import Types from 'pages/Types' import Tags from 'pages/Tags' import About from 'pages/About' import Archives from 'pages/Archives' import BlogsAdmin from 'pages/admin/BlogsAdmin' import BlogEdit from 'pages/admin/BlogEdit' import TypesAdmin from 'pages/admin/TypesAdmin' import TagsAdmin from 'pages/admin/TagsAdmin' import Login from 'pages/admin/Login' const routes = [ { path: '/admin', component: AdminLayout, children: [ { path: '/admin/blogs', name: 'BlogsAdmin', component: BlogsAdmin }, { path: '/admin/blogs/edit', component: BlogEdit }, { path: '/admin/blogs/edit/:blog_id', component: BlogEdit }, { path: '/admin/types', component: TypesAdmin }, { path: '/admin/tags', component: TagsAdmin } ] }, { path: '/', component: MainLayout, children: [{ path: '/', component: Index }, { path: '/blogs', component: Blogs }, { path: '/blogs/:blog_id', component: BlogDetail }, { path: '/types', component: Types }, { path: '/tags', component: Tags }, { path: '/about', component: About }, { path: '/archives', component: Archives }, { path: '/login', component: Login } ] }, // Always leave this as last one, // but you can also remove it { path: '*', component: () => import('pages/Error404.vue') } ] export default routes <file_sep>/router/comment_router.go package router import ( "github.com/gin-gonic/gin" "goblog/model" "goblog/service" "net/http" ) func ListCommentsByBlogId(c *gin.Context) { blogId := c.Query("blog_id") comments := service.ListCommentsByBlogId(blogId) c.JSON(http.StatusOK, comments) } func CreateComment(c *gin.Context) { comment := model.Comment{} if err := c.ShouldBind(&comment); err != nil { c.JSON(http.StatusBadRequest, err) } service.CreateComment(comment) } func DeleteComment(c *gin.Context) { commentId := c.Param("comment_id") service.DeleteCommentById(commentId) c.JSON(http.StatusAccepted, nil) }<file_sep>/config/config.go package config import ( "io/ioutil" "github.com/prometheus/common/log" "gopkg.in/yaml.v2" ) type Config struct { Port string `yaml:"port"` Mysql struct { Host string `yaml:"host"` Port string `yaml:"port"` Username string `yaml:"username"` Password string `yaml:"<PASSWORD>"` DatabaseName string `yaml:"dbname"` } } var Configuration Config func init() { configBytes, err := ioutil.ReadFile("config/conf.yaml") if err != nil { panic(err) } err = yaml.Unmarshal(configBytes, &Configuration) if err != nil { panic(err) } log.Infof("Successfully parsed config: %+v\n", Configuration) } <file_sep>/router/blog_router.go package router import ( "goblog/model" "goblog/model_view" "goblog/service" "log" "net/http" "github.com/gin-gonic/gin" ) func ListBlogs(c *gin.Context) { // offset and limit are in "offset=5&limit=15" form, so we should use Query instead of Param here offsetStr := c.Query("offset") limitStr := c.Query("limit") typeId := c.Query("type_id") tagId := c.Query("tag_id") pageOptions := model.ParsePageOptions(offsetStr, limitStr, 10, 0) code := http.StatusOK var blogs []model.Blog if typeId != "" { blogs = service.ListBlogsByTypeId(pageOptions, typeId) } else if tagId != "" { blogs = service.ListBlogsByTagId(pageOptions, tagId) } else { blogs = service.ListBlogs(pageOptions) } var blogsView []model_view.BlogView for _, blog := range blogs { blogType := service.GetTypeById(blog.TypeId) tags := service.ListTagsByBlogId(blog.BlogId) blogsView = append(blogsView, model_view.BlogView{ Blog: blog, Type: blogType, Tags: tags, }) } c.JSON(code, blogsView) } func GetBlog(c *gin.Context) { code := http.StatusOK blogId := c.Param("blog_id") blog := service.GetBlogById(blogId) blogType := service.GetTypeById(blog.TypeId) tags := service.ListTagsByBlogId(blogId) blogView := model_view.BlogView{ Blog: blog, Type: blogType, Tags: tags, } c.JSON(code, blogView) } func GetBlogsCount(c *gin.Context) { count := service.GetBlogsCount() c.JSON(http.StatusOK, count) } func CreateBlog(c *gin.Context) { blogView := model_view.BlogView{} if err := c.ShouldBind(&blogView); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing blogView, please check the input again") } service.CreateBlog(&blogView.Blog) service.SaveAssociationBetweenBlogAndTags(blogView.Blog.BlogId, blogView.Tags) c.JSON(http.StatusCreated, nil) } func UpdateBlog(c *gin.Context) { blogView := model_view.BlogView{} if err := c.ShouldBind(&blogView); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing blogView, please check the input again") } if err := service.UpdateBlog(&blogView.Blog); err != nil { c.JSON(http.StatusBadRequest, err) } service.SaveAssociationBetweenBlogAndTags(blogView.Blog.BlogId, blogView.Tags) c.JSON(http.StatusAccepted, nil) } func DeleteBlog(c *gin.Context) { blogId := c.Param("blog_id") if err := service.DeleteBlog(blogId); err != nil { c.JSON(http.StatusBadRequest, err) } c.JSON(http.StatusAccepted, nil) } func ListBlogsGroupedByYear(c *gin.Context) { blogsGroupedByYear := service.ListBlogsGroupedByYear() blogsViewGroupedByYear := make(map[string][]model_view.BlogView) for year, blogs := range blogsGroupedByYear { var blogsView []model_view.BlogView for _, blog := range blogs { blogType := service.GetTypeById(blog.TypeId) tags := service.ListTagsByBlogId(blog.BlogId) blogsView = append(blogsView, model_view.BlogView{ Blog: blog, Type: blogType, Tags: tags, }) } blogsViewGroupedByYear[year] = blogsView } c.JSON(http.StatusOK, blogsViewGroupedByYear) } <file_sep>/frontend/goblog-frontend/src/store/user/state.js export default function () { return { userToken: '' } } <file_sep>/service/tag_service.go package service import ( "goblog/model" "log" ) func ListTags() []model.Tag { var tags []model.Tag db.Find(&tags) return tags } func GetTagById(tagId string) model.Tag { var tag model.Tag db.Where("tag_id = ?", tagId).First(&tag) return tag } func ListTagsByBlogId(blogId string) []model.Tag { var tags []model.Tag rows, err := db.Table("blog_tag").Where("blog_id = ?", blogId).Select("tag_id").Rows() if err != nil { log.Printf("error occurred while listing tags by blog id, err is: %s\n", err) return nil } for rows.Next() { var tagId string rows.Scan(&tagId) tag := GetTagById(tagId) tags = append(tags, tag) } return tags } func CreateTag(t *model.Tag) { db.Create(t) } func DeleteTag(tagId string) error { if err := db.Where("tag_id = ?", tagId).Delete(model.Tag{}).Error; err != nil { log.Printf("error occurred while deleting tag, err is: %s\n", err) return err } return nil } func UpdateTag(t *model.Tag) error { if err := db.Save(t).Error; err != nil { log.Printf("error occurred while updating tag: %s\n", err) return err } return nil } <file_sep>/router/tag_router.go package router import ( "goblog/model" "goblog/service" "log" "net/http" "github.com/gin-gonic/gin" ) func ListTags(c *gin.Context) { tags := service.ListTags() c.JSON(http.StatusOK, tags) } func CreateTag(c *gin.Context) { t := model.Tag{} if err := c.ShouldBind(&t); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing tag, please check the input again") } service.CreateTag(&t) c.JSON(http.StatusCreated, nil) } func DeleteTag(c *gin.Context) { tagId := c.Param("tag_id") if err := service.DeleteTag(tagId); err != nil { c.JSON(http.StatusBadRequest, err) } c.JSON(http.StatusAccepted, nil) } func UpdateTag(c *gin.Context) { t := model.Tag{} if err := c.ShouldBind(&t); err != nil { log.Println(err) c.JSON(http.StatusBadRequest, "error occurred while parsing tag, please check the input again") } if err := service.UpdateTag(&t); err != nil { c.JSON(http.StatusBadRequest, err) } c.JSON(http.StatusAccepted, nil) } <file_sep>/service/db.go package service import ( "fmt" "goblog/config" "log" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) var db *gorm.DB func init() { host := config.Configuration.Mysql.Host port := config.Configuration.Mysql.Port username := config.Configuration.Mysql.Username password := config.Configuration.Mysql.Password databaseName := config.Configuration.Mysql.DatabaseName // must declare err here and use db, err = // instead of db, err := , because golang will treat db as a local variable, not the global one var err error db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, databaseName)) if err != nil { log.Fatal(2, "Failed to open mysql database connection", err) } db.DB().SetMaxIdleConns(10) db.DB().SetMaxOpenConns(100) // defer db.Close() } <file_sep>/router/router.go package router import ( "fmt" "goblog/config" "goblog/model" "goblog/service" "log" "net/http" "time" jwt "github.com/appleboy/gin-jwt/v2" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) type loginForm struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"<PASSWORD>" json:"password" binding:"required"` } const identityKey = "id" func InitRouter() { r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) // configure CORS r.Use(cors.Default()) apis := r.Group("/api") // create jwt middleware authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{ Realm: "test zone", Key: []byte("secret key"), Timeout: 2 * time.Hour, MaxRefresh: time.Hour, IdentityKey: identityKey, PayloadFunc: func(data interface{}) jwt.MapClaims { fmt.Printf("PayloadFunc, data: %+v\n", data) if v, ok := data.(*model.User); ok { return jwt.MapClaims{ identityKey: v.Username, "type": v.Type, "email": v.Email, } } return jwt.MapClaims{} }, IdentityHandler: func(c *gin.Context) interface{} { claims := jwt.ExtractClaims(c) fmt.Printf("IdentityHandler, claims: %+v\n", claims) return &model.User{ Username: claims[identityKey].(string), // when directly retrieve from claims, claims["type"] is a float64, so we must cast it into int // this might be a problem of json unmarshalling Type: int(claims["type"].(float64)), Email: claims["email"].(string), } }, Authenticator: func(c *gin.Context) (interface{}, error) { var loginVals loginForm if err := c.ShouldBind(&loginVals); err != nil { return "", jwt.ErrMissingLoginValues } username := loginVals.Username password := loginVals.Password if user := service.Login(username, password); user.UserId != "" { fmt.Printf("Authenticator: %+v\n", user) return &user, nil } return nil, jwt.ErrFailedAuthentication }, Authorizator: func(data interface{}, c *gin.Context) bool { v, ok := data.(*model.User) fmt.Printf("Authorizator: %+v\n", v) if ok && v.Type == 1 { return true } return false }, Unauthorized: func(c *gin.Context, code int, message string) { c.JSON(code, gin.H{ "code": code, "message": message, }) }, }) if err != nil { log.Fatal("JWT Error:" + err.Error()) } // user api apis.POST("/user/login", authMiddleware.LoginHandler) apis.GET("/user/refresh_token", authMiddleware.RefreshHandler) apis.POST("/user/logout", authMiddleware.LogoutHandler) apis.POST("/user/register", UserRegister) // authMiddlware only takes effect on the routers added after the authMiddlware is set // apis.Use(authMiddleware.MiddlewareFunc()) // blogs api apis.GET("/blogs", ListBlogs) apis.POST("/blogs", CreateBlog) apis.PUT("/blogs", UpdateBlog) apis.GET("/blogs/:blog_id", GetBlog) apis.DELETE("/blogs/:blog_id", DeleteBlog) apis.GET("/blogs-count", GetBlogsCount) apis.GET("blogs-archive", ListBlogsGroupedByYear) // types api apis.GET("/types", ListTypes) apis.GET("/types/:type_id", GetType) apis.POST("/types", CreateType) apis.DELETE("/types/:type_id", DeleteType) apis.PUT("/types", UpdateType) // tags api apis.GET("/tags", ListTags) apis.POST("/tags", CreateTag) apis.DELETE("/tags/:tag_id", DeleteTag) apis.PUT("/tags", UpdateTag) // comments api apis.GET("/comments", ListCommentsByBlogId) apis.POST("/comments", CreateComment) apis.DELETE("/comments/:comment_id", DeleteComment) r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "code": "CONTENT_NOT_FOUND", "message": "Content not found", }) }) r.Run(":" + config.Configuration.Port) } <file_sep>/service/user_service.go package service import "goblog/model" func Login(username, password string) model.User { user := model.User{} db.Where("username = ? AND password = ?", username, password).First(&user) return user } func Register(user *model.User) { db.Create(&user) } <file_sep>/go.mod module goblog go 1.13 require ( github.com/appleboy/gin-jwt/v2 v2.6.4 github.com/gin-contrib/cors v1.3.1 github.com/gin-gonic/gin v1.6.3 github.com/google/uuid v1.1.1 github.com/jinzhu/gorm v1.9.16 github.com/prometheus/common v0.12.0 gopkg.in/yaml.v2 v2.3.0 ) <file_sep>/service/comment_service.go package service import ( "goblog/model" "log" ) func ListCommentsByBlogId(blogId string) []model.Comment { var comments []model.Comment db.Where("blog_id = ?", blogId).Order("create_at desc").Find(&comments) return comments } func CreateComment(comment model.Comment) { db.Create(&comment) } func DeleteCommentById(commentId string) error { if err := db.Where("comment_id = ?", commentId).Delete(model.Comment{}).Error; err != nil { log.Printf("error occurred while deleting comment, err is: %s\n", err) return err } return nil } <file_sep>/model/tag.go package model import ( "github.com/google/uuid" "github.com/jinzhu/gorm" ) type Tag struct { TagId string `json:"tag_id" gorm:"column:tag_id;type:varchar(50);PRIMARY_KEY"` Name string `json:"name" gorm:"column:name;type:varchar(50)"` } func (t *Tag) BeforeCreate(scope *gorm.Scope) error { t.TagId = uuid.New().String() return nil } func (Tag) TableName() string { return "tag" } <file_sep>/service/type_service.go package service import ( "goblog/model" "log" ) func ListTypes() []model.Type { var types []model.Type db.Find(&types) return types } func GetTypeById(typeId string) model.Type { var blogType model.Type db.Where("type_id = ?", typeId).First(&blogType) return blogType } func CreateType(t *model.Type) { db.Create(t) } func DeleteType(typeId string) error { if err := db.Where("type_id = ?", typeId).Delete(model.Type{}).Error; err != nil { log.Printf("error occurred while deleting type: %s\n", err) return err } return nil } func UpdateType(t *model.Type) error { if err := db.Save(t).Error; err != nil { log.Printf("error occurred while updating type: %s\n", err) return err } return nil } <file_sep>/frontend/goblog-frontend/src/constants/const.js const MESSAGE_BOX_COLOR_PRIMARY = 'bg-primary' const MESSAGE_BOX_COLOR_POSITIVE = 'bg-positive' const MESSAGE_BOX_COLOR_WARNING = 'bg-warning' const MESSAGE_BOX_COLOR_NEGATIVE = 'bg-negative' export default { MESSAGE_BOX_COLOR_PRIMARY, MESSAGE_BOX_COLOR_POSITIVE, MESSAGE_BOX_COLOR_WARNING, MESSAGE_BOX_COLOR_NEGATIVE }<file_sep>/model/type.go package model import ( "github.com/google/uuid" "github.com/jinzhu/gorm" ) type Type struct { TypeId string `json:"type_id" gorm:"column:type_id;type:varchar(50);PRIMARY_KEY"` Name string `json:"name" gorm:"column:name;type:varchar(50)"` } func (t *Type) BeforeCreate(scope *gorm.Scope) error { t.TypeId = uuid.New().String() return nil } func (Type) TableName() string { return "type" }
b5e37749b2c137f71bb2f0dcadee6066f809ded2
[ "JavaScript", "Go Module", "Go" ]
26
Go
zclyne/Goblog
3ae2b80a63f9498a70c943a174ab4349a265b787
94cfc1fdbe7998f8275973c3d22e185a12b40255
refs/heads/master
<repo_name>A1000000/net.kibotu.android.deviceinfo<file_sep>/deviceinfo-lib/src/net/kibotu/android/deviceinfo/IPausable.java package net.kibotu.android.deviceinfo; public interface IPausable { public void onResume(); public void onPause(); } <file_sep>/deviceinfo-tests/pom.xml <?xml version="1.0" encoding="UTF-8"?> <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"> <parent> <artifactId>deviceinfo</artifactId> <groupId>net.kibotu.android.deviceinfo</groupId> <version>1.0.0-SNAPSHOT</version> <!--<relativePath>../pom.xml</relativePath>--> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>deviceinfo-tests</artifactId> <packaging>apk</packaging> <properties> <android.device>test</android.device> <android.enableIntegrationTest>false</android.enableIntegrationTest> </properties> <profiles> <profile> <id>integration-tests</id> <activation> <property> <name>integration-tests</name> </property> </activation> <properties> <android.enableIntegrationTest>true</android.enableIntegrationTest> </properties> </profile> </profiles> <dependencies> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>android-test</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>com.android.support</groupId> <artifactId>support-v4</artifactId> <version>18.0.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>net.kibotu.android.deviceinfo</groupId> <artifactId>deviceinfo-lib</artifactId> <version>1.0.0</version> <scope>compile</scope> <exclusions> <exclusion> <groupId>com.google.android</groupId> <artifactId>annotations</artifactId> </exclusion> <exclusion> <groupId>com.intellij</groupId> <artifactId>annotations</artifactId> </exclusion> </exclusions> </dependency> <!--<dependency>--> <!--<groupId>net.kibotu.android.deviceinfo</groupId>--> <!--<artifactId>deviceinfo-lib</artifactId>--> <!--<version>1.0.0</version>--> <!--<scope>compile</scope>--> <!--<type>apklib</type>--> <!--<exclusions>--> <!--&lt;!&ndash;<exclusion>&ndash;&gt;--> <!--&lt;!&ndash;<groupId>com.google.android</groupId>&ndash;&gt;--> <!--&lt;!&ndash;<artifactId>annotations</artifactId>&ndash;&gt;--> <!--&lt;!&ndash;</exclusion>&ndash;&gt;--> <!--&lt;!&ndash;<exclusion>&ndash;&gt;--> <!--&lt;!&ndash;<groupId>com.intellij</groupId>&ndash;&gt;--> <!--&lt;!&ndash;<artifactId>annotations</artifactId>&ndash;&gt;--> <!--&lt;!&ndash;</exclusion>&ndash;&gt;--> <!--</exclusions>--> <!--</dependency>--> <!-- @NotNull, etc. annotations --> <dependency> <groupId>com.intellij</groupId> <artifactId>annotations</artifactId> <version>12.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>annotations</artifactId> <version>4.1.1.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <!-- because JUnit 4.11 adds JUnit library and hamcrest jar library, although JUnit 4.11 already contains all the hamcrest classes, so hamcrest exists twice http://stackoverflow.com/a/13270983/957370 --> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> <groupId>org.hamcrest</groupId> </exclusion> </exclusions> </dependency> <!-- automated interactions with hardware like touches, etc. --> <dependency> <groupId>com.jayway.android.robotium</groupId> <artifactId>robotium-solo</artifactId> <version>3.6</version> </dependency> <!-- mockito needs multiple jars: http://corner.squareup.com/2012/10/mockito-android.html --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.9.5</version> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> <groupId>org.hamcrest</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.dexmaker</groupId> <artifactId>dexmaker-mockito</artifactId> <version>1.1</version> <exclusions> <exclusion> <artifactId>hamcrest-core</artifactId> <groupId>org.hamcrest</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.dexmaker</groupId> <artifactId>dexmaker</artifactId> <version>1.1</version> </dependency> <!-- json assert comparison independent of order --> <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.2.3</version> </dependency> <!-- junit logs --> <dependency> <groupId>com.github.stefanbirkner</groupId> <artifactId>system-rules</artifactId> <version>1.5.0</version> </dependency> </dependencies> <repositories> <repository> <id>android.support-mvn-repo</id> <url>https://raw.github.com/kmchugh/android.support/mvn-repo</url> <snapshots> <enabled>true</enabled> <updatePolicy>daily</updatePolicy> </snapshots> </repository> </repositories> <build> <finalName>${project.artifactId}</finalName> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-manifest</id> <phase>initialize</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${project.build.directory}</outputDirectory> <resources> <resource> <directory>${project.basedir}</directory> <includes> <include>AndroidManifest.xml</include> </includes> </resource> </resources> <overwrite>true</overwrite> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <configuration> <androidManifestFile>${project.build.directory}/../AndroidManifest.xml</androidManifestFile> <manifest> <versionName/> <versionCodeUpdateFromVersion>true</versionCodeUpdateFromVersion> </manifest> <mergeManifests>true</mergeManifests> <undeployBeforeDeploy>true</undeployBeforeDeploy> </configuration> <executions> <execution> <id>update-manifest</id> <phase>initialize</phase> <goals> <goal>manifest-update</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project><file_sep>/deviceinfo-lib/src/net/kibotu/android/deviceinfo/JsonParser.java package net.kibotu.android.deviceinfo; import net.kibotu.android.error.tracking.Logger; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; final public class JsonParser { private JsonParser() throws IllegalAccessException { throw new IllegalAccessException("static class"); } /** * reads json by url * * @param url * @return JSONObject */ @Nullable static public JSONObject readJson(final @NotNull String url) { final StringBuilder builder = new StringBuilder(); final HttpClient client = new DefaultHttpClient(); final HttpGet httpGet = new HttpGet(url); JSONObject finalResult = null; try { final HttpResponse response = client.execute(httpGet); final StatusLine statusLine = response.getStatusLine(); final int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } finalResult = new JSONObject(new JSONTokener(builder.toString())); } else { Logger.e("Failed to download status file."); } } catch (final JSONException e) { Logger.e(e); } catch (final ClientProtocolException e) { Logger.e(e); } catch (final IOException e) { Logger.e(e); } return finalResult; } }<file_sep>/deviceinfo-tests/src/net/kibotu/android/deviceinfo/ABTest.java package net.kibotu.android.deviceinfo; import android.annotation.TargetApi; import android.os.Build; import com.jayway.android.robotium.solo.Solo; import org.junit.Test; @TargetApi(Build.VERSION_CODES.CUPCAKE) public class ABTest extends ActivityInstrumentationImpl { private Solo solo; public void setUp() throws Exception { solo = new Solo(getInstrumentation(), getActivity()); } @Test public void testAB() throws Exception { assertTrue(true); } @Override public void tearDown() throws Exception { solo.finishOpenedActivities(); } } <file_sep>/deviceinfo-lib/src/net/kibotu/android/deviceinfo/Async.java package net.kibotu.android.deviceinfo; import android.annotation.TargetApi; import android.os.AsyncTask; import android.os.Build; import net.kibotu.android.error.tracking.Logger; import org.jetbrains.annotations.NotNull; public class Async { /** * Creates an async task and executes it. * * @param delegate Runnable. * @return AsyncTask. */ @TargetApi(Build.VERSION_CODES.CUPCAKE) public static AsyncTask<Void, Void, Void> safeAsync(@NotNull final Runnable delegate) { final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { protected Void doInBackground(final Void... voi) { try { delegate.run(); } catch (final Exception e) { Logger.e(e); } return null; } }; task.execute(); return task; } } <file_sep>/deviceinfo-app/src/net/kibotu/android/deviceinfo/fragments/menu/MenuFragment.java package net.kibotu.android.deviceinfo.fragments.menu; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; import net.kibotu.android.deviceinfo.DeviceOld; import net.kibotu.android.deviceinfo.MainActivity; import net.kibotu.android.deviceinfo.R; import net.kibotu.android.deviceinfo.Registry; public class MenuFragment extends ListFragment { private volatile MenuAdapter list; private volatile Context context; public volatile Registry lastItemList; public MenuFragment(Context context) { this.context = context; } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.list, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListAdapter(getFragmentListAdapter()); } public MenuAdapter getFragmentListAdapter() { return (list == null) ? (list = new MenuAdapter(context)) : list; } public void addItem(final String name, int iconRId) { getFragmentListAdapter().add(new MenuItem(name, iconRId)); } @Override public void onListItemClick(final ListView lv, final View v, final int position, final long id) { super.onListItemClick(lv, v, position, id); if (lastItemList != null) lastItemList.stopRefreshing(); final Registry currentItemList = Registry.values()[position]; currentItemList.startRefreshingList(1); // currentItemList.resumeThreads(); if (lastItemList != currentItemList) ((FragmentActivity) DeviceOld.context()).getSupportFragmentManager() .beginTransaction() .replace(R.id.content_frame, currentItemList.getFragmentList()) .commit(); lastItemList = currentItemList; changeActionBar(); } public void changeActionBar() { DeviceOld.context().setTitle(lastItemList.name()); ((SlidingFragmentActivity) context).getSupportActionBar().setIcon(lastItemList.iconR_i); ((MainActivity)context).getSlidingMenu().showContent(); } }<file_sep>/deviceinfo-lib/src/net/kibotu/android/deviceinfo/DeviceOld.java package net.kibotu.android.deviceinfo; import android.annotation.TargetApi; import android.app.*; import android.content.*; import android.content.pm.*; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Point; import android.hardware.Sensor; import android.hardware.SensorManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.opengl.GLES10; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.os.Build; import android.os.Environment; import android.os.StatFs; import android.provider.Settings; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.Display; import android.view.View; import android.webkit.WebView; import net.kibotu.android.error.tracking.Logger; import net.kibotu.android.error.tracking.ReflectionHelper; import org.apache.http.conn.util.InetAddressUtils; import org.jetbrains.annotations.Nullable; import org.json.JSONArray; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import java.io.*; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.NetworkInterface; import java.nio.IntBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.*; import static android.os.Build.*; /** * Variety ways to retrieve device id in Android. * <p/> * - Unique number (IMEI, MEID, ESN, IMSI) * - MAC Address * - Serial Number * - ANDROID_ID * <p/> * Further information @see http://developer.samsung.com/android/technical-docs/How-to-retrieve-the-Device-Unique-ID-from-android-device */ public class DeviceOld { public static final int HONEYCOMB = 11; public static final String TAG = DeviceOld.class.getSimpleName(); public static final int ANDROID_MIN_SDK_VERSION = 9; public static boolean ACTIVATE_TB = false; public static final int mTB_Y = 2012; public static final int mTB_M = 11; public static final int mTB_D = 30; public static final Class MAIN_CLASS = Activity.class; private static final String PREFS_NAME = "Tracking"; static IntBuffer size = IntBuffer.allocate(1); private static String sharedLibraries; private static String features; private static Object openGLShaderConstraints; private static DisplayHelper displayHelper; private static volatile Context context; private static volatile HashMap<File, String> cache; private static String uuid; private static Map<String, ?> buildInfo; // static private DeviceOld() throws IllegalAccessException { throw new IllegalAccessException("static class"); } public static void setContext(final Context context) { DeviceOld.context = context; new DisplayHelper((Activity) context); } public static Activity context() { if (context == null) throw new IllegalStateException("'context' must not be null. Please init Device.setContext()."); return (Activity) context; } public static JSONArray getPermissions() { final PackageManager pm = context().getPackageManager(); final ArrayList<String> permissions = new ArrayList<String>(); final List<PermissionGroupInfo> lstGroups = pm.getAllPermissionGroups(0); for (final PermissionGroupInfo pgi : lstGroups) { // permissions.add(pgi.name); try { final List<PermissionInfo> lstPermissions = pm.queryPermissionsByGroup(pgi.name, 0); for (final PermissionInfo pi : lstPermissions) { if (context().checkCallingOrSelfPermission(pi.name) == PackageManager.PERMISSION_GRANTED) permissions.add(pi.name); } } catch (final Exception e) { Logger.e(e); } } return new JSONArray(permissions); } /** * Returns the unique device ID. for example,the IMEI for GSM and the MEID or ESN for CDMA phones. * <p/> * IMPORTANT! it requires READ_PHONE_STATE permission in AndroidManifest.xml * <p/> * Disadvantages: * - Android devices should have telephony services * - It doesn't work reliably * - Serial Number * - When it does work, that value survives device wipes (Factory resets) * and thus you could end up making a nasty mistake when one of your customers wipes their device * and passes it on to another person. */ public static String getDeviceIdFromTelephonyManager() { return ((TelephonyManager) context().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId(); } /** * Returns the unique subscriber ID, for example, the IMSI for a GSM phone. * <p/> * Disadvantages: * - Android devices should have telephony services * - It doesn't work reliably * - Serial Number * - When it does work, that value survives device wipes (Factory resets) * and thus you could end up making a nasty mistake when one of your customers wipes their device * and passes it on to another person. */ public static String getSubscriberIdFromTelephonyManager() { return ((TelephonyManager) context().getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId(); } /** * Returns MAC Address. * <p/> * IMPORTANT! requires ACCESS_WIFI_STATE permission in AndroidManifest.xml * <p/> * Disadvantages: * - Device should have Wi-Fi (where not all devices have Wi-Fi) * - If Wi-Fi present in Device should be turned on otherwise does not report the MAC address */ public static String getMacAdress() { return ((WifiManager) context().getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getMacAddress(); } /** * Returns MAC address of the given interface name. * * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string */ public static String getMACAddress(String interfaceName) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (final byte aMac : mac) buf.append(String.format("%02X:", aMac)); if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); return buf.toString(); } } catch (final Exception ignored) { } // for now eat exceptions return ""; /*try { // this is so Linux hack return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim(); } catch (IOException ex) { return null; }*/ } /** * Get IP address from first non-localhost interface * * @param useIPv4 true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (final Exception ignored) { } // for now eat exceptions return ""; } /** * System Property ro.serialno returns the serial number as unique number Works for Android 2.3 and above. Can return null. * <p/> * Disadvantages: * - Serial Number is not available with all android devices */ public static String getSerialNummer() { String hwID = null; try { Class<?> c = Class.forName("android.os.SystemProperties"); Method get = c.getMethod("get", String.class, String.class); hwID = (String) (get.invoke(c, "ro.serialno", "unknown")); } catch (final Exception ignored) { } if (hwID != null) return hwID; try { Class<?> myclass = Class.forName("android.os.SystemProperties"); Method[] methods = myclass.getMethods(); Object[] params = new Object[]{"ro.serialno", "Unknown"}; hwID = (String) (methods[2].invoke(myclass, params)); } catch (final Exception ignored) { } return hwID; } /** * More specifically, Settings.Secure.ANDROID_ID. A 64-bit number (as a hex string) * that is randomly generated on the device's first boot and should remain constant * for the lifetime of the device (The value may change if a factory reset is performed on the device.) * ANDROID_ID seems a good choice for a unique device identifier. * <p/> * Disadvantages: * - Not 100% reliable of Android prior to 2.2 (�Froyo�) devices * - Also, there has been at least one widely-observed bug in a popular * handset from a major manufacturer, where every instance has the same ANDROID_ID. */ public static String getAndroidId() { return Settings.Secure.getString(context().getContentResolver(), Settings.Secure.ANDROID_ID); } public static int[] GetRealDimension() { final Display display = context().getWindowManager().getDefaultDisplay(); final int[] dimension = new int[2]; if (VERSION.SDK_INT >= 17) { try { //new pleasant way to get real metrics final DisplayMetrics realMetrics = new DisplayMetrics(); final Point p = new Point(); // display.getRealMetrics(realMetrics); Display.class.getMethod("getRealSize").invoke(p); dimension[0] = p.x; dimension[1] = p.y; } catch (final IllegalAccessException e) { Logger.e(e); } catch (final InvocationTargetException e) { Logger.e(e); } catch (final NoSuchMethodException e) { Logger.e(e); } catch (final NoClassDefFoundError e) { Logger.e(e); } } else if (VERSION.SDK_INT >= 14) { //reflection for this weird in-between time try { Method mGetRawH = Display.class.getMethod("getRawHeight"); Method mGetRawW = Display.class.getMethod("getRawWidth"); dimension[0] = (Integer) mGetRawW.invoke(display); dimension[1] = (Integer) mGetRawH.invoke(display); } catch (final Exception e) { //this may not be 100% accurate, but it's all we've got dimension[0] = display.getWidth(); dimension[1] = display.getHeight(); Logger.e("Couldn't use reflection to get the real display metrics.", e); } } else { //This should be close, as lower API devices should not have window navigation bars dimension[0] = display.getWidth(); dimension[1] = display.getHeight(); } return dimension; } public static DisplayMetrics getDisplayMetrics() { DisplayMetrics metrics = new DisplayMetrics(); context().getWindowManager().getDefaultDisplay().getMetrics(metrics); return metrics; } public static int glGetIntegerv(int value) { size = IntBuffer.allocate(1); GLES10.glGetIntegerv(value, size); return size.get(0); } public static int glGetIntegerv(GL10 gl, int value) { size = IntBuffer.allocate(1); gl.glGetIntegerv(value, size); return size.get(0); } public static int getOpenGLVersion() { final ActivityManager activityManager = (ActivityManager) context() .getSystemService(Context.ACTIVITY_SERVICE); final ConfigurationInfo configurationInfo = activityManager .getDeviceConfigurationInfo(); return configurationInfo.reqGlEsVersion; } public static boolean supportsOpenGLES2() { return getOpenGLVersion() >= 0x20000; } public static int getVersionFromPackageManager() { PackageManager packageManager = context().getPackageManager(); FeatureInfo[] featureInfos = packageManager.getSystemAvailableFeatures(); if (featureInfos != null && featureInfos.length > 0) { for (FeatureInfo featureInfo : featureInfos) { // Null feature name means this feature is the open gl es // version feature. if (featureInfo.name == null) { if (featureInfo.reqGlEsVersion != FeatureInfo.GL_ES_VERSION_UNDEFINED) { return getMajorVersion(featureInfo.reqGlEsVersion); } else { return 1; // Lack of property means OpenGL ES version 1 } } } } return 1; } public static List<ResolveInfo> installedApps() { final PackageManager pm = context().getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> apps = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA); // for(int i = 0; i < apps.size(); ++i) { // Logger.v(""+apps.get(i).activityInfo.name); // } return apps; } public static List<Sensor> getSensorList() { SensorManager manager = (SensorManager) context().getSystemService(Context.SENSOR_SERVICE); return manager.getSensorList(Sensor.TYPE_ALL); // SensorManager.SENSOR_ALL } /** * @see android.content.pm.FeatureInfo#getGlEsVersion() */ private static int getMajorVersion(int glEsVersion) { return ((glEsVersion & 0xffff0000) >> 16); } public static String getExtensions() { return GLES10.glGetString(GL10.GL_EXTENSIONS); } /** * @return integer Array with 4 elements: user, system, idle and other cpu * usage in percentage. */ public static int[] getCpuUsageStatistic() { String tempString = executeTop(); tempString = tempString.replaceAll(",", ""); tempString = tempString.replaceAll("User", ""); tempString = tempString.replaceAll("System", ""); tempString = tempString.replaceAll("IOW", ""); tempString = tempString.replaceAll("IRQ", ""); tempString = tempString.replaceAll("%", ""); for (int i = 0; i < 10; i++) { tempString = tempString.replaceAll(" ", " "); } tempString = tempString.trim(); String[] myString = tempString.split(" "); int[] cpuUsageAsInt = new int[myString.length]; for (int i = 0; i < myString.length; i++) { myString[i] = myString[i].trim(); cpuUsageAsInt[i] = Integer.parseInt(myString[i]); } return cpuUsageAsInt; } private static String executeTop() { java.lang.Process p = null; BufferedReader in = null; String returnString = null; try { p = Runtime.getRuntime().exec("top -n 1"); in = new BufferedReader(new InputStreamReader(p.getInputStream())); while (returnString == null || returnString.contentEquals("")) { returnString = in.readLine(); } } catch (IOException e) { Log.e("executeTop", "error in getting first line of top"); e.printStackTrace(); } finally { try { in.close(); p.destroy(); } catch (IOException e) { Log.e("executeTop", "error in closing and destroying top process"); e.printStackTrace(); } } return returnString; } public static String getCpuInfo() { return getContentRandomAccessFile("/proc/cpuinfo"); } public static String getContentRandomAccessFile(String file) { final StringBuffer buffer = new StringBuffer(); try { final RandomAccessFile reader = new RandomAccessFile(file, "r"); String load = reader.readLine(); while (load != null) { // Logger.v(reader.readLine()); buffer.append(load).append("\n"); load = reader.readLine(); } } catch (final IOException ex) { try { Thread.currentThread().join(); } catch (InterruptedException e) { Logger.e(e); } Logger.e(ex); } return buffer.toString(); } public static float[] readUsage() { try { RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r"); // RandomAccessFile reader = new RandomAccessFile("/proc/cpuinfo", "r"); String load = reader.readLine(); String[] toks = load.split(" "); long idle1 = Long.parseLong(toks[4]); long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); try { Thread.sleep(360); } catch (final Exception e) { } reader.seek(0); load = reader.readLine(); reader.close(); toks = load.split(" "); long idle2 = Long.parseLong(toks[4]); long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[5]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]); float[] cpus = new float[2]; cpus[0] = (float) cpu1 / ((float) cpu1 + (float) idle1); cpus[1] = (float) cpu2 / ((float) cpu2 + (float) idle2); // return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)); return cpus; } catch (final IOException e) { Logger.e(e); } return null; } /** * credits: * http://stackoverflow.com/questions/3170691/how-to-get-current-memory-usage-in-android */ public static long getFreeMemoryByActivityService() { ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); ActivityManager activityManager = (ActivityManager) context().getSystemService(Context.ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); return mi.availMem; } public static boolean isLowMemory() { ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo(); ActivityManager activityManager = (ActivityManager) context().getSystemService(Context.ACTIVITY_SERVICE); activityManager.getMemoryInfo(mi); return mi.lowMemory; } public static long getFreeMemoryByEnvironment() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getAvailableBlocks(); return availableBlocks * blockSize; } public static long getTotalMemoryByEnvironment() { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSize(); long availableBlocks = stat.getBlockCount(); return availableBlocks * blockSize; } public static long getRuntimeTotalMemory() { long memory = 0L; try { final Runtime info = Runtime.getRuntime(); memory = info.totalMemory(); } catch (final Exception e) { Logger.e(e); } return memory; } public static long getRuntimeMaxMemory() { long memory = 0L; try { Runtime info = Runtime.getRuntime(); memory = info.maxMemory(); } catch (final Exception e) { Logger.e(e); } return memory; } public static long getRuntimeFreeMemory() { long memory = 0L; try { final Runtime info = Runtime.getRuntime(); memory = info.freeMemory(); } catch (final Exception e) { Logger.e(e); } return memory; } public static long getUsedMemorySize() { long usedSize = 0L; try { final Runtime info = Runtime.getRuntime(); usedSize = info.totalMemory() - info.freeMemory(); } catch (final Exception e) { Logger.e(e); } return usedSize; } /** * @return * @see <a href="http://stackoverflow.com/questions/2630158/detect-application-heap-size-in-android">detect-application-heap-size-in-android</a> */ public static long getMaxMemory() { return Runtime.getRuntime().maxMemory(); } public static int getMemoryClass() { return ((ActivityManager) context().getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); } public static void screenshot(final String filepath, final String filename) { saveBitmap(save(context().getWindow().findViewById(android.R.id.content)), filepath, filename); } /** * http://stackoverflow.com/a/18489243 */ public static Bitmap save(View v) { Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.draw(c); return b; } public static void saveBitmap(Bitmap b, String filepath, String filename) { try { FileOutputStream out = new FileOutputStream(new File(filepath, filename)); b.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); b.recycle(); } catch (final Exception e) { Logger.e(e); } } public static TreeSet<String> getSharedLibraries2() { PackageManager pm = context().getPackageManager(); String[] libraries = pm.getSystemSharedLibraryNames(); TreeSet<String> l = new TreeSet<String>(); for (String lib : libraries) { if (lib != null) { l.add(lib); } } return l; } public static JSONArray getSharedLibraries() { PackageManager pm = context().getPackageManager(); String[] libraries = pm.getSystemSharedLibraryNames(); JSONArray l = new JSONArray(); for (String lib : libraries) { if (lib != null) { l.put(lib); } } return l; } public static TreeSet<String> getFeatures2() { PackageManager pm = context().getPackageManager(); FeatureInfo[] features = pm.getSystemAvailableFeatures(); TreeSet<String> l = new TreeSet<String>(); for (FeatureInfo f : features) { if (f.name != null) { l.add(f.name); } } return l; } public static Map<String, FeatureInfo> getAllFeatures() { final PackageManager pm = context().getPackageManager(); final FeatureInfo[] features = pm.getSystemAvailableFeatures(); final LinkedHashMap<String, FeatureInfo> featureMap = new LinkedHashMap<String, FeatureInfo>(); for (final FeatureInfo f : features) { if (f.name != null) { featureMap.put(f.name, f); } } return featureMap; } public static JSONArray getFeatures() { PackageManager pm = context().getPackageManager(); FeatureInfo[] features = pm.getSystemAvailableFeatures(); JSONArray l = new JSONArray(); for (FeatureInfo f : features) { if (f.name != null) { l.put(f.name); f.describeContents(); } } return l; } public static JSONArray getOpenGLES() { JSONArray json = new JSONArray(); // enableHardwareAcceleration(context()); // enableHardwareAcceleration(context().findViewById(android.R.id.content)); json.put("GL_MAX_TEXTURE_UNITS: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_UNITS)); json.put("GL_MAX_LIGHTS: " + glGetIntegerv(GLES10.GL_MAX_LIGHTS)); json.put("GL_SUBPIXEL_BITS: " + glGetIntegerv(GLES10.GL_SUBPIXEL_BITS)); json.put("GL_MAX_ELEMENTS_INDICES: " + glGetIntegerv(GLES10.GL_MAX_ELEMENTS_INDICES)); json.put("GL_MAX_ELEMENTS_VERTICES: " + glGetIntegerv(GLES10.GL_MAX_ELEMENTS_VERTICES)); json.put("GL_MAX_MODELVIEW_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_MODELVIEW_STACK_DEPTH)); json.put("GL_MAX_PROJECTION_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_PROJECTION_STACK_DEPTH)); json.put("GL_MAX_TEXTURE_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_STACK_DEPTH)); json.put("GL_MAX_TEXTURE_SIZE: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE)); json.put("GL_DEPTH_BITS: " + glGetIntegerv(GLES10.GL_DEPTH_BITS)); json.put("GL_STENCIL_BITS: " + glGetIntegerv(GLES10.GL_STENCIL_BITS)); json.put("GL_RENDERER: " + GLES20.glGetString(GLES10.GL_RENDERER)); json.put("GL_VENDOR: " + GLES20.glGetString(GLES10.GL_VENDOR)); json.put("GL_VERSION: " + GLES20.glGetString(GLES10.GL_VERSION)); json.put("GL_MAX_VERTEX_ATTRIBS: " + glGetIntegerv(GLES20.GL_MAX_VERTEX_ATTRIBS)); json.put("GL_MAX_VERTEX_UNIFORM_VECTORS: " + glGetIntegerv(GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS)); json.put("GL_MAX_FRAGMENT_UNIFORM_VECTORS: " + glGetIntegerv(GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS)); json.put("GL_MAX_VARYING_VECTORS: " + glGetIntegerv(GLES20.GL_MAX_VARYING_VECTORS)); int[] arr = new int[1]; GLES20.glGetIntegerv(GLES20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, arr, 0); json.put("Vertex Texture Fetch: " + (arr[0] != 0)); json.put("GL_MAX_TEXTURE_IMAGE_UNITS: " + glGetIntegerv(GLES20.GL_MAX_TEXTURE_IMAGE_UNITS)); int size[] = new int[2]; GLES20.glGetIntegerv(GLES10.GL_MAX_VIEWPORT_DIMS, size, 0); json.put("GL_MAX_VIEWPORT_DIMS: " + size[0] + "x" + size[1]); return json; } /** * http://stackoverflow.com/questions/18447875/print-gpu-info-renderer-version-vendor-on-textview-on-android * * @return */ public static TreeSet<String> getOpenGLShaderConstraints() { final TreeSet<String> l = new TreeSet<String>(); final GLSurfaceView gles10view = new GLSurfaceView(context()); final GLSurfaceView gles20view = new GLSurfaceView(context()); final GLSurfaceView.Renderer gles10 = new GLSurfaceView.Renderer() { @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { l.add("GL_MAX_TEXTURE_UNITS: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_UNITS)); l.add("GL_MAX_LIGHTS: " + glGetIntegerv(GLES10.GL_MAX_LIGHTS)); l.add("GL_SUBPIXEL_BITS: " + glGetIntegerv(GLES10.GL_SUBPIXEL_BITS)); l.add("GL_MAX_ELEMENTS_INDICES: " + glGetIntegerv(GLES10.GL_MAX_ELEMENTS_INDICES)); l.add("GL_MAX_ELEMENTS_VERTICES: " + glGetIntegerv(GLES10.GL_MAX_ELEMENTS_VERTICES)); l.add("GL_MAX_MODELVIEW_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_MODELVIEW_STACK_DEPTH)); l.add("GL_MAX_PROJECTION_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_PROJECTION_STACK_DEPTH)); l.add("GL_MAX_TEXTURE_STACK_DEPTH: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_STACK_DEPTH)); l.add("GL_MAX_TEXTURE_SIZE: " + glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE)); l.add("GL_DEPTH_BITS: " + glGetIntegerv(GLES10.GL_DEPTH_BITS)); l.add("GL_STENCIL_BITS: " + glGetIntegerv(GLES10.GL_STENCIL_BITS)); // context.runOnUiThread(new Runnable() { // // @Override // public void run() { // // List<Map<String, String>> listOfMaps = context.fragment.listOfMaps; // // for (int i = 0; i < listOfMaps.size(); ++i) { // for (Map.Entry<String, ?> map : listOfMaps.get(i).entrySet()) { // if (map.getValue().equals("OpenGL Constraints")) { // listOfMaps.get(i).put("data", buildLineItem("OpenGL Constraints", l).mData); // } // } // } // // // remove view after getting all required infos // final LinearLayout layout = (LinearLayout) context.findViewById(R.id.mainlayout); // layout.removeView(gles10view); // layout.findViewById(R.id.pager).setVisibility(VISIBLE); // // // update fragment adapter about changes // final ViewPager mPager = (ViewPager) context.findViewById(R.id.pager); // mPager.getAdapter().notifyDataSetChanged(); // } // }); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { } @Override public void onDrawFrame(GL10 gl) { } }; final GLSurfaceView.Renderer gles20 = new GLSurfaceView.Renderer() { @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { l.add("GL_RENDERER: " + gl.glGetString(GLES10.GL_RENDERER)); l.add("GL_VENDOR: " + gl.glGetString(GLES10.GL_VENDOR)); l.add("GL_VERSION: " + gl.glGetString(GLES10.GL_VERSION)); l.add("GL_MAX_VERTEX_ATTRIBS: " + glGetIntegerv(gl, GLES20.GL_MAX_VERTEX_ATTRIBS)); l.add("GL_MAX_VERTEX_UNIFORM_VECTORS: " + glGetIntegerv(gl, GLES20.GL_MAX_VERTEX_UNIFORM_VECTORS)); l.add("GL_MAX_FRAGMENT_UNIFORM_VECTORS: " + glGetIntegerv(gl, GLES20.GL_MAX_FRAGMENT_UNIFORM_VECTORS)); l.add("GL_MAX_VARYING_VECTORS: " + glGetIntegerv(gl, GLES20.GL_MAX_VARYING_VECTORS)); l.add("Vertex Texture Fetch: " + isVTFSupported(gl)); l.add("GL_MAX_TEXTURE_IMAGE_UNITS: " + glGetIntegerv(gl, GLES20.GL_MAX_TEXTURE_IMAGE_UNITS)); int size[] = new int[2]; gl.glGetIntegerv(GLES10.GL_MAX_VIEWPORT_DIMS, size, 0); l.add("GL_MAX_VIEWPORT_DIMS: " + size[0] + "x" + size[1]); // // List<Map<String, String>> listOfMaps = context.fragment.listOfMaps; // // for (int i = 0; i < listOfMaps.size(); ++i) { // for (Map.Entry<String, ?> map : listOfMaps.get(i).entrySet()) { // if (map.getValue().equals("OpenGL Constraints")) { // Map<String, String> extensions = new HashMap<String, String>(); // extensions.put("header", "OpenGL Extensions"); // extensions.put("data", gl.glGetString(GLES10.GL_EXTENSIONS)); // listOfMaps.add(i + 1, extensions); // } // } // } // // context.runOnUiThread(new Runnable() { // // @Override // public void run() { // // // remove view after getting all required infos // final LinearLayout layout = (LinearLayout) context.findViewById(R.id.mainlayout); // layout.removeView(gles20view); // // layout.addView(gles10view); // } // }); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { } @Override public void onDrawFrame(GL10 gl) { } }; // context.runOnUiThread(new Runnable() { // // @Override // public void run() { // gles20view.setEGLConfigChooser(true); // gles20view.setZOrderOnTop(true); // // gles10view.setEGLConfigChooser(true); // gles10view.setZOrderOnTop(true); // // // Check if the system supports OpenGL ES 2.0. // final ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); // final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); // final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000; // // if (supportsEs2) // gles20view.setEGLContextClientVersion(2); // gles10view.setEGLContextClientVersion(1); // // gles10view.setRenderer(gles10); // gles20view.setRenderer(gles20); // final LinearLayout layout = (LinearLayout) context.findViewById(R.id.mainlayout); // layout.addView(gles20view); // layout.findViewById(R.id.pager).setVisibility(View.GONE); // } // }); return l; } public static String getInternalStoragePath() { return context().getFilesDir().getParent(); } public static String getCachingPath() { return context().getCacheDir().getAbsolutePath(); } public static TreeSet<String> getFolder() { TreeSet<String> l = new TreeSet<String>(); l.add("Internal Storage Path\n" + context().getFilesDir().getParent() + "/"); l.add("APK Storage Path\n" + context().getPackageCodePath()); l.add("Root Directory\n" + Environment.getRootDirectory()); l.add("Data Directory\n" + Environment.getDataDirectory()); l.add("External Storage Directory\n" + Environment.getExternalStorageDirectory()); l.add("Download Cache Directory\n" + Environment.getDownloadCacheDirectory()); l.add("External Storage State\n" + Environment.getExternalStorageState()); l.add("Directory Alarms\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_ALARMS)); l.add("Directory DCIM\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)); l.add("Directory Downloads\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)); l.add("Directory Movies\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)); l.add("Directory Music\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)); l.add("Directory Notifications\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS)); l.add("Directory Pictures\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)); l.add("Directory Podcasts\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PODCASTS)); l.add("Directory Ringtones\n" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_RINGTONES)); return l; } public static String getOsBuildModel() { return Build.MODEL; } public static float getScreenDensity() { return context().getResources().getDisplayMetrics().density; } public static int getApiLevel() { return VERSION.SDK_INT; } public static Object getManufacturer() { return Build.MANUFACTURER; } public static String getLocale() { return Locale.getDefault().toString(); } public static boolean isVTFSupported(GL10 gl) { int[] arr = new int[1]; gl.glGetIntegerv(GLES20.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, arr, 0); return arr[0] != 0; } public static Map<String, ?> getBuildInfo() { return buildInfo; } public static String getRadio() { String radio = android.os.Build.RADIO; if (DeviceOld.getApiLevel() >= 14) radio = ReflectionHelper.get(android.os.Build.class, "getRadioVersion", null); return radio; } public static ProxySettings getProxySettings() { return new ProxySettings(context()); } public static String getMarketUrl() { return "market://details?id=" + DeviceOld.context().getPackageName(); } public interface AsyncCallback<T> { void onComplete(final T result); } public static void getUserAgent(final AsyncCallback<String> callback) { context().runOnUiThread(new Runnable() { @Override public void run() { WebView wb = new WebView(context()); String res = wb.getSettings().getUserAgentString(); callback.onComplete(res); } }); } public static long getDirectorySize(File directory, long blockSize) { File[] files = directory.listFiles(); if (files == null) { return 0; } // space used by directory itself long size = directory.length(); for (File file : files) { if (file.isDirectory()) { // space used by subdirectory size += getDirectorySize(file, blockSize); } else { // file size need to rounded up to full block sizes // (not a perfect function, it adds additional block to 0 sized files // and file who perfectly fill their blocks) size += (file.length() / blockSize + 1) * blockSize; } } return size; } public static long getFileSizeDir(String path) { File directory = new File(path); if (!directory.exists()) return 0; StatFs statFs = new StatFs(directory.getAbsolutePath()); long blockSize; // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { // blockSize = statFs.getBlockSizeLong(); // } else { blockSize = statFs.getBlockSize(); // } return getDirectorySize(directory, blockSize) / (1024 * 1024); } public static String getAvailableFileSize(String path) { try { StatFs fs = new StatFs(path); return android.text.format.Formatter.formatFileSize(context(), fs.getAvailableBlocks() * fs.getBlockSize()); } catch (final Exception e) { e.printStackTrace(); } return null; } public static String getSystemOSVersion() { return System.getProperty("os.version"); } /** * Checks if the phone is rooted. * * @return <code>true</code> if the phone is rooted, <code>false</code> * otherwise. * @credits: http://stackoverflow.com/a/6425854 */ public static boolean isPhoneRooted() { // get from build info String buildTags = TAGS; if (buildTags != null && buildTags.contains("test-keys")) { Log.v(TAG, "is rooted by build tag"); return true; } // check if /system/app/Superuser.apk is present try { File file = new File("/system/app/Superuser.apk"); if (file.exists()) { Log.v(TAG, "is rooted by /system/app/Superuser.apk"); return true; } } catch (Throwable e1) { // ignore } // from excecuting shell command return executeShellCommand("which su"); } /** * Executes a shell command. * * @param command - Unix shell command. * @return <code>true</code> if shell command was successful. * @credits http://stackoverflow.com/a/15485210 */ public static boolean executeShellCommand(final String command) { Process process = null; try { process = Runtime.getRuntime().exec(command); Log.v(TAG, "'" + command + "' successfully excecuted."); Log.v(TAG, "is rooted by su command"); return true; } catch (final Exception e) { Log.e(TAG, "" + e.getMessage()); return false; } finally { if (process != null) { try { process.destroy(); } catch (final Exception e) { Log.e(TAG, "" + e.getMessage()); } } } } public static String getFileSize(String file) { return getFileSize(new File(file)); } public static String getFileSize(File file) { if (cache == null) cache = new HashMap<File, String>(); if (cache.containsKey(file)) return cache.get(file); long size = DeviceOld.getFileSizeDir(file.toString()); String ret = size == 0 ? file.toString() : file + " (" + size + " MB)"; cache.put(file, ret); return ret; } public static String getReleaseVersion() { return VERSION.RELEASE; } public static String getOsName() { Field[] fields = VERSION_CODES.class.getFields(); for (Field field : fields) { String fieldName = field.getName(); int fieldValue = -1; try { fieldValue = field.getInt(new Object()); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NullPointerException e) { e.printStackTrace(); } if (fieldValue == VERSION.SDK_INT) { return fieldName; } } return "android"; } /** * Returns MAC address of the given interface name. * <p/> * credits to http://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device/13007325#13007325 * <p/> * Note: requires <uses-permission android:name="android.permission.INTERNET " /> and * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE " /> * * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string */ @TargetApi(VERSION_CODES.GINGERBREAD) public static String AndroidMacAddress(String interfaceName) { String macaddress = ""; try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { if (interfaceName != null) { if (!intf.getName().equalsIgnoreCase(interfaceName)) continue; } byte[] mac = intf.getHardwareAddress(); if (mac == null) return ""; StringBuilder buf = new StringBuilder(); for (byte aMac : mac) buf.append(String.format("%02X:", aMac)); if (buf.length() > 0) buf.deleteCharAt(buf.length() - 1); macaddress = buf.toString(); } } catch (final Exception ignore) { } // for now eat exceptions return macaddress; } @TargetApi(11) public static void enableHardwareAcceleration(Activity context) { if (VERSION.SDK_INT >= 11) context.runOnUiThread(new Runnable() { @Override public void run() { // context().getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); context().getWindow().setFlags(0x01000000, 0x01000000); } }); } @TargetApi(11) public static void enableHardwareAcceleration(final View view) { if (VERSION.SDK_INT >= 11) context().runOnUiThread(new Runnable() { @Override public void run() { // view.setLayerType(View.LAYER_TYPE_HARDWARE, null); todo find way for api 10 } }); } public static String HashIdentifier(int prefix, String addressAndDeviceName) { byte[] hash = new byte[0]; try { hash = md5(addressAndDeviceName).getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } long strippedMD548bit = (long) hash[0] | (long) hash[1] << 8 | (long) hash[2] << 16 | (long) hash[3] << 24 | (long) hash[4] << 32 | (long) hash[5] << 40; // add prefix strippedMD548bit += ((long) prefix * 1000000000000000L); return String.valueOf(strippedMD548bit); } public static String AndroidUniqueIdentifier() { // to compute the identifier for android // 7778${ANDROID_ID}${MAC_ADDRESS}:${DEVICE_NAME}' running Apportable' return HashIdentifier(7778, AndroidId() + AndroidMacAddress("wlan0") + ":" + MODEL + " running Apportable"); } public static String UniqueIdentifier() { return HashIdentifier(1111, AndroidUniqueIdentifier()); } @TargetApi(VERSION_CODES.CUPCAKE) public static String AndroidId() { return Settings.Secure.getString(context().getContentResolver(), Settings.Secure.ANDROID_ID); } /** * String to Md5 conversion. * * @param s Raw string * @return Returns md5 hash. * @credits http://stackoverflow.com/questions/4846484/md5-or-other-hashing-in-android */ public static String md5(final String s) { final String MD5 = "MD5"; try { // Create MD5 Hash MessageDigest digest = MessageDigest.getInstance(MD5); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { String h = Integer.toHexString(0xFF & aMessageDigest); while (h.length() < 2) h = "0" + h; hexString.append(h); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } // We return the lowest disk space out of the internal and sd card storage public static Long getFreeDiskSpace() { Long diskSpace = null; try { StatFs externalStat = new StatFs(Environment.getExternalStorageDirectory().getPath()); long externalBytesAvailable = (long) externalStat.getBlockSize() * (long) externalStat.getBlockCount(); StatFs internalStat = new StatFs(Environment.getDataDirectory().getPath()); long internalBytesAvailable = (long) internalStat.getBlockSize() * (long) internalStat.getBlockCount(); diskSpace = Math.min(internalBytesAvailable, externalBytesAvailable); } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return diskSpace; } private static Battery battery; public static Battery getBattery() { if (battery != null) return battery; battery = new Battery(context()); return battery; } public static int getOrientation() { return context().getResources().getConfiguration().orientation; } public static String getOrientationName() { String orientation = null; try { switch (context().getResources().getConfiguration().orientation) { case android.content.res.Configuration.ORIENTATION_LANDSCAPE: orientation = "landscape"; break; case android.content.res.Configuration.ORIENTATION_PORTRAIT: orientation = "portrait"; break; } } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return orientation; } public static String getUsableResolution() { return String.format("%dx%d", Math.max(DisplayHelper.mScreenWidth, DisplayHelper.mScreenHeight), Math.min(DisplayHelper.mScreenWidth, DisplayHelper.mScreenHeight)); } public static String getUsableResolutionDp() { return String.format("%.0fx%.0f", Math.max(DisplayHelper.mScreenWidth, DisplayHelper.mScreenHeight) / DisplayHelper.mDensity, Math.min(DisplayHelper.mScreenWidth, DisplayHelper.mScreenHeight) / DisplayHelper.mDensity); } public static String getResolution() { return String.format("%dx%d", Math.max(DisplayHelper.absScreenWidth, DisplayHelper.absScreenHeight), Math.min(DisplayHelper.absScreenWidth, DisplayHelper.absScreenHeight)); } public static String getResolutionDp() { return String.format("%.0fx%.0f", Math.max(DisplayHelper.absScreenWidth, DisplayHelper.absScreenHeight) / DisplayHelper.mDensity, Math.min(DisplayHelper.absScreenWidth, DisplayHelper.absScreenHeight) / DisplayHelper.mDensity); } // http://developer.android.com/reference/java/lang/System.html#getProperty(java.lang.String) public static String getJavaVmVersion() { return System.getProperty("java.vm.version"); } public static String getOsArch() { return System.getProperty("os.arch"); } public static String getJavaClassPath() { return System.getProperty("java.class.path"); } public static String getOsName2() { return System.getProperty("os.name"); } // This returns the maximum memory the VM can allocate which != the total // memory on the phone. public static Long totalMemoryAvailable() { Long totalMemory = null; try { if (Runtime.getRuntime().maxMemory() != Long.MAX_VALUE) { totalMemory = Runtime.getRuntime().maxMemory(); } else { totalMemory = Runtime.getRuntime().totalMemory(); } } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return totalMemory; } // This is the amount of memory remaining that the VM can allocate. public static Long totalFreeMemory() { Long freeMemory = null; try { freeMemory = totalMemoryAvailable() - memoryUsedByApp(); } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return freeMemory; } // This is the actual memory used by the VM (which may not be the total used // by the app in the case of NDK usage). public static Long memoryUsedByApp() { Long memoryUsedByApp = null; try { memoryUsedByApp = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return memoryUsedByApp; } public static Boolean lowMemoryState() { Boolean lowMemory = null; try { ActivityManager activityManager = (ActivityManager) context().getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memInfo); lowMemory = memInfo.lowMemory; } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return lowMemory; } // We might be able to improve this by checking for su, but i have seen // some reports that su is on non rooted phones too public static boolean checkIsRooted() { return checkTestKeysBuild() || checkSuperUserAPK() || executeShellCommand("which su"); } protected static boolean checkTestKeysBuild() { String buildTags = TAGS; return buildTags != null && buildTags.contains("test-keys"); } protected static boolean checkSuperUserAPK() { try { File file = new File("/system/app/Superuser.apk"); return file.exists(); } catch (final Exception e) { return false; } } // Requires android.permission.ACCESS_NETWORK_STATE public static String getNetworkStatus() { String networkStatus = null; try { // Get the network information ConnectivityManager cm = (ConnectivityManager) context().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) { if (activeNetwork.getType() == 1) { networkStatus = "wifi"; } else if (activeNetwork.getType() == 9) { networkStatus = "ethernet"; } else { // We default to cellular as the other enums are all cellular in some // form or another networkStatus = "cellular"; } } else { networkStatus = "none"; } } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return networkStatus; } @TargetApi(VERSION_CODES.CUPCAKE) public static String getGpsAllowed() { String gpsAllowed = null; try { ContentResolver cr = context().getContentResolver(); String providersAllowed = Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (providersAllowed != null && providersAllowed.length() > 0) { gpsAllowed = "allowed"; } else { gpsAllowed = "disallowed"; } } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return gpsAllowed; } public static String getPackageName() { try { return context().getPackageName(); } catch (final Exception e) { Log.w(DeviceOld.TAG, e); } return null; } public static String getAppName() { Resources appR = context().getResources(); CharSequence txt = appR.getText(appR.getIdentifier("app_name", "string", context().getPackageName())); return txt.toString(); } public static String getAppversion() { try { return context().getPackageManager().getPackageInfo(context().getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return null; } public static int getAppVersionCode() { try { return context().getPackageManager().getPackageInfo(context().getPackageName(), 0).versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return -1; } public static synchronized String getUUID() { if (uuid != null) return uuid; final SharedPreferences settings = context().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); uuid = settings.getString("userId", null); if (uuid == null) { uuid = UUID.randomUUID().toString(); // Save if for future final String finalUuid = uuid; Async.safeAsync(new Runnable() { @Override public void run() { SharedPreferences.Editor editor = settings.edit(); editor.putString("userId", finalUuid); editor.commit(); } }); } return uuid; } public static int getRotation() { return context().getWindowManager().getDefaultDisplay().getPixelFormat(); } public static int getPixelFormat() { return context().getWindowManager().getDefaultDisplay().getPixelFormat(); } public static float getRefreshRate() { return context().getWindowManager().getDefaultDisplay().getRefreshRate(); } public static Object getMobileCountryCode() { return context().getResources().getConfiguration().mcc; } public static Object getMobileNetworkCode() { return context().getResources().getConfiguration().mnc; } // region Supported Version public static String getTimeUTC(@Nullable final String format) { SimpleDateFormat dateFormatGmt = new SimpleDateFormat(format == null ? "dd:MM:yyyy HH:mm:ss" : format); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); return dateFormatGmt.format(new Date()); } public static float getDensityDpi() { if (supportsApi(14)) return getDisplayMetrics().densityDpi; else return context().getResources().getDisplayMetrics().density * 160f; } // endregion // region timebomb public static boolean supportsApi(int apiLevel) { return VERSION.SDK_INT >= apiLevel; } public static boolean checkAndroidVersion() { if (supportsApi(ANDROID_MIN_SDK_VERSION)) { AlertDialog.Builder builder = new AlertDialog.Builder(context()); builder.setMessage("Your Android OS is not officially supported. Please update your OS.") .setCancelable(false).setPositiveButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { context().finish(); } }); AlertDialog alert = builder.create(); alert.show(); return false; } return true; } public static void checkTimebombDialog() { if (ACTIVATE_TB) { final Date today = new Date(); final Date tb = new Date(); tb.setYear(mTB_Y - 1900); tb.setMonth(mTB_M - 1); tb.setDate(mTB_D); if (today.compareTo(tb) > 0) { final AlertDialog.Builder builder = new AlertDialog.Builder(context()); builder.setMessage("This version has expired. The Application will exit now.") .setCancelable(false).setPositiveButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int id) { context().finish(); } }); context().runOnUiThread(new Runnable() { @Override public void run() { final AlertDialog alert = builder.create(); alert.show(); } }); } } } public static void killApp() { android.os.Process.killProcess(android.os.Process.myPid()); } public static void restartScheduled() { // We restart the application and force to reload everything in order to clean all memory variables, etc.. Intent mStartActivity = new Intent(context(), MAIN_CLASS); int mPendingIntentId = 51459; PendingIntent mPendingIntent = PendingIntent.getActivity(context(), mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager) context().getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, mPendingIntent); System.exit(0); } public static void Restart() { Intent intent = context().getIntent(); context().finish(); context().startActivity(intent); } // region experimental public static void stuff() { //clearLog(); //saveLog(); // setContentView(R.layout.crashreport); // getThombstones(this); //readLogcat(this); // b.postDelayed(new Runnable() { // public void run() { // if (task.getStatus() == AsyncTask.Status.FINISHED) return; // // It's probably one of these devices where some fool broke logcat. // progress.dismiss(); // task.cancel(true); // new AlertDialog.Builder(JNICrashHandlerActivity.this) // .setMessage(MessageFormat.format(getString(R.string.get_log_failed), getString(R.string.author_email))) // .setCancelable(true) // .setIcon(android.R.drawable.ic_dialog_alert) // .show(); // } // }, 3000); // finish(); // Logger.v("start bugreport"); // try { // ShellUtils.doShellCommand(new String[]{"bugreport > /mnt/sdcard/bugreport.txt"}, new ShellUtils.ShellCallback() { // @Override // public void shellOut(String shellLine) { // Logger.v("doShellCommand shellOut: " + shellLine); // } // // @Override // public void processComplete(int exitValue) { // Logger.v("doShellCommand processComplete exitValue: " + exitValue); // } // },false,true); // } catch(final Exception e) { // e.printStackTrace(); // } // // Logger.v("end bugreport"); } // endregion // region Restarting app public static void clearLog() { try { ShellUtils.doShellCommand(new String[]{"logcat -c"}, new ShellUtils.ShellCallback() { @Override public void shellOut(String shellLine) { Logger.v("shellOut " + shellLine); } @Override public void processComplete(int exitValue) { Logger.v("shellOut " + exitValue); } }, false, true); } catch (final Exception e) { e.printStackTrace(); } } /* public static void readLogcat(final Activity context) { final TextView textView = (TextView) context.findViewById(R.id.reportTextView); if (textView == null) Logger.v("textview null"); final ProgressDialog progress = new ProgressDialog(context); progress.setMessage("Progress"); progress.setIndeterminate(true); progress.setCancelable(false); progress.show(); final AsyncTask task = new AsyncTask<Void, Void, Void>() { String log; Process process; @Override protected Void doInBackground(Void... v) { try { // Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept. // @see http://developer.android.com/reference/android/util/Log.html process = Runtime.getRuntime().exec(new String[]{"logcat", "-d", "-v", "threadtime"}); log = readAllOf(process.getInputStream()); context.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, "" + log, Toast.LENGTH_LONG).show(); } }); } catch (final IOException e) { e.printStackTrace(); context.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show(); } }); } return null; } @Override protected void onCancelled() { process.destroy(); } @Override protected void onPostExecute(Void v) { progress.setMessage("Sending report to backend."); if (textView != null) context.runOnUiThread(new Runnable() { @Override public void run() { textView.setText(log); } }); // boolean ok = SGTPuzzles.tryEmailAuthor(JNICrashHandlerActivity.this, true, getString(R.string.crash_preamble) + "\n\n\n\nLog:\n" + log); progress.dismiss(); // if (ok) { // if (cl.isChecked()) clearState(); // finish(); // } } }.execute(); }*/ // endregion public static String readAllOf(InputStream s) throws IOException { final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(s), 8096); String line; final StringBuilder log = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { log.append(line); log.append("\n"); } return log.toString(); } // http://bytesthink.com/blog/?p=133 // http://stackoverflow.com/questions/1083154/how-can-i-catch-sigsegv-segmentation-fault-and-get-a-stack-trace-under-jni-on // http://blog.httrack.com/blog/2013/08/23/catching-posix-signals-on-android/ public static void runAsync(final AsyncCallback<List<File>> callback) { final String cmd = "mv /data/tombstones/* " + getCachingPath(); // mv or cp final String chmod = "chmod -R 777 " + getCachingPath(); Logger.v("su " + cmd); try { ShellUtils.doShellCommand(new String[]{cmd, chmod}, new ShellUtils.ShellCallback() { @Override public void shellOut(String shellLine) { Logger.v("Shell shellOut: " + shellLine); } @Override public void processComplete(int exitValue) { Logger.v("Shell exitValue: " + exitValue); callback.onComplete(loadThombstones()); } }, true, true); } catch (final Exception e) { e.printStackTrace(); } } public static List<File> loadThombstones() { final List<File> thombstones = new ArrayList<File>(); // File thombstonesFolder = new File("/data/tombstones"); File thombstonesFolder = new File(getCachingPath()); Logger.v("Exists: " + thombstonesFolder.exists() + " is directory: " + thombstonesFolder.isDirectory() + " can be read: " + thombstonesFolder.canRead()); if (thombstonesFolder.exists() && thombstonesFolder.isDirectory() && thombstonesFolder.canRead()) Collections.addAll(thombstones, thombstonesFolder.listFiles()); return thombstones; } public static void saveLog() { /*try { File logfile = new File(SBSErrorTrackingCore.getCachePath() + "logfile.log"); logfile.createNewFile(); String cmd = "logcat -d -v threadtime -f " + logfile.getAbsolutePath(); Runtime.getRuntime().exec(cmd); } catch (IOException e) { e.printStackTrace(); }*/ Logger.v("start logcat"); String fileName = "logcat.txt"; File outputFile = new File("/mnt/sdcard/", fileName); try { Process process = Runtime.getRuntime().exec("logcat -d -v threadtime -f " + outputFile.getAbsolutePath()); } catch (final IOException e) { Logger.e(e); } Logger.v("end logcat"); } /*public static void getThombstones(final Activity context) { final ArrayList<String> thombstones = new ArrayList<String>(); final TextView textView = (TextView) context.findViewById(R.id.reportTextView); if (textView == null) Logger.v("textview null"); runAsync(new AsyncCallback() { @Override public void callback(Object o) { if (o instanceof List<?>) { List<File> list = (List<File>) o; Logger.v("Files: " + ((List) o).size()); for (File errorFile : list) { if (!errorFile.getName().startsWith("tombstone_")) continue; try { final Scanner in = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(errorFile), Charset.forName("UTF-8").newEncoder().charset()))); final StringBuffer buffer = new StringBuffer(); while (in.hasNextLine()) { buffer.append(in.nextLine()); } if (buffer.length() < 0) continue; thombstones.add(buffer.toString()); Logger.v(buffer.toString()); } catch (final Exception e) { Logger.w("Problem sending unsent error from disk", e); } } context.runOnUiThread(new Runnable() { @Override public void run() { // if(textView == null) // Logger.v("textview null again"); // else // textView.setText(thombstones.get(0)); textView.invalidate(); } }); } } }); }*/ private String getOpenGLVersion2() { Context context = DeviceOld.context(); PackageManager packageManager = context.getPackageManager(); FeatureInfo[] featureInfos = packageManager.getSystemAvailableFeatures(); if (featureInfos != null && featureInfos.length > 0) { for (FeatureInfo featureInfo : featureInfos) { // Null feature name means this feature is the open gl es version feature. if (featureInfo.name == null) { if (featureInfo.reqGlEsVersion != FeatureInfo.GL_ES_VERSION_UNDEFINED) { return String.valueOf((featureInfo.reqGlEsVersion & 0xFFFF0000) >> 16) + "." + String.valueOf((featureInfo.reqGlEsVersion & 0x0000FFFF)); } else { return "1.0"; // Lack of property means OpenGL ES version 1 } } } } return "1.0"; } protected String getPackageVersion(String packageName) { String packageVersion = null; try { PackageInfo pi = context().getPackageManager().getPackageInfo(packageName, 0); packageVersion = pi.versionName; } catch (final Exception e) { Log.w(DeviceOld.TAG, "Could not get package version", e); } return packageVersion; } protected String guessReleaseStage(String packageName) { String releaseStage = "production"; try { ApplicationInfo ai = context().getPackageManager().getApplicationInfo(packageName, 0); boolean debuggable = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; if (debuggable) { releaseStage = "development"; } } catch (final Exception e) { Log.w(DeviceOld.TAG, "Could not guess release stage", e); } return releaseStage; } // endregion } <file_sep>/deviceinfo-tests/src/net/kibotu/android/deviceinfo/DeviceTest.java package net.kibotu.android.deviceinfo; import net.kibotu.android.error.tracking.LogcatLogger; import net.kibotu.android.error.tracking.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DeviceTest extends ActivityInstrumentationImpl { @Before public void setUp() throws Exception { super.setUp(); // api 19 tests fail without setting it @see http://stackoverflow.com/questions/12267572/mockito-dexmaker-on-android System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().getPath()); Logger.init(new LogcatLogger(getActivity())); Device.init(getActivity()); } @After public void tearDown() throws Exception { super.tearDown(); } @Test public void testInit() throws Exception { try { Device.context(); assertTrue(true); } catch (final Exception e) { assertNull(e); } } @Test public void testSomething() throws Exception { } } <file_sep>/README.md Android Device Info ========================== [![Build Status](https://travis-ci.org/kibotu/net.kibotu.android.deviceinfo.svg)](https://travis-ci.org/kibotu/net.kibotu.android.deviceinfo) ### Introduction Library and app for showing tons of device information for your android device. ### How to build the lib: - `mvn package` ### How to build the app: - `git clone <EMAIL>:kibotu/net.kibotu.android.deviceinfo.git` - `git submodule update --init --recursive` - import pom.xml and run `mvn package` or `mvn install` ### Ready to use lib in /jar/deviceinfo-lib.jar ### Features ### Changelog ### Contact * [<NAME>](mailto:<EMAIL>) ### Known Issues aka To-Do - slow starting of the app and missing of a loading screen / progress bar - crashes on changing orientation - formatting for some fields are off on certain devices - icon size in actionbar is too big on tablets - cpu details only showing non idling cpu - missing of proper way to exit the app ### To-Do - settings for: - enabling / disabling error reporting - changing celcius / farenheit, cm / inch etc. - dark / light theme ### Contact **Contributers:** ### Dependancies * None for the library. ### Thanks to * [jfeinstein10](https://github.com/jfeinstein10) for [Slidemenu](https://github.com/jfeinstein10/SlidingMenu) * [JakeWharton](https://github.com/JakeWharton) for [ActionBarSherlock](https://github.com/JakeWharton/ActionBarSherlock) * [Kopfgeldjaeger](https://github.com/Kopfgeldjaeger) for [RateMeMaybe](https://github.com/Kopfgeldjaeger/RateMeMaybe) * [asystat](https://github.com/asystat) for [Final-Android-Resizer](https://github.com/asystat/Final-Android-Resizer) * [PNGQuant](https://github.com/pornel/pngquant) * [ImageMagic](https://github.com/trevor/ImageMagick) * [Facebook SDK](https://github.com/facebook/facebook-android-sdk) * [Parse.com](https://parse.com/) * [JQuery](https://github.com/jquery/jquery) * [Bootstrap](https://github.com/twbs/bootstrap) ## See also<file_sep>/deviceinfo-app/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>net.kibotu.android.deviceinfo</groupId> <artifactId>deviceinfo</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> <artifactId>deviceinfo-app</artifactId> <version>1.0</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>net.kibotu.android.deviceinfo</groupId> <artifactId>deviceinfo-lib</artifactId> <version>1.0.0</version> <scope>compile</scope> <exclusions> <exclusion> <groupId>com.google.android</groupId> <artifactId>annotations</artifactId> </exclusion> <exclusion> <groupId>com.intellij</groupId> <artifactId>annotations</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.android</groupId> <artifactId>support-v4</artifactId> <version>r7</version> </dependency> <dependency> <groupId>com.jeremyfeinstein.slidingmenu</groupId> <artifactId>slidingmenu</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.actionbarsherlock</groupId> <artifactId>actionbarsherlock</artifactId> <version>4.4.0</version> </dependency> <dependency> <groupId>org.twitter4j</groupId> <artifactId>twitter4j-core</artifactId> <version>[4.0,)</version> </dependency> <!--<dependency>--> <!--<groupId>FlurryAnalytics</groupId>--> <!--<artifactId>com.flurry.android.FlurryAgent</artifactId>--> <!--<version>4.1.0</version>--> <!--<scope>system</scope>--> <!--<systemPath>${project.basedir}/libs/FlurryAnalytics-4.1.0.jar</systemPath>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>Parse</groupId>--> <!--<artifactId>com.parse</artifactId>--> <!--<version>1.5.1</version>--> <!--<scope>system</scope>--> <!--<systemPath>${project.basedir}/libs/Parse-1.5.1.jar</systemPath>--> <!--</dependency>--> </dependencies> </project>
35c396b2a89a2d0305bc165596a6614850ad38eb
[ "Markdown", "Java", "Maven POM" ]
10
Java
A1000000/net.kibotu.android.deviceinfo
8a2947917c23d7d8e821a5b4436bc9c3115976e3
1bccefbfe0471637a5d0a78f483255138a2a0775
refs/heads/master
<repo_name>phuongy/point-break<file_sep>/src/helper/user.js import _ from 'lodash'; import Kefir from 'kefir'; import mori from 'mori'; /*---------------------------------------------------------- Permissions ----------------------------------------------------------*/ export const isAnonymous = function(user) { return mori.get(user, 'username') === ""; }; export const isAdmin = function(user) { if ( mori.get(user, 'roles') && (mori.get(user, 'roles').indexOf("Admin") != -1 || mori.get(user, 'roles').indexOf("Superuser") != -1)) { return true; } return false; }; export const hasPermission = function(user, permissions) { var roles = mori.get(user, "roles"); if (_.isUndefined(roles)) { return false; } for (var i = permissions.length - 1; i >= 0; i--) { if (roles.indexOf(permissions[i]) >= 0) { return true; } } return false; } /*---------------------------------------------------------- Computed Values ----------------------------------------------------------*/ export const getFullName = function(user) { var names = mori.get(user, 'names'); if (names && names.length && names[0].length) { return names.join(' '); } return mori.get(user, 'email'); }; const avatarColours = ['#E7965C', '#E3744E', '#E7B760', '#94BA69', '#69A6BA', '#867DC5', '#C57D9E']; // gets an avatar colour off its this users email export const getAvatarColour = function(user, index) { var hash = _.hashCode(mori.get(user, 'email')); return (index ? avatarColours[index] : avatarColours[hash % avatarColours.length]); }; // returns the short - (2 letter max) avatar ID of the user. This will use the name array by default but if that is not available, it will use the email address export const getAvatarID = function(user) { var avatarID, names = mori.get(user, 'names'), email = mori.get(user, 'email'); avatarID = (!_.isArray(names) || names.length === 0 || names[0].length === 0) ? [email] : names; avatarID = _.reduce(avatarID, function(memo, value) { return memo + value.slice(0, 1); }, ''); return avatarID; },<file_sep>/tasks/app.js var webpack = require("webpack"), webpackCompiler = webpack(require('../webpack.config')), gutil = require('gulp-util'), fs = require('fs-extra'); module.exports = function(gulp, config) { return function (callback) { webpackCompiler.run(function(err, stats) { if (err) throw new gutil.PluginError("webpack", err); gutil.log("[webpack]", stats.toString({ colors : true, assets: false, chunks: false, chunkModules : false })); callback(); }); } }; <file_sep>/src/app/index.js import 'helper/setup'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, browserHistory, IndexRoute, Redirect } from 'react-router' import { createStore, Provider } from 'store'; import { App as App, reducer as APP } from './app'; import NotFoundPage from './error/NotFoundPage.jsx'; import Alerts from 'app/alerts/Alerts'; import Discover from 'app/discover/Discover'; import NewAlert from 'app/newAlert/NewAlert'; import cookies from 'js-cookie'; // const cookie = cookies.get('pointbreak_auth'); // if (!cookie) { // window.location = 'http://192.168.2.110:4001/auth/github'; // } /*---------------------------------------------------------- Store ----------------------------------------------------------*/ const store = createStore({ APP }); window.store = store; /*---------------------------------------------------------- Root Component ----------------------------------------------------------*/ const Root = React.createClass({ propTypes: { store : React.PropTypes.object }, loadSessionAndResources: function(nextState, replace, callback) { let { dispatch, getState } = this.props.store; callback(); }, render: function() { const { store } = this.props; return ( <Provider store={store}> <Router history={browserHistory}> <Route path="/" onEnter={this.loadSessionAndResources} component={App}> <IndexRoute component={Discover}/> <Route path="discover" component={Discover} /> <Route path="alerts" component={Alerts} /> </Route> <Route path="alerts/new" component={NewAlert} /> <Route path="*" component={NotFoundPage} /> </Router> </Provider> ); } }); /*---------------------------------------------------------- Render ----------------------------------------------------------*/ ReactDOM.render( <Root store={store} />, document.getElementById('app') );<file_sep>/src/helper/setup.js /*---------------------------------------------------------- Override native promise ----------------------------------------------------------*/ // overrides native promises so we can throw unhandled exceptions within async functions. (function(Promise) { function catchException(fn) { return function(err) { if (err instanceof Error) { throw err; return; } fn(err); } } var catchProto = Promise.prototype.catch; Promise.prototype.catch = function(fn) { let catchExceptionFn = catchException(fn); return catchProto.call(this, catchExceptionFn); } })(Promise); <file_sep>/tasks/config/config.js module.exports = { dest : './build/', sass : { style: 'expanded' } }; <file_sep>/src/app/common/Nav.jsx import React from 'react'; import { Link } from 'react-router'; const Component = React.createClass({ propTypes: { currentPath: React.PropTypes.string }, render() { let { currentPath } = this.props; return <div className="nav"> <ul className="nav__nav-list"> <li className={`nav__nav-list__item ` + (currentPath === 'discover' ? `nav__nav-list__item--active` : '')}><Link to={`/discover/`}>Discover</Link></li> <li className={`nav__nav-list__item ` + (currentPath === 'alerts' ? `nav__nav-list__item--active`: '')}><Link to={`/alerts/`}>My Alerts</Link></li> </ul> </div> } }); export default Component;<file_sep>/src/store/data/schema.js // import joi from 'joi'; export const schema = { "user": { endpoint: '/user/' }, "organisation": { endpoint: '/organisation/' }, "queuedemail": { endpoint: '/queuedemail/' }, "share": { endpoint: '/share/' }, "evaluation": { endpoint: '/evaluation/' }, "survey": { endpoint: '/survey/' }, "question": { endpoint: '/question/' }, "slughash": { endpoint: '/slughash/' }, "dimension": { endpoint: '/dimension/' }, "dimension-category": { endpoint: '/dimension-category/' }, "surveyresponse": { endpoint: '/surveyresponse/' }, "questionresponse": { endpoint: '/questionresponse/' }, "customreport": { endpoint: '/customreport/' }, "datafact": { endpoint: '/datafact/' }, "traceback-report": { endpoint: '/traceback-report/' } };<file_sep>/src/app/common/inputs/SelectInput.jsx import React from 'react'; export default React.createClass({ propTypes: { options: React.PropTypes.array, className: React.PropTypes.string }, getInitialState() { return { value : this.props.value || "" }; }, handleOnChange : function(e) { var value = e.target.value; this.setState({ value }); }, render() { return <select className={`input__select ` + this.props.className} onChange={ this.handleOnChange }> {this.props.options.map(function(choice, i){ return <option value={ choice } key={ i }>{ choice }</option>; })} </select>; } });<file_sep>/src/app/discover/Discover.jsx import React from 'react'; // import CardList from 'app/discover/CardList'; const test_data = { alerts: [ { name: 'LOWER TRESTLES', beach: 'TRIGG BEACH, WA' }, { name: '<NAME>', beach: 'COTTESLOE, WA' } ] }; export default React.createClass({ getInitialState() { return test_data; }, render() { return <div className="page--create"> </div> } // renderExample() { // return <div className="page--create"> // <CardList alerts={this.state.alerts}> // </div> // } });<file_sep>/src/app/common/Header.jsx import React from 'react'; import { Link } from 'react-router'; import Icon from 'components/icons/Icon'; import Nav from 'app/common/Nav'; export default React.createClass({ propTypes: { currentPath: React.PropTypes.string }, render() { let { currentPath } = this.props; return <div className="header"> <div className="header__topzone"> <a href="#" className="header__info"></a> <div className="header__logo"> <img src="/img/logo.png" width="146" height="33" /> </div> <Link to={`/alerts/new`} className="header__add"></Link> </div> <Nav currentPath={currentPath} /> </div> } });<file_sep>/src/helper/streams.js import _ from 'lodash'; import Kefir from 'kefir'; import mori from 'mori'; /*---------------------------------------------------------- Streams ----------------------------------------------------------*/ export const streamFromPromise = function(promise) { return Kefir.stream(emitter => { promise.then(res => emitter.emit(res)).then(() => emitter.end()); }); }<file_sep>/src/app/newAlert/NewAlert.jsx import React from 'react'; import { Link } from 'react-router'; import TextInput from 'app/common/inputs/TextInput'; import SelectInput from 'app/common/inputs/SelectInput'; export default React.createClass({ propTypes: { }, render() { return <div className="newAlert"> <Link to={'/alerts'}>X</Link> <TextInput placeholder='New Alert Title' type="large" /> <div className="inputList"> <div className="inputList__item"> <label className="inputList__item__label">Activity</label> <SelectInput className="inputList__item__input" options={['Surfing', 'Fishing']} /> </div> </div> </div> } });<file_sep>/tasks/svgSprites.js var svgSprite = require('gulp-svg-sprite'), plumber = require('gulp-plumber'); var svgConfig = { mode: { inline: true, symbol: { bust: false } }, shape: { transform: ['svgo'] } }; function reportError(err) { console.log(err); }; module.exports = function(gulp, config) { return function(cb) { return gulp.src(['./src/img/icons/**/*.svg']) .pipe(plumber()) .pipe(svgSprite(svgConfig)) .on('error', reportError) .pipe(gulp.dest(config.dest + 'img/sprites')); } }<file_sep>/src/app/error/NotFoundPage.jsx import React from 'react'; import ErrorPage from './ErrorPage'; /*---------------------------------------------------------- Component ----------------------------------------------------------*/ export default React.createClass({ render: function() { return <ErrorPage detail="404 - Not Found" message="Sorry, we couldn't find the survey you were looking for." /> } });<file_sep>/src/store/session/index.js import mori from 'mori'; import _ from 'lodash'; import { callAPI } from 'store/api'; import { setResponse as setDataResponse, clear as clearData, selectData } from 'store/data'; import { createReducer, selectPath, createSelector } from 'store/utils'; /*---------------------------------------------------------- Settings ----------------------------------------------------------*/ const authURL = '/auth/local'; /*---------------------------------------------------------- Actions ----------------------------------------------------------*/ // Submit a thunk which dispatches an api call. If this call succeeds, the user model will be updated in the data store, and the authentication will be set // in the session state. export function login(email, password, remember) { return function(dispatch, getState) { let params = { url : authURL, data : { email, password, remember }, method : 'POST' }; return dispatch(callAPI(params)) .then(response => { dispatch(setDataResponse('user', [response.body.user])); dispatch(setAuthentication(response.body.auth, response.body.user.id)); return response; }); }; } // Submit a thunk which dispatches an api call. If this call succeeds, the authentication will be set in the session store and all objects in the data state will be // cleared. export function logout() { return function(dispatch, getState) { let params = { url : '/auth/logout/', method : 'GET' }; return dispatch(callAPI(params)) .then(response => { // clear the data then set the user dispatch(clearData()); dispatch(setDataResponse('user', [response.body.user])); dispatch(setAuthentication(response.body.auth, response.body.user.id)); return response; }); }; } // Get the authentication settings from the server with an `/auth/status/` call. Will insert the authenticated user into the store update the auth state with the result. export function authenticateSession() { return function(dispatch, getState) { let params = { url : '/auth/status/', method : 'GET' }; return dispatch(callAPI(params)) .then(response => { dispatch(setDataResponse('user', [response.body.user])); dispatch(setAuthentication(response.body.auth, response.body.user.id)); return response; }); }; } // Insert the the authentication const SESSION_SET_AUTHENTICATION = 'SESSION_SET_AUTHENTICATION'; export function setAuthentication(authStatus, userId) { return { type : SESSION_SET_AUTHENTICATION, payload : { authStatus, userId } }; } /*---------------------------------------------------------- Reducer ----------------------------------------------------------*/ function createInitialState() { return mori.toClj({ authStatus: 'uknown', userId: undefined }); } export const reducer = createReducer([SESSION_SET_AUTHENTICATION], function(state, action) { switch (action.type) { case SESSION_SET_AUTHENTICATION: return mori.toClj(action.payload); break; default: return state; } }, createInitialState); /*---------------------------------------------------------- Selectors ----------------------------------------------------------*/ // selects the page module export const selectSession = createSelector(selectPath('SESSION')); export const selectCurrentUserID = createSelector(state => { return mori.getIn(state, ['SESSION', 'userId']); }); // selects the current user model. export const selectCurrentUser = createSelector(state => { let userId = mori.getIn(state, ['SESSION', 'userId']); return mori.get(selectData.user(state), userId); });<file_sep>/src/helper/mori.js import _ from 'lodash'; import Kefir from 'kefir'; import mori from 'mori'; /*---------------------------------------------------------- Mori Helpers ----------------------------------------------------------*/ export function matcher(map) { return record => { for (let key in map) { if (_.isObject(map[key]) || _.isArray(map[key])) { if (matcher(map[key])(mori.get(record, key)) === false) { return false; } } else if (mori.equals(mori.get(record, `${key}`), map[key]) === false) { return false; } } return record; }; } // returns an array of records that match an objects perameters. Supports deeply nested structures export function where(map, collection) { collection = mori.isMap(collection) ? mori.vals(collection) : collection; return mori.into( mori.empty(collection), mori.filter(matcher(map), collection)); } // where but returns the first one export function find(map, collection) { collection = mori.isMap(collection) ? mori.vals(collection) : collection; return mori.some(matcher(map), collection); } // A more exciting but waaay less perfomant way of doing deep where. export function whereDeepFn(map, collection) { map = mori.toClj(map); // create a reducing function that will test each attribute let reduce = (map) => mori.reduceKV( (func, mapKey, mapValue) => { return mori.comp(func, (record) => { if (record === false ) return false; let recordValue = mori.get(record, mapKey); if (mori.isCollection(mapValue)) { return (reduce(mapValue)(recordValue) === true ? record : false); } if ( record && mori.equals(recordValue, mapValue) ) { return record; } return false; }) }, result => { return (result !== false ? true : false); }, map ); return mori.into( mori.empty(collection), mori.filter(reduce(map), collection) ); } // takes an arrays of keys, and returns the values in a hashMap that have those keys export function pluck(keys, hashMap) { let juxt = mori.juxt(...mori.take(keys.length, mori.repeat(mori.curry(mori.get, hashMap)))); return juxt(keys); } // takes an attribute from each item in a collection and returns it in an array export function pick(attr, collection) { return mori.intoArray(mori.map(record => mori.get(record, attr), collection)); } // plucks then picks export function pickAndPluck(attr, col1, col2) { return pluck(pick(attr, col1), col2) }<file_sep>/tasks/images.js module.exports = function(gulp, config) { return function(cb) { return gulp.src(['./src/img/**/*','!./src/img/**/icons/*.png', '!./src/img/**/icons/*.svg']) .pipe(gulp.dest(config.dest + 'img/')); } }<file_sep>/tasks/renderStatic.js // var rimraf = require('rimraf'); var fs = require('fs-extra') module.exports = function(gulp, config) { return function(cb) { fs.copy('./src/index.html', config.dest + 'index.html', cb); } }<file_sep>/src/store/data/index.js import _ from 'lodash'; import mori from 'mori'; // import joi from 'joi'; import { createReducer, createSelector, selectPath } from 'store/utils'; import { schema } from './schema'; import { callAPI } from 'store/api'; import { where } from 'helper/mori'; /*---------------------------------------------------------- Settings ----------------------------------------------------------*/ const data_config = { index : 'id', // the attribute to use as an index. If not set, will use the unique data id // validationSchema : _.mapValues(schema, (value) => { // return joi.object().keys(value.attributes); // }) }; /*---------------------------------------------------------- Actions ----------------------------------------------------------*/ // Inserts a new record. Accepts an object describing the record. const INSERT = 'DATA_INSERT'; export function insert(collectionName, record, sync = true) { if (mori.isCollection(record)) { record = mori.toJs(record); } return { type : INSERT, payload : { collectionName, record, sync } }; } // Creates an action which updates a single record. Accepts the id of the record and an object to update it with. const UPDATE = 'DATA_UPDATE'; export function update(collectionName, id, record, sync = true) { if (mori.isCollection(id)) { record = mori.toJs(id); id = mori.get(id, 'id'); } // Make sure to create copy of the record object with the id record = _.assign({ id }, record); let payload = {collectionName, sync, id, record }; return { type : UPDATE, payload }; } // Sets an array of records that have been passed along from the server. const SET_RESPONSE = 'DATA_SET_RESPONSE'; export function setResponse(collectionName, records) { return { type : SET_RESPONSE, payload : { collectionName, records, } }; } // Creates an action which destroys a single record. const DESTROY = 'DATA_DELETE'; export function destory(collectionName, id, sync = true) { if (mori.isCollection(id)) { id = mori.get(id, 'id'); } return { type : DESTROY, payload : { collectionName, id, sync } }; } // Creates an action which runs a query for a particular record. const FETCH = 'DATA_FETCH'; export function fetch(collectionName, query, options = {}) { let action = { type : FETCH, payload : { collectionName, query, // The force query forces the api request to append the query to the GET requests. Usually it would be removed if an ID is present forceQuery : options.forceQuery } }; // If you pass true or a function as the checkCache option, this method will first check the cache before running the action. If there is nothing in the // state, the fetch action is run. If checkCache is a function, it is treated as a selector. if (options.checkCache) { return function(dispatch, getState) { let selector = _.isFunction(options.checkCache) ? options.checkCache : createSelector(selectPath('DATA', collectionName), _.partial(where, query)); if (!getState(selector)) dispatch(action); } } return action; } // Inserts a new record. Accepts an object describing the record. const CLEAR = 'DATA_CLEAR'; export function clear() { return { type : CLEAR, payload : {} }; } /*---------------------------------------------------------- Reducer ----------------------------------------------------------*/ export const reducer = createReducer([INSERT, SET_RESPONSE, UPDATE, DESTROY, CLEAR], function(state, action) { let collectionName = action.payload.collectionName; let collection = mori.get(state, collectionName); if ( !mori.isCollection(collection) ) { throw new Error(`The collection "${collectionName}" doesn't exist in the data store. You probably tried to add to it accidently or haven't set it up in the schema`); } switch (action.type) { case INSERT: case SET_RESPONSE: case UPDATE: let records = action.payload.record || action.payload.records; records = _.isArray(records) ? records : [records]; state = mori.assoc(state, collectionName, setData(collection, records)); break; case DESTROY: state = mori.assoc(state, deleteData(collection, action.payload.id)); break; case CLEAR: state = createStructure(); break; default: return state; } return state; }, createStructure); /*---------------------------------------------------------- Lib ----------------------------------------------------------*/ // create a state structure of the collection function createStructure() { let map = []; for (let collection in schema) { map.push(collection, mori.hashMap()); } return mori.hashMap(...map); } // sets an array of records (objects) to a collection. This method will use an index if one exists, else it will create a unique data point function setData(collection, records = []) { let recordMap = mori.hashMap(); for (var i = records.length - 1; i >= 0; i--) { let record = records[i]; let id = _.get(record, data_config.index); if (!id) { id = _.uniqueId('data_'); record = _.assign({ id }, record); } recordMap = mori.assoc(recordMap, id, mori.toClj(record)); }; return mori.merge(collection, recordMap); } function deleteData(collection, id) { return mori.dissoc(collection, id); } /*---------------------------------------------------------- Middleware ----------------------------------------------------------*/ // intercepts fetch requests and makes an api call. Responses are then synced with the store. export const fetchDataMiddleware = store => next => action => { if (action.type !== FETCH) { return next(action); } // pass the action on through the chain so any other bit of middleware picks it up. next(action); let options = action.payload; let params = { url : '/api' + schema[options.collectionName].endpoint, query : options.query, method : 'GET' }; // if there is an ID just use that as the endpoint with no query if (params.query.id) { params.url += params.query.id + '/'; if (!options.forceQuery) { console.log(options.forceQuery); delete params.query; } } // dispatch the fetch call and return the promise to the dispatch function return store.dispatch(callAPI(params)) .then((response) => { // models need to be transformed let models, body; body = response.body; models = body.id ? [body] : body.results; // Add all the responses to the store by dispatching the setResponse action store.dispatch(setResponse(action.payload.collectionName, models)); return (body.id ? body: body.results); }); }; // Picks up any changes to the data cache store and syncs it back to the server. export const saveChangesMiddleware = store => next => action => { // only pick up changes to the store if the action is an insert or the sync in payload is a truthy value if ( [INSERT, UPDATE, DESTROY].indexOf(action.type) < 0 || !action.payload.sync ) { return next(action); } next(action); let params = { url : '/api' + schema[action.payload.collectionName].endpoint }; switch (action.type) { case INSERT: params.method = 'POST'; params.data = action.payload.record break case UPDATE: params.method = 'PUT'; params.data = action.payload.record params.url += action.payload.id; break case DESTROY: params.method = 'DELETE'; params.url += action.payload.id; break } // dispatch the fetch call and return the defferred promise to the dispatch function return store.dispatch(callAPI(params)) .then(response => { if ([INSERT, UPDATE].indexOf(action.type) >= 0) { store.dispatch(setResponse(action.payload.collectionName, response.body)); } else if (action.type === DESTROY) { store.dispatch(destory(action.payload.collectionName, response.body.id, false)) } return response.body; }); }; /*---------------------------------------------------------- Selectors ----------------------------------------------------------*/ // Select data const selectData = createSelector(selectPath('DATA')); // do some trickery to add each model to the select function as a method. So this is a function you can pass to createSelectors: `selectData.rows` Object.keys(schema).forEach((model) => { selectData[model] = createSelector(selectData, selectPath(model)); }); export { selectData }; /*---------------------------------------------------------- Lib ----------------------------------------------------------*/ // takes a plain object record and validates it against the schema function validate(collectionName, record) { // let error, schema = data_config.validationSchema[collectionName]; // joi.validate(record, schema, (err, value) => { // if (err) { error = err; } // }); // return (error ? error : true); return true; }<file_sep>/webpack.production.config.js /*---------------------------------------------------------- Settings ----------------------------------------------------------*/ // Main var webpack = require("webpack"); var path = require('path'); // Paths var projectRoot = process.env.PWD; // Absolute path to the project root var resolveRoot = path.join(projectRoot, 'node_modules'); // project root/node_modules var buildPath = path.resolve(__dirname, 'build/'); // Plugins var uglifyPlugin = new webpack.optimize.UglifyJsPlugin({ sourceMap: true, comments: false, compress: { dead_code: true, sequences: true, booleans: true, conditionals: true, if_return: true, join_vars: true, unused: true, warnings: true, evaluate: true, }, mangle: { toplevel: true, sort: true, properties: true }, output: { space_colon: false, comments: false } }); var settings = { // sass : { // outputStyle : (env === 'development' ? 'nested' : 'compressed') // }, // autoprefixer: { // browsers: ['> 1%', 'last 2 versions', 'IE 8', 'IE 9', 'Firefox >= 25', 'Firefox ESR', 'Opera 12.1'] // }, minify : (env === 'production'), eslint : { quiet : (env === 'production') }, devtool : (env === 'production') ? 'source-map' : 'eval-cheap-source-map' }; /*---------------------------------------------------------- Setup ----------------------------------------------------------*/ module.exports = { context: path.join(process.env.PWD, 'src'), entry: { 'app': 'app/index', }, output: { path: buildPath, filename: "[name].js" }, module: { preLoaders: [ {test: /\.jsx$/, exclude: /(node_modules|vendor)/, loader: "eslint-loader"}, {test: /\.js$/, exclude: /(node_modules|vendor)/, loader: "eslint-loader"} ], loaders: [ { test: /\.jsx$/, loaders: ['react-hot', 'babel'], exclude: /(node_modules|vendor)/ }, { test: /\.js$/, loaders: ['react-hot', 'babel'], exclude: /(node_modules|vendor)/ }, ] }, eslint: settings.eslint, resolve: { root: [ path.resolve('./src'), ], extensions: ['', '.js', '.html', '.jsx'] }, plugins: [ // Avoid publishing files when compilation failed new webpack.NoErrorsPlugin(), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"' + env + '"' } }) ].concat((env === 'production') ? [ uglifyPlugin, new webpack.optimize.OccurenceOrderPlugin() ] : []), stats: { // Nice colored output colors: true }, // // Create Sourcemaps for the bundle devtool: settings.devtool, node: { console: true } }; <file_sep>/src/app/common/inputs/TextInput.jsx import React from 'react'; export default React.createClass({ propTypes: { type: React.PropTypes.string, placeholder: React.PropTypes.string, value: React.PropTypes.string }, getInitialState : function() { return { value : this.props.value || "" }; }, handleOnChange(e) { let value = e.target.value; this.setState({ value }); }, render() { let className; switch(this.props.type) { case 'large': className = 'input__largeText'; break; case 'normal': className = 'input__text'; break; default: className = 'input__text'; } return <input type="text" onChange={ this.handleOnChange } className={className} value={this.state.value} placeholder={this.props.placeholder} /> } });<file_sep>/README.md # POINT BREAK #
f14c022569058dc36c5605eebb1bba9c8610f95e
[ "JavaScript", "Markdown" ]
22
JavaScript
phuongy/point-break
c6efafae667edf2243c880c872abedacd0849b2a
77f7edf7de44921547c7253f11dfa165992d1dd8
refs/heads/master
<file_sep>import random import time from threading import Thread from ovos_utils.intents import IntentBuilder from ovos_workshop.decorators import intent_handler from ovos_workshop.skills import OVOSSkill class EnclosureControlSkill(OVOSSkill): def initialize(self): self.thread = None self.playing = False self.animations = [] @property def crazy_eyes_animation(self): choices = [(self.enclosure.eyes_look, "d"), (self.enclosure.eyes_look, "u"), (self.enclosure.eyes_look, "l"), (self.enclosure.eyes_look, "r"), (self.enclosure.eyes_color, (255, 0, 0)), (self.enclosure.eyes_color, (255, 0, 255)), (self.enclosure.eyes_color, (255, 255, 255)), (self.enclosure.eyes_color, (0, 0, 255)), (self.enclosure.eyes_color, (0, 255, 0)), (self.enclosure.eyes_color, (255, 255, 0)), (self.enclosure.eyes_color, (0, 255, 255)), (self.enclosure.eyes_spin, None), (self.enclosure.eyes_narrow, None), (self.enclosure.eyes_on, None), (self.enclosure.eyes_off, None), (self.enclosure.eyes_blink, None)] anim = [] for i in range(0, 10): frame = random.choice(choices) anim.append(self.animate(i, 3, frame[0], frame[1])) return anim @property def up_down_animation(self): return [ self.animate(2, 6, self.enclosure.eyes_look, "d"), self.animate(4, 6, self.enclosure.eyes_look, "u"), ] @property def left_right_animation(self): return [ self.animate(2, 6, self.enclosure.eyes_look, "l"), self.animate(4, 6, self.enclosure.eyes_look, "r"), ] @staticmethod def animate(t, often, func, *args): ''' Args: t (int) : seconds from now to begin the frame (secs) often (int/string): (int) how often to repeat the frame (secs) (str) when to trigger, relative to the clock, for synchronized repetitions func: the function to invoke *args: arguments to pass to func ''' return { "time": time.time() + t, "often": often, "func": func, "args": args } @staticmethod def _get_time(often, t): return often - t % often def run(self): """ animation thread while performing speedtest """ while self.playing: for animation in self.animations: if animation["time"] <= time.time(): # Execute animation action animation["func"](*animation["args"]) # Adjust time for next loop if type(animation["often"]) is int: animation["time"] = time.time() + animation["often"] else: often = int(animation["often"]) t = animation["time"] animation["time"] = time.time() + self._get_time( often, t) time.sleep(0.1) self.thread = None self.enclosure.activate_mouth_events() self.enclosure.mouth_reset() self.enclosure.eyes_reset() def play_animation(self, animation=None): animation = animation or self.up_down_animation if not self.thread: self.playing = True # Display info on a screen self.enclosure.deactivate_mouth_events() # Build the list of animation actions to run self.animations = animation self.thread = Thread(None, self.run) self.thread.daemon = True self.thread.start() @intent_handler(IntentBuilder("SystemReboot") .require("perform").require("system").require("reboot")) def handle_system_reboot(self, message): self.speak("rebooting") self.bus.emit(message.reply("system.reboot", {})) @intent_handler(IntentBuilder("SystemUnmute") .require("system").require("unmute")) def handle_system_unmute(self, message): self.enclosure.system_unmute() self.speak("now that i have a voice, i shall not be silent") @intent_handler(IntentBuilder("SystemMute") .require("system").require("mute")) def handle_system_mute(self, message): self.speak("am i that annoying?") self.enclosure.system_mute() @intent_handler(IntentBuilder("EnclosureLookRight") .require("look").require("right") .optionally("enclosure")) def handle_look_right(self, message): self.speak("looking right") self.enclosure.eyes_look("r") @intent_handler(IntentBuilder("EnclosureLookLeft") .require("look").require("left").optionally("enclosure")) def handle_look_left(self, message): self.speak("looking left") self.enclosure.eyes_look("l") @intent_handler(IntentBuilder("EnclosureLookUp") .require("look").require("up").optionally("enclosure")) def handle_look_up(self, message): self.speak("looking up") self.enclosure.eyes_look("u") @intent_handler(IntentBuilder("EnclosureLookDown") .require("look").require("down").optionally("enclosure")) def handle_look_down(self, message): self.speak("looking down") self.enclosure.eyes_look("d") @intent_handler(IntentBuilder("EnclosureLookUpDown") .require("look").require("up") .require("down").optionally("enclosure") .optionally("animation")) def handle_look_up_down(self, message): self.speak("up and down, up and down") self.play_animation(self.up_down_animation) @intent_handler(IntentBuilder("EnclosureLookLeftRight") .require("look").require("right") .require("left").optionally("enclosure") .optionally("animation")) def handle_look_left_right(self, message): self.speak("left and right, left and right") self.play_animation(self.left_right_animation) @intent_handler(IntentBuilder("EnclosureEyesBlink") .require("blink").one_of("eyes", "animation") .optionally("enclosure").optionally("right") .optionally("left")) def handle_blink_eyes(self, message): for i in range(0, 10): if "right" in message.data: self.enclosure.eyes_blink("r") if "left" in message.data: self.enclosure.eyes_blink("l") else: self.enclosure.eyes_blink("b") self.speak("so this is what it feels like having low F P S") @intent_handler(IntentBuilder("EnclosureEyesSpin") .require("spin").one_of("eyes", "animation") .optionally("enclosure")) def handle_spin_eyes(self, message): self.speak("around the world, here i go") self.enclosure.eyes_spin() @intent_handler(IntentBuilder("EnclosureEyesNarrow") .require("narrow").require("eyes") .optionally("enclosure")) def handle_narrow_eyes(self, message): self.speak("this is my evil face") self.enclosure.eyes_narrow() self.enclosure.eyes_color(255, 0, 0) @intent_handler(IntentBuilder("EnclosureReset") .require("reset").require("enclosure")) def handle_enclosure_reset(self, message): self.enclosure.eyes_reset() self.enclosure.mouth_reset() self.speak("this was fun") @intent_handler(IntentBuilder("EnclosureMouthSmile") .require("smile").one_of("animation", "mouth") .optionally("enclosure")) def handle_enclosure_smile(self, message): self.enclosure.mouth_smile() self.speak("i don't know how to smile") @intent_handler(IntentBuilder("EnclosureMouthListen") .require("listen").one_of("animation", "mouth") .optionally("enclosure")) def handle_enclosure_listen(self, message): self.speak("when i do this i feel like I'm dancing") self.enclosure.mouth_listen() @intent_handler(IntentBuilder("EnclosureMouthThink") .require("think").one_of("animation", "mouth") .optionally("enclosure")) def handle_enclosure_think(self, message): self.speak("i love thinking") self.enclosure.mouth_think() @intent_handler(IntentBuilder("EnclosureCrazyEyes") .require("eyes").optionally("animation").require("crazy") .optionally("enclosure")) def handle_enclosure_crazy_eyes(self, message): self.speak("artificial intelligence performing artificial " "stupidity, you don't see this every day") self.play_animation(self.crazy_eyes_animation) def stop(self): if self.playing and self.thread is not None: self.playing = False self.thread.join(1) self.enclosure.activate_mouth_events() self.enclosure.eyes_reset() return True <file_sep>## Enclosure Control Controls the enclosure api vocally ## Description This skill can be used to trigger changes in the enclosure ## Examples * "look up" * "look down" * "look left" * "look right" * "look left and right" * "look up and down" * "reset enclosure" * "narrow your eyes" * "spin your eyes" * "blink your eyes" * "perform system reboot" * "system mute" * "system unmute" * "smile animation" * "listen animation" * "think animation" ## TODO * use dialog files * more animations * ssh enable/disable intents * Intents for viseme cycling / talking * fill eyes intents ## Credits JarbasAI
564f9b1679c834d517dc74b4f32391dd9330591d
[ "Markdown", "Python" ]
2
Python
JarbasSkills/skill-enclosure-ctrl
35f69bc75c1c5f55135ac0456f16a983492d80c8
fecb5e3d7297a6d99849a8fc2d72f95c1a1bafb9
refs/heads/master
<repo_name>jprando/jupyterlab<file_sep>/packages/apputils-extension/src/palette.ts /*----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ import { DisposableDelegate, IDisposable } from '@phosphor/disposable'; import { VirtualElement, h } from '@phosphor/virtualdom'; import { CommandPalette } from '@phosphor/widgets'; import { ILayoutRestorer, JupyterLab } from '@jupyterlab/application'; import { ICommandPalette, IPaletteItem } from '@jupyterlab/apputils'; /** * The command IDs used by the apputils extension. */ namespace CommandIDs { export const activate = 'apputils:activate-command-palette'; } /** * A thin wrapper around the `CommandPalette` class to conform with the * JupyterLab interface for the application-wide command palette. */ class Palette implements ICommandPalette { /** * Create a palette instance. */ constructor(palette: CommandPalette) { this._palette = palette; } /** * The placeholder text of the command palette's search input. */ set placeholder(placeholder: string) { this._palette.inputNode.placeholder = placeholder; } get placeholder(): string { return this._palette.inputNode.placeholder; } /** * Activate the command palette for user input. */ activate(): void { this._palette.activate(); } /** * Add a command item to the command palette. * * @param options - The options for creating the command item. * * @returns A disposable that will remove the item from the palette. */ addItem(options: IPaletteItem): IDisposable { let item = this._palette.addItem(options as CommandPalette.IItemOptions); return new DisposableDelegate(() => { this._palette.removeItem(item); }); } private _palette: CommandPalette; } /** * A custom renderer for the command palette that adds * `isToggled` checkmarks to the items. */ class Renderer extends CommandPalette.Renderer { /** * Render the icon element for a menu item. * * @param data - The data to use for rendering the icon. * * @returns A virtual element representing the item icon. */ renderItemIcon(data: CommandPalette.IItemRenderData): VirtualElement { let className = 'jp-CommandPalette-itemIcon'; return h.div({ className }); } /** * Render the virtual element for a command palette item. * * @param data - The data to use for rendering the item. * * @returns A virtual element representing the item. */ renderItem(data: CommandPalette.IItemRenderData): VirtualElement { let className = this.createItemClass(data); let dataset = this.createItemDataset(data); return ( h.li({ className, dataset }, this.renderItemIcon(data), this.renderItemLabel(data), this.renderItemShortcut(data), this.renderItemCaption(data) ) ); } } /** * Activate the command palette. */ export function activatePalette(app: JupyterLab, restorer: ILayoutRestorer): ICommandPalette { const { commands, shell } = app; const renderer = new Renderer(); const palette = new CommandPalette({ commands, renderer }); // Let the application restorer track the command palette for restoration of // application state (e.g. setting the command palette as the current side bar // widget). restorer.add(palette, 'command-palette'); palette.id = 'command-palette'; palette.title.label = 'Commands'; commands.addCommand(CommandIDs.activate, { execute: () => { shell.activateById(palette.id); }, label: 'Activate Command Palette' }); palette.inputNode.placeholder = 'SEARCH'; shell.addToLeftArea(palette); return new Palette(palette); }
7b36686a92d9e80361576f615c6f7b47f817a811
[ "TypeScript" ]
1
TypeScript
jprando/jupyterlab
610a2806bb883c8f150633bbe1e647a4c207e457
056f7985e6debb2ef5cf69c4b29c7c874a2654d6
refs/heads/main
<file_sep>// Higher order functions // function add(a, b) { // return a + b; // } // function operation(f, x, y) { // return f(x, y); // } // console.log( // operation( // function (a, b) { // return a / b; // }, // 2, // 3 // ) // ); // function map(f, arr) { // for (let index = 0; index < arr.length; index++) { // arr[index] = f(arr[index]); // } // return arr; // } // function multiplyBy2(x) { // return x * 2; // } // console.log(map(multiplyBy2, [1, 2, 3, 4, 5])); // function filter(arr, f) { // var array = []; // for (let i = 0; i < arr.length; i++) { // if (f(arr[i])) { // array.push(arr[i]); // } // } // return array; // } // console.log( // filter(["hello", "world", "how", "are"], function (element) { // return element.length > 3; // }) // ); // function reduce(arr, f, acc) { // for (let i = 0; i < arr.length; i++) { // acc = f(arr[i], acc); // } // return acc; // } // console.log( // reduce( // [1, 2], // function (a, b) { // return a + b; // }, // 0 // ) // ); // console.log( // reduce( // [1, 2], // function (a, b) { // return a * b; // }, // 1 // ) // ); // function filter(context, f, init) { // for (let key in context) { // if(Array.isArray(context) && f(context[key])){ // init.push(context[key]) // }else if(f(context[key])){ // init[key] = context[key] // } // } // return init; // } // setInterval(function () { // console.log("hello") // }, 2000); // setTimeout(function() { // console.log('hello later'); // }, 3000); var obj = { value: 10, output: function () { setTimeout(() => { console.log(this.value); }, 3000) } } obj.output();
3aebdf1ef4b4918267a2d3af2023652f19bb8e9d
[ "JavaScript" ]
1
JavaScript
MedTech-CS311/HOF
1492c360b8e32fbe6a2bfdc504a1a01b18f9d140
7c671077575330aac2911d45352f18729133cdef
refs/heads/main
<file_sep>package _test import ( "time" "fmt" ) //停止位 const ( //一位(常用) Stop1 byte = 1 Stop1Half byte = 15 Stop2 byte = 2 ) //校验位 const ( //无(常用) ParityNone byte = 'N' ParityOdd byte = 'O' ParityEven byte = 'E' ParityMark byte = 'M' // parity bit is always 1 ParitySpace byte = 'S' // parity bit is always 0 ) type Config struct { //端口名字 Name string //速率 Baud int//默认 115200 //超时时间 ReadTimeout time.Duration // 数据位 Size byte//默认 8位 // 校验位 Parity byte//默认 无 // 停止位 StopBits byte//默认 1位 } // ErrBadSize 错误的数据位 var ErrBadSize error = errors.New("unsupported serial data size") // ErrBadStopBits 错误的停止位 var ErrBadStopBits error = errors.New("unsupported stop bit setting") // ErrBadParity 错误的校验位 var ErrBadParity error = errors.New("unsupported parity setting") const ( //无(常用) DataSize_5 byte = 5 DataSize_6 byte = 6 DataSize_7 byte = 7 DataSize_8 byte = 8 ) func OpenPort(c *Config) (*Port, error) { size, par, stop := c.Size, c.Parity, c.StopBits if size == 0 { size = DataSize_8 } if par == 0 { par = ParityNone } if stop == 0 { stop = Stop1 } return openPort(c.Name, c.Baud, size, par, stop, c.ReadTimeout) } func main() { now := time.Now() fmt.Println(now) }<file_sep>package _10 import "fmt" import "unsafe" func main() { _int1 := 1 _int1 = 2 //指针的用法和c++差不多 //GO没有强制类型转化和编译器隐式转化 //所有类型转化必须显示 var _int_ptr *int = &_int1 fmt.Println(*_int_ptr) println("") //数据类型的强制转化 //格式1: //目标数据类型(数据) var _int2 int = int(2.0) println(_int2) println("") //!注意指针不能强制类型转化 必须要用 //指针数据类型的强制转化 //格式2: //(目标数据类型指针)unsafe.Pointer(某指针) var _int32_ptr *int32 = (*int32)(unsafe.Pointer(_int_ptr)) //int类型 != int32类型 fmt.Println(*_int32_ptr) }<file_sep>package _07 import "fmt" func main() { _int1 := 2 //switch格式1 switch (_int1) { case 0: fmt.Println("0") case 2: fmt.Println("2") default: fmt.Println("default") } fmt.Println("") //switch格式2 //fallthrough(强制执行下一个语句,很像c++没加break) switch { case _int1 == 0: fmt.Println("0") case _int1 == 2: fmt.Println("2") fallthrough default: fmt.Println("default") } fmt.Println("") //switch格式3 //通过判断数据类型 var _int2 interface {} switch _type := _int2.(type) { case nil: fmt.Println("类型:%T", _type) case int: fmt.Println("int") case func(int) float64: fmt.Println("func(int)") case bool, string: fmt.Println("bool or string") case float64: fmt.Println("float64") } fmt.Println("") } <file_sep>package main import ( "github.com/tarm/serial" "strings" "syscall" "strconv" // "os" "errors" "fmt" ) /** * @param return * * []int //可用端口编号数组 * int //可用端口数量 * **/ func Check_Serial() ([]int, int) { Serial_Name := "COM" var Serial_exists [50]int Serial_count := 0 for i := 1; i <= 50; i++ { Com_Name := (Serial_Name + strconv.Itoa(i) ) c := &serial.Config{Name: Com_Name, Baud: 115200} if SerialCom, err := serial.OpenPort(c); err != nil { } else { fmt.Printf("COM%d", i) fmt.Printf("存在\r\n") Serial_exists[Serial_count] = i Serial_count++ SerialCom.Close() } } Serial_exists_output := Serial_exists[:Serial_count] return Serial_exists_output, Serial_count } func (this *Serial_Windows)Serial_Loop(){ var err error var SerialPort *serial.Port SerialPort = nil for true { if this.Serial_state { SerialPort, err = this.Open_Serial(4, 115200) this.judgeError(err) err = this.ReadAShowSerial(SerialPort) this.judgeError(err) } else { if SerialPort != nil { SerialPort.Close() SerialPort = nil } } } } func (this *Serial_Windows)Open_Serial(Serial_index, Baud int) (*serial.Port, error) { Serial_name := "COM"+strconv.Itoa(Serial_index) temp := &serial.Config{Name: Serial_name, Baud: 115200} Serial_com, err := serial.OpenPort(temp) if err != nil { if err == syscall.ERROR_FILE_NOT_FOUND { err = errors.New("无法找到端口: " + Serial_name) } else if err == syscall.ERROR_ACCESS_DENIED { err = errors.New("端口: " + Serial_name + " 被占用") } else { err = errors.New("其他错误:" + err.Error()) } return nil, err } return Serial_com, err } func (this *Serial_Windows)ReadAShowSerial(Serial_com *serial.Port) error{ //串口读取错误 var SerialReadError error if Serial_com != nil { //临时存储变量 var words, word_all string //收到的字节数 var Rx_num int for this.Serial_state { buf := make([]byte, 1024) Rx_num, SerialReadError = Serial_com.Read(buf) if SerialReadError != nil { break } words = strings.Trim(fmt.Sprintf("%q", buf[:Rx_num]), "\"") word_all += words word_all = strings.Replace(word_all, "\\r\\n", "\r\n", -1) count := strings.Count(word_all, "\r\n") if count > 1 { this.Show_Text_On_Gui(word_all) // fmt.Printf(word_all) word_all = "" } else if count == 1{ this.Show_Text_On_Gui(word_all) // fmt.Printf(word_all) word_all = "" } } } else { SerialReadError = errors.New("端口打开错误") } return SerialReadError } func (this *Serial_Windows)judgeError (err error) { if err != nil { this.Show_Msg_Box("错误", err.Error()) } } /* func read(){ Com_Name := "COM4" c := &serial.Config{Name: Com_Name, Baud: 115200} s, err := serial.OpenPort(c) if err != nil { if err == syscall.ERROR_FILE_NOT_FOUND { fmt.Println( "无法找到端口: " + Com_Name ) } else if err == syscall.ERROR_ACCESS_DENIED { fmt.Println( "端口: " + Com_Name + " 被占用" ) } else { fmt.Print( "其他错误: ") fmt.Println( err ) } } //无法串口自动成帧 var words, word_all string file, err := os.OpenFile("./tt.txt", os.O_RDWR | os.O_APPEND | os.O_CREATE, 0666) defer file.Close() if err != nil { fmt.Println(err.Error()) } for true { buf := make([]byte, 1024) n, err := s.Read(buf) if err != nil { log.Fatal(err) } words = strings.Trim(fmt.Sprintf("%q", buf[:n]), "\"") word_all += words word_all = strings.Replace(word_all, "\\r\\n", "\r\n", -1) count := strings.Count(word_all, "\r\n") if count > 1 { fmt.Printf(word_all) // file.write(word_all) word_all = "" } else if count == 1{ // index := strings.Index(word_all, "\r\n") // fmt.Println(index) fmt.Printf(word_all) word_all = "" } } } */<file_sep>package main import ( "strings" "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) func main() { //声明两个文本域控件 var inTE, outTE *walk.TextEdit //配置主窗口,并运行起来 MainWindow{ //窗口标题 Title: "zoulee's Demo", //可拉伸的最小尺寸 MinSize: Size{620, 360}, //主布局:垂直布局 Layout: VBox{}, //窗口中的所有控件 Children: []Widget{ //水平分割器(水平小布局) HSplitter{ //局部水平排列的控件们 Children: []Widget{ //文本输入框 TextEdit{ //绑定到inTE变量 AssignTo: &inTE}, //文本输出框 TextEdit{ AssignTo: &outTE, //只读的文本框 ReadOnly: true}, }, }, //普通按钮 PushButton{ //按钮文本 Text: "Press me pls", //响应函数 OnClicked: func() { inputStr := inTE.Text() outputStr := strings.ToUpper(inputStr) outTE.SetText(outputStr) }, }, }, }.Run() }<file_sep>package main import ( "fmt" "log" "github.com/tarm/serial" "strings" "syscall" "os" ) func main() { Com_Name := "COM4" c := &serial.Config{Name: Com_Name, Baud: 115200} s, err := serial.OpenPort(c) if err != nil { if err == syscall.ERROR_FILE_NOT_FOUND { fmt.Println( "无法找到端口: " + Com_Name ) } else if err == syscall.ERROR_ACCESS_DENIED { fmt.Println( "端口: " + Com_Name + " 被占用" ) } else { fmt.Print( "其他错误: ") fmt.Println( err ) } } //无法串口自动成帧 var words, word_all string file, err := os.OpenFile("./tt.txt", os.O_RDWR | os.O_APPEND | os.O_CREATE, 0666) defer file.Close() if err != nil { fmt.Println(err.Error()) } for true { buf := make([]byte, 1024) n, err := s.Read(buf) if err != nil { log.Fatal(err) } words = strings.Trim(fmt.Sprintf("%q", buf[:n]), "\"") word_all += words word_all = strings.Replace(word_all, "\\r\\n", "\r\n", -1) count := strings.Count(word_all, "\r\n") if count > 1 { fmt.Printf(word_all) // file.write(word_all) word_all = "" } else if count == 1{ // index := strings.Index(word_all, "\r\n") // fmt.Println(index) fmt.Printf(word_all) word_all = "" } } }<file_sep>package _11 import "fmt" // import "unsafe" //结构体 //格式: /* type 变量名字 struct { 变量名字1 数据类型 变量名字2 数据类型 } */ type Books struct { title string author string subject string book_id int } func main() { var book1 Books book1.title = "Go语言新手入门" book1.author = "github.com/zoulee24/GO_NoobNote" book1.subject = "Go语言教程" book1.book_id = 876582827 fmt.Println(book1) fmt.Println("") print_Books(book1) } //结构体可以作为函数参数 //和c语言一样 func print_Books( book Books) { fmt.Printf( "Book title : %s\n", book.title) fmt.Printf( "Book author : %s\n", book.author) fmt.Printf( "Book subject : %s\n", book.subject) fmt.Printf( "Book book_id : %d\n", book.book_id) } <file_sep>package main import ( "fmt" // "string" // "github.com/lxn/walk" // . "github.com/lxn/walk/declarative" ) func main() { _, Serial_len := Check_Serial() fmt.Printf("端口数量 = %d\r\n", Serial_len) sw_run, sw := GUI_INIT() go sw.Serial_Loop() if _, err := sw_run.Run(); err != nil { fmt.Println(err) } } <file_sep>package main import ( "github.com/lxn/walk" . "github.com/lxn/walk/declarative" // "github.com/lxn/win" ) import ( // "fmt" "strings" ) const Menu1_str string = "设置" const Test1_str string = "测试" //可变 var Button1_str string = "打开端口" type Serial_Windows struct { *walk.MainWindow //菜单 action1 *walk.Action //文本框 textedit1 *walk.TextEdit //可能未来的文本框 scrollview1 *walk.ScrollView //打开关闭端口按钮 OnOffButton1 *walk.PushButton //打开端口 Serial_state bool } func GUI_INIT() (MainWindow, *Serial_Windows) { sw := new(Serial_Windows) serial_windows := (MainWindow{ AssignTo: &sw.MainWindow, Title: "串口示波器-v0.0.1", MinSize: Size{400, 300}, Size: Size{800, 600}, Layout: HBox{MarginsZero: true}, //菜单们 MenuItems: []MenuItem{ //菜单1 Menu{ Text: Menu1_str, //菜单1子项 Items: []MenuItem{ Action{ AssignTo: &sw.action1, Text: Test1_str, //回调函数 OnTriggered: func() { walk.MsgBox(sw, "点击", "菜单项1", walk.MsgBoxOKCancel) }, }, //分割线 Separator{}, Action{ Text: Test1_str, //回调函数 OnTriggered: func() { walk.MsgBox(sw, "点击", "菜单项2", walk.MsgBoxOKCancel) }, }, }, }, }, //控件们 Children: []Widget{ PushButton{ AssignTo: &sw.OnOffButton1, Text: Button1_str, StretchFactor:8, //回调函数 OnClicked: func() { sw.Serial_state = !sw.Serial_state if sw.Serial_state { sw.OnOffButton1.SetText("关闭端口") sw.textedit1.SetText(strings.ToUpper("已经打开端口\r\n")) walk.MsgBox(sw, "提示", "已经打开端口", walk.MsgBoxOK) } else { sw.OnOffButton1.SetText("打开端口") sw.textedit1.SetText(strings.ToUpper("已经关闭端口\r\n")) walk.MsgBox(sw, "提示", "已经关闭端口", walk.MsgBoxOK) } }, }, TextEdit{ // StretchFactor: 1, AssignTo: &sw.textedit1, ReadOnly: true, }, ScrollView{ AssignTo: &sw.scrollview1, Name: "test", }, }, }) return serial_windows, sw } func (this *Serial_Windows) Show_Msg_Box(title, text string) { walk.MsgBox(this, title, text, walk.MsgBoxOKCancel) } func (this *Serial_Windows) Show_Text_On_Gui(str string) error { if this.textedit1 != nil{ if err := this.textedit1.SetText(strings.ToUpper(this.textedit1.Text())+str); err != nil { return err } // if err := this.textedit1.SetText(str + "\r\n"); err != nil { // return err // } } return nil }<file_sep>package main import "fmt" type test struct { a int b int } func (t *test) get_a() int{ return t.a } func (t test) get_b() int{ t.b = 5 return t.b } func main() { tt := &test{1, 2} fmt.Println(tt) fmt.Println("") fmt.Println(tt.get_a()) fmt.Println(tt.get_b()) }<file_sep>### GOlang的学习笔记 Q1: 学习顺序: 从noob_go文件夹开始按照顺序阅读编译运行源码 Q2: 如何安装SDK: <https://golang.google.cn/dl/>或<https://golang.org/dl/> Windows选择go1.x.x.windows-amd64.msi 下载并运行 Q3: 如何运行代码: cd noob_go go run .\noob_go\xx.go Q4: package的用法: package main里面只能有一个main函数 可以有很多go文件是package main 或者 package 包名 必须放在GOPATH得src里面 不能有main函数<file_sep>package readserialcom import ( "syscall" "fmt" "os" // "errors" ) func main() { Com_Name := "COM4" filename := "\\\\.\\" + Com_Name fmt.Printf("filename = %s\n", Com_Name) h, err := syscall.CreateFile( syscall.StringToUTF16Ptr(filename), syscall.GENERIC_READ | syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL | syscall.FILE_FLAG_OVERLAPPED, 0) //如果有错误就进入 if err != nil { if err == syscall.ERROR_FILE_NOT_FOUND { fmt.Println( "无法找到端口: " + Com_Name ) } else if err == syscall.ERROR_ACCESS_DENIED { fmt.Println( "端口: " + Com_Name + " 被占用" ) } else { fmt.Print( "其他错误: ") fmt.Println( err ) } } f := os.NewFile(uintptr(h), filename) defer func() { if err != nil { f.Close() } }() }<file_sep>package main import ( "github.com/lxn/walk" ) type MainWindow struct { *walk.MainWindow } func main() { mainWnd, err := walk.NewMainWindow() if err != nil { return } mw := &MainWindow{MainWindow: mainWnd} mw.SetTitle("SocketIm Example") button1, _ := walk.NewPushButton(mw) button1.SetText("start port 8000") button1.SetX(10) button1.SetY(10) button1.SetWidth(100) button1.SetHeight(30) button1.Clicked().Attach(func() { go NewTalkWindow(mw, 8000, 8001) button1.SetEnabled(false) }) button2, _ := walk.NewPushButton(mw) button2.SetText("start port 8001") button2.SetX(10) button2.SetY(60) button2.SetWidth(100) button2.SetHeight(30) button2.Clicked().Attach(func() { go NewTalkWindow(mw, 8001, 8000) button2.SetEnabled(false) }) // mw.SetSize(walk.Size{120, 150}) mw.Show() mw.Run() }<file_sep>package main import ( "fmt" "github.com/tarm/serial" "syscall" "os" "log" "strings" // "time" "github.com/lxn/walk" ) type SerialData struct { index uint64 //下标 data float64 // } func Serial(mw *MyMainWindow) { Com_Name := "COM4" c := &serial.Config{Name: Com_Name, Baud: 115200} s, err := serial.OpenPort(c) if err != nil { if err == syscall.ERROR_FILE_NOT_FOUND { fmt.Println( "无法找到端口: " + Com_Name ) } else if err == syscall.ERROR_ACCESS_DENIED { fmt.Println( "端口: " + Com_Name + " 被占用" ) } else { fmt.Print( "其他错误: ") fmt.Println( err ) } } //无法串口自动成帧 var words, word_all string file, err := os.OpenFile("./tt.txt", os.O_RDWR | os.O_APPEND | os.O_CREATE, 0666) defer file.Close() if err != nil { fmt.Println(err.Error()) } var All_Index uint64 All_Index = 0 // ok:=false // for ok != true { // if mw.serialcanvas != nil { // sss, err := walk.NewCosmeticPen(walk.PenSolid, walk.RGB(0, 0, 0)) // if err != nil { // fmt.Println(err) // } // defer sss.Dispose() // p1, p2 := walk.Point{X: 150, Y: 456}, walk.Point{X: 245, Y: 247} // err = mw.serialcanvas.DrawLinePixels(sss, p1, p2) // p1, p2 = walk.Point{X: 150, Y: 100}, walk.Point{X: 400, Y: 400} // err = mw.serialcanvas.DrawLinePixels(sss, p1, p2) // // time.Sleep(time.Second * 5) // // mw.paintWidget.SetPaintMode(0) // if err != nil { // fmt.Println(err) // ok = false // } else { // ok = true // } // } else { // fmt.Println("serialcanvas is nil") // } // } for true { buf := make([]byte, 1024) n, err := s.Read(buf) if err != nil { log.Fatal(err) } words = strings.Trim(fmt.Sprintf("%q", buf[:n]), "\"") word_all += words word_all = strings.Replace(word_all, "\\r\\n", "\r\n", -1) count := strings.Count(word_all, "\r\n") if count > 1 { word_all_s := strings.Split(word_all,"\r\n") for _, _word := range word_all_s { index_start := strings.Index(_word, "=") if index_start != -1 { fmt.Println(_word[index_start+1:]) All_Index++ } else { fmt.Println(_word) } } word_all = "" } else if count == 1{ index_start := strings.Index(word_all, "=") index_end := strings.Index(word_all, "\r") fmt.Println(word_all[index_start+1:index_end]) word_all = "" All_Index++ } } }<file_sep>package _12 import "fmt" func main() { //数组切片 //格式1: //var 变量名字 []数据类型 = make([]数据类型, 开始, 结束) var numbers = make([]int,3,5) _int_s := []int{1, 2, 3, 4, 5} printSlice(numbers) printSlice(_int_s) //格式2: //变量名字 := 数组变量名字[开始:结束] // (很像python) _int_qp := _int_s[2:4] printSlice(_int_qp) } func printSlice(x []int){ fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x) } <file_sep>package main import ( "fmt" "ioutil" "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) type MyMainWindow struct { *walk.MainWindow te *walk.TextEdit } func main() { defer func() { if err := recover(); err != nil { errMsg := fmt.Sprintf("%#v", err) ioutil.WriteFile("fuck.log", []byte(errMsg), 0644) } }() myWindow = &MyMainWindow{model: NewEnvModel()} }<file_sep>package _03 import "fmt" //声明变量格式3: /* var{ 变量名1 数据类型 变量名2 数据类型 } */ var{ _int3 int _string3 string } func main() { //变量只能声明一次 //声明变量格式1: //var 变量名1, 变量名2 数据类型 //(不能声明的同时赋值) var _int int var _string string _int = 8 _string = "你好" fmt.Println(_int) fmt.Println(_string) //声明变量格式2: //变量名1, 变量名2 := 初始化数据(自动获取变量类型) _int2, _string2 := 10, "你好2" fmt.Println(_int2) fmt.Println(_string2) }<file_sep>package _04 import "unsafe" import "fmt" func main() { //const同c++ //只有const初始化的时候可以赋值 //const格式1: //const 变量名1, 变量名2 数据类型 const _int1 int = 10 println(_int1) //cosnt格式2:(自动获取变量类型) const ( _string1 = "zoulee" _int2 = len(_string1) _int3 = unsafe.Sizeof(_string1) ) println(_string1, _int2, _int3) //枚举1 //iota默认第一个为0 //cosnt格式2:(自动获取变量类型) const ( _int4 = iota _int5 _int6 ) println(_int4, _int5, _int6) //iota特殊例子1 const ( a = iota //0 b //1 c //2 d = "ha" //独立值,iota += 1 e //"ha" iota += 1 f = 100 //iota +=1 g //100 iota +=1 h = iota //7,恢复计数 i //8 ) fmt.Println(a,b,c,d,e,f,g,h,i) //iota特殊例子1 const ( tt1=1<<iota //左移 0 位,不变仍为 1。 tt2=3<<iota //左移 1 位,变为二进制 110,即 6。 tt3 //左移 2 位,变为二进制 1100,即 12。 tt4 //左移 3 位,变为二进制 11000,即 24。 ) fmt.Println("tt1=",tt1) fmt.Println("tt2=",tt2) fmt.Println("tt3=",tt3) fmt.Println("tt4=",tt4) }<file_sep>package main import ( "fmt" "io" "os" "strings" "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) type MyMainWindow struct { *walk.MainWindow edit *walk.TextEdit } func main() { mw := &MyMainWindow{} if err := (MainWindow{ AssignTo: &mw.MainWindow, MinSize: Size{400, 300}, Size: Size{600, 400}, MenuItems: []MenuItem{ Menu{ Text: "文件", Items: []MenuItem{ Action{ Text: "打开文件", Shortcut: Shortcut{ //定义快捷键后会有响应提示显示 Modifiers: walk.ModControl, Key: walk.KeyO, }, OnTriggered: mw.openFileActionTriggered, //点击动作触发响应函数 }, Action{ Text: "另存为", Shortcut: Shortcut{ Modifiers: walk.ModControl | walk.ModShift, Key: walk.KeyS, }, OnTriggered: mw.saveFileActionTriggered, }, Action{ Text: "退出", OnTriggered: func() { mw.Close() }, }, }, }, Menu{ Text: "帮助", Items: []MenuItem{ Action{ Text: "关于", OnTriggered: func() { walk.MsgBox(mw, "关于", "这是一个菜单和工具栏的实例", walk.MsgBoxIconInformation|walk.MsgBoxDefButton1) }, }, }, }, }, ToolBar: ToolBar{ //工具栏 ButtonStyle: ToolBarButtonTextOnly, Items: []MenuItem{ Menu{ Text: "New", Items: []MenuItem{ Action{ Text: "A", OnTriggered: mw.newAction_Triggered, }, Action{ Text: "B", OnTriggered: mw.newAction_Triggered, }, }, OnTriggered: mw.newAction_Triggered, //在菜单中不可如此定义,会无响应 }, Separator{}, //分隔符 Action{ Text: "View", OnTriggered: mw.changeViewAction_Triggered, }, }, }, Layout: VBox{}, Children: []Widget{ TextEdit{ AssignTo: &mw.edit, }, }, OnDropFiles: mw.dropFiles, //放置文件事件响应函数 }).Create(); err != nil { fmt.Fprintln(os.Stderr, err) return } mw.Run() } func (mw *MyMainWindow) openFileActionTriggered() { dlg := new(walk.FileDialog) dlg.Title = "打开文件" dlg.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*" if ok, err := dlg.ShowOpen(mw); err != nil { fmt.Fprintln(os.Stderr, "错误:打开文件时\r\n") return } else if !ok { fmt.Fprintln(os.Stderr, "用户取消\r\n") return } s := fmt.Sprintf("选择了:%s\r\n", dlg.FilePath) mw.edit.SetText(s) } func (mw *MyMainWindow) saveFileActionTriggered() { dlg := new(walk.FileDialog) dlg.Title = "另存为" dlg.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*" if ok, err := dlg.ShowSave(mw); err != nil { fmt.Fprintln(os.Stderr, err) return } else if !ok { fmt.Fprintln(os.Stderr, "取消") return } data := mw.edit.Text() filename := dlg.FilePath f, err := os.Open(filename) if err != nil { f, _ = os.Create(filename) } else { f.Close() f, err = os.OpenFile(filename, os.O_WRONLY, 0x666) } if len(data) == 0 { f.Close() return } io.Copy(f, strings.NewReader(data)) f.Close() } func (mw *MyMainWindow) newAction_Triggered() { walk.MsgBox(mw, "New", "Newing something up... or not.", walk.MsgBoxIconInformation) } func (mw *MyMainWindow) changeViewAction_Triggered() { walk.MsgBox(mw, "Change View", "By now you may have guessed it. Nothing changed.", walk.MsgBoxIconInformation) } func (mw *MyMainWindow) dropFiles(files []string) { mw.edit.SetText("") for _, v := range files { mw.edit.AppendText(v + "\r\n") } }<file_sep>package _06 import "fmt" func main() { count := 0 //for循环格式1 for true { if count > 10 { break } //报错syntax error: unexpected ++, expecting comma or ) //fmt.Println(count++) fmt.Println(count) count++ } fmt.Println("end1\n") count = 0 //for循环格式2 for count < 10 { fmt.Println(count) count++ } fmt.Println("end2\n") count = 0 //for循环格式3 for i := 0; i < 10; i++ { fmt.Println(i) } fmt.Println("end3\n") //for循环格式4 for ; count < 10; { fmt.Println(count) count++ } fmt.Println("end4\n") //for循环格式5 numbers := [6]int{1, 2, 3, 4, 5} for key, val := range numbers { fmt.Print("key: %d val: %d\n", key, val) } fmt.Println("end5\n") }<file_sep>package main import ( "log" "strconv" "fmt" // "math" ) import ( "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) type MyMainWindow struct { *walk.MainWindow paintWidget *walk.CustomWidget } //不能改变 const FORMATWIDGET int = 80 //框框宽 const FORMATHEIGHT int = 55 //框框高 //可以改变 const MAXCOUNT float64 = 10 //X轴坐标最大值 const MAXSerial int = 6000 //Y轴坐标最大值 const MINSerial int = -6000 //Y轴坐标最小值 func main() { mw := new(MyMainWindow) if _, err := (MainWindow{ AssignTo: &mw.MainWindow, Title: "坐标图-2", MinSize: Size{400, 400}, Size: Size{800, 600}, Layout: VBox{MarginsZero: true}, Children: []Widget{ CustomWidget{ AssignTo: &mw.paintWidget, ClearsBackground: true, InvalidatesOnResize: true, Paint: mw.CoordinateSystemInit, }, }, }).Run(); err != nil { log.Fatal(err) } //按关闭后才会执行(bug) a := 0 for a < 100 { fmt.Printf("a=%d\n", a) a++ } } func (mw *MyMainWindow) CoordinateSystemInit(canvas *walk.Canvas, updateBounds walk.Rectangle) error { bmp, err := createBitmap() if err != nil { return err } defer bmp.Dispose() //ClientBounds获取边界,可以随着拖动变化 bounds := mw.paintWidget.ClientBoundsPixels() bounds.X += 40 bounds.Y += 20 bounds.Width -= 60 bounds.Height -= 40 rectPen, err := walk.NewCosmeticPen(walk.PenSolid, walk.RGB(139, 69, 19)) if err != nil { return err } defer rectPen.Dispose() linePen, err := walk.NewCosmeticPen(walk.PenSolid, walk.RGB(205, 201, 201)) if err != nil { return err } defer linePen.Dispose() if err := canvas.DrawRectanglePixels(rectPen, bounds); err != nil { return err } font, err := walk.NewFont("Arial", 8, walk.FontBold) if err != nil { return err } defer font.Dispose() var lines_Width_count int var lines_Height_count int lines_Width_count = bounds.Width / FORMATWIDGET lines_Height_count = bounds.Height / FORMATHEIGHT var lines_Width []walk.Point = make([]walk.Point, lines_Width_count*2) var lines_Height []walk.Point = make([]walk.Point, lines_Height_count*2) //放置0 if err := canvas.DrawTextPixels( "0", font, walk.RGB(10, 10, 10), walk.Rectangle{X:bounds.X, Y:bounds.Y + bounds.Height, Width:25, Height:20}, walk.TextWordbreak); err != nil { return err } count := 1 for key, _ := range lines_Width { if key % 2 == 0 { lines_Width[key] = walk.Point{X: bounds.X + FORMATWIDGET*count, Y: bounds.Y } } else { lines_Width[key] = walk.Point{X: bounds.X + FORMATWIDGET*count, Y: bounds.Y + bounds.Height} if err := canvas.DrawLinePixels(linePen, lines_Width[key-1], lines_Width[key]); err != nil { return err } var nowcount_str string if int(MAXCOUNT) < bounds.Width / FORMATWIDGET { nowcount_str = strconv.FormatFloat(MAXCOUNT / float64(lines_Width_count) * float64(count), 'g', 5, 64) } else { nowcount_str = strconv.Itoa(int(MAXCOUNT) / lines_Width_count * count) } bounds_font := walk.Rectangle{X:lines_Width[key].X - len(nowcount_str)*2, Y:bounds.Y + bounds.Height, Width:35, Height:17} if err := canvas.DrawTextPixels(nowcount_str, font, walk.RGB(10, 10, 10), bounds_font, walk.TextWordbreak); err != nil { return err } count++ } } if err := canvas.DrawTextPixels( strconv.Itoa(MAXSerial), font, walk.RGB(10, 10, 10), walk.Rectangle{X:bounds.X - 23, Y:bounds.Y - 5, Width:25, Height:20}, walk.TextWordbreak); err != nil { return err } count = 0 for key, _ := range lines_Height { if key % 2 == 0 { count++ lines_Height[key] = walk.Point{X: bounds.X, Y: bounds.Y + FORMATHEIGHT*count} } else { lines_Height[key] = walk.Point{X: bounds.X + bounds.Width, Y: bounds.Y + FORMATHEIGHT*count} if err := canvas.DrawLinePixels(linePen, lines_Height[key-1], lines_Height[key]); err != nil { return err } nowserial_str := strconv.Itoa(MAXSerial - ((MAXSerial - MINSerial) / lines_Height_count) * count) bounds_font := walk.Rectangle{X:bounds.X - len(nowserial_str)*4 - 8, Y:lines_Height[key].Y - 6, Width:25, Height:20} if err := canvas.DrawTextPixels(nowserial_str, font, walk.RGB(10, 10, 10), bounds_font, walk.TextWordbreak); err != nil { return err } } } return nil } func createBitmap() (*walk.Bitmap, error) { bounds := walk.Rectangle{Width: 600, Height: 600} bmp, err := walk.NewBitmapForDPI(bounds.Size(), 192) if err != nil { return nil, err } succeeded := false defer func() { if !succeeded { bmp.Dispose() } }() // canvas, err := walk.NewCanvasFromImage(bmp) // if err != nil { // return nil, err // } // defer canvas.Dispose() succeeded = true return bmp, nil } <file_sep>package _08 import "fmt" func main() { c, d := 10, 20 var res int //例1 res = Max_1(c, d) fmt.Printf("res1=%d\n\n", res ) //例2 c, d = 100, 20 res = Max_2(c, d) fmt.Printf("res2=%d\n\n", res ) //例3 c, d = 5, 2 fmt.Printf("swap前c=%d\td=%d\n", c, d ) c, d = swap(c, d) fmt.Printf("swap后c=%d\td=%d\n\n", c, d ) //例4 show(1, "hello") } //可以有多个return //格式1 // func 函数名(变量名1, 变量名2 输入值数据类型) 返回值数据类型 func Max_1(a, b int) int { if a < b { return b } else { return a } } //Max_1 功能上等于 Max_2 func Max_2(a, b int) int { var rest int if a < b { rest = b } else { rest = a } return rest } //可以返回多个值,和pyhton很像 //格式2 // func 函数名(变量名1, 变量名2 输入值数据类型) (返回值数据类型1, 返回值数据类型2) func swap(a, b int) (int, int) { if a > b{ temp := b b = a a = temp } return a, b } //格式2 // func 函数名(变量名1, 变量名2 输入值数据类型, 变量名3 输入值数据类型) func show(a int, b string) { fmt.Println(a, b) }<file_sep>package main import ( "log" "strconv" // "fmt" // "math" ) import ( "github.com/lxn/walk" . "github.com/lxn/walk/declarative" ) type MyMainWindow struct { *walk.MainWindow paintWidget *walk.CustomWidget } const LINEWIDTHNUM int = 11 const LINEHEIGTNUM int = 8 const MAXCOUNT int = 800 const MAXSerial int = 60 const MINSerial int = -60 func main() { mw := new(MyMainWindow) if _, err := (MainWindow{ AssignTo: &mw.MainWindow, Title: "坐标图", MinSize: Size{400, 400}, Size: Size{800, 600}, MaxSize: Size{1000, 1000}, Layout: VBox{MarginsZero: true}, Children: []Widget{ CustomWidget{ AssignTo: &mw.paintWidget, ClearsBackground: true, InvalidatesOnResize: true, Paint: mw.drawStuff, }, }, }).Run(); err != nil { log.Fatal(err) } } func (mw *MyMainWindow) drawStuff(canvas *walk.Canvas, updateBounds walk.Rectangle) error { bmp, err := createBitmap() if err != nil { return err } defer bmp.Dispose() //ClientBounds获取边界,可以随着拖动变化 bounds := mw.paintWidget.ClientBoundsPixels() bounds.X += 40 bounds.Y += 20 bounds.Width -= 60 bounds.Height -= 40 //Snow3 RGB(205, 201, 201) //NewCosmeticPen()只能生成任意PEN类型和任意颜色的画笔 //不能设置宽度,默认为1 //PenSolid 实线 //PenDash 长虚线 //PenDot 短虚线 //PenDashDot 点划线 //PenDashDotDot 短线划线 //PenNull 无 //PenInsideFrame 暂无 //PenUserStyle 暂无 //PenAlternate 密集点 rectPen, err := walk.NewCosmeticPen(walk.PenSolid, walk.RGB(139, 69, 19)) if err != nil { return err } defer rectPen.Dispose() // //打印画笔宽度 // fmt.Println(rectPen.Width()) linePen, err := walk.NewCosmeticPen(walk.PenSolid, walk.RGB(205, 201, 201)) if err != nil { return err } defer linePen.Dispose() //画矩形 if err := canvas.DrawRectanglePixels(rectPen, bounds); err != nil { return err } //新建字体 //FontBold 粗体 //FontItalic 斜体 //FontUnderline 下划线 //FontStrikeOut 删除线 font, err := walk.NewFont("Times New Roman", 8, walk.FontBold) if err != nil { return err } defer font.Dispose() linsWidth := bounds.Width / LINEWIDTHNUM linsHeight := bounds.Height / LINEHEIGTNUM var lines_Width [LINEWIDTHNUM*2+1]walk.Point var lines_Height [LINEHEIGTNUM*2+1]walk.Point count := 0 for key, _ := range lines_Width { if key % 2 == 0 { lines_Width[key] = walk.Point{X: bounds.X + linsWidth*count, Y: bounds.Y } } else { lines_Width[key] = walk.Point{X: bounds.X + linsWidth*count, Y: bounds.Y + bounds.Height} if err := canvas.DrawLinePixels(linePen, lines_Width[key-1], lines_Width[key]); err != nil { return err } nowcount_str := strconv.Itoa(MAXCOUNT / LINEWIDTHNUM * count) bounds_font := walk.Rectangle{X:lines_Width[key].X - len(nowcount_str) - 5, Y:bounds.Y + bounds.Height, Width:25, Height:20} if err := canvas.DrawTextPixels(nowcount_str, font, walk.RGB(10, 10, 10), bounds_font, walk.TextWordbreak); err != nil { return err } count++ } } count = 0 for key, _ := range lines_Height { if key % 2 == 0 { lines_Height[key] = walk.Point{X: bounds.X, Y: bounds.Y + linsHeight*count} } else { lines_Height[key] = walk.Point{X: bounds.X + bounds.Width, Y: bounds.Y + linsHeight*count} if err := canvas.DrawLinePixels(linePen, lines_Height[key-1], lines_Height[key]); err != nil { return err } nowserial_str := strconv.Itoa(MAXSerial - (MAXSerial - MINSerial) / LINEHEIGTNUM * count) bounds_font := walk.Rectangle{X:bounds.X - len(nowserial_str)*4 - 8, Y:lines_Height[key].Y - 6, Width:25, Height:20} if err := canvas.DrawTextPixels(nowserial_str, font, walk.RGB(10, 10, 10), bounds_font, walk.TextWordbreak); err != nil { return err } count++ } } // //画圆的画笔 // ellipseBrush, err := walk.NewHatchBrush(walk.RGB(0, 255, 0), walk.HatchDiagonalCross) // if err != nil { // return err // } // defer ellipseBrush.Dispose() // if err := canvas.FillEllipsePixels(ellipseBrush, bounds); err != nil { // return err // } return nil } func createBitmap() (*walk.Bitmap, error) { bounds := walk.Rectangle{Width: 600, Height: 600} bmp, err := walk.NewBitmapForDPI(bounds.Size(), 192) if err != nil { return nil, err } succeeded := false defer func() { if !succeeded { bmp.Dispose() } }() // canvas, err := walk.NewCanvasFromImage(bmp) // if err != nil { // return nil, err // } // defer canvas.Dispose() succeeded = true return bmp, nil } <file_sep>package _09 import ( "fmt" ) func main() { //定义数组 //格式1: //var 变量名字 [大小]数据类型 var _floats32_s1 [5]float32 for key, _ := range _floats32_s1 { _floats32_s1[key] = float32(key) fmt.Println(_floats32_s1) } fmt.Println("") // //格式2: // //var 变量名字 = [大小]数据类型{数据1, 数据2} // var _int32_s = [3]int32{10, 1, 2} //格式3: //变量名字 := [大小]数据类型{数据1, 数据2} _floats32_s2 := [5]float32{1000.0, 2.0, 3.4, 7.0, 50.0} fmt.Println(_floats32_s2) fmt.Println("\n") //格式4: //变量名字 := [...]数据类型{数据1, 数据2} //...代表自动获取数组大小 _floats32_s3 := [...]float32{1000.0, 2.0, 3.4, 7.0, 50.0} fmt.Println(_floats32_s3) }<file_sep>package main import ( "github.com/lxn/walk" . "github.com/lxn/walk/declarative" "os" "strings" "io/ioutil" "fmt" "log" ) // 全局应用的菜单项 var myAction *walk.Action //自定义的主窗口 var myWindow *MyMainWindow //自定义窗口 type MyMainWindow struct { *walk.MainWindow te *walk.TextEdit //listbox使用的数据 model *EnvModel //listbox控件 listBox *walk.ListBox } //环境变量条目数据模型 type EnvItem struct { //环境变量的名字和值 name string value string } //列表数据模型 type EnvModel struct { //继承ListModelBase walk.ListModelBase //环境变量数集合 items []EnvItem } //列表数据模型的工厂方法 func NewEnvModel() *EnvModel { env := os.Environ() m := &EnvModel{items: make([]EnvItem, len(env))} for i, e := range env { j := strings.Index(e, "=") if j == 0 { continue } name := e[0:j] value := strings.Replace(e[j+1:], ";", "\r\n", -1) m.items[i] = EnvItem{name, value} } return m } //定义列表项目的单击监听 func (mw *MyMainWindow) lb_CurrentIndexChanged() { i := mw.listBox.CurrentIndex() item := &mw.model.items[i] mw.te.SetText(item.value) // fmt.Println("CurrentIndex: ", i) // fmt.Println("CurrentEnvVarName: ", item.name) } //定义列表项目的双击监听 func (mw *MyMainWindow) lb_ItemActivated() { value := mw.model.items[mw.listBox.CurrentIndex()].value walk.MsgBox(mw, "Value", value, walk.MsgBoxIconInformation) } //列表的系统回调方法:获得listbox的数据长度 func (m *EnvModel) ItemCount() int { return len(m.items) } //列表的系统回调方法:根据序号获得数据 func (m *EnvModel) Value(index int) interface{} { return m.items[index].name } //显示消息窗口 func ShowMsgBox(title, msg string) int { return walk.MsgBox(myWindow, "天降惊喜", "你老婆跟人跑了!", walk.MsgBoxOK) } //一个普通的事件回调函数 func TiggerFunc() { ShowMsgBox("天降惊喜", "你老婆跟人跑了!") } func main() { defer func() { if err := recover(); err != nil { errMsg := fmt.Sprintf("%#v", err) ioutil.WriteFile("fuck.log", []byte(errMsg), 0644) } }() myWindow = &MyMainWindow{model: NewEnvModel()} if _, err := (MainWindow{ AssignTo: &myWindow.MainWindow, Title: "常用控件", //窗口菜单 MenuItems: []MenuItem{ //主菜单一 Menu{ Text: "川菜", //菜单项 Items: []MenuItem{ //菜单项一 Action{ AssignTo: &myAction, Text: "鱼香肉丝", //菜单图片 Image: "img/open.png", //快捷键 Shortcut: Shortcut{walk.ModControl, walk.KeyO}, OnTriggered: func() { ShowMsgBox("已下单", "我是菜单项") }, }, //分隔线 Separator{}, //菜单项二 Action{ //文本 Text: "水煮鱼", //响应函数 OnTriggered: func() { ShowMsgBox("已下单", "您要的菜马上就去买") }, }, }, }, //主菜单二 Menu{ Text: "粤菜", //菜单项 Items: []MenuItem{ //菜单项一 Action{ Text: "鱼香肉丝", //菜单图片 Image: "img/open.png", //快捷键 Shortcut: Shortcut{walk.ModControl, walk.KeyO}, OnTriggered: func() { ShowMsgBox("已下单", "我是菜单项") }, }, //分隔线 Separator{}, //菜单项二 Action{ //文本 Text: "水煮鱼", //响应函数 OnTriggered: func() { ShowMsgBox("已下单", "您要的菜马上就去买") }, }, }, }, }, //工具栏 ToolBar: ToolBar{ //按钮风格:图片在字的前面 ButtonStyle: ToolBarButtonImageBeforeText, //工具栏中的工具按钮 Items: []MenuItem{ //引用现成的Action ActionRef{&myAction}, Separator{}, //自带子菜单的工具按钮 Menu{ //工具按钮本身的图文和监听 Text: "工具按钮2", Image: "img/document-properties.png", OnTriggered: TiggerFunc, //附带一个子菜单 Items: []MenuItem{ Action{ Text: "X", OnTriggered: TiggerFunc, }, Action{ Text: "Y", OnTriggered: TiggerFunc, }, Action{ Text: "Z", OnTriggered: TiggerFunc, }, }, }, Separator{}, //普通工具按钮 Action{ Text: "工具按钮3", Image: "img/system-shutdown.png", OnTriggered: func() { ShowMsgBox("天降惊喜", "你老婆跟人跑了!") }, }, }, }, MinSize: Size{600, 400}, Layout: VBox{}, //控件们 Children: []Widget{ //水平局部 HSplitter{ MinSize: Size{600, 300}, Children: []Widget{ ListBox{ StretchFactor: 1, //赋值给myWindow.listBox AssignTo: &myWindow.listBox, //要显示的数据 Model: myWindow.model, //单击监听 OnCurrentIndexChanged: myWindow.lb_CurrentIndexChanged, //双击监听 OnItemActivated: myWindow.lb_ItemActivated, }, TextEdit{ StretchFactor: 1, AssignTo: &myWindow.te, ReadOnly: true, }, }, }, HSplitter{ MaxSize:Size{600,50}, Children: []Widget{ //图像 ImageView{ Background: SolidColorBrush{Color: walk.RGB(255, 191, 0)}, //图片文件位置 Image: "img/open.png", //和四周的边距 Margin: 5, //定义最大拉伸尺寸 MinSize: Size{50, 50}, //显示模式 Mode: ImageViewModeZoom, }, //按钮 PushButton{ StretchFactor:8, Text: "摸我有惊喜", OnClicked: func() { ShowMsgBox("天降惊喜", "你老婆跟人跑了!") }, }, }, }, }, }.Run()); err != nil { log.Fatal(err) } }
16d64e62b9fbb9c385a0ac083d2d05f18e70bbea
[ "Markdown", "Go" ]
25
Go
zoulee24/GO_NoobNote
b7e4c7fd21bf342bd4b3180bfa1140f5a2c51305
d75840d4920902f1a631af02ac98b41bb7a0a6f3
refs/heads/master
<file_sep>package ModuleConnection; import ModuleFile.Part; import java.io.IOException; import java.rmi.Remote; import java.rmi.RemoteException; public interface IConnection extends Remote { public boolean isOn() throws RemoteException; public boolean hasPart(String id, int part) throws RemoteException; public Data getPart(Part part) throws RemoteException, IOException; } <file_sep>package ModuleSystem; import ModuleConnection.ConnectionController; import ModuleConnection.ConnectionUtilities; import ModuleFile.FileController; import ModuleSearch.SearchController; import ModuleServer.IServer; import ModuleView.MainMenu; import java.io.IOException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; public class SystemController { public static void start() { ConnectionController.init(); try { Registry registry = LocateRegistry.getRegistry(Settings.SERVER_IP); IServer stub = (IServer) registry.lookup("filetransferserver"); String ip = ConnectionUtilities.getLocalAddress().toString().substring(1); stub.initConnectionWithClient(ip); } catch(Exception e) { System.out.println("Não foi possível conectar ao servidor!"); e.printStackTrace(); } MainMenu.init(); } public static void finish() throws IOException{ ConnectionController.finish(); SearchController.finish(); } } <file_sep>package ModuleSearch; import ModuleFile.Part; import java.util.LinkedList; import java.util.Queue; public class SearchQueue extends Thread { private boolean finish; private Queue<Part> queue; public SearchQueue() { this.queue = new LinkedList<Part>(); this.finish = false; this.start(); } public void addToQueue(Part part) { synchronized (this.queue) { queue.add(part); } } public void finish() { this.finish = true; } @Override public void run() { while(!this.finish) { try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this.queue) { if(queue.size() == 0) continue; try { Part part = queue.element(); queue.remove(); SearchController.getPart(part); } catch (Exception e) { continue; } } } } } <file_sep>package ModuleServer; import java.rmi.RemoteException; public class Server implements IServer { @Override public void initConnectionWithClient(String ip) throws RemoteException { ServerController.addClient(ip); } @Override public String askForAPart(String id, int part) throws RemoteException { System.out.println("ASKING PART = " + id); return ServerController.askForAPart(id, part); } } <file_sep>package ModuleFile; import java.io.Serializable; import java.rmi.RemoteException; @SuppressWarnings("serial") public class Part implements Serializable { private String fileId; private int partId; private String hash; public Part(String fileId, int partId, String hash) throws RemoteException { this.fileId = fileId; this.partId = partId; this.hash = hash; } public String getFileId() { return this.fileId; } public int getPartId() { return this.partId; } public String getHashPart() { return this.hash; } } <file_sep>package ModuleFile; import ModuleView.MainMenu; import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.util.Formatter; import java.util.Scanner; public class FileClass { private String name; private String path; private String id; private int size; private int numParts; private boolean[] partsDownloaded; private String[] hashParts; public static final int PART_SIZE = 5000; public FileClass(String file) throws Exception { Path path = Paths.get(file); this.name = path.getFileName().toString(); this.path = path.toString(); this.id = createSha1(new File(file)); File f = new File(file); this.size = (int)f.length(); this.numParts = (this.size + PART_SIZE - 1) / PART_SIZE; this.partsDownloaded = new boolean[this.numParts]; this.hashParts = new String[this.numParts]; RandomAccessFile raf = new RandomAccessFile(this.path, "rw"); for(int i = 0; i < this.partsDownloaded.length; ++i) { this.partsDownloaded[i] = true; byte[] b; if(this.size % PART_SIZE == 0 || i != this.numParts - 1) { b = new byte[PART_SIZE]; } else { b = new byte[this.size % PART_SIZE]; } raf.read(b); this.hashParts[i] = SHAsum(b); } raf.close(); } public FileClass(String name, String path, String id, int size, int numParts, String hashParts[], boolean[] partsDownloaded) throws IOException { this.name = name; this.path = path; this.id = id; this.size = size; this.numParts = numParts; this.hashParts = hashParts; this.partsDownloaded = partsDownloaded; this.hashParts = hashParts; } public FileClass(String name, String path, String id, int size, String[] hashParts) throws IOException { this.name = name; this.path = path; this.id = id; this.size = size; this.numParts = size / PART_SIZE; if(size % PART_SIZE != 0) this.numParts++; this.partsDownloaded = new boolean[this.numParts]; this.hashParts = hashParts; this.createData(); } public void createData() throws IOException { RandomAccessFile f = new RandomAccessFile(this.path, "rw"); f.write(new byte[this.size]); f.close(); } static public String createSha1(File file) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); InputStream in = new FileInputStream(file); int n = 0; byte[] buffer = new byte[8192]; while (n != -1) { n = in.read(buffer); if (n > 0) { digest.update(buffer, 0, n); } } in.close(); return byteToHex(digest.digest()); } private static String byteToHex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String result = formatter.toString(); formatter.close(); return result; } public static String SHAsum(byte[] convertme) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); return byteArray2Hex(md.digest(convertme)); } catch (Exception e) { e.printStackTrace(); return null; } } private static String byteArray2Hex(final byte[] hash) { Formatter formatter = new Formatter(); for (byte b : hash) { formatter.format("%02x", b); } String s = formatter.toString(); formatter.close(); return s; } public void setData(byte[] data, int partId) throws IOException { RandomAccessFile f = new RandomAccessFile(this.path, "rw"); f.seek((long)partId * PART_SIZE); f.write(data); f.close(); partsDownloaded[partId] = true; MainMenu.refreshTable(); } public byte[] getData(int partId) { if(partsDownloaded[partId] == false) return null; byte[] data = null; if(this.size % PART_SIZE == 0 || partId != this.numParts - 1) { data = new byte[PART_SIZE]; } else { data = new byte[this.size % PART_SIZE]; } try { RandomAccessFile f = new RandomAccessFile(this.path, "r"); f.seek(partId * PART_SIZE); f.read(data); f.close(); } catch (Exception e) { data = null; } return data; } public boolean hasPart(int partId) { return this.partsDownloaded[partId]; } public String getHashPart(int partId) { return this.hashParts[partId]; } public double getPercentage() { double p = 0; for(int i = 0; i < this.numParts; ++i) { if(partsDownloaded[i] == true) p += 1.; } p = (p * 100. / this.numParts); return p; } public void createInfoFile(String path) throws FileNotFoundException, UnsupportedEncodingException { PrintWriter out = new PrintWriter(new File(path), "UTF-8"); String info = this.name + "\n" + this.id + "\n" + this.size + " " + this.numParts; for(int i = 0; i < this.numParts; ++i) { info += " " + hashParts[i]; } out.write(info); out.close(); } public String getInfo() { String info; info = this.name + "\n" + this.path + "\n" + this.id + "\n" + this.size + " " + this.numParts; for(int i = 0; i < this.numParts; ++i) { info += " " + hashParts[i]; } info += "\n"; return info; } public String getTorrentInfo() { String info; info = this.name + "\n" + this.id + "\n" + this.size + " " + this.numParts; for(int i = 0; i < this.numParts; ++i) { info += " " + hashParts[i]; } info += "\n"; return info; } public String getId() { return this.id; } public String getName(){ return this.name; } public String getPath(){ return this.path; } public int getSize(){ return this.size; } public boolean[] getPartsDownloaded() { return this.partsDownloaded; } static public FileClass readInfoFile(String pathInfo, String pathFile) { try { Scanner sc = new Scanner(new File(pathInfo), "UTF-8"); String name = sc.nextLine(); String id = sc.nextLine(); int size = sc.nextInt(); int numParts = sc.nextInt(); String[] hashParts = new String[numParts]; for(int i = 0; i < numParts; ++i) { hashParts[i] = sc.next(); } sc.close(); return new FileClass(name, pathFile, id, size, hashParts); } catch (Exception e) { return null; } } } <file_sep>package ModuleSearch; import ModuleConnection.ConnectionController; import ModuleConnection.Data; import ModuleFile.FileClass; import ModuleFile.FileController; import ModuleFile.Part; public class Search extends Thread { private Part part; public Search(Part part) { this.part = part; } @Override public void run() { String ip = SearchController.getRamdomClient(part); if(ip == null) { SearchController.searchQueue.addToQueue(part); return; } byte[] data = null; Data d = null; d = SearchController.getPartFromPeer(ip, part); if(d != null) { data = d.data; } if(data != null && d.partId != -1 && FileClass.SHAsum(data).compareTo(part.getHashPart()) == 0) { FileClass file = FileController.getFile(part.getFileId()); try { file.setData(data, part.getPartId()); } catch(Exception e) { addToQueue(part); } } else { addToQueue(part); } } private void addToQueue(Part part) { boolean ok = false; while(ok == false) { try { SearchController.searchQueue.addToQueue(part); ok = true; } catch (Exception e) { ok = false; } } } } <file_sep>package ModuleConnection; import java.rmi.Remote; import java.rmi.RemoteException; public interface IConnection extends Remote { public boolean isOn() throws RemoteException; public boolean hasPart(String id, int part) throws RemoteException; } <file_sep>package ModuleServer; import ModuleConnection.ConnectionUtilities; import ModuleConnection.IConnection; import ModuleServer.IServer; import ModuleServer.Server; import java.lang.reflect.Array; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.Random; import java.util.TreeSet; public class ServerController { static private Server obj; static private IServer stub; static private String ip; static private Registry registry; static public void createServer() { try { ip = ConnectionUtilities.getLocalAddress().toString().substring(1); System.out.println("Create server at ip = " + ip); System.setProperty("java.rmi.server.hostname", ip); obj = new Server(); stub = (IServer) UnicastRemoteObject.exportObject(obj, 1099); LocateRegistry.createRegistry(1099); registry = LocateRegistry.getRegistry(); registry.bind("filetransferserver", stub); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } static private final TreeSet<String> client = new TreeSet<String>(); public static TreeSet<String> getClients() { synchronized (client) { return client; } } public static void addClient(String ip) { synchronized (client) { client.add(ip); } } public static void removeClient(String ip) { synchronized (client) { client.remove(ip); } } public static void start() { System.out.println("Starting Controller"); createServer(); } public static String askForAPart(String id, int part) { ArrayList< String > hasPart = new ArrayList< String >(); synchronized (client) { for (String ip : client) { System.out.println(ip); try { Registry registry = LocateRegistry.getRegistry(ip); IConnection stub = (IConnection) registry.lookup("filetransfer"); if (stub.hasPart(id, part)) hasPart.add(ip); } catch (Exception e) { } } if (hasPart.size() == 0) return null; Random r = new Random(); return hasPart.get(r.nextInt(hasPart.size())); } } }
d2cf77b5b68e82e5643446104fe25bc1a297b781
[ "Java" ]
9
Java
juniorandrade1/TorrentProject
f5dd3ee21c5dc06acceb6dde98258cde6098a810
53f2fe835428db5c073317caabebe8d06e8ae835
refs/heads/master
<repo_name>ppedvAG/CSharp_Nuernberg_April<file_sep>/KaffeeBibliothek/Vollautomat.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KaffeeBibliothek { public class Vollautomat : MahlMaschine { public List<Milchbehälter> Milchcontainer { get; set; } public Vollautomat(string produktname, int bohnen = 500, int wasserkapazität = 1000) : base(produktname, bohnen, wasserkapazität) { Milchcontainer = new List<Milchbehälter>(); } public void BaueMilchbehälterEin(int anzahl, int kapazität = Milchbehälter.Standardkapazität) { for (int i = 0; i < anzahl; i++) { Milchcontainer.Add(new Milchbehälter(kapazität)); } } public void BefülleMilchContainer(int menge) { //Prüfen ob es reinpassen würde int restkapazität = 0; bool platzreicht = false; foreach (var milchbehälter in Milchcontainer) { //item steht für das aktuelle Objekt innerhalb der Liste, welches gerade durchlaufen wird restkapazität = restkapazität + (milchbehälter.Kapazität - milchbehälter.Milchfüllstand); if (restkapazität >= menge) { platzreicht = true; break; } } if(!platzreicht) { LöseStörungsEventAus(this, "Zu viel Milch!"); //TODO: Event } else { int restmenge = menge; //Behälter tatsächlich befüllen foreach (var milchbehälter in Milchcontainer) { //Ermittle zunächst wieviel in den jeweiligen Container eingefüllt werden muss //Je nachdem wieviel Milch noch eingefüllt werden muss, int restkapazitätImBehälter = milchbehälter.Kapazität - milchbehälter.Milchfüllstand; int einfüllmenge = Math.Min(restkapazitätImBehälter, restmenge); milchbehälter.BefülleMilch(einfüllmenge); restmenge -= einfüllmenge; if(restmenge <= 0) { break; } } } } public override bool MacheKaffee(int menge) { //Prüfe ob genug Milch vorhanden ist int vorhandeneMilch = 0; int benötigteMilch = menge; foreach (var behälter in Milchcontainer) { vorhandeneMilch += behälter.Milchfüllstand; } if(vorhandeneMilch < benötigteMilch) { LöseStörungsEventAus(this, "Zu wenig Milch!"); return false; } if(Milchcontainer.Count == 0) { return false; } if (!base.MacheKaffee(menge)) { return false; } //Milch abnehmen foreach (var milchbehälter in Milchcontainer) { int zuEntnehmendeMilch = Math.Min(benötigteMilch, milchbehälter.Milchfüllstand); milchbehälter.EntnehmeMilch(zuEntnehmendeMilch); benötigteMilch -= zuEntnehmendeMilch; if(benötigteMilch < 0) { break; } } return true; } public override string ToString() { string containerstring = "\n"; for (int i = 0; i < Milchcontainer.Count; i++) { containerstring += $"{i+1}.{Milchcontainer[i].ToString()}\n"; } return base.ToString() + containerstring; } } //Da diese Klasse vor allem vom Vollautomat benutzt wird //schreiben wir sie direkt mit in die gleiche Datei. //Sie ist aber trotzdem von überall im Projekt aus nutzbar. public class Milchbehälter { public const int Standardkapazität = 1000; /// <summary> /// in Milliliter /// </summary> public int Kapazität { get; private set; } public int Milchfüllstand { get; private set; } = 0; public Milchbehälter(int kapazität = Standardkapazität) { Kapazität = kapazität; } public void BefülleMilch(int menge) { if (Milchfüllstand + menge > Kapazität) { Milchfüllstand = Kapazität; return; } Milchfüllstand += menge; } public void EntnehmeMilch(int menge) { if(Milchfüllstand - menge < 0) { Console.WriteLine("Zu wenig Milch!"); return; } Milchfüllstand -= menge; } public override string ToString() { return $"Milchbehälter: {Milchfüllstand}/{Kapazität}"; } } } <file_sep>/LINQ_und_Lamda/Program.cs using PersonProjekt; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LINQ_und_Lamda { class Program { public delegate void DelegateTyp(int param1, int param2, ref int ergebnis); public delegate int DelegateMitIntRückgabe(int x); public delegate int DelegateMitIntRückgabeOhneParameter(); public static DateTime Geburtsdatum = new DateTime(2000, 1, 1); //public static int Property { get { return DateTime.Now.Year - Geburtsdatum.Year; } } public static int Property => DateTime.Now.Year - Geburtsdatum.Year; static void Main(string[] args) { int ergebnis = 0; DelegateTyp delegateVariable = Addiere; //=> steht für Lamda-Ausdruck, Lamda-Ausdruck beschreibt eine anonyme Methode delegateVariable += (int x, int y, ref int erg) => { erg += x * y; }; DelegateMitIntRückgabe delegateVariableMitRückgabe = x => 2 * x; DelegateMitIntRückgabeOhneParameter delegateVariableOhneParameter = () => 5; Console.WriteLine(delegateVariableOhneParameter()); Console.WriteLine(delegateVariableMitRückgabe(10)); Action<int, int, string> generischeVariable = (x, y, wort) => { int z = x + y; Console.WriteLine(wort + $" {z}"); }; generischeVariable(5, 5, "5 + 5 ="); Func<int, int, double> funcVariable = (x, y) => (double)x / y; Console.WriteLine(funcVariable(3, 5)); delegateVariable(2, 5, ref ergebnis); Console.WriteLine(ergebnis); List<Person> Personenliste = new List<Person>() { new Person("Alex", Person.Geschlechter.Männlich, new DateTime(2000, 2, 2)), new Person("Maria", Person.Geschlechter.Weiblich, new DateTime(1980, 2, 2)), new Person("Alex2", Person.Geschlechter.Männlich, new DateTime(2015, 2, 2)), new Person("Alex3", Person.Geschlechter.Männlich, new DateTime(2018, 2, 2)), new Person("Alex4", Person.Geschlechter.Männlich, new DateTime(1920, 2, 2)), new Person("Alex5", Person.Geschlechter.Männlich, new DateTime(1850, 2, 2)), }; Console.WriteLine(); List<Person> sortierteListe = Personenliste.OrderBy((Person p) => { return p.Geburtsdatum; }).ToList(); Console.WriteLine("Aufsteigend nach Geburtsdatum"); sortierteListe.ForEach(p => { Console.WriteLine(p.Name); }); Console.WriteLine("Absteigend nach Namen"); Personenliste.OrderByDescending(p => p.Name).ToList().ForEach(p => Console.WriteLine(p.Name)); Console.WriteLine("Filtere nach Frauen"); Personenliste.Where(p => p.Geschlecht == Person.Geschlechter.Weiblich).ToList().ForEach(p => Console.WriteLine(p.Name)); Console.ReadKey(); } private static void Addiere(int x, int y, ref int erg) { erg += x + y; } } } <file_sep>/Lotto/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lotto { class Program { static void Main(string[] args) { const int WERTEBEREICH = 49; const int ANZAHL_ZAHLEN = 6; while (true) { Random random = new Random(); //Arrays müssen immer eine feste Größe haben, darf nachträglich nicht //verändert werden int[] gezogeneZahlen = new int[] { -1, -1, -1, -1, -1, -1 }; int[] getippteZahlen = new int[ANZAHL_ZAHLEN]; Console.WriteLine($"Bitte geben Sie {ANZAHL_ZAHLEN} Zahlen zwischen 1 und {WERTEBEREICH} ein!"); //Zahlen einlesen, die der Nutzer tippt for (int i = 0; i < getippteZahlen.Length; i++) { Console.Write($"{i + 1}. Zahl: "); getippteZahlen[i] = int.Parse(Console.ReadLine()); } //Zufällige Gewinnzahlen generieren for (int i = 0; i < gezogeneZahlen.Length; i++) { int neueZahl; //Erst wenn die neu gerierte Zahl noch nicht //im Array enthalten ist, diese zum Array hinzufügen do { neueZahl = random.Next(1, WERTEBEREICH+1); } while (gezogeneZahlen.Contains(neueZahl)); gezogeneZahlen[i] = neueZahl; Console.WriteLine(gezogeneZahlen[i]); } //Auswertung int treffer = 0; for (int i = 0; i < gezogeneZahlen.Length; i++) { if (getippteZahlen.Contains(gezogeneZahlen[i])) { treffer++; } } Console.WriteLine($"Du hattest {treffer} Treffer"); Console.WriteLine("Möchten Sie ein weiteres Spiel spielen? y/n"); ConsoleKeyInfo gerückteTaste = Console.ReadKey(); Console.WriteLine(); if(gerückteTaste.Key == ConsoleKey.N) { break; } } } } } <file_sep>/KaffeeBibliothek/PadMaschine.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KaffeeBibliothek { public class PadMaschine : KaffeeBereiter { //Properties public bool PadVorhanden { get; set; } = false; public PadMaschine(string produktname, int wasserkapazität = 500) : base(produktname, wasserkapazität) { } public override bool MacheKaffee(int menge) { if (!PadVorhanden) { //Event LöseStörungsEventAus(this, "Kein Pad vorhanden!"); return false; } if (!base.MacheKaffee(menge)) { return false; } PadVorhanden = false; return true; } public override string ToString() { string padString = "kein Pad!"; if(PadVorhanden) { padString = "Pad vorhanden"; } return $"{base.ToString()}\n{padString}"; } } } <file_sep>/Person/Person.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonProjekt { public class Person { public enum Geschlechter { Männlich, Weiblich } public string Name { get; set; } public int Alter { get { //Alter berechnen TimeSpan span = DateTime.Now - Geburtsdatum; int year = span.Days / 365; return year; } } private Person _ehepartner; public Person Ehepartner { get { return _ehepartner; } set { //Scheidung prüfen if(value == null) { if(this._ehepartner != null) { value._ehepartner = null; } _ehepartner = null; return; } //Stand 2016: Volljährigkeit, keine Ich-Ehe, Nicht Gleichgeschlechtlich, Unverheiratet if(this.Alter < 18 || value.Alter < 18) { Console.WriteLine("Personen sind nicht beide volljährig!"); return; } if (this == value) { Console.WriteLine("Person darf sich nicht selbst heiraten!"); return; } if (this.Geschlecht == value.Geschlecht) { Console.WriteLine("Homo-Ehe (noch) verboten!"); return; } if(this.Ehepartner != null || value.Ehepartner != null ) { Console.WriteLine("Viel-Ehe!!"); return; } _ehepartner = value; value._ehepartner = this; } } public Geschlechter Geschlecht { get; private set; } //darf nur 1 Mal gesetzt werden public DateTime Geburtsdatum { get; private set; } //public string Password { private get; set; } public Person(string name, Geschlechter geschlecht, DateTime geburtsdatum) { Name = name; Geschlecht = geschlecht; Geburtsdatum = geburtsdatum; } public override string ToString() { string ehestand = "ledig"; if(Ehepartner != null) { ehestand = $" verheiratet mit {Ehepartner?.Name}"; } return $"{Name}, {Geschlecht} ({Alter}) {ehestand}"; } } } <file_sep>/KaffeeBibliothek/MahlMaschine.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KaffeeBibliothek { public class MahlMaschine : KaffeeBereiter, IMahlgutBefüllbar { /// <summary> /// in Gramm /// </summary> public int Bohnenkapazität { get; private set; } public int Bohnenfüllstand { get; private set; } = 0; public int Füllstand { get { return Bohnenfüllstand; } } public MahlMaschine(string produktname, int bohnen = 500, int wasserkapazität = 1000) : base(produktname, wasserkapazität) { Bohnenkapazität = bohnen; } public void BohnenBefüllen(int menge) { if (Bohnenfüllstand + menge > Bohnenkapazität) { Bohnenfüllstand = Bohnenkapazität; LöseStörungsEventAus(this, "Zu viele Bohnen!"); return; } Bohnenfüllstand += menge; } public override bool MacheKaffee(int menge) { if (Bohnenfüllstand < menge) { LöseStörungsEventAus(this, "Zu wenig Bohnen!"); return false; } if (!base.MacheKaffee(menge)) { return false; } Bohnenfüllstand -= menge; return true; } public override string ToString() { return $"{base.ToString()}\nBohnen: {Bohnenfüllstand}/{Bohnenkapazität} Gramm"; } public int Nachfüllen(int menge) { BohnenBefüllen(menge); return Bohnenfüllstand; } } } <file_sep>/Taschenrechner/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Taschenrechner { class Program { //man kann als Index für die Enumerator-Werte auch Chars verwenden, da diese intern ebenfalls //als Zahl abgespeichert werden (ASCII) enum Operatoren { Addition = '+', Subtraktion = '-', Multiplikation = '*', Division = '/' } static void Main(string[] args) { double ergebnis = 5; if(CalculateMitPrüfung(5, 0, Operatoren.Division, out ergebnis)) { Console.WriteLine("Ergebnis: " + ergebnis); } else { Console.WriteLine("Fehler!"); } double zahl1, zahl2; Operatoren rechenoperation; do { Console.Write("\nZahl1: "); zahl1 = double.Parse(Console.ReadLine()); Console.Write("Zahl2: "); zahl2 = double.Parse(Console.ReadLine()); Console.WriteLine("+: Addition"); Console.WriteLine("-: Subtraktion"); Console.WriteLine("*: Multiplikation"); Console.WriteLine("/: Division"); Console.Write("Geben Sie eine Rechenoperation ein: "); rechenoperation = (Operatoren)Console.ReadKey().KeyChar; } while (!CalculateMitPrüfung(zahl1, zahl2, rechenoperation, out ergebnis)); Console.WriteLine($"\nErgebnis: {ergebnis}"); int index; int erg; while (!int.TryParse(Console.ReadLine(), out erg)) { Console.WriteLine("Bitte gebe eine korrekte Zahl ein: "); } index = erg; Console.WriteLine(erg); Console.ReadKey(); } static double Calculate(double zahl1, double zahl2, Operatoren op) { switch (op) { case Operatoren.Addition: return zahl1 + zahl2; case Operatoren.Subtraktion: return zahl1 - zahl2; case Operatoren.Multiplikation: return zahl1 * zahl2; case Operatoren.Division: return zahl1 / zahl2; default: return 0; } } static bool CalculateMitPrüfung(double zahl1, double zahl2, Operatoren op, out double erg) { erg = 4; switch (op) { case Operatoren.Addition: erg = zahl1 + zahl2; break; case Operatoren.Subtraktion: erg = zahl1 - zahl2; break; case Operatoren.Multiplikation: erg = zahl1 * zahl2; break; case Operatoren.Division: if (zahl2 == 0) { Console.WriteLine("\nDivision durch Null verboten!"); return false; } erg = zahl1 / zahl2; break; default: return false; } return true; } } } <file_sep>/RateZahl/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RateZahl { class Program { static void Main(string[] args) { Random random = new Random(); int zufallszahl = random.Next(1, 11); int gerateneZahl = -1; Console.WriteLine("Rate Zahl zwischen 1 und 11"); while (gerateneZahl != zufallszahl) { gerateneZahl = int.Parse(Console.ReadLine()); if (gerateneZahl > zufallszahl) { Console.WriteLine("Zu groß!"); } else if (gerateneZahl < zufallszahl) { Console.WriteLine("Zu klein!"); } } Console.WriteLine("Richtig geraten!"); Console.ReadKey(); } } } <file_sep>/KaffeemschinenSimulator/Globals.cs using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Serialization; namespace KaffeemschinenSimulator { //interal ist der Standard-Modifier für Klassen public static class Globals { const string DATEI_NAME = "Highscore.hs"; public static Dictionary<DateTime, int> Highscore = new Dictionary<DateTime, int>(); //In diesem Dictionary könnten Daten aller Art abgespeichert werden public static Dictionary<object, object> SuperDictionary = new Dictionary<object, object>(); public static void LadeHighscore() { //Prüfen ob die Datei überhaupt existiert if(File.Exists(DATEI_NAME)) { StreamReader reader = new StreamReader(DATEI_NAME); string jsonString = reader.ReadToEnd(); Highscore = JsonConvert.DeserializeObject<Dictionary<DateTime, int>>(jsonString); reader.Close(); } } public static void ZeigeHighscore() { string ausgabe = ""; //Liste nach Score sortieren und nur die ersten 10 Ergebnisse selektieren var geordneteListe = Highscore.OrderByDescending(datensatz => datensatz.Value).Take(10).ToList(); foreach (var datensatz in geordneteListe) { //01.05.2018 15:20 => 4 Punkte ausgabe += $"{datensatz.Key.ToShortDateString()} => {datensatz.Value} Punkte\n"; } MessageBox.Show(ausgabe); } public static void FügeHighscoreHinzu(int highscore) { Highscore.Add(DateTime.Now, highscore); //Highscore in eine Datei abspeichern //zweite Parameter steht dafür, ob der neue Inhalt ans Ende der Datei angefügt werden soll //d.h. bei false wird die Datei stattdessen komplett überschrieben StreamWriter writer = new StreamWriter(DATEI_NAME, false); JsonSerializerSettings settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Objects; string jsonString = JsonConvert.SerializeObject(Highscore, settings); writer.Write(jsonString); writer.Close(); //TODO: in XML umwandeln //var jsonAsXML = JsonConvert.DeserializeXNode(jsonString, "Highscore"); //StreamWriter writerXml = new StreamWriter("Highscore.xml", false); //writerXml.Write(jsonAsXML.ToString()); //writerXml.Close(); } } } <file_sep>/KaffeemschinenSimulator/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using KaffeeBibliothek; namespace KaffeemschinenSimulator { public partial class Form1 : Form { enum Kaffeearten { Espresso, Cappuccino, Filterkaffee } PadMaschine espressoMaschine; Vollautomat cappuccinoMaschine; MahlMaschine filterkaffeeMaschine; KaffeeBereiter aktuelleMaschine; const int COUNTDOWN_START = 60; int countdown = 60; int score = 0; int gewünschteMengeFürBestellung = 0; Kaffeearten gewünschteKaffeeartFürBestellung; Random random; //Konstruktor public Form1() { InitializeComponent(); random = new Random(); listboxKaffeemaschine.Items.Add(Kaffeearten.Filterkaffee); listboxKaffeemaschine.Items.Add(Kaffeearten.Espresso); listboxKaffeemaschine.Items.Add(Kaffeearten.Cappuccino); espressoMaschine = new PadMaschine("Nespresso"); cappuccinoMaschine = new Vollautomat("Cappu-Deluxe"); cappuccinoMaschine.BaueMilchbehälterEin(3, 300); filterkaffeeMaschine = new MahlMaschine("Melitta"); //Event-Registrierung espressoMaschine.Störung += StörungsBehandlung; cappuccinoMaschine.Störung += StörungsBehandlung; filterkaffeeMaschine.Störung += StörungsBehandlung; labelCountdown.Text = COUNTDOWN_START.ToString(); //Erste Bestellung erstellen NeueBestellungErstellen(); } private void NeueBestellungErstellen() { //Zufällige Kaffeeart auswählen gewünschteKaffeeartFürBestellung = (Kaffeearten)random.Next(3); //Zufällige Menge gewünschteMengeFürBestellung = random.Next(1, 5) * 100; labelBestellung.Text = $"{gewünschteMengeFürBestellung} ml {gewünschteKaffeeartFürBestellung} bitte!"; } private void StörungsBehandlung(object sender, string störungsmeldung) { timerStörung.Stop(); labelStörung.Text = $"{störungsmeldung}\nbei {((KaffeeBereiter)sender).Produktname}"; if(score > 0) { score--; labelScore.Text = $"Score: {score}"; } timerStörung.Start(); } //Event-Handler, Ergeinisbehandlungsmethode private void listboxKaffeemaschine_SelectedIndexChanged(object sender, EventArgs e) { if (listboxKaffeemaschine.SelectedItem == null) return; Kaffeearten art = (Kaffeearten)listboxKaffeemaschine.SelectedItem; switch (art) { case Kaffeearten.Espresso: aktuelleMaschine = espressoMaschine; break; case Kaffeearten.Cappuccino: aktuelleMaschine = cappuccinoMaschine; break; case Kaffeearten.Filterkaffee: aktuelleMaschine = filterkaffeeMaschine; break; } //Beschreibung der aktuellen Maschine anzeigen labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } private void button1Wasser_Click(object sender, EventArgs e) { if (aktuelleMaschine == null) return; int zubefüllendeMenge = 0; try { zubefüllendeMenge = int.Parse(textBoxWassermenge.Text); } catch (OverflowException) { MessageBox.Show("Bist du verrückt? Möchtest du die Küche fluten???!"); return; } catch (FormatException) { MessageBox.Show("Deine eingebene Wassermenge ist keine gültige ganze Zahl!"); return; } catch (Exception exp) { MessageBox.Show(exp.Message); return; } //Wird sogar dann ausgeführt, wenn die Methode im Try-Catch-Block abgebrochen wird finally { textBoxWassermenge.Focus(); textBoxWassermenge.SelectAll(); } aktuelleMaschine.WasserFüllen(zubefüllendeMenge); labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } private void textBoxWassermenge_KeyUp_1(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Enter) { button1Wasser_Click(this, EventArgs.Empty); } } private void button2_Click(object sender, EventArgs e) { if (aktuelleMaschine is PadMaschine) { //as hat den gleichen Effekt wie (PadMaschine)aktuelleMaschine //Einziger Unterschied: Wenn das Casting fehlschlägt, stürzt //das Programm nicht ab, sondern es wird null zurückgegeben PadMaschine padmaschine = aktuelleMaschine as PadMaschine; if (padmaschine.PadVorhanden) { MessageBox.Show("Da liegt schon ein Pad drin!"); } else { padmaschine.PadVorhanden = true; labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } } else { MessageBox.Show("Das ist keine PadMaschine!"); } } private void button3_Click(object sender, EventArgs e) { if (aktuelleMaschine != null && aktuelleMaschine.MacheKaffee(gewünschteMengeFürBestellung)) { if(gewünschteKaffeeartFürBestellung != (Kaffeearten)listboxKaffeemaschine.SelectedItem) { StörungsBehandlung(this, "Falsche Kaffeeart!"); return; } //100 ml Kaffee ergeben 1 Punkt score += gewünschteMengeFürBestellung / 100; labelScore.Text = $"Score: {score}"; NeueBestellungErstellen(); timerCountdown.Start(); labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } } private void button4Bohnen_Click(object sender, EventArgs e) { if (!(aktuelleMaschine is IMahlgutBefüllbar)) return; int zubefüllendeMenge = 0; try { zubefüllendeMenge = int.Parse(textBoxBohnen.Text); } catch (OverflowException) { MessageBox.Show("Hast du eine Kaffeeplantage überfallen??!"); return; } catch (FormatException) { MessageBox.Show("Deine eingegebene Bohnenmenge ist keine gültige ganze Zahl!"); return; } catch (Exception exp) { MessageBox.Show(exp.Message); return; } //Wird sogar dann ausgeführt, wenn die Methode im Try-Catch-Block abgebrochen wird finally { textBoxBohnen.Focus(); textBoxBohnen.SelectAll(); } IMahlgutBefüllbar befüllbaresObjekt = (IMahlgutBefüllbar)aktuelleMaschine; befüllbaresObjekt.Nachfüllen(zubefüllendeMenge); labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } //Wird ausgeführt, sobald 3000 Millisekunden vergangen sind private void timerStörung_Tick(object sender, EventArgs e) { labelStörung.Text = string.Empty; //entspricht "" timerStörung.Stop(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { timerStörung.Stop(); } private void timerCountdown_Tick(object sender, EventArgs e) { countdown--; labelCountdown.Text = $"{countdown} Sekunden"; if (countdown == 0) { timerCountdown.Stop(); MessageBox.Show($"Game Over!\nScore: {score}!"); Globals.FügeHighscoreHinzu(score); countdown = 10; score = 0; labelCountdown.Text = $"{COUNTDOWN_START} Sekunden"; labelScore.Text = "Score: 0"; } } private void button5_Click(object sender, EventArgs e) { Form1 neuesFormular = new Form1(); neuesFormular.Show(); } private void button6_Click(object sender, EventArgs e) { Globals.ZeigeHighscore(); } private void beendenToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void button7Milch_Click(object sender, EventArgs e) { //nur Vollautomaten können Milch befüllen if (!(aktuelleMaschine is Vollautomat)) return; int zubefüllendeMenge = 0; try { zubefüllendeMenge = int.Parse(textBoxMilch.Text); } catch (OverflowException) { MessageBox.Show("So viel Milch braucht kein Mensch!"); return; } catch (FormatException) { MessageBox.Show("Deine eingegebene Milchmenge ist keine gültige ganze Zahl!"); return; } catch (Exception exp) { MessageBox.Show(exp.Message); return; } //Wird sogar dann ausgeführt, wenn die Methode im Try-Catch-Block abgebrochen wird finally { textBoxBohnen.Focus(); textBoxBohnen.SelectAll(); } Vollautomat vollautomat = (Vollautomat)aktuelleMaschine; vollautomat.BefülleMilchContainer(zubefüllendeMenge); labelMaschinenBeschreibung.Text = aktuelleMaschine.ToString(); } } } <file_sep>/KaffeeBibliothekTest/UnitTest1.cs using System; using KaffeeBibliothek; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace KaffeeBibliothekTest { [TestClass] public class VollautomatenTests { [TestMethod] public void TestMilchbefüllung() { Vollautomat testautomat = new Vollautomat("XYZ"); //3 Behälter mit jeweils einem Liter Fassungsvermögen testautomat.BaueMilchbehälterEin(3); testautomat.BefülleMilchContainer(2500); if(testautomat.Milchcontainer[0].Milchfüllstand != 1000) { Assert.Fail(); } Assert.AreEqual(1000, testautomat.Milchcontainer[1].Milchfüllstand); Assert.AreEqual(500, testautomat.Milchcontainer[2].Milchfüllstand); } } } <file_sep>/HelloWorld/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorld { class Program { static void Main(string[] args) { //Ohne Using-Anweisungen muss man den vollständigen Namespace-Pfad, //zu der eine Klasse gehört, immer dazuschreiben System.Console.Write("Hello World!\n"); Console.WriteLine("Bitte geben Sie Ihren Namen ein: "); string name = Console.ReadLine(); Console.Write("Alter: "); int alter = int.Parse(Console.ReadLine()); int alter2 = 10; Console.Write("Größe: "); double größe = double.Parse(Console.ReadLine()); Console.WriteLine($"\n{name} ist {alter} Jahre alt und {größe:00.00} Meter groß!"); //Erwartete Ausgabe: Durchschnitt von 20 und 10 ergibt 15 double durchschnittsalter = (alter + alter2) / (double)2; Console.WriteLine($"Durchschnittsalter von {alter2} und {alter}: {durchschnittsalter}"); //Snippets anzeigen: Strg+Leertaste //Console.WriteLine: cw + Tab + Tab Console.WriteLine(); Console.ReadKey(); } } }<file_sep>/KaffeeBibliothek/KaffeeBereiter.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KaffeeBibliothek { public abstract class Maschine { public int Preis { get; set; } public string Name { get; set; } public override string ToString() { return $"{Name}, Preis: {Preis}"; } //abstrakte Methoden geben die Signatur vor, die Implementierung //muss in den abgeleiteten Klassen erfolgen public abstract void MachWas(); } public class KaffeeBereiter : Maschine { //Events public delegate void StörungsEventDelegate(object sender, string störungsmeldung); //Am Anfang zeigt die Variable auf keine Methode, da sich noch niemand dafür registriert hat public event StörungsEventDelegate Störung = null; protected void LöseStörungsEventAus(object sender, string störungsmeldung) { Störung?.Invoke(sender, störungsmeldung); } //Properties /// <summary> /// in Millilitern /// </summary> public int Wasserkapazität { get; private set; } //Snippet: propfull private int _wasserstand; public int Wasserstand { get { return _wasserstand; } set { if(value > Wasserkapazität || value < 0) { //TODO: Durch Exception oder Event ersetzen! Störung?.Invoke(this, "Wasser läuft über!"); _wasserstand = Wasserkapazität; return; } _wasserstand = value; } } public string Produktname { get; private set; } //Konstruktor public KaffeeBereiter(string produktname, int wasserkapazität = 1000) { Wasserkapazität = wasserkapazität; Produktname = produktname; Wasserstand = 0; } //Sonstige Methoden public void WasserFüllen(int menge) { Wasserstand = Wasserstand + menge; } //virtual: Kinderklassen dürfen diese Methode überschreiben (neu definieren) public virtual bool MacheKaffee(int menge) { if(Wasserstand < menge) { //Event if(Störung != null) { Störung(this, "Nicht genügend Wasser vorhanden!"); } //Kurzversion //Störung?.Invoke(this, "Nicht genügend Wasser vorhanden!"); return false; } Wasserstand -= menge; return true; } public override void MachWas() { MacheKaffee(500); } public override string ToString() { return $"{Produktname}\n\nWasserstand: {Wasserstand}/{Wasserkapazität} ml"; } } } <file_sep>/KaffeeBibliothek/IMahlgutBefüllbar.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KaffeeBibliothek { public interface IMahlgutBefüllbar { /// <summary> /// In ein Behälter etwas einfüllen /// </summary> /// <param name="menge">Die Menge des zu Befüllenden Mahlguts</param> /// <returns>Der Füllstand nach der Befüllung</returns> int Nachfüllen(int menge); int Füllstand { get; } } }
055be92744a7b2d17dd34b96385e04390b933be0
[ "C#" ]
14
C#
ppedvAG/CSharp_Nuernberg_April
d081ea14c19fd039e47505f6ac4a6b8aecc9867a
8c9d511e753881c8ccc71a5a64c52179dfa6209d
refs/heads/master
<file_sep>"use strict" // 1 let submissions = [ { name: "jane", score: 95, date: "2020-01-24", passed: true, }, { name: "joe", score: 77, date: "2018-05-14", passed: true, }, { name: "jack", score: 59, date: "2019-07-05", passed: false, }, { name: "jill", score: 88, date: "2020-04-22", passed: true, }, ]; // 2 const addSubmission = (array, newName, newScore, newDate) => { let newSubmission = { name: newName, score: newScore, date: newDate, passed: newScore >= 60, }; array.push(newSubmission); } addSubmission(submissions, "amanda", 50, "2020-02-20"); console.log(submissions); // 3 const deleteSubmissionByIndex = (array, index) => { array.splice(index,1); }; // 4 const deleteSubmissionByName = (array, name) => { let targetedIndex = array.findIndex((person) =>{ return person.name === name; }); array.splice(targetedIndex,1); }; // 5 const editSubmission = (array, index, updatedScore) => { array[index].score = updatedScore; array[index].passed = updatedScore >=60 ? true : false; } editSubmission(submissions,2,58); console.log(submissions); // 6 const findSubmissionByName = (array, name) => { let found = array.find((item) => { return item.name === name; }); return found; } console.log(findSubmissionByName(submissions,"jane")); // 7 const letLowestScore = (array) => { let lowestScore = array [0]; array.forEach((person)=> { if(person.score<lowestScore.score){ lowestScore= person; } }); return lowestScore }; console.log(letLowestScore(submissions)); // 8 const findAverageScore = (array) =>{ let sum=0; let counter=0; for(let item of array){ sum += item.score counter++}; return sum/counter; }; console.log(findAverageScore(submissions)); // 9 const filterPassing = (array) =>{ let scores = array.filter((percent) =>{ return percent.score >= 60; }); return scores; }; console.log(filterPassing(submissions)); // 10 const filter90AndAbove = (array) => { let scores = array.filter((percent) =>{ return percent.score >= 90; }); return scores; }; console.log(filter90AndAbove(submissions));
d5635301c7f3195ab5cb6c9273d71b69eac21794
[ "JavaScript" ]
1
JavaScript
amanda-armbruster/Lab---Student-Submissions
02e9bce24dd8fe5ae4459ddbdf022dc0b3f6b319
f069dd09e6e2aea77d77aaceb19a2f9ae8385a76
refs/heads/master
<repo_name>fanzicai/docker-gitlab-cn<file_sep>/Dockerfile FROM centos:centos7 MAINTAINER fanzi "<EMAIL>" RUN yum -y install wget \ && wget http://repo.mysql.com//mysql57-community-release-el7-8.noarch.rpm \ && rpm -Uvh mysql57-community-release-el7-8.noarch.rpm \ && yum -y update \ && yum -y group install "development tools" \ && yum -y install epel-release \ && yum -y install sudo vim cmake mysql mysql-devel openssh-server go ruby redis nodejs nginx readline-devel gdbm-devel openssl-devel expat-devel sqlite-devel libyaml-devel libffi-devel libxml2-devel libxslt-devel libicu-devel python-devel xmlto logwatch perl-ExtUtils-CBuilder RUN adduser --system --shell /bin/bash --comment 'GitLab' --create-home --home-dir /home/git/ git \ && chmod -R go+rx /home/git WORKDIR /home/git RUN wget https://www.kernel.org/pub/software/scm/git/git-2.8.3.tar.gz \ && wget https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.1.tar.gz \ && wget https://storage.googleapis.com/golang/go1.5.3.linux-amd64.tar.gz \ && wget https://gitlab.com/larryli/gitlab/repository/archive.tar.gz?ref=v8.8.0.zh1 \ && tar xvf git-2.8.3.tar.gz \ && tar xvf ruby-2.3.1.tar.gz \ && tar xvf go1.5.3.linux-amd64.tar.gz -C /usr/local/ \ && tar xvf archive.tar.gz?ref=v8.8.0.zh1 \ && mv gitlab-v8.8.0.zh1* gitlab \ && ln -sf /usr/local/go/bin/{go,godoc,gofmt} /usr/bin/ \ # Git install && cd git-2.8.3 \ && ./configure --prefix=/usr \ && make \ && make install \ # Ruby update && cd ../ruby-2.3.1/ \ && ./configure --prefix=/usr --disable-install-rdoc \ && make \ && make install \ # Bundler && gem sources --add https://ruby.taobao.org/ --remove https://rubygems.org/ \ && gem install bundler \ && bundle config mirror.https://rubygems.org https://ruby.taobao.org \ # Redis config & start && echo 'unixsocket /var/run/redis/redis.sock' >> /etc/redis.conf \ && echo 'unixsocketperm 770' >> /etc/redis.conf \ && chown redis:redis /var/run/redis \ && chmod 755 /var/run/redis \ && usermod -aG redis git \ && (redis-server /etc/redis.conf &) # GitLab WORKDIR /home/git/gitlab/ RUN cp config/gitlab.yml.example config/gitlab.yml \ && cp config/secrets.yml.example config/secrets.yml \ && chmod 0600 config/secrets.yml \ && chown -R git log/ \ && chown -R git tmp/ \ && chmod -R u+rwX,go-w log/ \ && chmod -R u+rwX tmp/ \ && chmod -R u+rwX tmp/pids/ \ && chmod -R u+rwX tmp/sockets/ \ && mkdir public/uploads/ \ && chmod 0700 public/uploads \ && chmod -R u+rwX builds/ \ && chmod -R u+rwX shared/artifacts/ \ && cp config/unicorn.rb.example config/unicorn.rb \ && cp config/initializers/rack_attack.rb.example config/initializers/rack_attack.rb \ && git config --global core.autocrlf input \ && git config --global gc.auto 0 \ && cp config/resque.yml.example config/resque.yml \ && cp config/database.yml.mysql config/database.yml \ && sed -i 's/"secure password"/git/' config/database.yml \ && sed -i 's/# host: localhost/host: mysql/' config/database.yml \ && sed -i 's/rubygems.org/ruby.taobao.org/' Gemfile \ && bundle install --deployment --without development test postgres aws \ && bundle exec rake gitlab:shell:install REDIS_URL=unix:/var/run/redis/redis.sock RAILS_ENV=production \ && chown -R git:git /home/git/repositories/ \ && chmod -R ug+rwX,o-rwx /home/git/repositories/ \ && chmod -R ug-s /home/git/repositories/ \ && find /home/git/repositories/ -type d -print0 | xargs -0 chmod g+s \ && chmod 700 /home/git/gitlab/public/uploads \ && chown -R git:git config/ log/ \ # GitLab rc.file && cp lib/support/init.d/gitlab /etc/init.d/gitlab # Nginx config WORKDIR /home/git/gitlab/ RUN mkdir /etc/nginx/sites-available \ && mkdir /etc/nginx/sites-enabled \ && cp lib/support/nginx/gitlab /etc/nginx/sites-available/gitlab \ && ln -s /etc/nginx/sites-available/gitlab /etc/nginx/sites-enabled/gitlab \ && sed -i '20a\ server 127.0.0.1:8080;' /etc/nginx/sites-available/gitlab \ && sed -i '35,54d' /etc/nginx/nginx.conf \ && sed -i '33a\ include /etc/nginx/sites-enabled/*;' /etc/nginx/nginx.conf WORKDIR /home/git # Gitlab-Workhorse RUN git clone https://gitlab.com/gitlab-org/gitlab-workhorse.git \ && cd gitlab-workhorse/ \ && git checkout v0.7.2 \ && make \ && sshd-keygen EXPOSE 80 22 VOLUME ["/tmp/gitlab-cn"] ADD ./gitlab-init.sh /home/git/gitlab-init.sh ADD ./gitlab-run.sh /home/git/gitlab-run.sh RUN chmod +x /home/git/gitlab-init.sh RUN chmod +x /home/git/gitlab-run.sh ENTRYPOINT ["/home/git/gitlab-run.sh"] <file_sep>/gitlab-run.sh #!/bin/bash #gitlab start /etc/init.d/gitlab start & #nginx start nginx & #sshd start /usr/sbin/sshd #redis start sudo -u redis -H redis-server /etc/redis.conf <file_sep>/README.md # **docker-gitlab-cn** # Dockerfile是创建docker image的一种常用方式。本文采用dockerfile创建[gitlab-cn image](https://hub.docker.com/r/fanzi/gitlab-cn/)。该image基于Centos Image 7创建,并与mysql image联合使用。 <!-- more --> ## **1. 准备工作** ## 可参考[CentOS7上安装Docker及GitLab](http://fanzicai.github.io/Program/2016/05/25/CentOS7%E4%B8%8A%E5%AE%89%E8%A3%85Docker%E5%8F%8AGitLab.html)一文,先行安装CentOS、Docker。 - Docker MySQL Oracle官方已提供MySQL的[Docker Image](https://hub.docker.com/r/mysql/mysql-server/)。 ``` docker run --restart always --name mysql -e MYSQL_ROOT_PASSWORD=123 -d mysql/mysql-server:latest ``` > 进入mysql控制台 ``` docker exec -it mysql /bin/bash mysql -uroot -p123 ``` > 创建git用户及database,本文git用户密码设置为git ``` CREATE USER 'git'@'%' IDENTIFIED BY '$password'; CREATE DATABASE IF NOT EXISTS `gitlabhq_production` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_unicode_ci`; GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, CREATE TEMPORARY TABLES, DROP, INDEX, ALTER, LOCK TABLES ON `gitlabhq_production`.* TO 'git'@'%'; flush privileges; \q ``` ---------- ## **2. Image Build** ## 本Image已上传<https://hub.docker.com/r/fanzi/gitlab-cn/> ``` docker build --rm=true -t fanzi/gitlab-cn . ``` ---------- ## **3. Image USE** ## - 创建容器 ``` docker run -it --detach --restart always --link mysql:mysql -p 80:80 --name gitlab fanzi/gitlab-cn ``` - 初始化数据库 确保mysql容器运行,只在创建容器后运行一次 ``` docker exec -it gitlab /bin/bash -c /home/git/gitlab-init.sh ```<file_sep>/gitlab-init.sh #!/bin/bash cd /home/git/gitlab bundle exec rake gitlab:setup RAILS_ENV=production force=yes bundle exec rake assets:precompile RAILS_ENV=production chown -R git:git /home/git/ sudo -u git -H "/usr/bin/git" config --global core.autocrlf "input"
3ebbcadb3ae9809883afb1b71f7e43a97739deb6
[ "Markdown", "Dockerfile", "Shell" ]
4
Dockerfile
fanzicai/docker-gitlab-cn
0cd37217572c92e596bf973f920caa6d62619f85
bec8a6ba98bcdcb6bffa2727f0e3eb90d2fefd5c
refs/heads/master
<repo_name>redcap3000/bitfinex-api<file_sep>/bitfinex.js /* * bitfinex api wrapper * * planned : perhaps a reactive data source/publication that stores data in a Bfx.quotes object * that is queried at an interval specified in env variable * * authenticated paths */ Bfx = {}; // hmmm... not sure where to put this... var getResponseData = function(url,field){ var response = HTTP.get(url); if(response && typeof response.data != "undefined" && response.data && response.data != null){ if(typeof field != "undefined" && field && field != null){ if(typeof response.data[field] != "undefined"){ return response.data[field]; }else{ return false; } } return response.data; } return false; }; Bfx.symbols = function(){ if(typeof Bfx._symbols == "undefined"){ Bfx._symbols = getResponseData("https://api.bitfinex.com/v1/symbols"); } return Bfx._symbols; }; Bfx.ticker = function(symbol,field,asFloat){ if(typeof symbol == "undefined" || !symbol || symbol == null){ symbol = 'btcusd'; } if(Bfx._symbols.indexOf(symbol) > -1){ if(typeof field == "string" && asFloat == true){ var response = getResponseData("https://api.bitfinex.com/v1/pubticker/" + symbol,field); if(response){ return parseFloat(response); }else{ return false; } } return getResponseData("https://api.bitfinex.com/v1/pubticker/" + symbol,field); }else{ console.log(symbol + '\t : not supported'); console.log('\t ** Supported symbols **'); console.log(bitfinexSymbols); } return false; } Bfx.last_price = function(symbol){ return Bfx.ticker(symbol,'last_price',true); }<file_sep>/README.md Bitfinex API ========================== Wrapper to interface with the bitfinex cryptocurrency exchange. This package is not offically supported by Bitfinex. Not responsible for loss of your data or money by using this package. See https://www.bitfinex.com/pages/api for more information. ##Functions## **Bfx.symbols()** Returns a list of symbols that are compatable with the 'ticker' functions. **Bfx.ticker(symbol,fieldname,AsFloat)** When fieldname is specified returns that field; if 'AsFloat' is passed as true returns the specified fieldname as a float. Otherwise returns entire response from bitfinex. **Bfx.last_quote** Shortcut from Bfx.ticker(symbol,'last_quote',true); <file_sep>/package.js Package.describe({ name: "redcap3000:bitfinex-api", summary: "Wrapper to interface with the bitfinex cryptocurrency exchange.", version: "0.0.1", git: "https://github.com/redcap3000/bitfinex-api" }); Package.onUse(function(api) { api.versionsFrom("0.9.0"); api.use('http', 'server'); api.addFiles('bitfinex.js', 'server'); api.export('Bfx','server'); }); Package.onTest(function(api) { api.use(["redcap3000:bitfinex-api",'http']); api.use('tinytest@1.0.0'); api.addFiles(['bitfinex-tests.js'], ['server']); });<file_sep>/bitfinex-tests.js Tinytest.add('bitfinex-api - init', function(test) { test.equal(typeof Bfx,'object','Bfx is not an object'); test.equal(typeof Bfx.ticker,'function','Bfx.ticker not available.'); test.equal(typeof Bfx.symbols,'function','Bfx.symbols not a function'); }); Tinytest.add('bitfinex-api - ticker lookups',function(test){ var markets = Bfx.symbols(); // get last prices? // expect to fail since we do not have process.env variables for authentication test.length(markets, 5, "Bfx.symbols() did not return 5 responses. Did the api change?"); test.isTrue(Bfx.last_price(markets[0]),'number','Last Quote did not return a valid response.'); test.isTrue(Bfx.ticker(markets[1]),'object','Ticker lookup did not return a valid response.'); });
7bb79cc3d3ddd18cd8fb0f98dd3e101469b27f67
[ "JavaScript", "Markdown" ]
4
JavaScript
redcap3000/bitfinex-api
156a3a3565ab0e88987918a22d28bdb569bc11d8
46c0d0ea1634ea11cfe0e835f04b86e6441e21f9
refs/heads/main
<repo_name>uidaitc/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem<file_sep>/backend/hackathon_adhaar_solution/gateway.py from functools import wraps from django.http import JsonResponse from hackathon_adhaar_solution.helper_functions.jwtutils import decode from aadhaar_update_app.models import RequestRecord def user_login_gateway(view_func): @wraps(view_func) def wrap(request, *args, **kwargs): error = "" try: token = str(request.headers["Authorization"]).split(" ")[1] decoded_token_res = decode(token) if not decoded_token_res[0]: raise Exception("Token decryption failed") request.txn_id = decoded_token_res[1] request.is_landlord_neighbour = decoded_token_res[2] if decoded_token_res[2] != 0: error = "CROSS_USER request. You are not permitted" elif not RequestRecord.objects.filter(txn_id=request.txn_id).exists(): error = "Invalid requests ! Please retry" else: request_record = RequestRecord.objects.get(txn_id=request.txn_id) if request_record.status == "requested": return JsonResponse( {"success": True, "message": "Landlord has not taken any action till now ! Please wait", "error": "", "page_show": True}, status=200) elif request_record.status == "rejected_by_landlord": return JsonResponse( {"success": False, "message": "", "error": "Request rejected by landlord", "page_show": True}, status=200) elif request_record.status == "rejected_by_system": return JsonResponse( {"success": False, "message": "", "error": "Aadhaar update request rejected by system. For more contact customer care", "page_show": True}, status=200) elif request_record.status == "failed_due_to_limit_reach_of_landlord": return JsonResponse( {"success": False, "message": "", "error": "Landlord can't issue you the address due to limit at landlord's side", "page_show": True}, status=200) elif request_record.status == "updated": return JsonResponse( {"success": True, "message": "Aadhaar updated successfully", "error": "", "page_show": True}, status=200) return view_func(request, *args, **kwargs) except KeyError as e: error = "Token not found in header" except Exception as e: error = f"Error : {e}" return JsonResponse({"success": False, "message": "", "error": error, "page_show": True}, status=401) return wrap def landlord_login_gateway(view_func): @wraps(view_func) def wrap(request, *args, **kwargs): error = "" try: token = str(request.headers["Authorization"]).split(" ")[1] print(token) decoded_token_res = decode(token) if not decoded_token_res[0]: raise Exception("Token decryption failed") request.txn_id = decoded_token_res[1] request.is_landlord_neighbour = decoded_token_res[2] if decoded_token_res[2] != 1: error = "CROSS_USER request. You are not permitted" elif not RequestRecord.objects.filter(txn_id=request.txn_id).exists(): error = "Invalid requests ! Please retry" else: ''' CHECK STATUS AND AUTHENTICATE ''' request_record = RequestRecord.objects.get(txn_id=request.txn_id) if request_record.status != "requested": return JsonResponse({"success": True, "message": "You have completed your action ! Nothing left behind", "error": ""}, status=200) return view_func(request, *args, **kwargs) except KeyError as e: error = "Token not found in header" except Exception as e: error = f"Error : {e}" return JsonResponse({"success": False, "message": "", "error": error}, status=401) return wrap <file_sep>/backend/README.md #### Run Backend 1. Clone the repo 2. Go to ***backend*** directory 3. Create a virtualenv ```virtualenv venv``` 4. Activate the virtualenv ```source venv/bin.activate``` 5. Install all the library ```pip install -r requirements.txt``` 6. Rename ***.env-example*** to ***.env*** located in ```/backend/hackathon_adhaar_solution/``` 7. Update **FAST2SMS_API_KEY** & **GOOGLE_MAPS_API_KEY** and other variables in ***.env*** 8. Run ```python manage.py makemigrations``` 9. Run ```python manage.py migrate``` 10. Run ```python manage.py runserver``` 11. You can create superuser by ```python manage.py createsuperuser```<file_sep>/backend/audit_system/admin.py from django.contrib import admin from audit_system.models import AuditLog admin.site.register(AuditLog)<file_sep>/backend/aadhaar_update_app/admin.py from django.contrib import admin from aadhaar_update_app.models import * admin.site.register(RequestRecord) admin.site.register(AddressUpdateLog) admin.site.register(ConsentCountLog)<file_sep>/backend/aadhaar_update_app/views.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from hackathon_adhaar_solution.helper_functions.jwtutils import encode from hackathon_adhaar_solution.gateway import user_login_gateway, landlord_login_gateway from hackathon_adhaar_solution.helper_functions.api_utils import * from hackathon_adhaar_solution.helper_functions.ekyc_decoder import * from hackathon_adhaar_solution.helper_functions.communication import send_sms from hackathon_adhaar_solution.helper_functions.geo_utils import * from hackathon_adhaar_solution.settings import ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER from audit_system.audit_function import addAuditLog from . import models import hashlib class ResponseScheme: success = False payload = {} message = "" error = "" page_show = False def set_success(self, success): self.success = success def set_payload(self, payload): self.payload = payload def set_message(self, message): self.message = message def set_error(self, error): self.error = error def set_page_show(self, page_show): self.page_show = page_show def to_json(self): return { "success": self.success, "message": self.message, "error": self.error, "payload": self.payload, "page_show": self.page_show } def to_audit_json(self): return { "success": self.success, "message": self.message, "error": self.error, } ''' COMMON ROUTES [NO AUTHORIZATION REQUIRED] ''' @require_http_methods(["GET"]) def captcha_request(request): # print(get_client_ip(request)) response = ResponseScheme() try: response_captcha = generate_captcha() if response_captcha[0] == "-1" or response_captcha[1] == "-1": response.set_success(False) response.set_error("Captcha generate failed ! Aadhaar server unreachable") else: response.set_success(True) response.set_payload({ "captchaTxnId": response_captcha[0], "captchaBase64String": response_captcha[1] }) response.set_message("Captcha generated successfully") except: response.set_success(False) response.set_error("Captcha generate failed ! Unexpected Error") return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt def otp_request(request): response = ResponseScheme() request_id = str(request.POST.get("request_id", "-1")).strip() captcha_txnid = str(request.POST.get("captchaTxnId", "-1")).strip() captcha_value = str(request.POST.get("captchaValue", "-1")).strip() uid = str(request.POST.get("uid", "-1")).strip() transaction_id = uuid.uuid4() try: if captcha_txnid == "-1" or captcha_value == "-1" or captcha_value == "" or captcha_txnid == "": response.set_success(False) response.set_error("Captcha txn id or value is missing in request") elif uid == "-1" or len(uid) < 12: response.set_success(False) response.set_error("Invalid uid") else: response_otp = generate_otp(uid, captcha_txnid, captcha_value, str(transaction_id)) # print(response_otp) if not response_otp[0]: response.set_success(False) response.set_error(response_otp[1]["message"]) else: response.set_success(True) response.set_message(response_otp[1]["message"]) response.set_payload({ "request_transaction_id": str(transaction_id), "otp_transaction_id": response_otp[1]["txnId"] }) except Exception as e: print(e) response.set_success(False) response.set_error("OTP generate failed ! Unexpected Error") return JsonResponse(response.to_json(), safe=False) ''' ALL THE ROUTES REQUIRED BY THE USER WHO IS ASKING CONSENT FOR UPDATE ''' @require_http_methods(["POST"]) @csrf_exempt def eKyc_request(request): response = ResponseScheme() request_transaction_id = str(request.POST.get("request_transaction_id", "-1")).strip() uid = str(request.POST.get("uid", "-1")).strip() otp_transaction_id = str(request.POST.get("otp_transaction_id", "-1")).strip() otp_value = str(request.POST.get("otp", "-1")).strip() if request_transaction_id == "-1" or otp_transaction_id == "-1" or otp_value == "-1" or request_transaction_id == "" or otp_transaction_id == "" or otp_value == "" or uid == "" or uid == "-1": response.set_success(False) response.set_error("All information not filled") else: fetched_xml = fetch_offline_xml(uid, otp_value, otp_transaction_id, request_transaction_id) if not fetched_xml[0]: response.set_success(False) response.set_error("eKyc Failed please retry") else: response.set_success(True) response.set_message("Successfully eKYC Done") eKycXML = fetched_xml[1] ekycdoc = OfflinePaperlessKycData(eKycXML) request_record = models.RequestRecord.objects.create( txn_id=request_transaction_id, eKyc_data=json.dumps(ekycdoc.to_json()) ) request_record.uid_hash = str(hashlib.sha256(uid.encode()).hexdigest()) request_record.save() response.set_payload({ "jwt_token": encode(request_transaction_id,0), "request_status": request_record.status, "request_record_id": str(request_record.id) }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json(), is_requester=True) return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt def eKyc_request_with_request_id(request): response = ResponseScheme() request_id = str(request.POST.get("request_id", "-1")).strip() uid = str(request.POST.get("uid", "-1")).strip() otp_transaction_id = str(request.POST.get("otp_transaction_id", "-1")).strip() otp_value = str(request.POST.get("otp", "-1")).strip() if request_id == "-1" or otp_transaction_id == "-1" or otp_value == "-1" or request_id == "" or otp_transaction_id == "" or otp_value == "" or uid == "" or uid == "-1": response.set_success(False) response.set_error("All information not filled") else: request_record = models.RequestRecord.objects.get(id=request_id) if sha256(uid.encode()).hexdigest() != request_record.uid_hash: response.set_success(False) response.set_error("UID is not matching") response.set_page_show(True) else: fetched_xml = fetch_offline_xml(uid, otp_value, otp_transaction_id, str(request_record.txn_id)) if not fetched_xml[0]: response.set_success(False) response.set_error("eKyc Failed please retry") else: response.set_success(True) response.set_message("Successfully eKYC Done") response.set_payload({ "jwt_token": encode(request_record.txn_id,0), "request_status": request_record.status, "request_record_id": str(request_record.id) }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json(), is_requester=True) return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def update_number(request): response = ResponseScheme() mobile_number = str(request.POST.get("mobile_number", "-1")).strip() if mobile_number == "-1" or mobile_number == "" or len(mobile_number) < 10: response.set_success(False) response.set_error("Mobile number not valid") else: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) if str(request_record.mobile_no).strip() != "" : response.set_success(True) response.set_error("Mobile no is updated already") else: request_record.mobile_no = mobile_number request_record.save() response.set_success(True) response.set_message("Contact no updated") addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def submit_landlord_number(request): response = ResponseScheme() landlord_mobile_number = str(request.POST.get("landlord_mobile_number", "-1")).strip() if landlord_mobile_number == "-1" or landlord_mobile_number == "" or len(landlord_mobile_number) < 10: response.set_success(False) response.set_error("Mobile number not valid") else: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) if str(request_record.landlord_mobile_no).strip() != "" : response.set_success(False) response.set_error("Landlord mobile no is updated already and notification has been sent.") response.set_page_show(True) else: request_record.landlord_mobile_no = landlord_mobile_number request_record.status = "requested" request_record.save() send_sms(request_record.mobile_no, "You can check status here. https://main.d3mf157q8c6tmv.amplifyapp.com/r/" + str(request_record.id) + "/") send_sms(landlord_mobile_number, "Someone has requested for aaadhar update consent. Click on https://main.d3mf157q8c6tmv.amplifyapp.com/l/" + str(request_record.id) + "/") response.set_success(True) response.set_message("Request has been submitted & Landlord/neighbour has been notified. You will receive SMS regarding any update") response.set_page_show(True) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def check_status(request): response = ResponseScheme() try: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) response.set_success(True) response.set_success("Query Successful") response.set_payload({ "status_code": request_record.status, "status": request_record.get_status_display() }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) except: response.set_success(False) response.set_error("Record Expired or Not Found") return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def get_approved_address_of_landlord(request): response = ResponseScheme() try: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) response.set_success(True) response.set_success("Query Successful") landlord_eKyc_json = json.loads(request_record.landlord_eKyc_data) landlord_address = landlord_eKyc_json["poa"] landlord_name = landlord_eKyc_json["poi"]["name"] response.set_payload({ "landlord_name": landlord_name, "landlord_address": landlord_address, "landlord_mobile_no": request_record.landlord_mobile_no }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) except: response.set_success(False) response.set_error("Record Expired or Not Found") return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def check_distance_between_address(request): response = ResponseScheme() json_req_body = json.loads(request.body) print(json_req_body) if "updated_address" in json_req_body: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) updated_address = POA(json_req_body["updated_address"], from_json=True) landlord_eKyc_data = json.loads(request_record.landlord_eKyc_data) previous_address = POA(landlord_eKyc_data["poa"], from_json=True) # print(updated_address.to_serialized_format()) # print(previous_address.to_serialized_format()) updated_address_coordinate = get_coordinate_by_address(updated_address.to_serialized_format()) previous_address_coordinate = get_coordinate_by_address(previous_address.to_serialized_format()) distance = get_distance_between_coordinates_meter(updated_address_coordinate[0], updated_address_coordinate[1], previous_address_coordinate[0], previous_address_coordinate[1]) if distance >= ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER: response.set_success(False) response.set_error("Too much difference between landlord address and the updated address. Difference " "need to be less than " + str( ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER)) response.set_payload({ "distance": distance, "allowed_distance": ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER, "unit": " meter" }) else: response.set_success(True) response.set_message("Address is acceptable. You can proceed for aadhaar update submission") response.set_payload({ "distance": distance, "allowed_distance": ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER, "unit": " meter" }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) else: response.set_success(False) response.set_error("Updated address not sent with request") return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def submit_address_update(request): response = ResponseScheme() json_req_body = json.loads(request.body) print(json_req_body) if "updated_address" in json_req_body and "uid" in json_req_body: request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) if request_record.status == "updated" : response.set_success(False) response.set_message("Aadhaar is already updated ! Please refresh") response.set_page_show(True) else: updated_address = POA(json_req_body["updated_address"], from_json=True) landlord_eKyc_data = json.loads(request_record.landlord_eKyc_data) previous_address = POA(landlord_eKyc_data["poa"], from_json=True) previous_user_careof = json.loads(request_record.eKyc_data)["poa"]["careof"] updated_address_coordinate = get_coordinate_by_address(updated_address.to_serialized_format()) previous_address_coordinate = get_coordinate_by_address(previous_address.to_serialized_format()) distance = get_distance_between_coordinates_meter(updated_address_coordinate[0], updated_address_coordinate[1], previous_address_coordinate[0], previous_address_coordinate[1]) if distance >= ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER: response.set_success(False) response.set_error("Too much difference between landlord address and the updated address. Difference " "need to be less than " + str( ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER)) response.set_payload({ "distance": distance, "allowed_distance": ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER, "unit": " meter" }) else: if sha256(str(json_req_body["uid"]).strip().encode()).hexdigest() != request_record.uid_hash: response.set_success(False) response.set_error("You have entered wrong uid ! Please enter the correct one") else: updated_address.careof = previous_user_careof models.AddressUpdateLog.objects.create( request_record=request_record, uid=str(json_req_body["uid"]).strip(), previous_address=json.dumps(json.loads(request_record.eKyc_data)["poa"]), updated_address=json.dumps(updated_address.to_json()) ) request_record.status = "updated" request_record.save() send_sms(request_record.mobile_no, "Your aadhaar address has been updated successfully !") response.set_success(True) response.set_message("Aadhaar Update Completed") response.set_page_show(True) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) else: response.set_success(False) response.set_error("Updated address not sent with request") return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @user_login_gateway def ping_check_request_allowance(request): response = ResponseScheme() response.set_success(True) response.set_message("requests allowed") return JsonResponse(response.to_json()) ''' ALL THE LANDLORD ACTION RELATED TASKS ARE DEFINED HERE ''' @require_http_methods(["POST"]) @csrf_exempt def landlord_eKyc_request(request): response = ResponseScheme() request_id = str(request.POST.get("request_id", "-1")).strip() uid = str(request.POST.get("uid", "-1")).strip() otp_transaction_id = str(request.POST.get("otp_transaction_id", "-1")).strip() otp_value = str(request.POST.get("otp", "-1")).strip() if request_id == "-1" or otp_transaction_id == "-1" or otp_value == "-1" or request_id == "" or otp_transaction_id == "" or otp_value == "" or uid == "" or uid == "-1": response.set_success(False) response.set_error("All information not filled") else: request_record = models.RequestRecord.objects.get(id=request_id) if sha256(uid.encode()).hexdigest() == request_record.uid_hash: response.set_success(False) response.set_error("You can't sign your own address request consent") response.set_page_show(True) elif request_record.landlord_uid_hash != "": response.set_success(False) response.set_error("Already a landlord has completed his action. Can't resubmit consent") response.set_page_show(True) else: fetched_xml = fetch_offline_xml(uid, otp_value, otp_transaction_id, request_id) if not fetched_xml[0]: response.set_success(False) response.set_error("eKyc Failed please retry") else: response.set_success(True) response.set_message("Successfully eKYC Done") eKycXML = fetched_xml[1] ekycdoc = OfflinePaperlessKycData(eKycXML) request_record.landlord_eKyc_data = json.dumps(ekycdoc.to_json()) request_record.landlord_uid_hash = str(hashlib.sha256(uid.encode()).hexdigest()) request_record.save() requested_user_details = json.loads(request_record.eKyc_data) response.set_payload({ "jwt_token": encode(request_record.txn_id, 1), "request_record_id": str(request_record.id), "user": { "name": requested_user_details["poi"]["name"], "photo": requested_user_details["pht"], "mobile_no": request_record.mobile_no } }) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json(), is_requester=False) return JsonResponse(response.to_json(), safe=False) @require_http_methods(["POST"]) @csrf_exempt @landlord_login_gateway def landlord_decision(request): response = ResponseScheme() approve_action = str(request.POST.get("approve_action", "n")).strip() is_approved = True if approve_action == "y" else False message = "" error = "" success = True sms_content = "" request_record = models.RequestRecord.objects.get(txn_id=request.txn_id) if is_approved: is_consent_update_possible = True # Increase count of consents of landlord if models.ConsentCountLog.objects.filter(uid_hash=request_record.landlord_uid_hash).exists(): consent_log_landlord = models.ConsentCountLog.objects.get(uid_hash=request_record.landlord_uid_hash) if consent_log_landlord.consent_count <= consent_log_landlord.consent_limit: consent_log_landlord.consent_count = consent_log_landlord.consent_count + 1 consent_log_landlord.save() is_consent_update_possible = True else: is_consent_update_possible = False else: models.ConsentCountLog.objects.create(uid_hash=request_record.landlord_uid_hash, consent_count=1) if is_consent_update_possible: success = True message = "Request approved successfully" sms_content = "Landlord/neighbour has accepted your request for address update. Kindly confirm address and update your address" request_record.status = "approved_by_landlord" else: success = False sms_content = "Landlord/neighbour can't issue you the address due to limit at landlord's side" error = "You can't issue further consent due to reach limit of issuing consent" request_record.status = "failed_due_to_limit_reach_of_landlord" else: success = True message = "Request rejected successfully" sms_content = "Landlord/neighbour has denied your request for address update" request_record.status = "rejected_by_landlord" send_sms(request_record.mobile_no, sms_content) request_record.save() response.set_success(success) response.set_message(message) response.set_error(error) response.set_page_show(True) addAuditLog(request, request_record.id, request_record.status, response.to_audit_json()) return JsonResponse(response.to_json(), safe=False) <file_sep>/backend/hackathon_adhaar_solution/helper_functions/api_utils.py import base64 import random import zipfile from io import BytesIO import xml.etree.ElementTree as ET import requests import json import uuid # Constants appid = "MYAADHAAR" # Endpoint captcha_endpoint = "https://stage1.uidai.gov.in/unifiedAppAuthService/api/v2/get/captcha" otp_endpoint = "https://stage1.uidai.gov.in/unifiedAppAuthService/api/v2/generate/aadhaar/otp" offline_ekyc_endpoint = "https://stage1.uidai.gov.in/eAadhaarService/api/downloadOfflineEkyc" EKYC_APP_ID_VALUE = "PORTAL" EKYC_SHARE_CODE = "1234" def generate_captcha(): payload = json.dumps({ "langCode": "en", "captchaLength": "3", "captchaType": "2" }) headers = { 'Content-Type': 'application/json' } response = requests.request("POST", captcha_endpoint, headers=headers, data=payload) response_json = response.json() # print(response_json) if response_json["status"] != "Success" or response_json["statusCode"] != 200: return "-1", "-1" # return txnId, base64string Of captcha return response_json["captchaTxnId"], response_json["captchaBase64String"] def generate_otp(uid, captchaTxnId, captchaValue, transactionId): payload = json.dumps({ "uidNumber": str(uid), "captchaTxnId": captchaTxnId, "captchaValue": captchaValue, "transactionId": appid + ":" + transactionId }) headers = { 'Content-Type': 'application/json', 'appid': appid, 'Accept-Language': 'en_in' } response = requests.request("POST", otp_endpoint, headers=headers, data=payload) response_json = response.json() if response_json["status"] != "Success": return False, response_json # print(response_json) return True, response_json def base64_string_to_xml(xml, share_code): zf = zipfile.ZipFile(BytesIO(base64.b64decode(xml))) zf.setpassword(str(share_code).encode('utf-8')) filedata = zf.open(zf.namelist()[0]).read() parsedxml = ET.fromstring(filedata, parser=ET.XMLParser(encoding="utf-8")) return parsedxml def fetch_offline_xml(uid, otp, otpTxnId, transactionId): share_code = ''.join(random.sample('0123456789', 4)) payload = json.dumps({ "aadhaarOrVidNumber": 0, "txnNumber": otpTxnId, "shareCode": share_code, "otp": str(otp), "deviceId": None, "transactionId": transactionId, "unifiedAppRequestTxnId": None, "uid": str(uid), "vid": None }) headers = { 'Content-Type': 'application/json', 'X-Request-ID': str(uuid.uuid4()), 'appID': EKYC_APP_ID_VALUE, 'Accept-Language': 'en_in', 'transactionId': str(transactionId) } response = requests.request("POST", offline_ekyc_endpoint, headers=headers, data=payload) response_json = response.json() print(response_json) if response_json["status"] != "Success": return False, "-1", "-1" return True, base64_string_to_xml(response_json["eKycXML"], share_code), response_json["uidNumber"] <file_sep>/backend/audit_system/views.py from django.http import HttpResponse from django.shortcuts import render from aadhaar_update_app.models import RequestRecord from audit_system.models import AuditLog from django.contrib.auth.decorators import user_passes_test @user_passes_test(lambda u: u.is_superuser, login_url="/admin/login/") def search(request): data = {} if request.method == "POST": id = request.POST.get("request_id", "") if AuditLog.objects.filter(request_id=id).exists(): data["audit_log_records"] = AuditLog.objects.filter(request_id=id).order_by("-id") data["request_record"] = RequestRecord.objects.get(id=id) return render(request, "audit_system/show_details.html", data) else: data["message"] = "Record ID not exists" return render(request, "audit_system/id_input.html", data) <file_sep>/backend/audit_system/audit_function.py import json from audit_system.models import AuditLog from hackathon_adhaar_solution.helper_functions.ip_analyzer import get_client_ip, getLocationDetails def addAuditLog(request, request_id, request_status_current, response, is_requester=None): ip = get_client_ip(request) location_data = getLocationDetails(ip) location_details = {} if location_data[0]: location_details = location_data[1] audit_record = AuditLog.objects.create( request_id=request_id, request_status_current=request_status_current, ip=ip, ip_details=json.dumps(location_details), is_error=False if response["success"] else True, error=response["error"], message=response["message"] ) if is_requester is not None: audit_record.is_requester = is_requester audit_record.save() else: try: if request.is_landlord_neighbour == 0: audit_record.is_requester = True audit_record.save() elif request.is_landlord_neighbour == 1: audit_record.is_requester = False audit_record.save() except: print("Failed")<file_sep>/backend/hackathon_adhaar_solution/helper_functions/geo_utils.py import requests from geopy.distance import geodesic from hackathon_adhaar_solution.settings import GOOGLE_MAPS_API_KEY # GOOGLE_MAPS_API_KEY = "<KEY>" def get_coordinate_by_address(address): url = f"https://maps.googleapis.com/maps/api/geocode/json?key={GOOGLE_MAPS_API_KEY}&address={address}" payload = {} headers = {} response = requests.request("GET", url, headers=headers, data=payload) response_json = response.json() try: return True, response_json['results'][0]["geometry"]["location"]['lat'], \ response_json['results'][0]["geometry"]["location"]['lng'] except: return False, "-1", "-1" # print(get_coordinate_by_address("palitpara taherpur road,ward no 9, birnagar, nadia, west bengal, pincode 741127")) # print(get_coordinate_by_address("birnagar high school, birnagar, nadia, west bengal")) def get_distance_between_coordinates_meter(lat1, lon1, lat2, lon2): return geodesic((lat1, lon1), (lat2, lon2)).meters <file_sep>/backend/hackathon_adhaar_solution/helper_functions/ip_analyzer.py import requests def get_client_ip(request): try: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip except: return None def getLocationDetails(ip): try: res = requests.get(f"http://ip-api.com/json/{ip}").json() if res["status"] == "success": payload = { 'ip': ip, 'location_details': { 'lat': res["lat"], 'lon': res['lon'], 'city': res["city"], 'region': res["region"], 'country': res["country"], 'zip': res['zip'] }, 'provider': { 'isp': res['isp'], 'org': res['org'], 'as': res['as'] } } return True, payload else: return False, {} except: return False, {} # print(getLocationDetails("172.16.31.10"))<file_sep>/frontend/README.md ### Run in local server ##### Run Frontend 1. Clone the repo 2. Go to ***frontend*** directory 3. Run ``` npm install``` 4. Replace your backend url with "BACKEND" variable in ```frontend/src/helper_functions.js``` 5. Run ```npm run serve``` to start localserver<file_sep>/backend/aadhaar_update_app/urls.py from django.urls import path from . import views urlpatterns = [ path("request/captcha/",views.captcha_request), path("request/otp/", views.otp_request), path("request/ekyc/", views.eKyc_request), path("request/ekyc_id/", views.eKyc_request_with_request_id), path("update/user_mobile/", views.update_number), path("update/landlord_mobile/", views.submit_landlord_number), path("status/", views.check_status), path("ping/", views.ping_check_request_allowance), path("request_approval/ekyc/", views.landlord_eKyc_request), path("request_approval/decision/", views.landlord_decision), path("request/lanlord_approved_adddress/", views.get_approved_address_of_landlord), path("request/verify_address_distance/", views.check_distance_between_address), path("request/submit_update/", views.submit_address_update), ] <file_sep>/README.md <p align="center"><img src="https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/aadhaar_logo.svg" width="150px"/></p> <h1 align="center">Aadhaar Hackathon 2021</h1> <h4 align="center">Address Update Challenge in Urban Areas [Theme 1 , Problem 1]</h4> *** ### Presentation and Video > [🖥️ Click here to download pdf presentation](https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/Aadhar_Hackathon_ppt.pdf) > [📹 Click here to open the video presentation](https://www.youtube.com/watch?v=3Dt67_Fu8m0) ### Deployment > 🌀 Hosted in AWS Mumbai both the frontend and backend server > 🌀 The installation process has been discussed after the audit logs part. [Click here to jump in that part](#run-in-local-server) _ _ _ Frontend [App] : [https://main.d3mf157q8c6tmv.amplifyapp.com/ ](https://main.d3mf157q8c6tmv.amplifyapp.com/) _ _ _ Backend hosted at : [https://devhunt.in/](https://devhunt.in/) _ _ _ 🟠 🟡 Backend Admin Panel Test Account > Username : test > Password : <PASSWORD> _ _ _ 🟥 🟧 Backend Tasks with Admin Priviliges > Admin Panel of Backend [Default Django Admin Panel] : [https://devhunt.in/admin/](https://devhunt.in/admin/) > Audit log finder : [https://devhunt.in/audit/](https://devhunt.in/audit/) * * * ### Tech Stacks Used - In frontend, we have used VueJS - In backend, we have used Django with python * * * ### Aadhaar APIs Used - **Captcha API** > It is used during the eKYC of tenant and landlord to generate captcha. - **OTP Generation API** > It is used to handle OTP requests and send OTP to the Aadhaar registered number. - **eKYC API** > It is used to authenticate users and fetch their KYC data. Also used to get the landlord's address after consent approval * * * ### Third Party APIs Used - [Google Maps Geocoding APIS](https://developers.google.com/maps/documentation/geocoding/overview) > Used to get longitude and latitude by address - [IP API.com](https://ip-api.com/) > Used to retrieve location and isp details of an IP - [Fast2sms API](fast2sms.com) > Used to send SMS to users * * * ### In total 3 parts, The whole aadhaar address update process will be completed ! #### Part 1 | Tenant Submit Request ![https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part1.png](https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part1.png) #### Part 2 | Landlord either approve or reject consent ![https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part2.png](https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part2.png) #### Part 3 | Do some minor change in address and submit update ![https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part3.png](https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/flow_part3.png) ### DB Scheme Used in backend service ![https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/db_schema.png](https://raw.githubusercontent.com/Tanmoy741127/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem/main/resources/db_schema.png) ### Audit logs ##### It is stored in SQL database and in case of fraud we can get the audit details through the admin panel located at http://127.0.0.1:8000/audit/ or https://devhunt.in/audit/ [Deployed Version] You need to enter the request id that has been sent with SMS to users to get full audit log. For an example you can enter request id => **644481218072** > Audit logs have device details, ip location , request info, timestamp ### Run in local server ##### Run Frontend 1. Clone the repo 2. Go to ***frontend*** directory 3. Run ``` npm install``` 4. Replace your backend url with "BACKEND" variable in ```frontend/src/helper_functions.js``` 5. Run ```npm run serve``` to start localserver #### Run Backend 1. Clone the repo 2. Go to ***backend*** directory 3. Create a virtualenv ```virtualenv venv``` 4. Activate the virtualenv ```source venv/bin.activate``` 5. Install all the library ```pip install -r requirements.txt``` 6. Rename ***.env-example*** to ***.env*** located in ```/backend/hackathon_adhaar_solution/``` 7. Update **FAST2SMS_API_KEY** & **GOOGLE_MAPS_API_KEY** and other variables in ***.env*** 8. Run ```python manage.py makemigrations``` 9. Run ```python manage.py migrate``` 10. Run ```python manage.py runserver``` 11. You can create superuser by ```python manage.py createsuperuser``` ### How to update the distance threshold If we are using the .env file in backend then we should update the value of ***"ALLOWED_DISTANCE_BETWEEN_PREVIOUS_AND_UPDATED_ADDRESS_IN_METER"*** or if we are not using .env, we can update the enviroment variables of system directly #### Thanking You *We_r_TitanicX [Reference ID : HgpUQdPf9z]* #### Team Members - <NAME> - <NAME> - <NAME> - <NAME> - <NAME> <file_sep>/backend/hackathon_adhaar_solution/helper_functions/ekyc_decoder.py from hashlib import sha256 import base64 def isEmptyString(string): if str(string).strip() == "": return True return False class POA: careof = "" country = "" dist = "" house = "" landmark = "" loc = "" pc = "" po = "" state = "" street = "" subdist = "" vtc = "" def __init__(self, input, from_json=False): if not from_json: self.careof = input.get("careof") self.country = input.get("country") self.dist = input.get("dist") self.house = input.get("house") self.landmark = input.get("landmark") self.loc = input.get("loc") self.pc = input.get("pc") self.po = input.get("po") self.state = input.get("state") self.street = input.get("street") self.subdist = input.get("subdist") self.vtc = input.get("vtc") else: if "careof" in input: self.careof = input["careof"] if "house" in input: self.house = input["house"] if "landmark" in input: self.landmark = input["landmark"] if "loc" in input: self.loc = input["loc"] if "po" in input: self.po = input["po"] if "pc" in input: self.pc = input["pc"] if "dist" in input: self.dist = input["dist"] if "dist" in input: self.dist = input["dist"] if "subdist" in input: self.subdist = input["subdist"] if "vtc" in input: self.vtc = input["vtc"] if "street" in input: self.street = input["street"] if "country" in input: self.country = input["country"] def to_json(self): data = { "careof": self.careof, "house": self.house, "landmark": self.landmark, "loc": self.loc, "po": self.po, "pc": self.pc, "dist": self.dist, "subdist": self.subdist, "vtc": self.vtc, "street": self.street, "state": self.state, "country": self.country } return data def to_serialized_format(self): address = "" list_params = [self.house, self.loc, self.landmark, self.street, self.vtc, self.po, self.subdist, self.dist, self.state, self.country, self.pc] for i in range(0, len(list_params)): if not isEmptyString(list_params[i]): address += list_params[i] if i < len(list_params)-1: address += ", " return address class POI: dob = "" e = "" gender = "" m = "" name = "" def __init__(self, xml): self.dob = xml.get("dob") self.e = xml.get("e") self.gender = xml.get("gender") self.m = xml.get("m") self.name = xml.get("name") def verify_mobile_no(self, mobile_no, share_code, last_digit_uid): str_data = str(mobile_no) + str(share_code) tmp_sha = sha256(str_data.encode()).hexdigest() if not (last_digit_uid == 0 or last_digit_uid == 1): for i in range(last_digit_uid - 1): tmp_sha = sha256(tmp_sha.encode()).hexdigest() return tmp_sha == self.m def to_json(self): data = { "name": self.name, "gender": self.gender, "dob": self.dob, "e": self.e, "m": self.m } return data class OfflinePaperlessKycData: referenceId = "" poa = None poi = None pht = None def __init__(self, xml): self.referenceId = xml.get("referenceId") uidData = list(xml)[0] self.poi = POI(list(uidData)[0]) self.poa = POA(list(uidData)[1]) self.pht = list(uidData)[2].text def pht_base64(self): return base64.b64decode(self.pht) def to_json(self, with_photo=True): data = {} data["referenceId"] = self.referenceId data["poa"] = self.poa.to_json() data["poi"] = self.poi.to_json() if with_photo: data["pht"] = self.pht return data <file_sep>/backend/hackathon_adhaar_solution/helper_functions/communication.py from hackathon_adhaar_solution.settings import FAST2SMS_API_KEY import requests def send_sms(mobile_number, message): payload = f'''https://www.fast2sms.com/dev/bulkV2?authorization={FAST2SMS_API_KEY}&route=v3&sender_id=TXTIND&message={message}&language=english&flash=0&numbers={mobile_number}''' response = requests.get(payload) print(response.text) <file_sep>/backend/requirements.txt cryptography==35.0.0 Django==3.2.8 django-cors-headers==3.10.0 django-random-id-model==0.1.0 geographiclib==1.52 geopy==2.2.0 idna==3.3 pycparser==2.20 PyJWT==2.3.0 pytz==2021.3 requests==2.26.0 sqlparse==0.4.2 urllib3==1.26.7 django-environ <file_sep>/backend/audit_system/templatetags/json_tag.py from django import template import json register = template.Library() @register.filter def text_to_json(value): # print(value) try: return json.loads(value) except Exception as e: print(e) return {} @register.filter def get_value_json(value, key): # print(value["ip"]) try: return value[key] except: return "N/A" <file_sep>/backend/aadhaar_update_app/models.py from django.db import models from django_random_id_model import RandomIDModel from hackathon_adhaar_solution.settings import MAX_LIMIT_OF_CONSENT_PER_LANDLORD REQUEST_STATUS = ( ("request_draft", "Request Drafted"), ("requested", "Consent Requested to landlord"), ("approved_by_landlord", "Approved by landlord"), ("rejected_by_landlord", "Rejected by landlord"), ("rejected_by_system", "Rejected by system"), ("failed_due_to_limit_reach_of_landlord", "Landlord has reached his limit of issuing consent ! Auto rejection"), ("updated", "Aadhaar Details Updated") ) class RequestRecord(RandomIDModel): txn_id = models.TextField(null=True, default="") mobile_no = models.CharField(max_length=15, null=True, default="") uid_hash = models.TextField(null=True, default="") eKyc_data = models.TextField(null=True, default="") landlord_mobile_no = models.CharField(max_length=15, null=True, default="") landlord_uid_hash = models.TextField(null=True, default="") landlord_eKyc_data = models.TextField(null=True, default="") status = models.CharField(max_length=50, choices=REQUEST_STATUS, null=True, default="request_draft") initiated_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) class AddressUpdateLog(models.Model): request_record = models.OneToOneField(RequestRecord, on_delete=models.CASCADE, related_name="address_update_log") uid = models.CharField(max_length=15, null=True, default="") previous_address = models.TextField(null=True, default="") updated_address = models.TextField(null=True, default="") created_on = models.DateTimeField(auto_now_add=True, null=True, blank=True) class ConsentCountLog(models.Model): uid_hash = models.TextField(null=True, default="", unique=True) consent_count = models.IntegerField(null=True, default=0) consent_limit = models.IntegerField(null=True, default=MAX_LIMIT_OF_CONSENT_PER_LANDLORD) <file_sep>/backend/run.sh source venv/bin/activate pip install -r requirements.txt python manage.py makemigrations python manage.py migrate python manage.py runserver<file_sep>/backend/hackathon_adhaar_solution/helper_functions/jwtutils.py from hackathon_adhaar_solution.settings import SECRET_KEY import datetime import jwt from jwt.exceptions import ExpiredSignatureError, InvalidSignatureError def encode(txnid, is_landlord=0): header = {'alg': 'HS256', "typ": "jwt"} payload = {'_txnid': str(txnid), '_landlord' : is_landlord, "exp": datetime.datetime.utcnow() + datetime.timedelta(days=30)} jwtt = jwt.encode(payload, SECRET_KEY, algorithm="HS256", headers=header) return jwtt def decode(data): try: jwt_payload = jwt.decode(data, SECRET_KEY, algorithms=["HS256"]) return True, jwt_payload["_txnid"], jwt_payload["_landlord"] except ExpiredSignatureError: return False, "expired" except InvalidSignatureError: return False, "invalid" except: return False, "unknown" <file_sep>/backend/audit_system/models.py from django.db import models from aadhaar_update_app.models import RequestRecord, AddressUpdateLog, REQUEST_STATUS class AuditLog(models.Model): request_id = models.CharField(max_length=50, null=True, editable=False) request_status_current = models.CharField(max_length=150, choices=REQUEST_STATUS, null=True) ip = models.TextField(default="NOT RECORDED", null=True) ip_details = models.TextField(default="{}", null=True) is_requester = models.BooleanField(null=True) message = models.TextField(null=True) error = models.TextField(null=True) is_error = models.BooleanField(null=True) event_timestamp = models.DateTimeField(auto_now_add=True, null=True) <file_sep>/backend/audit_system/migrations/0001_initial.py # Generated by Django 3.2.8 on 2021-10-30 14:54 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AuditLog', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('request_id', models.CharField(editable=False, max_length=50, null=True)), ('request_status_current', models.CharField(choices=[('request_draft', 'Request Drafted'), ('requested', 'Consent Requested to landlord'), ('approved_by_landlord', 'Approved by landlord'), ('rejected_by_landlord', 'Rejected by landlord'), ('rejected_by_system', 'Rejected by system'), ('failed_due_to_limit_reach_of_landlord', 'Landlord has reached his limit of issuing consent ! Auto rejection'), ('updated', 'Aadhaar Details Updated')], max_length=150, null=True)), ('ip', models.TextField(default='NOT RECORDED', null=True)), ('ip_details', models.TextField(default='{}', null=True)), ('is_requester', models.BooleanField(null=True)), ('message', models.TextField(null=True)), ('error', models.TextField(null=True)), ('is_error', models.BooleanField(null=True)), ('event_timestamp', models.DateTimeField(auto_now_add=True, null=True)), ], ), ]
90e40a994041ce975bb3b76e6c19bc87180943bf
[ "Markdown", "Python", "Text", "Shell" ]
22
Python
uidaitc/We_r_Titanicx_Aadhaar_Hackathon_Address_Update_Problem
ddbe8ab42bf9509124e998d35682880d119506c0
729e435f884e1c649f0efde03c3528936bf434b7
refs/heads/master
<file_sep># PolarNow - 有料アセットが必要です。(ホッキョククマ)/ Assetsの中に入れてください - https://assetstore.unity.com/packages/3d/characters/animals/polar-bear-cub-109403<file_sep>using System; using System.Collections; using UnityEngine; using System.Collections.Generic; using UnityEngine.SceneManagement; namespace UnityEngine.XR.iOS { public class UnityARHitTestExample : MonoBehaviour { //public変数として、Camera型の変数Camを宣言する public Camera cam; private Animator anim; //private bool isWalking = false; //private bool Sit = false; //private bool rotateFlag = false; //float speed = 120f; float step; public float moveSpeed = 2f; private bool isMoveArCamera = false; private bool isFirst = true; private GameObject arcamera; private Animator aranim; // 回り込み対応書きかけ //void Start() //{ // anim = GetComponent<Animator>(); // arcamera = GameObject.Find("CameraParent"); //} void Update() { // 回り込み対応のための書きかけ //if (isWalking == true) //{ // transform.Translate(0, 0, moveSpeed * Time.deltaTime); // anim.SetBool("IsWalk", true); //} //if(isMoveArCamera == true) { // arcamera.transform.Translate(0, 0, moveSpeed * Time.deltaTime * 10); //} //if (Input.touchCount > 0) //{ // //Debug.Log("A-String"); // //anim.SetBool("IsWalk", true); // //anim.SetBool("IsIdle", false); // //isWalking = true; // Touch touch = Input.GetTouch(0); // if (touch.phase == TouchPhase.Began) // { // // タッチ開始 // isMoveArCamera = true; // } // else if (touch.phase == TouchPhase.Moved) // { // // タッチ移動 // } // else if (touch.phase == TouchPhase.Ended) // { // // タッチ終了 // isMoveArCamera = false; // StartCoroutine(DelayMethod()); // } // if (isFirst) // { // isFirst = false; // } else { // } //} //if (Input.GetKeyDown("1")) //{ // beginWalk(); //} //if (Input.GetKeyDown("2")) //{ // stopWalk(); //} //if (Input.GetKeyDown("3")) //{ // fall(); //} //step = speed * Time.deltaTime; //if(rotateFlag) { // //指定した方向にゆっくり回転する場合 // //step = speed * Time.deltaTime; // //transform.localRotation = Quaternion.Slerp(transform.localRotation, Quaternion.Euler(0, 0, 90f), step); // transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.Euler(0, 0, 90f), step); // anim.SetFloat("MovingSpeed", 0.0f); //} // サンプルコード //if (Input.touchCount > 0 && cam != null) { // SceneManager.LoadScene ("Scenes/hackathon"); //} //if (Input.touchCount > 0 && cam != null) //{ ////CreatePrimitiveで動的にGameObjectであるCubeを生成する //GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); ////Cubeに適用するランダムな色を生成する //Material material = new Material(Shader.Find("Diffuse")) //{ // color = new Color(Random.value, Random.value, Random.value) //}; ////ランダムに変化する色をCubeに適用する //cube.GetComponent<Renderer>().material = material; ////Android端末をタップして、ランダムな色のCubeを認識した平面上に投げ出すように追加していく ////Cubeの大きさも0.2fとして指定している //cube.transform.position = cam.transform.TransformPoint(0, 0, 0.5f); //cube.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f); ////CubeにはRigidbodyを持たせて重力を与えておかないと、床の上には配置されないので注意が必要。Rigidbodyで重力を持たせないとCubeは宙に浮いた状態になる //cube.AddComponent<Rigidbody>(); //cube.GetComponent<Rigidbody>().AddForce(cam.transform.TransformDirection(0, 1f, 2f), ForceMode.Impulse); //} } // 回り込み対応のための書きかけ //void beginWalk() //{ // Debug.Log("A-String"); // anim.SetBool("IsWalk", true); // anim.SetBool("IsIdle", false); // isWalking = true; //} //void stopWalk() //{ // Debug.Log("A-String"); // anim.SetBool("IsWalk", false); // anim.SetBool("IsIdle", true); // isWalking = false; //} //void fall() //{ // Debug.Log("A-String"); // anim.SetBool("IsWalk", false); // anim.SetBool("IsIdle", false); // isWalking = false; // //transform.Rotate(new Vector3(0, 0, 1), -90); // rotateFlag = true; //} //IEnumerator DelayMethod() //{ // //delay秒待つ // yield return new WaitForSeconds(1.0f); // beginWalk(); // yield return new WaitForSeconds(4.0f); // stopWalk(); // yield return new WaitForSeconds(1.0f); // fall(); //} } }
6bef2bf52f0fef9f53665e0c0f01b028864d1c96
[ "Markdown", "C#" ]
2
Markdown
keix1/PolarNow
464229e4a38f3eab08e324491f1d512d3ccf4be4
c033bb7e2fa2977520144f20fb9956c2af322d6a
refs/heads/master
<file_sep>export { postgresConfig } from './postgres.config' export { mongoConfig } from './mongo.config'<file_sep>import { Injectable } from '@nestjs/common'; import { ResetPasswordDTO } from 'common/dtos'; import { User } from 'common/entities/postgres'; import { AuthService } from 'services/auth/auth.service'; @Injectable() export class SelfService { constructor(private authService: AuthService) {} myDetails(username: string) { return User.findOne({ username }); } async resetPassword(username: string, body: ResetPasswordDTO) { const user = await this.authService.validateUser({ username, password: <PASSWORD> }); this.authService.resetPassword(user.username, body.newPassword); return null; } } <file_sep>import { Length } from 'class-validator'; export class LoginDTO { @Length(1, 320) username: string; @Length(6, 60) password: string; } <file_sep>import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule } from '@nestjs/config'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { AuthModule } from 'services/auth/auth.module'; import { SelfModule } from 'routes/self/self.module'; import { LogModule } from './services/log/log.module'; import { mongoConfig, postgresConfig } from 'config'; @Module({ imports: [ ConfigModule.forRoot(), TypeOrmModule.forRoot(postgresConfig), TypeOrmModule.forRoot(mongoConfig), AuthModule, SelfModule, LogModule, ], controllers: [AppController], providers: [AppService], exports: [AppService], }) export class AppModule {} <file_sep>import { Injectable } from '@nestjs/common'; import { TrimBody } from './trim-body'; @Injectable() export class TrimStrings extends TrimBody { private except = ['Password', 'password', 'currentPassword', 'newPassword']; transform(key: string | number, value: any) { if (this.isString(value) && this.isString(key) && !this.except.includes(key)) { return value.trim(); } return value; } isString(value: any): value is string { return typeof value === 'string' || value instanceof String; } } <file_sep>import { ValidationPipe } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { QueryFailedErrorFilter } from 'common/filters'; import { TrimStrings } from 'common/interceptors/trim-strings'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalFilters(new QueryFailedErrorFilter()); app.useGlobalPipes(new ValidationPipe()); app.useGlobalInterceptors(new TrimStrings()); await app.listen(3000); } bootstrap(); <file_sep>import { LogDTO } from 'services/log/dtos/Log.dto'; import { Entity, ObjectID, ObjectIdColumn, Column, CreateDateColumn } from 'typeorm'; @Entity() export class Log { @ObjectIdColumn() id: ObjectID; @Column() type: string; @Column() detail: string; @Column() exception: any; @Column() req: any; @CreateDateColumn({ type: 'timestamp' }) createdAt: Date; constructor(log: LogDTO) { /** * Try yapmazsan javascript'e dönüştürünce hata veriyor * Typeorm constructoru olduğu gibi alıyor ama * Field'ların isimlerini dönüştürüyor * Bu yüzden this.username'yi bulamıyor */ try { this.type = log.type; this.detail = log.detail; this.exception = log.exception; this.req = log.req; } catch (error) {} } } <file_sep>import { SelfService } from './self.service'; import { SelfController } from './self.controller'; import { Module } from '@nestjs/common'; @Module({ imports: [], controllers: [SelfController], providers: [SelfService], }) export class SelfModule { } <file_sep>import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable() export class AuthGuard implements CanActivate { constructor(private authService: AuthService) {} canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> { try { const request = context.switchToHttp().getRequest(); const token = request.headers['authorization']; const user = this.authService.decryptToken(token); request.user = user; return !!request.user; } catch (error) { throw new ForbiddenException(); } } } <file_sep>export { UnAutharizedErrorFilter } from './unautharized-error.filter'; export { QueryFailedErrorFilter } from './query-failed-error.filter'; <file_sep>import { Injectable } from '@nestjs/common'; import { AuthService } from 'services/auth/auth.service'; import { LoginDTO, RegisterDTO } from 'common/dtos'; @Injectable() export class AppService { constructor(private authService: AuthService) {} async login(user: LoginDTO): Promise<{ access_token }> { const token = await this.authService.login(user); return { access_token: token }; } async register(user: RegisterDTO): Promise<null> { await this.authService.createUser(user); return null; } } <file_sep>import { TypeOrmModuleOptions } from "@nestjs/typeorm"; export const mongoConfig: TypeOrmModuleOptions = { name: 'mongo', type: 'mongodb', port: Number(process.env.mongo_port), host: process.env.mongo_host, database: process.env.mongo_database, entities: ['dist/common/entities/mongo/*.entity{.ts,.js}'], autoLoadEntities: true, synchronize: true, useUnifiedTopology: true, }<file_sep>import { Injectable, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import * as bcrypt from 'bcrypt'; import { LoginDTO, RegisterDTO } from 'common/dtos'; import { User } from 'common/entities/postgres'; import { InsertResult } from 'typeorm'; @Injectable() export class AuthService { constructor(private jwtService: JwtService) {} async createUser(user: RegisterDTO): Promise<InsertResult> { user.password = await this.hashPassword(user); return User.insert(user); } async hashPassword(user: RegisterDTO): Promise<string> { return await bcrypt.hash(user.password, 10); } async login(user: LoginDTO): Promise<string> { const { username } = await this.validateUser(user); return this.generateToken(username); } async validateUser(user: LoginDTO) { let kullanici = await User.findOne({ username: user.username }, { select: ['username', 'password'] }); if (!kullanici) { kullanici = await User.findOne({ email: user.username }, { select: ['username', 'password', 'email'] }); } if (!kullanici) { throw new UnauthorizedException('Kullanıcı bulunamadı'); } const validPassword = await bcrypt.compare(user.password, kullanici.password); if (!validPassword) { throw new UnauthorizedException('Kullanıcı adı veya parola hatalı'); } return kullanici; } generateToken(username: string): string { return this.jwtService.sign({ username }); } decryptToken(token: string): User { return this.jwtService.verify(token); } async resetPassword(username, newPassword) { return await User.update({ username }, { password: await bcrypt.hash(newPassword, 10) }); } } <file_sep>/* eslint-disable @typescript-eslint/ban-types */ import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common'; import { Observable } from 'rxjs'; export abstract class TrimBody implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { this.cleanBody(context.switchToHttp().getRequest()); return next.handle(); } cleanBody(req: any): void { if (req.method !== 'GET') { req.body = this.cleanObject(req.body); } } cleanObject(obj: object | null | undefined) { if (!obj) { return obj; } for (const key in obj) { const value = obj[key]; if (value instanceof Object) { this.cleanObject(value); } else { obj[key] = this.transform(key, value); } } return obj; } abstract transform(key: string | number, value: boolean | number | string | null | undefined): any; } <file_sep>import { Global, Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { JwtModule } from '@nestjs/jwt'; import { AuthService } from './auth.service'; @Global() @Module({ imports: [ ConfigModule.forRoot(), JwtModule.register({ secret: process.env.jwt_secret, signOptions: { expiresIn: '12h' } }), ], controllers: [], providers: [AuthService], exports: [AuthService], }) export class AuthModule {} <file_sep>import { Body, Controller, Post, UseFilters } from '@nestjs/common'; import { LoginDTO, RegisterDTO } from 'common/dtos'; import { UnAutharizedErrorFilter } from 'common/filters/unautharized-error.filter'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @Post('/login') @UseFilters(UnAutharizedErrorFilter) login(@Body() body: LoginDTO): Promise<{ access_token }> { return this.appService.login(body); } @Post('/register') register(@Body() body: RegisterDTO): Promise<null> { return this.appService.register(body); } } <file_sep>import { Length } from 'class-validator'; import { Confirm } from 'common/decorators/Confirm.decorator'; export class ResetPasswordDTO { @Length(6, 60) currentPassword: string; @Length(6, 60) @Confirm('currentPassword', {message: 'Current password cannot be the same as the new password'}) newPassword: string; } <file_sep>export class LogDTO { type: string; detail: string; exception?: any; req?: any; } <file_sep>import { Get, Controller, UseGuards, Post, Body } from '@nestjs/common'; import { User as UserData } from 'common/decorators'; import { ResetPasswordDTO } from 'common/dtos'; import { User } from 'common/entities/postgres'; import { AuthGuard } from 'services/auth/auth.guard'; import { SelfService } from './self.service'; @UseGuards(AuthGuard) @Controller('self') export class SelfController { constructor(private selfService: SelfService) {} @Get('/') myDetails(@UserData() user: User) { return this.selfService.myDetails(user.username); } @Post('/resetPassword') resetPassword(@UserData() user: User, @Body() body: ResetPasswordDTO) { return this.selfService.resetPassword(user.username, body); } } <file_sep>import { TypeOrmModuleOptions } from "@nestjs/typeorm"; export const postgresConfig: TypeOrmModuleOptions = { type: 'postgres', username: process.env.psql_username, password: <PASSWORD>, port: Number(process.env.psql_port), host: process.env.psql_host, database: process.env.psql_database, entities: ['dist/common/entities/postgres/*.entity{.ts,.js}'], autoLoadEntities: true, synchronize: true, }<file_sep>import { getMongoManager } from 'typeorm'; import { Injectable } from '@nestjs/common'; import { LogDTO } from './dtos/Log.dto'; import { Log } from 'common/entities/mongo'; @Injectable() export class LogService { private Log = getMongoManager('mongo'); saveLog(log: LogDTO) { return this.Log.save(new Log(log)); } } <file_sep>import { ExceptionFilter, Catch, ArgumentsHost, UnauthorizedException } from '@nestjs/common'; import { Response } from 'express'; @Catch(UnauthorizedException) export class UnAutharizedErrorFilter implements ExceptionFilter { catch(exception: UnauthorizedException, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse<Response>(); const status = exception.getStatus(); response.status(status).json({ statusCode: status, message: exception.message, }); } } <file_sep>import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common'; import { Response, Request } from 'express'; import { LogService } from 'services/log/log.service'; import { QueryFailedError } from 'typeorm'; @Catch(QueryFailedError) export class QueryFailedErrorFilter implements ExceptionFilter { catch(exception: QueryFailedError, host: ArgumentsHost) { const ctx = host.switchToHttp(); const req = ctx.getRequest<Request>(); const res = ctx.getResponse<Response>(); const request = { method: req.method, headers: req.headers, body: req.body, originalUrl: req.originalUrl, cookies: req.cookies, ip: req.ip, }; switch (exception['code']) { case '23505': const error = { statusCode: HttpStatus.CONFLICT, message: 'Hali hazırda var olan anahtar', details: exception['detail'].replace(/\"/g, ''), }; return res.status(HttpStatus.CONFLICT).json(error); default: const logService = new LogService(); logService.saveLog({ type: 'QueryFailedError', detail: exception['detail'] || '', exception, req: request, }); return res.status(500).json('Sistemsel bir hata meydana geldi'); } } } <file_sep>import { IsEmail } from 'class-validator'; import { BaseEntity, Check, Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, Unique, UpdateDateColumn, } from 'typeorm'; @Entity('Users') @Unique(['username', 'email']) export class User extends BaseEntity { @PrimaryGeneratedColumn('increment') id: number; @Column({ length: 320 }) @IsEmail() email: string; @Column({ length: 50 }) username: string; @Column({ type: 'char', select: false, length: 60 }) @Check('check-minlen', 'length(password) >= 6') password: string; // @Column('timestamp with time zone', { nullable: false, default: () => 'CURRENT_TIMESTAMP' }) @CreateDateColumn({ type: 'timestamp' }) createdAt: Date; @UpdateDateColumn({ type: 'timestamp', nullable: true }) updatedAt?: Date; }
828ccd4aaa75f5e1c46f92cdeb8c0719238ee469
[ "TypeScript" ]
24
TypeScript
virtueer/nest-scaffold
2095bd92b8a322003fd5bf1582801fa01d4d7afb
c59abad704dc536a270dc7fec3b42013ae219876
refs/heads/master
<repo_name>Yuval938/flight-ex3<file_sep>/ConnectControlClientCommand.h // // Created by yuval on 21/12/2019. // #ifndef UNTITLED13_CONNECTCONTROLCLIENTCOMMAND_H #define UNTITLED13_CONNECTCONTROLCLIENTCOMMAND_H #include "globals.h" class ConnectControlClientCommand:public Command { public: virtual ~ConnectControlClientCommand(){} ConnectControlClientCommand(){} int execute(string str); bool ClientisConnected=false; int RunClient(string ipAsString, int port); }; #endif //UNTITLED13_CONNECTCONTROLCLIENTCOMMAND_H <file_sep>/ConditionParser.h // // Created by valdman40 on 12/21/19. // #ifndef UNTITLED13_CONDITIONPARSER_H #define UNTITLED13_CONDITIONPARSER_H #include "globals.h" class ConditionParser : public Command { public: ConditionParser() {} // void replaceAll(std::string &str, const std::string &from, const std::string &to); }; #endif //UNTITLED13_CONDITIONPARSER_H <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(untitled13) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_FLAGS -pthread) add_executable(untitled13 main.cpp globals.cpp globals.h DefineVarCommand.cpp DefineVarCommand.h OpenDataServerCommand.cpp OpenDataServerCommand.h ConnectControlClientCommand.cpp ConnectControlClientCommand.h WhileCommand.cpp WhileCommand.h SleepCommand.cpp SleepCommand.h PrintCommand.cpp PrintCommand.h IfCommand.cpp IfCommand.h ex1.cpp ex1.h Command.h Command.cpp ConditionParser.cpp ConditionParser.h)<file_sep>/ex1.h // // Created by valdman40 on 11/10/19. // #include <iostream> #include <stack> #include <regex> #ifndef UNTITLED13_H #define UNTITLED13_H using namespace std; // Function to convert Infix expression to postfix string InfixToPostfix(string mathExpression); // // Function to verify whether a char is a part of number or not. bool IsNumber(char ch); // Function to evaluate operator according to the assignment demands. int operatorValue(char c); // Function to verify whether a string is a valid var according to the assignment or not. bool varIsValid(string basicString); // Function to verify whether a string is a number (int\double) or not. bool valueIsValid(string basicString); // Function to verify whether a character is operator symbol or not. bool IsOperator(char C); bool isLetter(char ch); /** * Expression Interface */ class Expression { public: virtual double calculate() = 0; virtual ~Expression() {} }; Expression &action(Expression *operand1, Expression *operand2, char optor); Expression &evaluatePostfix(string str); /** * Value Class */ class Value : public Expression { private: double value; public: Value(double num); double calculate(); }; /** * BinaryOperator Interface */ class BinaryOperator : public Expression { protected: Expression *Bright; Expression *Bleft; public: BinaryOperator(Expression *left, Expression *right); virtual double calculate() = 0; ~BinaryOperator() { delete (Bleft); delete (Bright); }; }; /** * Variable Class */ class Variable : public Expression { protected: string expName; double value; public: Variable(string name, double num); double calculate(); Variable &operator++(); Variable &operator--(); Variable &operator+=(double valToAdd); Variable &operator-=(double valToDec); Variable &operator++(int); Variable &operator--(int); }; /** * Plus Class */ class Plus : public BinaryOperator { public: Plus(Expression *Bleft, Expression *Bright); double calculate(); }; /** * Minus Class */ class Minus : public BinaryOperator { public: Minus(Expression *Bleft, Expression *Bright); double calculate(); }; /** * Mul Class */ class Mul : public BinaryOperator { public: Mul(Expression *Bleft, Expression *Bright); double calculate(); }; /** * Div Class */ class Div : public BinaryOperator { public: Div(Expression *Bleft, Expression *Bright); double calculate(); }; /** * UnaryOperator Interface */ class UnaryOperator : public Expression { protected: Expression *Ue; public: UnaryOperator(Expression *e); virtual double calculate() = 0; ~UnaryOperator() { delete (this->Ue); }; }; /** * UPlus Class */ class UPlus : public UnaryOperator { public: UPlus(Expression *e); double calculate(); }; /** * UMinus Class */ class UMinus : public UnaryOperator { public: UMinus(Expression *e); double calculate(); }; /** * Interpreter Class */ class Interpreter { protected: std::map<string, string> variables; public: Expression *interpret(string); void setVariables(string); }; #endif //UNTITLED13_H <file_sep>/globals.cpp // // Created by valdman40 on 12/24/19. // #include "globals.h" map<string, Var> SymbolTable; map<string, Command *> CommandList; thread threads[2]; queue<string> SetCommands; bool endOfFile; bool is_number(const std::string &s) { std::string::const_iterator it = s.begin(); while (it != s.end() && std::isdigit(*it)) ++it; return !s.empty() && it == s.end(); } void replaceAll(std::string &str, const std::string &from, const std::string &to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } void updateVarValue(string var, string str) { // need to make the Expression Interpreter *in = makeInterpeter(); Expression *e; int posOfEq = str.find('=') + 2; int posOfEndl = str.find("endl "); str = str.substr(posOfEq, posOfEndl - posOfEq - 1); std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' '); str.erase(end_pos, str.end()); try { e = in->interpret(str); SymbolTable[var].setValue(e->calculate()); string set = SymbolTable[var].getType() + " " + SymbolTable[var].getSim() + " " + to_string(SymbolTable[var].getValue()) + "\r\n"; SetCommands.push(set); } catch (const std::exception &) { cout << "error at updateVarValue" << endl; } } Interpreter *makeInterpeter() { Interpreter *i = new Interpreter(); for (auto item: SymbolTable) { i->setVariables(item.first + "=" + std::to_string(item.second.getValue())); } return i; } int executeFromContent(std::vector<std::string> content, int position, map<string, Command *> CommandsMap) { bool gotCurlyBraces = false; int pos; int posOfRoundBrace = content[position].find("("); int posOfFirstSpace = content[position].find(" "); int posOfCloseCurlyBrace = content[position].find("}"); if (posOfRoundBrace == -1) { //means there was no '(' pos = posOfFirstSpace; } else if (posOfFirstSpace == -1) { //means there was no space pos = posOfRoundBrace; } else { pos = min(posOfFirstSpace, posOfRoundBrace); // take the first of them } if (posOfCloseCurlyBrace >= 0) { pos = 0; } string command = content[position].substr(0, pos); // get the first word string ExecuteInfo = content[position].substr(pos) + " endl "; // get the rest of the line if (content[position].find('{') != string::npos) { gotCurlyBraces = true; position++; } while (gotCurlyBraces) { if (content[position].find('}') != string::npos) { gotCurlyBraces = false; position--; } else { ExecuteInfo += content[position] + " endl "; position++; } } Command *c = CommandsMap[command]; if (c != NULL) { c->execute(ExecuteInfo); } else { // for now, we assume that if it's not a command, it's probably a defined var if (command.compare("}") != 0 && command.compare("") != 0) { cout << "updating \"" << command << "\"" << endl; updateVarValue(command, ExecuteInfo); } } return position; }<file_sep>/WhileCommand.cpp // // Created by yuval on 21/12/2019. // #include "WhileCommand.h" #include "globals.h" int WhileCommand::execute(string str) { cout << "WHILE_COMMAND: " << endl; // we want to split each line std::vector<std::string> content; replaceAll(str, "\t", ""); int i, strLen = str.length(); bool readingFirstLine = true; string conditionLine = ""; string line = ""; for (i = 0; i < strLen; i++) { string word = ""; while (str.at(i) != ' ') { word += str.at(i); i++; } if (word.compare("}") != 0) { line += word + " "; if (word.compare("endl") == 0) { //we're at the end of the line if (readingFirstLine) { conditionLine = line; readingFirstLine = false; } else { content.push_back(line); } line = ""; } } else { break; } } conditionLine.erase(conditionLine.begin(), std::find_if(conditionLine.begin(), conditionLine.end(), std::bind1st(std::not_equal_to<char>(), ' '))); string leftSide = ""; // example of str: warp -> sim("/sim/time/warp") endl int pos = conditionLine.find(" "); // getting the first space if (pos > 0) { leftSide = conditionLine.substr(0, pos); // getting first substring until first space } else { leftSide = conditionLine; } conditionLine = conditionLine.substr(pos + 1); // desposing the var now got left with: -> sim("/sim/time/warp") endl pos = conditionLine.find(" "); // getting the second space string operand = conditionLine.substr(0, pos); // getting the arrow conditionLine = conditionLine.substr(pos + 1); // now we got left with: sim("/sim/time/warp") endl pos = conditionLine.find("{"); // getting the third space string rightSide = conditionLine.substr(0, pos); replaceAll(rightSide, " ", ""); replaceAll(leftSide, " ", ""); string numberString; string var; if (leftSide.at(0) >= '0' && leftSide.at(0) <= '9') { numberString = leftSide; var = rightSide; } else if (rightSide.at(0) >= '0' && rightSide.at(0) <= '9') { numberString = rightSide; var = leftSide; } else { cout << "error, one of the sides isnt a number" << endl; } Interpreter *in = new Interpreter(); Expression *e; e = in->interpret(numberString); double number = e->calculate(); // SymbolTable[var].setValue(1); int contentSize = content.size(); if (operand.compare("<=") == 0) { while (SymbolTable[var].getValue() <= number) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } //cout << "ddd" << endl; //SymbolTable["rpm"].setValue(SymbolTable["rpm"].getValue() + 1); } } else if (operand.compare("<") == 0) { while (SymbolTable[var].getValue() < number) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } //cout << "fff" << endl; // SymbolTable["alt"].setValue(SymbolTable["alt"].getValue() + 20); } } else if (operand.compare(">=") == 0) { while (SymbolTable[var].getValue() >= number) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } } } else if (operand.compare(">") == 0) { while (SymbolTable[var].getValue() > number) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } } } else if (operand.compare("==") == 0) { while (SymbolTable[var].getValue() - number < 0.00000001) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } } } else if (operand.compare("!=") == 0) { while (SymbolTable[var].getValue() != number) { i = 0; while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } } } return 0; }<file_sep>/PrintCommand.cpp // // Created by yuval on 21/12/2019. // #include "PrintCommand.h" int PrintCommand::execute(string str) { //cout << "printing using this string: " << str << endl; cout << "PRINT_COMMAND: " << flush; int posOpenBrace = str.find("("); int posCloseBrace = str.find(")"); str = str.substr(posOpenBrace + 1, posCloseBrace - posOpenBrace - 1); if ( SymbolTable.find(str) == SymbolTable.end() ) { // not found - so we print the string inside the PrintCommand cout << str << endl; } else { // found - print var and it's value cout << str << " = " << SymbolTable[str].getValue() << endl; } return 0; }<file_sep>/README.md # Flight Simulator Interpreter This Project interprets a text file into a code that run's FlightGear simulator. this program will run in multithreaded application: - main theard reads the text file and interprets it - second thread connect's to the simulator as a server and receives data from the air craft in real time (the data is pre-determined by a generic xml file) - third thread will connect to the simulator as a client and will send commands to the aircraft as desired ### Prerequisites [FlightGear](https://www.flightgear.org/download/) (Flight Simulator): Version 2019.1.1 Versions c++14 and below are allowed for the project ### Installing 1.Clone the project: ```bash git clone https://github.com/Yuval938/flight-ex3.git ``` 2.Install FlightGear: after the installation make sure you have a generic file so the simulator will know what information to send to our server. (the xml file should be placed in "./FlightGear/protocol/") 3.Compiling: ```bash g++ -std=c++14 *.cpp -Wall -Wextra -Wshadow -Wnon-virtual-dtor -pedantic -o FGinterpreter.out -pthread ``` ### Running the application: 1.You should first run the application with the desired text file (we used fly.txt): ```bash ./a.out text_file.txt ``` 2.Run FlightGear: insert the following commands in FlightGear settings: ```bash --telnet=socket,in,10,127.0.0.1,5402,tcp=8080 --generic=socket,out,10,127.0.0.1,5400,tcp,generic_small ``` ## Authors * **<NAME>** * **<NAME>** <file_sep>/Command.cpp // // Created by valdman40 on 12/19/19. // #include "Command.h" <file_sep>/IfCommand.h // // Created by valdman40 on 12/25/19. // #ifndef EX3_4_IFCOMMAND_H #define EX3_4_IFCOMMAND_H #include <algorithm> #include "ConditionParser.h" using namespace std; class IfCommand: public ConditionParser { public: IfCommand() {} int execute(string str); }; #endif //EX3_4_IFCOMMAND_H <file_sep>/globals.h // // Created by valdman40 on 12/24/19. // #ifndef UNTITLED13_GLOBALS_H #define UNTITLED13_GLOBALS_H #include <fstream> #include <vector> #include <map> #include "Command.h" #include "Var.h" #include <queue> #include "ex1.h" extern map<string, Var> SymbolTable; extern map<string, Command *> CommandList; extern thread threads[2]; extern queue <string> SetCommands; extern bool endOfFile; Interpreter *makeInterpeter(); bool is_number(const std::string &s); void updateVarValue(string var, string str); void replaceAll(std::string &str, const std::string &from, const std::string &to); Interpreter *makeInterpeter(); int executeFromContent(std::vector<std::string> content, int position, map<string, Command *> CommandsMap); #endif //UNTITLED13_GLOBALS_H <file_sep>/DefineVarCommand.cpp // // Created by yuval on 17/12/2019. // #include "DefineVarCommand.h" DefineVarCommand::DefineVarCommand(){} /* * DefineVarCommand::execute(string str) will make a new Var Object and will insert it to our map. */ int DefineVarCommand::execute(string str) { cout << "making a Var Object using this string: " << str << endl; str.erase(str.begin(), std::find_if(str.begin(), str.end(), std::bind1st(std::not_equal_to<char>(), ' '))); // example of str: warp -> sim("/sim/time/warp") endl int pos = str.find(" "); // getting the first space string var = str.substr(0, pos); // getting first substring until first space str = str.substr(pos + 1); // desposing the var now got left with: -> sim("/sim/time/warp") endl pos = str.find(" "); // getting the second space string arrow = str.substr(0, pos); // getting the arrow str = str.substr(pos + 1); // now we got left with: sim("/sim/time/warp") endl pos = str.find(" "); // getting the third space string sim = str.substr(0, pos); pos = sim.find("\""); sim = sim.substr(pos + 1); pos = sim.find("\""); sim = sim.substr(0, pos); bool defineVarWithoutPath = false; string var2 = ""; string type = "error"; if (arrow.compare("<-") == 0) { type = "get"; } else if (arrow.compare("->") == 0) { type = "set"; } else if (arrow.compare("=") == 0) { defineVarWithoutPath = true; var2=sim; type = "set"; } if (!defineVarWithoutPath) { SymbolTable[var] = Var(type, sim); } else { sim =""; // cause we dont have path SymbolTable[var] = Var("set", sim); if ( SymbolTable.find("f") == SymbolTable.end() ) { // not found so it's must be number SymbolTable[var].setValue(atof(var2.c_str())); } else { // found so we'll take the value in the map SymbolTable[var].setValue(SymbolTable[var2].getValue()); } } return 0; } //make a new var object;<file_sep>/PrintCommand.h // // Created by yuval on 21/12/2019. // #ifndef UNTITlED13_PRINTCOMMAND_H #define UNTITLED13_PRINTCOMMAND_H #include "globals.h" class PrintCommand : public Command { public: virtual ~PrintCommand() {} PrintCommand() {} int execute(string str); }; #endif //UNTITLED13_PRINTCOMMAND_H <file_sep>/ConnectControlClientCommand.cpp // // Created by yuval on 21/12/2019. // #include "ConnectControlClientCommand.h" #include <sys/socket.h> #include <string> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> /* * execute command in this object will break down the string to a string(ip) and an int (port) , the port is calculated * via Interpreter (that we made in HW1) in order to treat expressions like 5000+400 (instead of 5400) * after that execute() will open a new thread and will run RunClient() on that thread. */ int ConnectControlClientCommand::execute(string str) { cout << "Connecting to Control Client using this string: " << str << endl; //example --> ("127.0.0.1",5402) int pos = 0; // getting the first space pos = str.find("\""); string ip = str.substr(pos + 1); string port = ip; pos = ip.find("\""); int pos2 = ip.find(','); ip = ip.substr(0, pos); port = port.substr(pos2 + 1); pos = port.find(')'); port = port.substr(0, pos); replaceAll(port, " ", ""); Interpreter *i = new Interpreter(); int portAsInt = (i->interpret(port))->calculate(); threads[1] = thread(&ConnectControlClientCommand::RunClient, this, ip, portAsInt); //main thread will wait until the Client connected successfully while (ClientisConnected == false) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } return 0; } /* * RunClient() will connect to a server as a client and will send massages to that server. * way of operation: * -connect's to server * -check's if there's any string in the Command Queue to output to the server * outputs the string to the server. */ int ConnectControlClientCommand::RunClient(string ipAsString, int PORT) { //create socket const char *ip = ipAsString.c_str(); int client_socket = socket(AF_INET, SOCK_STREAM, 0); if (client_socket == -1) { //error std::cerr << "Could not create a socket" << std::endl; return -1; } //We need to create a sockaddr obj to hold address of server sockaddr_in address; //in means IP4 address.sin_family = AF_INET;//IP4 address.sin_addr.s_addr = inet_addr(ip); //the localhost address address.sin_port = htons(PORT); //we need to convert our number (both port & localhost) // to a number that the network understands. // Requesting a connection with the server on local host with port 8081 int is_connect = connect(client_socket, (struct sockaddr *) &address, sizeof(address)); if (is_connect == -1) { std::cerr << "Could not connect to host server" << std::endl; return -2; } else { std::cout << "Client is now connected to server" << std::endl; ClientisConnected = true; } //if here we made a connection //the server will see if there's a set command for him in queue and if so - he will use it // string sim = "set "+rudder+" 1\r\n"; while (!endOfFile) { //will replace with a better condition.. if (!SetCommands.empty()) { string command = SetCommands.front(); int is_sent = send(client_socket, command.c_str(), command.size(), 0); if (is_sent == -1) { std::cout << "Error sending message" << std::endl; } else { SetCommands.pop(); } } } close(client_socket); return 0; }<file_sep>/SleepCommand.h // // Created by valdman40 on 12/21/19. // #ifndef EX3_2_SLEEPCOMMAND_H #define EX3_2_SLEEPCOMMAND_H #include "globals.h" #include <thread> #include <chrono> class SleepCommand : public Command { public: virtual ~SleepCommand() {} SleepCommand() {} int execute(string str); }; #endif //EX3_2_SLEEPCOMMAND_H <file_sep>/WhileCommand.h // // Created by yuval on 21/12/2019. // #ifndef EX3_WHILECOMMAND_H #define EX3_WHILECOMMAND_H #include "ConditionParser.h" using namespace std; class WhileCommand : public ConditionParser{ public: WhileCommand() {} int execute(string str); }; #endif //EX3_WHILECOMMAND_H <file_sep>/Command.h // // Created by yuval on 17/12/2019. // #ifndef UNTITLED8_COMMAND_H #define UNTITLED8_COMMAND_H using namespace std; #include <iostream> #include <map> #include <vector> #include <thread> #include "Var.h" #include "Var.cpp" #include <regex> /** * Command Interface */ class Command { public: virtual int execute(string str)=0; virtual ~Command() {} }; #endif //UNTITLED8_COMMAND_H <file_sep>/SleepCommand.cpp // // Created by valdman40 on 12/21/19. // #include "SleepCommand.h" int SleepCommand::execute(string str) { // cout << "sleep for this time: " << str << endl; cout << "SLEEP_COMMAND-> " << flush; int posOpenBrace = str.find("("); int posCloseBrace = str.find(")"); str = str.substr(posOpenBrace + 1, posCloseBrace - posOpenBrace - 1); Interpreter *i = new Interpreter(); int ms = (i->interpret(str))->calculate(); cout << "sleeps for "<< ms << " milliseconds"<< endl; std::this_thread::sleep_for(std::chrono::milliseconds(ms)); return 0; }<file_sep>/main.cpp #include <vector> #include <map> #include "DefineVarCommand.h" //#include "DefineVarCommand.cpp" #include "WhileCommand.h" //#include "WhileCommand.cpp" #include "ex1.h" #include "OpenDataServerCommand.h" //#include "OpenDataServerCommand.cpp" #include "ConnectControlClientCommand.h" //#include "ConnectControlClientCommand.cpp" #include "PrintCommand.h" //#include "PrintCommand.cpp" #include "SleepCommand.h" //#include "SleepCommand.cpp" #include "IfCommand.h" #include "globals.h" //#include "IfCommand.cpp" //#include "globals.cpp" using namespace std; std::vector<std::string> split(const std::string &s, char c); bool ignoreChars(char ch); void MakeCommandMap(); void updateVarValue(string basicString, string basicString1); int min(int a, int b) { if (a < b) { return a; } return b; } int main(int argc, char *argv[]) { string path = "fly.txt"; if(argc > 0) { path = argv[1]; } MakeCommandMap(); std::string file_path(path); // I assumed you have that kind of file std::ifstream in_s(file_path); std::vector<std::string> content; ifstream file(path); string line; while (std::getline(file, line)) { content.push_back(line); } endOfFile = false; // at this point, content contains fly.txt line by line. int i = 0, contentSize = content.size(); while (i < contentSize) { i = executeFromContent(content, i, CommandList) + 1; } endOfFile = true; threads[0].join(); threads[1].join(); return 0; } void MakeCommandMap() { CommandList["var"] = new DefineVarCommand(); CommandList["while"] = new WhileCommand(); CommandList["if"] = new IfCommand(); CommandList["openDataServer"] = new OpenDataServerCommand(); CommandList["connectControlClient"] = new ConnectControlClientCommand(); CommandList["Print"] = new PrintCommand(); CommandList["Sleep"] = new SleepCommand(); }<file_sep>/Var.cpp // // Created by yuval on 19/12/2019. // #include "Var.h" <file_sep>/ex1.cpp // // Created by valdman40 on 11/10/19. // #include "ex1.h" Variable &Variable::operator++() { double temp = this->value; ++temp; this->value = temp; return *this; } Variable &Variable::operator++(int) { double temp = this->value; ++temp; this->value = temp; return *this; } Variable &Variable::operator--() { double temp = this->value; --temp; this->value = temp; return *this; } Variable &Variable::operator--(int) { double temp = this->value; --temp; this->value = temp; return *this; } Variable &Variable::operator+=(double valToAdd) { this->value = this->value + valToAdd; return *this; } Variable &Variable::operator-=(double valToDec) { this->value = this->value - valToDec; return *this; } Variable::Variable(string name, double num) { this->expName = name; this->value = num; } UnaryOperator::UnaryOperator(Expression *e) { this->Ue = e; } BinaryOperator::BinaryOperator(Expression *left, Expression *right) { this->Bleft = left; this->Bright = right; } Value::Value(double num) { this->value = num; } UPlus::UPlus(Expression *e) : UnaryOperator(e) { this->Ue = e; } UMinus::UMinus(Expression *e) : UnaryOperator(e) { this->Ue = e; } Plus::Plus(Expression *left, Expression *right) : BinaryOperator(left, right) { this->Bleft = left; this->Bright = right; } Minus::Minus(Expression *left, Expression *right) : BinaryOperator(left, right) { this->Bleft = left; this->Bright = right; } Div::Div(Expression *left, Expression *right) : BinaryOperator(left, right) { this->Bleft = left; this->Bright = right; } Mul::Mul(Expression *left, Expression *right) : BinaryOperator(left, right) { this->Bleft = left; this->Bright = right; } double UMinus::calculate() { return -(this->Ue->calculate()); } double UPlus::calculate() { return (this->Ue->calculate()); } double Div::calculate() { double right = this->Bright->calculate(); if (right == 0) { throw "division by zero"; } else { return this->Bleft->calculate() / right; } } double Mul::calculate() { return this->Bleft->calculate() * this->Bright->calculate(); } double Variable::calculate() { return (this->value); } double Plus::calculate() { return this->Bleft->calculate() + this->Bright->calculate(); } double Minus::calculate() { return this->Bleft->calculate() - this->Bright->calculate(); } double Value::calculate() { return this->value; } bool IsNumber(char ch) { if ((ch >= '0' && ch <= '9') || ch == '.') { return true; } return false; } bool IsOperator(char C) { if (C == '+' || C == '-' || C == '*' || C == '/' || C == '&' || C == '%') { return true; } return false; } bool areParenthesisBalanced(string expr) { stack<char> s; char x; int length = expr.length(); for (int i = 0; i < length; i++) { x = expr.at(i); if (x == '(') { s.push(x); } else if (x == ')') { if ((!s.empty()) && (s.top() == '(')) { s.pop(); } else { // there was no matching pair for this Parenthesis return false; } } } return true; } bool validMathExpression(string expression) { int length = expression.length(); char ch = expression.at(0); if (ch == '*' || ch == '/' || ch == ')') { return false; } for (int i = 0; i < length; i++) { ch = expression.at(i); if (!IsNumber(ch) && !IsOperator(ch) && ch != ('(') && ch != (')') && ch != '.') { return false; } if (i > 0) { if ((ch == '-' && expression.at(i - 1) == '-') || (ch == '+' && expression.at(i - 1) == '+') || (ch == '*' && expression.at(i - 1) == '*') || (ch == '/' && expression.at(i - 1) == '/')) { return false; } } // check if we got ')(' in a row if( (i < length - 1) && ch == ')' && expression.at(i + 1) == '('){ return false; } } // the string is a valid expression, now we check if it's parenthesis are valid return areParenthesisBalanced(expression); } bool isLetter(char ch) { if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { return false; } return true; } bool validSetVeriableInput(string str) { // check all of the string if it has illigal chars int length = str.length(); char ch = str.at(0); for (int i = 1; i < length; i++) { ch = str.at(i); if (!isLetter(ch) && !IsNumber(ch) && !IsOperator(ch) && ch != '=' && ch != ';' && ch != '_') { if (!isLetter(ch) && !IsNumber(ch) && !IsOperator(ch) && ch != '=' && ch != ';' && ch != '_') { return false; } if ((ch == ';' && str.at(i - 1) == ';') || (ch == '=' && str.at(i - 1) == '=') || (ch == '_' && str.at(i - 1) == '_')) { return false; } } } // check for every var and val if they are valid as well int start = 0; for (int i = 0; i < length; i++) { if (str[i] == ';' || i == length - 1) { if (i == length - 1) { i++; } string substr = str.substr(start, i - start); // now we got substring from ';' to ';' int substrLength = substr.length(); string var = ""; int j = 0; while (j < substrLength && (substr.at(j) != '=')) { var += substr.at(j); j++; } if (!varIsValid(var)) { return false; } j++; string value = ""; while (j < substrLength && (substr.at(j) != ';')) { value += substr.at(j); j++; } if (!valueIsValid(value)) { return false; } start = i + 1; } } return true; } bool valueIsValid(string value) { int length = value.length(); if (value.at(0) == '.') { return false; } for (int i = 0; i < length; i++) { if (!IsNumber(value.at(i)) && value.at(i) != '-') { // check that each char in the value is actually a number or '.' , '-' return false; } } return true; } bool varIsValid(string var) { char firstChar = var.at(0); if (!isLetter(firstChar)) { return false; } int length = var.length(); for (int i = 1; i < length; i++) { if (i == 1) { // part of the assignment demands if (var.at(i) == ';' || var.at(i) == '=' || IsOperator(var.at(i))) { return false; } } if (var.at(i) == '.' || var.at(i) == ';' || var.at(i) == '=') return false; } return true; } int operatorValue(char c) { if (c == '*' || c == '/') return 2; else if (c == '+' || c == '-') return 1; else if (c == '&' || c == '%') return 3; else return -1; } string InfixToPostfix(string mathExpression) { stack<char> operatorStack; char token; string postfix = ""; string infixString = ""; int length = mathExpression.length(); // first, we'll make all the unary numbers more visual for us, we'll sign // them with '&' (for UMinus) and '%' (for UPlus) for (int i = 0; i < length; i++) { token = mathExpression.at(i); if (token == '-' || token == '+') { if (i == 0 || mathExpression.at(i - 1) == '(' || mathExpression.at(i - 1) == '/' || mathExpression.at(i - 1) == '*') { if (token == '-') { infixString += "&"; } else { infixString += "%"; } } else { infixString += token; } } else { infixString += token; } } bool writingANum = false; for (int i = 0; i < length; i++) { token = infixString.at(i); // Reads the next token each loop if (IsNumber(token)) { if (writingANum) { postfix += token; // because we dont need a space } else { postfix = postfix + " " + token; } writingANum = true; } else if (IsOperator(token)) { writingANum = false; while (!operatorStack.empty() && (operatorValue(token) <= operatorValue(operatorStack.top()))) { postfix = postfix + " " + operatorStack.top(); operatorStack.pop(); } operatorStack.push(token); } else if (token == '(') { operatorStack.push(token); } else if (token == ')') { while (operatorStack.top() != '(') { postfix = postfix + " " + operatorStack.top(); operatorStack.pop(); } operatorStack.pop(); // discard '(' } } while (!operatorStack.empty()) { postfix = postfix + " " + operatorStack.top(); operatorStack.pop(); } return postfix; } stack<string> getSubStrings(string str, char separator) { stack<string> s; int i = 0; int len = str.length(); while (i < len) { // separating each substrings (stops when engage separator) int startSubString = i; while (i < len && separator != str.at(i)) { // here need to add illegal characters check i++; } int subStringLength = i - startSubString; string subString = str.substr(startSubString, subStringLength); s.push(subString); i++; } return s; } void Interpreter::setVariables(string str) { if (!validSetVeriableInput(str)) { throw "illegal variable assignment!"; } stack<string> subStrings = getSubStrings(str, ';'); while (!subStrings.empty()) { stack<string> varAndVal = getSubStrings(subStrings.top(), '='); string value = varAndVal.top(); varAndVal.pop(); string var = varAndVal.top(); this->variables[var] = value; subStrings.pop(); } } Expression *Interpreter::interpret(string str) { for (auto const &x : this->variables) { str = regex_replace(str, regex(x.first), "(" + x.second + ")"); } // check if there are still characters in the expression bool legal = true; int length = str.length(); for (int i = 0; i < length; i++) { if (isLetter(str.at(i))) { legal = false; break; } } if (!validMathExpression(str) || !legal) { throw "illegal math expression"; } string pfString = InfixToPostfix(str); return &evaluatePostfix(pfString); } Expression &evaluatePostfix(string str) { stack<Expression *> expStack; int len = str.length(); int i; char optor; for (i = 0; i < len; i++) { if (str.at(i) == ' ') { i++; if (IsNumber(str.at(i))) { string numString = ""; while (i<len && IsNumber(str.at(i))) { numString += str.at(i); i++; } i--; Value *newNum = new Value(atof(numString.c_str())); expStack.push(newNum); } else { optor = str.at(i); if (optor != '&' && optor != '%') { if (expStack.empty()) { throw "Bad Input"; } Expression *operand2 = expStack.top(); expStack.pop(); if (expStack.empty()) { throw "Bad Input"; } Expression *operand1 = expStack.top(); expStack.pop(); expStack.push(&action(operand1, operand2, optor)); } else { // we got unary number so we push it alone instead of 2 elements Expression *u; if (optor == '&') { u = new UMinus(expStack.top()); } else { u = new UPlus(expStack.top()); } expStack.pop(); expStack.push(u); } } } } return *expStack.top(); } Expression &action(Expression *operand1, Expression *operand2, char optor) { Expression *e; if (optor == '+') { e = new Plus(operand1, operand2); } if (optor == '-') { e = new Minus(operand1, operand2); } if (optor == '*') { e = new Mul(operand1, operand2); } if (optor == '/') { e = new Div(operand1, operand2); } return *e; } <file_sep>/Var.h // // Created by yuval on 19/12/2019. // #ifndef EX3_VAR_H #define EX3_VAR_H #include <fstream> #include "ex1.h" using namespace std; class Var { string type; //get or set (<- || ->) string sim; double value; public: virtual ~Var() {}; Var() {}; Var(string type1, string sim1) { this->setType(type1); this->setSim(sim1); } string getSim() { return this->sim; } string getType() { return this->type; } double getValue() { return this->value; } void setValue(double newValue) { this->value = newValue; } void setType(string type1) { this->type = type1; } void setSim(string sim1) { this->sim = sim1; } }; #endif //EX3_VAR_H <file_sep>/DefineVarCommand.h // // Created by yuval on 17/12/2019. // #ifndef UNTITLED13_DEFINEVARCOMMAND_H #define UNTITLED13_DEFINEVARCOMMAND_H #include "globals.h" class DefineVarCommand : public Command { public: virtual ~DefineVarCommand() {} DefineVarCommand(); int execute(string str); }; #endif //UNTITLED13_DEFINEVARCOMMAND_H <file_sep>/ConditionParser.cpp // // Created by valdman40 on 12/21/19. // #include "ConditionParser.h" <file_sep>/OpenDataServerCommand.h // // Created by yuval on 21/12/2019. // #ifndef UNTITLED13_OPENDATASERVERCOMMAND_H #define EX3_OPENDATASERVERCOMMAND_H #include <thread> #include <sys/socket.h> #include <string> #include <unistd.h> #include <netinet/in.h> #include <sstream> #include "globals.h" #include "ex1.h" class OpenDataServerCommand : public Command { protected: bool isConnected = false; public: virtual ~OpenDataServerCommand() {} OpenDataServerCommand() {} int execute(string str); int RunServer(int PORT); vector<string> makeXmlArray(); }; #endif //EX3_OPENDATASERVERCOMMAND_H <file_sep>/OpenDataServerCommand.cpp // // Created by yuval on 21/12/2019. // #include "OpenDataServerCommand.h" /* * convertToDoubleArray will transform a char* buffer to a vector<double> * this func will make sure the vector<double> has 36 values. if the first line in the buffer has less than 36 values, * we can assume that the line is not a "full" line of values, therefore we will use the following line. */ vector<double> convertToDoubleArray(char *buffer) { string valuesAsString(buffer); // cout<<buffer<<endl; vector<double> valuesInDouble; string line = valuesAsString.substr(0,valuesAsString.find_first_of('\n')); size_t commaNum = std::count(line.begin(), line.end(), ','); if(commaNum!=35){ //if there are less than 35 commas we know that the line from the buffer is not "full" line = ""; //we will use the following line (starts when the first \n appears until the next \n for(int k=0;k<1024;k++){ if(buffer[k]=='\n'){ k++; while(buffer[k]!='\n'){ line+=buffer[k]; k++; } break; } } } //now we are certain we have a "full line" , we will separate each value and insert it to the vector string::size_type i = 0; string::size_type j = line.find(','); while (j != string::npos) { valuesInDouble.push_back(atof(line.substr(i, j - i).c_str())); i = ++j; j = line.find(',', j); if (j == string::npos) valuesInDouble.push_back(atof(line.substr(i, line.length()).c_str())); } return valuesInDouble; } /* * execute command in this object will break down the string to an int (port) , the port is calculated * via Interpreter (that we made in HW1) in order to treat expressions like 5000+400 (instead of 5400) * after that execute() will open a new thread and will run RunServer() on that thread. */ int OpenDataServerCommand::execute(string str) { cout << "opening data server using this string: " << str << endl; string portStr = str.substr(1, str.find_first_of(")") - 1); replaceAll(portStr, " ", ""); Interpreter *i = new Interpreter(); int port = (i->interpret(portStr))->calculate(); cout << port << endl; threads[0] = thread(&OpenDataServerCommand::RunServer, this, port); while (isConnected == false) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); } return 0; } /* * RunServer() will open a server and will wait for the FlightGear Simulator to connect. * way of operation: * -opens a server and waits for a request to connect from the Simulator * -once the Simulator is connected,the server will receive stats from it (as determined in the generic_small.xml file) * -the server will update the values in the map that are corresponding with the input we receive from the Simulator. */ int OpenDataServerCommand::RunServer(int PORT) { vector<string> XML_Array = makeXmlArray(); //create socket int socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd == -1) { //error std::cerr << "Could not create a socket" << std::endl; return -1; } //bind socket to IP address // we first need to create the sockaddr obj. sockaddr_in address; //in means IP4 address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; //give me any IP allocated for my machine address.sin_port = htons(PORT); //we need to convert our number // to a number that the network understands. //the actual bind command if (bind(socketfd, (struct sockaddr *) &address, sizeof(address)) == -1) { std::cerr << "Could not bind the socket to an IP" << std::endl; return -2; } //making socket listen to the port if (listen(socketfd, 5) == -1) { //can also set to SOMAXCON (max connections) std::cerr << "Error during listening command" << std::endl; return -3; } else { std::cout << "Server is now listening ..." << std::endl; } // accepting a client sockaddr_in ClientAddress; int client_socket = accept(socketfd, (struct sockaddr *) &ClientAddress, (socklen_t *) &ClientAddress); if (client_socket == -1) { std::cerr << "Error accepting client" << std::endl; return -4; } else { cout << "accepted" << endl; isConnected = true; } close(socketfd); //closing the listening socket //reading from client char buffer[1024] = {0}; vector<double> values; while (!endOfFile) { int valread = read(client_socket, buffer, 1024); values = convertToDoubleArray(buffer); // need to check if this part is still good for (int j = 0; j < values.size(); j++) { // map<string, Var>::iterator it = SymbolTable.begin(); for (map<string, Var>::iterator it = SymbolTable.begin(); it != SymbolTable.end(); it++) { if (it->second.getType().compare("get") != 0) { //if the var is not <- we will skip him continue; } else if (it->second.getSim().compare(XML_Array[j]) == 0) { //found a match it->second.setValue(values[j]); break; } } } } return 0; } //this is some hard-coded stuff : each address belongs to a certain object - as determined by the XML file vector<string> OpenDataServerCommand::makeXmlArray() { vector<string> pString; pString.push_back("/instrumentation/airspeed-indicator/indicated-speed-kt"); pString.push_back("/sim/time/warp"); pString.push_back("/controls/switches/magnetos"); pString.push_back("/instrumentation/heading-indicator/offset-deg"); pString.push_back("/instrumentation/altimeter/indicated-altitude-ft"); pString.push_back("/instrumentation/altimeter/pressure-alt-ft"); pString.push_back("/instrumentation/attitude-indicator/indicated-pitch-deg"); pString.push_back("/instrumentation/attitude-indicator/indicated-roll-deg"); pString.push_back("/instrumentation/attitude-indicator/internal-pitch-deg"); pString.push_back("/instrumentation/attitude-indicator/internal-roll-deg"); pString.push_back("/instrumentation/encoder/indicated-altitude-ft"); pString.push_back("/instrumentation/encoder/pressure-alt-ft"); pString.push_back("/instrumentation/gps/indicated-altitude-ft"); pString.push_back("/instrumentation/gps/indicated-ground-speed-kt"); pString.push_back("/instrumentation/gps/indicated-vertical-speed"); pString.push_back("/instrumentation/heading-indicator/indicated-heading-deg)"); pString.push_back("/instrumentation/magnetic-compass/indicated-heading-deg"); pString.push_back("/instrumentation/slip-skid-ball/indicated-slip-skid"); pString.push_back("/instrumentation/turn-indicator/indicated-turn-rate"); pString.push_back("/instrumentation/vertical-speed-indicator/indicated-speed-fpm"); pString.push_back("/controls/flight/aileron"); pString.push_back("/controls/flight/elevator"); pString.push_back("/controls/flight/rudder"); pString.push_back("/controls/flight/flaps"); pString.push_back("/controls/engines/engine/throttle"); pString.push_back("/controls/engines/current-engine/throttle"); pString.push_back("/controls/switches/master-avionics"); pString.push_back("/controls/switches/starter"); pString.push_back("/engines/active-engine/auto-start"); pString.push_back("/controls/flight/speedbrake"); pString.push_back("/sim/model/c172p/brake-parking"); pString.push_back("/controls/engines/engine/primer"); pString.push_back("/controls/engines/current-engine/mixture"); pString.push_back("/controls/switches/master-bat"); pString.push_back("/controls/switches/master-alt"); pString.push_back("/engines/engine/rpm"); return pString; }
f9cf2015befbe1bae5028d1675732e41428c3ea2
[ "Markdown", "CMake", "C++" ]
26
C++
Yuval938/flight-ex3
95d1d4841e32699ab83c87f4d43769d7fbde0a5f
95fc726c125405d48ab6e9ad278f7f2c7b88c866
refs/heads/master
<repo_name>hirsche/demo-sockets<file_sep>/src/at/fhs/nos/demosockets/ClientDemo.java package at.fhs.nos.demosockets; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class ClientDemo { public static void main(String[] args) { Socket echoSocket = null; try { System.out.println("Client starting..."); echoSocket = new Socket(Config.SOCKET_NAME, Config.SOCKET_PORT); //send stream to remote server host PrintWriter out = new PrintWriter(echoSocket.getOutputStream(), true); //receive a stream from remote server host BufferedReader in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); // standard-in reader BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while (!echoSocket.isClosed() && (userInput = stdIn.readLine()) != null) { if (userInput.equals("quit")) { // close connection if quit has been entered echoSocket.close(); } else { //sending to server over socket output stream out.println(userInput); // empty all buffers and send message out.flush(); //receiving from server over socket input stream System.out.println("server at "+ echoSocket.getInetAddress().getHostAddress() + " responses with echo: " + in.readLine()); } } } catch (IOException e) { e.printStackTrace(); closeConnection(echoSocket); } closeConnection(echoSocket); System.out.println("Client Done."); } /** * closes socket connection * * @param echoSocket socket for current connection */ private static void closeConnection(Socket echoSocket) { if (echoSocket != null && !echoSocket.isClosed()) { try { echoSocket.close(); } catch (IOException e1) { e1.printStackTrace(); } }; } }
e8c01ffb30cf9bee2c6ea3bbecc833010b53e264
[ "Java" ]
1
Java
hirsche/demo-sockets
0afeadfe28053a839d377a8e1faf649ad31d8ef7
b49661d5ef4cceb5c92d68aab16ae7bb6fdc5350
refs/heads/master
<file_sep>import sys import argparse from code_parse import get_statistic from repository import GitRepository from output_statistic import output_statistic import logging def convert_str_to_logging_level(level_str): level = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } return level.get(level_str, logging.WARNING) def parse_argv(): description_programm = '''Приложение для проведения лексического анализа \ программного кода''' parser = argparse.ArgumentParser(description=description_programm) parser.add_argument( '--path', help='''Пути к каталогам, где требуется провести анализ кода. Можно указать несколько катологов в кавычках: '/home/bill/coding/ /home/alisa/coding/' ''' ) parser.add_argument( '--git-url', help='URL git-репозитория с кодом, который требуется проанализировать' ) parser.add_argument( '--hg-url', help='''URL hg-репозитория с кодом, который требуется проанализировать \ (в разработке)''' ) parser.add_argument( '--top-size', type=int, default=20, help='Ограничивает вывод количества слов' ) parser.add_argument( '--word-type', choices=['verb', 'noun', 'any'], default='verb', help='''Параметр позволяет задать какая часть речи нас интересует для \ формирования статистики. Возможные значения: verb (по-умолчанию), noun и any. ''' ) parser.add_argument( '--parse-code-type', choices=['function-frequency-word', 'variable-frequency-word', 'function-frequency'], default='function-frequency-word', help='''Параметр позволяет задать, что мы будем анализировать: \ частота употребления слов в именах функций (function-frequency-word), \ частота употребления слов в именах переменных (variable-frequency-word),\ частота употребления имён функций (function-frequency). Возможные значения: function-frequency-word (по-умолчанию), \ variable-frequency-word, function-frequency. ''' ) parser.add_argument( '--output', choices=['stdout', 'json', 'csv'], default='stdout', help='''Формат вывода. Возможные значения: stdout (по-умолчанию) - печать на консоль; json - печать в json-файл; csv - печать в csv-файл. ''' ) parser.add_argument( '--language', choices=['python'], default='python', help='''Параметр позволяет задать язык, на котором написан проект. Возможные значения: python (по-умолчанию). ''' ) parser.add_argument( '--log-level', choices=['debug', 'info', 'warning', 'error', 'critical'], default='warning', help='Уровень вывода логов. По умолчанию warning.' ) parser.add_argument( '--log-file', default='{}.log'.format(__file__.rstrip('.py')), help='Имя логфайла. По-умолчанию {}.log'.format(__file__.rstrip('.py')) ) return parser.parse_args() def get_projects_from_path(path=''): if not path: return [] return path.split() def get_projects_from_git(git_repo=None): if not git_repo: return [] if not git_repo.is_cloned: git_repo.clone_url() if git_repo.local_path: return git_repo.local_path return [] def get_projects_from_hg(hg_repo=None): ''' заглушка ''' return [] def get_projects(local_path=None, git_repo=None, hg_repo=None): projects = get_projects_from_path(local_path) git_project = get_projects_from_git(git_repo) if git_project: projects.append(git_project) hg_project = get_projects_from_hg(hg_repo) if hg_project: projects.append(hg_project) return projects def main(args): # Парсим argv args = parse_argv() logging.basicConfig( filename=args.log_file, level=convert_str_to_logging_level(args.log_level), format='%(asctime)s:%(levelname)s:%(message)s' ) git_repository = GitRepository(args.git_url) projects = get_projects(local_path=args.path, git_repo=git_repository) if not projects: print('no projects...no statistics...') return None # Считаем статистику words_top = [] for path_project in projects: words_top.extend(get_statistic( path_project, args.top_size, word_type=args.word_type, parse_code_type=args.parse_code_type, language=args.language )) statistic = { 'word_type': args.word_type, 'top_size': args.top_size, 'parse_code_type': args.parse_code_type, 'language': args.language, 'words_top': words_top, 'projects': projects, } output_statistic(statistic, output_type=args.output) # Не надо забывать чистить за собой скачанные репозитории git_repository.remove_local_repository() if __name__ == "__main__": sys.exit(main(sys.argv)) <file_sep>import csv import json import logging def output_statistic(statistic, output_type='stdout'): output_type_handlers = { 'stdout': output_to_stdout, 'json': output_to_json, 'csv': output_type, 'ods': output_to_ods, 'pdf': output_to_pdf, } output_handler = output_type_handlers.get(output_type) if output_handler: output_handler(statistic) else: logging.error( 'output_statistic: handlers {} not found in output_type_handlers'.format(output_type) ) def print_statistics_words_top(words_top, words_type='words'): print('total {total} {words_type}'.format( total=len(words_top), words_type=words_type )) print('='*80) print('| {0:<60}|{1:^15} |'.format(words_type, 'occurence')) print('='*80) for word, occurence in words_top: print('| {0:<60}|{1:^15} |'.format(word, occurence)) print('='*80) def output_to_json(statistic): statistics_json = json.dumps(statistic, sort_keys=True, indent=4) try: with open('words_code_stat.json', 'w') as json_file: json_file.write(statistics_json) except IOError as e: logging.error('words_code_stat.json I/O error({0}): {1}'.format( e.errno, e.strerror )) def output_to_csv(statistic): try: with open('words_code_stat.csv', 'w') as csv_file: statistic_writer = csv.writer(csv_file) statistic_writer.writerow([statistic['word_type'], 'occurence']) for word, occurence in statistic['words_top']: statistic_writer.writerow([word, occurence]) except IOError as e: logging.error('words_code_stat.csv I/O error({0}): {1}'.format( e.errno, e.strerror )) def output_to_stdout(statistic): # Выводим на экран результаты print('statistic type: {0}'.format(statistic['parse_code_type'])) print_statistics_words_top(statistic['words_top'], words_type=statistic['word_type']) def output_to_ods(statistic): ''' заглушка ''' pass def output_to_pdf(statistic): ''' заглушка ''' pass <file_sep>import collections from nltk import pos_tag import logging from ast_tree import get_trees, get_all_names_in_tree, get_names_in_ast_tree def flatten_list(not_flat_list): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return [item for sublist in not_flat_list for item in sublist] def is_verb(word): ''' Проверка на глагол ''' if not word: return False pos_info = pos_tag([word]) # VB verb, base form take # VBD verb, past tense took # VBG verb, gerund/present participle taking # VBN verb, past participle taken # VBP verb, sing. present, non-3d take # VBZ verb, 3rd person sing. present takes return pos_info[0][1] in ('VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ') def is_noun(word): ''' Проверка является ли word существительным ''' if not word: return False pos_info = pos_tag([word]) # NN noun, singular 'desk' # NNS noun plural 'desks' # NNP proper noun, singular 'Harrison' # NNPS proper noun, plural 'Americans' return pos_info[0][1] in ('NN', 'NNS', 'NNP', 'NNPS') def get_verbs_from_name(name): return [word for word in name.split('_') if is_verb(word)] def get_nouns_from_name(name): return [word for word in name.split('_') if is_noun(word)] def get_any_words_from_name(name): return [word for word in name.split('_')] def get_words_from_name(name, word_type='verb'): word_type_handler = { 'verb': get_verbs_from_name, 'noun': get_nouns_from_name, 'any': get_any_words_from_name, } handler = word_type_handler.get(word_type) if not handler: logging.error( 'get_words_from_name: word_type_handler {} not found'.format( word_type ) ) return None return handler(name) def split_snake_case_name_to_words(name): ''' Разбить имя на слова ''' if not name: return [] return [n for n in name.split('_') if n] def get_all_words_in_path(path): ''' Получить все слова используемые в текстовых файлах каталога path ''' trees = [t for t in get_trees(path) if t] names = flatten_list([get_all_names_in_tree(t) for t in trees]) # Исключаем магические функции names = [ f for f in names if not (f.startswith('__') and f.endswith('__')) ] return flatten_list( [split_snake_case_name_to_words(name) for name in names] ) def get_functions_names_in_tree(tree): ''' Получить список функций в дереве ast ''' return get_names_in_ast_tree(tree, type_name='function') def get_top_verbs_in_path(path, top_size=10): ''' Получить ТОП используемых глаголов в каталоге path ''' return get_top_words_in_path(path, top_size, word_type='verb') def get_top_words_in_path_python(path, top_size=10, word_type='verb', parse_code_type='function'): trees = [t for t in get_trees(path) if t] names_in_code = flatten_list( [get_names_in_ast_tree(t, type_name=parse_code_type) for t in trees] ) # Удаляем магию names_in_code = [ name for name in names_in_code if not (name.startswith('__') and name.endswith('__')) ] words = flatten_list([ get_words_from_name(name, word_type=word_type) for name in names_in_code ]) return collections.Counter(words).most_common(top_size) def get_top_words_in_path(path, top_size=10, word_type='verb', parse_code_type='function', language='python'): ''' Получить ТОП используемых глаголов в каталоге path parse_code_type - function или variable ''' if language == 'python': return get_top_words_in_path_python(path, top_size, word_type, parse_code_type) def get_top_functions_names_in_path_python(path, top_size=10): ''' Получить ТОП используемых имён функций в каталоге path''' trees = get_trees(path) names = [ f for f in flatten_list( [get_functions_names_in_tree(t) for t in trees if t] ) if not (f.startswith('__') and f.endswith('__')) ] return collections.Counter(names).most_common(top_size) def get_top_functions_names_in_path(path, top_size=10, language='python'): ''' Получить ТОП используемых имён функций в каталоге path''' if language == 'python': return get_top_functions_names_in_path_python(path, top_size=10) def get_statistic(path, top_size=10, word_type='verb', parse_code_type='function-frequency-word', language='python'): parse_code_type_handlers = { # 'type': (function, kwargs) 'function-frequency-word': (get_top_words_in_path, { 'path': path, 'top_size': top_size, 'language': language, 'word_type': word_type, 'parse_code_type': 'function', } ), 'variable-frequency-word': (get_top_words_in_path, { 'path': path, 'top_size': top_size, 'language': language, 'word_type': word_type, 'parse_code_type': 'variable', } ), 'function-frequency': (get_top_functions_names_in_path, { 'path': path, 'top_size': top_size, 'language': language, } ) } calculate_statistic, kwargs_calculate_statistic = \ parse_code_type_handlers.get(parse_code_type, (None, None)) if not calculate_statistic: logging.error( 'get_statistic: handler for {0} not found'.format(parse_code_type) ) return None return calculate_statistic(**kwargs_calculate_statistic) <file_sep>GitPython==2.1.9 nltk==3.3 <file_sep>from git import Repo import shutil class Repository: """ Прототип классов для работы с репозиториями (git, mercurial и т.д.) """ def __init__(self, git_url, to_dir='/tmp/', branch='master'): self.git_url = git_url if not git_url: to_dir = '' if to_dir == '/tmp/': to_dir += git_url.split('/')[-1].replace('.git', '') + '/' self.local_path = to_dir self.branch = branch self.is_cloned = False def remove_local_repository(self): ''' Удаление локального репозитория. Возвращает в случае успеха True, иначе False ''' if (not self.local_path or self.local_path == '/tmp/'): return False try: shutil.rmtree(self.local_path) self.is_cloned = False except: return False return True class GitRepository(Repository): """ Класс для работы с git репозиторием """ def __init__(self, git_url, to_dir='/tmp/', branch='master'): super().__init__(git_url, to_dir, branch) def clone_url(self): ''' Возвращает путь до каталога, куда был клонирован репозиторий В случае ошибки возвращает пустую строку ''' if not self.git_url: return '' # на всякий случай чистим каталог self.remove_local_repository() try: Repo.clone_from( self.git_url, self.local_path, branch=self.branch ) self.is_cloned = True except: # Чистим за собой self.remove_local_repository() self.local_path = '' self.is_cloned = False return self.local_path class HgRepository(Repository): """ Класс для работы с hg репозиторием """ def __init__(self, git_url, to_dir='/tmp/', branch='master'): super().__init__(git_url, to_dir, branch) def clone_url(self): ''' заглушка ''' pass <file_sep># code_parse Библиотека позволяет оценить на сколько часто используются в проектах те или иные лексические конструкции. Умеет работать с глаголами и существительными, разбирать как названия функции так и названия переменных. ## Установка Установка из git: ``` git clone https://github.com/ds-vologdin/dcInt.git ``` ## Как использовать Пример использования библиотеки представлен в words_code_statistic.py ``` from code_parse import get_statistic words_top = get_statistic( path='/home/developer/code/', top_size=50, word_type='verb', parse_code_type='function-frequency-word', language='python' ) ``` top_size - максимальное количество выводимых в отчёт слов word_type - часть речи, которая нас интересует. Возможные значения: verb, noun, any. parse_code_type - говорит нам, что анализировать. Возможные значения: - function-frequency-word (топ используемых слов в названиях функции) - variable-frequency-word (топ используемых слов в названиях функции) - function-frequency (топ используемых имён функций) language - язык программирования, используемый в анализируемом проекте. Пока поддеживается только 'python' ## words_code_statistic.py Поставляется в составе библиотеки code_parse. Приложение для формирования статистики по частоте употребления в коде различных слов. Умеет работать с git-репозиториями и локальными проектами. Выводит результат выполнения на консоль, csv-файл, json-файл. ### Пример использования words_code_statistic.py ``` python3 words_code_statistic.py --git-url https://github.com/django/django.git --word-type noun --parse-code-type variable --output json ``` JSON-отчет будет записан в words_code_stat.json Информацию о возможных аргументах можно посмотреть в хелпе. ``` python3 words_code_statistic.py -h usage: words_code_statistic.py [-h] [--path PATH] [--git-url GIT_URL] [--hg-url HG_URL] [--top-size TOP_SIZE] [--word-type {verb,noun,any}] [--parse-code-type {function-frequency-word,variable-frequency-word,function-frequency}] [--output {stdout,json,csv}] [--language {python}] [--log-level {debug,info,warning,error,critical}] [--log-file LOG_FILE] Приложение для проведения лексического анализа программного кода optional arguments: -h, --help show this help message and exit --path PATH Пути к каталогам, где требуется провести анализ кода. Можно указать несколько катологов в кавычках: '/home/bill/coding/ /home/alisa/coding/' --git-url GIT_URL URL git-репозитория с кодом, который требуется проанализировать --hg-url HG_URL URL hg-репозитория с кодом, который требуется проанализировать (в разработке) --top-size TOP_SIZE Ограничивает вывод количества слов --word-type {verb,noun,any} Параметр позволяет задать какая часть речи нас интересует для формирования статистики. Возможные значения: verb (по-умолчанию), noun и any. --parse-code-type {function-frequency-word,variable-frequency-word,function-frequency} Параметр позволяет задать, что мы будем анализировать: частота употребления слов в именах функций (function- frequency-word), частота употребления слов в именах переменных (variable-frequency-word),частота употребления имён функций (function-frequency). Возможные значения: function-frequency-word (по- умолчанию), variable-frequency-word, function- frequency. --output {stdout,json,csv} Формат вывода. Возможные значения: stdout (по- умолчанию) - печать на консоль; json - печать в json- файл; csv - печать в csv-файл. --language {python} Параметр позволяет задать язык, на котором написан проект. Возможные значения: python (по-умолчанию). --log-level {debug,info,warning,error,critical} Уровень вывода логов. По умолчанию warning. --log-file LOG_FILE Имя логфайла. По-умолчанию words_code_statistic.log ```
89d68e4ad89566fd12cfc6a0072659eea0b2b7ce
[ "Markdown", "Python", "Text" ]
6
Python
ds-vologdin/code-parser
6f4475f2a399dd2819a5d426b943979045507fb0
56746f25aae93c21e54ccc9d135a2abc01c81c8d
refs/heads/master
<repo_name>kzeca/Snoopy-Social-Media<file_sep>/README.md # Snoopy-Social-Media A Music Social Media where you can post message and images in localStorage! <file_sep>/Social Media/js/login.js function validate(ev){ try{ ev.preventDefault(); const username = ev.target.elements["username"].value; const password = ev.target.elements["password"].value; var db = localStorage.getItem(username); let error = {}; if(db){ db = JSON.parse(db); const login = db.username; const pass = db.password; if(username === login && password === pass){ window.location.href = "home.html"; localStorage.setItem("token", username); return true; }else error = {code: "password", message: "That password is wrong :("} }else error = {code: "username", message: "Username doesn't exist"}; inError(error); }catch(e){ alert(e.message); } } const inError = (error) => { if (error.code === "username") { alert(error.message); } else if (error.code === "password") { alert(error.message); } };
25c7e38918c7b748ccae5eeaacf770f908f99579
[ "Markdown", "JavaScript" ]
2
Markdown
kzeca/Snoopy-Social-Media
804c09a487857e19e23906da3ff445ac47e2f86c
ff0e6c156fde9478e997b32934987ed0a69b4c3b
refs/heads/master
<repo_name>fmatangira/quiz<file_sep>/Homework4-Quiz/script.js var interval; var seconds = 75; var minutesFormat; var score = 0; var i = 0; var optionClick; var questions = [{ title: "Commonly used data types DO NOT include:", choices: ["strings", "booleans", "alerts", "numbers"], answer: "alerts" }, { title: "The condition in an if / else statement is enclosed within ____.", choices: ["quotes", "curly brackets", "parentheses", "alerts"], answer: "curly brackets" }, { title: "Which of the following is a valid type of function javascript supports?", choices: ["named function", "anonymous function", "Both of the above", "None of the above"], answer: "Both of the above" }, { title: "Which of the following type of variable is visible only within a function where it is defined?", choices: ["global variable", "local variable", "Both of the above", "None of the above"], answer: "local variable" }, { title: "Which built-in method returns the characters in a string beginning at the specified location?", choices: ["substr()", "getSubstring()", "slice()", "None of the above"], answer: "substr()" }, { title: "Which of the following function of String object is used to match a regular expression against a string?", choices: ["concat()", "match()", "search()", "replace()"], answer: "match()" } ]; $(document).ready(function() { //FUNCTION TO FORMAT MINUTES IN TIMER function formatMinutes() { var formattedMinutes; minutesFormat = Math.floor(seconds / 60); if (minutesFormat < 10) { formattedMinutes = "0" + minutesFormat; } else { formattedMinutes = minutesFormat; } return formattedMinutes; } // FUNCTION TO FORMAT SECONDS IN TIMER function formatSeconds() { var secondsFormat = seconds % 60; var formattedSeconds; if (secondsFormat < 10) { formattedSeconds = "0" + secondsFormat; } else { formattedSeconds = secondsFormat; } return formattedSeconds; } //START TIMER WHEN CLICKING ON "START QUIZ" BUTTON function quizStart() { $('#quizButton').on('click', function() { $('.landingRow').hide(); $('.quizRow').show(); startTimer(); }); } function quizQuestions() { optionClick = '#option' + questions[i].answer; $('#questionTitle').text(questions[i].title); $('.option1').text(questions[i].choices[0]); $('.option2').text(questions[i].choices[1]); $('.option3').text(questions[i].choices[2]); $('.option4').text(questions[i].choices[3]); } $('.option').click(function(event) { event.preventDefault(); if (i<5) { if (event.currentTarget.textContent === questions[i].answer) { alert('CORRECT ANSWER!'); i++; score++; quizQuestions(); } else { alert('WRONG ANSWER'); i++; quizQuestions(); seconds = seconds-10; } } else { if (event.currentTarget.textContent === questions[i].answer) { alert('CORRECT ANSWER!'); score++; clearInterval(interval); $('.quizRow').hide(); showScore(); $('.enterNameCont').show(); $('#nameSubmit').on('click',function(event) { event.preventDefault(); saveToLS(); alert('Score has been saved!'); location.reload(); }); } else { alert('WRONG ANSWER'); seconds = seconds-10; clearInterval(interval); $('.quizRow').hide(); showScore(); $('.enterNameCont').show(); $('#nameSubmit').on('click', function(event) { event.preventDefault(); saveToLS(); alert('Score has been saved!'); location.reload(); }); } } }); function startTimer() { interval = setInterval(function() { seconds--; $('#timer').html("TIMER: " + formatMinutes() + ":" + formatSeconds()); if (seconds === 0) { clearInterval(interval); $('#timer').text('TIMES UP!!!'); alert('QUIZ OVER!'); $('.quizRow').hide(); timesUp(); $('.enterNameCont').show(); return; } //FORMAT COLOR OF TIMER DEPENDING ON TIME LEFT $('#timer').css('color', 'green'); if (seconds < 60) { $('#timer').css('color', '#e5d429'); } if (seconds < 30) { $('#timer').css('color', 'orange'); } if (seconds < 10) { $('#timer').css('color', 'red'); } }, 1000); } function showScore() { $('#score').text('You received a score of: ' + Math.round(((score/6)*100)) + '%!'); $('#timeLeft').text('You finished this quiz in ' + (65 - seconds) + ' seconds!'); } function timesUp() { $('#score').text('You ran out of time! You received a score of: ' + Math.round(((score/6)*100)) + '%!'); } function saveToLS() { var name = document.querySelector('#nameHS').value; localStorage.setItem('user',JSON.stringify(highScores)); } function showHighScores1() { $('.viewScores').on('click', function() { $('.highScoreModal').show(); $('#hsExport').text(JSON.parse(localStorage.getItem('user'))); }); } //RUN QUIZ $('.quizRow').hide(); showHighScores1(); quizStart(); quizQuestions(); var highScores = {Name: document.querySelector('#nameHS').value, Score: score}; $('.enterNameCont').hide(); }); <file_sep>/Homework4-Quiz/readme.md This is a program that demonstrates creating a quiz in javascript.
ecd441848a87b9f69118ee9b5fa77af4bf748efe
[ "JavaScript", "Markdown" ]
2
JavaScript
fmatangira/quiz
e6a867ef691212e6c6f705691767215dff09c28c
73d041f59b7e615ccf260d6a3d15d9f5afea98d3
refs/heads/master
<file_sep>class AppDelegate def application(application, didFinishLaunchingWithOptions: launchOptions) @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds) @window.makeKeyAndVisible colors_controller = ColorsController.alloc.initWithNibName(nil, bundle: nil) navigation_controller = UINavigationController.alloc.initWithRootViewController colors_controller tab_controller = UITabBarController.alloc.initWithNibName(nil, bundle: nil) tab_controller.viewControllers= [navigation_controller] @window.rootViewController = tab_controller true end end
b20508304774fa7005feef74c19478a41764e27c
[ "Ruby" ]
1
Ruby
muescha/RubyMotionBook-ColorViewer
7d972f4c6dffb7df99a9b9d8ef6da82ea1ae1fff
c3e8b18f5a9765118f533657d120816ea7779239
refs/heads/master
<file_sep>package com.ingdirect.es.testbase.template; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import org.junit.Test; public abstract class AbstractPojoTest <T> { protected T pojo; protected T equalsPojo; protected T otherPojo; public abstract void beforeTests(); @Test public void shouldBeEquals() { assertThat( pojo, is( equalsPojo ) ); } @Test public void shouldBeDistinct() { assertThat( pojo, is( not( otherPojo ) ) ); } @Test public void shouldProduceSameHashCode() { assertThat( pojo.hashCode(), is( equalsPojo.hashCode() ) ); } @Test public void shouldProduceDistinctHashCode() { assertThat( pojo.hashCode(), is( not( otherPojo.hashCode() ) ) ); } @Test public void equalsMethodCheckTheType() { assertFalse( pojo.equals( "a string" ) ); } @Test public void equalsMethodWithNullObject() { assertFalse( pojo == null ); } @Test public void equalsMethodWithSameObject() { final T samePojo = pojo; assertTrue( pojo.equals( samePojo ) ); } @Test public void shouldHaveMethodAccessors() throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo( pojo.getClass() ) .getPropertyDescriptors()) { assertNotNull( propertyDescriptor.getReadMethod().invoke( pojo ) ); } } @Test public abstract void shouldHaveAllPropertiesAccesibles(); } <file_sep>package com.ingdirect.es.testbase.template; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import org.jadira.cloning.BasicCloner; import org.jadira.cloning.api.Cloner; import org.junit.Before; import org.junit.Test; import org.springframework.util.ReflectionUtils; import com.ingdirect.es.testbase.doubles.RandomGenerator; public abstract class AbstractPojoRandomizedTest<T> extends AbstractPojoTest<T> { protected Class<?> getConcreteClass(){ return (Class<?>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } @SuppressWarnings("unchecked") @Override @Before public void beforeTests() { Class<?> clazz = getConcreteClass(); pojo = (T) RandomGenerator.nextImmutableObject(clazz); equalsPojo = (T) clonePojoWithJadira( pojo ); otherPojo = (T) RandomGenerator.nextImmutableObject( clazz ); } protected T clonePojoWithJadira(T original){ Cloner cloner = new BasicCloner(); return cloner.clone( original ); } protected void changeFinalField(T object, String fieldName, Object newValue) throws NoSuchFieldException, IllegalAccessException { Field distinctField = getConcreteClass().getDeclaredField( fieldName ); distinctField.setAccessible( true ); distinctField.set( object, newValue ); } // private T clonePojoWithOrika(T original){ // DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().useAutoMapping( true ).useBuiltinConverters( true ).build(); // mapperFactory.classMap( AcquisitionOrderAggregateRootImpl.class, AcquisitionOrderAggregateRootImpl.class ).byDefault().register(); // T cloned = (T) mapperFactory.getMapperFacade().map( original, AcquisitionOrderAggregateRootImpl.class); // // return cloned; // } // // private T clonePojoWithMapperComponent(T original){ // // T cloned = (T) mapper.map( original, AcquisitionOrderAggregateRootImpl.class ); // // return cloned; // } // private AcquisitionOrderAggregateRootImpl clonePojoWithReflection(AcquisitionOrderAggregateRootImpl original){ // // Constructor<?> constructor = AcquisitionOrderAggregateRootImpl.class.getConstructors()[0]; // // List<String> fieldNames = Arrays.stream( constructor.getTypeParameters()) // .map( TypeVariable::getName ) // .collect( Collectors.toList() ); // // List<Object> fieldValues = fieldNames.stream().map( f -> readField( original, f ) ).collect( Collectors.toList() ); // // AcquisitionOrderAggregateRootImpl equal = null; // // try { // equal = (AcquisitionOrderAggregateRootImpl) constructor.newInstance( fieldValues.toArray( new Object[fieldValues.size()] ) ); // } catch (Exception e) { // // e.printStackTrace(); // } // // return equal; // } // private Object readField(Object object, String fieldName){ // Object result = null; // try { // result = FieldUtils.readField( object, fieldName ); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } // // return result; // } @Test @Override public void shouldHaveAllPropertiesAccesibles() { try { for (PropertyDescriptor property : Introspector.getBeanInfo( getConcreteClass() ).getPropertyDescriptors()){ Field field = ReflectionUtils.findField( getConcreteClass(), property.getName()); if (field != null){ field.setAccessible( true ); assertThat( property.getReadMethod().invoke( pojo ), is( field.get( pojo )) ); } } } catch (Exception e) { fail(); } } } <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>com.ingdirect.es</groupId> <artifactId>testbase</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <name>testbase</name> <properties> <junit.version>4.12</junit.version> <hamcrest.version>1.3</hamcrest.version> <mockito.version>1.10.19</mockito.version> <wiremock.version>2.6.0</wiremock.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>${hamcrest.version}</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>${mockito.version}</version> </dependency> <dependency> <groupId>com.github.tomakehurst</groupId> <artifactId>wiremock</artifactId> <version>${wiremock.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>io.github.benas</groupId> <artifactId>random-beans</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>org.jadira.cloning</groupId> <artifactId>cloning</artifactId> <version>3.1.0.CR10</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.5.RELEASE</version> </dependency> </dependencies> <build> <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> </configuration> </plugin> </plugins> </build> </project><file_sep>package com.ingdirect.es.testbase.template; public enum HttpMethod { POST("POST"), GET("GET"); private final String name; private HttpMethod(String name) { this.name = name; } public String getName() { return name; } } <file_sep>package com.ingdirect.es.testbase.doubles; import java.lang.reflect.Constructor; import java.util.Arrays; import io.github.benas.randombeans.EnhancedRandomBuilder; import io.github.benas.randombeans.FieldDefinitionBuilder; import io.github.benas.randombeans.api.EnhancedRandom; import io.github.benas.randombeans.api.Randomizer; public class RandomGenerator { private volatile static EnhancedRandom defaultEnhancedRandom; private static EnhancedRandom getDefaultRandomizer(){ if (defaultEnhancedRandom == null){ synchronized (RandomGenerator.class) { if (defaultEnhancedRandom == null){ defaultEnhancedRandom = EnhancedRandomBuilder.aNewEnhancedRandomBuilder() .collectionSizeRange( 1, 5 ) .scanClasspathForConcreteTypes( true ) .build(); } } } return defaultEnhancedRandom; } public static <T> T nextObject(Class<T> clazz, String... excludedFields){ return getDefaultRandomizer().nextObject( clazz, excludedFields); } @SuppressWarnings("unchecked") public static <T> T nextImmutableObject(Class<T> clazz, int... excludedPositions){ Constructor<?> constructor = clazz.getConstructors()[0]; Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] generatedParameters = Arrays.stream( parameterTypes ).map( t -> getDefaultRandomizer().nextObject(t)).toArray(); Arrays.stream( excludedPositions).forEach( i -> generatedParameters[i] = null ); T generatedInstance = null; try { generatedInstance = (T) constructor.newInstance( generatedParameters ); } catch (Exception e) { e.printStackTrace(); } return generatedInstance; } public static EnhancedRandomBuilder getBasicRandomBuilder(){ return EnhancedRandomBuilder.aNewEnhancedRandomBuilder(); } }
aa3231a4cec3cc2a118f5062470473d1d0cf1ce7
[ "Java", "Maven POM" ]
5
Java
ysegura/TestBase
11cc8fcfd6db4cfc3b931cacb3a09e30eb2ea1ae
31a041c01a556e085b7d80fad09af2389d3065fc
refs/heads/master
<repo_name>CavadJava/QeydDefteri<file_sep>/QeydDefteri/src/FileOxu.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; /* * 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. */ /** * * @author CBagirov */ public class FileOxu { public static void main(String[] args) throws FileNotFoundException, IOException { JFileChooser fayli_ac = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT fayllar", "TXT"); fayli_ac.setFileFilter(filter); int key = fayli_ac.showSaveDialog(null); if (key == JFileChooser.APPROVE_OPTION) { System.out.println(fayli_ac.getSelectedFile().getPath()); } //// BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\CBagirov\\Documents\\jsp file.txt"))); //// try { //// StringBuilder sb = new StringBuilder(); //// String line = br.readLine(); //// //// while (line != null) { //// sb.append(line + "\n"); //// line = br.readLine(); //// } //// String everything = sb.toString(); //// System.out.println(everything); //// } finally { //// br.close(); //// } } }
da1901c489c1ac0d2162a72d792959ff2bc96cc7
[ "Java" ]
1
Java
CavadJava/QeydDefteri
86a4c0bffe00410938f2cce0a15573473b9b0362
0e2ee84f6d0e5ac488cd9fe4eee4227b90c44db5
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { TestinputComponent } from './testinput/testinput.component'; import { NgxRouteParamsInputComponent } from 'ngx-route-params-input'; const routes: Routes = [{ path: 'test', children: [{ path: ':input', component: NgxRouteParamsInputComponent, data: { ngxRouteParamsInput: { component: TestinputComponent, routeParams: { input: 'testInput' }, queryParams: { content: 'contentInput' } } } }] }]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
70d62eaea5b02a66bb2406c09c8cce068487bf65
[ "TypeScript" ]
1
TypeScript
mrigne/test-proj
e4e2d6919120d46d676cc186a195bd0f9d861e14
b77cc50a5e7b298b94def65458eed0299f6dd173
refs/heads/master
<file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Utils/Dialog', 'text!Templates/SharePopup.html', 'text!Templates/SocialSharePopup.html', 'text!Templates/SendEmailPopup.html' ], function (_, Backbone, ModelsConstants, Dialog, templateHtml, socialTemplateHtml, sendEmailTemplateHtml) { 'use strict'; var fadeSpeed = 300; return Backbone.View.extend({ tagName: "div", className: "share-popup", template: _.template(templateHtml), socialTemplate: _.template(socialTemplateHtml), sendEmailTemplate: _.template(sendEmailTemplateHtml), currentUser: null, ui: { $listContainer: 'ul', errorClass: 'sign-row-error', successClass: 'sign-row-success', messages: { success: 'Your test room was shared successfully', error: 'Test share properties update failed. Please, try later' } }, events: { "click .id-remove-email": "_removeEmail", "click .id-button-share": "_shareTest", "click .id-button-add": "_addEmail", "keydown .id-add-email": "_addEmailOnEnter", "click .id-close": "_onClosePopup", "click #id-share-fb": "_shareFacebook", "click #id-share-twitter": "_shareTwitter", "click #id-share-google-plus": "_shareGooglePlus", "click #id-share-email": "_shareEmail", "click .id-button-send-email": "_sendEmails", "click .id-preview-link": function (e) { e.preventDefault(); return false; } }, initialize: function (options) { this.mode = options.mode; this.listenTo(this.model, { 'shared-save-success': this._onShareSuccess, 'error': this._onError }); this.dialog = new Dialog(); }, render: function () { switch (true) { case this.mode === 'email': this.$el.html(this.sendEmailTemplate({ Constants: ModelsConstants, model: this.model })); break; case !!this.model.get('token'): this.$el.html(this.socialTemplate({ Constants: ModelsConstants, model: this.model })); break; default: this.$el.html(this.template({ Constants: ModelsConstants, model: this.model })); break; } this.$emailList = this.$(this.ui.$listContainer); this.$email = this.$('.id-add-email'); this.$errorContainer = this.$('.errorContainer'); this.$testShareLink = this.$("#id-test-share-link"); this.$emailBody = this.$('.id-email-text'); return this; }, _hideErrorsAndStatuses: function () { this.$errorContainer.removeClass(this.ui.successClass).removeClass(this.ui.errorClass).hide(); }, _onShareSuccess: function () { this.dialog.show('alert', this.ui.messages.success); }, _onError: function (errorMessage) { this.$errorContainer.show() .addClass(this.ui.errorClass).removeClass(this.ui.successClass) .text(errorMessage || this.ui.messages.error); }, _removeEmail: function (e) { var $item = $(e.currentTarget).closest('li'); this._hideErrorsAndStatuses(); $item.find('*').unbind(); $item.fadeOut(fadeSpeed); setTimeout(function () { $item.remove(); }, fadeSpeed * 1.2); console.log('remove Email'); }, _addEmailOnEnter: function (e) { if (e.keyCode === 13) { this._addEmail(); } }, _addEmail: function () { var newItemValue = this.$email.val(), emailValidation = this.model.validateEmail(newItemValue, this.getEmailList()); this._hideErrorsAndStatuses(); if (!emailValidation.error) { var $newItem = this.$emailList.find('._proto_').clone(); $newItem.removeAttr('class') .appendTo(this.$emailList) .find('span').text(newItemValue); this.$email.val(''); } else { this._onError(emailValidation.error.description); } }, getEmailList: function () { var shareData = []; this.$emailList.find('>*:not(._proto_)').each(function (e) { shareData.push($(this).find('span').text()); }); return shareData; }, _shareTest: function () { this._hideErrorsAndStatuses(); this.trigger('save-shared', this.model, this.getEmailList()); }, _shareFacebook: function () { var link = "http://www.facebook.com/share.php?u={0}".format(encodeURIComponent(this.$testShareLink.val())); this.openShareWindow(link); }, _shareTwitter: function () { var link = "https://twitter.com/share?url={0}".format(encodeURIComponent(this.$testShareLink.val())); this.openShareWindow(link); }, _shareGooglePlus: function () { var link = "https://plus.google.com/share?url={0}".format(encodeURIComponent(this.$testShareLink.val())); this.openShareWindow(link); }, openShareWindow: function (url) { try { var width = 550, height = 286, screenHeight = window.innerHeight, screenWidth = window.innerWidth, left = Math.round((screenWidth / 2) - (width / 2)), top = 0; if (screenHeight > height) { top = Math.round((screenHeight / 2) - (height / 2)); } var k = window.open(url, "", "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height + ",personalbar=0,menubar=0,toolbar=0,scrollbars=1,resizable=1"); k.focus(); } catch (h) { console.log("Error happened while opening share window."); } }, _onClosePopup: function () { this.trigger('close-popup'); }, _closePopup: function () { this.$el.find('*').unbind(); this.$el.parent().html(''); }, _shareEmail: function () { this.trigger('start-email-share'); }, _sendEmails: function () { var message = this.$emailBody.val().replace(/\n/g, "<br/>"); this.trigger('share-email', this.getEmailList(), message); } }); }); <file_sep>/*global define: true */ define([ 'moment', 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants', 'DataLayer/Constants', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'DataLayer/ServerCommandExecutor', 'Utils/StringExtensions' ], function (moment, Backbone, _, Constants, ErrorConstants, DataConstants, ModelSyncExtension, ServerInteractionSerializersHash, ServerCommandExecutor, StringExtensions) { 'use strict'; var SharePopup = Backbone.Model.extend({ defaults: { id: null, shareData: null }, initialize: function () { }, validateEmail: function (email, emailList) { var error = null; if (StringExtensions.isTrimmedEmpty(email)) { error = ErrorConstants.Validation.EmptyEMail; } else if (!email.match(Constants.EmailPattern)) { error = ErrorConstants.Validation.InvalidEMail; } else if (emailList.indexOf(email) >= 0) { error = ErrorConstants.Validation.EMailIsNotUnique; } return {error: error}; }, fetch: function (options) { var success = options.success; options.success = function (model, xhr, options) { if (success) { success(model, xhr, options); } }; // Call base implementation Backbone.Model.prototype.fetch.call(this, options); }, getAll: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.getAllShareInfo, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), success: options.success }); }, unshare: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.removeEmail, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), email: options.email, success: options.success }); }, dropToken: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.dropToken, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), id: options.id, success: options.success }); }, leaveShare: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.leaveTests, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), user: options.user, project: options.project, success: options.success }); }, checkToken: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.checkToken, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), user: options.user, id: options.id, success: options.success }); }, generateToken: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.generateToken, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), user: options.user, id: options.id, success: options.success, error: options.error }); }, shareByMail: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.SharingManager.shareByMail, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), message: options.message, email: options.email, urlPath: 'http://' + window.location.hostname + '/kineticsweb/#shared-test/' + this.get('token'), success: options.success, error: options.error }); } }); ModelSyncExtension.extend(SharePopup.prototype, { read: ServerInteractionSerializersHash.SharingManager.getAllShareInfo, create: ServerInteractionSerializersHash.SharingManager.addEmail, update: ServerInteractionSerializersHash.SharingManager.addEmail // 'delete': ServerInteractionSerializersHash.ShareManager.deleteShare }); return SharePopup; });<file_sep>/*global define:true, prompt: true, confirm: true */ define([ 'jQuery', 'underscore', 'backbone', 'moment', 'DataLayer/Constants', 'Models/Constants', 'Models/ErrorConstants', 'Models/Sharing', 'Utils/Dialog', 'text!Templates/Profile.html', 'text!Templates/ProfileDestroyConfirmation.html', 'jQuery.placeholder' ], function ($, _, Backbone, moment, DataLayerConstants, Constants, ErrorConstants, SharePopup, Dialog, templateHtml, destroyConfirmationTemplateHtml) { 'use strict'; var SuccessStyle = "sign-row-success"; var ErrorStyle = "sign-row-error"; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), destroyConfirmationTemplate: _.template(destroyConfirmationTemplateHtml), projectsList: [], events: { "click .id-save-profile": "_onSaveProfile", "keypress .profile-data input": "_submitProfileDataOnEnter", "click .id-save-password": "_onSavePassword", "keypress .change-password input": "_submitChangePassOnEnter", "click .id-save-project": "_onSaveProject", "click .id-cancel": "_onCancel", "click .id-destroy": "_onDestroy", "click .project-add": "_projectAdd", "click .project-remove": "_projectRemove", "click .id-unshare": "_unshare", "click .id-leave-share": "_leaveShare", "click .id-share-all": "_shareAll", "click .id-share-test": "_shareTest", "click .id-unshare-test": "_unshareTest", "keypress #password-old, #password-new, #password-confirmation": "_validatePassword" }, initialize: function () { _.bindAll(this, "_hideErrorsAndStatuses"); var that = this; this.listenTo(this.model.userProfile, { "invalid": function (model, errors/*, options*/) { this._updateErrorMessage(errors); }, "error": function (error) { this._updateErrorMessage([ error ]); }, "sync": function () { this._setSaveStatus({ success: true }); }, "unshared": function (email) { var that = this; this.$('.id-unshare[data-email="' + email + '"]').parents('tr').fadeOut(function () { this.remove(); if (!that.$('.id-unshare').length) { that.$('table.sharing .no-tests').show(); } }); }, "unshared-test": function (id) { var that = this; this.$('.id-unshare-test[data-id="' + id + '"]').parents('tr').fadeOut(function () { this.remove(); if (!that.$('.id-unshare-test').length) { that.$('table.shared-tests .no-tests').show(); } }); }, "left-shared": function (id, project) { var that = this; this.$('.id-leave-share[data-id="' + id + '"][data-project="' + project + '"]').parents('tr').fadeOut(function () { this.remove(); if (!that.$('.id-leave-share').length) { that.$('table.shared .no-tests').show(); } }); } }); this.listenTo(this.model.passwordModifier, { "invalid": function (model, errors/*, options*/) { this._updateErrorMessage(errors); }, "success": function () { this._setChangePasswordStatus({ success: true }); }, "error": function (error) { this._setChangePasswordStatus(error); }, "resetFields": this._onResetPasswordFields }); this.listenTo(this.model.projectModifier, { "invalid": function (model, errors/*, options*/) { this._updateErrorMessage(errors); }, "success": function () { var projects = that.model.project.models, updatedProject = [], findProject = function (id) { for (var key in projects) { if (projects.hasOwnProperty(key) && projects[key].get('id') == id) { return projects[key].attributes; } } }; for (var key in that.projectsList) { if (that.projectsList.hasOwnProperty(key)) { updatedProject.push(findProject(this.projectsList[key])); } } that.model.userProfile.set('project', updatedProject); this._setChangeProjectStatus({ success: true }); }, "error": function (error) { this._setChangeProjectStatus(error); }, "resetFields": this._onResetProjectFields }); this.dialog = new Dialog(); this.listenTo(this.dialog, { 'last-field-confirmed': function () { that._onDestroy(); }, 'save-projects-confirmed': function () { that.trigger("saveProject", that.model.userProfile, this.projectsList); }, 'unshare-confirmed': function () { that.trigger('unshare', that.$lastUnshareButton.data('email')); }, 'unshare-test-confirmed': function () { that.trigger('unshare-test', that.$lastUnshareTestButton.data('id')); }, 'leave-share-confirmed': function () { that.trigger('leave-share', that.$lastLeaveShareButton.data('id'), that.$lastLeaveShareButton.data('project')); }, 'destroy-profile-prompted': function (input) { if (input === "DELETE") { that.trigger("destroy"); } } }); this.listenTo(this, { 'updated-shares': function () { var lines = ''; //todo move this to template _.each(this.model.shares.shareMine, function (share) { lines += '<tr><td>' + share.email + '</td><td>' + (share.name || '') + '</td><td><a class="button button-detail id-unshare" data-email="' + share.email + '">Unshare</a></td></tr>'; }); $('table.sharing tr:not(:first):not(:last)').remove(); $('table.sharing tr:first').after(lines); if (this.model.shares.shareMine.length) { this.$('table.sharing .no-tests').hide(); } }, 'last-site-admin': function () { $('.box-sign-in p').css({color: 'red'}); } }); this.sharePopup = new SharePopup(); }, render: function () { this.$el.html(this.template({ Constants: Constants, model: this.model.userProfile, homePageTitle: this.model.homePageTitle, shares: this.model.shares, moment: moment, isAvanir: DataLayerConstants.branding === "Avanir" })); this.$firstName = this.$(".id-first-name"); this.$secondName = this.$(".id-second-name"); this.$birthday = this.$(".id-birthday"); this.$genderRadios = this.$("input:radio[name=gender]"); this.$passwordOld = this.$(".id-password-old"); this.$passwordNew = this.$(".id-password-new"); this.$passwordConfirmation = this.$(".id-password-confirmation"); this.$errorFirstName = this.$(".id-error-first-name"); this.$errorSecondName = this.$(".id-error-second-name"); this.$errorGender = this.$(".id-error-gender"); this.$errorBirthday = this.$(".id-error-birthday"); this.$errorPasswordOld = this.$(".id-error-password-old"); this.$errorPasswordNew = this.$(".id-error-password-new"); this.$errorPasswordConfirm = this.$(".id-error-password-confirm"); this.$saveStatus = this.$(".id-save-status"); this.$changePasswordStatus = this.$(".id-change-password-status"); this.$changeProjectStatus = this.$(".id-change-project-status"); this.$capsLockWarning = this.$(".id-warning-message"); this.subsections = { "profile-data": { menu : this.$('.side-menu .profile-data'), subsection: this.$('.content-container>.profile-data') }, "change-password": { menu : this.$('.side-menu .change-password'), subsection: this.$('.content-container>.change-password') }, "project-list-selector": { menu : this.$('.side-menu .project-list-selector'), subsection: this.$('.content-container>.project-list-selector') }, "sharing": { menu : this.$('.side-menu .sharing'), subsection: this.$('.content-container>.sharing') } }; this.subsectionsPermissions = {}; this.subsectionsPermissions[Constants.UserRole.Patient] = ["profile-data", "change-password", "project-list-selector", "sharing"]; this.subsectionsPermissions[Constants.UserRole.Analyst] = ["profile-data", "change-password", "sharing"]; this.subsectionsPermissions[Constants.UserRole.SiteAdmin] = ["profile-data", "change-password"]; this.$("input, textarea").placeholder(); var gender = this.model.userProfile.get("gender"); this.$genderRadios.filter('[value="' + gender + '"]').attr("checked", true); // Add change lister // this.$("input").change(this._hideErrorsAndStatuses); this.$birthday.datepicker({ minDate: '-150y', maxDate: "-1y", yearRange: "-150:-1", dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true }); this.$projects = { all: this.$('#all_projects'), selected: this.$('#projects') }; //fill projects list this.projectsList = []; var projectList = this.model.userProfile.get('project'); for (var key in projectList) { if (projectList.hasOwnProperty(key)) { this.projectsList.push(projectList[key].id); } } this._hideErrorsAndStatuses(); this.$('.side-menu a').click(_.bind(this._subMenuNavigation, this)); if (this.model.shares.social && this.model.shares.social.length) { this.$('table.shared-tests .no-tests').hide(); } if (this.model.shares.shareMine && this.model.shares.shareMine.length) { this.$('table.sharing .no-tests').hide(); } if (this.model.shares.shareOthers && this.model.shares.shareOthers.length) { this.$('table.shared .no-tests').hide(); } var allowedSections = this.subsectionsPermissions[this.model.userProfile.get("role")]; var section = (this.options.activeSection && _.indexOf(allowedSections, this.options.activeSection) >= 0) ? this.subsections[this.options.activeSection] : this.subsections[_.first(allowedSections)]; section.menu.parent().addClass('active'); section.subsection.show(); return this; }, _hideErrorsAndStatuses: function () { this.$saveStatus.hide(); this.$changePasswordStatus.hide(); this.$changeProjectStatus.hide(); this.$(ErrorStyle).hide().removeAttr('title'); this.$('input, select').removeClass('errored'); }, _onResetPasswordFields: function () { this.$passwordOld.val(""); this.$passwordNew.val(""); this.$passwordConfirmation.val(""); }, _onResetProjectFields: function () { //todo: make function restore previous state }, _onSaveProfile: function () { this._hideErrorsAndStatuses(); var userProfileValues = { firstName: $.trim(this.$firstName.val()), secondName: $.trim(this.$secondName.val()), birthdayFormatted: $.trim(this.$birthday.val()), gender: this.$genderRadios.filter(":checked").val() }; // if (!this.model.userProfile.validate(userProfileValues, {birthdayRequired:true, genderRequired:true})) { this.trigger("saveProfile", this.model.userProfile, userProfileValues); // } }, _submitProfileDataOnEnter: function (e) { if (e.keyCode === 13) { this._onSaveProfile(); } }, _onSavePassword: function () { var newPasswordValues = { passwordOld: this.$<PASSWORD>.val(), passwordNew: <PASSWORD>.$<PASSWORD>(), passwordConfirmation: this.$<PASSWORD>.val() }; if (this.model.passwordModifier.set(newPasswordValues, { validate: true })) { this.trigger("savePassword", this.model.userProfile); } }, _submitChangePassOnEnter: function (e) { if (e.keyCode === 13) { this._onSavePassword(); } }, _onSaveProject: function () { var newProjectList = this.projectsList, oldProjectsList = this.model.userProfile.get('project'); this._hideErrorsAndStatuses(); if (projectsNotRemoved()) { if (newProjectList.length > oldProjectsList.length) { this.trigger("saveProject", this.model.userProfile, this.projectsList); } } else { this.dialog.show("confirm", "Data from unassigned " + Constants.customLabel("projects") + " will be lost permanently.<br><br>Proceed?", "save-projects"); } function projectsNotRemoved() { if (newProjectList.length < oldProjectsList.length) { return false; } else { for (var key = 0; key < oldProjectsList.length; key++) { if (newProjectList.indexOf(oldProjectsList[key].id) < 0) { return false; } } } return true; } }, _onCancel: function () { this.trigger("cancel"); }, _updateErrorMessage: function (errors) { _.forEach(errors, function (error) { var errored = { $container: null }; switch (error.code) { case ErrorConstants.Validation.EmptyFirstName.code: errored.$container = this.$errorFirstName; break; case ErrorConstants.Validation.EmptySecondName.code: errored.$container = this.$errorSecondName; break; case ErrorConstants.Validation.EmptyBirthday.code: case ErrorConstants.Validation.InvalidBirthday.code: errored.$container = this.$errorBirthday; this.$errorBirthday.show(); break; case ErrorConstants.Validation.EmptyGenderSelected.code: errored.$container = this.$errorGender; break; case ErrorConstants.Validation.EmptyOldPassword.code: errored.$container = this.$errorPasswordOld; break; case ErrorConstants.Validation.EmptyNewPassword.code: errored.$container = this.$errorPasswordNew; break; case ErrorConstants.Validation.InvalidPasswordConfirmation.code: errored.$container = this.$errorPasswordConfirm; break; default: this._setSaveStatus(error); break; } if (errored.$container) { errored.$container.show().html(error.description) .attr('title', error.description); errored.$input = errored.$input || errored.$container.closest('.sign-row').find('input[type!=radio], select'); errored.$input.addClass('errored'); } }, this); }, _validatePassword: function (e) { var keyCode = e.which; if (keyCode >= 65 && keyCode <= 90) { this._toggleCapsLockWarning(!e.shiftKey); } else if (keyCode >= 97 && keyCode <= 122) { this._toggleCapsLockWarning(e.shiftKey); } }, _toggleCapsLockWarning: function (showWarning) { if (showWarning) { this._capsLock = true; this.$capsLockWarning.show(); } else { this._capsLock = false; this.$capsLockWarning.hide(); } }, _setSaveStatus: function (status) { var prefix; if (status.success) { prefix = "User profile updated successfully. "; this.$saveStatus.removeClass(ErrorStyle) .addClass(SuccessStyle); } else { prefix = "User profile update failed. "; this.$saveStatus.removeClass(SuccessStyle) .addClass(ErrorStyle); } this.$saveStatus.html(prefix + (status.description ? status.description : "")) .show(); }, _setChangePasswordStatus: function (status) { var prefix; if (status.success) { prefix = "Password changed successfully. "; this.$changePasswordStatus.removeClass(ErrorStyle) .addClass(SuccessStyle); } else { prefix = "Password change failed. "; this.$changePasswordStatus.removeClass(SuccessStyle) .addClass(ErrorStyle); } this.$changePasswordStatus.html(prefix + (status.description ? status.description : "")) .show(); }, _setChangeProjectStatus: function (status) { var prefix; if (status.success) { prefix = Constants.customLabel("Projects") + " list changed successfully. "; this.$changeProjectStatus.removeClass(ErrorStyle) .addClass(SuccessStyle); } else { prefix = Constants.customLabel("Projects") + " list change failed. "; this.$changeProjectStatus.removeClass(SuccessStyle) .addClass(ErrorStyle); } this.$changeProjectStatus.html(prefix + (status.description ? status.description : "")) .show(); }, _onDestroy: function () { this.dialog.show('prompt', this.destroyConfirmationTemplate({ profile: this.model.userProfile }), 'destroy-profile'); }, _projectAdd: function () { var selectedOptions = this.$projects.all.find('option:selected'); if (selectedOptions.length) { var that = this; this.$projects.selected.append(selectedOptions); selectedOptions.each(function () { that.projectsList.push(parseInt($(this).val(), 10)); }); } }, _projectRemove: function () { var errorMessages = { lastField: 'You cannot unassign all projects.<br>Perhaps, you want to delete your account?', assigned: 'You cannot unassign from current project.<br>Please, login to different project to proceed' }, options = this.$projects.selected.find('option'), selectedOptions = options.filter(':selected'); if (options.length === selectedOptions.length) { this.dialog.show('confirm', errorMessages.lastField, 'last-field'); } else { var currentProject = this.model.userProfile.get('projectId'); if (selectedOptions.length) { var that = this; selectedOptions.each(function (index) { var id = parseInt($(this).val(), 10); if (currentProject == id) { that.dialog.show('alert', errorMessages.assigned); } else { that.$projects.all.append($(this)); that.projectsList.splice(that.projectsList.indexOf(id), 1); } }); } } }, _subMenuNavigation: function (e) { e.preventDefault(); var $menuContainer = $('.side-menu'), $oldSub = $('.side-menu .active a'), $newSub = $(e.currentTarget), oldSubClass = $oldSub.attr('class'), newSubClass = $newSub.attr('class'), active = $('.side-menu .active'); if (oldSubClass === newSubClass || $menuContainer.is('.in-progress')) { return false; } $menuContainer.addClass('in-progress'); active.removeClass('active'); $newSub.parent().addClass('active'); this.trigger("subsection-changed", newSubClass); $('.content-container>.' + oldSubClass).fadeOut(function () { $('.content-container>.' + newSubClass).fadeIn(function () { $menuContainer.removeClass('in-progress'); }); }); return false; }, _leaveShare: function (e) { this.$lastLeaveShareButton = $(e.target); this.dialog.show('confirm', 'You will lose access to this test room.<br><br>Proceed?', 'leave-share'); }, _unshare: function (e) { this.$lastUnshareButton = $(e.target); this.dialog.show('confirm', 'This user will loose access to your test room.<br><br>Proceed?', 'unshare'); }, _shareAll: function () { this.trigger('share-all'); }, _shareTest: function (e) { this.trigger('share-test', $(e.target).data('token')); }, _unshareTest: function (e) { this.$lastUnshareTestButton = $(e.target); this.dialog.show('confirm', 'Noone will be able to view this test with a previously generated link.<br><br>Proceed?', 'unshare-test'); } }); }); <file_sep>define({ TestType: { NM: "nmTest", PQ: "pqTest" }, TestHand: { Left: "left", Right: "right" }, TestResultState: { NotPassed: "n/a", Passing: "passing", Passed: "passed", Canceled: "canceled", Skipped: "skipped" } }); <file_sep>/*global define: true */ define([ 'underscore', 'backbone', 'Models/Constants', 'text!Templates/ResetPassword.html' ], function (_, Backbone, ModelsConstants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper reset-password", template: _.template(templateHtml), events: { "click .id-button-reset-password": "_resetPassword", "keypress input": "_submitOnEnter" }, initialize: function () { this.listenTo(this.model.reset, { "invalid": function (model, errors) { this._updateValidationError(errors); }, "error:reset-password": this._updateResetError }); }, render: function () { this.model.Constants = ModelsConstants; this.$el.html(this.template(this.model)); this.$email = this.$(".id-email"); this.$error = this.$(".id-error").hide(); if (this.model.reset.get('email')) { this.$email.val(this.model.reset.get('email')); } var that = this; //todo:refacor this to change render->afterRender events setTimeout(function () { that.$email.focus(); }); return this; }, _updateResetError: function (error) { this.$error.html(error.description) .show(); }, _updateValidationError: function (error) { this.$error.html(error.description) .show(); }, _hideErrorsAndStatuses: function () { this.$error.hide(); }, _resetPassword: function () { this._hideErrorsAndStatuses(); var email = $.trim(this.$email.val()); if (this.model.reset.set("email", email, { validate: true })) { this.model.reset.resetPassword(); } }, _submitOnEnter: function (e) { if (e.keyCode === 13) { this._resetPassword(); } } }); }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Utils/MathExtensions', 'text!Templates/TestSessionReport.html', 'text!Templates/TestSessionReportTestRoomLink.html', 'moment' ], function (_, Backbone, ModelsConstants, MathExtensions, templateHtml, templateTestRoomLinkHtml, moment) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), templateTestRoomLink: _.template(templateTestRoomLinkHtml), events: { "click .id-user-test-room": "_onClickUserTestRoom" }, _views: null, initialize: function () { this._views = []; }, render: function () { this.$el.html(this.template({ model: this.model, clientSystemInfo: this.model.parseClientSystemInfo(), moment: moment, Constants: ModelsConstants, MathExtensions: MathExtensions, shared: /^shared/.test(Backbone.history.fragment) })); this.$userRow = this.$(".id-user-test-room"); return this; }, showContentView: function (view) { this.$el.append(view.render().el); }, showLinkToTestRoom: function (userProfile) { this.$userRow.html(this.templateTestRoomLink(userProfile)); }, _onClickUserTestRoom: function () { this.trigger("user-test-room"); return false; } }); }); <file_sep> flot library - https://github.com/flot/flot flot plug-ins - https://github.com/flot/flot/wiki/Plugin-Repository flot curved line plug-in - http://www.billigerbiken.de/CurvedLines/ excanvas.js and excanvas.min.js get fom flot repository <file_sep>/*global define: true */ define([ 'jQuery', 'underscore', 'backbone', 'text!Templates/AnalystRoom.html', 'Models/UserProfileCollection', 'Views/AnalystRoomRowView' ], function ($, _, Backbone, templateHtml, UserProfileCollection, UserListRowView) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper analyst-room", template: _.template(templateHtml), events: { "click .id-button-create-new": "_onClickCreateNew", "click .id-button-add-existing": "_onClickAddExisting" }, initialize: function () { if (!this.model && this.model instanceof UserProfileCollection) { throw new Error("Model not set or wrong type."); } this._initializeRowViews(); //this._fillRows(); this.listenTo(this.model, { "reset": this._onReset }); this._rowViews = {}; }, _onReset: function () { this._removeAllRowsViews(); this._initializeRowViews(); this._fillRows(); }, // Remove view from DOM remove: function () { // Destroy row views this._removeAllRowsViews(); // Call base implementation Backbone.View.prototype.remove.call(this); }, // Destroy all row view _removeAllRowsViews: function () { _.each(this._rowViews, function (rowView, key, collection) { rowView.remove(); delete collection[key]; }); }, _initializeRowViews: function () { if (this.model) { _.forEach(this.model.models, function (rowModel) { this._rowViews[rowModel.cid] = new UserListRowView({ model: rowModel }); }, this); } }, _fillRows: function () { _.each(this.model.models, function (rowModel) { var rowView = this._rowViews[rowModel.cid]; this.$resultTable.append(rowView.render().el); }, this); this._updateNoResultRow(); }, _updateNoResultRow: function () { if (this.model.length > 0) { this.$noResultsRow.hide(); } else { this.$noResultsRow.show(); } }, render: function () { this.$el.html(this.template(this.model.attributes)); this.$noResultsRow = this.$(".id-no-results"); this.$resultTable = this.$(".result-table"); return this; }, hide: function () { this.$el.hide(); }, show: function () { this.$el.show(); }, _onClickAddExisting: function () { this.model.trigger("addExisting"); }, _onClickCreateNew: function () { this.model.trigger("createNew"); } }); }); <file_sep>/*global define: true */ define([ 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/ErrorConstants', 'Views/Constants', 'Models/Constants', 'Views/NotFoundView', 'formatter' ], function (Constants, ControllerBase, ErrorConstants, ViewsConstants, ModelsConstants, NotFoundView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); }, parseParams: function (params) { var result = {}; if (params.length > 0) { result.route = params[0]; } return result; }, activate: function (params) { if (params.route && /\/$/.test(params.route)) { this.trigger('removeSlash', params.route); return; } var accountManager = this.get("accountManager"); this.view = new NotFoundView(); this.listenTo(this.view, { }); // Initialize menu var applicationView = this.get("applicationView"); //get user role and show proper menu var role = this.get("accountManager").get("currentUser") && this.get("accountManager").get("currentUser").get("role"); switch (role) { case ModelsConstants.UserRole.Patient: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Patient); break; case ModelsConstants.UserRole.Analyst: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Analyst); break; case ModelsConstants.UserRole.SiteAdmin: applicationView.header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin); break; default: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Authorization); } // Show view applicationView.showView(this.view); }, deactivate: function () { this._reset(); } }); }); <file_sep><!DOCTYPE> <html lang="en-us" xml:lang="en-us" dir="ltr" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <title>Kinetics Foundation</title> <link type="text/css" rel="stylesheet" href="css/main.css"/> </head> <body> <div id="main-container"> <div class="content-wrapper landing-page"> <div class="landing-wrapper"> <div class="landing-presentation"> <div class="logo"> <p class="license"> <span>Kinetics Foundation has made it’s OPDM 2 tool Open Source per the</span> <a href="license-2.0.txt" target="_blank">Apache license</a></p> </div> <h1>Objective Movement<br>Disorders Measurement</h1> <p class="highlight">Take control of measuring your movement disorder symptoms today!</p> <div class="main clearfix"> <p>The Movement Disorder Objective Measurement System 2.0 features easy-to-use tests that enable you to measure your performance and store your results online. It's free. </p> <p class="highlight">All data can be saved for later viewing, and viewed graphically over time.</p> <div class="dexterity"> <div class="wrap"> <h2>Dexterity System</h2> <p>From any web enabled device you can take a simple test to see how fast you can press keys on a keyboard</p> <img src="images/dexterity-presentation.png"> </div> <a href="/kineticsweb/#testing/try" class="button id-sign-up">Try It!</a> <a href="/kineticsweb/#welcome" class="button id-sign-up">Login</a> <a href="/kineticsweb/#sign-up" class="button id-sign-up">Register</a> </div> <div class="mobility"> <div class="wrap"> <h2>Mobility System</h2> <p>Self-administer a Timed-Up-and-Go (TUG) test or a Postural-Stability-and-Sway test on any smartphone.</p> <img src="images/mobility-presentation.png"> </div> <a href="https://itunes.apple.com/us/app/opdm-mobility/id642954620?mt=8" class="appStore">App Store</a> <a href="https://play.google.com/store/apps/details?id=org.kineticsfoundation" class="googlePlay">Google Play</a> </div> </div> <div class="footer"> <p>The MDOMS 2.0 is a free service provided for by philanthropic funds. We’re not ad based, and we won't sell your data or e-mail address.<br> For support or more information you can visit us at <a href="http://www.kineticsfoundation.org">www.kineticsfoundation.org</a> </p> <p>Clinicians: be sure to inquire about our free trial management interface by contacting us at <a href="mailto:<EMAIL>"><EMAIL></a>. <!--(<a href="#">how do you want them to inquire or contact?</a>)--></p> <p class="info-links"> <a href="kineticsweb/#info/terms-of-service" class="link-to-info-page">Terms of Service</a> <span class="vertical-line">|</span> <a href="kineticsweb/#info/privacy-policy"class="link-to-info-page">Privacy Policy</a> </p> </div> </div> </div> </div> </div> <script>/* (function (i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m) })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga'); ga('create', 'UA-41772384-1', 'kineticsfoundation.org'); ga('send', 'pageview'); */ </script> </body> </html><file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'lowLag' ], function ($, _, lowLag) { "use strict"; var loaded = [], lowLagOptions = {'urlPrefix': 'audio/'}, audioHelper, a = document.createElement('audio'), audioSupport = { basic: !!a.canPlayType, mp3: !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, '')), ogg: !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, '')), wav: !!(a.canPlayType && a.canPlayType('audio/wav; codecs="1"').replace(/no/, '')) }, audioElements = {}; if ($.browser.msie) { audioHelper = { play: audioSupport.basic ? function (audio) { if (!audioElements[audio]) { audioElements[audio] = $('#' + audio).get(0); } audioElements[audio].pause(); audioElements[audio].currentTime = 0; audioElements[audio].play(); } : $.noop, pause: function (audio) { audioElements[audio].currentTime = 0; audioElements[audio].pause(); } }; } else { lowLag.init(lowLagOptions); audioHelper = { play: function (sound) { if (_.indexOf(loaded, sound) < 0) { var soundOrder = !$.browser.mozilla ? [sound + '.mp3', sound + '.ogg', sound + '.wav'] : [sound + '.ogg', sound + '.mp3', sound + '.wav']; lowLag.load(soundOrder, sound); loaded.push(sound); } lowLag.play(sound); }, pause: function (sound) { lowLag.pause(sound); } }; } return audioHelper; });<file_sep>define([ 'Testing/Models/TestScreens/ScreenBase', 'Testing/Models/TestScreens/CheckTestResultsState', 'Testing/Models/TestScreens/StartScreen', 'Testing/Models/TestScreens/CountdownScreen', 'Testing/Models/TestScreens/SelectTestTypeState', 'Testing/Models/TestScreens/TestEndsScreenBase', 'Testing/Models/TestScreens/TestingNMScreen', 'Testing/Models/TestScreens/TestingPQScreen', 'Testing/Models/TestScreens/SummaryScreen', 'Testing/Models/TestScreens/TestDetailsScreen' ], function (ScreenBase, CheckTestResultsState, StartScreen, CountdownScreen, SelectTestTypeState, TestEndsScreenBase, TestingNMScreen, TestingPQScreen, SummaryScreen, TestDetailsScreen) { 'use strict'; var TestScreens = { ScreenBase: ScreenBase, CheckTestResultsState: CheckTestResultsState, StartScreen: StartScreen, CountdownScreen: CountdownScreen, SelectTestTypeState: SelectTestTypeState, TestingNMScreen: TestingNMScreen, TestingPQScreen: TestingPQScreen, TestPassedScreen: TestEndsScreenBase.extend({}), TestCanceledScreen: TestEndsScreenBase.extend({}), SummaryScreen: SummaryScreen, TestDetailsScreen: TestDetailsScreen }; return TestScreens; }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Router', 'Views/ApplicationView', 'Views/CurrentUserView', 'Views/CurrentProjectView', 'Models/AccountManager' ], function (_, Backbone, Router, ApplicationView, CurrentUserView, CurrentProjectView, AccountManager) { 'use strict'; var Application = function () { this.homePage = {}; this.globalModels = {}; this.accountManager = new AccountManager(); this.applicationView = new ApplicationView({ model: { accountManager: this.accountManager } }); var currentUserView = new CurrentUserView({ model: this.accountManager }); this.applicationView.showView(currentUserView); var currentProjectView = new CurrentProjectView({ model: this.accountManager }); this.applicationView.showView(currentProjectView); this.router = new Router(null, this); Backbone.history.start(); }; _.extend(Application.prototype, {}); return Application; }); <file_sep>/*global define: true */ define([ 'jQuery', 'backbone', 'Views/HeaderView', 'DataLayer/Constants', 'hashchage' ], function ($, Backbone, HeaderView, constants) { 'use strict'; return Backbone.View.extend({ el: $("#main-container"), initialize: function () { var that = this; if (!this.model) { throw new Error("Model not set."); } var accountManager = this.model.accountManager; if (!accountManager) { throw new Error("Account manager not set in the model."); } this.header = new HeaderView({ model: { accountManager: accountManager } }); this.render(); if (constants.analytics) { window._gaq = window._gaq || []; window._gaq.push(['_setAccount', constants.analyticsId]); //_gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); this.trackPage(); $(window).hashchange(function () { that.trackPage(); }); } $(document) .ajaxStart(this._ajaxRequestStart) .ajaxStop(this._ajaxRequestStop) .ajaxError(this._ajaxRequestStop); if ('WebkitAppearance' in document.documentElement.style && navigator.userAgent.indexOf('Android') >= 0 && navigator.userAgent.indexOf('Chrome') === -1) { $('body').addClass('android-native'); } }, render: function () { this.$el.append(this.header.render().el); }, trackPage: function () { try { window._gaq.push(['_trackPageview', location.pathname + location.search + location.hash]); //console.info('really tracked'); } catch (e) { //console.info('not really tracked'); } }, showView: function (view) { this.$el.append(view.render().el); }, updateView: function (view) { this.$el.find('>.content-wrapper').remove(); this.showView(view); }, _ajaxRequestStart: function () { $('body').addClass('ajaxRequestInProcess'); }, _ajaxRequestStop: function () { $('body').removeClass('ajaxRequestInProcess'); } }); });<file_sep>/*global define: true */ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Testing/Views/TestSessionView', 'Testing/Models/DexterityCalculator', 'Testing/Models/TestSessionResults', 'Testing/Models/TestSession', 'Testing/Models/TestTransitionsInstance', 'Testing/Models/ScreenTransitionsInstance', 'Models/TestSessionResultsRow', 'Views/Constants', 'Models/ExtensionsCollection', 'Utils/Dialog' ], function ($, _, Constants, ControllerBase, TestSessionView, DexterityCalculator, TestSessionResults, TestSession, testTransitions, screenTransitions, TestSessionResultsRow, ViewsConstants, ExtensionsCollection, Dialog) { 'use strict'; return ControllerBase.extend({ registerAfterTest: false, initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("accountManager"); this.dexterityCalculator = new DexterityCalculator(); this.dialog = new Dialog(); }, parseParams: function (params) { var result = {}; if (params.length === 2 && params[0] === Constants.ActionMarker) { result.action = params[1]; } else { this.registerAfterTest = false; if (params.length === 1 && params[0] === Constants.TestTryIt) { this.registerAfterTest = true; result.userId = null; } else { result.userId = params[0]; } } return result; }, activate: function (params) { var accountManager = this.get("accountManager"); //todo: refactor this functionality if (this.registerAfterTest && accountManager.get('currentUser')) { // return to user-test-room this.trigger("user-test-room"); this.dialog.show('alert', '"Try It" is for new users. You are already logged in, we are taking you to the Test Room now.<br><br>If you want to use "Try It", please logout first.'); } else { // Create new test session results this.testSessionResults = new TestSessionResults(); // Initialize listening model for dexterity calculation this.dexterityCalculator.set("sessionResults", this.testSessionResults); if (this.registerAfterTest) { //Set blank custom question collection this._setNoCustomFields(); } else { // Getting test details custom questions this._getCustomFields(); } this.userId = params.userId; } this._toggleUserSelector(); }, _setNoCustomFields: function () { this.customFieldsCollection = {}; this._proceedControllerActivation(); }, _getCustomFields: function () { //Getting test custom fields this.customFieldsCollection = new ExtensionsCollection(); var self = this; var options = this._getFetchOptions(true, function () { self._proceedControllerActivation(); }, this._getCustomFields); this.customFieldsCollection.fetch(options); }, _proceedControllerActivation: function () { this.testSession = new TestSession({ sessionResults: this.testSessionResults, testTransitions: testTransitions(parseInt(this.customFieldsCollection.length, 10)), screenTransitions: screenTransitions, customFields: this.customFieldsCollection, registerAfterTest: this.registerAfterTest }); // Start listening control events this.listenTo(this.testSession, { "submit": this._onSubmit, "cancel": this._onCancel, "register": this._onRegister }); // Initialize menu var applicationView = this.get("applicationView"); applicationView.header.showMenu(ViewsConstants.HeaderMenu[this.registerAfterTest ? 'Authorization' : 'Testing']); // Show test session view this.view = new TestSessionView({ el: applicationView.el, model: { testTransitions: testTransitions(parseInt(this.customFieldsCollection.length, 10)), screenTransitions: screenTransitions, registerAfterTest: this.registerAfterTest}, accountManager: this.get("accountManager") }); // Show view this.view.render(); // Start test session if (this.testSession) { this.testSession.start(); } //Clear previous test data localStorage.removeItem('kinetics-TestResults'); }, deactivate: function () { if (this.testSession && this.testSession.isStarted()) { this.testSession.stop(); } this._reset(); }, _reset: function () { this._toggleUserSelector(true); this.stopListening(); this.dexterityCalculator.set("sessionResults", null); if (this.view) { this.view.remove(); this.view = null; } this.testSessionResults = null; this.customFieldsCollection = null; }, _toggleUserSelector: function (isShowed) { var $userSelector = $('.username select'); if ($userSelector.length) { if (isShowed) { $userSelector.removeAttr('disabled'); } else { $userSelector.attr('disabled', 'disabled'); } } }, _onSubmit: function () { var container = TestSessionResultsRow.buildFromTestSessionResults(this.testSessionResults, this.userId); this._submit(container); }, _submit: function (container) { var submitHandler = _.bind(this._submit, this, container), that = this; container.save(null, { wait: true, accountManager: this.get("accountManager"), userId: that.userId || null, errorOther: _.bind(function (model, xhr, options) { delete this.currentRequest; this.trigger("error", options.responseError); }, this), errorUnauthenticated: _.bind(function (/*errorObject*/) { delete this.currentRequest; this._sleep(submitHandler); // this.trigger("unauthenticated"); //looping welcome controller }, this), success: _.bind(function () { delete this.currentRequest; this.trigger("submit", container); this.trigger("submitted", that.userId); }, this) }); }, _onRegister: function (options) { var container = TestSessionResultsRow.buildFromTestSessionResults(this.testSessionResults, null), testResults = { type: container.get('type'), score: container.get('score'), rawData: container.get('rawData'), isValid: container.get('isValid'), notes: container.get('notes') }; localStorage.setItem('kinetics-TestResults', JSON.stringify(testResults)); this.trigger('sign-up'); }, _onCancel: function () { this.trigger("cancel", this.userId); } }); }); <file_sep>/*global define: true*/ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Views/Constants', 'Views/TrendReportView', 'Models/TestSessionResultsRowCollection', 'Models/TrendReportModel', 'Models/UserProfile', 'DataLayer/ErrorConstants', 'text!Templates/UserNotAccessible.html' ], function ($, _, Constants, ControllerBase, ViewsConstants, TrendReportView, TestSessionResultsRowCollection, TrendReportModel, UserProfile, ErrorConstants, UserNotAccessible) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("accountManager"); // Bind methods with 'this' reference _.bindAll(this, "_fetchRowCollection", "_initializeTrendModel"); // Elements of models collection will be disposed in the base class this.models = {}; }, parseParams: function (params) { var result = {}; if (params.length === 1) { result.userId = params[0]; } if (params.length === 2) { try { result.userId = +$.base64.decode(params[0]); result.project = +$.base64.decode(params[1]); } catch (e) { this.trigger('parsing-error'); } } return result; }, activate: function (params) { this._readOnly = !!params.userId && !!params.project; this.userId = params.userId; this.project = params.project; this.get('accountManager').trigger('viewed-user-updated', this.userId); this._viewInitialized = false; this._initializeRowCollection(params.userId, params.project); }, _initializeRowCollection: function (userId, project) { this.models.testResults = new TestSessionResultsRowCollection(null, { userId: userId, project: project }); this.models.testResults.comparator = "creationDate"; this._fetchRowCollection(); }, _fetchRowCollection: function () { var options = this._getFetchOptions(true, this._initializeTrendModel, this._fetchRowCollection), that = this; options.error = function (model, xhr, options) { if (options.responseError.code === ErrorConstants.ServerErrorsCodes.NoPermission) { that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; } if (options.responseError.code === ErrorConstants.ServerErrorsCodes.UserDoesNotExist) { var dropDownEntry = $('.username-text .id-username').find('option[value="' + that.get('accountManager').viewedUser + '"]'); if (dropDownEntry.length) { var dialog = $('#userNotAccessible'); dialog = dialog.length ? dialog : $('<div id="userNotAccessible"></div>'); dialog.html(_.template(UserNotAccessible)({username: dropDownEntry.text()})).dialog({modal: true}); setTimeout(function () { dialog.dialog('destroy'); that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; }, 3000); } else { that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; } } }; this.models.testResults.fetch(options); }, _initializeTrendModel: function () { this.models.trendModel = new TrendReportModel({ testResults: this.models.testResults }); this._initializeView(); }, _initializeView: function () { this.view = new TrendReportView({ model: this.models.trendModel, readOnly: this._readOnly }); this.listenTo(this.get("accountManager"), { "viewed-patient-changed": function (id) { this.trigger('change-patient', id); } }); this.listenTo(this.view, { "back-shared": function () { this.trigger('back-shared', $.base64.encode(this.userId), $.base64.encode(this.project)); } }); // Initialize menu var applicationView = this.get("applicationView"); // Show view applicationView.showView(this.view); this._viewInitialized = true; this.view.drawGraph(); }, // Initialize menu initializeMenu: function () { var activeButton = !this.userId ? "trendReport" : null; this.get("applicationView").header.showMenu(ViewsConstants.HeaderMenu.Default, activeButton); }, deactivate: function () { this._reset(); } }); }); <file_sep>// Require.js allows us to configure shortcut alias require.config({ // The shim config allows us to configure dependencies for // scripts that do not call define() to register a module shim: { 'underscore': { exports: '_' }, 'backbone': { deps: ['underscore', 'jQuery'], exports: 'Backbone' }, 'backbone.localStorage': ['backbone'], 'jQuery': { exports: 'jQuery' }, 'jQuery.ui': ['jQuery'], 'jQuery.hotkeys': ['jQuery'], 'jQuery.placeholder': ['jQuery'], 'jQuery.base64': ['jQuery'], 'jQuery.flot': ['jQuery'], 'jQuery.flot.time': ['jQuery.flot'], 'jQuery.flot.curvedLines': ['jQuery.flot'], 'jQuery.flot.valuelabels': ['jQuery.flot'], 'jQuery.flot.navigate': ['jQuery.flot'], 'recaptcha': { exports: 'Recaptcha' }, 'lowLag': { deps: ['soundmanager'], exports: 'lowLag' }, 'hashchage': ['jQuery'] }, paths: { 'jQuery': '../assets/jquery.min', 'jQuery.ui': '../assets/jquery-ui-min', 'jQuery.hotkeys': '../assets/jquery.hotkeys', 'jQuery.placeholder': '../assets/jquery.placeholder.min', 'jQuery.base64': '../assets/jquery.base64.min', 'excanvas': '../assets/excanvas', 'jQuery.flot': '../assets/jquery.flot', 'jQuery.flot.time': '../assets/jquery.flot.time', 'jQuery.flot.curvedLines': '../assets/jquery.flot.curvedLines', 'jQuery.flot.valuelabels': '../assets/jquery.flot.valuelabels', 'jQuery.flot.navigate': '../assets/jquery.flot.navigate', 'underscore': '../assets/lodash.underscore.min', 'backbone': '../assets/backbone.min', 'backbone.localStorage': '../assets/backbone.localStorage-min', 'recaptcha': 'https://www.google.com/recaptcha/api/js/recaptcha_ajax', 'text': '../assets/text', 'formatter': '../assets/string.format', 'moment': '../assets/moment.min', 'lowLag': '../assets/lowLag', 'soundmanager': '../assets/sm2/js/soundmanager2-nodebug', 'hashchage': '../assets/jquery.hashchange' } }); require([ 'Application' ], function (Application) { "use strict"; new Application(); });<file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants' ], function (Backbone, _, Constants, ErrorConstants) { 'use strict'; var isTrimmedEmpty = function (value) { return !_.isString(value) || (_.isString(value) && $.trim(value).length === 0); }; return Backbone.Model.extend({ defaults: { email: null, project: null, accountManager: null, finishStep:null, token:null }, initialize: function () { var accountManager = this.get("accountManager"); if (!accountManager) { throw new Error("Attribute 'accountManager' not set."); } // Retransmits events this.listenTo(accountManager, { "error:reset-password": function (errorObject) { this.trigger("error:reset-password", errorObject); } }); }, dispose: function () { this.stopListening(); }, validate: function (attrs) { if (attrs.token) { if (!attrs.password) { return ErrorConstants.Validation.EmptyPassword; } else { if (attrs.password != attrs.re_<PASSWORD>){ return ErrorConstants.Validation.InvalidPasswordConfirmation } } } else { if (isTrimmedEmpty(attrs.email)) { return ErrorConstants.Validation.EmptyEMail; } else if (!attrs.email.match(Constants.EmailPattern)) { return ErrorConstants.Validation.InvalidEMail; } } }, validateModel: function (options) { var error = this.validate(this.attributes); options = options || {}; if (error && !options.silent) { this.trigger('invalid', this, error, {}); } return !error; }, isReadyToConfirm: function () { return this.validateModel({ silent: true }); }, resetPassword: function () { var accountManager = this.get("accountManager"); accountManager.resetPassword(this.get("email")); }, setPassword:function(){ this.get('accountManager').setPassword({ password:<PASSWORD>('<PASSWORD>'), token:this.get('token'), email:this.get('email') }); } }); }); <file_sep>define([ 'Testing/Models/Test', 'Testing/Models/TestPropertiesHash', 'Testing/Models/ScreenTransitionsInstance' ], function (Test, testPropertiesHash, screenTransitions) { // Declare tests of test session var tests = { rightNMTest: new Test(null, null, testPropertiesHash.rightNMTest, screenTransitions), leftNMTest: new Test(null, null, testPropertiesHash.leftNMTest, screenTransitions), rightPQTest: new Test(null, null, testPropertiesHash.rightPQTest, screenTransitions), leftPQTest: new Test(null, null, testPropertiesHash.leftPQTest, screenTransitions) }; return tests; });<file_sep>define([ './StateTransitions', './TestScreens/TestScreenInstances' ], function (StateTransitions, screens) { var screenTransitions = new StateTransitions("checkResults", [ { stateName: "checkResults", state: screens.checkResults, transitions: [ { signal: "noResults", stateName: "start" }, { signal: "passed", stateName: "passed" }, { signal: "canceled", stateName: "canceled" } ] }, { stateName: "start", state: screens.startScreen, transitions: [ { signal: "start", stateName: "countdown" } ] }, { stateName: "countdown", state: screens.countdownScreen, transitions: [ { signal: "countdownEnds", stateName: "selectTest" }, { signal: "stop", stateName: "canceled" } ] }, { stateName: "selectTest", state: screens.selectTestState, transitions: [ { signal: "startNMTest", stateName: "testingNM" }, { signal: "startPQTest", stateName: "testingPQ" } ] }, { stateName: "testingNM", state: screens.testingNMScreen, transitions: [ { signal: "testEnds", stateName: "passed" }, { signal: "stop", stateName: "canceled" } ] }, { stateName: "testingPQ", state: screens.testingPQScreen, transitions: [ { signal: "testEnds", stateName: "passed" }, { signal: "stop", stateName: "canceled" } ] }, { stateName: "canceled", state: screens.testCanceledScreen, transitions: [ { signal: "repeat", stateName: "start" } ] }, { stateName: "passed", state: screens.testPassedScreen, transitions: [ { signal: "repeat", stateName: "start" } ] } ]); return screenTransitions; }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'Models/Constants', 'text!Templates/TestCustomFieldsRow.html', 'text!Templates/TestCustomFieldsText.html', 'text!Templates/TestCustomFieldsList.html' ], function (_, Backbone, ModelSyncExtension, ServerInteractionSerializersHash, Constants, TestCustomFieldsRowHtml, TestCustomFieldsText, TestCustomFieldsList) { 'use strict'; var textTpl = _.template(TestCustomFieldsText), listTpl = _.template(TestCustomFieldsList), gridTpl = _.template(TestCustomFieldsRowHtml); var Extension = Backbone.Model.extend({ 'defaults': { id: null, entity: null, name: null, type: null, properties: [], filters: [], list: [] }, getHtml: function (gridView) { gridView = gridView || false; var isRequiredField = (this.get('properties') || []).indexOf(Constants.CustomFields.Required) !== -1, id = this.get('id'), name = this.get('name'), list = this.get('list'), type = this.get('type'), isNumericField = type === Constants.CustomFields.Numeric, o = { "id": id, "name": name, "list": list, required: isRequiredField, numeric: isNumericField, type: type, delimiter: '; ', Constants: Constants }; if (gridView) { return gridTpl(o); } else { return type === Constants.CustomFields.List ? listTpl(o) : textTpl(o); } } }); ModelSyncExtension.extend(Extension.prototype, { "changeList": ServerInteractionSerializersHash.ExtensionManager.changeList, "changeProperties": ServerInteractionSerializersHash.ExtensionManager.changeProperties, "createListExtension": ServerInteractionSerializersHash.ExtensionManager.createListExtension, "createSimpleExtension": ServerInteractionSerializersHash.ExtensionManager.createSimpleExtension, "delete": ServerInteractionSerializersHash.ExtensionManager.deleteExtension, "modifyExtensionName": ServerInteractionSerializersHash.ExtensionManager.modifyExtensionName }); return Extension; }); <file_sep>/*global define: true */ define([ 'underscore', 'backbone', 'Models/Constants', 'DataLayer/ErrorConstants', 'text!Templates/SiteAdminProjectListRow.html' ], function (_, Backbone, ModelsConstants, ErrorConstants, templateHtml, templateConfirmationHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "result-row", template: _.template(templateHtml), templateConfirmation: _.template(templateConfirmationHtml), events: { "click .id-button-disable": "_onClickDisable", "click .id-button-manage": "_onClickManage", "click .id-name span": "_onClickName", "keypress .id-name input": "_onNameKeypress", "blur .id-name input": "_onNameBlur" }, initialize: function () { this.listenTo(this.model, { "change": this.render, "error": this._onError }); }, render: function () { this.$el.html(this.template({ model: this.model, Constants: ModelsConstants })); return this; }, _onError: function (error) { var errorMessage = this.$('.id-name .validationErrors').length ? this.$('.id-name .validationErrors') : $('<div class="validationErrors"></div>'); errorMessage.insertAfter(this.$('.id-name input')).hide().html(error.description).slideDown(); setTimeout(function () { errorMessage.slideUp(function () { $(this).remove(); }); }, 2000); this._onNameBlur(); }, _onClickDisable: function () { this.model.trigger("disable", this.model); }, _onClickName: function () { var $span = this.$('.id-name span'), $input = $span.siblings('input').length ? $span.siblings('input') : $('<input>').insertAfter($span); $span.hide(); $input.attr('disabled', false).val($span.text()).show().focus(); }, _onNameBlur: function () { var $input = this.$('.id-name input'), $span = $input.siblings('span'); $input.hide().val(''); $span.show(); }, _onNameKeypress: function (e) { var $input = this.$('.id-name input'); if (+e.keyCode === 13) { $input.attr('disabled', true); this.model.trigger("rename", this.model, $input.val()); } if (+e.keyCode === 27) { //doesn't work for some reason this._onNameBlur(); } }, _onClickManage: function () { this.model.trigger('manage-project', this.model.get('id')); } }); });<file_sep>/*global define: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/Constants', 'DataLayer/ErrorConstants', 'Views/Constants', 'Views/WelcomeView', 'formatter' ], function (_, Constants, ControllerBase, DataConstants, ErrorConstants, ViewsConstants, WelcomeView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); }, parseParams: function (params) { var result = {}; if (params.length > 0) { result.backToLocation = params[0]; if (/^shared-test\//.test(params[0])) { result.shareToken = params[0].split('/')[1]; } } return result; }, _onAuthenticate: function (email, password) { var accountManager = this.get("accountManager"), that = this; accountManager.authenticate(email, password, function (email, password, projects) { if (projects) { if (projects.length === 1) { accountManager.signIn(email, password, projects[0].id); } else { that.view.trigger('projectSelection', projects); } } else { accountManager.signIn(email, password); } }); }, _onProjectSelected: function (email, password, project) { this.get("accountManager").signIn(email, password, project); }, activate: function (params) { this.backToLocation = params.backToLocation; this.shareToken = params.shareToken; var accountManager = this.get("accountManager"); this._email = params.email; if (accountManager.isUserSignedIn()) { this.trigger("user-already-sign-in"); return; } this.view = new WelcomeView({ model: { accountManager: accountManager, email: this._email }}); // Start listening control events this.listenTo(accountManager, { "error": this._onError, "authenticated": this._onAuthenticated }); this.listenTo(this.view, { "sign-up": this._onSignUp, "forgot-password": this._onForgotPassword, "authenticate": this._onAuthenticate, "projectSelected": this._onProjectSelected }); // Initialize menu var applicationView = this.get("applicationView"); applicationView.header.showMenu(ViewsConstants.HeaderMenu.Welcome); // Show view applicationView.showView(this.view); }, deactivate: function () { this._reset(); }, _reset: function () { ControllerBase.prototype._reset.call(this); delete this.backToLocation; }, _onAuthenticated: function () { var accountManager = this.get("accountManager"), back; back = accountManager._previousRole === accountManager.currentUser().get("role") ? this.backToLocation : null; // Retransmits event this.trigger("authenticated", { back: back }); }, _onSignUp: function () { // Retransmits event this.trigger("sign-up", this.shareToken); }, _onForgotPassword: function (email) { // Retransmits event this.trigger("forgot-password", email); }, _onError: function (error, options) { if (+error.code === +ErrorConstants.ServerErrorsCodes.UserIsNotActivated) { this.trigger("user-is-not-activated", options.email); } } }); }); <file_sep>define(['underscore', 'formatter'], function (_) { // Represent state machine transitions table var StateTransitions = function (startStateName, stateTransitionsTable) { this.startStateName = startStateName; this.table = stateTransitionsTable; }; _.extend(StateTransitions.prototype, { getStateItemByName: function (stateName) { var stateItem = _.find(this.table, function (elem) { return elem.stateName == stateName; }); if (!stateItem) { throw new Error("State '{0}' not found in transition table.".format(stateName)); } return stateItem; }, getTransitionTarget: function (stateItem, signal) { var transitionItem = _.find(stateItem.transitions, function (elem) { return elem.signal == signal; }); if (!transitionItem) { throw new Error("Not found transition for state '{0}' by signal '{1}'." .format(stateItem.stateName, signal)); } return transitionItem.stateName; } }); return StateTransitions; }); <file_sep>/*global define: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/ErrorConstants', 'Views/Constants', 'Models/Constants', 'Models/UserProfileCollection', 'Utils/Dialog', 'Views/AddUserView', 'text!Templates/UserAdded.html', 'formatter' ], function (_, Constants, ControllerBase, ErrorConstants, ViewsConstants, ModelsConstants, UserProfileCollection, Dialog, AddUserView, UserAdded) { 'use strict'; return ControllerBase.extend({ _UserAddedMessage: _.template(UserAdded), initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this.dialog = new Dialog(); }, parseParams: function (params) { return params; }, activate: function (params) { var accountManager = this.get("accountManager"), that = this; if (params) { this._projectUsers = params.projectUsers; this._users = params.users; this._project = params.project; } if (!this._users || !this._project || !this._projectUsers) { this.trigger('not-enough-data'); return; } this.model = new UserProfileCollection(); this.view = new AddUserView(); this.listenTo(this.view, { 'cancel': function () { that.trigger('cancel', that._project); }, 'search': this._onSearch, 'add-user': this._addUser }); // Initialize menu var applicationView = this.get("applicationView"); //get user role and show proper menu var role = this.get("accountManager").get("currentUser") && this.get("accountManager").get("currentUser").get("role"); // Show view applicationView.showView(this.view); }, initializeMenu: function () { this.get("applicationView").header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin); }, deactivate: function () { this._reset(); }, _onSearch: function (name, email) { var that = this, foundUsers = _.filter(this._users, function (user) { if (!_.where(user.get('project'), {id: that._project}).length) { var userName = user.get('firstName').toLowerCase() + ' ' + user.get('secondName').toLowerCase(); if (name && userName.indexOf(name.toLowerCase()) >= 0) { return true; } if (email && user.get('email') && user.get('email').toLowerCase().indexOf(email.toLowerCase()) >= 0) { return true; } } return false; }); this.view.trigger('found-users', foundUsers); this.lastSearch = {name: name, email: email}; }, _addUser: function (id) { var that = this; this.model.saveAssignments({ project: this._project, accountManager: this.get("accountManager"), users: _.union(this._projectUsers, [id]), success: function () { that._projectUsers.push(id); that._users = _.filter(that._users, function (user) { return user.get('id') !== id; }); that.dialog.show('alert', that._UserAddedMessage()); that._onSearch(that.lastSearch.name, that.lastSearch.email); } }); }, _onAssignmentSaved: function () { var that = this; //LOGIC with this._users } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'text!Templates/NoConnectionError.html' ], function ($, _, noConnectionError) { "use strict"; return { templates: { noConnection: _.template(noConnectionError) }, el: 'error-container', container: null, show: function (error) { this.container = $('#' + this.el); var errorText, errorMessage; if (!this.container.length) { this.container = $('<div id="' + this.el + '" class="flash-error"></div>').appendTo('body'); } if (this.container.children('.' + error).length) { return; } switch (error) { case 'no-connection' : errorText = this.templates.noConnection(); break; } errorMessage = $('<div class="error"></div>').addClass(error).hide().html(errorText).appendTo(this.container); if (this.container.children('.error').length > 1) { errorMessage.fadeIn(); } else { errorMessage.show(); this.container.fadeIn(); } }, hide: function (error) { var that = this; if (this.container) { if (!error || this.container.children('.error').length) { this.container.fadeOut(function () { that.container.children().remove(); }); } else { this.container.children('.' + error).fadeOut(function () { $(this).remove(); }); } } } }; });<file_sep><div class="user-container"></div> <div class="content-container"> <h1>Managing <%= Constants.customLabel('project') %>: <select class="id-project-selector"> <% _.each(projects, function (project) { %> <option value="<%= project.id %>" <%= project.id == currentProject ? 'selected' : '' %>><%= project.name %></option> <% }); %> </select> </h1> </div> <% if (newProject) { %> <div class="notification">Remember to add at least some users to your newly created project.</div> <% } %> <div class="save-or-reset"> <div class="addUserContainer"> <button type="button" class="button id-button-add-users button-20">Add users</button> <button type="button" class="button id-button-create-user button-20">Create user</button> </div> <button type="button" class="button id-reset button-20">Reset</button> <button type="button" class="button id-save-changes button-20">Remove selected</button> </div> <table class="result-table"> <tr> <th class="test-taken"> Name </th> <th class="user-email"> E-mail </th> <th class="test-role user-role"> Role </th> <th class="test-status"> Status </th> <th class="test-detail"> Remove </th> </tr> </table> <div class="result-row id-no-results"> <p> There are no users </p> </div> <div class="save-or-reset"> <button type="button" class="button id-reset button-20">Reset</button> <button type="button" class="button id-save-changes button-20">Remove selected</button> </div> <div class="description-separator"></div><file_sep>define([ 'Testing/Models/TestScreens/ScreenBase', 'Testing/Models/Constants', 'Utils/ConsoleStub', 'formatter' ], function (ScreenBase, Constants) { 'use strict'; // Helper state that checks current test type and help to select respective testing screen. return ScreenBase.extend({ activate: function () { // Call method form base prototype ScreenBase.prototype.activate.call(this); var testType = this._testProperties.get("testType"); console.log("Current test type is {0}".format(testType)); switch (testType) { case Constants.TestType.NM: this.trigger("signal:startNMTest"); break; case Constants.TestType.PQ: this.trigger("signal:startPQTest"); break; default : throw new Error("Invalid test type value '{0}'.".format(testType)); } }, _checkContext: function () { // Call base implementation ScreenBase.prototype._checkContext.call(this); if (!this._testProperties.has("testType")) { throw new Error("'testType' not specified in the test properties."); } } }); }); <file_sep>define([ 'underscore', 'backbone', 'Testing/Models/Constants', 'Testing/Models/TestPropertiesHash' ], function (_, Backbone, Constants, TestPropertiesHash) { 'use strict'; var TestResults = Backbone.Model.extend({ defaults: { sortIndex: null, testTag: null, keyPresses: null, spentTime: null, score: null, raw: null, state: Constants.TestResultState.NotPassed }, getTestName: function () { var testName = null; var testTag = this.get("testTag"); if (testTag) { var testProperties = _.find(TestPropertiesHash, function (testProperties) { return testProperties.get("tag") == testTag; }); if (testProperties) { testName = testProperties.get("name"); } } return testName; } }); return TestResults; }); <file_sep>/*global define: true */ define([ 'underscore', 'moment', 'backbone', 'Models/Constants', 'text!Templates/PatientInfo.html' ], function (_, moment, Backbone, Constants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), _analystMode: null, initialize: function () { this._analystMode = this.options.analystMode; this._showProjects = this.options.showProjects; }, render: function () { this.$el.html(this.template({ moment: moment, model: this.model, analystMode: this._analystMode, Constants: Constants, showProjects: this._showProjects })); return this; }, embed: function ($el) { $el.after(this.template({ moment: moment, model: this.model, analystMode: this._analystMode, Constants: Constants, showProjects: this._showProjects })); $el.parent().find('.content-container h1, .content-container .user-container').remove(); }, remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'backbone', 'underscore', 'text!Templates/AlertDialog.html', 'text!Templates/ConfirmDialog.html', 'text!Templates/PromptDialog.html' ], function ($, Backbone, _, AlertDialogHtml, ConfirmDialogHtml, PromptDialogHtml) { "use strict"; return Backbone.View.extend({ tagName: "div", className: "universal-dialog", el: 'dialog-container', alertTemplate: _.template(AlertDialogHtml), confirmTemplate: _.template(ConfirmDialogHtml), promptTemplate: _.template(PromptDialogHtml), events: { "click .id-ok": "_onOk", "click .id-cancel": "_onCancel" }, initialize: function () { var that = this, el = 'dialog-container'; this.$el = $('#' + el); if (!this.$el.length) { this.$el = $('<div/>').attr('id', el).hide() .addClass(this.className) .appendTo('body') .dialog({ modal: true, close: function () { that._onCancel(); }, autoOpen: false, minHeight: 10, width: 400 }); } }, show: function (mode, message, eventPrefix) { var template; this._mode = mode; this._eventPrefix = eventPrefix || ''; switch (mode) { case 'alert': template = this.alertTemplate; break; case 'confirm': template = this.confirmTemplate; break; case 'prompt': template = this.promptTemplate; break; default: console.log('No dialog type was chosen'); return this; } this.$el.addClass(mode).html(template({ message: message })); this.$el.find('a').button(); this.$el.dialog('open'); return this; }, _onCancel: function () { this.$el.removeClass('alert, confirm, prompt').dialog('close'); this._eventPrefix = ''; }, _onOk: function () { if (this._mode === 'confirm') { this.trigger(this._eventPrefix + '-confirmed'); } if (this._mode === 'prompt') { this.trigger(this._eventPrefix + '-prompted', this.$el.find('.id-prompt-input').val()); } this.$el.dialog('close').removeClass('alert confirm prompt'); this._eventPrefix = ''; }, remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); } }); });<file_sep>define([ 'backbone', 'Testing/Models/Constants' ], function (Backbone, Constants) { var ScreenViewBase = Backbone.View.extend({ tagName: "div", className: "content-wrapper", attributes: { id: "keyboard-test" }, _activated: false, initialize: function () { this.$el.hide(); this.listenTo(this.model, { "state:activating": this._onActivating, "state:activated": this._onActivated, "state:deactivated": this._onDeactivated }); }, render: function () { // Render only if model is activated if (this._activated) { this.$el.html(this.template({ model: this.model.attributes, Constants: Constants })); } return this; }, _onActivating: function () { if (!this.model.get("aggregator")) { this._bindToContext(); } this._activated = true; this.render(); }, _bindToContext: function () { this._testContext = this.model.get("testContext"); if (!this._testContext) { throw new Error("Test context not set."); } this._testResults = this._testContext.get("results"); if (!this._testResults) { throw new Error("Test results not set."); } }, _unbindFromContext: function () { this._testResults = null; this._testContext = null; }, _onActivated: function () { this.$el.show(); }, _onDeactivated: function () { this._activated = false; if (!this.model.get("aggregator")) { this._unbindFromContext(); } this.$el.hide(); } }); return ScreenViewBase; }); <file_sep>/*global define:true */ define([ 'Testing/Models/TestScreens/ScreenBase', 'Testing/Models/Constants' ], function (ScreenBase, Constants) { 'use strict'; return ScreenBase.extend({ _checkContext: function () { // Call base implementation ScreenBase.prototype._checkContext.call(this); this._testResults = this._testContext.get("results"); if (!this._testResults) { throw new Error("Test result not specified in current test context."); } }, deactivate: function () { this.trigger("pause-video-tutorial"); // Call base implementation ScreenBase.prototype.deactivate.apply(this, arguments); }, startPressed: function () { this.trigger("signal:start"); }, backPressed: function () { if (this._testContext.get("firstTest")) { throw new Error("Back button cannot be pressed for first test."); } this.trigger("out_signal:back"); }, nextPressed: function () { // Set state to skipped this._testResults.set("state", Constants.TestResultState.Skipped); this.trigger("out_signal:next"); } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'Testing/Views/ScreenViewBase', 'Utils/Dialog', 'text!Testing/Templates/SummaryScreen.html', 'text!Testing/Templates/SummaryScreenSubmitConfirmation.html', 'text!Testing/Templates/SummaryScreenCancelConfirmation.html', 'text!Testing/Templates/SummaryScreenRegisterConfirmation.html', 'Utils/AudioHelper' ], function (_, ScreenViewBase, Dialog, templateHtml, templateSubmitConfirmationHtml, templateCancelConfirmationHtml, templateRegisterConfirmationHtml, sound) { 'use strict'; return ScreenViewBase.extend({ template: _.template(templateHtml), templateSubmitConfirmation: _.template(templateSubmitConfirmationHtml), templateCancelConfirmation: _.template(templateCancelConfirmationHtml), templateRegisterConfirmation: _.template(templateRegisterConfirmationHtml), events: { "click .id-button-back": "_onBack", "click .id-button-submit": "_onSubmit", "click .id-button-cancel": "_onCancel", "click .id-button-register": "_onRegister", "click .id-valid .tick": "_onCheckedValid" }, render: function () { // Call base implementation ScreenViewBase.prototype.render.call(this); this.$notes = this.$(".id-notes"); this.$valid = this.$(".id-valid .tick"); sound.play('test-sound-submit'); }, // Overridden for initial UI update by model attributes _onActivated: function () { var that = this; // Call base implementation ScreenViewBase.prototype._onActivated.call(this); this._updateValid(this.model.get("sessionResults").get("valid")); if (!this.dialog) { this.dialog = new Dialog(); this.listenTo(this.dialog, { 'cancel-confirmation-confirmed': function () { that._updateModel(); that.model.cancelPressed(); }, 'submit-confirmed': function () { that._updateModel(); that.model.submitPressed(); } }); } }, _updateValid: function (valid) { this.$valid.hasClass("checked"); if (valid) { this.$valid.addClass("checked"); } else { this.$valid.removeClass("checked"); } }, _onBack: function () { this._updateModel(); this.model.backPressed(); sound.pause('test-sound-submit'); }, _onSubmit: function () { this.dialog.show('confirm', this.templateSubmitConfirmation(), 'submit'); }, _onCancel: function () { this.dialog.show('confirm', this.templateCancelConfirmation(), 'cancel-confirmation'); }, _onRegister: function () { this._updateModel(); this.model.registerPressed(); }, _onExit: function () { //todo: goto landing page }, _onCheckedValid: function () { this.$valid.toggleClass("checked"); }, _updateModel: function () { this.model.get("sessionResults").set({ "notes": this.$notes.val(), "valid": this.$valid.hasClass("checked") }); } }); }); <file_sep>define([ 'Testing/Views/TestEndsScreenViewBase', 'text!Testing/Templates/TestCanceledScreen.html' ], function (TestEndsScreenViewBase, templateSource) { 'use strict'; var TestCanceledScreenView = TestEndsScreenViewBase.extend({ template: _.template(templateSource) }); return TestCanceledScreenView; }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Views/Constants', 'Views/KeyboardTestReportPartView', 'Views/PatientInfoView', 'text!Templates/TrendReport.html', 'Utils/MathExtensions', 'moment', 'jQuery.ui', 'jQuery.flot', 'jQuery.flot.time', 'jQuery.flot.curvedLines', 'jQuery.flot.valuelabels', 'jQuery.flot.navigate' ], function (_, Backbone, ModelsConstants, ViewsConstants, KeyboardTestReportPartView, PatientInfoView, templateHtml, MathExtensions, moment) { 'use strict'; var K = 10000000; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), format: "mm/dd/yy", events: { "change .id-type": "_onTypeFilterChanged", "click .id-button-shared-back": "_onBack" }, initialize: function (options) { _.bindAll(this, "_fromDateChanged", "_toDateChanged"); this._readOnly = options.readOnly; this.listenTo(this.model, { "change:graphData": this.drawGraph, "change:toDateMin": this._setToDateFilterLimits, "change:fromDateMax": this._setFromDateFilterLimits }); }, render: function () { this.$el.html(this.template({ readOnly: this._readOnly })); this.$from = this.$(".id-from"); this.$to = this.$(".id-to"); this.$type = this.$(".id-type"); this._initializeDateFilters(); this._initializeTypeFilter(); this.$graphPlaceholder = this.$(".id-trend-graph"); return this; }, _initializeGraphLabels: function () { this._graphLabels = { yAxisLabel: "", pointLabelMask: "" }; switch (this.model.get("type")) { case ModelsConstants.TestSessionType.Keyboard: this._graphLabels.yAxisLabel = "keys/second"; this._graphLabels.pointLabelMask = "{0}<br/>{1} {2}"; break; case ModelsConstants.TestSessionType.TUG: this._graphLabels.yAxisLabel = "seconds"; this._graphLabels.pointLabelMask = "{0}<br/>{1} {2}"; break; case ModelsConstants.TestSessionType.PST: this._graphLabels.yAxisLabel = "JERK"; this._graphLabels.pointLabelMask = "{0}<br/>{2}: {1}"; break; default: break; } }, _initializeTypeFilter: function () { var typeValues = this.model.get("typeValues"); var $type = this.$type; $type.empty(); _.forEach(typeValues, function (item) { $type.append($('<option></option>').attr("value", item.value).text(item.text)); }); var currentType = this.model.get("type"); $type.val(currentType).attr("selected", true); }, _initializeDateFilters: function () { this.$from.datepicker({ changeMonth: true, numberOfMonths: 2, dateFormat: this.format, onClose: this._fromDateChanged }); this.$to.datepicker({ changeMonth: true, numberOfMonths: 2, dateFormat: this.format, onClose: this._toDateChanged }); var fromDate = this.model.get("fromDate"); var toDate = this.model.get("toDate"); this.$from.val($.datepicker.formatDate(this.format, fromDate)); this.$to.val($.datepicker.formatDate(this.format, toDate)); this._setFromDateFilterLimits(this.model, this.model.get("fromDateMax")); this._setToDateFilterLimits(this.model, this.model.get("toDateMin")); }, _setFromDateFilterLimits: function (model, fromDateMax) { if (fromDateMax) { this.$from.datepicker("option", "maxDate", fromDateMax); } }, _setToDateFilterLimits: function (model, toDateMin) { if (toDateMin) { this.$to.datepicker("option", "minDate", toDateMin); } }, _fromDateChanged: function (selectedDate) { var date = this.$from.datepicker("getDate"); this.model.set("fromDate", date); }, _toDateChanged: function (selectedDate) { var date = this.$to.datepicker("getDate"); date = moment(date).add(ModelsConstants.FullDayOffset).toDate(); this.model.set("toDate", date); }, _onTypeFilterChanged: function () { var selectedType = this.$type.val(); this.model.set("type", selectedType); }, _getDataSeries: function (compositeData) { return _.map(compositeData, function (item) { return [item.tick / K, item.score]; }); }, _tickGenerator: function (axis) { var ticks = [], max = axis.max * K, min = axis.min * K, range = max - min, delta = axis.delta * K, marginK = 0.4, margin = delta * marginK, lDelta, format, days = moment.duration(range).asDays(), hourDuration = moment.duration(1, "hour").asMilliseconds(), dayDuration = 24 * hourDuration, k, fk; if (days <= 2) { lDelta = delta * 0.5; k = dayDuration / lDelta; format = "H:mm"; if (k > 1) { fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else if (days <= 10) { lDelta = delta * 0.45; k = dayDuration / lDelta; format = "D"; if (k > 1) { lDelta = delta * 0.7; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else { lDelta = delta * 0.7; k = dayDuration / lDelta; format = "MMM D"; if (k > 1) { lDelta = delta * 0.85; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "MMM D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } var start = min + margin, i = 0, v, dv; do { v = start + i * axis.tickSize; dv = moment(v).format(format); ticks.push([v / K, dv]); ++i; } while (v <= max - margin * 2); return ticks; }, drawGraph: function () { var fromDate = this.model.get("fromDate"); var toDate = this.model.get("toDate"); var graphData = this.model.get("graphData"); this._initializeGraphLabels(); var dataSeries = []; var minScoreValues = []; _.forEach(graphData, function (compositeData, key) { var series = this._getDataSeries(compositeData); // Determine minimal value of score in data series minScoreValues.push(_.min(series, function (pair) { return pair[1]; })[1]); //dataSeries.push({ data:series, points:{ show:false }, lines:{ show:true, lineWidth:5 }, curvedLines:{ apply:true, fit:true, fitPointDist:0.000001 } }); dataSeries.push({ data: series, points: { show: true }, lines: { show: true } }); }, this); // Determine minimal value of score minScoreValues = _.without(minScoreValues, 0); var minValue = minScoreValues.length ? _.min(minScoreValues) : 0; this._valuePrecision = MathExtensions.getPrecision(minValue); var options = _.extend({}, ViewsConstants.flotOptions); options.xaxes[0] = _.extend({}, options.xaxes[0], { ticks: this._tickGenerator, min: fromDate.valueOf() / K, max: toDate.valueOf() / K }); var panMin = fromDate.valueOf() / K, panMax = toDate.valueOf() / K, panMargin = (panMax - panMin) * 0.1; options.xaxis = { panRange: [panMin - panMargin, panMax + panMargin] }; var $graphPlaceholder = this.$graphPlaceholder; var plot = $.plot($graphPlaceholder, dataSeries, options); $("<div class='axisLabel yaxisLabel'></div>") .text(this._graphLabels.yAxisLabel) .appendTo($graphPlaceholder); this._attachTooltipOnHover($graphPlaceholder); this._attachLabelRedrawing($graphPlaceholder, plot); }, _attachLabelRedrawing: function ($graphPlaceholder, plot) { var that = this; // Add labels redraw by pan/zoom events var redrawLabels = function () { $graphPlaceholder.hide(); $graphPlaceholder.find(".valueLabel, .valueLabelLight").each(function () { var value = $(this).text(); $(this).text(that._labelFormatter(value, that._valuePrecision + 1)); }); $graphPlaceholder.show(); var fromDate = new Date(plot.getXAxes()[0].min * K); var toDate = new Date(plot.getXAxes()[0].max * K); that.model.set({ fromDate: fromDate, toDate: toDate }, { suppressRedraw: true }); that.$from.val($.datepicker.formatDate(that.format, fromDate)); that.$to.val($.datepicker.formatDate(that.format, toDate)); }; $graphPlaceholder.on("plotpan plotzoom", redrawLabels); redrawLabels(); }, _labelFormatter: function (value, precesion) { return (+value).toFixed(precesion); }, _attachTooltipOnHover: function ($graphPlaceholder) { var that = this; var previousPoint = null; $graphPlaceholder.bind("plothover", function (event, pos, item) { if (item) { if (previousPoint !== item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0]; var y = item.datapoint[1]; var time = moment(x * K).format("L HH:mm:ss"); var tooltip = that._graphLabels.pointLabelMask.format(time, that._labelFormatter(y, that._valuePrecision + 4), that._graphLabels.yAxisLabel); that._showTooltip(item.pageX, item.pageY, tooltip); } } else { $("#tooltip").fadeOut(50); previousPoint = null; } }); }, _showTooltip: function (x, y, contents) { var $tooltip = $("<div id='tooltip' class='tooltip'>" + contents + "</div>").css({ display: "none", top: y + 15, left: x + 15 }).appendTo("body"); var tooltipWidth = $tooltip.outerWidth(), freeSpace = $(window).width() - x - 20; if (freeSpace < tooltipWidth) { $tooltip.css({ left: "auto", right: 0 }); } $tooltip.fadeIn(200); }, _onBack: function () { this.trigger('back-shared'); } }); }); <file_sep>/*global define:true */ define([ 'Testing/Views/ScreenViewBase', 'Utils/KeyboardListener', 'jQuery.ui' ], function (ScreenViewBase, KeyboardListener) { 'use strict'; return ScreenViewBase.extend({ events: { "click .id-button-stop": "_onStop" }, initialize: function () { ScreenViewBase.prototype.initialize.call(this); this.listenTo(this.model, { "change:percentsDone": this._updateProgressbar }); this._keyboardListener = new KeyboardListener(); this.listenTo(this._keyboardListener, "keyup", this._onKeyUp); this.listenTo(this._keyboardListener, "keydown", this._onKeyDown); }, _updateProgressbar: function (model, percentsDone) { this.$progressbar.progressbar({ value: percentsDone }); }, render: function () { ScreenViewBase.prototype.render.call(this); this.$progressbar = this.$(".progressbar"); return this; }, _unbindFromContext: function () { if (!this._testResults) { throw new Error("Assertion failed."); } this.listenTo(this._testResults); }, _onActivated: function () { ScreenViewBase.prototype._onActivated.call(this); // Initial UI update by model attributes this._updateProgressbar(this.model, this.model.get("percentsDone")); this._keyboardListener.start(); }, _onDeactivated: function () { this._keyboardListener.stop(); ScreenViewBase.prototype._onDeactivated.call(this); }, _onStop: function () { this.model.stopPressed(); }, _onKeyUp: function (keyName/*, keyPressed*/) { this.model.keyUp(keyName); }, _onKeyDown: function (keyName/*, keyPressed*/) { this.model.keyDown(keyName); } }); }); <file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'text!Templates/PrivacyPolicy.html', 'text!Templates/TermsOfService.html', 'text!Templates/EULA.html' ], function (Backbone, _, templatePP, templateToS, templateEULA) { 'use strict'; var PAGES = { "privacy-policy": templatePP, "terms-of-service": templateToS, "eula": templateEULA }; return Backbone.View.extend({ tagName: "div", className: "content-wrapper info-page", template: _.template(templatePP), events: { }, initialize: function (params) { this.template = _.template(PAGES[params.page]); }, remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); }, render: function () { this.$el.html(this.template()); return this; } }); }); <file_sep>/*global define: true */ define([ 'Models/Constants' ], function (Constants) { "use strict"; return { Validation: { EmptyEMail: { code: 2000, description: "Please enter e-mail" }, InvalidEMail: { code: 2001, description: "Email has invalid format" }, EMailIsNotUnique: { code: 2011, description: "Email is not unique" }, EmptyBirthday: { code: 2002, description: "Please enter valid birthday date" }, InvalidBirthday: { code: 2003, description: "Birthday date is not valid" }, EmptyPassword: { code: 2004, description: "Please enter the password" }, InvalidPasswordConfirmation: { code: 2005, description: "Password confirmation mismatch with password" }, EmptyFirstName: { code: 2006, description: "Please enter " + Constants.customLabel("first name") }, EmptySecondName: { code: 2007, description: "Please enter " + Constants.customLabel("last name") }, EmptyOldPassword: { code: 2008, description: "Please enter the old password or leave this field empty" }, EmptyNewPassword: { code: 2009, description: "Please enter the new password or leave this field empty" }, EmptyGenderSelected: { code: 2010, description: "Please select gender" }, EmptyConfirmationCode: { code: 2100, description: "Please enter confirmation code from sent e-mail." }, EmptyProjectName: { code: 9000, description: "Please enter " + Constants.customLabel("project name") }, EmptyFromDate: { code: 9001, description: "Please enter starting date" }, EmptyToDate: { code: 9002, description: "Please enter ending date" }, InvalidFromDate: { code: 9003, description: "Invalid date format" }, InvalidToDate: { code: 9004, description: "Invalid date format" }, NoProjectSelected: { code: 9005, description: "Please select at least one " + Constants.customLabel("project") }, EmptyCaptcha: { code: 9006, description: "Please enter captcha solution" }, MismatchedDates: { code: 9007, description: "Starting date cannot be greater than ending date" }, InvalidFutureDate: { code: 9008, description: "Please do not enter dates from future" } }, Confirm: { } }; }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Utils/SimpleRequest', 'text!Templates/CurrentUser.html' ], function (_, Backbone, ModelsConstants, SimpleRequest, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "username", template: _.template(templateHtml), events: { "change .id-username": "_onChangePatient" }, _analystMode: false, _patients: null, _viewedPatient: null, initialize: function () { this._checkAnalystMode(); this.listenTo(this.model, { "change:currentUser": this._currentUserSwitched, "patient-list-updated": this._updatePatients, "viewed-user-updated": this._updateViewedUser }); this._currentUserSwitched(this.model, this.model.get("currentUser")); }, _checkAnalystMode: function () { this._analystMode = this.model.isUserSignedIn() && this.model.currentUser().get("isAnalyst"); }, render: function () { if (this._patients) { this._patients.user.sort(function (a, b) { if (a.secondName > b.secondName) { return 1; } if (a.secondName < b.secondName) { return -1; } return 0; }); } this.$el.html(this.template({ model: this.model, analystMode: this._analystMode, patients: this._patients })); if (this.model.viewedUser) { this.$('select option[value="' + this.model.viewedUser + '"]').attr('selected', true); } else { this.$('select option:first').attr('selected', true); } return this; }, _currentUserSwitched: function (model, currentUser) { var previous = model.previous("currentUser"); if (previous) { this.stopListening(previous); } if (currentUser) { this.listenTo(currentUser, "change", this._currentUserChanged); this._currentUserChanged(currentUser); this.$el.show(); } else { this.$el.hide().find('>*').html(''); } }, _updatePatients: function (patients) { var that = this; if (!this._analystMode) { this._patients = null; return; } if (patients) { this._patients = {user: []}; _.each(patients, function (patient) { that._patients.user.push({ id: patient.get('id'), firstName: patient.get('firstName'), secondName: patient.get('secondName') }); }); this.render(); } else { SimpleRequest({ target: 'AccountManager', method: 'getPatients', options: { sessionToken: that.model.getSessionToken() }, model: this.model, success: function (data) { that._patients = data; that.render(); } }); } }, _updateViewedUser: function (id) { if (this._analystMode) { this.model.viewedUser = id; this.$('select option[value="' + id + '"]').attr('selected', true); } }, _currentUserChanged: function (currentUser) { this.model.viewedUser = null; //this.model.currentUser().get('id'); this._checkAnalystMode(); this._updatePatients(); this.render(); }, _onChangePatient: function () { var uId = parseInt(this.$('.id-username').val(), 10); if (uId === this.model.currentUser().get('id')) { uId = null; console.log('null', uId, this.model.currentUser().get('id')); } this.model.viewedUser = uId; this.model.trigger('viewed-patient-changed', parseInt(this.$('.id-username').val(), 10)); }, remove: function () { } }); }); <file_sep>/*global define:true */ define([ 'underscore', 'jQuery', 'backbone', 'Models/Constants', 'Utils/SimpleRequest', 'Utils/Dialog', 'text!Templates/CurrentProject.html', 'text!Templates/ModalProjectSelector.html' ], function (_, $, Backbone, ModelsConstants, SimpleRequest, Dialog, templateHtml, projectSelector) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "project-info-container", template: _.template(templateHtml), projectSelectorTemplate: _.template(projectSelector), events: { "click .id-change": "_projectSelection" }, initialize: function () { var accountManager = this.model, that = this; this.listenTo(accountManager, { 'project-selected': this._updateProjectInfo, 'project-changed-success': this._updateProjectInfo, 'sign-out': this._hideProjectInfo }); this.dialog = new Dialog(); this.listenTo(this.dialog, { 'switch-confirmed': function () { that.model.switchProject({ 'id': this._switchingId }); } }); }, render: function () { var currentUser = this.model.currentUser(); this.$el.html(this.template({ Constants: ModelsConstants, model: this.model.currentUser() })); this.$projectSelector = this.$('#project-selector-drop'); $('.project-info-container').show(); return this; }, _projectSelection: function () { var that = this, projects = _.filter(this.model.currentUser().get('project'), function (project) { return (project.status == ModelsConstants.ProjectStatus.Active) && (project.id != that.model.currentUser().get('projectId')); }); projects = _.sortBy(projects, function (project) { return project.name; }); this.$projectSelector.html(this.projectSelectorTemplate({ projects: projects })).dialog({ modal: true }); this.$projectSelector.find('.project').button().click(function (e) { e.preventDefault(); that.$projectSelector.dialog('destroy'); that._onChangeProject($(this).data('id')); return false; }); }, _onChangeProject: function (id) { var messages = { analyst: 'After change you will be redirected to Analyst room', patient: 'After change you will be redirected to your Test room' }, isAnalyst = this.model.currentUser().get('isAnalyst'); this._switchingId = id; this.dialog.show('confirm', messages[isAnalyst ? 'analyst' : 'patient'], 'switch'); }, _updateProjectInfo: function (projects, selectedProjectId) { projects = projects || this.model.currentUser().get('project'); selectedProjectId = selectedProjectId || this.model.currentUser().get('projectId'); var $container = $('.project-info-container'), selected = projects.length === 1 ? projects : _.where(projects, {id: selectedProjectId}), activeProject = _.where(projects, {status: ModelsConstants.ProjectStatus.Active}); selected = selected.length ? selected[0].name : ''; $container.show().find('span').text(selected); if (activeProject.length > 1) { $container.find('i').removeClass('hidden'); } else { $container.find('i').addClass('hidden'); } }, _hideProjectInfo: function () { $('.project-info-container').hide().find('span').text(''); } }); }); <file_sep><% if (selected.length > 1) { %> <%= selected.length %> test results <% } else { %> Test result for <%= moment(selected[0].get("creationDate")).format("L LT") %> <% } %> will be permanently deleted and cannot be recovered. <br><br> Are you sure?<file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Controllers/Constants', 'formatter' ], function (_, Backbone, Constants) { 'use strict'; return Backbone.Model.extend({ defaults: { "state": Constants.ControllerState.Deactivated }, initialize: function () { this._checkAttribute("applicationView"); var router = this._checkAttribute("router"); }, _checkAttribute: function (attribute) { var value = this.get(attribute); if (value == null) { throw new Error("A '{0}' attribute not set.".format(attribute)); } return value; }, routeOut: function (/*route, params*/) { if (this.get("state") == Constants.ControllerState.Activated) { this.set("state", Constants.ControllerState.Deactivated); if (this.deactivate) { this.deactivate(); } } }, routeIn: function (route, params) { switch (this.get("state")) { case Constants.ControllerState.Deactivated: if (this.activate) { this.set("state", Constants.ControllerState.Activated); this.activate.apply(this, params); } else { throw new Error("A 'activate' method should be overridden in child class."); } if (this.initializeMenu) { this.initializeMenu(); } break; case Constants.ControllerState.Sleep: if (false) { //todo fix resuming with data //seems to be completely broken at the moment, at least in the profile this._resume(); } else { // There is no resume command, then controller should be deactivated first this.set("state", Constants.ControllerState.Deactivated); if (this.deactivate) { this.deactivate(); } this.set("state", Constants.ControllerState.Activated); this.activate.apply(this, params); } if (this.initializeMenu) { this.initializeMenu(); } break; } }, _sleep: function (continueAction) { this.set("state", Constants.ControllerState.Sleep); this._continueAction = continueAction; if (this.view) { if (!this.view.hide) { throw new Error(("Controller '{0}': There is no 'hide' method in current view." + "But controller have to sleep. View should implement 'show'/'hide' method pair in this case.") .format(this.get("name"))); } this.view.hide(); } }, _resume: function () { this.set("state", Constants.ControllerState.Activated); if (this.view) { if (!this.view.show) { throw new Error(("Controller '{0}': There is no 'show' method in current view." + "But controller have to resume. View should implement 'show'/'hide' method pair in this case.") .format(this.get("name"))); } this.view.show(); } if (this._continueAction) { this._continueAction(); } }, _reset: function (options) { options = options || {}; _.defaults(options, { deleteModel: true }); this.stopListening(); if (options.deleteModel) { if (this.model) { if (this.model.dispose) { this.model.dispose(); } delete this.model; } // Remove models collection if it defined if (this.models) { _.forEach(this.models, function (model, key, collection) { if (model.dispose) { model.dispose(); } delete collection[key]; }); } } if (this.view) { this.view.remove(); delete this.view; } }, // Generate options for fetching some data from server. // NOTE: This method should generalize building of options object in all inherited controllers. // TODO: Refactor inherited controllers to use this method. _getFetchOptions: function (withAccountManager, success, wakeUp, controller) { var self = this; var options = { errorOther: function (model, xhr, options) { self.trigger("error", options.responseError); }, errorUnauthenticated: function () { self._sleep(wakeUp); // self.trigger("unauthenticated", self.testSessionId); //looping welcome controller }, success: controller ? function () { success.call(controller); } : success }; if (withAccountManager) { options.accountManager = this.get("accountManager"); } return options; } }); });<file_sep>/*global define: true */ define([ 'underscore', 'backbone', 'text!Templates/TestSessionCustomFieldsReportView.html' ], function (_, Backbone, templateHtml) { 'use strict'; return Backbone.View.extend({ template: _.template(templateHtml), events: { }, initialize: function (options) { }, render: function () { this.$el.html(this.template()); this.$contextContainer = this.$(".content-container"); var self = this; _.each(this.model.get('extension'), function (item) { if (item.value === '') { item.value = '-'; } //todo refactor this; there should be no self.$contextContainer.append('<div class="list-row"><div class="list-row-label">' + item.name + '</div> <div class="list-row-text">' + item.value + '</div></div>'); }); return this; } }); }); <file_sep>define([ 'underscore', 'backbone', 'Views/KeyboardTestReportPartView', 'text!Templates/KeyboardTestSessionReport.html', 'moment' ], function (_, Backbone, KeyboardTestReportPartView, templateHtml, moment) { 'use strict'; return Backbone.View.extend({ className: "content-container report", template: _.template(templateHtml), events: { }, _views: null, initialize: function (options) { this._userProfile = options.userProfile; this._showLinkToTestRoom = options.showLinkToTestRoom; this._views = []; }, render: function () { this.$el.html(this.template({ model: this.model, moment: moment })); this.$contextContainer = this.$(".content-text"); this.$noResults = this.$(".id-no-results"); var testResultsCollection = this.model.get("testResultsCollection"); if (_.size(testResultsCollection) > 0) { this.$noResults.hide(); testResultsCollection.forEach(function (testModel) { var view = new KeyboardTestReportPartView({ model: testModel }); this.$contextContainer.append(view.render().el); this._views.push(view); }, this); } else { this.$noResults.show(); } return this; }, drawGraph: function () { _.forEach(this._views, function (view) { view.drawGraph(); }); } }); }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'Models/Constants', 'text!Templates/ResetPasswordSuccess.html' ], function (_, Backbone, ModelsConstants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), events: { "click .id-link": "_onNavigateByLink" }, initialize: function () { }, render: function () { this.model.Constants = ModelsConstants; this.$el.html(this.template(this.model)); return this; }, _onNavigateByLink: function () { this.trigger("navigate-by-link"); // Prevent navigation by hyperlink return false; } }); }); <file_sep>/*global define:true */ define([ 'underscore', 'Controllers/WelcomeController', 'Controllers/TestingController', 'Controllers/TestRoomController', 'Controllers/SignUpController', 'Controllers/ConfirmController', 'Controllers/ResetPasswordController', 'Controllers/TestSessionReportController', 'Controllers/TrendReportController', 'Controllers/ProfileController', 'Controllers/UserListController', 'Controllers/AnalystRoomController', 'Controllers/CreatePatientController', 'Controllers/AddPatientController', 'Controllers/TestCustomFieldsController', 'Controllers/ProjectListController', 'Controllers/NotFoundController', 'Controllers/ExportController', 'Controllers/InfoController', 'Controllers/CreateProjectController', 'Controllers/ManageController', 'Controllers/AddUsersController', 'Controllers/SharePopupController' ], function (_, WelcomeController, TestingController, TestRoomController, SignUpController, ConfirmController, ResetPasswordController, TestSessionReportController, TrendReportController, ProfileController, UserListController, AnalystRoomController, CreatePatientController, AddPatientController, TestCustomFieldsController, ProjectListController, NotFoundController, ExportController, InfoController, CreateProjectController, ManageController, AddUsersController, SharePopupController) { 'use strict'; return { create: function (application, applicationView, accountManager, router) { var params = { router: router, applicationView: applicationView, accountManager: accountManager }; var testingController = new TestingController(params); var testRoomController = new TestRoomController(_.extend(params, { testingController: testingController, globalModels: application.globalModels })); var controllers = { welcomeController: new WelcomeController(params), testingController: testingController, testRoomController: testRoomController, signUpController: new SignUpController(params), confirmController: new ConfirmController(params), resetPasswordController: new ResetPasswordController(params), testSessionReportController: new TestSessionReportController(params), trendReportController: new TrendReportController(params), profileController: new ProfileController(_.extend(params, { homePage: application.homePage })), userListController: new UserListController(_.extend(params, { globalModels: application.globalModels })), analystRoomController: new AnalystRoomController(params), createPatientController: new CreatePatientController(params), addPatientController: new AddPatientController(params), testCustomFieldsController: new TestCustomFieldsController(params), projectListController: new ProjectListController(params), notFoundController: new NotFoundController(params), exportController: new ExportController(params), infoController: new InfoController(params), createProjectController: new CreateProjectController(params), manageController: new ManageController(params), addUsersController: new AddUsersController(params), SharePopupController: new SharePopupController(params) }; _.forEach(controllers, function (controller, name) { controller.set("name", name); }); return controllers; } }; }); <file_sep>/*global define: true */ define([ 'underscore', 'Testing/Views/ScreenViewBase', 'text!Testing/Templates/StartScreen.html', 'Utils/AudioHelper' ], function (_, ScreenViewBase, templateSource, sound) { 'use strict'; return ScreenViewBase.extend({ events: { "click .id-button-back": "_onBack", "click .id-button-start": "_onStart", "click .id-button-next": "_onNext" }, template: _.template(templateSource), initialize: function () { // Call base implementation ScreenViewBase.prototype.initialize.apply(this, arguments); this._accountManager = this.options.accountManager; this.listenTo(this.model, { "pause-video-tutorial": this._pauseVideoTutorial }); }, render: function () { ScreenViewBase.prototype.render.call(this); this.video = this.$(".id-video")[0]; if (this.video) { this.$(".video-loading").fadeIn(100); this.$(".id-video").on("canplay", _.bind(function () { this.$(".video-loading").fadeOut(100); }, this)); } // Hide Back button for first test if (this._testContext) { if (this._testContext.get("firstTest")) { this.$(".id-button-back").toggleClass("hidden"); } } return this; }, _pauseVideoTutorial: function () { if (this.video.pause) { this.video.pause(); } }, _onBack: function () { this.model.backPressed(); }, _onStart: function () { // Fixed bug introduced in 63f7cf3 // No need to update ticket in try mode var currentUser = this._accountManager.get('currentUser'); if (currentUser) { currentUser.fetch({ accountManager: this._accountManager, getOwn: true, success: _.bind(this.startTest, this) }); } else { this.startTest(); } }, _onNext: function () { this.model.nextPressed(); }, startTest: function () { $('#dummy-input').focus(); sound.play('test-sound-start'); this.model.startPressed(); } }); }); <file_sep>define(['backbone'], function (Backbone) { var TestContext = Backbone.Model.extend({ defaults: { results: null, properties: null, firstTest: false, lastTest: false } }); return TestContext; });<file_sep>/*global define:true */ define([ 'Testing/Models/TestSessionResults', 'Testing/Models/TestSession', 'Testing/Models/TestScreens/TestScreenInstances', 'Testing/Models/TestTransitionsInstance', 'Utils/ConsoleStub', 'formatter' ], function (TestSessionResults, TestSession, screens, testTransitions) { 'use strict'; // ================= TEST ================================== var testCase = function () { var testSessionResults = new TestSessionResults(); var testSession = new TestSession({ "sessionResults": testSessionResults }, null, testTransitions); testSessionResults.on("change", function () { // Find add test result var testResults; var testTag; for (testTag in testSessionResults.changed) { // get tag of added test results testResults = testSessionResults.get(testTag); break; } testResults.on("change:spentTime", function () { var spentTime = testResults.get("spentTime"); console.log("Test {4} TestResults['spentTime'] = {0} hours, {1} minutes, {2} seconds, {3} milliseconds".format( spentTime.hours, spentTime.minutes, spentTime.seconds, spentTime.milliseconds, testTag )); }); testResults.on("change:keyPresses", function () { var keyPresses = testResults.get("keyPresses"); console.log("Test {1} TestResults['keyPresses'] = {0}".format( keyPresses, testTag)); }); }); testSession.on("test:activated", function (stateItem) { console.log("event test:activated ------- {0} -----------".format(stateItem.stateName)); screens.startScreen.startPressed(); }); var keyPressEmulationTimer; screens.testingPQScreen.on("state:activated", function () { console.log("testingPQScreen event state:activate"); var switcher = false; keyPressEmulationTimer = setInterval(function () { var key = switcher ? 'p' : 'q'; switcher = !switcher; console.log("testingPQScreen pressed key {0}".format(key)); screens.testingPQScreen.keyDown(key); }, 600); }); screens.testingPQScreen.on("change:remainedPresses", function () { console.log("testingPQScreen remainedPresses={0}".format(screens.testingPQScreen.get("remainedPresses"))); }); screens.testingPQScreen.on("state:deactivated", function () { clearInterval(keyPressEmulationTimer); }); screens.testingNMScreen.on("state:activated", function () { console.log("testingNMScreen event state:activate"); var switcher = false; keyPressEmulationTimer = setInterval(function () { var key = switcher ? 'n' : 'm'; switcher = !switcher; console.log("testingNMScreen pressed key {0}".format(key)); screens.testingNMScreen.keyDown(key); }, 600); }); screens.testingNMScreen.on("change:remainedSeconds", function () { console.log("testingNMScreen remainedSeconds={0}".format(screens.testingNMScreen.get("remainedSeconds"))); }); screens.testingNMScreen.on("state:deactivated", function () { clearInterval(keyPressEmulationTimer); }); var oneRepeat = true; screens.testPassedScreen.on("state:activated", function () { if (oneRepeat) { oneRepeat = false; setTimeout(function () { console.log("---------- Press REPEAT ------------"); screens.testPassedScreen.repeatPressed(); screens.startScreen.startPressed(); }, 100); } else { setTimeout(function () { screens.testPassedScreen.nextPressed(); }, 100); } }); testSession.start(); }; return testCase; // ------------ RUN TEST --------------- //testCase(); //======================================================= }); <file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'text!Templates/NotFound.html' ], function (Backbone, _, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper not-found", template: _.template(templateHtml), events: { // "click .id-sign-in": "_onSignIn", }, initialize: function () { }, remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); }, render: function () { this.$el.html(this.template()); return this; } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'formatter' ], function (_) { 'use strict'; var ErrorConstants = { UserIsSignedOut: { code: 1100, description: "User is signed out from system." }, ServerErrorsCodes: { InvalidSessionToken: 716, NoPermission: 721, SessionTokenIsExpired: 717, UserIsNotActivated: 803, UserDoesNotExist: 801, DuplicateProjectName: 806, ProjectDisabled: 817, NoTestFound: 807, UserDisabled: 808, CannotAccessSharedData: 822, LastSiteAdmin: 821, TokenIsGenerated: 823 }, AjaxErrors: { Failed: { code: 1000, description: "Server request failed." }, Timeout: { code: 1001, description: "Server request time out." }, Abort: { code: 1002, description: "Request to server aborted." }, ParserError: { code: 1003, description: "Server request failed. Parser error." } }, UnknownRequestErrorCode: 1100 }; ErrorConstants.UnknownRequestError = function (textStatus) { return { code: ErrorConstants.UnknownRequestErrorCode, description: "Server request error. ({0}).".format(textStatus) }; }; ErrorConstants.AjaxErrorsByStatus = { "error": ErrorConstants.AjaxErrors.Failed, "timeout": ErrorConstants.AjaxErrors.Timeout, "abort": ErrorConstants.AjaxErrors.Abort, "parsererror": ErrorConstants.AjaxErrors.ParserError }; ErrorConstants.genericErrors = { 'invalidCredentials': 'Invalid credentials' }; ErrorConstants.GetServerError = function (code) { return _.find(ErrorConstants.ServerErrorsCodes, function (value) { return value.code == code; }); }; return ErrorConstants; }); <file_sep>/*global define: true */ define([ 'underscore', 'Testing/Models/Constants', 'Testing/Views/TestEndsScreenViewBase', 'Testing/Views/SpentTimeUIUpdater', 'Testing/Views/CorrectPressesUIUpdater', 'text!Testing/Templates/TestPassedScreen.html', 'Utils/AudioHelper' ], function (_, Constants, TestEndsScreenViewBase, SpentTimeUIUpdater, CorrectPressesUIUpdater, templateSource, sound) { 'use strict'; return TestEndsScreenViewBase.extend({ template: _.template(templateSource), initialize: function () { TestEndsScreenViewBase.prototype.initialize.call(this); this._spentTimeUpdater = new SpentTimeUIUpdater(); this._correctPressesUpdater = new CorrectPressesUIUpdater(); }, render: function () { TestEndsScreenViewBase.prototype.render.call(this); var _testType = this._testContext.get("properties").get("testType"); switch (_testType) { case Constants.TestType.NM: this._correctPressesUpdater.findControls(this.$el); this._correctPressesUpdater.updateControls(this._testResults.get("keyPresses")); break; case Constants.TestType.PQ: this._spentTimeUpdater.findControls(this.$el); this._spentTimeUpdater.updateControls(this._testResults.get("spentTime")); break; } } }); }); <file_sep>var fs = require('fs'), cli = require('cli'), wrench = require('wrench'), AdmZip = require('adm-zip'), requirejs = require('requirejs'), source = __dirname + '/../Web', tmpRoot = __dirname + '/../tmp', tmp = tmpRoot + '/Web', sourceLanding = __dirname + '/../Landing', tmpLanding = tmpRoot + '/Landing', buildDir = __dirname + '/../build', version, files, i, j, options = cli.parse({ debug: ['d', 'Build debug version'], release: ['r', 'Build release version'], project: ['c', 'Chosen project', 'string', ''], suffix: ['s', 'Suffix for war file names', 'string', ''], noversion: ['n', 'Don\'t include version info in js, css and html files'] }), config = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf8')), target; cli.main(function (args, options) { "use strict"; if (fs.existsSync(tmpRoot)) { wrench.rmdirSyncRecursive(tmpRoot); } fs.mkdirSync(tmpRoot); if (!fs.existsSync(buildDir)) { fs.mkdirSync(buildDir); } getVersion(); if (options.debug) { wrench.copyDirSyncRecursive(source, tmp); if (fs.exists(tmp + '/.idea')) { wrench.rmdirSyncRecursive(tmp + '/.idea'); } if (!options.noversion) { setVersion(tmp); } packageFiles(tmp, 'kineticsweb'); buildLandingPage(); } if (options.release) { fs.mkdirSync(tmp); requirejs.optimize(config, function (buildResponse) { //cleanup //todo: a more graceful way of excluding files if (fs.exists(tmp + '/.idea')) { wrench.rmdirSyncRecursive(tmp + '/.idea'); } files = fs.readdirSync(tmp + '/js'); process.chdir(tmp + '/js'); for (i = 0; i < files.length; i++) { if (fs.statSync(files[i]).isDirectory()) { wrench.rmdirSyncRecursive(files[i]); } else { if (files[i] !== 'main.js') { fs.unlinkSync(files[i]); } } } files = fs.readdirSync(tmp + '/assets'); process.chdir(tmp + '/assets'); for (i = 0; i < files.length; i++) { if (fs.statSync(files[i]).isFile()) { if (files[i] !== 'require.min.js') { fs.unlinkSync(files[i]); } } } if (!options.noversion) { setVersion(tmp); } packageFiles(tmp, 'kineticsweb'); buildLandingPage(); }, function (err) { console.log(err); }); } function buildLandingPage() { //take care of landing page wrench.copyDirSyncRecursive(sourceLanding, tmpLanding); if (fs.exists(tmpLanding + '/.idea')) { wrench.rmdirSyncRecursive(tmpLanding + '/.idea'); } if (!options.noversion) { setVersion(tmpLanding); } packageFiles(tmpLanding, 'ROOT'); } function getVersion() { var oldVersion, now = (new Date()), month = now.getMonth() + 1, day = now.getDate(), year = now.getFullYear(), iteration = 1; if (fs.existsSync(__dirname + '/.oldversion')) { oldVersion = fs.readFileSync(__dirname + '/.oldversion', {encoding: 'utf8'}); oldVersion = oldVersion.split('-'); if (oldVersion && oldVersion.length === 4) { if (parseInt(oldVersion[0], 10) === month && parseInt(oldVersion[1], 10) === day && parseInt(oldVersion[2], 10) === year) { iteration = parseInt(oldVersion[3], 10) + 1; } } } version = month + '-' + day + '-' + year + '-' + iteration; fs.writeFileSync(__dirname + '/.oldversion', version, {encoding: 'utf8'}); version += (options.release ? ' release ' : ' debug ') + options.project; } function setVersion(dir) { var files = wrench.readdirSyncRecursive(dir); for (i = 0; i < files.length; i++) { switch (true) { case /\.(?:css|js)$/.test(files[i]): fs.appendFileSync(dir + '/' + files[i], '\r\n/* ' + version + ' */'); break; case (/\.html$/.test(files[i]) && !options.release): fs.appendFileSync(dir + '/' + files[i], '\r\n<!-- ' + version + ' -->'); break; } } } function packageFiles(dir, name) { var zip = new AdmZip(); if (!fs.existsSync(buildDir + '/' + version)) { fs.mkdirSync(buildDir + '/' + version); } process.chdir(dir); zip.addLocalFolder('.'); zip.writeZip(buildDir + '/' + version + '/' + name + (options.suffix ? '-' + options.suffix : '') + '.war'); } console.log('Version: ' + version); }); <file_sep>define([ 'backbone', 'Utils/TimerManager' ], function (Backbone, TimerManager) { 'use strict'; var CountdownTimer = Backbone.Model.extend({ defaults: { remainedSeconds: null }, initialize: function () { var remainedSeconds = this.get("remainedSeconds"); if (!remainedSeconds && remainedSeconds <= 0) { throw new Error("Invalid 'remainedSeconds' value."); } this._timer = new TimerManager(this._tick.bind(this), 1000); }, start: function () { this._timer.startTimer(); }, stop: function () { this._timer.stopTimer(); this.trigger("complete"); }, _tick: function () { var remainedSeconds = this.get("remainedSeconds"); this.set("remainedSeconds", --remainedSeconds); if (remainedSeconds <= 0) this.stop(); } }); return CountdownTimer; }); <file_sep>define([ 'jQuery', 'Controllers/Constants', 'Controllers/ControllerBase', 'Models/Constants', 'Models/ConfirmModel', 'Models/CountdownTimer', 'Views/Constants', 'Views/ConfirmView', 'Views/ConfirmSuccessView', 'formatter', 'jQuery.base64' ], function ($, Constants, ControllerBase, ModelsConstants, ConfirmModel, CountdownTimer, ViewsConstants, ConfirmView, ConfirmSuccessView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); }, parseParams: function (params) { var result = {}; try { if (params.length > 0) { result.email = $.base64.decode(params[0]); } if (params.length > 1) { result.code = $.base64.decode(params[1]); } if (params.length > 2) { result.sharingToken = $.base64.decode(params[2]); } } catch (e) { } return result; }, activate: function (params) { this.sharingToken = params.sharingToken; if (!params.email) { this.trigger("invalid-parameters"); return; } var accountManager = this.get("accountManager"); this.model = new ConfirmModel({ confirmationCode: params.code, email: params.email, accountManager: accountManager, project: params.project, token: this.sharingToken }); this.view = new ConfirmView({ model: this.model }); // Start listening control events this.listenTo(accountManager, { "email-confirmed": function (email, token) { this.email = email; this._showSuccessView(); } }); // Initialize menu var applicationView = this.get("applicationView"); applicationView.header.showMenu(ViewsConstants.HeaderMenu.Authorization); // Show view applicationView.showView(this.view); // If code specified in parameters and is valid then perform confirmation if (this.model.isReadyToConfirm()) { this.model.confirm(); } }, deactivate: function () { this._reset(); }, _showSuccessView: function () { this._reset(); this.model = new CountdownTimer({ remainedSeconds: Constants.RedirectTimeout }); this.view = new ConfirmSuccessView({ model: this.model }); this.listenTo(this.model, "complete", this._timeoutComplete); // Show view var applicationView = this.get("applicationView"); applicationView.showView(this.view); this.model.start(); }, _timeoutComplete: function () { this.trigger("email-confirmed", this.email, this.sharingToken); } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'jQuery', 'moment', 'backbone', 'DataLayer/Constants', 'text!Templates/TestRoomResultRow.html' ], function (_, $, moment, Backbone, Constants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "result-row", template: _.template(templateHtml), events: { "click .test-checkbox": "_onSelected", "click .id-button-detail": "_onClickDetail", "click .id-button-share": "_onClickShare", "click .test-valid": "_onClickValid" }, _adminMode: false, initialize: function (options) { this._adminMode = options.adminMode; this._ownRoom = options.ownRoom; this._readOnly = options.readOnly; this.listenTo(this.model, "change:isValid", this._updateValid); }, adminMode: function () { return this._adminMode; }, // Get/Set row selection flag selected: function (value) { if (value === undefined) { return this.$selectCheckBox.hasClass("checked"); } else { if (value) { this.$selectCheckBox.addClass("checked"); } else { this.$selectCheckBox.removeClass("checked"); } } }, render: function () { this.$el.html(this.template({ model: this.model, moment: moment, ownRoom: this._ownRoom, readOnly: this._readOnly, isAvanir: Constants.branding === "Avanir" })); this.$selectCheckBox = this.$(".test-checkbox .tick"); var $valid = this.$(".id-valid"); if (this.adminMode()) { $valid.removeClass("test-valid-ro"); } else { $valid.removeClass("test-valid"); } this.$validTick = $valid.find(".tick"); if (this.model.get("isValid")) { this.$validTick.addClass("checked"); } return this; }, _onSelected: function () { this.$selectCheckBox.toggleClass('checked'); }, _onClickDetail: function () { this.model.trigger("detail", this.model); }, _onClickShare: function () { this.model.trigger("shareTest", this.model.get('id')); }, _onClickValid: function () { var isValid = this.model.get("isValid"); this.model.set("isValid", !isValid); }, _updateValid: function (model, isValid) { if (isValid) { this.$validTick.addClass("checked"); } else { this.$validTick.removeClass("checked"); } } }); });<file_sep>define(['underscore'], function (_) { return { parse: function (rawData) { if (rawData != null && !_.isString(rawData)) { throw new Error("Invalid argument exception."); } if (rawData == null) return null; var splitData = rawData.split(";"); var parsedData = { AREA: splitData[0], RMS: splitData.length > 1 ? splitData[1] : null }; return parsedData; } }; });<file_sep>/*global define:true */ define(['jQuery', 'underscore', 'backbone', 'jQuery.hotkeys'], function ($, _, Backbone) { "use strict"; function getKeyName(keyCode) { return jQuery.hotkeys.specialKeys[keyCode] || String.fromCharCode(keyCode).toLowerCase(); } var KeyboardListener = function () { this.keyPressed = []; this.keysToIgnore = ["f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12"]; _.bindAll(this, "_onKeyDown", "_onKeyUp"); }; _.extend(KeyboardListener.prototype, Backbone.Events, { dummyInput: $('#dummy-input'), start: function () { // Clear cached keys this.keyPressed.splice(0, this.keyPressed.length); $(document).off(); $(document).on("keydown", this._onKeyDown); $(document).on("keyup", this._onKeyUp); $(document).on("click", function () { $('#dummy-input').focus(); }); }, stop: function () { // Clear cached keys this.keyPressed.splice(0, this.keyPressed.length); $(document).off(); }, _onKeyDown: function (event) { var keyName = getKeyName(event.which), fallback = $('#dummy-input'); if (_.indexOf(this.keysToIgnore, keyName) < 0) { if (event.which > 0) { event.preventDefault();//prevent test flow disruption if one of the control keys is accidentally clicked } else { keyName = fallback.val().length ? fallback.val()[fallback.val().length - 1] : -1; $('.timer-seconds').prepend(keyName + ' keyDown!!<br>'); } var isRepeat = false, i; for (i = 0; i < this.keyPressed.length; i++) { if (this.keyPressed[i] === keyName) { isRepeat = true; break; } } if (!isRepeat) { this.keyPressed.push(keyName); this.trigger("keydown", keyName, this.keyPressed); } } //return true; }, _onKeyUp: function (event) { var keyName = getKeyName(event.which), fallback = $('#dummy-input'); if (_.indexOf(this.keysToIgnore, keyName) < 0) { if (event.which > 0) { event.preventDefault();//prevent test flow disruption if one of the control keys is accidentally clicked } else { keyName = fallback.val().length ? fallback.val()[fallback.val().length - 1] : -1; fallback.val(''); $('.timer-seconds').prepend(keyName + ' keyUp!!<br>'); } for (var i = 0; i < this.keyPressed.length; i++) { if (this.keyPressed[i] === keyName) { this.keyPressed.splice(i, 1); this.trigger("keyup", keyName, this.keyPressed); break; } } } } }); return KeyboardListener; });<file_sep>/*global define:true */ define({ serverUrl: "https://stage.kineticsfoundation.org/kinetics/rest/mainpoint/execute", branding: '', analytics: false, analyticsId: 'UA-41772384-1' });<file_sep>/*global define: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/Constants', 'DataLayer/ErrorConstants', 'Views/Constants', 'Views/SiteAdminCreateProjectView', 'Models/Project', 'formatter' ], function (_, Constants, ControllerBase, DataConstants, ErrorConstants, ViewsConstants, SiteAdminCreateProjectView, Project) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); this._applicationView = this._checkAttribute("applicationView"); this._globalModels = this._checkAttribute("globalModels"); }, activate: function (params) { var that = this; this.view = new SiteAdminCreateProjectView({ model: new Project() }); // Start listening control events this.listenTo(this.view, { "create-project": this._onCreateProject, "cancel": function () { that.trigger('cancelCreate'); } }); // Show view this.get("applicationView").showView(this.view); this._applicationView.header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin, 'projects'); }, _onCreateProject: function (model) { var that = this; model.attributes.sessionToken = this.get("accountManager").getSessionToken(); model.save({}, { wait: true, accountManager: this.get("accountManager"), error: function (model, xhr, options) { model.trigger("error", options.responseError); }, success: function (model, xhr, options) { that.trigger("project-creation-success", xhr.response['function'].data.id); } }); }, _onError: function (error, options) { }, deactivate: function () { this._reset(); } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'backbone', 'recaptcha', 'Views/Constants', 'Models/Constants', 'Models/ErrorConstants', 'text!Templates/SignUp.html', 'text!Templates/CreateUser.html', 'text!Templates/CreateSharedUser.html', 'jQuery.placeholder', 'formatter' ], function ($, _, Backbone, Recaptcha, Constants, ModelsConstants, ErrorConstants, signUpHtml, createUserHtml, createSharedUserHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", signUpTemplate: _.template(signUpHtml), createUserTemplate: _.template(createUserHtml), createSharedUserTemplate: _.template(createSharedUserHtml), events: { "click .id-sign-up": "_signUp", "click .id-cancel": "_cancel", "change .id-role": "_changeUserRole", "change .select-all": "_toggleProjectSelection", "change input[name='project']": "_updateToggleCheckbox", "keypress #password, #password-confirmation": "_validatePassword" }, initialize: function () { this.listenTo(this.model.profile, { "invalid": function (model, errors) { this._updateErrorMessage(errors); }, "error": function (error) { if (error.code === 809) { Recaptcha.reload(); } this._updateErrorMessage([ error ]); } }); }, render: function (params) { switch (this.model.mode) { case 'sa-create-user': this.$el.html(this.createUserTemplate({ Constants: ModelsConstants, profile: this.model.profile, projects: this.model.projects, roles: ModelsConstants.UserRole, showProjectSelect: this.model.projects.length > 1 })); break; case 'invite': this.$el.html(this.signUpTemplate({ Constants: ModelsConstants, profile: this.model.profile, projects: this.model.projects, showProjectSelect: false })); break; case 'shared': this.$el.html(this.createSharedUserTemplate({ Constants: ModelsConstants, profile: this.model.profile })); break; default: this.$el.html(this.signUpTemplate({ Constants: ModelsConstants, profile: this.model.profile, projects: this.model.projects, showProjectSelect: this.model.projects.length > 1 })); } this.$firstName = this.$(".id-first-name"); this.$secondName = this.$(".id-second-name"); this.$birthday = this.$(".id-birthday"); this.$genderRadios = this.$("input:radio[name=gender]"); this.$email = this.$(".id-email"); this.$passwordOld = this.$(".id-password"); this.$passwordConfirmation = this.$(".id-password-confirmation"); this.$errorEmail = this.$(".id-error-email"); this.$project = this.$('input[name="project"]'); this.selectedProjects = function () { var val = []; this.$project.each(function () { var $this = $(this); if ($this.is(':checked')) { val.push($this.val()); } }); return val; }; this.$errorProject = this.$(".id-error-project"); this.$role = this.$('.id-role'); this.$errorBirthday = this.$(".id-error-birthday"); this.$errorGender = this.$(".id-error-gender"); this.$errorPassword = this.$(".id-error-password"); this.$errorPasswordConfirmation = this.$(".id-error-password-confirmation"); this.$errorGeneral = this.$(".id-error-general"); this.$errorFirstName = this.$(".id-error-first-name"); this.$errorSecondName = this.$(".id-error-second-name"); this.$errorCaptcha = this.$(".id-error-captcha"); this.$capsLockWarning = this.$(".id-warning-message"); this.$("input, textarea").placeholder(); this._hideErrorsAndStatuses(); this.$birthday.datepicker({ minDate: '-150y', maxDate: "-1y", yearRange: "-150:-1", dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true }); this._setUserProjects(-1); var that = this; //todo:refacor this to change render->afterRender events setTimeout(function () { that.$firstName.focus(); }); return this; }, showCaptcha: function () { Recaptcha.create(Constants.ReCaptchaPublicKey, "reCaptcha", { theme: "clean" }); //TODO: refactor this setTimeout(function () { this.$("#recaptcha_reload_btn, #recaptcha_switch_audio_btn, #recaptcha_whatsthis_btn").attr("tabindex", -1); }, 500); }, // Overload remove() method to reset reCaptcha inner state. remove: function () { Recaptcha.destroy(); // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); }, _hideErrorsAndStatuses: function () { this.$('.sign-row-error').hide().removeAttr('title'); this.$('input, select').removeClass('errored'); }, _signUp: function () { this._hideErrorsAndStatuses(); var values = { firstName: $.trim(this.$firstName.val()), secondName: $.trim(this.$secondName.val()), projectId: this.model.profile.get('projectId') || this.model.projects && (this.model.projects.length > 1 ? this.selectedProjects() || [] : [this.model.projects[0].get('id')]), birthdayFormatted: $.trim(this.$birthday.val()), email: $.trim(this.$email.val()) || this.model.profile.get('email'), gender: this.$genderRadios.filter(":checked").val(), password: this.$<PASSWORD>.val(), role: this.$role.val(), passwordConfirmation: this.$passwordConfirmation.val(), recaptchaChallenge: Recaptcha && Recaptcha.get_challenge(), recaptchaResponse: Recaptcha && Recaptcha.get_response() }; switch (this.model.mode) { case 'sa-create-user': if (this.model.profile.set(values, { validate: true, passwordRequired: false, birthdayRequired: false, genderRequired: false })) { this.trigger("sign-up", this.model.profile); } break; case 'invite': if (this.model.profile.set(values, { validate: true, passwordRequired: true, projectNotRequired: true, birthdayRequired: true, genderRequired: true })) { this.trigger("sign-up", this.model.profile); } break; case 'shared': if (this.model.profile.set(values, { validate: true, passwordRequired: true, projectNotRequired: true, birthdayRequired: true, genderRequired: true })) { this.trigger("sign-up", this.model.profile); } break; default: if (this.model.profile.set(values, { validate: true, passwordRequired: true, birthdayRequired: true, genderRequired: true })) { this.trigger("sign-up", this.model.profile); } } }, _cancel: function () { this.trigger('cancel-creation'); }, _updateErrorMessage: function (errors) { _.forEach(errors, function (error) { var errored = { $container: null }; switch (error.code) { case ErrorConstants.Validation.EmptyFirstName.code: errored.$container = this.$errorFirstName; break; case ErrorConstants.Validation.EmptySecondName.code: errored.$container = this.$errorSecondName; break; case ErrorConstants.Validation.EmptyEMail.code: case ErrorConstants.Validation.InvalidEMail.code: errored.$container = this.$errorEmail; break; case ErrorConstants.Validation.EmptyBirthday.code: case ErrorConstants.Validation.InvalidBirthday.code: errored.$container = this.$errorBirthday; break; case ErrorConstants.Validation.EmptyGenderSelected: case ErrorConstants.Validation.EmptyGenderSelected.code: errored.$container = this.$errorGender; break; case ErrorConstants.Validation.EmptyPassword.code: errored.$container = this.$errorPassword; break; case ErrorConstants.Validation.InvalidPasswordConfirmation.code: errored.$container = this.$errorPasswordConfirmation; break; case ErrorConstants.Validation.NoProjectSelected.code: errored.$container = this.$errorProject; break; case ErrorConstants.Validation.EmptyCaptcha.code: errored.$container = this.$errorCaptcha.show(); break; default: errored.$container = this.$errorGeneral; break; } errored.$container.show().html(error.description) .attr('title', error.description); errored.$input = errored.$input || errored.$container.closest('.sign-row').find('input[type!=radio], select'); errored.$input.addClass('errored'); }, this); }, _validatePassword: function (e) { var keyCode = e.which; if (keyCode >= 65 && keyCode <= 90) { this._toggleCapsLockWarning(!e.shiftKey); } else if (keyCode >= 97 && keyCode <= 122) { this._toggleCapsLockWarning(e.shiftKey); } }, _toggleCapsLockWarning: function (showWarning) { if (showWarning) { this._capsLock = true; this.$capsLockWarning.show(); } else { this._capsLock = false; this.$capsLockWarning.hide(); } }, _changeUserRole: function () { this._setUserProjects(this.$role.val().toUpperCase() === ModelsConstants.UserRole.SiteAdmin.toUpperCase()); }, _setUserProjects: function (params) { this.$project.removeAttr('disabled').removeClass('semitransparent'); switch (params - 0) { case 1: this.$project.attr('disabled', 'disabled').addClass('semitransparent') .find('option').each(function () { $(this).removeAttr('selected'); }); var $row = this.$project.closest('.sign-row'); $row.find('select').removeClass('errored'); $row.find('.sign-row-error').hide(); break; case -1: this.$role.val(ModelsConstants.UserRole.Patient.toUpperCase()); this.$project.find('option').each(function () { $(this).removeAttr('selected'); }); break; default: break; } }, _toggleProjectSelection: function (e) { var $this = $(e.target); if ($this.is(':checked')) { this.$project.attr('checked', true); } else { this.$project.attr('checked', false); } }, _updateToggleCheckbox: function () { $('.select-all').attr('checked', $('input[name="project"]:checked').length === $('input[name="project"]').length); } }); }); <file_sep>/*global define:true */ define([ 'Controllers/Constants', 'Controllers/ControllerBase', 'Models/ExtensionsCollection', 'Views/Constants', 'Views/TestCustomFieldsView' ], function (Constants, ControllerBase, ExtensionsCollection, ViewsConstants, TestCustomFieldsView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); }, activate: function () { this._loadTestCustomFields(); }, // Initialize menu initializeMenu: function () { this.get("applicationView").header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin, 'customFields'); }, deactivate: function () { this._reset(); }, _showView: function () { this.view = new TestCustomFieldsView({ model: this.customFieldsCollection, accountManager: this.get('accountManager') }); this.get("applicationView").showView(this.view); }, _loadTestCustomFields: function () { this.customFieldsCollection = new ExtensionsCollection(); var self = this; var options = this._getFetchOptions(true, function () { self._showView(); }, this._loadTestCustomFields); this.customFieldsCollection.fetch(options); } }); }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'moment', 'text!Templates/UserList.html', 'text!Templates/UserListBlockConfirmation.html', 'text!Templates/UserProjectManage.html', 'text!Templates/ManageProjects.html', 'Models/Constants', 'Models/UserProfileCollection', 'Views/UserListRowView', 'Utils/Dialog' ], function (_, Backbone, moment, templateHtml, blockConfirmationHtml, UserProjectManageHtml, manageProjectsHtml, ModelsConstants, UserProfileCollection, UserListRowView, Dialog) { 'use strict'; var SuccessStyle = "sign-row-success"; var ErrorStyle = "sign-row-error"; return Backbone.View.extend({ tagName: "div", className: "content-wrapper user-list", template: _.template(templateHtml), templateConfirmation: _.template(blockConfirmationHtml), templateManageProjects: _.template(manageProjectsHtml), projectManage: null, currentModel: null, sortType: 'name', sortOrder: 'asc', events: { "click #button-find": "_onSearch", "keypress #id-search-text": "_submitSearchOnEnter", "click #button-show-all": "_onShowAll", "click .all-check": "_onSelectAll", "click .id-button-block": function () { this._onBlockSelected(true); }, "click .id-button-unblock": function () { this._onBlockSelected(false); }, "click .id-button-test-custom-fields": "_onClickTestCustomFields", "click .id-button-create-user": function () { if (this._siteAdminMode) { this.trigger('create-user'); } }, 'click .id-reset': '_resetAssignments', 'click .id-save-changes': '_onSaveAssignments', "click .project-add": "_projectAdd", "click .project-remove": "_projectRemove", "click .manageProjectsContainer .id-save-project": "_onSaveProject", "click .manageProjectsContainer .id-cancel-project": "_onCancelProject", "click .result-table th i": "_changeSortOrder" }, initialize: function (options) { var that = this; if (!this.model && this.model instanceof UserProfileCollection) { throw new Error("Model not set or wrong type."); } this.listenTo(this.model, { "reset": this._onReset, "clickProject": this._onClickProject, "saveProjectSuccess": this._setSaveStatus, "error": this._setSaveStatus }); this.listenTo(this, { 'assignment-changed': function () { this.$('.save-or-reset').slideDown(); }, 'assignments-saved': function () { this.$('.save-or-reset').slideUp(); } }); this._manage = options.manage; this._newProject = options.newProject; this._searchText = options.searchText; this._siteAdminMode = options.siteAdminMode; this.projectsList = options.projectsList; this._rowViews = {}; this.dialog = new Dialog(); this.listenTo(this.dialog, { 'block-selected-confirmed': function () { that.trigger("block", that._getSelectedModels(), that._block); that._selectAll(false); }, 'save-project-confirmed': function () { that._hideSaveStatus(); that.model.trigger('change-project', that.currentModel, that.projectsListNew); } }); }, _initializeRowViews: function () { var that = this; // sort user's projects if (this.sortType === "project") { this.model.each(function (m) { var projects = m.get("project"); projects.sort(function (a, b) { var validator = that.sortOrder === "asc" ? a.name.toLowerCase() > b.name.toLowerCase() : a.name.toLowerCase() < b.name.toLowerCase(); return validator ? 1 : -1; }); }, this); } this.model.models.sort(function (a, b) { switch (true) { case (that.sortType === 'name' && that.sortOrder === 'asc'): return a.get('firstName') + a.get('secondName') > b.get('firstName') + b.get('secondName') ? 1 : -1; case (that.sortType === 'name' && that.sortOrder === 'desc'): return a.get('firstName') + a.get('secondName') < b.get('firstName') + b.get('secondName') ? 1 : -1; case (that.sortType === 'email' && that.sortOrder === 'asc'): return (a.get('email') || '') > (b.get('email') || '') ? 1 : -1; case (that.sortType === 'email' && that.sortOrder === 'desc'): return (a.get('email') || '') < (b.get('email') || '') ? 1 : -1; case (that.sortType === 'status' && that.sortOrder === 'asc'): return a.get('status') > b.get('status') ? 1 : -1; case (that.sortType === 'status' && that.sortOrder === 'desc'): return a.get('status') < b.get('status') ? 1 : -1; case (that.sortType === 'role' && that.sortOrder === 'asc'): return (_.isArray(a.get('roles')) ? a.get('roles')[0].name : '') > (_.isArray(b.get('roles')) ? b.get('roles')[0].name : '') ? 1 : -1; case (that.sortType === 'role' && that.sortOrder === 'desc'): return (_.isArray(a.get('roles')) ? a.get('roles')[0].name : '') < (_.isArray(b.get('roles')) ? b.get('roles')[0].name : '') ? 1 : -1; case (that.sortType === 'project' && that.sortOrder === 'asc'): return _.pluck(a.get('project'), 'name').join('') > _.pluck(b.get('project'), 'name').join('') ? 1 : -1; case (that.sortType === 'project' && that.sortOrder === 'desc'): return _.pluck(a.get('project'), 'name').join('') < _.pluck(b.get('project'), 'name').join('') ? 1 : -1; } }); _.forEach(this.model.models, function (rowModel) { this._rowViews[rowModel.cid] = new UserListRowView({ model: rowModel, siteAdminMode: this._siteAdminMode, manage: this._manage, showProjects: this.projectsList.models.length > 1 }); }, this); }, _onReset: function () { this._removeAllRowsViews(); this._initializeRowViews(); this._fillRows(); }, _onSelectAll: function () { this._selectAll(!this.$checkAll.hasClass("checked")); }, _selectAll: function (selectAll) { if (selectAll) { this.$checkAll.addClass("checked"); } else { this.$checkAll.removeClass("checked"); } _.each(this._rowViews, function (rowView) { rowView.selected(selectAll); }); }, render: function () { var view = null; if (this._manage) { view = this.templateManageProjects({ model: this.model, Constants: ModelsConstants, siteAdminMode: this._siteAdminMode, newProject: this._newProject }); } else { view = this.template({ model: this.model, Constants: ModelsConstants, siteAdminMode: this._siteAdminMode, showProjects: this.projectsList.models.length > 1 }); } this.$el.html(view); this.$checkAll = this.$(".all-check .tick"); this.$resultTable = this.$(".result-table"); this.$headerRow = this.$(".result-header-row"); this.$noResultsRow = this.$(".id-no-results"); this.$searchText = this.$(".id-search-text"); this.$searchText.val(this._searchText); var that = this; //todo:refacor this to change render->afterRender events setTimeout(function () { that.$searchText.focus(); }); return this; }, _fillRows: function () { _.each(this.model.models, function (rowModel) { var rowView = this._rowViews[rowModel.cid]; this.$resultTable.append(rowView.render().el); }, this); this._updateNoResultRow(); }, _updateNoResultRow: function () { if (this.model.length > 0) { this.$noResultsRow.hide(); } else { this.$noResultsRow.show(); } }, // Remove view from DOM remove: function () { // Destroy row views this._removeAllRowsViews(); // Call base implementation Backbone.View.prototype.remove.call(this); }, // Destroy all row view _removeAllRowsViews: function () { _.each(this._rowViews, function (rowView, key, collection) { rowView.remove(); delete collection[key]; }); }, _getSelectedModels: function () { var selected = []; _.each(this._rowViews, function (rowView) { if (rowView.selected()) { selected.push(rowView.model); } }); return selected; }, _onBlockSelected: function (block) { var selectedModels = this._getSelectedModels(); this._block = block; if (selectedModels.length > 0) { this.dialog.show('confirm', this.templateConfirmation({ moment: moment, selected: selectedModels, block: block }), 'block-selected'); } }, _onSearch: function () { this.trigger("search", this.$searchText.val()); this.$checkAll.removeClass("checked"); return false; }, _submitSearchOnEnter: function (e) { if (e.keyCode === 13) { this._onSearch(); } }, _onShowAll: function () { this.$searchText.val(""); this._onSearch(); }, hide: function () { this.$el.hide(); }, show: function () { this.$el.show(); }, _onClickTestCustomFields: function () { this.model.trigger("testCustomFields"); }, _resetAssignments: function () { this.trigger('reset-assignments'); this._onReset(); this.$('.save-or-reset').slideUp(); }, _onSaveAssignments: function () { this.trigger('save-assignments'); }, _hideSaveStatus: function () { this.$saveStatus.html('').hide(); }, _setSaveStatus: function (status) { var prefix; if (status.success) { this._onCancelProject(); this.dialog.show("alert", "User profile updated successfully."); this._removeAllRowsViews(); this._initializeRowViews(); this._fillRows(); } else { prefix = "User profile update failed. "; this.$saveStatus.removeClass(SuccessStyle) .addClass(ErrorStyle); } this.$saveStatus.html(prefix + (status.description ? status.description : "")).show(); }, _projectAdd: function () { var selectedOptions = this.$projects.all.find('option:selected'); if (selectedOptions.length) { var that = this; this.$projects.selected.append(selectedOptions); selectedOptions.each(function () { that.projectsListNew.push(parseInt($(this).val(), 10)); }); } }, _projectRemove: function () { var options = this.$projects.selected.find('option'), selectedOptions = options.filter(':selected'); if (selectedOptions.length) { var that = this; selectedOptions.each(function (index) { var id = parseInt($(this).val(), 10); that.$projects.all.append($(this)); that.projectsListNew.splice(that.projectsListNew.indexOf(id), 1); }); } }, _onChangeProject: function () { this.model.trigger('change-project', this.model); }, _onClickProject: function (model) { this.currentModel = model; this.projectManage = _.template(UserProjectManageHtml, { Constants: ModelsConstants, model: this.currentModel, projectsList: this.projectsList }); $('.manageProjectsContainer').show().html(this.projectManage); this.$projects = { all: $('#all_projects'), selected: $('#projects') }; this.$saveStatus = $('.id-change-project-status'); this._hideSaveStatus(); this.projectsListNew = []; var selectedProjects = model.get('project'); for (var key in selectedProjects) { if (selectedProjects.hasOwnProperty(key)) { this.projectsListNew.push(selectedProjects[key].id); } } }, _onCancelProject: function () { $('.manageProjectsContainer').html('').hide(); }, _onSaveProject: function () { var newProjectList = this.projectsListNew, oldProjectsList = this.currentModel.get('project'); if (!newProjectList.length) { this.dialog.show('alert', 'Please choose at least one project for selected user.<br>You can block the user to prevent his access.'); return; } if (projectsNotRemoved()) { if (newProjectList.length > oldProjectsList.length) { this._hideSaveStatus(); this.model.trigger('change-project', this.currentModel, this.projectsListNew); } else { this._onCancelProject(); } } else { this.dialog.show('confirm', 'Data from unassigned ' + ModelsConstants.customLabel('projects') + ' will be lost permanently.<br><br>Proceed?', 'save-project'); } function projectsNotRemoved() { if (newProjectList.length < oldProjectsList.length) { return false; } else { for (var key = 0; key < oldProjectsList.length; key++) { if (newProjectList.indexOf(oldProjectsList[key].id) < 0) { return false; } } } return true; } }, _changeSortOrder: function (e) { var $this = $(e.target); switch (true) { case $this.is('.sort-name'): this.sortType = 'name'; break; case $this.is('.sort-email'): this.sortType = 'email'; break; case $this.is('.sort-status'): this.sortType = 'status'; break; case $this.is('.sort-role'): this.sortType = 'role'; break; case $this.is('.sort-project'): this.sortType = 'project'; break; } switch (true) { case $this.is('.sort-asc'): this.sortOrder = 'asc'; break; case $this.is('.sort-desc'): this.sortOrder = 'desc'; break; } this.$('.result-table th .hidden').removeClass('hidden'); $this.addClass('hidden'); this._removeAllRowsViews(); this._initializeRowViews(); this._fillRows(); } }); }); <file_sep>This directory contains Dexterity web client project for Kinetics POC project.<file_sep>/*global define:true */ define([ 'underscore', 'DataLayer/Constants' ], function (_, Constants) { "use strict"; return { AccountManager: { authenticate: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "authenticate", "timestamp": null, "target": "AccountManager", "arguments": [ { "name": "email", "value": options.email }, { "name": "<PASSWORD>Hash", "value": options.password } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.project; } }, login: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "login", "timestamp": null, "target": "AccountManager", "arguments": [ { "name": "email", "value": options.email }, { "name": "<PASSWORD> <PASSWORD>", "value": <PASSWORD> }, { "name": "project", "value": options.project } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.sessionToken; } }, logout: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "logout", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function () { } }, confirmCreate: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "confirmCreate", "target": "AccountManager", "arguments": [ { "name": "email", "value": options.email }, { "name": "confirmationCode", "value": options.confirmationCode } ] } } }; }, parseResponse: function () { } }, resendConfirmation: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "resendConfirmation", "target": "AccountManager", "arguments": [ { "name": "email", "value": options.email }, { "name": "token", "value": options.token } ] } } }; }, parseResponse: function () { } }, resendInvite: { buildRequest: function (options) { return { "request": { "function": { "method": "resendInvite", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "email", "value": options.email } ] } } }; }, parseResponse: function () { } }, sendPatientInvite: { signInRequired: false, buildRequest: function (options, model) { return { "request": { "function": { "method": "sendPatientInvite", "target": "AccountManager", "arguments": [ { "name": "id", "value": model.id }, { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function () { } }, resetPassword: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "resetPassword", "target": "AccountManager", "arguments": [ { "name": "email", "value": options.email } ] } } }; }, parseResponse: function () { } }, setPassword: { signInRequired: false, buildRequest: function (options) { var persist = { email: options.email, passHash: <PASSWORD>.password, token: options.token }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "setPassword", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, getUserInfo: { buildRequest: function (options) { return { "request": { "function": { "method": "getUserInfo", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, getUserInfoById: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getUserInfoById", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": [ model.id ] } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user[0]; } }, getPatientInfoById: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getPatientInfoById", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": model.id } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, getPatientInfoByConfCode: { signInRequired: false, buildRequest: function (options, model) { return { "request": { "function": { "method": "getPatientInfoByConfCode", "target": "AccountManager", "arguments": [ { "name": "confirmationCode", "value": options.inviteId }, { "name": "email", "value": options.inviteEmail } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, getRoleList: { buildRequest: function (options) { return { "request": { "function": { "method": "getRoleList", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.role; } }, createPatient: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { sessionToken: attributes.sessionToken, email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createPatient", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, createUser: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options), persist = { // NOTE: Unique ID now not updateable email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender, // NOTE: Temporary workaround to set passHash passHash: <PASSWORD>, project: attributes.projectId }, method; if (attributes.recaptchaChallenge && attributes.recaptchaResponse) { persist.challenge = attributes.recaptchaChallenge; persist.solution = attributes.recaptchaResponse; method = 'createUserCaptcha'; } else { method = 'createUser'; } var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": method, "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, createUserCaptcha: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender, // NOTE: Temporary workaround to set passHash passHash: attributes.password, challenge: attributes.recaptchaChallenge, solution: attributes.recaptchaResponse, project: attributes.projectId, token: options.token }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createUserCaptcha", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, createShareUser: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, passHash: <PASSWORD>, birthday: attributes.birthday, gender: attributes.gender, project: attributes.projectId, user: options.user }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createShareUser", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, createUserByAdmin: { signInRequired: true, buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { sessionToken: options.sessionToken, email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender, role: attributes.role, project: attributes.projectId }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createUserByAdmin", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, createUserWithTest: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender, // NOTE: Temporary workaround to set passHash passHash: <PASSWORD>.<PASSWORD>, challenge: attributes.recaptchaChallenge, solution: attributes.recaptchaResponse, project: attributes.projectId, testSession: attributes.testSessionResults }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createUserWithTest", "target": "AccountManager", "timestamp": $.now(), "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, modifyUserInfo: { buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { sessionToken: options.sessionToken, firstName: attributes.firstName, secondName: attributes.secondName, birthday: attributes.birthday, gender: attributes.gender }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "modifyUserInfo", "target": "AccountManager", "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, modifyPatientInfo: { buildRequest: function (options, model) { var attributes = model.toJSON(options); // NOTE: Unique ID now not updateable var persist = { sessionToken: options.sessionToken, id: attributes.id, email: attributes.email, firstName: attributes.firstName, secondName: attributes.secondName, gender: attributes.gender, birthday: attributes.birthday }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "modifyPatientInfo", "target": "AccountManager", "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, confirmPatientProfile: { signInRequired: false, buildRequest: function (options, model) { var attributes = model.toJSON(options); var persist = { confirmationCode: options.confirmationCode, email: attributes.email, passHash: attributes.password }; if (attributes.firstName) { persist.firstName = attributes.firstName; } if (attributes.secondName) { persist.secondName = attributes.secondName; } if (attributes.gender) { persist.gender = attributes.gender; } if (attributes.birthday) { persist.birthday = attributes.birthday; } var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "confirmPatientProfile", "target": "AccountManager", "arguments": requestArguments } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, getUserInfoList: { buildRequest: function (options) { return { "request": { "function": { "method": "getUserInfoList", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, getPatients: { buildRequest: function (options) { return { "request": { "function": { "method": "getPatients", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, findUser: { buildRequest: function (options) { return { "request": { "function": { "method": "findUser", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "searchToken", "value": options.searchBy }, { "name": "searchData", "value": options.search } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, findPatient: { buildRequest: function (options) { return { "request": { "function": { "method": "findPatient", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "searchToken", "value": options.searchBy }, { "name": "searchData", "value": options.search } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user; } }, modifyUserStatus: { buildRequest: function (options) { return { "request": { "function": { "method": "modifyUserStatus", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids }, { "name": "disable", "value": options.disable } ] } } }; }, parseResponse: function (resp) { return {}; } }, assignRole: { buildRequest: function (options) { return { "request": { "function": { "method": "assignRole", "timestamp": null, "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp) { return {}; } }, changeRole: { buildRequest: function (options) { return { "request": { "function": { "method": "changeRole", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids }, { "name": "role", "value": options.role } ] } } }; }, parseResponse: function (resp) { return {}; } }, assignSiteAdminRole: { buildRequest: function (options) { return { "request": { "function": { "method": "assignSiteAdminRole", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids } ] } } }; }, parseResponse: function (resp) { return {}; } }, unassignRole: { buildRequest: function (options) { return { "request": { "function": { "method": "unassignRole", "timestamp": null, "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp) { return {}; } }, modifyPassword: { buildRequest: function (options) { return { "request": { "function": { "method": "ModifyPassword", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "newPassHash", "value": options.newPassHash }, { "name": "<PASSWORD>Hash", "value": options.pass<PASSWORD> } ] } } }; }, parseResponse: function (resp) { return {}; } }, modifyProjects: { buildRequest: function (options) { return { "request": { "function": { "method": "ModifyProjects", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "project", "value": options.project } ] } } }; }, parseResponse: function (resp) { return {}; } }, deleteUser: { buildRequest: function (options) { return { "request": { "function": { "method": "deleteUser", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp) { return {}; } }, unassignPatient: { buildRequest: function (options, model) { return { "request": { "function": { "method": "unassignPatient", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": [ model.id ] } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user[0]; } }, assignPatient: { buildRequest: function (options, model) { return { "request": { "function": { "method": "assignPatient", "target": "AccountManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": [ model.id ] } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.user[0]; } } }, TestSessionManager: { add: { buildRequest: function (options, model) { var method, args = [ { "name": "testSession", "value": model.toJSON() }, { "name": "sessionToken", "value": options.sessionToken } ]; if (options.userId) { method = 'addForPatient'; args.push({ "name": "id", "value": options.userId }); } else { method = 'add'; } return { "request": { "function": { "method": method, "target": "TestSessionManager", "arguments": args } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, addForPatient: { buildRequest: function (options, model) { return { "request": { "function": { "method": "addForPatient", "target": "TestSessionManager", "arguments": [ { "name": "id", "value": options.userId }, { "name": "sessionToken", "value": options.sessionToken }, { "name": "testSession", "value": model.toJSON() } ] } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, getDetails: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getDetails", "target": "TestSessionManager", "arguments": [ { "name": "id", "value": model.id }, { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getDetailsByToken: { signInRequired: false, buildRequest: function (options, model) { return { "request": { "function": { "method": "getDetailsByToken", "target": "TestSessionManager", "arguments": [ { "name": "token", "value": options.token } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getAll: { buildRequest: function (options) { return { "request": { "function": { "method": "getAll", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getAllByDate: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllByDate", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "dateFrom", "value": model.fromDate }, { "name": "dateTo", "value": model.toDate } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getAllShared: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllShared", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "project", "value": model.project }, { "name": "user", "value": model.userId } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getAllSharedByDate: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllSharedByDate", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "project", "value": model.project }, { "name": "user", "value": model.userId }, { "name": "dateFrom", "value": model.fromDate }, { "name": "dateTo", "value": model.toDate } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.testSession; } }, getAllForUser: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllForUser", "target": "TestSessionManager", "arguments": [ { "name": "id", "value": model.userId }, { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp, options) { return resp.response['function'].data.testSession; } }, getAllForUserByDate: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllForUserByDate", "target": "TestSessionManager", "arguments": [ { "name": "id", "value": model.userId }, { "name": "sessionToken", "value": options.sessionToken }, { "name": "dateFrom", "value": model.fromDate }, { "name": "dateTo", "value": model.toDate } ] } } }; }, parseResponse: function (resp, options) { return resp.response['function'].data.testSession; } }, 'delete': { buildRequest: function (options, models) { // Get ids of deleted models var ids = _.map(models, function (model) { return model.id; }); return { "request": { "function": { "method": "delete", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": ids } ] } } }; }, parseResponse: function (/*resp, options*/) { return {}; } }, modifyStatus: { buildRequest: function (options) { return { "request": { "function": { "method": "modifyStatus", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids }, { "name": "valid", "value": options.valid } ] } } }; }, parseResponse: function () { return {}; } }, getTestsForExport: { buildRequest: function (options) { return { "request": { "function": { "method": "getTestsForExport", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "dateFrom", "value": options.from }, { "name": "dateTo", "value": options.to }, { "name": "page", "value": options.page }, { "name": "size", "value": options.size } ] } } }; }, parseResponse: function (resp, options) { return resp.response['function'].data.testSession; } }, getTestsForExportCount: { buildRequest: function (options) { return { "request": { "function": { "method": "getTestsForExportCount", "target": "TestSessionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "dateFrom", "value": options.from }, { "name": "dateTo", "value": options.to } ] } } }; }, parseResponse: function (resp, options) { return resp.response['function'].data.size; } } }, ProjectManager: { getProjectInfoList: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "getProjectInfoList", "target": "ProjectManager", "arguments": [] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.project; } }, getProjectInfoById: { signInRequired: false, buildRequest: function (options) { return { "request": { "function": { "method": "getProjectInfoById", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.project; } }, createProject: { buildRequest: function (options, model) { var attributes = model.toJSON(options); var persist = { sessionToken: options.sessionToken, projectName: attributes.projectName }; var requestArguments = _.map(persist, function (value, key) { return { name: key, value: value }; }); return { "request": { "function": { "method": "createProject", "target": "ProjectManager", "arguments": requestArguments } } }; }, parseResponse: function (resp/*, options*/) { return resp.response['function'].data.id; } }, deleteProject: { buildRequest: function (options, model) { return { "request": { "function": { "method": "deleteProject", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": model.get("id") } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, modifyProjectStatus: { buildRequest: function (options, model) { return { "request": { "function": { "method": "modifyProjectStatus", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id }, { name: "disable", value: options.disable } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, modifyProjectInfo: { buildRequest: function (options, model) { return { "request": { "function": { "method": "modifyProjectInfo", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id }, { name: "projectName", value: options.name } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, changeProjects: { buildRequest: function (options, model) { return { "request": { "function": { "method": "changeProjects", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": options.ids } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, changeUserProjects: { buildRequest: function (options, model) { return { "request": { "function": { "method": "changeUserProjects", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "user", "value": options.user }, { "name": "ids", "value": options.ids } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, changeProjectUsers: { buildRequest: function (options, model) { return { "request": { "function": { "method": "changeProjectUsers", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "project", "value": options.project }, { "name": "ids", "value": options.ids } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } }, switchProject: { buildRequest: function (options, model) { return { "request": { "function": { "method": "switchProject", "target": "ProjectManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp/*, options*/) { return {}; } } }, ExtensionManager: { changeList: { buildRequest: function (options, model) { return { "request": { "function": { "method": "modifyListExtension", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": model.get("id") }, { "name": "listdata", "value": model.get("list") } ] } } }; }, parseResponse: function (resp) { return {}; } }, changeProperties: { buildRequest: function (options, model) { return { "request": { "function": { "method": "modifyExtensionProperties", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": model.get("id") }, { "name": "properties", "value": model.get("properties") } ] } } }; }, parseResponse: function (resp) { return {}; } }, createListExtension: { buildRequest: function (options, model) { return { "request": { "function": { "method": "addListExtension", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "name", "value": model.get("name") }, { "name": "entity", "value": model.get("entity") }, { "name": "listdata", "value": model.get("listdata") }, { "name": "properties", "value": model.get("properties") } ] } } }; }, parseResponse: function (resp) { return {}; } }, createSimpleExtension: { buildRequest: function (options, model) { return { "request": { "function": { "method": "addExtension", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "name", "value": model.get("name") }, { "name": "entity", "value": model.get("entity") }, { "name": "type", "value": model.get("type") }, { "name": "properties", "value": model.get("properties") } ] } } }; }, parseResponse: function (resp) { return {}; } }, deleteExtension: { buildRequest: function (options, model) { return { "request": { "function": { "method": "deleteExtension", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "ids", "value": [model.get("id")] } ] } } }; }, parseResponse: function (resp) { return {}; } }, getAll: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllExtensions", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.extension; } }, modifyExtensionName: { buildRequest: function (options, model) { return { "request": { "function": { "method": "modifyExtensionName", "target": "ExtensionManager", "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": model.get("id") }, { "name": "name", "value": model.get("name") } ] } } }; }, parseResponse: function (resp) { return {}; } } }, SharingManager: { addEmail: { buildRequest: function (options, model) { return { "request": { "function": { "method": "addEmail", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "email", "value": model.get('shareData') } ] } } }; }, parseResponse: function (resp) { return {}; } }, removeEmail: { buildRequest: function (options, model) { return { "request": { "function": { "method": "removeEmail", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "email", "value": [options.email] } ] } } }; }, parseResponse: function (resp) { return {}; } }, leaveTests: { buildRequest: function (options, model) { return { "request": { "function": { "method": "leaveTests", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "user", "value": options.user }, { "name": "project", "value": options.project } ] } } }; }, parseResponse: function (resp) { return {}; } }, getAllShareInfo: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAllShareInfo", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.shareData; } }, checkToken: { buildRequest: function (options, model) { return { "request": { "function": { "method": "checkToken", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.token; } }, generateToken: { buildRequest: function (options, model) { return { "request": { "function": { "method": "generateToken", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.token; } }, dropToken: { buildRequest: function (options, model) { return { "request": { "function": { "method": "dropToken", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "id", "value": options.id } ] } } }; }, parseResponse: function (resp) { return {}; } }, shareByMail: { buildRequest: function (options, model) { return { "request": { "function": { "method": "shareByMail", "target": "SharingManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "message", "value": options.message }, { "name": "email", "value": options.email }, { "name": "urlPath", "value": options.urlPath } ] } } }; }, parseResponse: function (resp) { return {}; } } }, AuditManager: { getAuditEvents: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAuditEvents", "target": "AuditManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.type; } }, getAuditData: { buildRequest: function (options, model) { return { "request": { "function": { "method": "getAuditData", "target": "AuditManager", "timestamp": null, "arguments": [ { "name": "sessionToken", "value": options.sessionToken }, { "name": "dateFrom", "value": options.from }, { "name": "dateTo", "value": options.to }, { "name": "type", "value": options.eventType } ] } } }; }, parseResponse: function (resp) { return resp.response['function'].data.auditData; } } } }; } ); <file_sep>Run "npm install" to load dependencies of this script. To build the project run "node build.js". To build for release provide -r option. To build for debug provide -d option. If you don't want to append version info to all html, js and css files provide -n option. Note: Currently there is a bug in adm-zip library, that corrupts most media files with compression https://github.com/cthackers/adm-zip/issues/45 To fix this edit zipEntry.js and on line 176 set the default method to STORED.<file_sep>define([ 'Testing/Models/Constants', 'Testing/Models/TestProperties' ], function (Constants, TestProperties) { 'use strict'; // Declare test properties // NOTE: Sort index used for sort left panel item in right order or when output results in Test Room. // Actual order of test execution determinate by test transition table (see TestTransitionsInstance). var testPropertiesHash = { rightNMTest: new TestProperties({ testType: Constants.TestType.NM, testHand: Constants.TestHand.Right, tag: "Rnm", sortIndex: 0, name: "Right hand 2-finger (mn) test", description: "Press keys 'N' and 'M' keys sequentially by RIGHT hand as quick as you can..." }), leftNMTest: new TestProperties({ testType: Constants.TestType.NM, testHand: Constants.TestHand.Left, tag: "Lnm", sortIndex: 1, name: "Left hand 2-finger (mn) test", description: "Press keys 'N' and 'M' keys sequentially by LEFT hand as quick as you can..." }), rightPQTest: new TestProperties({ testType: Constants.TestType.PQ, testHand: Constants.TestHand.Right, tag: "Rpq", sortIndex: 2, name: "Right hand 1-finger (pq) test", description: "Press keys 'P' and 'Q' keys sequentially by RIGHT hand as quick as you can..." }), leftPQTest: new TestProperties({ testType: Constants.TestType.PQ, testHand: Constants.TestHand.Left, tag: "Lpq", sortIndex: 3, name: "Left hand 1-finger (pq) test", description: "Press keys 'P' and 'Q' keys sequentially by LEFT hand as quick as you can..." }) }; return testPropertiesHash; }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'backbone', 'Models/Constants', 'Models/ErrorConstants', 'text!Templates/Confirm.html' ], function ($, _, Backbone, Constants, ErrorConstants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), events: { "click .id-button-confirm": "_confirm", "click .id-button-resend": "_resendConfirmation", "keypress input": "_submitOnEnter" }, initialize: function () { var that = this; this.listenTo(this.model, { "invalid": function (model, errors) { that._updateConfirmError(errors); }, "error:resend-confirmation": this._updateResendError, "error:confirm": this._updateConfirmError }); }, render: function () { var that = this; this.$el.html(this.template(this.model.attributes)); this.$confirmationCode = this.$(".id-code"); this.$email = this.$(".id-email"); this.$errorCode = this.$(".id-error-code"); this.$errorResend = this.$(".id-error-resend"); this._hideErrorsAndStatuses(); setTimeout(function () { that.$confirmationCode.focus(); }); return this; }, _updateResendError: function (error) { this.$errorResend.show().html(error.description); this.$email.addClass('errored'); }, _updateConfirmError: function (error) { this.$errorCode.show().html(error.description); this.$confirmationCode.addClass('errored'); }, _hideErrorsAndStatuses: function () { this.$errorCode.hide(); this.$errorResend.hide(); this.$confirmationCode.removeClass('errored'); this.$email.removeClass('errored'); }, _resendConfirmation: function () { this._hideErrorsAndStatuses(); this.model.resendConfirmation(); }, _confirm: function () { this._hideErrorsAndStatuses(); var confirmationCode = $.trim(this.$confirmationCode.val()); if (this.model.set("confirmationCode", confirmationCode, { validate: true })) { this.model.confirm(); } }, _submitOnEnter: function (e) { if (e.keyCode === 13) { this._confirm(); } } }); }); <file_sep>/*global define:true, alert: true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Models/ErrorConstants', 'Utils/Dialog', 'text!Templates/PatientProfile.html' ], function (_, Backbone, Constants, ErrorConstants, Dialog, templateHtml) { 'use strict'; var SuccessStyle = "sign-row-success"; var ErrorStyle = "sign-row-error"; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), events: { }, initialize: function () { // }, render: function () { var that = this; this.$el.html(this.template({ Constants: Constants, model: this.model.userProfile, homePageTitle: this.model.homePageTitle })); return this; } }); }); <file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'Models/Constants', 'text!Templates/Welcome.html', 'text!Templates/ModalProjectSelector.html' ], function (Backbone, _, ModelsConstants, templateHtml, projectSelector) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper welcome", template: _.template(templateHtml), projectSelectorTemplate: _.template(projectSelector), events: { "click #button-sign-up": function () { this.trigger("sign-up"); }, "click #button-sign-in": "_onSignIn", "click #button-forgot-password": "_onForgotPassword", "keypress #sign-in-password": "_validatePassword" }, initialize: function () { this.listenTo(this.model.accountManager, "error", this._showError); this.listenTo(this, 'projectSelection', this._projectSelection); this._capsLock = null; }, render: function () { this.model.Constants = ModelsConstants; this.$el.html(this.template(this.model)); this.$email = this.$("#sign-in-email"); this.$project = this.$('#sign-in-project'); this.$password = this.$("#sign-in-password"); this.$errorContainer = this.$(".id-error-row"); this.$errorContainer.hide(); this.$errorMessage = this.$(".id-error-message"); this.$capsLockWarning = this.$(".id-warning-message"); this.$projectSelector = this.$('#project-selector'); var that = this; //todo:refacor this to change render->afterRender events setTimeout(function () { that.$email.focus(); }); $('.project-info-container').hide(); return this; }, _showError: function (error) { this.$errorMessage.html(error.description); this.$errorContainer.show(); }, _projectSelection: function (projects) { var that = this; projects = _.sortBy(projects, function (project) { return project.name; }); this.$projectSelector.html(this.projectSelectorTemplate({projects: projects})).dialog({ modal: true }); this.$projectSelector.find('.project').button() .keydown(function (e) { var $this = $(this); if (e.keyCode === 38) { if ($this.is(':first-child')) { $this.parent().children(':last-child').focus(); } else { $this.prev().focus(); } } if (e.keyCode === 40) { if ($this.is(':last-child')) { $this.parent().children(':first-child').focus(); } else { $this.next().focus(); } } }) .click(function (e) { e.preventDefault(); that.$projectSelector.dialog('destroy'); that.trigger('projectSelected', that.$email.val(), that.$password.val(), $(this).data('id')); return false; }); }, _onSignIn: function (e) { e.preventDefault(); this.$errorContainer.hide(); var email = this.$email.val(), password = this.$password.val(), project = this.$project && this.$project.val(); this.trigger('authenticate', email, password); return false; }, _onForgotPassword: function () { this.trigger("forgot-password", this.$email.val()); // Prevent relocation by hyperlink return false; }, _validatePassword: function (e) { var keyCode = e.which; if (keyCode >= 65 && keyCode <= 90) { this._toggleCapsLockWarning(!e.shiftKey); } else if (keyCode >= 97 && keyCode <= 122) { this._toggleCapsLockWarning(e.shiftKey); } }, _toggleCapsLockWarning: function (showWarning) { if (showWarning) { this._capsLock = true; this.$capsLockWarning.show(); } else { this._capsLock = false; this.$capsLockWarning.hide(); } } }); }); <file_sep>/*global define: true, alert: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Views/Constants', 'Views/TestRoomView', 'Views/PatientInfoView', 'Models/Constants', 'Models/UserProfile', 'Models/TestSessionResultsRowCollection', 'Models/Sharing', 'DataLayer/ErrorConstants', 'Utils/Dialog', 'text!Templates/UserNotAccessible.html' ], function (_, Constants, ControllerBase, ViewsConstants, TestRoomView, PatientInfoView, ModelsConstants, UserProfile, TestSessionResultsRowCollection, Sharing, ErrorConstants, Dialog, UserNotAccessible) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("accountManager"); var testingController = this._checkAttribute("testingController"); this._checkAttribute("globalModels"); // Bind methods with 'this' reference _.bindAll(this, "_fetchRowCollection", "_fetchUserProfile", "_initializeView", "_onUserInfoFetched"); // Attach permanent listener to testing controller testingController.on("submit", this._onSubmitNewTestSessionResults, this); this.models = {}; this.dialog = new Dialog(); this.sharing = new Sharing(); }, parseParams: function (params) { var result = {}; if (params.length === 1 || params.length === 3) { result.userId = +params[0]; } if (params.length === 2 || params.length === 4) { try { result.userId = +$.base64.decode(params[0]); result.project = +$.base64.decode(params[1]); } catch (e) { this.trigger('parsing-error'); } } return result; }, activate: function (params) { var accountManager = this.get("accountManager"), currentUserRole = accountManager && accountManager.get("currentUser") && accountManager.get("currentUser").get("role"); if (!params.userId && currentUserRole === ModelsConstants.UserRole.SiteAdmin) { this.trigger("missing-user-id"); return; } var that = this; this.refreshOnly = false; this._readOnly = !!params.userId && !!params.project; this.userId = params.userId; this.project = params.project; accountManager.trigger('viewed-user-updated', this.userId); // Start listening control events this.listenTo(accountManager, { 'project-changed-success': this._refreshView }); this.analystMode = currentUserRole === ModelsConstants.UserRole.Analyst; this.ownTestRoom = !this.userId; this._viewInitialized = false; this._userProfileInitialized = false; this._initializeRowCollection(params.userId, params.project); if (params.userId && currentUserRole !== ModelsConstants.UserRole.Patient) { this._initializeUserProfile(params.userId); } this.listenTo(this.dialog, { 'generate-link-confirmed': function () { that._getOrGenerateToken(that._lastSharedTestId); } }); }, _initializeRowCollection: function (userId, project) { this.models.rowCollection = new TestSessionResultsRowCollection(null, { userId: userId, project: project }); this.listenTo(this.models.rowCollection, { "detail": this._onDetail, "change: isValid": this._onChangeIsValid, "shareTest": this._onShareTest }); this._fetchRowCollection(); }, _fetchRowCollection: function () { var options = this._getFetchOptions(true, this._initializeView, this._fetchRowCollection); options.analystMode = this.analystMode; this.models.rowCollection.fetch(options); }, _initializeUserProfile: function (userId) { this.models.userProfile = new UserProfile({ id: userId, analystMode: this._analystMode }); this._fetchUserProfile(); }, _fetchUserProfile: function () { var options = this._getFetchOptions(true, this._onUserInfoFetched, this._fetchUserProfile), that = this; options.analystMode = this.analystMode; options.error = function (model, xhr, options) { if (options.responseError.code === ErrorConstants.ServerErrorsCodes.NoPermission) { that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; } if (options.responseError.code === ErrorConstants.ServerErrorsCodes.UserDoesNotExist) { var dropDownEntry = $('.username-text .id-username').find('option[value="' + that.get('accountManager').viewedUser + '"]'); if (dropDownEntry.length) { var dialog = $('#userNotAccessible'); dialog = dialog.length ? dialog : $('<div id="userNotAccessible"></div>'); dialog.html(_.template(UserNotAccessible)({username: dropDownEntry.text()})).dialog({modal: true}); setTimeout(function () { dialog.dialog('destroy'); that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; }, 3000); } else { that.trigger('invalid-parameters'); that.get('accountManager').viewedUser = null; } } }; this.models.userProfile.fetch(options); }, _onUserInfoFetched: function () { this._userProfileInitialized = true; if (this.analystMode) { this._showUserInfo(); } else { this.view = new PatientInfoView({ model: this.models.userProfile }); this.get("applicationView").showView(this.view); } }, _showUserInfo: function () { if (this._viewInitialized && this._userProfileInitialized) { this.view.showUserInfo(this.models.userProfile); } }, _initializeView: function () { this.view = new TestRoomView({ model: this.models.rowCollection, analystMode: this.analystMode, ownTestRoom: this.ownTestRoom, readOnly: this._readOnly }); if (!this.refreshOnly) { // Show view this.get("applicationView").showView(this.view); } else { // Update view this.get("applicationView").updateView(this.view); } this.listenTo(this.view, { "start-test": this._onStartTest, "delete": this._onDelete, "trend-report": this._onTrendReport, "share-all": this._onShareAll }); this.listenTo(this.get("accountManager"), { "viewed-patient-changed": function (id) { this.trigger('change-patient', id); } }); this._viewInitialized = true; this._showUserInfo(); }, _refreshView: function () { var currentUserRole = this.get("accountManager") && this.get("accountManager").get("currentUser") && this.get("accountManager").get("currentUser").get("role"); this.analystMode = currentUserRole === ModelsConstants.UserRole.Analyst; if (this.analystMode) { return; } this.refreshOnly = true; this._initializeRowCollection(this.userId); }, // Initialize menu initializeMenu: function () { var activeButton = !this.userId ? "testRoom" : null; this.get("applicationView").header.showMenu(ViewsConstants.HeaderMenu.Default, activeButton); }, deactivate: function () { this._reset(); }, _onStartTest: function () { this.trigger("start-test", this.userId); }, _onDelete: function (selectedModels) { var that = this; if (this.models.rowCollection) { this.models.rowCollection.destroyMany(selectedModels, { wait: true, accountManager: this.get("accountManager"), errorOther: function (models, xhr, options) { that.trigger("error", options.responseError); }, success: function (models) { that.dialog.show('alert', "A {0} test result{1} successfully deleted.".format( models.length, models.length === 1 ? "" : "s" )); } }); } }, _onSubmitNewTestSessionResults: function (testSessionResultsContainer) { if (this.models.rowCollection) { this.models.rowCollection.add(testSessionResultsContainer); } }, _onDetail: function (model) { this.trigger("detail", model.id, model.collection.userId); }, _onChangeIsValid: function (model, isValid) { var that = this; var ids = [ model.id ]; var options = this._getFetchOptions(true, null, _.bind(that._onChangeIsValid, that, ids, isValid)); this.models.rowCollection.updateIsValid(ids, isValid, _.extend(options, { wait: true })); }, _onTrendReport: function () { if (this._readOnly) { this.trigger("trend-report", $.base64.encode(this.userId), $.base64.encode(this.project)); } else { this.trigger("trend-report", this.userId); } }, _onShareAll: function () { this.trigger('share-all'); }, _onShareTest: function (id) { var that = this; this.sharing.checkToken({ accountManager: this.get("accountManager"), id: id, success: function (model, token, options) { if (token) { that.trigger('share-test', token, id); } else { that._lastSharedTestId = id; that.dialog.show('confirm', 'Would you like to generate a link to share this test in social networks?', 'generate-link'); } } }); }, _getOrGenerateToken: function (id) { var that = this; this.sharing.generateToken({ accountManager: this.get("accountManager"), id: id, success: function (model, token, option) { that.trigger('share-test', token, id); } }); } }); });<file_sep>define([ 'underscore' ], function (_) { "use strict"; var CorrectPressesUIUpdater = function () { }; _.extend(CorrectPressesUIUpdater.prototype, { findControls: function ($el) { this.$correctPresses = $el.find(".correct-presses"); this.$correctPressesPluralEnds = $el.find(".correct-presses-plural-ends"); }, updateControls: function (correctPresses) { this.$correctPresses.html(correctPresses); if (correctPresses == 1) { this.$correctPressesPluralEnds.hide(); } else { this.$correctPressesPluralEnds.show(); } } }); return CorrectPressesUIUpdater; }); <file_sep>/*global define: true */ define([ 'jQuery', 'underscore', 'backbone', 'Models/Constants', 'Models/Project', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerCommandExecutor', 'DataLayer/ServerInteractionSerializersHash' ], function ($, _, Backbone, Constants, Project, ModelSyncExtension, ServerCommandExecutor, ServerInteractionSerializersHash) { 'use strict'; // Collection of users profiles var ProjectCollection = Backbone.Collection.extend({ model: Project /*, comparator: function (x, y) { var xx = x.get("creationDate"); var yy = y.get("creationDate"); return xx > yy ? -1 : (xx < yy ? 1 : 0); }*/ }); ModelSyncExtension.extend(ProjectCollection.prototype, { read: ServerInteractionSerializersHash.ProjectManager.getProjectInfoList }); return ProjectCollection; }); <file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'Models/Constants', 'text!Templates/AddUser.html', 'text!Templates/AddUserRow.html' ], function (Backbone, _, ModelsConstants, templateHtml, userRowHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper add-patient", template: _.template(templateHtml), userRowTemplate: _.template(userRowHtml), events: { 'click .id-search': '_onSearch', 'keypress #searchName, #searchEmail': '_onSubmitSearchByEnter', 'click .id-cancel': '_onCancel', 'click .id-add-user': '_onAddUser' }, initialize: function () { this.listenTo(this, { 'found-users': function (users) { var that = this; this.$results.html(''); if (!users.length) { this.$noResults.show(); } else { this.$noResults.hide(); var rows = ''; _.each(users, function (user) { rows += that.userRowTemplate({model: user}); }); this.$results.html(rows); } } }); }, remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); }, render: function () { this.$el.html(this.template({ Constants: ModelsConstants })); this.$name = this.$('#searchName'); this.$email = this.$('#searchEmail'); this.$noResults = this.$('.id-no-results'); this.$results = this.$('.results'); var that = this; //todo:refacor this to change render->afterRender events setTimeout(function(){ that.$name.focus(); }); return this; }, _renderResults: function () { }, _onSearch: function () { this.trigger('search', this.$name.val(), this.$email.val()); }, _onSubmitSearchByEnter: function (e) { if (e.keyCode === 13) { this._onSearch(); } }, _onCancel: function () { this.trigger('cancel'); }, _onAddUser: function (e) { this.trigger('add-user', $(e.target).data('id')); } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Models/Constants', 'Views/Constants', 'Views/AnalystRoomView', 'Models/AnalystPatientsCollection', 'Utils/SimpleRequest', 'formatter' ], function ($, _, Constants, ControllerBase, ModelsConstants, ViewsConstants, AnalystRoomView, AnalystPatientsCollection, SimpleRequest) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); this._applicationView = this._checkAttribute("applicationView"); this._globalModels = this._checkAttribute("globalModels"); _.bindAll(this, "_fetchData"); }, parseParams: function (params) { var result = {}; if (params.length > 0) { result.email = params[0]; } return result; }, _getData: function () { this._initializeRowCollection(); this._fetchData(); }, _setListeners: function () { this.listenTo(this.model, { "detail": this._onDetail, "unassign": this._onUnassign, "addExisting": this._onClickAddExisting, "createNew": this._onClickCreateNew }); this.listenTo(this.get('accountManager'), { 'project-changed-success': this._refreshView }); }, activate: function () { this._getData(); this._initializeView(); this._setListeners(); // Initialize menu this._applicationView.header.showMenu(ViewsConstants.HeaderMenu.Analyst); }, _refreshView: function () { this._getData(); this._updateView(); this._setListeners(); }, _onUnassign: function (model) { var that = this; SimpleRequest({ target: 'AccountManager', method: 'unassignPatient', options: { sessionToken: this.get("accountManager").getSessionToken() }, model: model, success: function (data) { that._fetchData(); that.view.trigger('reset'); that.get("accountManager").trigger('patient-list-updated'); } }); }, _onClickAddExisting: function () { this.trigger("add-patient"); }, _onClickCreateNew: function () { this.trigger("create-patient"); }, _initializeView: function () { this.view = new AnalystRoomView({ model: this.model }); // Show view this._applicationView.showView(this.view); }, _updateView: function () { this.view = new AnalystRoomView({ model: this.model }); // Show view this._applicationView.updateView(this.view); }, _fetchData: function () { var options = this._getFetchOptions(true, this._patientsFetched, this._fetchData, this); this.model.fetch(options); }, _patientsFetched: function () { this.get("accountManager").trigger('patient-list-updated', this.model.models); }, _initializeRowCollection: function () { this.model = new AnalystPatientsCollection(); }, initializeMenu: function () { // Initialize menu this.get("applicationView").header.showMenu(ViewsConstants.HeaderMenu.Default, "analystRoom"); }, deactivate: function () { this._reset(); }, _onDetail: function (model) { this.trigger("detail", model.id); this.get("accountManager").trigger('viewed-user-updated', model.id); } }); }); <file_sep>/*global define:true */ define([ 'Utils/MathExtensions', 'moment' ], function (MathExtensions, moment) { //why the hell do we even need this? "use strict"; return { HeaderMenu: { Default: "default", Welcome: "welcome", Patient: "patient", Authorization: "auth", Testing: "testing", Analyst: "analyst", SiteAdmin: "site_admin" }, ReCaptchaPublicKey: "<KEY>", flotOptions: { valueLabels: { show: true, showAsHtml: true }, series: { color: "#00A4CA", curvedLines: { active: true } }, grid: { show: true, borderWidth: { top: 0, bottom: 24, right: 0, left: 0 }, borderColor: "#ddd", tickColor: "rgba(255, 255, 255, 0)", margin: 0, hoverable: true, mouseActiveRadius: 30 }, xaxes: [{ color: "#00A4CA", font: { }/*, ticks: function (axis) { var K = 10000000, ticks = [], max = axis.max * K, min = axis.min * K, range = max - min, delta = axis.delta * K, marginK = 0.4, margin = delta * marginK, lDelta, format, days = moment.duration(range).asDays(), hourDuration = moment.duration(1, "hour").asMilliseconds(), dayDuration = 24 * hourDuration, k, fk; if (days <= 2) { lDelta = delta * 0.5; k = dayDuration / lDelta; format = "H:mm"; if (k > 1) { fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else if (days <= 10) { lDelta = delta * 0.45; k = dayDuration / lDelta; format = "D"; if (k > 1) { lDelta = delta * 0.7; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else { lDelta = delta * 0.7; k = dayDuration / lDelta; format = "MMM D"; if (k > 1) { lDelta = delta * 0.85; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "MMM D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } }*/ }], yaxes: [ { show: true, min: 0 } ], yaxis: { zoomRange: false, panRange: false }, zoom: { interactive: true }, pan: { interactive: true } } }; }); <file_sep>define([ 'underscore', 'backbone' ], function (_, Backbone) { 'use strict'; // NOTE: View should be created one for one test session then should be destroyed return Backbone.View.extend({ tagName: "div", className: "test-nav-row", initialize: function () { this.listenTo(this.model, { "state:activated": this._onActivated, "state:deactivated": this._onDeactivated }); }, render: function () { this.$el.html(this.template(this.model)); this.$score = this.$(".test-nav-score"); return this; }, _updateScore: function (scoreValue) { // Format number value if (_.isNumber(scoreValue)) { scoreValue = scoreValue.toFixed(2); } this.$score.html(scoreValue); }, _onActivated: function () { this.$el.addClass("active"); }, _onDeactivated: function () { this.$el.removeClass("active"); } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'backbone', 'moment', 'Views/Constants', 'Models/Constants', 'Models/ErrorConstants', 'Utils/MathExtensions', 'text!Templates/SiteAdminExport.html', 'text!Templates/ExportHeader.csv', 'text!Templates/ExportRow.csv', 'text!Templates/ExportHeaderTabs.csv', 'text!Templates/ExportRowTabs.csv', 'jQuery.placeholder', 'formatter', 'jQuery.ui', 'jQuery.flot', 'jQuery.flot.time', 'jQuery.flot.curvedLines', 'jQuery.flot.valuelabels', 'jQuery.flot.navigate' ], function ($, _, Backbone, moment, Constants, ModelsConstants, ErrorConstants, MathExtensions, templateHtml, csvHeader, csvRow, csvHeaderTabs, csvRowTabs) { 'use strict'; var K = 10000000; return Backbone.View.extend({ tagName: "div", className: "content-wrapper export", template: _.template(templateHtml), csvHeaderTemplate: _.template($.browser.msie ? csvHeaderTabs : csvHeader), csvRowTemplate: _.template($.browser.msie ? csvRowTabs : csvRow), events: { "click .id-export": "_onExport", "keypress .export-data input": "_submitExportOnEnter", "click .id-cancel": "_onCancel", "click .id-show-analytics": "_onAnalytics", "keypress .analytics-reports input": "_submitAnalyticsOnEnter", "change #range-from": "_onExportDatesChanged", "change #range-to": "_onExportDatesChanged" }, initialize: function () { this.listenTo(this.model, { 'invalid': function (model, errors) { this._updateErrorMessage(errors); }, 'error': function (error) { this._updateErrorMessage([ error ]); }, 'export-data-ready': this._prepareExportData, 'export-download-progress': function (state) { this.$('.stage1 .progress').progressbar('value', state); }, 'analytics-received': this._analyticsReceived }); }, render: function () { this.$el.html(this.template({ Constants: ModelsConstants, model: this.model, eventList: this.options.eventList })); this.$from = this.$(".id-range-from"); this.$to = this.$(".id-range-to"); this.$eventFrom = this.$(".id-event-range-from"); this.$eventTo = this.$(".id-event-range-to"); this.$errorFrom = { "export-data": this.$(".id-error-from"), "analytics-reports": this.$(".id-event-error-from") }; this.$errorTo = { "export-data": this.$(".id-error-to"), "analytics-reports": this.$(".id-event-error-to") }; this.$errorGeneral = { "export-data": this.$('.id-error-general'), "analytics-reports": this.$('.id-event-error-general') }; this.$graphPlaceholder = this.$(".id-trend-graph"); this.$from.datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true }); this.$to.datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true, maxDate: 'today' }); this.$eventTo.datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true, maxDate: 'today' }); this.$eventFrom.datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true }); this.$('.stage').hide(); this.$('.progress').progressbar(false); this.$("input, textarea").placeholder(); this._hideErrorsAndStatuses(); this.$('.profile-menu a').click(this._subMenuNavigation); var firstSubPage = this.$('.side-menu a').click(_.bind(this._subMenuNavigation, this)).first(); firstSubPage.parents('li').addClass('active'); this.$('.page-partial.' + firstSubPage.attr('class')).show(); return this; }, // Overload remove() method to reset reCaptcha inner state. remove: function () { // Call base implementation Backbone.View.prototype.remove.apply(this, arguments); }, _hideErrorsAndStatuses: function () { this.$('.sign-row-error').hide().removeAttr('title'); this.$('input, select').removeClass('errored'); }, _onCancel: function () { this.trigger('cancel', this.model); }, _onExport: function () { this._hideErrorsAndStatuses(); this.$('.id-export').attr('disabled', true); var values = { fromFormatted: $.trim(this.$from.val()), toFormatted: $.trim(this.$to.val()) }; if (this.model.set(values, { validate: true })) { this.$('.stage').hide(); this.$('.stage1').show(); this.$('.stage1 .progress').progressbar('value', false); this.trigger('export', this.model); } }, _submitExportOnEnter: function (e) { if (e.keyCode === 13) { this._onExport(); } }, _prepareExportData: function (data, name) { this.$('.stage').hide(); this.$('.stage2').show(); this.$('.stage2 .progress').progressbar('value', false); var that = this, output = this.csvHeaderTemplate(); _.each(data, function (e) { output += that.csvRowTemplate({'data': e}); }); data = undefined; this.$('.stage').hide(); this.$('.stage3').show(); if (!$.browser.msie) { this.$('.stage3 a').attr('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(output)).attr('download', name.replace(/\//g, '_')); } else { this.$('.stage3 a').off().click(function (e) { var oWin = window.open('about:blank', '_blank', 'width=100,height=100,menubar=no,location=no,resizable=no,scrollbars=no,status=no'); oWin.document.write(output); var success = oWin.document.execCommand('SaveAs', true, name.replace(/\//g, '_')); oWin.close(); e.preventDefault(); return false; }); } this.$('.id-export').attr('disabled', false); }, _updateErrorMessage: function (errors) { var activeMenu = this.$(".page-partial:visible").hasClass("export-data") ? "export-data" : "analytics-reports"; var $errorFrom = this.$errorFrom[activeMenu], $errorTo = this.$errorTo[activeMenu], $errorGeneral = this.$errorGeneral[activeMenu]; this.$('.id-export').attr('disabled', false); _.forEach(errors, function (error) { var errored = { $container: null }; switch (error.code) { case ErrorConstants.Validation.EmptyFromDate.code: errored.$container = $errorFrom; break; case ErrorConstants.Validation.EmptyToDate.code: errored.$container = $errorTo; break; case ErrorConstants.Validation.InvalidFromDate.code: errored.$container = $errorFrom; break; case ErrorConstants.Validation.InvalidToDate.code: errored.$container = $errorTo; break; case ErrorConstants.Validation.InvalidFutureDate.code: errored.$container = $errorTo; break; case ErrorConstants.Validation.MismatchedDates.code: errored.$container = $errorFrom; break; default: errored.$container = $errorGeneral; break; } errored.$container.show().html(error.description) .attr('title', error.description); errored.$input = errored.$input || errored.$container.closest('.sign-row').find('input[type!=radio], select'); errored.$input.addClass('errored'); }, this); }, _subMenuNavigation: function (e) { e.preventDefault(); var $menuContainer = $('.side-menu'), $oldSub = $('.side-menu .active a'), $newSub = $(e.currentTarget), oldSubClass = $oldSub.attr('class'), newSubClass = $newSub.attr('class'), active = $('.side-menu .active'); if (oldSubClass === newSubClass || $menuContainer.is('.in-progress')) { return false; } $menuContainer.addClass('in-progress'); active.removeClass('active'); $newSub.parent().addClass('active'); $('.content-container>.' + oldSubClass).fadeOut(function () { $('.content-container>.' + newSubClass).fadeIn(function () { $menuContainer.removeClass('in-progress'); }); }); return false; }, _onAnalytics: function () { this._hideErrorsAndStatuses(); var values = { type: $('#event-type').val(), fromFormatted: $.trim(this.$eventFrom.val()), toFormatted: $.trim(this.$eventTo.val()) }; if (this.model.set(values, { validate: true })) { this.trigger('analytics', this.model); } }, _submitAnalyticsOnEnter: function (e) { if (e.keyCode === 13) { this._onAnalytics(); } }, _analyticsReceived: function (data) { var fromDate = this.model.get("from"), toDate = this.model.get("to"); var dataSeries = [{ data: [], points: { show: true }, lines: { show: true } }]; var minScoreValues = []; _.forEach(data, function (item, key) { var series = [moment(item.date).valueOf() / K, item.total]; dataSeries[0].data.push(series); }, this); // Determine minimal value of score var minValue = _.min(minScoreValues); this._valuePrecision = MathExtensions.getPrecision(minValue); var options = _.extend({}, Constants.flotOptions); options.xaxes[0] = _.extend({}, options.xaxes[0], { ticks: this._tickGenerator, min: moment(fromDate).valueOf() / K, max: moment(toDate).valueOf() / K }); var panMin = fromDate.valueOf() / K, panMax = toDate.valueOf() / K, panMargin = (panMax - panMin) * 0.1; options.xaxis = { panRange: [panMin - panMargin, panMax + panMargin] }; var $graphPlaceholder = this.$graphPlaceholder; this.$('.graph-container').show(); var plot = $.plot($graphPlaceholder, dataSeries, options); this._attachTooltipOnHover($graphPlaceholder); }, _attachTooltipOnHover: function ($graphPlaceholder) { var that = this; var previousPoint = null; $graphPlaceholder.bind("plothover", function (event, pos, item) { if (item) { if (previousPoint !== item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0], y = item.datapoint[1], time = moment(x * K).format("MMM Do YY"); that._showTooltip(item.pageX, item.pageY, time); } } else { $("#tooltip").fadeOut(50); previousPoint = null; } }); }, _showTooltip: function (x, y, contents) { $("<div id='tooltip' class='tooltip'>" + contents + "</div>").css({ display: "none", top: y + 15, left: x + 15 }).appendTo("body").fadeIn(200); }, _tickGenerator: function (axis) { var ticks = [], max = axis.max * K, min = axis.min * K, range = max - min, delta = axis.delta * K, marginK = 0.4, margin = delta * marginK, lDelta, format, days = moment.duration(range).asDays(), hourDuration = moment.duration(1, "hour").asMilliseconds(), dayDuration = 24 * hourDuration, k, fk; if (days <= 2) { lDelta = delta * 0.5; k = dayDuration / lDelta; format = "H:mm"; if (k > 1) { fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else if (days <= 10) { lDelta = delta * 0.45; k = dayDuration / lDelta; format = "D"; if (k > 1) { lDelta = delta * 0.7; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } else { lDelta = delta * 0.7; k = dayDuration / lDelta; format = "MMM D"; if (k > 1) { lDelta = delta * 0.85; k = dayDuration / lDelta; fk = MathExtensions.floorInBase(k, 0.5); axis.tickSize = dayDuration / fk; if (fk > 1) { format = "MMM D, H:mm"; } } else { axis.tickSize = dayDuration * MathExtensions.floorInBase(1 / k, 0.5); } } var start = min + margin, i = 0, v, dv; do { v = start + i * axis.tickSize; dv = moment(v).format(format); ticks.push([v / K, dv]); ++i; } while (v <= max - margin * 2); return ticks; }, _onExportDatesChanged: function () { this.$('.stage3').hide(); } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/Constants', 'DataLayer/ErrorConstants', 'Views/Constants', 'Views/SiteAdminExportView', 'Models/Extra', 'formatter' ], function (_, Constants, ControllerBase, DataConstants, ErrorConstants, ViewsConstants, SiteAdminExportView, Extra) { 'use strict'; return ControllerBase.extend({ _flotOptions: { }, initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); this._applicationView = this._checkAttribute("applicationView"); this._globalModels = this._checkAttribute("globalModels"); }, activate: function (params) { var that = this; this.model = new Extra(); this.model.getAuditEvents({ accountManager: this.get('accountManager'), success: function (model, data, options) { that.view = new SiteAdminExportView({ model: that.model, eventList: data }); that.listenTo(that.view, { 'export': function (model) { model.export(that.get("accountManager")); }, "cancel": function (model) { model.trigger('cancelExport'); that.trigger('cancelCreate'); }, 'analytics': function (model) { model.getAuditData(that.get("accountManager")); } }); that.get("applicationView").showView(that.view); that._applicationView.header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin, 'export'); } }); }, _onError: function (error, options) { }, deactivate: function () { this._reset(); } }); }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Models/Constants', 'Views/Constants', 'Views/ManageView', 'Models/UserProfileCollection', 'Models/ProjectCollection', 'formatter' ], function ($, _, Constants, ControllerBase, ModelsConstants, ViewsConstants, ManageView, UserProfileCollection, ProjectCollection) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("accountManager"); this._applicationView = this._checkAttribute("applicationView"); this._globalModels = this._checkAttribute("globalModels"); this.projects = new ProjectCollection(); // Bind methods with 'this' reference _.bindAll(this, "_fetchData"); }, _assignmentChanges: {}, _unassigned: {}, _projectUsers: [], parseParams: function (params) { var result = {}; if (params.length === 1) { result.manage = params[0]; } return result; }, activate: function (params) { var currentUser = this.get('accountManager').currentUser(); if (currentUser) { this._siteAdminMode = currentUser.get("isSiteAdmin"); } //manage users in certain project this._manage = parseInt(params.manage, 10); this._newProject = params.newProject; // Check search text from url params // Store user list globally this._initializeRowCollection(); this._initializeView(); this._fetchData(); this.listenTo(this.model, { "detail": this._onDetail, "testCustomFields": this._onClickTestCustomFields, "status-changed": this._onStatusChanged, "role-changed": this._onRoleChanged, 'resend-admin-invitation': this._onResendConfirmation, 'assignment-changed': this._onAssignmentChanged, 'change-project': this._onChangeProject }); }, _initializeRowCollection: function () { this.model = new UserProfileCollection(); }, _fetchData: function () { var options = this._getFetchOptions(true, null, this._fetchData); this.model.fetch(_.extend(options, { search: this._globalModels.searchText, project: this._manage })); }, _fetchProjects: function () { var options = this._getFetchOptions(true, this._onProjectsFetched, this._fetchProjects, this); this.projects.fetch(options); }, _onProjectsFetched: function () { if (!_.where(this.projects.models, {'id': this._manage}).length) { console.log('Invalid project Id'); this.trigger('invalid-project-code'); } this.view = new ManageView({ model: this.model, projects: this.projects, siteAdminMode: this._siteAdminMode, manage: this._manage, newProject: this._newProject }); // Start listening control events this.listenTo(this.view, { 'create-user': this._onCreateUser, 'add-users': this._addUsers, 'reset-assignments': this._onAssignmentsReset, 'save-assignments': this._onAssignmentSaved, 'project-user-list': this._updateProjectUsers, 'project-switched': this._projectSwitched }); // Show view this._applicationView.showView(this.view); }, _initializeView: function () { var that = this; this._fetchProjects(); }, _updateProjectUsers: function (users) { this._projectUsers = users; }, initializeMenu: function () { // Initialize menu this._applicationView.header.showMenu(ViewsConstants.HeaderMenu.Default, "users"); }, deactivate: function () { this._globalModels.searchText = null; this._reset({ deleteModel: true }); }, _onCreateUser: function () { this.trigger('create-user', this._manage); }, _onDetail: function (model) { this.trigger("detail", model.id); }, _onAssignmentChanged: function (id, changed) { this._unassigned[id] = changed; this.view.trigger('assignment-changed'); }, _onAssignmentsReset: function () { this._unassigned = {}; }, _onAssignmentSaved: function () { var that = this, filteredUsers = _.reject(this._projectUsers, function (id) { return that._unassigned[id]; }); this.model.saveAssignments({ project: this._manage, accountManager: this.get("accountManager"), users: filteredUsers, success: function () { that._unassigned = {}; that.view.trigger('assignments-saved'); that._fetchData(); } }); }, _addUsers: function () { this.trigger('add-users', this._projectUsers, this._manage, this.model.backup); }, _projectSwitched: function (id) { this.trigger('project-switched', id); } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'moment', 'backbone', 'Models/Constants', 'text!Templates/UserListRow.html', 'text!Templates/RoleSelector.html', 'text!Templates/StatusSelector.html', 'text!Templates/ManageProjectsRow.html' ], function (_, moment, Backbone, ModelsConstants, templateHtml, RoleSelector, StatusSelector, manageProjectsRowHtml) { 'use strict'; return Backbone.View.extend({ tagName: "tr", className: "", template: _.template(templateHtml), roleSelector: null, statusSelector: _.template(StatusSelector), templateManageProjectsRow: _.template(manageProjectsRowHtml), events: { "click .test-checkbox": "_onSelected", "click .id-button-detail": "_onClickDetail", "click .id-status span": "_onClickStatus", "click .id-user-assigned": "_onAssignmentChanged", "click .id-manage-project": "_onClickProject", "mouseover .user-list .id-project": "_onFocusProject", "mouseout .user-list .id-project": "_onBlurProject" }, _selected: false, initialize: function (options) { this.listenTo(this.model, "change", this.render); this._siteAdminMode = options.siteAdminMode; this._manage = options.manage; this.showProjects = options.showProjects; }, // Get/Set row selection flag selected: function (value) { if (value === undefined) { return this._selected; } else { this._selected = value; this._updateSelectCheckbox(); } }, render: function () { if (this._manage) { this.$el.html(this.templateManageProjectsRow({ model: this.model, moment: moment, Constants: ModelsConstants, siteAdminMode: this._siteAdminMode, project: parseInt(this._manage, 10), showProjects: this.showProjects })); } else { this.$el.html(this.template({ model: this.model, moment: moment, Constants: ModelsConstants, siteAdminMode: this._siteAdminMode, showProjects: this.showProjects })); } this.$selectCheckBox = this.$(".test-checkbox .tick"); this._updateSelectCheckbox(); return this; }, _updateSelectCheckbox: function () { if (this._selected) { this.$selectCheckBox.addClass("checked"); } else { this.$selectCheckBox.removeClass("checked"); } }, _onClickProject: function () { this.model.trigger('clickProject', this.model); return false; }, _onFocusProject: function () { this.$el.find('.test-detail:first').addClass('test-detail-hover'); }, _onBlurProject: function () { this.$el.find('.test-detail:first').removeClass('test-detail-hover'); }, _onClickStatus: function () { console.info('status'); var that = this, status = this.model.get("status"), value = status.toLowerCase() === 'active' ? 0 : 1; //todo: rewrite this in a better way if (status === ModelsConstants.UserStatus.Waiting) { $('.dialog-waiting-user').dialog({ modal: true }).find('.resend').off().button().click(function (e) { e.preventDefault(); that.model.trigger('resend-admin-invitation', that.model.get("email")); $('.dialog-waiting-user').dialog('destroy'); return false; }); return; } this.$('.id-status span').hide(); if (this.$('.id-status select').length) { this.$('.id-status select').show().focus(); return; } this.$('.id-status').append(this.statusSelector); this.$('.id-status select').blur(function () { $(this).hide(); that.$('.id-status span').show(); }).change(function () { $(this).attr('disabled', true); that.model.trigger('status-changed', that.model, !!parseInt($(this).val(), 10)); }).children('[value=' + value + ']').attr('selected', true); this.$('.id-status select').focus(); }, _onSelected: function () { this.selected(!this.selected()); }, _onClickDetail: function () { this.model.trigger("detail", this.model); }, _onAssignmentChanged: function (e) { this.model.trigger('assignment-changed', this.model.get('id'), !!$(e.target).is(':checked')); } }); });<file_sep>/*global define:true */ define([ 'backbone', 'underscore', 'Models/Extension', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash' ], function (Backbone, _, ExtensionModel, ModelSyncExtension, ServerInteractionSerializersHash) { 'use strict'; var ExtensionsCollection = Backbone.Collection.extend({ model: ExtensionModel }); ModelSyncExtension.extend(ExtensionsCollection.prototype, { 'read': ServerInteractionSerializersHash.ExtensionManager.getAll }); return ExtensionsCollection; }); <file_sep>/*global define: true */ define([ 'moment', 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants', 'DataLayer/Constants', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'Utils/StringExtensions', 'backbone.localStorage' ], function (moment, Backbone, _, Constants, ErrorConstants, DataConstants, ModelSyncExtension, ServerInteractionSerializersHash, StringExtensions) { 'use strict'; var UserProfile = Backbone.Model.extend({ defaults: { userId: null, email: null, firstName: null, secondName: null, creationDate: null, timestamp: null, status: null, birthdayFormatted: null, birthday: null, gender: null, uid: null, passHash: <PASSWORD>, password: <PASSWORD>, passwordOld: <PASSWORD>, passwordNew: <PASSWORD>, passwordConfirmation: <PASSWORD>, role: null, recaptchaChallenge: null, recaptchaResponse: null, project: [], projectId: null /*projectId: null, project: DataConstants.predefinedProject ? DataConstants.predefinedProjectId : null*/ }, localStorage: new Backbone.LocalStorage("kinetics-UserProfile"), initialize: function () { this._updateBirthdayUIFields(this.get("birthday")); this.on({ "change:birthday": this._updateBirthdayUIFields, "change:birthdayFormatted": this._updateBirthday }); }, _updateBirthdayUIFields: function (model, birthday) { if (birthday) { var m = moment(birthday); this.set("birthdayFormatted", m.format("MM/DD/YYYY")); } }, _updateBirthday: function () { var birthdayFormatted = this.get("birthdayFormatted"); if (birthdayFormatted) { var birthday = moment(birthdayFormatted); if (birthday.isValid()) { this.set("birthday", birthday.format("YYYY-MM-DD")); } } }, validate: function (attrs, options) { options = options || {}; var errors = []; if (StringExtensions.isTrimmedEmpty(attrs.firstName)) { errors.push(ErrorConstants.Validation.EmptyFirstName); } if (StringExtensions.isTrimmedEmpty(attrs.secondName)) { errors.push(ErrorConstants.Validation.EmptySecondName); } if (typeof(options.birthdayRequired) === 'undefined' || options.birthdayRequired) { if (StringExtensions.isTrimmedEmpty(attrs.birthdayFormatted)) { errors.push(ErrorConstants.Validation.EmptyBirthday); } else { var birthdayDate = moment(attrs.birthdayFormatted, "MM/DD/YYYY"); if (!birthdayDate.isValid()) { errors.push(ErrorConstants.Validation.InvalidBirthday); } else { var age = (new Date()).getFullYear() - birthdayDate.year(); //birthdayYear = birthdayDate.year() if (age < 1 || age > 150) { errors.push(ErrorConstants.Validation.InvalidBirthday); } } } } if (StringExtensions.isTrimmedEmpty(attrs.email)) { if (!options.patientUpdate) { errors.push(ErrorConstants.Validation.EmptyEMail); } } else if (!attrs.email.match(Constants.EmailPattern)) { errors.push(ErrorConstants.Validation.InvalidEMail); } if ((typeof(options.genderRequired) === 'undefined' || options.genderRequired) && !attrs.gender) { errors.push(ErrorConstants.Validation.EmptyGenderSelected); } if (!(attrs.role && (attrs.role.toUpperCase() === Constants.UserRole.SiteAdmin.toUpperCase())) && attrs.projectId && attrs.projectId.length === 0) { errors.push(ErrorConstants.Validation.NoProjectSelected); } if (options.passwordRequired) { if (StringExtensions.isEmpty(attrs.password)) { errors.push(ErrorConstants.Validation.EmptyPassword); } if (attrs.password !== attrs.passwordConfirmation) { errors.push(ErrorConstants.Validation.InvalidPasswordConfirmation); } } if (/*options.capchaRequired && */(attrs.recaptchaResponse !== null) && StringExtensions.isTrimmedEmpty(attrs.recaptchaResponse)) { errors.push(ErrorConstants.Validation.EmptyCaptcha); } if (errors.length > 0) { return errors; } }, toJSON: function (options) { this._updateBirthday(); var result = Backbone.Model.prototype.toJSON.call(this, options); if (options.local) { result = _.pick(result, "dbId", "email", "firstName", "secondName", "creationDate", "status", "birthday", "gender", "uid", "role", "isAnalyst", "isSiteAdmin", "projectId", "project" ); } return result; }, configure: function (target) { switch (target) { case 'patient': this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.modifyPatientInfo; break; case 'user': this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.modifyUserInfo; break; case 'confirm': this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.confirmPatientProfile; break; } }, createUserConfigure: function (target) { switch (target) { case 'testUser': this.syncCommands.create = ServerInteractionSerializersHash.AccountManager.createUserWithTest; break; case 'createShared': this.syncCommands.create = ServerInteractionSerializersHash.AccountManager.createShareUser; break; case 'userCreation': this.syncCommands.create = ServerInteractionSerializersHash.AccountManager.createUserByAdmin; break; default: this.syncCommands.create = ServerInteractionSerializersHash.AccountManager.createUserCaptcha; } }, fetch: function (options) { var that = this; var success = options.success; options.success = function (model, xhr, options) { that._checkUserRole(); if (success) { success(model, xhr, options); } }; //todo: rewrite this // Select read command if (this.has(this.idAttribute) && !options.getOwn) { if (options.analystMode) { this.syncCommands.read = ServerInteractionSerializersHash.AccountManager.getPatientInfoById; //this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.modifyPatientInfo; } else { this.syncCommands.read = ServerInteractionSerializersHash.AccountManager.getUserInfoById; //this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.modifyUserInfo; } } else { if (options.inviteId) { this.syncCommands.read = ServerInteractionSerializersHash.AccountManager.getPatientInfoByConfCode; //this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.confirmPatientProfile; } else { this.syncCommands.read = ServerInteractionSerializersHash.AccountManager.getUserInfo; //this.syncCommands.update = ServerInteractionSerializersHash.AccountManager.modifyUserInfo; } } // Call base implementation Backbone.Model.prototype.fetch.call(this, options); }, _checkUserRole: function () { // TODO: Support multiple roles? var that = this, roles = this.get("roles"); _.each(this.get("roles"), function (role) { that.set('role', role.name.toLowerCase()); if (role.name.toLowerCase() === Constants.UserRole.Analyst) { that.set('isAnalyst', true); } if (role.name.toLowerCase() === Constants.UserRole.SiteAdmin) { that.set('isSiteAdmin', true); } }); } }); // Extend instance with server command to get/update information only for current user ModelSyncExtension.extend(UserProfile.prototype, { // create: ServerInteractionSerializersHash.AccountManager.createUserCaptcha, update: ServerInteractionSerializersHash.AccountManager.modifyUserInfo, 'delete': ServerInteractionSerializersHash.AccountManager.deleteUser }); return UserProfile; });<file_sep>define(function () { 'use strict'; var TimeCalculation = { getTimeSpan: function (ticks) { var d = new Date(ticks); return { ticks: ticks, totalSeconds: ticks / 1000, hours: d.getUTCHours(), minutes: d.getMinutes(), seconds: d.getSeconds(), milliseconds: d.getMilliseconds() } } }; return TimeCalculation; });<file_sep>/*global define: true */ define([ 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'backbone.localStorage' ], function (Backbone, _, Constants, ErrorConstants, ModelSyncExtension, ServerInteractionSerializersHash) { 'use strict'; var AnalystRoom = Backbone.Model.extend({ initialize: function () { } }); ModelSyncExtension.extend(AnalystRoom.prototype, { //'unassign': ServerInteractionSerializersHash.AccountManager.unassignPatient }); return AnalystRoom; });<file_sep>/*global define:true */ define([ 'backbone', 'underscore', 'Models/TestSessionResultsRow', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'DataLayer/MultiDeletionCollectionExtension', 'DataLayer/ServerCommandExecutor' ], function (Backbone, _, TestSessionResultsRow, ModelSyncExtension, ServerInteractionSerializersHash, MultiDeletionCollectionExtension, ServerCommandExecutor) { 'use strict'; // Collection of test session results mapped to server object. var TestSessionResultsRowCollection = Backbone.Collection.extend({ model: TestSessionResultsRow, initialize: function (models, options) { this.userId = options.userId; this.project = options.project; // Initialize sync command switch (true) { case !!this.userId && !!this.project: this.syncCommands.read = ServerInteractionSerializersHash.TestSessionManager.getAllShared; break; case !!this.userId: this.syncCommands.read = ServerInteractionSerializersHash.TestSessionManager.getAllForUser; break; default: this.syncCommands.read = ServerInteractionSerializersHash.TestSessionManager.getAll; } }, comparator: function (x, y) { var xx = x.get("creationDate"); var yy = y.get("creationDate"); return xx > yy ? -1 : (xx < yy ? 1 : 0); }, updateIsValid: function (ids, valid, options) { _.extend(options, { ids: ids, valid: valid }); ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.TestSessionManager.modifyStatus, options); } }); // Extend collection with data layer features MultiDeletionCollectionExtension.extend(TestSessionResultsRowCollection.prototype); ModelSyncExtension.extend(TestSessionResultsRowCollection.prototype, { 'delete': ServerInteractionSerializersHash.TestSessionManager['delete'] }); return TestSessionResultsRowCollection; }); <file_sep>define([ 'Testing/Models/TestScreens/TestingScreenBase', 'Testing/Models/TimeCalculation' ], function (TestingScreenBase, TimeCalculation) { 'use strict'; return TestingScreenBase.extend({ defaults: { "remainedSeconds": -1 }, _expectedKeySet: ["n", "m"], activate: function () { // Call method form base prototype TestingScreenBase.prototype.activate.call(this); this._nmTestTimeout = this._testProperties.get("nmTestTimeout"); this.set("remainedSeconds", this._nmTestTimeout); }, _checkContext: function () { // Call method form base prototype TestingScreenBase.prototype._checkContext.call(this); if (!this._testProperties.has("nmTestTimeout")) { throw new Error("'nmTestTimeout' not specified in the test properties."); } }, _tick: function () { var remainedSeconds = this.get("remainedSeconds"); this.set("remainedSeconds", --remainedSeconds); var spentSeconds = this._nmTestTimeout - remainedSeconds; var spentTime = TimeCalculation.getTimeSpan(spentSeconds * 1000); this._testResults.set("spentTime", spentTime); var percentsDone = 100 - (remainedSeconds / this._nmTestTimeout * 100); this.set("percentsDone", percentsDone); if (remainedSeconds <= 0) { this._testPassed(); } }, _expectedKeyPressed: function () { // Increment correct presses counter this._testResults.set("keyPresses", this._testResults.get("keyPresses") + 1); this._toggleExpectedKey(); } }); }); <file_sep>/*global define:true */ define([ 'backbone', 'underscore', 'Models/Constants', 'Utils/MathExtensions', 'moment' ], function (Backbone, _, Constants, MathExtensions, moment) { 'use strict'; var dayLength = moment.duration(1, "day").asMilliseconds(); return Backbone.Model.extend({ defaults: { testResults: null, fromDate: null, toDate: null, fromDateMax: null, toDateMin: null, typeValues: null, type: null, allData: null, graphData: null }, initialize: function () { var testResults = this.get("testResults"); if (!testResults) { throw new Error("A 'testResultCollection' not set."); } this._initializeTypeFilter(); this._initializeDataRanges(); this._initializeDateFilters(); this.on({ "change:toDate change:fromDate": this._recalculateGraphData, "change:type": this._onTypeFilterChanged // NOTE: It used without graph interaction when data loaded exactly for selected date range // to prevent drawing graph without y axis //"change:graphDataRange":this._calculateDateFilterLimit }); this._recalculateGraphData(); }, _initializeTypeFilter: function () { var testResults = this.get("testResults"); var groupedByType = testResults.groupBy(function (row) { return row.getType(); }); var keyboardExists = false; var typeValues = _(groupedByType).keys().map(function (typeTag) { if (typeTag == Constants.TestSessionType.Keyboard) { keyboardExists = true; } var caption = Constants.TestSessionTypeCaptions[typeTag] || typeTag; return { value: typeTag, text: caption }; }); this.set("typeValues", typeValues); if (typeValues.length > 0) { var defaultValue = keyboardExists ? Constants.TestSessionType.Keyboard : typeValues[0].value; this.set("type", defaultValue); } }, _calculateDateFilterLimit: function (model, range) { if (range) { this.set({ "fromDateMax": new Date(range.max), "toDateMin": new Date(range.min) }); } else { this.unset("fromDateMax"); this.unset("toDateMin"); } }, _correctDateFilterRange: function (fromDate, toDate) { var ranges = this.get("dataRanges"); // Get range of current type filter var type = this.get("type"); var range = ranges[type]; if (range && (toDate < range.min || fromDate > range.max)) { toDate = range.max; fromDate = new Date(MathExtensions.floorInBase( moment(toDate) .subtract('month', 1) .valueOf(), dayLength)); return { fromDate: fromDate, toDate: toDate } } }, _initializeDateFilters: function () { var now = moment(); var nowDate = moment([now.year(), now.month(), now.date()]); var range = { toDate: nowDate.clone().add(Constants.FullDayOffset).toDate(), fromDate: nowDate.clone().subtract(1, "month").toDate() }; range = this._correctDateFilterRange(range.fromDate, range.toDate) || range; this.set(range); }, _initializeDataRanges: function () { var ranges = this._getDataRangesByType(); // Round range dates by day for (var type in ranges) { var range = ranges[type]; range.min = new Date(range.min.getFullYear(), range.min.getMonth(), range.min.getDate()); range.max = moment([range.max.getFullYear(), range.max.getMonth(), range.max.getDate()]) .add(Constants.FullDayOffset).toDate(); } this.set("dataRanges", ranges); }, _getDataRangesByType: function () { var testResults = this.get("testResults"); var groupedByType = testResults.groupBy(function (row) { return row.getType(); }); var result = {}; _.forEach(groupedByType, function (rows, type) { var min = _.min(rows, function (row) { return row.get("creationDate"); }); var max = _.max(rows, function (row) { return row.get("creationDate"); }); result[type] = { max: max.get("creationDate"), min: min.get("creationDate") }; }); return result; }, dispose: function () { this.off(); }, _allData: null, // TODO: This method is temporary solution and should be deprecated in favor of // getting data form server with data period filter _getFilteredData: function (fromDate, toDate) { var testResults = this.get("testResults"); // Create pairs of data series for graph and group data by type return testResults.filter(function (row) { var creationDate = row.get("creationDate"); return creationDate >= fromDate && creationDate <= toDate; }); }, _getCreationDateDateFromRow: function (row) { var creationDate = row.get("creationDate"); return creationDate.valueOf(); }, _getDayFromRowCreationDate: function (row) { var creationDate = row.get("creationDate"); return (new Date( creationDate.getFullYear(), creationDate.getMonth(), creationDate.getDate())).valueOf(); }, // Calculate collapse period and score in this period _normalizeData: function (rows, getGroupTimestamp, collapsedScoreCalculator) { var result = []; var timeStampNewValue; var timeStampValue = null; var rowsGroup = null; var groupScore; var createNewGroup = function () { if (rowsGroup) { // Calculate collapsed score groupScore = collapsedScoreCalculator(rowsGroup); // Add new group result.push({ tick: timeStampValue, rows: rowsGroup, score: groupScore }); } // Create new empty group rowsGroup = []; // Store current group factor timeStampValue = timeStampNewValue; }; for (var i = 0; i < rows.length; i++) { // Calculate group factor timeStampNewValue = getGroupTimestamp(rows[i]); // Check end of group if (timeStampNewValue != timeStampValue) { createNewGroup(); } rowsGroup.push(rows[i]); } // Create last group createNewGroup(); return result; }, _onTypeFilterChanged: function () { var fromDate = this.get("fromDate"); var toDate = this.get("toDate"); var range = this._correctDateFilterRange(fromDate, toDate); if (range) { // Set new values of date filter this.set(range); } else { this._recalculateGraphData(); } }, // Collapse scores in period as average of scores in that period. _calculateAverageScores: function (rows) { var avg = 0; if (rows.length > 0) { var sum = 0; for (var i = 0; i < rows.length; i++) { sum += rows[i].get("score"); } avg = sum / rows.length; } return avg; }, _recalculateGraphData: function (model, value, options) { var fromDate = this.get("fromDate"); var toDate = this.get("toDate"); if (!fromDate || !toDate) { throw new Error("Invalid values of filter attributes 'toDate' or 'fromDate'."); } // NOTE: In case graph with interaction there is no calculation of data min/max in visible range // and logic of limitation date filter simplified this._calculateDateFilterLimit(null, { min: fromDate, max: toDate }); if (options && options.suppressRedraw) return; // Clear old graph data this.unset("graphData"); var filteredRows = this.get("testResults").models; var groupedRowsByType = _.groupBy(filteredRows, function (row) { return row.getType(); }); // Filter data by type var type = this.get("type"); if (type) groupedRowsByType = _.pick(groupedRowsByType, type); // Set timestamp period to 24 hours in milliseconds var timestampPeriod = moment.duration(1, "day").asMilliseconds(); this.set("timestampPeriod", timestampPeriod); // Prepare data for graph view var graphData = {}; _.forEach(groupedRowsByType, function (rows, type) { // NOTE: Now used period in one day and collapsing scores as average by scores in that day. // but it may not corrected in consideration of medical purposes. graphData[type] = this._normalizeData( rows, this._getCreationDateDateFromRow, this._calculateAverageScores ); }, this); var range = this._getDataRange(graphData); this.set({ graphData: graphData, graphDataRange: range }); }, _getDataRange: function (graphData) { var minList = [], maxList = []; var getTick = function (item) { return item.tick; }; var dataExists = false; _.forEach(graphData, function (rows, type) { if (rows.length > 0) { minList.push(_.min(rows, getTick)); maxList.push(_.max(rows, getTick)); dataExists = true; } }); var range; if (dataExists) { var min = _.min(minList, getTick); var max = _.max(maxList, getTick); range = { min: min.tick, max: max.tick}; } else { range = null; } return range; } }); }); <file_sep>define([ 'underscore' ], function (_) { 'use strict'; var SpentTimeUIUpdater = function () { }; _.extend(SpentTimeUIUpdater.prototype, { findControls: function ($el) { this.$el = $el; this.$hoursCounter = this.$el.find(".hours-counter"); this.$minutesCounter = this.$el.find(".minutes-counter"); this.$spentTimeHours = this.$el.find(".spent-time-hours"); this.$spentTimeMinutes = this.$el.find(".spent-time-minutes"); this.$spentTimeSeconds = this.$el.find(".spent-time-seconds"); this.$spentTimeHoursPluralEnds = this.$el.find(".spent-time-hours-plural-ends"); this.$spentTimeMinutesPluralEnds = this.$el.find(".spent-time-minutes-plural-ends"); this.$spentTimeSecondsPluralEnds = this.$el.find(".spent-time-seconds-plural-ends"); }, updateControls: function (spentTime) { this.$spentTimeHours.html(spentTime.hours); this.$spentTimeMinutes.html(spentTime.minutes); this.$spentTimeSeconds.html(spentTime.seconds); if (spentTime.seconds == 1) { this.$spentTimeSecondsPluralEnds.hide(); } else { this.$spentTimeSecondsPluralEnds.show(); } if (spentTime.hours > 0) { if (spentTime.hours == 1) { this.$spentTimeHoursPluralEnds.hide(); } else { this.$spentTimeHoursPluralEnds.show(); } this.$hoursCounter.show(); } else { this.$hoursCounter.hide(); } if (spentTime.minutes > 0) { if (spentTime.minutes == 1) { this.$spentTimeMinutesPluralEnds.hide(); } else { this.$spentTimeMinutesPluralEnds.show(); } this.$minutesCounter.show(); } else { this.$minutesCounter.hide(); } } }); return SpentTimeUIUpdater; }); <file_sep>/*global define: true */ define([ 'underscore', 'Testing/Views/ScreenViewBase', 'text!Testing/Templates/CountDownScreen.html', 'Utils/AudioHelper' ], function (_, ScreenViewBase, templateSource, sound) { 'use strict'; return ScreenViewBase.extend({ events: { "click .id-button-stop": "_onStop" }, template: _.template(templateSource), initialize: function () { // Call base implementation ScreenViewBase.prototype.initialize.call(this); this.listenTo(this.model, { "change:spentSeconds": this._updateTimer }); }, _updateTimer: function (model, spentSeconds) { this.$timer.html(spentSeconds); if (spentSeconds == 1) { this.$pluralEnds.hide(); } else { this.$pluralEnds.show(); } }, render: function () { // Call base implementation ScreenViewBase.prototype.render.call(this); this.$timer = this.$(".timer"); this.$pluralEnds = this.$(".plural-ends"); return this; }, // Overridden for initial UI update by model attributes _onActivated: function () { // Call base implementation ScreenViewBase.prototype._onActivated.call(this); this._updateTimer(this.model, this.model.get("spentSeconds")); var timerLabel = $(".timer-label").offset().top, activeNav = $(".test-nav-row.active").offset().top; //test-nav-row active $('html, body').animate({ scrollTop: timerLabel > activeNav ? activeNav : timerLabel }, 1000); }, _onStop: function () { this.model.stopPressed(); sound.pause('test-sound-start'); } }); }); <file_sep>define(['backbone'], function (Backbone) { 'use strict'; var TestProperties = Backbone.Model.extend({ defaults: { testType: null, secondsForCountdown: 3, nmTestTimeout: 30, pqTestCountOfExpectedCorrectPresses: 20 } }); return TestProperties; });<file_sep>/*global define:true, alert: true */ define([ 'underscore', 'backbone', 'Models/Constants', 'Models/ErrorConstants', 'Utils/Dialog', 'text!Templates/PatientProfileWaiting.html' ], function (_, Backbone, Constants, ErrorConstants, Dialog, templateHtml) { 'use strict'; var SuccessStyle = "sign-row-success"; var ErrorStyle = "sign-row-error"; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), events: { "click .id-save": "_onSave", "click .id-cancel": "_onCancel", "click .id-resend": "_onResend", "change input[type=text], input[type=radio]": "_onChangeInput", "keypress input[type=text]": "_onKeyPress" }, initialize: function () { var initialLoad = true; this.listenTo(this.model.userProfile, { "invalid": function (model, errors) { this._updateErrorMessage(errors); }, //TODO: URGENT!!! FIX error messages "error": function (error, xhr, options) { this._updateErrorMessage((options ? [options.responseError] : [error])); }, "sync": function () { if (!initialLoad) { this._setSaveStatus({ success: true }); } else { initialLoad = false; } } }); this.emailChanged = false; this.dialog = new Dialog(); }, render: function () { var that = this; this.$el.html(this.template({ Constants: Constants, model: this.model.userProfile, homePageTitle: this.model.homePageTitle })); this.$email = this.$(".id-email"); this.$firstName = this.$(".id-first-name"); this.$secondName = this.$(".id-second-name"); this.$genderRadios = this.$("input:radio[name=gender]"); this.$birthday = this.$(".id-birthday"); this.$errorEmail = this.$(".id-error-email"); this.$errorFirstName = this.$(".id-error-first-name"); this.$errorSecondName = this.$(".id-error-second-name"); this.$errorGender = this.$(".id-error-gender"); this.$errorBirthday = this.$(".id-error-birthday"); this.$saveStatus = this.$(".id-save-status"); this.$genderRadios.filter('[value="' + this.model.userProfile.get("gender") + '"]').attr("checked", true); this.$birthday.datepicker({ minDate: '-150y', maxDate: "-1y", yearRange: "-150:-1", dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true }); this._hideErrorsAndStatuses(); return this; }, _hideErrorsAndStatuses: function () { this.$("." + ErrorStyle).hide().removeAttr('title'); this.$('input, select').removeClass('errored'); this.$saveStatus.hide(); }, _onSave: function () { this._hideErrorsAndStatuses(); var userProfileValues = { email: $.trim(this.$email.val()), firstName: $.trim(this.$firstName.val()), secondName: $.trim(this.$secondName.val()), birthdayFormatted: $.trim(this.$birthday.val()), gender: this.$genderRadios.filter(":checked").val() }; this.trigger("save", this.model.userProfile, userProfileValues, true); this.emailChanged = false; }, _updateErrorMessage: function (errors) { _.forEach(errors, function (error) { switch (error.code) { case ErrorConstants.Validation.EmptyFirstName.code: this.$errorFirstName.html(error.description); this.$errorFirstName.show(); break; case ErrorConstants.Validation.EmptySecondName.code: this.$errorSecondName.html(error.description); this.$errorSecondName.show(); break; case ErrorConstants.Validation.EmptyBirthday.code: case ErrorConstants.Validation.InvalidBirthday.code: this.$errorBirthday.html(error.description); this.$errorBirthday.show(); break; case ErrorConstants.Validation.EmptyGenderSelected.code: this.$errorGender.html(error.description); this.$errorGender.show(); break; case ErrorConstants.Validation.EmptyEMail.code: case ErrorConstants.Validation.InvalidEMail.code: this.$errorEmail.html(error.description); this.$errorEmail.show(); break; default: this._setSaveStatus(error); break; } }, this); }, _setSaveStatus: function (status) { var prefix; if (status.success) { prefix = "User profile updated successfully. "; this.$saveStatus.removeClass(ErrorStyle); this.$saveStatus.addClass(SuccessStyle); } else { prefix = "User profile update failed. "; this.$saveStatus.removeClass(SuccessStyle); this.$saveStatus.addClass(ErrorStyle); } this.$saveStatus.html(prefix + (status.description ? status.description : "")); this.$saveStatus.show(); }, _onCancel: function () { this.trigger("cancel"); }, _onResend: function () { this._hideErrorsAndStatuses(); if (this.emailChanged) { //todo: refactor this this.dialog.show('alert', 'Please save the updated email before resending invitation'); } else { this.trigger('resend'); } }, _onChangeInput: function (e) { if ($(e.target).hasClass("id-email")) { var email = this.model.userProfile.get("email") || ""; this.emailChanged = email !== this.$email.val(); } this._hideErrorsAndStatuses(); }, _onKeyPress: function (e) { if (e.keyCode === 13) { this._onSave(); } } }); }); <file_sep>define([ 'backbone', 'text!Testing/Templates/TestAudio.html' ], function (Backbone, templateHtml) { 'use strict'; // Container for audio tags used for tests return Backbone.View.extend({ tagName: "div", className: "test-audio", template: _.template(templateHtml), initialize: function () { this.render(); }, render: function () { this.$el.html(this.template()); return this; } }); });<file_sep># Kinetics-Web This directory contains frontend for Kinetics POC project. **DEVELOPMENT HOW-TO** This project is based on Backbone.js MVC framework and uses RequireJS for module loading and resolving dependencies. **RUN LOCALLY** To run application locally clone repository to some folder and point webserver's document root to that folder. **BUILD AND DEPLOY** To build the project you should have [ Node.js ](http://nodejs.org/download/) installed. Navigate to "tools" folder and run the command: `node build [options]` This will create two .war files to deploy. E.g.: - *"build/10-24-2013-2-release/kineticsweb.war"* - *"build/10-24-2013-2-release/ROOT.war"* Available options: * *-d* Build development version (no code optimization) * *-r* Build release version. In this case all sources including stylesheets and templates are concatenated and compressed with "r.js" tool. Use this one to deploy on stage/production environments. *Note: before running build for some environment you have to set API endpoint in "serverUrl" property of "Web/js/DataLayer/Constants.js".*<file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'DataLayer/Constants', 'Controllers/ControllerBase', 'Models/Constants', 'Models/ResetPasswordModel', 'Views/Constants', 'Views/ResetPasswordView', 'Views/ResetPasswordSuccessView', 'Views/ResetPasswordTokenView', 'formatter' ], function ($, _, Constants, DataConstants, ControllerBase, ModelsConstants, ResetPasswordModel, ViewsConstants, ResetPasswordView, ResetPasswordSuccessView, ResetPasswordTokenView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this._checkAttribute("accountManager"); }, parseParams: function (params) { var result = {}; if (params.length > 0) { result.email = params[0]; result.token = params[1]; } return result; }, activate: function (params) { var accountManager = this.get("accountManager"), options = { email: params.email, accountManager: accountManager }; if (params.token) { options.email = $.base64.decode(params.email); options.token = $.base64.decode(params.token); options.finishStep = true; } this.models = { reset: new ResetPasswordModel(options) }; if (params.token) { this.view = new ResetPasswordTokenView({model: this.models}); } else { this.view = new ResetPasswordView({ model: this.models }); } // Start listening control events this.listenTo(accountManager, { "password-reset": function (email) { this.email = email; this._showSuccessView(options.finishStep); } }); // Initialize menu var applicationView = this.get("applicationView"); applicationView.header.showMenu(ViewsConstants.HeaderMenu.Authorization); // Show view applicationView.showView(this.view); }, deactivate: function () { this._reset(); }, _showSuccessView: function (finishStep) { this._reset(); this.view = new ResetPasswordSuccessView({ model: { email: this.email, finishStep: finishStep } }); this.listenTo(this.view, { "navigate-by-link": this._onNavigateByLink }); // Show view var applicationView = this.get("applicationView"); applicationView.showView(this.view); }, _onNavigateByLink: function () { this.trigger("password-reset", this.email); } }); }); <file_sep>/*global define:true */ define([ 'Testing/Models/StateTransitions', 'Testing/Models/TestInstances', 'Testing/Models/TestScreens/TestScreenInstances' ], function (StateTransitions, tests, screens) { 'use strict'; // Declare test session transitions table // Sequence of test: // - Right hand n-m // - Left hand n-m // - Right hand p-q // - Left hand p-q // First and last tests will be detected and marked by TestSession object // on the ground of they definition order in transition table. return function (detailsScreenRequired) { var stateTransitionsTable = [ { stateName: "testDetails", state: screens.testDetailsScreen, transitions: [ { signal: "next", stateName: "rightNMTest" } ] }, { stateName: "rightNMTest", state: tests.rightNMTest, transitions: [ { signal: "next", stateName: "leftNMTest" } ] }, { stateName: "leftNMTest", state: tests.leftNMTest, transitions: [ { signal: "back", stateName: "rightNMTest" }, { signal: "next", stateName: "rightPQTest" } ] }, { stateName: "rightPQTest", state: tests.rightPQTest, transitions: [ { signal: "back", stateName: "leftNMTest" }, { signal: "next", stateName: "leftPQTest" } ] }, { stateName: "leftPQTest", state: tests.leftPQTest, transitions: [ { signal: "back", stateName: "rightPQTest" }, { signal: "next", stateName: "summary" } ] }, { stateName: "summary", state: screens.summaryScreen, transitions: [ { signal: "back", stateName: "leftPQTest" } ] } ]; if (!detailsScreenRequired) { stateTransitionsTable.shift(); } return new StateTransitions(stateTransitionsTable[0].stateName, stateTransitionsTable); }; }); <file_sep>/*global define:true */ define([ 'underscore', 'backbone', 'text!Templates/ConfirmSuccess.html' ], function (_, Backbone, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), events: { "click .id-button-to-account": "_onNavigateByLink" }, initialize: function () { this.listenTo(this.model, { "change:remainedSeconds": this._updateTimer }); }, render: function () { this.$el.html(this.template(this.model.attributes)); this.$remainedSeconds = this.$(".id-remained-seconds"); this.$remainedSecondsPluralEnds = this.$(".id-remained-seconds-ends"); this._updateTimer(this.model, this.model.get("remainedSeconds")); return this; }, _updateTimer: function (model, remainedSeconds) { this.$remainedSeconds.html(remainedSeconds); if (remainedSeconds == 1) { this.$remainedSecondsPluralEnds.hide(); } else { this.$remainedSecondsPluralEnds.show(); } }, _onNavigateByLink: function () { this.model.stop(); // Prevent navigation by hyperlink return false; } }); }); <file_sep>define([ 'Testing/Models/TestScreens/ScreenBase', 'Testing/Models/Constants' ], function (ScreenBase, Constants) { "use strict"; // Helper state that checks exists of current test results and // help to select beginning screen: start/passed/canceled screen. return ScreenBase.extend({ activate: function () { // Call method form base prototype ScreenBase.prototype.activate.call(this); var testResults = this._testContext.get("results"); switch (testResults.get("state")) { case Constants.TestResultState.Passed: this.trigger("signal:passed"); break; case Constants.TestResultState.Canceled: this.trigger("signal:canceled"); break; default: this.trigger("signal:noResults"); break; } }, _checkContext: function () { // Call base implementation ScreenBase.prototype._checkContext.call(this); if (!this._testContext.has("results")) { throw new Error("'results' not specified in the test context."); } if (!this._testProperties.has("testType")) { throw new Error("'testType' not specified in the test properties."); } } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'moment', 'backbone', 'DataLayer/Constants', 'text!Templates/TestRoom.html', 'text!Templates/TestRoomConfirmation.html', 'Views/TestRoomResultRowView', 'Views/PatientInfoView', 'Models/Constants', 'Models/TestSessionResultsRowCollection', 'Utils/Dialog' ], function (_, moment, Backbone, DataLayerConstants, templateHtml, templateConfirmationHtml, TestRoomResultRowView, PatientInfoView, Constants, TestSessionResultsRowCollection, Dialog) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper", template: _.template(templateHtml), templateConfirmation: _.template(templateConfirmationHtml), events: { "click .id-button-start-test": "_onStartTest", "click .all-check": "_onSelectAll", "click .id-button-delete": "_onDeleteSelected", "click .id-button-trend-report": "_onTrendReport", "click .id-button-share-all": "_onShareAll" }, initialize: function (options) { var that = this; if (!this.model && this.model instanceof TestSessionResultsRowCollection) { throw new Error("Model not set or wrong type."); } this._adminMode = options.adminMode; this._ownTestRoom = options.ownTestRoom; this._analystMode = options.analystMode; this.model.readOnly = options.readOnly || false; this._readOnly = options.readOnly || false; this.model.analystMode = this._analystMode; this.model.ownRoom = this._ownTestRoom; this.listenTo(this.model, { "add": this._onAdd, "remove": this._onRemove, "reset": this._onReset }); this._rowViews = {}; this._initializeRowViews(); this.dialog = new Dialog(); this.listenTo(this.dialog, { 'delete-confirmed': function () { that.trigger("delete", that._getSelectedModels()); that._updateNoResultRow(); // Reset "select all" check box if (that.$checkAll.hasClass("checked")) { that.$checkAll.removeClass("checked"); } } }); }, ownTestRoom: function () { return this._ownTestRoom; }, _initializeRowViews: function () { var that = this; _.forEach(this.model.models, function (rowModel) { this._rowViews[rowModel.cid] = new TestRoomResultRowView({ model: rowModel, analystMode: that._analystMode, ownRoom: that._ownTestRoom, readOnly: that._readOnly }); }, this); }, _onAdd: function (rowModel) { var rowView = new TestRoomResultRowView({ model: rowModel }); this._rowViews[rowModel.cid] = rowView; // Because by default results sorted by date new result have to be at first position. // NOTE: If sorting may be changeable by UI then this piece of code should be refactored. this.$headerRow.after(rowView.render().el); this._updateNoResultRow(); }, _onRemove: function (rowModel) { // Find row view by model id var rowView = this._rowViews[rowModel.cid]; // Remove row view from DOM rowView.remove(); // Destroy row view delete this._rowViews[rowModel.cid]; this._updateNoResultRow(); }, _onReset: function () { this._removeAllRowsViews(); this._initializeRowViews(); }, _onSelectAll: function () { this.$checkAll.toggleClass("checked"); var checkedAll = this.$checkAll.hasClass("checked"); _.each(this._rowViews, function (rowView) { rowView.selected(checkedAll); }); }, render: function () { var isAvanir = DataLayerConstants.branding === "Avanir"; this.$el.html(this.template(_.extend(this.model, { _isAvanir: isAvanir }))); this.$checkAll = this.$(".all-check .tick"); this.$resultTable = this.$(".result-table"); this.$headerRow = this.$(".result-header-row"); this.$noResultsRow = this.$(".id-no-results"); this._fillRows(); return this; }, showUserInfo: function (userProfile) { if (userProfile) { // Get container for patient info var headerContainer = this.$(".id-header-container h1"); // Add patient info to container new PatientInfoView({ model: userProfile, analystMode: this._analystMode, showProjects: this.model.get('role') !== Constants.UserRole.SiteAdmin }).embed(headerContainer); } }, _fillRows: function () { _.each(this.model.models, function (rowModel) { var rowView = this._rowViews[rowModel.cid]; this.$resultTable.append(rowView.render().el); }, this); this._updateNoResultRow(); }, _updateNoResultRow: function () { if (this.model.length > 0) { this.$noResultsRow.hide(); } else { this.$noResultsRow.show(); } }, // Remove view from DOM remove: function () { // Destroy row views this._removeAllRowsViews(); // Call base implementation Backbone.View.prototype.remove.call(this); }, // Destroy all row view _removeAllRowsViews: function () { _.each(this._rowViews, function (rowView, key, collection) { rowView.remove(); delete collection[key]; }); }, _onStartTest: function () { this.trigger("start-test"); }, _onShareAll: function () { this.trigger('share-all'); }, _getSelectedModels: function () { var selected = []; _.each(this._rowViews, function (rowView) { if (rowView.selected()) { selected.push(rowView.model); } }); return selected; }, _onDeleteSelected: function () { var selectedModels = this._getSelectedModels(); if (selectedModels.length) { this.dialog.show('confirm', this.templateConfirmation({ moment: moment, selected: selectedModels }), 'delete'); } }, _onTrendReport: function () { this.trigger("trend-report"); }, hide: function () { this.$el.hide(); }, show: function () { this.$el.show(); } }); }); <file_sep>/*global define:true */ define([ 'moment', 'DataLayer/Constants' ], function (moment, DataConstants) { "use strict"; var Constants = { CurrentUserIdMarker: "CurrentUser", UserStatus: { Active: "ACTIVE", Disabled: "DISABLED", WaitingConfirmation: "WAITING_CONFIRMATION", Waiting: 'WAITING_PASS' }, ProjectStatus: { Active: 'ACTIVE', Disabled: 'DISABLED' }, TestSessionType: { Keyboard: "kb", TUG: "TUG", PST: "PST" }, Gender: { Male: "MALE", Female: "FEMALE" }, EmailPattern: /[a-zA-Z0-9\+\.\_\%\-\+]{1,256}\@[a-zA-Z0-9][a-zA-Z0-9\-]{0,64}(\.[a-zA-Z0-9][a-zA-Z0-9\-]{0,25})+/, FullDayOffset: moment.duration({ hours: 23, minutes: 59, seconds: 59 }), UserListSearchToken: { Name: "name", Email: "email", UID: "uid", Summary: "summary" }, UserRole: { Analyst: "analyst", Patient: "patient", SiteAdmin: "site_admin" }, UserRoleId: {}, CustomFields: { List: "LIST", Numeric: "NUMERIC", Required: "REQUIRED" }, CustomLabels: { 'Avanir': { 'First Name': 'Subject Initials', 'first name': 'subject initials', 'Last Name': 'Subject ID', 'last name': 'subject ID', 'Project': 'Site ID', 'project': 'site', 'Project list': 'Site list', 'Current Project': 'Current Site', 'Projects': 'Sites', 'projects': 'sites', 'Create project': 'Create site', 'new Project': 'new Site', 'Project Name': 'Site ID', 'project name': 'site ID', 'Not Applicable': 'Not Applicable', 'Name': 'Name/Subject ID', 'by name': 'by name/subject ID', 'NAME': 'NAME/SUBJECT ID' }, 'default': { 'Not Applicable': '' } }, customLabel: function (label) { var project = DataConstants.branding; return Constants.CustomLabels[project] && Constants.CustomLabels[project][label] ? Constants.CustomLabels[project][label] : Constants.CustomLabels['default'][label] || label; } }; Constants.TestSessionTypeCaptions = {}; Constants.TestSessionTypeCaptions[Constants.TestSessionType.Keyboard] = "Keyboard"; Constants.TestSessionTypeCaptions[Constants.TestSessionType.TUG] = "Timed Up and Go (TUG)"; Constants.TestSessionTypeCaptions[Constants.TestSessionType.PST] = "Postural Sway tests (PST)"; Constants.UserStatusCaptions = {}; Constants.UserStatusCaptions[Constants.UserStatus.Active] = "Active"; Constants.UserStatusCaptions[Constants.UserStatus.Disabled] = "Inactive"; Constants.UserStatusCaptions[Constants.UserStatus.WaitingConfirmation] = "Not confirmed"; Constants.UserStatusCaptions[Constants.UserStatus.Waiting] = "Waiting"; Constants.GenderCaptions = {}; Constants.GenderCaptions[Constants.Gender.Male] = "Male"; Constants.GenderCaptions[Constants.Gender.Female] = "Female"; return Constants; });<file_sep>define([ 'backbone', 'Testing/Models/TestContext' ], function (Backbone, TestContext) { 'use strict'; var TestDetailsScreen = Backbone.Model.extend({ defaults: { // Indicate to TestSession instance that screen aggregate testing results and // test session results have to be provided aggregator: true }, initialize: function () { // Creates test context for TestSession object be able to provide test results this.set("context", new TestContext()); }, activate: function () { }, continuePressed: function () { this.trigger("signal:next"); } }); return TestDetailsScreen; }); <file_sep>define([ 'Testing/Views/ScreenViewBase' ], function (ScreenViewBase) { 'use strict'; var TestEndsScreenViewBase = ScreenViewBase.extend({ events: { "click .id-button-back": "_onBack", "click .id-button-repeat": "_onRepeat", "click .id-button-next": "_onNext" }, render: function () { ScreenViewBase.prototype.render.call(this); // Hide Back button for first test if (this._testContext) { if (this._testContext.get("firstTest")) { this.$(".id-button-back").addClass('hidden'); } } }, _onBack: function () { this.model.backPressed(); }, _onRepeat: function () { this.model.repeatPressed(); }, _onNext: function () { this.model.nextPressed(); } }); return TestEndsScreenViewBase; }); <file_sep>define([ 'Testing/Models/TestScreens/TestingScreenBase', 'Testing/Models/TimeCalculation' ], function (TestingScreenBase, TimeCalculation) { 'use strict'; var TestingPQScreen = TestingScreenBase.extend({ defaults: { "remainedPresses": -1 }, _startTime: null, _expectedKeySet: ["p", "q"], activate: function () { // Call method form base prototype TestingScreenBase.prototype.activate.call(this); this._expextedPresses = this._testProperties.get("pqTestCountOfExpectedCorrectPresses"); this.set("remainedPresses", this._expextedPresses); this._startTime = new Date(); }, _checkContext: function () { // Call method form base prototype TestingScreenBase.prototype._checkContext.call(this); if (!this._testProperties.has("pqTestCountOfExpectedCorrectPresses")) { throw new Error("'pqTestCountOfExpectedCorrectPresses' not specified in the test properties."); } }, _tick: function () { var spentTime = this._calculateSpentTime(); this._testResults.set("spentTime", spentTime); }, _testPassed: function () { // Save last value of spent time in results var spentTime = this._calculateSpentTime(); this._testResults.set("spentTime", spentTime); TestingScreenBase.prototype._testPassed.call(this); }, _calculateSpentTime: function () { var spentTicks = (new Date()) - this._startTime; return TimeCalculation.getTimeSpan(spentTicks); }, _expectedKeyPressed: function () { // Decrement remained correct presses counter var remainedPresses = this.get("remainedPresses"); this.set("remainedPresses", --remainedPresses); // Set key presses counter this._testResults.set("keyPresses", this._expextedPresses - remainedPresses); var percentsDone = 100 - (remainedPresses / this._expextedPresses * 100); this.set("percentsDone", percentsDone); if (remainedPresses <= 0) { this._testPassed(); } else { this._toggleExpectedKey(); } } }); return TestingPQScreen; }); <file_sep>/*global define:true */ define([ 'jQuery', 'underscore', 'backbone', 'Views/Constants', 'Models/Constants', 'Models/Extension', 'Models/ErrorConstants', 'Utils/Dialog', 'text!Templates/TestCustomFields.html', 'jQuery.placeholder', 'formatter' ], function ($, _, Backbone, Constants, ModelsConstants, Extension, ErrorConstants, Dialog, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "content-wrapper test-custom-fields", template: _.template(templateHtml), events: { "click .id-add-new-question": "_triggerViews", "click .id-cancel-adding": "_onCancel", "click .id-save-new-question": "_createField", "keydown #question-label": "_createFieldOnEnter", "click .remove-custom-field": "_removeField", "click .editable-label-id": "_editLabel", "click .editable-options-id": "_editList", "change .required-checkbox": "_saveRequired" }, initialize: function (params) { var that = this; this.accountManager = params.accountManager; this.dialog = new Dialog(); this.listenTo(this.dialog, { 'remove-confirmed': function () { var field = that.model._byId[that._removeId]; if (field) { field.destroy({accountManager: that.accountManager}); } this.render(); } }); }, render: function () { this.$el.html(this.template()); this.$questionsList = this.$('.questions-list'); this.$questionsListContainer = this.$questionsList.find('.content-container'); //Add new custom field Form part this.$addNewQuestionForm = this.$('.add-new-question-form'); this.$questionLabel = this.$addNewQuestionForm.find('.id-question-label'); this.$questionType = this.$addNewQuestionForm.find('.id-question-type'); this.$isRequiredQuestion = this.$addNewQuestionForm.find('.id-question-required'); this.$optionsListRow = this.$addNewQuestionForm.find('.options-list-row'); this.$optionsListInput = this.$optionsListRow.find('.id-options-list'); this.$optionsListDemo = this.$optionsListRow.find('.id-options-list-demo'); this.$validationErrors = this.$addNewQuestionForm.find('.validationErrors'); var $optionsListRow = this.$optionsListRow; this.$questionType.change(function () { if ($(this).val() === 'list') { $optionsListRow.show(); } else { $optionsListRow.hide(); } }); var $optionsListDemo = this.$optionsListDemo; this.$optionsListInput.keyup(function () { var optionsList = $.trim($(this).val()).split(';'); $optionsListDemo.empty(); _.each(optionsList, function (e) { e = $.trim(e); if (e !== '') { $optionsListDemo.append('<option>' + e + '</option>'); } }); }); //custom fields list part this.$noCustomFields = this.$questionsList.find('.no-fields'); this.$customFieldsTable = this.$questionsList.find('.fields-table'); if (this.model.length) { var self = this; _.each(this.model.models, function (customFieldModel) { self.$customFieldsTable.append(customFieldModel.getHtml(true)); }); } else { this.$noCustomFields.show(); this.$customFieldsTable.hide(); } return this; }, _onCancel: function () { this._triggerViews(); this._resetAddForm(); }, _triggerViews: function () { this.$questionsList.toggle(); this.$addNewQuestionForm.toggle(); }, _createField: function () { if (!this._isAddFormValid()) { this.$validationErrors.text("Please fill all required fields"); } else { var model = new Extension(); var listData = this.$optionsListInput.val().split(";"); model.set("name", this.$questionLabel.val()); model.set("entity", "TEST_SESSION"); model.set("type", this.$questionType.val().toUpperCase()); if (this.$isRequiredQuestion.attr("checked")) { model.set("properties", ["REQUIRED"]); } else { model.set("properties", []); } model.set("listdata", listData); var fn = _.bind(this._successCallback, this), er = _.bind(this._errorCallback, this); if (this.$questionType.val() !== "list") { model.sync("createSimpleExtension", model, {accountManager: this.accountManager, success: fn, error: er}); } else { model.sync("createListExtension", model, {accountManager: this.accountManager, success: fn, error: er}); } } }, _createFieldOnEnter: function (e) { if (e.keyCode === 13) { this._createField(); } }, _successCallback: function () { var fn = _.bind(this._successRender, this); this.model.fetch({accountManager: this.accountManager, success: fn}); }, _errorCallback: function (model, xhr, options) { this.$validationErrors.text(options.responseError.description); }, _successRender: function () { this.render(); }, _removeField: function (e) { this._removeId = $(e.target).attr('data-field-id'); this.dialog.show('confirm', 'Remove this field?', 'remove'); }, _saveRequired: function (e) { var cmp = $(e.currentTarget), id = cmp.attr('data-field-id'), field = this.model._byId[id], fn = _.bind(this._saveCheckBoxSuccess, cmp), er = _.bind(this._saveCheckBoxError, cmp), props = _.without(field.get("properties"), "REQUIRED"); if (cmp.attr("checked")) { props.push("REQUIRED"); } field.set("properties", props); cmp.attr("disabled", true); field.sync("changeProperties", field, {accountManager: this.accountManager, success: fn, error: er}); }, _saveCheckBoxSuccess: function () { this.attr("disabled", false); }, _saveCheckBoxError: function () { this.attr("disabled", false); this.attr("checked", !this.attr("checked")); }, _resetAddForm: function () { this.$questionLabel.val(""); this.$questionType.val("numeric"); this.$isRequiredQuestion.attr("checked", false); this.$optionsListInput.val(""); this.$optionsListRow.hide(); $("option", this.$optionsListDemo).remove(); this.$validationErrors.text(""); }, _isAddFormValid: function () { var isLabelValid = this.$questionLabel.val() !== "", areOptionsValid = this.$optionsListInput.val() !== "", questionType = this.$questionType.val(), isFormValid = isLabelValid; if (questionType === "list") { isFormValid = isLabelValid && areOptionsValid; } return isFormValid; }, _editLabel: function (e) { var cell = $(e.target), originalValue = cell.text(), id = cell.attr('data-field-id'), record = this.model._byId[id], am = this.accountManager; var fn = (function (e) { return function (e) { var newValue = $("input", cell).val(), isSaveTriggered = e.keyCode === 13, isRestoreTriggered = e.keyCode === 27; if (isRestoreTriggered) { cell.html(originalValue); } else if (isSaveTriggered) { if (newValue === "") { return; } if (originalValue !== newValue) { var er = (function () { return function () { cell.html(originalValue); }; })(); record.set("name", newValue); record.sync("modifyExtensionName", record, {accountManager: am, error: er}); } cell.html(newValue); } }; })(); var blurFn = (function () { return function () { cell.html(originalValue); }; })(); cell.text("").append($('<input>', { value: originalValue, blur: blurFn, keydown: fn })); $("input", cell).focus().select(); }, _editList: function (e) { var cell = $(e.target), originalValue = cell.text(), id = cell.attr('data-field-id'), record = this.model._byId[id], am = this.accountManager; var fn = (function (e) { return function (e) { var newValue = $("input", cell).val(), isSaveTriggered = e.keyCode === 13, isRestoreTriggered = e.keyCode === 27; if (isRestoreTriggered) { cell.html(originalValue); } else if (isSaveTriggered) { if (newValue === "") { return; } if (originalValue !== newValue) { var er = (function () { return function () { cell.html(originalValue); }; })(); record.set("list", newValue.split(";")); record.sync("changeList", record, {accountManager: am, error: er}); } cell.html(newValue); } }; })(); var blurFn = (function () { return function () { cell.html(originalValue); }; })(); cell.text("").append($('<input>', { value: originalValue, blur: blurFn, keydown: fn, style: 'width: 95%' })); $("input", cell).focus().select(); } }); }); <file_sep>/*global define: true */ define([ 'moment', 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants', 'DataLayer/Constants', 'DataLayer/ModelSyncExtension', 'DataLayer/ServerInteractionSerializersHash', 'DataLayer/ServerCommandExecutor', 'Utils/StringExtensions' ], function (moment, Backbone, _, Constants, ErrorConstants, DataConstants, ModelSyncExtension, ServerInteractionSerializersHash, ServerCommandExecutor, StringExtensions) { 'use strict'; return Backbone.Model.extend({ defaults: { from: null, to: null, fromFormatted: null, toFormatted: null }, initialize: function () { this.on({ "change:fromFormatted": this._updateFrom, "change:toFormatted": this._updateTo }); }, _updateFrom: function () { var fromFormatted = this.get("fromFormatted"); if (fromFormatted) { var from = moment(fromFormatted); if (from.isValid()) { this.set("from", from.valueOf()); } } }, _updateTo: function () { var toFormatted = this.get("toFormatted"); if (toFormatted) { var to = moment(toFormatted); if (to.isValid()) { this.set("to", to.valueOf() + 24 * 60 * 60 * 1000); } } }, validate: function (attrs, options) { options = options || {}; var errors = [], from, to; if (StringExtensions.isTrimmedEmpty(attrs.fromFormatted)) { errors.push(ErrorConstants.Validation.EmptyFromDate); } else { from = moment(attrs.fromFormatted, "MM/DD/YYYY"); if (!from.isValid()) { errors.push(ErrorConstants.Validation.InvalidFromDate); } } if (StringExtensions.isTrimmedEmpty(attrs.toFormatted)) { errors.push(ErrorConstants.Validation.EmptyToDate); } else { to = moment(attrs.toFormatted, "MM/DD/YYYY"); if (!to.isValid()) { errors.push(ErrorConstants.Validation.InvalidToDate); } if (to.valueOf() > $.now().valueOf()) { errors.push(ErrorConstants.Validation.InvalidFutureDate); } } if (from && to && from.isValid() && to.isValid() && (from.valueOf() > to.valueOf())) { errors.push(ErrorConstants.Validation.MismatchedDates); } if (errors.length > 0) { return errors; } }, toJSON: function (options) { var result = Backbone.Model.prototype.toJSON.call(this, options); if (options.local) { result = _.pick(result, "from", "to" ); } return result; }, export: function (accountManager) { var that = this, parsedResponse = [], size = 500, pages = 1, pagesLeft = 0; ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.TestSessionManager.getTestsForExportCount, { accountManager: accountManager, sessionToken: accountManager.getSessionToken(), from: this.get('from'), to: this.get('to'), success: function (model, records) { that.trigger('export-download-progress', 10); if (records > size) { pages = Math.floor(records / size); if (records % size) { pages += 1; } size = Math.ceil(records / pages); } pagesLeft = pages; downloadChunk(); that.listenTo(that, {'cancelExport': function () { pagesLeft = 0; }}); }, error: null }); function downloadChunk() { ServerCommandExecutor.execute(that, ServerInteractionSerializersHash.TestSessionManager.getTestsForExport, { accountManager: accountManager, sessionToken: accountManager.getSessionToken(), from: that.get('from'), to: that.get('to'), page: pages - pagesLeft--, size: size, noLogging: true, success: function (model, data) { _.each(data, function (e) { var session = { subjectId: e.secondName, compositeScore: parseFloat(e.score).toFixed(2), assessmentDate: moment(e.creationDate).format('MM/DD/YYYY'), assessmentTime: moment(e.creationDate).format('HH:mm') }; _.each(e.extension, function (e) { switch (e.name.toLowerCase()) { case 'visit': session.visit = e.value; break; case 'planned time point': session.timePoint = e.value; break; } }); var testResultsCollection = JSON.parse(e.rawData.replace(/&quot;/g, '"')).testResultsCollection; _.each(testResultsCollection, function (e) { session[e.testTag + 'Score'] = e.score && e.score.toFixed(2); session[e.testTag + 'KeyPresses'] = e.keyPresses; session[e.testTag + 'Time'] = e.spentTime && Math.round(e.spentTime.totalSeconds); session[e.testTag + 'Inaccurate'] = - e.keyPresses; _.each(e.raw, function (k) { session[e.testTag + 'Inaccurate'] += k.down ? k.down.length : 0; }); }); parsedResponse.push(session); }); if (pagesLeft === 0) { that.trigger('export-data-ready', parsedResponse, 'Export_' + that.get('fromFormatted') + '-' + that.get('toFormatted') + '.csv'); parsedResponse = undefined; } else { that.trigger('export-download-progress', 10 + 90 * (pages - pagesLeft) / pages); downloadChunk(); } data = undefined; }, error: null }); } }, getAuditEvents: function (options) { ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.AuditManager.getAuditEvents, { accountManager: options.accountManager, sessionToken: options.accountManager.getSessionToken(), success: options.success }); }, getAuditData: function (accountManager) { var that = this; ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.AuditManager.getAuditData, { accountManager: accountManager, sessionToken: accountManager.getSessionToken(), from: this.get('from'), to: this.get('to'), eventType: this.get('type'), success: function (model, data, options) { that.trigger('analytics-received', data); } }); } }); }); <file_sep>define([ 'backbone', 'Testing/Models/TestResultsCollection', 'Testing/Models/Constants' ], function (Backbone, TestResultsCollection, Constants) { 'use strict'; var TestSessionResults = Backbone.Model.extend({ defaults: { testResultsCollection: null, navigator: {}, createDate: null, totalScore: 0, extension: [], notes: "", valid: true }, parse: function (resp, options) { var resp = Backbone.Model.prototype.parse.call(this, resp, options); resp.testResultsCollection = new TestResultsCollection(resp.testResultsCollection); return resp; }, toJSON: function () { var json = { testResultsCollection: this.get("testResultsCollection").toJSON() }; return json; }, initialize: function () { var testResultsCollection = this.get("testResultsCollection"); if (!testResultsCollection || !(testResultsCollection instanceof TestResultsCollection)) { this.set("testResultsCollection", new TestResultsCollection()); } }, passedTests: function () { var returnValue = ""; var testResultsCollection = this.get("testResultsCollection"); if (testResultsCollection) { _.each(testResultsCollection.models, function (testResults) { if (testResults.get("state") == Constants.TestResultState.Passed) { if (returnValue.length > 0) returnValue += " "; returnValue += testResults.get("testTag"); } }) } return returnValue; } }); return TestSessionResults; }); <file_sep>/*global define:true, confirm: true */ define([ 'underscore', 'backbone', 'moment', 'text!Templates/UserListBlockConfirmation.html', 'text!Templates/UserProjectManage.html', 'text!Templates/ManageProjects.html', 'Models/Constants', 'Models/UserProfileCollection', 'Views/UserListRowView' ], function (_, Backbone, moment, blockConfirmationHtml, UserProjectManageHtml, manageProjectsHtml, ModelsConstants, UserProfileCollection, UserListRowView) { 'use strict'; var SuccessStyle = "sign-row-success"; var ErrorStyle = "sign-row-error"; return Backbone.View.extend({ tagName: "div", className: "content-wrapper user-list manage", templateConfirmation: _.template(blockConfirmationHtml), templateManageProjects: _.template(manageProjectsHtml), projectManage: null, currentModel: null, events: { "click .id-button-create-user": function () { this.trigger('create-user'); }, 'click .id-button-add-users': function () { this.trigger('add-users'); }, 'click .id-reset': '_resetAssignments', 'click .id-save-changes': '_onSaveAssignments', 'change .id-project-selector': '_onProjectSwitched' }, initialize: function (options) { if (!this.model && this.model instanceof UserProfileCollection) { throw new Error("Model not set or wrong type."); } this.listenTo(this.model, { "reset": this._onReset }); this.listenTo(this, { /* 'assignment-changed': function () { this.$('.save-or-reset').slideDown(); }, 'assignments-saved': function () { this.$('.save-or-reset').slideUp(); } */ }); this._manage = options.manage; this._newProject = options.newProject; this._searchText = options.searchText; this._siteAdminMode = options.siteAdminMode; this._projects = options.projects; this._rowViews = {}; }, _initializeRowViews: function () { _.forEach(this.model.models, function (rowModel) { this._rowViews[rowModel.cid] = new UserListRowView({ model: rowModel, siteAdminMode: this._siteAdminMode, manage: this._manage }); }, this); }, _resetAssignments: function () { this.trigger('reset-assignments'); this._onReset(); //this.$('.save-or-reset').slideUp(); }, _onReset: function () { //filter site admins from view; this is a hack and should be done on serer side this.model.models = _.reject(this.model.models, function (model) { return model.attributes.roles && model.attributes.roles[0].name.toLowerCase() === ModelsConstants.UserRole.SiteAdmin; }); this._removeAllRowsViews(); this._initializeRowViews(); this._fillRows(); }, render: function () { var projects = this._projects .sortBy(function (project) { return project.get("name"); }, this) .map(function (project) { return { id: project.get("id"), name: project.get("name") }; }); var view = this.templateManageProjects({ model: this.model, Constants: ModelsConstants, siteAdminMode: this._siteAdminMode, newProject: this._newProject, currentProject: this._manage, projects: projects }); this.$el.html(view); this.$checkAll = this.$(".all-check .tick"); this.$resultTable = this.$(".result-table"); this.$headerRow = this.$(".result-header-row"); this.$noResultsRow = this.$(".id-no-results"); this.$projectSelector = this.$(".id-project-selector"); return this; }, _onProjectSwitched: function () { this.trigger('project-switched', this.$projectSelector.val()); }, _onSaveAssignments: function () { this.trigger('save-assignments'); }, _fillRows: function () { this.model.backup = _.rest(this.model.models, 0); var that = this, fit = [], unfit = []; _.each(this.model.models, function (m) { if (!_.where(m.get('project'), {id: that._manage}).length) { unfit.push(m); } else { fit.push(m.get('id')); } }); _.each(unfit, function (m) { that.model.remove(m); }); //send fit to store in controller this.trigger('project-user-list', fit); _.each(this.model.models, function (rowModel) { var rowView = this._rowViews[rowModel.cid]; this.$resultTable.append(rowView.render().el); }, this); this._updateNoResultRow(); }, _updateNoResultRow: function () { if (this.model.models.length > 0) { this.$noResultsRow.hide(); } else { this.$noResultsRow.show(); } }, // Remove view from DOM remove: function () { // Destroy row views this._removeAllRowsViews(); // Call base implementation Backbone.View.prototype.remove.call(this); }, // Destroy all row view _removeAllRowsViews: function () { _.each(this._rowViews, function (rowView, key, collection) { rowView.remove(); delete collection[key]; }); }, hide: function () { this.$el.hide(); }, show: function () { this.$el.show(); } }); });<file_sep>/*global define:true */ define([ 'underscore', 'Testing/Views/ScreenViewBase', 'text!Testing/Templates/TestDetailsScreen.html' ], function (_, ScreenViewBase, templateHtml) { 'use strict'; return ScreenViewBase.extend({ template: _.template(templateHtml), events: { "click .id-button-continue": "_onSubmit", "keypress .customField": "_submitOnEnter" }, render: function () { // Call base implementation ScreenViewBase.prototype.render.call(this); this.$contentContainer = this.$('.content-container'); }, // Overridden for initial UI update by model attributes _onActivated: function () { // Call base implementation ScreenViewBase.prototype._onActivated.call(this); var customFields = this.model.get('customFields'); var self = this; _.each(customFields.models, function (customFieldModel) { self.$contentContainer.append(customFieldModel.getHtml()); }); this.$contentContainer.append("<div class='validationErrors'></div>"); }, _onSubmit: function () { var errorMessages = [], inputs = $("input, select", this.$el), fn = this._isInvalidInput, result = false; inputs.each(function (index, input) { result = fn(input); if (result) { errorMessages.push(result); } }); if (errorMessages.length === 0) { this.model.get('sessionResults').set("extension", this._getCustomFields()); this.model.continuePressed(); } else { $(".validationErrors", this.$el).empty().append(errorMessages.join("<br/>")); } }, _submitOnEnter: function (e) { if (e.keyCode === 13) { this._onSubmit(); } }, _isInvalidInput: function (input) { if ($(input).attr("required") && ($.trim(input.value) === "" || input.value === "(None)")) { return ["Please fill '", input.id, "' field"].join(""); } if ($(input).attr("type") === "number" && isNaN(parseFloat(input.value)) && !isFinite(input.value)) { return ["Please type numeric value into '", input.id, "' field"].join(""); } }, _getCustomFields: function () { var results = []; $(".customField", this.$el).each(function (index, field) { results.push( { "name": field.id, "metaId": $(field).attr("data-field-id"), "value": $.trim(field.value) } ); }); return results; } }); }); <file_sep>/*global define: true */ define([ 'jQuery', 'moment', 'backbone', 'underscore', 'Models/Constants', 'Models/ErrorConstants', 'DataLayer/ModelSyncExtension', 'DataLayer/Constants', 'DataLayer/ServerInteractionSerializersHash', 'Utils/StringExtensions', 'backbone.localStorage' ], function ($, moment, Backbone, _, Constants, ErrorConstants, ModelSyncExtension, DataConstants, ServerInteractionSerializersHash, StringExtensions) { 'use strict'; var UserProfile = Backbone.Model.extend({ defaults: { sessionToken: null, email: null, firstName: null, secondName: null, birthdayFormatted: null, birthday: null, gender: null }, localStorage: new Backbone.LocalStorage("kinetics-UserProfile"), initialize: function () { this._updateBirthdayUIFields(this.get("birthday")); this.on({ "change: birthday": this._updateBirthdayUIFields, "change: birthdayFormatted": this._updateBirthday }); }, _updateBirthdayUIFields: function (model, birthday) { if (birthday) { var m = moment(birthday); this.set("birthdayFormatted", m.format("MM/DD/YYYY")); } }, _updateBirthday: function () { var birthdayFormatted = this.get("birthdayFormatted"); if (birthdayFormatted) { var birthday = moment(birthdayFormatted); if (birthday.isValid()) { this.set("birthday", birthday.format('YYYY-MM-DD')); } } }, validate: function (attrs, options) { options = options || {}; var errors = []; if (!StringExtensions.isTrimmedEmpty(attrs.email) && !attrs.email.match(Constants.EmailPattern)) { errors.push(ErrorConstants.Validation.InvalidEMail); } if (StringExtensions.isTrimmedEmpty(attrs.firstName)) { errors.push(ErrorConstants.Validation.EmptyFirstName); } if (StringExtensions.isTrimmedEmpty(attrs.secondName)) { errors.push(ErrorConstants.Validation.EmptySecondName); } if (options.birthdayRequired) { if (StringExtensions.isTrimmedEmpty(attrs.birthdayFormatted)) { errors.push(ErrorConstants.Validation.EmptyBirthday); } else { var birthdayDate = moment(attrs.birthdayFormatted, "MM/DD/YYYY"); if (!birthdayDate.isValid()) { errors.push(ErrorConstants.Validation.InvalidBirthday); } else { var age = (new Date()).getFullYear() - birthdayDate.year(); //birthdayYear = birthdayDate.year() if (age < 1 || age > 150) { errors.push(ErrorConstants.Validation.InvalidBirthday); } } } } if (options.passwordRequired) { if (StringExtensions.isEmpty(attrs.password)) { errors.push(ErrorConstants.Validation.EmptyPassword); } if (attrs.password !== attrs.passwordConfirmation) { errors.push(ErrorConstants.Validation.InvalidPasswordConfirmation); } } if (options.genderRequired && !attrs.gender) { errors.push(ErrorConstants.Validation.EmptyGenderSelected); } if (errors.length > 0) { return errors; } }, toJSON: function (options) { this._updateBirthday(); var result = Backbone.Model.prototype.toJSON.call(this, options); if (options.local) { result = _.pick(result, "email", "firstName", "secondName", "birthday", "gender" ); } return result; }, _checkUserRole: function () { // TODO: Support multiple roles? var that = this; _.each(this.get("roles"), function (role) { that.set('role', role.name.toLowerCase()); }); } }); // Extend instance with server command to get/update information only for current user ModelSyncExtension.extend(UserProfile.prototype, { create: ServerInteractionSerializersHash.AccountManager.createPatient }); return UserProfile; });<file_sep>define(function () { return { // Round to nearby lower multiple of base floorInBase: function (n, base) { return base * Math.floor(n / base); }, // Round to nearby upper multiple of base ceilInBase: function (n, base) { return base * Math.ceil(n / base); }, getPrecision: function (number) { var precision = 0; number = Math.abs(number); if (number < 1 && number > 0) { precision = 0; while (Math.floor(number *= 10) == 0) { precision++; } } return precision; } }; }); <file_sep>/*global define: true */ define([ 'backbone', 'DataLayer/ServerCommandExecutor', 'DataLayer/ServerInteractionSerializersHash', 'Utils/StringExtensions', 'Utils/Dialog' ], function (Backbone, ServerCommandExecutor, ServerInteractionSerializersHash, StringExtensions, Dialog) { 'use strict'; return Backbone.Model.extend({ defaults: { accountManager: null, project: null }, projectsList: [], initialize: function () { if (this.has("accountManager")) { throw new Error("An 'accountManager' not set."); } this.dialog = new Dialog(); }, // Change the password of current user changeProject: function (options) { var that = this; var success = options.success; options.success = function (model, resp, options) { that.trigger("success"); that._resetFields(); if (success) success(model, resp, options); }; var error = options.error; options.error = function (model, xhr, options) { that.trigger("error", options.responseError); that._resetFields(); if (error) error(model, xhr, options); }; ServerCommandExecutor.execute(this, ServerInteractionSerializersHash.ProjectManager.changeProjects, options); }, _resetFields: function () { //todo: clear fields // this.trigger("resetFields"); } }); }); <file_sep>define([ 'backbone', 'Testing/Models/TestContext', 'Testing/Models/StateMachine', 'Utils/ConsoleStub' ], function (Backbone, TestContext, StateMachine) { var Test = Backbone.Model.extend({ defaults: { context: null }, initialize: function (attributes, options, testProperties, screenTransitions) { var testContext = new TestContext(); testContext.set("properties", testProperties); this.set("context", testContext); this.screenTransitions = screenTransitions; // Create state machine for test that will switch test screens this._stateMachine = new StateMachine(null, null, this.screenTransitions); // Bind event handlers this._stateMachine.on({ "out_signal:back": this._onBack, "out_signal:next": this._onNext }, this); }, activate: function () { // Change test context attributes to actual for current test this._changeContext(false); // Start state machine (execute logic of first of last state screen, // bind event handlers to this state screen) this._stateMachine.start(true); }, deactivate: function () { // Stop state machine (unbinds all event handlers for current screen) this._stateMachine.stop(); // Reset test context for save consistency state this._changeContext(true); }, // Change test context to context of current test for all screens _changeContext: function (reset) { var testContext = reset ? null : this.get("context"); // Set test context to all test screens for (var i = 0; i < this.screenTransitions.table.length; i++) { var screen = this.screenTransitions.table[i].state; screen.set("testContext", testContext); } }, _onBack: function () { console.log("Test._onBack()"); // Retransmits event this.trigger("signal:back"); }, _onNext: function () { console.log("Test._onNext()"); // Retransmits event this.trigger("signal:next"); } }); return Test; });<file_sep>/*global define: true */ define([ 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'DataLayer/ErrorConstants', 'Views/Constants', 'Models/Constants', 'Views/InfoView', 'formatter' ], function (_, Constants, ControllerBase, ErrorConstants, ViewsConstants, ModelsConstants, InfoView) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); this._checkAttribute("applicationView"); this.validPages = ["privacy-policy", "terms-of-service", "eula"]; }, parseParams: function (params) { var result = {}; if (params.length > 0) { result.page = params[0]; } return result; }, activate: function (params) { if (_.indexOf(this.validPages, params.page) >= 0) { var accountManager = this.get("accountManager"); this.view = new InfoView({ page: params.page }); this.listenTo(this.view, { }); // Initialize menu var applicationView = this.get("applicationView"); //get user role and show proper menu var role = this.get("accountManager").get("currentUser") && this.get("accountManager").get("currentUser").get("role"); switch (role) { case ModelsConstants.UserRole.Patient: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Patient); break; case ModelsConstants.UserRole.Analyst: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Analyst); break; case ModelsConstants.UserRole.SiteAdmin: applicationView.header.showMenu(ViewsConstants.HeaderMenu.SiteAdmin); break; default: applicationView.header.showMenu(ViewsConstants.HeaderMenu.Authorization); } // Show view applicationView.showView(this.view); } else { this.trigger("wrongPage"); } }, deactivate: function () { this._reset(); } }); }); <file_sep><% if (!readOnly) { %> <div class="result-col test-checkbox"> <div class="tick"></div> </div> <% } %> <div class="result-col test-date"> <%= moment(model.get("creationDate")).format("L LT") %> </div> <div class="result-col test-taken"> <%= model.getTestTaken() %> </div> <div class="result-col test-score"> <%= (+model.get("score")).toFixed(2) %> </div> <div class="result-col test-valid test-valid-ro id-valid"> <div class="tick"></div> </div> <% if (ownRoom) { %> <% if (isAvanir) { %> <div class="result-col test-detail"></div> <% } %> <div class="result-col test-detail"> <button class="button button-detail id-button-detail">DETAIL</button> </div> <% if (!isAvanir) { %> <div class="result-col test-detail"> <button class="button button-detail id-button-share">SHARE</button> </div> <% } %> <% } else { %> <div class="result-col test-detail"></div> <div class="result-col test-detail"> <button class="button button-detail id-button-detail">DETAIL</button> </div> <% } %> <file_sep>/*global define: true */ define([ 'underscore', 'Testing/Models/TestScreens/ScreenBase', 'Utils/TimerManager', 'Testing/Models/TimeCalculation', 'Testing/Models/Constants', 'Utils/AudioHelper', 'Utils/ConsoleStub', 'formatter' ], function (_, ScreenBase, TimerManager, TimeCalculation, Constants, sound) { 'use strict'; var clearObject = function (obj) { for (var key in obj) { delete obj[key]; } }; return ScreenBase.extend({ defaults: { "expectedKey": null, "started": false, "percentsDone": -1 }, initialize: function () { /*attributes, options*/ this._timerManager = new TimerManager(this._tick.bind(this), 1000); }, activate: function () { // Call method form base prototype ScreenBase.prototype.activate.call(this); // Reset test results // NOTE: It should trigger test dexterity score calculation this._testResults.set({ "spentTime": TimeCalculation.getTimeSpan(0), "keyPresses": 0 }); // Set flag to passing // NOTE: It should trigger total dexterity score calculation this._testResults.set("state", Constants.TestResultState.Passing); // Set or clear raw data array if (this._testResults.has("raw")) { clearObject(this._testResults.get("raw")); } else { this._testResults.set("raw", {}); } this.set("percentsDone", 0); this._initializeExpectedKey(); this._timerManager.startTimer(); this.set("started", true); }, deactivate: function () { this._timerManager.stopTimer(); this.set("started", false); // Call base implementation ScreenBase.prototype.deactivate.call(this); this._testResults = null; }, stopPressed: function () { this._timerManager.stopTimer(); this.set("started", false); this._testResults.set("state", Constants.TestResultState.Canceled); this.trigger("signal:stop"); }, _checkContext: function () { // Call base implementation ScreenBase.prototype._checkContext.call(this); this._testResults = this._testContext.get("results"); if (!this._testResults) { throw new Error("Test result not specified in current test context."); } }, // Array of two expected key // Should be overridden in child prototypes _expectedKeySet: [], // Initialize first expected key as first key from set _initializeExpectedKey: function () { this.set("expectedKey", null); }, // Toggle expected key _toggleExpectedKey: function () { switch (this.get("expectedKey")) { case this._expectedKeySet[0]: this.set("expectedKey", this._expectedKeySet[1]); break; case this._expectedKeySet[1]: this.set("expectedKey", this._expectedKeySet[0]); break; default: throw new Error("Invalid value of attribute 'expectedKey'."); } }, // This method deactivate inner test logic and signals // that test ends and now owner can stores test results. _testPassed: function () { this._timerManager.stopTimer(); this.set("started", false); this._testResults.set("state", Constants.TestResultState.Passed); sound.play('test-sound-finish'); this.trigger("signal:testEnds"); }, keyDown: function (keyName) { if (this.get("started")) { // Add key down event to raw data var raw = this._testResults.get("raw"), keyLog = raw[keyName]; if (!keyLog) { keyLog = raw[keyName] = {}; } keyLog.down = keyLog.down || []; keyLog.down.push(this._timerManager.ticks()); //console.log("Key down '{0}'. raw.{0}.down={1}".format(keyName, JSON.stringify(raw[keyName].down))); if (this.get("expectedKey") === null && _.indexOf(this._expectedKeySet, keyName) >= 0) { this.set("expectedKey", keyName); this._expectedKeyPressed(keyName); sound.play('test-sound-correct-beep'); } else if (keyName === this.get("expectedKey")) { this._expectedKeyPressed(keyName); sound.play('test-sound-correct-beep'); } else { sound.play('test-sound-wrong-beep'); } } }, keyUp: function (keyName) { if (this.get("started")) { // Add key up event to raw data var raw = this._testResults.get("raw"), keyLog = raw[keyName]; if (!keyLog) { keyLog = raw[keyName] = {}; } keyLog.up = keyLog.up || []; keyLog.up.push(this._timerManager.ticks()); //console.log("Key up '{0}'. raw.{0}.up={1}".format(keyName, JSON.stringify(raw[keyName].up))); } } }); }); <file_sep>/*global define: true */ define([ 'jQuery', 'underscore', 'Controllers/Constants', 'Controllers/ControllerBase', 'Views/SharePopupView', 'Models/Sharing', 'Views/Constants', 'Models/ExtensionsCollection', 'Utils/Dialog' ], function ($, _, Constants, ControllerBase, SharePopupView, SharePoup, ViewsConstants, ExtensionsCollection, Dialog) { 'use strict'; return ControllerBase.extend({ initialize: function () { ControllerBase.prototype.initialize.apply(this, arguments); _.bindAll(this, "_fetchShared", "_initializeView"); this.dialog = new Dialog(); }, activate: function (options) { this.model = new SharePoup({ id: options && options.id || null, token: options && options.token || null }); //this._fetchShared(); this._initializeView(); }, _fetchShared: function () { var options = this._getFetchOptions(true, this._initializeView, this._fetchShared); this.model.fetch(options); }, _initializeView: function () { this.view = new SharePopupView({ model: this.model }); this.listenTo(this.view, { 'save-shared': this._onSaveShared, 'close-popup': this._closePopup, 'start-email-share': this._startEmailShare }); this.view.render(); this._initPopup(); }, _initPopup: function () { var that = this; $('.share-container').html(this.view.$el).dialog({ modal: true, width: 575, close: function () { that.view._closePopup(); $('.share-container').dialog('destroy'); } }); }, _onSaveShared: function (model, shareData) { this._save(model, {'shareData': shareData}); }, _save: function (model, attributes) { //todo this should not be a "save" method var that = this; model.save(attributes, { validate: false, accountManager: this.get("accountManager"), errorOther: function (models, xhr, options) { that.trigger("error", options.responseError); }, errorUnauthenticated: function () { that._sleep(_.bind(that._onSaveShared, that, model, attributes)); }, success: function () { that._onSuccess(); } }); }, _closePopup: function () { $('.share-container').dialog('close'); }, _onSuccess: function () { $('.share-container').dialog('close'); this.get("accountManager").trigger('updated-shares'); this.model.trigger('shared-save-success'); }, _startEmailShare: function () { this._closePopup(); this.view = new SharePopupView({ model: this.model, mode: 'email' }); this.listenTo(this.view, { 'share-email': this._shareEmail }); this.view.render(); this._initPopup(); }, _shareEmail: function (email, message) { var that = this; this.model.shareByMail({ email: email, message: message, accountManager: this.get("accountManager"), success: function () { that._closePopup(); that.dialog.show('alert', 'Invitations were sent.'); } }); } }); }); <file_sep>/*global define: true */ define([ 'underscore', 'moment', 'backbone', 'Models/Constants', 'text!Templates/AddPatientRow.html' ], function (_, moment, Backbone, ModelsConstants, templateHtml) { 'use strict'; return Backbone.View.extend({ tagName: "div", className: "result-row", template: _.template(templateHtml), events: { "click .id-add-patient": "_onAddPatient" }, initialize: function () { this.listenTo(this.model, "change", this.render); }, render: function () { this.$el.html(this.template({ model: this.model, moment: moment, Constants: ModelsConstants })); return this; }, _onAddPatient: function () { this.model.trigger("add-patient", this.model); } }); });<file_sep>define([ 'backbone', 'Utils/ConsoleStub', 'formatter' ], function (Backbone) { 'use strict'; var DexterityCalculator = Backbone.Model.extend({ defaults: { sessionResults: null }, initialize: function () { this.on("change:sessionResults", this._bindResultsListener); // First initialization call of bind method if (this.has("sessionResults")) { this._bindResultsListener(this, this.get("sessionResults")); } }, _bindResultsListener: function (model, sessionResults) { var previousSessionResults = this.previous("sessionResults"); if (previousSessionResults) { this.stopListening(previousSessionResults.get("testResultsCollection")); } if (sessionResults) { this.listenTo(sessionResults.get("testResultsCollection"), { "add remove change:spentTime change:keyPresses": this._calculateTestDexterityScore, "reset change:state": this._calculateTotalScore }); } }, _calculateTestDexterityScore: function (testResults) { var spentTime = testResults.get("spentTime"); var keyPresses = testResults.get("keyPresses"); if (spentTime != null && keyPresses != null) { var spentSeconds = spentTime.totalSeconds; var score = spentSeconds == 0 ? 0 : keyPresses / spentSeconds; //console.log("DexterityCalculator keyPresses={0} spentSeconds={1} score={2}".format(keyPresses, spentSeconds, score)); testResults.set("score", score); } else if (testResults.has("score")) { testResults.set("score", null); } }, _calculateTotalScore: function () { var sessionResults = this.get("sessionResults"); var testResultsCollection = sessionResults.get("testResultsCollection"); var testScores = testResultsCollection.chain() .map(function (testResults) { return testResults.get("state") == "passed" ? testResults.get("score") : null; }).filter(function (testScore) { return testScore != null; }).value(); if (testScores.length > 0) { var average = 0; if (testScores.length > 0) { for (var i = 0; i < testScores.length; i++) { average += testScores[i]; } average = average / testScores.length; } console.log("DexterityCalculator total dexterity score = {0}".format(average)); sessionResults.set("totalScore", average); } } }); return DexterityCalculator; });
4a07009fdc6a5a40fdc03a0f59f4e8b5eaf45546
[ "JavaScript", "Text", "HTML", "Markdown" ]
119
JavaScript
openOPDM/Kinetics-Web
1d848d299d4b234355c5d0d657926fc6f9f613d1
de215c2fad94814e0ea8c42d68f084e35775f66a
refs/heads/master
<repo_name>owen002/yingxiao<file_sep>/scripts/pages/contract_order.js (function () { var loadingFlag = true, priceSubFlag = true, currentPage = 1, number = 20, pageCount = 1, $priceItems = $('.price-items'), pHeight = 0, priceId = '', pid = '', showid = ''; var $bjdh = $('#bjdh'), $khbh = $('#khbh'), $bjdzt = $('#bjdzt'), $hpje = $('#hpje'), $sj = $('#sj'), $sjhj = $('#sjhj'), $zdzk = $('#zdzk'), $zzje = $('#zzje'), $fktj = $('#fktj'), $jhfs = $('#jhfs'), $paih = $('#paih'), $mingc = $('#mingc'), $pinp = $('#pinp'), $shul = $('#shul'), $jingj = $('#jingj'), $hansje = $('#hansje'), $jiaohqi = $('#jiaohqi'), $dropdownBox = $('.dropdown-box'), $jsfsjqx = $('#jsfsjqx'), $dropdownItems = $('.dropdown-box-items'), $stateSearch = $('#stateSearch'), $bjdSearch = $('#bjdSearch'), $submitPrice = $('#submitPrice'), $dhri = $('#dhri'), $gysfzr = $('#gysfzr'), $khwffzr = $('#khwffzr'), $mfmc = $('#mfmc'), $zdr = $('#zdr'); var msg = new msgBox(), status = '', quotationCode = ''; var clientH = document.documentElement.clientHeight; pHeight = clientH - 84; $priceItems.css('height', pHeight + 'px'); $('.dropdownArrow').on(CLICK_TYPE, function () { status = ''; quotationCode = ''; currentPage = 1; $('.price-items').html(''); $quaCode.html(''); getquoteprice(); hideBar(); }); //退出 var confirm = new msgBox('confirm'); confirm.confirmCallback(function () { $.cookie('userid', '', { path: '/' }); $.cookie('identity', '', { path: '/' }); location.href = '../login.html'; }); $('.logout').on(CLICK_TYPE, function () { confirm.showMsg('确认退出?'); }); $dropdownItems.on(CLICK_TYPE, '.options', function () { status = $(this).data('id'); currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); var $quaCode = $('#quaCode'); $('.filter-confirm').on(CLICK_TYPE, function () { var qu = $.trim($quaCode.val()); if (qu) { quotationCode = qu; } else { msg.showMsg('请输入要查询的单号数据') return; } currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); $('.boxPrimary').on(CLICK_TYPE, function () { hideBar(); }); var userid = $.cookie('userid'); var identity = $.cookie('identity'); function getquoteprice() { waitFun(function () { waitBoxShow(); loadingFlag = false; $.ajax({ url: API.contract_order_list, dataType: 'json', cache: false, data: { status: status, code: quotationCode, currentPage: currentPage, number: number, user_id: userid, user_identity: identity }, success: function (info) { if (info.code == 0) { pageCount = info.value.page.ipageRowCount; var list = info.value.list, quDom = ''; if (list.length > 0) { for (var i = 0, j = list.length; i < j; i++) { var li = list[i]; quDom += '<li data-id="' + li.id + '" class="b-no" data-showid="' + li.quotationCode + '"><div class="bill-no">' + li.quotationCode + '</div><div class="bill-state">' + htdd[li.status] + '</div></li>' } } else { currentPage -= 1; if ($('.loading-complete').length <= 0) { quDom += '<li class="loading-complete" style="text-align: center">没有更多了</li>' } } $priceItems.append(quDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); loadingFlag = true; $('.loading-content').remove(); } }); }) } function queryQutoPriceDetail() { $bjdh.text(''); $khbh.text(''); $bjdzt.text(''); $hpje.text(''); $dhri.text(''); $gysfzr.text(''); $khwffzr.text(''); $mfmc.text(''); $zdr.text(''); $sj.text(''); $sjhj.text(''); $zdzk.text(''); $zzje.text(''); $fktj.text(''); $jhfs.text(''); $jsfsjqx.text(''); waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_order_Detail, data: { id: priceId, user_identity: identity, user_id: userid }, dataType: 'json', cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $bjdh.text(val.orderCode); $khbh.text(val.supplierName); $bjdzt.text(val.contractCode); $hpje.text(toFixSpot(val.productMoney)); $dhri.text(val.orderDate); $gysfzr.text(val.supplierContactPerson); $khwffzr.text(val.ownContactPerson); $mfmc.text(val.companyName); $zdr.text(val.userName); $sj.text(toFixSpot((parseFloat(val.totalMoney) - parseFloat(val.productMoney)))); $sjhj.text(toFixSpot(val.totalMoney)); $zdzk.text(val.overallRebate); $zzje.text(toFixSpot(val.finalMoney)); $fktj.text(val.deliveryAddressType); $jhfs.text(val.trafficMode); $jsfsjqx.text(val.closingAccountMode); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) } $priceItems.on('scroll', function () { var rec = $priceItems[0] var sctop = rec.scrollTop; var scheight = rec.scrollHeight; var qy = scheight - pHeight - sctop; if (qy < 60 && loadingFlag) { loadingFlag = false; currentPage += 1; $('.loading-complete').remove(); $priceItems.append('<li class="loading-content" style="text-align: center">加载中...</li>'); getquoteprice(); } }).on(CLICK_TYPE, '.b-no', function () { priceId = $(this).data('id'); showid = $(this).data('showid'); addSelect($(this)); location.href = '#page2'; queryQutoPriceDetail(); }); //产品列表 $('#productsList').on(CLICK_TYPE, function () { $('#plist').html(''); waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_order_flist, dataType: 'json', data: { stockOrderInforId: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var plistDom = '<li class="list-li"><div class="products-content p-left">序号</div><div class="products-content p-right">报价单号</div></li>'; var val = info.value; for (var i = 0, j = val.length; i < j; i++) { plistDom += '<li data-id="' + val[i].quotationCode + '" class="list-li list-lidev"><div class="products-content p-left">' + (i + 1) + '</div><div class="products-content p-right color-blue" style="word-break: break-all;">' + val[i].quotationCode + '</div></li>' } $('#plist').html(plistDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }) $('#plist').on(CLICK_TYPE, '.list-lidev', function () { $paih.text(''); $mingc.text(''); $pinp.text(''); $shul.text(''); $jingj.text(''); $hansje.text(''); $jiaohqi.text(''); $('#zzzzjjee').text(''); $('#ffkkttjj').text(''); $('#jjhhffss').text(''); var id = $(this).data('id'); pid = id; addSelect($(this)); location.href = '#page4'; waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_order_fdetail, dataType: 'json', type: 'post', data: { code: id, user_identity: identity, user_id: userid }, cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $paih.text(val.quotationCode); $mingc.text(val.customerCode); $pinp.text(bjdzt[val.status]); $shul.text(toFixSpot(val.productMoney)); $jingj.text(toFixSpot(val.taxMoney)); $hansje.text(toFixSpot(val.totalMoney)); $jiaohqi.text(val.overallRebate); $('#zzzzjjee').text(toFixSpot(val.finalMoney)); $('#ffkkttjj').text(val.paymentCondition); $('#jjhhffss').text(val.deliveryType); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }); $submitPrice.on(CLICK_TYPE, function () { if (priceSubFlag) { priceSubFlag = false; $submitPrice.html('提交中...'); waitBoxShow(); $.ajax({ url: API.contract_order_submit, dataType: 'json', type: 'post', data: { id: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var alerthtml = '<div style="text-align: center"><div>合同订单确认下单成功</div><div>合同编号</div><div style="word-break: break-all;">' + showid + '</div></div>' msg.confirmCallback(function () { location.href = 'contract_order.html'; }); msg.showMsg(alerthtml); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); priceSubFlag = true; $submitPrice.html('提交此报价单'); } }) } }); $('#prolist').on(CLICK_TYPE, function () { $('#pplist').html(''); waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_order_prolist, dataType: 'json', data: { stockOrderInforId: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var plistDom = '<li class="list-li"><div class="products-content p-left">序号</div><div class="products-content p-right">牌号</div></li>'; var val = info.value; for (var i = 0, j = val.length; i < j; i++) { plistDom += '<li data-id="' + val[i].id + '" class="list-li list-lidev"><div class="products-content p-left">' + (i + 1) + '</div><div class="products-content p-right color-blue" style="word-break: break-all;">' + val[i].quotationCode + '</div></li>' } $('#pplist').html(plistDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }); $('#pplist').on(CLICK_TYPE, '.list-lidev', function () { $('#hpbh').text(''); $('#gjph').text(''); $('#mc').text(''); $('#pp').text(''); $('#sl').text(''); $('#jj').text(''); $('#hsje').text(''); var id = $(this).data('id'); addSelect($(this)); location.href = '#page6'; waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_order_proDetail, dataType: 'json', data: { id: id, user_identity: identity, user_id: userid }, cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $('#hpbh').text(val.brandCode); $('#gjph').text(val.productName); $('#mc').text(val.productBrand); $('#pp').text(val.contractAmount); $('#sl').text(val.price); $('#jj').text(val.productMoney); $('#hsje').text(val.deliveryDate); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }); getquoteprice(); })();<file_sep>/scripts/pages/contract_jhd.js (function () { var loadingFlag = true, priceSubFlag = true, currentPage = 1, number = 20, pageCount = 1, $priceItems = $('.price-items'), pHeight = 0, priceId = '', showid = ''; var $bjdh = $('#bjdh'), $khbh = $('#khbh'), $bjdzt = $('#bjdzt'), $hpje = $('#hpje'), $sj = $('#sj'), $sjhj = $('#sjhj'), $zdzk = $('#zdzk'), $bcrk = $('#bcrk'), $jlrk = $('#jlrk'), $cgdj = $('#cgdj'), $paih = $('#paih'), $mingc = $('#mingc'), $pinp = $('#pinp'), $shul = $('#shul'), $jingj = $('#jingj'), $hansje = $('#hansje'), $jiaohqi = $('#jiaohqi'), $dropdownBox = $('.dropdown-box'), $dropdownItems = $('.dropdown-box-items'), $stateSearch = $('#stateSearch'), $bjdSearch = $('#bjdSearch'), $submitPrice = $('#submitPrice'); var msg = new msgBox(), status = '', quotationCode = ''; var clientH = document.documentElement.clientHeight; pHeight = clientH - 84; $priceItems.css('height', pHeight + 'px'); $('.dropdownArrow').on(CLICK_TYPE, function () { status = ''; quotationCode = ''; currentPage = 1; $('.price-items').html(''); $quaCode.html(''); getquoteprice(); hideBar(); }); //退出 var confirm = new msgBox('confirm'); confirm.confirmCallback(function () { $.cookie('userid', '', { path: '/' }); $.cookie('identity', '', { path: '/' }); location.href = '../login.html'; }); $('.logout').on(CLICK_TYPE, function () { confirm.showMsg('确认退出?'); }); $dropdownItems.on(CLICK_TYPE, '.options', function () { status = $(this).data('id'); currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); var $quaCode = $('#quaCode'); $('.filter-confirm').on(CLICK_TYPE, function () { var qu = $.trim($quaCode.val()); if (qu) { quotationCode = qu; } else { msg.showMsg('请输入要查询的单号数据') return; } currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); $('.boxPrimary').on(CLICK_TYPE, function () { hideBar(); }); var userid = $.cookie('userid'); var identity = $.cookie('identity'); function getquoteprice() { loadingFlag = false; waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_jhlist, dataType: 'json', cache: false, data: { status: status, deliveryCode: quotationCode, currentPage: currentPage, number: number, user_id: userid, user_identity: identity }, success: function (info) { if (info.code == 0) { pageCount = info.value.page.ipageRowCount; var list = info.value.list, quDom = ''; if (list.length > 0) { for (var i = 0, j = list.length; i < j; i++) { var li = list[i]; quDom += '<li data-id="' + li.id + '" class="b-no" data-showid="' + li.deliveryCode + '"><div class="bill-no">' + li.deliveryCode + '</div><div class="bill-state">' + jiaohuo[li.status] + '</div></li>' } } else { currentPage -= 1; if ($('.loading-complete').length <= 0) { quDom += '<li class="loading-complete" style="text-align: center">没有更多了</li>' } } $priceItems.append(quDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); loadingFlag = true; $('.loading-content').remove(); } }); }) } function queryQutoPriceDetail() { $bjdh.text(''); $khbh.text(''); $bjdzt.text(''); $hpje.text(''); $sj.text(''); $sjhj.text(''); waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_jhDetail, data: { id: priceId, user_identity: identity, user_id: userid }, dataType: 'json', cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $bjdh.text(val.deliveryCode); $khbh.text(val.customerName); $bjdzt.text(val.deliveryDate); $hpje.text(val.contractCode); $sj.text(val.contactPerson); $sjhj.text(val.userName); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) } $priceItems.on('scroll', function () { var rec = $priceItems[0] var sctop = rec.scrollTop; var scheight = rec.scrollHeight; var qy = scheight - pHeight - sctop; if (qy < 60 && loadingFlag) { loadingFlag = false; currentPage += 1; $('.loading-complete').remove(); $priceItems.append('<li class="loading-content" style="text-align: center">加载中...</li>'); getquoteprice(); } }).on(CLICK_TYPE, '.b-no', function () { priceId = $(this).data('id'); showid = $(this).data('showid'); addSelect($(this)); location.href = '#page2'; queryQutoPriceDetail(); }); //产品列表 $('#productsList').on(CLICK_TYPE, function () { $('#plist').html(''); waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_jh_proList, dataType: 'json', data: { id: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var plistDom = '<li class="list-li" style="border-top: 1px solid #C7C7C7;"><div class="products-content p-left">牌号</div><div class="products-content p-right">报价单号</div></li>'; var val = info.value; for (var i = 0, j = val.length; i < j; i++) { plistDom += '<li data-id="' + val[i].id + '" class="list-li list-lidev"><div class="products-content p-left color-puple">' + val[i].brandCode + '</div><div class="products-content p-right color-blue" style="word-break: break-all;">' + val[i].proSortName + '</div></li>' } $('#plist').html(plistDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }) $('#plist').on(CLICK_TYPE, '.list-lidev', function () { $paih.text(''); $mingc.text(''); $pinp.text(''); $shul.text(''); $jingj.text(''); $hansje.text(''); $bcrk.text(''); $jlrk.text(''); var id = $(this).data('id'); addSelect($(this)); location.href = '#page4'; waitFun(function () { waitBoxShow(); $.ajax({ url: API.contract_jh_proDetail, dataType: 'json', data: { id: id, user_identity: identity, user_id: userid }, cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $paih.text(val.serialNumber); $mingc.text(val.proSortName); $pinp.text(val.productCode); $shul.text(val.brandCode); $jingj.text(val.productName); $hansje.text(val.contractAmount); $bcrk.text(val.allDeliveryAmount); $jlrk.text(val.amount); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() } }) }) }); $submitPrice.on(CLICK_TYPE, function () { if (priceSubFlag) { priceSubFlag = false; $submitPrice.html('确认中...'); waitBoxShow() $.ajax({ url: API.contract_jh_confirm, dataType: 'json', type: 'post', data: { id: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var alerthtml = '<div style="text-align: center"><div>合同交货单确认入库成功</div><div>交货单编号</div><div style="word-break: break-all;">' + showid + '</div></div>' msg.confirmCallback(function () { location.href = 'contract_jhd.html'; }); msg.showMsg(alerthtml); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide() priceSubFlag = true; $submitPrice.html('确认交货'); } }) } }); getquoteprice(); })();<file_sep>/scripts/login.js (function ($) { var loginFlag = true, cookieTime = 2; var msg = new msgBox(); $('#goLogin').on('click', function () { if (loginFlag) { loginFlag = false; var username = $.trim($('#username').val()); var password = $.trim($('#password').val()); password = <PASSWORD>(password); if (username && password) { waitBoxShow('登录中...'); $.ajax({ url: API.loginUrl, dataType: 'json', type: 'post', cache: false, data: {account: username, password: <PASSWORD>, source: 2}, success: function (info) { if (info.code == 0) { var uid = info.value.userId; var identity = info.value.identity; $.cookie('userid', uid); $.cookie('identity', identity); location.href = 'index.html' } else { msg.showMsg(info.msg || pubErrMsg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { $.mobile.loading("hide"); loginFlag = true; } }); } else { msg.showMsg('请输入正确的用户名和密码'); } } }) })(jQuery);<file_sep>/scripts/base.js var CLICK_TYPE = "ontouchend" in document ? 'tap' : 'click'; var pubErrMsg = "服务器忙,请稍后再试"; //普通报价状态 var bjdzt = {'0': '编制', '4': '提交合同', '5': '已经生成合同', '6': '提交订货', '7': '已转正式报价'}; //合同订单状态 var htdd = {'0': '编制', '1': '待审批', '2': '审批通过', '3': '审批退回', '4': '已下单', '5': '到货完毕', '6': '已做计划', '-1': '已作废'}; //合同管理状态 var htgl = {'0': '编制', '4': '执行', '5': '终结', '-1': '作废'}; //合同入库 var ruku = {'0': '入库未确认', '1': '入库已确认', '2': '入库已作废'}; //合同出库 var chuku = {'0': '编制', '1': '已确认'}; //交货 var jiaohuo = {'0': '编制', '1': '已确认', '2': '作废'}; // var baseUrl = 'localhost:8080'; var baseUrl = ''; // var baseUrl = 'http://192.168.127.12:88'; var API = { loginUrl: baseUrl + '/jxc/base/identity/login', normal_quote: baseUrl + '/jxc/price/list',//普通报价记录 normal_quote_detail: baseUrl + '/jxc/price/one',//报价详情 normal_quote_prolist: baseUrl + '/jxc/price/product/list',//产品列表 normal_quote_proDetail: baseUrl + '/jxc/price/product/one',//产品详情 normal_quote_priceSub: baseUrl + '/jxc/price/submit',//提交报价单 contract_list: baseUrl + '/jxc/contract/list',//合同列表 contract_Detail: baseUrl + '/jxc/contract/one',//合同详情 contract_prolist: baseUrl + '/jxc/contract/findRelQuotation',//合同报价单信息列表 contract_proDetail: baseUrl + '/jxc/price/one',//合同报价单详情 contract_zhixing: baseUrl + '/jxc/contract/runContract',//执行 contract_zuofei: baseUrl + '/jxc/contract/voidContract',//作废 contract_zhongjie: baseUrl + '/jxc/contract/endContract',//终结 contract_order_list: baseUrl + '/jxc/contract/order/list',//合同订单列表 contract_order_Detail: baseUrl + '/jxc/contract/order/one',//合同详情 contract_order_flist: baseUrl + '/jxc/contract/order/detail/price/list',//合同订单报价单信息列表 contract_order_fdetail: baseUrl + '/jxc/price/code/one',//合同订单报价单详情 contract_order_prolist: baseUrl + '/jxc/contract/order/detail/list',//合同订单报价单牌号列表 contract_order_proDetail: baseUrl + '/jxc/contract/order/detail/one',//合同订单报价单牌号详情 contract_order_submit: baseUrl + '/jxc/contract/order/submit', contract_rukulist: baseUrl + '/jxc/arrival/list',//合同入库列表 contract_rukuDetail: baseUrl + '/jxc/arrival/one',//合同入库详情 contract_ruku_prolist: baseUrl + '/jxc/arrival/productList',//合同入库牌号查询 contract_ruku_proDetail: baseUrl + '/jxc/arrival/ProductOne',//合同入库牌号查询 contract_ruku_confirm: baseUrl + '/jxc/arrival/arrivalSubmit',//确认 contract_chukulist: baseUrl + '/jxc/contract/out/list',//合同出库列表 contract_chukuDetail: baseUrl + '/jxc/contract/out/one',//合同出库详情 contract_chuku_prolist: baseUrl + '/jxc/contract/out/detail/list',//合同出库牌号查询 contract_chuku_proDetail: baseUrl + '/jxc/contract/out/detail/one',//合同出库牌号查询 contract_chuku_confirm: baseUrl + '/jxc/contract/out/submit',//确认 contract_jhlist: baseUrl + '/jxc/delivery/list',// contract_jhDetail: baseUrl + '/jxc/delivery/one',// contract_jh_proList: baseUrl + '/jxc/delivery/quaList',// contract_jh_proDetail: baseUrl + '/jxc/delivery/quaDetail',// contract_jh_confirm: baseUrl + '/jxc/delivery/confirmDelivery',// }; var tools = { getParam: function () { var _search = location.search; var _param = {}; if (_search) { _search = _search.substring(1, _search.length); var _searchArr; if (_search) { _searchArr = _search.split('&'); for (var i in _searchArr) { var each = _searchArr[i]; var eachArr = each.split('='); _param[eachArr[0]] = eachArr[1]; } } } return _param; }, addClass: function ($dom, className) { $dom.each(function (i, v) { if (!$(v).hasClass(className)) { $(v).addClass(className); } }) }, removeClass: function ($dom, className) { if ($dom.hasClass(className)) { $dom.removeClass(className); } } } function toFixSpot(str, nu) { nu = nu || 2; if (typeof str === 'number') { return str.toFixed(nu); } else { return str; } } var waitSec; function waitFun(callback, timeout) { timeout = timeout || 200; waitSec = setTimeout(callback, timeout); } function commonAjax(data, msgBox) { if (data.code == '1002') { msgBox.confirmCallback(function () { location.href = '../login.html'; }) } if (data.code != '0') { msgBox.showMsg(data.msg || pubErrMsg); } } function waitBoxShow(text) { text = text || '加载中...'; $.mobile.loading("show", { text: text, textVisible: true, theme: 'c' }); } function waitBoxHide() { $.mobile.loading('hide'); } var hideState = 0; var msgBox = function (type) { var msgDom = ''; if (type && type == 'confirm') { msgDom += '<section class="showBox_confirm"><div class="msg-box-background"></div><div class="msg-content"><div class="msg-content-header"><span id="msgTitle_confirm">提示信息</span><div class="close-background close-btn" id="msgCloseBtn_confirm"></div></div><div class="msg-content-body"><div class="msg-content-context"><div id="msgContext_confirm"></div><div class="msgBoxConfirmBtn" id="_msgBoxConfirmBtn_confirm">确定</div><div class="msgBoxConfirmBtn cancel_msg" id="_msgBoxCancelBtn_confirm">取消</div></div></div></div></section>' } else { msgDom += '<section class="showBox"><div class="msg-box-background"></div><div class="msg-content"><div class="msg-content-header"><span id="msgTitle">提示信息</span><div class="close-background close-btn" id="msgCloseBtn"></div></div><div class="msg-content-body"><div class="msg-content-context"><div id="msgContext"></div><div class="msgBoxConfirmBtn" id="_msgBoxConfirmBtn">确定</div></div></div></div></section>'; } $(document.body).append(msgDom); if (type && type == 'confirm') { this.$dom = $('.showBox_confirm'); this.msgContent = $('#msgContext_confirm'); this.msgTitle = $('#msgTitle_confirm'); this._msgBoxConfirmBtn = $('#_msgBoxConfirmBtn_confirm'); this._msgBoxCancelBtn = $('#msgCloseBtn_confirm,#_msgBoxCancelBtn_confirm'); } else { this.$dom = $('.showBox'); this.msgContent = $('#msgContext'); this.msgTitle = $('#msgTitle'); this._msgBoxConfirmBtn = $('#_msgBoxConfirmBtn'); this._msgBoxCancelBtn = $('#msgCloseBtn,#_msgBoxCancelBtn'); } this._msgBoxConfirmBtn.on(CLICK_TYPE, function () { setTimeout(function(){ $('.showBox,.showBox_confirm').hide(); },100) }); this._msgBoxCancelBtn.on(CLICK_TYPE, function () { setTimeout(function(){ $('.showBox,.showBox_confirm').hide(); },100) }); }; msgBox.prototype.showMsg = function (msgContent, msgTitle) { if (msgTitle) { this.msgTitle.html(msgTitle); } this.msgContent.html(msgContent); this.$dom.show(); }; msgBox.prototype.confirmCallback = function (callback) { if (typeof callback === 'function') { this._msgBoxConfirmBtn.off(CLICK_TYPE).on(CLICK_TYPE, function (e) { e.preventDefault(); e.stopPropagation(); callback(); }) } }; (function (factory) { if (typeof define === "function" && define.amd) { define(["jquery"], factory) } else { if (typeof exports === "object") { factory(require("jquery")) } else { factory(jQuery) } } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s) } function decode(s) { return config.raw ? s : decodeURIComponent(s) } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)) } function parseCookieValue(s) { if (s.indexOf('"') === 0) { s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\") } try { s = decodeURIComponent(s.replace(pluses, " ")); return config.json ? JSON.parse(s) : s } catch (e) { } } function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value } var config = $.cookie = function (key, value, options) { if (value !== undefined && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === "number") { var days = options.expires, t = options.expires = new Date(); t.setTime(+t + days * 86400000) } return (document.cookie = [encode(key), "=", stringifyCookieValue(value), options.expires ? "; expires=" + options.expires.toUTCString() : "", options.path ? "; path=" + options.path : "", options.domain ? "; domain=" + options.domain : "", options.secure ? "; secure" : ""].join("")) } var result = key ? undefined : {}; var cookies = document.cookie ? document.cookie.split("; ") : []; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split("="); var name = decode(parts.shift()); var cookie = parts.join("="); if (key && key === name) { result = read(cookie, value); break } if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie } } return result }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) === undefined) { return false } $.cookie(key, "", $.extend({}, options, {expires: -1})); return !$.cookie(key) } })); //后退 $('.back').on(CLICK_TYPE, function () { history.back(); }); function addSelect($this) { tools.addClass($this, 'selectActive'); setTimeout(function () { tools.removeClass($this, 'selectActive'); }, 1500); } function clearDom() {} function clearList(){ $('#plist,#pplist').html(''); } var $stateSearch = $('#stateSearch'), $bjdSearch = $('#bjdSearch'),$dropdownBox = $('.dropdown-box'), $dropdownItems = $('.dropdown-box-items'); $bjdSearch.on(CLICK_TYPE, function () { if ($stateSearch.hasClass('active-aa')) { $stateSearch.removeClass('active-aa'); $dropdownItems.slideUp(); } if ($bjdSearch.hasClass('active-search')) { $bjdSearch.removeClass('active-search'); $dropdownBox.slideUp(); } else { $bjdSearch.addClass('active-search'); $dropdownBox.slideDown(); } }); $stateSearch.on(CLICK_TYPE, function () { if ($bjdSearch.hasClass('active-search')) { $bjdSearch.removeClass('active-search'); $dropdownBox.slideUp(); } if ($stateSearch.hasClass('active-aa')) { $stateSearch.removeClass('active-aa'); $dropdownItems.slideUp(); } else { $stateSearch.addClass('active-aa'); $dropdownItems.slideDown(); } }); function hideBar() { if ($stateSearch.hasClass('active-aa')) { $stateSearch.removeClass('active-aa'); $dropdownItems.slideUp() } if ($bjdSearch.hasClass('active-search')) { $bjdSearch.removeClass('active-search'); $dropdownBox.slideUp() } }<file_sep>/scripts/pages/normal_qutoprice.js (function () { var loadingFlag = true, priceSubFlag = true, currentPage = 1, number = 20, pageCount = 1, $priceItems = $('.price-items'), pHeight = 0, priceId = '', showid = ''; var $bjdh = $('#bjdh'), $khbh = $('#khbh'), $bjdzt = $('#bjdzt'), $hpje = $('#hpje'), $sj = $('#sj'), $sjhj = $('#sjhj'), $zdzk = $('#zdzk'), $zzje = $('#zzje'), $fktj = $('#fktj'), $jhfs = $('#jhfs'), $paih = $('#paih'), $mingc = $('#mingc'), $pinp = $('#pinp'), $shul = $('#shul'), $jingj = $('#jingj'), $hansje = $('#hansje'), $jiaohqi = $('#jiaohqi'), $dropdownBox = $('.dropdown-box'), $dropdownItems = $('.dropdown-box-items'), $stateSearch = $('#stateSearch'), $bjdSearch = $('#bjdSearch'), $submitPrice = $('#submitPrice'); var $quaCode = $('#quaCode'); var msg = new msgBox(), status = '', quotationCode = ''; var clientH = document.documentElement.clientHeight; pHeight = clientH - 84; $priceItems.css('height', pHeight + 'px'); $('.dropdownArrow').on(CLICK_TYPE, function () { status = ''; quotationCode = ''; currentPage = 1; $('.price-items').html(''); $quaCode.val(''); getquoteprice(); hideBar(); }); //退出 var confirm = new msgBox('confirm'); confirm.confirmCallback(function () { $.cookie('userid', '', { path: '/' }); $.cookie('identity', '', { path: '/' }); location.href = '../login.html'; }); $('.logout').on(CLICK_TYPE, function () { confirm.showMsg('确认退出?'); }); $dropdownItems.on(CLICK_TYPE, '.options', function () { status = $(this).data('id'); currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); $('.filter-confirm').on(CLICK_TYPE, function () { var qu = $.trim($quaCode.val()); if (qu) { quotationCode = qu; } else { msg.showMsg('请输入要查询的单号数据') return; } currentPage = 1; $priceItems.html(''); getquoteprice(); hideBar() }); $('.boxPrimary').on(CLICK_TYPE, function () { hideBar(); }); var userid = $.cookie('userid'); var identity = $.cookie('identity'); function getquoteprice() { loadingFlag = false; waitBoxShow(); $.ajax({ url: API.normal_quote, dataType: 'json', cache: false, data: { status: status, code: quotationCode, currentPage: currentPage, number: number, user_id: userid, user_identity: identity }, success: function (info) { if (info.code == 0) { pageCount = info.value.page.ipageRowCount; var list = info.value.list, quDom = ''; if (list.length > 0) { for (var i = 0, j = list.length; i < j; i++) { var li = list[i]; quDom += '<li class="b-no" data-id="' + li.id + '" data-showid="' + li.quotationCode + '"><div class="bill-no">' + li.quotationCode + '</div><div class="bill-state">' + bjdzt[li.status] + '</div></li>' } } else { currentPage -= 1; if ($('.loading-complete').length <= 0) { quDom += '<li class="loading-complete" style="text-align: center">没有更多了</li>' } } $priceItems.append(quDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); loadingFlag = true; $('.loading-content').remove(); } }); } function queryQutoPriceDetail() { waitBoxShow(); $bjdh.text(''); $khbh.text(''); $bjdzt.text(''); $hpje.text(''); $sj.text(''); $sjhj.text(''); $zdzk.text(''); $zzje.text(''); $fktj.text(''); $jhfs.text(''); $.ajax({ url: API.normal_quote_detail, data: { id: priceId, user_identity: identity, user_id: userid }, dataType: 'json', cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $bjdh.text(val.quotationCode); $khbh.text(val.customerCode); $bjdzt.text(bjdzt[val.status]); $hpje.text(toFixSpot(val.productMoney)); $sj.text(toFixSpot(val.taxMoney)); $sjhj.text(toFixSpot(val.totalMoney)); $zdzk.text(val.overallRebate); $zzje.text(toFixSpot(val.finalMoney)); $fktj.text(val.paymentCondition); $jhfs.text(val.deliveryType); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); } }) } $priceItems.on('scroll', function () { var rec = $priceItems[0] var sctop = rec.scrollTop; var scheight = rec.scrollHeight; var qy = scheight - pHeight - sctop; if (qy < 60 && loadingFlag) { loadingFlag = false; currentPage += 1; $('.loading-complete').remove(); $priceItems.append('<li class="loading-content" style="text-align: center">加载中...</li>'); getquoteprice(); } }).on(CLICK_TYPE, '.b-no', function () { var $this = $(this); priceId = $this.data('id'); showid = $this.data('showid'); location.href = '#page2'; addSelect($this); waitFun(function () { queryQutoPriceDetail(); }) }); //产品列表 $('#productsList').on(CLICK_TYPE, function () { $('#plist').html(); waitBoxShow(); $.ajax({ url: API.normal_quote_prolist, dataType: 'json', data: { quotationInforId: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var plistDom = '<li class="list-li"><div class="products-content p-left">序号</div><div class="products-content p-right">牌号</div></li>'; var val = info.value; for (var i = 0, j = val.length; i < j; i++) { plistDom += '<li data-id="' + val[i].id + '" class="list-li list-lidev"><div class="products-content p-left">' + (i + 1) + '</div><div class="products-content p-right color-blue" style="word-break: break-all;">' + val[i].quotationCode + '</div></li>' } $('#plist').html(plistDom); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); } }) }) $('#plist').on(CLICK_TYPE, '.list-lidev', function () { clearDom(); $paih.text(''); $mingc.text(''); $pinp.text(''); $shul.text(''); $jingj.text(''); $hansje.text(''); $jiaohqi.text(''); $('#danjia').text(''); $('#hsjj').text(''); var $this = $(this); var id = $this.data('id'); addSelect($this); location.href = '#page4'; waitFun(function () { waitBoxShow(); $.ajax({ url: API.normal_quote_proDetail, dataType: 'json', data: { id: id, user_identity: identity, user_id: userid }, cache: false, success: function (info) { if (info.code == 0) { var val = info.value; $paih.text(val.brandCode); $mingc.text(val.productName); $pinp.text(val.productBrand); $shul.text(val.amount); $jingj.text(val.netPrice); $hansje.text(val.taxMoney); $jiaohqi.text(val.deliveryDate); $('#danjia').text(val.price); $('#hsjj').text(val.taxNetPrice); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); } }) }) }); $submitPrice.on(CLICK_TYPE, function () { if (priceSubFlag) { priceSubFlag = false; $submitPrice.html('提交中...'); waitBoxShow(); $.ajax({ url: API.normal_quote_priceSub, dataType: 'json', type: 'post', data: { id: priceId, user_id: userid, user_identity: identity }, cache: false, success: function (info) { if (info.code == 0) { var alerthtml = '<div style="text-align: center"><div>提交报价单成功</div><div>报价单号</div><div style="word-break: break-all;">' + showid + '</div></div>' msg.confirmCallback(function () { location.href = 'normal_quoteprice.html'; }); msg.showMsg(alerthtml); } else { commonAjax(info, msg); } }, error: function () { msg.showMsg(pubErrMsg); }, complete: function () { waitBoxHide(); priceSubFlag = true; $submitPrice.html('提交此报价单'); } }) } }); waitFun(function () { getquoteprice(); }) })();
baea23fce305d91e8c9044bfb0255c475a0421ac
[ "JavaScript" ]
5
JavaScript
owen002/yingxiao
b145826894f775d2497157ccb94d886cd5456bf4
c8698eddc1c773fe432c6fb04bb7de4f5c95d29e
refs/heads/master
<repo_name>DigitPaint/advent2012<file_sep>/html/23/23.js /* Digitpaint HTML and CSS Advent 2012 _____ _ ______ ________ _ (____ \ | | (_____ \(_______/ | | _ \ \ ____ ____ ____ ____ | | _ ____ ____ ____) ) ____ ____ _ | | | | | / _ ) ___) _ ) \| || \ / _ )/ ___) /_____/ (___ \ / ___) || | | |__/ ( (/ ( (___ (/ /| | | | |_) ) (/ /| | _______ _____) ) | ( (_| | |_____/ \____)____)____)_|_|_|____/ \____)_| (_______)______/|_| \____| Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var pointerLockError = function(e) { console.log("Error while locking pointer.", e); } document.addEventListener('pointerlockerror', pointerLockError, false); document.addEventListener('mozpointerlockerror', pointerLockError, false); document.addEventListener('webkitpointerlockerror', pointerLockError, false); var requestPointerLock = function(container){ // Lock the pointer container.requestPointerLock = container.requestPointerLock || container.mozRequestPointerLock || container.webkitRequestPointerLock; if(container.mozRequestFullScreen){ container.mozRequestFullScreen(); document.addEventListener('mozfullscreenchange', function fullscreenChange() { if (document.mozFullScreenElement === container || document.mozFullscreenElement === container) { container.requestPointerLock(); } }, false); } else { container.requestPointerLock(); } } // ======================= // = The panorama viewer = // ======================= !function() { var panorama = document.getElementById("panorama"); // create and set up the scene, etc var width = panorama.offsetWidth; var height = panorama.offsetHeight; var origWidth, origHeight; var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(35, width / height, 1, 1500); var renderer = new THREE.WebGLRenderer({antialias:true}); var time = 0; var ORIGIN = new THREE.Vector3(); // urls of the images, // one per half axis var urls = [ 'images/ice_river/posx.jpg', 'images/ice_river/negx.jpg', 'images/ice_river/posy.jpg', 'images/ice_river/negy.jpg', 'images/ice_river/posz.jpg', 'images/ice_river/negz.jpg' ]; // wrap it up into the object that we need var cubemap = THREE.ImageUtils.loadTextureCube(urls, undefined, function(){ renderer.render(scene, camera); }); // set the format, likely RGB // unless you've gone crazy cubemap.format = THREE.RGBFormat; // following code from https://github.com/mrdoob/three.js/blob/master/examples/webgl_materials_cubemap.html var shader = THREE.ShaderUtils.lib[ "cube" ]; shader.uniforms[ "tCube" ].texture = cubemap; var material = new THREE.ShaderMaterial( { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: shader.uniforms, depthWrite: false }); var skybox = new THREE.Mesh( new THREE.CubeGeometry( 1000, 1000, 1000 ), material ); skybox.flipSided = true; scene.add(camera); scene.add(skybox); renderer.setSize(width, height); panorama.appendChild(renderer.domElement); // ==================== // = Starting the fun = // ==================== var pos = {x : 0, y : 0}; panorama.addEventListener("click", function(){ requestPointerLock(panorama); }); var pointerLockChange = function() { var pointerLockElement = document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement; if (pointerLockElement == panorama) { document.addEventListener("mousemove", trackMouse, false); } else { document.removeEventListener("mousemove", trackMouse); } } var trackMouse = function(e){ var movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0, movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0; // Update the initial co-ords on mouse move pos.x += movementX * -0.005; pos.y += movementY * -0.0015; //Change camera position on move camera.position.x = Math.sin(pos.x) * 400; camera.position.z = Math.cos(pos.x) * 400; camera.position.y = Math.atan(pos.y) * 400; camera.lookAt(ORIGIN); renderer.render(scene, camera); } document.addEventListener("mozfullscreenchange", function(){ if (document.mozFullScreenElement === panorama || document.mozFullscreenElement === panorama) { origWidth = width; origHeight = height; width = window.screen.width; height = window.screen.height; } else { width = origWidth; height = origHeight; } camera.aspect = width/height; camera.updateProjectionMatrix(); renderer.setSize( width, height); renderer.render(scene, camera); }); document.addEventListener('pointerlockchange', pointerLockChange, false); document.addEventListener('mozpointerlockchange', pointerLockChange, false); document.addEventListener('webkitpointerlockchange', pointerLockChange, false); }(); !function(){ var container = document.getElementById("container"); var ctx = container.getContext("2d"); container.width = container.offsetWidth; container.height = container.offsetHeight; container.addEventListener("click", function(){ requestPointerLock(container); }); var pointerLockChange = function() { var pointerLockElement = document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement; // Let's not act if we're not the pointerLock Element if(pointerLockElement == container){ document.addEventListener("mousemove", trackMouse, false); } else { document.removeEventListener("mousemove", trackMouse); } } document.addEventListener('pointerlockchange', pointerLockChange, false); document.addEventListener('mozpointerlockchange', pointerLockChange, false); document.addEventListener('webkitpointerlockchange', pointerLockChange, false); var trackMouse = function(e){ var movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0, movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0; // Store the mousedata to be used in the drawing function draw(movementX, movementY) } var pos = {x : Math.floor(container.width/2), y : Math.floor(container.height/2)}; var lPos = {x : pos.x, y : pos.y}; var mPos = {x : 0, y : 0, dist : 0}; var segments = []; var keepSegments = 30; var draw = function(dX, dY){ pos.x += dX; pos.y += dY; if(pos.x < 0){ pos.x = 0; } if(pos.x > container.width){ pos.x = container.width; } if(pos.y < 0){ pos.y = 0; } if(pos.y > container.height){ pos.y = container.height; } segments.unshift({x : pos.x, y : pos.y}); if(segments.length > keepSegments){ segments.pop(); } ctx.strokeStyle = "#000"; ctx.fillStyle = "#000" ctx.lineWidth = 4; ctx.clearRect(0,0,container.width, container.height); for(var i=0; i < segments.length; i++){ var tS = segments[i], nS = segments[i+1]; if(nS){ ctx.strokeStyle = "rgba(0,0,0,"+(1/(i+1))+")"; ctx.beginPath(); ctx.moveTo(tS.x, tS.y); ctx.lineTo(nS.x, nS.y); ctx.stroke(); } } ctx.beginPath(); ctx.arc(pos.x, pos.y, 4, 0, Math.PI*2, true) ctx.fill(); } }(); });<file_sep>/html/9/9.js /* Digitpaint HTML and CSS Advent 2012 ____ _ ___ _ _ | _ \ ___ ___ ___ _ __ ___ | |__ ___ _ __ / _ \| |_| |__ | | | |/ _ \/ __/ _ \ '_ ` _ \| '_ \ / _ \ '__| | (_) | __| '_ \ | |_| | __/ (__ __/ | | | | | |_) | __/ | \__, | |_| | | | |____/ \___|\___\___|_| |_| |_|_.__/ \___|_| /_/ \__|_| |_| Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ // Normalize for vendor prefixes var requestFullScreen = function(element) { if(element.requestFullScreen) { element.requestFullScreen(); } else if(element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if(element.webkitRequestFullScreen) { element.webkitRequestFullScreen(); } } var cancelFullScreen = function(){ if (document.cancelFullScreen) { return document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { return document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { return document.webkitCancelFullScreen(); } } // Normalize for vendor prefixes, return event, and fullscreen Element name var methods = (function(){ if (document.cancelFullScreen) { return ["fullscreenchange", "fullscreenElement"]; } else if (document.mozCancelFullScreen) { return ["mozfullscreenchange", "mozFullscreenElement"]; } else if (document.webkitCancelFullScreen) { return ["webkitfullscreenchange", "webkitFullscreenElement"]; } })(); var fullscreenchange = methods[0]; var fullscreenElement = methods[1]; // Make the div#fullscreen go fullscreen document.getElementById("make-div-fullscreen").addEventListener("click", function(){ requestFullScreen(document.getElementById("fullscreen")); }); // Make the documentElement (whole page) go fullscreen document.getElementById("make-page-fullscreen").addEventListener("click", function(){ requestFullScreen(document.documentElement); }); // Cancel any fullscreen action document.getElementById("cancel-fullscreen").addEventListener("click", function(){ cancelFullScreen(); }); // Do something if we go into fullscreen mode document.addEventListener(fullscreenchange, function(){ if(window.console && window.console.log){ if(document[fullscreenElement]){ // We have a fullscreenElement so we must be in fullscreen mode console.log("Fullscreen mode on, with element:", document[fullscreenElement]); } else { // Exit fullcsreen console.log("Fullscreen mode off"); } } }) });<file_sep>/vendor/rss_generator.rb require 'builder' require 'hpricot' class RssGenerator def call(release, options={}) feed = generate_feed(release.build_path) File.open(release.build_path + "feed.rss", "w"){|f| f.write feed } end def generate_feed(path, feed_file=nil) feed = "" # We take a day if it has a \d.css of a \d.js days = Dir.glob(path + "**/*.{css,js}").map{|p| p[/\/(\d+)\//,1]}.compact.map{|i| i.to_i }.uniq.sort xml = Builder::XmlMarkup.new(:target => feed); nil xml.instruct! xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do xml.channel do xml.title "HTML and CSS Advent 2012" xml.link "http://advent2011.digitpaint.nl" xml.pubDate CGI.rfc1123_date Time.now xml.description "24 daily nuggets of HTML/CSS knowledge, brought to you by the front-end specialists at Digitpaint." days.to_a.reverse.each do |day| doc = Hpricot(File.read(path + "#{day}/index.html")) xml.item do xml.title doc.at(".main > .article-header h1").inner_text.strip xml.link "http://advent2012.digitpaint.nl/#{day}/" xml.description doc.at(".main > .body .intro").inner_text.strip xml.pubDate CGI.rfc1123_date Time.new(2012,12,day,12,0,0) xml.guid "http://advent2012.digitpaint.nl/#{day}/" xml.author "Digitpaint" end end end end return feed end end<file_sep>/html/5/5.js /* Digitpaint HTML and CSS Advent 2012 _____ _ _______ _ (____ \ | | (_______)_ | | _ \ \ ____ ____ ____ ____ | | _ ____ ____ ______ | |_ | | _ | | | / _ ) ___) _ ) \| || \ / _ )/ ___) (_____ \| _)| || \ | |__/ ( (/ ( (___ (/ /| | | | |_) ) (/ /| | _____) ) |__| | | | |_____/ \____)____)____)_|_|_|____/ \____)_| (______/ \___)_| |_| Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var container = document.getElementById("columns"); // A little helper method that removes all options as class names // from the .classList (this is seriously awesome btw, no more js lib needed for this!) // and adds the currently selected option as class. var setSelectedClassName = function(select){ var options = select.querySelectorAll("option"); for(var i=0; i < options.length; i++){ container.classList.remove(options[i].getAttribute("value")); } container.classList.add(select.value); } document.getElementById("column-count-modifier").addEventListener("change", function(ev){ var select = ev.target; setSelectedClassName(select); }); document.getElementById("column-fill-modifier").addEventListener("change", function(ev){ var select = ev.target; setSelectedClassName(select); }); });<file_sep>/script/generate.rb # Script to generate missing pages # require 'tilt' template = Tilt::ERBTemplate.new(File.dirname(__FILE__) + "/template.html.erb") days = [nil] + %w{1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th} items = File.read(File.dirname(__FILE__) + "/not-yet.txt").split("----\n").map do |item| title, body = item.split("\n", 2) tmp, day, title = title.split(/(\d+)\s(.*)/) {:day => day.to_i, :day_ord => days[day.to_i], :title => title, :body => body, :file => "#{day}/index.html"} end items.sort!{|a,b| a[:day] <=> b[:day]} build_dir = File.dirname(__FILE__) + "/build/" if !File.exist?(build_dir) system("mkdir #{build_dir}") end Dir.chdir(File.dirname(__FILE__) + "/build/") do items.each_with_index do |item, i| if !File.exist?(item[:day].to_s) system("mkdir #{item[:day]}") end scope = item.dup if items[i+1] scope[:tomorrow] = items[i+1] end if i > 0 scope[:yesterday] = items[i-1] end output = template.render(Object.new, {:item => scope}) File.open(scope[:file], "w"){|fh| fh.write output } end end<file_sep>/html/11/index.html <!DOCTYPE html> <html lang="en-US"> <head> <!-- [START:head] --> <!-- [STOP:head] --> <title>Read between, above, and under the underlines!- HTML and CSS Advent 2012 by Digitpaint</title> <meta name="author" content="All of us at Digitpaint"> <meta name="description" content="Going all out with the new text-decoration css properties."> <meta property="og:title" content="Read between, above, and under the underlines! - HTML &amp; CSS Advent 2012"> <meta property="og:url" content="http://advent2012.digitpaint.nl/11/"> <meta property="og:image" content="http://advent2012.digitpaint.nl/assets/opengraph/11.png"> <meta property="og:description" content="Going all out with the new text-decoration css properties."> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@digitpaint"> <meta name="twitter:creator" content="@flurin"> <meta name="twitter:title" content="Read between, above, and under the underlines! - HTML &amp; CSS Advent 2012"> <meta name="twitter:url" content="http://advent2012.digitpaint.nl/11/"> <meta name="twitter:image" content="http://advent2012.digitpaint.nl/assets/opengraph/11.png"> <meta name="twitter:description" content="Going all out with the new text-decoration css properties."> <link rel="stylesheet" href="11.css" /> <script src="11.js"></script> </head> <body class="layout-article"> <div class="page"> <!-- [START:layout/ribbon] --> <!-- [STOP:layout/ribbon] --> <article class="main"> <!-- [START:layout/article-header?nr=11&title=Read+between,+above,+and+under+the+underlines!&previous=/10/&next=/12/] --> <!-- [STOP:layout/article-header] --> <div class="body text"> <p class="intro"> While <code>text-decoration</code> certainly isn't the most cutting edge feature, it is a very useful one. It has been around quite a while, but recently got overhauled into the CSS Text Decoration Module Level 3 spec. The new text decoration features give you a lot more control than you had before. </p> <section class="examples"> <h2>Show me what you got!</h2> <p> <strong>Note:</strong> This examply only works in Firefox at the moment. </p> <div class="row"> <figure class="example"> <ul> <li class="underline wavy">Wavy underlines</li> <li class="underline dashed">Dashed underlines</li> <li class="underline colored">Underlines with different color</li> <li><span class="overline">Overline</span> can be <span class="overline wavy">wavy too</span></li> <li><span class="line-through">Line through</span> <span class="line-through colored">with different color</span></li> <li><span class="underline skip-spaces">Skip underlines on spaces</span> (no support yet..)</li> </ul> <figcaption> Some cool line coloring examples. :) </figcaption> </figure> </div> </section> <h2>How does it work?</h2> <p> After yesterday's extremly tricky Audio API, the text-decoration CSS property is a breeze. The CSS property <code>text-decoration-line</code> defines where you want your text line positioned. The value can be either <code>underline</code>, <code>overline</code> or <code>line-through</code>. With the <code>text-decoration-style</code> property you can choose what kind of line you want the <code>text-decoration-line</code> to be. You can use the most basic line style values you already know from CSS borders. The color of the line is controlled with <code>text-decoration-color</code>. </p> <p> Most unfortunately, the more useful features like <code>text-decoration-skip</code> have not been implemented by any browser yet. This would allow you to specify when you want the line interrupted, ie. you could have the line skip spaces. </p> <h2>Useful?</h2> <p> It's a tiny thing but it gives you a tad more control than the old CSS2.1 version. Previously, you needed all kinds of hacks to creaty nice wavy underlines — now we can replace all that junkyard code with clean-cut <code>text-decoration-*</code> properties in a breeze. </p> <h2>Great, but can I use it today?</h2> <p> Not quite. Firefox supports some of the spec since version 6, but none of the other browsers currently support it. There is a resolved bug for this in Webkit, but we couldn't get it to work in Chrome or in Chrome Canary. </p> <h2>Show me the source!</h2> <p> Feel free to look around the differente source files we used for this example. </p> <ul> <li><a href="11.css">The stylesheet</a></li> </ul> </div> <footer class="footer text"> <section class="attribution"> <h2>Attribution</h2> <p> Most of these examples we built straight from the spec: <a href="http://www.w3.org/TR/2012/WD-css-text-decor-3-20121113/" target="_blank">CSS Text Decoration Module Level 3</a> </p> <p> We got the idea for this entry from the post "<a href="http://bricss.net/post/8997944388/css3-text-decoration-implemented-first-in-firefox-6" target="_blank">CSS3 text-decoration implemented first in Firefox 6</a>" by <NAME> on BRICSS </p> </section> <!-- [START:share] --> <!-- [STOP:share] --> </footer> <!-- [START:layout/site-navigation] --> <!-- [STOP:layout/site-navigation] --> </article> </div> <script> var addthis_share = { templates: { twitter: 'Read between, above, and under the underlines! — The HTML and CSS Advent 2012 #dpadvent {{url}}' } } </script> <!-- [START:javascripts] --> <!-- [STOP:javascripts] --> </body> </html> <file_sep>/vendor/sass_inline_data.rb module InlineDataFunctions def inline_image(path, mime_type = nil) path = path.value real_path = File.join(self.options[:custom] && self.options[:custom][:root] || ::HTML_ROOT, path) inline_image_string(data(real_path), compute_mime_type(path, mime_type)) end protected def inline_image_string(data, mime_type) data = [data].flatten.pack('m').gsub("\n","") url = "url('data:#{mime_type};base64,#{data}')" Sass::Script::String.new(url) end private def compute_mime_type(path, mime_type = nil) return mime_type if mime_type case path when /\.png$/i 'image/png' when /\.jpe?g$/i 'image/jpeg' when /\.gif$/i 'image/gif' when /\.svg$/i 'image/svg+xml' when /\.otf$/i 'font/opentype' when /\.eot$/i 'application/vnd.ms-fontobject' when /\.ttf$/i 'font/truetype' when /\.woff$/i 'application/x-font-woff' when /\.off$/i 'font/openfont' when /\.([a-zA-Z]+)$/ "image/#{Regexp.last_match(1).downcase}" else raise ArgumentError, "A mime type could not be determined for #{path}, please specify one explicitly." end end def data(real_path) if File.readable?(real_path) File.open(real_path, "rb") {|io| io.read} else raise ArgumentError, "File not found or cannot be read: #{real_path}" end end end module Sass::Script::Functions include InlineDataFunctions end # Wierd that this has to be re-included to pick up sub-modules. Ruby bug? class Sass::Script::Functions::EvaluationContext include Sass::Script::Functions end <file_sep>/script/generate_days.rb # ===================== # = Generate all days = # ===================== # Including: # - JS # - CSS # - HTML require 'tilt' require 'artii' days = [nil] + %w{1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th} renderer = Artii::Base.new all_font_files = %w{univers.flf tombstone.flf tinker-toy.flf thin.flf anja.flf stop.flf stellar.flf speed.flf standard.flf smscript.flf smshadow.flf slant.flf sblood.flf rozzo.flf rectangles.flf pawp.flf nancyj.flf marquee.flf lean.flf kban.flf larry3d.flf graffiti.flf fraktur.flf epic.flf drpepper.flf cricket.flf cosmic.flf bdffonts/xhelvbi.flf bdffonts/clr8x8.flf basic.flf alligator2.flf computer.flf 3-d.flf}.map{|s| s.strip} template = Tilt::ERBTemplate.new(File.dirname(__FILE__) + "/template_pages.html.erb") build_dir = File.dirname(__FILE__) + "/build/" if !File.exist?(build_dir) system("mkdir #{build_dir}") end Dir.chdir(File.dirname(__FILE__) + "/build/") do (1..24).each do |nr| font = Artii::Figlet::Font.new(File.join(Artii::FONTPATH, all_font_files.slice(rand(all_font_files.size)))) figlet = Artii::Figlet::Typesetter.new(font) banner = <<-EOT /* Digitpaint HTML and CSS Advent 2012 #{figlet["December #{days[nr]}"]} Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ EOT if !File.exist?(nr.to_s) system("mkdir #{nr}") end scope = {:nr => nr} if nr < 24 scope[:tomorrow] = "/#{nr + 1}/" end if nr > 1 scope[:yesterday] = "/#{nr - 1}/" end output = template.render(Object.new, {:item => scope}) File.open("#{nr}/#{nr}.js", "w") {|fh| fh.write banner } File.open("#{nr}/#{nr}.css", "w") {|fh| fh.write banner } File.open("#{nr}/index.html", "w"){|fh| fh.write output } end end<file_sep>/html/24/24.js /* Digitpaint HTML and CSS Advent 2012 __, __, _, __, _, _ __, __, __, _, , ___ _,_ | \ |_ / ` |_ |\/| |_) |_ |_) ~ ) / | | |_| |_/ | \ , | | | |_) | | \ / ~~| | | | ~ ~~~ ~ ~~~ ~ ~ ~ ~~~ ~ ~ ~~~ ~ ~ ~ ~ Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ var ctx; var w, h; var snowCanvas, bgCanvas; var loadedImages = 0; var nrOfImages = 0; var loadImage = function(key, img){ nrOfImages += 1; var r = new Image(); r.onload = function(){ images[key] = imageToCanvas(this); loadedImages += 1; if(loadedImages == nrOfImages){ startDraw(); } } r.src = img; return r } loadImage("moon", "/images/moon.svg"), loadImage("mountains", "/images/mountains.svg"), loadImage("tree", "/images/tree.svg"), loadImage("trees-back", "/images/trees-back.svg") var images = {}; var imageToCanvas = function(img){ var canvas = document.createElement("canvas"); var tW = img.width; var tH = img.height; canvas.width = tW; canvas.height = tH; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); return canvas; } var startDraw = function(){ // var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; // Call the drawing method X times a second // setInterval( function () { // if(requestAnimationFrame){ // requestAnimationFrame( draw ); // } else { // draw(); // } // }, 1000 / 15 ); draw(); } var pageCanvas; var getCtxData = function(){ var nW = document.documentElement.offsetWidth; var nH = document.documentElement.offsetHeight; var nCtx, nCanvas; if(document.getCSSCanvasContext){ if(ctx && w == nW && h == nH){ nCtx = ctx; } else { nCtx = document.getCSSCanvasContext("2d", "page-bg", nW, nH); } } else { if(pageCanvas && ctx && w == nW && h == nH){ nCanvas = pageCanvas; nCtx = ctx; } else { nCanvas = document.createElement("canvas"); if(document.mozSetImageElement){ document.mozSetImageElement("page-bg", nCanvas); } else { nCanvas.id = "page-bg"; } nCanvas.width = nW; nCanvas.height = nH; nCtx = nCanvas.getContext("2d"); } } return [nW, nH, nCtx, nCanvas]; } var drawing = false; var draw = function(){ if(drawing){ return; } drawing = true; var data = getCtxData(); w = data[0]; h = data[1]; ctx = data[2]; pageCanvas = data[3]; ctx.clearRect(0,0,w,h); if(!bgCanvas){ prerenderBg(); } ctx.drawImage(bgCanvas, 0, 0); if(!snowCanvas){ var snowImage = new Image(); snowImage.onload = function(){ prerenderSnow(imageToCanvas(this)); drawSnow(0); } snowImage.src = "/images/snow.svg" } else { drawSnow(0); } drawing = false; } var prerenderSnow = function(snow){ snowCanvas = document.createElement('canvas'); snowCanvas.width = w; snowCanvas.height = 2 * h; var ctx = snowCanvas.getContext("2d"); var left = 0, top = 0; while(top < 2*h){ while(left < w){ ctx.drawImage(snow, left, top); left += snow.width; } left = 0; top += snow.height; } } var prerenderBg = function(){ w = document.documentElement.offsetWidth; h = document.documentElement.offsetHeight; bgCanvas = document.createElement("canvas"); bgCanvas.width = w; bgCanvas.height = h; var ctx = bgCanvas.getContext("2d"); ctx.clearRect(0,0,w,h); // Paint purple BG ctx.fillStyle = "#240029" ctx.fillRect(0,0,w,h); drawMoon(ctx, 0); drawMountains(ctx, 0); drawTrees(ctx, 0); } var drawSnow = function(pos){ ctx.drawImage(snowCanvas, 0, 0); } var drawTrees = function(ctx, pos){ var bottom = h - document.querySelector(".main > .bottom").offsetHeight; // Back trees var bTree = images["trees-back"]; ctx.drawImage(bTree, 0, bottom - bTree.height + 20, w, bTree.height); var tree = images["tree"]; var rotationMin = -15 * Math.PI/180, rotationMax = 15 * Math.PI/180, scaleMin = 0.2, scaleMax = 1, bottomMin = -50, bottomMax = 10; var r, s = 0, t = 0; var left = 0; while(left < (w - (tree.width * s / 2))){ r = rotationMin + Math.random(20) * (rotationMax - rotationMin); t = Math.round(bottomMin + Math.random() * (bottomMax - bottomMin)); s = scaleMax - Math.abs(t/(bottomMax - bottomMin)) * (scaleMax - scaleMin); ctx.save(); ctx.translate(left, Math.round(bottom - (tree.height * s))); ctx.rotate(r); ctx.drawImage(tree, 0, t, Math.round(tree.width * s), Math.round(tree.height * s)); ctx.restore(); left += tree.width*s/1.8; } } var drawMountains = function(ctx, pos){ var mountains = images["mountains"]; var baseTop = 260 var scale = w/mountains.width var mH = scale * mountains.height; ctx.drawImage(mountains, 0, baseTop, w, Math.round(mH)); ctx.fillStyle = "#0A1529"; ctx.fillRect(0, baseTop + mH - 1, w, h - baseTop + mH + 1); var moonshineColors = [] for(var i=13; i > 0; i-- ){ var step = 0.03 moonshineColors.push("rgba(176, 221, 246, "+step*i+")"); } ctx.save(); ctx.beginPath(); ctx.moveTo(scale * 0, baseTop + scale * 103); ctx.lineTo(scale * 93, baseTop + scale * 74); ctx.lineTo(scale * 141, baseTop + scale * 109); ctx.lineTo(scale * 205, baseTop + scale * 75); ctx.lineTo(scale * 302, baseTop + scale * 55); ctx.lineTo(scale * 368, baseTop + scale * 20); ctx.lineTo(scale * 537, baseTop + scale * 61); ctx.lineTo(scale * 600, baseTop + scale * 7); ctx.lineTo(scale * 693, baseTop + scale * 65); ctx.lineTo(scale * 760, baseTop + scale * 30); ctx.lineTo(scale * 841, baseTop + scale * 38); ctx.lineTo(scale * 900, baseTop + scale * 30); ctx.lineTo(scale * 949, baseTop + scale * 0); ctx.lineTo(scale * 978, baseTop + scale * 53); ctx.lineTo(scale * 1041,baseTop + scale * 91) ctx.lineTo(scale * 1111,baseTop + scale * 71); ctx.lineTo(scale * 1200,baseTop + scale * 20); ctx.lineTo(w, h); ctx.lineTo(0, h); ctx.lineTo(0, baseTop + scale * 103); ctx.closePath(); ctx.clip(); ctx.fillStyle = createSteppedGradient(moonshineColors, 125, 125, 750) ctx.fillRect(0,0,1500,1500); ctx.restore(); } var drawMoon = function(ctx, pos){ var baseTop = 0; // Moonshine var moonshineColors = ["#8b4f2a", "#854a2a", "#7d4429", "#773e2a", "#70382b", "#68312a", "#5f2c29", "#58252a", "#4e1e2a", "#46172b", "#3b102b", "#30082a","#25002b"]; ctx.fillStyle = createSteppedGradient(moonshineColors, 125, 125 + baseTop, 750); ctx.fillRect(0,0, 1500, 1500); var moon = images["moon"]; ctx.drawImage(moon, Math.round(125 - moon.width/2), Math.round(125 + baseTop - moon.height/2)); } var createSteppedGradient = function(colors, x, y, d){ var grad = ctx.createRadialGradient(x, y, 0, x, y, d); var step = 1/colors.length; for(var i=0; i < colors.length; i++){ grad.addColorStop(i * step, colors[i]); grad.addColorStop((i + 1) * step, colors[i]); } return grad; } window.addEventListener("resize", function(){ bgCanvas = null; snowCanvas = null; draw(); }) <file_sep>/html/20/index.html <!DOCTYPE html> <html lang="en-US"> <head> <!-- [START:head] --> <!-- [STOP:head] --> <title>HTML5 Form Field Frenzy - HTML and CSS Advent 2012 by Digitpaint</title> <meta name="author" content="All of us at Digitpaint"> <meta name="description" content="Highlights of new form field input types and features in HTML5"> <meta property="og:title" content="HTML5 Form Field Frenzy - HTML &amp; CSS Advent 2012"> <meta property="og:url" content="http://advent2012.digitpaint.nl/20/"> <meta property="og:image" content="http://advent2012.digitpaint.nl/assets/opengraph/20.png"> <meta property="og:description" content="Highlights of new form field input types and features in HTML5"> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@digitpaint"> <meta name="twitter:creator" content="@flurin"> <meta name="twitter:title" content="HTML5 Form Field Frenzy - HTML &amp; CSS Advent 2012 by Digitpaint"> <meta name="twitter:url" content="http://advent2012.digitpaint.nl/20/"> <meta name="twitter:image" content="http://advent2012.digitpaint.nl/assets/opengraph/20.png"> <meta name="twitter:description" content="Highlights of new form field input types and features in HTML5"> <link rel="stylesheet" href="20.css" /> </head> <body class="layout-article"> <div class="page"> <!-- [START:layout/ribbon] --> <!-- [STOP:layout/ribbon] --> <article class="main"> <!-- [START:layout/article-header?nr=20&title=HTML5 Form Field Frenzy&previous=/19/&next=/21/] --> <!-- [STOP:layout/article-header] --> <div class="body text"> <p class="intro"> Forms used to be pretty simple; you had your input boxes, textareas, selects, radio buttons, check boxes, and of course file inputs. For a long time this was pretty much it, they did their thing and did it well, but it was fairly limited. With HTML5 Forms, forms got a pretty big update, here we demonstrate some highlights (not all are standard). </p> <section class="examples"> <h2>Let's see here...</h2> <div class="row"> <figure class="example"> <div class="input"> <input type="text" lang="nl" spellcheck="true"> </div> <figcaption>Spellcheck</figcaption> </figure> <figure class="example"> <div class="input"> <input type="file" accept="image/*" multiple="multiple"> </div> <figcaption>Only accept image files (select multiple)</figcaption> </figure> <figure class="example"> <form action="#" method="get" class="input"> <input type="text" required="required" id="input-required"> <button type="submit">Go!</button> </form> <figcaption>You must fill in this field!</figcaption> </figure> </div> <div class="row"> <figure class="example"> <div class="input"> <label for="input-star">Type a star (ie. "Proxima Centauri"):</label> <input type="text" list="stars" id="input-star"> <datalist id="stars"> <option value="Sun"> <option value="Proxima Centauri"> <option value="Barnard's Star"> <option value="Wolf 359"> <option value="Lalande 21185"> <option value="Sirius"> <option value="Luyten"> </datalist> </div> <figcaption>Hassle free autocomplete with <code>datalist</code></figcaption> </figure> <figure class="example"> <div class="input"> <input type="color"> </div> <figcaption>Let's choose a color!</figcaption> </figure> <figure class="example"> <div class="input"> <div> <label for="input-english">English:</label> <input type="text" id="input-english" lang="en" x-webkit-speech="x-webkit-speech"> </div> <div> <label for="input-dutch">Dutch:</label> <input type="text" id="input-dutch" lang="nl" x-webkit-speech="x-webkit-speech"> </div> </div> <figcaption>Recognizes speech in English or Dutch (Chrome only)</figcaption> </figure> </div> </section> <h2>Let's look under the hood then, shall we?</h2> <p> The examples above are just some highlights of what you can do with the HTML5 form elements. We've split up the in-depth explanation according to topic. </p> <h3>Spellcheck</h3> <p> Enabling spellcheck is easy as pie, you just add the <code>spellcheck="true"</code> attribute to your <code>input</code> element. You can opt to specify the language with the <code>lang</code> attribute like this: </p> <pre class="language-markup code"><code>&lt;input type="text" spellcheck="true" lang="en"&gt;</code></pre> <h3>Input accept/multiple files</h3> <p> The new and improved file selector does not only allow you to upload multiple files at once (by setting the <code>multiple</code> attribute), but it also allows you to restrict what types files can be selected with the <code>accept</code> attribute. The <code>accept</code> attribute can be set to one or more mime-types (including wildcards). Of course you'd have to validate this again on the server. To select multiple images, you use: </p> <pre class="language-markup code"><code>&lt;input type="file" multiple="multiple" accept="image/*"&gt;</code></pre> <h3>Required fields</h3> <p> Client-side validation that's baked right into your browser and you can style it, too! To tell the browser a field is required, we simple set the <code>required</code> attribute and the browser should validate that these fields are filled in before submitting. We can style required fields by selecting them with the <code>:required</code> CSS pseudoclass, and if validation failed we can style them with the <code>:invalid</code> pseudoclass. </p> <pre class="language-markup code"><code>&lt;input type="text" required="required"&gt;</code></pre> <h3>Datalist autocomplete</h3> <p> With datalist you can "upgrade" your text input boxes with autosuggestion data. This kind of works like a list of set options, with an "other" option that you can fill in yourself. It's pretty straightforward: </p> <pre class="language-markup code"><code>&lt;input type=&quot;text&quot; list=&quot;stars&quot; id=&quot;input-star&quot;&gt; &lt;datalist id=&quot;stars&quot;&gt; &lt;option value=&quot;Sun&quot;&gt; &lt;option value=&quot;Proxima Centauri&quot;&gt; &lt;option value=&quot;Barnard&#x27;s Star&quot;&gt; &lt;/datalist&gt;</code></pre> <h3>Input color</h3> <p> The nicest way to input colors is by using a color picker. Instead of using complex javascript libraries which could do that for us, we can use <code>type="color"</code>. The color input type will pop-up a colorpicker to choose a color. As with all the new input types, the browser will fall back to a default text input box if <code>type="color"</code> is not supported. </p> <pre class="language-markup code"><code>&lt;input type="color"&gt;</code></pre> <h3>Webkit speech</h3> <p> Although speech input has not (yet) landed in any browser except Chrome, it's pretty cool. And there is an Editor's Draft of a Speech Input API spec which would allow us to do even cooler stuff, including speech synthesis. For now we can only use the <code>x-webkit-speech</code> attribute to add a microphone icon, which pops up to accept voice input. We can influence the recognition language by setting the <code>lang</code> attribute. </p> <pre class="language-markup code"><code>&lt;input type=&quot;text&quot; lang=&quot;en&quot; x-webkit-speech=&quot;x-webkit-speech&quot;&gt;</code></pre> <h2>Useful? Check. Fun? Check.</h2> <p> All these new input types make building interactive forms a lot easier. Client-side validation or autocomplete functionality always required a lot of Javascript, and multiple-file selections with a filter required a Flash, Silverlight or (mother of god!) an Active-X control. </p> <h2>Great, but can I use it today?</h2> <p> Yes, you can! A lot of these features are enhancements that add extra usability to the existing form elements. Almost all of these features can also be polyfilled without too much trouble. </p> <h2>Show me the source!</h2> <p> Feel free to look around the differente source files we used for this example. </p> <ul> <li><a href="20.css">The stylesheet</a></li> </ul> </div> <footer class="footer text"> <section class="attrbution"> <h2>Attribution</h2> <p> "<a href="http://www.wufoo.com/html5/" target="_blank">The Current State of HTML5 Forms</a>" by WUFOO is an excellent resource on all things HTML5 Forms </p> <p> Edd Turtle has a nice roundup of the "<a href="http://www.eddturtle.co.uk/2012/html5-webkit-speech-input/" target="_blank">HTML5 WebKit Speech Input</a>" </p> </section> <!-- [START:share] --> <!-- [STOP:share] --> </footer> <!-- [START:layout/site-navigation] --> <!-- [STOP:layout/site-navigation] --> </article> </div> <script> var addthis_share = { templates: { twitter: 'HTML5 Form Field Frenzy! The HTML and CSS Advent 2012 #dpadvent {{url}}' } } </script> <!-- [START:javascripts] --> <!-- [STOP:javascripts] --> </body> </html> <file_sep>/html/4/4.js /* Digitpaint HTML and CSS Advent 2012 _ \ | | | | | | | -_) _| -_) ` \ _ \ -_) _| __ _| _| \ ___/ \___| \__| \___| _|_|_| _.__/ \___| _| _| \__| _| _| Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var elements = document.querySelectorAll("input[data-filter]"); // Determine matchSelector function call var matchSelectorF = document.documentElement.mozMatchesSelector && "mozMatchesSelector" || document.documentElement.webkitMatchesSelector && "webkitMatchesSelector" || document.documentElement.matchesSelector && "matchesSelector"; // Attach event handler for(var i=0; i < elements.length; i++){ var e = elements[i]; var scope = function(e){ // Find the figure node var figure = e; while(!figure[matchSelectorF]("figure.example") && figure != document.documentElement){ figure = figure.parentNode; } var filterEl = figure.querySelector(".filter"); e.addEventListener("change", function(ev){ var style = e.getAttribute("data-filter"); filterEl.style.webkitFilter = style.replace(/VAL/g, e.value); }); } scope(e); } }) var blurHTML = function(){ document.documentElement.style.webkitFilter = "blur(1px)"; return false; }<file_sep>/html/12/12.js /* Digitpaint HTML and CSS Advent 2012 ______ __ _____ _______ __ __ | _ \ .-----..----..-----..--------.| |--..-----..----. | _ || || |_ | |--. |. | \ | -__|| __|| -__|| || _ || -__|| _| |.| ||___| || _|| | |. | \|_____||____||_____||__|__|__||_____||_____||__| `-|. | / ___/ |____||__|__| |: 1 / |: ||: 1 \ |::.. . / |::.||::.. . | `------' `---'`-------' Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ // Normalize vendor prefixes navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia; window.URL = window.webkitURL || window.URL; // Wrapper for IE10 so the d/l links work there too. var saveData = function(link, data, contentType){ var blob; // Creating a blob with binary data seems to fail in IE10 preview if(window.MSBlobBuilder){ var bb = MSBlobBuilder(); bb.append(data); blob = bb.getBlob(contentType); navigator.msSaveBlob(blob, link.getAttribute("download") || "file"); } else { blob = new Blob([data], {"type" : contentType}); link.href = URL.createObjectURL(blob); } } // ========================== // = Simple file generation = // ========================== var contentEl = document.getElementById("file-content"); var dlTxt = document.getElementById("download-txt"); var dlHtml = document.getElementById("download-html"); dlTxt.addEventListener("click", function(){ saveData(this, contentEl.value, "text/plain") }); dlHtml.addEventListener("click", function(){ saveData(this, "<html><head><title>Generated a HTML file!</title></head><body>" + contentEl.value + "</body></html>", "text/plain") }); // ============================ // = The animated gif creator = // ============================ var cam = document.getElementById("cam"); // Prepare the buffer var buffer = document.createElement("canvas"); var ctxB = buffer.getContext("2d"); var dlGif = document.getElementById("download-gif"); var recBtn = document.getElementById("record"); var sourceWebcamBtn = document.getElementById("select-webcam"); var sourceVideoBtn = document.getElementById("select-file"); var videoFileInput = document.getElementById("video-file"); var selectSourceEl = document.getElementById("select-source"); var recStatusEl = document.getElementById("record-status"); if(!navigator.getUserMedia){ sourceWebcamBtn.classList.add("hidden"); } var fps = 10; var maxFrames = 30; var maxWidth = 200; var scale = 1; var collectedFrames = 0; var canvasStreamInterval = null; var encoder = null; var theStream = null; // Show an error on screen var writeError = function(err){ if(window.console && window.console.log){ console.log(err); } } var streamStart = function(stream){ theStream = stream; if (window.URL) { cam.src = window.URL.createObjectURL(stream); } else { cam.src = stream; // Opera. } // Something went wrong with the video object cam.addEventListener("error", streamStop); } // Stop the stream var streamStop = function(){ theStream.stop(); theStream = null; clearInterval(canvasStreamInterval); }; var streamFailed = function(e){ var msg = 'No camera available.'; if (e.code == 1) { msg = 'User denied access to use camera.'; } writeError(msg); } sourceVideoBtn.addEventListener("click", function(e){ videoFileInput.click(); e.preventDefault(); }, false); videoFileInput.addEventListener("change", function(){ v = this.files[0]; cam.src = window.URL.createObjectURL(this.files[0]); cam.controls = true; cam.classList.remove("hidden"); selectSourceEl.classList.add("hidden"); }); sourceWebcamBtn.addEventListener("click", function(){ navigator.getUserMedia({video: true}, function(stream){ streamStart(stream); cam.controls = false; cam.classList.remove("hidden"); cam.play(); selectSourceEl.classList.add("hidden"); }, streamFailed); }); recBtn.addEventListener("click", function(){ if(!cam.src){ alert("You have to select an input source first!"); return; } // Remove the button when we're recording dlGif.classList.add("hidden"); // Scale factor, never scale under 1; scale = Math.min(maxWidth / cam.videoWidth, 1); buffer.width = cam.videoWidth * scale; buffer.height = cam.videoHeight * scale; encoder = new GIFEncoder(); encoder.setRepeat(0); encoder.setDelay(1000/fps); encoder.setSize(buffer.width, buffer.height); encoder.start(); recStatusEl.classList.remove("hidden"); recStatusEl.innerHTML = "Starting..." // Transfer the image every 15 secs to the canvas canvasStreamInterval = setInterval(captureStill, 1000/fps); }); // Actually capture the still. var captureStill = function(){ if(collectedFrames > maxFrames){ clearInterval(canvasStreamInterval); collectedFrames = 0; recStatusEl.innerHTML = "Finishing..." encoder.finish(); // Show the button dlGif.classList.remove("hidden"); recStatusEl.classList.add("hidden"); } else { ctxB.save(); ctxB.scale(-1, 1); ctxB.drawImage(cam, -1*buffer.width, 0, buffer.width, buffer.height); ctxB.restore(); encoder.addFrame(ctxB); collectedFrames += 1; recStatusEl.innerHTML = "Frame " + collectedFrames; } } dlGif.addEventListener("click", function(){ if(encoder){ // Convert to something the blob can deal with as binary data // If we don't do this it will return encoded data as string. var bin = encoder.stream().bin; var bArr = new Uint8Array(bin.length); for(var i = 0; i < bin.length; i++){ bArr[i] = bin[i]; } saveData(this, new DataView(bArr.buffer), "image/gif"); } }); });<file_sep>/html/8/8.js /* Digitpaint HTML and CSS Advent 2012 ####### ## #### ## ## /##////## /## #/// # /## /## /## /## ##### ##### ##### ########## /## ##### ###### /# /# ######/## /## /## ##///## ##///## ##///##//##//##//##/###### ##///##//##//# / #### ///##/ /###### /## /##/#######/## // /####### /## /## /##/##///##/####### /## / #/// # /## /##///## /## ## /##//// /## ##/##//// /## /## /##/## /##/##//// /## /# /# /## /## /## /####### //######//##### //###### ### /## /##/###### //######/### / #### //## /## /## /////// ////// ///// ////// /// // // ///// ////// /// //// // // // Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ !function(){ var timerEl, prevQuestionEl, prevAnswerEl, prevImageEl, nextQuestionEl, nextImageEl, becameHiddenAt, hiddenSeconds = 0; var questions = [ ["How much does <NAME> and <NAME>'s unabridged Christmas Carol (Audible Audio) cost on Amazon.com?", "$ 9.95", "images/library_tiny.jpg"], ["How tall was the tallest Rockefeller Center christmas tree according to Wikipedia?", "30m", "images/ball_tiny.jpg"], ["How far does WolframAlpha say is the north pole from Nijmegen, The Netherlands?", "4256km", "images/snowfield_tiny.jpg"] ] // Normalize prefixed versions (based on http://www.html5rocks.com/en/tutorials/pagevisibility/intro/) var prefixes = (function getHiddenProp(){ var prefixes = ['webkit','moz','ms','o']; // if 'hidden' is natively supported just return it if ('visibilityState' in document) { return ['visibilityState', "visibilitychange"]; } // otherwise loop over all the known prefixes until we find one for (var i = 0; i < prefixes.length; i++){ if ((prefixes[i] + 'VisibilityState') in document){ return [prefixes[i] + 'VisibilityState', prefixes[i] + "visibilitychange"]; } } // otherwise it's not supported return [null,null]; })(); var visibilityState = prefixes[0], visibilitychange = prefixes[1]; document.addEventListener(visibilitychange, function(){ var state = document[visibilityState]; if(state == "visible"){ // We just became visible hiddenSeconds += ((new Date()) - becameHiddenAt) / 1000 timerEl.innerHTML = formatSeconds(hiddenSeconds); hiddenSeconds = 0; becameHiddenAt = null; // Show answer and next question nextQuestion(); } else if(state == "hidden"){ // We just got hidden becameHiddenAt = new Date(); } else if(state == "prerender"){ // Still prerendering, not visible yet } else { // This is an unknown state. } }); var nextQuestion = function(){ var q = questions.shift(); if(nextQuestionEl.getAttribute("data-answer")){ prevQuestionEl.parentNode.classList.remove("hidden"); prevQuestionEl.innerHTML = nextQuestionEl.innerHTML; prevAnswerEl.innerHTML = nextQuestionEl.getAttribute("data-answer"); prevImageEl.src = nextImageEl.src; } if(q){ nextQuestionEl.innerHTML = q[0]; nextQuestionEl.setAttribute("data-answer", q[1]); nextImageEl.src = q[2]; } else { nextImageEl.parentNode.removeChild(nextImageEl); nextQuestionEl.innerHTML = "Sorry, that's all for today; no more questions, enjoy your day!" nextQuestionEl.removeAttribute("data-answer"); } }; // Helper function to format seconds in to time format: HH:mm:ss var formatSeconds = function(seconds){ if(seconds == Infinity){ return "infinity"; } var secondsLeft = Math.abs(seconds); var time = []; time.push(Math.floor(secondsLeft/3600)); secondsLeft = secondsLeft % 3600 time.push(Math.floor(secondsLeft/60)); time.push(Math.round(secondsLeft % 60)); return time.map(function(v){ return v < 10 ? "0" + v : "" + v}).join(":"); } // Attach eventlisteners document.addEventListener("DOMContentLoaded", function(){ prevQuestionEl = document.getElementById("prev-question"); prevAnswerEl = document.getElementById("prev-answer"); prevImageEl = document.getElementById("prev-image"); nextQuestionEl = document.getElementById("next-question"); nextImageEl = document.getElementById("next-image"); timerEl = document.getElementById("timer"); nextQuestion(); }); }(); <file_sep>/html/21/index.html <!DOCTYPE html> <html lang="en-US"> <head> <!-- [START:head] --> <!-- [STOP:head] --> <title>Wrap-flow &amp; the CSS Exclusions! - HTML and CSS Advent 2012 by Digitpaint</title> <meta name="author" content="All of us at Digitpaint"> <meta name="description" content="Demo of wrap-flow (part of CSS Exclusions), which allows you to define how text flows around an element."> <meta property="og:title" content='Please welcome to the stage: "Wrap-flow &amp; the CSS Exclusions"! - HTML &amp; CSS Advent 2012 by Digitpaint'> <meta property="og:url" content="http://advent2012.digitpaint.nl/21/"> <meta property="og:image" content="http://advent2012.digitpaint.nl/assets/opengraph/21.png"> <meta property="og:description" content="Demo of wrap-flow (part of CSS Exclusions), which allows you to define how text flows around an element."> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@digitpaint"> <meta name="twitter:creator" content="@flurin"> <meta name="twitter:title" content='Please welcome to the stage: "Wrap-flow &amp; the CSS Exclusions"! - HTML &amp; CSS Advent 2012 by Digitpaint'> <meta name="twitter:url" content="http://advent2012.digitpaint.nl/21/"> <meta name="twitter:image" content="http://advent2012.digitpaint.nl/assets/opengraph/21.png"> <meta name="twitter:description" content="Demo of wrap-flow (part of CSS Exclusions), which allows you to define how text flows around an element."> <link rel="stylesheet" href="21.css" /> <script src="21.js"></script> </head> <body class="layout-article"> <div class="page"> <!-- [START:layout/ribbon] --> <!-- [STOP:layout/ribbon] --> <article class="main"> <!-- [START:layout/article-header?nr=21&title=Please+welcome+to+the+stage%3A+%22Wrap-flow+%26+the+CSS+Exclusions%22%21&previous=/20/&next=/22/] --> <!-- [STOP:layout/article-header] --> <div class="body text"> <p class="intro"> Floats are pretty useful, but the only snag is that we can only float left or right and not in the center (or anywhere else for that matter). And if we have two adjecent divs or columns, we can't have the float affect the text-flow in both columns. Thankfully, this will change with CSS Exclusions. </p> <section class="examples"> <h2>Demo time!</h2> <div class="row"> <figure class="example"> <p class="warning"> The live demo only works in IE10 for now, but we've added screenshots for your viewing pleasure :) </p> <div class="content layout-regular" id="container"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <img src="images/alien.svg" alt="Bob, the floating alien!" id="float1" class="flow-both"> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> </div> <figcaption> <label for="wrap-flow">Wrap-flow:</label> <select id="wrap-flow"> <option value="flow-auto">auto</option> <option value="flow-both" selected="selected">both</option> <option value="flow-start">start</option> <option value="flow-end">end</option> <option value="flow-minimum">minimum</option> <option value="flow-maximum">maximum</option> <option value="flow-clear">clear</option> </select> <label for="content-layout">Layout:</label> <select id="content-layout"> <option value="layout-regular">Regular flow</option> <option value="layout-columns">Multicolumns</option> </select> <label for="wrap-through"> <input type="checkbox" id="wrap-through"> Ignore wrap on second paragraph </label> <div class="bonus">Bonus feature: try moving the Bob the Alien around!</div> </figcaption> </figure> </div> </section> <h2>But...how?</h2> <p> First thing to mention is that the image isn't a true float anymore, because it is actually just positioned absolute. The image is now called an exclusion, and its shape should be excluded from the text around it. </p> <p> To get this thing working we have to do two things: make the exclusion have <code class="language-css">position: absolute;</code>, and define the way the content wraps around the exclusion with the <code class="language-css">wrap-flow</code> CSS property. You can see the possible warp-flow values in the examples above. </p> <p> You can influence wether or not the surrounding content should wrap around the the exclusion or not. Setting <code class="language-css">wrap-through: none</code> makes the element ignore any exclusion it encounters. </p> <h2>Useful?</h2> <p> Very useful, and it's just the tip of the iceberg of what CSS Exclusions has to offer in the future. These kind of features allow us to create layouts that were previously either impossible, or only possible with ginormous amounts of hacking (which makes us feel dirty inside afterwards). </p> <h2>Is it real world proof then?</h2> <p> Cool as they might be, this is where they come up short. Nope. Sorry. You could, theoretically, but the positioned floats only work in IE10. Thanks to Adobe there is experimental support in Chrome Canary for some other (truly awesome) exclusion features, but work is still in progress. And even in IE10 it's not the most stable feature out there — we managed to crash the browser once or twice while playing with multiple exclusions. </p> <h2>Show me the source!</h2> <p> Feel free to look around the differente source files we used for this example. </p> <ul> <li><a href="21.css">The stylesheet</a></li> <li><a href="21.js">The javascripts</a></li> </ul> </div> <footer class="footer text"> <section class="attrbution"> <h2>Attribution</h2> <p> This entry was inspired by this Microsoft's positioned floats demo: <a href="http://ie.microsoft.com/testdrive/html5/positionedfloats/default.html" target="_blank">Positioned Floats</a> </p> <p> More info on the IE10 implementation of exclusions can be found in the Internet Explorer 10 Guide for Developers, in the chapter about <a href="http://msdn.microsoft.com/en-gb/library/hh673558.aspx" target="_blank">Exclusions</a> on MSDN </p> <p> While we didn't go into the other kinds of CSS Exclusions, the <a href="http://adobe.github.com/web-platform/samples/css-exclusions/" target="_blank">Adobe CSS Exclusion demos and support tables</a> are quite exceptional. </p> <p> The spec is a great read to find out what the different properties (should) do: <a href="http://dev.w3.org/csswg/css3-exclusions/" target="_blank">CSS Exclusions and Shapes Module Level 3</a> </p> </section> <!-- [START:share] --> <!-- [STOP:share] --> </footer> <!-- [START:layout/site-navigation] --> <!-- [STOP:layout/site-navigation] --> </article> </div> <script> var addthis_share = { templates: { twitter: 'Please welcome to the stage: "Wrap-flow & the CSS Exclusions"! via the HTML and CSS Advent 2012 #dpadvent {{url}}' } } </script> <!-- [START:javascripts] --> <!-- [STOP:javascripts] --> </body> </html> <file_sep>/html/1/1.js /* Digitpaint HTML and CSS Advent 2012 o-o o 0 o | \ | /| | | O o-o o-o o-o o-O-o O-o o-o o-o o | o-o -o- | / |-' | |-' | | | | | |-' | | \ | o-o o-o o-o o-o o o o o-o o-o o o-o-o o-o o Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener('DOMContentLoaded', function(){ // ================================= // = Wrapper to show notifications = // ================================= var displayNotification; // Legacy webkit notifications if(window.webkitNotifications){ // Function to actually display the notification displayNotification = function(icon, title, content){ // Check to see if we have permission to create notifications if (window.webkitNotifications.checkPermission() == 0) { // 0 is PERMISSION_ALLOWED // Create the notification object var notification = window.webkitNotifications.createNotification(icon, title, content); // Attach event listeners notification.addEventListener("close", function(){ if(window.console && window.console.log){ console.log("You closed the notification!" ); } }); notification.addEventListener("click", function(){ if(window.console && window.console.log){ console.log("You clicked the notification!" ); } }); // Show the notification notification.show(); } else { // Request permission to show the notifications first window.webkitNotifications.requestPermission(function(){ // Call myself again if (window.webkitNotifications.checkPermission() == 0){ displayNotification(icon, title, content); } }); } } } // W3C Notifications else if (window.Notification){ // Function to actually display the notification displayNotification = function(icon, title, content){ if (Notification.permissionLevel() === "granted") { // Create the notification object var notification = new Notification(title, { iconUrl: icon, body: content }); // Attach event listeners notification.addEventListener("close", function(){ if(window.console && window.console.log){ console.log("You closed the notification!" ); } }); notification.addEventListener("click", function(){ if(window.console && window.console.log){ console.log("You clicked the notification!" ); } }); // Show the notification notification.show(); } else if (Notification.permissionLevel() === "default") { Notification.requestPermission(function () { displayNotification(icon, title, content); }); } } } // ======================== // = Simple notifications = // ======================== if(displayNotification){ var oneButton = document.getElementById("one-notification"); // Attach the onclick handler oneButton.addEventListener("click", function(){ displayNotification("/favicon.ico", "Title", "Body"); }); } // ========================== // = Multiple notifications = // ========================== if(displayNotification){ var startButton = document.getElementById("start-multiple-notification"); var stopButton = document.getElementById("stop-multiple-notification"); var count = 0; var timer = null; var counterNotifications = function(){ count += 1; displayNotification("/favicon.ico", "Title " + count, "Body"); } // Attach the onclick handler startButton.addEventListener("click", function(){ timer = setInterval(counterNotifications, 5000); }); stopButton.addEventListener("click", function(){ clearInterval(timer); }); } }, false) <file_sep>/html/22/index.html <!DOCTYPE html> <html lang="en-US"> <head> <!-- [START:head] --> <!-- [STOP:head] --> <title>Drag 'till you drop! - HTML and CSS Advent 2012 by Digitpaint</title> <meta name="author" content="All of us at Digitpaint"> <meta name="description" content="Using native system drag and drop in the browser with the HTML5 Drag and Drop API"> <meta property="og:title" content="Drag 'till you drop! - HTML &amp; CSS Advent 2012"> <meta property="og:url" content="http://advent2012.digitpaint.nl/22/"> <meta property="og:image" content="http://advent2012.digitpaint.nl/assets/opengraph/22.png"> <meta property="og:description" content="Using native system drag and drop in the browser with the HTML5 Drag and Drop API"> <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@digitpaint"> <meta name="twitter:creator" content="@flurin"> <meta name="twitter:title" content="Drag 'till you drop! - HTML &amp; CSS Advent 2012 by Digitpaint"> <meta name="twitter:url" content="http://advent2012.digitpaint.nl/22/"> <meta name="twitter:image" content="http://advent2012.digitpaint.nl/assets/opengraph/22.png"> <meta name="twitter:description" content="Using native system drag and drop in the browser with the HTML5 Drag and Drop API"> <link rel="stylesheet" href="22.css" /> <script src="22.js"></script> </head> <body class="layout-article"> <div class="page"> <!-- [START:layout/ribbon] --> <!-- [STOP:layout/ribbon] --> <article class="main"> <!-- [START:layout/article-header?nr=22&title=Drag 'till you drop!&previous=/21/&next=/23/] --> <!-- [STOP:layout/article-header] --> <div class="body text"> <p class="intro"> Drag and drop used to be a lot of custom Javascript, relying on mousedown, mouseup, mousemove events to work. These drag and drop Javascript libraries do a decent job within their own environment, but they can't really interact with system drag and drop. With the HTML5 drag and drop API we can handle dragging stuff into the browser, dragging within the browser and dragging out of the browser. </p> <section class="examples"> <h2>What are we talking about?</h2> <div class="row"> <figure class="example"> <h3>Christmas</h3> <ul id="container1" class="container"> <li draggable="true">Eggs</li> <li draggable="true">Eggnog</li> <li draggable="true">Winter</li> <li draggable="true">Glühwein</li> </ul> <figcaption> Drag from here... (also try dragging to a mail client or texteditor) </figcaption> </figure> <figure class="example"> <h3>Easter</h3> <ul id="container2" class="container"> <li draggable="true">Santa Claus</li> <li draggable="true">Bunnies</li> <li draggable="true">Spring</li> <li draggable="true">Presents</li> </ul> <figcaption> ...to here, or vice versa. Or drag files, text or tweets in here. </figcaption> </figure> <figure class="example"> <h3>Files to download</h3> <span class="dragout" draggable="true" data-downloadpath="/22/files/merry_xmas.txt">A .txt file</span> <span class="dragout" draggable="true" data-downloadpath="/22/files/merry_xmas.html">A .html file</span> <span class="dragout" draggable="true" data-downloadpath="/22/files/merry_xmas.pdf">A .pdf file</span> <figcaption>Drag out files to your desktop (Chrome only)</figcaption> </figure> </div> </section> <h2>How does it work?</h2> <p> When we're dealing with elements within the browser, we have to tell the element that it's draggable with the <code class="language-markup">draggable="true"</code> attribute. After this the Javascript fun starts! </p> <p> We can attach the <code class="language-javascript">dragstart</code> and <code class="language-javascript">dragend</code> events to the draggable attribute to detect when the dragging starts and ends. When the dragging starts, you can set the data that should be set with the dragging operation. This is especially important if you want other programs to understand the thing you're dragging. You can attach your data in multiple formats to the event's <code class="language-javascript">dataTransfer</code> object with <code class="language-javascript">dataTransfer.setData(CONTENTTYPE, DATA)</code> the draggable data must always be a string. In the example above we did this: </p> <pre class="code language-javascript"><code>event.dataTransfer.setData("text/plain", category + " : " + this.innerText); event.dataTransfer.setData("text/html", "&lt;strong&gt;" + category + "&lt;/strong&gt; : " + this.innerHTML);</code></pre> <p> to set the draggable data in plain text and in html. </p> <p> Drop targets receive the <code class="language-javascript">dragenter</code> event when you enter the element while dragging something, or <code class="language-javascript">dragleave</code> when you leave the element. When you move your draggable over the drop target, the <code class="language-javascript">dragoverevent</code> gets called. Finally, when you drop somthing, the <code class="language-javascript">drop</code> event gets called. You can then read out the data with the event's <code class="language-javascript">dataTransfer.getData(CONTENTTYPE)</code> function. When you drop a file there is a special <code class="language-javascript">dataTransfer.files</code> property that contains a <code class="language-javascript">FileList</code> with the dropped files. </p> <p> In short: that's it. There are some quirks that take some time to figure out, but in general it works pretty well. </p> <h2>Useful?</h2> <p> Doing everything with Javascript is fine as long as you don't want to interact with the user's system. This is a very useful update to that functionality. But you can use the HTML drag and drop API for all kinds of operations, like: </p> <ul> <li>Uploading multiple files by drag and drop</li> <li>Dragging contactinformation directly into a webapp</li> <li>Dragging files out of your webapp (downloading them on demand) (Chrome only)</li> <li>Generally making easy drag and drop interfaces</li> </ul> <h2>Great, but can I use it today?</h2> <p> Yes sir (or madam), you can! Most of these API's have been supported in all major browsers for some time now &mdash; even though IE had only limited support until IE10. </p> <h2>Show me the source!</h2> <p> Feel free to look around the differente source files we used for this example. </p> <ul> <li><a href="/22.js">The javascripts</a></li> <li><a href="/22.css">The stylesheet</a></li> </ul> </div> <footer class="footer text"> <section class="attrbution"> <h2>Attribution</h2> <p> The HTML5 Rocks article "<a href="http://www.html5rocks.com/en/tutorials/dnd/basics/" target="_blank">Native HTML5 Drag and Drop</a>" by <NAME> is an excellent intro to Drag &amp; Drop. </p> <p> Remy Sharp made a nice demo for dragging anything into your browser in "<a href="http://html5demos.com/drag-anything" target="_blank">Simple Drag and Drop</a>" </p> <p> We got the dragging files out of Chrome code and idea from the article "<a href="http://www.thecssninja.com/javascript/gmail-dragout">Drag out files like Gmail</a>" by <NAME> from The CSS Ninja blog. </p> </section> <!-- [START:share] --> <!-- [STOP:share] --> </footer> <!-- [START:layout/site-navigation] --> <!-- [STOP:layout/site-navigation] --> </article> </div> <script> var addthis_share = { templates: { twitter: 'Drag \'till you drop! The HTML and CSS Advent 2012 #dpadvent {{url}}' } } </script> <!-- [START:javascripts] --> <!-- [STOP:javascripts] --> </body> </html> <file_sep>/Gemfile source :rubygems gem "html_mockup" gem "hpricot" gem "sass" gem "yui-compressor" gem "artii" gem "builder" gem "rmagick"<file_sep>/html/18/18.js /* Digitpaint HTML and CSS Advent 2012 ,--. | '|,--.| | | |,---.,---.,---.,-.-.|---.,---.,---. |,--.|--- |---. | ||---'| |---'| | || ||---'| || || | | `--' `---'`---'`---'` ' '`---'`---'` ``--'`---'` ' Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var container = document.getElementById("container"); var canvas; // ================== // = Draw the lines = // ================== // var drawArrows = function(){ var w = container.offsetWidth, h = container.offsetHeight; var ctx; // ========================== // = Get the canvas/context = // ========================== if(document.getCSSCanvasContext){ ctx = document.getCSSCanvasContext("2d", "arrows", w, h); } else { var canvas = document.createElement("canvas"); if(document.mozSetImageElement){ document.mozSetImageElement("arrows-bg", canvas); } else { canvas.id = "arrows-bg"; } canvas.width = w; canvas.height = h; ctx = canvas.getContext("2d"); } ctx.lineWidth = 3; ctx.strokeStyle = "rgba(0,0,0,0.8)"; ctx.clearRect(0,0,w,h); var elements = container.querySelectorAll(".connect"); var cY, cX, nY, nX; var cpBX, cpBY, cpEX, cpEY; var arrowOffset = 3; var ellpiseOffset = 2; for(var i = 0; i < elements.length; i++){ var c = elements[i]; var n = elements[i+1]; ctx.save(); ctx.strokeStyle = "rgba(255,0,0,0.5)" drawEllipse(ctx, c.offsetLeft - ellpiseOffset, c.offsetTop - ellpiseOffset, c.offsetWidth + 2*ellpiseOffset, c.offsetHeight + 2* ellpiseOffset); ctx.restore(); if(n){ cY = c.offsetTop + c.offsetHeight; cX = c.offsetLeft + (c.offsetWidth / 2); nY = n.offsetTop - arrowOffset; nX = n.offsetLeft + (n.offsetWidth / 2); if (c.offsetTop == n.offsetTop){ cY += arrowOffset; nY = cY; cpBX = cX + (nX - cX)/2; cpBY = cY + 10; cpEX = nX - (nX - cX)/2; cpEY = cY + 10; } else if (cX > nX) { cpBX = cX; cpBY = cY + 20; cpEX = nX; cpEY = nY - 20; } else{ cpBX = cX + (nX - cX)/2 + 20 cpBY = cY + (nY - cY)/2 cpEX = cX + (nX - cX)/2 + 20 cpEY = cY + (nY - cY)/2 } ctx.beginPath(); ctx.moveTo(cX, cY); ctx.bezierCurveTo(cpBX, cpBY, cpEX, cpEY, nX, nY); ctx.stroke(); var angle = findAngle(cpBX, cpBY, nX, nY); drawArrowhead(ctx, nX, nY, angle, 10, 10); } } } // =========== // = Helpers = // =========== var drawArrowhead = function(ctx, locx, locy, angle, sizex, sizey) { var hx = sizex / 2; var hy = sizey / 2; ctx.save(); ctx.translate((locx ), (locy)); ctx.rotate(angle); ctx.translate(-hx, -hy); ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(0,1*sizey); ctx.lineTo(1*sizex,1*hy); ctx.closePath(); ctx.fill(); ctx.restore(); } function drawEllipse(ctx, x, y, w, h) { var kappa = .5522848; ox = (w / 2) * kappa, // control point offset horizontal oy = (h / 2) * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle ctx.beginPath(); ctx.moveTo(x, ym); ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); ctx.closePath(); ctx.stroke(); } // returns radians var findAngle = function(sx, sy, ex, ey) { // make sx and sy at the zero point return Math.atan((ey - sy) / (ex - sx)); } // ========== // = Events = // ========== // Initial draw drawArrows(); // Resize window.addEventListener("resize", drawArrows); // # Observering the dom var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; if(MutationObserver){ var observer = new MutationObserver(function(mutations){ drawArrows(); }) observer.observe(container, { subtree: true, characterData : true, childList: true }); } // Add more text button var txt = "By adding a lot more text you can see that this is totally dynamic, the arrows should stay connected to the text ellipses."; var pEl = container.querySelector("p:nth-child(2)"); document.getElementById("add-text-to-2nd-p").addEventListener("click", function(){ pEl.innerHTML = pEl.innerHTML + " " + txt; }) }); <file_sep>/html/19/19.js /* Digitpaint HTML and CSS Advent 2012 ##### # # #### # # # # # ## # # # # # # ##### ##### ##### ### ## ###### ##### # ### # # # ###### ###### # # # # # # # # # # # # # # ## # ##### # # # # # ####### # ####### # # # # # ####### # # # # # # # # # # # # # # # # # # # # # # # ##### ##### ##### ##### # # ###### ##### # # ### ### # # Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var iframe = document.getElementById("region-source"); var container = document.querySelector(".container"); var semicircle = function(){ if(!container.classList.contains("formation1")){ var regions = container.querySelectorAll(".region"); for(var i=0; i < regions.length; i++){ var reg = regions[i] reg.style.transform = ""; reg.style.webkitTransform = ""; reg.style.mozTransform = ""; } return; } var r = null, a = container.offsetWidth, x = 50, deg = 0, degStart = 0; r = (Math.pow(a,2) + 4 * Math.pow(x,2)) / (8 * x); deg = Math.acos((r - x) / r) * 180/Math.PI * 2; var regions = container.querySelectorAll(".region"); degStart = 0 - deg/2; portion = deg / (regions.length -1); for(var i=0; i < regions.length; i++){ var reg = regions[i] reg.style.mozTransformOrigin = "50% " + r + "px"; reg.style.mozTransform = "rotate("+ (degStart + i * portion) +"deg)"; reg.style.webkitTransformOrigin = "50% " + r + "px"; reg.style.webkitTransform = "rotate("+ (degStart + i * portion) +"deg)"; reg.style.transformOrigin = "50% " + r + "px"; reg.style.transform = "rotate("+ (degStart + i * portion) +"deg)"; } } var detectMsFlow = function() { var d = document.createElement("detect"); if (d.style["msFlowInto"] === "") return true; return false; }; document.getElementById("add-text").addEventListener("click", function(){ var string = "Moar text in a new paragraph!"; iframe.contentWindow.postMessage(["addText", string], "*"); var p = document.createElement("p"); p.innerHTML = string; var rs = document.getElementById("region-source2"); rs.insertBefore(p, rs.firstChild); }) document.getElementById("add-region").addEventListener("click", function(){ var regions = document.querySelectorAll(".container .region"); if(regions.length <= 6){ var region = document.createElement("div"); region.className = "region"; container.appendChild(region); semicircle(); if(regions.length >= 5){ this.disabled = true; } } }) document.getElementById("change-formation").addEventListener("change", function(){ container.className = "container " + this.value; semicircle(); }); window.addEventListener("resize", semicircle); if(!Modernizr.regions && !detectMsFlow()){ container.innerHTML = "Sorry, you need IE10, Webkit nightly or Chrome Canary (with experimental WebKit features enabled) to see this example..."; container.parentNode.classList.add("no-support"); } if(detectMsFlow()){ document.getElementById("region-source2").className = "hidden"; } if(Modernizr.regions) { document.getElementById("region-source").className = "hidden"; } }); // We start with a CSS parser test then we check page geometry to see if it's affected by regions // Later we might be able to retire the second part, as WebKit builds with the false positives die out Modernizr.addTest('regions', function() { /* Get the 'flowFrom' property name available in the browser. Either default or vendor prefixed. If the property name can't be found we'll get Boolean 'false' and fail quickly */ var flowFromProperty = Modernizr.prefixed("flowFrom"), flowIntoProperty = Modernizr.prefixed("flowInto"); if (!flowFromProperty || !flowIntoProperty){ return false; } /* If CSS parsing is there, try to determine if regions actually work. */ var container = document.createElement('div'), content = document.createElement('div'), region = document.createElement('div'), /* we create a random, unlikely to be generated flow number to make sure we don't clash with anything more vanilla, like 'flow', or 'article', or 'f1' */ flowName = 'modernizr_flow_for_regions_check'; /* First create a div with two adjacent divs inside it. The first will be the content, the second will be the region. To be able to distinguish between the two, we'll give the region a particular padding */ content.innerText = 'M'; container.style.cssText = 'top: 150px; left: 150px; padding: 0px;'; region.style.cssText = 'width: 50px; height: 50px; padding: 42px;'; region.style[flowFromProperty] = flowName; container.appendChild(content); container.appendChild(region); document.documentElement.appendChild(container); /* Now compute the bounding client rect, before and after attempting to flow the content div in the region div. If regions are enabled, the after bounding rect should reflect the padding of the region div.*/ var flowedRect, delta, plainRect = content.getBoundingClientRect(); content.style[flowIntoProperty] = flowName; flowedRect = content.getBoundingClientRect(); delta = flowedRect.left - plainRect.left; document.documentElement.removeChild(container); content = region = container = undefined; return (delta == 42); }); ; <file_sep>/html/2/2.js /* Digitpaint HTML and CSS Advent 2012 ________ ___. ________ .___ \______ \ ____ ____ ____ _____\_ |__ ___________ \_____ \ ____ __| _/ | | \_/ __ \/ ___\/ __ \ / \| __ \_/ __ \_ __ \ / ____/ / \ / __ | | ` \ ___\ \___ ___/| Y Y \ \_\ \ ___/| | \/ / \| | \ /_/ | /_______ /\___ >___ >___ >__|_| /___ /\___ >__| \_______ \___| \____ | \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function () { // =============== // = EventSource = // =============== var initEventSource = function(){ // Open a new EventSource (does not work cross-domain) var source = new EventSource("/eventserver/loadavg"); // Listen to the "open" event; we log every time the browser // creates a new connection source.addEventListener("open", function(){ if(window.console && window.console.log){ console.log("Connection opened"); } }, false) // Listen to the "error" event; we log every time the connection // is being closed on us by the other side. source.addEventListener('error', function(e) { if (e.readyState == EventSource.CLOSED) { if(window.console && window.console.log){ console.log("Connection closed"); } } }, false); // Listen to the message event. This is where the magic happens! // Every time the server sends a message, this event is triggered source.addEventListener('message', function(e) { console.log(e); // We get the load averages in a JSON array // so we have to parse the data here. var loadAvg = JSON.parse(e.data); // Update the plot with our new Data updatePlot(loadAvg); }, false); } // =============== // = Chart stuff = // =============== // Setup data containers for the 3 load averages // Also specify the total number of points we want in the graph before discarding data var data1 = { "label" : "1 min", "data": [] }, data5 = { "label" : "5 min", "data" : [] }, data15 = { "label" : "15 min", "data" : [] }, totalPoints = 100; // Populate data for(var i=0; i < totalPoints; i++){ data1["data"].push(null); data5["data"].push(null); data15["data"].push(null); } // This function adds value to a data array var addData = function(value, data) { // If we got more than totalPoints, we're going to discard older data if (data["data"].length >= totalPoints){ data["data"].shift(); } // Add the value to data data["data"].push(value); } // Render newly received loadAvg data. var updatePlot = function(loadAvg){ // Push each value of the array into the respective // data object. addData(loadAvg[0] * 1, data1); addData(loadAvg[1] * 1, data5); addData(loadAvg[2] * 1, data15); // Set our newly received data and plot it! plot.setData(buildPlotData()); plot.setupGrid(); plot.draw(); } // Build plot data for all three data elements with X and Y values var buildPlotData = function(){ var plotData = [data1, data5, data15]; // Create output that can be read by the plot. // zip the generated y values with the x values var zipData = function(data){ var res = []; for (var i = 0; i < data["data"].length; ++i) res.push([i, data["data"][i]]) return {"label" : data["label"], data: res}; } return plotData.map(zipData); } // ================== // = Initialisation = // ================== // Setup the Flot chart var options = { series: { shadowSize: 0 // drawing is faster without shadows }, xaxis: { show: false }, yaxis: { min: 0 }, grid: { backgroundColor: "#fff" }, legend: { backgroundColor: "transparent", show: true, noColumns: 1, position: "sw" } }; // Actually put the plot in the container var plot = $.plot($("#loadavg-chart"), buildPlotData(), options); // Initialize our eventSource object initEventSource(); });<file_sep>/README.md The HTML & CSS Advent 2012 ========================== **Homepage**: [http://advent2012.digitpaint.nl/](http://advent2012.digitpaint.nl/) **Git**: [<EMAIL>:digitpaint/deployable.git](<EMAIL>:flurin/advent2012.git) **Author**: Digitpaint, <NAME> **License**: [MIT license](http://www.opensource.org/licenses/MIT) Synopsis -------- This is the repo of the HTML & CSS Advent 2012. All 24 daily nuggets of HTML/CSS knowledge, brought to you by the front-end specialists at Digitpaint can be seen here. You can also peek around the sources to see how our build-process works. Especially ahve a look at `Mockupfile` and `vendor/*.rb` Usage ----- 1. Clone the repo 2. Create a rvm gemset (if you're into that kind of thing) 3. Install bundler (`gem install bundler`) 4. `bundle install` 5. `mockup serve --port=9000` 6. Point your browser to http://localhost:9000 Copyright --------- The HTML & CSS Advent &copy; 2012 by [Digitpaint](mailto:<EMAIL>). Licensed under the MIT license. Please see the {file:LICENSE} for more information.<file_sep>/html/14/14.js /* Digitpaint HTML and CSS Advent 2012 ____ __ _____ __ __ __ / __ \___ ________ ____ ___ / /_ ___ _____ < / // / / /_/ /_ / / / / _ \/ ___/ _ \/ __ `__ \/ __ \/ _ \/ ___/ / / // /_/ __/ __ \ / /_/ / __/ /__/ __/ / / / / / /_/ / __/ / / /__ __/ /_/ / / / /_____/\___/\___/\___/_/ /_/ /_/_.___/\___/_/ /_/ /_/ \__/_/ /_/ Copyright 2012 by Digitpaint. This code is licensed under the MIT License. */ document.addEventListener("DOMContentLoaded", function(){ var bwTextEl = document.getElementById("bandwith-text"); var statusTextEl = document.getElementById("online-status-text"); var statusImgEl = document.getElementById("online-status-img"); var bandwidth = 1; var setStatus = function(online){ if(online){ setBandwidth(1); statusTextEl.innerHTML = "Online"; statusImgEl.src = "images/online.svg"; } else { setBandwidth(0); statusTextEl.innerHTML = "Offline"; statusImgEl.src = "images/offline.svg"; } }; var setBandwidth = function(v){ if(v == Infinity){ bandwidth = 1; } else { bandwidth = v; } } window.addEventListener("online", function(){ setStatus(true); }); window.addEventListener("offline", function(){ setStatus(false); }); // The connection, may not be available var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; if(connection){ setBandwidth(connection.bandwith); connection.addEventListener("change", function(){ setBandwidth(connection.bandwith); if(connection.bandwidth < Infinity){ bwTextEl.innerHTML = connection.bandwith + "Mb/s"; } else { bwTextEl.innerHTML = "Unknown"; } }); } // Preload images so they work in offline mode (we can't really fetch them then...) var img = new Image(); img.src = "images/online.svg"; img.src = "images/offline.svg"; // Set initial status; setStatus(navigator.onLine); // ===================== // = Drawing the graph = // ===================== var canvas = document.getElementById("online-graph"); var ctx = canvas.getContext("2d"); canvas.width = 520; var fps = 3; var lastTick = new Date(); var showWindow = 300 // Number of seconds to show var data = []; var pxPerW = canvas.width / showWindow; var calcBarHeight = function(h, max){ if(h > 0){ return h * (canvas.height / max); } else { return (canvas.height / max); } } var draw = function(){ data.push(bandwidth); if(data.length > showWindow){ data.shift(); } var max = Math.max(Math.max.apply( Math, data ), 50); var x,y, h; ctx.clearRect(0,0,canvas.width, canvas.height); ctx.font = "10px/1.2em Verdana"; for(var i=0; i < data.length; i++){ h = calcBarHeight(data[i], max); x = canvas.width - ((data.length - i) * pxPerW); y = (canvas.height / 2) - h/2; if((data[i] == 0 && data[i+1] > 0) || (data[i] > 0 && data[i+1] === 0)){ ctx.save(); ctx.fillStyle = "black"; if(data[i+1] > 0){ ctx.fillText("Online", x, y - calcBarHeight(data[i+1], max)/2); } else { ctx.fillText("Offline", x, y + calcBarHeight(data[i+1], max)/2 + 1.2*10); } ctx.restore(); // We draw a dransparent 1px line if we changed state ctx.fillStyle = "transparent"; } else { if(data[i] > 0){ ctx.fillStyle = "green"; } else { ctx.fillStyle = "red"; } } ctx.fillRect(x, y, pxPerW, h); } }; var requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; // Call the drawing method X times a second setInterval( function () { if(requestAnimationFrame){ requestAnimationFrame( draw ); } else { draw(); } }, 1000 / fps ); });<file_sep>/vendor/rsync_finalizer.rb require 'shellwords' class RsyncFinalizer def initialize(options = {}) @options = { :rsync => "rsync", :remote_path => "", :host => "", :username => "" }.update(options) end def call(release, options = {}) options = @options.dup.update(options) # Validate options validate_options!(release, options) begin `#{@options[:rsync]} --version` rescue Errno::ENOENT raise RuntimeError, "Could not find rsync in #{@options[:rsync].inspect}" end local_path = release.build_path.to_s remote_path = options[:remote_path] local_path += "/" unless local_path =~ /\/\Z/ remote_path += "/" unless remote_path =~ /\/\Z/ release.log(self, "Starting upload of #{(release.build_path + "*")} to #{options[:host]}") command = "rsync -az #{Shellwords.escape(local_path)} #{Shellwords.escape(options[:username])}@#{Shellwords.escape(options[:host])}:#{Shellwords.escape(remote_path)}" # Run r.js optimizer output = `#{command}` # Check if r.js succeeded unless $?.success? raise RuntimeError, "Rsync failed.\noutput:\n #{output}" end end protected def validate_options!(release, options) must_have_keys = [:remote_path, :host, :username] if (options.keys & must_have_keys).size != must_have_keys.size release.log(self, "You must specify these options: #{(must_have_keys - options.keys).inspect}") raise "Missing keys: #{(must_have_keys - options.keys).inspect}" end end end<file_sep>/script/generate_emails.rb # Script to generate missing pages # require 'tilt' require 'rmagick' template = Tilt::ERBTemplate.new(File.dirname(__FILE__) + "/template_email.html.erb") days = %w{1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th} buttons = "Let's go there! Let's see 'm! Check it! Iiiiinnnnterested? Show me what you got! Go go go! I have to see this! Take me there! On to the show! Enter here Click for the magic to start Open sesame Let's go! And we're off! Find out more Take me to your leader Ready for blast-off! Show me the money! Lead the way Off we go! Into the rabbithole Read more Show me how it's done! Clickedyclickclick here!".split("\n") build_dir = File.dirname(__FILE__) + "/build/" if !File.exist?(build_dir) system("mkdir #{build_dir}") end Dir.chdir(File.dirname(__FILE__) + "/../html/preparation") do days.each_with_index do |item, i| dayNr = i+1; nr_file = "../assets/newsletter/numbers/#{"%02d" % dayNr}.png" nr_img = Magick::Image::read(nr_file).first item = { :nr => dayNr, :title => "TITLE", :intro => "INTRO", :button_text => buttons[i], :nr_size => [nr_img.columns, nr_img.rows] } if !File.directory?(item[:nr].to_s) || File.exist?("#{item[:nr].to_s}/email.html") next end output = template.render(Object.new, {:item => item}) File.open("#{item[:nr].to_s}/email.html", "w"){|fh| fh.write output } end end
94dafe28a873b0147cc09732b74433f0abc9d083
[ "JavaScript", "Ruby", "HTML", "Markdown" ]
24
JavaScript
DigitPaint/advent2012
e75a63c58798f33e62ac3c72c4887c2656542060
54fc1d3fc1dc73e47cc9b039b4d191ab6be3a40b
refs/heads/development
<repo_name>gurbuzertunga/myWeatherApp<file_sep>/README.md [Hireable](https://img.shields.io/badge/Hireable-yes-success) ![](https://img.shields.io/badge/Mobile--responsive-yes-green) ![](https://img.shields.io/badge/-Microverse%20projects-blueviolet) # Weather app built with javascript > In this project I built a Weather app with javascript and webpack. with the use of openweather API. > <br> ## This web app is live, you can check it here: [Live demo](https://myweatherappbygurbuz.netlify.app/) ## Built With - HTML/CSS - Javascript/ES6 - Webpack - openweather API ## Getting started - open the live link provided above. - allow the site to capture your location. ## Prerequisities To get this project up and running locally, you must clone this repository or download the files and double click on `index.html` found in the `dist` folder. ## Authors 👤 **<NAME>** - Github: [@gurbuzertunga](https://github.com/gurbuzertunga) - Twitter: [@dantewuhu](https://twitter.com/dantewuhu) - Linkedin: [GurbuzErtunga](https://www.linkedin.com/in/gurbuz-ertunga-a607a2a5/) ## 🤝 Contributing Our favourite contributions are those that help us improve the project, whether with a contribution, an issue, or a feature request! ## Show your support If you've read this far....give us a ⭐️! ## 📝 License This project is licensed by Microverse and the Odin Project<file_sep>/src/utils/dom-elements.js const weatherOutput = document.getElementById('weather-output'); const input = document.getElementById('degree'); const button = document.getElementById('clickDegree'); const myApiKey = '827dd5ea0e30919f428e83ad227c3851'; const toggle = document.getElementById('toggle'); const cityName = document.createElement('p'); const degree = document.createElement('p'); const iconContainer = document.createElement('div'); const iconImg = document.createElement('img'); const degreeType = document.getElementById('degree-type'); let defUnit = 'celcius'; // eslint-disable-line let defValue = 0; // eslint-disable-line export { weatherOutput, input, button, myApiKey, toggle, cityName, degree, iconContainer, iconImg, defUnit, defValue, degreeType, };
fed8439b1e0df8d58b11e8cb9ac482853e3fe84f
[ "Markdown", "JavaScript" ]
2
Markdown
gurbuzertunga/myWeatherApp
fcdfc8fbdc8aafc68b1aa6ed171abf3149cb1a98
5f047a855ac947e404c3529b8e872b3abbecbc94
refs/heads/master
<file_sep>console.log('test'); blocks = SpriteMorph.prototype.blocks; // console.log(blocks); // function myFunction(item) { // // arr[index] = item * document.getElementById("multiplyWith").value; // // demo.innerHTML = numbers; // arr.push(item.spec); // } function saveScript(event) { arr = []; blockarr = []; for (var property in blocks) { if (blocks.hasOwnProperty(property)) { arr.push(blocks[property].spec); blockarr.push(property); } } script = []; scriptsOnScreen = getScripts(0); json_scripts = JSONscript(scriptsOnScreen[0]); arr.forEach(function(blockspec) { if(scriptContainsBlock(json_scripts, blockspec)){ script.push(blockspec); } }); blockscript = []; blockarr.forEach(function(property) { if(scriptContainsBlock(json_scripts, blocks[property].spec)){ blockscript.push(property); } }); console.log(script); var jsonscript = JSON.stringify(script); var blockarray = JSON.stringify(blockscript); console.log('jsonscript:', jsonscript); // var el = document.createElement('script'); // el.setAttribute('src', '?correctscript=' + script); // document.body.appendChild(el); //$(document).on("change", "#savescript_button", function() { $.ajax({ url: "testscripts", type: "POST", data: {"scriptarray" : jsonscript, "blockarray": blockarray}, dataType: "json", success: function(data) { console.log(data); $('#left').show(); alert('successfully saved the scriptarray: ' + jsonscript + blockarray + '. Please press the tasks button to go back to main menu'); } }).fail(function(error){ console.log(error); alert('failed because there is already an existing record'); } ).done(function() { // alert('done'); }); } <file_sep>// console.log('fang pi'); populateFeedback = function(feedbackLog, allFeedback, chunknum, tipnum) { // TODO: Declare move variables up here: var i, j, x; var comment = document.getElementById("comment"); comment.innerHTML = ""; while (comment.nextSibling) { document.getElementById("ag-results").removeChild(comment.nextSibling); } var log = feedbackLog; var chunks = log.chunk_list; var linebreak = document.createElement("br"); var numtips = 0; var chunkHasCorrectTip = false; var tipHasCorrectTest = false; var tipsDiv = document.getElementById("numtips"); ['correct', 'incorrect'].forEach(createCorrectIncorrectGrouping); var correct_total = 0; var incorrect_total = 0; var correct_feedbacks = []; var incorrect_feedbacks = []; for (i = 0; i < chunks.length; i++) { // console.log("chunks.length", chunks.length); var chunk = chunks[i]; var chunkPoints = ""; if (showPoints) { chunkPoints = " ({0} possible {1}) ".format( chunk.totalPoints, pluralize('point', chunk.totalPoints)); } var tips = chunk.tip_list; var header = document.createElement("p"); header.innerHTML = chunk.chunk_title + chunkPoints + '<br><br>'; header.classList.add("chunk-header", "chunk" + i); var correct_chunk = header.cloneNode(true); correct_chunk.classList.add("correct-chunk" + i); if (chunk.allCorrect) { document.getElementById("correct-section").style.display = "block"; document.getElementById("correct-section").appendChild(correct_chunk); } else { var incorrect_chunk = header.cloneNode(true); incorrect_chunk.classList.add("incorrect-chunk" + i); document.getElementById("incorrect-section").style.display = "block"; document.getElementById("incorrect-section").appendChild(incorrect_chunk); } var allFeedback = allFeedback !== undefined ? allFeedback : false; var currRank = 1; // console.log("tips: ", tips); // tipLoop: // TODO: Document this // for (x = 0; x < tips.length; x++) { x = 0; // console.log('x', x, 'tips.length', tips.length); var tip = tips[x]; var label_class = "incorrectans"; var div = document.createElement("div"); var current_chunk = document.getElementsByClassName("incorrect-chunk" + i)[0]; if (tip.allCorrect) { correct_total += 1; document.getElementById("correct-section").style.display = "block"; document.getElementById("correct-section").appendChild(correct_chunk); current_chunk = document.getElementsByClassName("correct-chunk" + i)[0]; label_class = "correctans"; var suggestion = tip.complement; } else { incorrect_total += 1; numtips += 1; var suggestion = tip.suggestion; } var tipPoints = ""; // TODO: Clean this up // TODO: Use a button and bootstrap collapse. div.innerHTML = '<input class="details" id="expander' + i + x + '" type="checkbox" ><label class="' + label_class + '" for="expander' + i + x + '">' + tipPoints + suggestion + '</label><div id="table-wrapper' + i + x + '">'; current_chunk.appendChild(div); var details = document.getElementById("table-wrapper" + i + x); details.previousSibling.click(); var allTests = tip.test_list; appendElement( "p", "", ["inner-titles", "observations" + i + x], details ); j = 0; // for (j = 0; j < allTests.length; j++) { // // console.log('alltests.length', allTests.length); var newRow = document.createElement("tr"); var thisTest = allTests[j]; var testPoints = showPoints ? "({0}) ".format( pluralizeWithNum('point', thisTest.points) ) : ''; if (thisTest.testClass !== "r") { if (document.getElementsByClassName("observations-section" + i + x[0]) !== []) { incorrect_assertions = 0; correct_assertions = 0; appendElement( "div", "", ["results", "observations-section" + i + x], document.getElementsByClassName("observations" + i + x)[0] ); } if (!tip.allCorrect && thisTest.correct) { tipHasCorrectTest = true; if (!document.getElementById("correct-tip" + i + x)) { // TODO: What's this for? } } if (thisTest.correct) { correct_feedbacks.push(thisTest.feedback); correct_assertions += 1; // TODO: Consider removing this conditional and always showing the test. if (allFeedback || tip.allCorrect) { appendElement( "p", "✔", "data", document.getElementsByClassName("observations-section" + i + x)[0] ); appendElement( "p", testPoints + "Tests Passed! " + thisTest.feedback, ["data", "assertion"], document.getElementsByClassName("observations-section" + i + x)[0] ); appendElement( "br", null, null, document.getElementsByClassName("observations-section" + i + x)[0] ); } } else { incorrect_feedbacks.push(thisTest.feedback); // Non-r class failing cases. appendElement( "p", "✖", "data", document.getElementsByClassName("observations-section" + i + x)[0] ); incorrect_assertions += 1; appendElement( "p", testPoints + thisTest.feedback, ["data", "assertion"], document.getElementsByClassName("observations-section" + i + x)[0] ); appendElement( "br", null, null, document.getElementsByClassName("observations-section" + i + x)[0] ); } } else { // TESTS WITH CLASS 'r' if (document.getElementsByClassName("tests-section" + i + x[0]) !== []) { incorrect_tests = 0; correct_tests = 0; appendElement( "div", "", ["results", "tests-section" + i + x], document.getElementsByClassName("observations" + i + x)[0] ); } if (thisTest.correct && !tip.allCorrect) { tipHasCorrectTest = true; if (!document.getElementById("correct-tip" + i + x)) { // TODO: This? } } if (thisTest.correct) { correct_tests += 1; } else { incorrect_tests += 1; } var htmlString, string_reporter, testSectionDiv; string_reporter = document.createElement("div") string_reporter.classList.add("data", "assertion"); // TODO: Try extracting this out. if (thisTest.correct) { // TODO: FIX THE CSS LIST HERE // passing-test-case is used for the show/hide button if (allFeedback || tip.allCorrect) { appendElement( "p", "✔", ["data", "passing-test-case"], document.getElementsByClassName("tests-section" + i + x)[0] ); // TODO Clean these strings up. var input = thisTest.input; if (input instanceof List || input instanceof Array) { input = arrayFormattedString(input); } htmlString = [ '<p class="data assertion">', testPoints + thisTest.feedback, ' The input: <code class="data assertion">', input, '</code>' ].join(''); if (thisTest.expOut.constructor !== Function) { var expOut = thisTest.expOut; if (expOut instanceof List || expOut instanceof Array) { expOut = arrayFormattedString(expOut); } htmlString += [ '<p class="data assertion">, returned the', ' expected value: <code class="data assertion">', expOut, '</code></p>' ].join(''); } else { htmlString += '<p class="data assertion">passed the tests.</p>'; } // TODO: Make a block ==> image call here! string_reporter.innerHTML = htmlString; // TODO: Clean up this... document.getElementsByClassName( "tests-section" + i + x )[0].appendChild(string_reporter); appendElement( "br", null, null, document.getElementsByClassName("tests-section" + i + x)[0] ); } } else { appendElement( "p", "✖", "data", document.getElementsByClassName("tests-section" + i + x)[0] ); string_reporter.classList.add("data", "assertion"); // TODO Clean these strings up. var input = thisTest.input; if (input instanceof List || input instanceof Array) { input = arrayFormattedString(input); } htmlString = [ '<p class="data assertion">', testPoints + thisTest.feedback, 'The input: <code>', input, '</code></p> ' ].join(''); // Don't show "expected output" if the output check is // a custon JS function (where no output type is known.) if (thisTest.expOut && thisTest.expOut.constructor !== Function) { var expOut = thisTest.expOut; if (expOut instanceof List || expOut instanceof Array) { expOut = arrayFormattedString(expOut); } htmlString += [ '<p class="data assertion">did <em>not</em> return the', ' expected value: ', '<code>', expOut, '</code></p>' ].join(''); } if (thisTest.output === null) { htmlString += [ '<p class="data assertion"> did <em>not</em> return the expected value.</p>', '' ].join(''); htmlString += '<p class="data assertion"> Instead it returned no output.</p>'; } else { var output = thisTest.output; if (output instanceof List || output instanceof Array) { output = arrayFormattedString(output); } htmlString += '<p class="data assertion">output: <code>' + output + '</code></p>'; } string_reporter.innerHTML = htmlString; document.getElementsByClassName( "tests-section" + i + x )[0].appendChild(string_reporter); appendElement( "br", null, null, document.getElementsByClassName("tests-section" + i + x)[0] ); } // 'r' test cases } // end adding test div if (tip.rank === currRank || tip.rank !== 0) { // TODO: document this.... if (!tip.allCorrect) { // break tipLoop; } else { currRank += 1; } } } // console.log('correct_total', correct_total); // console.log('incorrect_total', incorrect_total); // console.log('correct_feedback', correct_feedbacks); // console.log('incorrect_feedback', incorrect_feedbacks); stars = document.createElement('div'); stars.className = ('container'); stars.id = 'stars'; star = $('<div>') .html("<%= escape_javascript image_tag('star.jpg') %> <p>text<p> <p class = 'description'> description <p>").addClass('star'); // star.id = 'star'; // star.html("<p>text<\p>"); // star.className = 'star'; unstar = $('<div>') .html("<%= escape_javascript image_tag('unstar.jpg') %>").addClass('star'); // unstar.className = 'unstar'; if (numtips == 0) { divTest = $('<div>') .html("<%= escape_javascript button_to('Next Subtask', minitask_path(@nextminitask), {class: 'nextminitask'}) %>") ; $("#ag-results").append(divTest); } $("#ag-results").append(stars); $("#stars").append(star); $("#stars").append(unstar); // TODO Make a function for this. tipsDiv.innerHTML = '<span class="badge">{0}</span>'.format(numtips) + pluralize('tip', numtips); if (tipHasCorrectTest) { $(SELECT.toggle_correct_button).show(); } openResults(); };
fbb26b605af78fc1d89e718598f526220d59a190
[ "JavaScript" ]
2
JavaScript
emmableu/lambda-evaluator
c4d5f9fc87326d39940acb900f36a6385c943423
284bb9be5ecae5034a668920079ed1c68b50e831
refs/heads/master
<repo_name>wsprent/thesis-code<file_sep>/mtp/convert.py #! /usr/bin/env python3 import networkx as nx import gurobipy as grb import numpy as np import random import sys import argparse import itertools from stp import load_pcstp, write_stp from mtp import d, pairwise DESCRIPTION = """ Converts an STP PCSTP instance to a MTP instance using various methods: -- """ INF = float('inf') def connect_graph(g): source_nodes = set() for i, j in pairwise(nx.connected_components(g)): source_nodes |= i u = random.choice(tuple(source_nodes)) v = random.choice(tuple(j)) cost = sum(g[u][k]['weight'] for k in g.adj[u]) * 1.0 / len(g.adj[u]) g.add_edge(u, v, weight=cost) return g def assignment_by_distance(g, be_int=True): """ Assigns prizes as: prize * (d_ij / avg_dist) """ shortest = dict(nx.algorithms.all_pairs_dijkstra_path_length(g)) avg_p = sum(g.node[v]["prize"] for v in g.nodes) / g.number_of_nodes() for v in g.nodes: d = {} p = g.node[v]["prize"] or avg_p dists = shortest[v] avg_dist = sum(dists.values()) * 1.0 / len(dists.values()) for u in g.nodes: dist = dists[u] if u in dists else INF if p > 0 and u != v: dist = p * (dist / avg_dist) if avg_dist else INF d[u] = int(dist) if be_int else dist else: d[u] = 0 g.node[v]["assignment_costs"] = d return g def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument("-f", help="The PCSTP instance as a stp file") args = parser.parse_args() if args.f: with open(args.f) as fp: g, N, int_only = load_pcstp(fp) else: g, N, int_only = load_pcstp(sys.stdin) connect_graph(g) assignment_by_distance(g) write_stp(g) if __name__ == "__main__": main() <file_sep>/rust/cplex/src/main.rs mod cplex; fn main() { let cpx = match cplex::get_cplex() { Ok(cpx) => cpx, Err(err) => panic!(err) }; println!("Opened CPLEX."); println!("Hello, world!"); } <file_sep>/mtp/stp.py import networkx as nx from mtp import d, BIG_FLOAT INF = float('inf') def is_int(s): try: int(s) return True except ValueError: return False def chomp_section(f): for line in f: if line.startswith('END'): return def grow_graph(f, g): int_only = True for line in f: if line.startswith('Nodes'): _, num_nodes = line.strip().split() num_nodes = int(num_nodes) for i in range(1, num_nodes + 1): g.add_node(i, prize=0, _prize=0) continue if line.startswith('Edges'): continue if line.startswith('END'): break _, v, u, w = line.strip().split() u = int(u) v = int(v) if is_int(w): w = int(w) else: w = float(w) int_only = False g.add_edge(u, v, weight=w, _weight=w) return int_only def add_terminal_prizes(f, g): N = set() int_only = True for line in f: if line.startswith('Terminals'): continue if line == 'END\n': break _, v, p = line.strip().split() v = int(v) if is_int(p): p = int(p) else: p = float(p) int_only = False N.add(v) g.node[v]['prize'] = g.node[v]['_prize'] = p return N, int_only def add_assignment_costs(f, g): int_only = True for line in f: if line.startswith('AssignmentCosts'): continue if line == 'END\n': break _, u, v, c = line.strip().split() u = int(u) v = int(v) if is_int(c): c = int(c) else: c = float(c) int_only = False if "assignment_costs" not in g.node[u]: g.node[u]["assignment_costs"] = {} g.node[u]["assignment_costs"][v] = c return int_only def load_pcstp(fp): ''' Loads an .stp file into a networkX graph ''' g = nx.Graph() int_only = True for line in fp: if line.startswith('SECTION'): suffix = line[8:].strip() if suffix == 'Graph': int_only = grow_graph(fp, g) elif suffix == 'Terminals': N, int_only_N = add_terminal_prizes(fp, g) else: chomp_section(fp) return g, N, (int_only and int_only_N) def load_mtp(fp): ''' Loads an .stp file in MTP format into a networkX graph ''' g = nx.Graph() int_only = True for line in fp: if line.startswith('SECTION'): suffix = line[8:].strip() if suffix == 'Graph': int_only = grow_graph(fp, g) and int_only elif suffix == 'AssignmentCosts': int_only = add_assignment_costs(fp, g) and int_only else: chomp_section(fp) return g, int_only # Writing: def write_header(): print("33D32945 STP File, STP Format Version 1.0") print() def write_graph(g): print("SECTION Graph") print("Nodes", g.number_of_nodes()) print("Edges", g.number_of_edges()) for u, v, c in g.edges(data="weight"): print("E", u, v, c) print("END") print() def write_assignment_costs(g): print("SECTION AssignmentCosts") for u in g.nodes: for v in g.nodes: if d(g, u, v) < BIG_FLOAT: print("D", u, v, d(g, u, v)) print("END") def write_stp(g): write_header() write_graph(g) write_assignment_costs(g) <file_sep>/rust/cplex/wrapper.h #include <cplex.h> <file_sep>/mtp/mtp.py """ Utilities for the MTP problem on a NetworkX Graph """ import numpy as np import networkx as nx import random BIG_INT = np.iinfo(np.int64).max BIG_FLOAT = np.finfo(np.float64).max def pairwise(it): it = iter(it) one = next(it) two = next(it) while True: yield one, two one = two two = next(it) def d(g, u, v): try: return g.node[u]['assignment_costs'].get(v, BIG_FLOAT) except Exception as e: print(u, v) raise e def cost(T, G): cost = 0 assignment(T, G) # edge costs for _, _, w in T.edges(data="weight"): cost += w # assignment costs for i, (_, c) in G.nodes(data='assigned'): cost += c return cost def assignment(T, G): for v in G.nodes: if v in T.nodes: G.node[v]['assigned'] = v, 0 else: other_node = None cost = -1 for u in T.nodes: c = d(G, v, u) if other_node is None or c < cost: other_node = u cost = c G.node[v]['assigned'] = other_node, cost def getrec(di, x): """ Recursively get x from d until it does not exist """ default = None while x in di: default = di[x] x = default return default def truncate(g, n, m): """ Truncates the instance by contracting/deleting edges without disjoining the graph, g, to have n nodes and m edges. """ assignment_map = {} gp = g node_ratio = n / gp.number_of_nodes() while n < gp.number_of_nodes(): v = random.choice([i for i in gp]) v_adj = random.choice([i for i in gp.adj[v]]) # contract v_adj into v gp = nx.contracted_nodes(gp, v, v_adj, self_loops=False) assignment_map[v_adj] = v danger = False if gp.number_of_edges() > m: target = min(len(gp.adj[v]) * 1.0 * node_ratio, 1) while not danger and len(gp.adj[v]) > target: i, j, data = random.choice(tuple(gp.edges(v, data=True))) gp.remove_edge(i, j) if not nx.is_connected(gp): gp.add_edge(i, j, **data) danger = True # fix assignments # first for contracted nodes for u in assignment_map: v = getrec(assignment_map, u) # u has been contracted to v # we take the lowest assignment cost unless zero new_assignments = {} for i in gp.nodes: du = d(g, u, i) dv = d(g, v, i) if du == 0: new_assignments[i] = dv elif dv == 0: new_assignments[i] = du else: new_assignments[i] = min(dv, du) gp.nodes[v]['assignment_costs'] = new_assignments # remove all non existant assignments for i in gp.nodes: gp.node[i]['assignment_costs'] = {k: v for k, v in gp.node[i]['assignment_costs'].items() if k in gp} # relabel nodes to run from 1 to N j = 1 bmap = {} for i in gp.nodes: # i is now j bmap[i] = j j += 1 lmap = {v: k for k, v in bmap.items()} gpp = nx.relabel_nodes(gp, bmap) for i in gpp.nodes: gpp.node[i]['assignment_costs'] = {bmap[k]: v for k, v in gp.node[lmap[i]]['assignment_costs'].items()} return gpp <file_sep>/rust/cplex/src/cplex.rs mod internal { #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] include!(concat!(env!("OUT_DIR"), "/bindings.rs")); } use self::internal::CPXENVptr; pub struct Cplex { env: CPXENVptr, } pub fn get_cplex() -> Result<Cplex, String> { let (env, status) = unsafe { let mut status : i32 = -10; let env = internal::CPXopenCPLEX(&mut status); (env, status) }; if status == 0 { return Ok(Cplex { env: env }); } else { return Err(format!("Could not open CPLEX - status {}.", status)); } } <file_sep>/rust/steiner/Cargo.toml [package] name = "steiner" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] <file_sep>/mtp/main.py #! /usr/bin/env python3 import networkx as nx import gurobipy as grb import numpy as np import argparse import itertools import time import os from random import random import mtp from stp import load_mtp from mtp import d, pairwise DESCRIPTION = """ Solves an instance of the MTP using Gurobi Python. """ BIG_INT = np.iinfo(np.int64).max BIG_FLOAT = np.finfo(np.float64).max EPSILON = 10**(-5) def edge(x, i, j): return x[i, j] if i <= j else x[j, i] def build_ilp_model(g, args): model = grb.Model('mtp') # Edge Selection x = model.addVars(g.edges, vtype=grb.GRB.BINARY) # Vertex Assignment y = model.addVars(((i, j) for i in g.nodes for j in g.nodes), vtype=grb.GRB.BINARY) # OBJECTIVE edge_costs = grb.quicksum(g[i][j]['weight'] * x[i, j] for i, j in g.edges) assignment_cost = grb.quicksum(d(g, u, v) * y[u, v] for u in g.nodes for v in g.nodes) model.setObjective(edge_costs + assignment_cost) # one less edges than vertices model.addConstr(x.sum() == grb.quicksum(y[i, i] for i in g.nodes) - 1, name='x.sum == y.sum - 1') # Add all |S| = 2 GSECS for i, j in g.edges: model.addConstr(x[i, j] <= y[i, i]) model.addConstr(x[i, j] <= y[j, j]) # ?? # All Vertices must be assigned for i in g.nodes: model.addConstr(y.sum(i, '*') == 1) # Only assign to vetrices in the facility for i in g.nodes: for j in g.nodes: model.addConstr(y[i, j] <= y[j, j]) # In the facility iff connected for i in g.nodes: model.addConstr(y[i, i] <= grb.quicksum(edge(x, i, j) for j in g.adj[i])) if args.strengthen: for j in g.adj[i]: model.addConstr(y[i, i] >= edge(x, i, j)) return model, x, y def sum_edges(S, x): lhs = grb.LinExpr() for i, j in itertools.combinations(S, 2): if (i, j) in x: lhs.add(x[i, j]) elif (j, i) in x: lhs.add(x[j, i]) return lhs def separate_gsec_rel(model, x, y, x_bar, y_bar, G): F = nx.DiGraph() F.add_node(-1) # source F.add_node(-2) # sink for v in G.node: F.add_node(v) for i, j in G.edges: capacity = x_bar[i, j] / 2 F.add_edge(i, j, capacity=capacity) F.add_edge(j, i, capacity=capacity) total_source_cap = 0 for i in G.nodes: node = F.node[i] capacity = 0 for j in G.adj[i]: capacity += F[i][j]['capacity'] node['capacity'] = capacity source_cap = max(capacity - y_bar[i, i], 0) F.add_edge(-1, i, capacity=source_cap) F.add_edge(i, -2, capacity=max(y_bar[i, i] - capacity, 0)) total_source_cap += source_cap cuts = 0 # solve max flow problems and collect cuts for i in sorted(F.nodes): if i < 0: continue i_capacity = F[-1][i]['capacity'] F[-1][i]['capacity'] = float('inf') cut_val, cut = nx.minimum_cut(F, _s=-1, _t=-2) S, T = cut constr = -1 * (cut_val - total_source_cap) + y_bar[i, i] S.discard(-1) if constr - EPSILON > 0: lhs = sum_edges(S, x) rhs = grb.quicksum(y[v, v] for v in S if v != i) model.cbCut(lhs <= rhs) cuts += 1 rhs_bar = grb.quicksum(y_bar[v, v] for v in S if v != i) lhs_bar = sum_edges(S, x_bar) if lhs_bar.getValue() <= rhs_bar.getValue(): # print('not violated: ', lhs_bar.getValue(), '<=', rhs_bar.getValue()) pass else: pass else: rhs_bar = grb.quicksum(y_bar[v, v] for v in S if v != i).getValue() lhs_bar = sum_edges(S, x_bar).getValue() if lhs_bar > rhs_bar: # print('violated: ', lhs_bar, '>', rhs_bar) pass F[-1][i]['capacity'] = i_capacity F[i][-2]['capacity'] = float('inf') if cuts >= model._args.max_cuts: return cuts return cuts def add_gsecs(model, x, y, cycles): for cycle in cycles: ysum = grb.quicksum(y[v, v] for v in cycle) lhs = sum_edges(cycle, x) for k in cycle: if lhs <= (ysum - y[k, k]): model.cbLazy(lhs <= (ysum - y[k, k])) def edge_weight(x, i, j): if (i, j) not in x: return x[j, i] if (j, i) not in x: return x[i, j] return max(x[i, j], x[j, i]) def path_length_by_x(p, x_vals): length = 0 for i, j in pairwise(p): length += 1 - edge_weight(x_vals, i, j) return length def heuristics(G, x, y, x_val, y_val, model): selected = {} limit = 0.7 while len(selected) < 2: selected = {i for i in G.nodes if y_val[i, i] >= limit} limit -= 0.1 if limit < 0: return # selected = {i for i in G.nodes # if y_val[i, i] > random()} for i, j in G.edges: G[i][j]["lp_weight"] = 1 - edge_weight(x_val, i, j) sp = dict(nx.shortest_path(G, weight="lp_weight")) # spl = {u: {v: path_length_by_x(p, x_val) # for v, p in d.items()} # for u, d in sp.items()} spl = dict(nx.shortest_path_length(G, weight="lp_weight")) GS = nx.Graph() for i in selected: for j in selected: if i >= j: continue GS.add_edge(i, j, weight=spl[i][j]) mst = nx.algorithms.tree.minimum_spanning_tree(GS) S = set() for i, j in mst.edges: S = S.union(sp[i][j]) GH = G.subgraph(S) mst = nx.algorithms.tree.minimum_spanning_tree(GH) for i in G.nodes: for j in G.nodes: model.cbSetSolution(y[i, j], 0) other_node = -1 if i in S: model.cbSetSolution(y[i, i], 1) else: min_cost = None other_node = None for j in S: a_cost = d(G, i, j) if min_cost is None: min_cost = a_cost other_node = j elif a_cost <= min_cost: other_node = j min_cost = d(G, i, j) model.cbSetSolution(y[i, other_node], 1) for i, j in G.edges: model.cbSetSolution(edge(x, i, j), 1 if (i, j) in mst.edges else 0) if model._args.debug: print("Heuristics cost:", mtp.cost(mst, G)) print("Gurobi cost:", model.cbUseSolution()) model._mst = mst def callback(G, x, y, model, where): if where == grb.GRB.callback.MIPSOL: x_val = model.cbGetSolution(x) y_val = model.cbGetSolution(y) g = nx.Graph() for i, j in x_val.keys(): if x_val[i, j] > 0.5: g.add_edge(i, j) cycles = nx.cycle_basis(g) add_gsecs(model, x, y, cycles) elif where == grb.GRB.callback.MIPNODE: x_val = model.cbGetNodeRel(x) y_val = model.cbGetNodeRel(y) status = model.cbGet(grb.GRB.Callback.MIPNODE_STATUS) nodecount = model.cbGet(grb.GRB.Callback.MIPNODE_NODCNT) if status == grb.GRB.OPTIMAL \ and model._args.max_cuts > 0: cuts = separate_gsec_rel(model, x, y, x_val, y_val, G) if cuts > 0: # print("Generated", cuts, "cuts.") pass # 0 # return if status == grb.GRB.OPTIMAL \ and not model._args.no_heuristics \ and model._last_node < nodecount - 25: model._last_node = nodecount heuristics(G, x, y, x_val, y_val, model) def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument("mtp", help="The MTP instance as a stp file") parser.add_argument("--time", "-t", help="Output optimisation timings") parser.add_argument("--time-limit", "-l", help="Set timelimit for the gurobi optimiser", type=int) parser.add_argument("-r", "--repeat", metavar="<n>", help="Repeat the optimisation n times - only makes sense with the -t switch", type=int, default=1) parser.add_argument("--no-heuristics", action="store_true", default=False) parser.add_argument("--strengthen", action="store_true", default=False) parser.add_argument("--max-cuts", type=int, default=25, help="The max number of user cuts to be made at each node") parser.add_argument("--debug", action="store_true", default=False) args = parser.parse_args() runs = [] with open(args.mtp) as fp: g, int_only = load_mtp(fp) for i in range(args.repeat): if args.time is not None: start = time.time() model, x, y = build_ilp_model(g, args) model.Params.lazyConstraints = 1 if args.max_cuts > 0: model.Params.preCrush = 1 if not args.no_heuristics: # Disable Gurobi Heuristics model.Params.heuristics = 0 if args.time_limit: model.Params.timeLimit = args.time_limit model._args = args model._int_only = int_only model._last_node = -49 model.modelSense = grb.GRB.MINIMIZE for v in g.nodes: y[v, v].setAttr(grb.GRB.Attr.BranchPriority, 2) model.optimize(lambda m, w: callback(g, x, y, m, w)) x_val = model.getAttr("X", x) y_val = model.getAttr("X", y) g_fin = nx.Graph() seen = set() print("Facility:") for i, j in x_val.keys(): if x_val[i, j] > 0.5: seen.add(i) seen.add(j) print(i, j, x_val[i, j], g.adj[i][j]["weight"]) g_fin.add_edge(i, j) print("Assignments:") for i in g.nodes: for j in g.nodes: if y_val[i, j] > 0: print(i, j, y_val[i, j], d(g, i, j)) print(model.status) if args.time is not None: end = time.time() runs.append((model.status, end - start, model.objBound, model.objVal)) if args.time is not None: directory = os.path.join(args.time, args.mtp.split("/")[-2]) filename = args.mtp.split("/")[-1] + "." + str(time.time()) directory += "-h+" if not args.no_heuristics else "-h" directory += "-s+" if args.strengthen else "-s" directory += "-MC{}".format(args.max_cuts) if not os.path.exists(directory): os.makedirs(directory) with open(os.path.join(directory, filename), "w") as f: for st, timing, bound, obj in runs: print(g.number_of_nodes(), g.number_of_edges(), st, timing, bound, obj, file=f) if __name__ == "__main__": main() <file_sep>/util/make-table.sh #! /usr/bin/env bash if [[ -z $1 ]]; then echo "no args" exit 1 fi name=$1 util/${name}-table.py timings/ > ~/repos/final-boss/report/${name}-table.tex && cat ~/repos/final-boss/report/${name}-table.tex <file_sep>/makefile CONFIGS="--max-cuts 0 --no-heuristics; --max-cuts 1 --no-heuristics; --max-cuts 25 --no-heuristics; ; --no-heuristics --strengthen" OPTS="-r 5 -t 5 -l bench.log" benchmarks: echo $(CONFIGS) | util/run-tests.sh $(OPTS) data/tests/JMP-60/* data/tests/JMP-80/* <file_sep>/rust/cplex/Cargo.toml [package] name = "cplex" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [build-dependencies] bindgen = "0.35.0" glob = "0.2.11" <file_sep>/mtp/truncate_instance.py #! /usr/bin/env python3 import networkx as nx import gurobipy as grb import numpy as np import random import sys import argparse import itertools import mtp from stp import load_mtp, write_stp DESCRIPTION = """ Converts an STP PCSTP instance to a MTP instance using various methods: -- """ INF = float('inf') def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument("-f", help="The mtp instance as a stp file") parser.add_argument("--nodes", "-n", help="Desired number of nodes", type=int) parser.add_argument("--edges", "-e", help="Desired number of edges", type=int) args = parser.parse_args() if args.f is not None: with open(args.f) as fp: g, int_only = load_mtp(fp) else: g, int_only = load_mtp(sys.stdin) gp = mtp.truncate(g, args.nodes, args.edges) write_stp(gp) if __name__ == "__main__": main() <file_sep>/util/gather_tests.py import os import operator from functools import reduce ST = {"2": "OPT", "9": "TIMEOUT"} class TestCase(object): _time = None _var = None heuristics = None max_cuts = None def __init__(self, runs, path): self.opt = True self.n = len(runs) times = [] self.V = runs[0][0] if reduce(operator.__eq__, (n for n, *_ in runs)) else None self.E = runs[0][1] if reduce(operator.__eq__, (m for _, m, *_ in runs)) else None self.bound = float("inf") for n, m, st, t, b, v in runs: self.obj = v self.bound = min(self.bound, b) if st != "OPT": self.opt = False times.append(t) self.gap = max((self.obj - self.bound) / self.obj, 0) self.times = times # xxxx/timings/series-size-keys exploded = path.split("/") series_with_keys, test = exploded[exploded.index("timings")+1:] # Extract options and series exploded = series_with_keys.split("-") self.series = "-".join(exploded[:2]) for opt in exploded[2:]: if opt.startswith("MC"): self.max_cuts = int(opt[2:]) elif opt == "h": self.heuristics = False elif opt == "h+": self.heuristics = True elif opt == "s": self.strengthen = False elif opt == "s+": self.strengthen = True # Extract Name exploded = test.split(".") stp = exploded.index("stp") self.name = ".".join(exploded[:stp]) @property def mean(self): if self._time is not None: return self._time self._time = sum(self.times) / self.n return self.mean @property def var(self): if self._var is not None: return self._var self._var = sum((t - self.mean)**2 for t in self.times) / self.n return self.var def read_test(path): runs = [] with open(path) as f: for line in f: n, m, st, t, b, v = line.split() runs.append((int(n), int(m), ST[st], float(t), float(b), float(v))) return TestCase(runs, path) def get_tests(path): for dirpath, dirnames, filenames in os.walk(path): tests = [f for f in filenames if "stp" in f] if len(tests) == 0: continue for testp in tests: yield read_test(os.path.join(dirpath, testp)) def organize_tests(tests): series = {} for test in tests: if test.series not in series: series[test.series] = {} series_dict = series[test.series] if test.name not in series_dict: series_dict[test.name] = [] series_dict[test.name].append(test) return series def tprint(*args, line=True, lb=True, **kwargs): hline = "\\hline" if line else "" lb = " \\\\" if lb else " " end = lb + hline + "\n" print(*args, sep=" & ", end=end, **kwargs) def format_time(tc, lim=-float("inf")): num = "{:.5g}".format(tc.mean) if not tc.opt: num = "\\mathit{" + num + "}^*" elif tc.mean <= lim: num = "\\mathbf{" + num + "}" return "$" + num + "$" def format_times(*args): minarg = min(args, key=lambda tc: tc.mean) return map(lambda x: format_time(x, minarg.mean), args) def format_obj(*tc): for t in tc: if t.opt: return "${:.2f}$".format(t.obj) return "$\\mathit{:.2f}^*$".format(min(tc, key=lambda x: x.obj).obj) def format_gap(g): string = "{:.2%}".format(g) if g < 10e-6: string = "\\mathbf{" + string + "}" return ("$" + string + "$").replace("%", "\\%") def multicol(n, s): return "\multicolumn{{{}}}{{|c|}}{{{}}}".format(n, s) def print_ending(): print(""" %%% %%% Local Variables: %%% TeX-master: "report" %%% reftex-default-bibliography: ("lit.bib") %%% End: """) def get_max_cuts(tcs): for t in tcs: if t.heuristics or t.strengthen: continue if t.max_cuts == 0: zero = t elif t.max_cuts == 1: one = t elif t.max_cuts == 25: tf = t return zero, one, tf def get_heuristics(tcs, mc): for t in tcs: if not t.max_cuts == mc and not t.strengthen: continue if t.heuristics: plus = t else: minus = t return minus, plus def get_strengthen(tcs, mc): for t in tcs: if t.heuristics or not t.max_cuts == mc: continue if t.strengthen: plus = t else: minus = t return minus, plus <file_sep>/util/max-cut-table.py #! /usr/bin/env python3 import sys from gather_tests import (tprint, multicol, print_ending, format_time, format_times, format_obj, format_gap, get_max_cuts, get_tests, organize_tests) def print_max_cut_table(series): cols = 6 tprint("\multirow{2}{*}{Instance}", multicol(3, "$t(s)$"), "\multirow{2}{*}{$GAP$}", "\multirow{2}{*}{$OPT$}", line=False) tprint("", "MC-0", "MC-1", "MC-25", "", "") for sname, tests in series.items(): tprint(lb=False) tprint("", multicol(cols-2, sname), "") names = sorted(tests.keys()) for name in names: a, b, c = get_max_cuts(tests[name]) tprint(name, *format_times(a, b, c), format_gap(max(a.gap, b.gap, c.gap)), format_obj(a, b, c), line=False) tprint("", lb=False) print_ending() def main(): timings_dir = sys.argv[1] if len(sys.argv) > 1 else "./timings" series = organize_tests(get_tests(timings_dir)) print_max_cut_table(series) if __name__ == "__main__": main() <file_sep>/python_gurobi/pcstp/stp.py import networkx as nx def is_int(s): try: int(s) return True except ValueError: return False def chomp_section(f): for line in f: if line.startswith('END'): return def grow_graph(f, g): int_only = True for line in f: if line.startswith('Nodes'): _, num_nodes = line.strip().split() num_nodes = int(num_nodes) for i in range(1, num_nodes + 1): g.add_node(i, prize=0, _prize=0) continue if line.startswith('Edges'): continue if line.startswith('END'): break _, v, u, w = line.strip().split() u = int(u) v = int(v) if is_int(w): w = int(w) else: w = float(w) int_only = False g.add_edge(u, v, weight=w, _weight=w) return int_only def add_terminal_prizes(f, g): N = set() int_only = True for line in f: if line.startswith('Terminals'): continue if line == 'END\n': break _, v, p = line.strip().split() v = int(v) if is_int(p): p = int(p) else: p = float(p) int_only = False N.add(v) g.node[v]['prize'] = g.node[v]['_prize'] = p return N, int_only def load_stp(path): ''' Loads an .stp file into a networkX graph ''' g = nx.Graph() int_only = True with open(path) as f: for line in f: if line.startswith('SECTION'): suffix = line[8:].strip() if suffix == 'Graph': int_only = grow_graph(f, g) elif suffix == 'Terminals': N, int_only_N = add_terminal_prizes(f, g) else: chomp_section(f) return g, N, (int_only and int_only_N) <file_sep>/util/convert.sh #! /usr/bin/env bash if [[ ! -z $1 ]]; then convert=$1 else convert=../mtp/convert.py fi for file in PCSTP/*/*; do [ -e "$file" ] || continue ending=$(echo $file|cut -d'/' -f2-) folders=$(dirname $ending) mkdir -p MTP/$folders if $convert -f $file > MTP/$ending; then echo "converted $file to MTP/$ending" else echo "something went horribly wrong with $file" exit 1 fi done <file_sep>/rust/cplex/build.rs extern crate bindgen; extern crate glob; use glob::glob; use std::env; use std::path::PathBuf; const TYPES : [&'static str; 1] = ["CPXENVptr"]; const FUNCTIONS : [&'static str; 1] = ["CPXopenCPLEX"]; fn main () { let mut builder = bindgen::Builder::default() // The input header we would like to generate // bindings for. .header("wrapper.h"); // Link with cplex for prefix in glob("/opt/ibm/ILOG/*/cplex/").unwrap() { let prefix = prefix.unwrap(); for path in glob(&format!("{}/lib/*/static_pic/", prefix.display())).unwrap() { match path { Ok(libdir) => println!("cargo:rustc-link-search=native={}", libdir.display()), Err(e) => println!("{:?}", e) } } builder = builder.clang_arg(format!("-I{}/include/ilcplex", prefix.display())); } println!("cargo:rustc-link-lib=static=cplex"); builder = TYPES.into_iter().fold(builder, |b, t| b.whitelist_type(t)); builder = FUNCTIONS.into_iter().fold(builder, |b, f| b.whitelist_function(f)); let bindings = builder.generate() .expect("Unable to generate bindings"); // Write the bindings to the $OUT_DIR/bindings.rs file. let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); } <file_sep>/util/run-tests.sh #! /usr/bin/env bash function usage () { echo "Usage:" echo "util/run-tests.sh [-t <per run timeout in minutes>] [-r < #repitions>] [-l <logfile>] [tests...]" echo "Default is 10 repetions with 10 minute timeout" echo "Timings will be placed in ./timings" echo echo "Be the root folder of the repo" exit 2 } if [[ ! -f "mtp/main.py" ]]; then echo "Error: \"mtp/main.py\" is not a file" usage fi args=`getopt ht:r:l: $*` # you should not use `getopt abo: "$@"` since that would parse # the arguments differently from what the set command below does. if [[ $? != 0 ]]; then usage exit 2 fi set -- $args reps=10 timeout=$[10*60] log="" for i; do case "$i" in "-r") reps="$2" shift; shift;; "-t") timeout=$["$2"*60] shift; shift;; "-h") usage;; "-l") log="$2" shift; shift;; "--") shift break;; esac done extra_args=$(cat) declare -a args_array if [[ -z extra_args ]]; then args_array[0] = "" else IFS=';' read -r -a args_array <<< "$extra_args" fi n=$[${#}*${#args_array[@]}] echo "Running $n tests" i=1 for stp in $@; do for extra_args in "${args_array[@]}"; do echo "Running test $i out of $n" cmd="mtp/main.py -r $reps -l $timeout -t ./timings $stp" if [[ ! -z $extra_args ]]; then cmd="$cmd $extra_args" fi echo $cmd if [[ -z $log ]]; then $cmd else $cmd &> $log fi if [[ $? != 0 ]]; then echo "Something went wrong with running $stp" exit 1 fi let "i++" done done <file_sep>/python_gurobi/pcstp/main.py #! /usr/bin/env python3 import networkx as nx import gurobipy as grb import numpy as np import argparse import itertools from pcst_fast import pcst_fast from stp import load_stp DESCRIPTION = """ Solves an instance of the PCSTP using Gurobi Python. """ BIG_INT = np.iinfo(np.int64).max BIG_FLOAT = np.finfo(np.float64).max EPSILON = 10**(-9) MAX_CUTS = 1 def build_ilp_model(g): model = grb.Model('pcstp') x = model.addVars(g.edges, vtype=grb.GRB.BINARY) y = model.addVars(g.nodes, vtype=grb.GRB.BINARY) # OBJECTIVE edge_costs = grb.quicksum(g[i][j]['weight'] * x[i, j] for i, j in g.edges) prize_cost = grb.quicksum(g.node[v]['prize'] * (1 - y[v]) for v in g.nodes) model.setObjective(edge_costs + prize_cost) # one less edges than vertices model.addConstr(x.sum() == (y.sum() - 1), name='x.sum == y.sum - 1') # Add all |S| = 2 GSECS for i, j in g.edges: model.addConstr(x[i, j] <= y[i]) model.addConstr(x[i, j] <= y[j]) # degree of nonterminals must be at least 2 # for v in g.node: # if g.node[v]['prize'] > 0: # continue # model.addConstr(x.sum(v, '*') + x.sum('*', v) >= 2 * y[v]) return model, x, y def sum_edges(S, x): lhs = grb.LinExpr() for i, j in itertools.combinations(S, 2): if (i, j) in x: lhs.add(x[i, j]) elif (j, i) in x: lhs.add(x[j, i]) return lhs def separate_gsec_rel(model, x, y, x_bar, y_bar, G): F = nx.DiGraph() F.add_node(-1) # source F.add_node(-2) # sink for v in G.node: F.add_node(v) for i, j in G.edges: capacity = x_bar[i, j] / 2 F.add_edge(i, j, capacity=capacity) F.add_edge(j, i, capacity=capacity) total_source_cap = 0 for i in G.nodes: node = F.node[i] capacity = 0 for j in G.adj[i]: capacity += F[i][j]['capacity'] node['capacity'] = capacity source_cap = max(capacity - y_bar[i], 0) F.add_edge(-1, i, capacity=source_cap) F.add_edge(i, -2, capacity=max(y_bar[i] - capacity, 0)) total_source_cap += source_cap cuts = 0 # solve max flow problems and collect cuts for i in sorted(F.nodes): if i < 0: continue i_capacity = F[-1][i]['capacity'] F[-1][i]['capacity'] = float('inf') cut_val, cut = nx.minimum_cut(F, _s=-1, _t=-2) S, T = cut constr = -1 * (cut_val - total_source_cap) + y_bar[i] S.discard(-1) if constr > 0: rhs = grb.quicksum(y[v] for v in S if v != i) lhs = sum_edges(S, x) model.cbCut(lhs <= rhs) cuts += 1 rhs_bar = grb.quicksum(y_bar[v] for v in S if v != i) lhs_bar = sum_edges(S, x_bar) if lhs_bar.getValue() <= rhs_bar.getValue(): print('not violated: ', lhs_bar.getValue(), '<=', rhs_bar.getValue()) else: rhs_bar = grb.quicksum(y_bar[v] for v in S if v != i).getValue() lhs_bar = sum_edges(S, x_bar).getValue() if lhs_bar > rhs_bar: print('violated: ', lhs_bar, '>', rhs_bar) F[-1][i]['capacity'] = i_capacity F[i][-2]['capacity'] = float('inf') if cuts >= MAX_CUTS: return cuts return cuts def add_gsecs(model, x, y, cycles): for cycle in cycles: ysum = grb.quicksum(y[v] for v in cycle) lhs = sum_edges(cycle, x) for k in cycle: model.cbLazy(lhs <= (ysum - y[k])) def callback(G, x, y, model, where): if where == grb.GRB.callback.MIPSOL: x_val = model.cbGetSolution(x) # y_val = model.cbGetSolution(y) g = nx.Graph() for i, j in x_val.keys(): if x_val[i, j] > 0.5: g.add_edge(i, j) cycles = nx.cycle_basis(g) add_gsecs(model, x, y, cycles) elif where == grb.GRB.callback.MIPNODE: x_val = model.cbGetNodeRel(x) y_val = model.cbGetNodeRel(y) status = model.cbGet(grb.GRB.Callback.MIPNODE_STATUS) nodecount = model.cbGet(grb.GRB.Callback.MIP_NODCNT) if status == grb.GRB.OPTIMAL: cuts = separate_gsec_rel(model, x, y, x_val, y_val, G) # if cuts > 0: # 0 # return if status == grb.GRB.OPTIMAL: model._last_node = nodecount for v in G.node: node = G.node[v] if y_val[v] > 0.5: node['prize'] = BIG_INT else: node['prize'] = node['_prize'] for i, j in G.edges: edge = G[i][j] edge['weight'] = BIG_FLOAT if x_val[i, j] < 0.1 else edge['_weight'] gw_nodes, gw_edges = gw(G) for v in G.nodes: model.cbSetSolution(y[v], 1 if v in gw_nodes else 0) for i, j in G.edges: model.cbSetSolution(x[i, j], 1 if (i, j) in gw_edges else 0) def gw(g): _e = [(i-1, j-1) for i, j in g.edges] # print(_e, len(g.node)) edges = np.array(_e, dtype='int64') costs = np.array([g[i][j]['weight'] for i, j in g.edges], dtype='float64') prizes = np.array([g.node[v]['prize'] for v in sorted(g.node)], dtype='int64') gw_nodes, gw_edges = pcst_fast(edges, prizes, costs, -1, 1, 'strong', 0) # print(gw_edges) return set(v+1 for v in gw_nodes), set((i+1, j+1) for i, j in edges[gw_edges]) def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument('pcstp', help='The PCSTP instance as a stp file') args = parser.parse_args() g, N, int_only = load_stp(args.pcstp) model, x, y = build_ilp_model(g) # Get GW initial solution gw_nodes, gw_edges = gw(g) for v in g.nodes: y[v].start = 1 if v in gw_nodes else 0 y[v].setAttr(grb.GRB.Attr.BranchPriority, 2 if v in N else 0) for i, j in g.edges: x[i, j].start = 1 if (i, j) in gw_edges else 0 model.Params.lazyConstraints = 1 model.Params.preCrush = 1 model.Params.heuristics = 0 model._int_only = int_only model._last_node = 0 model.modelSense = grb.GRB.MINIMIZE model.optimize(lambda m, w: callback(g, x, y, m, w)) if __name__ == '__main__': main() <file_sep>/util/generate-testcases.sh #! /usr/local/bin/bash # We assume that the MTP files are at data/MTP/** # The test cases are placed at data/tests/<series>/file if [[ ! -z $1 ]]; then truncate=$1 else truncate=../mtp/truncate_instance.py fi function trunc() { dir=$1 file=$2 [ -e "$file" ] || continue mkdir -p $dir base=$(basename $file) if $truncate -f $file -n $3 -e $4 > $dir/$base; then echo "truncated $file to $dir/$base" else echo "something went horribly wrong with $file" exit 1 fi } # 100 -> 65 400 -> 85 for file in MTP/JMP/K100*.stp; do trunc "tests/JMP-60" $file 60 120 done for file in MTP/JMP/K400*.stp; do trunc "tests/JMP-80" $file 80 170 done # For completeness sake, we also take the JMP 100 full versions # mkdir -p tests/JMP-100 # cp MTP/JMP/*100* tests/JMP-100 <file_sep>/util/get-files.sh #! /usr/bin/env bash CURDIR=$(pwd) cd $TMPDIR function dimacs() { name=$1 mkdir -p $CURDIR/PCSTP/$name curl http://dimacs11.zib.de/instances/PCSPG-$name.zip -o PCSPG-$name.zip unzip PCSPG-$name.zip mv PCSPG-$name/* $CURDIR/PCSTP/$name } dimacs JMP dimacs CRR dimacs PUCNU
d335f0f4ad3e00f56f69dda28054d86f4726a352
[ "TOML", "Makefile", "Rust", "Python", "C", "Shell" ]
21
Python
wsprent/thesis-code
67f50ec140287449982af68b9c81f33fb20b93a1
eb7758bddb9b52840f178c6cb03af6be6bebd6e6
refs/heads/master
<file_sep>local AddonName, Addon = ... local function print(msg) Addon:Print("FrameTest", msg) end -- Lib local DFL = Addon.DethsFrameLib -- Frames local FrameTest = Addon.Frames.FrameTest local ParentTest = Addon.Frames.ParentTest -- Test entry point function FrameTest:OnCmd(cmd, ...) local buttonGrid = self.ButtonGrid local scrollFrames = self.Scrollframes if (cmd == "alignment") then local children = buttonGrid:GetChildren() for _, child in pairs(children) do child:SetAlignment(...) end elseif (cmd == "direction") then scrollFrames:SetDirection(...) elseif (cmd == "layout") then scrollFrames:SetLayout(...) elseif (cmd == "padding") then local x, y = ... local child = buttonGrid child:SetPadding(tonumber(x), tonumber(y)) elseif (cmd == "spacing") then local spacing = ... frame:SetSpacing(tonumber(spacing)) elseif (cmd == "text") then local button = buttonGrid:GetChildren()[1]:GetChildren()[1] button:SetText(...) end end -- ============================================================================ -- OnInitialize() -- ============================================================================ function FrameTest:OnInitialize() local frame = self.Frame frame:SetDirection(DFL.Directions.DOWN) frame:SetSpacing(DFL:Padding(0.25)) self:CreateButtonGrid(frame) self:CreateCheckButtons(frame) self:CreateSliders(frame) self:CreateScrollFrame(frame) self:CreateFauxScrollFrame(frame) end -- ============================================================================ -- Button Grid -- ============================================================================ function FrameTest:CreateButtonGrid(parent) local buttonGrid = DFL.Frame:Create(parent, "CENTER", "DOWN") buttonGrid:SetColors(DFL.Colors.Area) buttonGrid:SetPadding(DFL:Padding(0.5)) buttonGrid:SetSpacing(DFL:Padding(0.25)) DFL:AddBorder(buttonGrid) do -- Alignment local buttonRow = DFL.Frame:Create(buttonGrid, "CENTER") buttonRow:SetSpacing(DFL:Padding(0.25)) buttonRow:SetMinHeight(100) buttonGrid:Add(buttonRow) local data = { { text = "A-Left", align = "LEFT" }, { text = "A-Center", align = "CENTER" }, { text = "A-Right", align = "RIGHT" }, } for k, v in ipairs(data) do -- Alignment local b = DFL.Button:Create(buttonRow, v.text) b:SetMinHeight(math.random(20, 60)) b:SetMinWidth(math.random(20, 60)) function b:OnClick(button, down) for _, row in pairs(buttonGrid:GetChildren()) do row:SetAlignment(v.align) end end DFL:AddBorder(b, unpack(DFL.Colors.Frame)) buttonRow:Add(b) end end do -- Direction local buttonRow = DFL.Frame:Create(buttonGrid, "CENTER") buttonRow:SetSpacing(DFL:Padding(0.25)) buttonGrid:Add(buttonRow) local data = { { text = "D-Right", dir = "RIGHT" }, { text = "D-Left", dir = "LEFT" }, { text = "D-Down", dir = "DOWN" }, { text = "D-Up", dir = "UP" }, } for k, v in ipairs(data) do -- Alignment local b = DFL.Button:Create(buttonRow, v.text) b:SetMinHeight(math.random(20, 60)) b:SetMinWidth(math.random(20, 60)) function b:OnClick(button, down) for _, row in pairs(buttonGrid:GetChildren()) do row:SetDirection(v.dir) end end DFL:AddBorder(b, unpack(DFL.Colors.Frame)) buttonRow:Add(b) end end do -- Layout local buttonRow = DFL.Frame:Create(buttonGrid, "CENTER") buttonRow:SetSpacing(DFL:Padding(0.25)) buttonGrid:Add(buttonRow) local data = { { text = "Flow", layout = "FLOW" }, { text = "Flow E", layout = "FLOW_EQUAL" }, { text = "Flow W", layout = "FLOW_EQUAL_W" }, { text = "Flow H", layout = "FLOW_EQUAL_H" }, { text = "Flex", layout = "FLEX" }, { text = "Flex E", layout = "FLEX_EQUAL" }, { text = "Flex W", layout = "FLEX_EQUAL_W" }, { text = "Flex H", layout = "FLEX_EQUAL_H" }, { text = "Fill", layout = "FILL" }, { text = "Fill W", layout = "FILL_W" }, { text = "Fill H", layout = "FILL_H" } } for k, v in ipairs(data) do -- Alignment local b = DFL.Button:Create(buttonRow, v.text) b:SetMinHeight(math.random(20, 60)) b:SetMinWidth(math.random(20, 60)) function b:OnClick(button, down) for _, row in pairs(buttonGrid:GetChildren()) do row:SetLayout(v.layout) end end DFL:AddBorder(b, unpack(DFL.Colors.Frame)) buttonRow:Add(b) end end parent:Add(buttonGrid) self.ButtonGrid = buttonGrid end -- ============================================================================ -- Check Buttons -- ============================================================================ function FrameTest:CreateCheckButtons(parent) local checkButtons = DFL.Frame:Create(parent, "CENTER") checkButtons:SetPadding(DFL:Padding()) checkButtons:SetSpacing(DFL:Padding()) for i = 1, 2 do local text = "Check Button "..i local cb = DFL.CheckButton:Create(checkButtons, text, "This is a check button.") function cb:SetUserValue(checked) print(text.." is now "..(checked and "on." or "off.")) end checkButtons:Add(cb) end parent:Add(checkButtons) self.CheckButtons = checkButtons end -- ============================================================================ -- Sliders -- ============================================================================ function FrameTest:CreateSliders(parent) local sliders = DFL.Frame:Create(parent, "CENTER", "DOWN", "FLOW_EQUAL") sliders:SetSpacing(DFL:Padding(0.5)) do -- Padding sliders:Add(DFL.FontString:Create(sliders, "Padding")) local s = DFL.Slider:Create(sliders) s:SetOrientation(DFL.Orientations.HORIZONTAL) s:SetMinMaxValues(parent:GetPadding().X, 100) s:SetValueStep(1) s:SetWidth(150) s:SetShowTooltip(true) function s:SetUserValue(value) parent:SetPadding(value) end sliders:Add(s) end do -- Spacing sliders:Add(DFL.FontString:Create(sliders, "Spacing")) local s = DFL.Slider:Create(sliders) s:SetOrientation(DFL.Orientations.HORIZONTAL) s:SetMinMaxValues(parent:GetSpacing(), 100) s:SetValueStep(1) s:SetWidth(100) s:SetShowTooltip(true) function s:SetUserValue(value) parent:SetSpacing(value) end sliders:Add(s) end parent:Add(sliders) self.Sliders = sliders end -- ============================================================================ -- ScrollFrame -- ============================================================================ function FrameTest:CreateScrollFrame(parent) local frame = DFL.Frame:Create(parent, DFL.Alignments.CENTER) -- frame:SetLayout("FILL") frame:SetPadding(DFL:Padding(0.5)) frame:SetSpacing(DFL:Padding()) for i=1, 2 do local scrollFrame = DFL.ScrollFrame:Create(frame) scrollFrame:SetMinHeight(200/i) scrollFrame:SetMinWidth(100 * i) do -- Frame of check boxes local f = DFL.Frame:Create(scrollFrame, "TOPLEFT", "DOWN") f:SetSpacing(DFL:Padding(0.25)) f:Add(DFL.FontString:Create(f, "Options")) for i=1, 3 do local cb = DFL.CheckButton:Create(f, "Option #"..i, "Tooltip for option #"..i) function cb:SetUserValue(checked) local text = checked and ("Checked CB #"..i) or ("Unchecked CB #"..i) scrollFrame:Add(DFL.FontString:Create(scrollFrame, text)) end f:Add(cb) end scrollFrame:Add(f) end do -- EditBox local ebArgs = { {}, {5, false, DFL.Fonts.Huge}, {[2] = true}, {8, true} } for _, args in ipairs(ebArgs) do local eb = DFL.EditBox:Create(scrollFrame, args[1], args[2], args[3]) eb:SetMinWidth(200) scrollFrame:Add(eb) end end frame:Add(scrollFrame) end -- TextArea do local textArea = DFL.TextArea:Create(frame) textArea:SetMinWidth(250) textArea:SetMinHeight(100) frame:Add(textArea) end parent:Add(frame) self.Scrollframes = frame end -- ============================================================================ -- FauxScrollFrame -- ============================================================================ do local GetMouseFocus = GetMouseFocus local function setData(self, data) if (self._data == data) then return end self._data = data self.Text:SetText(data.text) self.Tooltip = data.tooltip if self:IsEnabled() and (GetMouseFocus() == self) then self:GetScript("OnEnter")(self) end end local function setColors(self, textureColor, textColor) self.Text:SetTextColor(unpack(DFL.Colors.Text)) end local function onSetEnabled(self, enabled) DFL:SetEnabledAlpha(self, enabled) end local function onEnter(self) DFL:ShowTooltip(self, DFL.Anchors.TOP, self.Text:GetText(), self.Tooltip) end local function onLeave(self) DFL:HideTooltip() end local function createObject(parent) local button = DFL.Creator:CreateButton(parent) button:SetWidth(300) button:SetHeight(32) DFL:AddBorder(button) button.Texture = DFL.Creator:CreateTexture(button) button.Texture:SetColorTexture(unpack(DFL.Colors.Button)) button.Text = DFL.Creator:CreateFontString(button, "OVERLAY", DFL.Fonts.Normal) button.Text:SetPoint("LEFT", DFL:Padding(0.5), 0) button.Text:SetPoint("RIGHT", -DFL:Padding(0.5), 0) button.Text:SetWordWrap(false) button.Text:SetJustifyH("LEFT") DFL:AddDefaults(button) button.SetData = setData button.SetColors = setColors button.OnSetEnabled = onSetEnabled button:SetScript("OnEnter", onEnter) button:SetScript("OnLeave", onLeave) button:SetColors() return button end local data = { { text = "Hello, world!", tooltip = "Tooltip #1" }, { text = "This is a test.", tooltip = "Tooltip #2" }, { text = "More text, more text, more text!", tooltip = "Tooltip #3" }, { text = "Lorem ipsumthing, omg much text wow.", tooltip = "Tooltip #4" }, { text = "This text is very, very, very loooooooooooooooooooooooooooooong.", tooltip = "Tooltip #5" }, } function FrameTest:CreateFauxScrollFrame(parent) local frame = DFL.Frame:Create(parent, DFL.Alignments.CENTER) frame:SetPadding(DFL:Padding(0.5)) frame:SetSpacing(DFL:Padding(0.5)) frame:Add(DFL.FauxScrollFrame:Create(frame, data, createObject, 3)) parent:Add(frame) self.FauxScrollFrame = frame end end <file_sep>local AddonName, Addon = ... local function print(msg) Addon:Print("ParentTest", msg) end -- Libs local DFL = Addon.DethsFrameLib -- Frames local ParentTest = Addon.Frames.ParentTest -- Test entry point function ParentTest:OnCmd(cmd, ...) if (cmd == "enable") then self:SetEnabled(true) elseif (cmd == "disable") then self:SetEnabled(false) elseif (cmd == "alignment") then self:SetAlignment(...) elseif (cmd == "direction") then self:SetDirection(...) elseif (cmd == "layout") then self:SetLayout(...) elseif (cmd == "padding") then local x, y = ... self:SetPadding(tonumber(x), tonumber(y)) elseif (cmd == "spacing") then local spacing = ... self:SetSpacing(tonumber(spacing)) elseif (cmd == "scale") then local scale = ... self:SetScale(tonumber(scale)) elseif (cmd == "title") then self.TitleFontString:SetText(...) self:Resize() elseif (cmd == "refresh") then self:Refresh() print("Refreshing...") elseif (cmd == "resize") then self:Resize() print("Resizing...") end end -- ============================================================================ -- OnInitialize() -- ============================================================================ function ParentTest:OnInitialize() local frame = ParentTest.Frame frame:SetPadding(DFL:Padding(0.5)) frame:SetSpacing(DFL:Padding(0.25)) self:CreateTitle(frame) self.CreateTitle = nil end -- ============================================================================ -- Test Functions -- ============================================================================ function ParentTest:CreateTitle() local titleFrame = DFL.ChildFrame:Create() titleFrame:Initialize() local frame = titleFrame.Frame frame:SetAlignment(DFL.Alignments.CENTER) frame:SetLayout(DFL.Layouts.FLEX) frame:SetSpacing(DFL:Padding()) local titleText = DFL.FontString:Create(frame, AddonName, DFL.Fonts.Small) self.TitleFontString = titleText frame:Add(titleText) local closeButton = DFL.Button:Create(frame, "X", DFL.Fonts.Small) DFL:AddBorder(closeButton) function closeButton:OnClick() ParentTest:Hide() end frame:Add(closeButton) closeButton.SetEnabled = nop self:SetTitle(titleFrame) end <file_sep>-- CheckButton: contains functions to create a DFL check button. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local assert, ceil, pairs, type, unpack = assert, ceil, pairs, type, unpack -- CheckButton local CheckButton = DFL.CheckButton CheckButton.Scripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL check button. -- @param parent - the parent frame -- @param text - the string to set the check button's text [optional] -- @param tooltip - the body text of the tooltip shown when highlighted [optional] -- @param font - the font of the check button's text [optional] function CheckButton:Create(parent, text, tooltip, font) local frame = DFL.Creator:CreateFrame(parent) frame._tooltip = tooltip local checkButton = DFL.Creator:CreateCheckButton(frame) checkButton:SetPoint("TOPLEFT") frame._checkButton = checkButton frame._texture = DFL.Creator:CreateTexture(checkButton) frame._label = DFL.FontString:Create(checkButton, text, font) frame._label:SetPoint("LEFT", checkButton, "RIGHT", DFL:Padding(0.5), 0) DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) DFL:AddScripts(checkButton, self.Scripts) frame:SetColors() frame:Refresh() return frame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = CheckButton.Functions function Functions:GetChecked() return self._checkButton:GetChecked() end function Functions:SetChecked(checked) self._checkButton:SetChecked(checked) if self.SetUserValue then self:SetUserValue(checked) end end function Functions:GetText() return self._label:GetText() end function Functions:SetText(text) self._label:SetText(text) DFL:ResizeParent(self) end function Functions:GetTooltip() return self._tooltip end function Functions:SetTooltip(tooltip) self._tooltip = tooltip end function Functions:SetColors(textColor, textureColor, borderColor) self._label:SetColors(textColor) self._textureColor = textureColor or self._textureColor or DFL.Colors.Area self._borderColor = borderColor or self._borderColor or DFL.Colors.Black end function Functions:OnSetEnabled(enabled) DFL:SetEnabledAlpha(self, enabled) self._checkButton:SetEnabled(enabled) end function Functions:Refresh() self._label:Refresh() self._texture:SetColorTexture(unpack(self._textureColor)) DFL:AddBorder(self._checkButton, unpack(self._borderColor)) if self.GetUserValue then self._checkButton:SetChecked(self:GetUserValue()) end end function Functions:Resize() local cbSize = ceil(self._label:GetStringHeight()) + DFL:Padding(0.3) local width = ceil(cbSize + self._label:GetStringWidth() + DFL:Padding(0.5)) self._checkButton:SetWidth(cbSize) self._checkButton:SetHeight(cbSize) self:SetSize(width, cbSize) end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = CheckButton.Scripts function Scripts:OnClick() local parent = self:GetParent() if parent.SetUserValue then parent:SetUserValue(self:GetChecked()) end end function Scripts:OnEnter() local parent = self:GetParent() if parent._tooltip then DFL:ShowTooltip(parent, DFL.Anchors.TOP, parent._label:GetText(), parent._tooltip) end end Scripts.OnLeave = DFL.HideTooltip end <file_sep>-- Button: contains functions to create a DFL button. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local GetMouseFocus = GetMouseFocus local ceil, pairs, unpack = ceil, pairs, unpack -- Button local Button = DFL.Button Button.Scripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL button. -- @param parent - the parent frame -- @param text - the string to set the button's text [optional] -- @param font - the font of the button's text [optional] function Button:Create(parent, text, font) local button = DFL.Creator:CreateButton(parent) button._texture = DFL.Creator:CreateTexture(button) button._label = DFL.FontString:Create(button, text, font) button:SetFontString(button._label) DFL:AddDefaults(button) DFL:AddMixins(button, self.Functions) DFL:AddScripts(button, self.Scripts) button:SetColors() button:Refresh() return button end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = Button.Functions -- Sets the text for the button. function Functions:SetText(text) self._label:SetText(text) DFL:ResizeParent(self) end function Functions:SetColors(color, colorHi, textColor, textColorHi, borderColor) self._color = color or self._color or DFL.Colors.Button self._colorHi = colorHi or self._colorHi or DFL.Colors.ButtonHi self._textColor = textColor or self._textColor or DFL.Colors.Text self._textColorHi = textColorHi or self._textColorHi or DFL.Colors.White self._borderColor = borderColor or self._borderColor end function Functions:OnSetEnabled(enabled) DFL:SetEnabledAlpha(self, enabled) end function Functions:Refresh() if (self == GetMouseFocus()) then self:GetScript("OnEnter")(self) else self:GetScript("OnLeave")(self) end if self._borderColor then DFL:AddBorder(self, unpack(self._borderColor)) end end function Functions:Resize() local width = ceil(self._label:GetStringWidth()) + DFL:Padding() local height = ceil(self._label:GetStringHeight()) + DFL:Padding() if (width < height) then width = height end self:SetSize(width, height) end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = Button.Scripts function Scripts:OnClick(button, down) if self.OnClick then self:OnClick(button, down) end end function Scripts:OnEnter() self._texture:SetColorTexture(unpack(self._colorHi)) self._label:SetTextColor(unpack(self._textColorHi)) end function Scripts:OnLeave() self._texture:SetColorTexture(unpack(self._color)) self._label:SetTextColor(unpack(self._textColor)) end end <file_sep>-- Frame: a frame for DFL objects. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end local Alignments = DFL.Alignments local Directions = DFL.Directions local Layouts = DFL.Layouts -- Upvalues local assert, error, format, ipairs, max, next, pairs, tonumber, type = assert, error, format, ipairs, max, next, pairs, tonumber, type local tinsert, tremove = table.insert, table.remove -- Frame local Frame = DFL.Frame -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL frame. -- @param parent - the parent of the frame -- @param alignment - the alignment of the frame's children [optional] -- @param direction - the growth direction of the frame's children [optional] -- @param layout - the layout style of the frame's children [optional] function Frame:Create(parent, alignment, direction, layout) local frame = DFL.Creator:CreateFrame(parent) frame._alignHelper = DFL.Creator:CreateTexture(frame) -- used to align the canvas with padding in the frame frame._canvas = DFL.Creator:CreateTexture(frame) -- used to position children frame._padding = {X = 0, Y = 0} -- space between frame edges and children frame._spacing = 0 -- space between children frame._children = {} frame._maxChildWidth = 0 frame._maxChildHeight = 0 frame._requiredWidth = 0 frame._requiredHeight = 0 DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) frame:SetDirection(direction) frame:SetAlignment(alignment) frame:SetLayout(layout) return frame end -- ============================================================================ -- Functions -- ============================================================================ local Functions = Frame.Functions -- Adds a child object to the frame. -- @param child - the object to add -- @param index - the index at which to add the object [optional] -- @return true if the object was added function Functions:Add(child, index) assert(child, "child cannot be nil") if self:Contains(child) then return false end if index then index = tonumber(index) or error("index must be a number") assert((index >= 1) and (index <= #self._children+1), "index out of bounds") tinsert(self._children, index, child) else self._children[#self._children+1] = child end child:SetParent(self) if child.Refresh then child:Refresh() end child:Show() DFL:ResizeParent(self) return true end -- Removes a child object from the frame. -- @param child - the object to remove -- @return the removed object, or nil if the object was not found function Functions:Remove(child) local index = self:Contains(child) if not index then return nil end tremove(self._children, index) -- child:ClearAllPoints() -- NOTE: Seems to introduce bugs during ParentFrame:SetContent() child:Hide() DFL:ResizeParent(self) return child end -- Removes all child objects from the frame. function Functions:RemoveAll() for k, child in pairs(self._children) do self._children[k] = nil child:ClearAllPoints() child:Hide() end DFL:ResizeParent(self) end -- Returns the index of the child if it exists within the frame. -- @param child - the object to check for function Functions:Contains(child) for i, v in pairs(self._children) do if (v == child) then return i end end end --[[ Grows children in size based on direction and layout. Frame children are resized to have equal width or height based on direction. Remaining children may be resized to fill space based on layout. --]] function Functions:GrowChildren() local alignHelper = self._alignHelper local children = self._children local direction = self._direction local width, height = alignHelper:GetWidth(), alignHelper:GetHeight() -- Horizontal if (direction == Directions.RIGHT) or (direction == Directions.LEFT) then for _, child in pairs(children) do -- If child is a Frame, grow vertically if DFL:IsType(child, Frame:GetType()) then child:SetHeight(height) -- Otherwise, if using a FILL layout, distribute extra space amongst children elseif self._fill_w or self._fill_h then if self._fill_w then -- Distribute extra width local fillWidth = ((width - self:GetRequiredWidth()) / #children) + self._maxChildWidth if (fillWidth > 0) then for i, child in ipairs(children) do child:SetWidth(fillWidth) end end end if self._fill_h then -- Set child heights to alignHelper height for i, child in ipairs(children) do child:SetHeight(height) end end end end -- Vertical elseif (direction == Directions.DOWN) or (direction == Directions.UP) then for _, child in pairs(children) do -- If child is a Frame, grow horizontally if DFL:IsType(child, Frame:GetType()) then child:SetWidth(width) -- Otherwise, if using a FILL layout, distribute extra space amongst children elseif self._fill_w or self._fill_h then if self._fill_h then -- Distribute extra height local fillHeight = ((height - self:GetRequiredHeight()) / #children) + self._maxChildHeight if (fillHeight > 0) then for i, child in ipairs(children) do child:SetHeight(fillHeight) end end end if self._fill_w then -- Set child widths to alignHelper width for i, child in ipairs(children) do child:SetWidth(width) end end end end else error(format("Unsupported direction: \"%s\"", direction)) end end -- Positions all children within the frame. function Functions:PositionChildren() local alignHelper = self._alignHelper local alignment = self._alignment local canvas = self._canvas local children = self._children local direction = self._direction local flexible = self._flexible local spacing = self._spacing -- Calculate additional spacing for flexible layouts if flexible and (#children > 1) then local flexSpacing, diff = 0, 0 if (direction == Directions.RIGHT) or (direction == Directions.LEFT) then diff = alignHelper:GetWidth() - self:GetRequiredWidth() elseif (direction == Directions.DOWN) or (direction == Directions.UP) then diff = alignHelper:GetHeight() - self:GetRequiredHeight() end diff = (diff >= 0) and diff or 0 flexSpacing = diff / (#children - 1) spacing = spacing + flexSpacing end -- Position children for i, child in ipairs(children) do local prevChild = children[i-1] child:ClearAllPoints() local p1, p2 -- Points local x, y -- Offsets -- Determine points if flexible and (#children == 1) then p1, p2 = Alignments.CENTER, Alignments.CENTER elseif (direction == Directions.RIGHT) or (direction == Directions.LEFT) then -- Align children by top, center, or bottom -- Top if (alignment == Alignments.TOPLEFT) or (alignment == Alignments.TOP) or (alignment == Alignments.TOPRIGHT) then p1, p2 = Alignments.TOPLEFT, Alignments.TOPRIGHT -- Center elseif (alignment == Alignments.LEFT) or (alignment == Alignments.CENTER) or (alignment == Alignments.RIGHT) then p1, p2 = Alignments.LEFT, Alignments.RIGHT -- Bottom elseif (alignment == Alignments.BOTTOMLEFT) or (alignment == Alignments.BOTTOM) or (alignment == Alignments.BOTTOMRIGHT) then p1, p2 = Alignments.BOTTOMLEFT, Alignments.BOTTOMRIGHT end elseif (direction == Directions.DOWN) or (direction == Directions.UP) then -- Align children by left, center, or right -- Left if (alignment == Alignments.TOPLEFT) or (alignment == Alignments.LEFT) or (alignment == Alignments.BOTTOMLEFT) then p1, p2 = Alignments.TOPLEFT, Alignments.BOTTOMLEFT -- Center elseif (alignment == Alignments.TOP) or (alignment == Alignments.CENTER) or (alignment == Alignments.BOTTOM) then p1, p2 = Alignments.TOP, Alignments.BOTTOM -- Right elseif (alignment == Alignments.TOPRIGHT) or (alignment == Alignments.RIGHT) or (alignment == Alignments.BOTTOMRIGHT) then p1, p2 = Alignments.TOPRIGHT, Alignments.BOTTOMRIGHT end else error(format("Unsupported direction: \"%s\"", direction)) end -- Swap p1 & p2 if reverse if (direction == Directions.LEFT) or (direction == Directions.UP) then p1, p2 = p2, p1 end -- Determine offsets x = ((direction == Directions.RIGHT) and spacing) or ((direction == Directions.LEFT) and -spacing) or 0 y = ((direction == Directions.DOWN) and -spacing) or ((direction == Directions.UP) and spacing) or 0 -- Position child if (prevChild) then child:SetPoint(p1, prevChild, p2, x, y) else child:SetPoint(p1, canvas) end end -- Resize canvas to fit children local width, height = self._maxChildWidth, self._maxChildHeight -- Set width/height for horizontal/vertical directions respectively if (direction == Directions.RIGHT) or (direction == Directions.LEFT) then width = (flexible or self._fill_w) and alignHelper:GetWidth() or self:GetRequiredWidth() elseif (direction == Directions.DOWN) or (direction == Directions.UP) then height = (flexible or self._fill_h) and alignHelper:GetHeight() or self:GetRequiredHeight() else error(format("Unsupported direction: \"%s\"", direction)) end canvas:SetWidth(width) canvas:SetHeight(height) end -- ============================================================================ -- Getters & Setters -- ============================================================================ -- Returns the alignHelper of the frame. function Functions:GetAlignHelper() return self._alignHelper end -- Returns the alignment of the frame. function Functions:GetAlignment() return self._alignment end -- Returns the canvas of the frame. function Functions:GetCanvas() return self._canvas end -- Returns the children of the frame. function Functions:GetChildren() return self._children end -- Returns the direction of the frame. function Functions:GetDirection() return self._direction end -- Returns the layout of the frame. function Functions:GetLayout() return self._layout end -- Returns the frame's padding. function Functions:GetPadding() return self._padding end -- Returns the frame's required minimum width. function Functions:GetRequiredWidth() return self._requiredWidth end -- Returns the frame's required minimum height. function Functions:GetRequiredHeight() return self._requiredHeight end -- Returns the frame's child spacing. function Functions:GetSpacing() return self._spacing end -- Sets the alignment of the frame's children. -- @param _alignment - a value in DFL.Alignments function Functions:SetAlignment(alignment) if alignment and not Alignments[alignment] then error(format("invalid alignment: \"%s\"", tostring(alignment))) end self._alignment = alignment or Alignments.TOPLEFT self._canvas:ClearAllPoints() self._canvas:SetPoint(self._alignment, self._alignHelper) DFL:ResizeParent(self) end -- Sets the direction of the frame. -- @param _direction - a value in DFL.Directions function Functions:SetDirection(direction) if direction and not Directions[direction] then error(format("invalid direction: \"%s\"", tostring(direction))) end self._direction = direction or Directions.RIGHT DFL:ResizeParent(self) end -- Sets the layout for the frame and resizes the ParentFrame. -- @param layout - a layout type in DFL.Layouts function Functions:SetLayout(layout) if layout and not Layouts[layout] then error(format("invalid layout: \"%s\"", tostring(layout))) end self._layout = layout or Layouts.FLOW self._fill_w = ( (layout == Layouts.FILL) or (layout == Layouts.FILL_W) ) self._fill_h = ( (layout == Layouts.FILL) or (layout == Layouts.FILL_H) ) self._equalize_w = ( self._fill_w or (layout == Layouts.FLEX_EQUAL) or (layout == Layouts.FLEX_EQUAL_W) or (layout == Layouts.FLOW_EQUAL) or (layout == Layouts.FLOW_EQUAL_W) ) self._equalize_h = ( self._fill_h or (layout == Layouts.FLEX_EQUAL) or (layout == Layouts.FLEX_EQUAL_H) or (layout == Layouts.FLOW_EQUAL) or (layout == Layouts.FLOW_EQUAL_H) ) self._flexible = ( (layout == Layouts.FLEX) or (layout == Layouts.FLEX_EQUAL) or (layout == Layouts.FLEX_EQUAL_W) or (layout == Layouts.FLEX_EQUAL_H) ) DFL:ResizeParent(self) end -- Sets the frame's horizontal and vertical space between its edges and children. -- @param x - the horizontal space -- @param y - the vertical space [optional] function Functions:SetPadding(x, y) assert((type(x) == "number") and (x >= 0), "x must be >= 0") if y then assert((type(y) == "number") and (y >= 0), "y must be >= 0") end self._padding.X = x self._padding.Y = y or x DFL:ResizeParent(self) end -- Sets the frame's horizontal and vertical space between children. -- @param spacing - the spacing function Functions:SetSpacing(spacing) assert((type(spacing) == "number") and (spacing >= 0), "spacing must be >= 0") self._spacing = spacing DFL:ResizeParent(self) end function Functions:OnSetEnabled(enabled) for k, v in pairs(self._children) do if v.SetEnabled then v:SetEnabled(enabled) end end end function Functions:SetColors(color) if not self._texture then self._texture = DFL.Texture:Create(self) end self._texture:SetColors(color or DFL.Colors.Frame) end function Functions:Refresh() if self._texture then self._texture:Refresh() end for i, child in pairs(self._children) do if child.Refresh then child:Refresh() end end end do -- Resize() -- Updates the required width and height of the frame. local function updateRequiredSize(self) local children = self._children local direction = self._direction local minWidth, minHeight = 0, 0 local maxChildWidth, maxChildHeight = 0, 0 local totalSpacing = (#children - 1) * self._spacing -- Resize children, get largest width and height for _, child in pairs(children) do if child.Resize then child:Resize() end maxChildWidth = max(maxChildWidth, child:GetWidth()) maxChildHeight = max(maxChildHeight, child:GetHeight()) end self._maxChildWidth = maxChildWidth self._maxChildHeight = maxChildHeight -- Equalize child sizes if necessary if self._equalize_w and self._equalize_h then for _, child in pairs(children) do if child.SetWidth then child:SetWidth(maxChildWidth) end if child.SetHeight then child:SetHeight(maxChildHeight) end end elseif self._equalize_w then -- equalize child widths for _, child in pairs(children) do if child.SetWidth then child:SetWidth(maxChildWidth) end end elseif self._equalize_h then -- equalize child heights for _, child in pairs(children) do if child.SetHeight then child:SetHeight(maxChildHeight) end end end -- Calculate min width & height if (direction == Directions.RIGHT) or (direction == Directions.LEFT) then -- minHeight, tallest child minHeight = maxChildHeight -- minWidth, sum of child widths plus total spacing if self._equalize_w then minWidth = (#children * maxChildWidth) else for _, child in pairs(children) do minWidth = minWidth + child:GetWidth() end end minWidth = minWidth + totalSpacing elseif (direction == Directions.DOWN) or (direction == Directions.UP) then -- minWidth, widest child minWidth = maxChildWidth -- minHeight, sum of child heights plus total spacing if self._equalize_h then minHeight = (#children * maxChildHeight) else for _, child in pairs(children) do minHeight = minHeight + child:GetHeight() end end minHeight = minHeight + totalSpacing end self._requiredWidth = minWidth self._requiredHeight = minHeight end function Functions:Resize() local alignHelper = self._alignHelper local children = self._children local direction = self._direction local padding = self._padding local spacing = self._spacing -- Show if children, hide if none if next(children) then self:Show() else self:Hide() return end -- Reposition alignHelper alignHelper:ClearAllPoints() alignHelper:SetPoint("TOPLEFT", self, padding.X, -padding.Y) alignHelper:SetPoint("BOTTOMRIGHT", self, -padding.X, padding.Y) updateRequiredSize(self) -- Set size local width = max(self._requiredWidth, self:GetMinWidth()) + (padding.X * 2) local height = max(self._requiredHeight, self:GetMinHeight()) + (padding.Y * 2) self:SetSize(width, height) end end do -- OnSetWidth(), OnSetHeight(), OnSetSize() local function updateChildren(self) self:GrowChildren() self:PositionChildren() end Functions.OnSetWidth = updateChildren Functions.OnSetHeight = updateChildren Functions.OnSetSize = updateChildren end <file_sep>-- FontString: contains functions for a DFL font string. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local pairs, unpack = pairs, unpack -- FontString local FontString = DFL.FontString -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL font string. -- @param parent - the parent frame -- @param text - the initial text [optional] -- @param font - the font style to inherit [optional] -- @param layer - the draw layer ("ARTWORK", "BACKGROUND", etc.) [optional] function FontString:Create(parent, text, font, layer) local fontString = DFL.Creator:CreateFontString(parent, text, font, layer) DFL:AddDefaults(fontString) DFL:AddMixins(fontString, self.Functions) fontString:SetColors() fontString:Refresh() return fontString end -- ============================================================================ -- Functions -- ============================================================================ local Functions = FontString.Functions function Functions:SetColors(color, shadowColor) self._color = color or self._color or DFL.Colors.Text self._shadowColor = shadowColor or self._shadowColor or DFL.Colors.Black end function Functions:OnSetEnabled(enabled) DFL:SetEnabledAlpha(self, enabled) end function Functions:Refresh() self:SetTextColor(unpack(self._color)) self:SetShadowColor(unpack(self._shadowColor)) -- A FontString's alpha gets reset when updating its color DFL:SetEnabledAlpha(self, self:IsEnabled()) end <file_sep>-- https://github.com/moody/DethsFrameLib local LibName, LibVersion = "DethsFrameLib", "1.1" -- DethsLibLoader local DFL = DethsLibLoader:Create(LibName, LibVersion) if not DFL then return end DFL.Creator = {} -- Upvalues local abs, assert, error, floor, nop, pairs, ipairs, tonumber, tostring, type = abs, assert, error, floor, nop, pairs, ipairs, tonumber, tostring, type -- ============================================================================ -- Consts Tables -- ============================================================================ -- Alignments, Points DFL.Alignments = { -- Top TOPLEFT = "TOPLEFT", TOP = "TOP", TOPRIGHT = "TOPRIGHT", -- Middle LEFT = "LEFT", CENTER = "CENTER", RIGHT = "RIGHT", -- Bottom BOTTOMLEFT = "BOTTOMLEFT", BOTTOM = "BOTTOM", BOTTOMRIGHT = "BOTTOMRIGHT" } DFL.Points = DFL.Alignments -- Anchors DFL.Anchors = { NONE = "ANCHOR_NONE", CURSOR = "ANCHOR_CURSOR", PRESERVE = "ANCHOR_PRESERVE", -- Top TOPLEFT = "ANCHOR_TOPLEFT", TOP = "ANCHOR_TOP", TOPRIGHT = "ANCHOR_TOPRIGHT", -- Middle LEFT = "ANCHOR_LEFT", RIGHT = "ANCHOR_RIGHT", -- Bottom BOTTOMLEFT = "ANCHOR_BOTTOMLEFT", BOTTOM = "ANCHOR_BOTTOM", BOTTOMRIGHT = "ANCHOR_BOTTOMRIGHT" } -- Colors DFL.Colors = { None = {0, 0, 0, 0}, Black = {0, 0, 0, 1}, White = {1, 1, 1, 1}, Area = {0.1, 0.1, 0.2, 0.5}, Button = {0.05, 0.05, 0.15, 1}, ButtonHi = {0.15, 0.15, 0.3, 1}, Frame = {0, 0, 0.05, 0.95}, Text = {0.35, 0.35, 0.6, 1}, Thumb = {0.1, 0.1, 0.2, 1} } -- Directions DFL.Directions = { UP = "UP", DOWN = "DOWN", LEFT = "LEFT", RIGHT = "RIGHT" } -- Fonts DFL.Fonts = { -- GameFont Huge = "GameFontNormalHuge", HugeOutline = "GameFontNormalHugeOutline", Large = "GameFontNormalLarge", LargeOutline = "GameFontNormalLargeOutline", Normal = "GameFontNormal", NormalOutline = "GameFontNormalOutline", Medium = "GameFontNormalMed1", Small = "GameFontNormalSmall", Tiny = "GameFontNormalTiny", -- NumberFont Number = "NumberFontNormal", NumberHuge = "NumberFontNormalHuge", NumberSmall = "NumberFontNormalSmall", } -- Layouts DFL.Layouts = { -- Layouts are used by DFL.Frame when resizing and positioning children. -- FILL: with 3 children, |-11-2-333-------| becomes |-1111-2222-3333-| -- |----------------| becomes |-1111-2222-3333-| FILL = "FILL", -- FILL_W: with 3 children, |-11-2-333-------| becomes |-1111-2222-3333-| -- |----------------| becomes |----------------| FILL_W = "FILL_W", -- FILL_H: with 3 children, |-11-2-333-------| becomes |-11-2-333-------| -- |----------------| becomes |-11-2-333-------| FILL_H = "FILL_H", -- FLEX: with 3 children, |-1-2-3-----| becomes |-1---2---3-| -- |-1---3-----| becomes |-1-------3-| FLEX = "FLEX", -- FLEX_EQUAL: with 3 children, |-1-22-333------| becomes |-111--222--333-| -- |------333------| becomes |-111--222--333-| FLEX_EQUAL = "FLEX_EQUAL", -- FLEX_EQUAL_W: with 3 children, |-1-22-333------| becomes |-111--222--333-| -- |------333------| becomes |-----------333-| FLEX_EQUAL_W = "FLEX_EQUAL_W", -- FLEX_EQUAL_H: with 3 children, |-1-22-333-----| becomes |-1---22---333-| -- |------333-----| becomes |-1---22---333-| FLEX_EQUAL_H = "FLEX_EQUAL_H", -- FLOW: (Default) Children are simply positioned one by one. FLOW = "FLOW", -- FLOW_EQUAL: with 3 children, |-1-22-333-| becomes |-111-222-333-| -- |---22-----| |-111-222-333-| FLOW_EQUAL = "FLOW_EQUAL", -- FLOW_EQUAL_W: with 3 children, |-1-22-333-| becomes |-111-222-333-| -- |---22-----| |-----222-----| FLOW_EQUAL_W = "FLOW_EQUAL_W", -- FLOW_EQUAL_H: with 3 children, |-1-22-333-| becomes |-1-22-333-| -- |---22-----| |-1-22-333-| FLOW_EQUAL_H = "FLOW_EQUAL_H", } -- Orientations DFL.Orientations = { VERTICAL = "VERTICAL", HORIZONTAL = "HORIZONTAL" } -- ============================================================================ -- Tooltip Functions -- ============================================================================ do -- ShowTooltip(), HideTooltip() local GameTooltip = GameTooltip -- Displays a generic game tooltip. -- @param owner - the frame the tooltip belongs to -- @param anchorType - the anchor type ("ANCHOR_LEFT", "ANCHOR_CURSOR", etc.) -- @param title - the title of the tooltip -- @param ... - the body lines of the tooltip function DFL:ShowTooltip(owner, anchorType, title, ...) GameTooltip:SetOwner(owner, anchorType) GameTooltip:SetText(title, 1.0, 0.82, 0) for i=1, select("#", ...) do local line = select(i, ...) if (type(line) == "function") then line = line() end GameTooltip:AddLine(line, 1, 1, 1, true) end GameTooltip:Show() end -- Hides the game tooltip. function DFL:HideTooltip() GameTooltip:Hide() end end -- ============================================================================ -- UI Functions -- ============================================================================ do -- AddBorder() local BACKDROP = { edgeFile = "Interface/Buttons/WHITE8X8", edgeSize = 1 } function DFL:AddBorder(frame, ...) local r, g, b = ... frame:SetBackdrop(BACKDROP) frame:SetBackdropColor(0, 0, 0, 0) frame:SetBackdropBorderColor(r or 0, g or 0, b or 0) end function DFL:RemoveBorder(frame) frame:SetBackdrop(nil) end end do -- Measure() local sizer = UIParent:CreateTexture(format("%s_%s_MeasureTexture", LibName, LibVersion), "BACKGROUND") sizer:SetColorTexture(0, 0, 0, 0) -- Measures the width and height between the top-left point of the startRegion -- and the bottom-right point of the endRegion. -- @param parent - the parent frame used to create a temporary texture -- @param startRegion - the left-most region -- @param endRegion - the right-most region -- @param startPoint - the point on the startRegion to measure from [optional] -- @param endPoint - the point on the endRegion to measure to [optional] -- @return width - the width between the two regions -- @return height - the height function DFL:Measure(parent, startRegion, endRegion, startPoint, endPoint) sizer:ClearAllPoints() sizer:SetParent(parent) sizer:SetPoint(startPoint or "TOPLEFT", startRegion) sizer:SetPoint(endPoint or "BOTTOMRIGHT", endRegion) return sizer:GetWidth(), sizer:GetHeight() end end do -- Padding() local paddingCache = {} -- Returns the default padding with an optional multiplier. -- @param multiplier - a number to multiply padding by [optional] -- @return - the absolute value of default padding times the multiplier or 1. function DFL:Padding(multiplier) multiplier = tonumber(multiplier) or 1 local key = tostring(multiplier) if not paddingCache[key] then paddingCache[key] = floor(abs(10 * multiplier) + 0.5) end return paddingCache[key] end end -- ============================================================================ -- Helper Functions -- ============================================================================ -- Adds mixins to the specified object. -- @param obj - the object to add mixins to -- @param mixins - a table of values to add function DFL:AddMixins(obj, mixins) for k, v in pairs(mixins) do obj[k] = v end end -- Removes mixins from the specified object. -- @param obj - the object to remove mixins from -- @param mixins - a table of values to remove function DFL:RemoveMixins(obj, mixins) for k in pairs(mixins) do obj[k] = nil end end -- Adds scripts to the specified object. -- @param obj - the object to add scripts to -- @param scripts - a table of script functions to add function DFL:AddScripts(obj, scripts) for k, v in pairs(scripts) do obj:SetScript(k, v) end end -- Removes scripts from the specified object. -- @param obj - the object to remove scripts from -- @param scripts - a table of script functions to remove function DFL:RemoveScripts(obj, scripts) for k in pairs(scripts) do obj:SetScript(k, nil) end end -- Returns true if the specified object is of the specified type. -- @param obj - the object -- @param objType - the type to test for function DFL:IsType(obj, objType) return (type(obj) == "table") and obj.GetType and (obj:GetType() == objType) end -- Sets the enabled or disabled alpha of the specified object. function DFL:SetEnabledAlpha(obj, enabled) obj:SetAlpha(enabled and 1 or 0.3) end -- Returns the ParentFrame the specified object ultimately belongs to, or nil. -- @param obj - an object ultimately belonging to a ParentFrame function DFL:GetParentFrame(obj) -- If obj is a ParentFrame, return it if self:IsType(obj, self.ParentFrame:GetType()) then return obj else -- Otherwise, if object has a parent... local parent = obj.GetParent and obj:GetParent() if parent then return self:GetParentFrame(parent) end end end --[[ Calls QueueResize() on the ParentFrame the specified object ultimately belongs to. If a ParentFrame is not found in the object's parent hierarchy, then this function does nothing. WARNING: Resizing will occur infinitely if called during an object's Resize(). @param obj - an object ultimately belonging to a ParentFrame ]] function DFL:ResizeParent(obj) local parentFrame = self:GetParentFrame(obj) if parentFrame then parentFrame:QueueResize() end end -- ============================================================================ -- NewObjectTable() -- ============================================================================ do local function create(self) error("Create() not implemented for object type "..self:GetType()) end -- Returns a new object table with default functionality. function DFL:NewObjectTable() --[[ Using a unique table as the key instead of a generic value prevents issues regarding object type comparisons. If two different types of objects' GetType() function returned the same value, their types would be indistinguishable from one another. With a unique table, the type is guaranteed to be unique (unless someone gets stupid and codes a custom GetType() function). --]] local type = {} local getType = function() return type end return { Create = create, GetType = getType, Functions = { GetType = getType } } end end -- ============================================================================ -- AddDefaults() -- ============================================================================ do local Defaults, objCache = {}, {} -- Adds default functionality to a specified object. This is required for -- objects to be handled properly by DFL in most cases. -- @param obj - the object to add defaults to function DFL:AddDefaults(obj) assert(type(obj) == "table", "obj must be a table") assert(not objCache[obj], "object already passed to AddDefaults()") objCache[obj] = true obj.SetColors = Defaults.SetColors -- State obj._defaults_isEnabled = true obj.IsEnabled = Defaults.IsEnabled obj._Enable = obj.Enable obj.Enable = Defaults.Enable obj._Disable = obj.Disable obj.Disable = Defaults.Disable obj._SetEnabled = obj.SetEnabled obj.SetEnabled = Defaults.SetEnabled obj.OnSetEnabled = Defaults.OnSetEnabled -- Width if obj.SetWidth then obj._defaults_minWidth = 0 obj._SetWidth = obj.SetWidth obj.GetMinWidth = Defaults.GetMinWidth obj.SetMinWidth = Defaults.SetMinWidth obj.SetWidth = Defaults.SetWidth obj.OnSetWidth = Defaults.OnSetWidth end -- Height if obj.SetHeight then obj._defaults_minHeight = 0 obj._SetHeight = obj.SetHeight obj.GetMinHeight = Defaults.GetMinHeight obj.SetMinHeight = Defaults.SetMinHeight obj.SetHeight = Defaults.SetHeight obj.OnSetHeight = Defaults.OnSetHeight end -- Size if obj.SetSize and obj._SetWidth and obj._SetHeight then obj._SetSize = obj.SetSize obj.SetSize = Defaults.SetSize obj.OnSetSize = Defaults.OnSetSize end obj.Refresh = Defaults.Refresh obj.Resize = Defaults.Resize return obj end -- Sets the colors of the object. Override as required. -- @param ... - variable number of tables containing rgba [0-1] color values Defaults.SetColors = nop -- Returns true if the object is enabled. function Defaults:IsEnabled() return self._defaults_isEnabled end -- Enables the object. function Defaults:Enable() self:SetEnabled(true) end -- Disables the object. function Defaults:Disable() self:SetEnabled(false) end -- Enables or disables the object. -- Implement OnSetEnabled() instead of overriding. function Defaults:SetEnabled(enabled) if (self._defaults_isEnabled == enabled) then return end self._defaults_isEnabled = enabled if self._SetEnabled then self:_SetEnabled(enabled) elseif enabled then if self._Enable then self:_Enable() end else if self._Disable then self:_Disable() end end self:OnSetEnabled(enabled) end Defaults.OnSetEnabled = nop -- Returns the minimum width of the object. function Defaults:GetMinWidth() return self._defaults_minWidth end -- Sets the minimum width of the object. function Defaults:SetMinWidth(width) self._defaults_minWidth = (width >= 0) and width or error("width must be >= 0") end -- Sets the width of the object. -- Implement OnSetWidth(width, oldWidth) instead of overriding. function Defaults:SetWidth(width) local oldWidth = self:GetWidth() if (width < self._defaults_minWidth) then width = self._defaults_minWidth end self:_SetWidth(width) self:OnSetWidth(width, oldWidth) end Defaults.OnSetWidth = nop -- Returns the minimum height of the object. function Defaults:GetMinHeight() return self._defaults_minHeight end -- Sets the minimum height of the object. function Defaults:SetMinHeight(height) self._defaults_minHeight = (height >= 0) and height or error("height must be >= 0") end -- Sets the height of the object. -- Implement OnSetHeight(height, oldHeight) instead of overriding. function Defaults:SetHeight(height) local oldHeight = self:GetHeight() if (height < self._defaults_minHeight) then height = self._defaults_minHeight end self:_SetHeight(height) self:OnSetHeight(height, oldHeight) end Defaults.OnSetHeight = nop -- Sets the width and height of the object. -- Implement OnSetSize(width, height, oldWidth, oldHeight) instead of overriding. function Defaults:SetSize(width, height) local oldWidth, oldHeight = self:GetWidth(), self:GetHeight() if (width < self._defaults_minWidth) then width = self._defaults_minWidth end if (height < self._defaults_minHeight) then height = self._defaults_minHeight end self:_SetWidth(width) self:_SetHeight(height) self:OnSetSize(width, height, oldWidth, oldHeight) end Defaults.OnSetSize = nop -- Refreshes the object. Override as required. -- Use this function to update the object's appearance. Defaults.Refresh = nop -- Resizes the object. Override as required. -- Use this function to determine and set the object's required size. Defaults.Resize = nop end -- ============================================================================ -- Initialize object tables -- ============================================================================ do local objects = { "Button", "CheckButton", "ChildFrame", "EditBox", "FauxScrollFrame", "FontString", "Frame", "ParentFrame", "ScrollFrame", "Slider", "TextArea", "Texture" } for _, k in pairs(objects) do DFL[k] = DFL:NewObjectTable() end end <file_sep>-- Creator: contains simple create functions for UIObjects (frames, buttons, textures, etc.). local LibName, LibVersion = "DethsFrameLib", "1.1" -- DFL local DFL = DethsLibLoader(LibName, LibVersion) if not DFL.__initial_load then return end local Creator = DFL.Creator -- Wow upvalues local CreateFrame, UIParent = CreateFrame, UIParent -- ============================================================================ -- Frame -- ============================================================================ do local count = 0 local name = format("%s_%s_Frame_", LibName, LibVersion) -- Returns a frame. -- @param parent - the parent frame -- @return - a basic frame function Creator:CreateFrame(parent) count = count + 1 local frame = CreateFrame("Frame", name..count, parent or UIParent) frame:Show() return frame end end -- ============================================================================ -- Button -- ============================================================================ do local count = 0 local name = format("%s_%s_Button_", LibName, LibVersion) -- Returns a button. -- @param parent - the parent of the button -- @return - a basic button function Creator:CreateButton(parent) count = count + 1 local button = CreateFrame("Button", name..count, parent) button:RegisterForClicks("LeftButtonUp") button:Show() return button end end -- ============================================================================ -- Check Button -- ============================================================================ do local count = 0 local name = format("%s_%s_CheckButton_", LibName, LibVersion) local checkedTexture = "Interface\\Buttons\\UI-CheckBox-Check" local disabledTexture = "Interface\\Buttons\\UI-CheckBox-Check-Disabled" -- Returns a check button. -- @param parent - the parent of the check button -- @return - a basic check button function Creator:CreateCheckButton(parent) count = count + 1 local checkButton = CreateFrame("CheckButton", name..count, parent) checkButton:SetCheckedTexture(checkedTexture) checkButton:SetDisabledCheckedTexture(disabledTexture) checkButton:Show() return checkButton end end -- ============================================================================ -- Texture -- ============================================================================ do local count = 0 local name = format("%s_%s_Texture_", LibName, LibVersion) -- Returns a texture. -- @param parent - the parent frame -- @param layer - the draw layer ("ARTWORK", "BACKGROUND", etc.) -- @return - a basic texture function Creator:CreateTexture(parent, layer) count = count + 1 local texture = parent:CreateTexture(name..count, (layer or "BACKGROUND")) texture:SetAllPoints() texture:Show() return texture end end -- ============================================================================ -- Font String -- ============================================================================ do local count = 0 local name = format("%s_%s_FontString_", LibName, LibVersion) -- Returns a font string. -- @param parent - the parent frame -- @param text - the initial text [optional] -- @param font - the font style to inherit [optional] -- @param layer - the draw layer ("ARTWORK", "BACKGROUND", etc.) [optional] -- @return - a basic font string function Creator:CreateFontString(parent, text, font, layer) count = count + 1 local fontString = parent:CreateFontString(name..count, (layer or "OVERLAY"), (font or DFL.Fonts.Normal)) fontString:SetText(text) fontString:Show() return fontString end end -- ============================================================================ -- Scroll Frame -- ============================================================================ do local count = 0 local name = format("%s_%s_ScrollFrame_", LibName, LibVersion) -- Returns a scroll frame. -- @param parent - the parent frame -- @return - a basic scroll frame function Creator:CreateScrollFrame(parent) count = count + 1 local scrollFrame = CreateFrame("ScrollFrame", name..count, parent) scrollFrame:SetClipsChildren(true) scrollFrame:Show() return scrollFrame end end -- ============================================================================ -- Slider -- ============================================================================ do local count = 0 local name = format("%s_%s_Slider_", LibName, LibVersion) -- Returns a slider. -- @param parent - the parent frame -- @return - a basic slider function Creator:CreateSlider(parent) count = count + 1 local slider = CreateFrame("Slider", name..count, parent) slider:SetObeyStepOnDrag(true) slider:SetMinMaxValues(0, 0) slider:SetValue(0) slider:Show() return slider end end -- ============================================================================ -- Edit Box -- ============================================================================ do local count = 0 local name = format("%s_%s_EditBox_", LibName, LibVersion) local EditBox_ClearFocus = EditBox_ClearFocus -- Returns an edit box. -- @param parent - the parent frame -- @param maxLetters - the maximum amount of characters [optional] -- @param numeric - whether or not the edit box only accepts numeric input [optional] -- @param font - the font style for the edit box to inherit [optional] -- @return - a basic edit box function Creator:CreateEditBox(parent, maxLetters, numeric, font) count = count + 1 local editBox = CreateFrame("EditBox", name..count, parent) editBox:SetScript("OnEscapePressed", EditBox_ClearFocus) editBox:SetFontObject(font or DFL.Fonts.Normal) editBox:SetMaxLetters(maxLetters or 0) editBox:SetNumeric(numeric) editBox:SetMultiLine(false) editBox:SetAutoFocus(false) editBox:ClearFocus() editBox:Show() return editBox end end <file_sep>-- TextArea: contains functions to create a DFL text area. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end local Points = DFL.Points -- TextArea local TextArea = DFL.TextArea TextArea.Scripts = {} TextArea.EditBoxScripts = {} TextArea.SliderScripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL text area. -- @param parent - the parent frame -- @param sliderSpacing - spacing between the frame and slider -- @param padding - padding between the frame edges and text function TextArea:Create(parent, sliderSpacing, padding) local frame = DFL.Creator:CreateFrame(parent) frame._sliderSpacing = tonumber(sliderSpacing) or DFL:Padding(0.25) padding = tonumber(padding) or DFL:Padding(0.5) -- Texture, used to position the scroll frame to allow for padding without -- using SetTextInsets() on the edit box. Doing it this way because it -- doesn't cause text to spill out over the bottom edge of the texture. local texture = DFL.Texture:Create(frame) frame._texture = texture -- Scroll frame local scrollFrame = DFL.Creator:CreateScrollFrame(frame) scrollFrame:SetPoint(Points.TOPLEFT, texture, padding, -padding) scrollFrame:SetPoint(Points.BOTTOMRIGHT, texture, -padding, padding) frame._scrollFrame = scrollFrame -- Edit box (scroll child) local editBox = DFL.Creator:CreateEditBox(scrollFrame) editBox:SetMultiLine(true) editBox.cursorOffset = 0 -- For ScrollingEdit_* functions editBox.cursorHeight = 0 -- For ScrollingEdit_* functions editBox._frame = frame frame._editBox = editBox scrollFrame:SetScrollChild(editBox) -- Slider local slider = DFL.Slider:Create(frame) slider.SetEnabled = nop slider._scrollFrame = scrollFrame frame._slider = slider DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) DFL:AddScripts(frame, self.Scripts) DFL:AddScripts(editBox, self.EditBoxScripts) DFL:AddScripts(slider, self.SliderScripts) frame:SetMinWidth(100) frame:SetMinHeight(100) frame:SetColors() frame:Refresh() return frame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = TextArea.Functions -- Sets the colors of the text area. function Functions:SetColors(textColor, textureColor, sliderColors) self._textColor = textColor or DFL.Colors.Text self._texture:SetColors(textureColor or DFL.Colors.Area) if sliderColors then self._slider:SetColors(unpack(sliderColors)) end end -- Enables or disables the text area. function Functions:OnSetEnabled(enabled) self._editBox:SetEnabled(enabled) DFL:SetEnabledAlpha(self._editBox, enabled) end -- Refreshes the text area. function Functions:Refresh() self._editBox:SetTextColor(unpack(self._textColor)) self._texture:Refresh() self._slider:Refresh() end -- Resizes the text area. function Functions:Resize() local scrollFrame = self._scrollFrame local editBox = self._editBox local slider = self._slider slider:Resize() local minWidth = self:GetMinWidth() + (self._sliderSpacing + slider:GetWidth()) local minHeight = self:GetMinHeight() self:SetWidth(minWidth) self:SetHeight(minHeight) end -- When the height is changed, update the visibility of the slider. function Functions:OnSetHeight() local scrollFrame = self._scrollFrame local editBox = self._editBox local slider = self._slider local spacing = self._sliderSpacing local texture = self._texture -- Update slider values, reposition texture local maxVal = max(editBox:GetHeight() - scrollFrame:GetHeight(), 0) texture:SetPoint(Points.TOPLEFT) if (maxVal > 0) then slider:SetMinMaxValues(0, maxVal) slider:Show() texture:SetPoint(Points.BOTTOMRIGHT, -(spacing + slider:GetWidth()), 0) slider:SetPoint(Points.TOPLEFT, texture, Points.TOPRIGHT, spacing, 0) slider:SetPoint(Points.BOTTOMLEFT, texture, Points.BOTTOMRIGHT, spacing, 0) else slider:SetMinMaxValues(0, 0) slider:Hide() texture:SetPoint(Points.BOTTOMRIGHT) end editBox:SetWidth(scrollFrame:GetWidth()) end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = TextArea.Scripts -- Update the slider when the mouse wheel is scrolled. function Scripts:OnMouseWheel(delta) local slider = self._slider -- scroll by 12.5% on each wheel (delta will be 1 or -1) local percent = (select(2, slider:GetMinMaxValues()) * 0.125 * delta) slider:SetValue(slider:GetValue() - percent) end -- When frame is clicked, set focus on the edit box and reposition the cursor -- to the end of it. function Scripts:OnMouseUp() self._editBox:SetFocus() self._editBox:HighlightText(0, 0) self._editBox:SetCursorPosition(self._editBox:GetNumLetters()) end end -- ============================================================================ -- EditBoxScripts -- ============================================================================ do local Scripts = TextArea.EditBoxScripts function Scripts:OnUpdate(elapsed) self._frame:OnSetHeight() -- update slider visibility ScrollingEdit_OnUpdate(self, elapsed) local scroll = self:GetParent():GetVerticalScroll() self._frame._slider:SetValue(scroll) end Scripts.OnCursorChanged = ScrollingEdit_OnCursorChanged end -- ============================================================================ -- SliderScripts -- ============================================================================ do local SliderScripts = TextArea.SliderScripts -- Update the scroll frame when the slider's value changes. function SliderScripts:OnValueChanged(value) self._scrollFrame:SetVerticalScroll(value) end end <file_sep>local AddonName, Addon = ... -- Libs local DCL = DethsLibLoader("DethsColorLib", GetAddOnMetadata("DethsColorLib", "Version")) local DFL = DethsLibLoader(AddonName, GetAddOnMetadata(AddonName, "Version")) Addon.DethsFrameLib = DFL -- Initialize objects local ParentTest = DFL.ParentFrame:Create() Addon.Frames = { ParentTest = ParentTest, FrameTest = DFL.ChildFrame:Create() } -- ============================================================================ -- Slash Command -- ============================================================================ do -- Get frame test keys local keys = {} for k in pairs(Addon.Frames) do keys[#keys+1] = k end table.sort(keys) local function cmdFunc(frameName, cmd, ...) local frame = Addon.Frames[frameName] if frame then ParentTest:Initialize() -- nop'd after first run, see Objects/ParentFrame.lua if not ParentTest:IsVisible() then ParentTest:Show() end if (frame ~= ParentTest) and (frame ~= ParentTest:GetContent()) then ParentTest:SetContent(frame) end frame:OnCmd(cmd, ...) else -- Print keys for i, v in ipairs(keys) do Addon:Print(format("%s. %s", i, v)) end end end DethsLibLoader("DethsCmdLib", GetAddOnMetadata("DethsCmdLib", "Version")):Create("dfl", cmdFunc) end -- ============================================================================ -- General Functions -- ============================================================================ function Addon:Print(title, msg) print(format( msg and "[%s] %s: %s" or "[%s] %s", DCL:ColorString(AddonName, DCL.CSS.Crimson), DCL:ColorString(title, DCL.CSS.AliceBlue), msg and DCL:ColorString(msg, DCL.CSS.Yellow)) ) end <file_sep>-- Texture: contains functions to create a DFL texture. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local pairs, unpack = pairs, unpack -- Texture local Texture = DFL.Texture -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL texture. -- @param parent - the parent frame -- @param layer - the draw layer ("ARTWORK", "BACKGROUND", etc.) [optional] function Texture:Create(parent, layer) local texture = DFL.Creator:CreateTexture(parent, layer) DFL:AddDefaults(texture) DFL:AddMixins(texture, self.Functions) texture:SetColors() texture:Refresh() return texture end -- ============================================================================ -- Functions -- ============================================================================ local Functions = Texture.Functions function Functions:SetColors(color) self._color = color or self._color or DFL.Colors.None end function Functions:Refresh() self:SetColorTexture(unpack(self._color)) end <file_sep>-- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local unpack = unpack -- EditBox local EditBox = DFL.EditBox EditBox.EditBoxScripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL edit box. -- @param parent - the parent frame -- @param maxLetters - the maximum amount of characters [optional] -- @param numeric - whether or not the edit box only accepts numeric input [optional] -- @param font - the font style for the edit box to inherit [optional] function EditBox:Create(parent, maxLetters, numeric, font) local frame = DFL.Creator:CreateFrame(parent) frame._texture = DFL.Texture:Create(frame) local editBox = DFL.Creator:CreateEditBox(frame, maxLetters, numeric, font) editBox:SetScript("OnEnterPressed", EditBox_ClearFocus) editBox:SetPoint("TOPLEFT", DFL:Padding(0.5), -DFL:Padding(0.25)) editBox:SetPoint("BOTTOMRIGHT", -DFL:Padding(0.5), DFL:Padding(0.25)) editBox.SetMultiLine = nop frame._editBox = editBox DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) DFL:AddScripts(editBox, self.EditBoxScripts) frame:SetMinWidth(50) frame:SetColors() frame:Refresh() return frame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = EditBox.Functions function Functions:SetPrevTabTarget(object) assert(type(object.SetFocus) == "function", "object does not support SetFocus()") self._editBox._prevTabTarget = object end function Functions:SetNextTabTarget(object) assert(type(object.SetFocus) == "function", "object does not support SetFocus()") self._editBox._nextTabTarget = object end function Functions:SetColors(textColor, textureColor, borderColor) self._textColor = textColor or self._textColor or DFL.Colors.Text self._texture:SetColors(textureColor or DFL.Colors.Frame) self._borderColor = borderColor or self._borderColor or DFL.Colors.Area end function Functions:OnSetEnabled(enabled) DFL:SetEnabledAlpha(self, enabled) self._editBox:SetEnabled(enabled) end function Functions:Refresh() self._editBox:SetTextColor(unpack(self._textColor)) self._texture:Refresh() DFL:AddBorder(self, unpack(self._borderColor)) if self._editBox:HasFocus() then self._editBox:ClearFocus() end if self.GetUserValue then self._editBox:SetText(self:GetUserValue()) end end function Functions:Resize() local _, height = self._editBox:GetFont() self:SetWidth(self:GetMinWidth()) self:SetHeight(height + DFL:Padding()) end end -- ============================================================================ -- EditBoxScripts -- ============================================================================ do local EditBoxScripts = EditBox.EditBoxScripts local IsShiftKeyDown = IsShiftKeyDown function EditBoxScripts:OnTextChanged() local value = self:IsNumeric() and self:GetNumber() or self:GetText() local parent = self:GetParent() if parent.SetUserValue then parent:SetUserValue(value) end end function EditBoxScripts:OnEditFocusLost() self:HighlightText(0, 0) local parent = self:GetParent() if parent.GetUserValue then self:SetText(parent:GetUserValue()) end end function EditBoxScripts:OnTabPressed() if (IsShiftKeyDown()) then if self._prevTabTarget then self._prevTabTarget:SetFocus() end else if self._nextTabTarget then self._nextTabTarget:SetFocus() end end end end <file_sep>-- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local UIParent, UISpecialFrames, nop = UIParent, UISpecialFrames, nop local pairs, unpack = pairs, unpack -- ChildFrame local ChildFrame = DFL.ChildFrame -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL child frame. function ChildFrame:Create() local childFrame = {} DFL:AddMixins(childFrame, self.Functions) return childFrame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = ChildFrame.Functions -- Initializes the frame. function Functions:Initialize() self.Frame = DFL.Frame:Create() self:OnInitialize() self.Frame:Hide() -- Nop so the above code is only executed once self.Initialize = nop self.OnInitialize = nop end Functions.OnInitialize = nop -- Displays the frame. function Functions:Show() self.Frame:Resize() self.Frame:Refresh() self.Frame:Show() self:OnShow() end Functions.OnShow = nop -- Hides the frame. function Functions:Hide() self.Frame:Hide() self:OnHide() end Functions.OnHide = nop -- Returns true if the frame is visible. function Functions:IsVisible() return self.Frame:IsVisible() end -- Toggles the frame. function Functions:Toggle() if not self.Frame:IsVisible() then self:Show() else self:Hide() end end -- Returns true if the frame is enabled. function Functions:IsEnabled() return self.Frame:IsEnabled() end -- Enables the frame. function Functions:Enable() self:SetEnabled(true) end -- Disables the frame. function Functions:Disable() self:SetEnabled(false) end -- Enables or disables the frame. function Functions:SetEnabled(enabled) if (self.Frame:IsEnabled() == enabled) then return end self.Frame:SetEnabled(enabled) self:OnSetEnabled(enabled) end Functions.OnSetEnabled = nop -- Refreshes the frame. function Functions:Refresh() self.Frame:Refresh() self:OnRefresh() end Functions.OnRefresh = nop -- Resizes the frame. function Functions:Resize() self.Frame:Resize() self:OnResize() end Functions.OnResize = nop -- Sets the parent of the frame. -- @param parent - the new parent function Functions:SetParent(parent) self.Frame:SetParent(parent) end -- Sets the point of the frame. -- @param point - the new point function Functions:SetPoint(...) self.Frame:SetPoint(...) end -- Sets the scale of the frame. -- @param scale - the new scale function Functions:SetScale(scale) self.Frame:SetScale(scale) self.Frame:Resize() end end <file_sep>-- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local UIParent, UISpecialFrames = UIParent, UISpecialFrames local pairs, unpack = pairs, unpack -- ParentFrame local ParentFrame = DFL.ParentFrame ParentFrame.FrameFunctions = {} ParentFrame.FrameScripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL parent frame. function ParentFrame:Create() local parentFrame = DFL.ChildFrame:Create() DFL:AddMixins(parentFrame, self.Functions) return parentFrame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = ParentFrame.Functions -- Initializes the frame. function Functions:Initialize() -- Create underlying frame local frame = DFL.Frame:Create() self.Frame = frame frame._parent_frame = self -- Center frame:SetPoint("CENTER") frame:SetFrameStrata("FULLSCREEN_DIALOG") frame:SetToplevel(true) -- Make draggable frame:SetClampedToScreen(true) frame:EnableMouse(true) frame:SetMovable(true) frame:RegisterForDrag("LeftButton") -- Allow WoW to handle hiding frame when necessary UISpecialFrames[#UISpecialFrames+1] = frame:GetName() DFL:AddMixins(frame, ParentFrame.FrameFunctions) DFL:AddScripts(frame, ParentFrame.FrameScripts) frame:SetDirection(DFL.Directions.DOWN) frame:SetMinWidth(10) frame:SetMinHeight(10) frame:SetColors() frame:Refresh() self:OnInitialize() frame:Hide() -- Nop so the above code is only executed once self.Initialize = nop self.OnInitialize = nop end Functions.OnInitialize = nop -- Returns the title ChildFrame of the ParentFrame. function Functions:GetTitle() return self._title end -- Returns the content ChildFrame of the ParentFrame. function Functions:GetContent() return self._content end do -- SetTitle(), SetContent() local function addChild(self, child, index) if child then child:Initialize() child:Show() child:SetEnabled(self:IsEnabled()) self.Frame:Add(child.Frame, index) end --[[ NOTE: Certain objects (ScrollFrame/FauxScrollFrame) are not resized or displayed properly within the Title/Content child frames unless we call self.Frame:Resize() an extra time here. I don't know why. Also, note that that the ParentFrame's Frame will be queued for resize if either of the calls to Frame:Add() or Frame:Remove() are executed. It's a band-aid, but the perfomance impact is negligible. --]] self.Frame:Resize() self.Frame:Resize() end -- Sets the title ChildFrame of the ParentFrame. function Functions:SetTitle(title) if self._title then self.Frame:Remove(self._title.Frame) end if title then assert(DFL:IsType(title, DFL.ChildFrame:GetType()), "title must be a ChildFrame") end self._title = title addChild(self, title, 1) end -- Sets the content ChildFrame of the ParentFrame. function Functions:SetContent(content) if self._content then self.Frame:Remove(self._content.Frame) end if content then assert(DFL:IsType(content, DFL.ChildFrame:GetType()), "content must be a ChildFrame") end self._content = content addChild(self, content) end end -- Queues the ParentFrame's frame for resizing. function Functions:QueueResize() self.Frame._resize_queued = true end end -- ============================================================================ -- FrameFunctions -- ============================================================================ do local Functions = ParentFrame.FrameFunctions -- Returns the ParentFrame the frame belongs to. function Functions:GetParent() return self._parent_frame end function Functions:SetColors(color, borderColor) DFL.Frame.Functions.SetColors(self, color) self._borderColor = borderColor or self._borderColor or DFL.Colors.Area end function Functions:Refresh() DFL.Frame.Functions.Refresh(self) DFL:AddBorder(self, unpack(self._borderColor)) end end -- ============================================================================ -- FrameScripts -- ============================================================================ do local Scripts = ParentFrame.FrameScripts function Scripts:OnDragStart() self:StartMoving() end function Scripts:OnDragStop() self:StopMovingOrSizing() end function Scripts:OnUpdate(elapsed) if self._resize_queued then self._resize_queued = false self:Resize() end if self._parent_frame.OnUpdate then self._parent_frame:OnUpdate(elapsed) end end end <file_sep>-- ScrollFrame: contains functions to create a DFL scroll frame. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end local Points = DFL.Points -- ScrollFrame local ScrollFrame = DFL.ScrollFrame ScrollFrame.Scripts = {} ScrollFrame.SliderScripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL scroll frame. -- @param parent - the parent frame -- @param sliderSpacing - spacing between the frame and slider -- @param padding - scroll child padding -- @param spacing - scroll child spacing function ScrollFrame:Create(parent, sliderSpacing, padding, spacing) local frame = DFL.Creator:CreateFrame(parent) frame._sliderSpacing = tonumber(sliderSpacing) or DFL:Padding(0.25) padding = tonumber(padding) or DFL:Padding(0.5) frame._padding = padding -- Texture, used to position the scroll frame to allow for padding without -- using SetPadding() on the scroll child Frame. Doing it this way because it -- doesn't cause objects to spill out over the bottom edge of the texture. local texture = DFL.Texture:Create(frame) frame._texture = texture -- Scroll frame local scrollFrame = DFL.Creator:CreateScrollFrame(frame) scrollFrame:SetPoint(Points.TOPLEFT, texture, padding, -padding) scrollFrame:SetPoint(Points.BOTTOMRIGHT, texture, -padding, padding) frame._scrollFrame = scrollFrame -- Scroll child local scrollChild = DFL.Frame:Create(scrollFrame, DFL.Alignments.TOPLEFT, DFL.Directions.DOWN) scrollChild:SetSpacing(tonumber(spacing) or DFL:Padding(0.5)) scrollFrame:SetScrollChild(scrollChild) frame._scrollChild = scrollChild -- Slider local slider = DFL.Slider:Create(frame) slider.SetEnabled = nop slider._scrollFrame = scrollFrame frame._slider = slider DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) DFL:AddScripts(frame, self.Scripts) DFL:AddScripts(slider, self.SliderScripts) frame:SetMinWidth(10) frame:SetMinHeight(10) frame:SetColors() frame:Refresh() return frame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = ScrollFrame.Functions -- Adds an object to the scroll frame. function Functions:Add(child) self._scrollChild:Add(child) end -- Removes an object from the scroll frame. function Functions:Remove(child) self._scrollChild:Remove(child) end -- Sets the colors of the scroll frame. function Functions:SetColors(color, sliderColors) self._texture:SetColors(color or DFL.Colors.Area) if sliderColors then self._slider:SetColors(unpack(sliderColors)) end end -- Enables or disables the scroll frame. function Functions:OnSetEnabled(enabled) self._scrollChild:SetEnabled(enabled) end -- Refreshes the scroll frame. function Functions:Refresh() self._texture:Refresh() self._scrollChild:Refresh() self._slider:Refresh() end -- Resizes the scroll frame. function Functions:Resize() local scrollFrame = self._scrollFrame local scrollChild = self._scrollChild local slider = self._slider scrollChild:Resize() slider:Resize() local scWidth = scrollChild:GetWidth() + (self._padding * 2) local sliderWidth = self._sliderSpacing + slider:GetWidth() self:SetWidth(max(self:GetMinWidth(), scWidth) + sliderWidth) self:SetHeight(self:GetMinHeight()) end -- When the height is changed, update the visibility of the slider. function Functions:OnSetHeight() local scrollFrame = self._scrollFrame local scrollChild = self._scrollChild local slider = self._slider local spacing = self._sliderSpacing local texture = self._texture local sfHeight = self:GetHeight() - (self._padding * 2) -- Update slider values, reposition texture local maxVal = max(scrollChild:GetHeight() - sfHeight, 0) texture:SetPoint(Points.TOPLEFT) if (maxVal > 0) then slider:SetMinMaxValues(0, maxVal) slider:Show() texture:SetPoint(Points.BOTTOMRIGHT, -(spacing + slider:GetWidth()), 0) slider:SetPoint(Points.TOPLEFT, texture, Points.TOPRIGHT, spacing, 0) slider:SetPoint(Points.BOTTOMLEFT, texture, Points.BOTTOMRIGHT, spacing, 0) else slider:SetMinMaxValues(0, 0) slider:Hide() texture:SetPoint(Points.BOTTOMRIGHT) end end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = ScrollFrame.Scripts -- Update the slider when the mouse wheel is scrolled. function Scripts:OnMouseWheel(delta) local slider = self._slider -- scroll by 12.5% on each wheel (delta will be 1 or -1) local percent = (select(2, slider:GetMinMaxValues()) * 0.125 * delta) slider:SetValue(slider:GetValue() - percent) end end -- ============================================================================ -- SliderScripts -- ============================================================================ do local SliderScripts = ScrollFrame.SliderScripts -- Update the scroll frame when the slider's value changes. function SliderScripts:OnValueChanged(value) self._scrollFrame:SetVerticalScroll(value) end end <file_sep>-- Slider: contains functions to create a DFL slider. -- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end -- Upvalues local Clamp = Clamp local assert, format, pairs, tonumber, type, unpack = assert, format, pairs, tonumber, type, unpack -- Slider local Slider = DFL.Slider Slider.Scripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL slider. -- @param parent - the parent frame function Slider:Create(parent) local slider = DFL.Creator:CreateSlider(parent) slider._texture = DFL.Creator:CreateTexture(slider) slider._thumb = DFL.Creator:CreateTexture(slider) slider:SetThumbTexture(slider._thumb) slider._tooltip_anchor = DFL.Anchors.TOP DFL:AddDefaults(slider) DFL:AddMixins(slider, self.Functions) DFL:AddScripts(slider, self.Scripts) slider:SetSize(10, 10) slider:SetColors() slider:Refresh() return slider end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = Slider.Functions -- If true, a tooltip with the current value is displayed upon interaction. -- @param b - boolean function Functions:SetShowTooltip(b) self._show_tooltip = not not b end -- Sets the anchor point of the tooltip. function Functions:SetTooltipAnchor(anchor) self._tooltip_anchor = anchor or DFL.Anchors.TOP end -- If true, the slider's value will be clamped to a maximum number of decimals. -- Example: if set to 2, 3.14159 becomes 3.14 function Functions:SetMaxDecimals(maxDecimals) assert(type(maxDecimals) == "number", "maxDecimals must be a number") self._max_decimals = maxDecimals end function Functions:SetColors(color, thumbColor, thumbColorHi) self._color = color or self._color or DFL.Colors.Area self._thumbColor = thumbColor or self._thumbColor or DFL.Colors.Thumb self._thumbColorHi = thumbColorHi or self._thumbColorHi or DFL.Colors.ButtonHi end function Functions:Refresh() self._texture:SetColorTexture(unpack(self._color)) self._thumb:SetColorTexture(unpack(self._thumbColor)) if self.GetUserValue then self:SetValue(self:GetUserValue()) end end function Functions:Resize() local width, height = 0, 0 if (self:GetOrientation() == DFL.Orientations.VERTICAL) then width = self:GetWidth() height = width * 2 else height = self:GetHeight() width = height * 2 end self._thumb:SetSize(width, height) end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = Slider.Scripts local function showTooltip(self, value) DFL:ShowTooltip(self._thumb, self._tooltip_anchor, value) end function Scripts:OnValueChanged(value) local minVal, maxVal = self:GetMinMaxValues() value = Clamp(value, minVal, maxVal) -- Round if necessary if self._max_decimals then value = tonumber(format("%."..self._max_decimals.."f", value)) end -- Show tooltip if necessary if self._show_tooltip and self._mouse_down then showTooltip(self, value) end -- Only call SetUserValue handler if value has changed if self.SetUserValue and (self._last_value ~= value) then self:SetUserValue(value) end self._last_value = value end function Scripts:OnMouseDown() self._thumb:SetColorTexture(unpack(self._thumbColorHi)) self._mouse_down = true if self._show_tooltip then showTooltip(self, self:GetValue()) end end function Scripts:OnMouseUp() self._thumb:SetColorTexture(unpack(self._thumbColor)) self._mouse_down = false if self._show_tooltip then DFL:HideTooltip() end end end <file_sep>-- DFL local DFL = DethsLibLoader("DethsFrameLib", "1.1") if not DFL.__initial_load then return end local Points = DFL.Points -- Upvalues local assert, floor, pairs, ipairs, max, nop, tonumber, type, unpack = assert, floor, pairs, ipairs, max, nop, tonumber, type, unpack -- FauxScrollFrame local FauxScrollFrame = DFL.FauxScrollFrame FauxScrollFrame.Scripts = {} FauxScrollFrame.SliderScripts = {} -- ============================================================================ -- Creation Function -- ============================================================================ -- Creates and returns a DFL faux scroll frame. -- @param parent - the parent frame -- @param data - a table of data for faux objects. Data items are retrieved by -- index and passed to objects using an object's SetData(data) function. -- @param objFunc - the function called to create faux scroll objects. These -- objects must implement a SetData(data) function. -- @param numObjects - the number of objects to create -- @param sliderSpacing - spacing between the frame and slider [optional] -- @param objSpacing - padding and spacing for the objects [optional] function FauxScrollFrame:Create(parent, data, objFunc, numObjects, sliderSpacing, objSpacing) assert(type(data) == "table", "data must be a table") assert(type(objFunc) == "function", "objFunc must be a function") numObjects = tonumber(numObjects) or 0 assert(numObjects > 0, "numObjects must be > 0") local frame = DFL.Creator:CreateFrame(parent) frame._sliderSpacing = tonumber(sliderSpacing) or DFL:Padding(0.25) frame._objSpacing = tonumber(objSpacing) or DFL:Padding(0.5) frame._data = data frame._offset = 0 -- objFrame, holds objects created with objFunc local objFrame = DFL.Creator:CreateFrame(frame) objFrame._texture = DFL.Texture:Create(objFrame) objFrame._objects = {} frame._objFrame = objFrame do -- Add required number of objects local lastObj local minWidth = 0 local minHeight = 0 for i = 1, numObjects do local obj = objFunc(objFrame) minWidth = max(minWidth, obj:GetWidth()) minHeight = minHeight + obj:GetHeight() if not (type(obj.SetData) == "function") then error("FauxScrollFrame objects must have a SetData function") end if lastObj then obj:SetPoint(Points.TOPLEFT, lastObj, Points.BOTTOMLEFT, 0, -frame._objSpacing) obj:SetPoint(Points.TOPRIGHT, lastObj, Points.BOTTOMRIGHT, 0, -frame._objSpacing) else obj:SetPoint(Points.TOPLEFT, frame._objSpacing, -frame._objSpacing) obj:SetPoint(Points.TOPRIGHT, -frame._objSpacing, -frame._objSpacing) end lastObj = obj objFrame._objects[#objFrame._objects+1] = obj end minHeight = minHeight + (#objFrame._objects+1) * frame._objSpacing objFrame._minWidth = minWidth + (frame._objSpacing * 2) objFrame:SetHeight(minHeight) end -- slider local slider = DFL.Slider:Create(frame) slider.SetEnabled = nop slider:SetValueStep(1) frame._slider = slider -- Mixins DFL:AddDefaults(frame) DFL:AddMixins(frame, self.Functions) DFL:AddScripts(frame, self.Scripts) DFL:AddScripts(slider, self.SliderScripts) frame:SetColors() frame:Refresh() return frame end -- ============================================================================ -- Functions -- ============================================================================ do local Functions = FauxScrollFrame.Functions function Functions:SetData(data) assert(type(data) == "table", "data must be a table") self._data = data self._offset = 0 self._slider:SetValue(0) end -- Enables or disables the faux scroll frame. function Functions:OnSetEnabled(enabled) for _, obj in pairs(self._objFrame._objects) do if obj.SetEnabled then obj:SetEnabled(enabled) end end end function Functions:SetColors(color, sliderColors, ...) self._objFrame._texture:SetColors(color or DFL.Colors.Area) if sliderColors then self._slider:SetColors(unpack(sliderColors)) end if (select("#", ...) > 0) then for _, object in pairs(self._objFrame:GetChildren()) do if object.SetColors then object:SetColors(...) end end end end -- Refreshes the faux scroll frame. function Functions:Refresh() for _, obj in pairs(self._objFrame._objects) do if obj.Refresh then obj:Refresh() end end self._objFrame._texture:Refresh() self._slider:Refresh() end function Functions:Resize() local objFrame = self._objFrame local slider = self._slider -- Resize slider slider:Resize() -- Resize frame local minWidth = objFrame._minWidth + (self._sliderSpacing + slider:GetWidth()) self:SetWidth(minWidth) self:SetHeight(objFrame:GetHeight()) end end -- ============================================================================ -- Scripts -- ============================================================================ do local Scripts = FauxScrollFrame.Scripts function Scripts:OnUpdate(elapsed) local objFrame = self._objFrame local slider = self._slider local spacing = self._sliderSpacing local objects = self._objFrame._objects -- Update objects for i, object in ipairs(objects) do local index = (i + self._offset) local data = self._data[index] if data then object:Show() object:SetData(data) else object:Hide() end end -- Update slider values, show slider if max value is > 0 local maxVal = max((#self._data - #objects), 0) objFrame:SetPoint(Points.TOPLEFT) if (maxVal > 0) then slider:SetMinMaxValues(0, maxVal) slider:Show() objFrame:SetPoint(Points.BOTTOMRIGHT, -(spacing + slider:GetWidth()), 0) slider:SetPoint(Points.TOPLEFT, objFrame, Points.TOPRIGHT, spacing, 0) slider:SetPoint(Points.BOTTOMLEFT, objFrame, Points.BOTTOMRIGHT, spacing, 0) else slider:SetMinMaxValues(0, 0) slider:Hide() objFrame:SetPoint(Points.BOTTOMRIGHT) end if self.OnUpdate then self:OnUpdate(elapsed) end end function Scripts:OnMouseWheel(delta) self._slider:SetValue(self._slider:GetValue() - delta) end end -- ============================================================================ -- SliderScripts -- ============================================================================ do local SliderScripts = FauxScrollFrame.SliderScripts function SliderScripts:OnValueChanged() self:GetParent()._offset = floor(self:GetValue() + 0.5) end end
c3b7b51361b063909b86e97c19ddca8d484adb9c
[ "Lua" ]
17
Lua
moody/DethsFrameLib-1.0
a3ddb951ab26cf038a3a9868bc6921b211522f89
f19c70866e235a6fef881378403a7908831f3500
refs/heads/master
<file_sep>#!/usr/bin/env bash yum update -y cat >> /etc/ecs/ecs.config << EOF ECS_CLUSTER=${cluster_name} ECS_LOGLEVEL=info ECS_LOGFILE=/var/log/ecs-agent.log EOF <file_sep># Ansible Template ## Virtual Env ```bash pyhton3 -m pip install virtualenv pyhton3 -m virtualenv -p $(which python) source ./venv/bin/activate pyhton3 -m pip install -r requirements.txt ``` <file_sep>#!/bin/bash # # Ansible Password Creator # Platform: Unix # # Author: <NAME> # echo "=== Welcome to Ansible Password Creator ===" echo read -n 1 -p " Do you want to proceed? (y/[Any key to cancel]): " WANT_PROCEED [ "$WANT_PROCEED" = "y" ] || exit 1 echo # Environment ANSIBLE_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )" VAULT_PASS_FILE="${ANSIBLE_HOME}/secrets/ansible_password" VAULT_PASS_FILE_GPG="${ANSIBLE_HOME}/secrets/ansible_password.gpg" VAULT_PASS_FILE_TMP="/tmp/ansible_password.tmp" if [ -f ${VAULT_PASS_FILE} ]; then echo ">>> Warning: ${VAULT_PASS_FILE} already exist!" read -n 1 -p "Do you want to replace it? (y/[Any key to cancel]): " WANT_REPLACE [ "${WANT_REPLACE}" = "y" ] || exit 2 echo fi if [ -f ${VAULT_PASS_FILE_GPG} ]; then echo ">>> Error: ${VAULT_PASS_FILE_GPG} already exist!" echo ">>> Error: Please decrypt it via \"${BASH_SOURCE[0]}/gpg.sh\". Exiting..." exit 3 fi read -p "Enter ansible vault password: " VAULT_PASS echo # Script touch $VAULT_PASS_FILE echo "$VAULT_PASS" > $VAULT_PASS_FILE echo exit 0 <file_sep>--- type: note tags: keyword: keyword foam_template: name: ${1:$TM_FILENAME_BASE} description: Some description --- # ${1:$TM_FILENAME_BASE} Date accessed:${CURRENT_DATE}/${CURRENT_MONTH}/${CURRENT_YEAR} ${CLIPBOARD} <file_sep>--- type: book-review tags: keyword: keyword foam_template: name: ${1:$TM_FILENAME_BASE} description: Some description --- # `TITLE_OF_BOOK` | Book Metadata | | | ------------- | ------------------------------------------------------ | | Pages | xxx | | Format | Paperback/E-book/Audiobook | | Published | xx/xx/xx | | Read | ${FOAM_DATE_YEAR}/${FOAM_DATE_MONTH}/${FOAM_DATE_DATE} | | Score | x/5 | | Goodreads | - | ## Main takeaway `In a couple sentences the main idea of the book in your own words.` ## Summary `Write a brief summary of the book in a couple of sentences.` ## Highlights `All of the highlights from the book thinkgs like quotes and examples.` ## Notes `Some notes in your own words.` <file_sep> set $cors ""; if ($http_origin ~* (.*\.example.com)) { set $cors "true"; } if ($request_method = 'OPTIONS') { set $cors "${cors}options"; } if ($request_method = 'GET') { set $cors "${cors}get"; } if ($request_method = 'POST') { set $cors "${cors}post"; } if ($cors = "true") { add_header 'Access-Control-Allow-Origin' "$http_origin"; } if ($cors = "trueget") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($cors = "trueoptions") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } if ($cors = "truepost") { add_header 'Access-Control-Allow-Origin' "$http_origin"; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } <file_sep>version: "3.9" services: kroki: image: "yuzutech/kroki" ports: - "8000:8099" <file_sep>--- type: daily-note tags: daily-notes keyword: keyword foam_template: name: ${1:$TM_FILENAME_BASE} description: Daily note ${FOAM_DATE_YEAR}/${FOAM_DATE_MONTH}/${FOAM_DATE_DATE} --- # Daily / Meeting Notes `${FOAM_DATE_YEAR}/${FOAM_DATE_MONTH}/${FOAM_DATE_DATE}` Date accessed: `${FOAM_DATE_YEAR}/${FOAM_DATE_MONTH}/${FOAM_DATE_DATE}` ## Participants - Name1 - Name2 - Name3 ## Topics | Item | Presenter | Notes | | :--- | :-------- | :---- | | | | | | | | | | | | | ## Bullet points `In bullet points the main tasks that I did todo. Have a look at your calendar and to-do list.` ## Note `Free writing about the day.` ## Feelings `How was the day? How did I feel?` ## Action items - [ ] Item 1 - [ ] Item 2 - [ ] Item 3 ## Decisions <file_sep>--- type: note tags: keyword: keyword foam_template: name: ${1:$TM_FILENAME_BASE} description: Some description --- # ${1:$TM_FILENAME_BASE} <file_sep># Ways to structurize TF projects * [Workspaces](workspaces) * [Environment directories](env-dirs) <file_sep>--- type: work tags: keyword: --- # Inbox <file_sep>--- type: work tags: keyword: --- # Workspace ## Main - [[inbox]] - #docs ## Projects - [[Projects]] ## Work - [[Work]] ## Self-Development - [[Self Development]] <file_sep>#!/bin/bash # Encrypt or decrypt protected files. # Platform: Unix # Author: <NAME> f_usage() { local Y="\033[0;33m" # Yellow local ZZ="\033[0m" # Reset printf "${Y}Usage: $(basename $0) <option>${ZZ}\n\n" printf "${Y} Options: [e]ncrypt [d]ecrypt${ZZ}\n" } ANSIBLE_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )" declare -a secured_files=( "${ANSIBLE_HOME}/secrets/ansible_password" ) declare -a recipients=() for key in `ls ${ANSIBLE_HOME}/gpg`; do recipients+="-r $(basename -- ${key%.*}) " done echo "Trusted persons: ${recipients}" [[ -f $(which gpg2) ]] && gpg_exe='gpg2' [[ -z ${gpg_exe} ]] && gpg_exe='gpg' case $1 in e|encrypt ) shift for file in "${secured_files[@]}"; do printf "\033[0;32mEncrypting $file\033[0m\n" ${gpg_exe} -e --yes --trust-model always "${recipients}" "${file}" done ;; d|decrypt ) shift for file in "${secured_files[@]}"; do printf "\033[0;32mDecrypting $file\033[0m\n" ${gpg_exe} --output ${file} --decrypt ${file}.gpg done ;; * ) f_usage ;; esac echo exit 0 <file_sep>--- type: todo-list tags: todo-lists keyword: keyword foam_template: name: ${1:$TM_FILENAME_BASE} description: Daily note ${CURRENT_DATE}/${CURRENT_MONTH}/${CURRENT_YEAR} --- # Todo You can create TODOs in Foam. - [x] This is an example of a todo list item that's complete - [ ] This one is not completed yet - [ ] You can mark it completed by pressing `Option`+`C` (or `Alt`+`C`) when your cursor is on this line - [ ] You can also select multiple lines and mark them all at once!<file_sep># Environment folder Terraform sample configuraion ## Services * Autoscalling group * DNS zone * ECS cluster * ECS serices * Load Balancer ## Information ### Environments * Global * Staging * Production ## Usage ```bash # cd to environment forlder cd <environment_folder> # Initalize clonned repo terraform init # Look at changes terrafrom plan -out terraform.plan # Apply changes terraform apply "terraform.plan" ``` <file_sep># Initialisation of Git Repository <file_sep># Wokrspace-basesTerrinitial configuration aform configuration for XXX services ## Services * Autoscalling group * DNS zone * ECS cluster * ECS Services * Load Balancer ## Information ### Environments * prod * stage > Other environments restricted ## Usage ```bash # Create workspace terraform workspace create <prod|stage> # List workspace terraform workspace list # Select workspace terraform workspace select <prod|stage> # Initalize clonned repo terraform init # Look at changes terrafrom plan -out terraform.plan # Apply changes terraform apply "terraform.plan" # Destroy all terraform destroy -out terraform.plan # Destroy partial terraform plan -destroy -target <resource1> -target <resource2> -target <resourceN> -out terraform.plan terraform apply "terraform.plan" ``` <file_sep>#!/bin/bash # # Wrapper to run Ansible in playbook mode # Platform: Unix # # Author: <NAME> # echo "=== Welcome to Ansible runner ===" echo # Environment ANSIBLE_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" VAULT_PASS_FILE="${ANSIBLE_HOME}/secrets/ansible_password" VAULT_PASS_FILE_TMP="/tmp/ansible_password.tmp" if [ ! -f ${VAULT_PASS_FILE} ]; then echo ">>> Error: Ansible password is missing!" echo "Please run ${ANSIBLE_HOME}/create_pass.sh to configure your ansible password" read -n 1 -p "Do you want to do it right now? (y/[Any key to cancel]): " WANT_INIT [ "${WANT_INIT}" = "y" ] || exit 1 echo ${ANSIBLE_HOME}/bin/create_pass.sh echo fi # Temporary files with autodeletion trap "{ rm -f ${VAULT_PASS_FILE_TMP}; }" EXIT cat ${VAULT_PASS_FILE} > ${VAULT_PASS_FILE_TMP} chmod 600 ${VAULT_PASS_FILE_TMP} # Script f_usage() { echo "Usage: $0 <COMMAND>" echo " COMMAND: a - to run ansible ad-hoc commands ap - to rub ansibpe-playbooks " } case $1 in a ) shift eval ansible \ -i ${ANSIBLE_HOME}/inventory \ --vault-password-file=${VAULT_PASS_FILE_TMP} \ $@ ;; ap ) shift ansible-playbook \ -i ${ANSIBLE_HOME}/inventory \ --vault-password-file=${VAULT_PASS_FILE_TMP} \ ${ANSIBLE_HOME}/dell-7510.yml \ $@ ;; * ) f_usage ;; esac echo exit 0
039d321874715b9a5f4f6996b58bbd4ab64d3d53
[ "Markdown", "YAML", "PHP", "Shell" ]
18
Shell
d-k-ivanov/templates
6db769e8b6221b3290f88d8e18d43ec9838849e2
3f969bb0074f5fae99935561bedc57ddd52a2ba1
refs/heads/master
<repo_name>JaysonChiang/practice-ionic-weather<file_sep>/www/views/weather/weather.html <ion-view view-title="{{params.city}}"> <ion-nav-buttons side="left"> <button class="button button-clear" menu-toggle="left"> <span class="icon ion-navicon"></span> </button> </ion-nav-buttons> <ion-nav-buttons side="right"> <button class="button button-icon" ng-click="showOptions()"> <span class="icon ion-more"></span> </button> </ion-nav-buttons> <ion-content scroll="false" class="background-img"> <ion-slides options="options" slider="data.slider"> <!-- PAGE 1--> <ion-slide-page> <div class="scroll-page center" ng-if="!isLoading"> <div class="has-header info-zone info-zone-current"> <h2 class="primary"> {{forecast.currently.temperature | number:0}}&deg; </h2> <h3 class="tertiary">體感溫度 <span class="large">{{forecast.currently.apparentTemperature|number:0}}&deg;</span> </h3> <h2 class="secondary icon" ng-class="forecast.currently.icon | icons"></h2> <h3 class="tertiary"> <span class="large">{{forecast.currently.summary}}</span> </h3> <h3 class="tertiary"> 最低 <span class="large">{{forecast.daily.data[0].temperatureMin|number:0}}&deg;</span> | 最高 <span class="large">{{forecast.daily.data[0].temperatureMax|number:0}}&deg;</span> </h3> <h3 class="tertiary"> 日出 <span class="large"> {{forecast.daily.data[0].sunriseTime| timezone:forecast.timezone}}</span> | 日落 <span class="large"> {{forecast.daily.data[0].sunsetTime| timezone:forecast.timezone}}</span> </h3> <h3 class="tertiary"> 風速 <span class="large">{{forecast.currently.windSpeed|number:0}} </span> 公里/時 </h3> <h3 class="tertiary"> 濕度 <span class="large">{{forecast.currently.humidity * 100}} % </span> </h3> </div> </div> </ion-slide-page> <!-- PAGE 2--> <ion-slide-page> <div class="scroll-page"> <div class="has-header info-zone info-zone-forcast"> <p class="padding tertiary">{{forecast.daily.summary}}</p> <div class="row" ng-repeat="day in forecast.daily.data| limitTo:settings.days"> <div class="col col-center tertiary"> <span ng-if="$first" class="today">今天</span> <span ng-if="!$first">{{day.time+'000'|date:'EEEE'| toZhTw}}</span> </div> <div class="col col-center tertiary"> <span class="icon" ng-class="day.icon | icons"></span> </div> <div class="col col-center tertiary"> <span>{{day.precipProbability | chance}} %</span> </div> <div class="col col-center tertiary">{{day.temperatureMax | number:0}}&deg; | {{day.temperatureMin | number:0}}&deg;</div> </div> </div> </div> </ion-slide-page> </ion-slides> </ion-content> </ion-view><file_sep>/www/views/search/search.js angular.module('App') .controller('SearchController', function ($scope, $http, $ionicLoading) { $scope.model = { term: '' }; $scope.search = function () { $ionicLoading.show(); $http.get('https://maps.googleapis.com/maps/api/geocode/json', { params: { address: $scope.model.term } }) .then(function (res) { $scope.results = res.data.results; $ionicLoading.hide(); }, function (err) { $ionicLoading.show({ template: err, duration: 3000 }); }) } })<file_sep>/www/js/app.js // Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' angular .module("App", ["ionic"]) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state("search", { url: "/search", controller: "SearchController", templateUrl: "views/search/search.html" }) .state("settings", { url: "/settings", controller: "SettingsController", templateUrl: "views/settings/settings.html" }) .state("weather", { url: "/weather/:city/:lat/:lng", controller: "WeatherController", templateUrl: "views/weather/weather.html" }); $urlRouterProvider.otherwise("/weather/台北/23.03/121.57"); }) .controller("LeftMenuController", function($scope, Locations) { $scope.locations = Locations.data; $scope.getIcon = function(current) { if (current) { return "ion-ios-navigate"; } return "ion-ios-location"; }; }) .factory("Settings", function() { var Settings = { units: "si", days: 8 }; return Settings; }) .factory("Locations", function($ionicPopup) { function store() { localStorage.setItem("locations", angular.toJson(Locations.data)); } var Locations = { data: [], //確定地點在結果列表的索引 getIndex: function(item) { console.log(item); var index = -1; Locations.data.forEach(function(location, i) { if (item.lat === location.lat && item.lng === location.lng) { index = i; } }); return index; }, // 從結果列表中增加或是刪除 toggle: function(item) { var index = Locations.getIndex(item); if (index >= 0) { $ionicPopup .confirm({ title: "Are you sure?", template: "This will remove " + Locations.data[index].city }) .then(function(res) { if (res) { Locations.data.splice(index, 1); } }); } else { Locations.data.push(item); $ionicPopup.alert({ title: "Location saved" }); } store(); }, // 如果新增資料,將其移到最頂層或將它增加到最頂層 primary: function(item) { var index = Locations.getIndex(item); if (index >= 0) { Locations.data.splice(index, 1); Locations.data.splice(0, 0, item); } else { Locations.data.unshift(item); } store(); } }; try { var items = angular.fromJson(localStorage.getItem("locations")) || []; Locations.data = items; } catch (e) { Locations.data = []; } return Locations; }) .filter("timezone", function() { return function(input, timezone) { if (input && timezone) { var time = moment.tz(input * 1000, timezone); return time.format("LT"); } return ""; }; }) .filter("chance", function() { return function(chance) { if (chance) { var value = Math.round(chance / 10); return value * 10; } return 0; }; }) .filter("icons", function() { var map = { "clear-day": "ion-ios-sunny", "clear-night": "ion-ios-moon", rain: "ion-ios-rainy", snow: "ion-ios-snowy", sleet: "ion-ios-rainy", wind: "ion-ios-flag", fog: "ion-ios-cloud", cloudy: "ion-ios-cloudy", "partly-cloudy-day": "ion-ios-partlysunny", "partly-cloudy-night": "ion-ios-cloudy-night" }; return function(icon) { return map[icon] || ""; }; }) .filter("toZhTw", function() { var map = { Monday: "週一", Tuesday: "週二", Wednesday: "週三", Thursday: "週四", Friday: "週五", Saturday: "週六", Sunday: "週日" }; return function(txt) { return map[txt] || txt; }; }) .run(function($ionicPlatform, $http, $state, Locations) { $ionicPlatform.ready(function() { if (window.cordova && window.cordova.plugins.Keyboard) { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); // Don't remove this line unless you know what you are doing. It stops the viewport // from snapping when text inputs are focused. Ionic handles this internally for // a much nicer keyboard experience. cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { StatusBar.styleDefault(); } if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition( function(position) { console.log(position.coords.latitude, position.coords.longitude); /* $http.get('https://maps.googleapis.com/maps/api/geocode/json', { params: { latlng: position.coords.latitude + ',' + position.coords.longitude } }) .then(function (res) { //建立一個新的地點到地點列表 var location = { lat: position.coords.latitude, lng: position.coords.longitude, city: res.data.results[0].formatted_address, current: true }; Locations.data.unshift(location); $state.go('weather', location) } ); */ }, function(err) { console.log("error", err); } ); } else { console.log("geolocation IS NOT available"); } }); }); <file_sep>/www/views/weather/weather.js angular .module("App") .controller("WeatherController", function( $scope, $http, $stateParams, $ionicActionSheet, $ionicModal, $ionicLoading, Settings, Locations ) { $scope.params = $stateParams; $scope.settings = Settings; $ionicLoading.show(); $scope.isLoading = true; $http .get("/api/forecast/" + $stateParams.lat + "," + $stateParams.lng, { params: { units: Settings.units, lang:'zh-tw' } }) .then( function(res) { $scope.forecast = res.data; console.log(res.data); $ionicLoading.hide(); $scope.isLoading = false; }, function(err) { $ionicLoading.show({ template: err.data, duration: 3000 }); $scope.isLoading = true; } ); // $ionicSlides START $scope.options = { loop: false, effect: "slide", speed: 500 }; $scope.$on("$ionicSlides.sliderInitialized", function(event, data) { // data.slider is the instance of Swiper $scope.slider = data.slider; }); $scope.$on("$ionicSlides.slideChangeStart", function(event, data) { console.log("Slide change is beginning"); }); $scope.$on("$ionicSlides.slideChangeEnd", function(event, data) { // note: the indexes are 0-based $scope.activeIndex = data.slider.activeIndex; $scope.previousIndex = data.slider.previousIndex; }); // $ionicSlides END //Scroll var barHeight = document.getElementsByTagName("ion-header-bar")[0] .clientHeight; $scope.getWidth = function() { return window.innerWidth + "px"; }; $scope.getHeight = function() { return parseInt(window.innerHeight - barHeight) + "px"; }; $scope.getTotalHeight = function() { return parseInt(parseInt($scope.getHeight()) * 3) + "px"; }; $scope.showOptions = function() { var sheet = $ionicActionSheet.show({ buttons: [ { text: "Toggle Favorite" }, { text: "Set as Primary" }, { text: "Sunrise Sunset Chart" } ], cancelText: "Cancel", buttonClicked: function(index) { var item = { city: $scope.params.city, lat: +$scope.params.lat, lng: +$scope.params.lng }; if (index === 0) { Locations.toggle(item); } if (index === 1) { Locations.primary(item); } if (index === 2) { $scope.showModal(); } return true; } }); }; $scope.showModal = function() { if ($scope.modal) { $scope.modal.show(); } else { $ionicModal .fromTemplateUrl("views/weather/modal-chart.html", { scope: $scope }) .then(function(modal) { $scope.modal = modal; var days = []; var day = Date.now(); for (var i = 0; i < 365; i++) { day += 1000 * 60 * 60 * 24; days.push( SunCalc.getTimes(day, $scope.params.lat, $scope.params.lng) ); } $scope.chart = days; $scope.modal.show(); }); } }; $scope.hideModal = function() { $scope.modal.hide(); }; $scope.$on("$destroy", function() { $scope.modal.remove(); }); });
bf2d40f127b035cb18b329c85449429cb8a0df8a
[ "JavaScript", "HTML" ]
4
HTML
JaysonChiang/practice-ionic-weather
2099bd2f0faa03a58e92e0d4e257239992ef2854
1393900df9441008a2fc1b5426d7d339dfe746dd
refs/heads/master
<repo_name>buluf/PUC<file_sep>/Redes 1/notações/notas_aulas_redes.md Aulas ### Camada Física * Meios de transmissão * Largura de banda e taxa de dados * Unidades Métricas * Atrasos em redes de comutação de pacotes Oque é largura de banda? é a faixa de frequências que aquele canal físico suporta sem grande atenuação, então ela é dada em hertz. #### Meios de Transmissão * Objetivo da camada física: * Transportar uma sequência de bits de uma máquina para outra * Problema a ser resolvido: * Codificação de bits * O tipo de meio físico a ser usado depende, dentre outros fatores de: * Largura de banda (bandwidth) * Atraso (delay) ou latência (latency) ou retardo * Custo * Facilidade de instalação e manutenção * Os meios podem ser agrupados em: * Guiados: as ondas são guiadas através de um caminho físico (par trançado, cabo coaxial ou fibra óptica) * Não-guiados: as ondas se propagam sem haver um caminho físico (ondas de rádio, microondas ou infravermelho) meio com fio probabilidade de erro na transmissão baixa sem fio probabilidade de erro na transmissão mais alta #### Largura de Banda * É a faixa de frequência transmitida por um meio físico sem serem fortemente atenuadas, denomina-se largura de banda * A largura de banda é uma propriedade física do meio de transmissão e, em geral, depende da construção, da espessura e do comprimento do meio * Limitando-se a largura de banda, limita-se a taxa de dados ![taxa de dados](images/taxa_de_dados.PNG) ### Subcamada de controle de Acesso ao Meio (MAC) #### Problema de Alocação de Canais * Protocolos para * Canais difusão, ou * Canais de acesso múltiplo(multiacesso), ou * Canais de acesso aleatório * Problema básico a ser resolvido: * Como "gerenciar" o acesso a canais difusão * Protocolos responsáveis por fazer esse gerenciamento: * Protocolos de acesso ao meio, ou Medium Access Control (MAC) * Sub-camada MAC está presente em quase todas as LANs * Problema: * Como alocar um único canal difusão entre vários usuários? * Duas classes de algoritmos: * Alocação estática * Alocação dinâmica #### Alocação Estática de Canais * FDM (***Frequency Division Multiplexing***) * Se existem N usuários, a largura de banda é dividida em N partes do mesmo tamanho e a cada usuário será atribuída uma parte * FDM é a forma tradicional quando: * Existe um número pequeno e fixo de usuários * Cada um possui um tráfego pesado * Outro cenário: * Grande número de estações * Esse número varia ao longo do tempo * Tráfego é em rajadas * Normalmente, FDM não é a solução: * Sub-canais ficam ociosos quando não há nada a transmitir * Em sistemas de computação, o tráfego é tipicamente em rajadas #### Alocação Dinâmica de Canais * Estações: * Existem N estações independentes que geram quadros a serem transmitidos * A estação fica bloqueada até o quadro ser totalmente transmitido * Único canal de comunicação: * Todas estações compartilham um único canal de comunicação para transmissão e recepção * Do ponto de vista de hardware, as estações são equivalentes * Do ponto de vista de software, as estações podem ter prioridades * Colisões: * A transmissão "simultânea" de dois ou mais quadros por estações diferentes causa uma colisão * Estações são capazes de detectar colisões * Quadros envolvidos em colisões devem ser transmitidos mais tarde * Política de transmissão de quadros ao longo do tempo: * Tempo contínuo (continuous time): qualquer instante * Tempo segmentado (slotted time): o tempo é dividido em intervalos discretos(slots), as transmissões de quadros sempre começam no início de um slot <file_sep>/Redes 1/notações/exercicios.md # Exercícios #### 2. Explique a necessidade de um mecanismo de controle de acesso ao meio nas redes difusão. Porque se não tivesse um dispositivo de controle de acesso numa rede broadcast(difusão) sendo que o canal de comunicação dela é compartilhado qualquer um poderia acessar mensagens que não lhe é destinado. Por isso também foi adicionado um campo de endereço em toda mensagem. #### 3. Dê um exemplo de um serviço orientado a conexão confiável. Justifique sua resposta. Transferência de arquivos(transporte). TCP(Transmission Control Protocol) é um exemplo disso, pois ele permite a entrega sem erros(confiável) de dados de uma determinada máquina a outra máquina da rede. O proprietário do arquivo deseja se certificar que todos os bits chegaram corretamente e na mesma ordem em que foram enviados. #### 4. Em alguns casos, quando uma conexão é estabelecida, o transmissor e o receptor conduzem uma “negociação” sobre os parâmetros a serem usados. Dê um exemplo do uso de negociação pelos protocolos de rede. Como por exemplo definir o tamanho máximo das mensagens, a qualidade do serviço exigida e entre outra possibilidades. Em geral, um lado faz uma proposta e a outra parte pode aceitá-la, rejeitá-la ou fazer um contraproposta. #### 5 Como seria o tipo de serviço que um usuário de uma aplicação de tempo real precisaria? Justifique. Seria algo no estilo do protocolo UDP(User Datagram Protocol) algo que não será orientado a conexão, pois não há garantia de envio/recebimento de pacotes e isso é caro, para um aplicação de tempo real não serviria. #### 6. Quando um arquivo é transferido entre dois computadores, são possíveis duas estratégias de confirmação. Na primeira, o arquivo é dividido em pacotes, que são confirmados individualmente pelo receptor, mas a transferência do arquivo como um todo não é confirmada. Na segunda, os pacotes não são confirmados individualmente mas, ao chegar a seu destino, o arquivo inteiro é confirmado. Analise essas duas abordagens. Começando pela segunda abordagem tem um problema bem nítido, e provável que aconteça, que é o problema de houver um falha logo de começo, ele só será noticiado no final de seu destino, e terá que retransmitir tudo de novo. A primeira abordagem se houver falha no meio do caminho ela responderá muito melhor, mas ela terá um overhead muito alto, ter que enviar confirmação toda hora pode não valer muita a pena. #### 7. Determine qual das camadas do modelo OSI trata de cada uma das tarefas a seguir: * Dividir o fluxo de bits transmitidos em quadros. * Definir a rota que será utilizada na sub-rede. a) Camada de enlace de dados, é usado quando ela mascara os erros de transmissão para a camada de rede(para que a camada de rede não veja), fazendo com que o transmissor divida os dados de entrada em quadros de dados(que, em geral, tem algumas centenas ou alguns milhares de bytes). b) Camada de rede, é nela que é determinado a maneira como os pacotes serão transportados(roteados) da origem até o destino. #### 8. Um sistema tem uma hierarquia de protocolos com n camadas. As aplicações geram mensagens com M bytes de comprimento. Em cada uma das camadas, é acrescentado um cabeçalho com h bytes. Qual é a fração da largura de banda da rede é preenchida pelos cabeçalhos? fração da largura de banda = h.n/(M + h.n) #### 9. Cite dois aspectos em que o modelo de referência OSI e o modelo de referência TCP/IP são iguais. Agora cite dois aspectos em que eles são diferentes. O uso da camada de aplicação, a única diferença nesse sentido é que o modelo TCP/IP não tem as camadas de sessão nem de apresentação, não havia necessidade, então ele usa a camada de aplicação para meio que tapar esse "buraco", mas tirando isso é usada da mesma forma, tem até protocolos em comum usados na mesma camada, como o HTTP por exemplo. Outros aspectos iguais são nas duas terem também a camada de enlace e de transporte. E outro aspecto diferente que eu acho importante citar, seria na camada de transporte, o modelo TCP/IP ter um serviço orientado a conexão e não orientado a conexão, dando essa versatilidade com os protocolos TCP e UDP, e no OSI só o orientado a conexão. Ambos se baseiam no conceito de uma pilha de protocolos independentes. #### 10. Qual é a principal diferença entre o TCP e o UDP? TCP usa um serviço orientado à conexão UDP não orientado a conexão/ não é confiável #### 20. Compare o retardo do ALOHA puro com o do slotted ALOHA com uma carga mínima (por exemplo, apenas uma estação usando o canal). Qual deles é menor? Explique sua resposta. Slotted ALOHA, pois seu throughput é maior já que sua probabilidade de colisão é menor em relação ao ALOHA puro, logo menos retardo. Vulnerable Time = Frame Transmission time.(duas vezes menor em relação ao ALOHA puro) Throughput = G x e^-G; Where G is the number of stations wish to transmit in the same time. Maximum throughput = 0.368 for G=1 (o dobro do ALOHA original). #### 21. Suponha um enlace de comunicação que utiliza CRC com o polinômio gerador x8+x5+x4+x2+1 que recebe duas mensagens: 10011001111010101111000 10011001111010101110000 1. Qual é o tamanho do total de verificação deste enlace? Justifique Segundo o método do código polinomial o tamanho do nosso CRC seria igual ao grau do polinômio gerador. O grau do nosso polinômio gerador é 8, esse será o tamanho do código de verificação que será acrescentado na extremidade de baixa ordem do nosso quadro. 2. Estas mensagens contêm erros? Justifique. hora do teste 10011001111010101111000 % 100110101 = 0 -> logo não teve erro na primeira mensagem 10011001111010101110000 % 100110101 = 1000 -> segunda mensagem teve erro de transmissão 3. Encontre a mensagem original (sem o total de verificação) das mensagens sem erro. 10011001111010101111000 -> 100110011110101 (mensagem original) 4. Para as mensagens que não contêm erros, apresente um erro que não seria detectado pelo CRC. se eu pegar a primeira mensagem 10011001111010101111000 e soma-la ao meu gerador, se tornará outro múltiplo dele onde que a divisão continuará zero, mas mesmo assim com alguns bits trocados. exemplo de como nossa mensagem poderia ficar com erro mais indetectável pelo nosso CRC: 10011001111010001001101 #### 22. Uma LAN CSMA/CD de 10 Mbps (não 802.3) com a extensão de 1 km tem uma velocidade de propagação de 200m/s. Não são permitidos repetidores nesse sistema. Os quadros de dados têm 256 bits, incluindo 32 bits de cabeçalho, totais de verificação e outras formas de overhead. O primeiro slot de bits depois de uma transmissão bem-sucedida é reservado para o receptor capturar o canal com o objetivo de enviar um quadro de confirmação de 32 bits. Qual será a taxa de dados efetiva, excluindo o overhead, se partirmos do princípio de que não há colisões? <file_sep>/CP/Tarefas/Projeto01/mlp/converteEntrada.cpp #include <bits/stdc++.h> int main(){ FILE *fileEntrada; fileEntrada = fopen("X.txt","rb"); FILE *fileSaida; fileSaida = fopen("X-Text.txt","w") return 0; } <file_sep>/BD/AS03/README.md # as03-buluf <file_sep>/LP/TP1/notes.md ## Valores ### Tipos de dados #### Tuplas Tuplas é um tipo de dados semelhante a um registro, exceto que os elementos não são nomeados. #### Equivalência de Tipos Talvez o resultado mais importante de duas variáveis serem de tipos equivalentes é que uma pode ter seu valor atribuído para a outra. A equivalência de tipos por estrutura é mais flexível que a equivalência por nome, mas é mais difícil de ser implementada. ### Expressões Expressões são os meios fundamentais de especificar computações em uma linguagem de programação. A essência das linguagens de programação imperativas é o papel dominante das sentenças de atribuição. A finalidade dessas sentenças é causar o efeito colateral de alterar os valores de variáveis, ou o estado, do programa. Então, uma parte integrante de todas as linguagens imperativas é o conceito de variáveis cujos valores mudam durante a execução de um programa. <file_sep>/Redes 1/notações/notas_livro_redes.md ## **Acrônimos:** * VPNs (Virtual Private Networks) * NFC (Near Field Communication) * RFID (Radio Frequency IDentification) * LAN (Local Area Network) * AP (Access Point) * MAN (Metropolitan Area Network) * WAN (Wide Area Network) * ISP (Internet Service Provider) * ISO (International Standards Organization) * OSI (Open Systems Interconnection) * IP (Internet Protocol) * TCP (Trnasmission Control Protocol) * UDP (User Datagram Protocol) * ICMP(Internet Control Message Protocol) * DNS (Domain Name Service) * FTTH (Fiber to the home) * CSMA (Carrier Sense Multiple Access) # Termos importantes #### Peer-to-peer(do inglês par-a-par ou ponto-a-ponto, famoso P2P) é uma arquitetura de redes de computadores onde cada um dos pontos ou nós da rede funciona tanto como cliente quanto como servidor, permitindo compartilhamentos de serviços e dados sem a necessidade de um servidor central. Seu projeto tem como objetivo distribuir um serviço totalmente descentralizado e organizado, equilibrando, automaticamente, as cargas de armazenamento e processamento de forma dinâmica entre todos os computadores participantes à medida que as máquinas entram e saem do serviço. # Tópicos do livro ## HARDWARE DE REDE redes de computadores hoje que se destacam além das demais: a tecnologia de transmissão e a escala. #### Tecnologias de transmissão Em termos gerais, há dois tipos de tecnologias de transmissão em uso disseminado nos dias de hoje: enlaces de **broadcast** e enlaces **ponto a ponto**. Os enlaces ponto a ponto conectam pares de máquinas individuais. Para ir da origem ao destino em uma rede composta de enlaces ponto a ponto, mensagens curtas, chamadas **pacotes** em certos contextos, talvez tenham de visitar primeiro uma ou mais máquinas intermediárias. A transmissão ponto a ponto com exatamente um transmissor e exatamente um receptor às vezes é chamada de **unicasting**. Já as redes de broadcast tem apenas um canal de comunicação, compartilhado por todas as máquinas da rede; os pacotes enviados por qualquer máquina são recebidos por todas as outras. **Obs:** *Uma rede sem fio é um exemplo comum de um enlace broadcast, com a comunicação compartilhada por uma região de cobertura que depende do canal sem fios e da máquina transmissora.* ##### Escala ou escalabilidade Um critério alternativo para classificar as redes. A distância é importante como métrica de classificação, pois diferentes tecnologias são usadas em diferentes escalas. ![escalabilidade](images/escalabilidade.PNG) #### Redes Pessoais As redes pessoais, ou PANs (Personal Area Networks), permitem que dispositivos se comuniquem pelo alcance de uma pessoa. **Bluetooth** as redes Bluetooth usam um paradigma mestre-escravo. ![bluetooth](images/bluetooth.PNG) A unidade do sistema(PC) normalmente é o mestre, e os periféricos, escravos. O mestre diz aos escravos quais endereços usar, quando eles podem transmitir, por quanto tempo, quais frequências eles podem usar e assim por diante. #### Redes Locais **Rede local**, ou **LAN(Local Area Network).** Uma LAN é uma rede particular que opera dentro e próximo de um único prédio, como uma residência, um escritório ou uma fábrica. As LANs são muito usadas para conectar computadores pessoais e aparelhos eletrônicos, para permitir que compartilhem recursos (como impressoras) e troquem informações. **obs**: Quando as LANs são usadas pelas empresas, elas são chamadas **redes empresariais.** LANs sem fio são muito populares atualmente, especialmente nas residências, prédios de escritórios antigos e lugares onde a instalção de cabos é muito trabalhosa. Nesses sistemas, cada computador tem um rádio modem e uma antena, que ele usa para se comunicar com outros computadores. Quase sempre, cada computador fala com um dispositivo no teto, chamado **ponto de acesso**, **roteador sem fio** ou **estação-base**,repassa os pacotes entre os computadores sem fio e também entre eles e a Internet. Ser o AP é como ser o garoto popular na escola, pois todos querem falar com você. Porém, se os outros computadores estiverem próximos o suficiente, eles podem se comunicar diretamente em uma configuração peer-to-peer. Existe um padrão para as LANs sem fios, chamado **IEEE 802.11**, nosso famigerado **WiFi**. Ele trabalha em velocidades de 11 a centenas de Mbps. ![WiFi](images/ponto_de_acesso.PNG) As LANs com fios Utilizam uma série de tecnologias de transmissão diferentes. A maioria delas usa fios de cobre, mas algumas usam fibra óptica. A topologia de muitas LANs com fios é embutida a partir de enlaces ponto a ponto. O IEEE 802.3, popularmente chamado **Ethernet**, é de longe o tipo mais comum de LAN com fios. **Ethernet comutada** ![comutada](images/ethernet_comutada.PNG) Cada computador troca informações usando o protocolo Ethernet e se conecta a um dispositivo de rede chamado **switch**, com um enlace ponto a ponto. Daí o nome. Um switch tem várias **portas**, cada qual podendo se conectar a um computador. A função do switch é repassar os pacotes entre os computadores que estão conectados a ela, usando o endereço em cada pacote para determinar para qual computador enviá-lo. Os switches podem ser conectados uns aos outros usando suas portas. Também é possível dividir uma LAN física grande em duas LANs lógicas menores(VLAN). As redes de broadcast, com e sem fios, ainda podem ser divididas em estáticas e dinâmicas, dependendo do modo como o canal é alocado. Em uma alocação estática típica, o tempo seria dividido em intervalos discretos e seria utilizado um algoritmo de rodízio, fazendo com que cada máquina transmitisse apenas no intervalo de que dispõe. Mas a maioria dos sistemas procura alocar o canal dinamicamente(por demanda) pois não compensa ficar esperando... Os métodos de alocação dinâmica de um canal comum são centralizados ou descentralizados. No método centralizado de alocação de canal, existe apenas uma entidade, por exemplo, a estação-base nas redes celulares, que determina quem transmitirá em seguida. No método descentralizado de alocação de canal, não existe nenhuma entidade central; cada máquina deve decidir por si mesma se a transmissão deve ser realizada. Da a ideia de que isso sempre leva ao caos, mas isso não acontece. Depois estudaremos algoritmos criados para impedir a instauração do caos potencial. #### Redes Metropolitanas Uma **rede metropolitana**, ou **MAN (Metropolitan Area Network), abrange uma cidade. O exemplo mais conhecido de MANs é a rede de televisão a cabo disponível em muitas cidades. Em uma primeira aproximação, uma MAN seria semelhante ao sistema mostrado abaixo: ![MAN](images/man.PNG) observamos que os sinais de televisão e de internet são transmitidos à **central a cabo** centralizada para distribuição subsequente às casas das pessoas. Porém, a televisão a cabo não é a única MAN. OS desenvolvimentos recentes para acesso à internet de alta velocidade sem fio resultaram em outra MAN, que foi padronizada como IEEE 802.16 e é conhecida popularmente como **WiMax.** #### Redes A Longas Distâncias Uma **rede a longa distância**, ou **WAN (Wide Area Network)**, abrange uma grande área geográfica, com frequência um país ou continente. Na maioria das WANs, a sub-rede consiste em dois componentes distintos: linhas de transmissão e elementos de comutação. As **linhas de transmissão** transportam bits entre as máquinas. Elas podem ser formadas por fios de cobre, fibra óptica, ou mesmo enlaces de radiofusão. Os **elementos de comutação**, ou apenas comutadores, são computadores especializados que conectam três ou mais linhas de transmissão. Quando os dados chegam a uma interface de entrada, o elemento de comutação deve escolher uma interface de saída para encaminhá-los. Esses computadores de comutação receberam diversos nomes no passado; o nome **roteador** é, agora o mais comumente usado. Obs: 'sub-rede'. Originalmente, seu **único** significado identificava o conjunto de roteadores e linhas de comunicação que transportava pacotes entre os hosts de origem e de destino. ##### Variedade de WANs Primeiro , em vez de alugar linhas de transmissão dedicadas, uma empresa pode conectar seus escritórios à Internet. Isso permite que as conexões sejam feitas entre os escritórios como enlaces virturais que usam a capacidade de infraestrutura da Internet. Esse arranjo: ![vpn](images/vpn.PNG) é chamado de **rede privada virtual,** ou **VPN (Virtual Private Network)**. Em comparação com o arranjo dedicado, uma VPN tem a vantagem comum da virtualização, ou seja, ela oferece flexibilidade na reutilização de recurso (conectividade com a Internet). Com uma VPN, suas milhas estão sujeitas à variação, de acordo com o serviço da internet. A segunda variação é que a sub-rede pode ser operada por uma empresa diferente. O operador da sub-rede é conhecido como um **provedor de serviço de rede**, e os escritórios são seus clientes. O operador da sub-rede também se conectará a outros clientes, desde que eles possam pagar e ela possa oferecer o serviço. O operador da sub-rede também se conectará a outras redes que fazem parte da Internet. Esse operador de sub-rede é chamado de **provedor de serviço de Internet,** ou **ISP (Internet Service Provider),** e a sub-red é uma **rede ISP.** Seus clientes que se conectam à ISP recebem serviço de internet. A rede de telefonia celular é outro exemplo de uma WAN que usa tecnologia sem fio. Esse sistema já passou por três gerações, e uma quarta está a caminho. A primeira geração era analógica e usada apenas para voz e usada apenas para voz. a segunda geração era digital e apenas para voz. A terceira geração é digital e se destina a voz e dados. #### Redes Interligadas (Internets) Existem muitas redes no mundo, frequentemente apresentando diferentes tipos de hardware e software. normalmente, as pessoas conectadas a redes distintas precisam se comunicar entre si. Para que esse desejo se torne uma realidade, é preciso que se estabeleçam conexões entre redes quase sempre incompatíveis. Um conjunto de redes interconectadas forma uma **rede interligada** ou **internet**. O nome geral para uma máquina que faz uma conexão entre duas ou mais redes e oferece a conversão necessária, tanto em termos de hardware quanto de software, é um **gateway.** Os gateways são distinguidos pela camada em que operam na hierarquias de protocolos. Como o benefício de formar uma rede interligada é conectar computadores pelas redes, não queremos usar um gateway em muito baixo nível, ou então não poderemos fazer conexões entre diferentes tipos de redes. Também não queremos usar um gateway em um nível muito alto, ou então a conexão só funcionará para determinadas aplicações. O nível do meio, que é o mais apropriado, normalmente é chamado de camada de rede, e um roteador é um gateway que comuta pacotes nessa camada. Agora podemos localizar uma rede interligada descobrindo uma rede que tem roteadores. #### Software De Rede ##### Hierarquias De Protocolos Para reduzir a complexidade de seu projeto, a maioria das redes é organizada como uma pilha de **camadas**(ou **níveis**), colocadas umas sobre as outras. O número, o nome, o conteúdo e a função de cada camada diferem de uma rede para outra. No entanto, em todas as redes o objetivo de cada camada é oferecer determinados serviços às camadas superiores, isolando essas camadas dos detalhes de implementação real desses recursos. Em certo sentido, cada camada é uma espécie de máquina virtual, oferecendo determinados serviços à camada situada acima dela. Quando a camada n de uma máquina se comunica com a camada n de outra máquina, coletivamente, as regras e convenções usadas nesse diálogo são conhecidas como protocolo da camada n. Basicamente, um **protocolo** é um acordo entre as partes que se comunicam, estabelecendo como se dará a comunicação. Rede de cinco camadas: ![camadas](images/cinco_camadas.PNG) As entidade que ocupam as camadas correspondentes em diferentes máquinas são chamadas pares(ou **peers**). Os pares podem ser processos de software, dispositivos de hardware, ou mesmo seres humanos. Em outras palavras, são os pares que se comunicam utilizando o protocolo. Não há comunicação direta entre a camada n de uma máquina para camada n de outra máquina. Em vez disso, cada camada transfere os dados e as informações de controle para a camada imediatamente abaixo dela, até a camada mais baixa ser alcançada, abaixo da camada 1 encontra-se o **meio físico** por meio do qual se dá a comunicação propriamente dita. Entre cada par de camadas adjacentes existe uma **interface**. Esta define as operações e os serviços que a camada inferior tem a oferecer à camada acima dela. Um conjunto de camadas e protocolos é chamado de **arquitetura de rede**. A especificação de uma arquitetura deve conter informações suficientes para permitir que um implementador desenvolva o programa ou construa o hardware de cada camada de forma que ela obedeça corretamente ao protocolo adequado. Uma lista de protocolos usados por um determinado sistema, um protocolo por camada, é chamada **pilha de protocolos.** ##### Questões de projeto relacionadas às camadas Confiabilidade é a questão de projeto de criar uma rede que opere corretamente, embora sendo composta de uma coleção de componentes que não são confiáveis. Imaginando bits de um pacote trafegando pela rede. Há uma chance de que alguns desses bits sejam recebidos com problemas(invertidos) em virtude de um ruído elétrico casual, sinais sem fio aleatórios, falhas de hardware, bugs de software e assim por diante. Uma segunda questão de projeto se refere à evolução da rede. Com o tempo, as redes se tornam maiores e novos projetos aparecem precisando ser conectados à rede existente. Recentemente, vimos o mecanismo-chave de estrutura usado para dar suporte à mudança, dividindo o problema geral e ocultando detalhes da implementação: as **camadas de protocolos.** Mas existem outras estratégias. Uma terceira questão de projeto é a alocação de recursos. As redes oferecem um serviço aos hosts a partir de seus recursos subjacentes, como a capacidade de linhas de transmissão. Para fazer isso bem, elas precisam de mecanismos que dividem seus recursos de modo que um host não interfira muito em outro. A última questão de projeto trata de proteger a rede, defendendo-a contra diferentes tipos de ameaças. Uma das ameaças que mencionamos anteriormente é a de bisbilhotagem nas comunicações. Mecanismos que oferecem **confidencialidade** defendem contra essa ameaça e são usados em várias camadas. Os mecanismos para **autenticação** impedem que alguém finja ser outra pessoa. ##### Serviços orientados e não orientados a conexões O serviço **orientado a conexões** se baseia no sistema telefônico. Para falar com alguém, você tira o fone do gancho, digita o número, fala e, em seguida, desliga. Da mesma forma, para utilizar um serviço de rede orientado a conexões, primeiro o usuário do serviço estabelece uma conexão, a utiliza, e depois a libera. Em alguns casos, quando uma conexão é estabelecida, o transmissor, o receptor e a sub-rede conduzem uma negociação sobre os parâmetros a serem usados, como o tamanho máximo das mensagens, a qualidade do serviço exigida e outras questões. Ao contrário do serviço orientado a conexões, o serviço **não orientado a conexões** se baseia no sistema postal. Cada mensagem(carta) carrega o endereço de destino completo e cada uma delas é roteada pelos nós intermediários através do sistema, independentemente de todas as outras. Existem diferentes nomes para mensagens em diferentes contextos; um **pacote** é uma mensagem na camada de rede. Quando os nós intermediários recebem uma mensagem completa antes de enviá-la para o próximo nó, isso é chamado **comutação store-and-forward.** A alternativa, em que a transmissão de uma mensagem em um nó começa antes de ser completamente recebida por ele é chamada **comutação cut-through.** Cada tipo de serviço pode ser caracterizado por sua confiabilidade. Em geral, um serviço confiável é implementado para que o receptor confirme o recebimento de cada mensagem, de modo que o transmissor se certifique de que ela chegou. Para algumas aplicações, os atrasos introduzidos pelas confirmações são inaceitáveis. Uma dessas aplicações é o tráfego de voz digital por **Voice over IP (VoIP).** Os usuários de telefone preferem ouvir um pouco de ruído na linha ou uma palavra truncada de vez em quando a experimentar um atraso para aguardar confirmações. O serviço não orientado a conexões não confiável (ou seja, sem confirmação) costuma ser chamado serviço de **datagramas**, em uma analogia com o serviço de telegramas, que também não oferece uma confirmação ao transmissor. Em outras situações, a conveniência de não ter de estabelecer uma conexão para enviar uma única mensagem curta é desejável, mas a confiabilidade é essencial. O serviço de **datagramas confirmados** pode ser oferecido para essas aplicações. Ele é semelhante a enviar uma carta registrada e solicitar um aviso de recebimento. Quando o aviso é devolvido, o transmissor fica absolutamente certo de que a carta foi entregue ao destinatário e não perdida ao longo do caminho.(tipo o zap zap) Outro serviço é o de **solicitação/resposta.** Nele, o transmissor envia um único datagrama contendo uma solicitação; a resposta contém a réplica. A solicitação/resposta é em geral usada para implementar a comunicação no modelo cliente-servidor: o cliente emite uma solicitação e o servidor responde. ![servicos](images/servicos_orientado_nao.PNG) ##### Primitivas De Serviço Um serviço é especificado formalmente por uma conjunto de **primitivas** (operações) disponíveis para que os processos do usuários acessem o serviço. Essas primitivas informam ao serviço que ele deve executar alguma ação ou relatar uma ação executada por uma entidade par. Se a pilha de protocolos estiver localizada no sistema operacional, como ocorre com frequência, as primitivas serão normalmente chamadas do sistema. Essas chamadas geram uma armadilha para o kernel, que então devolve o controle da máquina ao sistema operacional para enviar os pacotes necessários. ##### Relacionamento Entre Serviços E Protocolos Serviços e protocolos são conceitos diferentes. Um serviço é um conjunto de primitivas (operações) que uma camada oferece à camada situada acima dela. O serviço define as operações que a camada está preparada para executar em nome de seus usuários, mas não informa absolutamente nada sobre como essas operações são implementadas. Um serviço se relaciona a uma interface entre duas camadas, sendo a camada inferior o fornecedor do serviço e a camada superior, o usuário do serviço. Ao contrário, o protocolo é um conjunto de regras que controla o formato e o significado dos pacotes ou mensagens que são trocadas pelas entidades pares contidas em uma camada. As entidades utilizam protocolos com a finalidade de implementar suas definições de serviço. Elas têm a liberdade de trocar seus protocolos, desde que não alterem o serviço visível para seus usuários. Portanto, o serviço e o protocolo são independentes um do outro. ![servico/protocolo](images/servico_protocolo.PNG) #### Modelos De Referência Modelos de referência a se tratar, OSI e TCP/IP. Embora os protocolos associados ao modelo OSI raramente sejam usados nos dias de hoje, o modelo em si é de fato bastante geral e ainda válido, e as características descritas em cada camada ainda são muito importantes. O modelo TCP/IP tem características opostas: o modelo propriamente dito não é muito utilizado, mas os protocolos são bastante utilizados. ##### O Modelo De Referência OSI Esse modelo se baseia em uma proposta desenvolvida pela ISO (International Standards Organization) como um primeiro passo em direção à padronização internacional dos protocolos usados nas várias camadas (Day e Zimmermann, 1983). Ele foi revisado em 1995. O modelo se chama **Modelo de Referência ISO OSI (Open Systems Interconnection),** pois ele trata da interconexão de sistemas abertos - ou seja, sistemas abertos à comunicação com outros sistemas. Para abreviar chamaremos de **modelo OSI**. O modelo OSI tem sete camadas. Veja, a seguir, um resumo dos princípios aplicados para chegar às sete camadas. 1. Uma camada deve ser criada onde houver necessidade de outro grau de abstração. 2. Cada camada deve executar uma função bem definida. 3. A função de cada camada deve ser escolhida tendo em vista a definição de protocolos padronizados internacionalmente. 4. Os limites de camadas devem ser escolhidos para minimizar o fluxo de informações pelas interfaces. 5. O número de camadas deve ser grande o bastante para que funções distintas não precisem ser desnecessariamente colocadas na mesma camada e pequeno o suficiente para que a arquitetura não se torne difícil de controlar. **A Camada Física** A **camada física** trata da transmissão de bits normais por um canal de comunicação. O projeto da rede deve garantir que, quando um lado enviar um bit 1, o outro lado o receberá como um bit 1, não como um bit 0. As questões mais comuns aqui são quais o sinais elétricos que devem ser usados para representar um bit 1 e um bit 0, que quantidade de nanossegundos que um bit deve durar, se a transmissão pode ou não ser realizada simultaneamente nos dois sentidos, a forma como a conexão inicial será estabelecida e de que maneira ela será encerrada quando ambos os lados tiverem terminado, e ainda quantos pinos o conector de rede terá e qual será a finalidade de cada pino. Nessa situação, as questões de projeto lidam em grande parte com interfaces mecânicas, elétricas e de sincronização, e com o meio físico de transmissão que se situa abaixo da camada física. **A Camada De Enlaces De Dados** A principal tarefa da **camada de enlace de dados** é transformar um canal de transmissão normal em uma linha que pareça livre de erros de transmissão. Para fazer isso, a camada de enlace mascara os erros reais, de modo que a camada de rede não os veja. Isso é executado fazendo com que o transmissor divida os dados de entrada em **quadros de dados** (que, em geral, têm algumas centenas ou alguns milhares de bytes) e transmita os quadros sequencialmente. Se o serviço for confiável, o receptor confirmará a recepção correta de cada quadro, enviando de volta um **quadro de confirmação.** As redes de broadcast têm uma questão adicional a ser resolvida na camada de enlace de dados: como controlar o acesso ao canal compartilhado. Uma subcamada especial da camada de enlace de dados, a subcamada de **controle de acesso ao meio**, trata desse problema. **A Camada De Rede** A **camada de rede** controla a operação da sub-rede. Uma questão fundamental de projeto é determinar a maneira como os pacotes são roteados da origem até o destino. As rotas podem se basear em tabelas estáticas, 'amaradas' à rede e raramente alteradas, ou frequentemente podem ser atualizadas de forma automática, para evitar componentes defeituosos. Elas também podem ser determinadas no início de cada conversação; por exemplo, uma sessão de terminal, como um login em uma máquina remota. Por fim, elas podem ser altamente dinâmicas, sendo determinadas para cada pacote, refletindo a carga atual da rede. De modo mais geral, a qualidade do serviço fornecido (atraso, tempo em trânsito, instabilidade etc.) também é uma questão da camada de rede. Quando um pacote precisa trafegar de uma rede para outra até chegar a seu destino, podem surgir muitos problemas. O endereçamento utilizado pela segunda rede pode ser diferente do que é usado pela primeira. Talvez a segunda rede não aceite o pacote por ele ser muito grande. Os protocolos podem ser diferentes e assim por diante. Cabe à camada de rede superar todos esses problemas, a fim de permitir que redes heterogêneas sejam interconectadas. Nas redes de broadcast, o problema de roteamento é simples e, assim, a camada de rede geralmente é estreita, ou mesmo inexistente. **A Camada De Transporte** A função básica da camada de transporte é aceitar dados da camada acima dela, dividi-los em unidades menores, se for preciso, repassar essas unidades à camada de rede e garantir que todos os fragmentos chegarão corretamente à outra extremidade. A camada de transporte também determina que tipo de serviço deve ser fornecido à camada de sessão e, por fim, aos usuários da rede. O tipo mais popular de conexão de transporte é um canal ponto a ponto livre de erros que entrega mensagens ou bytes na ordem em que eles foram enviados. O tipo de serviço é determinado quando a conexão é estabelecida. A camada de transporte é uma verdadeira camada de ponta a ponta, que liga origem ao destino. Em outras palavras, um programa na máquina de origem mantém uma conversação com um programa semelhante instalado na máquina destino, utilizando os cabeçalhos de mensagens e as mensagens de controle. A camada de transporte é uma verdadeira camada de ponta a ponta, que liga a origem ao destino. **A Camada De Sessão** A camada de sessão permite que os usuários em diferentes máquinas estabeleçam **sessões de comunicação** entre eles. Uma sessão oferece diversos serviços, inclusive o **controle de diálogo** (mantendo o controle de quem deve transmitir em cada momento), o **gerenciamento de tokens** (impedindo que duas partes tentem executar a mesma operação crítica ao mesmo tempo) e a **sincronização** (realizando a verificação periódica de longas transmissões para permitir que elas continuem a partir do ponto em que estavam ao ocorrer uma falha e a subsequente recuperação). **A Camada De Apresentação** A **camada de apresentação** está relacionada à sintaxe e à semântica das informações transmitidas. Para tornar possível a comunicação entre computadores com diferentes representações internas dos dados, as estruturas de dados a serem trocadas podem ser definidas de maneira abstrata, com uma codificação padrão que será usada durante a conexão. A camada de apresentação gerencia essas estruturas de dados abstratas e permite a definição e o intercâmbio de estruturas de dados de nível mais alto (por exemplo, registros bancários). **A Camada De Aplicação** A camada de aplicação contém uma série de protocolos comumente necessários para os usuários. Um protocolo de aplicação amplamente utilizado é o **HTTP (HyperText Transfer Protocol)**, que constitui a base da World Wide Web. Quando um navegador deseja uma página Web, ele envia o nome da página desejada ao servidor que hospeda a página, utilizando o HTTP. O servidor, então, transmite a página ao navegador. Outros protocolos de aplicação são usados para transferência de arquivos, correio eletrônico e transmissão de notícias pela rede. ##### O Modelo De Referência TCP/IP Modelo de referência usado na 'avó' de todas as redes de computadores a longa distância, a ARPANET, e sua sucessora, a Internet mundial. Essa arquitetura posteriormente ficou conhecida como **modelo de referência TCP/IP**, graças a seus dois principais protocolos. Uma rede de comutação de pacotes baseada em uma camada de interligação de redes com serviço não orientado a conexões, passando por diferentes topologias de redes. **A Camada De Enlace** A **camada de enlace**, a mais baixa no modelo, descreve o que os enlaces como linhas seriais e a Ethernet clássica precisam fazer para cumprir os requisitos dessa camada de interconexão com serviço não orientado a conexões. Ela não é uma camada propriamente dita, no sentido normal do termo, mas uma interface entre os hosts e os enlaces de transmissão. **A Camada Internet (Camada De Rede)** A **camada internet** integra toda a arquitetura, mantendo-a unida. Sua tarefa é permitir que os hosts injetem pacotes em qualquer rede e garantir que eles trafegarão independentemente até o destino (talvez em uma rede diferente). Eles podem chegar até mesmo em uma ordem diferente daquela em que foram enviados, obrigando as camadas superiores a reorganizá-los, caso a entrega em ordem seja desejável. A camada internet define um formato de pacote oficial e um protocolo chamado **IP (Internet Protocol)**, mais um protocolo que o acompanha, chamado ICMP (**Internet Control Message Protocol**). A tarefa da camada internet é entregar pacotes IP onde eles são necessários. **A Camada De Transporte** No modelo TCP/IP, a camada localizada acima da camada internet agora é chamada **camada de transporte.** A finalidade dessa camada é permitir que as entidades pares dos hosts de origem e de destino mantenham uma conversação. Dois protocolos de ponta a ponta foram definidos aqui. O primeiro deles, o protocolo de controle de transmissão, ou TCP (Transmission Control Protocol), é um protocolo orientado a conexões confiável que permite a entrega sem erros de um fluxo de bytes originário de uma determinada máquina em qualquer computador da internet. Esse protocolo fragmenta o fluxo de bytes de entrada em mensagens discretas e passa cada uma delas para a camada internet. No destino, o processo TCP receptor volta a montar as mensagens recebidas no fluxo de saída. O TCP também cuida do controle de fluxo, impedindo que um transmissor rápido sobrecarregue um receptor lento com um volume de mensagens maior do que ele pode manipular. O segundo protocolo nessa camada, o protocolo de datagrama do usuário, ou **UDP (User Datagram Protocol),** é um protocolo sem conexões, não confiável, para aplicações que não desejam a sequência ou o controle de fluxo do TCP, e que desejam oferecer seu próprio controle. Ele é muito usado para consultas isoladas, com solicitação e resposta, tipo cliente-servidor, e aplicações em que a entrega imediata é mais importante do que a entrega precisa, como na transmissão de voz ou vídeo. **A Camada De Aplicação** O modelo TCP/IP não tem as camadas de sessão ou de apresentação. Não foi percebida qualquer necessidade para elas. Ao invés disso, as aplicações simplesmente incluem quaisquer funções e apresentação que forem necessárias. Acima da camada de transporte, encontramos a **camada de aplicação.** Ela contém todos os protocolos de nível mais alto. Dentre eles estão o protocolo de terminal virtua (TELNET), o protocolo de transferência de arquivos (FTP) e o protocolo de correio eletrônico (SMTP). Muitos outros protocolos foram incluídos no decorrer dos anos. Alguns dos mais importantes, incluem o DNS (Domain Name Service), que mapeia os nomes de hosts para seus respectivos endereços da camada de rede (Internet), o HTTP, protocolo usado para buscar páginas na World Wide Web, e o RTP, protocolo para entregar mídia em tempo real, como voz ou vídeo. ![modelo](images/modelo_TCP_IP.PNG) #### Exemplos De Redes ##### A Internet A internet não é de modo algum uma rede, mas sim um vasto conjunto de redes diferentes que utilizam certos protocolos comuns e fornecem determinados serviços comuns. É um sistema incomum no sentido de não ter sido planejado nem ser controlado por ninguém. **A ARPANET** A história começa no final da década de 1950. No auge da Guerra Fria, o Departamento de Defesa dos Estados Unidos queria uma rede de controle e comando capaz de sobreviver a uma guerra nuclear. Nessa época, toda as comunicações militares passavam pela rede de telefonia pública, considerada vulnerável. Foi sugerido por <NAME>, a criação de uma sub-rede comutada por pacotes, dando a cada host seu próprio roteador. A sub-rede consistiria em minicomputadores chamados processadores de mensagens de interface, ou **IMPs(Interface Message Processors)**, conectados por linhas de transmissão de 56 kbps. Para garantir sua alta confiabilidade, cada IMP seria conectado a pelo menos dois outros IMPs. A sub-rede tinha de ser uma sub-rede de datagrama, de modo que, se algumas linhas e alguns IMPs fossem destruídos, as mensagens poderiam ser roteadas automaticamente para caminhos alternativos. Cada nó da rede deveria ter um IMP e um host na mesma sala, conectados por um fio curto. Um host poderia enviar mensagens de até 8.063 bits para seu IMP que, em seguida, dividiria essas mensagens em pacotes de no máximo 1.008 bits e os encaminharia de forma independente até o destino. Cada pacote era recebido por completo antes de ser encaminhado; assim, a sub-rede se tornou a primeira rede eletrônica de comutação de pacotes de store-and-forward (de armazenamento e encaminhamento). BBN, empresa que ficará encarregada da contrução da sub-rede. A BBN resolveu utilizar, como IMPs, minicomputadores Honeywell DDP-316 especialmente modificados, com 12k palavras de 16 bits de memória principal. Os IMPs não tinham unidades de discos, pois os componentes móveis eram considerados pouco confiáveis .Os IMPs eram interconectados por linhas privadas das companhias telefônicas, de 56 kbs. O software foi dividido em duas partes: sub-rede e host. O software da sub-rede consistia na extremidade IMP da conexão host-IMP, no protocolo IMP-IMP e em um protocolo do IMP de origem para o IMP de destino, criado para aumentar a confiabilidade. O TCP/IP foi criado especificamente para manipular a comunicação entre redes interligadas, algo que se tornou mais importante à medida que um número maior de redes era conectado à ARPANET. Os pesquisadores na University of California em Berkeley reescreveram o TCP/IP com uma nova interface de programação **(soquetes)** para o lançamento iminente da versão 4.2BSD do UNIX de Berkeley. Durante a década de 1980, novas redes, em particular as LANs, foram conectadas à ARPANET. À medida que a escala aumentou, tornou-se cada vez mais dispendioso localizar os hosts, e assim foi criado o sistema de nomes de domínio, ou **DNS** (**Domain Name System**), para organizar máquinas em domínios e relacionar nomes de hosts com endereços IP. Desde então, o DNS se transformou em um sistema generalizado de bancos de dados distribuídos, capaz de armazenar uma série de informações referentes à atribuição de nomes. **NSFNET** A National Science Foundation Network foi um programa de financiamento da internet, patrocinado pela National Science Foundation entre 1985 e 1995, para promover uma rede de educação e pesquisa nos Estados Unidos. Também é nome dos primeiros backbones existentes da internet. Para ter algo concreto com que começar, a NSF decidiu construir uma rede de backbone para conectar seus seis centros de supercomputadores. Cada supercomputador ganhou um irmão mais novo, um micro computador LSI-11, chamado **fuzzball**. Os fuzzballs estavam conectados a linhas privadas de 56 kbps e formavam a sub-rede, usando a mesma tecnologia de hardware da ARPANET. Porém, a tecnologia de software era diferente: os fuzzballs se comunicavam diretamente com o tcp/ip desde o início, criando, assim, a primeira WAN TCP/IP. Ela se conectava à ARPANET por meio de um link entre um IMP e um fuzzball na central de processamento de dados da Carnegie-Mellon. Para facilitar a transição e garantir que todas as redes regionais pudessem se comunicar entre si, a NSF contratou quatro diferentes operadoras de redes para estabelecer um ponto de acesso de rede, ou **NAP** (**Network Access Point**). A Internet mudou muito dessa época para cá. Seu tamanho explodiu com o surgimento da World Wide Web(WWW), no início da década de 1990. Dados recentes do Internet Systems Consortium indicam que o número de hosts visíveis na internet supera os 600 milhões(por baixo e ultrapassado já). A maneira como usamos a Internet também mudou radicalmente. No início, aplicações como e-mail para acadêmicos, grupos de notícias, login remoto e transferência de arquivos dominavam. Depois, ela passou a ser um e-mail para cada um, depois a Web e a distribuição de conteúdo peer-to-peer, como o Napster, hoje fora de operação. Atualmente, distribuição de mídia em tempo real, redes sociais e microblogging estão ganhando cada vez mais força. ### A subcamada de controle de acesso ao meio #### Protocolos de acesso múltiplo ##### ALOHA **ALOHA Original** A ideia básica de um sistema ALOHA é simples: permitir que os usuários transmitam sempre que tiverem dados para enviar. Naturalmente, haverá colisões, e os quadros que colidirem serão danificados. Os transmissores precisam, de alguma maneira, descobrir se isso acontece. No sistema ALOHA, após cada estação ter transmitido seu quadro para o computador central, este computador retransmite o quadro para todas as estações. Desse modo, uma estação transmissora pode escutar por broadcast a partir do hub para ver se seu quadro passou. Em outros sistemas, como nas LANs com fios, o transmissor precisa ser capaz de escutar colisões enquanto transmite. Se o quadro foi destruído, o transmissor apenas espera um período aleatório e o envia novamente. O tempo de espera deve ser aleatório, caso contrário os mesmos quadros continuarão a colidir repetidas vezes, de forma inflexível. Os sistemas em que vários usuários compartilham um canal comum de forma que possa gerar conflitos em geral são conhecidos como sistemas de **disputa**. Sempre que dois quadros tentarem ocupar o canal ao mesmo tempo, haverá uma colisão e ambos serão danificados. Se o primeiro bit de um novo quadro se sobrepuser apenas ao último bit de um quadro quase terminado, os dois quadros serão totalmente destruídos (ou seja, terão checksums incorretos) e terão de ser retransmitidos posteriormente. O checksum não consegue (e não deve) fazer distinção entre uma perda total e uma perda parcial. Quadro com erro é quadro com erro, sem distinções. ![aloha original](images/pure_aloha.PNG) **Slotted ALOHA** Logo depois que o ALOHA entrou em cena, Roberts(1972) publicou um método para duplicar a capacidade de um sistema ALOHA. Sua proposta era dividir o tempo em intervalos discretos, chamados **slots**, com cada intervalo correspondendo a um quadro. Esse método exige que os usuários concordem em relação às fronteiras dos slots. Uma forma de alcançar a sincronização entre os usuários seria ter uma estação especial que emitisse um sinal sonoro no início de cada intervalo, como um relógio. Em contraste com o ALOHA original de Abramson, um computador não tem permissão para transmitir sempre que o usuário digita uma linha. Em vez disso, é necessário esperar o início do próximo slot. Consequentemente, o ALOHA original contínuo transforma-se em um sistema discreto. O período de vulnerabilidade está agora reduzido à metade. ![slotted aloha](images/slotted_aloha.PNG) **Slotted ALOHA** Vulnerable Time = Frame Transmission time. Throughput = G x e^-G; Where G is the number of stations wish to transmit in the same time. Maximum throughput = 0.368 for G=1. O slotted ALOHA é importante por uma razão que, em princípio, talvez não seja óbvia. Ele foi criado na década de 70, foi usado em alguns sistemas experimentais e depois foi quase esquecido. Quando foi criado o acesso a Internet por cabo, surgiu o problema de como alocar um canal compartilhado entre vários usuários concorrentes, e o slotted ALOHA foi resgatado para salvar a situação. ## Curiosidades: * ##### Napster foi o programa de compartilhamento de arquivos em rede P2P criado em 1999, que protagonizou o primeiro grande episódio na luta jurídica entre a indústria fonográfica e as redes de compartilhamento de música na internet. * ##### Talk do UNIX troca de mensagens instantâneas. Esses recurso, derivado do programa talk do UNIX, em uso desde aproximadamente 1970. * ##### Comércio eletrônico ![abreviacao](images/abreviacoes.PNG) * #### DCS1000 (Carnivore) Carnivore foi um sistema implementado pelo Federal Bureau of investigation - FBI, projetado para monitorar as comunicações de e-mail e eletrônicos. É utilizado um packet siniffer personalizável que pode monitorar todo o tráfego de um usuário da internet. * #### Phishing é o crime de enganar as pessoas para que compartilhem informações confidenciais como senhas e número de cartões de crédito. Como uma verdadeira pescaria, há mais de uma maneira fisgar uma vítima, mas uma tática de phishing é a mais comum. * #### <NAME> 'Não há nenhuma razão para qualquer indivíduo ter um computador em casa'. * A palavra **modem** é uma construção de 'modulador-demodulador' e refere-se a qualquer dispositivo que faz a conversão entre bits digitais e sinais analógicos. * O acesso à Internet em velocidades muito maiores que as discadas é chamado de **banda larga (broadband).** <file_sep>/CP/Tarefas/Tarefa04/notes.md # OpenMP Multiplicação de matriz utiliza-se de duplo for, para paralizar isto teremos que entender da diretiva que eu escreverei logo abaixo: ## Collapse One directive i required for each nested loop. This tends to be cumbersome especially if multiple nested loops are to be treated in the same way. The **collapse clause** comes in handy in such a case. The argument to the collapse clause is a constant positive integer, which specifies how many tightly nested loops are associated with the loop construct. Consequently, you can describe the scheduling of the iterations of these loops using a single loop construct according to the rest of its clases(ohter than the collapse). <file_sep>/CP/Tarefas/Projeto01/mlp/choro.cpp #include <stdio.h> #include <stdlib.h> #include <stdio.h> #include <cmath> #include <time.h> int main() { FILE *pFile; pFile = fopen("entrada.txt", "w"); FILE *fileSaida; fileSaida = fopen("saida.txt","w"); int numeros[2][1000]; srand(time(NULL)); for (int i = 1; i <= 1000; i ++) { numeros[0][i] = rand()%1000; numeros[1][i] = rand()%1000;; } for (int i = 1; i <= 1000; i ++) { int sum = numeros[0][i] + numeros[1][i]; fprintf(pFile,"%d %d\n",numeros[0][i],numeros[1][i]); fprintf(fileSaida,"%d\n",sum); } fclose(pFile); return 0; }<file_sep>/PAA/tarefas/Tarefa 02/unificacaoLista.cpp #include <stdlib.h> struct Celula { Celula* prox; Celula* ant; int elemento; }; class Lista{ public: Celula* primeiro; Lista(){ primeiro = (Celula *)malloc(sizeof(Celula)); primeiro->prox = NULL; primeiro->ant = NULL; } int remove(int position){ } void inserir(int position, int valor){ } void inserirFinal(int valor){ } }; void unificacaoLista(int tamLista, Lista lista){ int a, b; for(int i = 0; i < (tamLista-1); i++){ a = lista.remove(1); b = lista.remove(2); int valor = a+b; bool menor = true; bool inserido = false; Celula* count = lista.primeiro; //celula int count2 = 0; // position while(menor && count !=NULL){ if(count->elemento > valor ){ menor = false; lista.inserir(count2, valor); inserido = true; } count2++; } if(!inserido){ lista.inserirFinal(valor); } } } int main(){ }<file_sep>/README.md # PUC Onde postarei materiais que eu produzi relacionados a faculdade <file_sep>/CP/Material de Estudo/virtual-notas-aula.md # Computação Paralela ## Padrões de Programação Paralela ### Programação Estruturada * A "programação estruturada" (sequencial) é composta pelos seguintes Padrões * Estruturas de Seleção e Repetição * Funções, Recursão etc. * Estas boas práticas de programação eliminam problemas como o GOTO * Melhora a manutenabilidade do software. * Aumenta o reuso de software. * Problema: Serialização ### Serialização * **Abstração de uma máquina sequencial.** * Possui ordem temporal. * É determinística. * Fácil de codificar, depurar e testar. * **Limita o paralelismo sem necessidade.** * Paralelismo não é determinístico. ### Quebrando a Serialização Por padrão o for por exemplo, ele força uma serialização no nosso código, ou seja, uma ordem a ser executada. Mas em muitos casos não necessariamente essas ações de um mesmo laço necessita de vir em uma ordem não há dependência de dados entre as camadas de um mesmo for. * #### Que tal um for sem serialização? ![](images/parallel_for.png) * **Agora lê-se:** A "palavra" pode ser buscada em todas as páginas "i" ao mesmo tempo, ou seja, em paralelo. ### Programação Paralela Estruturada * **A "programação paralela estruturada" é composta por padrões paralelos ou esqueletos algoritmicos ou paralelos.** * Fork-Join, Map, Reduce, Scan, Stencil etc. * **Estes padrões paralelos capturam estruturas comuns a programas paralelos.** * Elimina o uso explícito de threads. * Remove(relaxa) as restrições de serialização dos padrões sequenciais. #### Fork-Join * **É o padrão paralelo mais simples.** * **Permite que uma mesma seção de código seja executada em paralelo por várias threads trabalhadoras.** * **Uma thread mestre dispara(fork) várias threads trabalhadoras e ao final da execução de cada thread, elas sincronizam-se, restando apenas a thread mestre(join).** #### Map * **O padrão Map replica uma função sobre cada elemento de um conjunto de índices(ou dados diferentes).** * **Ele é mais comumente encontrado na forma de uma estrutura de repetição sem a restrição de ordem de execução das iterações.** * É necessário que as funções(iterações) sejam independentes. #### Reduce * **O padrão Reduce combina cada elemento de uma coleção, geralmente em pares, utilizando um operador, até reduzi-los a um único elemento.** * **Exemplos** * Realizar somatório de inteiros. #### Stencil * **O padrão Stencil é uma generalização do MAP, onde cada função acessa não somente um único elemento, mas também seus vizinhos.** * Condições de borda precisam ser checadas. * **Exemplos** * Convolução de imagens * Detecção de quinas * Simulação de nuvens #### Scan * **O padrão Scan computa todas as reduções parciais de uma coleção de elementos, ou seja, para cada saída, uma redução parcial é computada até o elemento atual.** * **Exemplo** * Somatório parciais ![somatorio_parcial](images/somatorio_parcial.png) * ** ## Semântica e implementação * **Semântica** * O que o padrão faz? * É apenas a funcionalidade do padrão (visão de fora). * **Implementação** * Como o padrão executa na prática? * Várias implementações são possíveis. * Visão de dentro do padrão. ## Suporte aos Padrões pelos Modelos de Programação * **Open Multi-processing (OpenMP)** * Fork-Join, Map e Reduce * **Compute Unified Device Architecture(CUDA) Open Computing Language(OpenCL)** * Map * **Intel Thread Building Blocks (TBB)** * Fork-Join, Map, Reduction, Pipeline, Scan e outros * **Message Passing Interface (MPI)** * Map, Gather, Scatter, Reduce e outros ## Padrão REDUCE em OpenMP * **Shared** - a variavel declarada como shared, ela terá apenas uma única cópia dessa mesma variavel para todas as threads que tivermos. E variaveis declaradas fora do laço serão declaradas por default como shared. * **Critical** - Diretiva que garante atomicidade em um área de código de sua paralelização. <file_sep>/CP/Material de Estudo/estudo03.md # Arquiteturas Paralelas * Leia a seção "2.4 Machine Models" do livro texto, para entender um pouco mais sobre os modelos de máquinas paralelas, hierarquia de memória e desempenho. ## *2.4* MACHINE MODELS To write efficiente programs, it is important to have a clear mental model of the organization of the hardware resources being used. ![multicore](images/multicore_processor.png) This is a sketch of a typical **multicore processor**. Inside every **core** there are multiple functional units, each such funcional unit being able to do a single arithmetic operation. ### Instruction parallelism Since cores usually have multiple functional units, multiple arithmetic operationms can often be performed in parallel, even in a single core. Parallel use of multiple functional units in a single core can be done either implicitly, by a **superscalar execution of serial instructions, hardware multithreading, or bu explicit vector instructions. A **superscalar processor** analyzes an instruction stream and executes multiple instructions in parallel as long as they do not depend on each other. Vector instructions enable explicit use of multiple functional units at once by specifying an operation on a small collection of data elements. <file_sep>/CP/Tarefas/Tarefa15/Bubble Sort/bubble_sort.c #include <stdio.h> #include <stdlib.h> int array [100000]; void bubble_sort(){ int n = sizeof(array)/sizeof(array[0]); int aux; for (int i = 0; i < n-1; i++) { #pragma omp parallel for schedule(dynamic, 1000) shared (n, array) private(aux) for (int j = 0; j < (n/2); j++) { if (array[2*j] > array[2*j + 1]) { aux = array[2*j]; array[2*j] = array[2*j + 1]; array[2*j + 1] = aux; } } #pragma omp parallel for schedule(dynamic, 100) shared (n, array) private(aux) for (int j = 0; j < (n/2)-1; j++) { if (array[2*j + 1] > array[2*j + 2]) { aux = array[2*j + 1]; array[2*j + 1] = array[2*j + 2]; array[2*j + 2] = aux; } } } } void fill_array(){ int n = sizeof(array)/sizeof(array[0]); for(int i = 0; i < n; i++){ array[i] = n - i; // array decrescente } } void print_array(){ int n = sizeof(array)/sizeof(array[0]); for(int i = 0; i < n; i++){ printf("%d ", array[i]); } } int main(){ fill_array(); bubble_sort(); print_array(); return 0; } <file_sep>/CP/Tarefas/Projeto01/mlp/back.cpp /********************************************************************** * Algoritmo de treinamento back-propagation para redes multicamadas **********************************************************************/ /************************* BIBLIOTECAS *******************************/ #include <iostream> #include <stdlib.h> #include <stdio.h> #include <cmath> #include <time.h> #include <omp.h> using namespace std; /************************* DEFINICOES ********************************/ #define MAXCAM 5 // N�mero m�ximo de camadas #define MAXNEU 100 // N�mero m�ximo de neur�nios #define MAXPES 100 // N�mero m�ximo de pesos #define MAXLIN 100 // N�mero m�ximo de linhas #define MAXCOL 20 // N�mero m�ximo de colunas #define NUMLIN 26 // N�mero de Linhas da Matriz de Entrada #define NUMCOLENT 8// N�mero de Colunas da Matriz de Entrada #define NUMCOLSAI 5 // N�mero de Colunas de Saida #define NUMITE 1 // Numero de Iteracoes #define ESC 27 #define MI 0.6 #define TOLERANCIA 0.00001 // N�mero de erros consecutivos double BETA = MI; // Fator de ajuste das correcoes int random(int n) { return rand() % n; } /************************* CLASSES **********************************/ /*********************** CLASSE NEURONIO ****************************/ class Neuronio { private: int Numero_Pesos; // N�mero de pesos do neur�nio double W[MAXPES]; // Vetor de pesos public: void Inicializar_Neuronio(int Numero_Pesos); // Inicia os valores dos pesos void Ajustar_Peso(double Entrada, double Erro, int Indice_Peso); // Ajusta os valores dos pesos double Somatorio(double Entrada[]); // Retorna os pesos e quantos s�o double Erro_Peso(double Erro, int Indice_Peso); }; /********************************************************* Inicializa o N�mero de Pesos e tamb�m os valores iniciais dos pesos *********************************************************/ void Neuronio ::Inicializar_Neuronio(int Numero_Pesos) { int i; this->Numero_Pesos = Numero_Pesos; for (i = 0; i < Numero_Pesos; i++) W[i] = (double)(rand()%11 / 10.0) * (random(3) - 1.0); } /********************************************************* Multilica o Erro da sa�da de um neur�nio por um Peso de Indice_Peso *********************************************************/ double Neuronio ::Erro_Peso(double Erro, int Indice_Peso) { return (Erro * W[Indice_Peso]); } /********************************************************* Dada uma entrada, retorna a sa�da do neur�nio multiplicando-a pelos pesos *********************************************************/ double Neuronio ::Somatorio(double Entrada[]) { int i; double Som = 0; #pragma omp paralle for reduction(+:Som) for (i = 0; i < Numero_Pesos; i++) Som += Entrada[i] * W[i]; return Som; } /********************************************************* Dado o erro da camada da frente, a sa�da do neur�nio, e Indice do Peso, calcula-se o novo peso *********************************************************/ void Neuronio ::Ajustar_Peso(double Entrada, double Erro, int Indice_Peso) { W[Indice_Peso] += BETA * Erro * Entrada; } /*********************** CLASSE CAMADA ****************************/ class Camada { private: int Numero_Neuronios; // N�mero de neur�nios na camada int Numero_Pesos; double Saida[MAXNEU]; // Sa�da dos neur�nios da camada Neuronio N[MAXNEU]; // Neur�nios da camada public: void Inicializar_Camada(int Numero_Neuronios, int Numero_Pesos); // Atribui o n�mero de neur�nios void Treinar_Neuronios(double Entrada[]); // Treina os neur�nios com uma entrada void Funcao_Ativacao(); // Joga sa�da linear na funcao de ativacao void Retornar_Saida(double Linha[]); // Retorna a sa�da dos neur�nios void Ajustar_Pesos_Neuronios(double Erros[], double Entrada[]); void Calcular_Erro_Camada_Saida(double Erros[], double Y[]); void Calcular_Erro_Camada(double Erros[]); double Somatorio_Erro(double Erros[]); void Calcular_Erro_Final(double Erros[], double Y[]); }; /********************************************************* Inicializa o Numero de Neuronios e o Numero de Pesos e invoca a inicializa��o dos neur�nios *********************************************************/ void Camada ::Inicializar_Camada(int Numero_Neuronios, int Numero_Pesos) { int i; this->Numero_Neuronios = Numero_Neuronios; this->Numero_Pesos = Numero_Pesos; for (i = 0; i < Numero_Neuronios; i++) N[i].Inicializar_Neuronio(Numero_Pesos); } /********************************************************* Calcula os erros da camada de sa�da com base na sa�da desejada Y, retornando os erros *********************************************************/ void Camada ::Calcular_Erro_Final(double Erros[], double Y[]) { int i; for (i = 0; i < Numero_Neuronios; i++) Erros[i] = (Y[i] - Saida[i]); } /********************************************************* Dispara o somat�rio de um neur�nio para uma certa entrada armazenando a sua sa�da *********************************************************/ void Camada ::Treinar_Neuronios(double Entrada[]) { int i; for (i = 0; i < Numero_Neuronios; i++) Saida[i] = N[i].Somatorio(Entrada); } /********************************************************* Calcula os erros da camada de sa�da com base na sa�da desejada Y, retornando os erros *********************************************************/ void Camada ::Calcular_Erro_Camada_Saida(double Erros[], double Y[]) { int i; for (i = 0; i < Numero_Neuronios; i++) Erros[i] = (Y[i] - Saida[i]) * Saida[i] * (1 - Saida[i]); } /********************************************************* Calcula os erros da camada escondida com base no erro da camada da frente, retornando os erros *********************************************************/ void Camada ::Calcular_Erro_Camada(double Erros[]) { int i; for (i = 0; i < Numero_Neuronios; i++) Erros[i] = Saida[i] * (1 - Saida[i]) * Erros[i]; } /********************************************************* Ajusta os pesos dos neur�nios da camada de acordo com os erros da camada da frente, e retorna o som�r�rio de erros da pr�pria camada *********************************************************/ void Camada ::Ajustar_Pesos_Neuronios(double Erros[], double Entrada[]) { int i, j; double Temp, Erro_Aux[MAXNEU]; /* C�lculo do Somat�rio que ser� usado para o c�lculo do erro da camada anterior */ //#pragma omp parallel for schedule(dynamic, 100) for (i = 1; i < Numero_Pesos; i++) { Temp = 0; for (j = 0; j < Numero_Neuronios; j++) { Temp += N[j].Erro_Peso(Erros[j], i); } Erro_Aux[i - 1] = Temp; } /* Ajusta os pesos de cada neur�nio de acordo com o erro da camada da frente e a sa�da da pr�pria camada */ for (i = 0; i < Numero_Neuronios; i++) for (j = 0; j < Numero_Pesos; j++) N[i].Ajustar_Peso(Entrada[j], Erros[i], j); /* Atribui o vetor de erros calculado, para o vetor erro que ser� retornado */ for (i = 0; i < (Numero_Pesos - 1); i++) Erros[i] = Erro_Aux[i]; } /********************************************************* Atualiza a sa�da da camada passando-a por uma fun��o de ativa��o *********************************************************/ void Camada ::Funcao_Ativacao() { int i; for (i = 0; i < Numero_Neuronios; i++) Saida[i] = 1 / (1 + exp(-Saida[i])); } /********************************************************* Retorna a Sa�da da Camada *********************************************************/ void Camada ::Retornar_Saida(double Linha[]) { int i; Linha[0] = 1; for (i = 1; i <= Numero_Neuronios; i++) Linha[i] = Saida[i - 1]; } /*********************** CLASSE REDE ******************************/ class Rede { private: int Numero_Camadas; // N�mero de camadas da rede int Numero_Linhas; // N�mero de linhas de entrada int Numero_Colunas_Entrada; // N�mero de colunas de entrada int Numero_Colunas_Saida; // N�mero de colunas da sa�da Camada C[MAXCAM]; // Camadas da rede double X[MAXLIN][MAXCOL]; // Matriz de entrada da rede double Y[MAXLIN][MAXCOL]; // Matriz de sa�da da rede public: void Inicializar_Rede(int, int, int, int, int Numero_Neuronio_Camada[]); // Inicializa os valores das vari�veis void Treinar(); // Treina toda a rede void Calcular_Resultado(double Entrada[], double Saida[]); }; /********************************************************* Inicializa todas as vari�veis da rede, inclusive a leitura das entradas e sa�das da rede *********************************************************/ void Rede ::Inicializar_Rede(int Numero_Camadas, int Numero_Linhas, int Numero_Colunas_Entrada, int Numero_Colunas_Saida, int Numero_Neuronio_Camada[]) { int i, j; FILE *Entrada, *Saida; this->Numero_Camadas = Numero_Camadas; this->Numero_Linhas = Numero_Linhas; this->Numero_Colunas_Entrada = Numero_Colunas_Entrada; this->Numero_Colunas_Saida = Numero_Colunas_Saida; Entrada = fopen("X-text.txt", "r"); Saida = fopen("Y-text.txt", "r"); for (i = 0; i < Numero_Linhas; i++){ for (j = 0; j < Numero_Colunas_Entrada; j++){ fscanf(Entrada, "%lf", &X[i][j]); //fread(&X[i][j], sizeof(double), 1, Entrada); //cout<<X[i][j]<<" "; } //cout<<endl; } for (i = 0; i < Numero_Linhas; i++){ for (j = 0; j < Numero_Colunas_Saida; j++){ fscanf(Saida, "%lf", &Y[i][j]); //fread(&Y[i][j], sizeof(double), 1, Saida); //cout<<Y[i][j]<<" "; } //cout<<endl; } fclose(Entrada); fclose(Saida); C[0].Inicializar_Camada(Numero_Neuronio_Camada[0], Numero_Colunas_Entrada); for (i = 1; i < Numero_Camadas; i++) C[i].Inicializar_Camada(Numero_Neuronio_Camada[i], (Numero_Neuronio_Camada[i - 1] + 1)); } /********************************************************* Calcula a resposta da rede para uma certa entrada, retornando a sa�da *********************************************************/ void Rede ::Calcular_Resultado(double Entrada[], double Saida[]) { int i, j; for (i = 0; i < Numero_Camadas; i++) { C[i].Treinar_Neuronios(Entrada); C[i].Funcao_Ativacao(); C[i].Retornar_Saida(Saida); for (j = 0; j < MAXNEU; j++) Entrada[j] = Saida[j]; } } /********************************************************* Algoritmmo de Treinamento Back Propagation *********************************************************/ void Rede ::Treinar() { int i, j, Linha_Escolhida, Iteracoes, Camada_Saida, Marcados[MAXLIN]; double Vetor_Saida[MAXNEU], Erros[MAXNEU], Somatorio_Erro, Maior; long Contador, Dinamico; char Sair; /* Inicializando vari�veis */ for (i = 0; i < MAXLIN; i++) Marcados[i] = 0; Dinamico = 0; Sair = 0; Contador = 0; Maior = 1; Iteracoes = 0; Camada_Saida = Numero_Camadas - 1; do { Linha_Escolhida = random(NUMLIN); j = 0; while (Marcados[Linha_Escolhida] == 1) { Linha_Escolhida++; j++; if (Linha_Escolhida == NUMLIN) Linha_Escolhida = 0; if (j == NUMLIN){ for (i = 0; i < MAXLIN; i++) Marcados[i] = 0; } } Marcados[Linha_Escolhida] = 1; Contador++; // FEED-FORWARD C[0].Treinar_Neuronios(X[Linha_Escolhida]); C[0].Funcao_Ativacao(); C[0].Retornar_Saida(Vetor_Saida); for (i = 1; i < Numero_Camadas; i++) { C[i].Treinar_Neuronios(Vetor_Saida); C[i].Funcao_Ativacao(); C[i].Retornar_Saida(Vetor_Saida); } // BACK-PROPAGATION /* Ajustando pesos da camada de sa�da */ C[Camada_Saida].Calcular_Erro_Camada_Saida(Erros, Y[Linha_Escolhida]); C[Camada_Saida - 1].Retornar_Saida(Vetor_Saida); C[Camada_Saida].Ajustar_Pesos_Neuronios(Erros, Vetor_Saida); /* Ajustando pesos das camadas intermedi�rias */ for (i = Camada_Saida - 1; i > 0; i--) { C[i].Calcular_Erro_Camada(Erros); C[i - 1].Retornar_Saida(Vetor_Saida); C[i].Ajustar_Pesos_Neuronios(Erros, X[Linha_Escolhida]); } /* Ajustando pesos da primeira camada */ C[0].Calcular_Erro_Camada(Erros); C[0].Ajustar_Pesos_Neuronios(Erros, X[Linha_Escolhida]); /* Calculando o erro global */ C[Camada_Saida].Calcular_Erro_Final(Erros, Y[Linha_Escolhida]); Somatorio_Erro = 0; for (i = 0; i < Numero_Colunas_Saida; i++) Somatorio_Erro += pow(Erros[i], 2); Somatorio_Erro /= 2; /* Verificando condi��es */ if (Somatorio_Erro < Maior) { Dinamico = 0; //cout << "\n\nErro = " << Somatorio_Erro << " "; Maior = Somatorio_Erro; } else Dinamico++; if (Somatorio_Erro <= TOLERANCIA) Iteracoes++; else Iteracoes = 0; /* Beta din�mico */ if (Dinamico == 200000) { Dinamico = 0; BETA += (random(6) / 10.0) * (random(3) - 1); } if (Dinamico == 50000) BETA = MI; /* Exibi��o na tela */ if (Contador % 10000 == 0) { //cout << "\nIteracoes = " << Contador; //cout << "\n\nBeta = " << BETA << " "; } /* Op��o de escape */ // if(Contador%10000000 == 0) // Sair = (char)getch(); } while (Iteracoes < NUMITE); } /****************** PROGRAMA PRINCIPAL *****************************/ int main() { srand(time(NULL)); int Numero_Camadas; // N�mero de camadas da rede int Numero_Linhas; // N�mero de linhas de entrada int Numero_Colunas_Entrada; // N�mero de colunas de entrada int Numero_Colunas_Saida; // N�mero de colunas da sa�da int Numero_Neuronio_Camada[MAXCAM]; int i; double Entrada[MAXNEU]; double Saida[MAXNEU]; char Continua = 'r'; Rede R; Numero_Linhas = NUMLIN; Numero_Colunas_Entrada = NUMCOLENT; Numero_Colunas_Saida = NUMCOLSAI; while (Continua != 'n') { if (Continua == 'r') { cout << "\n\nDigite o numero de camadas: "; cin >> Numero_Camadas; for (i = 0; i < Numero_Camadas; i++) { cout << "\n\nDigite o numero de neuronios da camada " << i << " : "; cin >> Numero_Neuronio_Camada[i]; } double start = omp_get_wtime(); R.Inicializar_Rede(Numero_Camadas, Numero_Linhas, Numero_Colunas_Entrada, Numero_Colunas_Saida, Numero_Neuronio_Camada); double end = omp_get_wtime(); printf("\nTime Inicializar Rede= %f", end - start); start = omp_get_wtime(); R.Treinar(); end = omp_get_wtime(); printf("\nTime Treinar Rede= %f", end - start); } cout << "\n\nDigite as entradas da rede:\n"; for (i = 0; i < Numero_Colunas_Entrada; i++) { cout << "\nEntrada " << i << " : "; cin >> Entrada[i]; } R.Calcular_Resultado(Entrada, Saida); for (i = 1; i <= Numero_Colunas_Saida; i++) { cout << "\nSaida " << i << " : " << Saida[i]; } cout << "\n\nContinua ? (s/n/r)"; cin >> Continua; } return 0; } <file_sep>/CP/Material de Estudo/estudo02.md # Padrões de Programação Paralela * Leia as seções 1.4, 3.3.1 e 3.3.2 do livro texto para entender um pouco mais sobre padrões de programação paralela (esqueletos paralelos), e especificamente os padrões FORK-JOIN e MAP. # Introdução ao OpenMP * Tutorial no Eitas!: [Introdução a Programação Paralela com OpenMP](http://www.eitas.com.br/tutorial/12/26) * ** ## 2.1 STRUCTURED PATTERN-BASED PROGRAMMING Algorithm strategy patterns have two parts: semantics and implementation. Three patterns deserve special mention: **nesting, map,** and **for-join.** **Nesting** means that patterns can be hierarchically composed. This is important for modular programming. The **map** pattern divides a problem into a number of uniform parts and represents a regular parallelization. This is also known as **embarrassing parallelism.** The map pattern is worth using whenever possible since it allows for both efficient parallelization and efficient vectorization. The **fork-join** pattern recursively subdivides a problem into subparts and can be used for both regular and irregular parallelization. It is useful for implementating a **divide-and-conquer** strategy. In summary, patterns provide a common vocabulary for discussing approaches to problem solving and allow reuse of best practices. Patterns transcend languages, programming models, and even computer architectures, and you can use patterns whether or not the programming system you are using explicitly supports a given pattern with a specific feature. ![patterns](images/parallel_patterns.png) ## 3.3.1 Fork-Join Fork-join should not be confused with **barriers**. A barrier is a synchronization construct across multiple threads. In a barrier, each thread must wait for all other threads to reach the barrier before any of them leave. The difference is that after a barrier all threads continue, but after a join only one does. Sometimes barriers are used to imitate joins, by making all threads execute identical code after the barrier, until the next conceptual fork. ## 3.3.2 Map The **map** pattern replicates a function over every element of an index set. The index set may be abstract or associated with the elements of a collection. The function being replicated is called an **elemental function** since it applies to the elements of an actual collection of input data. The map pattern replaces one specific usage of iteration in serial programs: a loop in which every iteration is independent, in which the number of iterations is known is advance, and in which every computation depends only on the iteration count and data read using the iteration count as an index into a collection. This form of loop is often used, like map, for processing every element of a collection with an independent operation. The elemental function must be pure(that is, whithout side-effects) in order for the map to be implementable in parallel while achieving deterministic results. In particular, elemental funcions must not modify global data that other instances of that function depend on. <file_sep>/CP/Tarefas/Tarefa20/Tarefa20.c /* aumentei entrada para 90000 Sequencial: real 0m16.953s user 0m16.885s sys 0m0.012s Parallel: real 0m14.997s user 0m26.395s sys 0m0.020s Parallel_GPU: real 0m2.261s user 0m1.086s sys 0m1.090s speedup do Parallel_GPU em relação ao Parallel: 6,632 */ #include <stdio.h> #include <stdlib.h> int main() { int i, j, n = 90000; // Allocate input, output and position arrays int *in = (int*) calloc(n, sizeof(int)); int *pos = (int*) calloc(n, sizeof(int)); int *out = (int*) calloc(n, sizeof(int)); // Initialize input array in the reverse order for(i=0; i < n; i++) in[i] = n-i; // Print input array // for(i=0; i < n; i++) // printf("%d ",in[i]); // Silly sort (you have to make this code parallel) #pragma omp target map(tofrom:in[:n], pos[:n]) #pragma omp teams distribute parallel for simd for(i=0; i < n; i++) for(j=0; j < n; j++) if(in[i] > in[j]) pos[i]++; // Move elements to final position for(i=0; i < n; i++) out[pos[i]] = in[i]; // print output array // for(i=0; i < n; i++) // printf("%d ",out[i]); // Check if answer is correct for(i=0; i < n; i++) if(i+1 != out[i]) { printf("test failed\n"); exit(0); } printf("test passed\n"); } <file_sep>/CP/Tarefas/Tarefa09/Tarefa09.c /* Sequencial: real 0m16.953s user 0m16.885s sys 0m0.012s Parallel: real 0m3.471s user 0m6.353s sys 0m0.020s Parallel_Schedule: real 0m3.266s user 0m6.372s sys 0m0.096s speedup(média de 5 execuções):4.676/3.338 = 1,4008 */ #include <stdio.h> #include <stdlib.h> int main() { int i, j, n = 80000; // Allocate input, output and position arrays int *in = (int*) calloc(n, sizeof(int)); int *pos = (int*) calloc(n, sizeof(int)); int *out = (int*) calloc(n, sizeof(int)); // Initialize input array in the reverse order for(i=0; i < n; i++) in[i] = n-i; // Print input array // for(i=0; i < n; i++) // printf("%d ",in[i]); // Silly sort (you have to make this code parallel) #pragma omp parallel for private(i,j) schedule(dynamic, 100) num_threads(2) for(i=0; i < n; i++) for(j=0; j < n; j++) if(in[i] > in[j]) pos[i]++; // Move elements to final position for(i=0; i < n; i++) out[pos[i]] = in[i]; // print output array // for(i=0; i < n; i++) // printf("%d ",out[i]); // Check if answer is correct for(i=0; i < n; i++) if(i+1 != out[i]) { printf("test failed\n"); exit(0); } printf("test passed\n"); } <file_sep>/CP/Tarefas/Tarefa19/devec.c #include <stdio.h> #include <stdlib.h> #include <math.h> int main (void) { // 1 //devec.c:4:5: note: not vectorized: not enough data-refs in basic block. //Número de interações baixa /* int a [4] = {1,2,3,4}; int b [4] = {1,2,3,4}; int c [4] = {1,2,3,4}; for (int i = 0; i <sizeof(a)/sizeof(a[0]); i++) { a [i] = b[i] + c[i]; } */ //2 // O programa possui um break. // devec.c:26:3: note: not vectorized: loop contains function calls or data references that cannot be analyzed /* int n = 1000000000; int a[1000000000]; int b[1000000000]; int c[1000000000]; for (int i = 0; i < n;i++) { a[i] = rand()%1000; b[i] = rand()%1000; c[i] = rand()%1000; } for (int j = 0; j < n; j++) { a [j] = b[j] + c[j]; if (a[j] == 100000000){ break; } } */ /* 3- Dependência na variável result. devec.c:47:3: note: not vectorized: loop contains function calls or data references that cannot be analyzed devec.c:47:3: note: bad data references. */ /* int n = 1000000000; int a[n]; int b[n]; int result = 0; for (int i = 0; i < n;i++) { a[i] = rand()%1000; b[i] = rand()%1000; } for (int j = 1; j < n; j++) { result = result + a[j] * b[j]; } */ /* 4- // diferentes fluxo de controle pelo if aleatoriamente ficar alternando // entre ele e o else. devec.c:83:3: missed: not vectorized: control flow in loop. */ int n = 1000000000; int a[n]; int b[n]; for (int i=0; i< n; i++) { a[i] = rand()%1000; b[i] = rand()%1000; } for (int j = 1; j < n; j++) { float random = b[j]*b[j] - 2*a[j]*b[j]; if(random >= 0){ random = sqrt(random); a[j-1] = a[j] +1*random; b[j] = a[j] * 2/random; } else{ a[j] = 0; b[j] = 0; } } /* 5- Conversão de tipos. note: not vectorized: not enough data-refs in basic block. */ /* long long num = 1000000000; double passo; passo = 1.0/(double)num; */ return 0; }
2b8bb5fcc6ee28eeacca98b7982d2a0162acbd7c
[ "Markdown", "C", "C++" ]
18
Markdown
buluf/PUC
43aa97ef0469dc6a138607f5f3089d4389433d0e
bde399ba26499cd73fedf97d0164223b0cfdce17
refs/heads/master
<repo_name>GriwMF/spree_avatax_certified<file_sep>/Gemfile source 'http://rubygems.org' gem "spree", ">= 3.1.0", "< 4.0" gem "codeclimate-test-reporter", group: :test, require: nil gem 'pry' gemspec
f59f1416ba5fbb75674254e54be698d09b77fd72
[ "Ruby" ]
1
Ruby
GriwMF/spree_avatax_certified
2afb0911df119165d3f62bfbf086828aedc79cfa
774b5b66eb1a95b05fa7fe9722e18f47a4728062
refs/heads/master
<repo_name>himkt/hanyu<file_sep>/main.py # -*- coding: utf-8 -*- from hanyu import Hanyu import re hanyu = Hanyu() hanyu.watch() # for msg in hanyu.watch(): # # if 'retweeted_status' not in msg: # # if 'text' in msg: # screen_name = msg['user']['screen_name'] # if screen_name != hanyu.SCREEN_NAME: # if hanyu.SCREEN_NAME in msg['text']: # tweet_id = msg['id'] # search = re.search( # ("@%s (.*)って(何|なに)" % hanyu.SCREEN_NAME), msg['text']) # # if search: # hanyu.answer(tweet_id, screen_name, search.group(1)) # # else: # hanyu.reply(tweet_id, screen_name, "hey!") <file_sep>/account.py # -*- coding: utf-8 -*- from yaml import load from twitter import Twitter, TwitterStream, OAuth def rest_config(): config = load(open("config/account.yaml")) return Twitter(auth = OAuth( config["ACCESS_TOKEN"], config["ACCESS_TOKEN_SECRET"], config["CONSUMER_KEY"], config["CONSUMER_KEY_SECRET"] )) def stream_config(): config = load(open("config/account.yaml")) return TwitterStream(auth = OAuth( config["ACCESS_TOKEN"], config["ACCESS_TOKEN_SECRET"], config["CONSUMER_KEY"], config["CONSUMER_KEY_SECRET"] ), domain='userstream.twitter.com' ) <file_sep>/model.py # coding=utf-8 from sqlalchemy import Column, String, Integer, ForeignKey, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base class Logic(declarative_base()): __tablename__ = 'logics' id = Column(Integer, primary_key=True) type = Column(String) a = Column(String) b = Column(String) def __init__(self, type, a, b): self.type = type self.a = a self.b = b <file_sep>/batch/update_kb.py # -*- coding: utf-8 -*- def run(): # do some updating <file_sep>/hanyu.py # -*- coding: utf-8 -*- from account import rest_config, stream_config from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from model import Logic from re import search class Hanyu: NAME = "ha2u_" def __init__(self): self.client = rest_config() self.stream = stream_config() __engine = create_engine('sqlite:///db/logic.db', echo=True) __Session = sessionmaker(bind=__engine) self.session = __Session() def watch(self): for msg in self.stream.user(): if 'retweeted_status' not in msg and 'text' in msg: screen_name = msg['user']['screen_name'] if screen_name != self.NAME: if '@%s' % self.NAME in msg['text']: factoid_question = search( "@%s (.*)って(何|なに)" % self.NAME, msg['text']) start_task = search( "@%s 開始.*? (.*)" % self.NAME, msg['text']) finish_task = search( "@%s 終了.*? (.*)" % self.NAME, msg['text']) if factoid_question: self.answer(msg['id'], screen_name, factoid_question.roup(1)) elif start_task: print('a') elif finish_task: print('b') else: print(start_task, finish_task) self.reply(msg['id'], screen_name, "hey!") ''' text: tweet body screen_name: screen_name which you want to reply to ''' def reply(self, tweet_id, screen_name, text): reply_text = "@%s %s" % (screen_name, text) self.client.statuses.update(status=reply_text, in_reply_to_status_id=tweet_id) def answer(self, tweet_id, screen_name, query): answer = "しらないっ" # TODO: scoreing each answer candidates for record in self.session.query(Logic) \ .filter(Logic.a.contains(query)).all(): answer = "%sだよ" % record.b break for record in self.session.query(Logic) \ .filter(Logic.a == query).all(): answer = "%sだよ" % record.b break self.reply(tweet_id, screen_name, answer)
99fa77def8342accfb1f44380a1fbb4e747ad7cc
[ "Python" ]
5
Python
himkt/hanyu
72fb0646fbd6c4c50ec0c0b605af5323b59f7c54
b26c2429f41f4ebd97f0eac17d77c8ab9121d419
refs/heads/main
<repo_name>LuisH1/react-projeto-api-rest-1<file_sep>/api-rest-1/src/components/Container/Container.jsx import React, { useEffect, useState } from 'react'; import api from '../../services/api'; import './Styles.css'; export default function Container(){ const [person, setPerson] = useState([]); const [btn, setBtn] = useState(true); var valor = []; useEffect(() => { api.get('') .then((resp) => setPerson(resp.data.results)) .catch((error) => console.log(error)) }, [btn]) valor = person.slice(0, 10); return( <> <div className="container"> <h1>Gerador de usuário</h1> <button onClick={() => { btn ? setBtn(false) : setBtn(true) }}>Gerar</button> <div className="conteudo"> { valor.map(resp => { return <div className="person"> <img src={resp.picture.large} alt="foto" /> <p>Nome: {resp.name.first} {resp.name.last}</p> <p>Idade: {resp.dob.age}</p> </div> }) } </div> </div> </> ); }
3c2d31d0d018a1021ced45c043ff27475f57fc53
[ "JavaScript" ]
1
JavaScript
LuisH1/react-projeto-api-rest-1
3ca148f072af1b511bcf23bdb8b67a7f65a1b05f
9667e283553a77c36b689b7d94e7f9eb2bb8a7fe
refs/heads/master
<repo_name>cgriffin902/chapter-4<file_sep>/LanguageFeatures/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using LanguageFeatures.Models; using System.Text; namespace LanguageFeatures.Controllers { public class HomeController : Controller { // GET: Home public string Index() { return "Navagate to a Url To show an exsample"; } public ViewResult AutoProperty() { //instanciates a new product Product myProduct = new Product(); //Sets the property value myProduct.Name = "Chris"; myProduct = new Product() { Name = "Chris", Description = "The best in the world", Category = "People", Price = 9999M, ProductId = 1, }; //get the property string productName = myProduct.Name; //Generates the property return View("Index", (object)String.Format("Product name:: {0}", productName)); } //other Actions and methods public ViewResult CreateCollection() { string[] stringArray = { "apple", "orange", "plum" }; List<int> intList = new List<int>() { 10, 20, 30, 40 }; Dictionary<string, int> myDict = new Dictionary<string, int>() { { "apple", 10 }, { "orange", 20 }, { "plum", 30 } }; return View("Index", (object)stringArray[1]); } public ViewResult UseExtensionEnumerable() { //enum List IEnumerable<Product> products = new ShoppingCart() { Products = new List<Product>{ new Product{Name = "Comic Book", Price=99M}, new Product{Name = "Movie", Price=10M}, new Product{Name = "Something", Price=20M}, new Product{Name = "Karate", Price=30M} } }; //Create and populate An Array of product Objects Product[] productArray ={ new Product{Name = "Comic Book", Price=99M}, new Product{Name = "Movie", Price=10M}, new Product{Name = "Something", Price=20M}, new Product{Name = "Karate", Price=30M}, }; //Get Total value of the products in the cart decimal cartTotal = products.TotalPrice(); decimal arrayTotal = productArray.TotalPrice(); return View("Index", (object)String.Format("Cart Total: {0}, Array Total: {1}", cartTotal, arrayTotal)); } public ViewResult UseExtentionMethod() { //Create and Populate ShoppingCart cart = new ShoppingCart() { Products = new List<Product>() { new Product{Name ="Comic Book", Price = 99M}, new Product{Name ="Movie", Price = 10M}, new Product{Name ="Something", Price = 20M}, new Product{Name ="Karate", Price = 100M} } }; //Get the total of the products in Products decimal cartTotal = cart.TotalPrice(); return View("Index", (object)String.Format("Total:{0:c}", cartTotal)); } public ViewResult UserFilterExtensionMethod() { IEnumerable<Product> products = new ShoppingCart { Products = new List<Product>{ new Product{ Name= "Cool Book", Category= "Book", Price = 99M}, new Product{ Name= "Movie", Category= "Movie", Price = 10M}, new Product{ Name= "Somthing", Category= "Book", Price = 20M}, new Product{ Name= "Karate", Category= "Movie", Price = 30M}, } }; string cat = "Movie"; string prodName = "Karate"; /* Func<Product, bool> catagoryFilter = delegate(Product prod) { return prod.Category == cat; };*/ // Func<Product,bool> catagoryFilter = prod => prod.Category == cat; decimal total = 0; foreach (Product prod in /*products.FilterByCatagory(cat)*/ products.Filter(prod => prod.Category == cat && prod.Name == prodName)) { total += prod.Price; } return View("Index", (object)String.Format("it will be {0} for the {1}s", total, cat)); } public ViewResult CreateAnonArray() { var oddsAndEnds = new[]{ new{Name = "MVC", Catagory = "Pattern"}, new{Name = "Hat", Catagory = "Clothing"}, new{Name = "Apple", Catagory = "Fruit"} }; StringBuilder result = new StringBuilder(); foreach (var item in oddsAndEnds) { result.Append(item.Name).Append(" "); } return View("Index", (object)result.ToString()); } public ViewResult FindProducts() { Product[] products ={ new Product{Name = "Cool Book", Category ="Book", Price= 99M}, new Product{Name = "Movie", Category ="Movie", Price= 10M}, new Product{Name = "Somthing", Category ="Book", Price= 20M}, new Product{Name = "Karate", Category ="Movie", Price= 30M}, }; //create the result using SQL /*var foundProducts = from match in products orderby match.Price descending select new { match.Name, match.Price }; */ //create the result using LINQ var foundProducts = products.OrderByDescending(e => e.Price) .Take(4) .Select(e => new { e.Name, e.Price }); int count = 0; var results = products.Sum(e => e.Price); products[2] = new Product { Name = "House", Price = 550M }; StringBuilder result = new StringBuilder(); foreach (var p in foundProducts) { result.AppendFormat("Price: {0} Name: {1}", p.Price, p.Name); /*if (++count == 4) { break; }*/ } //return View("Index", (object)result.ToString()); return View("Index", (object)String.Format("Sum of All = {0:c}", results)); } } }
e3dc0666b62adb4394f15d8194f59a8f04e54994
[ "C#" ]
1
C#
cgriffin902/chapter-4
c4e6d3b2db9ab6a0c7194e36b5fbf848bdc79646
acf82ca4c01ca0843338bb1aaa6295d81a1681e1
refs/heads/master
<repo_name>ornl-ndav/Binner<file_sep>/binner/src/volume.c /** \ingroup rebinner_core \file src/volume.c \brief CURRENT core API -- implementation for volume.h \note This API works with internal geometry formats of rebinner. The rebinner core assumes the wrapper functions to convert any application mesh formats into the internal format. Currently the main (actively used) mesh geometry format is gmesh. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include "vcblinalg.h" #include "binner.h" #include "cell.h" #include "clip.h" double tri_area(double *v) { double a[3]; /* compute the area of a triangle */ cal_normal(a, v); return BINNER_NORM(a)/2.0; } void center_vertex(int n, double * v, double * ctr) { /* always assume v contains all the vertices */ /* * ctr: the center (xyz) of the paralleliped * assume 3 elements are already alloated */ int i; assert(v != NULL); assert(ctr != NULL); for (i = 0; i < 3; ctr[i] = 0.0, i ++); for (i = 0; i < n*3; ctr[i%3] += v[i], i ++); for (i = 0; i < 3; ctr[i] /= n, i ++); /* now, ctr has the coordinate of the center */ } double polygon_area(int n, double *v) { /* * compute the area of a parallelogram affine * transformed from a 2D quad * * the function name: para_area might be confused to mean area of * a paralleliped. hence, we use the name quad_area instead. */ int i; double area, tri2[9]; /* assume v contains xyz coordinates of 4 vertices */ assert(v != NULL); center_vertex(n, v, tri2); /* tri2[0-3]: center */ /* now, let's build triangles */ for (i = 0, area = 0.0; i < n-1; i ++) { memcpy(tri2+3, v+i*3, 6*sizeof(double)); area += tri_area(tri2); } /* the last edge goes from the last vertex back to the first vertex */ memcpy(tri2+3, v+i*3, 3*sizeof(double)); memcpy(tri2+6, v, 3*sizeof(double)); area += tri_area(tri2); return area; } double pyramid_volume(int nv, double * apex, double * v) { /* * assume there are n vertices (xyz) in v * apex: the apex of the pyramid * v: form the base polygon, so (nv) edges/vertices */ double v1[3], n[3]; double base_area, height, norm, volume; base_area = polygon_area(nv, v); cal_normal(n, v); /* v1[0] = v[6] - v[3]; v1[1] = v[7] - v[4]; v1[2] = v[8] - v[5]; v2[0] = v[9] - v[3]; v2[1] = v[10] - v[4]; v2[2] = v[11] - v[5]; VCB_CROSS(n, v1, v2); */ v1[0] = apex[0] - v[0]; v1[1] = apex[1] - v[1]; v1[2] = apex[2] - v[2]; /* norm = BINNER_NORM(n); */ norm = vec_normalize(n); /* returns norm before normalization */ /* if (norm < 1e-8) { n[0] = n[1] = n[2] = 0.0; } else { n[0] /= norm; n[1] /= norm; n[2] /= norm; } */ height = fabs(VCB_DOT(v1, n)); volume = height * base_area /3.0; return volume; } double polyhedral_volume(int nfacets, int * nverts, double * v) { int totalnverts; double ctr[3], *f; double volume; /* the volume of the paralleliped */ int i; /* always assume v contains all the vertices for all the facets */ assert(v != NULL); for (i = 0, totalnverts = 0; i < nfacets; i ++) totalnverts += nverts[i]; /* xyz of the apex for all the pyramids is the ctr of the polyhedron */ center_vertex(totalnverts, v, ctr); /* * after knowing the center, let us build nfacets number of pyramids. * each with one of the facets as the base. */ for (i = 0, volume = 0.0, f = v; i < nfacets; i ++) { /*memcpy(&pyram[3], &v[i*12], sizeof(double)*12);*/ volume += pyramid_volume(nverts[i], ctr, f); f += nverts[i]*3; } return volume; } double partialvoxel_volume( int nwf, /* number of working facets - clipping planes */ int * nv, /* number of vertices on each working face */ double * wf, /* vertices on working facets */ int * worig, double ccs) { int nfacets; int * nverts; double * cubev; /*[6*4*3];*/ double * plane_eq, *p; double * w, volume; int i, j; /* first prepare the basic geometry of a cube */ nfacets = 6; nverts = malloc(nfacets*sizeof(int)); for (i = 0; i < nfacets; nverts[i] = 4, i ++); cubev = malloc(6*4*3*sizeof(double)); basicCubed(cubev); plane_eq = malloc(nwf * 4 *sizeof(double)); /*printf("%lf ", ccs);*/ /* move and scale the cube to conform to the voxel in question */ for (i = 0; i < 6 * 4; i ++) for (j = 0; j < 3; j ++) cubev[i*3+j] = (cubev[i*3+j] + worig[j])*ccs; /* A,B,C,D in plane normal as in Ax+By+Cz+D = 0 */ for (i = 0, p = plane_eq, w = wf; i < nwf; p+=4, i ++) { cal_normal(p, w); vec_normalize(p); p[3] = -VCB_DOT(w, p); w += nv[i] * 3; } /*printf("%e %e %e on %d faces ", cubev[3], cubev[4], cubev[5], nfacets);*/ /* start clipping by each clipping plane */ for (i = 0, nfacets = 6, p = plane_eq; ((nfacets > 0) && (i < nwf)); p+= 4, i ++) { //printf("clipping polyheral, clip plane %d of %d, still %d faces left in cube\n", i, nwf, nfacets); nfacets = clip_polyhedral(nfacets, &nverts, &cubev, p); } /* now we have a polyhedral cell. compute its volume */ if (nfacets > 0) volume = polyhedral_volume(nfacets, nverts, cubev); else volume = 0; //printf("partialvolume = %lf, nfacets = %d\n", volume, nfacets); free(plane_eq); if (nverts != NULL) free(nverts); if (cubev != NULL) free(cubev); return volume; } <file_sep>/binner/src/gmeshmat.c /** \ingroup rebinner_execs \file src/gmeshmat.c \brief CURRENT executable transforms a gmesh using a transformation matrix usage: gmeshmat mat0 mat1 mat2 mat3 mat4 mat5 mat6 mat7 mat8 < BINARY_gmesh \note gmeshmat expects a 3x3 matrix in row-major order as command line input. $Id$ */ #include <stdlib.h> #include <stdio.h> void matMult3x3(double * v0, double * mat, double * v1) { double v[4]; v[0] = mat[0] *v1[0] + mat[1] *v1[1] + mat[2] *v1[2]; /* + mat[3] *v1[3]; */ v[1] = mat[4] *v1[0] + mat[5] *v1[1] + mat[6] *v1[2]; /* + mat[7] *v1[3]; */ v[2] = mat[8] *v1[0] + mat[9] *v1[1] + mat[10]*v1[2]; /* + mat[11]*v1[3]; */ /*v[3] = mat[12]*v1[0] + mat[13]*v1[1] + mat[14]*v1[2] + mat[15]*v1[3];*/ v0[0] = v[0]; v0[1] = v[1]; v0[2] = v[2]; /* v0[3] = 1.f; */ } int main(int argc, char ** argv) { int i, n, buf[1]; double vdata[4 + 8*3], *v; double mat[16]; if (argc != 10) { fprintf(stderr, "usage: %s mat0 mat1 mat2 mat3 mat4 mat5 mat6 mat7 mat8\n", argv[0]); fprintf(stderr, " %s expects a 3x3 matrix in row-major order for input\n", argv[0]); exit(1); } mat[0] = atof(argv[1]); mat[1] = atof(argv[2]); mat[2] = atof(argv[3]); mat[4] = atof(argv[4]); mat[5] = atof(argv[5]); mat[6] = atof(argv[6]); mat[8] = atof(argv[7]); mat[9] = atof(argv[8]); mat[10] = atof(argv[9]); v = vdata + 4; for (n = 0; ; n ++) { if (fread(buf, sizeof(int), 1, stdin) <= 0) break; fwrite(buf, sizeof(int), 1, stdout); fread(vdata, sizeof(double), 4 + 8 *3, stdin); for (i = 0; i < 8; i ++) matMult3x3(v + i * 3, mat, v + i*3); fwrite(vdata, sizeof(double), 4 + 8*3, stdout); } return 0; } <file_sep>/binner/vcb/CMakeModules/OpenGLConfig.cmake find_path(OPENGL_INCLUDE_DIR gl.h /usr/local/include/GL /usr/include/GL /usr/local/include /usr/include) find_library(OPENGL_gl_LIBRARY NAMES GL gl PATHS /usr/local/lib64 NO_DEFAULT_PATH) find_library(OPENGL_gl_LIBRARY NAMES GL gl PATHS /usr/lib64 /usr/local/lib /usr/lib /usr/X11R6/lib) find_library(OPENGL_glu_LIBRARY NAMES GLU glu PATHS ${OPENGL_gl_LIBRARY} /usr/local/lib64 NO_DEFAULT_PATH) find_library(OPENGL_glu_LIBRARY NAMES GLU glu PATHS /usr/lib64 /usr/local/lib /usr/lib /usr/X11R6/lib) find_path(GLUT_INCLUDE_DIR glut.h /usr/local/include/GL /usr/include/GL /usr/local/include /usr/include) find_library(GLUT_LIBRARY NAMES glut GLUT PATHS ${OPENGL_gl_LIBRARY} /usr/local/lib64 /usr/lib64 /usr/local/lib /usr/lib /usr/X11R6/lib) <file_sep>/binner/src/gmesht2b.c /** \ingroup rebinner_execs \file src/gmesht2b.c \brief CURRENT executable to convert from ASCII to binary gmesh formats. gmesht2b < ASCII_gmesh > BINARY_gmesh \note This executable is designed to act as a filter. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, char ** argv) { int nfacets, i, n, sliceid; double * vdata; double emin, emax, hitcnt, hiterr, threshold; char * buf; int lastchar[50], c; buf = malloc(1024*8); vdata = malloc(1024 * sizeof(double)); threshold = 1e-16; if (argc == 3) { if (strcmp(argv[1],"-t") == 0) threshold = atof(argv[2]); else { fprintf(stderr, "usage: %s [-t threshhold] \n", argv[0]); exit(1); } } else if (argc != 1) { fprintf(stderr, "usage: %s [-t threshhold] \n", argv[0]); exit(1); } for (nfacets = 0; fgets(buf, 1024*8, stdin) != NULL; ) { for (i = 0, c = 0; buf[i] != '\0'; i ++) if (isspace(buf[i])) { buf[i] = '\0'; lastchar[c] = i; c ++; } if (c == 29) nfacets ++; else continue; hitcnt = atof(buf + lastchar[2] + 1); if (hitcnt < threshold) continue; c = 0; sliceid = atoi(buf+c); c = lastchar[0] + 1; emin = atof(buf + c); c = lastchar[1] + 1; emax = atof(buf + c); c = lastchar[2] + 1; hitcnt = atof(buf +c); c = lastchar[3] + 1; hiterr = atof(buf +c); c = lastchar[4] + 1; for (n = 0; n < 8 * 3; n ++) { vdata[n] = atof(buf + c); c = lastchar[n + 5] + 1; } fwrite(&sliceid, sizeof(int), 1, stdout); fwrite(&emin, sizeof(double), 1, stdout); fwrite(&emax, sizeof(double), 1, stdout); fwrite(&hitcnt, sizeof(double), 1, stdout); fwrite(&hiterr, sizeof(double), 1, stdout); fwrite(vdata, sizeof(double), 8*3, stdout); } free(vdata); free(buf); /* fprintf(stderr, "nfacets = %d\n", nfacets); */ if (nfacets > 0) return 0; /* successful */ else return 1; /* failure */ } <file_sep>/binner/script/gmesht2b.sh #!/bin/bash # use: gmesht2b.sh directory if [ ! -e "$1" ] && [ ! -d "$1" ] # test if target directory exists then echo "$1 is not a valid directory" exit 127 # error code 127 fi echo -n "deleting all *.inb files ... " rm -rf $1/*.inb echo "done" for f in $1/*.in do echo -n "$f --> ${f}b: " gmesht2b < $f > $1/${f}.tmp return_val=$? if (( return_val > 0 )) then echo "failed" else gmeshorderv < $1/${f}.tmp > ${f}b echo "successful" fi rm -rf $1/${f}.tmp done exit 0 <file_sep>/binner/src/CMakeLists.txt # # $Id$ # set(TOP ${PROJECT_SOURCE_DIR}) include_directories( ${TOP}/include ${TOP}/vcb/include ) if(NOT BINNER_INSTALL_DIR) set(DEST ${TOP}) else(NOT BINNER_INSTALL_DIR) set(DEST ${BINNER_INSTALL_DIR}) endif(NOT BINNER_INSTALL_DIR) #set(LIBS vcbnogl) #add_library(${LIBS} STATIC IMPORTED) #set_property( # TARGET # ${LIBS} PROPERTY IMPORTED_LOCATION ${TOP}/vcb/lib/libvcbnogl.a #) set(EXES gmeshrebin gmeshrebin2 gmeshrebin3 gmeshrot gmeshrot2 gmeshrot3 gmeshmat gmesht2b gmeshb2t gmeshindex gmeshquery gmeshorderv bmeshrebin largebmeshrebin bounds bslicer clip3d clipvoxel compvol collector counts export2vtk export2vcb gencell getfrom giveto netrebin pix2mesh rebin rot3d rotmat map reduce scale3d serve sorter tran3d) set(GLEXES seeall seepara seegmesh seebmeshvol seebmeshvolc) link_libraries(pthread vcbnogl m) add_executable(netrebin netrebin.c socketfun.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(getfrom getfrom.c socketfun.c) add_executable(giveto giveto.c socketfun.c) add_executable(serve serve.c socketfun.c) add_executable(pix2mesh pix2mesh.c cell.c binnerio.c) add_executable(gencell gencell.c cell.c binnerio.c) add_executable(rot3d rot3d.c binnerio.c) add_executable(rotmat rotmat.c) add_executable(gmeshindex gmeshindex.c) add_executable(gmeshquery gmeshquery.c) add_executable(gmeshorderv gmeshorderv.c cell.c) add_executable(gmeshrot gmeshrot.c binnerio.c) add_executable(gmeshrot2 gmeshrot2.c) add_executable(gmeshrot3 gmeshrot3.c) add_executable(gmeshmat gmeshmat.c) add_executable(gmesht2b gmesht2b.c) add_executable(gmeshb2t gmeshb2t.c) add_executable(tran3d tran3d.c binnerio.c) add_executable(scale3d scale3d.c binnerio.c) add_executable(clip3d clip3d.c clip.c geometry.c binnerio.c) add_executable(clipvoxel clipvoxel.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(compvol compvol.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(rebin rebin.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(bounds bounds.c cell.c binnerio.c) add_executable(counts counts.c binnerio.c) add_executable(bmeshrebin bmeshrebin.c rebinapp.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(gmeshrebin gmeshrebin.c rebinapp.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(gmeshrebin2 gmeshrebin2.c rebinapp.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(gmeshrebin3 gmeshrebin3.c rebinapp.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(reduce reduce.c reducefunc.c rebinapp.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(map map.c) add_executable(largebmeshrebin largebmeshrebin.c binner.c voxelize.c volume.c clip.c cell.c geometry.c binnerio.c) add_executable(export2vtk export2vtk.c binnerio.c) add_executable(export2vcb export2vcb.c binnerio.c) add_executable(bslicer bslicer.c binnerio.c) find_library(PTHREAD_LIBRARY NAMES pthread) add_executable(collector collector.c socketfun.c) target_link_libraries(collector ${PTHREAD_LIBRARY}) add_executable(sorter sorter.c socketfun.c binnerio.c) target_link_libraries(sorter ${PTHREAD_LIBRARY}) if (NOT NOGL) #find_package(OPENGL REQUIRED) #find_package(GLUT REQUIRED) include(${TOP}/vcb/CMakeModules/OpenGLConfig.cmake) include_directories( # ${OPENGL_INCLUDE_DIR}/Headers ${OPENGL_INCLUDE_DIR} ${GLUT_INCLUDE_DIR} ) link_libraries(vcbgl) add_executable(seeall seeall.cpp formain.cpp binnerio.c) add_executable(seepara seepara.cpp formain.cpp cell.c binnerio.c) add_executable(seegmesh seegmesh.cpp formain.cpp cell.c binnerio.c) add_executable(seebmeshvol seebmeshvol.cpp formain.cpp cell.c binnerio.c) add_executable(seebmeshvolc seebmeshvolc.cpp formain.cpp cell.c binnerio.c) install(TARGETS ${EXES} ${GLEXES} RUNTIME DESTINATION ${DEST}/bin LIBRARY DESTINATION ${DEST}/lib ARCHIVE DESTINATION ${DEST}/lib) else(NOT NOGL) install(TARGETS ${EXES} RUNTIME DESTINATION ${DEST}/bin LIBRARY DESTINATION ${DEST}/lib ARCHIVE DESTINATION ${DEST}/lib) endif(NOT NOGL) <file_sep>/binner/src/giveto.c /** \ingroup rebinner_sdk \file src/giveto.c \brief CURRENT sdk executable to send out data to a network port. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include <signal.h> #include "socketfun.h" int sock, n = 0; char netbuf[5000]; void sigpipe_handler(int dummy) { /* keep on reading until done */ for ( ; read(0, netbuf, 4096) > 0; ); close (sock); exit(2); } int main(int argc, char ** argv) { int i, n; signal(SIGPIPE, sigpipe_handler); if (0 > (sock = request_connection(argv[1], atoi(argv[2])))) { perror("giveto: cannot get a connection"); exit(1); } for (n = 0; (i = read(0, netbuf, 4096)) > 0; ) n += write(sock, netbuf, i); close(sock); return 0; } <file_sep>/binner/src/reduce.c /** \ingroup rebinner_sdk \file src/reduce.c \brief CURRENT sdk executable to reduce results from multi-process. \note This process is never invoked directly, always implicitly created by map via fork(). $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/select.h> #include "reducefunc.h" #include "macros.h" #define BUFSIZE 2*1024*1024 /* reduce receives the whole list or argv received by "map", verbatim */ int main(int argc, char ** argv) { fd_set readfds, masterfds; int i, n, m, k, nbytes = 0, ninputs; char * netbuf; int unitsize; char * backup[16]; /* maximum - 16 inputs */ int bcnt[16]; /* if (argc != 2) { fprintf(stderr, "usage: reduce number_of_input_streams\n"); fprintf(stderr, "%s %s\n", argv[0], argv[1]); exit(1); } */ close(0); unitsize = reduce_init(argc, argv); ninputs = (int)(atof(argv[2])); for (i = 3; i < 3+ninputs; i ++) { backup[i] = malloc(unitsize); bcnt[i] = 0; } #if REBINDEBUG fprintf(stderr, "reduce running with %d inputs\n", ninputs); #endif netbuf = malloc(BUFSIZE); FD_ZERO(&masterfds); for (i = 3; i < 3 + ninputs; i++) FD_SET(i, &masterfds); for (m = ninputs ; m > 0; ) { /* * FD_COPY(&masterfds, &readfds); * not portable on all unix flavors */ memcpy(&readfds, &masterfds, sizeof(fd_set)); if ((n = select(ninputs + 3, &readfds, NULL, NULL, NULL)) < 0) { perror("select failed in reduce"); exit(2); } #if 0 fprintf(stderr, "reduce select returned %d, ninputs = %d \n", n, m); #endif for (i = 3; i < 3 + ninputs; i ++) if (FD_ISSET(i, &readfds)) { n = read(i, netbuf, BUFSIZE); #if REBINDEBUG fprintf(stderr, "reduce read %d bytes from fd: %d, bcnt = %d, %d items, %d extra bytes\n", n, i, bcnt[i], n/unitsize, n%unitsize); #endif if (n > 0) { if (bcnt[i] > 0) { k = unitsize - bcnt[i]; memcpy(backup[i]+bcnt[i], netbuf, k); reduce_func(backup[i], 1); } else k = 0; reduce_func(netbuf+k, (n-k)/unitsize); bcnt[i] = (n-k)%unitsize; memcpy(backup[i], netbuf+ n - bcnt[i], bcnt[i]); nbytes += n; } else { #if REBINDEBUG fprintf(stderr,"reduce input %d is done\n", i - 3); #endif FD_CLR(i, &masterfds); m --; close(i); } } } if (strcmp(argv[3],"-nd") == 0) reduce_done(1); /* no factorial division */ else reduce_done(0); /* do factorial division */ #if REBINDEBUG fprintf(stderr,"reduce ninputs = %d \n", ninputs); fprintf(stderr,"reduce read %d bytes.\n", nbytes); #endif free(netbuf); for (i = 3; i < 3+ninputs; i ++) free(backup[i]); return 0; } <file_sep>/binner/src/bmeshrebin.c #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include "vcblinalg.h" #include "vcbutils.h" #include "rebinapp.h" #include "binnerio.h" #include "binner.h" #include "cell.h" #include "volume.h" /** * $Id$ * */ char md5string[100], fname[200], rbuf[8192]; float vbuf[1024]; int main(int argc, char ** argv) { clock_t time1, time2; int i, j, n, f, npara, sliceid, res, nvoxel, orig[3], xyzsize[3]; double * vdata, * hcnt, * herr, spacing[3]; int * nverts, * sid; double totalvolume, cellsize, bounds[6], askbounds[6]; double * voxels; float hitcnt, hiterr, corners[8][4]; float rebintime = 0; int FV = 0; /* 0 - FV unspecified; 1 - FV specified */ /* for (nfacets = 0, v = vdata; (n = get_polygond(v)) > 0; nfacets ++) { nverts[nfacets] = n; v += n * 3; } */ i = getchar(); ungetc(i, stdin); if (i == 'M') { /* * if an md5string is provided * all results will be saved to a MR-JH directory */ fgets(rbuf, 8192, stdin); /* get everything on that first line */ sscanf(rbuf, "%s", md5string); /* sprintf(fname, "%s.bin", md5string); fgets(md5string, 100, stdin); get whatever that is left on this line */ sprintf(fname, "mkdir %s\n", md5string); system(fname); sprintf(fname, "%s",md5string); } else fname[0] = 0; /* f = atoi(argv[2]); */ scanf("%d", &f); fgets(md5string, 100, stdin); /* get whatever that is left on this line */ fprintf(stderr, "rebin data name : %s\n", fname); vdata = malloc(f * 6 * 4 * 3 * sizeof(double)); nverts = malloc(f * 6 * sizeof(int)); hcnt = malloc(f * sizeof(double)); herr = malloc(f * sizeof(double)); sid = malloc(f * sizeof(int)); i = getchar(); ungetc(i, stdin); if (i == 'F') { /* ignore FV field so far */ j = getchar(); j = getchar(); if (j != 'V') fprintf(stderr, "wrong input format on line #3: FV ... FV field\n"); fgets(rbuf, 8192, stdin); /* get everything on that first line */ if (argc < 2) if (strlen(rbuf) > 20) /* not empty between the beginning and ending FV field */ { sscanf(rbuf, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d %d %d", &vdata[0], &vdata[1], &vdata[2], &vdata[3], &vdata[4], &vdata[5], &vdata[6], &vdata[7], &vdata[8], &vdata[9], &vdata[10], &vdata[11], &vdata[12], &vdata[13], &vdata[14], &vdata[15], &vdata[16], &vdata[17], &vdata[18], &vdata[19], &vdata[20], &vdata[21], &vdata[22], &vdata[23], &xyzsize[0],&xyzsize[1], &xyzsize[2]); /* for (j = 0; j < 24; j ++) fprintf(stderr,"%.2lf ", vdata[j]); fprintf(stderr,"\n"); for (j = 0; j < 3; j ++) fprintf(stderr,"%d ", xyzsize[j]); fprintf(stderr,"\n"); */ bounding_box(8, askbounds, vdata); for (j = 0; j < 3; j++) spacing[j] = (askbounds[j*2+1] - askbounds[j*2])/xyzsize[j]; output_askinginfo(askbounds, xyzsize, spacing); FV = 1; } } for (npara = 0; (n = get_pixelf(&sliceid,&hitcnt,&hiterr,corners)) > 0; npara ++) { if (npara >= f) break; /* read at most f faces, i.e. f/6 parallelipeds */ if (hitcnt >= 1e-16) { /* only ones with real hitcnt should be fixed */ /* otherwise, just keep the space filled would be fine */ correctCornersf3d(corners, NULL); } realCubef(corners, vbuf); for (i = 0; i < 6*4; i ++) { vdata[(npara*6*4+i)*3+0] = vbuf[i*4+0]; vdata[(npara*6*4+i)*3+1] = vbuf[i*4+1]; vdata[(npara*6*4+i)*3+2] = vbuf[i*4+2]; } for (i = 0; i < 6; i ++) nverts[npara*6+i] = 4; hcnt[npara] = hitcnt; herr[npara] = hiterr; sid[npara] = sliceid; #if REBINDEBUG fprintf(stderr,"sid, hcnt, herr: %d %lf %lf\n", sid[npara], hcnt[npara], herr[npara]); #endif } bounding_box(npara*6*4, bounds, vdata); output_actualinfo(bounds); if (FV == 1) { cellsize = fv_bounds(askbounds, spacing, orig, xyzsize); scale_vertices( npara * 6 * 4, vdata, cellsize/spacing[0], cellsize/spacing[1], cellsize/spacing[2]); } else { res = 100; /* this is the default resolution */ if (argc > 1) res = atoi(argv[1]); cellsize = padded_bounds(bounds, res, orig, xyzsize); } output_prerebininfo(orig, xyzsize, spacing, cellsize); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double) * 2); /* rebin both counts and error */ time1 = clock(); totalvolume = rebin_byslice(npara, nverts, vdata, /* the vertices */ sid, hcnt, /* hit counter */ herr, /* hit counter error */ orig, xyzsize, cellsize, spacing, voxels, fname); time2 = clock(); rebintime += (float)(time2-time1)/CLOCKS_PER_SEC; output_postrebininfo(rebintime, npara, totalvolume, nvoxel); free(sid); free(herr); free(hcnt); free(voxels); free(nverts); free(vdata); return 0; } <file_sep>/binner/src/netrebin.c #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <math.h> #include <unistd.h> #include "vcblinalg.h" #include "vcbutils.h" #include "binnerio.h" #include "binner.h" #include "volume.h" /** * $Id$ * */ int main(int argc, char ** argv) { int nfacets, i, j, k, n, vid; double * vdata, * v; int * nverts; /* at most 200 facets */ double totalvolume, cellsize; double bounds[6], * voxels; int nvoxel; int orig[3], xyzsize[3]; int f, toread; static char netbuf[1000000]; char * cp; cellsize = atof(argv[1]); f = 150*6; /* the internal buffer holds at most 150 parallelipeds */ /* input has at most 1k vertices */ vdata = malloc(f * 4 * 3 * sizeof(double)); /* input has at most 200 facets */ nverts = malloc(f * sizeof(int)); voxels = NULL; /* read and write the 8 bytes header without looking */ //n = fread(netbuf, 2, sizeof(int), stdin); read(0, netbuf, 2*sizeof(int)); //fwrite(netbuf, 2, sizeof(int), stdout); write(1,netbuf, 2*sizeof(int)); while (1) { //n = fread(netbuf, 1, f * (sizeof(int)+4*3*sizeof(double)), stdin); toread = f * (sizeof(int)+4*3*sizeof(double)); for (cp = netbuf, n = 0; (i = read(0, cp, toread)) > 0; toread -=i, cp+=i) n += i; /*fprintf(stderr,"after fread n = %d\n", n);*/ if (n <= 0) break; /* got nothing. so done */ /* now let's see if we can find up to 150 parallelipeds to work with */ for (nfacets = 0, v = vdata, cp = netbuf; (nfacets < f/6) && n > 0; nfacets ++) { i = *((int *) cp); nverts[nfacets] = i; cp += 4; n -= 4; memcpy(v, cp, i * 3 * sizeof(double)); cp += i * 3 * sizeof(double); n -= i * 3 * sizeof(double); v += i * 3; } if (nfacets <= 0) break; /* got nothing workable. so done */ fprintf(stderr, "netrebin got %d facets\n", nfacets); bounding_box((v-vdata)/3, bounds, vdata); orig[0] = (int)(bounds[0]/cellsize); orig[1] = (int)(bounds[2]/cellsize); orig[2] = (int)(bounds[4]/cellsize); xyzsize[0] = (int)(bounds[1]/cellsize+0.5) - orig[0]; xyzsize[1] = (int)(bounds[3]/cellsize+0.5) - orig[1]; xyzsize[2] = (int)(bounds[5]/cellsize+0.5) - orig[2]; fprintf(stderr,"orig: %d %d %d, xyzsize: %d %d %d\n", orig[0], orig[1], orig[2], xyzsize[0], xyzsize[1], xyzsize[2]); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double)); for (i = 0; i < nvoxel; voxels[i] = 0.0, i ++); totalvolume = bin_para_3dvoxelize(nfacets, nverts, vdata, /* the vertices */ orig, xyzsize, cellsize, voxels); for (i = 0, n = 0; i < nvoxel; i ++) if (voxels[i] > 0) n ++; /* fwrite(&n, 1, sizeof(int), stdout); fwrite(orig, 3, sizeof(int), stdout); fwrite(xyzsize, 3, sizeof(int), stdout); */ cp = netbuf; memcpy(cp, &n, sizeof(int)); cp+= sizeof(int); memcpy(cp, orig, 3*sizeof(int)); cp+=3*sizeof(int); memcpy(cp, xyzsize, 3*sizeof(int)); cp+=3*sizeof(int); write(1, netbuf, cp-netbuf); n = 0; for (i = 0; i < xyzsize[0]; i ++) for (j = 0; j < xyzsize[1]; j ++) for (k = 0; k < xyzsize[2]; k ++) { vid = (i*xyzsize[1] + j)*xyzsize[2] + k; if (voxels[vid] > 0) { /* fwrite(&i, 1, sizeof(int), stdout); fwrite(&j, 1, sizeof(int), stdout); fwrite(&k, 1, sizeof(int), stdout); fwrite(&voxels[vid], 1, sizeof(double), stdout); */ cp = netbuf; memcpy(cp, &i, sizeof(int)); cp+= sizeof(int); memcpy(cp, &j, sizeof(int)); cp+= sizeof(int); memcpy(cp, &k, sizeof(int)); cp+= sizeof(int); memcpy(cp, &voxels[vid], sizeof(double)); cp+=sizeof(double); write(1, netbuf, cp-netbuf); } n ++; } } if (voxels != NULL) free(voxels); if (nverts != NULL) free(nverts); if (vdata != NULL) free(vdata); return 0; } <file_sep>/binner/src/gmeshrot3.c /** \ingroup rebinner_execs \file src/gmeshrot3.c \brief CURRENT executable for rotating gmesh geometry. $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" void matMult3x3(double * v0, double * mat, double * v1) { double v[4]; v[0] = mat[0] *v1[0] + mat[1] *v1[1] + mat[2] *v1[2]; /* + mat[3] *v1[3]; */ v[1] = mat[4] *v1[0] + mat[5] *v1[1] + mat[6] *v1[2]; /* + mat[7] *v1[3]; */ v[2] = mat[8] *v1[0] + mat[9] *v1[1] + mat[10]*v1[2]; /* + mat[11]*v1[3]; */ /*v[3] = mat[12]*v1[0] + mat[13]*v1[1] + mat[14]*v1[2] + mat[15]*v1[3];*/ v0[0] = v[0]; v0[1] = v[1]; v0[2] = v[2]; /* v0[3] = 1.f; */ } int main(int argc, char ** argv) { int i, n, buf[1]; double vdata[4 + 8*3], *v; double mat[16], axis[3], angle; if (argc != 5) { fprintf(stderr, "usage: %s x_axis y_axis z_axis angle\n", argv[0]); exit(1); } axis[0] = atof(argv[1]); axis[1] = atof(argv[2]); axis[2] = atof(argv[3]); angle = atof(argv[4]); vcbRotate3dv(mat, axis, angle); v = vdata + 4; for (n = 0; ; n ++) { if (fread(buf, sizeof(int), 1, stdin) <= 0) break; fwrite(buf, sizeof(int), 1, stdout); fread(vdata, sizeof(double), 4 + 8 *3, stdin); for (i = 0; i < 8; i ++) matMult3x3(v + i * 3, mat, v + i*3); fwrite(vdata, sizeof(double), 4 + 8*3, stdout); } return 0; } <file_sep>/binner/src/socketfun.c /** \file src/socketfun.c \brief <NAME>'s socket functions. Released as "do whatever you want with it". $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <signal.h> #include <time.h> #include "socketfun.h" /*static */ char * inadport_decimal(struct sockaddr_in *sad) { static char buf[32]; int a; a = ntohl(0xffffffff & sad->sin_addr.s_addr); sprintf(buf, "%d.%d.%d.%d:%d", 0xff & (a >> 24), 0xff & (a >> 16), 0xff & (a >> 8), 0xff & a, 0xffff & (int)ntohs(sad->sin_port)); return buf; } int server_setup(char * dn, int * pn) { int port, i, sock; srandom((unsigned long)time(NULL)); for (i = 0; i < 20; i ++) { port = 6000 + (random()&0xfff); /*fprintf(stderr, "%d\n",port);*/ sock = serve_socket(dn, port); *pn = port; if (sock > 0) return sock; } fprintf(stderr, "server_setup: failed to get an open port after 20 tries\n"); return -100; } int serve_socket(char *hn, int port) { struct sockaddr_in sn; int s; struct hostent *he; if (!(he = gethostbyname(hn))) { puts("can't gethostname"); exit(-101); } memset(&sn, 0, sizeof(sn)); sn.sin_family = AF_INET; sn.sin_port = htons((short)port); sn.sin_addr = *(struct in_addr*)(he->h_addr_list[0]); if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) { /*perror("socket()");*/ return -102; } if (bind(s, (struct sockaddr*)&sn, sizeof(sn)) == -1) { /*perror("bind()");*/ return -103; } return s; } int accept_connection(int s) { unsigned int l; struct sockaddr_in sn; int x; sn.sin_family = AF_INET; if (listen(s, 1) == -1) { /*perror("listen()");*/ return -104; } l = sizeof(sn); if ((x = accept(s, (struct sockaddr*)&sn, &l)) == -1) { /*perror("accept()");*/ return -105; } return x; } int request_connection(char *hn, int port) { struct sockaddr_in sn; int s, ok; struct hostent *he; if (!(he = gethostbyname(hn))) { puts("can't gethostname"); return -106; } ok = 0; while (!ok) { sn.sin_family = AF_INET; sn.sin_port = htons((short)port); sn.sin_addr.s_addr = *(u_long*)(he->h_addr_list[0]); if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -107; } ok = (connect(s, (struct sockaddr*)&sn, sizeof(sn)) != -1); if (!ok) return -108; /*sleep (1);*/ } return s; } <file_sep>/binner/src/gmeshorderv.c /** \ingroup rebinner_execs \file src/gmeshorderv.c \brief CURRENT executable for fixing vertex ordering. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "cell.h" int main(int argc, char ** argv) { int i, n, buf[1]; double vdata[4 + 8*3], *v, out[8*3]; float corners[8][4]; int id_array[8] = {0, 1, 2, 3, 4, 5, 6, 7}; int ids[8]; v = vdata + 4; for (i = 0; i < 8; corners[i][3] = 0., i ++); for (n = 0; ; n ++) { if (fread(buf, sizeof(int), 1, stdin) <= 0) break; fwrite(buf, sizeof(int), 1, stdout); fread(vdata, sizeof(double), 4 + 8 *3, stdin); memcpy(out, v, sizeof(double)*8*3); memcpy(ids, id_array, sizeof(int)*8); for (i = 0; i < 8; i ++) { corners[i][0] = v[i*3]; corners[i][1] = v[i*3+1]; corners[i][2] = v[i*3+2]; } correctCornersf3d(corners, ids); for (i = 0; i < 8; i ++) { v[i*3] = out[ids[i]*3]; v[i*3+1] = out[ids[i]*3 + 1]; v[i*3+2] = out[ids[i]*3 + 2]; } fwrite(vdata, sizeof(double), 4 + 8*3, stdout); } return n; } <file_sep>/binner/script/gmesh_mthread_test.sh #!/bin/bash time map -n 2 gmeshrebin3 -f 0.0 2.0 2.0 0.0 6.0 3.0 0.0 6.0 3.0 < ../data/reuter_input.inb > /dev/null time map -n 3 gmeshrebin3 -f -0.8 0 0.002 -0.21 0.21 0.001 0.5 2.0 0.002 < ../exp/rotdata_test.inb > /dev/null <file_sep>/README.md # Binner This page is the home of the 3 dimensional rebinning software written by <NAME> of the University of Tennessee. This software was developed for use in the analysis of data from the inelastic instruments at the SNS. <file_sep>/binner/src/reducefunc.c /** \ingroup rebinner_sdk \file src/reducefunc.c \brief CURRENT sdk API -- implements reducefunc.h Sample implementation designed for handling gmesh rebinnering. $Id$ */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <unistd.h> #include "jrb.h" #include "dmem.h" #include "rebinapp.h" #include "reducefunc.h" #include "macros.h" #define ITEMSIZE (sizeof(int)*4 + sizeof(double)*5) static JRB b; static Dmlist dm; static double volumescale, spacing[3]; static int orig[3]; static void calc_bounds(int argc, char ** argv) { int c, j, xyzsize[3]; double cellsize, askbounds[6]; c = argc - 10; askbounds[0] = atof(argv[c+1]); askbounds[1] = atof(argv[c+2]); spacing[0] = atof(argv[c+3]); askbounds[2] = atof(argv[c+4]); askbounds[3] = atof(argv[c+5]); spacing[1] = atof(argv[c+6]); askbounds[4] = atof(argv[c+7]); askbounds[5] = atof(argv[c+8]); spacing[2] = atof(argv[c+9]); for (j = 0; j < 3; j++) xyzsize[j] = (int)ceil((askbounds[j*2+1] - askbounds[j*2])/spacing[j]); for (j = 0; j < 3; j++) spacing[j] = (askbounds[j*2+1] - askbounds[j*2])/xyzsize[j]; cellsize = fv_bounds(askbounds, spacing, orig, xyzsize); volumescale = (cellsize/spacing[0]) * (cellsize/spacing[1]) * (cellsize/spacing[2]); volumescale = 1.0/volumescale; output_askinginfo(askbounds, xyzsize, spacing); output_prerebininfo(orig, xyzsize, spacing, cellsize); } int reduce_init(int argc, char ** argv) { b = make_jrb(); dm = new_dmlist(); #if REBINDEBUG fprintf(stderr, "reduce_init, argc = %d\n", argc); #endif calc_bounds(argc, argv); /* return unitsize */ return ITEMSIZE; } static int cmp (Jval a, Jval b) { int * i1, * i2, k; i1 = (int *)(jval_v(a)); i2 = (int *)(jval_v(b)); /* i1[0], i2[0]: sliceid, should be the same */ for (k = 1; k < 4; k ++) if (i1[k] != i2[k]) return (i1[k] - i2[k]); return 0; } static void accumulate_counts(void * h, void * v) { char * hc, * vc; double * d1, * d2; hc = h; vc = v; hc += sizeof(int)*4; vc += sizeof(int)*4; d1 = (double *) hc; d2 = (double *) vc; d1[0] += d2[0]; /* rebinned counts */ d1[1] += d2[1]; /* rebinned error */ d1[4] += d2[4]; /* rebin fractions */ } static int found = 0; int reduce_func(void * v, int k) { void * h; Jval key; JRB bn; int i; /* * the input contains k items * starting at the address pointed to by v */ /*printf("reduce_func running\n");*/ #if 0 write(1, v, k*ITEMSIZE); return 0; #endif for (i = 0; i < k; v += ITEMSIZE, i ++) { key.v = v; bn = jrb_find_gen(b, key, cmp); if (bn == NULL) { h = dml_append(dm, v, ITEMSIZE); key.v = h; jrb_insert_gen(b, key, key, cmp); } else { h = jval_v(bn->val); accumulate_counts(h, v); found ++; } } return 0; } int reduce_done(int nd) { /* nd == 1 -- TRUE, no factorial division */ /* nd == 0 -- FALSE, do fatorial division */ JRB bn; void * v; char * c; int * ip; double * dp; double totalvolume = 0.; int nvox = 0; jrb_traverse(bn, b) { v = jval_v(bn->key); ip = v; c = v; dp = (double *)(c+sizeof(int)*4); /*if (dp[0] > 1e-16)*/ { dp[4] *= volumescale; if (nd == 0) { dp[0] /= dp[4]; dp[1] /= dp[4]; } /* dp[0] /= volumescale; */ totalvolume += dp[0]; if (nd == 0) gmesh_singlebin_output(dp, ip[0], ip[1], ip[2], ip[3], orig, spacing); else gmesh_singlebin_output_nd(dp, ip[0], ip[1], ip[2], ip[3], orig, spacing); nvox ++; } /*write(1, v, ITEMSIZE);*/ } fprintf(stderr, "no. nonempty bins : %d\n", nvox); fprintf(stderr, "recorded total cnt : %le\n", totalvolume*spacing[0]*spacing[1]*spacing[2]); /*fprintf(stderr, "volumescale : %le\n", volumescale);*/ free_dmlist(dm); jrb_free_tree(b); return 0; } <file_sep>/binner/src/serve.c /** \ingroup rebinner_sdk \file src/serve.c \brief CURRENT sdk executable to serve sockets in distributed rebinner runs. Slight customization by <NAME>. $Id$ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> #include "socketfun.h" #define fullsz 4*1024*1024 char s[fullsz]; float fastinout(int in, int out) { int i, l; float c; i = 0; l = 0; c = 0; while((l = read(in, s+i, fullsz))!= 0) { i += l; if (i > 1024*1024) { write(out, s, i); c += i; i = 0; } } write(out, s, i); c += i; return c; } int inout(int in, int out) { int i, l; i = 0; l = 0; while(read(in, s+i, 1) != 0) { if (s[i] == '\n') { write(out, s, i+1); l ++; i = 0; } else i++; } write(out, s, i); return l; } int main(int argc, char **argv) { char *hn; int port, sock, fd; float i; clock_t time1, time2; float t; if (argc != 3) { fprintf(stderr, "usage: %s hostname port\n",argv[0]); exit(1); } hn = argv[1]; port = atoi(argv[2]); if (port < 5000) { fprintf(stderr, "usage: %s hostname port\n",argv[0]); fprintf(stderr, " port must be > 5000\n"); exit(1); } sock = serve_socket(hn, port); fprintf(stderr, "server running on : %s\n", hn); fprintf(stderr, "port number : %d\n", port); fd = accept_connection(sock); time1 = clock(); i = fastinout(fd, 1); time2 = clock(); t = (float)(time2-time1)/CLOCKS_PER_SEC; fprintf(stderr, "number of bytes read: %.0f\n", i); fprintf(stderr, "time spent : %.2f seconds\n", t); fprintf(stderr, "input bandwidth : %8.4f MB/second\n", (float)i/t/1e6f); return 0; } <file_sep>/binner/src/tran3d.c /** \ingroup rebinner_tests \file src/tran3d.c \brief CURRENT test of core API -- binnerio.h and using vcb $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binnerio.h" int main(int argc, char ** argv) { int nfacets, i, n; float mat[16], v0[4], v1[4], t[3]; float vdata[1024], * v; t[0] = (float)atof(argv[1]); t[1] = (float)atof(argv[2]); t[2] = (float)atof(argv[3]); vcbTranslate3fv(mat, t); v0[3] = 1.f; /* v = malloc(nfacets * 4 * 3 * sizeof(float));*/ for (nfacets = 0; (n = get_polygonf(vdata)) > 0; nfacets ++) { printf("%d ", n); for (i = 0, v = vdata; i < n; v+= 3, i ++) { v0[0] = v[0]; v0[1] = v[1]; v0[2] = v[2]; vcbMatMult4fv(v1, mat, v0); printvertexf(v1, 3); } printf("\n"); } /*printf("%d \n", nfacets);*/ return nfacets; } <file_sep>/binner/script/gmesh_correctness_test.sh #!/bin/bash #test 1 echo -n "test 1: " map -n 2 gmeshrebin3 -f 0.0 2.0 2.0 0.0 6.0 2.0 0.0 6.0 2.0 < ../data/reuter_input.inb 2>&1 | grep "total cnt" #test 2 echo -n "test 2: " map -n 2 gmeshrebin3 -f 0.0 2.0 1.0 0.0 6.0 2.0 0.0 6.0 2.0 < ../data/reuter_input.inb 2>&1 | grep "total cnt" #test 3 echo -n "test 3: " map -n 2 gmeshrebin3 -f 0.0 2.0 2.0 0.0 6.0 3.0 0.0 6.0 3.0 < ../data/reuter_input.inb 2>&1 | grep "total cnt" #test 4 echo -n "test 4: " map -n 2 gmeshrebin3 -f 0.0 2.0 1.0 0.0 6.0 3.0 0.0 6.0 3.0 < ../data/reuter_input.inb 2>&1 | grep "total cnt" #test 5 echo -n "test 5: " map -n 2 gmeshrebin3 -f 0.0 2.0 2.0 0.0 6.0 3.0 0.0 6.0 6.0 < ../data/reuter_input.inb 2>&1 | grep "total cnt" <file_sep>/binner/src/bslicer.c /** \ingroup rebinner_tests \file src/bslicer.c $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "vcbimage.h" #include "vcbutils.h" #define MAXDIMS 4 int main(int argc, char ** argv) { vcbdatatype datatype; int ndims, nattribs, imgsz[2]; int orig[MAXDIMS], dsize[MAXDIMS]; int lb[MAXDIMS], ub[MAXDIMS]; double * rawdata; double minval, maxval, pixel; int slice_dim, slice_no, nval; unsigned char * img; int i, j, k, l, m; if (argc != 6) { fprintf(stderr, "usage: %s dataset slice_dim slice_id minval maxval\n", argv[0]); return -1; } slice_dim = atoi(argv[2]); slice_no = atoi(argv[3]); minval = atof(argv[4]); maxval = atof(argv[5]); /*printf("minval maxval: %lf %lf\n", minval, maxval);*/ /* input */ rawdata = vcbReadBinm(argv[1], &datatype, &ndims, orig, dsize, &nattribs); if (rawdata == NULL) { perror("problem with loading data"); exit(-1); } /*printf("%u %u \n", rawdata[1], rawdata[301]);*/ if (nattribs != 1) { fprintf(stderr, "%s will slice the first attribute of %d attributes in %s\n", argv[0], nattribs, argv[1]); } if (datatype != VCB_DOUBLE) { fprintf(stderr, "%s can only handle data of unsigned int type\n", argv[0]); free(rawdata); exit(-1); } for (i = 0; i < ndims; lb[i] = 0, ub[i] = dsize[i] - 1, i ++); lb[slice_dim] = ub[slice_dim] = slice_no; printf("dsize (%d,%d,%d). ", dsize[0],dsize[1],dsize[2]); printf("slice (%d,%d,%d) - ", lb[0], lb[1], lb[2]); printf("(%d,%d,%d). ", ub[0], ub[1], ub[2]); /*for (i = 0; i < ndims; printf("%d %d ",lb[i],ub[i]), i ++);*/ for (i = 0, nval = 1; i < ndims; nval *= (ub[i]-lb[i]+1), i ++); printf("%d pixels\n", nval); img = malloc(nval*3); if (img == NULL) { perror("problem allocating img"); exit(-1); } m = 0; for (i = lb[0]; i <= ub[0]; i ++) for (j = lb[1]; j <= ub[1]; j ++) for (k = lb[2]; k <= ub[2]; k ++) { l = (i * dsize[1] + j) * dsize[2] + k; pixel = (rawdata[l*nattribs]-minval)*255/(maxval-minval); if (pixel < 0) pixel = 0; if (pixel > 255) pixel = 255; img[m*3] = img[m*3+1] = img[m*3+2] = (unsigned char)pixel; m ++; } for (i = 0, j = 0; i < ndims; i ++) { if (i != slice_dim) { imgsz[j] = dsize[i]; j ++; } if (j > 1) break; } /* output */ vcbImgWriteBMP("bslice.bmp", img, 3, imgsz[1], imgsz[0]); free(img); free(rawdata); return 0; } <file_sep>/binner/vcb/src/makefile SHELL = /bin/sh LIBNAME = vcb RM = /bin/rm AR = ar cq TOP = .. C++ = g++ CC = gcc ifeq ($(BUILD),debug) CCFLAGS := -g else CCFLAGS := -O3 #CCFLAGS := -pg endif INCLUDE = -I. -I../include -I../Task -I/usr/include/GL LIBS = -lm OBJS = dllist.o jval.o jrb.o dmem.o exhash.o fields.o hilbert.o intersect.o kernel.o nr.o nrcomplex.o nrutil.o raycasting.o vcbdebug.o vcbfitting.o vcbimage.o vcblinalg.o vcbmath.o vcbmcube.o vcbops.o vcbspcurve.o vcbtrimesh.o vcbutils.o vcbvolren.o zcurve.o vcbcolor.o vbutrcast.o vcblic.o Lic.o slic.o slic_aux.o .SUFFIXES: .cc .c .cpp .cc.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .cpp.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .c.o: $(CC) $(CCFLAGS) $(INCLUDE) -c $< all: lib$(LIBNAME).a dynamic: lib$(LIBNAME).so lib$(LIBNAME).a : $(OBJS) $(RM) -f $@ # libtool -static -o $@ $(OBJS) $(AR) $@ $(OBJS) mv $@ ../lib lib$(LIBNAME).so : $(OBJS) $(RM) -f $@ ld -G $(OBJS) -o $@ clean: rm -f *.o *.a *~ <file_sep>/binner/src/seeall.cpp #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <string.h> #include <time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbmath.h" #include "vcbglutils.h" #include "vcblinalg.h" #include "vcbmcube.h" #include "vcbimage.h" #include "binnerio.h" #include "atypes.h" /** * $Id$ * */ char projmode = 'O'; /* P for perspective, O for orthogonal */ projStruct proj; viewStruct view; lightStruct light0; ArcBall spaceball; int iwinWidth; int iwinHeight; int mainwin, sidewin; /* application specific data starts here */ int nverts, nfacets; float vdata[1024]; /* end of application specific data */ bbox abbox; char inputbuf[1024]; int list_id; void display (void) { int i; spaceball.Update(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(view.center[0],view.center[1],view.center[2]); glMultMatrixf(spaceball.GetMatrix()); glTranslated(-view.center[0],-view.center[1],-view.center[2]); /* if want wireframe mode, then use the following */ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glClear(GL_COLOR_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT); glCallList(list_id); vcbDrawAxis(spaceball.GetMatrix(), 100); glPopMatrix(); glutSwapBuffers(); } void cleanup (void) { printf("done with app clean up, ogl version %2.1f ...\n",vcbGetOGLVersion()); fflush(stdout); } int main(int argc, char ** argv) { vcbdatatype dtype; int i, n, ndims, orig, nvals, dummy; mainwin = initGLUT(argc,argv); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr,"glew error, initialization failed\n"); fprintf(stderr,"Glew Error: %s\n", glewGetErrorString(err)); } abbox.low[0] = abbox.low[1] = abbox.low[2] = 1e6; abbox.high[0] = abbox.high[1] = abbox.high[2] = -1e6; list_id = glGenLists(1); glNewList(list_id, GL_COMPILE); for (nfacets = 0; (n = get_polygonf(vdata)) > 0; nfacets ++) { for (i = 0; i < n; i ++) { abbox.low [0] = VCB_MINVAL(abbox.low [0],vdata[i*3]); abbox.high[0] = VCB_MAXVAL(abbox.high[0],vdata[i*3]); abbox.low [1] = VCB_MINVAL(abbox.low [1],vdata[i*3+1]); abbox.high[1] = VCB_MAXVAL(abbox.high[1],vdata[i*3+1]); abbox.low [2] = VCB_MINVAL(abbox.low [2],vdata[i*3+2]); abbox.high[2] = VCB_MAXVAL(abbox.high[2],vdata[i*3+2]); } glBegin(GL_POLYGON); for (i = 0; i < n; i ++) glVertex3fv(&vdata[i*3]); glEnd(); } glEndList(); printf("bounding box: (%f %f %f) (%f %f %f)\n",abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); initApp(); /* initialize the application */ initGLsettings(); atexit(cleanup); glutKeyboardFunc(keys); //glColor4f(0.7038f, 0.27048f, 0.0828f, 1.0f); glColor4f(1.f, 1.f, 1.f, 1.0f); glutMainLoop(); return 0; } <file_sep>/binner/include/socketfun.h /** \file include/socketfun.h \brief <NAME>'s socket functions. Released as "do whatever you want with it". Slight customization by <NAME>. $Id$ */ #ifndef _SOCKETFUN_ #define _SOCKETFUN_ #ifdef __cplusplus extern "C" { #endif /* * keep polling for an open socket * after success, serve the socket and output on stdout the following line * sorterserver_setup: serving socket id. 6000 * * assuming the socket opened is numbered 6000 * * this routine continues to randomly poke for an open port in the * 4k port numbers starting from 6000 * the final port number in use is returned as *pn * * return -1 for failure */ int server_setup(char * dn, int * pn); int serve_socket(char *hn, int port); /* This serves a socket at the given host name and port number. It returns an fd for that socket. Hn should be the name of the server's machine. */ int accept_connection(int s); /* This accepts a connection on the given socket (i.e. it should only be called on by the server. It returns the fd for the connection. This fd is of course r/w */ int request_connection(char *hn, int port); /* This is what the client calls to connect to a server's port. It returns the fd for the connection. */ #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/gmeshrot.c /** \ingroup rebinner_execs \file src/gmeshrot.c \brief DEPRECATED executable for rotating gmesh geometry. \deprecated due to input format change. $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binnerio.h" int main(int argc, char ** argv) { int nfacets, i, n, sliceid; float mat[16], v0[4], v1[4], axis[3], angle; float emin, emax, hitcnt, hiterr, corners[8][4]; axis[0] = (float)atof(argv[1]); axis[1] = (float)atof(argv[2]); axis[2] = (float)atof(argv[3]); angle = -(float)atof(argv[4]); vcbRotate3fv(mat, axis, angle); v0[3] = 1.f; /* v = malloc(nfacets * 4 * 3 * sizeof(float));*/ for (nfacets = 0; (n = get_pixel_energy(&sliceid,&emin,&emax,&hitcnt,&hiterr,corners)) > 0; nfacets ++) { printf("%d %f %f %f %f", sliceid, emin, emax, hitcnt, hiterr); for (i = 0; i < 8; i ++) { corners[i][3] = 1.f; vcbMatMult4fv(v1, mat, corners[i]); /*printvertexf(v1, 3);*/ printf(" %f %f %f", v1[0], v1[1], v1[2]); } printf("\n"); } /*printf("%d \n", nfacets);*/ return nfacets; } <file_sep>/binner/src/geometry.c /** \ingroup rebinner_core \file src/geometry.c \brief CURRENT core API -- implementation for geometry.h $Id$ */ #include "geometry.h" #include "vcblinalg.h" double dist_plane(double * normal, double * pnt, double * vert0) { double d; d = -(VCB_DOT(normal, vert0)); return (VCB_DOT(normal, pnt) + d); } double inside_prism(double * pnt, int n, double * normals, double * verts) { int i; for (i = 0; i < n; i ++) if (dist_plane(&normals[i*3], pnt, &verts[i*3]) > BINNER_EPSILON) return 0; return 1; } void cal_normal(double * n, double * v) { double v1[3], v2[3]; v1[0] = v[3] - v[0]; v1[1] = v[4] - v[1]; v1[2] = v[5] - v[2]; v2[0] = v[6] - v[0]; v2[1] = v[7] - v[1]; v2[2] = v[8] - v[2]; VCB_CROSS(n,v1,v2); } double vec_normalize(double * n) { double norm; norm = BINNER_NORM(n); if (norm < BINNER_EPSILON) { n[0] = n[1] = n[2] = 0.0; return 0.0; } else { n[0] /= norm; n[1] /= norm; n[2] /= norm; return norm; } } <file_sep>/binner/src/getfrom.c /** \ingroup rebinner_sdk \file src/getfrom.c \brief CURRENT sdk executable to stream input data from a network port. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <unistd.h> #include "socketfun.h" int main(int argc, char ** argv) { int sock; int i, n; static char netbuf[5000]; if (0 > (sock = request_connection(argv[1], atoi(argv[2])))) { /*perror("get: cannot get a connection");*/ exit(111); } for (n = 0; (i = read(sock, netbuf, 4096)) > 0; ) n += write(1, netbuf, i); fprintf(stderr,"wrote %d bytes.\n", n); close(sock); return 0; } <file_sep>/binner/script/uvtestc1 #!/usr/bin/env python # This script is made to run test case 1 on the RDAV UltraViolet machine. # This script will provide the option to extend test case 1 by running VisIt from __future__ import division import os VERSION = "1.0" NUM_SLICES = 160 ROTDATA_LOC = "800-rebin" ROTDATA_HEAD = "CNCS_800_rbmesh" ROTDATA_EXT = ".inb" LOGDIR = "logs" LOG_EXT = ".out" FILEFORMAT = "%s%04d%s" REBINNER_CMD = "gmeshrebin3 -f" MULTI_THREAD_REBINNER_CMD = "map -n %d " + REBINNER_CMD REBIN_GRID = [-1.6, 2.0, 0.01, -0.4, 0.4, 0.01, -0.1, 2.4, 0.01] REBINDATA_HEAD = "CNCS_800_rebin" REBINDATA_EXT = ".in" def format_time(jtime): if jtime < 60: return "%.1f seconds" % jtime else: if jtime < 3600: jtime /= 60 return "%.1f minutes" % jtime else: jtime /= 3600 return "%.1f hours" % jtime def make_cmd(opt, ibin, logloc): ifile = FILEFORMAT % (ROTDATA_HEAD, ibin, ROTDATA_EXT) ofile = FILEFORMAT % (REBINDATA_HEAD, ibin, REBINDATA_EXT) cmd = [] cmd.append("cat") cmd.append(os.path.join(opt.inputdir, ifile)) cmd.append("|") cmd.append(opt.rebin_cmd) cmd.extend(opt.grid) cmd.append(">") cmd.append(os.path.join(opt.outputdir, ofile)) return " ".join(cmd) def run(opts): # Create log file directory if necessary log_location = os.path.join(opts.outputdir, LOGDIR) if not os.path.exists(log_location): os.mkdir(log_location) proc_list = [] if opts.max_slice is not None: nslices = int(opts.max_slice) else: nslices = NUM_SLICES # Launch rebinning jobs import subprocess as sub import time start_time = None # Make things that only need to be done once opts.grid = [str(x) for x in REBIN_GRID] if opts.max_threads is not None: opts.threads = int(opts.max_threads / nslices) opts.rebin_cmd = MULTI_THREAD_REBINNER_CMD % opts.threads # Execute rebinning jobs for i in range(nslices): rcmd = make_cmd(opts, i, log_location) if opts.verbose > 1: print "Rebin Cmd:", rcmd if opts.verbose > 0: print "Executing Slice", i lfile = FILEFORMAT % (REBINDATA_HEAD, i, LOG_EXT) log_file = os.path.join(log_location, lfile) lfh = open(log_file, 'w') if i == 0: start_time = time.time() proc = sub.Popen(rcmd, stdout=lfh, stderr=lfh, shell=True) proc_list.append(proc) if opts.verbose > 0: print "PIDs:", [proc.pid for proc in proc_list] # Begin PID watch jobs_complete = False while not jobs_complete: status = [pid.poll() for pid in proc_list] if opts.verbose > 0: print "Status:", status try: index = status.index(None) time.sleep(30) except ValueError: jobs_complete = True print "Jobs Completed" # Determine success/fail criteria import dircache import stat loglist = [(os.stat(os.path.join(log_location, lfile))[stat.ST_MTIME], lfile) for lfile in dircache.listdir(log_location) \ if lfile.endswith(LOG_EXT)] loglist.sort() if opts.verbose > 0: print "Log Files Found:", loglist end_time = loglist[-1][0] job_time = end_time - start_time print "Total Running Time:", format_time(job_time) if __name__ == "__main__": import optparse description = [] description.append("This script launches test case 1 with option to run") description.append("VisIt extension.") parser = optparse.OptionParser("usage: %prog [options]", None, optparse.Option, VERSION, 'error', " ".join(description)) parser.add_option("-v", "--verbose", dest="verbose", action="count", help="Flag for turning on script verbosity") parser.add_option("-o", "--outputdir", dest="outputdir", help="Specify a directory to receive the rebinning "\ +"output. This location will also house the log files.") parser.add_option("-i", "--inputdir", dest="inputdir", help="Specify a directory to get the rebinning input.") parser.add_option("-t", "--threads", dest="threads", type=int, help="Flag to set the number of threads. Default is 1.") parser.set_defaults(threads=1) parser.add_option("-x", "--max-slice", dest="max_slice", help="Flag to set the maximum slice to use.") parser.add_option("", "--max-threads", dest="max_threads", type=int, help="Specify the maximum number of threads for the "\ +"given system.") (options, args) = parser.parse_args() if options.inputdir is None: parser.error("Please specify the directory for the input (rotated) "\ +"data files!") if options.outputdir is None: parser.error("Please specify the location to write the rebinned data!") run(options) <file_sep>/binner/src/rot3d.c /** \ingroup rebinner_tests \file src/rot3d.c \brief CURRENT test of core API -- binnerio.h and using vcb $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binnerio.h" int main(int argc, char ** argv) { int nfacets, i, n; float mat[16], v0[4], v1[4], axis[3], angle; float vdata[1024], * v; axis[0] = (float)atof(argv[1]); axis[1] = (float)atof(argv[2]); axis[2] = (float)atof(argv[3]); angle = (float)atof(argv[4]); vcbRotate3fv(mat, axis, angle); v0[3] = 1.f; /* v = malloc(nfacets * 4 * 3 * sizeof(float));*/ for (nfacets = 0; (n = get_polygonf(vdata)) > 0; nfacets ++) { printf("%d ", n); for (i = 0, v = vdata; i < n; v+= 3, i ++) { v0[0] = v[0]; v0[1] = v[1]; v0[2] = v[2]; vcbMatMult4fv(v1, mat, v0); printvertexf(v1, 3); } printf("\n"); } /*printf("%d \n", nfacets);*/ return nfacets; } <file_sep>/binner/src/binnerio.c /** \ingroup rebinner_core \file src/binnerio.c \brief CURRENT core API -- implementation for binnerio.h $Id$ */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "binnerio.h" #include "vcbutils.h" void printvertexf(float *v, int ndim) { int i; assert(ndim <= 4); for (i = 0; i < ndim; printf("%f ",v[i]), i ++); } void printvertexd(double *v, int ndim) { int i; assert(ndim <= 4); for (i = 0; i < ndim; printf("%f ",(float)(v[i])), i ++); } int getquada3d(float * vdata) /* * return value: num_vertices read in successfully * -1 on failure * getquad_a_: 'a' for ascii */ { int i; /* assume a quad in 3d space. 4 vertices, x-y-z coord each */ for (i = 0; i < 4; scanf("\n"), vdata += 3, i ++) if (3 > scanf("%f %f %f", &vdata[0], &vdata[1], &vdata[2])) break; return i; } int binnerin3d(int nfacets, float *vdata) { int i; for (i = 0; i < nfacets; i ++) getquada3d(&vdata[i*4*3]); return nfacets; } void binnerout3d(int nfacets, float *v) { int i, j; for (i = 0; i < nfacets; i ++) { for (j = 0; j < 4; j ++) printvertexf(&v[i*4*3+j*3], 3); printf("\n"); } } int get_polygonf(float * v) /* * return value: num_vertices actually read in successfully */ { int i, n; if (scanf("%d", &n) <= 0) return -1; /* assume a quad in 3d space. 4 vertices, x-y-z coord each */ for (i = 0; i < n; v += 3, i ++) if (3 > scanf("%f %f %f", v, v+1, v+2)) break; scanf("\n"); return i; } int get_pixelf(int * id, float * cnt, float * err, float (* v)[4]) /* * always read in 8 vertices and 3 preceding values: sliceID, cnt, err * return value: num_vertices actually read in successfully */ { int i; if (scanf("%d", id) <= 0) return -1; if (scanf("%f", cnt) <= 0) return -1; if (scanf("%f", err) <= 0) return -1; /* assume a 8 vertices, x-y-z coord each */ for (i = 0; i < 8; v ++, i ++) { if (3 > scanf("%f %f %f", &v[0][0], &v[0][1], &v[0][2])) break; v[0][3] = 0.f; } scanf("\n"); return i; } int get_pixel_energy(int * id, float * emin, float * emax, float * cnt, float * err, float (* v)[4]) /* * always read in 8 vertices and 3 preceding values: sliceID, cnt, err * return value: num_vertices actually read in successfully */ { int i; /* if (scanf("%d", id) <= 0) return -1; if (scanf("%f", emin) <= 0) return -1; if (scanf("%f", emax) <= 0) return -1; if (scanf("%f", cnt) <= 0) return -1; if (scanf("%f", err) <= 0) return -1; */ if (scanf("%d %f %f %f %f", id, emin, emax, cnt, err) <= 0) return -1; /* assume a 8 vertices, x-y-z coord each */ for (i = 0; i < 8; v ++, i ++) { if (3 > scanf("%f %f %f", &v[0][0], &v[0][1], &v[0][2])) break; v[0][3] = 0.f; } scanf("\n"); return i; } int binnerin_phcf(int nfacets, int * nverts, float * v) { int i, total; total = 0; for (i = 0; i < nfacets; v += nverts[i]*3, i ++) { nverts[i] = get_polygonf(v); total += nverts[i]; } return total; } int get_polygond(double * v) /* * return value: num_vertices actually read in successfully */ { int i, n; scanf("%d", &n); /* assume a quad in 3d space. 4 vertices, x-y-z coord each */ for (i = 0; i < n; v += 3, i ++) if (3 > scanf("%lf %lf %lf", v, v+1, v+2)) break; scanf("\n"); return i; } int binnerin_phcd(int nfacets, int * nverts, double * v) { int i, total; total = 0; for (i = 0; i < nfacets; v += nverts[i]*3, i ++) { nverts[i] = get_polygond(v); total += nverts[i]; } return total; } void binnerout_phcf(int nfacets, int * nverts, float *v) { int i, j; for (i = 0; i < nfacets; i ++) { printf("%d ", nverts[i]); for (j = 0; j < nverts[i]; j ++) { printvertexf(v, 3); v += 3; } printf("\n"); } } void binnerout_phcd(int nfacets, int * nverts, double *v) { int i, j; for (i = 0; i < nfacets; i ++) { printf("%d ", nverts[i]); for (j = 0; j < nverts[i]; j ++) { printvertexd(v, 3); v += 3; } printf("\n"); } } int output_with_compression(char * fname, int * sz, double * vol) { int i, j, k, nvox; double * dvol; unsigned int * hash; unsigned short * xyz; int ori[3], size[3]; char fullname[256]; nvox = 0; for (i = 0; i < sz[0]; i ++) for (j = 0; j <sz[1]; j ++) for (k = 0; k <sz[2]; k ++) { if (vol[((i * sz[1] + j)*sz[2] + k)*2] > 1e-16) nvox ++; } dvol = malloc(nvox * sizeof(double) * 2); hash = malloc(sz[0]*sz[1]*sizeof(int)); xyz = malloc(nvox * 3 * sizeof(unsigned short)); nvox = 0; for (i = 0; i < sz[0]; i ++) for (j = 0; j <sz[1]; j ++) { hash[i * sz[1] + j] = nvox; for (k = 0; k <sz[2]; k ++) { if (vol[(i * sz[1] + j)*sz[2] + k] > 1e-16) { dvol[nvox*2] = vol[((i * sz[1] + j)*sz[2] + k)*2]; dvol[nvox*2+1] = vol[((i * sz[1] + j)*sz[2] + k)*2 + 1]; xyz[nvox*3+0] = (unsigned short)(i); xyz[nvox*3+1] = (unsigned short)(j); xyz[nvox*3+2] = (unsigned short)(k); nvox ++; } } } ori[0] = ori[1] = ori[2] = 0; size[0] = nvox; sprintf(fullname, "%s.bin", fname); vcbGenBinm(fullname, VCB_DOUBLE, 1, ori, size, 2, dvol); /* sprintf(fullname, "%s.bin", fname); vcbGenBinm(fullname, VCB_UNSIGNEDINT, 2, ori, sz, 1, hash); */ sprintf(fullname, "%s.bin", fname); vcbGenBinm(fullname, VCB_UNSIGNEDSHORT, 1, ori, size, 3, xyz); free(dvol); free(hash); free(xyz); return nvox; } void export_VTKvol(char * fname, double * orig, int * sz, double * cellsize, double * vol) { FILE * fp; char fullname[256]; int i, j, k; double val; float * cvol; sprintf(fullname, "%s.vtk", fname); fp = fopen(fullname, "w"); fprintf(fp, "# vtk DataFile Version 2.0\n"); fprintf(fp, "rebinned Qxyz histogram %s\n", fname); fprintf(fp, "BINARY\n"); fprintf(fp, "DATASET STRUCTURED_POINTS\n"); fprintf(fp, "DIMENSIONS %d %d %d\n", sz[0], sz[1], sz[2]); /*fprintf(fp, "ASPECT_RATIO 1.0 1.0 1.0\n");*/ fprintf(fp, "ORIGIN %e %e %e\n",orig[0], //*cellsize[0], orig[1], //*cellsize[1], orig[2]); //*cellsize[2]); fprintf(fp, "SPACING %e %e %e\n", cellsize[0], cellsize[1], cellsize[2]); fprintf(fp, "POINT_DATA %d\n", sz[0]*sz[1]*sz[2]); fprintf(fp, "SCALARS scalars float\n"); fprintf(fp, "LOOKUP_TABLE default\n"); cvol = malloc(sizeof(float)*sz[0]*sz[1]*sz[2]); for (i = 0; i < sz[0]; i ++) for (j = 0; j <sz[1]; j ++) for (k = 0; k <sz[2]; k ++) { /* val = log10(vol[(i * sz[1] + j) * sz[2] +k]); val += 16; val *= 16; if (val < 0) val = 0; */ val = vol[(i * sz[1] + j) * sz[2] +k]; cvol[(k * sz[1] + j) * sz[0] +i] = (float)val; } for (i = 0; i < sz[0]*sz[1]*sz[2]; i ++) vcbToggleEndian(cvol+i, sizeof(float)); fwrite(cvol, sizeof(float), sz[0]*sz[1]*sz[2], fp); free(cvol); fclose(fp); } void export_VTKhdr(char * fname, int * orig, int * sz, double * cellsize, int nonempty) { FILE * fp; char fullname[256]; sprintf(fullname, "%s/run.hdr", fname); fp = fopen(fullname, "w"); fprintf(fp, "REBINNED Qxyz HISTOGRAM\n%s\n", fname); fprintf(fp, "DIMENSIONS %d %d %d\n", sz[0], sz[1], sz[2]); fprintf(fp, "ORIGIN %e %e %e\n",orig[0]*cellsize[0], orig[1]*cellsize[1], orig[2]*cellsize[2]); fprintf(fp, "SPACING %e %e %e\n", cellsize[0], cellsize[1], cellsize[2]); fprintf(fp, "NUMBER OF BINS %d\n", sz[0]*sz[1]*sz[2]); fprintf(fp, "Total NUMBER OF NONEMPTY BINS IN ALL SLICES %d\n", nonempty); fprintf(fp, "BINARY FLOAT VOLUME REQUIRES %d byes\n", (int)(sz[0]*sz[1]*sz[2]*sizeof(float))); fclose(fp); } <file_sep>/binner/src/export2vcb.c /** \ingroup rebinner_sdk \file src/export2vcb.c \brief CURRENT sdk executable to convert gmesh to vcb geometry format. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include "vcbutils.h" #include "binnerio.h" #include "binner.h" int main(int argc, char ** argv) { FILE * hdr; char fullname[256], dataname[256], idstring[10]; double orig[3], spacing[3]; int i, j, k, n, sz[3]; double * dvol, * vol; unsigned short * coord; vcbdatatype rawdatatype; int dims[3], ori[3], dsize[3], nattribs; printf("exporting from directory: %s\n", argv[1]); sprintf(fullname, "%s/run.hdr", argv[1]); hdr = fopen(fullname, "r"); fscanf(hdr, "REBINNED Qxyz HISTOGRAM\n%s\n", dataname); fscanf(hdr, "DIMENSIONS %d %d %d\n", &sz[0], &sz[1], &sz[2]); fscanf(hdr, "ORIGIN %lf %lf %lf\n", &orig[0], &orig[1], &orig[2]); fscanf(hdr, "SPACING %lf %lf %lf\n", &spacing[0], &spacing[1], &spacing[2]); fclose(hdr); vol = malloc(sz[0]*sz[1]*sz[2]*sizeof(double)); for (i = 0; i < sz[0]*sz[1]*sz[2]; vol[i] = 0.0, i ++); printf("sliceid to include: "); for ( ; fscanf(stdin, "%s", idstring) > 0; printf("sliceid to include (CNTL-D to end): ")) { sprintf(fullname, "%s/%s.bin.d", argv[1], idstring); dvol = vcbReadBinm(fullname, &rawdatatype, dims, ori, dsize, &nattribs); if (dvol == NULL) continue; sprintf(fullname, "%s/%s.bin.us", argv[1], idstring); printf("opening %s\n", fullname); coord = vcbReadBinm(fullname, &rawdatatype, dims, ori, dsize, &nattribs); if (coord == NULL) continue; printf("loading slice %s under %s\n",idstring, argv[1]); for (n = 0; n < dsize[0]; n ++) { i = coord[n*3 + 0]; j = coord[n*3 + 1]; k = coord[n*3 + 2]; vol[(i * sz[1] + j) * sz[2] +k] = dvol[n]; printf("vol(%d,%d,%d) = %lf\n", i, j, k, dvol[n]); } free(dvol); free(coord); } for (i = 0, j = 0; i < sz[0]*sz[1]*sz[2]; i ++) if (vol[i] > 1e-16) j ++; sprintf(fullname, "%s/combined", argv[1]); output_with_compression(fullname, sz, vol); //vcbGenBinm(fullname, VCB_DOUBLE, 3, ori, sz, 1, vol); printf("\n\nVolume saved to %s.bin\n", fullname); printf("Domain size %d %d %d\n", sz[0], sz[1], sz[2]); printf("Domain origin %e %e %e\n", orig[0], orig[1], orig[2]); printf("Domain spacing %e %e %e\n", spacing[0], spacing[1], spacing[2]); printf("Num non-empty voxels %d\n", j); printf("Num of all voxels %d\n", i); printf("Non-empty percentage %.2f%%\n", (float)j/i*100); return 0; } <file_sep>/binner/src/bounds.c /** \ingroup rebinner_tests \file src/bounds.c \brief CURRENT test of core API -- binnerio.h. Outputs bounds of a gmesh. $Id$ */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <string.h> #include <sys/time.h> #include "atypes.h" #include "cell.h" #include "binnerio.h" #include "vcbutils.h" /* application specific data starts here */ int nverts, npara; float vdata[1024]; /* end of application specific data */ bbox abbox; char inputbuf[1024]; int list_id; float xmin, xmax, ymin, ymax; int main(int argc, char ** argv) { int i, n; int sliceid; float hitcnt, hiterr, corners[8][4]; abbox.low[0] = abbox.low[1] = abbox.low[2] = 1e6; abbox.high[0] = abbox.high[1] = abbox.high[2] = -1e6; for (npara = 0; (n = get_pixelf(&sliceid,&hitcnt,&hiterr,corners)) > 0; ) { correctCornersf3d(corners, NULL); realCubef(corners, vdata); for (i = 0; i < 6*4; i ++) { abbox.low [0] = VCB_MINVAL(abbox.low [0],vdata[i*4]); abbox.high[0] = VCB_MAXVAL(abbox.high[0],vdata[i*4]); abbox.low [1] = VCB_MINVAL(abbox.low [1],vdata[i*4+1]); abbox.high[1] = VCB_MAXVAL(abbox.high[1],vdata[i*4+1]); abbox.low [2] = VCB_MINVAL(abbox.low [2],vdata[i*4+2]); abbox.high[2] = VCB_MAXVAL(abbox.high[2],vdata[i*4+2]); } npara ++; if (argc > 1) if (npara % 50000 == 0) { printf("number of parallelipeds = %d\n",npara); printf("bounding box: (%f %f %f) (%f %f %f)\n", abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); } } printf("number of parallelipeds = %d\n",npara); printf("bounding box: (%f %f %f) (%f %f %f)\n",abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); return 0; } <file_sep>/binner/src/makefile # # $Id$ # SHELL = /bin/sh RM = /bin/rm AR = ar cq TOP = .. C++ = g++ CC = gcc ifeq ($(BUILD),debug) CCFLAGS := -ggdb -Wall else CCFLAGS := -O3 #CCFLAGS := -pg endif INCLUDE = -I. -I$(TOP)/include -I$(TOP)/vcb/include LIB_PATH = -L$(TOP)/vcb/lib -L/sw/lib LIBS = -lpthread -lvcbnogl -lm EXES = gmeshindex gmeshquery gmeshrebin gmeshrebin2 gmeshrebin3 gmeshrot gmeshrot2 gmeshrot3 gmeshb2t gmesht2b gmeshorderv bmeshrebin largebmeshrebin bounds bslicer clip3d clipvoxel compvol export2vtk export2vcb gencell pix2mesh rebin rot3d rotmat scale3d tran3d collector getfrom giveto reduce serve netrebin sorter counts map gmeshmat .SUFFIXES: .cc .c .cpp .cc.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .cpp.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .c.o: $(CC) $(CCFLAGS) $(INCLUDE) -c $< all: $(EXES) sorter: sorter.o socketfun.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) netrebin: netrebin.o socketfun.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) getfrom: getfrom.o socketfun.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) giveto: giveto.o socketfun.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) reduce: reduce.o reducefunc.o rebinapp.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) map: map.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) serve: serve.o socketfun.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) collector: collector.o socketfun.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) pix2mesh: pix2mesh.o cell.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gencell: gencell.o cell.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) rot3d: rot3d.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) rotmat: rotmat.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrot: gmeshrot.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrot2: gmeshrot2.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrot3: gmeshrot3.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshmat: gmeshmat.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshorderv: gmeshorderv.o cell.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmesht2b: gmesht2b.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshb2t: gmeshb2t.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) tran3d: tran3d.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) scale3d: scale3d.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) clip3d: clip3d.o clip.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) clipvoxel: clipvoxel.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) compvol: compvol.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) rebin: rebin.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) bounds: bounds.o cell.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) counts: counts.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) bmeshrebin: bmeshrebin.o rebinapp.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrebin: gmeshrebin.o rebinapp.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrebin2: gmeshrebin2.o rebinapp.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshrebin3: gmeshrebin3.o rebinapp.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshindex: gmeshindex.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) gmeshquery: gmeshquery.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) largebmeshrebin: largebmeshrebin.o binner.o voxelize.o volume.o clip.o cell.o geometry.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) export2vtk: export2vtk.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) export2vcb: export2vcb.o binnerio.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) bslicer: bslicer.o $(CC) -o $@ $^ $(LIB_PATH) $(LIBS) install: all mv $(EXES) $(TOP)/bin clean: rm -f *.o $(EXES) *.a *~ <file_sep>/binner/script/rebinall.sh #!/bin/bash #rebinall.sh 10 , i.e. want 10 parallel threads TOP=.. count=0; nd=`hostname` # node echo "machinename $nd" sorterproc="${TOP}/bin/sorter" rebinproc="${TOP}/bin/netrebin" collectorproc="${TOP}/bin/collector" from="${TOP}/bin/getfrom" to="${TOP}/bin/giveto" getport() { # wait for $pnumfile to be created while [ ! -e $1 ] || [ ! -s $1 ] do : done # read from $pnumfile and then remove it read $2 < $1 rm $1 } pnumfile=sorterport.num ${sorterproc} $nd < ${TOP}/tests/v750a & getport $pnumfile sp pnumfile=collectorport.num ${collectorproc} 300 300 300 $nd & getport $pnumfile cp #echo "sp $sp cp $cp" # # main task starts here # by now, both sorter and collector should be up. let's run netrebin # # function start_child() { ${TOP}/script/rebinone.sh $nd $sp $cp & } for ((i=1; i <= $1; i++)) do start_child; done wait echo "rebinall exiting " exit 0 <file_sep>/binner/include/reducefunc.h /** \ingroup rebinner_sdk \file include/reducefunc.h \brief CURRENT sdk API for controlling map/reduce functions. $Id$ */ #ifndef _REDUCEFUNC_ #define _REDUCEFUNC_ #ifdef __cplusplus extern "C" { #endif int reduce_init(int argc, char ** argv); /* * the input contains k items * starting at the address pointed to by v * * return -1 to indicate that this reduction function * has failied */ int reduce_func(void * v, int k); int reduce_done(int nd); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/seegmesh.cpp /** \ingroup rebinner_execs \file src/seegmesh.cpp \brief CURRENT executable of rebinner that renders a gmesh. usage: \code UNIX> cat ASCII_gmesh | seegmesh UNIX> cat BINARY_gmesh | gmeshb2t | seegmesh \endcode \note This is executable does not behave as a filter. It starts rendering only after detecting end of file on input (STDIN). $Id$ */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <string.h> #include <sys/time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbmath.h" #include "vcbglutils.h" #include "vcblinalg.h" #include "vcbmcube.h" #include "vcbimage.h" #include "cell.h" #include "binnerio.h" #include "atypes.h" #include "vcbcolor.h" char projmode = 'O'; /* P for perspective, O for orthogonal */ projStruct proj; viewStruct view; lightStruct light0; ArcBall spaceball; int iwinWidth; int iwinHeight; int mainwin, sidewin; extern int wireframe; /* application specific data starts here */ int nverts, npara; float vdata[1024]; /* end of application specific data */ bbox abbox; char inputbuf[1024]; int list_id; /* nframes and fps are used for calculating frame rates in formain.cpp:idle() */ extern int nframes; extern float fps; /* texture to hold grid info */ #define gridtexsz 32 static float gridtex[gridtexsz*gridtexsz]; static int gtex; float xmin, xmax, ymin, ymax; extern int ncuts; void makeGrid(void) { int i, j, k; for (k = 0; k < gridtexsz/2; k ++) for (i = k; i < gridtexsz-k; i ++) for (j = k; j < gridtexsz-k; j ++) { gridtex[i*gridtexsz+j] = (gridtexsz/2.f - k)/(gridtexsz/2.f)*0.3; } xmin = view.center[0]+5*proj.xmin; ymin = view.center[1]+5*proj.ymin; xmax = view.center[0]+5*proj.xmax; ymax = view.center[1]+5*proj.ymax; } extern float mradius; void drawGrid(void) { float divfac = ncuts/mradius; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBegin(GL_QUADS); glColor3f(0.774597, 0.774597, 0.774597); glTexCoord2f(xmin*divfac, ymin*divfac); //0.f, 0.f); glVertex2f(xmin, ymin); glTexCoord2f(xmin*divfac, ymax*divfac); //0.f, 1.f); glVertex2f(xmin, ymax); glTexCoord2f(xmax*divfac, ymax*divfac); //1.f, 1.f); glVertex2f(xmax, ymax); glTexCoord2f(xmax*divfac, ymin*divfac); //1.f, 0.f); glVertex2f(xmax, ymin); glEnd(); glDisable(GL_TEXTURE_2D); } float tlut[256*4]; void drawCLUT() { float x, y, xs, ys; int i; glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_1D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0., 1., 0., 1., -1., 1.); /* end set up */ x = 0.9;//(proj.xmax - proj.xmin)*0.95f + proj.xmin; xs = 0.05;//(proj.xmax - proj.xmin)*0.05f; y = 0.05;//proj.ymin + (proj.ymax - proj.ymin)*0.1; ys = 0.9/256;//(proj.ymax - proj.ymin)*0.9/256; glBegin(GL_QUADS); for (i = 0; i < 256; i ++) { glColor4fv(&tlut[i*4]); glVertex3f(x, y+i*ys, .95f); // Bottom Left glVertex3f(x+xs, y+i*ys, .95f); // Bottom Right glVertex3f(x+xs, y+(i+1)*ys, .95f); // Top Right glVertex3f(x, y+(i+1)*ys, .95f); // Top Left } glEnd(); /* restore opengl state machine */ glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); //vcbDrawAxis(spaceball.GetMatrix(), 100); //vcbOGLprint(0.01f,0.01f, 1.f, 1.f, 0.f, echofps); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_1D); } void display (void) { char echofps[80]; int i; glClear(GL_COLOR_BUFFER_BIT); drawGrid(); glClear(GL_DEPTH_BUFFER_BIT); spaceball.Update(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(view.center[0],view.center[1],view.center[2]); glMultMatrixf(spaceball.GetMatrix()); glTranslated(-view.center[0],-view.center[1],-view.center[2]); /* if want wireframe mode, then use the following */ if (wireframe > 0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glFrontFace(GL_CCW); glDisable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glCallList(list_id); glDisable(GL_BLEND); drawCLUT(); /* draw the color lookup table */ glColor3f(0.f, 0.f, 1.f); vcbDrawAxis(spaceball.GetMatrix(), 100); glPopMatrix(); sprintf(echofps,"fps: %4.2f %6.2f mil tri/sec: division factor: %d",fps, fps*npara*12/1e6, ncuts); /* glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_1D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); */ vcbOGLprint(0.01f,0.01f, 1.f, 1.f, 0.f, echofps); /* glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_1D); */ nframes ++; glutSwapBuffers(); } void cleanup (void) { printf("done with rendering cleanup, ogl version %2.1f ...\n",vcbGetOGLVersion()); fflush(stdout); } int main(int argc, char ** argv) { vcbdatatype dtype; int i, j, n, ndims, orig, nvals, dummy; int sliceid; float hitcnt, hiterr, corners[8][4], emin, emax; double red; vcbCustomizeColorTableColdHot(tlut, 0, 255); for (i = 0; i < 256; i ++) tlut[i * 4+3] = i/255.f; mainwin = initGLUT(argc,argv); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr,"glew error, initialization failed\n"); fprintf(stderr,"Glew Error: %s\n", glewGetErrorString(err)); } abbox.low[0] = abbox.low[1] = abbox.low[2] = 1e6; abbox.high[0] = abbox.high[1] = abbox.high[2] = -1e6; list_id = glGenLists(1); glNewList(list_id, GL_COMPILE); glBegin(GL_QUADS); for (npara = 0; (n = get_pixel_energy(&sliceid,&emin,&emax,&hitcnt,&hiterr,corners)) > 0; npara ++) { /* for (i = 0; i < 8; i ++) printf("%f, %f, %f, %f\n", corners[i][0], corners[i][1], corners[i][2], corners[i][3]); */ correctCornersf3d(corners, NULL); realCubef(corners, vdata); for (i = 0; i < 6*4; i ++) { abbox.low [0] = VCB_MINVAL(abbox.low [0],vdata[i*4]); abbox.high[0] = VCB_MAXVAL(abbox.high[0],vdata[i*4]); abbox.low [1] = VCB_MINVAL(abbox.low [1],vdata[i*4+1]); abbox.high[1] = VCB_MAXVAL(abbox.high[1],vdata[i*4+1]); abbox.low [2] = VCB_MINVAL(abbox.low [2],vdata[i*4+2]); abbox.high[2] = VCB_MAXVAL(abbox.high[2],vdata[i*4+2]); } /* red = (8+log10(hitcnt)); if (red < 0) red = 0; if (red > 6) red = 6; i = (int)(red*42 + 0.5); if (i > 255) i = 255; */ i = (int)(hitcnt/1e-2 * 255); if (i > 255) i = 255; if (i < 0) i = 0; glColor4fv(&tlut[i*4]); for (i = 0; i < 6; i ++) for (j = 0; j < 4; j ++) glVertex3fv(&vdata[(i*4+j)*4]); } glEnd(); glEndList(); printf("number of parallelipeds = %d\n",npara); printf("bounding box: (%f %f %f) (%f %f %f)\n",abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); wireframe = 0; initApp(); /* initialize the application */ initGLsettings(); makeGrid(); gtex = vcbBindOGLTexture2D(GL_TEXTURE0, GL_NEAREST, GL_LUMINANCE, GL_LUMINANCE, GL_FLOAT, gridtexsz, gridtexsz, gridtex, GL_MODULATE, NULL); atexit(cleanup); //glutKeyboardFunc(keys); //glColor4f(0.7038f, 0.27048f, 0.0828f, 1.0f); glColor4f(1.f, 1.f, 1.f, 1.0f); glutMainLoop(); return 0; } <file_sep>/binner/include/geometry.h /** \ingroup rebinner_core \file include/geometry.h \brief CURRENT core API -- functions for geometric operations. $Id$ */ #ifndef _BINNER_GEOMETRY_ #define _BINNER_GEOMETRY_ #include <math.h> #include "macros.h" #ifdef __cplusplus extern "C" { #endif void cal_normal(double * n, double * v); double vec_normalize(double * n); double dist_plane(double * normal, double * pnt, double * vert0); double inside_prism(double * pnt, int n, double * normals, double * verts); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/map.c /** \ingroup rebinner_sdk \file src/map.c \brief CURRENT sdk executable to launch an app in parallel multi-process. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/wait.h> #include <pthread.h> #include <sys/time.h> #include "macros.h" static char * usage = "usage: %s -n num_forks runner arguments_for_runner_to_use\n"; #define BATCH_SZ 2000 #define ITEM_SZ (sizeof(int) + sizeof(double)*(4 + 8*3)) #define TASK_SZ (ITEM_SZ * BATCH_SZ) typedef struct map_thread { pid_t pid; /* child pid */ int fd; int offset; int nbytes; char * buffer; pthread_t tid; } task_t; task_t * t; pthread_mutex_t lock1; pthread_mutex_t lock2; char errormsg [80]; int totalpixcnt = 0; void sigpipe_handler(int dummy) { fprintf(stderr, "%d: caught a SIGPIPE\n", getpid()); exit(1); } void * pusher(void * ip) { int i = ((int *)ip)[0], n, towrite, total = 0; char * bp; #if REBINDEBUG fprintf(stderr, "pusher %d is here, fd= %d, pid = %d\n", i, t[i].fd, (int)(t[i].pid)); #endif while(1) { if (t[i].nbytes == 0) { pthread_mutex_lock(&lock1); n = fread(t[i].buffer, ITEM_SZ, BATCH_SZ, stdin); totalpixcnt += n; #if REBINDEBUG fprintf(stderr, "pusher %d read %d items\n", i, n); #endif pthread_mutex_unlock(&lock1); if (n <= 0) break; /* exit point. leaving while loop */ t[i].nbytes = n*ITEM_SZ; t[i].offset = 0; } if (t[i].nbytes > 0) { #if REBINDEBUG fprintf(stderr, "pusher %d to write %d bytes\n", i, t[i].nbytes - t[i].offset); #endif bp = t[i].buffer+t[i].offset; for (n = 0, towrite = t[i].nbytes; towrite > 0; ) { n += write(t[i].fd, bp+n, towrite); /* make sure write occurs on boundaries of ITEM_SZ bytes */ if (n % ITEM_SZ != 0) towrite = ITEM_SZ - (n % ITEM_SZ); else towrite = 0; } if (n <= 0) { sprintf(errormsg, "thread %d failed writing to fd: %d, %d bytes left.\n", i, t[i].fd, t[i].nbytes); perror(errormsg); break; /*exit point. leaving while loop */ } #if REBINDEBUG fprintf(stderr, "pusher %d done writing %d bytes\n", i, n); #endif t[i].offset += n; t[i].nbytes -= n; total += n; } } fprintf(stderr, "thread %d processed : %d input pixels, %d bytes left\n", i, total/ITEM_SZ, total%ITEM_SZ); close(t[i].fd); free(t[i].buffer); return NULL; } int main(int argc, char ** argv, char ** envp) { int i, status; pid_t pid, sink; int pipefd1[2], pipefd2[2], *sinkstreams, *vals; pthread_attr_t attr[1]; char * sinkinput; int c = 1, nforks = 2; /* default to a parallelism of 2 */ struct timeval time1, time2; float seconds; gettimeofday(&time1, 0); #if REBINDEBUG fprintf(stderr, "argc = %d \n", argc); #endif if (argc < 3) { fprintf(stderr, usage, argv[0]); exit(1); } if (strcmp(argv[c],"-n") == 0) { nforks = (int)(atof(argv[c+1])); argc -= 2; c += 2; } else { fprintf(stderr, usage, argv[0]); exit(1); } /* new arg added for RM to test the option of "no factorial division" */ if (strcmp(argv[c],"-nd") == 0) { argc -= 1; c += 1; } signal(SIGPIPE, sigpipe_handler); /* spawn off "nforks" rebinner and one sink processes */ /* accordingly, there are "nforks" threads to push data through */ #if REBINDEBUG fprintf(stderr, "sizeof(struct map_thread) = %ld, nforks = %d\n", sizeof(struct map_thread), nforks); #endif t = (task_t *) malloc(sizeof(struct map_thread) * nforks); sinkstreams = (int *) malloc(sizeof(int) * nforks); vals = (int *) malloc(sizeof(int) * nforks); #if REBINDEBUG fprintf(stderr, "sizes: item = %ld, batchsz = %d, tasksz = %ld\n", ITEM_SZ,BATCH_SZ,TASK_SZ); #endif for (i = 0; i < nforks; i++) { if (pipe(pipefd1) < 0) { sprintf(errormsg, "incoming pipe for rebinner #%d", i); perror(errormsg); exit(1); } #if REBINDEBUG fprintf(stderr, "fork: pid = %d\n", pid); #endif if (pipe(pipefd2) < 0) { sprintf(errormsg, "outgoing pipe for rebinner #%d", i); perror(errormsg); exit(1); } pid = fork(); #if REBINDEBUG fprintf(stderr, "fork: pid = %d\n", pid); #endif if (pid < 0) { sprintf(errormsg, "forking off rebinner process %d", i); perror(errormsg); exit(1); } if (pid > 0) /* still in parent process */ { close(pipefd1[0]); t[i].fd = pipefd1[1]; t[i].pid = pid; sinkstreams[i] = pipefd2[0]; close(pipefd2[1]); } else /* child process - the real rebinner */ { close(pipefd1[1]); dup2(pipefd1[0], 0); close(pipefd1[0]); close(pipefd2[0]); dup2(pipefd2[1], 1); close(pipefd2[1]); execvp(argv[c], &argv[c]); sprintf(errormsg, "exec failed for rebinner process %d", i); perror(errormsg); exit(1); } #if REBINDEBUG fprintf(stderr, "t[%d] has pid=%d, fd = %d\n", i, t[i].pid, t[i].fd); #endif } /* now let's create the sink */ sink = fork(); if (sink < 0) { sprintf(errormsg, "forking off sink process"); perror(errormsg); exit(1); } if (sink > 0) { for (i = 0; i < nforks; i ++) close(sinkstreams[i]); free(sinkstreams); } else /* in the sink process */ { for (i = 0; i < nforks; i ++) { dup2(sinkstreams[i], i + 3); close(sinkstreams[i]); close(t[i].fd); } /* execlp("reduce", "reduce", sinkinput, NULL); */ execvp("reduce", argv); perror("exec failed for reduce process"); exit(1); } pthread_mutex_init(&lock1, NULL); pthread_mutex_init(&lock2, NULL); pthread_attr_init(attr); pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM); for (i = 0; i < nforks; i ++) { t[i].buffer = malloc(TASK_SZ); t[i].nbytes = 0; t[i].offset = 0; vals[i] = i; pthread_create(&(t[i].tid), attr, pusher, vals+i); } for (i = i; i > nforks; i ++) { pthread_join(t[i].tid, NULL); #if REBINDEBUG fprintf(stderr,"t[%d] joined\n",i); #endif } for (i = 0; i < nforks + 1; i ++) { #if REBINDEBUG fprintf(stderr, "pid = %ld wait returned \n", wait(&status)); #else wait(&status); #endif } free(t); free(vals); gettimeofday(&time2, 0); fprintf(stderr, "num_pixels processed: %d\n", totalpixcnt); seconds = (time2 . tv_sec - time1 . tv_sec ) + (time2 . tv_usec - time1 . tv_usec) / 1e6f; fprintf(stderr, "rebinner runtime : %f sec\n", seconds); fprintf(stderr, "rebin throughput : %.2f pixels/sec\n", totalpixcnt/seconds); return 0; } <file_sep>/binner/src/clipvoxel.c /** \ingroup rebinner_tests \file src/clipvoxel.c \brief CURRENT test of core API -- binnerio.h, clip.h, volume.h, voxelize.h $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binner.h" #include "clip.h" #include "binnerio.h" #include "volume.h" int main(int argc, char ** argv) { double * vdata, * v, * voxels, ccs, voxel_volume; int * nverts; /* at most 200 facets */ int dim, i, j, k, nfacets, n, coord[3]; /* * this code cuts the space of a 1.0 height, width, depth cube * to dim pieces in each direction */ dim = atoi(argv[1]); ccs = 1.0/dim; voxels = malloc(dim*dim*dim* sizeof(double)); /* input has at most 1k vertices */ vdata = malloc(1024 * 3 * sizeof(double)); /* input has at most 200 facets */ nverts = malloc(200 * sizeof(int)); for (nfacets = 0, v = vdata; (n = get_polygond(v)) > 0; nfacets ++) { nverts[nfacets] = n; v += n * 3; } voxel_volume = 0; for (i = 0; i < dim; i ++) for (j = 0; j < dim; j ++) for (k = 0; k < dim; k ++) { coord[0] = i; coord[1] = j; coord[2] = k; voxels[(i*dim + j)*dim + k] = partialvoxel_volume(nfacets, nverts, vdata, coord, ccs); voxel_volume += voxels[(i*dim + j)*dim + k]; printf("%d %d %d: %lf\n", i, j, k, voxels[(i*dim + j)*dim + k]); } printf("total volume: %lf\n", voxel_volume); //nfacets = clip_polyhedral(nfacets, &nverts, &vdata, plane); //binnerout_phcd(nfacets, nverts, vdata); /*printf("%d \n", nfacets);*/ free(nverts); free(vdata); free(voxels); return nfacets; } <file_sep>/binner/script/buildall.sh #!/bin/sh #build cd ../vcb/src make make -f makefile_withgl make clean cd ../libtestsrc make make install make clean cd ../../src make all make install make -f makefile_withgl install make clean cd ../docs doxygen exit 0 <file_sep>/binner/src/collector.c /** \ingroup rebinner_sdk \file src/collector.c \brief CURRENT sdk executable to collect results in distributed rebinner runs. $Id$ */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <pthread.h> #include "socketfun.h" #include "binnerio.h" #include "vcbutils.h" typedef struct collector_thread { pthread_t tid; int socket; int offset; int nbytes; int status; /* 0: untouched, 1: in progress, 2: succeeded, -1: failed */ char buffer[8000]; } task_t; int sock1; int orig[3], xyzsize[3]; double * voxels; int maxtaskid, alreadyfinal, curtaskcnt; pthread_mutex_t lock1, lock2; clock_t time1, time2; void * collector_thread(void * in) { task_t * me; char * p; int i, n, x, y, z, vid, toread; int taskcnt[2]; int nvoxel, orig[3], blksize[3]; char * netbuf; me = (task_t *) in; fprintf(stderr,"collector_thread start reading ..."); fflush(stderr); n = read(me->socket, taskcnt, sizeof(int)*2); if (n > 0) { pthread_mutex_lock(&lock1); curtaskcnt ++; pthread_mutex_unlock(&lock1); } pthread_mutex_lock(&lock1); if (taskcnt[1] > 0) alreadyfinal = 1; /* this means you know the final total cnt */ if (taskcnt[0] > maxtaskid) maxtaskid = taskcnt[0]; /* which is maxtaskid */ pthread_mutex_unlock(&lock1); fprintf(stderr,"done reading max/cur/final: %d %d %d\n", maxtaskid, curtaskcnt, alreadyfinal); fflush(stderr); toread = 7 *sizeof(int); for (p = me->buffer, n = 0; (i = read(me->socket, p, toread)) > 0; toread -= i, p+=i) n += i; p = me->buffer; memcpy(&nvoxel, p, sizeof(int)); p+= sizeof(int); memcpy(orig, p, sizeof(int)*3); p+= sizeof(int)*3; memcpy(blksize, p, sizeof(int)*3); p+= sizeof(int)*3; toread = nvoxel * (3*sizeof(int)+sizeof(double)); netbuf = malloc(toread); for (p = netbuf, n = 0; (i = read(me->socket, p, toread)) > 0; toread -= i, p+=i) n += i; close(me->socket); /* write into the volume */ for (i = 0, p = netbuf; i < nvoxel; p+=20, i ++) { x = *((int*)p) + orig[0]; y = *((int*)(p+4)) + orig[1]; z = *((int*)(p+8)) + orig[2]; vid = (x*xyzsize[1] + y)*xyzsize[2] + z; voxels[vid] = *((double*)(p+12)); } free(netbuf); free(me); if ((alreadyfinal > 0) && ((curtaskcnt - 1) >= maxtaskid)) { pthread_mutex_lock(&lock2); close(sock1); time2 = clock(); printf("total collector up time: %.3f sec\n",(float)(time2-time1)/CLOCKS_PER_SEC); orig[0] = orig[1] = orig[2] = 0; vcbGenBinm("400.bin", VCB_DOUBLE, 3, orig, xyzsize, 1, voxels); free(voxels); exit(maxtaskid); pthread_mutex_unlock(&lock2); } pthread_exit(NULL); } int main(int argc, char ** argv) { int sock2, i; int nvoxel; task_t *t; int port; FILE * portnum_file; pthread_attr_t attr[1]; xyzsize[0] = atoi(argv[1]); xyzsize[1] = atoi(argv[2]); xyzsize[2] = atoi(argv[3]); //ntasks = atoi(argv[4]); sock1 = server_setup(argv[4], &port); fprintf(stderr, "%s server_setup: serving socket port. %d\n", argv[0], port); time1 = clock(); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double)); for (i = 0; i < nvoxel; voxels[i] = 0.0, i ++); pthread_mutex_init(&lock1, NULL); pthread_mutex_init(&lock2, NULL); maxtaskid = 0; alreadyfinal = 0; portnum_file = fopen("collectorport.num","w"); fprintf(portnum_file,"%d\n", port); fflush(portnum_file); fclose(portnum_file); for (curtaskcnt = 0; (alreadyfinal == 0) || ((curtaskcnt - 1) != maxtaskid); ) { sock2 = accept_connection(sock1); if (sock2 < 0) break; fprintf(stderr, "%s got a new connection\n", argv[0]); t = (task_t *) malloc(sizeof(task_t)); t -> socket = sock2; pthread_attr_init(attr); pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM); pthread_create(&t->tid, NULL, collector_thread, t); } pthread_mutex_lock(&lock2); close(sock1); orig[0] = orig[1] = orig[2] = 0; //vcbGenBinm("400.bin", VCB_DOUBLE, 3, orig, xyzsize, 1, voxels); free(voxels); pthread_mutex_unlock(&lock2); return 0; } <file_sep>/binner/include/binnerio.h /** \ingroup rebinner_core \file include/binnerio.h \brief CURRENT core API -- I/O functions for different data formats $Id$ */ #ifndef _BINNERIO_ #define _BINNERIO_ #ifdef __cplusplus extern "C" { #endif void printvertexf(float *v, int ndim); void printvertexd(double *v, int ndim); int binnerin3d(int nfacets, float *v); /*return val: nfacets*/ void binnerout3d(int nfacets, float *v); int get_polygonf(float * v); int get_polygond(double * v); int get_pixelf(int * id, float * cnt, float * err, float (* v)[4]); int get_pixel_energy(int * id, float * emin, float * emax, float * cnt, float * err, float (* v)[4]); int binnerin_phcf(int nfacets, int * nverts, float * v); int binnerin_phcd(int nfacets, int * nverts, double * v); void binnerout_phcf(int nfacets, int * nverts, float *v); void binnerout_phcd(int nfacets, int * nverts, double *v); int output_with_compression(char * fname, int * sz, double * vol); void export_VTKhdr(char * fname, int * orig, int * sz, double * cellsize, int nonempty); void export_VTKvol(char * fname, double * orig, int * sz, double * cellsize, double * vol); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/binner.c /** \ingroup rebinner_core \file src/binner.c \brief CURRENT core API -- implementation for binner.h $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <math.h> #include <unistd.h> #include "binner.h" #include "vcbutils.h" #include "vcblinalg.h" #include "voxelize.h" #include "volume.h" void bounding_box(int n, double * bound, double * v) { double fimin,fjmin,fkmin,fimax,fjmax,fkmax; int k; double * vp; fimin = fjmin = fkmin = 1e6; fimax = fjmax = fkmax = -1e6; for (k = 0, vp = v; k < n; vp += 3, k++) { if (vp[0]<fimin) fimin=vp[0]; if (vp[0]>fimax) fimax=vp[0]; if (vp[1]<fjmin) fjmin=vp[1]; if (vp[1]>fjmax) fjmax=vp[1]; if (vp[2]<fkmin) fkmin=vp[2]; if (vp[2]>fkmax) fkmax=vp[2]; } bound[0] = fimin; bound[1] = fimax; bound[2] = fjmin; bound[3] = fjmax; bound[4] = fkmin; bound[5] = fkmax; } void flood_wvol(unsigned int * wvol, int * xyzsize) { int notdone, i, j, k, id; int xy = xyzsize[2]*xyzsize[1]; int xyz = xy*xyzsize[0]; int xdim = xyzsize[2]; unsigned int * vol; unsigned int seed = 0xffffffff; vol = (unsigned int *) wvol; vol[0] = seed; /* seed flooding at the origin */ for (notdone = 1; notdone > 0; ) { //printf("flooding ..."); fflush(stdout); notdone = 0; for(k = 0; k < xyz; k += xy) for(j = 0; j < xy; j += xdim) for(i=0, id = k+j; i < xdim; i++, id++) if (vol[id] == 0) if ((i == 0) || (j == 0) || (k == 0) || (vol[id-1] == seed) || (vol[id-xdim] == seed) || (vol[id-xy] == seed)) vol[id] = seed; for(k = xyz-xy; k >= 0; k -= xy) for(j = xy-xdim; j >= 0; j -= xdim) for(i = xdim-1, id = k+j+i; i >= 0; i--, id--) { if (vol[id] == 0) if ((i == xdim-1) || (j == xy-xdim) || (k == xyz-xy) || (vol[id+1] == seed) || (vol[id+xdim] == seed) || (vol[id+xy] == seed)) vol[id] = seed; /* check and see if we are done. should be by here */ if (vol[id] == seed) if (((i < xdim-1) && (vol[id+1] == 0)) || ((j < xy-xdim) && (vol[id+xdim] == 0)) || ((k < xyz-xy) && (vol[id+xy] == 0))) notdone = 1; } //printf(" pass\n"); } for (i = 0, j = 0, k = 0; i < xyz; i ++) { if (vol[i] == 0xffffffff) j ++; if (vol[i] == 0) k ++; } fprintf(stderr,"nvoxel %d, out/in/sur: %d/%d/%d\n", xyz, j, k, xyz-j-k); } void pad_bounds3d(double * bounds, double decr_lb, double incr_ub) { /* now let's pad 2 cells on each end of the 3 dimensions */ bounds[0] -= decr_lb; bounds[1] += incr_ub; bounds[2] -= decr_lb; bounds[3] += incr_ub; bounds[4] -= decr_lb; bounds[5] += incr_ub; } void roundup_bounds(double * bounds, int * lb, int * ub, double ccs) { /* make sure bounds end on integar intervals of ccs */ lb[0] = (int)floor(bounds[0]/ccs); bounds[0] = lb[0] * ccs; lb[1] = (int)floor(bounds[2]/ccs); bounds[2] = lb[1] * ccs; lb[2] = (int)floor(bounds[4]/ccs); bounds[4] = lb[2] * ccs; /* ub[0] = (int)ceil(bounds[1]/ccs); bounds[1] = ub[0] * ccs; ub[1] = (int)ceil(bounds[3]/ccs); bounds[3] = ub[1] * ccs; ub[2] = (int)ceil(bounds[5]/ccs); bounds[5] = ub[2] * ccs; */ ub[0] = (int)floor(bounds[1]/ccs); bounds[1] = ub[0] * ccs; ub[1] = (int)floor(bounds[3]/ccs); bounds[3] = ub[1] * ccs; ub[2] = (int)floor(bounds[5]/ccs); bounds[5] = ub[2] * ccs; } double count_volume(double * vol, int len, int step) { int i; /* int xyz = xyzsize[0]*xyzsize[1]*xyzsize[2]; */ double volume; for (i = 0, volume = 0.0; i < len; volume += vol[i], i += step) #if REBINDEBUG printf("vol[%d] = %lf\n", i, vol[i]); #else ; #endif return volume; } double bin_para_3dvoxelize( int nfacets, int * nverts, double *v, /* the vertices */ int * orig, int * xyzsize, double ccs, /* cubic cell size */ double *voxels) { clock_t time1, time2, time3, time4; /* return value: is the total volume in the subdivided grid */ double cs, voxel_volume, total_volume, inside_vol, surface_vol; double * vp; double bounds[6]; double wv[6*4*3]; int wnfacets, wnverts[6]; int *face_starts; //char fname[100]; int i, j, k, nvoxel, id, vid; unsigned int temp, pid; int lb[3], ub[3], ori[3], coord[3], totalverts; unsigned int *wvol; /* working volume */ int wsize[3]; unsigned int base = 1024; time1 = clock(); face_starts = malloc(nfacets * sizeof(int)); /* find out the bounding box */ for (i = 0, totalverts = 0; i < nfacets; totalverts += nverts[i], i ++) face_starts[i] = totalverts; /* assume uniform cell size: ccs, cubic cell size; cs: half of cell size */ cs = ccs/2; bounding_box(totalverts, bounds, v); pad_bounds3d(bounds, ccs*2, ccs*3); /* pad on each end of the 3 dimensions */ roundup_bounds(bounds, lb, ub, ccs); /* make sure bounds end on integar intervals of ccs */ /* knowing the proper bounds, wvol should be of wsize */ wsize[0] = ub[0] - lb[0]; wsize[1] = ub[1] - lb[1]; wsize[2] = ub[2] - lb[2]; nvoxel = wsize[0]*wsize[1]*wsize[2]; //printf("wsize: %d %d %d\n",wsize[0], wsize[1], wsize[2]); wvol = malloc(nvoxel * sizeof(unsigned int)); if (wvol == NULL) { perror("bin_para3d_150 wvol allocation error"); exit(1); } /* for (i = 0; i < nvoxel; wvol[i] = 100, i ++); for (i = 0; i < wsize[0]; i ++) for (j = 0; j < wsize[1]; j ++) for (k = 0; k < wsize[2]; k ++) wvol[(i*wsize[1]+j)*wsize[2] +k] = k; ori[0] = ori[1] = ori[2] = 0; */ //vcbGenBinm("100.bin", VCB_UNSIGNEDINT, 3, ori, wsize, 1, wvol); memset(wvol, 0, nvoxel * sizeof(unsigned int)); voxel_volume = ccs * ccs * ccs; /* (0,0,0) in wvol should appear on ori[0-3] in voxels */ ori[0] = lb[0] - orig[0]; ori[1] = lb[1] - orig[1]; ori[2] = lb[2] - orig[2]; //printf("ori: %d %d %d\n",ori[0], ori[1], ori[2]); for (i = 0, vp= v; i < nfacets; vp += nverts[i]*3, i ++) { /* * facet[i] starts at v[i*(3*4)] and lasts 12 values * i.e. 4 vertices of xyz coordinates */ //printf("facet #%d\n", i); voxelize_poly(nverts[i], vp, wvol, lb, wsize, ccs, base, i+1); //sprintf(fname,"1%d.bin", i); //vcbGenBinm(fname, VCB_UNSIGNEDINT, 3, ori, wsize, 1, wvol); } time2 = clock(); for (i = 0, j = 0, k = 0; i < nvoxel; i ++) { if (wvol[i] > 0) j ++; if (wvol[i] == 0) k ++; } //printf("nvoxel %d, out+in/sur: %d/%d\n", nvoxel, k, j); //vcbGenBinm("150.bin", VCB_UNSIGNEDINT, 3, ori, wsize, 1, wvol); flood_wvol(wvol, wsize); //vcbGenBinm("200.bin", VCB_UNSIGNEDINT, 3, ori, wsize, 1, wvol); time3 = clock(); //printf("computing volume, orig: %d %d %d -- wvol bounded by (%d,%d,%d) - (%d,%d,%d) ... \n", orig[0], orig[1], orig[2], lb[0], lb[1], lb[2], ub[0], ub[1], ub[2]); /* now let's figure out the volumes */ total_volume = inside_vol = surface_vol = 0.0; nvoxel = 0; for (i = 0; i < xyzsize[0]; i ++) for (j = 0; j < xyzsize[1]; j ++) for (k = 0; k < xyzsize[2]; k ++) { /*id = (i * wsize[1] + j) * wsize[2] + k;*/ vid = (i*xyzsize[1] + j)*xyzsize[2] + k; id = ((i-ori[0])*wsize[1] + (j-ori[1]))*wsize[2] + (k-ori[2]); temp = wvol[id]; if (temp == 0xffffffff) /* you are outside */ continue; if (temp == 0) /* you are inside */ { voxels[vid] = voxel_volume; total_volume += voxel_volume; inside_vol += voxel_volume; nvoxel ++; continue; } /* if you are still here, you are on an edge */ /*printf("id (%d,%d,%d): temp: %d ",i, j, k, temp); */ for (wnfacets = 0, vp = wv; temp > 0; temp /= base) { assert(temp % base > 0); pid = temp % base - 1; wnverts[wnfacets] = nverts[pid]; memcpy(vp, &v[face_starts[pid]*3], nverts[pid]*3*sizeof(double)); vp += nverts[pid]*3; wnfacets ++; /*printf("# %d %d ", pid, nverts[pid]);*/ } coord[0] = i - orig[0]; coord[1] = j - orig[1]; coord[2] = k - orig[2]; /* printf(" coord (%d, %d, %d) ",coord[0], coord[1], coord[2]); */ voxels[vid] = partialvoxel_volume(wnfacets, wnverts, wv, coord, ccs); total_volume += voxels[vid]; surface_vol += voxels[vid]; /*printf(" volume = %lf\n", voxels[vid]);*/ } time4 = clock(); free(wvol); free(face_starts); //printf("volsz: %d %d %d. ", xyzsize[0], xyzsize[1], xyzsize[2]); fprintf(stderr,"volume(total:in:surf) = %lf:%lf:%lf.\n", total_volume, inside_vol, surface_vol); fprintf(stderr,"time(voxelize:flood:rebin) = %.3f:%.3f:%.3f sec\n", (float)(time2-time1)/CLOCKS_PER_SEC, (float)(time3-time2)/CLOCKS_PER_SEC, (float)(time4-time3)/CLOCKS_PER_SEC); return total_volume; } int pipedump(int mode, int sliceid, double emin, double emax, int x, int y, int z, double en, double er, double fraction) { #define UNIT 56 #define max_n_units 1300 static int cnt = 0; static char buf[UNIT*max_n_units]; static totalwrote = 0; if (mode == 1) { write(1, buf, cnt*UNIT); totalwrote += cnt; #if REBINDEBUG fprintf(stderr, "pipedump total n_voxels wrote: %d\n", totalwrote); #endif cnt = 0; return 1; } else { memcpy(&buf[cnt*UNIT+0], &sliceid, sizeof(int)); memcpy(&buf[cnt*UNIT+4], &x, sizeof(int)); memcpy(&buf[cnt*UNIT+8], &y, sizeof(int)); memcpy(&buf[cnt*UNIT+12], &z, sizeof(int)); memcpy(&buf[cnt*UNIT+16], &en, sizeof(double)); memcpy(&buf[cnt*UNIT+24], &er, sizeof(double)); memcpy(&buf[cnt*UNIT+32], &emin, sizeof(double)); memcpy(&buf[cnt*UNIT+40], &emax, sizeof(double)); memcpy(&buf[cnt*UNIT+48], &fraction, sizeof(double)); cnt ++; } if (cnt == max_n_units) { write(1, buf, cnt*UNIT); totalwrote += cnt; cnt = 0; } return 0; } double bin_para_3dclip( int sliceid, int nfacets, int * nverts, double *v, /* the vertices */ double *hitcnt, double *hiterr, int * orig, int * xyzsize, double ccs, /* cubic cell size, assume uniform cell size */ double *voxels, double emin, double emax) { clock_t time1, time2; /* return value: is the total volume in the subdivided grid */ double voxel_volume, total_volume, factor, para_volume; double * vp; double smallbounds[6]; int wnfacets; //wnverts[6]; int *face_starts; int i, j, k, l, id, nwrote = 0; int smalllb[3], smallub[3], coord[3], totalverts; double one = 1.0, a, b; #if REBINDEBUG fprintf(stderr, "bin_small start: npixels = %d\n", nfacets/6); #endif time1 = clock(); face_starts = malloc(nfacets * sizeof(int)); for (i = 0, totalverts = 0; i < nfacets; totalverts += nverts[i], i ++) face_starts[i] = totalverts; #if REBINDEBUG for (i = 0, vp= v; i < nfacets; i += 6, vp += 6*4*3) fprintf(stderr, "hitcnt[%d] = %lf\n", i/6, hitcnt[i/6]); #endif wnfacets = 6; for (i = 0, vp= v; i < nfacets; i += 6, vp += 6*4*3) { if ((hitcnt != NULL) && (hiterr != NULL)) if (hitcnt[i/6] < 1e-16) continue; /* consider this empty. no rebinning needed */ bounding_box(6*4, smallbounds, vp); roundup_bounds(smallbounds, smalllb, smallub, ccs); /* printf("processing paralleliped %d: lb %d %d %d, ub %d %d %d: hit %e \n", i/6, smalllb[0], smalllb[1], smalllb[2], smallub[0], smallub[1], smallub[2], hitcnt[i/6]); */ if ( (smalllb[0] == smallub[0]) && (smalllb[1] == smallub[1]) && (smalllb[2] == smallub[2])) { if (smalllb[0] < orig[0]) continue; if (smalllb[1] < orig[1]) continue; if (smalllb[2] < orig[2]) continue; if (smallub[0] >= orig[0]+xyzsize[0]) continue; if (smallub[1] >= orig[1]+xyzsize[1]) continue; if (smallub[2] >= orig[2]+xyzsize[2]) continue; id = ((smalllb[0] - orig[0])*xyzsize[1] + smalllb[1] - orig[1]) * xyzsize[2] + smalllb[2] - orig[2]; if ((hitcnt != NULL) && (hiterr != NULL)) { if (voxels != NULL) { voxels[id*2] += hitcnt[i/6]; voxels[id*2+1] += hiterr[i/6]; } else { nwrote ++; pipedump(0, sliceid, emin, emax, smalllb[0] - orig[0], smalllb[1] - orig[1], smalllb[2] - orig[2], hitcnt[i/6], hiterr[i/6], one); } } else { if (voxels != NULL) { voxels[id*2] += 1.0; voxels[id*2+1] += 1.0; } else { pipedump(0, sliceid, emin, emax, smalllb[0] - orig[0], smalllb[1] - orig[1], smalllb[2] - orig[2], one, one, one); nwrote ++; } } } else { /*clip this paralleliped to within this cell */ if (smalllb[0] < orig[0]) smalllb[0] = orig[0]; if (smalllb[1] < orig[1]) smalllb[1] = orig[1]; if (smalllb[2] < orig[2]) smalllb[2] = orig[2]; if (smallub[0] >= orig[0]+xyzsize[0]) smallub[0] = orig[0]+xyzsize[0]-1; if (smallub[1] >= orig[1]+xyzsize[1]) smallub[1] = orig[1]+xyzsize[1]-1; if (smallub[2] >= orig[2]+xyzsize[2]) smallub[2] = orig[2]+xyzsize[2]-1; #if 1 para_volume = polyhedral_volume(wnfacets, &nverts[i], vp); #else para_volume = (smallub[0]-smalllb[0]+1)*(smallub[1]-smalllb[1]+1)*(smallub[2]-smalllb[2]+1); #endif assert(para_volume >= 0); if (para_volume < 1e-16) continue; /*don't do anything */ for (j = smalllb[0]; j <= smallub[0]; j ++) for (k = smalllb[1]; k <= smallub[1]; k ++) for (l = smalllb[2]; l <= smallub[2]; l ++) { coord[0] = j; coord[1] = k; coord[2] = l; #if REBINDEBUG fprintf(stderr, "coord: %d %d %d, hitcnt %lf, factor %lf, para_volume %f\n", j, k, l, hitcnt[i/6], factor, para_volume); #endif id = ((j - orig[0])*xyzsize[1] + k - orig[1])*xyzsize[2] + l - orig[2]; voxel_volume = partialvoxel_volume(wnfacets, &nverts[i], vp, coord, ccs); assert(voxel_volume >= 0); if (voxel_volume > 1e-17) { factor = voxel_volume/para_volume; a = hitcnt[i/6]/para_volume*factor; b = hiterr[i/6] * factor * factor; assert(a >= 0); assert(b >= 0); if (voxels != NULL) { voxels[id*2] += a; voxels[id*2+1] += b; } else { pipedump(0, sliceid, emin, emax, j - orig[0], k - orig[1], l - orig[2], a, b, factor); nwrote ++; } } } } } pipedump(1, sliceid, emin, emax, j, k, l, a, b, one); time2 = clock(); free(face_starts); /* sum up only the hits: voxels[i*2]. errs are at voxels[2*i+1] */ if (voxels != NULL) total_volume = count_volume(voxels, xyzsize[0]*xyzsize[1]*xyzsize[2]*2, 2); #if REBINDEBUG fprintf(stderr, "bin_small end: npixels = %d, wrote nvoxels = %d, %d bytes\n", nfacets/6, nwrote, nwrote * 28); #endif #if REBINDEBUG fprintf(stderr, "bin_small recorded total_volume = %lf, before scaling\n", total_volume); #endif return total_volume; } <file_sep>/binner/include/voxelize.h /** \ingroup rebinner_core \file include/voxelize.h \brief CURRENT core API -- base module to support bin_para3dvoxelize in binner.h $Id$ */ #ifndef _BINNERVOXELIZE_ #define _BINNERVOXELIZE_ #ifdef __cplusplus extern "C" { #endif double dist_plane(double * normal, double * pnt, double * vert0); void voxelize_poly( int n, double * v, /* the polygon */ unsigned int * wvol, /* working volume, contain tags when done */ int * orig, int * xyzsize, double cs, int base, /* base is the max val of polyid */ int polyid); /* cell size */ #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/script/timing_bmeshrebin.sh #!/bin/bash # use: timgin_bmeshrebin.sh minres maxres incr testin TOP=.. rebinproc="${TOP}/bin/bmeshrebin" logfile="${TOP}/log/bmeshrebin_timing_`hostname`.log" echo `date` >> $logfile echo `hostname` >> $logfile for ((i = $1; i <= $2; i += $3)) do echo rebinproc $i >> $logfile $rebinproc $i < $4 2>>$logfile done echo >> $logfile exit 0 <file_sep>/binner/src/gmeshindex.c /** \ingroup rebinner_execs \file src/gmeshindex.c \brief CURRENT executable of rebinner for indexing bounds of many gmehs files. usage: gmeshindex all_files_to_index, for example: \code UNIX> gmeshindex 81[3-9]-mesh/* \endcode This command will index the bounds of all files under 813-mesh to 819-mesh. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "binner.h" void update_bounds(int n, double * bound, double * v) { double fimin,fjmin,fkmin,fimax,fjmax,fkmax; int k; double * vp; fimin = bound[0]; fimax = bound[1]; fjmin = bound[2]; fjmax = bound[3]; fkmin = bound[4]; fkmax = bound[5]; for (k = 0, vp = v; k < n; vp += 3, k++) { if (vp[0]<fimin) fimin=vp[0]; if (vp[0]>fimax) fimax=vp[0]; if (vp[1]<fjmin) fjmin=vp[1]; if (vp[1]>fjmax) fjmax=vp[1]; if (vp[2]<fkmin) fkmin=vp[2]; if (vp[2]>fkmax) fkmax=vp[2]; } bound[0] = fimin; bound[1] = fimax; bound[2] = fjmin; bound[3] = fjmax; bound[4] = fkmin; bound[5] = fkmax; } int main(int argc, char ** argv) { int i, n, buf[1]; char PATH[1024]; double vdata[4 + 8*3], *v; double bounds[6]; FILE * fp; if (argc <= 1) { fprintf(stderr, "usage: %s all_files_to_index \n", argv[0]); exit(1); } v = vdata + 4; getcwd(PATH, 1024); /* fprintf(stderr, "path = %s\n", PATH); */ for (i= 1; i < argc; i ++) { fp = fopen(argv[i], "rb"); if (fp == NULL) { /* something is wrong with this file */ /* move on to the next file */ continue; } bounds[0] = bounds[2] = bounds[4] = 1e16; bounds[1] = bounds[3] = bounds[5] = -1e16; for (n = 0; ; n ++) { if (fread(buf, sizeof(int), 1, fp) <= 0) break; fread(vdata, sizeof(double), 4 + 8 *3, fp); update_bounds(8, bounds, v); } if (argv[i][0] != '/') fprintf(stdout, "%s/%s ", PATH, argv[i]); else fprintf(stdout, "%s ", argv[i]); fprintf(stdout, "%d %le %le %le %le %le %le\n", n, bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); fclose(fp); } return 0; } <file_sep>/binner/src/pix2mesh.c #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include "vcbmath.h" #include "cell.h" #include "binnerio.h" /** * $Id$ * */ /* this program generates a single paralleliped */ int main(int argc, char ** argv) { int i, j; float corners[8][4]; float v[6*4*4]; for (i = 0; i < 8; i ++) scanf("%f, %f, %f, %f\n", &corners[i][0], &corners[i][1], &corners[i][2], &corners[i][3]); correctCornersf3d(corners, NULL); realCubef(corners, v); for (i = 0; i < 6; i ++) { printf("4"); for (j = 0; j < 4; j ++) printf(" %f %f %f", v[(i*4+j)*4+0], v[(i*4+j)*4+1], v[(i*4+j)*4+2]); printf("\n"); } return 6; } <file_sep>/binner/src/voxelize.c /** \ingroup rebinner_core \file src/voxelize.c \brief CURRENT core API -- implementation for voxelize.h $Id$ */ #include <stdio.h> #include <math.h> #include "vcblinalg.h" #include "binner.h" #include "geometry.h" #include "voxelize.h" void voxelize_poly( int n, double * v, /* the polygon */ unsigned int * wvol, /* working volume, contain tags when done */ int * orig, int * xyzsize, double ccs, int base, /* base is the max val of polyid */ int polyi) /* cell size */ { //double fimin,fjmin,fkmin,fimax,fjmax,fkmax; int imin,imax,jmin,jmax,kmin,kmax; double poly_eq[4]; double edge[10*3], edget[10], *ep; /* direction vector and length of each edge */ double crossedge[10*3], * cp; double cs; /* half of cell size */ double a, b, c, d, limitf, sqrt3, limit, limitf_2, t, tmax; int i, j, k, f, id, xdim, ydim, zdim, flag, fill; double xyz[3], ori[3], dist, v1[3], bounds[6], radi; double maxcos, temp; unsigned int polyid = (unsigned int) polyi; cs = ccs/2.0; sqrt3 = sqrt(3.0); limitf = sqrt3*cs; ori[0] = orig[0] * ccs + cs; ori[1] = orig[1] * ccs + cs; ori[2] = orig[2] * ccs + cs; xdim = xyzsize[0]; ydim = xyzsize[1]; zdim = xyzsize[2]; bounding_box(n, bounds, v); /* fimin = fjmin = fkmin = 1e6; fimax = fjmax = fkmax = -1e6; for (k = 0, vp = v; k < n; vp += 3, k++) { if (vp[0]<fimin) fimin=vp[0]; if (vp[0]>fimax) fimax=vp[0]; if (vp[1]<fjmin) fjmin=vp[1]; if (vp[1]>fjmax) fjmax=vp[1]; if (vp[2]<fkmin) fkmin=vp[2]; if (vp[2]>fkmax) fkmax=vp[2]; } */ /* make a bounding box of the facet */ imin = (int)floor(bounds[0]/ccs); jmin = (int)floor(bounds[2]/ccs); kmin = (int)floor(bounds[4]/ccs); imax = (int)ceil(bounds[1]/ccs); jmax = (int)ceil(bounds[3]/ccs); kmax = (int)ceil(bounds[5]/ccs); /* imin=(int)(fimin/ccs); imax=(int)(fimax/ccs); jmin=(int)(fjmin/ccs); jmax=(int)(fjmax/ccs); kmin=(int)(fkmin/ccs); kmax=(int)(fkmax/ccs); */ /* compute polygon's equation */ cal_normal(poly_eq, v); vec_normalize(poly_eq); poly_eq[3] = -VCB_DOT(poly_eq, v); /* a,b,c,d of the equation in poly_eq */ a = poly_eq[0]; b = poly_eq[1]; c = poly_eq[2]; d = poly_eq[3]; //printf("orig: (%d %d %d) bounds (%d %d %d) - (%d %d %d), eq:%lf %lf %lf %lf\n",orig[0], orig[1], orig[2], imin, jmin, kmin, imax, jmax, kmax, a, b, c, d); maxcos=0.0; temp=fabs(a+b+c)/sqrt3; if(temp>maxcos) maxcos=temp; temp=fabs(a-b+c)/sqrt3; if(temp>maxcos) maxcos=temp; temp=fabs(-a+b+c)/sqrt3; if(temp>maxcos) maxcos=temp; temp=fabs(-a-b+c)/sqrt3; if(temp>maxcos) maxcos=temp; /* voxel center distanced > limit are not on surface */ limit = limitf*maxcos + BINNER_EPSILON; /* for comparing against radius^2 */ limitf_2 = (limitf+BINNER_EPSILON) * (limitf+BINNER_EPSILON); //printf("ccs %lf, maxcos %lf, limitf %lf, limit %lf, limif_2 %lf\n", ccs, maxcos, limitf, limit, limitf_2); /* * General calculations for each polygon edge. We hold the results for * reference during the evaluation of the potential voxels. */ for (i=0, ep=edge, cp=crossedge; i<n; ep+=3, cp+= 3, i++) { j = (i+1)%n; ep[0] = v[j*3+0] - v[i*3+0]; ep[1] = v[j*3+1] - v[i*3+1]; ep[2] = v[j*3+2] - v[i*3+2]; vec_normalize(ep); tmax=(v[j*3+0]-v[i*3+0])/ep[0]; temp=(v[j*3+1]-v[i*3+1])/ep[1]; if (temp > tmax) tmax=temp; temp=(v[j*3+2]-v[i*3+2])/ep[2]; if (temp > tmax) tmax=temp; edget[i] = tmax; VCB_CROSS(cp, ep, poly_eq); vec_normalize(cp); } /* * for all voxels in the bounding box, DO ... */ for (i=imin;i<=imax;i++) for (j=jmin;j<=jmax;j++) for (k=kmin;k<=kmax;k++) { id = ((i - orig[0]) * ydim + (j-orig[1])) * zdim + k - orig[2]; /* xyz[0] = ori[0] + i * ccs; xyz[1] = ori[1] + j * ccs; xyz[2] = ori[2] + k * ccs; */ xyz[0] = i*ccs + cs; xyz[1] = j*ccs + cs; xyz[2] = k*ccs + cs; dist = fabs(VCB_DOT(xyz, poly_eq) + poly_eq[3]); flag=0; if (dist<=(limitf + BINNER_EPSILON)) { /* SPHERE TEST: in the sphere at the vertex ??? */ for (f=0;f<n;f++) { v1[0] = xyz[0] - v[f*3+0]; v1[1] = xyz[1] - v[f*3+1]; v1[2] = xyz[2] - v[f*3+2]; radi = VCB_DOT(v1, v1); if (radi<=limitf_2) { flag=1; wvol[id] = wvol[id] * base + polyid; /*printf("updated0: %d %d %d, polyid: %d\n", i,j,k,polyid-1);*/ break; } } /* CYLINDER TEST: Voxel in the cylinder ??? */ if (flag==0) { fill=1; for (f=0;f<n;f++) { v1[0] = xyz[0] - v[f*3+0]; v1[1] = xyz[1] - v[f*3+1]; v1[2] = xyz[2] - v[f*3+2]; t = VCB_DOT((&edge[f*3]), v1); tmax = edget[f]; if ((t >= 0.0)&&(t <= tmax)) { v1[0] = xyz[0] - (v[f*3+0]+t*edge[f*3+0]); v1[1] = xyz[1] - (v[f*3+1]+t*edge[f*3+1]); v1[2] = xyz[2] - (v[f*3+2]+t*edge[f*3+2]); radi = VCB_DOT(v1, v1); if (radi<=limitf_2) { flag=1; wvol[id] = wvol[id] * base + polyid; /*printf("updated1: %d %d %d, polyid: %d\n", i,j,k,polyid-1);*/ break; } } if (flag==0) if (inside_prism(xyz, n, crossedge, v) != 1) fill = 0; } } if (flag == 0) if ((fill==1)&&(dist <= limit)) { flag=1; wvol[id] = wvol[id] * base + polyid; /*printf("updated2: %d %d %d, polyid: %d\n", i,j,k,polyid-1);*/ } } } } <file_sep>/binner/include/rebinapp.h /** \ingroup rebinner_core \file include/rebinapp.h \brief CURRENT core API -- utility functions in rebinner $Id$ */ #ifndef _REBINAPP_ #define _REBINAPP_ #ifdef __cplusplus extern "C" { #endif char * rebinner_versionstring(); void scale_vertices(int n, double * vdata,double xscale, double yscale, double zscale); double fv_bounds(double * askbounds, double * spacing, int * orig, int * xyzsize); double padded_bounds(double * bounds, int res, int * orig, int * xyzsize); double rebin_byslice(int npara, int * nverts, double *vdata, /* the vertices */ int *sliceid, double *hitcnt, double *hiterr, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, char * outputpath); double rebin_gmesh(int npara, int * nverts, double *vdata, /* the vertices */ int *sliceid, double *hitcnt, double *hiterr, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, double emin, double emax); double rebin_gmesh_output( int sliceid, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, double emin, double emax, double threshold); void output_askinginfo(double * askbounds, int * xyzsize, double * spacing); void output_askinginfo_short(int * xyzsize); void output_actualinfo(double * bounds); void output_prerebininfo(int * orig, int * xyzsize, double * spacing, double cellsize); void output_postrebininfo(float rebintime, int npara, double totalvolume, int nvoxel); void output_gmesh_formaterr(); void gmesh_singlebin_output(double * dp, int sliceid, int x, int y, int z, int * orig, double * spacing); void gmesh_singlebin_output_nd(double * dp, int sliceid, int x, int y, int z, int * orig, double * spacing); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/rotmat.c /** \ingroup rebinner_execs \file src/rotmat.c \brief CURRENT executable that outputs an axis-centered rotation matrix usage: rotmat axis_x axis_y axis_z rotation_angle_in_degree $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" int main(int argc, char ** argv) { int i; float mat[16], axis[3], angle; if (argc != 5) { fprintf(stderr,"usage: %s axis_x axis_y axis_z rotation_angle_in_degree\n", argv[0]); exit(1); } axis[0] = (float)atof(argv[1]); axis[1] = (float)atof(argv[2]); axis[2] = (float)atof(argv[3]); angle = (float)atof(argv[4]); vcbRotate3fv(mat, axis, angle); printf("%e %e %e ", mat[0], mat[1], mat[2]); printf("%e %e %e ", mat[4], mat[5], mat[6]); printf("%e %e %e \n", mat[8], mat[9], mat[10]); return 0; } <file_sep>/binner/src/gmeshquery.c /** \ingroup rebinner_execs \file src/gmeshquery.c \brief CURRENT executable of rebinner for querying many gmehs files by bounds. usage: gmeshquery [-x xmin xmax] [-y ymin ymax] [-z zmin zmax] $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "binner.h" static char buf[4096]; static char fn[2048]; static double fimin,fjmin,fkmin,fimax,fjmax,fkmax; void init_bounds() { fimin = -1e16; fimax = 1e16; fjmin = -1e16; fjmax = 1e16; fkmin = -1e16; fkmax = 1e16; } int main(int argc, char ** argv) { int i, n, tag; double bounds[6]; if ((argc <= 1) || (argc >= 10)) { fprintf(stderr, "usage: %s [-x xmin xmax] [-y ymin ymax] [-z zmin zmax] \n", argv[0]); exit(1); } #if REBINDEBUG for (i = 0; i < argc; printf("%s\n", argv[i]), i ++); #endif init_bounds(); i = 1; if (i <= argc - 3 && 0 == strcmp("-x", argv[i])) { fimin = atof(argv[i+1]); fimax = atof(argv[i+2]); i += 3; } if (i <= argc - 3 && 0 == strcmp("-y", argv[i])) { fjmin = atof(argv[i+1]); fjmax = atof(argv[i+2]); i += 3; } if (i <= argc - 3 && 0 == strcmp("-z", argv[i])) { fkmin = atof(argv[i+1]); fkmax = atof(argv[i+2]); i += 3; } #if REBINDEBUG fprintf(stderr, "bounds: %le %le %le %le %le %le\n", fimin, fimax,fjmin,fjmax,fkmin,fkmax); #endif for (i = 0; fgets(buf, 4096, stdin) != NULL; i++) { sscanf(buf, "%s %d %le %le %le %le %le %le\n", fn, &n, &bounds[0], &bounds[1], &bounds[2], &bounds[3], &bounds[4], &bounds[5]); if (bounds[0] < fimin) bounds[0] = fimin; if (bounds[2] < fjmin) bounds[2] = fjmin; if (bounds[4] < fkmin) bounds[4] = fkmin; if (bounds[1] > fimax) bounds[1] = fimax; if (bounds[3] > fjmax) bounds[3] = fjmax; if (bounds[5] > fkmax) bounds[5] = fkmax; tag = 1; if (bounds[1] < fimin) tag = 0; if (bounds[3] < fjmin) tag = 0; if (bounds[5] < fkmin) tag = 0; if (bounds[0] > fimax) tag = 0; if (bounds[2] > fjmax) tag = 0; if (bounds[4] > fkmax) tag = 0; if (tag > 0) fprintf(stdout, "%s %d\n", fn, n); } return 0; } <file_sep>/binner/src/seepara.cpp /** \ingroup rebinner_tests \file src/seepara.cpp \brief CURRENT test of core API -- binnerio.h, cell.h, using vcb with opengl Tests core APIs of binnerio, cell, geometry. usage: \code UNIX> cat parallelipeds | seepara \endcode \note This is executable does not behave as a filter. It starts rendering only after detecting end of file on input (STDIN). $Id$ */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <string.h> #include <sys/time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbmath.h" #include "vcbglutils.h" #include "vcblinalg.h" #include "vcbmcube.h" #include "vcbimage.h" #include "cell.h" #include "binnerio.h" #include "atypes.h" #include "vcbcolor.h" char projmode = 'O'; /* P for perspective, O for orthogonal */ projStruct proj; viewStruct view; lightStruct light0; ArcBall spaceball; int iwinWidth; int iwinHeight; int mainwin, sidewin; extern int wireframe; /* application specific data starts here */ int nverts, npara; float vdata[1024]; /* end of application specific data */ bbox abbox; char inputbuf[1024]; int list_id; /* nframes and fps are used for calculating frame rates in formain.cpp:idle() */ extern int nframes; extern float fps; /* texture to hold grid info */ #define gridtexsz 32 static float gridtex[gridtexsz*gridtexsz]; static int gtex; float xmin, xmax, ymin, ymax; extern int ncuts; void makeGrid(void) { int i, j, k; for (k = 0; k < gridtexsz/2; k ++) for (i = k; i < gridtexsz-k; i ++) for (j = k; j < gridtexsz-k; j ++) { gridtex[i*gridtexsz+j] = (gridtexsz/2.f - k)/(gridtexsz/2.f)*0.3; } xmin = view.center[0]+5*proj.xmin; ymin = view.center[1]+5*proj.ymin; xmax = view.center[0]+5*proj.xmax; ymax = view.center[1]+5*proj.ymax; } extern float mradius; void drawGrid(void) { float divfac = ncuts/mradius; glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_CULL_FACE); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glBegin(GL_QUADS); glColor3f(0.774597, 0.774597, 0.774597); glTexCoord2f(xmin*divfac, ymin*divfac); //0.f, 0.f); glVertex2f(xmin, ymin); glTexCoord2f(xmin*divfac, ymax*divfac); //0.f, 1.f); glVertex2f(xmin, ymax); glTexCoord2f(xmax*divfac, ymax*divfac); //1.f, 1.f); glVertex2f(xmax, ymax); glTexCoord2f(xmax*divfac, ymin*divfac); //1.f, 0.f); glVertex2f(xmax, ymin); glEnd(); glDisable(GL_TEXTURE_2D); } void display (void) { char echofps[80]; int i; glClear(GL_COLOR_BUFFER_BIT); drawGrid(); glClear(GL_DEPTH_BUFFER_BIT); spaceball.Update(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(view.center[0],view.center[1],view.center[2]); glMultMatrixf(spaceball.GetMatrix()); glTranslated(-view.center[0],-view.center[1],-view.center[2]); /* if want wireframe mode, then use the following */ if (wireframe > 0) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glFrontFace(GL_CCW); glDisable(GL_CULL_FACE); glCallList(list_id); glColor3f(0.f, 0.f, 1.f); vcbDrawAxis(spaceball.GetMatrix(), 100); glPopMatrix(); sprintf(echofps,"fps: %4.2f %6.2f mil tri/sec: division factor: %d",fps, fps*npara*12/1e6, ncuts); /* glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_1D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); */ vcbOGLprint(0.01f,0.01f, 1.f, 1.f, 0.f, echofps); /* glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_1D); */ nframes ++; glutSwapBuffers(); } void cleanup (void) { printf("done with app clean up, ogl version %2.1f ...\n",vcbGetOGLVersion()); fflush(stdout); } float tlut[256*4]; int main(int argc, char ** argv) { vcbdatatype dtype; int i, j, n, ndims, orig, nvals, dummy; int sliceid; float hitcnt, hiterr, corners[8][4]; double red; vcbCustomizeColorTableColdHot(tlut, 0, 255); for (i = 0; i < 256; i ++) tlut[i * 4+3] = 1.f; mainwin = initGLUT(argc,argv); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr,"glew error, initialization failed\n"); fprintf(stderr,"Glew Error: %s\n", glewGetErrorString(err)); } abbox.low[0] = abbox.low[1] = abbox.low[2] = 1e6; abbox.high[0] = abbox.high[1] = abbox.high[2] = -1e6; list_id = glGenLists(1); glNewList(list_id, GL_COMPILE); glBegin(GL_QUADS); for (npara = 0; (n = get_pixelf(&sliceid,&hitcnt,&hiterr,corners)) > 0; npara ++) { /* for (i = 0; i < 8; i ++) printf("%f, %f, %f, %f\n", corners[i][0], corners[i][1], corners[i][2], corners[i][3]); */ correctCornersf3d(corners, NULL); realCubef(corners, vdata); for (i = 0; i < 6*4; i ++) { abbox.low [0] = VCB_MINVAL(abbox.low [0],vdata[i*4]); abbox.high[0] = VCB_MAXVAL(abbox.high[0],vdata[i*4]); abbox.low [1] = VCB_MINVAL(abbox.low [1],vdata[i*4+1]); abbox.high[1] = VCB_MAXVAL(abbox.high[1],vdata[i*4+1]); abbox.low [2] = VCB_MINVAL(abbox.low [2],vdata[i*4+2]); abbox.high[2] = VCB_MAXVAL(abbox.high[2],vdata[i*4+2]); } red = (16+log10(hitcnt+1e-16)); if (red < 0) red = 0; if (red > 16) red = 16; glColor3fv(&tlut[((int)(red+0.5))*16*4]); for (i = 0; i < 6; i ++) for (j = 0; j < 4; j ++) glVertex3fv(&vdata[(i*4+j)*4]); } glEnd(); glEndList(); printf("number of parallelipeds = %d\n",npara); printf("bounding box: (%f %f %f) (%f %f %f)\n",abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); wireframe = 1; initApp(); /* initialize the application */ initGLsettings(); makeGrid(); gtex = vcbBindOGLTexture2D(GL_TEXTURE0, GL_NEAREST, GL_LUMINANCE, GL_LUMINANCE, GL_FLOAT, gridtexsz, gridtexsz, gridtex, GL_MODULATE, NULL); atexit(cleanup); //glutKeyboardFunc(keys); //glColor4f(0.7038f, 0.27048f, 0.0828f, 1.0f); glColor4f(1.f, 1.f, 1.f, 1.0f); glutMainLoop(); return 0; } <file_sep>/binner/src/counts.c /** \ingroup rebinner_tests \file src/counts.c \brief CURRENT test of core API -- binnerio.h. Sums total counts in a gmesh $Id$ */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <string.h> #include <sys/time.h> #include "atypes.h" #include "binnerio.h" /* application specific data starts here */ int nverts, npara; float vdata[1024]; /* end of application specific data */ bbox abbox; char inputbuf[1024]; int list_id; float xmin, xmax, ymin, ymax; int main(int argc, char ** argv) { int n, nzero, sliceid; float hitcnt, hiterr, corners[8][4]; float totalhitcnt, totalhiterr; float maxcnt, maxerr, mincnt, minerr; nzero = 0; totalhitcnt = 0; totalhiterr = 0; maxcnt = 0; maxerr = 0; mincnt = 1e6; minerr = 1e6; for (npara = 0; (n = get_pixelf(&sliceid,&hitcnt,&hiterr,corners)) > 0; ) { if (hitcnt > 1e-16) { nzero ++; totalhitcnt += hitcnt; totalhiterr += hiterr; if (maxcnt < hitcnt) maxcnt = hitcnt; if (maxerr < hiterr) maxerr = hiterr; if (mincnt > hitcnt) mincnt = hitcnt; if (minerr > hiterr) minerr = hiterr; } npara ++; if (argc > 1) if (npara % 50000 == 0) { printf("number of parallelipeds = %d, nonempty = %d\n",npara, nzero); printf("tc: %e c: [%e, %e]\nte: %e e: [%e, %e]\n", totalhitcnt, mincnt, maxcnt, totalhiterr, minerr, maxerr); } } printf("number of parallelipeds = %d, nonempty = %d\n",npara, nzero); printf("tc: %e c: [%e, %e]\nte: %e e: [%e, %e]\n", totalhitcnt, mincnt, maxcnt, totalhiterr, minerr, maxerr); return 0; } <file_sep>/binner/include/clip.h /** \ingroup rebinner_core \file include/clip.h \brief CURRENT core API -- base module to support bin_para3dclip in binner.h $Id$ */ #ifndef _BINNERCLIP_ #define _BINNERCLIP_ #define INTERP( t, x1, x2 ) ( (x1) + (t) * ((x2) - (x1)) ) #ifdef __cplusplus extern "C" { #endif int clip(int nv, double * verts, double * vbuf, int * onbuf, double * cplane); int clip_polyhedral(int nfaces, int ** nverts, double ** verts, double * cplane); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/compvol.c /** \ingroup rebinner_tests \file src/compvol.c \brief CURRENT test of core API -- binnerio.h, volume.h. $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binnerio.h" #include "volume.h" int main(int argc, char ** argv) { int nfacets, n; double * vdata, * v; int * nverts; /* at most 200 facets */ double volume; /* double vdata[128];*/ /* input has at most 1k vertices */ vdata = malloc(1024 * 3 * sizeof(double)); /* input has at most 200 facets */ nverts = malloc(200 * sizeof(int)); for (nfacets = 0, v = vdata; (n = get_polygond(v)) > 0; nfacets ++) { nverts[nfacets] = n; v += n * 3; } volume = polyhedral_volume(nfacets, nverts, vdata); printf("volume = %16.14lf \n", volume); return 0; } <file_sep>/binner/script/binnermake.sh #!/bin/sh # README: # # RUN IN A CLEAN AND SAFE DIRECTORY ONLY. # # THIS SCRIPT GRABS THE LATEST FILES IN SVN AND BUILDS # THE ENTIRE BINNER DIRECTORY # THIS SCRIPT OVERWRITES FILES AND SUB-DIECTORIES # BEFORE BUILDING BINNER, VCB AND LDFR LIBRIRIES. # # AT PRESENT, VCB AND LDFR ARE BUILT AS ONE PACKAGE # ALTHOUGH THEY ARE INDEPENDENT OF EACH OTHER. # # THIS SCRIPT IS MODIFIED FROM A SIMILAR SCRIPT FOR # VCBLIB. THAT SCRIPT WAS CALL LIB_MAKE, FIRST WRITTEN # BY <NAME> AND LATER MAINTAINED BY <NAME>. # # END OF README. #default values build="release" checkout="yes" opengl="OpenGL" #check arguments for arg ; do if [ $arg = "debug" ] ; then build="debug" elif [ $arg = "noco" ] ; then checkout="no" elif [ $arg = "noogl" ] ; then opengl="no-OpenGL" else echo "Usage: lib_make [debug] [noco] [noogl]" >&2 echo "The \"noco\" option will prevent checking code out again." >&2 echo "The \"debug\" option will cause the library to be compiled with -g." echo "The \"noogl\" option will cause opengl related part to be excluded." echo "Options can be added in any order." exit 1 fi done #report settings to be used echo "Build mode: $build, $checkout, $opengl" >&2 echo "SVN Checkout: $checkout" >&2 #build cd vcb/src if [ opengl = "OpenGL" ] ; then make -f makefile_withgl else make fi cd ../../src make all make install make clean exit 0 <file_sep>/binner/script/rebinone.sh #!/bin/bash TOP=.. rebinproc="${TOP}/bin/netrebin" from="${TOP}/bin/getfrom" to="${TOP}/bin/giveto" count=0 while : do #$from $nd $sp | $rebinproc 0.1 | $to $nd $cp $from $1 $2 | $rebinproc 0.04 | $to $1 $3 if [ $? -ne 0 ];then break fi ((count++)) done echo "done with $count tasks" exit 0 <file_sep>/binner/include/volume.h /** \ingroup rebinner_core \file include/volume.h \brief CURRENT core API -- volume calculation function: partialvoxel_volume $Id$ */ #ifndef _BINNERVOLUME_ #define _BINNERVOLUME_ #ifdef __cplusplus extern "C" { #endif double tri_area(double *v); void center_vertex(int n, double * v, double * ctr); double polygon_area(int n, double *v); double pyramid_volume(int n, double * apex, double * v); double polyhedral_volume(int nfacets, int * nverts, double * v); double partialvoxel_volume( int nwf, /* number of working facets - clipping planes */ int * nv, /* number of vertices on each working face */ double * wf, /* vertices on working facets */ int * worig, double cellsize); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/script/getstats_g3 #!/usr/bin/env python import dircache import drplot import numpy import pylab HOSTS = {"gemini": 0, "molly": 1, "orion": 2, "dev": 3} starttime = [] hostname = [] jobtime = [] rebintime = [] rebinvol = [] rebinthp = [] recordedcnts = [] nonemptybins = [] inputpix = [] realtime = [] usertime = [] systime = [] def get_col_val(istr, **kwargs): units = kwargs.get('units', False) thp = kwargs.get('thp', False) percent = kwargs.get('percent', False) stime = kwargs.get('stime', False) volume = kwargs.get('volume', False) parts = istr.split(':') if units: return parts[-1].split()[0].strip() if thp: return parts[-1].split()[3].strip() if percent: return parts[-1].split()[0].strip().strip('%') if stime: min = float(istr.split()[-1].split('m')[0]) sec = float(istr.split()[-1].split('m')[1].rstrip('s')) return sec + (min * 60.0) if volume: size = 1 for x in parts[-1].split(): size *= int(x) return size return parts[-1].strip() for ifile in dircache.listdir('.'): if not ifile.endswith('.out'): continue ifileh = open(ifile, 'r') ilines = ifileh.readlines() ifileh.close() for iline in ilines: if "Start" in iline: starttime.append(int(get_col_val(iline))) elif "Hostname" in iline: hname = get_col_val(iline) hostname.append(HOSTS[hname]) elif "Job Time" in iline: jobtime.append(int(get_col_val(iline))) elif "real" in iline: realtime.append(get_col_val(iline, stime=True)) elif "user" in iline: usertime.append(get_col_val(iline, stime=True)) elif "sys" in iline: systime.append(get_col_val(iline, stime=True)) elif "rebin throughput" in iline: rebinthp.append(float(get_col_val(iline, units=True))) elif "num_pixels processed" in iline: inputpix.append(int(get_col_val(iline))) elif "recorded total cnt" in iline: recordedcnts.append(float(get_col_val(iline))) elif "nonempty bins" in iline: nonemptybins.append(int(get_col_val(iline))) elif "volume size" in iline: rebinvol.append(get_col_val(iline, volume=True)) # Get the fraction of the rebinned volume that is occupied rebinvolnp = numpy.array(rebinvol, dtype=numpy.float64) nonemptybinsnp = numpy.array(nonemptybins, dtype=numpy.float64) rebinfrac = nonemptybinsnp / rebinvolnp * 100.0 starttimenp = numpy.array(starttime) jobtimenp = numpy.array(jobtime) totaltime = starttime + jobtime mintime = numpy.min(starttimenp) maxtime = numpy.max(totaltime) print "Total Run Time:", maxtime - mintime, "seconds" xaxis = numpy.arange(len(starttime)) f1 = pylab.figure(1) pylab.subplot(3,5,1) drplot.plot_1D_arr(xaxis, numpy.array(jobtime), xlabel="Slice ID", ylabel="Job Time (sec)") pylab.subplot(3,5,2) drplot.plot_1D_arr(xaxis, numpy.array(starttime), xlabel="Slice ID", ylabel="Start Time (Unix sec)") pylab.subplot(3,5,3) drplot.plot_1D_arr(xaxis, numpy.array(rebinthp), xlabel="Slice ID", ylabel="Rebin Throughput (pix/sec)") pylab.subplot(3,5,4) drplot.plot_1D_arr(xaxis, rebinfrac, xlabel="Slice ID", ylabel="Rebin Volume (% occ)") pylab.subplot(3,5,5) drplot.plot_1D_arr(xaxis, numpy.array(recordedcnts), xlabel="Slice ID", ylabel="Recorded Total Counts") pylab.subplot(3,5,6) drplot.plot_1D_arr(xaxis, numpy.array(inputpix), xlabel="Slice ID", ylabel="Input Pixels") pylab.subplot(3,5,7) drplot.plot_1D_arr(xaxis, numpy.array(realtime), xlabel="Slice ID", ylabel="Real Time (sec)") pylab.subplot(3,5,8) drplot.plot_1D_arr(xaxis, numpy.array(usertime), xlabel="Slice ID", ylabel="User Time (sec)") pylab.subplot(3,5,9) drplot.plot_1D_arr(xaxis, numpy.array(systime), xlabel="Slice ID", ylabel="Sys Time (sec)") pylab.subplot(3,5,10) drplot.plot_1D_arr(xaxis, numpy.array(nonemptybins), xlabel="Slice ID", ylabel="Non-Empty Bins") pylab.subplot(3,5,11) drplot.plot_1D_arr(numpy.array(jobtime), numpy.array(recordedcnts), xlabel="Job Time (sec)", ylabel="Recorded Total Counts") pylab.subplot(3,5,12) drplot.plot_1D_arr(numpy.array(jobtime), numpy.array(rebinthp), xlabel="Job Time (sec)", ylabel="Rebin Throughput (pix/sec)") pylab.subplot(3,5,13) drplot.plot_1D_arr(numpy.array(jobtime), rebinfrac, xlabel="Job Time (sec)", ylabel="Rebin Volume (% occ)") pylab.subplot(3,5,14) drplot.plot_1D_arr(numpy.array(rebinthp), rebinfrac, xlabel="Rebin Throughput (pix/sec)", ylabel="Rebin Volume (% occ)") pylab.subplot(3,5,15) drplot.plot_1D_arr(numpy.array(hostname), numpy.array(jobtime), xlabel="Host", ylabel="Job Time (sec)") pylab.show() <file_sep>/binner/vcb/src/CMakeLists.txt set(TOP ${PROJECT_SOURCE_DIR}) if(NOT BINNER_INSTALL_DIR) set(DEST ${TOP}) else(NOT BINNER_INSTALL_DIR) set(DEST ${BINNER_INSTALL_DIR}) endif(NOT BINNER_INSTALL_DIR) include_directories( ${TOP}/include ) add_definitions("-O3") set(SRCS dllist.c jval.c jrb.c fields.c dmem.c exhash.c hilbert.c zcurve.c intersect.c kernel.c raycasting.c nr.c nrcomplex.c nrutil.c vcbbtree.c vcbcolor.c vcbcluster.c vcbdebug.c vcbhist.c vcbfitting.c vcbimage.c vcblinalg.c vcbmath.c vcbmcube.c vcbmntree.c vcbops.c vcbrange.c vcbspcurve.c vcbtrimesh.c vcbutils.c vcbvolren.c vbutrcast.c vcblic.cpp Lic.cpp slic.cpp slic_aux.cpp ) add_library(vcbnogl STATIC ${SRCS}) if (NOT NOGL) set(GLSRCS ${SRCS} ArcBall.cpp glew.c splatting.c vcbglutils.c ) #find_package(OPENGL REQUIRED) #find_package(GLUT REQUIRED) include(${TOP}/CMakeModules/OpenGLConfig.cmake) include_directories( ${OPENGL_INCLUDE_DIR} ${GLUT_INCLUDE_DIR} ) add_library(vcbgl STATIC ${GLSRCS}) target_link_libraries(vcbgl ${OPENGL_glu_LIBRARY} ${OPENGL_gl_LIBRARY} ${GLUT_LIBRARY}) install(TARGETS vcbnogl vcbgl LIBRARY DESTINATION ${DEST}/lib ARCHIVE DESTINATION ${DEST}/lib) else(NOT NOGL) install(TARGETS vcbnogl LIBRARY DESTINATION ${DEST}/lib ARCHIVE DESTINATION ${DEST}/lib) endif(NOT NOGL) <file_sep>/binner/vcb/libtestsrc/makefile SHELL = /bin/sh C++ = g++ CC = gcc ifeq ($(BUILD),debug) CCFLAGS := -g else CCFLAGS := -O3 endif INCLUDE = -I. -I../include -I/usr/include/GL LIB_PATH = -L../lib -L/usr/lib LIBS = -lvcb -lm EXECUTABLES = vcbcomp vcbrcast vcbhead vcbrange vcbcut .SUFFIXES: .cc .c .cpp .cc.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .cpp.o: $(C++) $(CCFLAGS) $(INCLUDE) -c $< .c.o: $(CC) $(CCFLAGS) $(INCLUDE) -c $< all: $(EXECUTABLES) vcbcomp: vcbcomp.o $(CC) -o $@ $(CFLAGS) vcbcomp.o $(LIB_PATH) $(LIBS) vcbrcast: vcbrcast.o $(CC) -o $@ $(CCFLAGS) vcbrcast.o $(LIB_PATH) $(LIBS) vcbhead: vcbhead.o $(CC) -o $@ $(CCFLAGS) vcbhead.o $(LIB_PATH) $(LIBS) vcbrange: vcbrange.o $(CC) -o $@ $(CCFLAGS) vcbrange.o $(LIB_PATH) $(LIBS) vcbcut: vcbcut.o $(CC) -o $@ $(CCFLAGS) vcbcut.o $(LIB_PATH) $(LIBS) clean: rm -f $(EXECUTABLES) *.o core *~ install: all mv -f $(EXECUTABLES) ../bin/ <file_sep>/binner/include/macros.h /** \file include/macros.h \brief CURRENT basic global settings in the rebinner package. $Id$ */ #ifndef _BINNERMACROS_ #define _BINNERMACROS_ /*! \def BINNER_EPSILON Rebinner truncates all numbers smaller than threshold to zero. */ #ifndef BINNER_EPSILON #define BINNER_EPSILON 1e-6 #endif /*! A convenience macro to compute the norm of a vector \a n.*/ #define BINNER_NORM(n) sqrt((n)[0]*(n)[0]+(n)[1]*(n)[1]+(n)[2]*(n)[2]) #define REBINDEBUG 0 #endif<file_sep>/binner/script/generate_report.sh #!/bin/bash #use: generate_report.sh logfile TOP=.. logfile=$1 grep rebinproc $logfile | cut -f2 -d" " > t1 grep throughput $logfile | cut -f2 -d":" | cut -f2 -d" " > t2 grep time $logfile | cut -f2 -d":" | cut -f2 -d" " > t3 grep percentage $logfile | cut -f2 -d":" | cut -f2 -d" " | cut -f1 -d"%" > t4 echo "res num_p/s sec %non_empty" paste t1 t2 t3 t4 rm t1 t2 t3 t4 exit 0 <file_sep>/binner/src/clip3d.c /** \ingroup rebinner_tests \file src/clip3d.c \brief CURRENT test of core API -- binnerio.h, clip.h $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binner.h" #include "clip.h" #include "binnerio.h" int main(int argc, char ** argv) { int nfacets, n; double * vdata, * v, norm; double plane[4]; int * nverts; /* at most 200 facets */ plane[0] = (double)atof(argv[1]); plane[1] = (double)atof(argv[2]); plane[2] = (double)atof(argv[3]); plane[3] = (double)atof(argv[4]); /* normalize the normal. adjust d accordingly */ norm = vec_normalize(plane); plane[3] /= norm; /* input has at most 1k vertices */ vdata = malloc(1024 * 3 * sizeof(double)); /* input has at most 200 facets */ nverts = malloc(200 * sizeof(int)); for (nfacets = 0, v = vdata; (n = get_polygond(v)) > 0; nfacets ++) { nverts[nfacets] = n; v += n * 3; } nfacets = clip_polyhedral(nfacets, &nverts, &vdata, plane); binnerout_phcd(nfacets, nverts, vdata); /*printf("%d \n", nfacets);*/ return nfacets; } <file_sep>/binner/include/cell.h /** \ingroup rebinner_core \file include/cell.h \brief CURRENT core API -- functions to generate cells and fix topology $Id$ */ #ifndef _BINNERCELL_ #define _BINNERCELL_ #ifdef __cplusplus extern "C" { #endif int basicCubef(float * v); int basicCubed(double * v); int realCubef(float (* corners)[4], float * v); int realCube3d(double * corners, double * v); int correctCornersf3d(float (* vertices)[4], int * ids); void parallelipedByInputd(double * v); void parallelipedByInputf(float * v); void facetsRot3f(int nfacets, float * v, float * axis, float angle); int facetsScale3f(int nfacets, float * v, float * s); void facetsTrans3d(int nfacets, float *v, float * t); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/gmeshb2t.c /** \ingroup rebinner_execs \file src/gmeshb2t.c \brief CURRENT executable to convert from binary to ASCII gmesh formats. gmesht2b < BINARY_gmesh > ASCII_gmesh \note This executable is designed to act as a filter. $Id$ */ #include <stdlib.h> #include <stdio.h> int main(int argc, char ** argv) { int nfacets, i, buf[1]; double vdata[4 + 8*3]; for (nfacets = 0; ; nfacets ++) { if (fread(buf, sizeof(int), 1, stdin) <= 0) break; printf("%d", buf[0]); fread(vdata, sizeof(double), 4 + 8 *3, stdin); for (i = 0; i < 4 + 8 *3; i ++) printf(" %le", vdata[i]); printf("\n"); } return nfacets; } <file_sep>/binner/vcb/libtestsrc/CMakeLists.txt set(TOP ${PROJECT_SOURCE_DIR}) include_directories( ${TOP}/include ) add_definitions("-O3") link_libraries(vcbnogl m) add_executable(vcbcomp vcbcomp.c) add_executable(vcbrcast vcbrcast.c) add_executable(vcbhead vcbhead.c) add_executable(vcbrange vcbrange.c) add_executable(vcbcut vcbcut.c) if(NOT BINNER_INSTALL_DIR) set(DEST ${TOP}) else(NOT BINNER_INSTALL_DIR) set(DEST ${BINNER_INSTALL_DIR}) endif(NOT BINNER_INSTALL_DIR) install(TARGETS vcbcomp vcbrcast vcbhead vcbrange vcbcut RUNTIME DESTINATION ${DEST}/bin LIBRARY DESTINATION ${DEST}/lib ARCHIVE DESTINATION ${DEST}/lib) <file_sep>/binner/src/gmeshrot2.c /** \ingroup rebinner_execs \file src/gmeshrot2.c \brief DEPRECATED executable for rotating gmesh geometry. \deprecated due to input format change. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include "vcblinalg.h" int main(int argc, char ** argv) { int nfacets, i, n, sliceid; float mat[16], v0[4], v1[4], axis[3], angle; float vdata[1024]; float emin, emax, hitcnt, hiterr; char * buf; int lastchar[50], c; axis[0] = (float)atof(argv[1]); axis[1] = (float)atof(argv[2]); axis[2] = (float)atof(argv[3]); angle = -(float)atof(argv[4]); buf = malloc(1024*8); for (nfacets = 0; fgets(buf, 1024*8, stdin) != NULL; nfacets ++) { for (i = 0, c = 0; buf[i] != '\0'; i ++) if (isspace(buf[i])) { buf[i] = '\0'; lastchar[c] = i; c ++; } c = 0; sliceid = atoi(buf+c); c = lastchar[0] + 1; emin = (float)atof(buf + c); c = lastchar[1] + 1; emax = (float)atof(buf + c); c = lastchar[2] + 1; hitcnt = (float)atof(buf +c); c = lastchar[3] + 1; hiterr = (float)atof(buf +c); c = lastchar[4] + 1; for (n = 0; n < 8 * 3; n ++) { vdata[n] = (float)atof(buf + c); c = lastchar[n + 5] + 1; } for (i = 0; i < 8; i ++) { v0[0] = vdata[i*3]; v0[1] = vdata[i*3+1]; v0[2] = vdata[i*3+2]; v0[3] = 1.f; vcbMatMult4fv(v1, mat, v0); vdata[i*3] = v1[0]; vdata[i*3+1] = v1[1]; vdata[i*3+2] = v1[2]; /*printvertexf(v1, 3);*/ //printf(" %f %f %f", v1[0], v1[1], v1[2]); } fwrite(&sliceid, sizeof(int), 1, stdout); fwrite(&emin, sizeof(float), 1, stdout); fwrite(&emax, sizeof(float), 1, stdout); fwrite(&hitcnt, sizeof(float), 1, stdout); fwrite(&hiterr, sizeof(float), 1, stdout); fwrite(vdata, sizeof(float), 8*3, stdout); } free(buf); return nfacets; } <file_sep>/binner/script/getstats_old #!/usr/bin/env python import dircache import drplot import numpy import pylab starttime = [] hostname = [] jobtime = [] rebintime = [] rebinvol = [] rebinthp_ps = [] rebinthp_tot = [] recordedcnts = [] rebinbatchsize = [] bins = [] inputtime = [] outputtime = [] realtime = [] usertime = [] systime = [] def get_col_val(istr, **kwargs): units = kwargs.get('units', False) thp = kwargs.get('thp', False) percent = kwargs.get('percent', False) stime = kwargs.get('stime', False) parts = istr.split(':') if units: return parts[-1].split()[0].strip() if thp: return parts[-1].split()[3].strip() if percent: return parts[-1].split()[0].strip().strip('%') if stime: min = float(istr.split()[-1].split('m')[0]) sec = float(istr.split()[-1].split('m')[1].rstrip('s')) return sec + (min * 60.0) return parts[-1] for ifile in dircache.listdir('.'): if not ifile.endswith('.out'): continue ifileh = open(ifile, 'r') ilines = ifileh.readlines() ifileh.close() for iline in ilines: if "Start" in iline: starttime.append(int(get_col_val(iline))) elif "Hostname" in iline: hostname.append(get_col_val(iline)) elif "recorded total cnt" in iline: recordedcnts.append(float(get_col_val(iline))) elif "Job Time" in iline: jobtime.append(int(get_col_val(iline))) elif "all bins" in iline: bins.append(int(get_col_val(iline))) elif "rebin time" in iline: rebintime.append(float(get_col_val(iline, units=True))) elif "batch size" in iline: rebinbatchsize.append(int(get_col_val(iline, units=True))) elif "rebin throughput" in iline: rebinthp_ps.append(float(get_col_val(iline, units=True))) rebinthp_tot.append(int(get_col_val(iline, thp=True))) elif "rebinned volume" in iline: rebinvol.append(float(get_col_val(iline, percent=True))) elif "real" in iline: realtime.append(get_col_val(iline, stime=True)) elif "user" in iline: usertime.append(get_col_val(iline, stime=True)) elif "sys" in iline: systime.append(get_col_val(iline, stime=True)) elif "output time" in iline: outputtime.append(float(get_col_val(iline, units=True))) elif "input time" in iline: inputtime.append(float(get_col_val(iline, units=True))) xaxis = numpy.arange(len(starttime)) f1 = pylab.figure(1) pylab.subplot(4,5,1) drplot.plot_1D_arr(xaxis, numpy.array(jobtime), xlabel="Slice ID", ylabel="Job Time (sec)") pylab.subplot(4,5,2) drplot.plot_1D_arr(xaxis, numpy.array(rebintime), xlabel="Slice ID", ylabel="Rebin Time (sec)") pylab.subplot(4,5,3) drplot.plot_1D_arr(xaxis, numpy.array(starttime), xlabel="Slice ID", ylabel="Start Time (Unix sec)") pylab.subplot(4,5,4) drplot.plot_1D_arr(xaxis, numpy.array(rebinthp_ps), xlabel="Slice ID", ylabel="Rebin Throughput (pix/sec)") pylab.subplot(4,5,5) drplot.plot_1D_arr(xaxis, numpy.array(rebinthp_tot), xlabel="Slice ID", ylabel="Rebin Throughput (total)") pylab.subplot(4,5,6) drplot.plot_1D_arr(xaxis, numpy.array(rebinvol), xlabel="Slice ID", ylabel="Rebin Volume (% occ)") pylab.subplot(4,5,7) drplot.plot_1D_arr(xaxis, numpy.array(recordedcnts), xlabel="Slice ID", ylabel="Recorded Total Counts") pylab.subplot(4,5,8) drplot.plot_1D_arr(xaxis, numpy.array(inputtime), xlabel="Slice ID", ylabel="Input Time (sec)") pylab.subplot(4,5,9) drplot.plot_1D_arr(xaxis, numpy.array(outputtime), xlabel="Slice ID", ylabel="Output Time (sec)") pylab.subplot(4,5,10) drplot.plot_1D_arr(xaxis, numpy.array(realtime), xlabel="Slice ID", ylabel="Real Time (sec)") pylab.subplot(4,5,11) drplot.plot_1D_arr(xaxis, numpy.array(usertime), xlabel="Slice ID", ylabel="User Time (sec)") pylab.subplot(4,5,12) drplot.plot_1D_arr(xaxis, numpy.array(systime), xlabel="Slice ID", ylabel="Sys Time (sec)") pylab.subplot(4,5,13) drplot.plot_1D_arr(xaxis, numpy.array(bins), xlabel="Slice ID", ylabel="Bins") pylab.subplot(4,5,14) drplot.plot_1D_arr(xaxis, numpy.array(rebinbatchsize), xlabel="Slice ID", ylabel="Rebin Batch Size") pylab.subplot(4,5,15) drplot.plot_1D_arr(numpy.array(jobtime), numpy.array(rebintime), xlabel="Job Time (sec)", ylabel="Rebin Time (sec)") pylab.subplot(4,5,16) drplot.plot_1D_arr(numpy.array(rebintime), numpy.array(recordedcnts), xlabel="Rebin Time (sec)", ylabel="Recorded Total Counts") pylab.subplot(4,5,17) drplot.plot_1D_arr(numpy.array(rebintime), numpy.array(rebinthp_ps), xlabel="Rebin Time (sec)", ylabel="Rebin Throughput (pix/sec)") pylab.subplot(4,5,18) drplot.plot_1D_arr(numpy.array(rebintime), numpy.array(rebinvol), xlabel="Rebin Time (sec)", ylabel="Rebin Volume (% occ)") pylab.subplot(4,5,19) drplot.plot_1D_arr(numpy.array(rebinthp_ps), numpy.array(rebinvol), xlabel="Rebin Throughput (pix/sec)", ylabel="Rebin Volume (% occ)") pylab.show() <file_sep>/binner/src/sorter.c /** \ingroup rebinner_sdk \file src/sorter.c \brief CURRENT sdk executable to dispatch jobs in distributed rebinner runs. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include "dllist.h" #include "jval.h" #include "socketfun.h" #include "binnerio.h" typedef struct sorter_thread { pthread_t tid; int socket; int offset; int nbytes; int status; /* 0: untouched, 1: in progress, 2: succeeded, -1: failed */ char * buffer; } task_t; Dllist taskpool; pthread_mutex_t lock1, lock2; int tasksz, taskpool_sz; int taskcnt[2]; /* read the next k paralleliped from fd, -1 ret means all done */ int read_nextask(int tasksz, void * buf) { int i, n; char * v; static double vdata[1024]; v = buf; for (n = 0; (n < tasksz) && ((i = get_polygond(vdata)) > 0); ) { memcpy(v+n, &i, sizeof(int)); n += sizeof(int); memcpy(v+n, vdata, i*3*sizeof(double)); n += i*3*sizeof(double); } /* fprintf(stderr,"read_nextask: want %d bytes, got %d bytes\n",tasksz, n); */ return n; /* number of facets */ } void * sorter_thread(void * sock) { task_t * me; Dllist tmp; int s, n; s = *((int *) sock); fprintf(stderr,"sorter_thread %d tasks in pool ...", taskpool_sz); if (taskpool -> flink == taskpool) /* nothing in the pool */ { pthread_mutex_lock(&lock1); taskcnt[1] = 1; write(s, taskcnt, sizeof(int)*2); pthread_mutex_unlock(&lock1); close(s); pthread_exit(NULL); } if (taskpool_sz <= 1) /* last task in the pool */ { pthread_mutex_lock(&lock1); taskcnt[1] = 1; //write(s, taskcnt, sizeof(int)*2); pthread_mutex_unlock(&lock1); } fprintf(stderr,"%d %d ...\n", taskcnt[0], taskcnt[1]); /* otherwise, let's do something */ pthread_mutex_lock(&lock1); tmp = taskpool->flink; me = (task_t *) jval_v(dll_val(tmp)); dll_delete_node(tmp); taskpool_sz --; write(s, taskcnt, sizeof(int)*2); taskcnt[0] ++; pthread_mutex_unlock(&lock1); /*fprintf(stderr,"want to write %d bytes to fd: %d\n", me->nbytes, me->socket);*/ n = write(s, me->buffer, me->nbytes); /* if (n < 0) perror("write n"); */ /*fprintf(stderr,"wrote %d bytes, 0x%x\n", n, me->buffer);*/ close(s); /* get mutax and do a read */ pthread_mutex_lock(&lock2); n = read_nextask(tasksz, me->buffer); pthread_mutex_unlock(&lock2); if (n > 0) { me-> nbytes = n; pthread_mutex_lock(&lock1); dll_append(taskpool, new_jval_v(me)); taskpool_sz ++; pthread_mutex_unlock(&lock1); } else { free(me->buffer); free(me); } pthread_exit(NULL); } int main(int argc, char ** argv) { int sock1, sock2, port; int i, readin; task_t *t; pthread_t tid; pthread_attr_t attr[1]; FILE * portnum_file; taskcnt[0] = taskcnt[1] = 0; sock1 = server_setup(argv[1], &port); fprintf(stderr, "%s server_setup: serving socket port. %d\n", argv[0], port); /* task buf size are pre-determined on cmd-line argument */ /* size of task pool is also pre-determined on cmd-line */ tasksz = (sizeof(int) + 4*3*sizeof(double))*30; /* *10*6; */ taskpool_sz = 20; taskpool = new_dllist(); pthread_mutex_init(&lock1, NULL); pthread_mutex_init(&lock2, NULL); /* buffered read in bunches. buffer sized to fill at least 10 tasks */ for (i = 0, readin = 0; i < taskpool_sz; i ++) { t = malloc(sizeof(task_t)); t -> buffer = malloc(tasksz); t -> nbytes = read_nextask(tasksz, t->buffer); readin += t->nbytes; if (t -> nbytes > 0) dll_append(taskpool, new_jval_v(t)); else { free(t->buffer); free(t); break; } } taskpool_sz = i; /* fprintf(stderr,"done readin = %d bytes, taskpool_sz = %d\n", readin, taskpool_sz); dll_traverse(tmp, taskpool) fprintf(stderr,"taskpool 0x%x\n", jval_v(dll_val(tmp))); */ /* work as a web server. * upon request, spawn off a new thread to serve the request * write() call according to the offset and length in the buffer */ portnum_file = fopen("sorterport.num","w"); fprintf(portnum_file,"%d\n", port); fflush(portnum_file); fclose(portnum_file); for (; taskpool_sz > 0; ) { sock2 = accept_connection(sock1); pthread_attr_init(attr); pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM); pthread_create(&tid, attr, sorter_thread, &sock2); } free_dllist(taskpool); close(sock1); return 0; } <file_sep>/binner/src/cell.c /** \ingroup rebinner_core \file src/cell.c \brief CURRENT core API -- implementation for cell.h $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "vcblinalg.h" #include "cell.h" #include "geometry.h" static float verticesf[16][4] = {{0, 0, 0, 0}, /* vertex 0, 4 dims */ {1, 0, 0, 0}, /* vertex 1 */ {1, 1, 0, 0}, /* vertex 2 */ {0, 1, 0, 0}, /* vertex 3 */ {0, 0, 1, 0}, /* vertex 4 */ {1, 0, 1, 0}, /* vertex 5 */ {1, 1, 1, 0}, /* vertex 6 */ {0, 1, 1, 0}, /* vertex 7 */ {0, 0, 0, 1}, /* vertex 8 */ {1, 0, 0, 1}, /* vertex 9 */ {1, 1, 0, 1}, /* vertex 10 */ {0, 1, 0, 1}, /* vertex 11 */ {0, 0, 1, 1}, /* vertex 12 */ {1, 0, 1, 1}, /* vertex 13 */ {1, 1, 1, 1}, /* vertex 14 */ {0, 1, 1, 1}}; /* vertex 15 */ static double verticesd[16][4] = {{0, 0, 0, 0}, /* vertex 0, 4 dims */ {1, 0, 0, 0}, /* vertex 1 */ {1, 1, 0, 0}, /* vertex 2 */ {0, 1, 0, 0}, /* vertex 3 */ {0, 0, 1, 0}, /* vertex 4 */ {1, 0, 1, 0}, /* vertex 5 */ {1, 1, 1, 0}, /* vertex 6 */ {0, 1, 1, 0}, /* vertex 7 */ {0, 0, 0, 1}, /* vertex 8 */ {1, 0, 0, 1}, /* vertex 9 */ {1, 1, 0, 1}, /* vertex 10 */ {0, 1, 0, 1}, /* vertex 11 */ {0, 0, 1, 1}, /* vertex 12 */ {1, 0, 1, 1}, /* vertex 13 */ {1, 1, 1, 1}, /* vertex 14 */ {0, 1, 1, 1}}; /* vertex 15 */ static int quads3d[6][4] = {{0, 3, 2, 1}, /* out facing quads */ {4, 5, 6, 7}, {1, 2, 6, 5}, {2, 3, 7, 6}, {3, 0, 4, 7}, {0, 1, 5, 4}}; int basicCubef(float * v) { int i, j, cnt; /* return value: number of floats written in v */ for (i = 0, cnt = 0; i < 6; i ++) { for (j = 0; j < 4; cnt += 3, j ++) memcpy(&v[cnt], &verticesf[quads3d[i][j]], 3*sizeof(float)); } return cnt; } int basicCubed(double * v) { int i, j, cnt; /* return value: number of floats written in v */ for (i = 0, cnt = 0; i < 6; i ++) { for (j = 0; j < 4; cnt += 3, j ++) memcpy(&v[cnt], &verticesd[quads3d[i][j]], 3*sizeof(double)); } return cnt; } int realCubef(float (* corners)[4], float * v) /* corners: input, v: output quad list */ { /* assume corners has at least (8 corners) * 4 coordinate floats */ /* assume v has at least (6 * 4 vertices) * 4 coordinate floats */ /* assume all coordinates are in 4d space */ int i, j; for (i = 0; i < 6; i ++) for (j = 0; j < 4; j ++) memcpy(&v[(i*4 + j)*4], corners[quads3d[i][j]], 4 * sizeof(float)); return 6; } int realCube3d(double * corners, double * v) /* corners: input, v: output quad list */ { /* * a derivative of realCubef. * this time assuming input is in 3d coordinates * already sorted in the correct vertex order */ int i, j; for (i = 0; i < 6; i ++) for (j = 0; j < 4; j ++) memcpy(&v[(i*4 + j)*3], &corners[quads3d[i][j]*3], 3 * sizeof(double)); return 6; } static void swapVec4(float * v1, float * v2) { int j; float tmp [4]; for (j = 0; j < 4; j ++) { tmp[j] = v1[j]; v1[j] = v2[j]; v2[j] = tmp[j]; } } static void swapVec4_id(float * v1, float * v2, int * id1, int * id2) { int j; float tmp [4]; for (j = 0; j < 4; j ++) { tmp[j] = v1[j]; v1[j] = v2[j]; v2[j] = tmp[j]; } j = id1[0]; id1[0] = id2[0]; id2[0] = j; } static float ordermetric(float * ctr, float * n, float * v1, float * v2) { float vec1[4], vec2[4], cross[4]; int i; float val; for (i = 0; i < 4; i ++) { vec1[i] = v1[i] - ctr[i]; vec2[i] = v2[i] - ctr[i]; } la_cross3(cross, vec1, vec2); val = la_norm3(cross); if (la_dot3(n, cross) > 0) val *= -1; return val; } int correctCornersf3d(float (* vertices)[4], int * ids) /* vertices: input/output */ { /* assume vertices has at least 8 * 4 floats */ /* assume all coordinates are in x,y,z,w */ int i, j, k; float ctr[4], normals[8][4], fnormal[4], fctr[4]; int d; float distvec[4], dist; float tab[4]; int lh[2], step = 0, pivot, opposite; ctr[0] = ctr[1] = ctr[2] = ctr[3] = 0.f; for (i = 0; i < 8; i ++) { for (j = 0; j < 4; j ++) ctr[j] += vertices[i][j]/8.f; } for (lh[0] = 0, lh[1] = 7, step = 0; lh[0] < lh[1]; step ++) { pivot = lh[step%2]; opposite = lh[1 - (step%2)]; for (i = lh[0], d = pivot, dist = 0.f; i <= lh[1]; i ++) { for (j = 0; j < 4; j ++) distvec[j] = vertices[i][j] - vertices[pivot][j]; if (la_norm3(distvec) > dist) { dist = la_norm3(distvec); d = i; } } if (opposite != d) { #ifdef DEBUG printf("exchanging vertex %d with vertex %d\n", opposite, d); #endif if (ids == NULL) swapVec4(vertices[opposite], vertices[d]); else swapVec4_id(vertices[opposite], vertices[d], ids + opposite, ids+ d); } if (pivot < opposite) lh[0]++; else lh[1]--; } for (i = 0; i < 8; i ++) { for (j = 0; j < 4; j ++) normals[i][j] = vertices[i][j] - ctr[j]; la_normalize3(normals[i]); } /* now we have 2 oppositing faces, let's make vertices appear in the right order */ for (i = 0; i < 4; i ++) { fctr[i] = 0; fnormal[i] = 0; for (j = 0; j < 4; j ++) { fnormal[i] += normals[j][i]; fctr[i] += vertices[j][i]/4.f; } } la_normalize3(fnormal); for (k = 0; k < 2; k ++) { for (j = k; j < 4; j ++) tab[j] = ordermetric(fctr, fnormal, vertices[k], vertices[j]); for (i = k+1, d = 0, dist = 0; i < 4; i ++) { if (dist < tab[i]) { dist = tab[i]; d = i; } } if ( k+1 != d) { #ifdef DEBUG printf("exchanging vertex %d with vertex %d\n", k+1, d); #endif if (ids == NULL) swapVec4(vertices[k+1], vertices[d]); else swapVec4_id(vertices[k+1], vertices[d], ids + k+1, ids+ d); } } /* now need to align the vertices on two faces, basically fix the anchors at 0 and 4 */ for (k = 0; k < 4; k ++) { for (i = 0, dist = 1e6; i < 4; i ++) { for (j = 0; j < 4; j ++) distvec[j] = vertices[i+4][j] - vertices[k][j]; if (la_norm3(distvec) < dist) { dist = la_norm3(distvec); d = i+4; } } if ( k + 4 != d) { #ifdef DEBUG printf("exchanging vertex %d with vertex %d\n", d, k+4); #endif if (ids == NULL) swapVec4(vertices[d], vertices[k+4]); else swapVec4_id(vertices[d], vertices[k+4], ids + d, ids+ k+4); } } return 0; } void parallelipedByInputd(double * v) { int i, j, cnt; for (i = 0; i < 8; i ++) scanf("%lf, %lf, %lf, %lf\n", &verticesd[i][0], &verticesd[i][1], &verticesd[i][2], &verticesd[i][3]); for (i = 0, cnt = 0; i < 6; i ++) { for (j = 0; j < 4; cnt += 3, j ++) memcpy(&v[cnt], &verticesd[quads3d[i][j]], 3*sizeof(double)); } } void parallelipedByInputf(float * v) { int i, j, cnt; for (i = 0; i < 8; i ++) scanf("%f, %f, %f, %f\n", &verticesf[i][0], &verticesf[i][1], &verticesf[i][2], &verticesf[i][3]); for (i = 0, cnt = 0; i < 6; i ++) { for (j = 0; j < 4; cnt += 3, j ++) memcpy(&v[cnt], &verticesf[quads3d[i][j]], 3*sizeof(float)); } } void vRot3f(int n, float * v, float * axis, float angle) { int i; float mat[16], v0[4], v1[4]; vcbRotate3fv(mat, axis, angle); v0[3] = 1.f; for (i = 0; i < n; i ++) { v0[0] = v[i*3+0]; v0[1] = v[i*3+1]; v0[2] = v[i*3+2]; vcbMatMult4fv(v1, mat, v0); v[i*3+0] = v1[0]; v[i*3+1] = v1[1]; v[i*3+2] = v1[2]; } } void vScale3f(int n, float * v, float * s) /* scale factors s[3] */ { int i; float mat[16], v0[4], v1[4]; vcbScale3fv(mat, s); v0[3] = 1.f; for (i = 0; i < n; i ++) { v0[0] = v[i*3+0]; v0[1] = v[i*3+1]; v0[2] = v[i*3+2]; vcbMatMult4fv(v1, mat, v0); v[i*3+0] = v1[0]; v[i*3+1] = v1[1]; v[i*3+2] = v1[2]; } } void vTrans3f(int n, float *v, float * t) /* translat factors t[3] */ { int i; float mat[16], v0[4], v1[4]; vcbTranslate3fv(mat, t); v0[3] = 1.f; for (i = 0; i < n; i ++) { v0[0] = v[i*3+0]; v0[1] = v[i*3+1]; v0[2] = v[i*3+2]; vcbMatMult4fv(v1, mat, v0); v[i*3+0] = v1[0]; v[i*3+1] = v1[1]; v[i*3+2] = v1[2]; } } /* for (i = 0; i < 6; i ++) { for (j = 0; j < 4; j ++) printvertex(vertices[quads3d[i][j]], 3); printf("\n"); } return 0; */ <file_sep>/binner/src/largebmeshrebin.c #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include "vcblinalg.h" #include "vcbutils.h" #include "binnerio.h" #include "binner.h" #include "cell.h" #include "volume.h" /** * $Id$ * */ static char md5string[100], fname[200], fullname[200], rbuf[8192]; static float vbuf[1024]; void scale_vertices(int n, double * vdata,double xscale, double yscale, double zscale) { int i; float mat[16], v0[4], v1[4], s[3]; double *v; s[0] = (float) xscale; s[1] = (float) yscale; s[2] = (float) zscale; vcbScale3fv(mat, s); v0[3] = 1.f; for (i = 0, v = vdata; i < n; v+= 3, i ++) { v0[0] = (float)v[0]; v0[1] = (float)v[1]; v0[2] = (float)v[2]; vcbMatMult4fv(v1, mat, v0); v[0] = v1[0]; v[1] = v1[1]; v[2] = v1[2]; } } int main(int argc, char ** argv) { clock_t time1, time2; int i, j, n, f, npara, sliceid, res, nvoxel, orig[3], xyzsize[3], nonempty; double * vdata, * hcnt, * herr, spacing[3]; int * nverts, * sid; double totalvolume, cellsize, tmp, askbounds[6]; double * voxels; float hitcnt, hiterr, corners[8][4]; float rebintime = 0; int FV = 0; /* 0 - FV unspecified; 1 - FV specified */ double volumescale; /* always assume FV is there */ i = getchar(); ungetc(i, stdin); if (i == 'M') { /* * if an md5string is provided * all results will be saved to a MR-JH directory */ fgets(rbuf, 8192, stdin); /* get everything on that first line */ sscanf(rbuf, "%s", md5string); /* sprintf(fname, "%s.bin", md5string); fgets(md5string, 100, stdin); get whatever that is left on this line */ sprintf(fname, "mkdir %s\n", md5string); system(fname); sprintf(fname, "%s",md5string); } else fname[0] = 0; /* f = atoi(argv[2]); */ scanf("%d", &f); fgets(md5string, 100, stdin); /* get whatever that is left on this line */ fprintf(stderr, "rebin data name : %s\n", fname); vdata = malloc(f * 6 * 4 * 3 * sizeof(double)); nverts = malloc(f * 6 * sizeof(int)); hcnt = malloc(f * sizeof(double)); herr = malloc(f * sizeof(double)); sid = malloc(f * sizeof(int)); i = getchar(); ungetc(i, stdin); if (i == 'F') { /* ignore FV field so far */ j = getchar(); j = getchar(); if (j != 'V') fprintf(stderr, "wrong input format on line #3: FV ... FV field\n"); fgets(rbuf, 8192, stdin); /* get everything on that first line */ /* if (argc < 2) */ if (strlen(rbuf) > 20) /* not empty between the beginning and ending FV field */ { sscanf(rbuf, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d %d %d", &vdata[0], &vdata[1], &vdata[2], &vdata[3], &vdata[4], &vdata[5], &vdata[6], &vdata[7], &vdata[8], &vdata[9], &vdata[10], &vdata[11], &vdata[12], &vdata[13], &vdata[14], &vdata[15], &vdata[16], &vdata[17], &vdata[18], &vdata[19], &vdata[20], &vdata[21], &vdata[22], &vdata[23], &xyzsize[0],&xyzsize[1], &xyzsize[2]); bounding_box(8, askbounds, vdata); fprintf(stderr, "asking x domain : %.3lf %.3lf\n", askbounds[0], askbounds[1]); fprintf(stderr, "asking y domain : %.3lf %.3lf\n", askbounds[2], askbounds[3]); fprintf(stderr, "asking z domain : %.3lf %.3lf\n", askbounds[4], askbounds[5]); fprintf(stderr, "asking dimension : %d %d %d\n", xyzsize[0], xyzsize[1], xyzsize[2]); for (j = 0; j < 3; j++) spacing[j] = (askbounds[j*2+1] - askbounds[j*2])/xyzsize[j]; fprintf(stderr, "asking bin size : %e %e %e\n", spacing[0], spacing[1], spacing[2]); FV = 1; } } if (FV != 1) { fprintf(stderr, "%s cannot find a valid FV field. aborting rebinning process ...\n", argv[0]); free(sid); free(herr); free(hcnt); free(voxels); free(nverts); free(vdata); exit(-1); } { res = 100; /* this is the default resolution */ if (argc > 1) res = atoi(argv[1]); cellsize = (askbounds[1] - askbounds[0])/res; tmp = (askbounds[3] - askbounds[2])/res; if (tmp > cellsize) cellsize = tmp; tmp = (askbounds[5] - askbounds[4])/res; if (tmp > cellsize) cellsize = tmp; orig[0] = (int)floor(askbounds[0]/cellsize); orig[1] = (int)floor(askbounds[2]/cellsize); orig[2] = (int)floor(askbounds[4]/cellsize); xyzsize[0] = (int)ceil(askbounds[1]/cellsize) - orig[0]+1; xyzsize[1] = (int)ceil(askbounds[3]/cellsize) - orig[1]+1; xyzsize[2] = (int)ceil(askbounds[5]/cellsize) - orig[2]+1; spacing[0] = spacing[1] = spacing[2] = cellsize; volumescale = 1.0; } fprintf(stderr, "rebin volume origin : %d %d %d\n", orig[0], orig[1], orig[2]); fprintf(stderr, "rebin volume size : %d %d %d\n", xyzsize[0], xyzsize[1], xyzsize[2]); fprintf(stderr, "rebin bin size : %e %e %e\n", cellsize, cellsize, cellsize); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double)); totalvolume = 0; while (1) { time1 = clock(); for (npara = 0; (n = get_pixelf(&sliceid,&hitcnt,&hiterr,corners)) > 0; npara ++) { if (npara >= f) break; /* read at most f faces, i.e. f/6 parallelipeds */ correctCornersf3d(corners, NULL); realCubef(corners, vbuf); hcnt[npara] = hitcnt; herr[npara] = hiterr; sid[npara] = sliceid; for (i = 0; i < 6*4; i ++) { vdata[(npara*6*4+i)*3+0] = vbuf[i*4+0]; vdata[(npara*6*4+i)*3+1] = vbuf[i*4+1]; vdata[(npara*6*4+i)*3+2] = vbuf[i*4+2]; } for (i = 0; i < 6; i ++) nverts[npara*6+i] = 4; } if (npara <= 0) break; /* exit point: we are done with all slices */ bounding_box(npara*6*4, askbounds, vdata); fprintf(stderr, "slice %04d x domain : %.3lf %.3lf\n", sid[0], askbounds[0], askbounds[1]); fprintf(stderr, "slice %04d y domain : %.3lf %.3lf\n", sid[0], askbounds[2], askbounds[3]); fprintf(stderr, "slice %04d z domain : %.3lf %.3lf\n", sid[0], askbounds[4], askbounds[5]); fprintf(stderr, "slice %04d has : %d paras\n", sid[0], npara); for (i = 0; i < nvoxel; voxels[i] = 0.0, i ++); totalvolume += bin_para_3dclip(sid[0], npara*6, nverts, vdata, /* the vertices */ hcnt, /* hit counter */ herr, /* hit counter error */ orig, xyzsize, cellsize, voxels, 0., 0.); time2 = clock(); rebintime += (float)(time2-time1)/CLOCKS_PER_SEC; for (i = 0; i < nvoxel; voxels[i] *= volumescale, i ++); sprintf(fullname, "%s/%04d", fname, sid[0]); nonempty += output_with_compression(fullname, xyzsize, voxels); } totalvolume *= volumescale; export_VTKhdr(fname, orig, xyzsize, spacing, nonempty); fprintf(stderr, "rebin time : %.3f sec\n", rebintime); fprintf(stderr, "rebin throughput : %.2f per second\n", f/rebintime); fprintf(stderr, "recorded count sum : %e\n", totalvolume); fprintf(stderr, "nonempty bins : %d\n", nonempty); fprintf(stderr, "all bins : %d\n", nvoxel); fprintf(stderr, "nonempty percentage : %.2f%%\n", (float)nonempty/nvoxel*100); free(sid); free(herr); free(hcnt); free(voxels); free(nverts); free(vdata); return 0; } <file_sep>/binner/script/numbers.sh #!/bin/bash # use: numbers.sh 10 100 2 # this generate all numbers between 10 and 100 use an incremental of 2 for (( i = $1; i <= $2; i = $i + $3)) do if [ $i -lt 10 ]; then echo -n 000$i " " continue fi if [ $i -lt 100 ]; then echo -n 00$i " " continue fi if [ $i -lt 1000 ]; then echo -n 0$i " " continue fi echo -n $i " " done echo exit 0 <file_sep>/binner/script/bmeshrebin_server.sh #!/bin/bash # use: bmeshrebin_server hostname port_number resolution TOP=.. serveproc="${TOP}/bin/serve" rebinproc="${TOP}/bin/bmeshrebin" logfile="${TOP}/log/bmeshrebin_server.log" echo -n "server up at : " >> $logfile echo `date` >> $logfile $serveproc $1 $2 2>>$logfile | $rebinproc $3 2>>$logfile echo >> $logfile exit 0 <file_sep>/binner/src/rebinapp.c /** \ingroup rebinner_core \file src/rebinapp.c \brief CURRENT core API -- implementation for rebinapp.h $Id$ */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "vcblinalg.h" #include "binner.h" #include "binnerio.h" static char * versionstring = "1.1.0"; char * rebinner_versionstring() { return versionstring; } void scale_vertices(int n, double * vdata,double xscale, double yscale, double zscale) { int i; float mat[16], v0[4], v1[4], s[3]; double *v; s[0] = (float) xscale; s[1] = (float) yscale; s[2] = (float) zscale; vcbScale3fv(mat, s); v0[3] = 1.f; for (i = 0, v = vdata; i < n; v+= 3, i ++) { v0[0] = (float)v[0]; v0[1] = (float)v[1]; v0[2] = (float)v[2]; vcbMatMult4fv(v1, mat, v0); v[0] = v1[0]; v[1] = v1[1]; v[2] = v1[2]; } } double fv_bounds(double * askbounds, double * spacing, int * orig, int * xyzsize) { /* return value: double cellsize */ /* inputs: askbounds[3], spacing[3] */ /* outputs: orig[3], xyzsize[3] */ double cellsize; orig[0] = (int)floor(askbounds[0]/spacing[0]); orig[1] = (int)floor(askbounds[2]/spacing[1]); orig[2] = (int)floor(askbounds[4]/spacing[2]); xyzsize[0] = (int)ceil(askbounds[1]/spacing[0]) - orig[0]; /* + 1 */ xyzsize[1] = (int)ceil(askbounds[3]/spacing[1]) - orig[1]; /* + 1 */ xyzsize[2] = (int)ceil(askbounds[5]/spacing[2]) - orig[2]; /* + 1 */ /* let's figure out the actual binning cell size */ cellsize = spacing[0]; if (spacing[1] > cellsize) cellsize = spacing[1]; if (spacing[2] > cellsize) cellsize = spacing[2]; return cellsize; } double padded_bounds(double * bounds, int res, int * orig, int * xyzsize) { double cellsize, tmp; cellsize = (bounds[1] - bounds[0])/res; tmp = (bounds[3] - bounds[2])/res; if (tmp > cellsize) cellsize = tmp; tmp = (bounds[5] - bounds[4])/res; if (tmp > cellsize) cellsize = tmp; orig[0] = (int)floor(bounds[0]/cellsize); orig[1] = (int)floor(bounds[2]/cellsize); orig[2] = (int)floor(bounds[4]/cellsize); xyzsize[0] = (int)ceil(bounds[1]/cellsize) - orig[0]+1; xyzsize[1] = (int)ceil(bounds[3]/cellsize) - orig[1]+1; xyzsize[2] = (int)ceil(bounds[5]/cellsize) - orig[2]+1; return cellsize; } double rebin_byslice(int npara, int * nverts, double *vdata, /* the vertices */ int *sliceid, double *hitcnt, double *hiterr, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, char * outputpath) { int i, j, n, nonempty, nvoxel; double totalvolume = 0.0, volumescale; char fullname[200]; nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; volumescale = (cellsize/spacing[0]) * (cellsize/spacing[1]) * (cellsize/spacing[2]); volumescale = 1.0/volumescale; for (n = 0, j = 0, nonempty = 0; n < npara; n += j) { for (i = n; i < npara; i++) /* sliceid monotonically increase */ if (sliceid[i] != sliceid[n]) break; j = i - n; /* now we know this many para are on the same slice */ #if REBINDEBUG fprintf(stderr, "before rebin: n = %d, npara = %d, slice %d has %d paras\n", n, npara, sliceid[n], j); #endif for (i = 0; i < nvoxel*2; voxels[i] = 0.0, i ++); totalvolume += bin_para_3dclip( sliceid[n], j * 6, /* npara*6 */ nverts + n*6, vdata + n*6*4*3, /* the vertices */ hitcnt + n, /* hit counter */ hiterr + n, /* hit counter error */ orig, xyzsize, cellsize, voxels, 0., 0.); for (i = 0; i < nvoxel; voxels[i*2] *= volumescale, i ++); /* counts */ for (i = 0; i < nvoxel; voxels[i*2+1] *= volumescale, i ++); /* error */ totalvolume *= volumescale; sprintf(fullname, "%s/%04d", outputpath, sliceid[n]); nonempty += output_with_compression(fullname, xyzsize, voxels); fprintf(stderr, "rebinned slice %04d : %.2f%% nonempty, %d parallelipeds\n", sliceid[n], (100.f*nonempty)/nvoxel, j); /* vcbGenBinm("500.bin", VCB_DOUBLE, 3, orig, xyzsize, 2, voxels); */ #if REBINDEBUG fprintf(stderr, "rebin_slice recorded totalvolume = %lf, before scaling\n", totalvolume); for (i = 0; i < nvoxel; i ++) fprintf(stderr, "voxels[%d] = %lf error[%d] = %lf\n", i, voxels[i*2], i, voxels[i*2+1]); #endif } export_VTKhdr(outputpath, orig, xyzsize, spacing, nonempty); return totalvolume; } void printcorners(int x, int y, int z, int * orig, double * spacing) { x = x + orig[0]; y = y + orig[1]; z = z + orig[2]; printf("%f %f %f ", x*spacing[0], y*spacing[1], z*spacing[2]); } double rebin_gmesh(int npara, int * nverts, double *vdata, /* the vertices */ int *sliceid, double *hitcnt, double *hiterr, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, double emin, double emax) { int i, j, n, nonempty, nvoxel; double totalvolume = 0.0, volumescale; nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; volumescale = (cellsize/spacing[0]) * (cellsize/spacing[1]) * (cellsize/spacing[2]); volumescale = 1.0/volumescale; for (n = 0, j = 0, nonempty = 0; n < npara; n += j) { for (i = n; i < npara; i++) /* sliceid monotonically increase */ if (sliceid[i] != sliceid[n]) break; j = i - n; /* now we know this many para are on the same slice */ #if REBINDEBUG fprintf(stderr, "before rebin: n = %d, npara = %d, slice %d has %d paras\n", n, npara, sliceid[n], j); #endif if (j > 0) { #if REBINDEBUG fprintf(stderr, "calling bin_para_3dclip on %d pixels, voxels = 0x%lx\n", j, voxels); #endif totalvolume += bin_para_3dclip( sliceid[n], j * 6, /* npara*6 */ nverts + n*6, vdata + n*6*4*3, /* the vertices */ hitcnt + n, /* hit counter */ hiterr + n, /* hit counter error */ orig, xyzsize, cellsize, voxels, emin, emax); } } return totalvolume; } void gmesh_singlebin_output(double * dp, int sid, int x, int y, int z, int * orig, double * spacing) { printf("%d %le %le %le %le ", sid, dp[2], dp[3], dp[0], dp[1]); printcorners(x, y, z, orig, spacing); printcorners(x+1, y, z, orig, spacing); printcorners(x+1, y+1, z, orig, spacing); printcorners(x, y+1, z, orig, spacing); printcorners(x, y, z+1, orig, spacing); printcorners(x+1, y, z+1, orig, spacing); printcorners(x+1, y+1, z+1, orig, spacing); printcorners(x, y+1, z+1, orig, spacing); printf("\n"); } void gmesh_singlebin_output_nd( double * dp, int sid, int x, int y, int z, int * orig, double * spacing) { printf("%d %le %le %le %le %le ", sid, dp[2], dp[3], dp[0], dp[1], dp[4]); printcorners(x, y, z, orig, spacing); printcorners(x+1, y, z, orig, spacing); printcorners(x+1, y+1, z, orig, spacing); printcorners(x, y+1, z, orig, spacing); printcorners(x, y, z+1, orig, spacing); printcorners(x+1, y, z+1, orig, spacing); printcorners(x+1, y+1, z+1, orig, spacing); printcorners(x, y+1, z+1, orig, spacing); printf("\n"); } double rebin_gmesh_output( int sliceid, int * orig, int * xyzsize, double cellsize, /* assume uniform cell size, hence cubic cells */ double *spacing, double *voxels, double emin, double emax, double threshold) { int i, nonempty, nvoxel, x, y, z; double totalvolume = 0.0, volumescale; nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; volumescale = (cellsize/spacing[0]) * (cellsize/spacing[1]) * (cellsize/spacing[2]); volumescale = 1.0/volumescale; for (i = 0; i < nvoxel; voxels[i*2] *= volumescale, i ++); /* counts */ for (i = 0; i < nvoxel; voxels[i*2+1] *= volumescale, i ++); /* error */ for (i = 0, x = 0; x < xyzsize[0]; x ++) for (y = 0; y < xyzsize[1]; y ++) for (z = 0; z < xyzsize[2]; z ++) { if (voxels[i*2] < threshold) { i ++; continue;} /* gmesh_singlebin_output(&voxels[i*2], sliceid, x, y, z, orig, spacing); */ #if 1 printf("%d %e %e ", sliceid, emin, emax); printf("%le %le ", voxels[i*2], voxels[i*2+1]); printcorners(x, y, z, orig, spacing); printcorners(x+1, y, z, orig, spacing); printcorners(x+1, y+1, z, orig, spacing); printcorners(x, y+1, z, orig, spacing); printcorners(x, y, z+1, orig, spacing); printcorners(x+1, y, z+1, orig, spacing); printcorners(x+1, y+1, z+1, orig, spacing); printcorners(x, y+1, z+1, orig, spacing); printf("\n"); #endif i ++; } for (i = 0, nonempty = 0; i < nvoxel; i ++) if (voxels[i*2] > threshold) { nonempty ++; totalvolume += voxels[i*2]; } fprintf(stderr, "no. nonempty bins : %d\n", nonempty); fprintf(stderr, "rebinned volume : %.2f%% occupied\n", (100.f*nonempty)/nvoxel); #if REBINDEBUG fprintf(stderr, "rebin_slice recorded totalvolume = %lf, after scaling\n", totalvolume); for (i = 0; i < nvoxel; i ++) fprintf(stderr, "voxels[%d] = %lf error[%d] = %lf\n", i, voxels[i*2], i, voxels[i*2+1]); #endif return totalvolume; } void output_askinginfo(double * askbounds, int * xyzsize, double * spacing) { fprintf(stderr, "asking x domain : %.3lf %.3lf\n", askbounds[0], askbounds[1]); fprintf(stderr, "asking y domain : %.3lf %.3lf\n", askbounds[2], askbounds[3]); fprintf(stderr, "asking z domain : %.3lf %.3lf\n", askbounds[4], askbounds[5]); fprintf(stderr, "asking dimension : %d %d %d\n", xyzsize[0], xyzsize[1], xyzsize[2]); fprintf(stderr, "asking spacing : %e %e %e\n", spacing[0], spacing[1], spacing[2]); } void output_askinginfo_short(int * xyzsize) { fprintf(stderr, "asking x domain : unspecified\n"); fprintf(stderr, "asking y domain : unspecified\n"); fprintf(stderr, "asking z domain : unspecified\n"); fprintf(stderr, "asking dimension : %d %d %d\n", xyzsize[0], xyzsize[1], xyzsize[2]); fprintf(stderr, "asking bin size : unspecified\n"); } void output_actualinfo(double * bounds) { fprintf(stderr, "actual x domain : %.3lf %.3lf\n", bounds[0], bounds[1]); fprintf(stderr, "actual y domain : %.3lf %.3lf\n", bounds[2], bounds[3]); fprintf(stderr, "actual z domain : %.3lf %.3lf\n", bounds[4], bounds[5]); } void output_prerebininfo(int * orig, int * xyzsize, double * spacing, double cellsize) { fprintf(stderr, "rebin volume origin : %d %d %d\n", orig[0], orig[1], orig[2]); fprintf(stderr, "rebin volume size : %d %d %d\n", xyzsize[0], xyzsize[1], xyzsize[2]); fprintf(stderr, "rebin spacing : %e %e %e\n", spacing[0], spacing[1], spacing[2]); fprintf(stderr, "rebin cell size : %e\n", cellsize); } void output_postrebininfo(float rebintime, int npara, double totalvolume, int nvoxel) { fprintf(stderr, "rebinned pixels : %d\n", npara); fprintf(stderr, "rebin time : %.3f sec\n", rebintime); fprintf(stderr, "rebin throughput : %.2f pixels/sec\n", npara/rebintime); fprintf(stderr, "recorded total cnt : %le\n", totalvolume); } void output_gmesh_formaterr() { fprintf(stderr,"gmeshrebin error:\n"); fprintf(stderr,"wrong input format on stdin. need either of on line 1:\n"); fprintf(stderr,"FV: xmin xmax num_binx; ymin ymax num_biny; zmin zmax num_binz \n"); fprintf(stderr,"IV: num_bins \n"); fprintf(stderr,"line 2: number_of_pixels by itself \n"); fprintf(stderr,"line 3 and on: sid emin emax hits err [x y z] for all 8 corners \n"); } <file_sep>/binner/script/rebinit #!/usr/bin/env python import os VERSION = "1.1" REBINNER_CMD = "gmeshrebin3 -f" MULTI_THREAD_REBINNER_CMD = "map -n %d " + REBINNER_CMD ROTATE_CMD = "gmeshrot3 0 1 0" MAKE_VTK_CMD = "python /SNS/software/bin/convert_vtk_8.py" MATRIX_ROT_CMD = "gmeshmat" def myExtend(a,b): """Append the items in b into a. This does do error checking.""" if a is None: a = None if b is None or len(b) <= 0: return a for i in b: remove = False if i < 0: remove = True i = -1*i try: a.index(i) if remove: a.remove(i) except ValueError: if not remove: a.append(i) return a def generateList(args, options=None): """Convert a string list into a list of integers""" if len(args) <= 0: return [] if type(args) == type(""): args = [args] runs = [] for run in args: if run.find(",") >= 0: myExtend(runs,generateList(run.split(","))) else: try: iRun = int(run) runs.append(iRun) except: ends = run.split("-") if len(ends) == 2: ends = map(lambda x: int(x),ends) ends.sort() myExtend(runs,range(ends[0],ends[1]+1)) else: if options is not None and options.verbose: print "WARN: Skipping run \"%s\"" %run runs.sort() return runs def get_angle_map(afilename): amap = {} afile = open(afilename, 'r') for line in afile: parts = line.split() # Flip sign for convention amap[parts[0].strip()] = -1.0 * float(parts[1]) afile.close() return amap def get_queue(inst): return "asg" if inst == "ARCS": return "arcs" elif inst == "CNCS": return "cncsq" elif inst == "SEQ" or inst == "SEQUOIA": return "sequoiaq" else: raise RuntimeError("Do not have a SLURM queue for instrument %s" \ % inst) def get_value(tag, lines): for line in lines: sline = line.strip() if tag in sline: if sline.startswith('#'): return None else: return sline.split(':')[-1] return None def make_axis(avals): avals = avals.split(',') return avals def make_cmdscript(cname, mnum, amap, odir, ifiles, apar, opt): cscr = os.path.join(odir, "_".join(cname) + ".sh") if opt.verbose > 0: print "Command Script:", cscr ofile = "_".join(cname) + ".in" del cname[-1] cname.append("rbmesh"+str(mnum)) rot_file = "_".join(cname) + ".inb" fcscr = open(cscr, 'w') if opt.pbs is not None: # Setup PBS stuff print >> fcscr, "#!/bin/bash" if opt.pbs == "lens": print >> fcscr, "#PBS -A csc030" if opt.pbs == "oic": print >> fcscr, "#PBS -q nssd08q" print >> fcscr, "#PBS -j oe" if opt.walltime is None: print >> fcscr, "#PBS -l walltime=00:15:00" else: print >> fcscr, "#PBS -l walltime=%s" % opt.walltime print >> fcscr, "#PBS -l nodes=1:ppn=%d" % opt.threads p_rot_file = os.path.join(odir, rot_file) if opt.pbs is not None and opt.pbs == "oic": if os.path.exists(p_rot_file): print >> fcscr, "cp", p_rot_file, "$PBS_SCRATCH" else: for ifile in ifiles: print >> fcscr, "cp", ifile, "$PBS_SCRATCH" if opt.pbs is None or opt.pbs == "lens": print >> fcscr, "cd", odir else: print >> fcscr, "cd $PBS_SCRATCH" print >> fcscr, "start=$(date +%s)" print >> fcscr, "echo \"Start:\" ${start}" print >> fcscr, "echo \"Hostname:\" ${HOSTNAME}" print >> fcscr, "" if opt.force_rot and os.path.exists(p_rot_file): os.remove(p_rot_file) if not os.path.exists(p_rot_file): for ifile in ifiles: if opt.pbs is not None and opt.pbs == "oic": ifileb = os.path.basename(ifile) else: ifileb = ifile ifilerun = os.path.basename(ifile).split('_')[1] if opt.use_matrix is None: print >> fcscr, "cat", ifileb, "|", ROTATE_CMD, \ amap[ifilerun], ">>", rot_file else: mat_vals = " ".join(opt.use_matrix.split(',')) print >> fcscr, "cat", ifileb, "|", MATRIX_ROT_CMD, mat_vals, \ ">>", rot_file # Call rebinner command if opt.multi_thread: rebin_cmd = MULTI_THREAD_REBINNER_CMD % opt.threads else: rebin_cmd = REBINNER_CMD print >> fcscr, "time cat", rot_file, "| " + rebin_cmd, \ "-b", str(opt.batch_size), "-t", str(opt.threshold), \ " ".join(apar), ">", ofile print >> fcscr, "end=$(date +%s)" print >> fcscr, "let diff=${end}-${start}" print >> fcscr, "echo \"Job Time: ${diff}\"" if opt.pbs is not None: if opt.pbs == "oic": print >> fcscr, "cp", ofile, odir if not os.path.exists(p_rot_file): print >> fcscr, "cp", rot_file, odir fcscr.close() os.chmod(cscr, 0755) return (cscr, ofile) def make_vtkscript(outputdir, out_file, instrument, runlist, mesh_num, opt): vtkcmd = [MAKE_VTK_CMD] vtkcmd.append(os.path.join(outputdir, out_file)) vtk_name = [] vtk_name.append(instrument) vtk_name.append(str(runlist[0])) vtk_name.append("rvtk"+mesh_num) if opt.verbose: print "VTK Job name:", "_".join(vtk_name) print "VTK Input File:", vtkcmd[-1] vscr = os.path.join(outputdir, "_".join(vtk_name) + ".sh") vcscr = open(vscr, 'w') print >> vcscr, "#!/bin/bash" print >> vcscr, " ".join(vtkcmd) vcscr.close() os.chmod(vscr, 0755) voutlog_name = "_".join(vtk_name) + ".out" return (vtk_name, voutlog_name) def run(opts, tempfile, atempfile): if opts.verbose: print "Opening", tempfile tfile = open(tempfile, "r") flines = tfile.readlines() tfile.close() # Parse and retrieve all template information instrument = get_value("INST", flines) runs = get_value("RUN", flines) #import sns_inst_util #runlist = sns_inst_util.generateList(runs) runlist = generateList(runs) num_runs = len(runlist) if opts.verbose: print "Instrument:", instrument print "Runs:", runlist xaxis = make_axis(get_value("XAXIS", flines)) yaxis = make_axis(get_value("YAXIS", flines)) zaxis = make_axis(get_value("ZAXIS", flines)) axis_pars = [] axis_pars.extend(xaxis) axis_pars.extend(yaxis) axis_pars.extend(zaxis) threshold = get_value("THRESH", flines) # Get angle map if opts.use_matrix is None: angle_map = get_angle_map(atempfile) else: angle_map = None # Make a home for the output if opts.outputdir is None: basedir = os.path.join(os.path.expanduser("~/results"), instrument) outputdir = os.path.join(basedir, str(runlist[0])+"-rebin") else: outputdir = os.path.expanduser(opts.outputdir) if not os.path.exists(outputdir): os.makedirs(outputdir) if opts.verbose: print "Output File directory:", outputdir # Gather the base set of files if opts.inputdir is not None: filedir = opts.inputdir else: filedir = os.path.join(basedir, str(runlist[0]), str(runlist[0])+"-mesh") if opts.verbose: print "Input File directory:", filedir import dircache filelist = [dfile for dfile in dircache.listdir(filedir) \ if "bmesh" in dfile and dfile.endswith(".inb")] if opts.verbose > 1: print "Files:", filelist # Construct the jobs for ifile in filelist: rebin_input = [] pifile = os.path.join(filedir, ifile) rebin_input.append(pifile) if num_runs > 1: for run in runlist[1:]: rebin_input.append(pifile.replace(str(runlist[0]), str(run))) if opts.verbose > 1: print "Input files:", rebin_input mesh_num = ifile.split('bmesh')[-1].split('.')[0] if opts.min_slice != -1: if int(mesh_num) < opts.min_slice: continue if opts.max_slice != -1: if int(mesh_num) > opts.max_slice: continue base_name = [] base_name.append(instrument) base_name.append(str(runlist[0])) base_name.append("rebin"+mesh_num) job_name = "_".join(base_name) outlog_name = "_".join(base_name) + ".out" errlog_name = "_".join(base_name) + ".err" if opts.verbose > 1: print "Job name:", job_name print "Output Log name:", outlog_name (job_script, out_file) = make_cmdscript(base_name, mesh_num, angle_map, outputdir, rebin_input, axis_pars, opts) if not opts.debug: if opts.pbs is None: # Send out SLURM jobs kwargs = {} if opts.multi_thread and opts.threads > 1: kwargs["nodes"] = 1 kwargs["cpus"] = opts.threads import slurm jid = slurm.run(job_script, get_queue(instrument), outlog_name, None, verbose=opts.verbose, jobname=job_name, **kwargs) if opts.make_vtk: vjid = slurm.run(vscr, get_queue(instrument), voutlog_name, verbose=opts.verbose, precursor=jid, jobname="_".join(vtk_name)) else: import sns_os cmd = [] cmd.append("qsub") cmd.append("-N %s" % job_name) cmd.append("-o %s" % outlog_name) cmd.append(job_script) jid = sns_os.run2(" ".join(cmd)) if __name__ == "__main__": import optparse description = [] description.append("This script launches rebinning jobs using a template") description.append("file that contains the rebinning grid information.") description.append("This script assumes your files are stored in the") description.append("results directory in your home area where the run_dgs") description.append("command places its output.") parser = optparse.OptionParser("usage: %prog [options] <template file> "\ +"<angle map>", None, optparse.Option, VERSION, 'error', " ".join(description)) parser.add_option("-v", "--verbose", dest="verbose", action="count", help="Flag for turning on script verbosity") parser.add_option("-d", "--debug", dest="debug", action="store_true", help="Flag for turning off SLURM submission.") parser.set_defaults(debug=False) parser.add_option("-o", "--outputdir", dest="outputdir", help="Specify a directory to receive the rebinning "\ +"output.") parser.add_option("-n", "--inputdir", dest="inputdir", help="Specify a directory to get the rebinning input.") parser.add_option("-k", "--make-vtk", dest="make_vtk", action="store_true", help="Flag to turn on creation of vtk files from "\ +"rebining output.") parser.set_defaults(make_vtk=False) parser.add_option("-r", "--force-rot", dest="force_rot", action="store_true", help="Flag to force the creation "\ +"of the file containing rotated data information.") parser.set_defaults(force_rot=False) parser.add_option("-i", "--min-slice", dest="min_slice", type=int, help="Flag to set the minimum slice to use.") parser.set_defaults(min_slice=-1) parser.add_option("-x", "--max-slice", dest="max_slice", type=int, help="Flag to set the maximum slice to use.") parser.set_defaults(max_slice=-1) parser.add_option("-b", "--batch-size", dest="batch_size", type=int, help="Flag to set the batch size for the rebinning job.") parser.set_defaults(batch_size=10000) parser.add_option("-t", "--threshold", dest="threshold", type=float, help="Flag to set the threshold for writing rebinned "\ +"voxels to file.") parser.set_defaults(threshold=1.0e-16) parser.add_option("-m", "--multi-thread", dest="multi_thread", action="store_true", help="Trigger the use of "\ +"multi-threading") parser.set_defaults(multi_thread=False) parser.add_option("-p", "--threads", dest="threads", type=int, help="Flag to set the number of threads. Default is 1.") parser.set_defaults(threads=1) parser.add_option("", "--pbs", dest="pbs", help="Specify the PBS machine "\ +"to use.") parser.add_option("-w", "--walltime", dest="walltime", help="Set the "\ +"walltime for the PBS jobs.") parser.add_option("", "--use-matrix", dest="use_matrix", help="Use a "\ +"matrix to perform the rotation.") (options, args) = parser.parse_args() if len(args) < 2 and options.use_matrix is None: parser.error("Must specify the template file and the angle map on "\ +"the command-line") else: args.append(None) run(options, args[0], args[1]) <file_sep>/binner/src/gmeshrebin3.c /** \ingroup rebinner_execs \file src/gmeshrebin3.c \brief CURRENT executable of rebinner that rebins gmesh data. gmeshrebin3 [-f] [-b batchsize] [-t threshold] xmin xmax xspacing ymin ymax yspacing zmin zmax zspacing \li [-f]: toggle of filter mode. If set, gemeshrebin3 acts as a filter. The output is not a full fledged volume. The missing piece is implemented by reduce functions, which collects and generates a globally consistent rebinned volume. \li [-b batchsize] number of pixels to rebin as a batch. Default to 10000. \li [-t threshold] rebinner truncates values below the threshold to zero. Default to \link macros#BINNER_EPSILON BINNER_EPSILON\endlink. \note This is the only rebinner executable capable of acting as a filter, intended to be used as one of many rebinner threads, designed primarily for handling large amounts of data. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include "vcblinalg.h" #include "vcbutils.h" #include "rebinapp.h" #include "binnerio.h" #include "binner.h" #include "cell.h" #include "volume.h" #include <unistd.h> static char * usage = "usage: %s [-f] [-b batchsize] [-t threshold] \ xmin xmax xspacing ymin ymax yspacing zmin zmax zspacing\n"; int main(int argc, char ** argv) { clock_t time1, time2, time3, time4; int i, j, f, npara, sliceid, nvoxel, orig[3], xyzsize[3]; double * vdata, * hcnt, * herr, spacing[3]; int * nverts, * sid; double totalvolume = 0., cellsize, bounds[6], askbounds[6]; double * voxels; double emin, emax, threshold; float rebintime = 0, outputtime = 0, inputtime = 0; int pixelcnt = 0, c = 0, filtermode = 0; double inputv[4 + 8*3]; pid_t pid = getpid(); if ((argc < 10) || (argc > 15)) { fprintf(stderr, usage, argv[0]); exit(1); } fprintf(stderr, "rebinner version : %s\n", rebinner_versionstring()); f = 10000; threshold = 1e-16; while (argc > 10) { if (strcmp(argv[c+1],"-f") == 0) { filtermode = 1; argc -= 1; c += 1; } else if (strcmp(argv[c+1],"-b") == 0) { f = (int)(atof(argv[c+2])); argc -= 2; c += 2; } else if (strcmp(argv[c+1],"-t") == 0) { threshold = atof(argv[c+2]); argc -= 2; c += 2; } else { fprintf(stderr, usage, argv[0]); exit(1); } } #if REBINDEBUG fprintf(stderr, "rebinner batch size : %d pixels\n", f); fprintf(stderr, "rebinner threshold : %le \n", threshold); #endif askbounds[0] = atof(argv[c+1]); askbounds[1] = atof(argv[c+2]); spacing[0] = atof(argv[c+3]); askbounds[2] = atof(argv[c+4]); askbounds[3] = atof(argv[c+5]); spacing[1] = atof(argv[c+6]); askbounds[4] = atof(argv[c+7]); askbounds[5] = atof(argv[c+8]); spacing[2] = atof(argv[c+9]); for (j = 0; j < 3; j++) xyzsize[j] = (int)ceil((askbounds[j*2+1] - askbounds[j*2])/spacing[j]); if (filtermode < 1) output_askinginfo(askbounds, xyzsize, spacing); for (j = 0; j < 3; j++) spacing[j] = (askbounds[j*2+1] - askbounds[j*2])/xyzsize[j]; cellsize = fv_bounds(askbounds, spacing, orig, xyzsize); if (filtermode < 1) output_prerebininfo(orig, xyzsize, spacing, cellsize); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; if (filtermode == 1) voxels = NULL; /* NULL tells rebin_gmesh to output voxel directly on stdout */ else { voxels = malloc(nvoxel * sizeof(double) * 2); /* rebin both counts and error */ for (i = 0; i < nvoxel*2; voxels[i] = 0.0, i ++); } vdata = malloc(f * 6 * 4 * 3 * sizeof(double)); nverts = malloc(f * 6 * sizeof(int)); hcnt = malloc(f * sizeof(double)); herr = malloc(f * sizeof(double)); sid = malloc(f * sizeof(int)); while (1) { time3 = clock(); #if REBINDEBUG fprintf(stderr, "%d ready to take new inputs. lasttime did %d pixels\n", pid, npara); #endif /* read at most f pixels in each pass */ for (npara = 0; npara < f; npara ++) { if (fread(&sliceid, sizeof(int), 1, stdin) <= 0) { #if REBINDEBUG fprintf(stderr, "%d did not read correct sliceid\n", pid); #endif break; /* did not read in a correct pixel */ } if (fread(inputv, sizeof(double), 4 + 8 *3, stdin) < 28) { #if REBINDEBUG fprintf(stderr, "%d did not read correct doubles\n", pid); #endif break; /* did not read in a correct pixel */ } realCube3d(inputv + 4, &vdata[(npara*6*4)*3]); for (i = 0; i < 6; i ++) nverts[npara*6+i] = 4; emin = inputv[0]; emax = inputv[1]; hcnt[npara] = inputv[2];//hitcnt; herr[npara] = inputv[3];//hiterr; sid[npara] = sliceid; #if REBINDEBUG fprintf(stderr, "sid, emin, emax, hcnt, herr: %d %f %f %lf %lf\n", sid[npara], inputv[0], inputv[1], hcnt[npara], herr[npara]); #endif } #if REBINDEBUG fprintf(stderr, "%d done reading inputs: %d pixels\n", pid, npara); #endif if (npara <= 0) { #if REBINDEBUG fprintf(stderr, "%d read no more pixels. quitting\n", pid); #endif break; /* did not read in any pixels */ } /* bounding_box(npara*6*4, bounds, vdata); //#if REBINDEBUG output_actualinfo(bounds); //#endif */ time4 = clock(); inputtime += (float)(time4-time3)/CLOCKS_PER_SEC; time1 = clock(); #if REBINDEBUG fprintf(stderr, "%d begin scaling %d pixels\n", pid, npara); #endif scale_vertices( npara * 6 * 4, vdata, cellsize/spacing[0], cellsize/spacing[1], cellsize/spacing[2]); pixelcnt += npara; #if REBINDEBUG fprintf(stderr, "%d begin rebinning\n", pid); #endif rebin_gmesh(npara, nverts, vdata, /* the vertices */ sid, hcnt, /* hit counter */ herr, /* hit counter error */ orig, xyzsize, cellsize, spacing, voxels, emin, emax); time2 = clock(); #if REBINDEBUG fprintf(stderr, "%d completes rebinning %d pixels, %d total\n", pid, npara, pixelcnt); #endif rebintime += (float)(time2-time1)/CLOCKS_PER_SEC; if (npara < f) break; /* cannot read enough inputs to fullfill pipeline */ } #if REBINDEBUG fprintf(stderr, "%d finished rebinning %d pixels\n", pid, pixelcnt); #endif if (filtermode == 0) { time3 = clock(); totalvolume = rebin_gmesh_output(sid[0], orig, xyzsize, cellsize, spacing, voxels, emin, emax, threshold); time4 = clock(); outputtime += (float)(time4-time3)/CLOCKS_PER_SEC; fprintf(stderr, "rebin input time : %f sec\n", inputtime); fprintf(stderr, "rebin input rate : %.3f MB/sec\n", pixelcnt*(sizeof(int)+sizeof(double)*(4 + 8 *3)/inputtime/1e6)); fprintf(stderr, "rebin output time : %f sec\n", outputtime); output_postrebininfo(rebintime, pixelcnt, totalvolume, nvoxel); } free(sid); free(herr); free(hcnt); if (filtermode == 0) free(voxels); free(nverts); free(vdata); return 0; } <file_sep>/binner/include/binner.h /** \ingroup rebinner_core \file include/binner.h \brief CURRENT core API -- main rebinner functions bin_para3d[clip/voxelize] $Id$ */ #ifndef _BINNER_ #define _BINNER_ #include <math.h> #include "macros.h" #ifdef __cplusplus extern "C" { #endif void cal_normal(double * n, double * v); double vec_normalize(double * n); void bounding_box(int n, double * bound, double * v); double para_volume(double * v); /* volume of a paralleliped */ /** * edge + corner voxels * return value: subdivision factor in the final discrete volume * for achieving the etorl. * all voxels are assumed to be uniformly sized in all dimensions * * iterate until meeting this criterion: * etol[0]: the maximum allowed per boundary voxel error tolerance, * as a percentage of the voxel's space * etol[1-3]: the final achieved max/min/avg etol * double etol[4]: must be pre-allocated * */ int esti_res3d( int nfacets, double *v, double volume, double *xyzunit, double *tol_relativeE); /** * upon voxelization, since we need a multi-level resolutioned representation * the volume is not held in a single array * * instead, we use a red-black tree to hold a pointer to all the smaller volume * blocks. each block can be of a different resolution, going from a different * origin (and hence be of different sizes) */ int bin_quad3d( int nfacets, double *v, double volume, int * orig, int * xyzsize, double *xyzunit, int maxres, double *voxel); double bin_para_3dvoxelize( int nfacets, int * nverts, double *v, /* the vertices */ int * orig, int * xyzsize, double ccs, /* cubic cell size */ double *voxels); /** This function return the total volume of the rebinned parallelipeds. There is no limit on how many parallelipeds can be processed together. \param[in] v Pointer to vertices array describing the parallelipeds. \param[in] hitcnt Pointer to hit counts array for the parallelipeds. \param[in] hiterr Pointer to hit error metrics array for the parallelipeds. \param[out] voxels If this is a NULL pointer, the function dumps the rebinned voxels directly through pipedump; otherwise voxels is assumed to have enough memory space to store xyzsize[0]*xyzsize[1]*xyzsize[2] double values. */ double bin_para_3dclip( int sliceid, int nfacets, int * nverts, double *v, /* the vertices */ double *hitcnt, double *hiterr, int * orig, int * xyzsize, double ccs, /* cubic cell size, assume uniform cell size */ double *voxels, double emin, double emax); #ifdef __cplusplus } /* extern C */ #endif #endif <file_sep>/binner/src/gmeshrebin2.c /** \ingroup rebinner_execs \file src/gmeshrebin2.c \brief DEPRECATED executable of rebinner that handles gmesh formats. \deprecated gmeshrebin2 [-b batchsize] [-t threshold] xmin xmax xspacing ymin ymax yspacing zmin zmax zspacing \li [-b batchsize] number of pixels to rebin as a batch. Default to 10000. \li [-t threshold] rebinner truncates values below the threshold to zero. Default to \link macros#BINNER_EPSILON BINNER_EPSILON\endlink. \note This executable has been deprecated due to the lack of ability to act as a streaming filter. Its memory footprint is directly related to the volume size. $Id$ */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include "vcblinalg.h" #include "vcbutils.h" #include "rebinapp.h" #include "binnerio.h" #include "binner.h" #include "cell.h" #include "volume.h" char rbuf[8192]; float vbuf[1024]; int main(int argc, char ** argv) { clock_t time1, time2, time3, time4; int i, j, f, npara, sliceid, nvoxel, orig[3], xyzsize[3]; double * vdata, * hcnt, * herr, spacing[3]; int * nverts, * sid; double totalvolume = 0., cellsize, bounds[6], askbounds[6]; double * voxels; double emin, emax, threshold; float rebintime = 0, outputtime = 0, inputtime = 0; int pixelcnt = 0, c = 0; double inputv[4 + 8*3]; if ((argc != 10) && (argc != 12) && (argc != 14)) { fprintf(stderr, "usage: %s [-b batchsize] [-t threshold] xmin xmax xspacing ymin ymax yspacing zmin zmax zspacing\n", argv[0]); exit(1); } fprintf(stderr, "rebinner version : %s\n", rebinner_versionstring()); /* f: number of pixels to rebin together, default to 10000 */ f = 10000; threshold = 1e-16; while (argc > 10) { if (strcmp(argv[c+1],"-b") == 0) { f = (int)(atof(argv[c+2])); argc -= 2; c += 2; } else if (strcmp(argv[c+1],"-t") == 0) { threshold = atof(argv[c+2]); argc -= 2; c += 2; } else { fprintf(stderr, "usage: %s [-b batchsize] [-t threshold] xmin xmax xspacing ymin ymax yspacing zmin zmax zspacing\n", argv[0]); exit(1); } } fprintf(stderr, "rebinner batch size : %d pixels\n", f); fprintf(stderr, "rebinner threshold : %le \n", threshold); askbounds[0] = atof(argv[c+1]); askbounds[1] = atof(argv[c+2]); spacing[0] = atof(argv[c+3]); askbounds[2] = atof(argv[c+4]); askbounds[3] = atof(argv[c+5]); spacing[1] = atof(argv[c+6]); askbounds[4] = atof(argv[c+7]); askbounds[5] = atof(argv[c+8]); spacing[2] = atof(argv[c+9]); for (j = 0; j < 3; j++) xyzsize[j] = (int)ceil((askbounds[j*2+1] - askbounds[j*2])/spacing[j]); output_askinginfo(askbounds, xyzsize, spacing); for (j = 0; j < 3; j++) spacing[j] = (askbounds[j*2+1] - askbounds[j*2])/xyzsize[j]; cellsize = fv_bounds(askbounds, spacing, orig, xyzsize); output_prerebininfo(orig, xyzsize, spacing, cellsize); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double) * 2); /* rebin both counts and error */ for (i = 0; i < nvoxel*2; voxels[i] = 0.0, i ++); vdata = malloc(f * 6 * 4 * 3 * sizeof(double)); nverts = malloc(f * 6 * sizeof(int)); hcnt = malloc(f * sizeof(double)); herr = malloc(f * sizeof(double)); sid = malloc(f * sizeof(int)); while (1) { time3 = clock(); /* read at most f pixels in each pass */ for (npara = 0; npara < f; npara ++) { if (fread(&sliceid, sizeof(int), 1, stdin) <= 0) break; /* did not read in a correct pixel */ fread(inputv, sizeof(double), 4 + 8 *3, stdin); realCube3d(inputv + 4, &vdata[(npara*6*4)*3]); for (i = 0; i < 6; i ++) nverts[npara*6+i] = 4; emin = inputv[0]; emax = inputv[1]; hcnt[npara] = inputv[2];//hitcnt; herr[npara] = inputv[3];//hiterr; sid[npara] = sliceid; #if REBINDEBUG fprintf(stderr, "sid, emin, emax, hcnt, herr: %d %f %f %lf %lf\n", sid[npara], inputv[0], inputv[1], hcnt[npara], herr[npara]); #endif } if (npara <= 0) break; /* did not read in any pixels */ bounding_box(npara*6*4, bounds, vdata); #if REBINDEBUG output_actualinfo(bounds); #endif time4 = clock(); inputtime += (float)(time4-time3)/CLOCKS_PER_SEC; time1 = clock(); scale_vertices( npara * 6 * 4, vdata, cellsize/spacing[0], cellsize/spacing[1], cellsize/spacing[2]); pixelcnt += npara; rebin_gmesh(npara, nverts, vdata, /* the vertices */ sid, hcnt, /* hit counter */ herr, /* hit counter error */ orig, xyzsize, cellsize, spacing, voxels, emin, emax); time2 = clock(); rebintime += (float)(time2-time1)/CLOCKS_PER_SEC; } time3 = clock(); totalvolume = rebin_gmesh_output(sid[0], orig, xyzsize, cellsize, spacing, voxels, emin, emax, threshold); time4 = clock(); outputtime += (float)(time4-time3)/CLOCKS_PER_SEC; fprintf(stderr, "rebin input time : %f sec\n", inputtime); fprintf(stderr, "rebin input rate : %.3f MB/sec\n", pixelcnt*(sizeof(int)+sizeof(double)*(4 + 8 *3)/inputtime/1e6)); fprintf(stderr, "rebin output time : %f sec\n", outputtime); output_postrebininfo(rebintime, pixelcnt, totalvolume, nvoxel); free(sid); free(herr); free(hcnt); free(voxels); free(nverts); free(vdata); return 0; } <file_sep>/binner/src/clip.c /** \ingroup rebinner_core \file src/clip.c \brief CURRENT core API -- implementation for clip.h $Id$ */ #include <stdlib.h> #include <string.h> #include <math.h> #include "vcblinalg.h" #include "binner.h" #include "clip.h" #define INTERP( t, x1, x2 ) ( (x1) + (t) * ((x2) - (x1)) ) void vertex_interp(double t, double * result, double * v1, double * v2) { result[0] = INTERP(t, v1[0], v2[0]); result[1] = INTERP(t, v1[1], v2[1]); result[2] = INTERP(t, v1[2], v2[2]); } int clip(int nv, double * verts, double * vbuf, int * onbuf, double * cplane) { /* * vbuf is intended to be something like: double vbuf[3*10]; * the vertex buffer: caller should allocate for a safe number of vertices * say, more than 10 vertices in the resulting polygon? * * onbuf is of a similar intention. onbuf tells which vertices are on the cplane */ double *vp; /* iterator pointer into vbuf */ double *v; /* iterator pointer into verts */ double *s; int i, ninside; double ddist, sdist, t; s = verts + (nv - 1) * 3; /* s is the starting point */ /* vp is the current point */ for (i = 0, ninside = 0, vp = vbuf, v = verts; i < nv; v+= 3, i ++) { ddist = VCB_DOT(v, cplane) + cplane[3]; if (ddist < 0.0) /* d is inside */ { if ((sdist = (VCB_DOT(s, cplane) + cplane[3])) < 0.0) /* s is also inside */ ; else /* s is outside */ { /* between s and d, there is an interaction point */ ddist = fabs(ddist); sdist = fabs(sdist); t = sdist/(sdist + ddist); vertex_interp(t, vp, s, v); vp += 3; onbuf[ninside] = 1; ninside ++; } vp[0] = v[0]; vp[1] = v[1]; vp[2] = v[2]; vp += 3; onbuf[ninside] = 0; ninside ++; } else /* d is outside */ { if ((sdist = (VCB_DOT(s, cplane) + cplane[3])) < 0.0) /* s is inside */ { /* between s and d, there is an interaction point */ ddist = fabs(ddist); sdist = fabs(sdist); t = sdist/(sdist + ddist); vertex_interp(t, vp, s, v); vp += 3; onbuf[ninside] = 1; ninside ++; } else /* if s is also outside, nothing to do */ ; } s = v; } return ninside; } void swap_v1v2(double * c1, double * c2) { double tm[3]; tm[0] = c1[0]; tm[1] = c1[1]; tm[2] = c1[2]; c1[0] = c2[0]; c1[1] = c2[1]; c1[2] = c2[2]; c2[0] = tm[0]; c2[1] = tm[1]; c2[2] = tm[2]; } double clockwise_cmp(double * c1, double * c2, double * center, double * cplane) { double v1[3], v2[3], n[3]; v1[0] = c1[0] - center[0]; v1[1] = c1[1] - center[1]; v1[2] = c1[2] - center[2]; v2[0] = c2[0] - center[0]; v2[1] = c2[1] - center[1]; v2[2] = c2[2] - center[2]; VCB_CROSS(n,v1,v2); return VCB_DOT(n, cplane); } int close_enough(double * c1, double * c2) { double v1[3], dist; v1[0] = c1[0] - c2[0]; v1[1] = c1[1] - c2[1]; v1[2] = c1[2] - c2[2]; dist = BINNER_NORM(v1); if (dist <= BINNER_EPSILON) return 1; else return 0; } int build_polygon(int ne, double * inbuf, double * cplane) { int i; double center[3], *cbuf, *cp, *np; if (ne <=2) return 0; /* cannot build a meaningful polygon */ cbuf = inbuf; /* can we do a sort? */ center[0] = center[1] = center[2] = 0.0; for (i = 0, cp = cbuf; i < ne*2; cp += 3, i ++) { center[0] += cp[0]; center[1] += cp[1]; center[2] += cp[2]; } center[0] /= (ne * 2); center[1] /= (ne * 2); center[2] /= (ne * 2); /* now let's turn all edges to clockwise direction */ for (i = 0, cp = cbuf; i < ne; cp += 6, i ++) if (clockwise_cmp(cp, cp+3, center, cplane) < 0.0) swap_v1v2(cp, cp+3); /* need to flip order */ for (cp = cbuf+3; cp < cbuf + (ne*6); cp += 6) { for ( np = cp + 3; np < cbuf + (ne*6); np +=6) if (close_enough(cp, np) > 0) { swap_v1v2(cp+3, np); swap_v1v2(cp+6, np+3); } } np = inbuf; cbuf = malloc(ne * 3 * sizeof(double)); cp = cbuf; memcpy(cp, np, 3 * sizeof(double)); cp += 3; np += 3; for (i = 1; i < ne; cp += 3, np+=6, i ++) memcpy(cp, np, 3 * sizeof(double)); memcpy(inbuf, cbuf, ne*3*sizeof(double)); free(cbuf); return ne; } int clean_polyhedron(int nfacets, int ** nverts, double **v) { /* * after a sequence of clipping operations * a facet may become a single point, while an edge maybe * have its two end points being the same * * this function produces a cleaned polyhedron */ int nv[100]; double vbuf[100*3]; /* each facet has fewer than 10 vertices */ double pbuf[100*3*20]; /* each polyhedron has fewer han 20 facets */ double * vp, *vpbuf; int i, j, n, nf; nf = 0; vp = (*v); vpbuf = pbuf; for (i = 0; i < nfacets; vp += (*nverts)[i]*3, i ++) { n = 0; for (j = 0; j < (*nverts)[i]-1; j ++) if (close_enough(&vp[j*3], &vp[j*3+3]) == 0) { vbuf[n*3+0] = vp[j*3+0]; vbuf[n*3+1] = vp[j*3+1]; vbuf[n*3+2] = vp[j*3+2]; n ++; } if (close_enough(&vp[j*3], &vp[0]) == 0) { vbuf[n*3+0] = vp[j*3+0]; vbuf[n*3+1] = vp[j*3+1]; vbuf[n*3+2] = vp[j*3+2]; n ++; } if (n > 2) { nv[nf] = n; memcpy(vpbuf, vbuf, n*3*sizeof(double)); vpbuf += n*3; nf++; } } free(*nverts); free(*v); (*nverts) = malloc(nf * sizeof(int)); memcpy((*nverts), nv, nf * sizeof(int)); (*v) = malloc((vpbuf - pbuf)*sizeof(double)); memcpy((*v), pbuf, (vpbuf - pbuf)*sizeof(double)); return nf; } /* return val: number of resulting faces. >= nfacets */ int clip_polyhedral(int nfaces, int ** nverts, double ** verts, double * cplane) { /* * a polyhedral cell is described by: * nfaces: number of faces * *nverts[nfaces]: the number of vertices on each face * *verts: a linear array of vertices * * note: faces are treated as independent of each other * i.e. no mesh type of topology is stored, although such information * can be computed from the available data */ double vbuf[100 * 3], *vp; int nv, onbuf[100]; int noutfaces, * noutverts, totalvertices; double * outverts, *op; double cbuf[200*3], *cp; /* vertex buffer for polygon on clipping plane */ int nc; /* number of polygon vertices on clipping plane */ int ne; /* number of polygon edges on clipping plane */ int i, j; /* * at maximal, the new polyhedra have one more face * still assume 10 vertices per face * 3 cooridnates (xyz) on each vertex * everything in double precision */ outverts = malloc((nfaces*3)*100*3*sizeof(double)); noutverts = malloc((nfaces*3)*sizeof(int)); noutfaces = 0; op = outverts; totalvertices = 0; ne = 0; cp = cbuf; for (i = 0, vp = (*verts); i < nfaces; vp += ((*nverts)[i]*3), i ++) { nv = clip((*nverts)[i], vp, vbuf, onbuf, cplane); if (nv > 0) /* not all vertices are clipped out */ { noutverts[noutfaces] = nv; memcpy(op, vbuf, nv*3*sizeof(double)); op += nv * 3; noutfaces ++; totalvertices += nv; /* * now scan for all edges on the clipping plane * if there are > 1 edge on the clipping plane * the clipping plane should make up a new face * * actually, there should always be a new face * formed by the clipping plane, if there is truly * a cross-section/intersection */ for (j = 0; j < nv; j ++) if (onbuf[j] > 0) if (onbuf[(j + 1)%nv] > 0) if (close_enough(&vbuf[j*3],&vbuf[((j+1)%nv)*3]) == 0) { memcpy(cp, &vbuf[j*3], 3*sizeof(double)); cp += 3; memcpy(cp, &vbuf[((j+1)%nv)*3], 3*sizeof(double)); cp += 3; ne ++; } } } if (ne > 0) { nc = build_polygon(ne, cbuf, cplane); if (nc > 0) /* succeeded in building a polygon on clipping plane */ { memcpy(op, cbuf, nc*3*sizeof(double)); noutverts[noutfaces] = nc; noutfaces ++; totalvertices += nc; } } free(*nverts); free(*verts); if (noutfaces > 0) { (*nverts) = malloc(noutfaces * sizeof(int)); memcpy((*nverts), noutverts, noutfaces * sizeof(int)); (*verts) = malloc(totalvertices * 3 * sizeof(double)); memcpy((*verts), outverts, totalvertices * 3 * sizeof(double)); noutfaces = clean_polyhedron(noutfaces, nverts, verts); } else { noutfaces = 0; *nverts = NULL; *verts = NULL; } free(outverts); free(noutverts); return noutfaces; } <file_sep>/binner/src/seebmeshvol.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbglutils.h" #include "vcbmath.h" #include "atypes.h" #include "vcbvolren.h" #include "vcblinalg.h" #include "vcbcolor.h" /** * $Id$ * */ char projmode = 'O'; /* P for perspective, O for orthogonal: a toggle field*/ projStruct proj; viewStruct view; lightStruct light0; ArcBall spaceball; int iwinWidth; int iwinHeight; GLuint texobj; int mainwin, sidewin; clock_t time1, time2, time3, time4; bbox abbox; unsigned char * voxels; int nvox; float tlut[256*4]; #define FTB 1 double *binvol; int sz[3], orig[3]; int ndims,nattribs; vcbdatatype rawdatatype; int load_vox(char * dataname) { if ((binvol = (double*) vcbReadBinm(dataname, &rawdatatype, &ndims, orig, sz, &nattribs)) == NULL) { fprintf(stderr, "load_data: error loading datafile\n"); return -1; } return 0; } void load_classify(void) /* * -1 for failure, 0 for success * transflut is assumed to have valid memory allocation */ { int i; vcbCustomizeColorTableColdHot(tlut, 0, 255); for (i = 0; i < 256; i ++) tlut[i * 4+3] = 1.f; } void voxtransf (float * rgba, void * vox) { unsigned char * voxel = (unsigned char *) vox; int id = voxel[0] * 4; rgba[0] = tlut[id+0]; rgba[1] = tlut[id+1]; rgba[2] = tlut[id+2]; rgba[3] = tlut[id+3]; } void load_data(char * dataname) { unsigned char * fvox; unsigned short * cvox; int i, j, k, numvox; double val; if (load_vox(dataname) < 0) { fprintf(stderr, "load_data: error loading datafile\n"); exit(-1); } load_classify(); nvox = 0; for (i = 0; i < sz[0]; i ++) for (j = 0; j <sz[1]; j ++) for (k = 0; k <sz[2]; k ++) { if (binvol[vcbid3(i,j,k,sz,0,1)] > 1e-16) nvox ++; } fvox = (unsigned char *) malloc(nvox*10*sizeof(unsigned char)); nvox = 0; for (i = 0; i < sz[0]; i ++) for (j = 0; j <sz[1]; j ++) for (k = 0; k <sz[2]; k ++) { val = log10(binvol[vcbid3(i,j,k,sz,0,1)]); val += 16; val *= 16; if (val < 0) continue; cvox = (unsigned short*)&fvox[nvox*10+4]; fvox[nvox*10+0] = val; //voxels[i*4+0]; fvox[nvox*10+1] = 0; //voxels[i*4+1]; fvox[nvox*10+2] = 0; //voxels[i*4+2]; fvox[nvox*10+3] = (unsigned char)((char)(127)); //voxels[i*4+3]; cvox[0] = (unsigned short)i; cvox[1] = (unsigned short)j; cvox[2] = (unsigned short)k; nvox ++; } free(binvol); voxels = fvox; abbox.low[0] = abbox.low[1] = abbox.low[2] = 0.f; abbox.high[0] = sz[0]; abbox.high[1] = sz[1]; abbox.high[2] = sz[2]; } void display (void) { char echofps[80]; float * m_spaceball; float x, y, xs, ys; int i; time1 = clock(); glDisable(GL_LIGHTING); glColor4f(1.f, 1.f, 1.f, 1.f); spaceball.Update(); m_spaceball = spaceball.GetMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(view.center[0],view.center[1],view.center[2]); glMultMatrixf(spaceball.GetMatrix()); glTranslated(-view.center[0],-view.center[1],-view.center[2]); glClear(GL_COLOR_BUFFER_BIT); vcbVolrSsplats(voxels, nvox, sz);//, m_spaceball); glPopMatrix(); time2 = clock(); sprintf(echofps,"fps: %6.2f",(float)CLOCKS_PER_SEC/(time2-time1)); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_1D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0., 1., 0., 1., -1., 1.); /* end set up */ x = 0.9;//(proj.xmax - proj.xmin)*0.95f + proj.xmin; xs = 0.05;//(proj.xmax - proj.xmin)*0.05f; y = 0.05;//proj.ymin + (proj.ymax - proj.ymin)*0.1; ys = 0.9/256;//(proj.ymax - proj.ymin)*0.9/256; glBegin(GL_QUADS); for (i = 0; i < 256; i ++) { glColor4fv(&tlut[i*4]); glVertex3f(x, y+i*ys, 0.0f); // Bottom Left glVertex3f(x+xs, y+i*ys, 0.0f); // Bottom Right glVertex3f(x+xs, y+(i+1)*ys, 0.0f); // Top Right glVertex3f(x, y+(i+1)*ys, 0.0f); // Top Left } glEnd(); /* restore opengl state machine */ glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); //glEnable(GL_LIGHTING); vcbDrawAxis(spaceball.GetMatrix(), 100); vcbOGLprint(0.01f,0.01f, 1.f, 1.f, 0.f, echofps); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_1D); glutSwapBuffers(); } void cleanup (void) { vcbVolrCloseS(); printf("finished cleaning up ...\n"); fflush(stdout); } int main(int argc, char ** argv) { float oglverno; int ntexunits; load_data(argv[1]); printf("%d voxels in a bounding box of: (%f %f %f) (%f %f %f)\n", nvox, abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); initApp(); /* initialize the application */ mainwin = initGLUT(argc,argv); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr,"glew error, initialization failed\n"); fprintf(stderr,"Glew Error: %s\n", glewGetErrorString(err)); } initGLsettings(); vcbEnableOGLlight(0.1f); vcbSetOGLlight(GL_LIGHT0, 0.1f, 1.0f, light0.lightpos[0], light0.lightpos[1], light0.lightpos[2], 40.f); atexit(cleanup); oglverno = vcbGetOGLVersion(); printf("using ogl version %f",oglverno); glGetIntegerv(GL_MAX_TEXTURE_UNITS, & ntexunits); printf(" with %d texture units\n", ntexunits); vcbVolrInitS(voxtransf); glutMainLoop(); return 0; } <file_sep>/binner/vcb/CMakeLists.txt cmake_minimum_required(VERSION 2.6) project(vcblib) add_subdirectory(src) add_subdirectory(libtestsrc)<file_sep>/binner/src/rebin.c #include <stdlib.h> #include <stdio.h> #include <time.h> #include "vcblinalg.h" #include "vcbutils.h" #include "binnerio.h" #include "binner.h" #include "volume.h" /** * $Id$ * */ int main(int argc, char ** argv) { clock_t time1, time2; int nfacets, i, n; double * vdata, * v; int * nverts; /* at most 200 facets */ double totalvolume, cellsize; double bounds[6], * voxels; int nvoxel; int orig[3], xyzsize[3]; int res; int f; res = atoi(argv[1]); f = atoi(argv[2]); /* input has at most 1k vertices */ vdata = malloc(f * 4 * 3 * sizeof(double)); /* input has at most 200 facets */ nverts = malloc(f * sizeof(int)); for (nfacets = 0, v = vdata; (n = get_polygond(v)) > 0; nfacets ++) { nverts[nfacets] = n; /*for (i = 0; i < n; i ++) printf("%lf %lf %lf ", v[i*3], v[i*3+1], v[i*3+2]); printf("\n"); */ v += n * 3; } time1 = clock(); bounding_box((v-vdata)/3, bounds, vdata); cellsize = (bounds[1] - bounds[0])/res; orig[0] = (int)floor(bounds[0]/cellsize); orig[1] = (int)floor(bounds[2]/cellsize); orig[2] = (int)floor(bounds[4]/cellsize); xyzsize[0] = (int)ceil(bounds[1]/cellsize) - orig[0] + 1; xyzsize[1] = (int)ceil(bounds[3]/cellsize) - orig[1] + 1; xyzsize[2] = (int)ceil(bounds[5]/cellsize) - orig[2] + 1; printf("orig: %d %d %d, volume size: %d %d %d\n", orig[0], orig[1], orig[2], xyzsize[0], xyzsize[1], xyzsize[2]); nvoxel = xyzsize[0]*xyzsize[1]*xyzsize[2]; voxels = malloc(nvoxel * sizeof(double)); for (i = 0; i < nvoxel; voxels[i] = 0.0, i ++); totalvolume = bin_para_3dclip(0, nfacets, nverts, vdata, /* the vertices */ NULL, /* no hit counter */ NULL, /* no hit error */ orig, xyzsize, cellsize, voxels, 0., 0.); time2 = clock(); printf("total time: %.3f sec, total volume: %lf\n",(float)(time2-time1)/CLOCKS_PER_SEC, totalvolume); //printf("rebin completed. totalvolume = %lf \n", totalvolume); vcbGenBinm("400.bin", VCB_DOUBLE, 3, orig, xyzsize, 1, voxels); free(voxels); free(nverts); free(vdata); return 0; } <file_sep>/binner/src/formain.cpp /** * $Id$ * */ /* for use with application main to reduce manual work */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #include <sys/time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbglutils.h" #include "vcbmath.h" #include "vcbimage.h" #include "atypes.h" /* assumed external functions that will be defined with main() in a different file */ extern void display(void); /* assumed globals */ extern char projmode; /* P for perspective, O for orthogonal */ extern projStruct proj; extern viewStruct view; extern lightStruct light0; extern ArcBall spaceball; extern int iwinWidth; extern int iwinHeight; extern bbox abbox; float mradius = 0.f; int wireframe = 0; void initApp (void) { /*float mradius = 0.f;*/ spaceball.SetWidth(iwinWidth); spaceball.SetHeight(iwinHeight); view.center[0] = (abbox.low[0] + abbox.high[0])/2.; view.center[1] = (abbox.low[1] + abbox.high[1])/2.; view.center[2] = (abbox.low[2] + abbox.high[2])/2.; if ((abbox.high[0]-abbox.low[0]) > mradius) mradius = abbox.high[0]-abbox.low[0]; if ((abbox.high[1]-abbox.low[1]) > mradius) mradius = abbox.high[1]-abbox.low[1]; if ((abbox.high[2]-abbox.low[2]) > mradius) mradius = abbox.high[2]-abbox.low[2]; /*printf("view.center = (%f %f %f)\n",view.center[0],view.center[1],view.center[2]);*/ view.eye[0] = view.center[0]; view.eye[1] = view.center[1]; view.eye[2] = view.center[2]; view.eye[2] += mradius*10.f; view.up[0] = 0.; view.up[1] = 1.; view.up[2] = 0.; proj.aspect = 1.0; proj.fov = 10.; proj.hither = mradius*5.f; proj.yon = mradius*15.f; proj.xmin = mradius*(-1.); proj.xmax = mradius*1.; proj.ymin = mradius*(-1.); proj.ymax = mradius*1.; light0.lightpos[0] = view.eye[0]; /* using headlight */ light0.lightpos[1] = view.eye[1]; light0.lightpos[2] = view.eye[2]; } void initGLsettings(void) { glClearColor(0.,0.,0.,1.); glViewport(0,0,iwinWidth,iwinHeight); glMatrixMode(GL_PROJECTION); glPopMatrix(); glLoadIdentity(); if (projmode == 'P') gluPerspective(proj.fov, proj.aspect, proj.hither, proj.yon); else glOrtho(proj.xmin,proj.xmax, proj.ymin,proj.ymax, proj.hither,proj.yon); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glLoadIdentity(); gluLookAt(view.eye[0],view.eye[1],view.eye[2], view.center[0],view.center[1],view.center[2], view.up[0],view.up[1],view.up[2]); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glDepthMask(1); glClearDepth(1.); } float fps; int nframes = 0; void idle(void) { static double lastime, newtime; struct timeval current_time; /* assume global variable: float fps;*/ /* assume global variable: nframes */ gettimeofday(&current_time, 0); newtime = current_time.tv_sec + current_time.tv_usec/1000000.0; /* *printf("idle: nframes = %d, newtime = %lf, lastime = %lf\n", nframes, newtime, lastime); */ if (nframes > 10) { fps = (float)(nframes/(newtime - lastime)); lastime = newtime; nframes = 0; } display(); } void reshape(int width,int height) { glMatrixMode(GL_MODELVIEW); glPopMatrix(); glLoadIdentity(); gluLookAt(view.eye[0],view.eye[1],view.eye[2], view.center[0],view.center[1],view.center[2], view.up[0],view.up[1],view.up[2]); if (width <= 0 || height <= 0) return; iwinWidth = width; iwinHeight = height; spaceball.SetWidth(width); spaceball.SetHeight(height); double aspect_ratio = width*1.0/height; proj.aspect = aspect_ratio; glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (projmode == 'P') { gluPerspective(proj.fov, proj.aspect, proj.hither, proj.yon); } else { double x_center, y_center, x_rad, y_rad; x_center = (proj.xmin + proj.xmax)/2.; y_center = (proj.ymin + proj.ymax)/2.; x_rad = (proj.xmax - proj.xmin)/2.; y_rad = (proj.ymax - proj.ymin)/2.; if (width < height) y_rad = x_rad/proj.aspect; else x_rad = y_rad * proj.aspect; proj.xmin = x_center - x_rad; proj.xmax = x_center + x_rad; proj.ymin = y_center - y_rad; proj.ymax = y_center + y_rad; glOrtho(proj.xmin,proj.xmax, proj.ymin,proj.ymax, proj.hither,proj.yon); } display(); } int ncuts = 100; void keys(unsigned char c, int x, int y) { float fzin = 0.05; float fzout = 0.05; float dist; unsigned char * pixels, *bmpbuf; int i; /*printf("this keys func\n");*/ switch(c) { case 'h': fprintf(stderr,"\n Key Help Page\n"); fprintf(stderr,"---------------------------------------------------\n"); fprintf(stderr," w: toggle Wireframe mode\n"); fprintf(stderr," s: Save framebuffer\n"); fprintf(stderr," f: Finer binning resolution\n"); fprintf(stderr," c: Coarser binning resolution\n"); fprintf(stderr," b: reset rendering to Beginning frustum setting\n"); fprintf(stderr," i: zoom IN\n"); fprintf(stderr," o: zoom OUT\n"); fprintf(stderr," l: move Left\n"); fprintf(stderr," r: move Right\n"); fprintf(stderr," u: move Up\n"); fprintf(stderr," d: move Down\n"); fprintf(stderr,"---------------------------------------------------\n\n"); break; case 'i': dist = proj.xmax - proj.xmin; proj.xmin += fzin*dist; proj.xmax -= fzin*dist; dist = proj.ymax - proj.ymin; proj.ymin += fzin*dist; proj.ymax -= fzin*dist; proj.fov *= fzin; reshape(iwinWidth,iwinHeight); break; case 'o': dist = proj.xmax - proj.xmin; proj.xmin -= fzout*dist; proj.xmax += fzout*dist; dist = proj.ymax - proj.ymin; proj.ymin -= fzout*dist; proj.ymax += fzout*dist; proj.fov *= fzout; reshape(iwinWidth,iwinHeight); break; case 's': /* save framebuffer */ pixels = (unsigned char *) malloc(iwinWidth*iwinHeight*4*sizeof(unsigned char)); bmpbuf = (unsigned char *) malloc(iwinWidth*iwinHeight*3*sizeof(unsigned char)); glReadPixels(0,0,iwinWidth,iwinHeight,GL_RGBA,GL_UNSIGNED_BYTE,pixels); for (i = 0; i < iwinWidth*iwinHeight; i ++) { bmpbuf[i*3+0] = pixels[i*4+0]; bmpbuf[i*3+1] = pixels[i*4+1]; bmpbuf[i*3+2] = pixels[i*4+2]; } vcbImgWriteBMP("screencap.bmp",bmpbuf,3, iwinWidth, iwinHeight); free(bmpbuf); free(pixels); break; case 'f': ncuts += 100; break; case 'c': if (ncuts > 100) ncuts -= 100; break; case 'q': exit(0); break; case 'b': initApp(); initGLsettings(); reshape(iwinWidth,iwinHeight); break; case 'l': fzin = proj.xmax - proj.xmin; proj.xmin += fzin/100; proj.xmax += fzin/100; reshape(iwinWidth,iwinHeight); break; case 'r': fzin = proj.xmax - proj.xmin; proj.xmin -= fzin/100; proj.xmax -= fzin/100; reshape(iwinWidth,iwinHeight); break; case 'u': fzin = proj.ymax - proj.ymin; proj.ymin += fzin/100; proj.ymax += fzin/100; reshape(iwinWidth,iwinHeight); break; case 'd': fzin = proj.ymax - proj.ymin; proj.ymin -= fzin/100; proj.ymax -= fzin/100; reshape(iwinWidth,iwinHeight); break; case 'w': wireframe = 1 - wireframe; break; default: break; } } void mouse_handler(int button, int bstate, int x, int y) { if (button == GLUT_LEFT_BUTTON) { if (bstate == GLUT_DOWN) { spaceball.StartMotion( x, y, glutGet(GLUT_ELAPSED_TIME)); } else if (bstate == GLUT_UP) { spaceball.StopMotion( x, y, glutGet(GLUT_ELAPSED_TIME)); } } } void trackMotion(int x, int y) { if (spaceball.Track()) spaceball.TrackMotion( x, y, glutGet(GLUT_ELAPSED_TIME)); } int initGLUT(int argc, char **argv) { int winid; iwinWidth = 500; iwinHeight = 500; glutInit( &argc, argv); glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE|GLUT_DEPTH); glutInitWindowSize(iwinWidth,iwinHeight); glutInitWindowPosition(50,50); winid = glutCreateWindow(argv[0]); glutSetWindowTitle(argv[0]); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(idle); glutMouseFunc(mouse_handler); glutMotionFunc(trackMotion); glutKeyboardFunc(keys); //glutSpecialFunc(SpecialKeys); return winid; } <file_sep>/binner/src/seebmeshvolc.cpp #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <time.h> #include "glew.h" #include <glut.h> #include "vcbutils.h" #include "ArcBall.h" #include "vcbglutils.h" #include "vcbmath.h" #include "atypes.h" #include "vcbvolren.h" #include "vcblinalg.h" #include "vcbcolor.h" /** * $Id$ * */ char projmode = 'O'; /* P for perspective, O for orthogonal */ projStruct proj; viewStruct view; lightStruct light0; ArcBall spaceball; int iwinWidth; int iwinHeight; GLuint texobj; int mainwin, sidewin; clock_t time1, time2, time3, time4; bbox abbox; unsigned char * voxels; int nvox; float tlut[256*4]; #define FTB 1 double * dvol; unsigned short * coord; int sz[3], orig[3]; int ndims,nattribs; vcbdatatype rawdatatype; int load_vox(char * dataname) { /* if ((binvol = (double*) vcbReadBinm(dataname, &rawdatatype, &ndims, orig, sz, &nattribs)) == NULL) { fprintf(stderr, "load_data: error loading datafile\n"); return -1; } return 0; */ FILE * hdr; char fullname[256], data[256]; double ori[3], spacing[3]; int i, j, k, n; int dims[3], dsize[3]; sprintf(fullname, "%s/run.hdr", dataname); fprintf(stderr,"trying %s\n", fullname); hdr = fopen(fullname, "r"); fscanf(hdr, "REBINNED Qxyz HISTOGRAM\n%s\n", data); fscanf(hdr, "DIMENSIONS %d %d %d\n", &sz[0], &sz[1], &sz[2]); fscanf(hdr, "ORIGIN %lf %lf %lf\n", &ori[0], &ori[1], &ori[2]); fscanf(hdr, "SPACING %lf %lf %lf\n", &spacing[0], &spacing[1], &spacing[2]); fclose(hdr); fprintf(stderr,"vol size %d %d %d\n", sz[0],sz[1],sz[2]); fprintf(stderr,"vol orig %lf %lf %lf\n", ori[0],ori[1],ori[2]); sprintf(fullname, "%s/combined.bin.d", dataname); dvol = (double*)vcbReadBinm(fullname, &rawdatatype, dims, orig, dsize, &nattribs); if (dvol == NULL) return -1; sprintf(fullname, "%s/combined.bin.us", dataname); coord = (unsigned short *)vcbReadBinm(fullname, &rawdatatype, dims, orig, dsize, &nattribs); if (coord == NULL) return -1; fprintf(stderr,"done reading %s, %d voxels\n", fullname, dsize[0]); return dsize[0]; } void load_classify(void) /* * -1 for failure, 0 for success * transflut is assumed to have valid memory allocation */ { int i; float a; vcbCustomizeColorTableColdHot(tlut, 0, 255); for (i = 0; i < 256; i ++) { a = (float)i/255; tlut[i * 4+3] = i/255.;//1.f;// a*a; } } void voxtransf (float * rgba, void * vox) { unsigned char * voxel = (unsigned char *) vox; int id = voxel[0] * 4; rgba[0] = tlut[id+0]; rgba[1] = tlut[id+1]; rgba[2] = tlut[id+2]; rgba[3] = tlut[id+3]; } void load_data(char * dataname) { unsigned char * fvox; unsigned short * cvox; int i, j, k, numvox, t; double val, range; double minval, maxval, total; minval = 1e6; maxval = -1e6; total = 0; nvox = load_vox(dataname); if (nvox < 0) { fprintf(stderr, "load_data: error loading datafile\n"); exit(-1); } load_classify(); fprintf(stderr, "loaded %d voxels\n", nvox); fvox = (unsigned char *) malloc(nvox*10*sizeof(unsigned char)); for (i = 0; i < nvox; i ++) { val = dvol[i]; total += val; if (minval > val) minval = val; if (maxval < val) maxval = val; } #define logon 0 #if logon range = log10(maxval) - log10(minval); #else range = maxval - minval; #endif range = 255/range; for (i = 0; i < nvox; i ++) { val = dvol[i]; #if logon val = log10(val + 1e-16) - log10(minval + 1e-16); #else val = val - minval; #endif val = val - minval; //log10(val + 1e-16) - log10(minval + 1e-16); t = (int)(val*range+0.5); if (t < 0) t = 0; //t = t * 32; if (t > 255) t = 255; cvox = (unsigned short*)&fvox[i*10+4]; fvox[i*10+0] = (unsigned char)t; //voxels[i*4+0]; fvox[i*10+1] = 0; //voxels[i*4+1]; fvox[i*10+2] = 0; //voxels[i*4+2]; fvox[i*10+3] = (unsigned char)((char)(127)); //voxels[i*4+3]; cvox[0] = coord[i*3+0]; cvox[1] = coord[i*3+1]; cvox[2] = coord[i*3+2]; } printf("domain sz: %d %d %d\n", sz[0], sz[1], sz[2]); printf("total sum: %e; range: [%e %e]\n",total, minval, maxval); free(dvol); free(coord); voxels = fvox; abbox.low[0] = abbox.low[1] = abbox.low[2] = 0.f; abbox.high[0] = sz[0]; abbox.high[1] = sz[1]; abbox.high[2] = sz[2]; } void display (void) { char echofps[80]; float * m_spaceball; float x, y, xs, ys; int i; time1 = clock(); glDisable(GL_LIGHTING); glColor4f(1.f, 1.f, 1.f, 1.f); spaceball.Update(); m_spaceball = spaceball.GetMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslated(view.center[0],view.center[1],view.center[2]); glMultMatrixf(spaceball.GetMatrix()); glTranslated(-view.center[0],-view.center[1],-view.center[2]); glClear(GL_COLOR_BUFFER_BIT); vcbVolrSsplats(voxels, nvox, sz);//, m_spaceball); glPopMatrix(); time2 = clock(); sprintf(echofps,"fps: %6.2f",(float)CLOCKS_PER_SEC/(time2-time1)); glActiveTexture(GL_TEXTURE0); glDisable(GL_TEXTURE_1D); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0., 1., 0., 1., -1., 1.); /* end set up */ x = 0.9;//(proj.xmax - proj.xmin)*0.95f + proj.xmin; xs = 0.05;//(proj.xmax - proj.xmin)*0.05f; y = 0.05;//proj.ymin + (proj.ymax - proj.ymin)*0.1; ys = 0.9/256;//(proj.ymax - proj.ymin)*0.9/256; glBegin(GL_QUADS); for (i = 0; i < 256; i ++) { glColor4fv(&tlut[i*4]); glVertex3f(x, y+i*ys, 0.0f); // Bottom Left glVertex3f(x+xs, y+i*ys, 0.0f); // Bottom Right glVertex3f(x+xs, y+(i+1)*ys, 0.0f); // Top Right glVertex3f(x, y+(i+1)*ys, 0.0f); // Top Left } glEnd(); /* restore opengl state machine */ glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); //glEnable(GL_LIGHTING); vcbDrawAxis(spaceball.GetMatrix(), 100); vcbOGLprint(0.01f,0.01f, 1.f, 1.f, 0.f, echofps); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glEnable(GL_TEXTURE_1D); glutSwapBuffers(); } void cleanup (void) { vcbVolrCloseS(); printf("finished cleaning up ...\n"); fflush(stdout); } int main(int argc, char ** argv) { float oglverno; int ntexunits; load_data(argv[1]); printf("%d non-empty voxels\nbounding box: (%f %f %f) (%f %f %f)\n", nvox, abbox.low[0], abbox.low[1], abbox.low[2], abbox.high[0],abbox.high[1],abbox.high[2]); initApp(); /* initialize the application */ mainwin = initGLUT(argc,argv); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr,"glew error, initialization failed\n"); fprintf(stderr,"Glew Error: %s\n", glewGetErrorString(err)); } initGLsettings(); vcbEnableOGLlight(0.1f); vcbSetOGLlight(GL_LIGHT0, 0.1f, 1.0f, light0.lightpos[0], light0.lightpos[1], light0.lightpos[2], 40.f); atexit(cleanup); oglverno = vcbGetOGLVersion(); printf("using ogl version %f",oglverno); glGetIntegerv(GL_MAX_TEXTURE_UNITS, & ntexunits); printf(" with %d texture units\n", ntexunits); vcbVolrInitS(voxtransf); glutMainLoop(); return 0; } <file_sep>/binner/src/scale3d.c /** \ingroup rebinner_tests \file src/scale3d.c \brief CURRENT test of core API -- binnerio.h and using vcb $Id$ */ #include <stdlib.h> #include <stdio.h> #include "vcblinalg.h" #include "binnerio.h" int main(int argc, char ** argv) { int nfacets, i, n; float mat[16], v0[4], v1[4], s[3]; float vdata[1024], * v; s[0] = (float)atof(argv[1]); s[1] = (float)atof(argv[2]); s[2] = (float)atof(argv[3]); vcbScale3fv(mat, s); v0[3] = 1.f; for (nfacets = 0; (n = get_polygonf(vdata)) > 0; nfacets ++) { printf("%d ", n); for (i = 0, v = vdata; i < n; v+= 3, i ++) { v0[0] = v[0]; v0[1] = v[1]; v0[2] = v[2]; vcbMatMult4fv(v1, mat, v0); printvertexf(v1, 3); } printf("\n"); } /*printf("%d \n", nfacets);*/ return nfacets; }
0d1b6ce99b5c6293f4dbc57097fd292d11e37660
[ "CMake", "Markdown", "Makefile", "Python", "C", "C++", "Shell" ]
85
C
ornl-ndav/Binner
5ecd614413bb8dd393506f4a8ebae431546286f8
2fe200534c0567df3b0e2218f3950ea96f0c449c
refs/heads/master
<file_sep>// // CHRTimerInternal.h // Chronos // // Copyright (c) 2015 <NAME>. All rights reserved. // // 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. // #ifndef Chronos_CHRTimerInterval #define Chronos_CHRTimerInterval #pragma mark - Type Definitions typedef NS_ENUM(int32_t, CHRTimerState) { CHRTimerStateStopped = 0, CHRTimerStateRunning = 1, CHRTimerStateValid = 2, CHRTimerStateInvalid = 3 }; #pragma mark - Constants and Functions /** Computes the leeway for the given interval. Currently set to 5% of the total interval time. */ static inline uint64_t chr_leeway(NSTimeInterval interval) { return 0.05 * interval * NSEC_PER_SEC; } /** Computes the start time of the timer, given the interval and whether the timer should start immediately. */ static inline dispatch_time_t chr_startTime(NSTimeInterval interval, BOOL now) { return dispatch_time(DISPATCH_TIME_NOW, (now)? 0 : interval * NSEC_PER_SEC); } #endif <file_sep>## DEPRECATED IN FAVOR OF [Chronos-Swift](https://github.com/comyarzaheri/Chronos-Swift) ![](header.png) # Overview [![Build Status](https://travis-ci.org/comyar/Chronos.svg)](https://travis-ci.org/comyar/Chronos) [![Version](http://img.shields.io/cocoapods/v/Chronos.svg)](http://cocoapods.org/?q=Chronos) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Olympus-Library/Chronos) [![Platform](http://img.shields.io/cocoapods/p/Chronos.svg)]() [![License](http://img.shields.io/cocoapods/l/Chronos.svg)](https://github.com/Olympus-Library/Chronos/blob/master/LICENSE) Chronos is a collection of useful Grand Central Dispatch utilities. If you have any specific requests or ideas for new utilities, don't hesitate to create a new issue. ## Utilities * **DispatchTimer** - A repeating timer that fires according to a static interval, e.g. "Fire every 5 seconds". * **VariableTimer** - A repeating timer that allows you to vary the interval between firings, e.g. "Fire according to the function `interval = 2 * count`." # Usage ### Quick Start ##### CocoaPods Add the following to your Podfile: ```ruby pod 'Chronos' ``` ##### Carthage Add the following to your Cartfile: ```ruby github "comyarzaheri/Chronos" "master" ``` ### Using a Dispatch Timer ```objective-c #import <Chronos/Chronos.h> /** Create and start a timer */ CHRDispatchTimer timer = [CHRDispatchTimer timerWithInterval:1.0 executionBlock:^(CHRDispatchTimer *__weak timer, NSUInteger invocation) { NSLog(@"%@", @"Execute repeating task here"); }]; [timer start:YES]; // Fire timer immediately /** Pausing the timer */ [timer pause]; /** Permanently canceling the timer */ [timer cancel]; ``` ### Using a Variable Timer ```objective-c #import <Chronos/Chronos.h> /** Create and start a timer */ CHRVariableTimer *timer = [CHRVariableTimer timerWithIntervalProvider:^NSTimeInterval(CHRVariableTimer *__weak timer, NSUInteger nextInvocation) { return 2 * count; // Return interval according to function } executionBlock:^(__weak id<CHRRepeatingTimer> timer, NSUInteger invocation) { NSLog(@"Execute repeating task here"); }]; [timer start:YES]; // Fire timer immediately /** Pausing the timer */ [timer pause]; /** Permanently canceling the timer */ [timer cancel]; ``` # Requirements * iOS 7.0 or higher * OS X 10.9 or higher # License Chronos is available under the [MIT License](LICENSE). # Contributors * [@comyar](https://github.com/comyar) * [@schun93](https://github.com/schun93)
3f4fcd0173c3d95ff071d626220ed4db6d5dc09b
[ "Markdown", "C" ]
2
C
ardupaul/Chronos
a50b708d2d8579fdc884272d83f6f03c65ccb9eb
7fbc91b17252c5ae8058798bcdfd879ddff22d7e
refs/heads/main
<file_sep>var request = new XMLHttpRequest() request.open('GET','https://restcountries.com/v2/all',true); request.send(); request.onload=function(){ var data = JSON.parse(request.response); // for(i=0; i<=data.length; i++) //{ let res = (data.filter((ele)=>ele.population<100000)); console.log(res); //} }
b90b1f5c645db7c8465a9e22ca8b7c8ed75efb51
[ "JavaScript" ]
1
JavaScript
Nadish-kumar/day-1
e7c2ce46de49e54e13721e78b7108f7c5b157688
a74d216f7462400b07e7223621efcf831ab65ed4
refs/heads/master
<repo_name>aweris/dev<file_sep>/Makefile # Project directories ROOT_DIR := $(CURDIR) SCRIPTS_DIR := $(ROOT_DIR)/scripts RESOURCES_DIR := $(ROOT_DIR)/resources TMP_DIR := $(ROOT_DIR)/tmp HELM_DIR := $(ROOT_DIR)/.helm GOBIN := $(ROOT_DIR)/.gobin # override helm path configurations export XDG_CACHE_HOME := $(HELM_DIR)/cache export XDG_CONFIG_HOME := $(HELM_DIR)/config export XDG_DATA_HOME := $(HELM_DIR)/home # Helper variables V = 0 Q = $(if $(filter 1,$V),,@) M = $(shell printf "\033[34;1m▶\033[0m") # External targets include .bingo/Variables.mk include scripts/make/help.mk include scripts/make/k3d.mk # Non phony targets $(TMP_DIR): ; $(info $(M) creating tmp directory ...) $(Q) mkdir -p $@ <file_sep>/scripts/k3s/init-k3s-services.sh #!/bin/bash set -euo pipefail RESOURCES_DIR=${RESOURCES_DIR:-"resources"} HELM_CMD=${HELM_CMD:-"helm"} TRAEFIK_REPO_NAME="traefik" TRAEFIK_REPO_URL="https://helm.traefik.io/traefik" TRAEFIK_CHART_NAME="traefik" TRAEFIK_CHART_VERSION="9.13.0" TRAEFIK_RELEASE_NAME="traefik" TRAEFIK_NS="router" TRAEFIK_VALUES="${RESOURCES_DIR}/helm/traefik/values.yaml" TRAEFIK_MANIFESTS="${RESOURCES_DIR}/manifests/traefik/" ARGOCD_REPO_NAME="argo" ARGOCD_REPO_URL="https://argoproj.github.io/argo-helm" ARGOCD_CHART_NAME="argo-cd" ARGOCD_CHART_VERSION="2.11.3" ARGOCD_RELEASE_NAME="argocd" ARGOCD_NS="argocd" ARGOCD_VALUES="${RESOURCES_DIR}/helm/argocd/values.yaml" ARGOCD_MANIFESTS="${RESOURCES_DIR}/manifests/argocd/" init() { # Add repositories ${HELM_CMD} repo add "${TRAEFIK_REPO_NAME}" "${TRAEFIK_REPO_URL}" ${HELM_CMD} repo add "${ARGOCD_REPO_NAME}" "${ARGOCD_REPO_URL}" # Update repo ${HELM_CMD} repo update # Install traefik ${HELM_CMD} upgrade --install "${TRAEFIK_RELEASE_NAME}" "${TRAEFIK_REPO_NAME}/${TRAEFIK_CHART_NAME}" \ --version "${TRAEFIK_CHART_VERSION}" \ --namespace "${TRAEFIK_NS}" --create-namespace \ --values "${TRAEFIK_VALUES}" # Install traefik ${HELM_CMD} upgrade --install "${ARGOCD_RELEASE_NAME}" "${ARGOCD_REPO_NAME}/${ARGOCD_CHART_NAME}" \ --version "${ARGOCD_CHART_VERSION}" \ --namespace "${ARGOCD_NS}" --create-namespace \ --values "${ARGOCD_VALUES}" # Apply additional manifests kubectl apply -f "${TRAEFIK_MANIFESTS}" kubectl apply -f "${ARGOCD_MANIFESTS}" } init "$@" <file_sep>/scripts/make/k3d.mk # configuration K3D_CLUSTER ?= dev K3D_CLUSTER_CONFIG := $(RESOURCES_DIR)/k3d/$(K3D_CLUSTER).yaml K3D_REG_CONFIG = $(TMP_DIR)/k3d/$(K3D_CLUSTER)/registries.yaml K3D_EXTRA_ARGS ?= "" K3D_ARGS := $(K3D_EXTRA_ARGS) # Scripts INIT_K3D_REG_CONF := $(SCRIPTS_DIR)/k3s/init-k3d-reg-config.sh INIT_K3S_SERVICES := $(SCRIPTS_DIR)/k3s/init-k3s-services.sh .PHONY: k3d_list k3d_list: ## list cluster(s) k3d_list: $(K3D) $(Q) $(K3D) cluster list .PHONY: k3d_create k3d_create: ## create a new cluster k3d_create: $(K3D) $(HELM) $(TMP_DIR) $(K3D_REG_CONFIG) ; $(info $(M) creating cluster $(K3D_CLUSTER) ...) $(Q) $(K3D) cluster create --config $(K3D_CLUSTER_CONFIG) --registry-config $(K3D_REG_CONFIG) $(K3D_ARGS) $(Q) RESOURCES_DIR=$(RESOURCES_DIR) HELM_CMD=$(HELM) $(INIT_K3S_SERVICES) .PHONY: k3d_delete k3d_delete: ## delete cluster k3d_delete: $(K3D) ; $(info $(M) deleting cluster $(K3D_CLUSTER) ...) $(Q) $(K3D) cluster delete $(K3D_CLUSTER) $(Q) rm -rf $(TMP_DIR)/k3d/$(K3D_CLUSTER) .PHONY: k3d_start k3d_start: ## start existing k3d cluster k3d_start: $(K3D) $(TMP_DIR); $(info $(M) starting cluster $(K3D_CLUSTER) ...) $(Q) $(K3D) cluster start $(K3D_CLUSTER) .PHONY: k3d_stop k3d_stop: ## stop existing k3d cluster k3d_stop: $(K3D) ; $(info $(M) stoping cluster $(K3D_CLUSTER) ...) $(Q) $(K3D) cluster stop $(K3D_CLUSTER) $(K3D_REG_CONFIG): ; $(info $(M) initializing $(K3D_REG_CONFIG) ...) $(Q) OUTPUT=$(K3D_REG_CONFIG) $(INIT_K3D_REG_CONF) <file_sep>/scripts/k3s/init-k3d-reg-config.sh #!/bin/bash set -euo pipefail OUTPUT=${OUTPUT:-"tmp/k3d/registries.yaml"} init() { # make sure config directory exist mkdir -p "$(dirname ${OUTPUT})" # request access token from gcloud password=$(gcloud auth print-access-token) # generate cat <<EOF >"${OUTPUT}" mirrors: eu.gcr.io: endpoint: - https://eu.gcr.io configs: eu.gcr.io: auth: username: oauth2accesstoken password: <PASSWORD>} EOF } init "$@" <file_sep>/README.md # dev Personal development environment ## How to use ```shell Usage: make <target> Targets: help shows this help message k3d_list list cluster(s) k3d_create create a new cluster k3d_delete delete cluster k3d_start start existing k3d cluster k3d_stop stop existing k3d cluster ``` ## Services - http://traefik.k3d.localhost/dashboard/ - http://argocd.k3d.localhost/ , username=admin, password=<PASSWORD> ### ArgoCD cli cheatsheet - login ```shell argocd login localhost:9999 --insecure --username admin --password <PASSWORD> --plaintext ``` - add a repository using local ssh private key ```shell argocd repo add ssh://git@git.example.com:2222/repos/repo --ssh-private-key-path ~/.ssh/id_rsa ```
6e32a7736c8826156a252e178a0fbb89f838a001
[ "Markdown", "Makefile", "Shell" ]
5
Makefile
aweris/dev
aefdbd326bf562b9420fd3e6eba988ecd5660aaf
e713b200097668f1ed50d52ded6dc345f1777904
refs/heads/main
<file_sep><? $name = $_POST['user_name']; $surname = $_POST['user_surname']; $email = $_POST['user_email']; $com = $_POST['user_com']; $token = "1627619015:<KEY>"; $chat_id = "-580183338"; $arr = array( 'Name:' => $name, 'Surname:' => $surname, 'Email:' => $email, 'Comment:' => $com ); foreach($arr as $key => $value){ $text.= "<b>" .$key. "</b>" .$value. "%0A"; } $sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$text}", "r"); //https://api.telegram.org/bot1627619015:AAF1S8iRemWeZdO0CO4qxkZ7zgJ7eL4hTIs/getUpdates header( "location: index.html"); ?><file_sep>$(function(){ $('.burger').click(function(){ $('.burger').toggleClass('burger_active'); }); $('.burger').click(function(){ $('.menu_ul').toggleClass('active'); }); $('.menu_ul').click(function(){ $('.menu_ul').removeClass('active'); $('.burger').removeClass('burger_active'); }); });
389529b39b8969584e138e7de593604642aa686a
[ "JavaScript", "PHP" ]
2
PHP
khusainovabduboriy/portfolio
613f94d7c9bc5e86ad79b894cd43de79d478bf2a
3097ee5328a1e4e990566e97015ece29435953e8
refs/heads/master
<file_sep>import $ from 'jquery' // import Component from './component' // 工厂方法,根据参数生产不同类型的实例,这些实例都是同一个父类的子类 function createReactUnit(element) { if (typeof element === 'string' || typeof element == 'number') { return new ReactTextUnit(element) } // {type: 'button', props: {}} //原生dom节点 if (typeof element === 'object' && typeof element.type === 'string') { return new ReactNativeUnit(element) } if (typeof element === 'object' && typeof element.type === 'function') { return new ReacCompositeUnit(element) } } class Unit { constructor(element) { this._currElement = element } } class ReactTextUnit extends Unit { getMarkUp(rootId) { this._rootId = rootId return `<span data-reactid="${rootId}">${this._currElement}</span>` } update(nextElement) { if(this._currElement !== nextElement) { this._currElement = nextElement $(`[data-reactid="${this._rootId}"]`).html(this._currElement) } } } class ReactNativeUnit extends Unit { getMarkUp(rootId) { this._rootId = rootId const {type, props} = this._currElement let tagStart = `<${type} data-reactid="${rootId}" ` let childString = '' let tagEnd = `</${type}>` let renderedChildren = [] for (const propKey in props) { if (/^on[A-Za-z]+/.test(propKey)) { const eventType = propKey.slice(2).toLowerCase() $(document).delegate(`[data-reactid="${rootId}"]`, `${eventType}.${rootId}`, props[propKey]) } else if (propKey === 'children') { const children = props.children || [] childString = children.map((child, index) => { let childReactUnit = createReactUnit(child) renderedChildren.push(childReactUnit) let childMarkUp = childReactUnit.getMarkUp(`${rootId}-${index}`) return childMarkUp }).join('') } else { tagStart += (' ' + propKey + '=' + props[propKey]) } } this.renderedChildren = renderedChildren return tagStart + '>' + childString + tagEnd } update(nextElement) { this._currElement = nextElement // 获取旧的属性对象 const oldProps = this._currElement.props // 获取新的属性对象 const newProps = nextElement.props // 修改属性对象 this.updateProperties(oldProps, newProps) // 更新子元素 this.updateChildren(newProps.children) } // 执行这个方法的时候,属性是直接操作dom改掉了 updateProperties(oldProps, newProps) { let propKey for (propKey in oldProps) { if (!newProps.hasOwnProperty(propKey)) { $(`[data-reactid="${this._rootId}"]`).removeAttr(propKey) } if (/^on[A-Za-z]+/.test(propKey)) { $(document).undelegate('.' + this._rootId) } } for (propKey in newProps) { if (propKey === 'children') continue // 重新绑定事件 if (/^on[A-Za-z]+/.test(propKey)) { const eventType = propKey.slice(2).toLowerCase() $(document).delegate(`[data-reactid="${this._rootId}"]`, `${eventType}.${this._rootId}`, newProps[propKey]) continue } // 更新新的属性 $(`[data-reactid="${this._rootId}"]`).prop(propKey, newProps[propKey]) } } updateChildren(newChildrenEle) { this.diff(newChildrenEle) } diff(newChildrenEle) { // 为了判断新的元素在旧的元素里有没有 const oldChildrenMap = this.getChildrenMap(this.renderedChildren) this.getNewChildren(oldChildrenMap, newChildrenEle) } // 这个方法的作用是获取新的虚拟dom,还会直接修改匹配的属性 getNewChildren(oldChildrenMap, newChildrenEle) { const newChildren = [] newChildrenEle.forEach((newElement, idx) => { const newKey = (newElement.props && newElement.props.key) || idx.toString() //这里的key写错了 // 通过key找到旧的unit const oldChild = oldChildrenMap[newKey] const oldElement = oldChild && oldChild._currElement // 比较新旧的元素是否一样,如果是一样,可以进行深度比较 if (shouldDeepCompare(oldElement, newElement)) { oldChild.update(newElement) // 如果当前的key在老的集合里,则可以复用旧的unit newChildren[idx] = oldChild } else { const newChildInstance = createReactUnit(newElement) newChildren[idx] = newChildInstance } }) return newChildren } getChildrenMap(children) { const childrenMap = {} for (let i = 0; i < children.length; i++) { const key = (children[i]._currElement.props && children[i]._currElement.props.key || i.toString()) childrenMap[key] = children[i] } return childrenMap } } class ReacCompositeUnit extends Unit { // 一个虚拟dom,element的实例,但是最终还是要落实到native或text上 getMarkUp(rootId) { this._rootId = rootId const {type: Component, props} = this._currElement // 创建组件的实例 const componentInstance = this._componentInstance = new Component(props) // 让此组件的实例的unit属性指向自己这个unit this._componentInstance.unit = this componentInstance.componentWillMount && componentInstance.componentWillMount() // 得到返回的虚拟dom,react元素 const renderedElement = componentInstance.render() // 获取要渲染的单元实例 const renderedUnitInstance = this._renderedUnitInstance = createReactUnit(renderedElement) // 获取对应的markup const renderedMarkUp = renderedUnitInstance.getMarkUp(rootId) $(document).on('mounted', () => { componentInstance.componentDidMount && componentInstance.componentDidMount() }) return renderedMarkUp } // 更新有两种可能,新元素或新状态 update(nextElement, partialState) { this._currElement = nextElement || this._currElement const nextState = this._componentInstance.state = Object.assign(this._componentInstance.state, partialState) const nextProps = this._currElement.props //新的属性对象 if ( this._componentInstance.shouldComponentUpdate && !this._componentInstance.shouldComponentUpdate(nextProps, nextState)) { return; } // 执行组件将要更新的生命周期函数 this._componentInstance.componentWillUpdate && this._componentInstance.componentWillUpdate() // 老的render出来的unit的元素 const preRendererUnitInstance = this._renderedUnitInstance const preRenderedElement = preRendererUnitInstance._currElement const nextRenderElement = this._componentInstance.render() if (shouldDeepCompare(preRenderedElement, nextRenderElement)) { // ReacCompositeUnit不是自己干活 preRendererUnitInstance.update(nextRenderElement) this._componentInstance.componentDidUpdate && this._componentInstance.componentDidUpdate() } else { //如果不需要深度比较,直接删除老的,重建新的 // 根据新的react元素创建新的instance实例并且直接重建新的节点 this._renderedUnitInstance = createReactUnit(nextRenderElement) const nextMarkUp = this._renderedUnitInstance.getMarkUp(this._rootId) $(`[data-reactid="${this._rootId}"]`).replaceWith(nextMarkUp) } } } function shouldDeepCompare(oldEle, newEle) { if (oldEle != null && newEle != null) { const oldType = typeof oldEle const newType = typeof newEle if (oldType === 'string' || oldType === 'number') { return newType === 'string' || newType === 'number' } else { return newType === 'object' && oldEle.type === newEle.type } } else { // 此时不用进行深度对比 return false } } export { createReactUnit }<file_sep>class Component { constructor(props) { this.props = props //接收子类传递过来的props } setState = (partialState) => { // 修改状态 this.unit.update(null, partialState) } } export default Component
e73828249b8034d375883f4c827c0f76d00bfa9d
[ "JavaScript" ]
2
JavaScript
DCbryant/rs
3270bf71de795ab66ecd07a460d87d60c04f67e1
e4352351f68644d2faefe223c960bd7394a33352
refs/heads/master
<repo_name>nickvlku/spec-in-a-box<file_sep>/spec_in_a_box/urls.py from django.conf.urls.defaults import patterns, include import spec_in_a_box urlpatterns = patterns('', (r'^spec/', include(spec_in_a_box.urls)), ) <file_sep>/spec_in_a_box/sample_service/urls.py from django.conf.urls.defaults import patterns, url urlpatterns = patterns('spec_in_a_box.sample_service', url(r'^login$', 'login_landing_page', name='login_page'), url(r'^logout$', 'logout_landing_page', name='logout_page'), url(r'^sample_service/login$', 'sample_service_login', name='service_login'), # this is the page defers to the service for login url(r'^sample_service/done$', 'sample_service_done', name='service_done'), # this is the bounceback url for an OAuth auth (if needed) url(r'^stuff$', 'stuff_view', name='stuff_view') ) <file_sep>/spec_in_a_box/sample_service/models.py from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.contrib.auth.models import User # This isn't "GeoDjango" aware because Spec-In-A-Box is meant to be as easy # as possible to get up and running. GeoDjango is not that easy to get running # and we use our own Geo system that is different anyway. # (hint, see: http://github.com/nickvlku/mongoengine ) class Location(models.Model): x = models.FloatField() y = models.FloatField() def __unicode__(self): return "(%s, %s)" % (self.x, self.y) class Credential(models.Model): # Put in here the appropriate credential # Be it OAuth token, or something else pass class Identity(models.Model): user = models.ForeignKey(User) sample_service_user_id = models.CharField(max_length=255) # different services have different length requirements credential = models.ForeignKey(Credential) created_on = models.DateTimeField(auto_now_add=True) # Below add all the custom attributes for your identity # End custom attributes class Url(models.Model): url = models.URLField(verify_exists=False) type = models.CharField(max_length=255) # Something like 'thumbnail', 'medium', etc content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') # We're not using a tagging library because we want this as simple as possible # and we have our own tagging system that we can port this too. class Tag(models.Model): tag = models.CharField(max_length=255) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') class Photo(models.Model): title = models.CharField(max_length=255, blank=True) owner = models.ForeignKey(Identity) description = models.CharField(max_length=255, blank=True, null=True) internal_service_id = models.CharField(max_length=255) internal_album_id = models.CharField(max_length=255) license = models.CharField(max_length=255) height = models.IntegerField() width = models.IntegerField() location = models.ForeignKey(Location) public = models.BooleanField(default=True) date_created = models.DateTimeField() urls = generic.GenericRelation(Url) tags = generic.GenericRelation(Tag) <file_sep>/spec_in_a_box/sample_service/management/commands/createservicestub.py from django.core.management.base import BaseCommand, CommandError import shutil import fileinput import sys class Command(BaseCommand): args = '<service name>' help = 'Creates a service stub so you can implement your own Spec in a Box' def handle(self, *args, **options): if not args: raise CommandError("Enter a service name") shutil.copytree("sample_service", args[0]) files_to_replace = ['/urls.py', '/views.py', '/models.py', '/auth_backend.py'] for file in files_to_replace: for line in fileinput.FileInput(args[0]+file,inplace=1): if "sample_service" in line: line = line.replace('sample_service', args[0]) sys.stdout.write(line) <file_sep>/spec_in_a_box/flickr/views.py # Create your views here. def login_landing_page(request): pass def logout_landing_page(request): pass def flickr_login(request): pass def flickr_done(request): pass def stuff_view(request): pass <file_sep>/spec_in_a_box/flickr/auth_backend.py from django.contrib.auth.models import User from spec_in_a_box import settings class flickrIdentityCreator: @staticmethod def create_or_find(credential, save_on_create=False): pass class flickrBackend: def authenticate(self, credential): identity = flickrIdentityCreator.create_or_find(credential) if identity.user is None: count = User.objects.filter(username__startswith = "flickr_%s" % identity.flickr_user_id) if count: username = 'flickr_%s%s' % (identity.flickr_user_id, count+1) else: username = 'flickr_%s%s' email_address = '%sflickruser.%s.com' % (username, settings.SITE_NAME) user = User.objects.create_user(username=username, email=email_address) # the password should be unusable identity.user = user identity.save() return user else: return identity.user def get_user(self, username): try: return User.objects.get(username=username) except: return None<file_sep>/spec_in_a_box/sample_service/views.py # Create your views here. def login_landing_page(request): pass def logout_landing_page(request): pass def sample_service_login(request): pass def sample_service_done(request): pass def stuff_view(request): pass
ad8fadeb5a1e073e7f8dd9f7c40b2eb3620dbf2e
[ "Python" ]
7
Python
nickvlku/spec-in-a-box
add3d847a88152234a6690354ca1032eefde063a
50965a75509ec095e70cc9626a62fac0b16d0ca6
refs/heads/master
<repo_name>MistletoeXW/HTTPSocket<file_sep>/src/webservices/HttpServer.java package webservices; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @program: httpSocket * @description: 启动服务器 * @author: xw * @create: 2018-09-16 12:02 */ public class HttpServer { @SuppressWarnings("resource") public static void main(String[] args) { Socket socket = null; try { ServerSocket s = new ServerSocket(8080,5); System.out.println("[Server] 服务器正常启动,等待连接...\n"); while (true) { socket = s.accept(); System.out.println("[Server] 建立一个客户端连接 => 源IP:"+socket.getInetAddress()+ "源端口:"+socket.getPort()); new HttpService(socket).start(); } } catch (IOException e) { e.printStackTrace(); } } }
a1f9fbb21d633ef35485519cf28700cdd67da4af
[ "Java" ]
1
Java
MistletoeXW/HTTPSocket
f873de04a730aaebc0c228d5de96f07bc30c3e98
9bc6b3f015752febae339340dbd5c295619de28b
refs/heads/master
<file_sep># Generated by Django 3.0.5 on 2020-12-11 04:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.DeleteModel( name='Policy', ), ] <file_sep>"# TonkaBI_RVCE-Intern" "# TonkaBI_RVCE-Intern" <file_sep>import datetime from django.shortcuts import render, redirect from django.views.generic import TemplateView def HomePageView(request): to_be_paid = 0 insuranace_amt = 0 name = None dob = None if request.POST: name = request.POST.get('name') dob = request.POST.get('dob') insurance_type = request.POST.get('insurance_type') insuranace_amt = int(request.POST.get('insurance_amt')) dob_list = dob.split('-') birth_date = int(dob_list[0]) today = datetime.datetime.now() date_now = int(today.year) age = date_now - birth_date if age <= 24: return render(request, 'index.html', {'message': "Age must be above 24"}) else: if insurance_type == "auto" and age in range(25, 36): to_be_paid = insuranace_amt * 0.03 elif insurance_type == "health" and age in range(25, 36): to_be_paid = insuranace_amt * 0.08 elif insurance_type == "term" and age in range(25, 36): to_be_paid = insuranace_amt * 0.002 elif insurance_type == "health" and age in range(36, 46): to_be_paid = insuranace_amt * 0.11 return render(request, 'index.html', {'to_be_paid': to_be_paid, 'name': name, 'dob': dob, 'insuranace_amt': insuranace_amt})
3891a95d39507242a1a239f4bdd08d5f925bb1ae
[ "Markdown", "Python" ]
3
Python
sdhanush13/TonkaBI_RVCE-Intern
8505d77310e04dc5f567e75ca61315081eb63e76
47d9955104a36d0551384bc371b7fa3b6b3dff7c
refs/heads/main
<file_sep># Lab6_CSE110Shop Done by <NAME> and <NAME> ### [Link to our shop](https://alexischen99.github.io/Lab6_CSE110Shop/index.html) Sometimes you need to refresh to see the items populate <file_sep>class ProductItem extends HTMLElement { constructor(id, imgSrc, title, itemPrice, added) { //always call super first in the constructor super(); // create a shadowroot that attach to product-list const shadowRoot = this.attachShadow({ mode: "open" }); //create the name of the product var name = document.createElement("p"); name.setAttribute("class", "title"); name.innerHTML = title; //create the image of the product var image = document.createElement("img"); image.setAttribute("width", 200); image.setAttribute("alt", title); image.setAttribute("src", imgSrc); //create the price of the product var price = document.createElement("p"); price.setAttribute("class", "price"); // Append $ sign to item price price.innerHTML = "$" + itemPrice; //create the button of the product var button = document.createElement("button"); button.innerHTML = added; //when users click, change added and modify cart and count button.onclick = function () { //get the count element let count = document.getElementById("cart-count"); //if the item is not added if (button.innerHTML == "Add to Cart") { //add the item and change the added to remove addList.push(id); button.innerHTML = "Remove from Cart"; alert("Added to Cart!!"); } //if the item is also added else { //remove the item from the cart addList.splice(addList.indexOf(id), 1); button.innerHTML = "Add to Cart"; alert("Removed from Cart!"); } //update cart in local storage and count in the page locStor.setItem("itemCount", JSON.stringify(addList)); count.innerHTML = addList.length; }; // create a list that stores name, image, price, and button var list = document.createElement("li"); list.setAttribute("class", "product"); // Store the data onto the 'li' tag list.appendChild(image); list.appendChild(name); list.appendChild(price); list.appendChild(button); //create the element style var style = document.createElement("style"); //append list and style to the root shadowRoot.appendChild(list); shadowRoot.appendChild(style); //css style style.textContent = ` .price { color: green; font-size: 1.8em; font-weight: bold; margin: 0; } .product { align-items: center; background-color: white; border-radius: 5px; display: grid; grid-template-areas: 'image' 'title' 'price' 'add'; grid-template-rows: 67% 11% 11% 11%; height: 450px; filter: drop-shadow(0px 0px 6px rgb(0,0,0,0.2)); margin: 0 30px 30px 0; padding: 10px 20px; width: 200px; } .product > button { background-color: rgb(255, 208, 0); border: none; border-radius: 5px; color: black; justify-self: center; max-height: 35px; padding: 8px 20px; transition: 0.1s ease all; } .product > button:hover { background-color: rgb(255, 166, 0); cursor: pointer; transition: 0.1s ease all; } .product > img { align-self: center; justify-self: center; width: 100%; } .title { font-size: 1.1em; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .title:hover { font-size: 1.1em; margin: 0; white-space: wrap; overflow: auto; text-overflow: unset; } `; } } customElements.define("product-item", ProductItem);
acb571e164611b3341912f64450d5389f682a2f1
[ "Markdown", "JavaScript" ]
2
Markdown
AlexisChen99/Lab6_CSE110Shop
c31d883a7301e4ecbf5ff0c102ca47f4d1a76872
ab774273e7d9031bdb59c8bd275561f3c67be9c7
refs/heads/master
<file_sep>import React from 'react'; import './index.scss'; const PhasesBar = () => ( <div className="phasesBar"> <div className="phaseTitleContainer"> <h3>To do</h3> </div> <div className="phaseTitleContainer"> <h3>Flowcharts</h3> </div> <div className="phaseTitleContainer"> <h3>Wireframes</h3> </div> <div className="phaseTitleContainer"> <h3>Prototype</h3> </div> <div className="phaseTitleContainer"> <h3>Development</h3> </div> <div className="phaseTitleContainer"> <h3>Test</h3> </div> <div className="phaseTitleContainer"> <h3>Launch</h3> </div> </div> ); export default PhasesBar; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import close from '../../assets/icons/close_icon.svg'; import './index.scss'; class TaskCard extends React.Component { constructor(props) { super(props); this.state = { }; } remove = () => { const { onRemove, id } = this.props; onRemove(id); } drag = () => { const { onDrag, id } = this.props; onDrag(id); } render() { const { title, description } = this.props; return ( <div draggable onDrag={this.drag} className="cardContainer" > <div className="titleContainer"> <h4>{title}</h4> <button type="button" onClick={this.remove} > <img src={close} alt="close" /> </button> </div> <div className="descriptionContainer"> <p>{description}</p> </div> </div> ); } } TaskCard.propTypes = { onDrag: PropTypes.func.isRequired, title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, onRemove: PropTypes.func.isRequired, id: PropTypes.number.isRequired, }; export default TaskCard; <file_sep>import React from 'react'; import './index.scss'; import TaskCard from '../TaskCard'; import NewTaskForm from '../NewTaskForm'; import unicorn from '../../assets/img/runningunigif.gif'; class PhasesBoard extends React.Component { constructor(props) { super(props); this.state = { tasks: [ { id: 1, title: 'Low-fidelity prototype', description: 'Create prototype on paper with all the awesome functionalities. Keep it simple and obvious.', category: 'prototype', }, { id: 2, title: 'Mobile version', description: 'This is a description about some cool wireframes for mobile version of application.', category: 'wireframes', }, { id: 3, title: 'Desktop version', description: 'This is a really nice description about some cool wireframes for desktop version of application.', category: 'wireframes', }, ], draggedTask: {}, showUnicorn: false, }; } remove = (id) => { console.log('remove', id); this.setState(prevState => ({ tasks: prevState.tasks.filter(task => task.id !== id), })); } addNewTask = (task) => { console.log('this is the task', task); const { tasks, showUnicorn } = this.state; const nextId = Number(tasks.length + 1); this.setState(prevState => ({ tasks: [ ...prevState.tasks, { id: nextId, ...task, }, ], })); setTimeout(() => { this.setState({ showUnicorn: false, }); }, 3000); this.setState({ showUnicorn: !showUnicorn, }); } drag = (e, task) => { console.log(task); this.setState({ draggedTask: task, }); } onDragOver = (event, category) => { event.preventDefault(); } onDrop = (event, category) => { const { tasks, draggedTask } = this.state; const newTasks = tasks.filter((task) => { if (draggedTask.id === task.id) { task.category = category; } return task; }); this.setState({ tasks: newTasks, }); } render() { const { tasks, showUnicorn } = this.state; const todoTasks = tasks.filter(task => task.category === 'todo'); const flowchartTasks = tasks.filter(task => task.category === 'flowchart'); const wireframesTasks = tasks.filter(task => task.category === 'wireframes'); const prototypeTasks = tasks.filter(task => task.category === 'prototype'); const developmentTasks = tasks.filter(task => task.category === 'development'); const testTasks = tasks.filter(task => task.category === 'test'); const launchTasks = tasks.filter(task => task.category === 'launch'); const unicornClass = showUnicorn ? 'unicorn show' : 'unicorn'; return ( <div className="phasesWrapper"> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'todo')} onDragOver={event => this.onDragOver(event, 'todo')} > {todoTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'flowchart')} onDragOver={event => this.onDragOver(event, 'flowchart')} > {flowchartTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'wireframes')} onDragOver={event => this.onDragOver(event, 'wireframes')} > {wireframesTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'prototype')} onDragOver={event => this.onDragOver(event, 'prototype')} > {prototypeTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'development')} onDragOver={event => this.onDragOver(event, 'development')} > {developmentTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'test')} onDragOver={event => this.onDragOver(event, 'test')} > {testTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <div className="phaseContainer" onDrop={event => this.onDrop(event, 'launch')} onDragOver={event => this.onDragOver(event, 'launch')} > {launchTasks.map(task => ( <TaskCard key={task.id} onRemove={this.remove} onDrag={event => this.drag(event, task)} {...task} /> ))} </div> <NewTaskForm submitHandler={this.addNewTask} /> <div className={unicornClass}> <img src={unicorn} width="400px" height="auto" alt="unicorn" /> </div> </div> ); } } export default PhasesBoard; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import './index.scss'; class NewTaskForm extends React.Component { constructor(props) { super(props); this.state = { title: '', description: '', }; } handleOnChangeInput = (name, value) => { this.setState({ [name]: value, }); } handleSubmit = () => { const { submitHandler } = this.props; const { title, description, } = this.state; const task = { title, description, category: 'todo', }; submitHandler(task); this.setState({ title: '', description: '', }); } render() { const { title, description } = this.state; return ( <div className="formContainer"> <form> <h3>New task</h3> <input className="taskTitle" placeholder="Add task title..." value={title} onChange={event => this.handleOnChangeInput('title', event.target.value)} /> <textarea className="taskDescription" placeholder="Add task description..." value={description} onChange={event => this.handleOnChangeInput('description', event.target.value)} /> <button className="addBtn" type="button" onClick={this.handleSubmit} > <p>Add task</p> </button> </form> </div> ); } } NewTaskForm.propTypes = { submitHandler: PropTypes.func.isRequired, }; export default NewTaskForm;
1e8b5129ff930d8da3cc848cd023c14d9464176f
[ "JavaScript" ]
4
JavaScript
saraaaroee/CoolTool
01ed3fb52e032dac26e3790f168efb7a01a94eed
ad28b4f1a4d5b83e948684346abcd957b31e6ea7
refs/heads/master
<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif #include <iostream> #include <vector> #include "Quad.h" Quad::Quad(float col[3], float pSize) :Shape(GL_LINE_LOOP, GL_QUADS, col, pSize, false, false) { } bool Quad::isDrawn() { if (vertices.size() == 2 * 2) { return true; } return false; } //Overriding the parent method to draw a rectangle with only two vertices void Quad::Draw() { SetSize(); glColor3fv(color); glBegin(GL_QUADS); glVertex2f(vertices[0], vertices[1]); glVertex2f(vertices[2], vertices[1]); glVertex2f(vertices[2], vertices[3]); glVertex2f(vertices[0], vertices[3]); glEnd(); } //Overriding the parent method to draw a rectangle with one vertex and mousepos void Quad::Draw(float mousePos[2]) { SetSize(); glColor3fv(color); glBegin(GL_LINE_LOOP); glVertex2f(vertices[0], vertices[1]); glVertex2f(mousePos[0], vertices[1]); glVertex2f(mousePos[0], mousePos[1]); glVertex2f(vertices[0], mousePos[1]); glEnd(); }<file_sep>#pragma once #include <vector> using std::vector; /* Base class for all shapes. */ class Shape { public: Shape(int _glShapeDrawing, int _glShapeDrawn, float col[3], float pSize, bool usePointSize, bool useLineWidth); void UpdateColor(float color[3]); void AddVertex(float loc[2]) ; virtual void Draw(void); virtual void Draw(float mousePos[2]); //Overloaded draw method when the drawing is still going on virtual bool isDrawn() = 0; //Making it a virtual class. protected: float color[3]; //Stores the color to be used to draw this shape float pointSize; //Stores the size to be used to draw this shape int glShapeDrawn; //Type of shape to be used after drawing is complete int glShapeDrawing;// Type of shape to be used while drawing is still going on bool usesPointSize; //Does the shape uses a custom point size? bool usesLineWidth; // Does the shape uses a custom line size? float defPointSize; //If not custom size, use this float defLineWidth; // ^^ vector<float> vertices; //Holds the vertices of this shape void SetSize(void); //sets the point and line size based on the above boolean variables };<file_sep>#include "Point.h" #ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif Point::Point(float col[3], float pSize) : Shape(GL_POINTS, GL_POINTS, col, pSize, true, false) { } bool Point::isDrawn() { if (vertices.size() >= 1 * 2) return true; return false; }<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif #include <iostream> #include <vector> #include "Shape.h" #include "Point.h" #include "Line.h" #include "Triangle.h" #include "Quad.h" #include "Polygon.h" using std::vector; enum class ShapeType { PT, LINE, TRIANGLE, QUAD, POLYGON, NONE }; ShapeType currShapeType = ShapeType::NONE; vector <Shape*> shapes; Shape* currShape = nullptr; bool isDrawing = false; float color[3]; float size = 1.0f; float mousePos[2]; float canvasSize[] = { 10.0f, 10.0f }; int rasterSize[] = { 800, 600 }; void init(void) { mousePos[0] = mousePos[1] = 0.0f; color[0] = color[1] = color[2] = 0.0f; } void drawCursor(void) { glColor3fv(color); glPointSize(size); glBegin(GL_POINTS); glVertex2fv(mousePos); glEnd(); } void display(void) { glClearColor(1.0, 1.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if (currShapeType != ShapeType::NONE) { for (Shape* shape : shapes) { shape->Draw(); } if (isDrawing) { (currShape) ? (currShape->Draw(mousePos)) : drawCursor(); } else { drawCursor(); } } glutSwapBuffers(); } Shape* CreateCurrentShape() { switch (currShapeType) { case ShapeType::PT: return (Shape*) new Point(color, size); case ShapeType::LINE: return (Shape*) new Line(color, size); case ShapeType::TRIANGLE: return (Shape*) new Triangle(color, size); case ShapeType::QUAD: return (Shape*) new Quad(color, size); case ShapeType::POLYGON: return (Shape*) new Polyg(color, size); default: return nullptr; } return nullptr; } void mouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && currShapeType != ShapeType::NONE) { mousePos[0] = (float)x / rasterSize[0] * canvasSize[0]; mousePos[1] = (rasterSize[1] - (float)y) / rasterSize[1] * canvasSize[1]; if (!isDrawing) isDrawing = true; if (!currShape) { if((currShape = CreateCurrentShape()) == nullptr) std::cout << "Couldn't recognize current shape!" << std::endl; } currShape->AddVertex(mousePos); if (currShape->isDrawn()) { shapes.push_back(currShape); currShape = nullptr; isDrawing = false; } glutPostRedisplay(); } } void reshape(int w, int h) { rasterSize[0] = w; rasterSize[1] = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, canvasSize[0], 0.0, canvasSize[1]); glViewport(0, 0, rasterSize[0], rasterSize[1]);; glutPostRedisplay(); } void motion(int x, int y) { // mouse events are handled by OS, eventually. When using mouse in the raster window, it assumes top-left is the origin. // Note: the raster window created by GLUT assumes bottom-left is the origin. mousePos[0] = (float)x / rasterSize[0] * canvasSize[0]; mousePos[1] = (float)(rasterSize[1] - y) / rasterSize[1] * canvasSize[1]; glutPostRedisplay(); } void updateColor() { if (isDrawing) { if (currShape) { currShape->UpdateColor(color); } } } //Finishes drawing for continous shapes like line strips and polygons void finishDrawing() { if ((currShapeType == ShapeType::LINE || currShapeType == ShapeType::POLYGON) && isDrawing) { if (currShape) { shapes.push_back(currShape); currShape = nullptr; } isDrawing = false; } } void keyboard(unsigned char key, int x, int y) { switch (key) { case 27: exit(0); break; case 13: finishDrawing(); break; } } void menu(int value) { switch (value) { case 0: // clear for (Shape *x : shapes) { delete x; } shapes.clear(); glutPostRedisplay(); break; case 1: //exit exit(0); case 2: // red color[0] = 1.0f; color[1] = 0.0f; color[2] = 0.0f; updateColor(); glutPostRedisplay(); break; case 3: // green color[0] = 0.0f; color[1] = 1.0f; color[2] = 0.0f; updateColor(); glutPostRedisplay(); break; case 4: // blue color[0] = 0.0f; color[1] = 0.0f; color[2] = 1.0f; updateColor(); glutPostRedisplay(); break; case 5: currShapeType = ShapeType::PT; glutPostRedisplay(); break; case 6: currShapeType = ShapeType::LINE; if (!isDrawing) isDrawing = true; glutPostRedisplay(); break; case 7: currShapeType = ShapeType::TRIANGLE; if (!isDrawing) isDrawing = true; glutPostRedisplay(); break; case 8: currShapeType = ShapeType::QUAD; glutPostRedisplay(); break; case 9: currShapeType = ShapeType::POLYGON; glutPostRedisplay(); break; case 10: size = 1.0f; glutPostRedisplay(); break; case 11: size = 3.0f; glutPostRedisplay(); break; case 12: size = 6.0f; glutPostRedisplay(); break; case 13: finishDrawing(); break; default: break; } } void createMenu() { int colorMenu = glutCreateMenu(menu); glutAddMenuEntry("Red", 2); glutAddMenuEntry("Green", 3); glutAddMenuEntry("Blue", 4); int objectMenu = glutCreateMenu(menu); glutAddMenuEntry("Point", 5); glutAddMenuEntry("Line", 6); glutAddMenuEntry("Triangle", 7); glutAddMenuEntry("Quad", 8); glutAddMenuEntry("Polygon", 9); int sizeMenu = glutCreateMenu(menu); glutAddMenuEntry("Small", 10); glutAddMenuEntry("Medium", 11); glutAddMenuEntry("Large", 12); glutCreateMenu(menu); glutAddMenuEntry("Clear", 0); glutAddMenuEntry("Cursor", 13); glutAddSubMenu("Objects", objectMenu); glutAddSubMenu("Colors", colorMenu); glutAddSubMenu("Size", sizeMenu); glutAddMenuEntry("Exit", 1); glutAttachMenu(GLUT_RIGHT_BUTTON); } int main(int argc, char* argv[]) { init(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(rasterSize[0], rasterSize[1]); glutCreateWindow("Interactive 2D Graphics"); glutReshapeFunc(reshape); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutPassiveMotionFunc(motion); createMenu(); glutMainLoop(); return 0; }<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif #include "Shape.h" Shape::Shape(int _glShapeDrawing, int _glShapeDrawn, float col[3], float pSize, bool usePointSize, bool useLineWidth) { glShapeDrawing = _glShapeDrawing; //The inherited shapes set the shape type to be used while drawing glShapeDrawn = _glShapeDrawn; //The inherited shapes set the shape type to be used after it is drawn color[0] = col[0]; color[1] = col[1]; color[2] = col[2]; pointSize = pSize; usesLineWidth = useLineWidth; //Inherited shapes mention if they use custom linewidth usesPointSize = usePointSize; //Inherited shapes mention if they use custom point size defPointSize = 1.0f; defLineWidth = 1.0f; } void Shape::UpdateColor(float col[3]) { color[0] = col[0]; color[1] = col[1]; color[2] = col[2]; } void Shape::AddVertex(float loc[2]) { vertices.push_back(loc[0]); vertices.push_back(loc[1]); } void Shape::Draw(void) { SetSize(); glColor3fv(color); glBegin(glShapeDrawn); for (int i = 0; i < vertices.size(); i = i + 2) { glVertex2f(vertices[i], vertices[i + 1]); } glEnd(); } void Shape::Draw(float mousePos[2]) { SetSize(); glColor3fv(color); glBegin(glShapeDrawing); for (int i = 0; i < vertices.size(); i = i + 2) { glVertex2f(vertices[i], vertices[i + 1]); } glVertex2fv(mousePos); glEnd(); } void Shape::SetSize(void) { if (usesPointSize) glPointSize(pointSize); else glPointSize(defPointSize); if (usesLineWidth) glLineWidth(pointSize); else glLineWidth(defLineWidth); }<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif #include <iostream> #include <vector> #include "Triangle.h" Triangle::Triangle(float col[3], float pSize) :Shape(GL_LINE_STRIP, GL_TRIANGLES, col, pSize, false, false) { } bool Triangle::isDrawn() { if (vertices.size() == 3 * 2) { return true; } return false; } <file_sep>#pragma once #include "Shape.h" #include <vector> using std::vector; class Line : public Shape { public: Line(float color[3], float pSize); bool isDrawn(); };<file_sep>#pragma once #include "Shape.h" class Point :public Shape { public: Point(float color[3], float pSize); bool isDrawn(); };<file_sep>#pragma once #include <vector> #include "Shape.h" using std::vector; class Triangle :public Shape { public: Triangle(float color[3], float pSize); bool isDrawn(); };<file_sep>#pragma once #include <vector> #include "Shape.h" using std::vector; class Polyg :public Shape { public: Polyg(float color[3], float pSize); bool isDrawn(); void Draw(float mousePos[2]); };<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif #include <iostream> #include <vector> #include "Polygon.h" Polyg::Polyg(float col[3], float pSize) :Shape(GL_POLYGON, GL_POLYGON, col, pSize, false, false) { } bool Polyg::isDrawn() { return false; } //Overriding the parent Draw method with GL_LINE_STRIP shape when the number of vertices drawn is upto 2. void Polyg::Draw(float mousePos[2]) { if (vertices.size() >= 4) { Shape::Draw(mousePos); return; } SetSize(); glColor3fv(color); glBegin(GL_LINE_STRIP); for (int i = 0; i < vertices.size(); i = i + 2) { glVertex2f(vertices[i], vertices[i + 1]); } glVertex2fv(mousePos); glEnd(); }<file_sep>#ifdef __APPLE__ #include <GLUT/glut.h> // include glut for Mac #else #include <GL/freeglut.h> //include glut for Windows #endif #include <iostream> #include <vector> #include "Line.h" Line::Line(float color[3], float pSize): Shape(GL_LINE_STRIP, GL_LINE_STRIP, color, pSize, false, true) { } bool Line::isDrawn() { return false; }<file_sep>#pragma once #include <vector> #include "Shape.h" using std::vector; class Quad :public Shape { public: Quad(float color[3], float pSize); bool isDrawn(); void Draw(void); void Draw(float mousePos[2]); };
4a27418755a5e69ba5456634ef572ba1bdd03b67
[ "C++" ]
13
C++
1955mars/Interactive2DGraphics-OpenGL
47f107f159ab0fd06bd8e742766f84f0f683540c
3d15c4922a64c8fa303c1bfbba7f8995c08e6269
refs/heads/main
<file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 24 10:54:31 2021 @author: bawej """ import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt import sklearn from sklearn.neural_network import MLPClassifier from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from math import sqrt from sklearn.metrics import r2_score df = pd.read_csv('full3 (1).csv') print(df.shape) df.describe().transpose() X=df.drop(columns = ['PCOS']) y = df['PCOS'] y = np.array(y) X= np.array(X) y = y.reshape(-1,1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=45) print(X_train.shape); print(X_test.shape) from sklearn.neural_network import MLPClassifier mlp = MLPClassifier(hidden_layer_sizes=(5,8,5), activation='relu', solver='adam', max_iter=1000) mlp.fit(X_train,y_train.ravel()) predict_train = mlp.predict(X_train) predict_test = mlp.predict(X_test) pickle.dump(mlp, open('model.pkl','wb')) model = pickle.load(open('model.pkl','rb')) from sklearn.metrics import classification_report,confusion_matrix print(confusion_matrix(y_train,predict_train)) print(classification_report(y_train,predict_train)) print(confusion_matrix(y_test,predict_test)) print(classification_report(y_test,predict_test)) <file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 24 11:12:40 2021 @author: bawej """ import numpy as np from flask import Flask, request, jsonify, render_template import pickle app = Flask(__name__) model = pickle.load(open('model.pkl', 'rb')) @app.route('/') def home(): return render_template('index.html') ###################################################################################################### @app.route('/about') def about(): #CHANGES MADE ONLY HERE return render_template('about.html') ###################################################################################################### @app.route("/practice") def practice(): """ return the rendered template """ return render_template("practice.html") ####################################################################################################### def check_user_input(input): try: # Convert it into integer val = int(input) except ValueError: try: #BLOCK CAN BE REMOVED # Convert it into float val = float(input) except ValueError: val=str(input) return val ######################################################################################################## @app.route('/predict',methods=['POST']) def predict(): ''' For rendering results on HTML GUI ''' l=[] for x in request.form.values() : z=x if isinstance(check_user_input(x),int)== True: #REMOVE CHECK_USER_INPUT() x=z elif isinstance(check_user_input(x),str)== True: #REMOVE CHECK_USER_INPUT() if x == 'yes': x=1 elif x=='no': x=0 elif x=='regular': x=2 elif x == 'irregular': x=4 ################################################################################################################## else: return render_template('practice.html', prediction_text='Kindly enter valid input ') else: #BLOCK CAN BE REMOVED return render_template('practice.html', prediction_text='Kindly enter valid input ') ################################################################################################################### l.append(int(x)) final_features = [np.array(l)] prediction = model.predict(final_features) output = round(prediction[0], 2) if output == 1: output ='Yes' elif output == 0: output ='No' return render_template('practice.html', prediction_text='Do I have PCOS ? {}'.format(output)) @app.route('/predict_api',methods=['POST']) def predict_api(): ''' For direct API calls trought request ''' data = request.get_json(force=True) prediction = model.predict([np.array(list(data.values()))]) output = prediction[0] return jsonify(output) if __name__ == "__main__": app.run(debug=True)<file_sep># -*- coding: utf-8 -*- """ Created on Wed Mar 24 11:25:42 2021 @author: bawej """ import requests url = 'http://localhost:5000/predict_api' r = requests.post(url,json={ 'Age (yrs)':28,'BMI':19.3,'Cycle(R/I)':2,'Weight gain(Y/N)':0,'hairgrowth(Y/N)':0,'Skin darkening (Y/N)':0,'Hair loss(Y/N)':0,'Pimples(Y/N)':0,'Fast food (Y/N)':1,'Reg.Exercise(Y/N)':0}) print(r.json())
1ee1d80f37e41af329d86f90c9001400c325e932
[ "Python" ]
3
Python
asiskaur/PCOS-Predictor-
afe5ceaee1dd3e4307304f9b85da356c98cf26c9
44a12390b837199204f650357cf478d9b42e5ba7
refs/heads/master
<repo_name>nyu-devops/lab-docker<file_sep>/service/__init__.py # Copyright 2016, 2023 <NAME>. All Rights Reserved. # # 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 # # https://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 for the application models and service routes """ from flask import Flask from flask_redis import FlaskRedis from service import config from service.common import log_handlers # Globally accessible libraries # redis = FlaskRedis() ############################################################ # Initialize the Flask instance ############################################################ def init_app(): """Initialize the core application.""" app = Flask(__name__) app.config.from_object(config) # Initialize Plugins # redis.init_app(app) with app.app_context(): # Include our Routes # pylint: disable=import-outside-toplevel, unused-import from service import routes, models from service.common import error_handlers # Set up logging for production log_handlers.init_logging(app, "gunicorn.error") app.logger.info(70 * "*") app.logger.info(" H I T C O U N T E R S E R V I C E ".center(70, "*")) app.logger.info(70 * "*") app.logger.info("Service initialized!") # Initialize the database try: app.logger.info("Initializing the Redis database") models.Counter.connect(app.config['DATABASE_URI']) app.logger.info("Connected!") except models.DatabaseConnectionError as err: app.logger.error(str(err)) return app <file_sep>/.devcontainer/scripts/setup-lab.sh #!/bin/bash echo "Setting up Docker lab environment..." docker pull alpine docker pull python:3.11-slim docker run --restart=always -d --name redis -p 6379:6379 -v redis:/data redis:6-alpine echo "Setup complete"<file_sep>/service/config.py """ Global Configuration for Application """ import os import logging # Get configuration from environment DATABASE_URI = os.getenv("DATABASE_URI", "redis://:@localhost:6379/0") LOGGING_LEVEL = logging.INFO <file_sep>/Dockerfile FROM python:3.11-slim # Create working folder and install dependencies WORKDIR /app COPY requirements.txt . RUN pip install -U pip wheel && \ pip install --no-cache-dir -r requirements.txt # Copy the application contents COPY wsgi.py . COPY service/ ./service/ # Switch to a non-root user RUN useradd --uid 1000 vagrant && chown -R vagrant /app USER vagrant # Expose any ports the app is expecting in the environment ENV FLASK_APP=wsgi:app ENV PORT 8080 EXPOSE $PORT ENV GUNICORN_BIND 0.0.0.0:$PORT ENTRYPOINT ["gunicorn"] CMD ["--log-level=info", "wsgi:app"] <file_sep>/requirements.txt # Pin dependancies that might cause breakage Werkzeug==2.3.3 # Build dependencies Flask==2.3.2 redis==4.5.5 flask-redis==0.4.0 python-dotenv==0.21.1 # Runtime dependencies gunicorn==20.1.0 honcho==1.1.0 # Code quality pylint==2.16.2 flake8==6.0.0 black==23.1.0 # Testing dependencies green==3.4.3 factory-boy==3.2.1 coverage==7.1.0 # Utilities httpie==3.2.1 <file_sep>/Makefile # # Makefile to build and push docker images # # This Makefile assumes that the current folder has a secret file called .env which contains: # export API_KEY=... # IMAGE_NAME ?= lab-docker .PHONY: help help: ## Display this help @awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n"} /^[a-zA-Z_0-9-\\.]+:.*?##/ { printf " \033[36m%-15s\033[0m %s\n", $$1, $$2 } /^##@/ { printf "\n\033[1m%s\033[0m\n", substr($$0, 5) } ' $(MAKEFILE_LIST) .PHONY: all all: help ##@ Development venv: ## Create a Python virtual environment $(info Creating Python 3 virtual environment...) python3 -m venv .venv install: ## Install dependencies $(info Installing dependencies...) sudo pip install -r requirements.txt lint: ## Run the linter $(info Running linting...) flake8 service tests --count --select=E9,F63,F7,F82 --show-source --statistics flake8 service tests --count --max-complexity=10 --max-line-length=127 --statistics pylint service tests --max-line-length=127 test: ## Run the unit tests $(info Running tests...) green -vvv --processes=1 --run-coverage --termcolor --minimum-coverage=95 ##@ Runtime run: ## Run the service $(info Starting service...) honcho start build: ## Build a docker image $(info Building $(IMAGE_NAME) Image...) docker build --rm --pull -t $(IMAGE_NAME) . clean: ## Prune untagged Docker images $(info Checking for untagged images) docker images prune <file_sep>/tests/test_routes.py # -*- coding: utf-8 -*- # Copyright status.HTTP_201_CREATED6, 2020 <NAME>. All Rights Reserved. # # 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 # # https://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. """ Counter API Service Test Suite Test cases can be run with the following: nosetests -v --with-spec --spec-color coverage report -m """ import os import logging from unittest import TestCase from unittest.mock import patch from wsgi import app from service.models import Counter, DatabaseConnectionError from service.common import status # logging.disable(logging.CRITICAL) DATABASE_URI = os.getenv("DATABASE_URI", "redis://:@localhost:6379/0") ###################################################################### # T E S T C A S E S ###################################################################### class ServiceTest(TestCase): """REST API Server Tests""" @classmethod def setUpClass(cls): """This runs once before the entire test suite""" app.testing = True app.debug = False @classmethod def tearDownClass(cls): """This runs once after the entire test suite""" def setUp(self): """This runs before each test""" Counter.connect(DATABASE_URI) Counter.remove_all() self.app = app.test_client() def tearDown(self): """This runs after each test""" ###################################################################### # T E S T C A S E S ###################################################################### def test_index(self): """It should return the home page""" resp = self.app.get("/") self.assertEqual(resp.status_code, status.HTTP_200_OK) def test_health(self): """It should get the health endpoint""" resp = self.app.get("/health") self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() self.assertEqual(data["status"], "OK") def test_create_counter(self): """It should Create a counter""" resp = self.app.post("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_201_CREATED) data = resp.get_json() self.assertEqual(data["counter"], 0) def test_counter_already_exists(self): """It should not Counter that already exists""" resp = self.app.post("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = self.app.post("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT) def test_list_counters(self): """It should Get multiple counters""" resp = self.app.post("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = self.app.post("/counters/bar") self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = self.app.get("/counters") self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() self.assertEqual(len(data), 2) def test_get_counter(self): """It should Get a counter""" self.test_create_counter() resp = self.app.get("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() self.assertEqual(data["counter"], 0) def test_get_counter_not_found(self): """It should not return a counter that does not exist""" resp = self.app.get("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND) def test_put_counter_not_found(self): """It should not update a counter that does not exist""" resp = self.app.put("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND) def test_increment_counter(self): """It should Increment the counter""" self.test_get_counter() resp = self.app.put("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() self.assertEqual(data["counter"], 1) resp = self.app.put("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.get_json() logging.debug(data) self.assertEqual(data["counter"], 2) def test_delete_counter(self): """It should Delete the counter""" self.test_create_counter() resp = self.app.delete("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) def test_method_not_allowed(self): """It should not allow usuported Methods""" resp = self.app.post("/counters") self.assertEqual(resp.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) ###################################################################### # T E S T E R R O R H A N D L E R S ###################################################################### @patch("service.routes.Counter.redis.get") def test_failed_get_request(self, redis_mock): """It should handle Error for failed GET""" redis_mock.return_value = 0 redis_mock.side_effect = DatabaseConnectionError() resp = self.app.get("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) @patch("service.models.Counter.increment") def test_failed_update_request(self, value_mock): """It should handle Error for failed UPDATE""" value_mock.return_value = 0 value_mock.side_effect = DatabaseConnectionError() self.test_create_counter() resp = self.app.put("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) @patch("service.models.Counter.__init__") def test_failed_post_request(self, value_mock): """It should handle Error for failed POST""" value_mock.return_value = 0 value_mock.side_effect = DatabaseConnectionError() resp = self.app.post("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) @patch("service.routes.Counter.redis.keys") def test_failed_list_request(self, redis_mock): """It should handle Error for failed LIST""" redis_mock.return_value = 0 redis_mock.side_effect = Exception() resp = self.app.get("/counters") self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) def test_failed_delete_request(self): """It should handle Error for failed DELETE""" self.test_create_counter() with patch("service.routes.Counter.redis.get") as redis_mock: redis_mock.return_value = 0 redis_mock.side_effect = DatabaseConnectionError() resp = self.app.delete("/counters/foo") self.assertEqual(resp.status_code, status.HTTP_503_SERVICE_UNAVAILABLE) <file_sep>/Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : ###################################################################### # Virtual Development Environment for Python 3 with Docker ###################################################################### Vagrant.configure(2) do |config| config.vm.box = "bento/ubuntu-21.04" config.vm.hostname = "ubuntu" # config.vm.network "forwarded_port", guest: 80, host: 8080 config.vm.network "forwarded_port", guest: 8080, host: 8080, host_ip: "127.0.0.1" # Create a private network, which allows host-only access to the machine # using a specific IP. config.vm.network "private_network", ip: "192.168.56.10" # Mac users can comment this next line out but # Windows users need to change the permission of files and directories config.vm.synced_folder ".", "/vagrant", mount_options: ["dmode=755,fmode=644"] ############################################################ # Configure Vagrant to use VirtualBox on Intel: ############################################################ config.vm.provider "virtualbox" do |vb| # Customize the amount of memory on the VM: vb.memory = "1024" vb.cpus = 2 # Fixes some DNS issues on some networks vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"] end ############################################################ # Configure Vagrant to use for Docker on Intel or ARM ############################################################ config.vm.provider :docker do |docker, override| override.vm.box = nil docker.image = "rofrano/vagrant-provider:debian" docker.remains_running = true docker.has_ssh = true docker.privileged = true docker.volumes = ["/sys/fs/cgroup:/sys/fs/cgroup:ro"] # Uncomment to force arm64 for testing images on Intel # docker.create_args = ["--platform=linux/arm64"] end ############################################################ # Copy some host files to configure VM like the host ############################################################ # Copy your .gitconfig file so that your git credentials are correct if File.exists?(File.expand_path("~/.gitconfig")) config.vm.provision "file", source: "~/.gitconfig", destination: "~/.gitconfig" end # Copy your ssh keys for github so that your git credentials work if File.exists?(File.expand_path("~/.ssh/id_rsa")) config.vm.provision "file", source: "~/.ssh/id_rsa", destination: "~/.ssh/id_rsa" end # Copy your .vimrc file so that your VI editor looks right if File.exists?(File.expand_path("~/.vimrc")) config.vm.provision "file", source: "~/.vimrc", destination: "~/.vimrc" end ###################################################################### # Create a Python 3 development environment ###################################################################### config.vm.provision "shell", inline: <<-SHELL # Install Python 3 and dev tools apt-get update apt-get install -y git vim tree wget jq python3-dev python3-pip python3-venv apt-transport-https apt-get upgrade python3 # Create a Python3 Virtual Environment and Activate it in .profile sudo -H -u vagrant sh -c 'python3 -m venv ~/venv' sudo -H -u vagrant sh -c 'echo ". ~/venv/bin/activate" >> ~/.profile' # Install app dependencies in virtual environment as vagrant user sudo -H -u vagrant sh -c '. ~/venv/bin/activate && cd /vagrant && pip install -U pip wheel && pip install docker-compose && pip install -r requirements.txt' # Check versions to prove that everything is installed python3 --version # Create .env file if it doesn't exist sudo -H -u vagrant sh -c 'cd /vagrant && if [ ! -f .env ]; then cp dot-env-example .env; fi' SHELL ############################################################ # Provision Docker with Vagrant before starting kubernetes ############################################################ config.vm.provision "docker" do |d| d.pull_images "alpine" d.pull_images "python:3.9-slim" d.pull_images "redis:6-alpine" d.run "redis:6-alpine", args: "--restart=always -d --name redis -p 6379:6379 -v redis:/data" end end <file_sep>/wsgi.py """ Web Server Gateway Interface (WSGI) entry point """ from service import init_app app = init_app() if __name__ == "__main__": app.run(host='0.0.0.0') <file_sep>/.devcontainer/Dockerfile # Image for a Python 3 development environment FROM python:3.11-slim # Add any tools that are needed beyond Python 3 RUN apt-get update && \ apt-get install -y sudo vim make git zip tree curl wget jq && \ apt-get autoremove -y && \ apt-get clean -y # Create a user for development ARG USERNAME=vscode ARG USER_UID=1000 ARG USER_GID=$USER_UID # Create the user with passwordless sudo privileges RUN groupadd --gid $USER_GID $USERNAME \ && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME -s /bin/bash \ && usermod -aG sudo $USERNAME \ && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \ && chmod 0440 /etc/sudoers.d/$USERNAME # Set up the Python development environment WORKDIR /app COPY requirements.txt . RUN python -m pip install --upgrade pip wheel && \ pip install docker-compose && \ pip install -r requirements.txt # Enable color terminal for docker exec bash ENV TERM=xterm-256color EXPOSE 5000 # Become a regular user for development USER $USERNAME <file_sep>/README.md # NYU DevOps Docker Lab [![Build Status](https://github.com/nyu-devops/lab-docker/actions/workflows/workflow.yaml/badge.svg)](https://github.com/nyu-devops/lab-docker/actions) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![made-with-python](https://img.shields.io/badge/Made%20with-Python-green.svg)](https://www.python.org/) [![Open in Remote - Containers](https://img.shields.io/static/v1?label=Remote%20-%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/nyu-devops/lab-docker) What is Docker? How can Docker containers help you build and deploy a cloud native solution as micro-services? This lab will teach you what-you-need-to-know to get started building and running Docker Containers. It covers what Docker is, and more importantly, what Docker is not! You will learn how to deploy and run existing Docker community images, how to create your own Docker images, and how to connect containers together using Docker Compose. If you want to know what all this fuss about containers is about, come to this lab and spin up a few containers and see for yourself why everyone is adopting Docker. This lab is an example of how to create a Python / Flask / Redis app using Docker. ## Prerequisite Software Installation This lab uses Docker and Visual Studio Code with the Remote Containers extension to provide a consistent repeatable disposable development environment for all of the labs in this course. You will need the following software installed: - [Docker Desktop](https://www.docker.com/products/docker-desktop) - [Visual Studio Code](https://code.visualstudio.com) - [Remote Containers](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) extension from the Visual Studio Marketplace All of these can be installed manually by clicking on the links above or you can use a package manager like **Homebrew** on Mac of **Chocolatey** on Windows. ### Install with homebrew If you are on a Mac you can easily install this software with [Home Brew](http://brew.sh) ```bash brew install --cask docker brew install --cask visual-studio-code ``` You must setup Visual Studio Code as a Mac to launch from the command line using [these instructions](https://code.visualstudio.com/docs/setup/mac#_launching-from-the-command-line). Then you can run the code command to install the remote containers extension. ```bash code --install-extension ms-vscode-remote.remote-containers ``` You are now ready to work in the lab. ### Alternate using Vagrant Alternately, you can use [Vagrant](https://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/) to create a consistent development environment in a virtual machine (VM). You can read more about creating these environments in my article: [Creating Reproducible Development Environments](https://johnrofrano.medium.com/creating-reproducible-development-environments-fac8d6471f35) ## Bring up the development environment To bring up the development environment you should clone this repo, change into the repo directory: ```bash $ git clone https://github.com/nyu-devops/lab-docker.git $ cd lab-docker ``` Depending on which development environment you created, pick from the following: ### Start developing with Visual Studio Code and Docker Open Visual Studio Code using the `code .` command. VS Code will prompt you to reopen in a container and you should say **yes**. This will take a while as it builds the Docker image and creates a container from it to develop in. ```bash $ code . ``` Note that there is a period `.` after the `code` command. This tells Visual Studio Code to open the editor and load the current folder of files. Once the environment is loaded you should be placed at a `bash` prompt in the `/app` folder inside of the development container. This folder is mounted to the current working directory of your repository on your computer. This means that any file you edit while inside of the `/app` folder in the container is actually being edited on your computer. You can then commit your changes to `git` from either inside or outside of the container. ## Running the tests As developers we always want to run the tests before we change any code. That way we know if we broke the code or if someone before us did. Always run the test cases first! Run the tests using `nosetests` ```shell $ nosetests ``` Nose is configured via the included `setup.cfg` file to automatically include the flags `--with-spec --spec-color` so that red-green-refactor is meaningful. If you are in a command shell that supports colors, passing tests will be green while failing tests will be red. ## What's featured in the project? This project uses Python Flask and Redis to create a RESTful counter service that can keep track of multiple named counters. ```text service <- Package for the service ├── common <- Common error and log handlers ├── models.py <- Model for Redis based counter ├── routes.py <- Controller for REST API └── static <- Status HTML assets tests <- Tests package ├── test_models.py <- Test cases for the models └── test_routes.py <- Test cases for the routes ``` The development environment uses **Docker-in-Docker** so that you have an isolated Docker environment within your Docker development container. ## License Copyright (c) <NAME>. All rights reserved. Licensed under the Apache License. See [LICENSE](LICENSE) This repo is part of the NYU masters class: **CSCI-GA.2820-001 DevOps and Agile Methodologies** conceived, created and taught by *<NAME>* <file_sep>/service/routes.py # Copyright 2015, 2021 <NAME> All Rights Reserved. # # 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 # # https://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. """ Redis Counter Demo in Docker """ import os from flask import jsonify, abort, url_for from flask import current_app as app from service.common import status # HTTP Status Codes from .models import Counter, DatabaseConnectionError DEBUG = os.getenv("DEBUG", "False") == "True" PORT = os.getenv("PORT", "8080") ############################################################ # Health Endpoint ############################################################ @app.route("/health") def health(): """Health Status""" return {"status": "OK"}, status.HTTP_200_OK ############################################################ # Home Page ############################################################ @app.route("/") def index(): """Home Page""" return app.send_static_file("index.html") ############################################################ # List counters ############################################################ @app.route("/counters", methods=["GET"]) def list_counters(): """List counters""" app.logger.info("Request to list all counters...") try: counters = Counter.all() except DatabaseConnectionError as err: abort(status.HTTP_503_SERVICE_UNAVAILABLE, err) return jsonify(counters) ############################################################ # Read counters ############################################################ @app.route("/counters/<name>", methods=["GET"]) def read_counters(name): """Read a counter""" app.logger.info("Request to Read counter: %s...", name) try: counter = Counter.find(name) except DatabaseConnectionError as err: abort(status.HTTP_503_SERVICE_UNAVAILABLE, err) if not counter: abort(status.HTTP_404_NOT_FOUND, f"Counter {name} does not exist") app.logger.info("Returning: %d...", counter.value) return jsonify(counter.serialize()) ############################################################ # Create counter ############################################################ @app.route("/counters/<name>", methods=["POST"]) def create_counters(name): """Create a counter""" app.logger.info("Request to Create counter...") try: counter = Counter.find(name) if counter is not None: return jsonify(code=409, error="Counter already exists"), 409 counter = Counter(name) except DatabaseConnectionError as err: abort(status.HTTP_503_SERVICE_UNAVAILABLE, err) location_url = url_for("read_counters", name=name, _external=True) return ( jsonify(counter.serialize()), status.HTTP_201_CREATED, {"Location": location_url}, ) ############################################################ # Update counters ############################################################ @app.route("/counters/<name>", methods=["PUT"]) def update_counters(name): """Update a counter""" app.logger.info("Request to Update counter...") try: counter = Counter.find(name) if counter is None: return jsonify(code=404, error=f"Counter {name} does not exist"), 404 count = counter.increment() except DatabaseConnectionError as err: abort(status.HTTP_503_SERVICE_UNAVAILABLE, err) return jsonify(name=name, counter=count) ############################################################ # Delete counters ############################################################ @app.route("/counters/<name>", methods=["DELETE"]) def delete_counters(name): """Delete a counter""" app.logger.info("Request to Delete counter...") try: counter = Counter.find(name) if counter: del counter.value except DatabaseConnectionError as err: abort(status.HTTP_503_SERVICE_UNAVAILABLE, err) return "", status.HTTP_204_NO_CONTENT <file_sep>/docker-compose.yml version: "3" services: app: build: . image: hitcounter:1.0 container_name: hitcounter hostname: hitcounter ports: - "8080:8080" environment: DATABASE_URI: "redis://redis:6379/0" depends_on: - redis networks: - web redis: image: redis:6-alpine restart: always hostname: redis ports: - "6379:6379" volumes: - redis-data:/data networks: - web volumes: redis-data: networks: web: <file_sep>/tests/test_models.py # -*- coding: utf-8 -*- # Copyright 2016, 2021 <NAME>. All Rights Reserved. # # 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 # # https://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. # pylint: disable=disallowed-name """ Test cases for Counter Model Test cases can be run with the following: nosetests -v --with-spec --spec-color coverage report -m """ import os import logging from unittest import TestCase from unittest.mock import patch from redis.exceptions import ConnectionError as RedisConnectionError from service.models import Counter, DatabaseConnectionError DATABASE_URI = os.getenv("DATABASE_URI", "redis://:@localhost:6379/0") logging.disable(logging.CRITICAL) ###################################################################### # T E S T C A S E S ###################################################################### class CounterTests(TestCase): """Counter Model Tests""" @classmethod def setUpClass(cls): """Run before all tests""" # Counter.connect(DATABASE_URI) def setUp(self): """This runs before each test""" Counter.connect(DATABASE_URI) Counter.remove_all() self.counter = Counter() def tearDown(self): """This runs after each test""" # Counter.redis.flushall() ###################################################################### # T E S T C A S E S ###################################################################### def test_create_counter_with_name(self): """It should Create a counter with a name""" counter = Counter("foo") self.assertIsNotNone(counter) self.assertEqual(counter.name, "foo") self.assertEqual(counter.value, 0) def test_create_counter_no_name(self): """It should not Create a counter without a name""" self.assertIsNotNone(self.counter) self.assertEqual(self.counter.name, "hits") self.assertEqual(self.counter.value, 0) def test_serialize_counter(self): """It should Serialize a counter""" self.assertIsNotNone(self.counter) data = self.counter.serialize() self.assertEqual(data["name"], "hits") self.assertEqual(data["counter"], 0) def test_set_list_counters(self): """It should List all of the counters""" _ = Counter("foo") _ = Counter("bar") counters = Counter.all() self.assertEqual(len(counters), 3) def test_set_find_counter(self): """It should Find a counter""" _ = Counter("foo") _ = Counter("bar") foo = Counter.find("foo") self.assertEqual(foo.name, "foo") def test_counter_not_found(self): """It should not find a counter""" foo = Counter.find("foo") self.assertIsNone(foo) def test_set_get_counter(self): """It should Set and then Get the counter""" self.counter.value = 13 self.assertEqual(self.counter.value, 13) def test_delete_counter(self): """It should Delete a counter""" counter = Counter("foo") self.assertEqual(counter.value, 0) del counter.value found = Counter.find("foo") self.assertIsNone(found) self.assertEqual(self.counter.value, 0) def test_increment_counter(self): """It should Increment the current value of the counter by 1""" count = self.counter.value next_count = self.counter.increment() logging.debug( "count(%s) = %s, next_count(%s) = %s", type(count), count, type(next_count), next_count, ) self.assertEqual(next_count, count + 1) def test_increment_counter_to_2(self): """It should Increment the counter to 2""" self.assertEqual(self.counter.value, 0) self.counter.increment() self.assertEqual(self.counter.value, 1) counter = Counter.find("hits") counter.increment() self.assertEqual(counter.value, 2) @patch("redis.Redis.ping") def test_no_connection(self, ping_mock): """It should Handle a failed connection""" ping_mock.side_effect = RedisConnectionError() self.assertRaises(DatabaseConnectionError, self.counter.connect, DATABASE_URI) @patch.dict(os.environ, {"DATABASE_URI": ""}) def test_missing_environment_creds(self): """It should detect Missing environment credentials""" self.assertRaises(DatabaseConnectionError, self.counter.connect) <file_sep>/service/models.py ###################################################################### # Copyright 2016, 2020 <NAME>. All Rights Reserved. # # 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 # # https://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. ###################################################################### """ Counter Model """ import os import logging from redis import Redis from redis.exceptions import ConnectionError as RedisConnectionError logger = logging.getLogger(__name__) DATABASE_URI = os.getenv("DATABASE_URI", "redis://localhost:6379") class DatabaseConnectionError(RedisConnectionError): """Generic Exception for Redis database connection errors""" class Counter: """An integer counter that is persisted in Redis You can establish a connection to Redis using an environment variable DATABASE_URI in the following format: DATABASE_URI="redis://userid:password@localhost:6379/0" This follows the same standards as SQLAlchemy URIs """ redis = None def __init__(self, name: str = "hits", value: int = None): """Constructor""" self.name = name if not value: self.value = 0 else: self.value = value @property def value(self): """Returns the current value of the counter""" return int(Counter.redis.get(self.name)) @value.setter def value(self, value): """Sets the value of the counter""" Counter.redis.set(self.name, value) @value.deleter def value(self): """Removes the counter fom the database""" Counter.redis.delete(self.name) def increment(self): """Increments the current value of the counter by 1""" return Counter.redis.incr(self.name) def serialize(self): """Converts a counter into a dictionary""" return { "name": self.name, "counter": int(Counter.redis.get(self.name)) } ###################################################################### # F I N D E R M E T H O D S ###################################################################### @classmethod def all(cls): """Returns all of the counters""" try: counters = [ {"name": key, "counter": int(cls.redis.get(key))} for key in cls.redis.keys("*") ] except Exception as err: raise DatabaseConnectionError(err) from err return counters @classmethod def find(cls, name): """Finds a counter with the name or returns None""" counter = None try: count = cls.redis.get(name) if count: counter = Counter(name, count) except Exception as err: raise DatabaseConnectionError(err) from err return counter @classmethod def remove_all(cls): """Removes all of the keys in the database""" try: cls.redis.flushall() except Exception as err: raise DatabaseConnectionError(err) from err ###################################################################### # R E D I S D A T A B A S E C O N N E C T I O N M E T H O D S ###################################################################### @classmethod def test_connection(cls): """Test connection by pinging the host""" success = False try: cls.redis.ping() logger.info("Connection established") success = True except RedisConnectionError: logger.warning("Connection Error!") return success @classmethod def connect(cls, database_uri=None): """Established database connection Arguments: database_uri: a uri to the Redis database Raises: DatabaseConnectionError: Could not connect """ if not database_uri: if "DATABASE_URI" in os.environ and os.environ["DATABASE_URI"]: database_uri = os.environ["DATABASE_URI"] else: msg = "DATABASE_URI is missing from environment." logger.error(msg) raise DatabaseConnectionError(msg) logger.info("Attempting to connecting to Redis...") cls.redis = Redis.from_url( database_uri, encoding="utf-8", decode_responses=True ) if not cls.test_connection(): # if you end up here, redis instance is down. cls.redis = None logger.fatal("*** FATAL ERROR: Could not connect to the Redis Service") raise DatabaseConnectionError("Could not connect to the Redis Service") logger.info("Successfully connected to Redis") return cls.redis
6ae8a20288ab9fe30ada2443db5e8c377fac835f
[ "Ruby", "YAML", "Markdown", "Makefile", "Python", "Text", "Dockerfile", "Shell" ]
15
Python
nyu-devops/lab-docker
557f24b0c193109a9dd4feef682827e1f50855a6
39c524ffc719507ae889ffb2f5be2e8d66aae09b
refs/heads/master
<repo_name>lismansihotang/jtable-mysqli<file_sep>/PersonActions.php <?php include_once 'mysqli/CrudMysqliHelper.php'; try { $tableName = 'people'; $primaryKey = 'PersonId'; if ($_GET["action"] === "list") { # Untuk mendapatkan list data dari table $header = getHeaderTable($tableName); $data = getData($tableName); $rows = []; $i = 0; foreach ($data as $subData) { foreach ($subData as $key => $row) { $rows[$i][$key] = $row; $rows[$i][$header[$key]] = $row; } $i++; } $jTableResult = []; $jTableResult['Result'] = "OK"; $jTableResult['Records'] = $rows; print json_encode($jTableResult); } else if ($_GET["action"] === "create") { # Untuk menambahkan data $insert = insertData($tableName, $_POST); $header = getHeaderTable($tableName); $data = getData($tableName, '*', [$primaryKey => $insert]); $rows = []; foreach ($data as $subData) { foreach ($subData as $key => $row) { $rows[$key] = $row; $rows[$header[$key]] = $row; } } $jTableResult = []; $jTableResult['Result'] = "OK"; $jTableResult['Record'] = $rows; print json_encode($jTableResult); } else if ($_GET["action"] === "update") { # Untuk mengubah Data $header = getHeaderTable($tableName); $data = []; foreach ($header as $key => $value) { if ($value !== $primaryKey) { if (array_key_exists($value, $_POST) === true) { $data[$value] = $_POST[$value]; } } } updateData($tableName, $data, [$primaryKey => $_POST[$primaryKey]]); $jTableResult = []; $jTableResult['Result'] = "OK"; print json_encode($jTableResult); } else if ($_GET["action"] === "delete") { # Untuk menghapus data deleteData($tableName, [$primaryKey => $_POST[$primaryKey]]); $jTableResult = []; $jTableResult['Result'] = "OK"; print json_encode($jTableResult); }else if ($_GET["action"] === "list_dropdown") { # Untuk mendapatkan list data dari table $header = getHeaderTable($tableName); $data = getData($tableName); $rows = []; $i = 0; foreach ($data as $row) { $rows[$i]['DisplayText'] = $row[1]; $rows[$i]['Value'] = $row[0]; $i++; } $jTableResult = []; $jTableResult['Result'] = "OK"; $jTableResult['Options'] = $rows; print json_encode($jTableResult); } } catch (Exception $ex) { # Menampilkan pesan error jika data tidak berhasil di load $jTableResult = []; $jTableResult['Result'] = "ERROR"; $jTableResult['Message'] = $ex->getMessage(); print json_encode($jTableResult); } <file_sep>/mysqli/CrudMysqliHelper.php <?php /** * @author : <NAME> * @email : <EMAIL> */ /** * @define dbHost */ define('dbHost', 'localhost'); /** * @define dbUser */ define('dbUser', 'root'); /** * @define dbPass */ define('dbPass', ''); /** * @define dbName */ define('dbName', 'jtabletestdb'); if (function_exists('connDb') === false) { /** * connection into database. * * @return \mysqli */ function connDb() { return new mysqli(dbHost, dbUser, dbPass, dbName); } } if (function_exists('insertData') === false) { /** * @param string $tblName * @param array $data * @return bool|mysqli_result */ function insertData($tblName = '', array $data = []) { $field = implode(',', array_keys($data)); $values = []; foreach (array_values($data) as $value) { $values[] = '"' . $value . '"'; } $dataValues = implode(', ', $values); $strSQL = 'INSERT INTO ' . $tblName . '(' . $field . ') VALUES (' . $dataValues . ') '; $conn = connDb(); if ($conn->query($strSQL) !== false) { return mysqli_insert_id($conn); } else { return $conn->query($strSQL); } } } if (function_exists('updateData') === false) { /** * update data in table. * * @param string $tblName * @param array $data * @param array $condition * * @return boolean */ function updateData($tblName = '', array $data = [], array $condition = []) { # params for update data $fieldKeyData = array_keys($data); $arrData = []; for ($i = 0; $i < count($fieldKeyData); ++$i) { $arrData[$i] = $fieldKeyData[$i] . '="' . $data[$fieldKeyData[$i]] . '"'; } $updateData = implode(', ', $arrData); # params for condition update data $fieldKeyCondition = array_keys($condition); $arrCondition = []; for ($i = 0; $i < count($fieldKeyCondition); ++$i) { $arrCondition[$i] = $fieldKeyCondition[$i] . '="' . $condition[$fieldKeyCondition[$i]] . '"'; } $where = implode(', ', $arrCondition); $strSQL = 'UPDATE ' . $tblName . ' SET ' . $updateData . ' WHERE ' . $where . ' '; $conn = connDb(); return $conn->query($strSQL); } } if (function_exists('deleteData') === false) { /** * delete data in table. * * @param string $tblName * @param array $condition * * @return boolean */ function deleteData($tblName = '', array $condition = []) { # params for condition update data $fieldKeyCondition = array_keys($condition); $arrCondition = []; for ($i = 0; $i < count($fieldKeyCondition); ++$i) { $arrCondition[$i] = $fieldKeyCondition[$i] . '="' . $condition[$fieldKeyCondition[$i]] . '"'; } $where = implode(', ', $arrCondition); $strSQL = 'DELETE FROM ' . $tblName . ' WHERE ' . $where . ' '; $conn = connDb(); return $conn->query($strSQL); } } if (function_exists('getData') === false) { /** * get data from table. * * @param string $tblName * @param string $field * @param array $condition * @param string $result * * @return array */ function getData($tblName = '', $field = '*', array $condition = [], $result = 'result') { $strSQL = 'SELECT ' . $field . ' FROM ' . $tblName . ' '; if (count($condition) > 0) { # params for condition select data $fieldKeyCondition = array_keys($condition); $arrCondition = []; for ($i = 0; $i < count($fieldKeyCondition); ++$i) { $arrCondition[$i] = $fieldKeyCondition[$i] . '="' . $condition[$fieldKeyCondition[$i]] . '"'; } $where = implode(' and ', $arrCondition); $strSQL .= ' WHERE ' . $where . ' '; } $conn = connDb(); $records = $conn->query($strSQL); $data = []; if ($records !== false) { if ($records->num_rows > 0) { switch (strtolower($result)) { case 'result': $data = $records->fetch_all(); break; case 'row': $data = $records->fetch_assoc(); break; } } } return $data; } } if (function_exists('getHeaderTable') === false) { /** * @param $tableName * @return array */ function getHeaderTable($tableName) { $strSQL = 'SHOW COLUMNS FROM ' . $tableName . ' '; $conn = connDb(); $records = $conn->query($strSQL); $data = []; if ($records->num_rows > 0) { foreach ($records->fetch_all() as $row) { $data[] = $row[0]; } } return $data; } } <file_sep>/README.md # jtable-mysqli @author : <NAME> @email : <EMAIL> DIRECTORY --------- db/ Contains a table sample jtble/ library from jtable. http://jtable.org/ mysqli/ Crud helper for handle MySQLi native function CONFIGURATION ------------- Change Database configuration in "mysqli/CrudMysqliHelper.php" Change your field structure in "jTableSimple.php" Change your table name and primary key to use crud helper in "PersonActions.php" **NOTES:** For purpose any help please send me an email.
c939c263ab02729f672916af7d21c10942a938aa
[ "Markdown", "PHP" ]
3
PHP
lismansihotang/jtable-mysqli
a6f6464fa49922602cb6feed506c52f586fb3ffd
a060d30ce8671d9e3282e208b9e93e0e0923e0d8
refs/heads/master
<file_sep>const renderSkill = (skill) => { return `<div class="grid-item"> <div class="skill-container"> <div class="img-container"> <img src="../skills/${skill}.png"> </div> <div class="skill-name"> <p>${skill}</p> </div> </div> </div>` } const technologies = () => { let technologies = ['HTML5', 'CSS3', 'NodeJS', 'React', 'Github', 'Git', 'Webpack', 'Vim','PostgreSQL', 'MongoDB', 'MySQL', 'Postman', 'jQuery', 'Firebase']; return `<div class=skill-wrapper> <h2 class="title">Technologies / Frameworks</h2> <div class=grid-wrapper id="technologies"> ${technologies.map(technology => renderSkill(technology)).join('')} </div> </div>` } const languages = () => { let languages = ['C', 'C++', 'Python', 'Javascript', 'PHP']; return `<div class=skill-wrapper> <h2 class="title">Languages</h2> <div class=grid-wrapper id="languages"> ${languages.map(language => renderSkill(language)).join('')} </div> </div>` }<file_sep> const ls = (file) => { return `<span class="file">${file}</span>` } const about = () => { return `<span>Originally from Iowa, I am a software engineer living in the Bay Area. I have experience in both frontend and backend, as well as low-level C programming and hardware. I have always been interested in learning and try to learn something new each day. You can check out my projects here or find me on github / Linkedin with the social.txt file. </span>` } const social = () => { return `<span class="social"><a target="_blank" rel="noopener noreferrer" href="https://www.linkedin.com/in/kyleamckee/">LinkedIn</a></span> <span class="social"><a target="_blank" rel="noopener noreferrer" href="https://github.com/KyleAMcKee/">Github</a></span><br> <span>Results above are clickable</span>` } const help = () => { return `<span>The following commands are available:</span><br/> <span class="help-text">ls</span> <span class="help-text">clear</span> <span class="help-text">cat</span><br/>` } const handleTab = (event) => { if (event.keyCode === 9 || event.which === 9) { console.log("auto complete"); } } const updateTerminal = (event) => { let input = document.querySelector('#terminal-input'); if (event.which === 13 || event.keyCode === 13) { let history = document.querySelector("#history") let files = ["about.txt", "social.txt"] let [command, argument] = input.value.split(' '); history.innerHTML += `<span class="history-item"><EMAIL> ${input.value}</span>`; if (!input.value) {return} if (command === "ls") { history.innerHTML += `<span class="history-item">${files.map(file => ls(file)).join('')}</span>` } else if (command === "cat") { if (argument === "about.txt") { history.innerHTML += about(); } else if (argument === "social.txt") { history.innerHTML += social(); } else { history.innerHTML += `${command}: ${argument}: No such file or directotry`; } } else if (command === "clear") { history.innerHTML = ""; } else if (command === "help") { history.innerHTML += help(); } else { history.innerHTML += `<span class="history-item">zsh: command not found: ${command}</span>` } input.value = ""; } } const setDate = () => { let currentdate = new Date(); let datetime = currentdate.getDate() + "/" + (currentdate.getMonth()+1) + "/" + currentdate.getFullYear() + " @ " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds(); return datetime; } const terminal = () => { return `<div id="terminal-wrapper"> <div id="terminal"> <div id="history"><span>Last login: ${setDate()}</span></div> <div id="terminal-line"> <span id="terminal-user"><EMAIL></span> <input type="text" id="terminal-input" value=""> </div> </div> <div id="terminal-help"> <h2>Unfamiliar with the terminal? Use the navigation bar up top instead.</h2> <h3>Type help for a list of commands. Autocomplete with <code>tab</code> and more features to be implemented later</h3> </div> </div>` }<file_sep># Website of skills and projects Can be viewed publicly at www.kylemckee.io Written in vanilla JS without any frameworks ToDo: update terminal on main page to add more functions / make it more robust
851e17e35c190e7de0c95526f79bbce6fefec08b
[ "JavaScript", "Markdown" ]
3
JavaScript
KyleAMcKee/portfolio
74bccfdaadc0d502a380a28b08d64daa4ad3019d
a10bbb74e55d322a9c32a21326cbcadb651d9a5f
refs/heads/main
<repo_name>SnigdhaKanchana/HacktoberFest_2021<file_sep>/Binary Tree/iscomplete.cpp #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include<bits/stdc++.h> using namespace std; struct Node{ int data; struct Node *left,*right; }; Node* newNode(int x){ Node* nn = new Node; nn->data = x; nn->left = nn->right = NULL; return nn; } Node* insert(Node* root,int x){ if(root == NULL){ return newNode(x); } else if(root->data < x){ root->right = insert(root->right,x); } else{ root->left = insert(root->left,x); } return root; } bool isComplete(Node* root){ queue<Node*> q; bool flag = false; q.push(root); while(!q.empty()){ int size = q.size(); while(size--){ Node* f = q.front(); q.pop(); if(f != NULL){ if(flag) return false; q.push(f->left); q.push(f->right); } else{ flag = true; } } } return true; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t; cin >> t; while(t--){ int n; cin >> n; Node* root = NULL; for(int i = 0 ; i < n; i++){ int x; cin >> x; root = insert(root,x); } isComplete(root)? cout << "Yes" : cout << "No"; cout << endl; } return 0; } <file_sep>/Greedy/mytree.cpp #include<bits/stdc++.h> #include<iostream> using namespace std; struct Node{ int data; struct Node *left,*right; }; Node* newnode(int ele){ Node* node = new Node; node->data = ele; node->left = NULL; node->right = NULL; return node; } Node* insert(Node* root,int ele){ if(root==NULL) return newnode(ele); if(root->data < ele) root->right = insert(root->right,ele); if(root->data > ele) root->left = insert(root->left,ele); return root; } void pre(Node* root){ if(root == NULL) return; cout << root->data << endl; pre(root->left); pre(root->right); } int main(){ int n,data; cin >> n; Node* root = NULL; while(n--){ cin >> data; root = insert(root, data); } pre(root); return 0; } <file_sep>/Greedy/01knapsack_Recursion.cpp #include<bits/stdc++.h> #include<iostream> using namespace std; int knapsack(int wt[], int v[], int w, int n){ if(n==0 || w==0) return 0; if(wt[n-1] <= w) return max((v[n-1]+knapsack(wt,v,w-wt[n-1],n-1)), knapsack(wt,v,w,n-1)); else if(wt[n-1] > w) return knapsack(wt,v,w,n-1); } int main(){ int n,w,wt[100],v[100]; cin >> n >> w ; for(int i=0;i<n;i++){ cin >> wt[i] ; } for(int i=0;i<n;i++){ cin >> v[i] ; } cout << knapsack(wt,v,w,n) << endl; } <file_sep>/Binary Tree/zigzaglevelorder.cpp #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include<bits/stdc++.h> using namespace std; struct Node{ int data; struct Node *left,*right; }; Node* newNode(int x){ Node* nn = new Node; nn->data = x; nn->left = nn->right = NULL; return nn; } Node* insert(Node* root,int x){ if(root == NULL){ return newNode(x); } else if(root->data < x){ root->right = insert(root->right,x); } else{ root->left = insert(root->left,x); } return root; } /* Method1 : using 1 uqeue, 1 stack*/ void zigzagl(Node* root){ bool d = false; queue<Node*> q; q.push(root); stack<Node*> s; while(!q.empty()){ int size = q.size(); while(size--){ Node* f = q.front(); q.pop(); if(d){ cout << f->data << " "; } else{ s.push(f); } if(f->left != nullptr) q.push(f->left); if(f->right != NULL) q.push(f->right); } if(!d){ while(!s.empty()){ Node* x= s.top(); s.pop(); cout << x->data << " "; } } d = !d; } } /* Method2 : using 2stacks*/ void zigzagl(Node* root){ //bool d = false; stack<Node*> s1; stack<Node*> s2; s1.push(root); while(!s1.empty() || !s2.empty()){ while(!s1.empty()){ Node* f = s1.top(); s1.pop(); cout << f->data << " "; if(f->right != NULL) s2.push(f->right); if(f->left != NULL) s2.push(f->left); } while(!s2.empty()){ Node* f = s2.top(); s2.pop(); cout << f->data << " "; if(f->left != NULL) s1.push(f->left); if(f->right != NULL) s1.push(f->right); } } } /* Method3 : using deque*/ void zigzagl(Node* root){ bool d = false; deque<Node*> dq; dq.push_front(root); while(!dq.empty()){ int size = dq.size(); while(size--){ if(d){ Node* f = dq.front(); dq.pop_front(); cout << f->data << " "; if(f->left != NULL) dq.push_back(f->left); if(f->right != NULL) dq.push_back(f->right); } else{ Node* f = dq.back(); dq.pop_back(); cout << f->data << " "; if(f->right != NULL) dq.push_front(f->right); if(f->left != NULL) dq.push_front(f->left); } } d = !d; } } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t; cin >> t; while(t--){ int n; cin >> n; Node* root = NULL; for(int i = 0 ; i < n; i++){ int x; cin >> x; root = insert(root,x); } zigzagl(root); cout << endl; } return 0; } <file_sep>/Greedy/subsetsum_tab.cpp #include<bits/stdc++.h> #include<iostream> using namespace std; bool t[102][102]; int ss(int arr[], int n, int sums){ for(int j=0;j<sums;j++){ t[0][j] = false; } for(int i=0;i<n;i++){ t[i][0] = true; } for(int i=1;i<=n;i++){ for(int j=1;j<=sums;j++){ if(arr[i-1] <= j){ t[i][j] = t[i][j-arr[i-1]] || t[i-1][j]; } else{ t[i][j] = t[i-1][j]; } } } return t[n][sums]; } int main(){ int n , sums , arr[n]; cin >> n >> sums; for(int i=0;i<n;i++){ cin >> arr[i]; } cout << ss(arr, n , sums); } <file_sep>/Greedy/01knapsack_tabulation.cpp #include<bits/stdc++.h> #include<iostream> using namespace std; int t[102][102]; int knapsack(int wt[], int v[], int w, int n){ for(int i=0;i<n;i++){ for(int j=0;j<w;j++){ if(i==0 || j==0){ t[i][j] = 0; } if(wt[i-1] <= j){ t[i][j] = max((v[n-1]+t[i-1][j-wt[i-1]]),t[i-1][j]); } else if(wt[i-1] > j){ t[i][j] = t[i-1][j]; } } } return t[n][w]; } int main(){ int n,w,wt[100],v[100]; cin >> n >>w ; memset(t,-1,sizeof(t)); for(int i=0;i<n;i++){ cin >> wt[i]; } for(int i=0;i<n;i++){ cin >> v[i]; } cout << knapsack(wt,v,w,n) << endl; }
43661db5030006848d4762e8c4570eda0515f540
[ "C++" ]
6
C++
SnigdhaKanchana/HacktoberFest_2021
7a6e7cc801bfb3ade4a80cfc642c4b4f685b8364
abd45d1c8b83b4a919ac525aad9b325ae54e2901
refs/heads/master
<file_sep>package com.gao.gdbookself.fragments; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gao.gdbookself.R; import com.gao.gdbookself.adapters.BookListAdapter; import com.gao.gdbookself.entities.BookInfoEntity; import com.gao.gdbookself.entities.BookListEntity; import com.gao.gdbookself.utils.JsonUtils; import com.gao.gdbookself.utils.ListOnItemClickListener; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.lidroid.xutils.view.annotation.ViewInject; public class BookListFragment extends Fragment { private String path; private BookListAdapter listAdapter; private List<BookInfoEntity> infoEntities; @ViewInject(R.id.booklist_listview) private PullToRefreshListView bookListView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_book_list, container, false); ViewUtils.inject(this, view); bookListView.setMode(Mode.BOTH); path = getArguments().getString("path"); if (infoEntities == null) { infoEntities = new ArrayList<BookInfoEntity>(); } if (listAdapter == null) { listAdapter = new BookListAdapter(getActivity()); listAdapter.bindData(infoEntities); } bookListView.setAdapter(listAdapter); ListOnItemClickListener listener = new ListOnItemClickListener( getActivity(), listAdapter); bookListView.setOnItemClickListener(listener); return view; } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); if (infoEntities.size() == 0 || infoEntities == null) { HttpUtils utils = new HttpUtils(); downloadData(utils); } } private void downloadData(HttpUtils utils) { utils.send(HttpMethod.GET, path, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { // TODO Auto-generated method stub BookListEntity listEntity = JsonUtils .parseBookList(responseInfo.result); if (listEntity != null) { infoEntities = listEntity.getInfoEntities(); if (infoEntities != null) { listAdapter.bindData(infoEntities); listAdapter.notifyDataSetChanged(); } } } @Override public void onFailure(HttpException error, String msg) { // TODO Auto-generated method stub Log.i("BookListFragment", "--onFailure->>path" + path + "result" + msg); } }); } } <file_sep>package com.gao.gdbookself.fragments; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.gao.gdbookself.R; import com.gao.gdbookself.adapters.BookInfoAdapter; import com.gao.gdbookself.entities.BookInfoEntity; import com.gao.gdbookself.entities.BookListEntity; import com.gao.gdbookself.utils.CommonUtils; import com.gao.gdbookself.utils.FooterOnClickListener; import com.gao.gdbookself.utils.JsonUtils; import com.gao.gdbookself.utils.ListOnItemClickListener; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.lidroid.xutils.view.annotation.ViewInject; public class SearchHotFragment extends Fragment { private ArrayList<String> paths; @ViewInject(R.id.bookshop_search_hot_list) private ListView searchHotListView; @ViewInject(R.id.bookshop_new_book_list) private ListView newBookListView; @ViewInject(R.id.bookshop_boy_list) private ListView boyListView; @ViewInject(R.id.bookshop_girl_list) private ListView girlListView; @ViewInject(R.id.bookshop_agency_list) private ListView agencyListView; private BookInfoAdapter searchHotAdapter, newBookAdapter, boyAdapter, girlAdapter, agencyAdapter; private List<BookInfoEntity> infoEntities; private List<TextView> headers, footers; private int[] searchHotId, wholeBookId; private String loadingMore; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_search_hot, container, false); ViewUtils.inject(this, view); paths = getArguments().getStringArrayList("paths"); // 设置头部 headers = setListViews(headers); // 设置脚部 footers = setListViews(footers); loadingMore = getActivity().getResources().getString( R.string.loading_more); // 设置脚步的监听事件 searchHotId = new int[] { CommonUtils.HOT_LIST, CommonUtils.HOT_NEW_BOOK, CommonUtils.HOT_BOY, CommonUtils.HOT_GIRL, CommonUtils.HOT_AGENCY }; wholeBookId = new int[] { CommonUtils.WHOLE_SEARCH, 0, CommonUtils.WHOLE_BOY, CommonUtils.WHOLE_GIRL, 0 }; for (int i = 0; i < footers.size(); i++) { TextView txtView = footers.get(i); FooterOnClickListener clickListener = null; if (paths.size() == 5) { clickListener = new FooterOnClickListener(getActivity(), searchHotId[i]); } else if (paths.size() == 3) { clickListener = new FooterOnClickListener(getActivity(), wholeBookId[i]); } txtView.setOnClickListener(clickListener); } // 初始化实体类列表 if (infoEntities == null) { infoEntities = new ArrayList<BookInfoEntity>(); } // 创建Adapter实例以及绑定数据 searchHotAdapter = initAdapter(searchHotAdapter); newBookAdapter = initAdapter(newBookAdapter); boyAdapter = initAdapter(boyAdapter); girlAdapter = initAdapter(girlAdapter); agencyAdapter = initAdapter(agencyAdapter); // 给listView添加头部,脚部,以及绑定Adapter searchHotListView.addHeaderView(headers.get(0)); searchHotListView.addFooterView(footers.get(0)); searchHotListView.setAdapter(searchHotAdapter); newBookListView.addHeaderView(headers.get(1)); newBookListView.addFooterView(footers.get(1)); newBookListView.setAdapter(newBookAdapter); boyListView.addHeaderView(headers.get(2)); boyListView.addFooterView(footers.get(2)); boyListView.setAdapter(boyAdapter); girlListView.addHeaderView(headers.get(3)); girlListView.addFooterView(footers.get(3)); girlListView.setAdapter(girlAdapter); agencyListView.addHeaderView(headers.get(4)); agencyListView.addFooterView(footers.get(4)); agencyListView.setAdapter(agencyAdapter); ListOnItemClickListener searchHotListener = new ListOnItemClickListener( getActivity(), searchHotAdapter); ListOnItemClickListener newBookListener = new ListOnItemClickListener( getActivity(), newBookAdapter); ListOnItemClickListener boyListener = new ListOnItemClickListener( getActivity(), boyAdapter); ListOnItemClickListener girlListener = new ListOnItemClickListener( getActivity(), girlAdapter); ListOnItemClickListener agencylListener = new ListOnItemClickListener( getActivity(), agencyAdapter); searchHotListView.setOnItemClickListener(searchHotListener); newBookListView.setOnItemClickListener(newBookListener); boyListView.setOnItemClickListener(boyListener); girlListView.setOnItemClickListener(girlListener); agencyListView.setOnItemClickListener(agencylListener); return view; } /** * 初始化Adapter * * @param adatper * @return */ private BookInfoAdapter initAdapter(BookInfoAdapter adatper) { if (adatper == null) { adatper = new BookInfoAdapter(getActivity()); adatper.bindData(infoEntities); } return adatper; } /** * 初始化头部和脚部 * * @param views * @return */ private List<TextView> setListViews(List<TextView> views) { if (views == null) { views = new ArrayList<TextView>(); // 计算像素 int txtDp = getActivity().getResources().getDimensionPixelSize( R.dimen.dp10); for (int i = 0; i < 5; i++) { TextView txtView = new TextView(getActivity()); txtView.setTextSize(17); txtView.setPadding(txtDp, txtDp, txtDp, txtDp); views.add(txtView); } } return views; } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); HttpUtils utils = new HttpUtils(); if (paths.size() == 5) { if (infoEntities == null || infoEntities.size() == 0) { downloadData(utils, paths.get(0), searchHotAdapter, 0); downloadData(utils, paths.get(1), newBookAdapter, 1); downloadData(utils, paths.get(2), boyAdapter, 2); downloadData(utils, paths.get(3), girlAdapter, 3); downloadData(utils, paths.get(4), agencyAdapter, 4); } } else if (paths.size() == 3) { newBookListView.setVisibility(View.GONE); agencyListView.setVisibility(View.GONE); if (infoEntities == null || infoEntities.size() == 0) { downloadData(utils, paths.get(0), searchHotAdapter, 0); downloadData(utils, paths.get(1), boyAdapter, 2); downloadData(utils, paths.get(2), girlAdapter, 3); } } } /** * 从网络上下载数据 * * @param utils * @param path * @param adapter * @param position */ private void downloadData(HttpUtils utils, String path, final BookInfoAdapter adapter, final int position) { utils.send(HttpMethod.GET, path, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { // TODO Auto-generated method stub BookListEntity listEntity = JsonUtils .parseBookList(responseInfo.result); if (listEntity != null) { // 设置头部详细属性 TextView header = headers.get(position); header.setText(listEntity.getGroupName()); header.setFocusable(true); // 设置脚部详细属性 TextView footer = footers.get(position); footer.setGravity(Gravity.CENTER); footer.setText(loadingMore); infoEntities = listEntity.getInfoEntities(); if (infoEntities != null) { adapter.bindData(infoEntities); adapter.notifyDataSetChanged(); } } } @Override public void onFailure(HttpException error, String msg) { // TODO Auto-generated method stub } }); } } <file_sep>package com.gao.gdbookself.activities; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import com.gao.gdbookself.R; import com.gao.gdbookself.fragments.BookTypeFragment; import com.gao.gdbookself.fragments.RankListsFragment; import com.gao.gdbookself.fragments.SearchHotFragment; import com.gao.gdbookself.utils.CommonUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ContentView; import com.lidroid.xutils.view.annotation.ViewInject; /** * 书城部分 * * @author GaoHanqiong */ @ContentView(R.layout.activity_book_shop) public class BookShopActivity extends FragmentActivity implements OnCheckedChangeListener { private List<Fragment> fragments; private FragmentManager manager; private FragmentTransaction transaction; @ViewInject(R.id.bookshop_radio_group) private RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewUtils.inject(this); radioGroup.setOnCheckedChangeListener(this); if (fragments == null) { fragments = new ArrayList<Fragment>(); fragments.add(new SearchHotFragment()); fragments.add(new RankListsFragment()); fragments.add(new SearchHotFragment()); fragments.add(new BookTypeFragment()); } manager = getSupportFragmentManager(); transaction = manager.beginTransaction(); // 传值 setListBundle(fragments.get(0), CommonUtils.getPaths(CommonUtils.HOT)); transaction.add(R.id.bookshop_changed_fragment, fragments.get(0)); transaction.commit(); } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub transaction = manager.beginTransaction(); ArrayList<String> paths = null; switch (checkedId) { case R.id.bookshop_radio_button0: paths = CommonUtils.getPaths(CommonUtils.HOT); setListBundle(fragments.get(0), paths); transaction.replace(R.id.bookshop_changed_fragment, fragments.get(0)); break; case R.id.bookshop_radio_button1: transaction.replace(R.id.bookshop_changed_fragment, fragments.get(1)); break; case R.id.bookshop_radio_button2: paths = CommonUtils.getPaths(CommonUtils.WHOLE); setListBundle(fragments.get(2), paths); transaction.replace(R.id.bookshop_changed_fragment, fragments.get(2)); break; case R.id.bookshop_radio_button3: transaction.replace(R.id.bookshop_changed_fragment, fragments.get(3)); break; default: break; } transaction.commit(); } /** * 传List值的方法 * * @param fragment * @param paths */ private void setListBundle(Fragment fragment, ArrayList<String> paths) { Bundle args = new Bundle(); args.putStringArrayList("paths", paths); fragment.setArguments(args); } } <file_sep>package com.gao.gdbookself.entities; import java.io.Serializable; import java.util.List; /** * 分类的实体类 * * @author GaoHanqiong */ public class TypeEntity implements Serializable { private static final long serialVersionUID = 5482142618472601511L; private List<ChannelEntity> boyChannel; private List<ChannelEntity> girlChannel; private List<ChannelEntity> sepcialChannel; private List<ChannelEntity> searchChannel; public List<ChannelEntity> getBoyChannel() { return boyChannel; } public void setBoyChannel(List<ChannelEntity> boyChannel) { this.boyChannel = boyChannel; } public List<ChannelEntity> getGirlChannel() { return girlChannel; } public void setGirlChannel(List<ChannelEntity> girlChannel) { this.girlChannel = girlChannel; } public List<ChannelEntity> getSepcialChannel() { return sepcialChannel; } public void setSepcialChannel(List<ChannelEntity> sepcialChannel) { this.sepcialChannel = sepcialChannel; } public List<ChannelEntity> getSearchChannel() { return searchChannel; } public void setSearchChannel(List<ChannelEntity> searchChannel) { this.searchChannel = searchChannel; } } <file_sep>package com.gao.gdbookself.activities; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import com.gao.gdbookself.R; import com.gao.gdbookself.fragments.BookListFragment; import com.gao.gdbookself.utils.CommonUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ContentView; @ContentView(R.layout.activity_book_list) public class BookListActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewUtils.inject(this); int groupId = getIntent().getIntExtra("groupId", 0); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); Fragment fragment = new BookListFragment(); Bundle args = new Bundle(); args.putString("path", CommonUtils.getMoreListPath(groupId)); fragment.setArguments(args); transaction.add(R.id.booklist_changed_fragment, fragment); transaction.commit(); } } <file_sep>package com.gao.gdbookself.activities; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.gao.gdbookself.R; import com.gao.gdbookself.adapters.ContentsAdapter; import com.gao.gdbookself.adapters.ContentsSpinnerAdapter; import com.gao.gdbookself.customview.ListViewForScrollView; import com.gao.gdbookself.entities.BookBriefEntity; import com.gao.gdbookself.entities.BookInfoEntity; import com.gao.gdbookself.entities.ContentsEntity; import com.gao.gdbookself.utils.CommonUtils; import com.gao.gdbookself.utils.JsonUtils; import com.lidroid.xutils.BitmapUtils; import com.lidroid.xutils.HttpUtils; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.lidroid.xutils.http.client.HttpRequest.HttpMethod; import com.lidroid.xutils.view.annotation.ContentView; import com.lidroid.xutils.view.annotation.ViewInject; @ContentView(R.layout.activity_contents) public class ContentsActivity extends Activity implements OnItemSelectedListener { private int flag; private String update; private HttpUtils utils; private BookInfoEntity infoEntity; private List<ContentsEntity> cEntities; private ContentsAdapter cAdapter; private List<String> pages; private ContentsSpinnerAdapter sAdapter; private BookBriefEntity briefEntity; private BookBriefEntity parentContents; @ViewInject(R.id.contents_imgview) private ImageView imgCover; @ViewInject(R.id.contents_bookname) private TextView txtName; @ViewInject(R.id.contents_author) private TextView txtAuthor; @ViewInject(R.id.contents_type) private TextView txtType; @ViewInject(R.id.contents_origin) private TextView txtOrigin; @ViewInject(R.id.contents_brief) private TextView txtBrief; @ViewInject(R.id.contents_last_name) private TextView txtLastName; @ViewInject(R.id.contents_last_time) private TextView txtLastTime; @ViewInject(R.id.contents_listview) private ListViewForScrollView contentsList; @ViewInject(R.id.contents_spinner) private Spinner spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewUtils.inject(this); utils = new HttpUtils(); // 为了使ScrollView滚动条在最上方 txtName.setFocusable(true); txtName.setFocusableInTouchMode(true); infoEntity = (BookInfoEntity) getIntent().getSerializableExtra( "infoEntity"); update = getResources().getString(R.string.contents_update); txtName.setText(infoEntity.getResourceName()); txtAuthor.append(infoEntity.getAuthor()); txtType.append(infoEntity.getSubject()); if (cAdapter == null) { cAdapter = new ContentsAdapter(this); if (cEntities == null) { cEntities = new ArrayList<ContentsEntity>(); } cAdapter.bindData(cEntities); } TextView header = new TextView(this); header.setText("目录"); int headerDp = getResources().getDimensionPixelSize(R.dimen.dp10); float txtSize = getResources().getDimensionPixelSize(R.dimen.sp10); header.setPadding(headerDp, headerDp, headerDp, headerDp); header.setTextSize(txtSize); contentsList.addHeaderView(header); contentsList.setAdapter(cAdapter); if (sAdapter == null) { sAdapter = new ContentsSpinnerAdapter(this); if (pages == null) { pages = setPages(1); } sAdapter.bindData(pages); } spinner.setAdapter(sAdapter); spinner.setOnItemSelectedListener(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if (briefEntity == null) { BitmapUtils bitmapUtils = new BitmapUtils(this); String briefPath = CommonUtils.getBookInfoPath(infoEntity .getResourceId()); downloadInfo(briefPath); String bitmapPath = infoEntity.getPicUrl(); bitmapUtils.display(imgCover, bitmapPath); } } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub downloadContents(position + 1); flag = position - 1; } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } public void firstPageOnClick(View view) { spinner.setSelection(0); } public void lastestPageOnClick(View view) { if (parentContents != null) { // 当前位置 int position = parentContents.getPage_No() - 1; if (position <= 0) { Toast.makeText(this, "已经是第一页了", Toast.LENGTH_SHORT).show(); } else if (flag == position) { Log.i("", "--->>" + position); } else { spinner.setSelection(position - 1); } } } public void nextPageOnClick(View view) { if (parentContents != null) { // 当前位置 int position = parentContents.getPage_No() - 1; if (position >= parentContents.getPage_count() - 1) { Toast.makeText(this, "已经是最后一页了", Toast.LENGTH_SHORT).show(); } else if (flag == position) { Log.i("", "--->>" + position); } else { spinner.setSelection(position + 1); } } } public void lastPageOnClick(View view) { if (parentContents != null) { spinner.setSelection(parentContents.getPage_count() - 1); } } /** * 下载目录 * * @param position */ private void downloadContents(int position) { String path = CommonUtils.getContentsPath(infoEntity.getResourceId(), position, infoEntity.getSerialNum()); utils.send(HttpMethod.GET, path, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { // TODO Auto-generated method stub parentContents = JsonUtils.parseContents(responseInfo.result); if (parentContents != null) { cEntities = parentContents.getContentsEntities(); if (cEntities != null) { cAdapter.bindData(cEntities); cAdapter.notifyDataSetChanged(); } } } @Override public void onFailure(HttpException error, String msg) { // TODO Auto-generated method stub } }); } /** * 下载书本简介信息 * * @param utils * @param path */ private void downloadInfo(String path) { utils.send(HttpMethod.GET, path, new RequestCallBack<String>() { @Override public void onSuccess(ResponseInfo<String> responseInfo) { briefEntity = JsonUtils.parseBrief(responseInfo.result); if (briefEntity != null) { infoEntity = briefEntity.getInfoEntity(); txtBrief.setText(infoEntity.getBrief()); txtLastName.setText(infoEntity.getLastSerialName()); txtLastTime.setText(CommonUtils.getDate(infoEntity .getLastUpDateTime()) + update); cEntities = briefEntity.getContentsEntities(); if (cEntities != null) { cAdapter.bindData(cEntities); cAdapter.notifyDataSetChanged(); } } int pageCount = briefEntity.getPage_count(); pages = setPages(pageCount); sAdapter.bindData(pages); sAdapter.notifyDataSetChanged(); } @Override public void onFailure(HttpException error, String msg) { // TODO Auto-generated method stub } }); } private List<String> setPages(int pageCount) { List<String> lists = new ArrayList<String>(); for (int i = 0; i < pageCount; i++) { lists.add("第" + (i + 1) + "页" + "/共" + pageCount + "页"); } return lists; } } <file_sep>package com.gao.gdbookself.entities; import java.util.List; public class BookBriefEntity { private String accountId; private int isPrice; private int page_No; private int page_count; private String resourceid; private String ret; private BookInfoEntity infoEntity; private List<ContentsEntity> contentsEntities; public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public int getIsPrice() { return isPrice; } public void setIsPrice(int isPrice) { this.isPrice = isPrice; } public int getPage_No() { return page_No; } public void setPage_No(int page_No) { this.page_No = page_No; } public int getPage_count() { return page_count; } public void setPage_count(int page_count) { this.page_count = page_count; } public String getResourceid() { return resourceid; } public void setResourceid(String resourceid) { this.resourceid = resourceid; } public String getRet() { return ret; } public void setRet(String ret) { this.ret = ret; } public BookInfoEntity getInfoEntity() { return infoEntity; } public void setInfoEntity(BookInfoEntity infoEntity) { this.infoEntity = infoEntity; } public List<ContentsEntity> getContentsEntities() { return contentsEntities; } public void setContentsEntities(List<ContentsEntity> contentsEntities) { this.contentsEntities = contentsEntities; } } <file_sep>package com.gao.gdbookself.entities; import java.util.List; public class BookListEntity { private int ret; // ?? private int dataNum; private String groupName;// list的名字 热搜榜单 private List<BookInfoEntity> infoEntities; public int getRet() { return ret; } public void setRet(int ret) { this.ret = ret; } public int getDataNum() { return dataNum; } public void setDataNum(int dataNum) { this.dataNum = dataNum; } public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } public List<BookInfoEntity> getInfoEntities() { return infoEntities; } public void setInfoEntities(List<BookInfoEntity> infoEntities) { this.infoEntities = infoEntities; } } <file_sep>GDBookSelf ========== read app <file_sep>package com.gao.gdbookself.entities; public class ContentsEntity { private int chargeType; private int contentLen; private int contentType; private String intro; private int price; private String resourceId; private int serialId; private String serialName; public int getChargeType() { return chargeType; } public void setChargeType(int chargeType) { this.chargeType = chargeType; } public int getContentLen() { return contentLen; } public void setContentLen(int contentLen) { this.contentLen = contentLen; } public int getContentType() { return contentType; } public void setContentType(int contentType) { this.contentType = contentType; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public int getSerialId() { return serialId; } public void setSerialId(int serialId) { this.serialId = serialId; } public String getSerialName() { return serialName; } public void setSerialName(String serialName) { this.serialName = serialName; } } <file_sep>package com.gao.gdbookself.utils; import android.content.Context; import android.content.Intent; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import com.gao.gdbookself.activities.ContentsActivity; import com.gao.gdbookself.entities.BookInfoEntity; public class ListOnItemClickListener implements OnItemClickListener{ private Context context; private BaseAdapter adapter; public ListOnItemClickListener(Context context,BaseAdapter adapter) { // TODO Auto-generated constructor stub this.context = context; this.adapter = adapter; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub BookInfoEntity entity = (BookInfoEntity) adapter.getItem(position-1); Intent intent = new Intent(context, ContentsActivity.class); intent.putExtra("infoEntity", entity); context.startActivity(intent); } } <file_sep>package com.gao.gdbookself.adapters; import java.util.List; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.gao.gdbookself.R; public class ContentsSpinnerAdapter extends BaseAdapter { private Context context; private List<String> lists; public ContentsSpinnerAdapter(Context context) { // TODO Auto-generated constructor stub this.context = context; } public void bindData(List<String> lists){ this.lists = lists; } @Override public int getCount() { // TODO Auto-generated method stub return lists.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return lists.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub TextView view = null; if (convertView == null) { view = new TextView(context); } else { view = (TextView) convertView; } int txtDp = context.getResources().getDimensionPixelSize(R.dimen.dp10); view.setPadding(txtDp, txtDp, txtDp, txtDp); view.setText(lists.get(position)); return view; } }
3bbced18bdedbb9ac26d271afcecd5b117377676
[ "Markdown", "Java" ]
12
Java
GaoHanqiong/GDBookSelf
c2f8f557177fb0590fff0f75279a8faed7d4d23e
9758609991d434745a2f523edc85816cbc46e187
refs/heads/master
<file_sep>#include "ros/ros.h" #include "std_msgs/String.h" #include "ArduinoJson.h" #include <iostream> #include <sstream> #include <string> #include <geometry_msgs/Twist.h> #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <sensor_msgs/NavSatFix.h> #include <ctime> #include <fstream> #include <unistd.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/Image.h> #include <std_msgs/Int32.h> #include <sensor_msgs/LaserScan.h> #include <stdlib.h> #include <stdio.h> #include <std_msgs/Empty.h> #include <std_srvs/Empty.h> #include <atlas80evo_msgs/SetONOFF.h> #include <atlas80evo_msgs/SetSound.h> #include <atlas80evo_msgs/SetFSMState.h> #include <atlas80evo_msgs/FSMState.h> #include <atlas80evo_msgs/SetFSMState.h> #include <atlas80evo_msgs/SetPose2D.h> #include <geometry_msgs/PoseStamped.h> using namespace std; using namespace std_msgs; using namespace ros; string ver = "FMS_Handler Version 1.9.7"; string AGV_ID = "AT200_1"; Publisher health_pub; Publisher diag_pub; Publisher slam_pt_pub; Publisher encr_pub; Publisher encl_pub; Publisher sr_break_pub; Publisher led_pub; Publisher nav_pub; Publisher arm_pub; Publisher point_pub; Publisher mv_pub; Publisher skip_pub; Publisher sos_pub; Publisher moveskipper_pub; Publisher sus_pub; Publisher to_obu_pub; Publisher sched_pub; Publisher reg_pub; Publisher arm_param_pub; Publisher armxtra_pub; Publisher sysled_pub; ServiceClient shutdownClient; ServiceClient findpickdropClient; ServiceClient findchargerClient; ServiceClient playsound; ServiceClient findoutchargerClient; ServiceClient stateClient; ServiceClient findtableClient; ServiceClient checkposeClient; atlas80evo_msgs::SetSound srv; geometry_msgs::Twist sr_break; int SR_SW = 0; bool suspend = false; bool found_table = false;//change this if true if bypass findtable bool found_charger = false; float max_charge = 100.0; float low_charge = 5.0; float junc_offset = 1.2; float last_pX = 0.0; float last_pY = 0.0; float last_encL = 0.0; float last_encR = 0.0; float distPXY = 0.0; float distENC = 0.0; float MoveSOS_XYtoENC_Err = 10.0; int batt_int = 0; int RainFall = 1; int HighHumidity = 50; int sr_led = 0; bool error = false; bool wait = false; bool waita = false; bool juncfound = false; bool NoTableError = false; bool NoChargerError = false; bool HumidSOS = false; bool RainSOS = false; bool OfflineSOS = false; bool NoExit = false; bool stopobs = false; bool firstNavi = true; string cur_arm = ""; string ms_a=""; string ms_pt=""; string ms_x="999"; string ms_y="999"; string ms_x_1="999"; string ms_y_1="999"; string ms_z=""; string ms_w=""; string ms_act="done"; string ms_seq=""; string sched_id=""; string ss_id=""; string charge="0"; string SR="0"; string sos_ID=""; string sos_type=""; string env_temp=""; string humid=""; string obu_id=""; string obu_temp=""; string rain=""; string Tray1="1"; string Tray2="1"; string Tray3="1"; string Tray4="1"; string cur_obj_detected ="4.0"; string cur_state="STANDBY"; string before_state="STANDBY"; string STATE = "STANDBY"; string armparam; vector<string> sosID; vector<int>sosID_enum; DynamicJsonBuffer msstobj_Buffer; JsonVariant msstObj; JsonVariant msstptxy_ref; //General variable bool move_skip = false; string ms_id = ""; int ms_cnt = 0; int ms_max = 0; string cur_lat= ""; string cur_long = ""; string cur_mapfname = ""; string ptsX="0.0"; string ptsY="0.0"; bool DropError = false; bool PickError = false; bool DropFail = false; bool PickFail = false; //for diagnostic string ldr_2df = "1", ldr_2dr = "1", ldr_3d= "1"; string batt = ""; string lowbatt = "1"; string mot_l = "1",mot_r = "1"; string llc = "1"; string obu = "1"; string enc_l = "1", enc_r = "1"; string cam = "1",cpu= "1",ram = "1",arm="1"; string esw="1"; string imu="1"; string tcam="1"; string tray="1"; Time llc_time; Time lidar3_time; Time lidar2f_time; Time lidar2r_time; Time cam_time; Time obu_time; Time arm_time; Time health_t; Time imu_time; Time tray_time; Time tcam_time; Time sus_t; Time wait_t; Time waita_t; Time obs_t; Time alert_t; Time same_loc_delay; string sos_ref[]={ "indexIncreaser", "<KEY>",//1 "<KEY>",//2 "5e0e1370119f20805c774dba",//3 "5e0e1370119f20805c774dba",//4 "<KEY>",//5 "<KEY>",//6 "<KEY>",//7 "<KEY>",//8 "<KEY>",//9 "<KEY>",//10 "<KEY>",//11 "<KEY>",//12 "<KEY>",//13 "<KEY>",//14 "<KEY>",//15 "<KEY>",//16 "<KEY>",//17 "5e1a3335fb289204edb2490b",//18 "5e1a3348fb289204edb2490d",//19 "5e1a335ffb289204edb2490f",//20 "5e1a336bfb289204edb24911",//21 "5<KEY>",//22 "5e0e1495119f20805c774dc9",//23 "5e0e14a7119f20805c774dca",//24 "5e0<KEY>",//25 "5e0e14e4119f20805c774dcc",//26 "5e0e259b3d05532a38036794" //27 override }; string sos_res_ref[]={ "indexIncreaser", "Suspend",//1 "WaitAlarm",//2 "GoCharge",//3 "AbortGoHome",//4 "Wait",//5 "AbortSuspend"//6 }; int findres_enum(string sos_res) { int o = 99; int mx = sizeof(sos_res_ref)/sizeof(sos_res_ref[0]); for(int x = 0; x < mx;x++) { if(sos_res_ref[x]==sos_res) { o = x; break; } } return 0; } void callstate(string str) { if(str == "SUSPEND" || str == "MANUAL"){ before_state = cur_state; } cur_state = str; // cout<<"BS:"<<before_state<<endl; // cout<<"S:"<<cur_state<<endl; atlas80evo_msgs::SetFSMState srvcall; srvcall.request.state = str.c_str(); stateClient.call(srvcall); } void process_mem_usage(double& vm_usage, double& resident_set) { vm_usage = 0.0; resident_set = 0.0; // the two fields we want unsigned long vsize; long rss; { std::string ignore; std::ifstream ifs("/proc/self/stat", std::ios_base::in); ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> vsize >> rss; } long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages vm_usage = vsize / 1024.0; resident_set = rss * page_size_kb; } void process_cpu_usage(double& cpu) { cpu = 0.0; { std::string ignore; std::ifstream ifs("/proc/loadavg", std::ios_base::in); ifs >> cpu >> ignore >> ignore >> ignore >> ignore; } cpu = cpu*100/6.0; } void soswait() { Duration diff_w=Time::now()-wait_t; if(diff_w.toSec() > 5) { wait_t = Time::now(); wait = true; } if(wait) { sr_break_pub.publish(sr_break); cout<<"Waiting 5s..........."<<endl; wait = false; } } void soswaitalarm() { Duration diff_wa=Time::now()-waita_t; if(diff_wa.toSec() > 5) { waita_t = Time::now(); waita = true; srv.request.path2file = "/home/endstruct2/catkin_ws/src/atlas80evo/sounds/pleasemove.wav"; srv.request.channel = 1; srv.request.volume = 1.0; srv.request.loop = -1; srv.request.interval = 0; playsound.call(srv); } if(waita) { sr_break_pub.publish(sr_break); cout<<"Waiting and Alarm 5s....."<<endl; sr_break_pub.publish(sr_break); srv.request.path2file = "/home/endstruct2/catkin_ws/src/atlas80evo/sounds/siren_beeping.ogg"; srv.request.channel = 1; srv.request.volume = 1.0; srv.request.loop = -1; srv.request.interval = 0; playsound.call(srv); waita = false; } } void publish_diagnostic() { DynamicJsonBuffer jsonWriteBuffer; JsonObject& root = jsonWriteBuffer.createObject(); // cout<<"in"<<endl; success output:in root["agv_ID"]= AGV_ID; // cout<<root["agv_ID"]<<endl; success output:1 JsonObject& ldrObj = root.createNestedObject("ldr"); ldrObj["2df"]= ldr_2df; // cout<<ldrObj["2df"]<<endl; success output:0 ldrObj["2dr"]= ldr_2dr; // cout<<ldrObj["2dr"]<<endl; success output:0 ldrObj["3d"]= ldr_3d; // cout<<ldrObj["3d"]<<endl; success output:0 root["batt"]= lowbatt; //cout<<root["batt"]<<endl; success output:"" JsonObject& motObj = root.createNestedObject("mot"); motObj["l"]=mot_l; // cout<<motObj["l"]<<endl; success output:"" motObj["r"]=mot_r; // cout<<motObj["r"]<<endl; success output:"" root["cam"]= cam; // cout<<root["cam"]<<endl; success output:0 root["cpu"]= cpu; // cout<<root["cpu"]<<endl; success output:7.8333 root["ram"]= ram; // cout<<root["ram"]<<endl; success output:335148:11044 root["llc"]= llc; // cout<<root["llc"]<<endl; success output:0 root["arm"]= arm; // cout<<root["arm"]<<endl; success output:0 root["obu"]= obu; // cout<<root["arm"]<<endl; success output:0 root["esw"]= esw; // cout<<root["arm"]<<endl; success output:0 root["imu"]= imu; // cout<<root["arm"]<<endl; success output:0 root["tray"]= tray; // cout<<root["arm"]<<endl; success output:0 root["tcam"]= tcam; // cout<<root["obu"]<<endl; success output:0 JsonObject& encObj = root.createNestedObject("enc"); encObj["l"]=enc_l; // cout<<encObj["l"]<<endl; success output:" " encObj["r"]=enc_r; // cout<<encObj["r"]<<endl; success output:" " string tmpstr; root.printTo(tmpstr); // cout<<tmpstr<<endl; success //output: {"agv_ID":"1","ldr":{"2df":"0","2dr":"0","3d":"0"}, // "batt":"","mot":{"l":"","r":""},"cam":"0", // "cpu":"3.33333","ram":"335148:10836","llc":"0", // "arm":"0","obu":"0","enc":{"l":"","r":""}} String strt; strt.data = tmpstr; //cout<<strt<<endl; //success // output: data: {"agv_ID":"1","ldr":{"2df":"0","2dr":"0","3d":"0"}, // "batt":"","mot":{"l":"","r":""},"cam":"0", // "cpu":"2.33333","ram":"335152:10956","llc":"0", // "arm":"0","obu":"0","enc":{"l":"","r":""}} diag_pub.publish(strt); } void gotocharge() { DynamicJsonBuffer navcBufferNav; JsonObject& cnobj = navcBufferNav.createObject(); cnobj["map"] = msstObj["fname"]; cnobj ["to_pt"] = "Home"; cnobj ["to_x"] = msstObj["fname"]["Home_x"]; cnobj ["to_y"] = msstObj["fname"]["Home_y"]; cnobj ["to_z"] = msstObj["fname"]["Home_z"]; cnobj ["to_w"] = msstObj["fname"]["Home_w"]; string root2; cnobj.printTo(root2); String s; s.data = root2; cout<<"Go To: Home to Charge"<<endl; nav_pub.publish(s); } //process and publish the diagnostic data to FMS when requested void sys_diag_Callback(const std_msgs::String::ConstPtr& msg) { // {"agv_ID" : "1", "cmd" : "1" } string out = msg->data.c_str(); DynamicJsonBuffer jsonBufferSysDiag; JsonObject& doc = jsonBufferSysDiag.parseObject(out); //cout<<doc["agv_ID"].as<string>()<<endl; success output:1 if(doc["agv_ID"]==AGV_ID) { //cout<<"in"<<endl; success output:in if(doc["cmd"]=="1") { publish_diagnostic(); cout<<"FMS request diagnostic..."<<endl; } } } void lidar3Callback(const sensor_msgs::PointCloud2::ConstPtr& msg) { lidar3_time = Time::now(); } void lidar2fCallback(const sensor_msgs::LaserScan::ConstPtr& scan) { lidar2f_time = Time::now(); } void lidar2rCallback(const sensor_msgs::LaserScan::ConstPtr& scan) { lidar2r_time = Time::now(); } void camCallback(const sensor_msgs::Image::ConstPtr& msg) { cam_time = Time::now(); } void obuCallback(const std_msgs::String::ConstPtr& msg) { obu_time = Time::now(); string sr_data = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferObu; JsonObject& readObj = jsonReadBufferObu.parseObject(sr_data); if(readObj["envPM25"] == NULL) { obu_temp = readObj["temperature"].as<string>(); obu_id = readObj["obu_ID"].as<string>(); } if(readObj["temperature"] == NULL) { env_temp = readObj["envTemperature"].as<string>(); humid = readObj["envHumidity"].as<string>(); rain = readObj["rainfallIntensity"].as<string>(); if(atoi(humid.c_str())>= HighHumidity) { HumidSOS = true; } if(atoi(rain.c_str())>= RainFall) { RainSOS=true; } } } //void armCallback(const std_msgs::String::ConstPtr& msg) void armCallback(const geometry_msgs::PoseStamped::ConstPtr& msg) { arm_time = Time::now(); } void tcamCallback(const std_msgs::String::ConstPtr& msg) { tcam_time = Time::now(); } void trayCallback(const std_msgs::String::ConstPtr& msg) { tray_time = Time::now(); string tr_data = msg->data.c_str(); DynamicJsonBuffer jsonReadBuffertray; JsonObject& readTRObj = jsonReadBuffertray.parseObject(tr_data); Tray1 = readTRObj["t1"].as<string>(); Tray2 = readTRObj["t2"].as<string>(); Tray3 = readTRObj["t3"].as<string>(); Tray4 = readTRObj["t4"].as<string>(); } void ObjectRecogCallback(const std_msgs::String::ConstPtr& msg) { tray_time = Time::now(); cur_obj_detected = msg->data.c_str(); } bool isOnline() { FILE *output; if(!(output = popen("/sbin/route -n | grep -c '^0\\.0\\.0\\.0'","r"))) { return 1; } unsigned int i; int x = fscanf(output,"%u",&i); if(i==0) { OfflineSOS = true; //cout<<"offline"<<endl; } else if(i==1) { OfflineSOS = false; //cout<<"online"<<endl; } pclose(output); return 1; } void sos_trigger_response(int res) { switch(res) { case 1://Suspend { suspend = true; cout<<"SOS Triggered: Suspend"<<endl; break; } case 2://Wait and alarm { soswaitalarm(); cout<<"SOS Triggered: Wait Alarm"<<endl; break; } case 3://Go To Charge (AGV only) { gotocharge(); cout<<"SOS Triggered: Go to charge"<<endl; break; } case 4://Abort Mission and go to Charge { cout<<"SOS Triggered: Abort! Cancel All go to Home"<<endl; gotocharge(); msstObj = 0;//clear mission break; } case 5: { soswait(); cout<<"SOS Triggered: Wait"<<endl; break; } case 6: { soswait(); cout<<"SOS Triggered: Abort and Suspend"<<endl; suspend = true; break; } } //After trigger response, reset the error trigger PickError = false; DropError = false; PickFail = false; DropFail = false; juncfound = false; NoTableError=false; NoChargerError=false; HumidSOS = false; RainSOS = false; OfflineSOS = false; NoExit = false; } void sos_trigger_response_str(string res) { sos_trigger_response(findres_enum(res)); } //apply response accordingly void sos_response(int sos_ID) { if(STATE != "ERROR" && cur_state != "ERROR") { callstate("ERROR"); } switch(sos_ID) { case 1://SOS:Cam, Response: Suspend(1) { sos_trigger_response(1); break; } case 2://SOS:Lidar3D, Response: Suspend(1) { sos_trigger_response(1); break; } case 3://SOS:Lidar2DF, Response: Suspend(1) { sos_trigger_response(1); break; } case 4://SOS:Lidar2DR, Response: Suspend(1) { sos_trigger_response(1); break; } case 5://SOS:LLC, Response: Suspend(1) { sos_trigger_response(1); break; } case 6://SOS:OBU, Response: Suspend(1) { sos_trigger_response(1); break; } case 7://SOS:Arm, Response: Suspend(1) { sos_trigger_response(1); break; } case 8://SOS:Imu, Response: Suspend(1) { sos_trigger_response(1); break; } case 9://SOS:Tray, Response: Suspend(1) { sos_trigger_response(1); break; } case 10://SOS:tcam, Response: Suspend(1) { sos_trigger_response(1); break; } case 11://SOS:offline, Response: Suspend(1) { sos_trigger_response(1); break; } case 12://SOS:short, Response: WaitAlarm(4) { sos_trigger_response(4); break; } case 13://SOS:long, Response: Suspend(1) { sos_trigger_response(1); break; } case 14://SOS:rain, Response: Suspend(1) { sos_trigger_response(1); break; } case 15://SOS:humidity, Response: AbortGoHome(3) { sos_trigger_response(3); break; } case 16://SOS:eswitch, Response: AbortSuspend(6) { sos_trigger_response(4); break; } case 17://SOS:derr, Response: Suspend(1) { sos_trigger_response(1); break; } case 18://SOS:perr, Response: Suspend(1) { sos_trigger_response(1); break; } case 19://SOS:dfail, Response: (1) { sos_trigger_response(1); break; } case 20://SOS:pfail, Response: Suspend(1) { sos_trigger_response(1); break; } case 21://SOS:junc, Response: Suspend(1) { sos_trigger_response(1); break; } case 22://SOS:notable, Response: Suspend(1) { sos_trigger_response(1); break; } case 23://SOS:no charger, Response: Suspend(1) { sos_trigger_response(1); break; } case 24://SOS:noexit, Response: Suspend(1) { sos_trigger_response(1); break; } case 25://SOS:moveerr, Response: Suspend(1) { sos_trigger_response(1); break; } case 26://SOS:lowbatt, Response: Gocharge(2) { sos_trigger_response(2); break; } } } void sos_notify(string err_id) { DynamicJsonBuffer jsonSosWriteBuffer; JsonObject& rosos = jsonSosWriteBuffer.createObject(); rosos["agv_ID"]= AGV_ID; JsonArray& arr = rosos.createNestedArray("sos_ID"); string ID=""; if(err_id != "0")//if sos trigger coming from FMS { ID = err_id; arr.add(ID); } else { for(std::vector<string>::size_type i = 0; i != sosID.size(); i++) { ID = sosID[i]; arr.add(ID); //sos_response(sosID_enum[i]); //cout<<i<<":"<<sosID_enum[i]<<","<<sos_ref[i]<<","<<ID<<endl; } //cout<<endl; } //------------Shoot to FMS for NOTIFICATION-------------- string tmpstr; rosos.printTo(tmpstr); String strt; strt.data = tmpstr; sos_pub.publish(strt); sosID.clear(); sosID_enum.clear(); error = false; } //check have exit or not before exit charging house bool findExit() { return true; } void generic_check() { String sysled; sysled.data = "1"; sysled_pub.publish(sysled); //----------------------GENERIC REPEAT CHECK--------------------------- //check online isOnline(); //check junction // JsonArray& msjunc = msstObj["junc"]; // for(int x = 0; x<msjunc.size();x++) // { // string sx = msjunc [x]["x"].as<string>(); // float px = atof(sx.c_str()); // string sy = msjunc [x]["y"].as<string>(); // float py = atof(sy.c_str()); // float djx = atof(ptsX.c_str())-px; // float djy = atof(ptsY.c_str())-py; // float distjxy = sqrt(pow(djx,2)+pow(djy,2)); // if(distjxy<junc_offset) // { // suspend = true; // cout<<"Suspended on Junction"<<endl; // juncfound = true; // } // } // //check pickdrop region string lt = msstptxy_ref[ms_cnt]["arm"]["cmd"].as<string>(); string first_four = lt.substr(0, 4); // if(msstptxy_ref.as<string>() != "") // cout <<"AMCL_X:"<< ptsX<<endl; // cout <<"AMCL_Y:"<< ptsY<<endl; // cout <<"TargetPoint_X:"<< ms_x<<endl; // cout <<"TargetPoint_Y:"<< ms_y<<endl; // if(first_four == "pick" || first_four == "drop" || lt == "gohome") // { float dx = atof(ptsX.c_str())-atof(ms_x.c_str()); float dy = atof(ptsY.c_str())-atof(ms_y.c_str()); float distxy = sqrt(pow(dx,2)+pow(dy,2)); float dx_1 = atof(ptsX.c_str())-atof(ms_x_1.c_str()); float dy_1 = atof(ptsY.c_str())-atof(ms_y_1.c_str()); float distxy_1 = sqrt(pow(dx_1,2)+pow(dy_1,2)); // cout<< "Diff_CMsquare:"<<distxy<<endl; String m; if(distxy<junc_offset || distxy_1<junc_offset) { //cout<<"Entering PickDrop Region..."<<endl; m.data = "pickdrop"; reg_pub.publish(m); } else { m.data = "normal"; reg_pub.publish(m); } // } //check charging condition if(charge == "1" && found_charger==true)//if in charging mode { if(atof(batt.c_str()) > max_charge)//check current battery { charge = "0"; //go out of charger house if(STATE != "LEAVING" && cur_state != "LEAVING") { callstate("LEAVING"); } atlas80evo_msgs::SetONOFF srvco; if(findExit() == true) { srvco.request.data = true; findoutchargerClient.call(srvco); found_charger=false; cout<<"Go out of chargin house..."<<endl; }else { NoExit = true; } } } //Execution of suspend and Resume if (suspend) { if(STATE != "SUSPEND" && cur_state != "SUSPEND") { callstate("SUSPEND"); } sr_break_pub.publish(sr_break); sr_led = 1; SR = "1";//FMS SR status //cout << "Suspend -- Suspend -- Suspend -- Suspend --Suspend "<<Time::now()<< endl; sus_pub.publish(SR); } else { // if(cur_state != before_state) // { // callstate(before_state); // } sr_led = 0; SR = "0";//FMS SR status sus_pub.publish(SR); //cout << "Move -- Move -- Move -- Move -- Move -- Move -- Move -- Move " << endl; } } void sos_check() { //-------------------------------Diagnostic Error SOS Publish------------ //check ram double vm, rss; process_mem_usage(vm, rss); ostringstream ss,sw; ss << rss; sw << vm; ram = sw.str() + ":" + ss.str(); //check cpu double cu; process_cpu_usage(cu); ostringstream cp; cp << cu; cpu = cp.str(); // //1check camera (1)------------------------OK // Duration diff_c=Time::now()-cam_time; // if(diff_c.toSec() > 5) // { // cam = "0";error = true; // sosID.push_back(sos_ref[1]); // sosID_enum.push_back(1); // cout<<"SOS!: Camera Error"<<endl; // } // else // { // cam = "1"; // } // //2check lidar3d (2) // Duration diffl3=Time::now()-lidar3_time; // if(diffl3.toSec() > 5) // { // ldr_3d = "0";error = true; // sosID.push_back(sos_ref[2]); // sosID_enum.push_back(2); // cout<<"SOS!: Lidar3D Error"<<endl; // } // else // { // ldr_3d = "1"; // } // //3check lidar2d front (3) // Duration diffl2f=Time::now()-lidar2f_time; // if(diffl2f.toSec() > 5) // { // ldr_2df = "0";error = true; // sosID.push_back(sos_ref[3]); // sosID_enum.push_back(3); // cout<<"SOS!: Lidar2D Front Error"<<endl; // } // else // { // ldr_2df = "1"; // } // //4check lidar2d rear (4) // Duration diffl2r=Time::now()-lidar2r_time; // if(diffl2r.toSec() > 5) // { // ldr_2dr = "0";error = true; // sosID.push_back(sos_ref[4]); // sosID_enum.push_back(4); // cout<<"SOS!: Lidar2D Rear Error"<<endl; // } // else // { // ldr_2dr = "1"; // } // //5check llc (5) // Duration diff=Time::now()-llc_time; // if(diff.toSec() > 5) // { // llc = "0";error = true; // sosID.push_back(sos_ref[5]); // sosID_enum.push_back(5); // cout<<"SOS!: Low Level Controller Error"<<endl; // } // else // { // llc = "1"; // } // //6check obu (6) // Duration diffo=Time::now()-obu_time; // if(diffo.toSec() > 5) // { // obu = "0";error = true; // sosID.push_back(sos_ref[6]); // sosID_enum.push_back(6); // cout<<"SOS!: OBU Error"<<endl; // } // else // { // obu= "1"; // } // //7check arm (7) // Duration diffar=Time::now()-arm_time; // if(diffar.toSec() > 5) // { // arm = "0";error = true; // sosID.push_back(sos_ref[7]); // sosID_enum.push_back(7); // cout<<"SOS!: Arm Error"<<endl; // } // else // { // arm= "1"; // } // //8check imu (8) // Duration diffimu=Time::now()-imu_time; // if(diffimu.toSec() > 5) // { // imu = "0";error = true; // sosID.push_back(sos_ref[8]); // sosID_enum.push_back(8); // cout<<"SOS!: IMU Error"<<endl; // } // else // { // imu = "1"; // } // //9check tray (9) // Duration difftray=Time::now()-tray_time; // if(difftray.toSec() > 5) // { // tray = "0";error = true; // sosID.push_back(sos_ref[9]); // sosID_enum.push_back(9); // cout<<"SOS!: Tray Sensor Error"<<endl; // } // else // { // tray = "1"; // } // //10check tower camera (10) // Duration difftcam=Time::now()-tcam_time; // if(difftcam.toSec() > 5) // { // tcam = "0";error = true; // sosID.push_back(sos_ref[10]); // sosID_enum.push_back(10); // cout<<"SOS!: Tower Camera Error"<<endl; // } // else // { // tcam = "1"; // } // //-------------------------------operation Error SOS only------------ // //11check offline (11) if(OfflineSOS) { error = true; sosID.push_back(sos_ref[11]); sosID_enum.push_back(11); ROS_INFO("SOS!: Offline Error"); } // //12check obstacle_short (12) // Duration diffobs=Time::now()-obs_t; // if(diffobs.toSec() > 5)//timeout if no obstacle detected in 5s // { // stopobs=false; // } // else//if detected under 5s. keep true // { // stopobs=true; // } // if(stopobs)//while true // { // Duration durofobs=Time::now()-obs_t; // if(durofobs.toSec() > 2 && durofobs.toSec() <= 30) // { //if obstacle keep on detected between 5s to 30s // Duration alertobs=Time::now()-alert_t; // if(alertobs.toSec() > 5)//shoot alert every 5s only // { // //12check obstacle_short (12) // error = true; // sosID.push_back(sos_ref[12]); // sosID_enum.push_back(12); // alert_t = Time::now(); // cout<<"SOS!: Obstacle Short Error"<<endl; // } // } // else if(durofobs.toSec() > 30)//if occure more than 30s // { //if obstacle keep on detected more 30s // //13check obstacle_long (13) // error = true; // sosID.push_back(sos_ref[13]); // sosID_enum.push_back(13); // cout<<"SOS!: Obstacle Long Error"<<endl; // } // } // //14check rain (14) // if(HumidSOS) // { // error = true; // sosID.push_back(sos_ref[14]); // sosID_enum.push_back(14); // cout<<"SOS!: Rain Error"<<endl; // } // //15high humidity (15) // if(RainSOS) // { // error = true; // sosID.push_back(sos_ref[15]); // sosID_enum.push_back(15); // cout<<"SOS!: Humidity Error"<<endl; // } // //16check emergency button (16) if(esw == "0") { error = true; sosID.push_back(sos_ref[16]); sosID_enum.push_back(16); ROS_INFO("SOS!: Emergency Button Error"); } // //17container_perr (17) // if(PickError) // { // error = true; // sosID.push_back(sos_ref[17]); // sosID_enum.push_back(17); // cout<<"SOS!: Container Pick Error"<<endl; // } // //18container_derr (18) // if(DropError) // { // error = true; // sosID.push_back(sos_ref[18]); // sosID_enum.push_back(18); // cout<<"SOS!: Container Drop Error"<<endl; // } // //19container_dfail(19) // if(DropFail) // { // error = true; // sosID.push_back(sos_ref[19]); // sosID_enum.push_back(19); // cout<<"SOS!: Container Drop Fail"<<endl; // } // //20container_pfail (20) // if(PickFail) // { // error = true; // sosID.push_back(sos_ref[20]); // sosID_enum.push_back(20); // cout<<"SOS!: Container Pick Fail"<<endl; // } // //21junction (21) // if(juncfound) // { // error = true; // sosID.push_back(sos_ref[21]); // sosID_enum.push_back(21); // cout<<"SOS!: Junction Error"<<endl; // } // //22no_table (22) // if(NoTableError) // { // error = true; // sosID.push_back(sos_ref[22]); // sosID_enum.push_back(22); // cout<<"SOS!: No Table Error"<<endl; // } // //23no_charger (23) // if(NoChargerError) // { // error = true; // sosID.push_back(sos_ref[23]); // sosID_enum.push_back(23); // cout<<"SOS!: No Charger Error"<<endl; // } // //24no_exit (24) // if(NoExit) // { // error = true; // sosID.push_back(sos_ref[24]); // sosID_enum.push_back(24); // cout<<"SOS!: No Exit Error"<<endl; // } // //25move_error (25) // if(abs(distENC - distPXY) > MoveSOS_XYtoENC_Err) // { // error = true; // sosID.push_back(sos_ref[25]); // sosID_enum.push_back(25); // cout<<"SOS!: Move Error"<<endl; // } // //26low battery (26) if(lowbatt=="0") { error = true; sosID.push_back(sos_ref[26]); sosID_enum.push_back(26); ROS_INFO("SOS!: Low Battery"); } //SOS RESPONSE AND NOTIFICATION if(error)//reset { sos_notify("0"); publish_diagnostic(); } } //process and publish the health data to FMS periodically //including all Suspend Resume stat void agv_health_pub(const std_msgs::String::ConstPtr& msg) { //get health data from here and there llc_time = Time::now(); //publish it string sr_data = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferHealth; DynamicJsonBuffer jsonWriteBufferHealth; JsonObject& readObj = jsonReadBufferHealth.parseObject(sr_data); if(readObj.success()) { // cout<<readObj<<endl; success output: ___ JsonObject& root = jsonWriteBufferHealth.createObject(); root["agv_ID"] = AGV_ID; // cout<<root<<endl; success output: {"agv_ID":"1"} string tmpRenc = readObj["ENC?"][0]; string tmpLenc = readObj["ENC?"][2]; float encR = atof(tmpRenc.c_str()); float encL = atof(tmpLenc.c_str()); distENC = sqrt(pow(encL-last_encL,2)+pow(encR-last_encR,2)); last_encR = encR; last_encL = encL; string motorX = readObj["MOV?"][0]; string motorZ = readObj["MOV?"][1]; if(tmpRenc != ""){ enc_r = "1"; } else { enc_r = "0"; } if(tmpLenc != ""){ enc_l = "1"; } else { enc_l = "0"; } string tmpRT = readObj["STA?"][1]; string tmpLT = readObj["STA?"][6]; if(tmpRT != ""){ mot_r = "1"; } else { mot_r = "0"; } if(tmpLT!= ""){ mot_l = "1"; } else { mot_l = "0"; } string rawBatt = readObj["STA?"][0]; batt = rawBatt; batt_int = atoi(batt.c_str()); // cout<<batt_int<<endl; float bm = (float(batt_int-41))/15*100; // cout<<bm<<endl; ostringstream btw; btw << fixed<<setprecision(1)<<bm; root["batt"] = btw.str(); string mmb = btw.str(); if(atof(mmb.c_str()) < low_charge) { charge = "1"; lowbatt = "0"; } else { lowbatt = "1"; } // Duration diff_sus=Time::now()-sus_t; // if(diff_sus.toSec() > 1 && readObj["DI?"][3] == 0 && readObj["DI?"][3] == SR_SW) // { // SR_SW = readObj["DI?"][3]; // suspend = !suspend; // sus_t = Time::now(); // if(cur_state == "SUSPEND") // { // callstate(before_state); // } // } JsonObject& msObj = root.createNestedObject("ms"); msObj["ms_ID"] = ms_id; msObj["sched_ID"] = sched_id; msObj["ss_id"] = ss_id; ostringstream ss; ss << ms_cnt+1; msObj["act_Seq"] = ms_seq; msObj["point"] = ms_pt; msObj["act"] = ms_act; root["charge"]=charge; root["SR"]=SR; JsonObject& msObj2 = root.createNestedObject("loc"); msObj2["lat"]=cur_lat; msObj2["long"]=cur_long; JsonObject& msObj3 = root.createNestedObject("pnt"); msObj3["x"]=ptsX; msObj3["y"]=ptsY; JsonObject& msObj4 = root.createNestedObject("spd"); msObj4["x"]=motorX; msObj4["z"]=motorZ; JsonObject& msObj5 = root.createNestedObject("tmp"); msObj5["l"]=tmpLT; msObj5["r"]=tmpRT; string tmpobu; root.printTo(tmpobu); String stobu; stobu.data = tmpobu; JsonObject& msObj7 = root.createNestedObject("obu"); msObj7["env_temp"]=env_temp; msObj7["humid"]=humid; msObj7["obu_id"]=obu_id; msObj7["obu_temp"]=obu_temp; msObj7["rainfallintensity"]=rain; string tmpstr; root.printTo(tmpstr); String strt; strt.data = tmpstr; Duration diff_c=Time::now()-health_t; if(diff_c.toSec() > 1) { //cout<<strt<<endl; health_pub.publish(strt); to_obu_pub.publish(stobu); health_t = Time::now(); /* cout<<"cpu :"<<cpu<<"%"<<endl;*/ } } } //entering Teleop void TeleOPCallback(const std_msgs::String::ConstPtr &msg) { string manData = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferMvMan; JsonObject& readObj = jsonReadBufferMvMan.parseObject(manData); // cout<<readObj["agv_ID"]<<endl; success output:1 if(readObj["agv_ID"]== AGV_ID) { if(readObj["status"]== "0") { if(STATE != before_state && cur_state != before_state) { callstate(before_state); } // srv.request.path2file = "/home/endstruct2/catkin_ws/src/atlas80evo/sounds/stand.wav"; // srv.request.channel = 1; // srv.request.volume = 1.0; // srv.request.loop = -1; // srv.request.interval = 0; // playsound.call(srv); } else if(readObj["status"]== "1") { if(STATE != "MANUAL" && cur_state != "MANUAL") { callstate("MANUAL"); } // srv.request.path2file = "/home/endstruct2/catkin_ws/src/atlas80evo/sounds/manual.wav"; // srv.request.channel = 1; // srv.request.volume = 1.0; // srv.request.loop = -1; // srv.request.interval = 0; // playsound.call(srv); } } } //Handlin TeleOP of AGV void mvSysCallback(const std_msgs::String::ConstPtr &msg) { //move robot using fms UI from server //{"agv_ID" : "1","x": "0.1","z": "0.1","cmd": "0/1"} //cmd 1 is start, 0 is stop string mvData = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferMvSys; JsonObject& readObj = jsonReadBufferMvSys.parseObject(mvData); // cout<<readObj["agv_ID"]<<endl; success output:1 if(readObj["agv_ID"]== AGV_ID) { // cout<<"in"<<endl; success output:in if(readObj["cmd"]=="1") { // cout<<"in"<<endl; success when cmd is 1 output:in if(esw != "0") { geometry_msgs::Twist move; move.linear.x = float(readObj["x"]); move.linear.y = move.linear.z = 0.0; move.angular.x = move.angular.y = 0.0; move.angular.z = float(readObj["z"]); cout<<move<<endl; mv_pub.publish(move); } } } } void nanocallback(const std_msgs::String::ConstPtr& msg) { string srt_data = msg->data.c_str(); DynamicJsonBuffer jsonReadBuffernano; JsonObject& readnano = jsonReadBuffernano.parseObject(srt_data); //emergency switch ostringstream sesw; sesw << readnano["DMI?"][4]; esw = sesw.str(); Duration diff_sus=Time::now()-sus_t; if(diff_sus.toSec() > 1 && readnano["DMI?"][5] == 0 && readnano["DMI?"][5] == SR_SW) { string srt_data = msg->data.c_str(); DynamicJsonBuffer jsonReadBuffernano; JsonObject& readnano = jsonReadBuffernano.parseObject(srt_data); Duration diff_sus=Time::now()-sus_t; if(diff_sus.toSec() > 1 && readnano["DMI?"][5] == 0 && readnano["DMI?"][5] == SR_SW) { SR_SW = readnano["DMI?"][5]; suspend = !suspend; sus_t = Time::now(); if(cur_state == "SUSPEND") { String tz; tz.data = "resume"; armxtra_pub.publish(tz); if(cur_arm != "") { String armove; armove.data = cur_arm; arm_pub.publish(armove); } callstate(before_state); } else { String ta; ta.data = "suspend"; armxtra_pub.publish(ta); } } // SR_SW = readnano["DMI?"][3]; // suspend = !suspend; // sus_t = Time::now(); // if(cur_state == "SUSPEND") // { // callstate(before_state); // String tz; // tz.data = "resume"; // armxtra_pub.publish(tz); // Duration(1).sleep(); // if(cur_arm != "") // { // String armove; // armove.data = cur_arm; // arm_pub.publish(armove); // } // } // else // { // String ta; // ta.data = "suspend"; // armxtra_pub.publish(ta); // } } } void gpsCallback(const sensor_msgs::NavSatFixConstPtr& msg) { char lt[30]; char lg[30]; sprintf(lg,"%.25f",msg->longitude); sprintf(lt,"%.25f",msg->latitude); string xlg(lg); string xlt(lt); cur_long = xlg; cur_lat = xlt; } void ptsCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& msgAMCL){ ostringstream px,py; float pX = msgAMCL->pose.pose.position.x; float pY = msgAMCL->pose.pose.position.y; px << pX; py << pY; ptsX = px.str(); ptsY = py.str(); distPXY = sqrt(pow(pX-last_pX,2)+pow(pY-last_pY,2)); last_pX = pX; last_pY = pY; } void sys_sos_Callback(const std_msgs::String::ConstPtr &msg){ string off = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferOff; JsonObject& readObjO = jsonReadBufferOff.parseObject(off); if (readObjO["agv_ID"]==AGV_ID)//check ID { if(readObjO["sos_ID"] == sos_ref[26])//if it is override { sos_notify(readObjO["sos_ID"]);//for notification sos_trigger_response_str(readObjO["res"]);//response } } } void sys_off_Callback(const std_msgs::String::ConstPtr &msg){ string off = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferOff; JsonObject& readObjO = jsonReadBufferOff.parseObject(off); if (readObjO["agv_ID"]==AGV_ID)//check ID { if (readObjO["status"] == "shutdown")//Check command { //call python shutdown service // std_srvs::Empty srv; // shutdownClient.call(srv); // std_srvs::Empty srvg; // armgohomeClient.call(srvg); } } } void goOutHome() { //go out of charger house atlas80evo_msgs::SetONOFF srvco; if(findExit() == true) { if(STATE != "LEAVING" && cur_state != "LEAVING") { callstate("LEAVING"); } srvco.request.data = true; findoutchargerClient.call(srvco); cout<<"Go out of chargin house (HOME)..."<<endl; }else { NoExit = true; } } void NaviFirstMission() { if(STATE != "DELIVERY" && cur_state != "DELIVERY") { callstate("DELIVERY"); } DynamicJsonBuffer navBuffer; JsonObject& obj = navBuffer.createObject(); JsonArray& msstptxy = msstObj["activity"]; msstptxy_ref = msstptxy; obj["map"] = msstObj["fname"]; ms_max = msstptxy.size(); //cout<<"Json msst"<<msstptxy<<endl; //cout<<ms_max<<endl; //success output:2 sched_id = msstObj["sched_ID"].as<string>(); ms_id = msstObj["ms_ID"].as<string>(); ss_id = msstObj["ss_id"].as<string>(); obj ["to_pt"] = msstptxy [0]["pt"].as<string>(); obj ["to_x"] = msstptxy [0]["x"].as<string>(); obj ["to_y"] = msstptxy [0]["y"].as<string>(); obj ["to_z"] = msstptxy [0]["z"].as<string>(); obj ["to_w"] = msstptxy [0]["w"].as<string>(); ms_seq = msstptxy [0]["Seq"].as<string>();; ms_pt = "home"; ms_act = "move"; ms_x_1 = ms_x; ms_y_1 = ms_y; ms_x = msstptxy [0]["x"].as<string>(); ms_y = msstptxy [0]["y"].as<string>(); string root2; obj.printTo(root2); // cout<<root2<<endl; success output:{"map":"OneNorth_1351434245", // "to_x":"4.4","to_y":"5.5"} String s; s.data = root2; nav_pub.publish(s);//go to 1st location msstptxy [0]["pt"] ms_pt = msstptxy [0]["pt"].as<string>(); cout<<"Go To: "<<obj["to_pt"]<<endl; } //start the mission from FMS web void msstCallback(const std_msgs::String::ConstPtr &msg) { if(ms_act=="done") { string Data = msg->data.c_str(); msstObj = msstobj_Buffer.parseObject(Data); // cout<<msstObj["agv_ID"]<<endl; success output:1 //cout<<msstObj<<endl; //cout<<msstObj<<endl; if(msstObj["agv_ID"]==AGV_ID) { //cout<<"in"<<endl; //cout<<msstObj["fname"]<<endl; // cout<<"in"<<endl; success output:in //goOutHome(); NaviFirstMission(); } } } //find table before do navigate to table void findPickDrop() { //cout<<"Detecting Table with camera..."<<endl; if(cur_obj_detected =="4.0")//check can see table or not { cout<<"Table Found: Calling PickDrop Point"<<endl; // cout<<"Table Found: Navigating to table."<<endl; atlas80evo_msgs::SetONOFF srvft; srvft.request.data = true; findpickdropClient.call(srvft); } else { NoTableError=true; } } void findTable() { atlas80evo_msgs::SetONOFF srvft; srvft.request.data = true; Duration(1).sleep(); findtableClient.call(srvft); cout<<"Find and align with table..."<<endl; } //Server callback when charging Navigation to Charging Dock Done bool DoneFindChargingDockCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { if(ms_act=="gohome") { String s; s.data = "{\"st\":\"0\",\"act\":\"arm\"}"; sched_pub.publish(s); } else { found_charger = true; } return true; } //will be called after AGV get out of the Charging house, then proceed with navigation bool DoneFindOutChargingDockCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { if(firstNavi) { NaviFirstMission(); } else { //publish hdl DynamicJsonBuffer navBuffer; JsonObject& nobj = navBuffer.createObject(); nobj["st"] = "0"; nobj ["act"] = "arm"; string root2; nobj.printTo(root2); String s; s.data = root2; cout<<"Charging DONE: Go to next point directly"<<s<<endl; sched_pub.publish(s); } return true; } //will be called after AGV get out of the Charging house, then proceed with navigation bool DoneFindPickupCallback(atlas80evo_msgs::SetPose2D::Request& request, atlas80evo_msgs::SetPose2D::Response& response) { found_table = true; cout<<"Called /check/pose. Waiting for service callback"<<endl; //Duration(0.5).sleep(); atlas80evo_msgs::SetPose2D srvft; srvft.request.x = request.x; srvft.request.y = request.y; srvft.request.theta = request.theta; checkposeClient.call(srvft); armparam=""; DynamicJsonBuffer paramBuffer; JsonObject& paramobj = paramBuffer.createObject(); ostringstream xx,yy,tt; xx << request.x; yy << request.y; tt << request.theta; paramobj["new_x"]=xx.str(); paramobj["new_y"]=yy.str(); paramobj["new_deg"]=tt.str(); paramobj.printTo(armparam); return true; } //Server callback when find table for arm Done bool DoneFindTableCallback(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { // found_table = true; // DynamicJsonBuffer dftBuffer; // JsonObject& dftobj = dftBuffer.createObject(); // dftobj["st"] = "0"; // dftobj ["act"] = "move"; // string root2; // dftobj.printTo(root2); // String s; // s.data = root2; // cout<<"Find Table DONE: Preceed to Action"<<endl; // sched_pub.publish(s); cout<<"Find Table DONE: Preceed to Find PickDrop Point"<<endl; findPickDrop(); return true; } //Server callback when checkpose done bool DoneCheckPoseCallback(atlas80evo_msgs::SetONOFF::Request& request, atlas80evo_msgs::SetONOFF::Response& response) { cout<<"PickDrop point OK: Proceed with PickDrop"<<endl; String param; param.data = armparam; arm_param_pub.publish(param); cout<<"Sending new parameter to Robotic arm: "<<armparam<<endl; //Duration(1).sleep(); //pickup action to arm DynamicJsonBuffer dftBuffer; JsonObject& dftobj = dftBuffer.createObject(); dftobj["st"] = "0"; dftobj ["act"] = "move"; string root2; dftobj.printTo(root2); String s; s.data = root2; cout<<"PickDrop Point Found: Updating new Arm parameter and PickDrop"<<endl; sched_pub.publish(s); // cout<<request<<endl; // if(request.data == true) // { // //do pickdrop // cout<<"PickDrop point OK: Proceed with PickDrop"<<endl; // String param; // param.data = armparam; // arm_param_pub.publish(param); // cout<<"Sending new parameter to Robotic arm: "<<armparam<<endl; // //Duration(1).sleep(); // //pickup action to arm // DynamicJsonBuffer dftBuffer; // JsonObject& dftobj = dftBuffer.createObject(); // dftobj["st"] = "0"; // dftobj ["act"] = "move"; // string root2; // dftobj.printTo(root2); // String s; // s.data = root2; // cout<<"PickDrop Point Found: Updating new Arm parameter and PickDrop"<<endl; // sched_pub.publish(s); // } // else // { // //do table align call // cout<<"PickDrop point NOK: Proceed with Table Alignment Call"<<endl; // atlas80evo_msgs::SetONOFF srvft; // srvft.request.data = true; // findtableClient.call(srvft); // } return true; } void navactCallback(const std_msgs::String::ConstPtr &msg)//mission scheduler { //cout<<"obj:"<<msstObj<<endl; // handling msg from navi or charge or arm: // { // "st":"0", // "to_y":"move/arm", // } string Data = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferNav; JsonObject& readObj = jsonReadBufferNav.parseObject(Data); DynamicJsonBuffer navBufferNav; JsonObject& nobj = navBufferNav.createObject(); JsonArray& msstptxy = msstObj["activity"]; msstptxy_ref = msstptxy; string lt=""; string first_four=""; int traynum= 0; //cout<<"in"<<endl; failure cause: success if to_x and to_y initialize according to payload if(readObj["st"]== "0")//if task done { // cout<<"in"<<endl; failure cause:success if readObj["st"] is set according to payload if (ms_cnt < ms_max) //check within mission list { // cout<<"in"<<endl; failure cause: 1<0 IS WRONG //cout<<ms_st<<endl; success output:__ if(readObj["act"]== "arm")//check type what is done: if arm is done, do move { //If in charging mode if(charge=="1") { sos_trigger_response(2); } else {//before do next move, check pick/drop success or not lt = msstptxy [ms_cnt-1]["arm"]["cmd"].as<string>(); first_four = lt.substr(0, 4); // if(first_four == "pick" || first_four == "drop") // { // string tsid = lt.substr(4, sizeof(lt)); // traynum = atoi(tsid.c_str()); // if(first_four== "pick") // { // cout<<"Checking tray AFTER pick...."<<endl; // switch(traynum) // { // case 1:{ // if(Tray1=="1") // { // cout<<"Action "<<lt<<" Failed, Tray1 is still empty"<<endl; // PickFail = true; // } // else // { // cout<<"Tray1 is occupied. Picking to Tray"<<traynum<<" success"<<endl; // } // break; // } // case 2:{ // if(Tray2=="1") // { // cout<<"Action "<<lt<<" Failed, Tray2 is still empty"<<endl; // PickFail= true; // } // else // { // cout<<"Tray2 is occupied. Picking to Tray"<<traynum<<" success"<<endl; // } // break; // } // case 3:{ // if(Tray3=="1") // { // cout<<"Action "<<lt<<" Failed, Tray3 is still empty"<<endl; // PickFail = true; // } // else // { // cout<<"Tray3 is occupied. Picking to Tray"<<traynum<<" success"<<endl; // } // break; // } // case 4:{ // if(Tray4=="1") // { // cout<<"Action "<<lt<<" Failed, Tray4 is still empty"<<endl; // PickFail = true; // } // else // { // cout<<"Tray4 is occupied. Picking to Tray"<<traynum<<" success"<<endl; // } // break; // } // } // } // else if(first_four=="drop") // { // cout<<"Checking tray AFTER drop...."<<endl; // switch(traynum) // { // case 1:{ // if(Tray1=="0") // { // cout<<"Action "<<lt<<" Failed, Tray1 is still occupied"<<endl; // DropFail = true; // } // else // { // cout<<"Tray1 is empty. Droping from Tray"<<traynum<<" success"<<endl; // } // break; // } // case 2:{ // if(Tray2=="0") // { // cout<<"Action "<<lt<<" Failed, Tray2 is still occupied"<<endl; // DropFail = true; // } // else // { // cout<<"Tray2 is empty. Droping from Tray"<<traynum<<" success"<<endl; // } // break; // } // case 3:{ // if(Tray3=="0") // { // cout<<"Action "<<lt<<" Failed, Tray3 is still occupied"<<endl; // DropFail = true; // } // else // { // cout<<"Tray3 is empty. Droping from Tray"<<traynum<<" success"<<endl; // } // break; // } // case 4:{ // if(Tray4=="0") // { // cout<<"Action "<<lt<<" Failed, Tray4 is still occupied"<<endl; // DropFail = true; // } // else // { // cout<<"Tray4 is empty. Droping from Tray"<<traynum<<" success"<<endl; // } // break; // } // } // } // } if(STATE != "DELIVERY" && cur_state != "DELIVERY") { callstate("DELIVERY"); } string mx = msstptxy [ms_cnt]["x"].as<string>(); string my = msstptxy [ms_cnt]["y"].as<string>(); if(mx!=ms_x && my != ms_y) { ms_act="move"; ms_seq = msstptxy [ms_cnt]["Seq"].as<string>(); ms_pt = msstptxy [ms_cnt]["pt"].as<string>(); ms_x_1 = ms_x; ms_y_1 = ms_y; ms_x = msstptxy [ms_cnt]["x"].as<string>(); ms_y = msstptxy [ms_cnt]["y"].as<string>(); ms_z = msstptxy [ms_cnt]["z"].as<string>(); ms_w = msstptxy [ms_cnt]["w"].as<string>(); //cout<<"in"<<endl; failure cause:__=="1" is wrong // cout<<nobj["map"]<<endl; success output:__ since msstObj output is [] nobj["map"] = msstObj["fname"]; nobj ["to_pt"] = ms_pt; nobj ["to_x"] = ms_x; nobj ["to_y"] = ms_y; nobj ["to_z"] = ms_z; nobj ["to_w"] = ms_w; string root2; nobj.printTo(root2); // cout<<root2<<endl; success output:{"map":,"to_x":"","to_y":""} String s; s.data = root2; // cout<<s; success output: data: {"map":,"to_x":"","to_y":""} cout<<"Go To: "<<nobj["to_pt"]<<endl; nav_pub.publish(s); } else { ms_act="skip move"; cout<<"Skipping Moving at same location.."<<endl; ms_seq = msstptxy [ms_cnt]["Seq"].as<string>(); ms_act = "move"; move_skip = true; } } }//if(action arm done) //Done move: do action pick/drop/wait/find_charger/suspend if(readObj["act"]== "move" || move_skip == true) { if(charge=="1")//if in charging mode do find charger { if(STATE != "CHARGING" && cur_state != "CHARGING") { callstate("CHARGING"); } if(cur_obj_detected=="2.0") { cout<<"Charger Found: Docking to charger now.."<<endl; atlas80evo_msgs::SetONOFF srvfc; srvfc.request.data = true; findchargerClient.call(srvfc);//service call to find charger } else { NoChargerError = true; cout<<"Charger Not Found"<<endl; } }//if charge == "1" else { ms_a = msstptxy [ms_cnt]["arm"].as<string>(); if(ms_a=="gohome") { ms_act="gohome"; cout<<"Entering Charger House"<<endl; //uncomment this for in charger ending // if(STATE != "CHARGING" && cur_state != "CHARGING") // { // callstate("CHARGING"); // } // atlas80evo_msgs::SetONOFF srvfc; // srvfc.request.data = true; // findchargerClient.call(srvfc);//service call to find charger ms_cnt ++; move_skip = false; //comment this for in charger ending String s; s.data = "{\"st\":\"0\",\"act\":\"arm\"}"; sched_pub.publish(s); } else if(ms_a=="wait") { ms_act="wait"; cout<<"Waiting at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; String zw; zw.data="wait"; skip_pub.publish(zw); ms_cnt ++; move_skip = false; } else if(ms_a=="suspend") { ms_act="suspend"; cout<<"Suspending at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; String zs; suspend = true; zs.data="suspend"; skip_pub.publish(zs); ms_cnt ++; move_skip = false; } else//arm action { if(STATE != "PICKDROP" && cur_state != "PICKDROP") { callstate("PICKDROP"); } //check find table or not if(found_table) { DynamicJsonBuffer meReadBuffer; JsonObject& armObj = meReadBuffer.parseObject(ms_a); lt = armObj["cmd"].as<string>(); ms_act=lt; string first_four = lt.substr(0, 4); string tsid = lt.substr(4, sizeof(lt)); traynum = atoi(tsid.c_str()); // if(first_four == "pick") // { // cout<<"Checking tray BEFORE pick...."<<endl; // switch(traynum) // { // case 1:{ // if(Tray1=="1") // { // cout<<"Pick Error:Unable to "<<lt<<", Tray1 is occupied"<<endl; // PickError = true; // } // else // { // cout<<"Tray1 is empty. Picking to Tray"<<traynum<<" at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 2:{ // if(Tray2=="1") // { // cout<<"Pick Error:Unable to "<<lt<<", Tray2 is occupied"<<endl; // PickError = true; // } // else // { // cout<<"Tray2 is empty. Picking to Tray"<<traynum<<" at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 3:{ // if(Tray3=="1") // { // cout<<"Pick Error:Unable to "<<lt<<", Tray3 is occupied"<<endl; // PickError = true; // } // else // { // cout<<"Tray3 is empty. Picking to Tray"<<traynum<<" at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 4:{ // if(Tray4=="1") // { // cout<<"Pick Error:Unable to "<<lt<<", Tray4 is occupied"<<endl; // PickError = true; // } // else // { // cout<<"Tray4 is empty. Picking to Tray"<<traynum<<" at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // } // } // else if(first_four=="drop") // { // cout<<"Checking tray BEFORE drop...."<<endl; // switch(traynum) // { // case 1:{ // if(Tray1=="0") // { // cout<<"Drop Error:Unable to "<<lt<<", Tray1 is empty"<<endl; // DropError = true; // } // else // { // cout<<"Tray1 is occupied. Droping from Tray"<<traynum<<"at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 2:{ // if(Tray2=="0") // { // cout<<"Drop Error:Unable to "<<lt<<", Tray2 is empty"<<endl; // DropError = true; // } // else // { // cout<<"Tray2 is occupied. Droping from Tray"<<traynum<<"at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 3:{ // if(Tray3=="0") // { // cout<<"Drop Error:Unable to "<<lt<<", Tray3 is empty"<<endl; // DropError = true; // } // else // { // cout<<"Tray3 is occupied. Droping from Tray"<<traynum<<"at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // case 4:{ // if(Tray4=="0") // { // cout<<"Drop Error:Unable to "<<lt<<", Tray4 is empty"<<endl; // DropError = true; // } // else // { // cout<<"Tray4 is occupied. Droping from Tray"<<traynum<<"at: "<<msstptxy [ms_cnt]["pt"].as<string>()<<endl; // } // break; // } // } // } //if(PickError==false && DropError==false)//if no error at all //{ String ss; ss.data = ms_a; // cout<<ss<<endl; success //output: data:{"agv_ID":"1","s":"2"} arm_pub.publish(ss); cur_arm = ms_a; ms_cnt ++; move_skip = false; found_table = false; //} // else // {//repeat action // String s; // s.data = "{\"st\":\"0\",\"act\":\"navi\"}"; // sched_pub.publish(s); // } } else { // findPickDrop(); if(move_skip == false) { findTable(); } else { cout<<"Delaying the next PICKDROP..."<<endl; same_loc_delay = Time::now(); String xms; xms.data = "{\"st\":\"1\",\"act\":\"bypass\"}"; sched_pub.publish(xms); } } } }//if charge NOT "1" }//if(move DONE) } else if (ms_cnt == ms_max)//reset all when mission finished { // cout<<"in"<<endl; total failure no output cout<<"ALL DONE"<<endl; cur_arm = ""; ms_cnt = 0; ms_id = ""; ms_seq = ""; ms_pt = ""; ss_id = ""; sched_id = ""; ms_act = "done"; msstObj = 0; ms_x=""; ms_y=""; ms_x_1 = ""; ms_y_1 = ""; firstNavi = true; found_table = false; if(STATE != "STANDBY" && cur_state != "STANDBY") { callstate("STANDBY"); } }//check current mission number }//Check task done else //if st == 1 { //do loop of this callback till certain amount of time Duration diff_dly=Time::now()-same_loc_delay; cout<<"Delay Time:"<<diff_dly.toSec()<<endl; if(diff_dly.toSec() > 5) { found_table = true; DynamicJsonBuffer dftBuffer; JsonObject& dftobj = dftBuffer.createObject(); dftobj["st"] = "0"; dftobj ["act"] = "move"; string root2; dftobj.printTo(root2); String s; s.data = root2; cout<<"Same Point Using Old Arm parameter and PickDrop"<<endl; sched_pub.publish(s); } else { String xm; xm.data = "{\"st\":\"1\",\"act\":\"bypass\"}"; sched_pub.publish(xm); } } } void srCallback(const std_msgs::String::ConstPtr &msg)//FMS SR { //{"agv_ID":"1", "cmd" :"1"} string Data = msg->data.c_str(); DynamicJsonBuffer jsonReadBufferSr; JsonObject& readObj = jsonReadBufferSr.parseObject(Data); cout << "FMS SR REQ" << endl; //success output:FMS SR REQ // cout<<readObj["agv_ID"]<<endl; success output: 1 if(readObj["agv_ID"]==AGV_ID) { // cout<<"in"<<endl; success output:in string text = readObj["cmd"]; if (text == "1") { //cout<<text<<endl; //success output:1 suspend = !suspend; } else if(text == "0") { suspend = !suspend; callstate(before_state); } } } void obstacleCallback(const std_msgs::String::ConstPtr &msg) { string Data = msg->data.c_str(); if(Data == "Obstacle") { if(stopobs==false) { obs_t = Time::now(); } } } void ledpub() { String strt; strt.data = sr_led; led_pub.publish(strt); } void state_Callback(const atlas80evo_msgs::FSMState &msg) { STATE = msg.state; // cout<<"--------------------------------"<<STATE<<endl; } int main(int argc, char **argv) { ros::init(argc, argv, "fms_handler"); ros::NodeHandle nh; sr_break.linear.x = sr_break.linear.y = sr_break.linear.z = 0.0; sr_break.angular.x = sr_break.angular.y = sr_break.angular.z = 0.0; //mission start (/f2a/ms/st) is listen directly by mission handler package; //arm movement data (/f2a/sys/arm) is listen directly by arm; //arm movement data (/f2a/sys/mv) is listen directly by agv; ros::Subscriber state = nh.subscribe("/fsm_node/state", 1000, state_Callback); ros::Subscriber sys_sos = nh.subscribe("/f2a/sys/sos", 1000, sys_sos_Callback); ros::Subscriber sys_off = nh.subscribe("/f2a/sys/off", 1000, sys_off_Callback); ros::Subscriber sys_diag = nh.subscribe("/f2a/sys/diag", 1000, sys_diag_Callback); ros::Subscriber healthSubs = nh.subscribe("/low_level/status", 1000, agv_health_pub); ros::Subscriber moveSubs = nh.subscribe("/f2a/sys/mv", 1000, mvSysCallback); ros::Subscriber srtSubs = nh.subscribe("/led/status", 1000, nanocallback); ros::Subscriber srSubs = nh.subscribe("/f2a/ms/sr", 1000, srCallback); ros::Subscriber msstSubs = nh.subscribe("/f2a/ms/st", 1000, msstCallback); ros::Subscriber navactSubs = nh.subscribe("/a2a/ms/hdl", 1000, navactCallback); ros::Subscriber gpsSubs = nh.subscribe("/vectornav/GPS", 5, gpsCallback); ros::Subscriber traySubs = nh.subscribe("/a2f/arm/tray", 1000, trayCallback); ros::Subscriber tcamSubs = nh.subscribe("/a2a/tcam/raw", 1000, tcamCallback); ros::Subscriber obstacleSubs = nh.subscribe("obstacle_stop/debug", 1000, obstacleCallback); ros::Subscriber lidar3Subs = nh.subscribe("/os1_cloud_node/points", 1000, lidar3Callback);//listen 3D lidar ros::Subscriber lidar2fSubs = nh.subscribe("/cloud1", 1000, lidar2fCallback);//listen 2D Lidar f ros::Subscriber lidar2rSubs = nh.subscribe("/cloud2", 1000, lidar2rCallback);//listen 2D Lidar r ros::Subscriber camSubs = nh.subscribe("/camera/color/image_raw", 1000, camCallback);//listen camera ros::Subscriber obuSubs = nh.subscribe("/a2a/obu", 1000, obuCallback);//listen obu ros::Subscriber armSubs = nh.subscribe("/a2a/arm/live", 1000, armCallback);//listen arm location ros::Subscriber Manstart = nh.subscribe("/f2a/sys/man", 1000, TeleOPCallback); //Teleopstart ros::Subscriber objrstart = nh.subscribe("/a2a/object/detection", 1000, ObjectRecogCallback); //Status from tower object detection ros::Subscriber ptsSubs = nh.subscribe("/amcl_pose", 1000, ptsCallback); shutdownClient = nh.serviceClient<std_srvs::Empty>("/shutdown"); findpickdropClient = nh.serviceClient<atlas80evo_msgs::SetONOFF>("/find_pickdrop"); findchargerClient = nh.serviceClient<atlas80evo_msgs::SetONOFF>("/charging/call"); playsound = nh.serviceClient<atlas80evo_msgs::SetSound>("/sound/call"); findoutchargerClient = nh.serviceClient<atlas80evo_msgs::SetONOFF>("/leaving/call"); stateClient = nh.serviceClient<atlas80evo_msgs::SetFSMState>("/fsm_node/set_state"); findtableClient = nh.serviceClient<atlas80evo_msgs::SetONOFF>("/aligning/call"); checkposeClient = nh.serviceClient<atlas80evo_msgs::SetPose2D>("/check/pose"); ServiceServer donecheckpose_serv = nh.advertiseService("/check/reply", DoneCheckPoseCallback); ServiceServer donepickdrop_serv = nh.advertiseService("/find_pickdrop/goal", DoneFindPickupCallback); ServiceServer donecharger_serv = nh.advertiseService("charging/done", DoneFindChargingDockCallback); ServiceServer doneoutcharger_serv = nh.advertiseService("/leaving/done", DoneFindOutChargingDockCallback); ServiceServer donetable_serv = nh.advertiseService("/aligning/done", DoneFindTableCallback); reg_pub = nh.advertise<String>("/pd_state", 1000); sched_pub = nh.advertise<String>("/a2a/ms/hdl", 1000); sos_pub = nh.advertise<String>("/a2f/sys/sos", 1000); skip_pub = nh.advertise<String>("/a2a/ms/skip", 1000); arm_pub = nh.advertise<String>("/f2a/arm/mv", 1000); nav_pub = nh.advertise<String>("/a2a/nav", 1000); led_pub = nh.advertise<String>("/a2a/led", 1000); health_pub = nh.advertise<String>("/a2f/ms/ht", 1000); diag_pub = nh.advertise<String>("/a2f/sys/diag", 1000); arm_param_pub = nh.advertise<String>("/a2a/agv/loc", 1000); to_obu_pub = nh.advertise<String>("/a2a/to_obu", 1000); sr_break_pub = nh.advertise<geometry_msgs::Twist>("/twist_cmd_mux/input/suspend", 10); mv_pub = nh.advertise<geometry_msgs::Twist>("/twist_cmd_mux/input/webop", 1000); sus_pub = nh.advertise<String>("/a2a/led",1000); armxtra_pub = nh.advertise<String>("/a2a/arm/xtra",10); sysled_pub = nh.advertise<String>("/a2a/sysled",10); // srv.request.path2file = "/home/endstruct2/catkin_ws/src/atlas80evo/sounds/stand.wav"; // srv.request.channel = 1; // srv.request.volume = 1.0; // srv.request.loop = -1; // srv.request.interval = 0; // playsound.call(srv); Rate loop_rate(20); cout << ver << endl; health_t = Time::now(); wait_t = Time::now(); sus_t = Time::now(); waita_t = Time::now(); alert_t = Time::now(); cam_time = Time::now(); same_loc_delay = Time::now(); while(ok()) { sos_check(); generic_check(); spinOnce(); loop_rate.sleep(); } return 0; }
549ce7ba5ae7e2339d08b721593671293012c655
[ "C++" ]
1
C++
melloremell/atlas
05dcefd5834b7d23e6e21b697d753127b64f1901
c786c0750ff7a3ba1a33520df92edb6d1386468e
refs/heads/master
<repo_name>pro-panesar/weather-panesar-api<file_sep>/src/main/java/code/models/CityInfo.java package code.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Data public class CityInfo { private String cityname; }<file_sep>/README.md # weather-api Send POST request to weather-panesar-api.herokuapp.com/weather/current to get weather info ### must include { "cityname": "your city name" } in body
8f2aa7fe4b9919b1e142e52d9899b233836b77cf
[ "Markdown", "Java" ]
2
Java
pro-panesar/weather-panesar-api
bbdf2f73227298604cfc297d1f0794b5b5d77535
4f42bdd1d40ab85948a88578623597106f4dec09
refs/heads/master
<repo_name>yasaswiduvvuru/assignment2<file_sep>/Assignment 2 CS1520/validate.js function validateMath() { var z = document.forms["arr"]["arithanswer"].value; if (z == ""){ alert("An empty answer is futile!"); return false; } if (z == "5"){ alert("Correct!"); } else { alert("Incorrect! Must MATH HARDER!!!"); } } function validateBook() { var b = document.forms["book"]["bookname"].value; if (b == ""){ alert("An empty answer is futile!"); return false; } if (b.toUpperCase() == "HAT"){ alert("Correct!"); } else { alert("Incorrect! DOGS > CATS!!!"); } }
43f15ecb4e92c22d2c19871db6cd028b20596f4c
[ "JavaScript" ]
1
JavaScript
yasaswiduvvuru/assignment2
67d5612e3fe94c249af744d46d10e77b319514ed
b284df21e169f8dca6e28b59a2a310c7b0e60b84
refs/heads/master
<file_sep><?php class PluginThemeVersion{ private $data = null; private $has_mysql = false; private $mysql = null; private $builder = null; function __construct() { $this->data = wfPlugin::getPluginSettings('theme/version', true); wfPlugin::includeonce('mysql/builder'); $this->builder = new PluginMysqlBuilder(); if($this->data->get('data/mysql')){ $this->has_mysql = true; } if($this->has_mysql){ wfPlugin::includeonce('wf/mysql'); $this->mysql = new PluginWfMysql(); $this->mysql->open($this->data->get('data/mysql')); } wfPlugin::includeonce('wf/array'); wfPlugin::includeonce('wf/yml'); wfPlugin::enable('wf/table'); } private function db_account_role_tester(){ if(!$this->has_mysql){ return array(); } $this->builder->set_schema_file('/plugin/wf/account2/mysql/schema.yml'); $this->builder->set_table_name('account_role'); $criteria = new PluginWfArray(); $criteria->set('select_filter/0', 'account.email'); $criteria->set('join/0/field', 'account_id'); $criteria->set('where/account_role.role/value', 'tester'); $sql = $this->builder->get_sql_select($criteria->get()); $this->mysql->execute($sql); return $this->mysql->getMany($sql); } private function db_theme_version_user_all_working(){ if(!$this->has_mysql){ return new PluginWfArray(); } $rs = $this->mysql->runSql("select theme_version_user.version, group_concat(concat(account.email, '(', theme_version_user.created_at, ')')) as users from theme_version_user inner join account on theme_version_user.created_by=account.id where theme_version_user.response='Working' group by theme_version_user.version", 'version'); $rs = new PluginWfArray($rs['data']); return $rs; } private function db_theme_version_user_all_issue(){ if(!$this->has_mysql){ return new PluginWfArray(); } $rs = $this->mysql->runSql("select theme_version_user.version, group_concat(concat(account.email, '(', theme_version_user.response, ', ', theme_version_user.created_at, ')') separator ', ') as users from theme_version_user inner join account on theme_version_user.created_by=account.id where theme_version_user.response<>'Working' group by theme_version_user.version", 'version'); $rs = new PluginWfArray($rs['data']); return $rs; } private function db_theme_version_user_responses(){ if(!$this->has_mysql){ return new PluginWfArray(); } $created_by = wfUser::getSession()->get('user_id'); $rs = $this->mysql->runSql("select theme_version_user.version, theme_version_user.response from theme_version_user where created_by='$created_by'", 'version'); $rs = ($rs['data']); return $rs; } private function db_theme_version_user_one(){ $created_by = wfUser::getSession()->get('user_id'); $version = wfRequest::get('version'); $rs = $this->mysql->runSql("select * from theme_version_user where created_by='$created_by' and version='$version'", null); if($rs['num_rows']){ $rs = new PluginWfArray($rs['data'][0]); }else{ $rs = new PluginWfArray(); } return $rs; } private function db_theme_version_user_insert(){ $created_by = wfUser::getSession()->get('user_id'); $version = wfRequest::get('version'); $id = wfCrypt::getUid(); $this->mysql->runSql("insert into theme_version_user (id, created_by, version) values ('$id', '$created_by', '$version')"); return null; } private function db_theme_version_user_update(){ $created_by = wfUser::getSession()->get('user_id'); $response = wfRequest::get('response'); $version = wfRequest::get('version'); $this->mysql->runSql("update theme_version_user set response='$response' where created_by='$created_by' and version='$version'"); return null; } private function db_theme_version_user_delete(){ $created_by = wfUser::getSession()->get('user_id'); $version = wfRequest::get('version'); $this->mysql->runSql("delete from theme_version_user where created_by='$created_by' and version='$version'"); return null; } private function getHistoryAll(){ $history = array(); /** * Sys */ $sys_manifest = new PluginWfYml(wfGlobals::getSysDir().'/manifest.yml'); if($sys_manifest->get('history')){ foreach ($sys_manifest->get('history') as $key => $value) { $i2 = new PluginWfArray($value); $history[] = array('name' => wfGlobals::getVersion(), 'version' => $key, 'date' => $i2->get('date'), 'description' => $this->replace_line_break($i2->get('description')), 'type' => 'system', 'title' => $i2->get('title'), 'webmaster' => $this->replace_line_break($i2->get('webmaster'))); } } /** * Theme */ $theme_manifest = new PluginWfYml(wfGlobals::getAppDir().'/theme/'.wfGlobals::getTheme().'/config/manifest.yml'); if($theme_manifest->get('history')){ foreach ($theme_manifest->get('history') as $key => $value) { $i2 = new PluginWfArray($value); $history[] = array('name' => wfGlobals::getTheme(), 'version' => $key, 'date' => $i2->get('date'), 'description' => $this->replace_line_break($i2->get('description')), 'type' => 'theme', 'title' => $i2->get('title'), 'webmaster' => $this->replace_line_break($i2->get('webmaster'))); } } /** * Plugin */ wfPlugin::includeonce('plugin/analysis'); $plugin_analysis = new PluginPluginAnalysis(); wfRequest::set('theme', wfGlobals::getTheme()); $plugin_analysis->setPlugins(); foreach ($plugin_analysis->plugins->get() as $key => $value) { $i = new PluginWfArray($value); if($i->get('manifest/history')){ foreach ($i->get('manifest/history') as $key2 => $value2) { $i2 = new PluginWfArray($value2); $history[] = array('name' => $i->get('name'), 'version' => $key2, 'date' => $i2->get('date'), 'description' => $this->replace_line_break($i2->get('description')), 'type' => 'plugin', 'title' => $i2->get('title'), 'webmaster' => $this->replace_line_break($i2->get('webmaster'))); } } } /** * */ return $history; } private function replace_line_break($v){ return str_replace("\n", '<br>', $v); } public function widget_history_all($data){ $history = $this->getHistoryAll(); $widget = new PluginWfYml(__DIR__.'/element/history_all.yml'); /** * */ if(wfUser::hasRole('webmaster')){ $widget->set('0/data/data/field/webmaster', 'Webmaster'); } /** * */ $widget->setByTag(array('data' => $history)); wfDocument::renderElement($widget->get()); } public function widget_history($data){ /** * */ $has_mysql = false; if($this->has_mysql){ $has_mysql = true; } /** * */ $widget = new PluginWfYml(__DIR__.'/element/history.yml'); $application = array('title' => wfGlobals::get('settings/application/title'), 'host' => wfServer::getHttpHost()); $tester = $this->db_account_role_tester(); $responses = $this->db_theme_version_user_responses(); $test_users = ''; foreach($tester as $v){ $i = new PluginWfArray($v); $test_users .= ','.$i->get('account.email'); } $test_users = substr($test_users, 1); $widget->setByTag(array('test_users' => $test_users)); $widget->setByTag(array('application_data' => "if(typeof PluginThemeVersion=='object'){ PluginThemeVersion.data.application=".json_encode($application)."; PluginThemeVersion.data.tester=".json_encode($tester)."; PluginThemeVersion.data.responses=".json_encode($responses)."; PluginThemeVersion.data.has_mysql=".json_encode($has_mysql)."; }"), 'script'); /** * */ wfDocument::renderElement($widget->get()); } public function page_history(){ /** * Including Datatable */ wfPlugin::includeonce('datatable/datatable_1_10_18'); $datatable = new PluginDatatableDatatable_1_10_18(); /** * Data */ $plugin_data = wfPlugin::getPluginSettings('theme/version'); $history_data = $this->getHistory($plugin_data); $data = array(); foreach($history_data->get('item') as $v){ $data[] = $v; } /** * Render all data */ exit($datatable->set_table_data($data)); } public function widget_version($data){ $history = $this->getHistory($data); $element = array(); $element[] = wfDocument::createHtmlElement('text', $history->get('version')); wfDocument::renderElement($element); } private function getHistory($data){ $data = new PluginWfArray($data); if(!wfFilesystem::fileExist(wfGlobals::getAppDir().$data->get('data/history/filename'))){ throw new Exception("PluginThemeVersion.widget_history says: File ".$data->get('data/history/filename')." does not exist."); } $yml = new PluginWfYml($data->get('data/history/filename')); $history = new PluginWfArray($yml->get('history')); if($history->get()){ /** * Data fix. */ wfPlugin::includeonce('readme/parser'); $parser = new PluginReadmeParser(); foreach ($history->get() as $key => $value) { $item = new PluginWfArray($value); if(wfUser::hasRole('webmaster') && $item->get('webmaster')){ $history->set("$key/webmaster_enabled", true); }else{ $history->set("$key/webmaster_enabled", false); } $history->set("$key/version", $key); /** * Replace € with #. */ $item->set("description", str_replace("€", '#', $item->get('description')) ); $item->set("webmaster", str_replace("€", '#', $item->get('webmaster')) ); /** * */ $history->set("$key/description", $parser->parse_text($item->get('description')) ); $history->set("$key/webmaster", $parser->parse_text($item->get('webmaster')) ); } /** * user_working, user_issue */ $theme_version_user_working = $this->db_theme_version_user_all_working(); $theme_version_user_issue = $this->db_theme_version_user_all_issue(); foreach($history->get() as $k => $v){ $i = new PluginWfArray($v); /** * Rename param settings to row_settings according to PluginWfTable. */ $history->set("$k/row_settings", $i->get('settings')); $history->setUnset("$k/settings"); /** * Add role webmaster if row_settings/role/item is set. */ if($history->get("$k/row_settings/role/item")){ /** * Add string with roles to webmaster param. */ $roles = ''; foreach($history->get("$k/row_settings/role/item") as $v){ $roles .= ", $v"; } $roles = substr($roles, 2); $history->set("$k/webmaster", $history->get("$k/webmaster").''.$roles); /** * Add role webmaster. */ $history->set("$k/row_settings/role/item/", 'webmaster'); } /** * Add users working/issue */ $history->set("$k/users_working", $theme_version_user_working->get($i->get('version').'/users')); $history->set("$k/users_issue", $theme_version_user_issue->get($i->get('version').'/users')); } /** * New key to sort on. */ $temp = array(); foreach ($history->get() as $key => $value) { $a = preg_split('/[.]/', $key); $new_key = null; foreach ($a as $value2) { $new_key .= ($value2+1000); } if(sizeof($a)==2){ $new_key .= 1000; } $temp[$new_key] = $value; } krsort($temp); /** * Current version. */ $version = null; foreach ($temp as $key => $value) { $version = $value['version']; break; } /** * */ $history = new PluginWfArray(array('item' => $temp, 'version' => $version)); } return $history; } public function widget_include(){ wfDocument::renderElementFromFolder(__DIR__, __FUNCTION__); } public function page_response(){ if(!wfRequest::get('response')){ $this->db_theme_version_user_delete(); }else{ $rs = $this->db_theme_version_user_one(); if(!$rs->get('id')){ $this->db_theme_version_user_insert(); } $this->db_theme_version_user_update(); } $plugin_data = wfPlugin::getPluginSettings('theme/version'); $history_data = $this->getHistory($plugin_data); $history_item = new PluginWfArray(); foreach($history_data->get('item') as $k => $v){ $i = new PluginWfArray($v); if($i->get('version')==wfRequest::get('version')){ $history_item = new PluginWfArray($i->get()); break; } } exit(json_encode($history_item->get())); } } <file_sep>function PluginThemeVersion(){ this.data = {row_index: null, row_data: null, application: null, tester: [], responses: null, has_mysql: false}; this.row_click = function(){ /** * */ var btn_response_style = 'display:none'; if(this.data.has_mysql){ btn_response_style = 'display:'; } /** * */ PluginWfBootstrapjs.modal({id: 'modal_version_row', content: '', label: 'Version'}); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Application'}, {type: 'div', innerHTML: this.data.application.title}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Host'}, {type: 'div', innerHTML: this.data.application.host}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Date'}, {type: 'div', innerHTML: this.data.row_data.date}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Version'}, {type: 'div', innerHTML: this.data.row_data.version}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Title'}, {type: 'div', innerHTML: this.data.row_data.title}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Roles'}, {type: 'div', innerHTML: this.data.row_data.webmaster, attribute: {id: 'version_row_webmaster'}}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Working'}, {type: 'div', innerHTML: this.data.row_data.users_working, attribute: {id: 'version_row_users_working'}}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Issue'}, {type: 'div', innerHTML: this.data.row_data.users_issue, attribute: {id: 'version_row_users_issue'}}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [{type: 'strong', innerHTML: 'Description'}, {type: 'div', innerHTML: this.data.row_data.description}]}], 'modal_version_row_body'); PluginWfDom.render([{type: 'div', innerHTML: [ {type: 'a', innerHTML: 'Send mail', attribute: {class: 'btn btn-secondary', onclick: 'PluginThemeVersion.send_mail()'}}, {type: 'a', innerHTML: 'Response', attribute: {class: 'btn btn-primary', onclick: 'PluginThemeVersion.response()', style: btn_response_style}} ], attribute: {style: 'margin-top:40px;margin-bottom:40px'}}], 'modal_version_row_body'); } this.response = function(){ PluginWfBootstrapjs.modal({id: 'modal_version_response', content: null, label: 'Response', size: 'sm'}); PluginWfDom.render([{type: 'ul', innerHTML: [ {type: 'a', innerHTML: 'Do not understand', attribute: {href: '#', onclick: 'PluginThemeVersion.response_click(this)', data_value: 'Do not understand', class: 'list-group-item list-group-item-action'}}, {type: 'a', innerHTML: 'Working', attribute: {href: '#', onclick: 'PluginThemeVersion.response_click(this)', data_value: 'Working', class: 'list-group-item list-group-item-action'}}, {type: 'a', innerHTML: 'Not working', attribute: {href: '#', onclick: 'PluginThemeVersion.response_click(this)', data_value: 'Not working', class: 'list-group-item list-group-item-action'}}, {type: 'a', innerHTML: 'Could not test', attribute: {href: '#', onclick: 'PluginThemeVersion.response_click(this)', data_value: 'Could not test', class: 'list-group-item list-group-item-action'}}, {type: 'a', innerHTML: '(no response)', attribute: {href: '#', onclick: 'PluginThemeVersion.response_click(this)', data_value: '', class: 'list-group-item list-group-item-action'}} ], attribute: {class: 'list-group'}} ], 'modal_version_response_body'); if(typeof this.data.responses[this.data.row_data.version] != 'undefined'){ $("#modal_version_response [data_value='"+this.data.responses[this.data.row_data.version].response+"']").addClass('active'); } } this.response_click = function(btn){ $.get( "/theme_version/response?version="+this.data.row_data.version+"&response="+btn.getAttribute('data_value'), function( data ) { /** * */ $('#modal_version_response').modal('hide'); /** * */ var table = $('#dt_history').DataTable(); data_json = JSON.parse(data); PluginThemeVersion.data.row_data = data_json; table.row(PluginThemeVersion.data.row_index).data( PluginThemeVersion.data.row_data ).draw(); /** * */ document.getElementById('version_row_users_working').innerHTML = data_json.users_working; document.getElementById('version_row_users_issue').innerHTML = data_json.users_issue; /** * */ PluginThemeVersion.data.responses[PluginThemeVersion.data.row_data.version] = {response: data}; }); } this.send_mail = function(){ var mailto = ''; for(i=0; i<this.data.tester.length; i++){ mailto += ';'+this.data.tester[i]['account.email']; } mailto = mailto.substr(1); var subject = 'Version '+this.data.row_data.version; subject += ' ('+this.data.application.host+')'; if(this.data.application.title){ subject += ' - '+this.data.application.title; } var description = this.data.row_data.description; description = description.replace(/(<([^>]+)>)/gi, ""); var body = ''; body += 'Application: '+this.data.application.title+'%0D%0A'; body += 'Host: '+this.data.application.host+'%0D%0A'; body += 'Date: '+this.data.row_data.date+'%0D%0A'; body += 'Version: '+this.data.row_data.version+'%0D%0A'; body += 'Title: '+this.data.row_data.title+'%0D%0A'; body += 'Roles: '+this.data.row_data.webmaster+'%0D%0A'; if(!this.data.row_data.users_working){ this.data.row_data.users_working = ''; } if(!this.data.row_data.users_issue){ this.data.row_data.users_issue = ''; } body += 'Working: '+this.data.row_data.users_working+'%0D%0A'; body += 'Issue: '+this.data.row_data.users_issue+'%0D%0A'; body += 'Description:%0D%0A '+description+'%0D%0A'; window.location.href='mailto:'+mailto+'?subject='+subject+'&body='+body; } } var PluginThemeVersion = new PluginThemeVersion(); <file_sep># Buto-Plugin-ThemeVersion Plugin to show software history registrated in yml file. User with role tester can response on each version. ## Include js Optional. When click on a row in widget history a modals is shown with an email link ``` type: widget data: plugin: theme/version method: include ``` ## List widgets ### History View a list of theme history. ## Page Page registration to handle response and widget history. ``` plugin_modules: theme_version: plugin: 'theme/version' ``` #### Theme settings Set filename where history file is. ``` plugin: theme: version: enabled: true data: history: filename: /theme/[theme]/config/manifest.yml ``` #### Widget ``` type: widget data: plugin: theme/version method: history ``` Retrict some items. In this example using role webdeveloper. ``` history: 1.0.0: date: '2020-01-01' title: '' description: '' webmaster: 'Only show this post if user has role webdeveloper. Role webmaster will always be able to see all data.' settings: role: item: - webdeveloper ``` #### Email link By click on a row a modal is shown with an email link. Set param application/title in theme settings to add it to email subject. ``` application: title: Datos ``` ### History all View a list of all history for plugin, theme and sys. ``` type: widget data: plugin: theme/version method: history_all ``` Theme must have file /config/manifest.yml with param history. ``` history: '1.1': date: '2019-10-10' title: Improvement description: Improvement for this theme. '1.0': date: '2019-10-09' title: First version. description: First version of this theme. ``` ## Version number Get current version. ``` type: widget data: plugin: theme/version method: version data: filename: /theme/[theme]/data/version_history.yml ``` ## Data Param description and webmaster will be parsed by PluginReadmeParser. Character € will be replaced by #. ``` history: '1.0': date: '2018-11-01' title: First version description: Add files. webmaster: This is a comment only to be seen by webmaster. '1.0.1': date: '2018-11-02' title: Bug fix description: A bug fix. '1.1': date: '2018-11-03' title: Improvement description: | €€€H3 headline - Some list text. €€€H3 headline - Some list text. - Some list text. ``` ## Tester Optional. Get tester email from table account if user has role tester. One has to set mysql param. ``` plugin: theme: version: data: mysql: 'yml:/../buto_data/theme/sit/kanin/mysql.yml' ``` ## Schema ``` /plugin/theme/version/mysql/schema.yml ```
fbfd4d7ab21e29f2d5664f2742136ae18fc18faa
[ "JavaScript", "Markdown", "PHP" ]
3
PHP
costlund/Buto-Plugin-ThemeVersion
929307daa28f1a30d162f4565d9f34f947d79987
f1a124da9386bc4870915ca48838e65007500c21
refs/heads/master
<file_sep>import filepaths as FILES import sys # import matplotlib.pyplot as plt #example = '"[{""text"":""TrumpTrain""},{""text"":""Trump""},{""text"":""Putin""}]",2016-11-01T00:00:00.000Z' # Argument 1: File path of input file (eg. nov-hashtags.data) # Argument 2: File path of output file (eg. nov-hashtags-occurrences.data) # If there were any hashtags def tokens_to_hashtags(tweet): hashtags = [] if len(tweet) > 1 and not tweet[0] == "[]": tweet[0] = tweet[0].replace('"[', '') tweet[len(tweet)-2] = tweet[len(tweet)-2].replace(']"', '') prefix = '{""text"":""' suffix = '""}' for e in range(len(tweet)-1): tweet[e] = tweet[e].replace(prefix, '') tweet[e] = tweet[e].replace(suffix, '') hashtags.append(tweet[e]) return hashtags def format_tweet(tweet): entries = tweet.split(',') dttm = entries[len(entries)-1] # datetime hashtags = tokens_to_hashtags(entries) return dttm, hashtags def load_hashtags(filepath): data = [] with open(FILES.get_filepath(filepath), 'r') as file: ignore = 1 for line in file: line = line.replace('\n', '') if ignore == 0: data.append((format_tweet(line))) else: ignore -= 1 return data hashtag_occurrences = load_hashtags(str(sys.argv[1])) hashtag_counts = {} for h_o in hashtag_occurrences: # Hashtags for h in h_o[1]: print(h_o[1]) if not h in hashtag_counts: hashtag_counts[h] = 1 else: hashtag_counts[h] += 1 hashtag_count_distribution = [] with open(FILES.get_filepath(str(sys.argv[2])), 'w') as file: for h_c in hashtag_counts.keys(): file.write(h_c + ',' + str(hashtag_counts[h_c]) + '\n') hashtag_count_distribution.append(hashtag_counts[h_c]) # fig, ax = plt.subplots() # # ax.hist(hashtag_count_distribution) # # plt.show()<file_sep>import sys def get_filepath(file): if not sys.platform == "win32": return "../data/" + file else: return "..\\..\\data\\new\\"+ file <file_sep>import filepaths as FILES import csv from collections import OrderedDict files = ["xaa","xab","xac","xad","xae","xaf","xag","xah","xai","xaj"] total_count = {} for f in files: with open(FILES.get_filepath("hashtags\\" + f + "-occurrences"), 'r') as csvfile: reader = csv.reader(csvfile) for line in reader: if line[0] in total_count: total_count[line[0]] += int(line[1]) else: total_count[line[0]] = int(line[1]) ordered_counts = OrderedDict(sorted(total_count.items(), key=lambda t: -t[1])) with open(FILES.get_filepath("hashtags\\nov-all-occurrences"), 'w') as csvfile: for o_c in ordered_counts.keys(): if ordered_counts[o_c] > 100: print(o_c, str(ordered_counts[o_c]) + '\n') csvfile.write(o_c + ',' + str(ordered_counts[o_c]) + '\n')
b8c3fb6375d78c7bb2d03820f680550cc15d0c44
[ "Python" ]
3
Python
shasaur/Nutshell
6df15252ee235bfa62a67231d8573a9e749f4a0b
a055e544a2e9e175d9048e99ec1546e77c2dfd16
refs/heads/main
<repo_name>iiyuwan/react-manage-system<file_sep>/frontend/src/api/request.js // 封装 ajax模块 import axios from "axios"; import { message } from "antd"; import {ip} from '../config' axios.defaults.baseURL = ip // 这里可以不用配置了,因为设置了代理 /* * 优化点1:请求出错时,可以在这里直接全局拦截 * 优化点2:异步得到的结果是 response.data 就只含有后台返回的数据了 * */ export default function request(url, data = {}, method = 'GET') { return new Promise((resolve, reject) => { let promise if (method === 'GET') { promise = axios.get(url, {params: data}) } else { promise = axios.post(url, data) } promise.then(resp => { resolve(resp.data) }).catch(err => { message.error(err.response.data.message) // 全局错误处理,这里就不能 reject 了 }) }) } <file_sep>/backend/server.js const express = require('express') const app = express() const port = 5000 const userRouter = require('./routes/user.js') const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) // 添加中间件解析post表单数据 app.use(bodyParser.json()) app.use(express.static('public')) // 指定公开目录 const User = require('./models/user') const md5 = require('blueimp-md5') app.use(userRouter) // 引入 user 路由 app.listen(port, () => { console.log(`server listening at http://localhost:${port}`) }) // new User({username:'admin','password':md5('<PASSWORD>'),role_id:1}).save() <file_sep>/backend/routes/user.js let express = require('express'); const User = require('../models/user') const md5 = require('blueimp-md5') let router = express.Router(); const {stateAndCode} = require('../config') /** * @api {post} /login 用户登录 * @apiDescription 用户登录 * @apiName login * @apiGroup User * @apiParam {String} username 用户名 * @apiParam {String} password 密码 * @apiSuccess {json} result * @apiSuccessExample {json} 成功响应示例: * { * "status": 0, * "data": { * "_id": "465f4df34324", * "password": "<PASSWORD>", * "username": "admin", * "create_time": 15473243<PASSWORD>, * "_v": 0, * "role": { * "menus": [] * } * } * * @apiError {json} result * @apiErrorExample {json} 失败响应示例: * { * "status" : "1", * "message" : "用户名或密码不正确" * } * @apiSampleRequest http://localhost:5000/login * @apiVersion 1.0.0 */ router.post('/login', async (req, res) => { const {username, password} = req.body; try { const user = await User.findOne({username: username, password: md5(password)}) if (user) { // 登录成功 return res.status(200).json({ status: 0, data: user }) } return res.status(200).json({ // 账号或密码不正确 status: 1, message: stateAndCode.LOGIN_FAILED }) } catch (e) { res.status(500).json({ status: 1, message: stateAndCode.SERVER_BUSY }) } }); /** * @api {post} /user/add 添加用户 * @apiDescription 添加用户 * @apiName addUser * @apiGroup User * @apiParam {String} username 用户名 * @apiParam {String} password 密码 * @apiParam {String} phone 手机号码 * @apiParam {String} bio 自我介绍 * @apiParam {String} avatar 头像地址 * @apiParam {Number} gender 性别(-1=>保密 0=>女 1=>男) * @apiSuccess {json} result * @apiSuccessExample {json} 成功响应示例: * { * "status": 0, * "data": "注册成功" * } * * @apiError {json} result * @apiErrorExample {json} 失败响应示例: * { * "status" : "1", * "message" : "服务器正忙" * } * @apiSampleRequest http://localhost:5000/user/add * @apiVersion 1.0.0 */ router.post('/user/add', async (req, resp) => { try { if(await User.findOne({username:req.body.username})){ // 用户已存在 return resp.status(200).json({ status: 1, data: stateAndCode.USER_EXISTS }) } req.body.password = md5(req.body.password) if(new User(req.body).save()){ // 注册成功 return resp.status(200).json({ status: 0, data: stateAndCode.REGIST_SUCCESS }) } } catch (e) { resp.status(500).json({ status: 1, message: stateAndCode.SERVER_BUSY }) } }) module.exports = router <file_sep>/backend/README.md # 后端设计 ## 生成 api 文档 [具体参考](https://www.jianshu.com/p/7e1b057b047c/) ```bash npm i apidoc -g apidoc -i routes/ -o public/apidoc/ # 生成文件 nodemon server.js # 访问 localhost:5000/apidoc/index.html ``` ## API 接口说明 后台接口地址:`localhost:5000` <file_sep>/frontend/src/pages/home/home.jsx import React, {Component} from 'react'; import { Redirect, Route, Switch} from 'react-router-dom' import {Layout} from 'antd'; import Sidebar from "../../components/Sidebar"; import Header from '../../components/Header' import Dashboard from '../dashboard/dashboard' import Category from "../product/category"; import Product from "../product"; import User from "../user/user"; import Role from "../role/role"; import Line from '../chart/line' import Bar from "../chart/bar"; import Pie from "../chart/pie"; import './home.less' import storageUtil from "../../utils/storage"; const {Footer, Sider, Content} = Layout; // 只能写在 import 下面 // 主页的路由组件 class Home extends Component { render() { const user = storageUtil.getUser() if (!user || !user._id) { console.log('进来了') return <Redirect to='/login'/> } return ( <Layout style={{height: '100%'}}> <Sider> <Sidebar /> </Sider> <Layout> <Header /> <Content style={{backgroundColor:'#fff',margin:'16px',overflow:'auto'}}> {/* 匹配一个路由组件 */} <Switch> {/* 注册路由 */} <Route path='/dashboard' component={Dashboard}></Route> <Route path='/product/index' component={Product}></Route> <Route path='/product/category' component={Category}></Route> <Route path='/user' component={User}></Route> <Route path='/role' component={Role}></Route> <Route path='/charts/line' component={Line}></Route> <Route path='/charts/bar' component={Bar}></Route> <Route path='/charts/pie' component={Pie}></Route> <Redirect to='/dashboard' /> </Switch> </Content> <Footer style={{textAlign:'center',color:'darkgray'}}>柠檬味的蜡笔小新&reg;</Footer> </Layout> </Layout> ); } } export default Home; <file_sep>/frontend/src/pages/product/category.jsx import React, {Component} from 'react'; import { Card, Button} from "antd"; import './index.less' class Category extends Component { render() { return ( <div className='category'> <Card title="一级分类" extra={<Button >More</Button>} style={{width:'100%',height:'100%'}}> <p>Card content</p> <p>Card content</p> <p>Card content</p> </Card> </div> ); } } export default Category; <file_sep>/frontend/README.md # 前端设计 ## 前端路由 ```bash /login / /home /category # 分类管理 /product # 商品管理 /product/index # 主页 /product/saveupdate # 添加/修改 /product/detail # 详情 /user # 用户管理 /role # 角色管理 /charts/bar # 图表界面-柱状 /charts/pie # 图表界面-饼状 /charts/line # 图表界面-折线 ``` ## 目录结构 ``` frontend ├─ package-lock.json ├─ package.json ├─ public │ ├─ favicon.ico │ └─ index.html ├─ README.md └─ src ├─ api # ajax 相关 ├─ App.js # 根组件 ├─ assets # 公共资源 ├─ components # 非路由组件 ├─ config # 配置 ├─ index.js # 入口文件 ├─ pages # 路由组件 └─ utils # 工具模块 ``` ## 具体实现细节 1.[按需加载 antd 和自定义主题](https://3x.ant.design/docs/react/use-with-create-react-app-cn) react-app-rewired 会 读取 config-overrides [less-loader版本过高问题](https://blog.csdn.net/weixin_42614080/article/details/113749476) 2.代理问题【只能在开发环境中由前端配置,生产环境在后端配置】 3.async 和 await【只能拿到成功的回调,以同步编码方式获取异步结果】 4.如何动态生成 Menu+SubMenu【map、reduce】 5.刷新时如何选中对应菜单、如何打开折叠项【selectedKeys、openKeys】 jsonp主要是用来解决 get 跨域问题 【跨域问题--需要总结】 它不是 ajax 请求,而是一般的 get 请求 基本原理: 浏览器动态生成 script 来请求后台接口(src就是接口的url) 定义好用于处理响应的函数 fn ,并将函数名通过请求参数提交到后台(如:callback = fn) 服务器端处理好数据后,返回一个函数调用的 js 代码,并将结果作为实参传入函数调用 浏览器端收到响应自动执行函数调用的 js 代码,也就执行了提前定义好的回调函数,并得到了需要的结果数据 6.头部布局、显示登录用户、时间(格式化)、请求天气、当前请求页面title的获取、退出登录 <file_sep>/README.md # 后台管理系统 ## 技术选型 前端: - react - react-router-dom - antd - redux - ajax - axios - jsonp - promise/async/await - 富文本 - react-draft-wysiwyg - draft-js - draftjs-to-html 模块化: - ES6 - CommonJS 项目构件/工程化 - webpack - create-react-app - eslint 图表: - echarts - echarts-for-react 后端: - node - mongodb - mongoose - multer:文件上传 - blueimp-md5 ## 运行项目 ```bash npm start # 运行项目 npm run build # 项目打包 ``` <file_sep>/frontend/src/api/index.js import request from "./request"; import jsonp from 'jsonp' import {message} from "antd"; // 登录 export const reqLogin = (params) => request('/login', params,'POST') // 添加用户 export const reqAddUser = (params) => request('/user/add',params,'POST') export const reqWeather = (city) => { return new Promise((resolve,reject)=>{ let url = `https://v0.yiketianqi.com/api?version=v61&city=${city}&appid=23764888&appsecret=khb8ICSg` jsonp(url,{}, (err,data)=>{ if(!err){ const { wea,wea_img } = data resolve({wea,wea_img}) }else{ message.error('获取天气信息失败!') } }) }) } <file_sep>/frontend/src/utils/storage.js // 持久化存储的模块 import store from 'store' // store 更简洁、而且兼容性高 const storageUtil = { saveUser(user){ store.set('user', user) }, getUser(){ return store.get('user') || {} }, removeUser(){ store.remove('user') } } export default storageUtil <file_sep>/frontend/src/components/Sidebar/index.jsx import React, {Component} from 'react'; import {Link, withRouter} from 'react-router-dom' import {Menu} from 'antd'; import './index.less' import logo from '../../assets/images/logo.png' import { createFromIconfontCN } from '@ant-design/icons'; import menuList from "../../config/menus"; const IconFont = createFromIconfontCN({ scriptUrl: [ '/font/iconfont.js' ], }); const {SubMenu} = Menu; // 不是路由组件,要使用路由组件的 api class Sidebar extends Component { constructor(props) { super(props); this.menuNodes = this.getMenuNodes(menuList) // 先调用这个,保证能够先执行才获取到 openKey【这里执行一次,缓存起来了,就不必要每次render都去执行】 } render() { const curPath = this.props.location.pathname return ( <div className="sidebar"> <Link to='/' className='sidebar-title'> <img src={logo} alt="logo"/> <h2>起什么名~</h2> </Link> {/* defaultSelectedKeys 也是在第一次被选中,直接浏览器输入 / 就会绑定 /,而 /dashboard 无法再绑定*/} <Menu mode="inline" theme="dark" selectedKeys={[curPath]} defaultOpenKeys={[this.openKey]}> { this.menuNodes // 获取 menu 节点 } </Menu> </div> ); } getMenuNodes = (menuList) => { // map + 递归调用来实现层级(也可以用reduce实现:往空数组添加元素) const curPath = this.props.location.pathname return menuList.map(item => { if (item.children) { if(item.children.find(child => child.key === curPath)){ // 当前是二级路由 this.openKey = item.key // 需要记录下它的一级路由 } return ( <SubMenu key={item.key} icon={<IconFont type={item.icon}/>} title={item.title}> { this.getMenuNodes(item.children) } </SubMenu> ) } else { return ( <Menu.Item key={item.key}> <Link to={item.key}> <IconFont type={item.icon}/> {item.title}</Link> </Menu.Item> ) } }) } } export default withRouter(Sidebar);
9356a5832985733ae4c28f3171c72526846ae8b0
[ "JavaScript", "Markdown" ]
11
JavaScript
iiyuwan/react-manage-system
57f8a0a8ca3792a0ca3d00f089dc114e962ced54
b3d381dc7c125512ec1556447d197a10f882ce0a
refs/heads/master
<file_sep>// Setup Environment var express = require('express'), morgan = require('morgan'), app = express(), spark = require('spark'), cors = require('cors'); var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1"; var port = process.env.OPENSHIFT_NODEJS_PORT || 50000; var photonAccess; var device; var request = require('request'); var webAppURL = "oldeb.res.cmu.edu:3000/inputstreamround" var sendURL; var dataArr = [0,0,0,0] spark.login({username: '<EMAIL>', password: '<PASSWORD>'}, function(err, body) { console.log('API call login completed on callback:', body); photonAccess = body.access_token spark.getDevice('350022000147343337373738', function(err, deviceRet) { device = deviceRet; console.log('Device name: ' + device.name); }); } ); app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', '*'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); app.options('*', cors()); app.use(morgan('dev')); // Add headers setInterval(function(){ console.log(dataArr); sendURL= "http://" + webAppURL + '/' + dataArr[0] + '/' + dataArr[1] + '/' + dataArr[2] + '/' + dataArr[3]; console.log(sendURL) request(sendURL, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(Date.now()); } else { console.log("This is an Error: " + error); } }); }, 3000) setInterval(function(){ device.getVariable("fsrReading1", function(err, data) { if (err) { console.log('An error occurred while getting attrs:', err); } else { dataArr[0] = data.result } }); }, 500) setInterval(function(){ device.getVariable("fsrReading2", function(err, data) { if (err) { console.log('An error occurred while getting attrs:', err); } else { dataArr[1] = data.result } }); }, 500) setInterval(function(){ device.getVariable("fsrReading3", function(err, data) { if (err) { console.log('An error occurred while getting attrs:', err); } else { dataArr[2] = data.result } }); }, 500) setInterval(function(){ device.getVariable("fsrRead ing4", function(err, data) { if (err) { console.log('An error occurred while getting attrs:', err); } else { dataArr[3] = data.result } }); }, 500) app.listen(port, ipaddress, function() { console.log('%s: Node server started on %s:%d ...', Date(Date.now() ), ipaddress, port); });
61f8e59b8e5f02a8aa49d5d68a230b759cba2b4d
[ "JavaScript" ]
1
JavaScript
jahilliard/PostChairPhotonServ
4979bc802f9a844dab82c6862ec88ab150fffad9
a134be9315c5a833e38cf8be5a8309f0fc314720
refs/heads/master
<repo_name>MWBethke/GreenvilleRevenueGUIrevision<file_sep>/Form1.cs //Written By <NAME>, <NAME> //Date: 02/15/17 //Chapter 4, Case Problem 1 //Program Calculates Estimated revenue for contest and displays revenue and whether or not it increased from the year prior //No Issues Encountered again using System; using System.Windows.Forms; namespace GreenvilleRevenueGUI { public partial class RevenueForm : Form { public RevenueForm() { InitializeComponent(); } private void getRevenue_Click(object sender, EventArgs e) { int lastAttend = Convert.ToInt32(lastYearInput.Text); int thisAttend = Convert.ToInt32(thisYearInput.Text); bool isGreater = (thisAttend > lastAttend); bool isDouble = (thisAttend >= (2 * lastAttend)); if (thisAttend < 0 || thisAttend > 30 || lastAttend < 0 || lastAttend > 30) { greaterOutput.Text = "error pick a number between 0-30"; } else { if ((isGreater == true) && (isDouble == true)) { greaterOutput.Text = "The compertition is more than twice as big this year"; } else if ((isGreater == true) && (isDouble == false)) { greaterOutput.Text = "The compertition is bigger than ever"; } else { greaterOutput.Text = "A tighter race this year! Come out and cast your vote!"; } revenueOutput.Text = Convert.ToString(thisAttend * 25); } } private void TYALabel_Click(object sender, EventArgs e) { } private void RevenueForm_Load(object sender, EventArgs e) { } } } <file_sep>/README.md # GreenvilleRevenueGUIrevision Latest Itteration of GUI
414d89af528235bd8602833df341329117902eac
[ "Markdown", "C#" ]
2
C#
MWBethke/GreenvilleRevenueGUIrevision
4cf75cbcfca5050b8951548472d89fe6b9feab6f
c3824d9c681a543bc31b8eaede37d8068d507e23
refs/heads/master
<file_sep># janje Pokedex in Python. Data is scraped from http://www.serebii.net. ![screenshot](screenshot.png "Screenshot.") <file_sep>import tkinter as tk import io import urllib.request import PIL.Image as pim import PIL.ImageTk as pimtk import pyquery as pq current_no = 1 def set_current_no(new_value): if new_value is not None and 1 <= new_value <= 151: global current_no current_no = new_value def main(): win = tk.Tk() win.wm_title('Pokedex') btn_prev = tk.Button(win, text='<') btn_prev.pack(side='left') btn_next = tk.Button(win, text='>') btn_next.pack(side='right') fr_selector = tk.Frame(win) ent_num = tk.Entry(fr_selector, width=5) ent_num.pack(side='left') btn_go = tk.Button(fr_selector, border=3, text='Go!') btn_go.pack(side='left') canvas = tk.Canvas(win, relief='sunken', width='4c', height='4c', border=5) canvas.pack(side='top') o = canvas['border'] canvas_image = canvas.create_image(o, o, anchor='nw') im_size = int(canvas['width']), int(canvas['height']) lbl_name = tk.Label(win, font=('TkDefaultFont', '12', 'bold')) lbl_name.pack(side='top') msg_desc = tk.Message(win, width='4c') msg_desc.pack(side='top') fr_selector.pack(side='top') im_pokemon = None def btn_callback(btn): def callback(): if btn['text'] == '<': set_current_no(current_no - 1) elif btn['text'] == '>': set_current_no(current_no + 1) elif btn['text'] == 'Go!': value = try_parse(ent_num.get(), int) set_current_no(value) ent_num.delete(0, 'end') else: return refresh_gui() return callback btn_prev['command'] = btn_callback(btn_prev) btn_next['command'] = btn_callback(btn_next) btn_go['command'] = btn_callback(btn_go) def refresh_gui(): name, desc = scrape_data(get_url(current_no), ['name', 'desc']) lbl_name['text'] = name msg_desc['text'] = desc nonlocal im_pokemon im_pokemon = open_image(get_image_url(current_no), size=im_size) canvas.delete() show_image(canvas, im_pokemon, canvas_image) btn_prev['state'] = 'normal' btn_next['state'] = 'normal' if current_no <= 1: btn_prev['state'] = 'disabled' elif current_no >= 151: btn_next['state'] = 'disabled' win.pack_slaves() refresh_gui() win.mainloop() def open_image(url, size=None): data = urllib.request.urlopen(url).read() image = pim.open(io.BytesIO(data)) if size is not None: image = pim.Image.resize(image, size, pim.ANTIALIAS) im = pimtk.PhotoImage(image) return im def show_image(canvas, image, canvas_image): canvas.itemconfigure(canvas_image, image=image) def get_url(no): return 'http://www.serebii.net/pokedex-rs/{:03d}.shtml'.format(no) def scrape_data(url, what) -> tuple: rval = () document = pq.PyQuery(url=url) if 'name' in what: name = document('.dextab').eq(0).find('table td').eq(1)('font b').html().strip() rval += name, if 'desc' in what: desc = (document('b:contains("Flavour Text")') .parents('table').eq(1).find('tr').eq(3).find('td').eq(1).html().strip()) rval += desc, return rval def get_image_url(no): return 'http://www.serebii.net/art/th/{}.png'.format(no) def try_parse(s, f): try: return f(s) except ValueError: return None if __name__ == '__main__': main()
55f7fe947514e087c8496c476c3ecab622d19c51
[ "Markdown", "Python" ]
2
Markdown
mrlovre/janje
0e2fe9caf33fd380a45f0464dc3201c75406d934
7bb7a4e5cb6a33cb54313c969361181efd2f7e18
refs/heads/master
<repo_name>YasinCengiz/markov<file_sep>/run.py from markov_python.cc_markov import MarkovChain mc = MarkovChain() mc.add_file("dnine.txt") conversation = mc.generate_text() print ("This is D-9. I know all the lyrics of Metallica - Nothing Else Matters. You can sing with me.") print ("Write the lyric.") <file_sep>/fetch_data.py import requests from bs4 import BeautifulSoup NEM = https://www.lyricsfreak.com/l/lucie+silvas/nothing+else+matters_10168262.html nemstr = "" ###take lyrics from url and store under one variable for url in NEM: page = requests.get(url) bsoup = BeautifulSoup(page.text, 'html.parser') div = soup.select_one('#content_h') for x in soup.find_all('br'): e.replace_with('\n') found += div.text ###save data to file string = "" for word in found: string += word f = open("dnine.txt", "w") f.write(string) f.close()
f5c8aee7db64985102cdd9eb9b0dc7bc0ae296d2
[ "Python" ]
2
Python
YasinCengiz/markov
88ad41937e50d0bd9d09602a5c8f7958891dd57f
ccdb9a2230d2bf482a612959541b5134831d47e6
refs/heads/master
<repo_name>tipabu/no_op_gatekeeper<file_sep>/update-readme.sh #!/usr/bin/sh < setup.py sed -e '1,/"""$/d;/^"""/,$d' > README.rst <file_sep>/README.rst No-op Gatekeeper ================ OpenStack Swift has a ``gatekeeper`` middleware that gets automatically inserted in ``proxy-server`` pipelines if not present. Its job is to act as a firewall, both preventing Swift internals like backend and sysmeta headers from leaking out to the client and also ensuring that such headers coming from clients are ignored. That's all well and good, but sometimes as a developer you just want a persistent ``internal_client`` with ``curl`` as an interface. This lets you have that. Usage ----- Update your ``[filter:gatekeeper]`` to look like:: [filter:gatekeeper] use = egg:no_op_gatekeeper#gatekeeper # no_log = false <file_sep>/setup.py # Copyright (c) 2019-2020 <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. import setuptools setuptools.setup( name="no_op_gatekeeper", author="<NAME>", author_email="<EMAIL>", url="https://github.com/tipabu/no-op-gatekeeper", version="1.2", description="An insecure no-op gatekeeper for OpenStack Swift", long_description=""" No-op Gatekeeper ================ OpenStack Swift has a ``gatekeeper`` middleware that gets automatically inserted in ``proxy-server`` pipelines if not present. Its job is to act as a firewall, both preventing Swift internals like backend and sysmeta headers from leaking out to the client and also ensuring that such headers coming from clients are ignored. That's all well and good, but sometimes as a developer you just want a persistent ``internal_client`` with ``curl`` as an interface. This lets you have that. Usage ----- Update your ``[filter:gatekeeper]`` to look like:: [filter:gatekeeper] use = egg:no_op_gatekeeper#gatekeeper # no_log = false """.strip(), long_description_content_type="text/x-rst", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: OpenStack", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", "Topic :: Software Development", ], py_modules=["no_op_gatekeeper"], requires=["swift"], entry_points={ "paste.filter_factory": "gatekeeper = no_op_gatekeeper:filter_factory" }, ) <file_sep>/no_op_gatekeeper.py # Copyright (c) 2019-2020 <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. from swift.common import utils def filter_factory(global_conf, **local_conf): conf = dict(global_conf, **local_conf) no_log = utils.config_true_value(conf.get("no_log")) def filter(app): if not no_log: logger = utils.get_logger(conf) logger.warning("Using INSECURE, DANGEROUS no-op gatekeeper!") def new_app(env, start_response): env['swift_owner'] = True env['reseller_request'] = True env['swift.content_type_overridden'] = True env.setdefault('HTTP_X_BACKEND_ALLOW_RESERVED_NAMES', 'True') env.setdefault('HTTP_X_BACKEND_ALLOW_PRIVATE_METHODS', 'True') return app(env, start_response) return new_app return filter
12cceec91384e2b3582d0d514e87aabe0e6b08fd
[ "Python", "reStructuredText", "Shell" ]
4
Shell
tipabu/no_op_gatekeeper
2ee40f68055d5b28993ac234dc33a3fb43d334bc
908c3384d1942a8bcd2440b677a66ab84c87e62c
refs/heads/master
<repo_name>isma4102/Culturarte_Web_SitioMovil<file_sep>/web/classes/servicios/PublicadorConsultarUsuario.java package servicios; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.Action; import javax.xml.ws.FaultAction; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "PublicadorConsultarUsuario", targetNamespace = "http://Servicios/") @SOAPBinding(style = SOAPBinding.Style.RPC) @XmlSeeAlso({ ObjectFactory.class }) public interface PublicadorConsultarUsuario { /** * * @param arg0 */ @WebMethod @Action(input = "http://Servicios/PublicadorConsultarUsuario/publicarConsultarUsuarioRequest", output = "http://Servicios/PublicadorConsultarUsuario/publicarConsultarUsuarioResponse") public void publicarConsultarUsuario( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @param nick * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "DesactivarProponente") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/DesactivarProponenteRequest", output = "http://Servicios/PublicadorConsultarUsuario/DesactivarProponenteResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarUsuario/DesactivarProponente/Fault/Exception") }) public boolean desactivarProponente( @WebParam(name = "nick", partName = "nick") String nick) throws Exception_Exception ; /** * * @return * returns servicios.DtListUsuario */ @WebMethod(operationName = "ListarUsuarios") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ListarUsuariosRequest", output = "http://Servicios/PublicadorConsultarUsuario/ListarUsuariosResponse") public DtListUsuario listarUsuarios(); /** * * @param nickname * @return * returns servicios.DtListInfoPropuesta * @throws Exception_Exception */ @WebMethod(operationName = "ListarPropuestasDeProponenteX") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ListarPropuestasDeProponenteXRequest", output = "http://Servicios/PublicadorConsultarUsuario/ListarPropuestasDeProponenteXResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarUsuario/ListarPropuestasDeProponenteX/Fault/Exception") }) public DtListInfoPropuesta listarPropuestasDeProponenteX( @WebParam(name = "nickname", partName = "nickname") String nickname) throws Exception_Exception ; /** * * @param nickname * @return * returns servicios.DtinfoColaborador */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/getDtColaboradorRequest", output = "http://Servicios/PublicadorConsultarUsuario/getDtColaboradorResponse") public DtinfoColaborador getDtColaborador( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @param nickname * @return * returns servicios.DtListInfoPropuesta */ @WebMethod(operationName = "ListarPropuestasNoIngresadas") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ListarPropuestasNoIngresadasRequest", output = "http://Servicios/PublicadorConsultarUsuario/ListarPropuestasNoIngresadasResponse") public DtListInfoPropuesta listarPropuestasNoIngresadas( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @param nickname * @return * returns servicios.DtListUsuario */ @WebMethod(operationName = "ObtenerSeguidores") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ObtenerSeguidoresRequest", output = "http://Servicios/PublicadorConsultarUsuario/ObtenerSeguidoresResponse") public DtListUsuario obtenerSeguidores( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @return * returns servicios.DtListUsuario */ @WebMethod(operationName = "ListarUsuariosRanking") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ListarUsuariosRankingRequest", output = "http://Servicios/PublicadorConsultarUsuario/ListarUsuariosRankingResponse") public DtListUsuario listarUsuariosRanking(); /** * * @param colaborador * @return * returns servicios.DtListColaboraciones */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/getMontoColaboracionRequest", output = "http://Servicios/PublicadorConsultarUsuario/getMontoColaboracionResponse") public DtListColaboraciones getMontoColaboracion( @WebParam(name = "colaborador", partName = "colaborador") String colaborador); /** * * @param nick * @return * returns byte[] * @throws Exception_Exception */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/retornarImagenRequest", output = "http://Servicios/PublicadorConsultarUsuario/retornarImagenResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarUsuario/retornarImagen/Fault/Exception") }) public byte[] retornarImagen( @WebParam(name = "nick", partName = "nick") String nick) throws Exception_Exception ; /** * * @param nickname * @return * returns servicios.DtListUsuario */ @WebMethod(operationName = "ObtenerSeguidos") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ObtenerSeguidosRequest", output = "http://Servicios/PublicadorConsultarUsuario/ObtenerSeguidosResponse") public DtListUsuario obtenerSeguidos( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @param nickname * @return * returns servicios.DtListInfoPropuesta */ @WebMethod(operationName = "VerPropuestas") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/VerPropuestasRequest", output = "http://Servicios/PublicadorConsultarUsuario/VerPropuestasResponse") public DtListInfoPropuesta verPropuestas( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @param login * @return * returns servicios.DtUsuario */ @WebMethod(operationName = "ObtenerDtUsuario") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ObtenerDtUsuarioRequest", output = "http://Servicios/PublicadorConsultarUsuario/ObtenerDtUsuarioResponse") public DtUsuario obtenerDtUsuario( @WebParam(name = "login", partName = "login") String login); /** * * @param nickname * @return * returns servicios.DtListInfoPropuesta */ @WebMethod(operationName = "ObtenerFavoritas") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ObtenerFavoritasRequest", output = "http://Servicios/PublicadorConsultarUsuario/ObtenerFavoritasResponse") public DtListInfoPropuesta obtenerFavoritas( @WebParam(name = "nickname", partName = "nickname") String nickname); /** * * @param nick * @param titulo * @return * returns boolean */ @WebMethod(operationName = "AgregarFavortio") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/AgregarFavortioRequest", output = "http://Servicios/PublicadorConsultarUsuario/AgregarFavortioResponse") public boolean agregarFavortio( @WebParam(name = "titulo", partName = "titulo") String titulo, @WebParam(name = "nick", partName = "nick") String nick); /** * * @param nick2 * @param nick1 * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "SeguirUsuario") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/SeguirUsuarioRequest", output = "http://Servicios/PublicadorConsultarUsuario/SeguirUsuarioResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarUsuario/SeguirUsuario/Fault/Exception") }) public boolean seguirUsuario( @WebParam(name = "nick1", partName = "nick1") String nick1, @WebParam(name = "nick2", partName = "nick2") String nick2) throws Exception_Exception ; /** * * @param login * @return * returns servicios.DtUsuario */ @WebMethod(operationName = "ObtenerDtUsuario_Correo") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/ObtenerDtUsuario_CorreoRequest", output = "http://Servicios/PublicadorConsultarUsuario/ObtenerDtUsuario_CorreoResponse") public DtUsuario obtenerDtUsuarioCorreo( @WebParam(name = "login", partName = "login") String login); /** * * @param nick2 * @param nick1 * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "DejarSeguirUsuario") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarUsuario/DejarSeguirUsuarioRequest", output = "http://Servicios/PublicadorConsultarUsuario/DejarSeguirUsuarioResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarUsuario/DejarSeguirUsuario/Fault/Exception") }) public boolean dejarSeguirUsuario( @WebParam(name = "nick1", partName = "nick1") String nick1, @WebParam(name = "nick2", partName = "nick2") String nick2) throws Exception_Exception ; } <file_sep>/web/classes/servicios/DtComentarios.java package servicios; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para dtComentarios complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="dtComentarios"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Colaborador" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Propuesta" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Comentario" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dtComentarios", propOrder = { "colaborador", "propuesta", "comentario" }) public class DtComentarios { @XmlElement(name = "Colaborador") protected String colaborador; @XmlElement(name = "Propuesta") protected String propuesta; @XmlElement(name = "Comentario") protected String comentario; /** * Obtiene el valor de la propiedad colaborador. * * @return * possible object is * {@link String } * */ public String getColaborador() { return colaborador; } /** * Define el valor de la propiedad colaborador. * * @param value * allowed object is * {@link String } * */ public void setColaborador(String value) { this.colaborador = value; } /** * Obtiene el valor de la propiedad propuesta. * * @return * possible object is * {@link String } * */ public String getPropuesta() { return propuesta; } /** * Define el valor de la propiedad propuesta. * * @param value * allowed object is * {@link String } * */ public void setPropuesta(String value) { this.propuesta = value; } /** * Obtiene el valor de la propiedad comentario. * * @return * possible object is * {@link String } * */ public String getComentario() { return comentario; } /** * Define el valor de la propiedad comentario. * * @param value * allowed object is * {@link String } * */ public void setComentario(String value) { this.comentario = value; } } <file_sep>/web/classes/servicios/DtUsuario.java package servicios; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Clase Java para dtUsuario complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="dtUsuario"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="nickname" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nombre" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="apellido" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="correo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="fechaN" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;element name="imagen" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="password" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="esproponente" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="biografia" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="direccion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="sitioweb" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="seguidores" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="seguidos" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dtUsuario", propOrder = { "nickname", "nombre", "apellido", "correo", "fechaN", "imagen", "password", "<PASSWORD>", "biografia", "direccion", "sitioweb", "seguidores", "seguidos" }) public class DtUsuario { protected String nickname; protected String nombre; protected String apellido; protected String correo; @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar fechaN; protected String imagen; protected String password; protected boolean esproponente; protected String biografia; protected String direccion; protected String sitioweb; @XmlElement(nillable = true) protected List<String> seguidores; @XmlElement(nillable = true) protected List<String> seguidos; /** * Obtiene el valor de la propiedad nickname. * * @return * possible object is * {@link String } * */ public String getNickname() { return nickname; } /** * Define el valor de la propiedad nickname. * * @param value * allowed object is * {@link String } * */ public void setNickname(String value) { this.nickname = value; } /** * Obtiene el valor de la propiedad nombre. * * @return * possible object is * {@link String } * */ public String getNombre() { return nombre; } /** * Define el valor de la propiedad nombre. * * @param value * allowed object is * {@link String } * */ public void setNombre(String value) { this.nombre = value; } /** * Obtiene el valor de la propiedad apellido. * * @return * possible object is * {@link String } * */ public String getApellido() { return apellido; } /** * Define el valor de la propiedad apellido. * * @param value * allowed object is * {@link String } * */ public void setApellido(String value) { this.apellido = value; } /** * Obtiene el valor de la propiedad correo. * * @return * possible object is * {@link String } * */ public String getCorreo() { return correo; } /** * Define el valor de la propiedad correo. * * @param value * allowed object is * {@link String } * */ public void setCorreo(String value) { this.correo = value; } /** * Obtiene el valor de la propiedad fechaN. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getFechaN() { return fechaN; } /** * Define el valor de la propiedad fechaN. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setFechaN(XMLGregorianCalendar value) { this.fechaN = value; } /** * Obtiene el valor de la propiedad imagen. * * @return * possible object is * {@link String } * */ public String getImagen() { return imagen; } /** * Define el valor de la propiedad imagen. * * @param value * allowed object is * {@link String } * */ public void setImagen(String value) { this.imagen = value; } /** * Obtiene el valor de la propiedad password. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Define el valor de la propiedad password. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Obtiene el valor de la propiedad esproponente. * */ public boolean isEsproponente() { return esproponente; } /** * Define el valor de la propiedad esproponente. * */ public void setEsproponente(boolean value) { this.esproponente = value; } /** * Obtiene el valor de la propiedad biografia. * * @return * possible object is * {@link String } * */ public String getBiografia() { return biografia; } /** * Define el valor de la propiedad biografia. * * @param value * allowed object is * {@link String } * */ public void setBiografia(String value) { this.biografia = value; } /** * Obtiene el valor de la propiedad direccion. * * @return * possible object is * {@link String } * */ public String getDireccion() { return direccion; } /** * Define el valor de la propiedad direccion. * * @param value * allowed object is * {@link String } * */ public void setDireccion(String value) { this.direccion = value; } /** * Obtiene el valor de la propiedad sitioweb. * * @return * possible object is * {@link String } * */ public String getSitioweb() { return sitioweb; } /** * Define el valor de la propiedad sitioweb. * * @param value * allowed object is * {@link String } * */ public void setSitioweb(String value) { this.sitioweb = value; } /** * Gets the value of the seguidores property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the seguidores property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSeguidores().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getSeguidores() { if (seguidores == null) { seguidores = new ArrayList<String>(); } return this.seguidores; } /** * Gets the value of the seguidos property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the seguidos property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSeguidos().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getSeguidos() { if (seguidos == null) { seguidos = new ArrayList<String>(); } return this.seguidos; } } <file_sep>/web/classes/servicios/PublicadorConsultarPropuesta.java package servicios; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.Action; import javax.xml.ws.FaultAction; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "PublicadorConsultarPropuesta", targetNamespace = "http://Servicios/") @SOAPBinding(style = SOAPBinding.Style.RPC) @XmlSeeAlso({ ObjectFactory.class }) public interface PublicadorConsultarPropuesta { /** * * @param titulo * @param nickProp * @return * returns servicios.DtConsultaPropuesta */ @WebMethod(operationName = "SeleccionarPropuesta") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/SeleccionarPropuestaRequest", output = "http://Servicios/PublicadorConsultarPropuesta/SeleccionarPropuestaResponse") public DtConsultaPropuesta seleccionarPropuesta( @WebParam(name = "titulo", partName = "titulo") String titulo, @WebParam(name = "nickProp", partName = "nickProp") String nickProp); /** * * @param arg0 */ @WebMethod @Action(input = "http://Servicios/PublicadorConsultarPropuesta/publicarConsultaPropuestaRequest", output = "http://Servicios/PublicadorConsultarPropuesta/publicarConsultaPropuestaResponse") public void publicarConsultaPropuesta( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @param titulo * @return * returns boolean */ @WebMethod(operationName = "ExtenderFinanciacion") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ExtenderFinanciacionRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ExtenderFinanciacionResponse") public boolean extenderFinanciacion( @WebParam(name = "titulo", partName = "titulo") String titulo); /** * * @param nombre * @return * returns servicios.DtListInfoPropuesta */ @WebMethod(operationName = "ListarPropuestasCategoria") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasCategoriaRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasCategoriaResponse") public DtListInfoPropuesta listarPropuestasCategoria( @WebParam(name = "nombre", partName = "nombre") String nombre); /** * * @param nick * @return * returns servicios.DtListNickTitProp */ @WebMethod(operationName = "ListarPropuestasCancelar") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasCancelarRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasCancelarResponse") public DtListNickTitProp listarPropuestasCancelar( @WebParam(name = "nick", partName = "nick") String nick); /** * * @param nick * @param texto * @param titulo * @throws Exception_Exception */ @WebMethod(operationName = "ComentarPropuesta") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ComentarPropuestaRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ComentarPropuestaResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/ComentarPropuesta/Fault/Exception") }) public void comentarPropuesta( @WebParam(name = "titulo", partName = "titulo") String titulo, @WebParam(name = "nick", partName = "nick") String nick, @WebParam(name = "texto", partName = "texto") String texto) throws Exception_Exception ; /** * * @param nick * @param titulo * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "CancelarPropuesta") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/CancelarPropuestaRequest", output = "http://Servicios/PublicadorConsultarPropuesta/CancelarPropuestaResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/CancelarPropuesta/Fault/Exception") }) public boolean cancelarPropuesta( @WebParam(name = "titulo", partName = "titulo") String titulo, @WebParam(name = "nick", partName = "nick") String nick) throws Exception_Exception ; /** * * @return * returns servicios.DtListConsultaPropuesta * @throws Exception_Exception */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/getDtPropuestasRequest", output = "http://Servicios/PublicadorConsultarPropuesta/getDtPropuestasResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/getDtPropuestas/Fault/Exception") }) public DtListConsultaPropuesta getDtPropuestas() throws Exception_Exception ; /** * * @param titulo * @return * returns byte[] * @throws Exception_Exception */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/retornarImagenRequest", output = "http://Servicios/PublicadorConsultarPropuesta/retornarImagenResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/retornarImagen/Fault/Exception") }) public byte[] retornarImagen( @WebParam(name = "titulo", partName = "titulo") String titulo) throws Exception_Exception ; /** * * @return * returns servicios.DtListNickTitProp */ @WebMethod(operationName = "ListarPropuestas") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasResponse") public DtListNickTitProp listarPropuestas(); /** * * @param titulo * @return * returns servicios.DtConsultaPropuesta */ @WebMethod(operationName = "SeleccionarPropuesta2") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/SeleccionarPropuesta2Request", output = "http://Servicios/PublicadorConsultarPropuesta/SeleccionarPropuesta2Response") public DtConsultaPropuesta seleccionarPropuesta2( @WebParam(name = "titulo", partName = "titulo") String titulo); /** * * @param nick * @return * returns servicios.DtListNickTitProp */ @WebMethod(operationName = "ListarPropuestasX_deProponenteX") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasX_deProponenteXRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasX_deProponenteXResponse") public DtListNickTitProp listarPropuestasXDeProponenteX( @WebParam(name = "nick", partName = "nick") String nick); /** * * @return * returns servicios.DtListNickTitProp */ @WebMethod(operationName = "ListarPropuestasComentar") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasComentarRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasComentarResponse") public DtListNickTitProp listarPropuestasComentar(); /** * * @param titulo * @return * returns servicios.DtListConsultaPropuesta2 * @throws Exception_Exception */ @WebMethod(operationName = "ListarColaboradoresProp") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarColaboradoresPropRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarColaboradoresPropResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/ListarColaboradoresProp/Fault/Exception") }) public DtListConsultaPropuesta2 listarColaboradoresProp( @WebParam(name = "titulo", partName = "titulo") String titulo) throws Exception_Exception ; /** * * @return * returns servicios.DtListInfoPropuesta */ @WebMethod(operationName = "ListarPropuestasNoI") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasNoIRequest", output = "http://Servicios/PublicadorConsultarPropuesta/ListarPropuestasNoIResponse") public DtListInfoPropuesta listarPropuestasNoI(); /** * * @param tituloP * @return * returns servicios.DtListComentarios * @throws Exception_Exception */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorConsultarPropuesta/listarComentariosRequest", output = "http://Servicios/PublicadorConsultarPropuesta/listarComentariosResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorConsultarPropuesta/listarComentarios/Fault/Exception") }) public DtListComentarios listarComentarios( @WebParam(name = "TituloP", partName = "TituloP") String tituloP) throws Exception_Exception ; } <file_sep>/web/config.properties Porth=8280 Ip=192.168.1.112 AltaPropuesta=AltaP ConsultaPropuesta=ConsultaP AltaUsuario=AltaUsuario ConsultaUsuario=ConsultaU Inicio=Inicio RegistrarColaboracion=RegistrarC sAltaPropuesta=/servicioAltaP sConsultaPropuesta=/servicioConsultaP sAltaUsuario=/servicioAltaUsuario sConsultaUsuario=/servicioConsultaU sInicio=/servicioInicio sRegistrarColaboracion=/servicioRegistrarC<file_sep>/web/classes/servicios/PublicadorAltaPropuesta.java package servicios; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.Action; import javax.xml.ws.FaultAction; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "PublicadorAltaPropuesta", targetNamespace = "http://Servicios/") @SOAPBinding(style = SOAPBinding.Style.RPC) @XmlSeeAlso({ ObjectFactory.class }) public interface PublicadorAltaPropuesta { /** * * @param arg0 */ @WebMethod @Action(input = "http://Servicios/PublicadorAltaPropuesta/publicarRequest", output = "http://Servicios/PublicadorAltaPropuesta/publicarResponse") public void publicar( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @return * returns servicios.DtCategorias */ @WebMethod(operationName = "ListarCategorias") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorAltaPropuesta/ListarCategoriasRequest", output = "http://Servicios/PublicadorAltaPropuesta/ListarCategoriasResponse") public DtCategorias listarCategorias(); /** * * @param descripcion * @param fecha * @param retorno * @param lugar * @param montoTot * @param tituloP * @param montoE * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "CrearPropuesta") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorAltaPropuesta/CrearPropuestaRequest", output = "http://Servicios/PublicadorAltaPropuesta/CrearPropuestaResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorAltaPropuesta/CrearPropuesta/Fault/Exception") }) public boolean crearPropuesta( @WebParam(name = "tituloP", partName = "tituloP") String tituloP, @WebParam(name = "descripcion", partName = "descripcion") String descripcion, @WebParam(name = "lugar", partName = "lugar") String lugar, @WebParam(name = "fecha", partName = "fecha") String fecha, @WebParam(name = "montoE", partName = "montoE") float montoE, @WebParam(name = "montoTot", partName = "montoTot") float montoTot, @WebParam(name = "retorno", partName = "retorno") String retorno) throws Exception_Exception ; /** * * @param nick * @param categoria * @return * returns boolean * @throws Exception_Exception */ @WebMethod(operationName = "SeleccionarUC") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorAltaPropuesta/SeleccionarUCRequest", output = "http://Servicios/PublicadorAltaPropuesta/SeleccionarUCResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorAltaPropuesta/SeleccionarUC/Fault/Exception") }) public boolean seleccionarUC( @WebParam(name = "nick", partName = "nick") String nick, @WebParam(name = "categoria", partName = "categoria") String categoria) throws Exception_Exception ; } <file_sep>/web/classes/servicios/DtListaPropuestasR.java package servicios; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para dtListaPropuestasR complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="dtListaPropuestasR"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Titulo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Proponente" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Estado" type="{http://Servicios/}tipoE" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dtListaPropuestasR", propOrder = { "titulo", "proponente", "estado" }) public class DtListaPropuestasR { @XmlElement(name = "Titulo") protected String titulo; @XmlElement(name = "Proponente") protected String proponente; @XmlElement(name = "Estado") @XmlSchemaType(name = "string") protected TipoE estado; /** * Obtiene el valor de la propiedad titulo. * * @return * possible object is * {@link String } * */ public String getTitulo() { return titulo; } /** * Define el valor de la propiedad titulo. * * @param value * allowed object is * {@link String } * */ public void setTitulo(String value) { this.titulo = value; } /** * Obtiene el valor de la propiedad proponente. * * @return * possible object is * {@link String } * */ public String getProponente() { return proponente; } /** * Define el valor de la propiedad proponente. * * @param value * allowed object is * {@link String } * */ public void setProponente(String value) { this.proponente = value; } /** * Obtiene el valor de la propiedad estado. * * @return * possible object is * {@link TipoE } * */ public TipoE getEstado() { return estado; } /** * Define el valor de la propiedad estado. * * @param value * allowed object is * {@link TipoE } * */ public void setEstado(TipoE value) { this.estado = value; } } <file_sep>/web/classes/servicios/TipoRetorno.java package servicios; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para tipoRetorno. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * <p> * <pre> * &lt;simpleType name="tipoRetorno"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Entradas"/> * &lt;enumeration value="porGanancias"/> * &lt;enumeration value="EntGan"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "tipoRetorno") @XmlEnum public enum TipoRetorno { @XmlEnumValue("Entradas") ENTRADAS("Entradas"), @XmlEnumValue("porGanancias") POR_GANANCIAS("porGanancias"), @XmlEnumValue("EntGan") ENT_GAN("EntGan"); private final String value; TipoRetorno(String v) { value = v; } public String value() { return value; } public static TipoRetorno fromValue(String v) { for (TipoRetorno c: TipoRetorno.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } } <file_sep>/web/classes/servicios/PublicadorInicio.java package servicios; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.Action; import javax.xml.ws.FaultAction; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.2 * */ @WebService(name = "PublicadorInicio", targetNamespace = "http://Servicios/") @SOAPBinding(style = SOAPBinding.Style.RPC) @XmlSeeAlso({ ObjectFactory.class }) public interface PublicadorInicio { /** * * @param arg0 */ @WebMethod @Action(input = "http://Servicios/PublicadorInicio/publicarInicioRequest", output = "http://Servicios/PublicadorInicio/publicarInicioResponse") public void publicarInicio( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @return * returns servicios.DtListPropuestaWeb */ @WebMethod(operationName = "ListarPropuestasWeb") @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorInicio/ListarPropuestasWebRequest", output = "http://Servicios/PublicadorInicio/ListarPropuestasWebResponse") public DtListPropuestaWeb listarPropuestasWeb(); /** * * @param arg0 * @return * returns java.lang.String */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorInicio/leerPropiedadesRequest", output = "http://Servicios/PublicadorInicio/leerPropiedadesResponse") public String leerPropiedades( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @param navegador * @param sitio * @param ip * @param so * @return * returns boolean */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorInicio/agregarRegistroRequest", output = "http://Servicios/PublicadorInicio/agregarRegistroResponse") public boolean agregarRegistro( @WebParam(name = "ip", partName = "ip") String ip, @WebParam(name = "navegador", partName = "navegador") String navegador, @WebParam(name = "sitio", partName = "sitio") String sitio, @WebParam(name = "SO", partName = "SO") String so); /** * * @return * returns servicios.DtListConsultaPropuesta * @throws Exception_Exception */ @WebMethod @WebResult(partName = "return") @Action(input = "http://Servicios/PublicadorInicio/getDtPropuestasRequest", output = "http://Servicios/PublicadorInicio/getDtPropuestasResponse", fault = { @FaultAction(className = Exception_Exception.class, value = "http://Servicios/PublicadorInicio/getDtPropuestas/Fault/Exception") }) public DtListConsultaPropuesta getDtPropuestas() throws Exception_Exception ; } <file_sep>/web/classes/servicios/DtNickTitProp.java package servicios; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para dtNickTitProp complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="dtNickTitProp"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Titulo" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Proponente" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "dtNickTitProp", propOrder = { "titulo", "proponente" }) public class DtNickTitProp { @XmlElement(name = "Titulo") protected String titulo; @XmlElement(name = "Proponente") protected String proponente; /** * Obtiene el valor de la propiedad titulo. * * @return * possible object is * {@link String } * */ public String getTitulo() { return titulo; } /** * Define el valor de la propiedad titulo. * * @param value * allowed object is * {@link String } * */ public void setTitulo(String value) { this.titulo = value; } /** * Obtiene el valor de la propiedad proponente. * * @return * possible object is * {@link String } * */ public String getProponente() { return proponente; } /** * Define el valor de la propiedad proponente. * * @param value * allowed object is * {@link String } * */ public void setProponente(String value) { this.proponente = value; } }
0fdce991f71313bb86773111df59ff74238dc86f
[ "Java", "INI" ]
10
Java
isma4102/Culturarte_Web_SitioMovil
a4b463a6e9598d604399a9bfe4e47cda08fd4c7e
55be5e045b3a5511abe16e17d69f56e3f53492db
refs/heads/master
<repo_name>kinosas/LeetCode<file_sep>/1.TwoSum/TwoSum.cpp class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> ret; int i=0, j=nums.size()-1; vector<int> tmp(nums); sort(tmp.begin(), tmp.end()); while(i < j){ if(tmp[i]+tmp[j] < target){ i++; } else if(tmp[i]+tmp[j] == target){ int x=0; int p,q; while(x < nums.size()) if(nums[x] == tmp[i]){ p = x; break; } else{ x++; } x = nums.size()-1; while(x >= 0) if(nums[x] == tmp[j]){ q = x; break; } else{ x--; } ret.push_back(p<q?p:q); ret.push_back(p>q?p:q); return ret; } else{ j--; } } } };<file_sep>/README.md # LeetCode解题 文件夹是题目编号和名字,里面的.cpp是代码,思路和想法都写在.md中
375dea3a3dcfc401e81e7c36a52d4d3052c653d4
[ "Markdown", "C++" ]
2
C++
kinosas/LeetCode
2645cb4e03fa1358d0061154c85db1fa6d1e503d
683d88937b96d4db9f18a1745f6f497faca069a8
refs/heads/master
<repo_name>gruntjs-updater/grunt-jsonschema-amd-restclient-generator<file_sep>/Gruntfile.js /* * grunt-jsonschema-amd-restclient-generator * https://github.com/geobricks/grunt-jsonschema-amd-restclient-generator * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. */ (function () { 'use strict'; /*global module*/ module.exports = function (grunt) { /* Project configuration. */ grunt.initConfig({ /* Plugin configuration. */ jsonschema_amd_restclient_generator: { custom_options: { options: { base_url: 'http://fenixapps2.fao.org/api/v1.0/', output_name: 'RESTClient', output_folder: 'src/js', useQ: true } } } }); /* Actually load this plugin's task(s). */ grunt.loadTasks('tasks'); /* Test task. */ grunt.registerTask('default', ['jsonschema_amd_restclient_generator']); }; }());
b6a965c9848893f2a1234bd162f79f761aaa6d86
[ "JavaScript" ]
1
JavaScript
gruntjs-updater/grunt-jsonschema-amd-restclient-generator
e36131f8bc3daf44f1a535f8e2321871ceeba0e4
569a9830b75a742bdee564f7a8c808436c1dd4fe