branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
##################
# CentOS nodes #
##################
# Ansible-Node01
config.vm.define "ansible-node01" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node01"
end
cfg.vm.host_name = "ansible-node01"
cfg.vm.network "public_network", ip: "192.168.25.111"
cfg.vm.network "forwarded_port", guest:22, host:60011, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
# Ansible-Node02
config.vm.define "ansible-node02" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node02"
end
cfg.vm.host_name = "ansible-node02"
cfg.vm.network "public_network", ip: "192.168.25.112"
cfg.vm.network "forwarded_port", guest:22, host:60012, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
# Ansible-Node03
config.vm.define "ansible-node03" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node03"
end
cfg.vm.host_name = "ansible-node03"
cfg.vm.network "public_network", ip: "192.168.25.113"
cfg.vm.network "forwarded_port", guest:22, host:60013, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
##################
# Ubuntu nodes #
##################
# Ansible-Node04
config.vm.define "ansible-node04" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node04"
end
cfg.vm.host_name = "ansible-node04"
cfg.vm.network "public_network", ip: "192.168.25.114"
cfg.vm.network "forwarded_port", guest:22, host:60014, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
# Ansible-Node05
config.vm.define "ansible-node05" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node05"
end
cfg.vm.host_name = "ansible-node05"
cfg.vm.network "public_network", ip: "192.168.25.115"
cfg.vm.network "forwarded_port", guest:22, host:60015, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
# Ansible-Node06
config.vm.define "ansible-node06" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node06"
end
cfg.vm.host_name = "ansible-node06"
cfg.vm.network "public_network", ip: "192.168.25.116"
cfg.vm.network "forwarded_port", guest:22, host:60016, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
##################
# Windows node #
##################
# Ansible-Node07
config.vm.define "ansible-node07" do |cfg|
cfg.vm.box = "sysnet4admin/Windows2016"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node07"
vb.customize ['modifyvm',:id,'--clipboard','bidirectional']
vb.gui = false
end
cfg.vm.host_name = "ansible-node07"
cfg.vm.network "public_network", ip: "192.168.25.117"
cfg.vm.network "forwarded_port", guest:22, host:60017, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", inline: "netsh advfirewall set allprofiles state off"
end
##################
# Ansible Server #
##################
config.vm.define "ansible-server" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Server"
end
cfg.vm.host_name = "ansible-server"
cfg.vm.network "public_network", ip: "192.168.25.110"
cfg.vm.network "forwarded_port", guest: 22, host: 60010, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", inline: "yum install ansible -y"
cfg.vm.provision "file", source: "ansible_env_ready.yml",
destination: "ansible_env_ready.yml"
cfg.vm.provision "shell", inline: "ansible-playbook ansible_env_ready.yml"
cfg.vm.provision "shell", inline: "ansible-playbook vimrc.yml"
cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false
cfg.vm.provision "shell", inline: "ansible-playbook nginx_install.yml"
end
end
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
##################
# CentOS nodes #
##################
# Ansible-node101
config.vm.define "ansible-node101" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node101"
end
cfg.vm.host_name = "ansible-node101"
cfg.vm.network "public_network", ip: "192.168.25.101"
cfg.vm.network "forwarded_port", guest:22, host:60101, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
# Ansible-node102
config.vm.define "ansible-node102" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-node102"
end
cfg.vm.host_name = "ansible-node102"
cfg.vm.network "public_network", ip: "192.168.25.102"
cfg.vm.network "forwarded_port", guest:22, host:60102, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
# Ansible-Node03
config.vm.define "ansible-node103" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node103"
end
cfg.vm.host_name = "ansible-node103"
cfg.vm.network "public_network", ip: "192.168.25.103"
cfg.vm.network "forwarded_port", guest:22, host:60103, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", path: "bash_ssh_conf_4_CentOS.sh"
end
##################
# Ubuntu nodes #
##################
# Ansible-node201
config.vm.define "ansible-node201" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-node201"
end
cfg.vm.host_name = "ansible-node201"
cfg.vm.network "public_network", ip: "192.168.25.201"
cfg.vm.network "forwarded_port", guest:22, host:60201, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
# Ansible-node202
config.vm.define "ansible-node202" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-node202"
end
cfg.vm.host_name = "ansible-node202"
cfg.vm.network "public_network", ip: "192.168.25.202"
cfg.vm.network "forwarded_port", guest:22, host:60202, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
# Ansible-Node203
config.vm.define "ansible-node203" do |cfg|
cfg.vm.box = "ubuntu/trusty64"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node203"
end
cfg.vm.host_name = "ansible-node203"
cfg.vm.network "public_network", ip: "192.168.25.203"
cfg.vm.network "forwarded_port", guest:22, host:60203, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
end
##################
# Ansible Server #
##################
config.vm.define "ansible-server" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Server"
end
cfg.vm.host_name = "ansible-server"
cfg.vm.network "public_network", ip: "192.168.25.10"
cfg.vm.network "forwarded_port", guest: 22, host: 60010, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", inline: "yum install epel-release -y"
cfg.vm.provision "shell", inline: "yum install ansible -y"
cfg.vm.provision "file", source: "ansible_env_ready.yml", destination: "ansible_env_ready.yml"
cfg.vm.provision "shell", inline: "ansible-playbook ansible_env_ready.yml"
cfg.vm.provision "file", source: "vimrc.yml", destination: "vimrc.yml"
cfg.vm.provision "shell", inline: "ansible-playbook vimrc.yml", privileged: false
cfg.vm.provision "file", source: "auto_pass.yml", destination: "auto_pass.yml"
cfg.vm.provision "shell", inline: "ansible-playbook auto_pass.yml", privileged: false
end
end
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
##################
# CentOS nodes #
##################
# Ansible-node101
config.vm.define "ansible-node101" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Node101"
end
cfg.vm.host_name = "ansible-node101"
# cfg.vm.network "public_network",bridge:"eth0",ip:"192.168.2.211",netmask:"255.255.255.192"
# cfg.vm.network "public_network",ip:"192.168.2.211",netmask:"255.255.255.192"
cfg.vm.network "private_network",ip:"10.10.2.211",netmask:"255.255.255.192"
cfg.vm.network "forwarded_port",guest:22,host:60101,auto_correct:true,id:"ssh"
cfg.vm.synced_folder "../data","/vagrant",disabled:true
cfg.vm.provision "shell",inline:"yum install net-tools -y"
cfg.vm.provision "shell",path:"bash_ssh_conf_4_CentOS.sh"
end
##################
# Ansible Server #
##################
config.vm.define "ansible-server" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Server"
end
cfg.vm.host_name = "ansible-server"
# cfg.vm.network "public_network", ip:"192.168.2.231", netmask:"255.255.255.192"
cfg.vm.network "public_network", bridge: "eth0", ip: "192.168.2.231", netmask: "255.255.255.192"
# cfg.vm.network "public_network", :bridge => "Microsoft Hyper-V Network Adapter #2", type: "static", ip: "192.168.2.10"
cfg.vm.network "forwarded_port", guest: 22, host: 60010, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", inline: "yum install epel-release -y"
cfg.vm.provision "shell", inline: "yum install ansible -y"
cfg.vm.provision "file", source: "ansible_env_ready.yml", destination: "ansible_env_ready.yml"
cfg.vm.provision "shell", inline: "ansible-playbook ansible_env_ready.yml"
cfg.vm.provision "file", source: "vimrc.yml", destination: "vimrc.yml"
cfg.vm.provision "shell", inline: "ansible-playbook vimrc.yml", privileged: false
cfg.vm.provision "file", source: "auto_pass.yml", destination: "auto_pass.yml"
cfg.vm.provision "shell", inline: "ansible-playbook auto_pass.yml", privileged: false
end
end
<file_sep>#! /usr/bin/env bash
#ssh key Generate
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.151
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.152
<file_sep>#! /usr/bin/env bash
#ssh key Generate
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.161
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.162
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.163
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.164
<file_sep>#! /usr/bin/env bash
#ssh key Generate
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.111
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.112
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.113
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.114
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.115
sshpass -p vagrant ssh -T -o StrictHostKeyChecking=no vagrant@192.168.25.116
<file_sep># -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
#============#
# VyOS Nodes #
#============#
# Ansible-VyOS01
config.vm.define "ansible-vyos01" do |vy|
vy.vm.box = "sysnet4admin/VyOS"
vy.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-VyOS01"
end
vy.vm.host_name = "ansible-vyos01"
vy.vm.network "public_network", ip: "192.168.25.151"
vy.vm.network "forwarded_port", guest:22, host:60051, auto_correct: true, id: "ssh"
vy.vm.network "private_network", virtualbox__intnet: "eth2", auto_config: false
vy.vm.network "private_network", virtualbox__intnet: "eth3", auto_config: false
vy.vm.synced_folder "../data", "/vagrant", disabled: true
vy.vbguest.auto_update = false
end
# Ansible-VyOS02
config.vm.define "ansible-vyos02" do |vy|
vy.vm.box = "sysnet4admin/VyOS"
vy.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-VyOS02"
end
vy.vm.host_name = "ansible-vyos02"
vy.vm.network "public_network", ip: "192.168.25.152"
vy.vm.network "forwarded_port", guest:22, host:60052, auto_correct: true, id: "ssh"
vy.vm.network "private_network", virtualbox__intnet: "eth2", auto_config: false
vy.vm.network "private_network", virtualbox__intnet: "eth3", auto_config: false
vy.vm.synced_folder "../data", "/vagrant", disabled: true
vy.vbguest.auto_update = false
end
##################
# Ansible Server #
##################
config.vm.define "ansible-server" do |cfg|
cfg.vm.box = "centos/7"
cfg.vm.provider "virtualbox" do |vb|
vb.name = "Ansible-Server"
end
cfg.vm.host_name = "ansible-server"
cfg.vm.network "public_network", ip: "192.168.25.110"
cfg.vm.network "forwarded_port", guest: 22, host: 60010, auto_correct: true, id: "ssh"
cfg.vm.synced_folder "../data", "/vagrant", disabled: true
cfg.vm.provision "shell", inline: "yum install ansible -y"
cfg.vm.provision "file", source: "ansible_env_ready.yml", destination: "ansible_env_ready.yml"
cfg.vm.provision "file", source: "vimrc.yml", destination: "vimrc.yml"
cfg.vm.provision "shell", inline: "ansible-playbook ansible_env_ready.yml"
cfg.vm.provision "shell", inline: "ansible-playbook vimrc.yml"
cfg.vm.provision "shell", path: "add_ssh_auth.sh", privileged: false
end
end
|
bec358722fda08013d53644ba6c79652e2e0dbcf
|
[
"Ruby",
"Shell"
] | 7
|
Ruby
|
20eung/ansible
|
6b2104ce9ee3c82f4279f99b26e51014924f8171
|
f11be6f735b480fd268f02853a5fa9724505fa0b
|
refs/heads/master
|
<file_sep>'use-strict'
class Questions {
constructor (db) {
this.db = db
this.ref = this.db.ref('/')
this.collection = this.ref.child('questions')
}
async create (data, user) {
const ask = {
...data
}
ask.owner = user
const question = this.collection.push()
question.set(ask)
return question.key
}
async getLast (amount) {
const query = await this.collection.limitToLast(amount).once('value')
const data = query.val()
return data
}
}
module.exports = Questions
<file_sep># APIHapi
This is a project to learn hapi
<file_sep>'use strict'
const Questions = require('../models/index').questions
async function home (req, h) {
let data
try {
data = await Questions.getLast(10)
} catch (e) {
console.error(e)
}
return h.view('index', {
title: 'Home',
user: req.state.user,
questions: data
})
}
function register (req, h) {
if (req.state.user) {
return h.redirect('/')
}
return h.view('register', {
title: 'Register',
user: req.state.user
})
}
function login (req, h) {
if (req.state.user) {
return h.redirect('/')
}
return h.view('login', {
title: 'Login',
user: req.state.user
})
}
function notFound (req, h) {
return h.view('404', {}, { layout: 'error-layout' }).code(404)
}
function fileNotFound (req, h) {
const response = req.response
if (response.isBoom && response.output.statusCode === 404) {
return h.view('404', {}, { layout: 'error-layout' }).code(404)
}
return h.continue
}
function ask (req, h) {
if (!req.state.user) {
return h.redirect('/login')
}
return h.view('ask', {
title: 'Crear pregunta',
user: req.state.user
})
}
module.exports = {
home,
register,
login,
ask,
notFound,
fileNotFound
}
<file_sep>'use strict'
const Hapi = require('@hapi/hapi')
const Inert = require('@hapi/inert')
const Vision = require('@hapi/vision')
const Handlebars = require('handlebars')
const Path = require('path')
const Routes = require('./routes')
const Site = require('./controllers/site.js')
// Configurar el servidor de nuestra aplicación. En un contenedor (Docker) si marca error colocar 0.0.0.0 (todos)
const server = Hapi.server({
port: process.env.PORT || 4000,
host: 'localhost',
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')
}
}
})
// Definicion de función para inicializar el proyecto. Internamete hay tareas asincronas
async function init () {
// Arrancar el servidor de HapiJS, se considera una tarea asincrona.
try {
await server.register(Inert)
await server.register(Vision)
// Configurar el servidor para el envio de cookies (nombreCookie, opciones)
// https://hapi.dev/tutorials/cookies/?lang=en_US
// tiempo de vida de la cookie (en milisegundos)
// localhost no es seguro
// codificación de la cookie
server.state('user', {
// Time to live
// 1000 = 1 seg, 60= 1min, 60=1hr, 24=1dia, 7=1semana
ttl: 1000 * 60 * 60 * 24 * 7,
// Propiedad para saber si es segura
isSecure: process.env.NODE_ENV === 'prod',
encoding: 'base64json'
})
server.views({
engines: { // --- hapi puede usar diferentes engines
hbs: Handlebars // --- asociamos el plugin al tipo de archivos
},
relativeTo: __dirname, // --- para que las vistas las busque fuera de /public
path: 'views', // --- directorio donde colocaremos las vistas dentro de nuestro proyecto
layout: true, // --- indica que usaremos layouts
layoutPath: 'views' // --- ubicación de los layouts
})
server.ext('onPreResponse', Site.fileNotFound)
server.route(Routes)
await server.start()
} catch (e) {
console.log(e)
// Salir de nodeJS con un código de error (1), 0 es un código de exito
process.exit(1)
}
console.log(`Servidor lanzado en ${server.info.uri}`)
}
// Manejadores de errores
process.on('unhandledRejection', error => {
console.error('unhandledRejection', error.message, error)
})
process.on('unhandledException', error => {
console.error('unhandledException', error.message, error)
})
// Inicializar el proyecto
init()
<file_sep>'use strict'
// Información de configuración proporcionada en
// NombreProyectoFirebase -> configuración del proyecto -> cuentas del servicio
const Firebase = require('firebase-admin')
const serviceAccount = require('../config/firebase.json')
// Importar modulos (CLASES) correspondientes a los modelos de la base de datos
const Users = require('./users')
const Questions = require('./questions')
Firebase.initializeApp({
credential: Firebase.credential.cert(serviceAccount),
databaseURL: 'https://hapidb-a2d42.firebaseio.com/'
})
// Crear una instancia (referencia) de la base de datos
const db = Firebase.database()
// Recordar que los modelos esperan como parámetro una referencia hacia la base de datos.
// Exportamos las instancias de los modelos listas para ser invocadas en los controladores correspondientes
module.exports = {
users: new Users(db),
questions: new Questions(db)
}
<file_sep>'use strict'
const Joi = require('@hapi/joi')
const Site = require('./controllers/site')
const User = require('./controllers/user')
const Question = require('./controllers/question')
module.exports = [
// Definición de rutas (indicar el método HTTP, URL y controlador de ruta)
{
method: 'GET',
path: '/',
handler: Site.home
},
{
method: 'GET',
path: '/register',
handler: Site.register
},
{
method: 'GET',
path: '/login',
handler: Site.login
},
{
method: 'GET',
path: '/logout',
handler: User.logout
},
{
method: 'GET',
path: '/ask',
handler: Site.ask
},
{
method: 'POST',
path: '/create-user',
options: {
validate: {
payload: Joi.object({
name: Joi.string().required().min(10),
email: Joi.string().email().required(),
password: Joi.string().required().min(6)
}),
failAction: User.failValidation
}
},
handler: User.createUser
},
{
method: 'POST',
path: '/validate-user',
options: {
validate: {
payload: Joi.object({
email: Joi.string().email().required(),
password: Joi.string().required().min(6)
}),
failAction: User.failValidation
}
},
handler: User.validateUser
},
{
method: 'POST',
path: '/create-question',
options: {
validate: {
payload: Joi.object({
title: Joi.string().required(),
description: Joi.string().required()
}),
failAction: User.failValidation
}
},
handler: Question.createQuestion
},
{
method: 'GET',
path: '/assets/{param*}',
handler: {
directory: {
path: '.',
index: ['index.html']
}
}
},
{
method: ['GET', 'POST'],
path: '/{any*}',
handler: Site.notFound
}
]
<file_sep>'use-strict'
/**
* Clase compatible con Firebase Data Base
*/
const Bcrypt = require('bcrypt')
class Users {
// La clase recibe una referencia hacia la base de datos de firebase donde se guardará la información
constructor (db) {
this.db = db
this.ref = this.db.ref('/')
this.collection = this.ref.child('users')
}
// Método de clase para guardar un usuario en la base de datos de firebase
async create (data) {
// Destructuro el objeto con el payload enviado. Ya que Hapi lo decora con un prototipo null que no es compatible con Firebase
const User = {
...data
}
// Se genera una contraseña encriptada a partir de la proporcionada. this.constructor llama a la clase, ya que el método encrypt es estático
User.password = await this.constructor.encrypt(User.password)
const newUser = this.collection.push(User)
newUser.set(User)
// Retornamos el id del usuario
return newUser.key
}
async validate (data) {
// Ordenar la colección por email, consultar el usuario por su email (no me interesa escuchar cambios en la data, por ello once)
const userQuery = await this.collection.orderByChild('email').equalTo(data.email).once('value')
// Obtengo el objeto con los resultados de mi consulta {objId: {}, objId: {}, objId: {}}
const userFound = userQuery.val()
if (userFound) {
// Obtengo un arreglo con los ids de los documentos que forman parte de los resultados de mi busqueda. Me interesa quedarme con el elemento (ObjectId) del primer documento, mas no con el arreglo
const userId = Object.keys(userFound)[0]
// comparar si las contraseñas son correctas {documentoResultado.objectId.password}
const passwdRight = await Bcrypt.compare(data.password, userFound[userId].password)
const result = (passwdRight) ? userFound[userId] : false
return result
}
return false
}
// Método estático asincrono para la encriptacion de contraseñas
static async encrypt (passwd) {
const saltRounds = 10
const hashedPassword = await Bcrypt.hash(passwd, saltRounds)
return hashedPassword
}
}
module.exports = Users
<file_sep>'use strict'
const Questions = require('../models/index').questions
async function createQuestion (req, h) {
let result
try {
result = await Questions.create(req.payload, req.state.user)
console.log(`Pregunta creada con el ID ${result}`)
} catch (error) {
console.error(`Ocurrio un error: ${error}`)
return h.view('ask', {
title: 'Crear pregunta',
error: 'Problemas creando la pregunta'
}).code(500).takeover()
}
return h.response(`Pregunta creada con el ID ${result}`)
}
module.exports = {
createQuestion
}
|
0f0247190c81ef67fe67a8feb4c447dcd498bc32
|
[
"JavaScript",
"Markdown"
] | 8
|
JavaScript
|
betonajera9/APIHapi
|
782583bc7b6a008c02e346f37abc9c552665ba05
|
4b274d46962ee7b19111050c2838c7a374edcf23
|
refs/heads/master
|
<file_sep>/*JAVASCRIPT
Ao clicar no botão de enviar do formulário deve aparecer os dados digitados abaixo do formulário.
Cada vez que clica no botão aparecem os dados (acumulativo).
Na apresentação dos dados utilize o efeito de expandir e ocultar os dados do contato.
Os scripts devem estar em um arquivo externo.
*/
var count = 0;
function insertParada () {
// var e = document.createElement("p");
// e.value= "texto";
// document.getElementById('trashArea').innerHTML = "texto";
var name, email, purpouse, text, checkbox, date;
name = document.getElementById("nameForm").value;
email = document.getElementById("emailForm").value;
purpouse = document.getElementById("optForm").ELEMENT_NODE;
text = document.getElementById("textForm").value;
if(name == "" || email == "" || purpouse == 0 || text == ""){
return;
}
checkbox = document.getElementById("checkboxForm").value;
date = new Date();
purpouseString = translatePurpouse(purpouse);
checkboxString = translateCheckbox(checkbox);
// tam = document.getElementById('trashArea').length;
// tam = tam*3 + 1;
var newChild = "\<p><a id=\"elementChildDate\" href='#trashArea' onclick=\"hideStuff('elementResult"+count+"', this)\">Contato de : "+date+"</a></p>\n\
<div id='elementResult"+count+"' class=\"elementResult\">\n\
<div class=\"elementDivTittle\" >\n\
<p class=\"elementResultTitles\" ><span>Nome: </span>"+name+"</p>\n\
<p class=\"elementResultTitles\" ><span>E-mail: </span>"+email+"</p>\n\
<p class=\"elementResultTitles\" ><span>Propósito: </span>"+purpouseString+"</p>\n\
</div>\n\
<div class=\"elementDivMessage\" >\n\
<p class=\"elementResultMessage\" ><span>Mensagem: </span>"+text+"</p>\n\
</div>\n\
<p class=\"elementResultTitles elementCheckbox\" ><span>Acept: </span>"+checkboxString+"</p>\n\
</div><hr>";
document.getElementById('trashArea').innerHTML += newChild;
// document.getElementsByClassName('trashArea').innerHTML += newChild; It don't works on Firefox
count++
}
function translatePurpouse (value) {
var s;
switch (value){
case 1:
s = "Contato Profissional";
break;
case 2:
s = "Consultoria";
break;
case 3:
s = "Palestra";
break;
case 4:
s = "Cumê Água";
break;
default:
break;
}
return s;
}
function translateCheckbox (value) {
return (value )? "true" : "false";
}
function showStuff(id, me) {
document.getElementById(id).style.display = 'block';
var attr = "hideStuff('"+id+"', this); return false;";
me.setAttribute("onclick", attr);
}
function hideStuff(id, me) {
document.getElementById(id).style.display = 'none';
var attr = "showStuff('"+id+"', this); return false;";
me.setAttribute("onclick", attr);
}
|
7363c2088a33d91f306db0609adce74ebb4aacd8
|
[
"JavaScript"
] | 1
|
JavaScript
|
Marinofull/aulasLabWeb
|
dca632dbf2a8633d1e8d577f3d305d5b257694be
|
af0d6ef47f0f37eccec98c528f02098b5ae7837d
|
refs/heads/master
|
<repo_name>patelvishu05/PythonURLShortener<file_sep>/app.py
#!/usr/bin/python3
import json
from os import path
class ShortURL:
def __init__(self,debug):
self.shortenedUrls = {}
self.visitCounter = {}
self.debug = False
if path.exists("data.json"):
with open("data.json") as f:
self.shortenedUrls = json.load(f)
if path.exists("counter.json"):
with open("counter.json") as f:
self.visitCounter = json.load(f)
def menu(self):
choice = 0
# Visually help the user choose the menu
while int(choice) != 3:
print("\nChoose from the following :")
print("1. Shorten URL")
print("2. Visit URL")
print("3. Exit")
choice = input("> : ")
# If the user chooses 1
# have the menu direct them to the menu where they can
# shorten the URL based on the desired name they would like to use
if int(choice) == 1:
desiredUrl = input("Please enter the URL you want to shorten: ")
shortUrl = input("Please enter the desired short url: ")
self.shorten(desiredUrl, shortUrl)
# If the user chooses 2
# Have the menu irect them to the page where they can enter the short URL
# which will take them to the intended URL with the full URL format
if int(choice) == 2:
visitUrl = input("Please enter the url you want to visit: ")
self.visit(visitUrl)
def shorten(self, desiredUrl, shortUrl):
if "http://localhost/"+shortUrl in self.shortenedUrls.keys():
print("Duplicate URL. A URL with that name already exists")
return("Duplicate")
self.shortenedUrls["http://localhost/"+shortUrl] = desiredUrl
self.visitCounter["http://localhost/"+shortUrl] = 0
# write the existing data for shortened URLs to the json file
# so that it persists after the termination of the program
writer = json.dumps(self.shortenedUrls)
f = open("data.json","w")
f.write(writer)
f.close()
# write the existing data for Metric counts of URL visits to the json file
# so that it persists after the termination of the program
writer = json.dumps(self.visitCounter)
f = open("counter.json","w")
f.write(writer)
f.close()
return "http://localhost/"+shortUrl
# The below function will help decrypt the shortened URL back
# to its original full format and return it so they the browser
# can visit the intended URL
def visit(self, visitUrl):
if visitUrl in self.shortenedUrls.keys():
tempCounter = self.visitCounter[visitUrl] + 1
self.visitCounter[visitUrl] = tempCounter
else:
return "302"
# write the existing data for Metric counts of URL visits to the json file
# so that it persists after the termination of the program
writer = json.dumps(self.visitCounter)
f = open("counter.json","w")
f.write(writer)
f.close()
return self.shortenedUrls[visitUrl]
def countsVisited(self,website):
return int(self.visitCounter[website])
# Execute the App from the menu for the URL Shortener to begin
urlObj = ShortURL(True)
# if urlObj.debug is True:
urlObj.menu()<file_sep>/test.py
#!/usr/bin/python3
from app import *
import unittest
class MyTest(unittest.TestCase):
urlObj = ShortURL(False)
def test_shortURLTest(self):
self.assertEqual(urlObj.shorten("www.samsung.com","sam"),"http://localhost/sam")
def test_visitURLTest(self):
self.assertEqual(urlObj.visit("http://localhost/sam"),"www.samsung.com")
def test_counterURLTest(self):
self.assertEqual(urlObj.countsVisited("http://localhost/sam"),2)
def test_dummyURLTest(self):
self.assertEqual(urlObj.visit("http://localhost/dummy"),"302")
def test_duplicateURLTest(self):
self.assertEqual(urlObj.shorten("www.tmobile.com","tmob"),"Duplicate")
if __name__ == '__main__':
unittest.main()<file_sep>/simple.py
#!/usr/bin/python3
import json
from os import path
class ShortURL:
def __init__(self):
if path.exists("data.json"):
with open("data.json") as f:
shortenedUrls = json.load(f)
visitCounter = {}
if path.exists("counter.json"):
with open("counter.json") as f:
visitCounter = json.load(f)
choice = 0
while int(choice) != 3:
print("\nChoose from the following :")
print("1. Shorten URL")
print("2. Visit URL")
print("3. Exit")
choice = input("> : ")
if int(choice) == 1:
desiredUrl = input("Please enter the URL you want to shorten: ")
shortUrl = input("Please enter the desired short url: ")
shortenedUrls["http://localhost/"+shortUrl] = desiredUrl
visitCounter["http://localhost/"+shortUrl] = 0
writer = json.dumps(shortenedUrls)
f = open("data.json","w")
f.write(writer)
writer = json.dumps(visitCounter)
f = open("counter.json","w")
f.write(writer)
f.close()
if int(choice) == 2:
visitUrl = input("Please enter the url you want to visit: ")
print(shortenedUrls[visitUrl])
tempCounter = visitCounter[visitUrl] + 1
visitCounter[visitUrl] = tempCounter
writer = json.dumps(visitCounter)
f = open("counter.json","w")
f.write(writer)
f.close()
|
f3ece3b906144090ec8550ff84ab5cad8f5050d3
|
[
"Python"
] | 3
|
Python
|
patelvishu05/PythonURLShortener
|
63b8b264694bddf799b9d15bfce6c61f8066a3b8
|
9263ecc89f082dffcf3eff26c2f500ad1fb51b8c
|
refs/heads/master
|
<repo_name>leochen4891/hadoop-benchmarker<file_sep>/hadoopBenchmarker.py
import argparse
import ConfigParser
import subprocess
#create a parser which evaluate command line arguments.
def createArgumentParser():
usage = './bin/hadoop-benchmarker.sh --config-file <configFileName>'
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('--config-file','-c' , dest='configFile', required=True)
return parser
# configuration for tests are loaded. The configuration files are expected to be
# in conf directory
def loadConfiguration(configFile):
config = ConfigParser.ConfigParser(allow_no_value=True)
config.optionxform = str
config.readfp(open('conf/'+configFile))
return config
#This function extracts the argument of the command.
def getToolArguments(config, testName):
args = []
options = config.options(testName)
for option in options:
if (option != 'tool') & (option != 'command'):
args.append(option)
value = config.get(testName, option)
if (option.startswith('--')):
continue
args.append(value)
return args
#This function validates the commands and tools and raise an error, command
# and tool are not in allowed list
def constructCommand(config, testName):
process = []
allowedCommands = ['hbase']
allowedTools = ['pe']
command = config.get(testName, 'command')
if command not in allowedCommands:
raise Exception('command: '+command + ' is not supported')
tool = config.get(testName, 'tool')
if tool not in allowedTools:
raise Exception('tool: '+tool + ' is not supported')
process.append(command)
process.append(tool)
process.extend(getToolArguments(config, testName))
print process
return process
def executeCommand(process):
p = subprocess.Popen(process)
result = p.communicate()
print '####RESULT OF TEST####'
print result
def main():
print 'Starting Tests....'
argParser = createArgumentParser()
args = argParser.parse_args()
print 'configFile='+args.configFile
testRunConfig = loadConfiguration(args.configFile)
testNames = testRunConfig.sections()
print testNames
for testName in testNames:
try:
process = constructCommand(testRunConfig, testName)
executeCommand(process)
except Exception as exp:
print 'Test: '+testName +' is failed ', exp
if __name__ == '__main__':
main()
|
8907cd5925531c293e836dddf6ac936b16ba087d
|
[
"Python"
] | 1
|
Python
|
leochen4891/hadoop-benchmarker
|
16328e2f9f0508c4e7010e07c2f06306a41f156b
|
cfdf06e54c6ef4c28ce8350f5f36abba28b62356
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package substats;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author Keith
*/
public class DataGatherer {
Client client;
WebTarget freqWebTarget;
Gson gson;
URI frequencyUri;
public DataGatherer(URI uri) {
gson = new Gson();
frequencyUri = uri;
}
public void setupClient() {
//Set up the client
client = ClientBuilder.newClient();
//Create WebTarget for the service to query
freqWebTarget = client.target(frequencyUri);
}
public PlatformData getPlatformData(String name) {
List<String> queries = new ArrayList<>();
queries.add(name);
for (String s : queries) {
//Add on the specific resource we want to target, deriving from original target
WebTarget platformTarget = freqWebTarget.path(s);
//Build an invication to send the actual GET command
Invocation.Builder invocationBuilder = platformTarget.request(MediaType.APPLICATION_JSON);
invocationBuilder.header("some-header", "true");
//Directly query and get my response (Synchronously)
long start = System.currentTimeMillis();
Response response = invocationBuilder.get();
long end = System.currentTimeMillis();
System.out.println(response.getStatus());
String json = response.readEntity(String.class);
System.out.println(json);
System.out.println("Time (ms): " + (end - start));
Map<String, String> result = new Gson().fromJson(json, Map.class);
JsonObject jsonRoot = gson.fromJson(json, JsonObject.class);
String nameResult = jsonRoot.get("platformClass").getAsString();
String typeResult = jsonRoot.get("type").getAsString();
List<String> countryResult = gson.fromJson(jsonRoot.get("countries"), ArrayList.class);
List<Integer> freqsResult = gson.fromJson(jsonRoot.get("frequencies"), new TypeToken<ArrayList<Integer>>(){}.getType());
int bladesResult = jsonRoot.get("numBlades").getAsInt();
int tpkResult = jsonRoot.get("turnsPerKnot").getAsInt();
PlatformData p = new PlatformData(nameResult,
typeResult,
countryResult,
freqsResult,
bladesResult,
tpkResult);
return p;
}
return null;
}
}
<file_sep>apply plugin: 'java'
sourceCompatibility = '1.8'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
// NetBeans will automatically add "run" and "debug" tasks relying on the
// "mainClass" property. You may however define the property prior executing
// tasks by passing a "-PmainClass=<QUALIFIED_CLASS_NAME>" argument.
//
// Note however, that you may define your own "run" and "debug" task if you
// prefer. In this case NetBeans will not add these tasks but you may rely on
// your own implementation.
if (!hasProperty('mainClass')) {
ext.mainClass = 'substats.SubStats'
}
repositories {
mavenCentral()
// You may define additional repositories, or even remove "mavenCentral()".
// Read more about repositories here:
// http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:repositories
}
dependencies {
// TODO: Add dependencies here ...
// You can read more about how to add dependency here:
// http://www.gradle.org/docs/current/userguide/dependency_management.html#sec:how_to_declare_your_dependencies
testCompile group: 'junit', name: 'junit', version: '4.10'
compile "com.google.code.gson:gson:2.8.2"
compile group: 'javax', name: 'javaee-api', version:'8.0'
compile group: 'org.glassfish.jersey.core', name: 'jersey-client', version: '2.26'
compile group: 'org.glassfish.jersey.core', name: 'jersey-common', version: '2.26'
compile group: 'org.glassfish.jersey.inject', name: 'jersey-hk2', version: '2.26'
compile group: 'org.glassfish.tyrus.bundles', name: 'tyrus-standalone-client', version: '1.12'
//compile group: 'org.glassfish.tyrus', name: 'tyrus-client', version: '1.12'
//compile group: 'org.glassfish.tyrus', name: 'tyrus-container-grizzly', version: '1.12'
}
<file_sep>rootProject.name = 'SubStats'
|
a1af3ca5253cd5d0fe3718b3ca261719f361778b
|
[
"Java",
"Gradle"
] | 3
|
Java
|
KeithDeRuiter/SubStats
|
a936d93299d5b7ca45be002eee9ecac52da8dd47
|
7f474081fb7cedbd1d79672f40c944de42c2f64d
|
refs/heads/master
|
<repo_name>khris22/fewpjs-js-fundamentals-scope-lab-online-web-pt-061019<file_sep>/index.js
const animal = "dog"
// const is also block-scoped restricts over-writing variables. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. const variables also cannot be declared a without assigning its (constant) value
function myAnimal() {
return animal
}
function yourAnimal() {
let animal = 'cat'
// const animal = 'cat'
// How can we make sure that this function
// and the above function both pass?
// P.S.: You can't just hard-code 'cat' below
return animal
}
// let variables are block-scoped, and allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used
function add2(n) {
const two = 2
return n + two
// Feel free to move things around!
}
|
7039ffef0243bbf010ac1eb89d47a76bb84f95cd
|
[
"JavaScript"
] | 1
|
JavaScript
|
khris22/fewpjs-js-fundamentals-scope-lab-online-web-pt-061019
|
c5ba091accc5ae1e22abb219c83b09fb59d7bcc6
|
84fb1621f72d4a6aa2a135c7c9d6545a4c966689
|
refs/heads/master
|
<file_sep>
import sys
import cdsw
import pandas as pd
import numpy as np
import pickle
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.model_selection import cross_val_score
# == for Testing ==
features = ['stunting_2cat','agemonr1','chsexr1','agegapr1','momeduyrsr1','hhsizer1','wi_newr1']
args={"stunting_2cat":"1",
"agemonr1":"49",
"chsexr1":"1",
"agegapr1":"6",
"momeduyrsr1":"5",
"hhsizer1":"5",
"wi_newr1":"0.11"}
#==Main Funtion==
def PredictFunc(args):
# Load Data
filtArgs={key:[args[key]] for key in features}
data=pd.DataFrame.from_dict(filtArgs)
# Load Model
with open('HeightPredictor.pickle','rb') as handle:
mdl=pickle.load(handle)
model=pickle.loads(mdl)
# Get Prediction
prediction=model.predict(data)
#Return Prediction
return prediction<file_sep># Brazil-Pelotas
Estimating Costs of Child Stunting on Business/Private Sectors in LMICs
<file_sep>dill==0.3.1.1
lime==0.1.1.36
scikit-learn==0.24.2
xlrd==1.2.0
pandas==0.25.1
numpy==1.17.2
flask==1.1.2
|
22b98534834b0ab586a34af43765dfcc4eb3376a
|
[
"Markdown",
"Python",
"Text"
] | 3
|
Python
|
rramraj08/Brazil-Pelotas
|
1b9a3221b920c2d10d06f47c57e4f9a423bde1dd
|
752c562b46c450fda78590cfdd4467a364904ce0
|
refs/heads/master
|
<file_sep># grpc-rest-springboot<file_sep>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.google.protobuf.gradle.*
plugins {
id("org.springframework.boot") version "2.2.2.RELEASE"
id("io.spring.dependency-management") version "1.0.8.RELEASE"
id("com.google.protobuf") version "0.8.11"
kotlin("jvm") version "1.3.61"
kotlin("plugin.spring") version "1.3.61"
}
group = "com.instructure.bridge.ngilbert.hackweek"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("com.google.protobuf:protobuf-java:3.6.1")
implementation("io.grpc:grpc-netty-shaded:1.26.0")
implementation("io.grpc:grpc-protobuf:1.26.0")
implementation("io.grpc:grpc-stub:1.26.0")
implementation("io.github.lognet:grpc-spring-boot-starter:3.5.1")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}
protobuf {
generatedFilesBaseDir = "$projectDir/src/main/java/generated"
protoc {
// The artifact spec for the Protobuf Compiler
artifact = "com.google.protobuf:protoc:3.6.1"
}
plugins {
// Optional: an artifact spec for a protoc plugin, with "grpc" as
// the identifier, which can be referred to in the "plugins"
// container of the "generateProtoTasks" closure.
id("grpc") {
artifact = "io.grpc:protoc-gen-grpc-java:1.15.1"
}
}
generateProtoTasks {
ofSourceSet("main").forEach {
it.plugins {
// Apply the "grpc" plugin whose spec is defined above, without options.
id("grpc") {
outputSubDir = ""
}
}
}
}
}
<file_sep>package com.instructure.bridge.ngilbert.hackweek.demo.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.converter.protobuf.ProtobufJsonFormatHttpMessageConverter
@Configuration
class ApiConfig {
@Bean
fun protobufHttpMessageConverter(): ProtobufJsonFormatHttpMessageConverter {
return ProtobufJsonFormatHttpMessageConverter()
}
}<file_sep>package com.instructure.bridge.ngilbert.hackweek.demo.controller
import com.instructure.bridge.ngilbert.hackweek.demo.DemoServiceGrpc
import org.lognet.springboot.grpc.GRpcService
@GRpcService
class GrpcController : DemoServiceGrpc.DemoServiceImplBase() {
@Override
fun msg(): String {
return "I'm alive"
}
}
<file_sep>package com.instructure.bridge.ngilbert.hackweek.demo.controller
import com.instructure.bridge.ngilbert.hackweek.demo.MsgResponse
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
@RestController
@RequestMapping("/api/hackweek")
class RestController {
@GetMapping("/")
fun msg(): String {
return "I'm alive"
}
@GetMapping(value = ["/protobuf"], produces = [PROTOBUF_MEDIA_TYPE_VALUE])
fun protobufMsg(): ResponseEntity<MsgResponse> = ResponseEntity.ok(
MsgResponse
.newBuilder()
.setMessage("Hello, Yes, I am alive.")
.build()
)
companion object {
const val PROTOBUF_MEDIA_TYPE_VALUE = "application/x-protobuf"
}
}
<file_sep>package com.instructure.bridge.ngilbert.hackweek.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.http.converter.protobuf.ProtobufHttpMessageConverter
@SpringBootApplication
class GrpcRestDemoApplication
/*{
@Bean
fun protobufHttpMessageConverter(): ProtobufHttpMessageConverter = ProtobufHttpMessageConverter()
}*/
fun main(args: Array<String>) {
runApplication<GrpcRestDemoApplication>(*args)
}
|
7560d6dc8034fcbdf569988bc21e5f0910962b0d
|
[
"Markdown",
"Kotlin"
] | 6
|
Markdown
|
ngilbert-inst/grpc-rest-springboot
|
a34a78bac6bd8f26b10fe48e99ccd373183182a4
|
0957f56c44506bb5671c0f528e22689e0f364fd9
|
refs/heads/master
|
<file_sep>/*import * as rc522 from 'rc522-c7z';
export class Rc552{
rc522((serial) => {
console.log(serial);
});
}*/
/*var rfid=require('node-rfid');
rfid.read(function(err,result){
if(err) console.log("Sorry, some hardware error occurred"); //some kind of hardware/wire error
console.log(result); //print rfid tag UID
});*/<file_sep>import { Component, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'The Locker Management';
ngAfterViewInit(){
var s=document.createElement("script");
s.type="text/javascript";
s.innerHTML="alert('done');"; //inline script
//s.src="../../node_modules/rc522-rfid/main.js"; //external script
s.src="../assets/rc522-rfid/main.js"; //external script
}
}
|
52ce0e827432d991611faeefc271ddb475fd974a
|
[
"TypeScript"
] | 2
|
TypeScript
|
pepcs0530/TheLocker
|
fa5884911a8c70ff72d0a010a7ca317881383055
|
d4500768c1b999c021fb58ca66fcdf95f2f43ffe
|
refs/heads/master
|
<repo_name>jstf9673/fedPro-cli<file_sep>/readme.md
# gulp自动化项目
## 使用
```bash
git clone ......
npm i
//test
gulp server
```bash
<!-- webpack多页配置
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
entry: {
p1: "./page1",
p2: "./page2",
p3: "./page3",
ap1: "./admin/page1",
ap2: "./admin/page2"
},
output: {
filename: "[name].js"
},
plugins: [
new CommonsChunkPlugin("admin-commons.js", ["ap1", "ap2"]),
new CommonsChunkPlugin("commons.js", ["p1", "p2", "admin-commons.js"])
]
};
//在不同页面用<script>标签引入如下js:
// page1.html: commons.js, p1.js
// page2.html: commons.js, p2.js
// page3.html: p3.js
// admin-page1.html: commons.js, admin-commons.js, ap1.js
// admin-page2.html: commons.js, admin-commons.js, ap2.js
-->
<file_sep>/dist/js/demos.js
"use strict";module.export=function(){console.log("hello webpack")};
|
52df3160595a5f902d9f57291c547cbeaec07b08
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
jstf9673/fedPro-cli
|
e90d2fa2478908dd1ddf483901c71ef830f84156
|
ffda134dcc73c441db15c17cf92afc3d8fbc2f25
|
refs/heads/master
|
<repo_name>HTGAzureX1212/rslint<file_sep>/crates/rslint_lsp/src/provider/actions.rs
//! Code action support, for example, actions to automatically fix an error.
use crate::core::session::Session;
use anyhow::Result;
use rslint_errors::Severity;
use std::ops::Range;
use tower_lsp::lsp_types::{
CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams, CodeActionResponse,
TextEdit, WorkspaceEdit,
};
pub async fn actions(
session: &Session,
params: CodeActionParams,
) -> Result<Option<CodeActionResponse>> {
let document = session.get_document(¶ms.text_document.uri).await?;
if document
.parse
.parser_diagnostics()
.iter()
.any(|d| d.severity == Severity::Error)
&& !session.config.read().unwrap().incorrect_file_autofixes
{
return Ok(None);
}
let action_range =
rslint_errors::lsp::range_to_byte_span(&document.files, document.file_id, ¶ms.range)?;
let mut actions = vec![];
for res in document.rule_results.iter() {
if let Some(fixer) = res.fixer.as_ref() {
let has_match = res.diagnostics.iter().any(|d| {
rslint_errors::lsp::range_to_byte_span(&document.files, document.file_id, &d.range)
.ok()
== Some(action_range.to_owned())
});
if has_match {
let edits = fixer
.indels
.iter()
.filter_map(|i| {
Some(TextEdit {
range: rslint_errors::lsp::byte_span_to_range(
&document.files,
document.file_id,
Range::<usize>::from(i.delete),
)
.ok()?,
new_text: i.insert.to_owned(),
})
})
.collect::<Vec<_>>();
let edit = Some(WorkspaceEdit::new(
vec![(params.text_document.uri.to_owned(), edits)]
.into_iter()
.collect(),
));
let diagnostics = Some(
res.diagnostics
.iter()
.filter(|d| {
rslint_errors::lsp::range_to_byte_span(
&document.files,
document.file_id,
&d.range,
)
.ok()
== Some(action_range.to_owned())
})
.cloned()
.collect(),
);
let action = CodeAction {
title: "Fix this issue".to_string(),
edit,
is_preferred: Some(true),
diagnostics,
kind: Some(CodeActionKind::QUICKFIX),
..Default::default()
};
actions.push(CodeActionOrCommand::CodeAction(action));
}
}
}
Ok(Some(actions))
}
<file_sep>/crates/rslint_core/src/directives/commands.rs
//! All directive command implementations.
use super::{Component, ComponentKind, Instruction};
use crate::CstRule;
use rslint_lexer::SyntaxKind;
use rslint_parser::SyntaxNode;
use std::ops::Range;
/// All different directive commands.
#[derive(Debug, Clone)]
pub enum Command {
/// Ignore all rules in the whole file.
IgnoreFile,
/// Ignore only a subset of rules in the whole file.
IgnoreFileRules(Vec<Box<dyn CstRule>>),
/// Ignore all rules for a specific `SyntaxNode`.
IgnoreNode(SyntaxNode),
/// Ignore only a subset of rules for a specific `SyntaxNode`.
IgnoreNodeRules(SyntaxNode, Vec<Box<dyn CstRule>>),
/// Ignore all rules in a range of lines.
IgnoreUntil(Range<usize>),
/// Ignore only a subset of rules in a range of lines.
IgnoreUntilRules(Range<usize>, Vec<Box<dyn CstRule>>),
}
impl Command {
pub fn instructions() -> Box<[Box<[Instruction]>]> {
use Instruction::*;
vec![vec![
CommandName("ignore"),
Repetition(Box::new(RuleName), SyntaxKind::COMMA),
Optional(vec![
Literal("until"),
Either(Box::new(Literal("eof")), Box::new(Number)),
]),
]
.into_boxed_slice()]
.into_boxed_slice()
}
/// Takes a parsed `Directive`, and tries to convert it into a `Command`.
pub fn parse(components: &[Component], line: usize, node: Option<SyntaxNode>) -> Option<Self> {
let Component { kind, .. } = components.first()?;
let name = match kind {
ComponentKind::CommandName(name) => name.as_str(),
_ => return None,
};
match name {
"ignore" => parse_ignore_command(components, line, node),
_ => None,
}
}
}
fn parse_ignore_command(
components: &[Component],
line: usize,
node: Option<SyntaxNode>,
) -> Option<Command> {
// TODO: We can probably warn the user about directives like this:
// ```
// // rslint-ignore no-empty until eof
// if (true) {}
// ```
// because this will be parsed as a `IgnoreNodeRules` and thus
// ignores the `until eof` part, which may not be obivous when looking at it.
if let Some(rules) = components.get(1).and_then(|c| c.kind.repetition()) {
let rules = rules.iter().flat_map(|c| c.kind.rule()).collect::<Vec<_>>();
if components
.get(2)
.and_then(|c| c.kind.literal())
.map_or(false, |l| l == "until")
{
match components.get(3).map(|c| &c.kind)? {
ComponentKind::Literal("eof") => {
Some(Command::IgnoreUntilRules(line..usize::max_value(), rules))
}
ComponentKind::Number(val) => {
Some(Command::IgnoreUntilRules(line..line + *val as usize, rules))
}
_ => None,
}
} else if let Some(node) = node {
Some(Command::IgnoreNodeRules(node, rules))
} else {
Some(Command::IgnoreFileRules(rules))
}
} else if components
.get(1)
.and_then(|c| c.kind.literal())
.map_or(false, |l| l == "until")
{
match components.get(2).map(|c| &c.kind)? {
ComponentKind::Literal("eof") => Some(Command::IgnoreUntil(line..usize::max_value())),
ComponentKind::Number(val) => Some(Command::IgnoreUntil(line..line + *val as usize)),
_ => None,
}
} else if let Some(node) = node {
Some(Command::IgnoreNode(node))
} else {
Some(Command::IgnoreFile)
}
}
<file_sep>/crates/rslint_core/benches/bench.rs
use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};
use rslint_core::CstRuleStore;
use rslint_lexer::Lexer;
use rslint_parser::{parse_text, Syntax};
const ENGINE_262_URL: &str = "https://engine262.js.org/engine262/engine262.js";
fn parse(source: &str) {
parse_text(source, 0);
}
fn tokenize(source: &str) {
Lexer::from_str(source, 0).for_each(drop);
}
fn lint(source: &str) {
let _ = rslint_core::lint_file(
0,
source,
Syntax::default(),
&CstRuleStore::new().builtins(),
false,
);
}
fn bench_source(c: &mut Criterion, name: &str, source: &str) {
let mut group = c.benchmark_group(name);
group.sample_size(10);
group.throughput(Throughput::Bytes(source.len() as u64));
group.bench_function("tokenize", |b| b.iter(|| tokenize(black_box(&source))));
group.bench_function("parse", |b| b.iter(|| parse(black_box(&source))));
group.bench_function("lint", |b| b.iter(|| lint(black_box(&source))));
group.finish();
}
fn engine262(c: &mut Criterion) {
let source = ureq::get(ENGINE_262_URL)
.call()
.into_string()
.expect("failed to get engine262 source code");
bench_source(c, "engine262", &source);
}
criterion_group!(benches, engine262);
criterion_main!(benches);
<file_sep>/crates/rslint_lsp/src/provider/completion.rs
//! Autocompletion support for directives
use crate::core::session::Session;
use anyhow::Result;
use rslint_core::{
directives::ComponentKind, directives::Instruction, util::levenshtein_distance, CstRuleStore,
DirectiveErrorKind,
};
use tower_lsp::lsp_types::{
CompletionItem, CompletionItemKind, CompletionParams, CompletionResponse, Documentation,
MarkupContent, MarkupKind,
};
pub async fn complete(
session: &Session,
params: CompletionParams,
) -> Result<Option<CompletionResponse>> {
let document = session
.get_document(¶ms.text_document_position.text_document.uri)
.await?;
if !document.directive_errors.is_empty() {
let loc = rslint_errors::lsp::position_to_byte_index(
&document.files,
document.file_id,
¶ms.text_document_position.position,
)?;
if let Some(err) = document
.directive_errors
.iter()
.find(|x| x.range().end == loc)
{
return Ok(Some(match err.kind {
DirectiveErrorKind::ExpectedCommand => completion_list(
vec![(
"rslint-ignore",
ComponentKind::CommandName("ignore".into())
.documentation()
.unwrap(),
)],
false,
),
DirectiveErrorKind::InvalidRule => {
let wrong_text = &document.text[err.range()];
let available_rules = CstRuleStore::new().builtins().rules.into_iter();
let mut list = available_rules
.map(|r| (r.name(), r.docs()))
.collect::<Vec<_>>();
list.sort_by(|(l_name, _), (r_name, _)| {
levenshtein_distance(wrong_text, l_name)
.cmp(&levenshtein_distance(wrong_text, r_name))
});
completion_list(list, true)
}
DirectiveErrorKind::ExpectedNotFound(Instruction::RuleName) => completion_list(
CstRuleStore::new()
.builtins()
.rules
.into_iter()
.map(|x| (x.name(), x.docs()))
.collect(),
true,
),
DirectiveErrorKind::InvalidCommandName => {
let available = vec![(
"rslint-ignore",
ComponentKind::CommandName("ignore".into())
.documentation()
.unwrap(),
)];
completion_list(available, false)
}
_ => return Ok(None),
}));
}
}
Ok(None)
}
fn completion_list(items: Vec<(impl ToString, impl ToString)>, rules: bool) -> CompletionResponse {
CompletionResponse::Array(
items
.into_iter()
.map(|(label, detail)| {
string_to_completion_item(label.to_string(), detail.to_string(), rules)
})
.collect(),
)
}
fn string_to_completion_item(label: String, detail: String, rules: bool) -> CompletionItem {
if rules {
let mut split = detail.split('\n');
let header = split.next().unwrap_or("");
let body = split.next().unwrap_or("").to_string();
let documentation = Some(Documentation::MarkupContent(MarkupContent {
kind: MarkupKind::Markdown,
value: body,
}));
CompletionItem {
documentation,
detail: Some(header.to_string()),
kind: Some(CompletionItemKind::Field),
label,
..Default::default()
}
} else {
CompletionItem {
label,
detail: Some(detail),
kind: Some(CompletionItemKind::Field),
..Default::default()
}
}
}
<file_sep>/crates/rslint_cli/src/flame.rs
//! Implementation of our own wrapper around the `FlameLayer`.
use std::{
io::{BufWriter, Write},
sync::mpsc::{Receiver, Sender},
};
use tracing_flame::FlameLayer;
use tracing_subscriber::Registry;
const FLAMEGRAPH_FILE: &str = "rslint.svg";
type Writer = BufWriter<ChannelWriter>;
pub fn flame() -> (FlameGuard, FlameLayer<Registry, Writer>) {
let (tx, rx) = std::sync::mpsc::channel();
let write = BufWriter::new(ChannelWriter(Some(tx)));
let flame = FlameLayer::new(write);
let guard = FlameGuard {
recv: rx,
inner: flame.flush_on_drop(),
};
(guard, flame)
}
/// The guard will try to receive all bytes and then convert them
/// to a flamegraph which will then be outputted to a file if it is dropped.
pub struct FlameGuard {
inner: tracing_flame::FlushGuard<Writer>,
recv: Receiver<Vec<u8>>,
}
impl Drop for FlameGuard {
fn drop(&mut self) {
self.inner.flush().expect("failed to flush flame layer");
let string = self
.recv
.iter()
.filter_map(|buf| String::from_utf8(buf).ok())
.collect::<String>();
let out = std::fs::File::create(FLAMEGRAPH_FILE).expect("failed to open flamegraph file");
let mut out = BufWriter::new(out);
inferno::flamegraph::from_lines(&mut Default::default(), string.lines(), &mut out)
.expect("failed to generate flamegraph");
}
}
/// A `Write` implementation that will send the received bytes through a channel.
///
/// It's recommended to wrap this type into a `BufWriter`.
pub struct ChannelWriter(Option<Sender<Vec<u8>>>);
impl Write for ChannelWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if let Some(sender) = &self.0 {
sender
.send(buf.to_vec())
.expect("failed to send data through channel");
Ok(buf.len())
} else {
Ok(0)
}
}
fn flush(&mut self) -> std::io::Result<()> {
let _ = self.0.take();
Ok(())
}
}
|
d9c2197cedc6d846f1c8315e44df3d98feebc1ac
|
[
"Rust"
] | 5
|
Rust
|
HTGAzureX1212/rslint
|
7659fdfe9e89d3e9a403a1b280547b74bbabca07
|
e8207fd8ff7605079265c127cb212f62bf7da3c8
|
refs/heads/master
|
<file_sep>from schematics.exceptions import DataError
from transmute_core.function import TransmuteFunction
from swagger_schema import (Operation, Schema, PathParameter, BodyParameter)
from transmute_core.context import default_context
class DjaioTransmuteFunction(TransmuteFunction):
"""
Class based on TransmuteFunction.
For our realies we rebuild it's main functions and adapt it
for djaio and ClassBasedView architecture
"""
BODY_METHODS = ('post', 'put')
def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = ('application/json',)
return Operation({
"summary": self.description,
"description": self.description,
"consumes": consumes,
"produces": produces,
"parameters": self._get_swagger_parameters(context),
"responses": {
"200": {
"description": "successful operation",
"schema": Schema({
"title": "success",
"properties": {
"success": {"type": "boolean"},
"result":{"type":"array"},
"errors":{"type":"array"}
},
"required": ["success"]
})
},
}
})
def get_swagger_schema(self):
"""
function try to build swagger-json by Scheme Model.
If dict of data has wrong format in raise an error.
:return Scheme object:
"""
scheme = self.raw_func.swagger_dict
try:
return Schema(scheme)
except DataError:
raise ValueError('Error! Your YAML description is not valid! See the docs here: {docs}\n{scheme}'.
format(scheme=scheme, docs='http://swagger.io/specification/#schemaObject'))
def _get_swagger_parameters(self, context=default_context):
parameters = []
if self.raw_func.__name__ in self.BODY_METHODS:
# Create here a constant field for methods of post and put
# and if there is a database schema for it then initialize
body = BodyParameter({
"name": "body",
"required": True,
"description": "Json, Array or other data to POST or PUT",
})
schema = self.get_swagger_schema()
if schema:
body.schema = schema
parameters.append(body)
# Create body IN params
for name, details in self.parameters.body.items():
parameters.append(BodyParameter({
"name": name,
"description":'body_param: {}'.format(name),
"required": details.default is None,
"schema": context.serializers.to_json_schema(details.type),
}))
# Create path IN params
for name, details in self.parameters.path.items():
parameters.append(PathParameter({
"name": name,
"description":name,
"required": True,
"type": context.serializers.to_json_schema(details.type) if details else 'string',
}))
# Not used for this moment
# for name, details in self.parameters.query.items():
# parameters.append(QueryParameter({
# "name": name,
# "required": details.default is None,
# "type": "string"
# }))
#
# for name, details in self.parameters.header.items():
# parameters.append(HeaderParameter({
# "name": name,
# "required": details.default is None,
# "type": "string"
# }))
return parameters<file_sep># djaio-swagger
Battery for djaio
More documentation at
# ToDo: Add documentation here
<file_sep>import yaml
import re
from transmute_core import default_context
from transmute_core import describe
from aiohttp.web import UrlDispatcher
from djaio_swagger.transmute import DjaioTransmuteFunction
class TransmuteUrlDispatcher(UrlDispatcher):
"""
A UrlDispatcher which instruments the add_route function to
collect swagger spec data from transmuted functions.
"""
def __init__(self, *args, context=default_context, **kwargs):
super().__init__()
self._transmute_context = context
self._swagger = {}
def get_swagger_dict(self, cls):
"""
Get YAML description from class __doc__ and transform it to python dict
"""
doc = cls.__doc__
if not doc:
return {}
try:
start = str("<start_YAML>")
end = str("<end_YAML>")
doc = re.search('%s(.*)%s' % (start, end), doc, re.DOTALL).group(1)
doc = yaml.load(doc) if doc else {}
# ToDo Need to add logging here!
except ValueError:
pass
except AttributeError:
pass
else:
pass
return doc
def add_transmute_route(self, *args):
methods, paths, cls, name = args
swagger_dict = self.get_swagger_dict(cls)
if type(methods) == str:
methods=[methods]
for method in methods:
obj = cls.__dict__.get(method.lower(), None)
obj.swagger_dict = swagger_dict
if obj:
describe(methods=methods, paths=paths)(obj)
transmute_func = DjaioTransmuteFunction(obj, args_not_from_request=["request"])
swagger_path = transmute_func.get_swagger_path(self._transmute_context)
for p in transmute_func.paths:
# add to swagger
if p not in self._swagger:
self._swagger[p] = swagger_path
else:
for mth, definition in swagger_path.items():
if mth == method.lower():
setattr(self._swagger[p], mth, definition)
# add to aiohttp
# ATTENTION!!! WE ADD a Class to aiohttp, not class-method!
aiohttp_path = self._convert_to_aiohttp_path(p)
resource = self.add_resource(aiohttp_path)
resource.add_route(method, cls)
def swagger_paths(self):
"""
returns a swagger Paths object representing all transmute
functions registered.
"""
return self._swagger
@staticmethod
def _convert_to_aiohttp_path(path):
""" convert a transmute path to one supported by aiohttp. """
return path
|
2aab6d043b14c45a852801afbdcf00369ddab25d
|
[
"Python",
"reStructuredText"
] | 3
|
Python
|
alex-vento/djaio-swagger
|
99d3472f712c5c26538dfb2ff8a331cc8b48302b
|
a3ede1bf573023fee9fe28b5ad97db358ee441c2
|
refs/heads/master
|
<repo_name>DukeOwlington/lkm_port_redirector<file_sep>/nf_pr.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netfilter_ipv4.h>
#include <linux/skbuff.h>
#include <linux/udp.h>
#include <linux/tcp.h>
#include <linux/ip.h>
#define SOURCE_PORT 7777
#define DESTINATION_PORT 7778
MODULE_LICENSE("GPL");
MODULE_AUTHOR("MadMax");
MODULE_DESCRIPTION("A simple Linux port redirector");
MODULE_VERSION("0.1");
/* This function to be called by hook */
static unsigned int hook_func(void *priv, struct sk_buff *skb,
const struct nf_hook_state *state) {
struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb);
struct udphdr *udp_header;
struct tcphdr *tcp_header;
switch (ip_header->protocol) {
case IPPROTO_UDP:
udp_header = (struct udphdr *)skb_transport_header(skb);
if (udp_header->dest == htons(SOURCE_PORT)) {
udp_header->dest = htons(DESTINATION_PORT);
printk(KERN_INFO "UDP dest port has been redirected.\n");
}
case IPPROTO_TCP:
tcp_header = (struct tcphdr *)skb_transport_header(skb);
if (tcp_header->dest == htons(SOURCE_PORT)) {
tcp_header->dest = htons(DESTINATION_PORT);
printk(KERN_INFO "TCP dest port has been redirected.\n");
}
}
return NF_ACCEPT;
}
static struct nf_hook_ops nfho = {
.hook = hook_func, /* hook function */
.hooknum = NF_INET_PRE_ROUTING, /* watch all packets */
.pf = PF_INET, /* ip protocol family */
.priority = NF_IP_PRI_FIRST, /* high priority */
};
static int __init init_nf(void) {
printk(KERN_INFO "Register netfilter module.\n");
nf_register_hook(&nfho);
return 0;
}
static void __exit exit_nf(void) {
printk(KERN_INFO "Unregister netfilter module.\n");
nf_unregister_hook(&nfho);
}
module_init(init_nf);
module_exit(exit_nf);
|
e4df20817c7847883e918ad09564344f36c20387
|
[
"C"
] | 1
|
C
|
DukeOwlington/lkm_port_redirector
|
e6ecf966437f4fe0f9602f68ac24bbc7427fa23f
|
cf17b405130e3e49cc108a7244cd6b657e1b03b4
|
refs/heads/master
|
<file_sep>from django.shortcuts import render
from django.contrib.auth.decorators import login_required
import random
from django.http import HttpResponse
from .models import Emp_Leaves,Emp_basic_update,Hr_Data,Finance_Login,Emp_account,Emp_Data,Company,Finance_Data,Hr_Login,Emp_Login
from.forms import Hr_LoginForm
# Create your views here.
def home(request):
return render(request, 'home.html')
@login_required
def mylogin(request):
if request.user.is_authenticated:
qs = Company.objects.all()
if request.user.is_hr:
return render(request,'hr.html',{"qs":qs})
elif request.user.is_finance:
return render(request,'finance.html',{"qs":qs})
elif request.user.is_emp:
return render(request,'emp.html',{"qs":qs})
def hr_pwd_chg(request):
ot="12345" #random.randint(100000,999999)
#request.session["pwd"]=request.POST["t1"]
request.session["details"]=request.POST
request.session["otp"]=ot
return render(request, "hr_otpvalid.html")
def hr_otpvalid(request):
reeotp=request.POST["ot"]
print(request.session["otp"])
if request.session["otp"]==reeotp:
data=request.session["details"]
hd=Hr_Data(hrid=data['hrid'],fname=data['fname'],lname=data['lname'],
email=data['email'],mobno=data['mobno'],comapny_id=data['cmpid'])
hd.save()
hrlg=Hr_Login(hrid=data['hrid'],company_id=data['cmpid'],uname=data["uname"],pwd=data["pwd"])
hrlg.save()
return render(request,"hr_home.html")
else:
return render(request, "hr_update.html")
def hr_login(request):
if request.method == "POST":
MyLoginForm = Hr_LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Hr_Login.objects.filter(uname=un,pwd=pw)
if not dbuser:
return HttpResponse('login faild')
else:
for p in dbuser:
request.session["cmpid"] = p.company_id
return render(request,'hr_dashbord.html')
else:
form = Hr_LoginForm()
return render(request,'hr_login.html',
{'form': form})
def emp_pwd_chg(request):
ot="12345" #random.randint(100000,999999)
#request.session["pwd"]=request.POST["t1"]
request.session["details"]=request.POST
request.session["otp"]=ot
return render(request, "emp_otpvalid.html")
def emp_otpvalid(request):
reeotp=request.POST["ot"]
print(request.session["otp"])
if request.session["otp"]==reeotp:
data=request.session["details"]
hd=Emp_Data(empid=data['empid'],fname=data['fname'],lname=data['lname'],
email=data['email'],mobno=data['mobno'],company_id=data['cmpid'])
hd.save()
hrlg=Emp_Login(empid=data['empid'],company_id=data['cmpid'],uname=data["uname"],pwd=data["pwd"])
hrlg.save()
return render(request,"emp_home.html")
else:
return render(request, "emp_update.html")
def emp_login(request):
if request.method == "POST":
MyLoginForm = Hr_LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Emp_Login.objects.filter(uname=un,pwd=pw)
if not dbuser:
return HttpResponse('login faild')
else:
for p in dbuser:
request.session["empid"] = p.empid
request.session["cmpid"] = p.company_id
return render(request,'emp_dashbord.html')
else:
form = Hr_LoginForm()
return render(request,'emp_login.html',
{'form': form})
def accountupdate(request):
if request.method=="GET":
return render(request,'accountupdate.html')
else:
ea=Emp_account(acno=int(request.POST['accno']),
bankname=request.POST['bankname'],
ifsccode=request.POST['ifsccode'],
branchname=request.POST['branchname'],
empid=request.session['empid'],cmpid=request.session['cmpid'])
ea.save()
return render(request,'emp_dashbord.html')
def finance_pwd_chg(request):
ot="12345" #random.randint(100000,999999)
#request.session["pwd"]=request.POST["t1"]
request.session["details"]=request.POST
request.session["otp"]=ot
return render(request, "finance_otpvalid.html")
def finance_otpvalid(request):
reeotp=request.POST["ot"]
print(request.session["otp"])
if request.session["otp"]==reeotp:
data=request.session["details"]
hd=Finance_Data(acid=data['acid'],fname=data['fname'],lname=data['lname'],
email=data['email'],mobno=data['mobno'],
company_id=data['cmpid'])
hd.save()
hrlg = Finance_Login(acid=data['acid'], company_id=data['cmpid'], uname=data["uname"], pwd=data["pwd"])
hrlg.save()
return render(request,"finance_home.html")
else:
return render(request, "finance_update.html")
def finance_login(request):
if request.method == "POST":
MyLoginForm = Hr_LoginForm(request.POST)
if MyLoginForm.is_valid():
un =MyLoginForm.cleaned_data['user']
pw=MyLoginForm.cleaned_data['pwd']
dbuser = Finance_Login.objects.filter(uname=un,pwd=pw)
if not dbuser:
return HttpResponse('login faild')
else:
rec=dbuser.get(uname=un)
request.session["cmpid"]=rec.company_id
return render(request,'finance_dashbord.html')
else:
form = Hr_LoginForm()
return render(request,'finance_login.html',
{'form': form})
def empdetails(request):
emps=Emp_account.objects.filter(cmpid=request.session['cmpid'])
return render(request,"empdetails.html",{"emps":emps})
def activate(request):
myacno= request.GET["acno"]
Emp_account.objects.filter(acno=myacno).update(isactivated=True)
emps = Emp_account.objects.filter(cmpid=request.session['cmpid'])
return render(request, "empdetails.html", {"emps": emps})
def empactive(request):
emps = Emp_account.objects.filter(cmpid=request.session['cmpid'],isactivated=True)
return render(request, "empactive.html", {"emps": emps})
def empbasicupdate(request):
emps = Emp_account.objects.filter(cmpid=request.session['cmpid'],isactivated=True)
return render(request, "empbasicupdate.html", {"emps": emps})
def basicpay(request):
if request.method=="GET":
empid=request.GET["empid"]
return render(request,'basicupdate.html',{'empiid':empid})
else:
empid1=request.POST['eid']
bpay1=float(request.POST['bpay'])
dbuser=Emp_Data.objects.filter(empid=empid1)
rec=dbuser.get(empid=empid1)
cid=rec.company_id
e1=Emp_basic_update(empid=empid1,basicpay=bpay1,comapny_id=cid)
e1.save()
return render(request,'hr_dashbord.html')
def empleavesupdate(request):
if request.method == "GET":
empid = request.GET["empid"]
return render(request,'leaves_update.html',{'empid':empid})
else:
empid1 = request.POST['eid']
tnwd1 = int(request.POST['tnwd'])
pl1 = int(request.POST['pl'])
npl1 = int(request.POST['npl'])
dbuser = Emp_Data.objects.filter(empid=empid1)
rec = dbuser.get(empid=empid1)
cid = rec.company_id
e1 = Emp_Leaves(empid=empid1,total_no_of_leaves=tnwd1,paid_leaves=pl1,non_paid_leaves=npl1, comapny_id=cid,)
e1.save()
return render(request, 'hr_dashbord.html')
|
127145571a96414634061ed3633d65a0ee4fad50
|
[
"Python"
] | 1
|
Python
|
NannapaneniPrasanth/Christmas
|
85758fad8797cf5f461b5412b157070ad227f666
|
ac1a17acfc90ebdfcea9b00c61627cb34fb21243
|
refs/heads/master
|
<file_sep>#include "ProcessesDialog.h"
wxBEGIN_EVENT_TABLE(ProcessesDialog, wxFrame)
EVT_BUTTON(1, onConfirmClicked)
EVT_BUTTON(2, onCancelClicked)
wxEND_EVENT_TABLE()
/*ProcessesDialog::ProcessesDialog(ProcessesDialog& other) // copy constructor
{
SetBackgroundColour(wxColour(232, 232, 232, 255));
this->confirm = other.confirm;
this->cancel = other.cancel;
this->process_list = other.process_list;
this->processesids = NULL;
//this->parentpanel = nullptr;
//printProcessses();
}*/
ProcessesDialog::ProcessesDialog(ScannerPanel& parent) :wxFrame(NULL, 8888, "Select Process", wxPoint(30, 30), wxSize(250, 300)) // constructor with a ScannerPanel
{
SetBackgroundColour(wxColour(232, 232, 232, 255));
confirm = new wxButton(this, 1, "Confirm", wxPoint(20, 220), wxDefaultSize);
cancel = new wxButton(this, 2, "Cancel", wxPoint(120, 220), wxDefaultSize);
this->process_list = new wxListBox(this, wxID_ANY, wxPoint(6, 10), wxSize(220, 200));
this->processesids = NULL;
this->parentpanel = &parent;
printProcessses();
}
/*ProcessesDialog& ProcessesDialog::operator=(const ProcessesDialog& other)
{
this->confirm = other.confirm;
this->cancel = other.cancel;
this->process_list = other.process_list;
this->processesids = other.processesids;
//this->parentpanel = other.parentpanel;
return *this;
}*/
void ProcessesDialog::printProcessses() // fix the issue of printing random ass name
{
DWORD processesid[1024];
DWORD read;
vector<string> tracker;
EnumProcesses(processesid, sizeof(processesid), &read);
int size = sizeof(processesid) / sizeof(DWORD);
this->processesids = new DWORD[size];
int lastvalid = -1;
for (int i = 0; i < size; i++)
{
char processname[1024] = "Unknown";
DWORD rights = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ;
HANDLE proc = OpenProcess(rights, false, processesid[i]);
if (proc == NULL)
{
auto error = GetLastError();
}
else
{
HMODULE hMod;
DWORD needed;
if (EnumProcessModules(proc, &hMod, sizeof(hMod), &needed))
{
GetModuleBaseNameA(proc, NULL, &processname[0], sizeof(processname) / sizeof(char));
string tmp = processname;
int found = tmp.find(".exe");
//if (found != string::npos && (lastvalid == -1 || tmp != tracker[lastvalid]))//keep in mind that all module with
//{//same name would occur together, so comparing with the last one would
//get to the result
this->process_list->AppendString(processname);
tracker.push_back(tmp);
this->processesids[lastvalid] = processesid[i];
lastvalid++;
//}
}
}
}
}
void ProcessesDialog::onCancelClicked(wxCommandEvent& evt)
{
this->Close();
evt.Skip();
}
ProcessesDialog::ProcessesDialog() :wxFrame(NULL, 8888, "Select Process", wxPoint(30, 30), wxSize(250, 300))
{
//initlizing the panel when the constructor is called
//move on with printing processes.
SetBackgroundColour(wxColour(232, 232, 232, 255));
confirm = new wxButton(this, 1, "Confirm", wxPoint(20, 220), wxDefaultSize);
cancel = new wxButton(this, 2, "Cancel", wxPoint(120, 220), wxDefaultSize);
this->process_list = new wxListBox(this, wxID_ANY, wxPoint(6, 10), wxSize(220, 200));
this->processesids = NULL;
//this->parentpanel = NULL;
printProcessses();
}
ProcessesDialog::~ProcessesDialog()
{
delete[] this->processesids;
//delete this->parentpanel;
//this->parentpanel = NULL;
this->processesids = NULL;
}<file_sep>#include "GUIMain.h"
wxIMPLEMENT_APP(GUIMain);
GUIMain::GUIMain()
{
}
GUIMain::~GUIMain()
{
}
bool GUIMain::OnInit()
{
SP = new ScannerPanel();
SP->Show();
return true;
}<file_sep>#pragma once
#ifndef GUIMAIN_H
#define GUIMAIN_H
#include "wx\wx.h"
#include "ScannerPanel.h"
//#include "..\Easy Engine\MemoryScanner.h"
class GUIMain:public wxApp
{
private:
ScannerPanel* SP;
public:
GUIMain();
~GUIMain();
virtual bool OnInit();
};
#endif
<file_sep>#pragma once
template<typename T>
int partition(int low, int high, T * target)
{
T pivot = target[low + (high - low) / 2];
bool done = false;
while (!done)
{
while (target[low] < pivot)
{
low++;
}
while (target[high] > pivot)
{
high--;
}
if (low >= high)
{
done = true;
}
else
{
T temp = target[low];
target[low] = target[high];
target[high] = temp;
low++;
high--;
}
}
return high; //returns the starting index for high partition;
}
/*****************************************************************
* Recursively compare the array values to the pivot value(mid of array) and by
* putting them in the correct partition, it sorts the array
* data: array of integers.
* low: index.
* high: index.
*****************************************************************/
template<typename T>
void quicksort(int low, int high, T& target) //target will be an array
{
if (low < high)
{
int last = partition(low, high, target);
quicksort(low, last, target);
quicksort(last + 1, high, target);
}
}<file_sep>#include "stdafx.h"
#include "InerCom.h"
InerCom::InerCom()
{
this->client = INVALID_SOCKET;
}
void InerCom::init()
{
WSADATA wsaData;
auto start_iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (start_iResult != 0) {
printf("WSAStartup failed: %d\n", start_iResult);
return;
}
struct addrinfo* result = NULL, * ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
auto iResult = getaddrinfo(NULL, PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return;
}
else
{
SOCKET listener = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (listener == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return;
}
printf("Sucessfully initialized socket\n");
auto bind_iResult = bind(listener, result->ai_addr, (int)result->ai_addrlen);
listen(listener, SOMAXCONN);
sockaddr_in client_ip;
int client_size = sizeof(client_ip);
this->client = accept(listener, (sockaddr*)&client_ip, &client_size);
//stop it from listning for now
closesocket(listener);
}
}
char* InerCom::recvData()
{
char buff[4096];
while (true)//set up time out later
{
memset(buff, 0, 4096);
int bytereceived = recv(this->client, buff, 4096, 0);
//send(client, buff, bytereceived + 1, 0);
if (bytereceived != 0)
{
return buff;
}
}
}
int InerCom::sendData(char* data, int size)
{
auto iResult = send(this->client, data, size + 1, 0);
if (iResult == SOCKET_ERROR)
{
printf("Error %d occured when sending data", iResult);
closesocket(this->client);
WSACleanup();
return -1;
}
return 0;
}<file_sep>#include "ScannerPanel.h"
wxBEGIN_EVENT_TABLE(ScannerPanel, wxFrame)
EVT_BUTTON(10000, onOpenProcessClicked)
EVT_BUTTON(10001, onFirstScanCliced)
EVT_BUTTON(10002, onSecondScanClicked)
wxEND_EVENT_TABLE()
ScannerPanel::ScannerPanel() :wxFrame(NULL, wxID_ANY, "Easy Engine Scanner", wxPoint(30,30), wxSize(800,600))
{
SetBackgroundColour(wxColour(232, 232, 232, 255));
openprocess = new wxButton(this, 10000, "Open process", wxPoint(25, 20), wxSize(80, 30));
listctrl = new wxDataViewListCtrl(this, wxID_ANY, wxPoint(20, 80), wxSize(350, 450));
firstscan = new wxButton(this, 10001, "First scan", wxPoint(500, 80), wxSize(80, 25));
nextscan = new wxButton(this, 10002, "Next scan", wxPoint(650, 80), wxSize(80, 25));
//dialog = NULL;
wxString choices[] = { "Int32", "Hex", "Float" };
valuetype = new wxComboBox(this, wxID_ANY, "Int32", wxPoint(600, 120), wxSize(80, 30), 3, choices, wxCB_DROPDOWN, wxDefaultValidator, "Value options");
targetvalue = new wxTextCtrl(this, wxID_ANY, "enter a value here", wxPoint(400, 220), wxSize(300, 20),
NULL);
scantype = NULL;
meaubar = new wxMenuBar();
tool_menu = new wxMenu();
tool_menu->Append(wxID_OPEN, "AI finder");
meaubar->Append(tool_menu, "Tools");
SetMenuBar(meaubar);
listctrl->AppendTextColumn("Value");
listctrl->AppendTextColumn("Address");
listctrl->AppendTextColumn("Previous value");
listctrl->SetClientSize(wxRect(wxPoint(50, 50), wxPoint(350, 450)));
}
ScannerPanel::ScannerPanel(ScannerPanel& parent)
{
this->procID = parent.procID; // for now, only thing needed is procID
}
ScannerPanel::~ScannerPanel()
{
}
string ScannerPanel::toUpperCase(string& original)
{
string convereted;
for (int i = 0; i < original.size(); i++)
{
char currentchar = original.at(i);
if (currentchar > 96 && currentchar < 123)
{
//ASCII difference
currentchar -= 32;
}
convereted += currentchar;
}
return convereted;
}
void ScannerPanel::printScannedResult(int type, MemoryScanner<int>* ms_int,
MemoryScanner<float>* ms_float)
{
if (((ms_int != NULL && ms_int->getSize() == 0) || (ms_float != NULL && ms_float->getSize() == 0)))
{
this->listctrl->ClearColumns();
this->listctrl->AppendTextColumn("Value");
this->listctrl->AppendTextColumn("Address");
this->listctrl->AppendTextColumn("Previous value");
return;
}
//this->listctrl->ClearColumns();
if (type == 0)
{
const MemoryScanner<int>::ScannerOutput* result = ms_int->getSCOU();
for (int i = 0; i < ms_int->getSize(); i++)
{
MemoryScanner<int>::ScannerOutput entry = result[i];
wxVector<wxVariant> data;
stringstream ss;
//converting int to hex
ss << std::hex << entry.address;
data.push_back(toUpperCase(ss.str()));
data.push_back(std::to_string(entry.value));
if (entry.changed)
{
data.push_back(std::to_string(entry.difference));
}
else
{
data.push_back(NULL);
}
this->listctrl->AppendItem(data);
data.clear();
}
}
else if (type == 1)
{
//hex
}
else
{
//float
const MemoryScanner<float>::ScannerOutput* result = ms_float->getSCOU();
for (int i = 0; i < ms_float->getSize(); i++)
{
MemoryScanner<float>::ScannerOutput entry = result[i];
wxVector<wxVariant> data;
stringstream ss;
//converting address(int) to hex
ss << std::hex << entry.address;
data.push_back(toUpperCase(ss.str()));
data.push_back(std::to_string(entry.value));
if (entry.changed)
{
data.push_back(std::to_string(entry.difference));
}
else
{
data.push_back(NULL);
}
this->listctrl->AppendItem(data);
data.clear();
}
}
}
void ScannerPanel::onSecondScanClicked(wxCommandEvent& evt)
{
if (this->ms == NULL)
{
return;
}
if (this->scantype == 0)
{
//int
int target;
string searchvalue = this->targetvalue->GetLineText(0);
stringstream convereter(searchvalue);
convereter >> target;
MemoryScanner<int>* scanner_cast = (MemoryScanner<int>*)this->ms;
scanner_cast->scanNext(target);
//ms = &scanner_cast;
printScannedResult(0, scanner_cast, NULL);
}
else if (this->scantype == 1)
{
//hex
}
else
{
//float
}
}
void ScannerPanel::onFirstScanCliced(wxCommandEvent& evt)
{
if (this->procID == NULL)//print a message box later
return;
int temp = this->valuetype->GetCurrentSelection();
this->scantype = temp;
string searchvalue = this->targetvalue->GetLineText(0);
stringstream converter(searchvalue);
if (temp == 0)
{
//int
this->ms = new MemoryScanner<int>(this->procID);//construct the object first, then give it to ms
MemoryScanner<int>* scanner_cast = (MemoryScanner<int>*)this->ms;
scanner_cast->init();
int target = 0;
converter >> target;
scanner_cast->firstScan(target);
printScannedResult(0, scanner_cast, NULL);
}
else if (temp == 1)
{
//hex
this->ms = new MemoryScanner<DWORD>(this->procID);
MemoryScanner<DWORD> scanner_cast = *((MemoryScanner<DWORD>*)this->ms);
float target = 0;
converter >> target;
scanner_cast.firstScan(target);
printScannedResult(0);
}
else
{
//float
this->ms = new MemoryScanner<float>(this->procID);
MemoryScanner<float>* scanner_cast = (MemoryScanner<float>*)this->ms;
float target = 0;
converter >> target;
scanner_cast->init();
scanner_cast->firstScan(target);
printScannedResult(2, NULL, scanner_cast);
}
evt.Skip();
}
void ScannerPanel::onOpenProcessClicked (wxCommandEvent& evt)
{
if (this->dialog->FindWindowById(8888) != NULL) // id is defined in ProcessesDialog.cpp
{
evt.Skip();
return;
}
this->dialog = new ProcessesDialog(*this);
this->dialog->Show();
evt.Skip();
}
ScannerPanel& ScannerPanel:: operator = (const ScannerPanel& other)
{
this->procID = other.procID;
return *this;
}
void ScannerPanel::updateProcID(int id)
{
this->procID = id;
}
void ProcessesDialog::onConfirmClicked(wxCommandEvent& evt) //this is calling a method of ScannerPanel
{//from ProcessesDialog.cpp but ScannerPanel is only forward declared there
// so in order to call the function, the function needs to be defined here so it has a definition of ScannePanel
int index = this->process_list->GetSelection();
//this referes to ProcessesDialog
//see https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c for reference
if (index != wxNOT_FOUND)
{
this->parentpanel->updateProcID(this->processesids[index - 1]);
evt.Skip();
this->Hide();
}
else
{
//Print out ID index is not in the list
evt.Skip();
}
}<file_sep>// Easy Engin.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MemoryScanner.h"
#include <iostream>
int main()
{
MemoryScanner<float> * ms = new MemoryScanner<float>(8228);
ms->init();
ScannerInput SCIN(0, 0);
ms->firstScan(100);
//ms->scanNext(100);
cout << "Address Values" << endl;
for (int i = 0; i < ms->getSize(); i++)
{
cout << ms->getSCOU()[i].address;
cout << " " << ms->getSCOU()[i].value << endl;
}
ms->~MemoryScanner();
delete ms;
ms = NULL;
while (1) {}
}
<file_sep>#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#define PORT "8080"
class InerCom
{
private:
SOCKET client;
public:
InerCom();
void init();
char* recvData();
int sendData(char* data, int size);
};
<file_sep>#include "stdafx.h"
//#include "MemoryScanner.h"
/*template <typename T>
MemoryScanner<T>::MemoryScanner(DWORD procID)
{
this->pid = procID;
this->hProc = NULL;
this->SCOU = NULL;
this->size = NULL;
}
template <typename T>
void MemoryScanner<T>::init()
{
DWORD access = PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
this->hProc = OpenProcess(access, false, this->pid);
}
template <typename T>
DWORD MemoryScanner<T>::firstScan(ScannerInput SCIN, int val)
{
SYSTEM_INFO info = { 0 };
GetSystemInfo(&info);
DWORD add_sta = (DWORD)info.lpMinimumApplicationAddress;
DWORD add_end = (DWORD)info.lpMaximumApplicationAddress;
DWORD pagesize = info.dwPageSize;
int found = 0;
vector<MEMORY_BASIC_INFORMATION> search_region;
vector<ScannerOutput> SCOU_V; //temporary
for (DWORD current_base = add_sta; current_base <= add_end;)
{
MEMORY_BASIC_INFORMATION mbi = { 0 };
if (!VirtualQueryEx(this->hProc, (LPVOID)current_base, &mbi, sizeof(mbi)))
{
//if return 0, means it failed
current_base += pagesize;
}
else
{
if (mbi.State == MEM_COMMIT && mbi.Protect != PAGE_GUARD)
{
search_region.push_back(mbi);
}
current_base += mbi.RegionSize;
}
}
for each (MEMORY_BASIC_INFORMATION mbi in search_region)
{
unsigned char * buffer = new unsigned char[mbi.RegionSize + 1];
if (ReadProcessMemory(this->hProc, mbi.BaseAddress, &buffer[0], mbi.RegionSize, NULL))
{
int read = 0;
uint8_t increament = 4;
for (int i = 0; i < mbi.RegionSize; i += increament)
{
DWORD address = (DWORD)mbi.BaseAddress + i;
int value = NULL;
for (int j = increament - 1; j >= 0; j--)
{
value = value << (8 * j) | buffer[j + read];
}
read += increament;
if (value == val)
SCOU_V.push_back(ScannerOutput(address, value));
}
}
else
{
auto error = GetLastError();
cout << "Read process memory failed, " + error << endl;
}
delete[] buffer;
buffer = NULL;
}
this->SCOU = (ScannerOutput*)malloc(sizeof(ScannerOutput) * SCOU_V.size());
this->size = SCOU_V.size();
transferElement(SCOU, SCOU_V);
return 0x10;
}
template<typename T>
DWORD MemoryScanner<T>::scanNext(DWORD scanFlag, T val)
{
DWORD scantype = scanFlag & 0xF0; //take out the lower half
DWORD scanmethod = scanFlag & 0x0F;
uint8_t increment = sizeof(T);
ScannerOutput* updated_SCOU = (ScannerOutput*)malloc(sizeof(ScannerOutput) * this->size);
for (int i = 0; i < this->size; i++)
{
unsigned char* buffer = new unsigned char[sizeof(T)];
updateScannedList(this->SCOU[i], buffer, scantype);
T updated_value = NULL;
for (int i = increment - 1; i >= 0; i--)
{
updated_value = updated_value << (i * 8) | buffer[i];
}
if (updated_value == val && updated_value != this->SCOU[i].value)
{
this->SCOU[i].changed = true;
this->SCOU[i].difference = this->SCOU[i].value - updated_value;
this->SCOU[i].value = updated_value;
}
else if (updated_value == this->SCOU[i].value)
{
this->SCOU[i].changed = false;
this->SCOU[i].difference = NULL;
}
updated_SCOU[i] = ScannerOutput(this->SCOU[i].address, updated_value);
delete[] buffer;
buffer = NULL;
}
free(this->SCOU);
this->SCOU = updated_SCOU;
updated_SCOU = NULL;
return 0x10;
}
template <typename T>
void MemoryScanner<T>::updateScannedList(ScannerOutput& SCOU, unsigned char* buffer, DWORD scanflag)
{
if (ReadProcessMemory(this->hProc, (LPVOID)SCOU.address, &buffer[0], (int)scanflag, NULL) == 0)
{
auto error = GetLastError();
cout << "Read process memory failed, " + error << endl;
}
}
template <typename T>
void MemoryScanner<T>::transferElement(MemoryScanner<T>::ScannerOutput* values, vector<MemoryScanner<T>::ScannerOutput>& temp)
{
int size = temp.size();
for (int i = 0; i < size; i++)
{
values[i] = temp[i];
}
}
template<typename T>
MemoryScanner<T>::~MemoryScanner()
{
free(this->SCOU);
this->SCOU = NULL;
}*/<file_sep>#pragma once
#ifndef SCANNERPANEL_H
#define SCANNERPANEL_H
#include "wx\wx.h"
#include "wx\dataview.h"
#include "wx\listctrl.h"
#include "..\Easy Engine\MemoryScanner.h"
#include <sstream>
class ProcessesDialog;
#include "ProcessesDialog.h"
class ScannerPanel :public wxFrame
{
private:
wxButton* firstscan;
wxButton* nextscan;
wxButton* openprocess;
wxDataViewListCtrl* listctrl;
wxComboBox* valuetype;
ProcessesDialog* dialog;
DWORD procID;
LPVOID ms;//memory scanner
wxTextCtrl* targetvalue;
int scantype;
wxMenuBar* meaubar;
wxMenu* tool_menu;
public:
ScannerPanel();
ScannerPanel(ScannerPanel& parent);
~ScannerPanel();
void onFirstScanCliced(wxCommandEvent& evt);
void onOpenProcessClicked(wxCommandEvent& evt);
ScannerPanel& operator= (const ScannerPanel& other);
void updateProcID(int id);
void printScannedResult(int type, MemoryScanner<int>* ms_int = NULL,
MemoryScanner<float>* ms_float = NULL);
void onSecondScanClicked(wxCommandEvent& evt);
wxDECLARE_EVENT_TABLE();
private:
//helper functions
string toUpperCase(string& original);
};
#endif
<file_sep>#pragma once
#ifndef PROCESSDIALOG_H
#define PROCESSDIALOG_H
#include "wx\wx.h"
#include <string>
#include <Windows.h>
#include <psapi.h>
#include <vector>
using namespace std;
//this file is included in ScannerPanel.h
class ScannerPanel; //forward declaration to avoid nested include loops
//see https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c for reference
class ProcessesDialog : public wxFrame //the panel to pop up when open process is clicked
{
private:
DWORD* processesids;
wxListBox* process_list;
wxButton* confirm;
wxButton* cancel;
ScannerPanel* parentpanel;
public:
ProcessesDialog();
//ProcessesDialog(ProcessesDialog& other);
ProcessesDialog(ScannerPanel& parent);
//ProcessesDialog& operator=(const ProcessesDialog& other);
~ProcessesDialog();
void printProcessses();
void onConfirmClicked(wxCommandEvent& evt);
void onCancelClicked(wxCommandEvent& evt);
wxDECLARE_EVENT_TABLE();
};
#endif
<file_sep># Easy-Engine
An easy, smart, beginner-friendly cheat engine
<file_sep>#pragma once
#ifndef MEMORYSCANNER_H
#define MEMORYSCANNER_H
#include <Windows.h>
#include <string>
#include <iostream>
#include <vector>
#include "sorting.h"
using namespace std;
//scan type takes the higher half;
#define ST_INT 0x40
#define ST_FLOAT 0x80
#define ST_BOOL 0x10
//scan method only takes the lower half
#define SME_UNKNOWN 0x01
#define SME_CHANGED 0x02
#define SME_DECREASED 0x05
#define SME_INCREASED 0x09
#define SME_CHANGED_EXACT 0x0E
enum ScanType
{
int_value = 0x40,
float_value = 0x08,
boolean_value = 0x11
};
enum ScanMethod : byte
{
search_unknown = 0x01,
search_changed = 0x10,
search_decreased = 0x80,
search_increased = 0x90,
search_changed_exact = 0xCE
};
typedef const struct ScannerInput
{
ScanType ST;
ScanMethod SME;
ScannerInput(int scanType, int scanMethod = NULL)
{
this->ST = (ScanType)scanType;
this->SME = (ScanMethod)scanMethod;
}
} SI;
template <typename T>
class MemoryScanner
{
public:
typedef struct ScannerOutput
{
DWORD address;
T value;
bool changed;
T difference;
ScannerOutput(DWORD add, T val)
{
this->address = add;
this->value = val;
this->changed = false;
this->difference = NULL;
}
ScannerOutput()
{
this->address = NULL;
this->value = NULL;
this->changed = false;
this->difference = NULL;
}
bool operator > (const ScannerOutput& other) const
{
T difference = this->value - other.value;
return difference > 0;
}
bool operator < (const ScannerOutput& other) const
{
T difference = this->value - other.value;
return difference < 0;
}
} SO, NEXT_SCAN_INPUT;
private:
DWORD pid;
HANDLE hProc;
ScannerOutput* SCOU;
int size;
public:
MemoryScanner(DWORD procID)
{
this->pid = procID;
this->hProc = NULL;
this->SCOU = NULL;
this->size = NULL;
}
MemoryScanner(const MemoryScanner<T>& other)
{
this->SCOU = other.SCOU;
this->hProc = other.hProc;
this->pid = other.pid;
this->size = other.size;
}
//template <typename T>
void MemoryScanner<T>::init()
{
DWORD access = PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION;
this->hProc = OpenProcess(access, false, this->pid);
}
int MemoryScanner<T>::getSize()
{
return this->size;
}
//template <typename T>
DWORD MemoryScanner<T>::firstScan(T val)
{
SYSTEM_INFO info = { 0 };
GetSystemInfo(&info);
DWORD add_sta = (DWORD)info.lpMinimumApplicationAddress;
DWORD add_end = (DWORD)info.lpMaximumApplicationAddress;
DWORD pagesize = info.dwPageSize;
vector<MEMORY_BASIC_INFORMATION> search_region;
vector<ScannerOutput> SCOU_V; //temporary
for (DWORD current_base = add_sta; current_base <= add_end;)
{
MEMORY_BASIC_INFORMATION mbi = { 0 };
if (!VirtualQueryEx(this->hProc, (LPVOID)current_base, &mbi, sizeof(mbi)))
{
//if return 0, means it failed
current_base += pagesize;
}
else
{
if (mbi.State == MEM_COMMIT && mbi.Protect != PAGE_GUARD)
{
search_region.push_back(mbi);
}
current_base += mbi.RegionSize;
}
}
for each (MEMORY_BASIC_INFORMATION mbi in search_region)
{
T* buffer = (T*)malloc(mbi.RegionSize + 1);
if (ReadProcessMemory(this->hProc, mbi.BaseAddress, &buffer[0], mbi.RegionSize, NULL))
{
int8_t increament = sizeof(T);
for (int i = 0; i < mbi.RegionSize; i += increament)
{
DWORD address = (DWORD)mbi.BaseAddress + i;
T value = buffer[i / sizeof(T)];
if (value == val)
SCOU_V.push_back(ScannerOutput(address, value));
}
}
else
{
auto error = GetLastError();
cout << "Read process memory failed, " + error << endl;
}
delete[] buffer;
buffer = NULL;
}
this->SCOU = (ScannerOutput*)malloc(sizeof(ScannerOutput) * SCOU_V.size());
this->size = SCOU_V.size();
transferElement(this->SCOU, SCOU_V);
return 0x10;
}
DWORD MemoryScanner<T>::scanNext(T val)
{
//DWORD scantype = scanFlag & 0xF0; //take out the lower half
//DWORD scanmethod = scanFlag & 0x0F;
uint8_t increment = sizeof(T);
uint32_t updated_size = 0;
ScannerOutput* updated_SCOU = (ScannerOutput*)malloc(sizeof(ScannerOutput) * this->size);
for (int i = 0; i < this->size; i++)
{
T* buffer = (T*)malloc(sizeof(T));
updateScannedList(this->SCOU[i], &buffer[0], increment);
T updated_value = *buffer;
if (updated_value == val)
{
updated_SCOU[i] = ScannerOutput(this->SCOU[i].address, updated_value);
updated_size++;
if (updated_value != this->SCOU[i].value)
{
updated_SCOU[i].changed = true;
updated_SCOU[i].difference = updated_value - this->SCOU[i].value;
}
}
delete[] buffer;
buffer = NULL;
}
free(this->SCOU);
this->SCOU = updated_SCOU;
this->size = updated_size;
updated_SCOU = NULL;
return 0x10;
}
void MemoryScanner<T>::updateScannedList(ScannerOutput& SCOU, T* buffer, uint8_t bytes)
{
SIZE_T read;
if (ReadProcessMemory(this->hProc, (LPVOID)SCOU.address, &buffer[0], bytes, &read) == 0)
{
auto error = GetLastError();
cout << "Read process memory failed, " + error << endl;
}
}
ScannerOutput* MemoryScanner<T>::getSCOU()
{
return this->SCOU;
}
void MemoryScanner<T>::transferElement(MemoryScanner<T>::ScannerOutput* values, vector<MemoryScanner<T>::ScannerOutput>& temp)
{
int size = temp.size();
for (int i = 0; i < size; i++)
{
values[i] = temp[i];
}
}
//This is a situtation where all the memory scanner object is local variables
//which is essentially all pointing to the the address of a LPVOID variable
//freeing the memory inside is deleting the where the LPVOID points to
//and when LPVOID accesses it next time it will trigger exception
//so leave the job to the LPVOID to free up memory
MemoryScanner::~MemoryScanner()
{
//free(this->SCOU);
this->SCOU = NULL;
}
};
#endif
|
e95d819462d38ac2f07a0dabbf62ff41183c5964
|
[
"Markdown",
"C++"
] | 13
|
C++
|
didntpay/Easy-Engine
|
9ba7c75d4443474eb11a694793e9dbd6d081fa6d
|
1a55027b6ff4172cc0dfe0fed9fd5b7e1223bce5
|
refs/heads/master
|
<repo_name>KevinSaulOrtizVarela/EVA1_7_KILLING_OBJECTS<file_sep>/src/eva1_7_killing_objects/EVA1_7_KILLING_OBJECTS.java
package eva1_7_killing_objects;
/*PROYECTO PARA DAR UN EJEMPLO DE COMO SE ELIMINA UN OBJETO*/
/**
* @author 16550549
*/
public class EVA1_7_KILLING_OBJECTS {
public static void main(String[] args) {
// TODO code application logic here
Prueba pObj = new Prueba();
pObj= null; //ASI SE DESTRUYE UN OBJETO EN JAVA
}
}
class Prueba{
}
|
ecc83722bc736937516da227ba073d6703a163b2
|
[
"Java"
] | 1
|
Java
|
KevinSaulOrtizVarela/EVA1_7_KILLING_OBJECTS
|
2837fee0811f5ccf44ca21dc05f90f89ba73cade
|
a0878478eaf5a207d9206dada4d6f0641b1e12bc
|
refs/heads/master
|
<repo_name>mikaelm12/ProxyDemo<file_sep>/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DataProxy.Models;
using Microsoft.AspNet.Mvc;
namespace DataProxy.Controllers
{
public class HomeController : Controller
{
[FromServices]
public ApplicationDbContext DbContext { get; set; }
public IActionResult Index()
{
//More information!
var requests = new SiteData(DbContext.Requests.OrderBy(p => p.TimeStamp).ToArray());
return View(requests);
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
public IActionResult Error()
{
return View("~/Views/Shared/Error.cshtml");
}
}
}
<file_sep>/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication.Facebook;
using Microsoft.AspNet.Authentication.Google;
using Microsoft.AspNet.Authentication.MicrosoftAccount;
using Microsoft.AspNet.Authentication.Twitter;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Diagnostics;
using Microsoft.AspNet.Diagnostics.Entity;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Routing;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Logging.Console;
using Microsoft.Dnx.Runtime;
using DataProxy.Models;
using DataProxy.Services;
using Microsoft.AspNet.Proxy;
using Microsoft.AspNet.Mvc;
namespace DataProxy
{
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
// Setup configuration sources.
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add Entity Framework services to the services container.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Configure the options for the authentication middleware.
// You can add options for Google, Twitter and other middleware as shown below.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
services.Configure<FacebookAuthenticationOptions>(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
services.Configure<MicrosoftAccountAuthenticationOptions>(options =>
{
options.ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"];
options.ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"];
});
// Add MVC services to the services container.
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
// Register application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// Configure is called after ConfigureServices is called.
[FromServices]
public ApplicationDbContext DbContext { get; set; }
private string host = "microsoft.com";
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.MinimumLevel = LogLevel.Information;
loggerFactory.AddConsole();
// Configure the HTTP request pipeline.
// Add the following to the request pipeline only in development environment.
if (env.IsDevelopment())
{
app.UseErrorPage();
app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
}
else
{
// Add Error handling middleware which catches all application specific errors and
// sends the request to the following path or controller action.
app.UseErrorHandler("/Home/Error");
}
// Add static files to the request pipeline.
app.UseStaticFiles();
// Add cookie-based authentication to the request pipeline.
app.UseIdentity();
// Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
// For more information see http://go.microsoft.com/fwlink/?LinkID=532715
// app.UseFacebookAuthentication();
// app.UseGoogleAuthentication();
// app.UseMicrosoftAccountAuthentication();
// app.UseTwitterAuthentication();
app.Use(next =>
{
return async context =>
{
var DbContext = (ApplicationDbContext)context.RequestServices.GetService(typeof(ApplicationDbContext));
var request = new Request();
if (!context.Request.Path.ToString().Contains("secret-route"))
{
var url = $"{context.Request.Scheme}://{host}:{ context.Connection.RemotePort} { context.Request.PathBase}{ context.Request.Path}{ context.Request.QueryString}";
request.MethodType = context.Request.Method.ToString();
request.Url = url;
request.TimeStamp = DateTime.Now;
DbContext.Add(request);
DbContext.SaveChanges();
}
await next(context);
};
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "secret-route/{controller=Home}/{action=Index}/{id?}");
});
var options = new ProxyOptions()
{
Scheme = "https",
Host = host,
Port = "443"
};
app.RunProxy(options);
}
}
}
<file_sep>/Models/SiteData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DataProxy.Models
{
public class SiteData
{
public Request[] request;
public int GetRequests { get; set; }
public int PostRequests { get; set; }
public int PutRequests { get; set; }
public int DeleteRequest { get; set; }
public List<Request> RequestSet { get; set; }
public Dictionary<String, String> Requestinfo { get; set; }
public int MyProperty { get; set; }
public SiteData(Request[] requests)
{
this.request = requests;
GetRequests = requests.Where(r => r.MethodType == "GET").Count();
PostRequests = requests.Where(r => r.MethodType == "POST").Count();
DeleteRequest = requests.Where(r => r.MethodType == "DELETE").Count();
PutRequests = requests.Where(r => r.MethodType == "PUT").Count();
}
}
}
|
0443fd281d8349aeb140332cee0e2213e5e07e5b
|
[
"C#"
] | 3
|
C#
|
mikaelm12/ProxyDemo
|
a04489d7c133dcc1b7acc031ac9622b62852fea0
|
db13d3e2f2b5722130e0a45800d3b64279b52368
|
refs/heads/master
|
<repo_name>rexoriousyun/rexoriousyun.github.io<file_sep>/README.md
<NAME>'s Personal site
<file_sep>/js/main.js
window.onload = function(){
$('#loader').css({'display':'none'});
$('header, .container').css({'display': 'flex'});
$('.backgroundVideo').animate({'opacity':'1'}, 'fast',
function(){
$('header, .container').animate({'opacity': '1'}, 'slow');
}
);
}
var menuOpen = false;
var modalOpen = false;
var currentNumber;
var maxModalValue = $('.modal:first-child').attr('value');
var liVal = 0;
var liValMax = parseInt($('li:last-child').attr('value'));
function isTouchDevice() {
return 'ontouchstart' in document.documentElement;
}
$('.trigger').click(function(){
if (modalOpen && menuOpen == false) {
$('.modal').hide();
$('.works').animate({'opacity':'show'}, 200);
$(this).css({'transition': 'transform 0.5s', 'transform': 'rotate(0deg)'});
modalOpen = false;
} else if (menuOpen == false){
if (window.innerWidth < 600) {
$('.menu').animate({'width': '100%'});
$('.content').hide();
} else {
$('.menu').animate({'width': '30%', 'minWidth': '300px'});
}
$('.page').animate({'marginLeft': '20px', 'marginRight': '20px'});
$(this).css({'transition': 'transform 0.5s', 'transform': 'rotate(45deg)'});
menuOpen = true;
} else {
$('.menu').animate({'width': '0px', 'minWidth': '0px', 'marginRight': '0px'});
$('.content').animate({'opacity': 'show'});
if (window.innerWidth > 1024) {
$('.page').animate({'marginLeft': '0px'});
$('.page').animate({'marginRight': '0px'});
}
$(this).css({'transition': 'transform 0.5s', 'transform': 'rotate(0deg)'});
menuOpen = false;
}
})
$('.menu li').click(function(){
liVal = $(this).attr('value');
$('.page').each(function(){
if (liVal == $(this).attr('value')){
$(this).animate({'opacity':'show'}, 1000);
} else {
$(this).hide();
}
})
if (window.innerWidth < 600) {
$('.trigger').trigger('click');
}
})
$('.card').hover(function() {
$(this).children('.color').animate({'opacity': 0.2}, 200);
}, function() {
$(this).children('.color').animate({'opacity': 1}, 200);
}
);
$('.card').click(function(){
$('.works').animate({'opacity':'hide'});
if (menuOpen) {
$('.menu').animate({'width': '0px', 'minWidth': '0px', 'marginRight': '0px'});
if (window.innerWidth > 1024) {
$('.page').animate({'marginLeft': '0px'});
$('.page').animate({'marginRight': '0px'});
}
$(this).css({'transition': 'transform 0.5s', 'transform': 'rotate(0deg)'});
menuOpen = false;
}
var cardNumber = parseInt($(this).attr('value'));
$('.modal').each(function(index){
var modalNumber = parseInt($(this).attr('value'));
if (cardNumber == modalNumber){
$(this).animate({'opacity':'show'}, function(){
$( 'html, body' ).animate( { scrollTop : '0' }, 300, 'swing' )
});
var treeVideoHeight = parseInt($('#treeVideo').css('width'));
$('#treeVideo').css({'height': treeVideoHeight * 0.5625});
document.getElementsByClassName('codepen')[0].src = document.getElementsByClassName('codepen')[0].src
$('.trigger').css({'transition': 'transform 0.5s', 'transform': 'rotate(45deg)'});
currentNumber = modalNumber;
}
})
modalOpen = true;
})
function toLeft() {
document.getElementById('treeVideo').src += '';
var treeVideoHeight = parseInt($('#treeVideo').css('width'));
$('#treeVideo').css({'height': treeVideoHeight * 0.5625});
document.getElementsByClassName('codepen')[0].src = document.getElementsByClassName('codepen')[0].src
$('.modal[value=' + currentNumber + ']').animate({
'left':'-100%'
}, function(){
$(this).css({'left':'0'});
$(this).hide();
});
if (currentNumber <= 0) {
currentNumber = maxModalValue;
} else {
currentNumber -= 1;
}
$('.modal[value=' + currentNumber + ']').animate({'opacity':'show'},
function(){
document.getElementById('treeVideo').src += '';
var treeVideoHeight = parseInt($('#treeVideo').css('width'));
$('#treeVideo').css({'height': treeVideoHeight * 0.5625});
$( 'html, body' ).animate( { scrollTop : '0' }, 300, 'swing' )
}
);
}
function toRight() {
document.getElementById('treeVideo').src += '';
var treeVideoHeight = parseInt($('#treeVideo').css('width'));
$('#treeVideo').css({'height': treeVideoHeight * 0.5625});
document.getElementsByClassName('codepen')[0].src = document.getElementsByClassName('codepen')[0].src
$('.modal[value=' + currentNumber + ']').animate({
'left':'100%'
}, function(){
$(this).css({'left':'0'});
$(this).hide();
});
if (currentNumber >= maxModalValue) {
currentNumber = 0;
} else {
currentNumber += 1;
}
$('.modal[value=' + currentNumber + ']').animate({'opacity':'show'},
function(){
document.getElementById('treeVideo').src += '';
var treeVideoHeight = parseInt($('#treeVideo').css('width'));
$('#treeVideo').css({'height': treeVideoHeight * 0.5625});
$( 'html, body' ).animate( { scrollTop : '0' }, 300, 'swing' )
}
);
}
$('.front').click(function(){
toRight();
})
$('.modal').on('swiperight', function(){
if (isTouchDevice()) {
toRight();
}
})
$('.back').click(function(){
toLeft();
})
$('.modal').on('swipeleft', function(){
if (isTouchDevice()) {
toLeft();
}
})
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 27 || evt.keyCode == 32) {
$('.trigger').trigger('click');
} else if (modalOpen) {
if (evt.keyCode == 39) {
toLeft();
} else if (evt.keyCode == 37) {
toRight();
}
}
};
$('.page[value="1"], .page[value="2"], .page[value="3"]').hide();
$('.modal').hide();
$('.back, .front').css({'top': window.innerHeight/2})
|
62218e2be53c5f91d3209d94a5a5569ebef97d9d
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
rexoriousyun/rexoriousyun.github.io
|
5d179cdda1cfef370720687a3f49b53a941d1f34
|
acb560cc2857fe0df940944d8b04f067ef0afb2d
|
refs/heads/master
|
<file_sep>angular.module("new",[]).directive("new",[function(){
return {
restrict:"ECMA",
templateUrl:"views/main.html",
scope:{data:'=gyr',data2:'@gyr2',img:'=gyr3'},
replace:true,
}
}]).filter("f",[function(){
return function(elength){
if(elength.length>12){
return elength.substr(0,12)+'...'
}else{
return elength
}
}
}]);
|
33104248175d115eb0412e94a461db18e06510ca
|
[
"JavaScript"
] | 1
|
JavaScript
|
AliceRu/gyr
|
d997a8aa98c4284c06d06ba9f734d0dcf2d5b703
|
aecff896f11b266a6fff440fc1eefd5145e1fbfe
|
refs/heads/main
|
<file_sep>class GameStats():
"""Отслеживание статистики"""
def __init__(self, ai_game):
"""Инициализирует статистику"""
self.settings = ai_game.settings
self.reset_status()
self.game_active = False
self.read_high_score()
def read_high_score(self):
"""Читает рекорд"""
filename = 'PY\\alien_invasion\\record.txt'
with open(filename) as f:
self.high_score = f.read()
def reset_status(self):
"""Инициализирует статистику, изменяющуюся в ходе игры"""
self.ships_left = self.settings.ship_limit
# Игра запускается в активном состоянии
self.game_active = True
self.score = 0
self.level = 1<file_sep>import pygame.font
from pygame.sprite import Group
from ship import Ship
class ScoreBoard():
"""Выводит Информацию о игре"""
def __init__(self, ai_game):
"""Инициализация атрибутов подсчёта очков"""
self.ai_game = ai_game
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.stats = ai_game.stats
# Настройка шрифта
self.text_color = (255, 255, 255)
self.font = pygame.font.Font(
'PY/alien_invasion/other_files/pixel.ttf', 48)
# Подготовка исходнодного изображения счётов
self.prep_score()
self.prep_high_score()
self.prep_level()
self.prep_ships()
def prep_score(self):
"""Преобразует счёт в картинку"""
rounded_score = round(self.stats.score, -1)
score_str = "Score:{:,}".format(rounded_score)
self.score_img = self.font.render(
score_str, True, self.text_color, self.settings.bg_color)
# Вывод счёта в правом верхнем углу
self.score_rect = self.score_img.get_rect()
self.score_rect.right = self.screen_rect.right - 20
self.score_rect.top = 20
def prep_high_score(self):
"""Преобразует рекордный счёт в изображение"""
high_score = self.stats.high_score
high_score_str = f"Record:{high_score}"
self.high_score_img = self.font.render(
high_score_str, True, self.text_color, self.settings.bg_color)
self.high_score_rect = self.high_score_img.get_rect()
self.high_score_rect.centerx = self.screen_rect.centerx
self.high_score_rect.top = self.score_rect.top
def prep_level(self):
"""Преобразует уровень в изображение"""
level = self.stats.level
level_str = f"LVL:{level}"
self.level_img = self.font.render(
level_str, True, self.text_color, self.settings.bg_color)
# Уровень выводится под текущим счётом
self.level_rect = self.level_img.get_rect()
self.level_rect.right = self.score_rect.right
self.level_rect.top = self.score_rect.bottom + 10
def show_score(self):
"""Вывод счёта на экран"""
self.screen.blit(self.score_img, self.score_rect)
self.screen.blit(self.high_score_img, self.high_score_rect)
self.screen.blit(self.level_img, self.level_rect)
self.ships.draw(self.screen)
def check_high_score(self):
"""Проверяет, появился ли новый рекорд"""
self.stats.high_score = int(self.stats.high_score)
if self.stats.score > self.stats.high_score:
self.stats.high_score = self.stats.score
self.prep_high_score()
def write_high_score(self):
"""Записыает наибольший рекорд в файл"""
self.stats.high_score = int(self.stats.high_score)
if self.stats.score >= self.stats.high_score:
self.stats.high_score = self.stats.score
filename = 'record.txt'
with open(filename, "w") as f:
f.write(str(self.stats.high_score))
def read_high_score(self):
"""Читает рекорд"""
filename = 'PY/alien_invasion/record.txt'
with open(filename) as f:
self.high_score = f.read()
def prep_ships(self):
"""Показывает количество оставшихся кораблей"""
self.ships = Group()
for ship_number in range(self.stats.ships_left):
ship = Ship(self.ai_game)
ship.image = pygame.image.load(
'PY/alien_invasion/other_files/spaceship_small.png')
ship.rect.x = 10 + ship_number * ship.rect.width / 2
ship.rect.y = 10
self.ships.add(ship)
<file_sep>import sys
from random import randint, randrange
import pygame
from pygame import Rect
from time import sleep
import os
from settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
from stars import Star
from game_stats import GameStats
from button import Button
from scoreboard import ScoreBoard
from bonus import Bonus
class AlienInvasion:
def __init__(self):
pygame.init()
self.settings = Settings()
self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
self.settings.screen_width = self.screen.get_rect().width
self.settings.screen_height = self.screen.get_rect().height
pygame.display.set_caption("Alien Invasion")
self.stats = GameStats(self)
self.sb = ScoreBoard(self)
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.alien = Alien(self)
self.aliens = pygame.sprite.Group()
self._create_fleet()
self.stars = pygame.sprite.Group()
self._create_stars_grid()
self.bonus = pygame.sprite.Group()
self.easy_button = Button(self, 850, 250, (102, 255, 0), "Easy")
self.normal_button = Button(self, 850, 450, (255, 216, 0), "Normal")
self.hard_button = Button(self, 850, 650, (255, 36, 0), "Hard")
self.zerout_record_button = Button(
self, 850, 850, (0, 0, 0), "Zero out a record")
def run_game(self):
"""Запускает основной цикл игры"""
while True:
self._check_events()
self.sb.read_high_score()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self._update_bonus()
self._update_screen()
def _check_events(self):
"""Обрабатывает события клавиш и мыши"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
self._difficulty_buttons(mouse_pos)
self._check_play_button(mouse_pos)
self._zerout_record(mouse_pos)
def _check_keydown_events(self, event):
"""Реакция на нажите клавиш"""
if event.key == pygame.K_d:
self.ship.moving_right = True
elif event.key == pygame.K_a:
self.ship.moving_left = True
elif event.key == pygame.K_ESCAPE:
self.sb.write_high_score()
sys.exit()
elif event.key == pygame.K_SPACE:
if self.stats.game_active:
self._fire_bullet()
def _check_keyup_events(self, event):
"""Реакция на отпускание клавиш"""
if event.key == pygame.K_d:
self.ship.moving_right = False
elif event.key == pygame.K_a:
self.ship.moving_left = False
def _zerout_record(self, mouse_pos):
"""Обнуляет рекорд при нажатии кнопки"""
button_clicked = self.zerout_record_button.rect.collidepoint(mouse_pos)
if button_clicked and not self.stats.game_active:
os.system('python D:\\Programming\\Python\\alien_invasion\\start.py')
sys.exit()
def _check_play_button(self, mouse_pos):
"""Запускает новую игру при нажатии кнопки play"""
easy_button_clicked = self.easy_button.rect.collidepoint(mouse_pos)
normal_button_clicked = self.normal_button.rect.collidepoint(mouse_pos)
hard_button_clicked = self.hard_button.rect.collidepoint(mouse_pos)
if easy_button_clicked or normal_button_clicked or hard_button_clicked and not self.stats.game_active:
# Cброс статистики
self.stats.reset_status()
self.stats.game_active = True
self.sb.prep_level()
self.sb.prep_ships()
self.aliens.empty()
self.bullets.empty()
self._create_fleet()
self.ship.center_ship()
pygame.mouse.set_visible(False)
def _difficulty_buttons(self, mouse_pos):
easy_button_clicked = self.easy_button.rect.collidepoint(mouse_pos)
normal_button_clicked = self.normal_button.rect.collidepoint(mouse_pos)
hard_button_clicked = self.hard_button.rect.collidepoint(mouse_pos)
if easy_button_clicked or normal_button_clicked or hard_button_clicked and not self.stats.game_active:
pygame.mixer.music.load(
'PY/alien_invasion/other_files/for_levels.mp3')
pygame.mixer.music.set_volume(50)
pygame.mixer.music.play(-1)
if easy_button_clicked:
self.settings.dynamic_settings()
self.settings.alien_speed = 0.7
self.settings.ship_speed = 1.8
self.settings.bullet_speed = 1.9
self._check_play_button(mouse_pos)
if normal_button_clicked:
self.settings.dynamic_settings()
self.settings.alien_speed = 1.0
self.settings.ship_speed = 1.5
self.settings.bullet_speed = 1.5
self._check_play_button(mouse_pos)
if hard_button_clicked:
self.settings.dynamic_settings()
self.settings.alien_speed = 1.8
self.settings.ship_speed = 0.8
self.settings.bullet_speed = 0.7
self._check_play_button(mouse_pos)
def _bonus_start_fly(self):
"""Создание нового бонуса и добавление в группу"""
if len(self.bonus) < self.settings.bonus_allowed and randint(0, 75) > 70 :
new_bonus = Bonus(self)
self.bonus.add(new_bonus)
def _update_bonus(self):
"""Обновляет места бонусов и убирает старые бонусы"""
self.bonus.update()
for new_bonus in self.bonus.copy():
if new_bonus.rect.bottom <= 1080:
self.bullets.remove(new_bonus)
self._check_bullet_alien_collisions()
def _fire_bullet(self):
"""Создание нового снаряда и включение его в группу"""
if len(self.bullets) < self.settings.bullet_allowed:
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
fire_sound = pygame.mixer.Sound("PY/alien_invasion/other_files/shot.wav")
fire_sound.play()
def _update_bullets(self):
"""Обновляет позиции снарядов и уничтожает старые снаряды"""
self.bullets.update()
for bullet in self.bullets.copy():
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
self._check_bullet_alien_collisions()
def _check_bullet_alien_collisions(self):
if not self.aliens:
# Уничтожение существующих снарядов и создание нового флота
self.bullets.empty()
self._create_fleet()
self.bonus.empty()
self.settings.inscrease_speed()
# Увеличение уровня
self.stats.level += 1
self.sb.prep_level()
# проверка попаданий в пришельцев.При попадании удаляет снаряд и пришельца
collisions = pygame.sprite.groupcollide(
self.bullets, self.aliens, True, True)
if collisions:
for aliens in collisions.values():
self.stats.score += self.settings.alien_points * len(aliens)
#self._bonus_start_fly()
hit_sound = pygame.mixer.Sound(
'PY/alien_invasion/other_files/ufo.wav')
hit_sound.play()
self.sb.prep_score()
self.sb.check_high_score()
def _create_fleet(self):
"""Создание флота пришельцев"""
alien = Alien(self)
alien_width, alien_height = alien.rect.size
avaible_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = avaible_space_x // (2 * alien_width)
"""Определяет количество рядов, помещающихся на экране"""
ship_height = self.ship.rect.height
avaible_space_y = (self.settings.screen_height -
(3 * alien_height) - ship_height)
number_rows = avaible_space_y // (2 * alien_height)
# Создание флота
for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
"""Создание пришельца и размещение его в ряду"""
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
self.aliens.add(alien)
def _check_fleet_edges(self):
"""Реакция на достижение края экрана"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _change_fleet_direction(self):
"""Опускает флот и меняет направление"""
for alien in self.aliens.sprites():
alien.rect.y += self.settings.fleet_drop_speed
self.settings.fleet_direction *= -1
def _check_aliens_bottom(self):
"""Проверяет, добрались ли пришельцы до нижнего края экрана"""
screen_rect = self.screen.get_rect()
for alien in self.aliens.sprites():
if alien.rect.bottom >= screen_rect.bottom:
self._ship_hit()
break
def _update_aliens(self):
"""Обновляет позиции всех прищельцев"""
self._check_fleet_edges()
self.aliens.update()
# Проверка коллизий пришельца с кораблём
if pygame.sprite.spritecollide(self.ship, self.aliens, True):
self._ship_hit()
# Проверяет, добрались ли пришельцы до нижнего края экрана
self._check_aliens_bottom()
def _create_stars_grid(self):
"""Создание сетки звёзд"""
# Создание одной звезды
star = Star(self)
avaible_star_space_x = self.settings.screen_width
avaible_star_space_y = self.settings.screen_height
star_height = star.rect.y
star_width = star.rect.x
i = 0
star_x = [0]
star_y = [0]
for i in range(60):
cur_pos_x = randrange(0, 1900, 50)
cur_pos_y = randrange(0, 1080, 45)
for x in star_x:
if cur_pos_x == x:
cur_pos_x = randrange(0, 1900, 50)
star_x.append(cur_pos_x)
break
else:
star_x.append(cur_pos_x)
break
for y in star_y:
if cur_pos_y == y:
cur_pos_y = randrange(0, 1080, 45)
star_y.append(cur_pos_y)
break
else:
star_y.append(cur_pos_y)
break
if star_x[i] == 0 and star_y[i] == 0:
star.remove()
else:
self._create_star(star_x[i], star_y[i])
def _create_star(self, x, y):
star = Star(self)
star.rect.x = x
star.rect.y = y
self.stars.add(star)
def _ship_hit(self):
"""Обрабатывает столкновения корабля с пришельцами"""
if self.stats.ships_left > 0:
# Уменьшение ships_left
self.stats.ships_left -= 1
#Проигравание звука при потере жизни
ship_hit_sound = pygame.mixer.Sound('alien_invasion/other_files/minus_hp.wav')
ship_hit_sound.play()
self.sb.prep_ships()
# Очистка списков пришельцев и пуль
self.aliens.empty()
self.bullets.empty()
# Созание нового флота и размещение корабля в центре
self._create_fleet()
self.ship.center_ship()
# Пауза
sleep(0.5)
else:
self.stats.game_active = False
pygame.mixer.music.stop()
pygame.mouse.set_visible(True)
def _update_screen(self):
"""Обновляет изображение на экране"""
self.screen.fill(self.settings.bg_color)
self.stars.draw(self.screen)
self.sb.show_score()
self.ship.blitme()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
self.aliens.draw(self.screen)
for bonus in self.bonus.sprites():
bonus.blitme()
if not self.stats.game_active:
self.easy_button.draw_button()
self.normal_button.draw_button()
self.hard_button.draw_button()
self.zerout_record_button.draw_button()
pygame.display.flip()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
<file_sep>import os
filename = 'record.txt'
with open(filename, "w") as f:
f.write('0')
os.system('python D:\\Programming\\Python\\alien_invasion\\alien_invasion.py')<file_sep>class Settings():
"""В этом классе все настройки"""
def __init__(self):
# параметры экрана
self.screen_width = 1920
self.screen_height = 1080
self.bg_color = (0, 19, 50)
# Настройки коробля
self.ship_limit = 3
# параметры снаряда
self.bullet_width = 5
self.bullet_height = 15
self.bullet_color = (255, 255, 255)
self.bullet_allowed = 3
# Ускорение игры
self.speedup_scale = 1.1
# Настройка прищельцев
self.fleet_drop_speed = 10
# self.fleet_direction 1 - движение вправо. self.fleet_direction -1 -движение влево
self.fleet_direction = 1
#Темп роста стоимости пришельцев
self.score_scale = 1.5
# Скорость падения бонусов
self.bonus_speed = 1.5
self.bonus_allowed = 2
def dynamic_settings(self):
self.alien_speed = 1.0
self.bullet_speed = 1.5
self.ship_speed = 1.5
# Подсчёт очков
self.alien_points = 10
def inscrease_speed(self):
"""Увеличивает настройки скорости"""
self.ship_speed *= self.speedup_scale
self.bullet_speed *= self.speedup_scale
self.alien_speed *= self.speedup_scale
self.alien_points = int(self.alien_points * self.score_scale)<file_sep>import pygame
from pygame.sprite import Sprite
from alien import Alien
class Bonus(Sprite):
def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.settings = ai_game.settings
self.img = pygame.image.load("alien_invasion/other_files/bonus.png")
self.rect = self.img.get_rect()
self.rect.midbottom = self.screen_rect.midbottom
self.y = float(ai_game.alien.y)
self.x = ai_game.alien.rect.y
def update(self):
"""Перемещает бонус вниз по экрану"""
self.y += self.settings.bonus_speed
self.rect.y = self.y
self.rect.x = self.x
def blitme(self):
"""Рисует бонус в текущей позиции"""
self.screen.blit(self.img, self.rect)<file_sep>import pygame
from pygame.sprite import Sprite
class Boss(Sprite):
def __init__(self, ai_game):
"""Инициализация босса"""
super().__init__()
self.screen = ai_game.screen
self.screen_rect = ai_game.screen.get_rect()
self.settings = ai_game.settings
# Изображение босса
self.image = pygame.image.load('alien_invasion/other_files/boss.png')
self.rect = self.image.get_rect()
# каждый босс появляется у верхнего края экрана
self.rect.midtop = self.screen_rect.midtop
self.moving_right = False
self.moving_left = False
# сохранение вещественной координаты босса
self.x = float(self.rect.x)
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x += self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x -= self.settings.ship_speed
self.rect.x = self.x
def blitme(self):
"""Рисует босса в текущей позиции"""
self.screen.blit(self.image, self.rect)
def center_ship(self):
"""Размещает босса в центре верхней стороны"""
self.rect.midtop = self.screen_rect.midtop
self.x = float(self.rect.x)
|
25715ff658f22af73a15824391bdac015b6eaff7
|
[
"Python"
] | 7
|
Python
|
EgorikEbolik/Alien-Invasion-Game
|
6aea28525b84b823cdb1b9cbc71d943b6c1ac015
|
ab1db732ea7bd16059c8199e849e1b88f2317ddd
|
refs/heads/master
|
<repo_name>YangSeung-min/react-multi-page-app-test<file_sep>/webpack.config.js
const path = require('path');
var webpack = require('webpack');
module.exports = {
entry: {
// 'whatwg-fetch' : IE에서 fetch를 사용하기 위해 필요하다.
// '@babel/polyfill' : IE에서 Promise를 사용하기 위해 필요하다.
// main: ['whatwg-fetch', '@babel/polyfill','./public/main/resources/static/js/es6/main.js'],
index: './public/devJs/index.js',
sub: './public/devJs/sub.js'
},
// 컴파일 + 번들링된 js 파일이 저장될 경로와 이름 지정
output: {
path: path.resolve(__dirname, './public/js'),
filename: '[name].js',
// publicPath: '/public/'
},
module: {
rules: [
{
test: /\.js$/,
include: [
path.resolve(__dirname, 'public/devJs')
],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react', '@babel/preset-env']
// presets: ['@babel/react', '@babel/preset-env']
}
}
}
]
},
devtool: 'source-map',
// https://webpack.js.org/concepts/mode/#mode-development
// development/production
mode: 'development',
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
|
295e079d01a33c0dc1d5a5ac195597584aac4c2d
|
[
"JavaScript"
] | 1
|
JavaScript
|
YangSeung-min/react-multi-page-app-test
|
2583a9dca3d96bba748d68eec1cfec0e99ff0e62
|
7fb011934d2f450ad433e927a84058c4c636f02f
|
refs/heads/master
|
<repo_name>melentyev/llvm<file_sep>/tools/llvm-xray/xray-log-reader.h
//===- xray-log-reader.h - XRay Log Reader Interface ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Define the interface for an XRay log reader. Currently we only support one
// version of the log (naive log) with fixed-sized records.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_XRAY_XRAY_LOG_READER_H
#define LLVM_TOOLS_LLVM_XRAY_XRAY_LOG_READER_H
#include <cstdint>
#include <deque>
#include <vector>
#include "xray-record-yaml.h"
#include "xray-record.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
namespace llvm {
namespace xray {
class LogReader {
XRayFileHeader FileHeader;
std::vector<XRayRecord> Records;
typedef std::vector<XRayRecord>::const_iterator citerator;
public:
typedef std::function<Error(StringRef, XRayFileHeader &,
std::vector<XRayRecord> &)>
LoaderFunction;
LogReader(StringRef Filename, Error &Err, bool Sort, LoaderFunction Loader);
const XRayFileHeader &getFileHeader() const { return FileHeader; }
citerator begin() const { return Records.begin(); }
citerator end() const { return Records.end(); }
size_t size() const { return Records.size(); }
};
Error NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader,
std::vector<XRayRecord> &Records);
Error YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader,
std::vector<XRayRecord> &Records);
} // namespace xray
} // namespace llvm
#endif // LLVM_TOOLS_LLVM_XRAY_XRAY_LOG_READER_H
<file_sep>/tools/llvm-xray/xray-record.h
//===- xray-record.h - XRay Trace Record ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file replicates the record definition for XRay log entries. This should
// follow the evolution of the log record versions supported in the compiler-rt
// xray project.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TOOLS_LLVM_XRAY_XRAY_RECORD_H
#define LLVM_TOOLS_LLVM_XRAY_XRAY_RECORD_H
#include <cstdint>
namespace llvm {
namespace xray {
struct XRayFileHeader {
uint16_t Version = 0;
uint16_t Type = 0;
bool ConstantTSC;
bool NonstopTSC;
uint64_t CycleFrequency = 0;
};
enum class RecordTypes { ENTER, EXIT };
struct XRayRecord {
uint16_t RecordType;
// The CPU where the thread is running. We assume number of CPUs <= 256.
uint8_t CPU;
// Identifies the type of record.
RecordTypes Type;
// The function ID for the record.
int32_t FuncId;
// Get the full 8 bytes of the TSC when we get the log record.
uint64_t TSC;
// The thread ID for the currently running thread.
uint32_t TId;
};
} // namespace xray
} // namespace llvm
#endif // LLVM_TOOLS_LLVM_XRAY_XRAY_RECORD_H
<file_sep>/tools/llvm-xray/xray-log-reader.cc
//===- xray-log-reader.cc - XRay Log Reader Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XRay log reader implementation.
//
//===----------------------------------------------------------------------===//
#include "xray-log-reader.h"
#include "xray-record-yaml.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/FileSystem.h"
using namespace llvm;
using namespace llvm::xray;
using llvm::yaml::Input;
LogReader::LogReader(
StringRef Filename, Error &Err, bool Sort,
std::function<Error(StringRef, XRayFileHeader &, std::vector<XRayRecord> &)>
Loader) {
ErrorAsOutParameter Guard(&Err);
int Fd;
if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
Err = make_error<StringError>(
Twine("Cannot read log from '") + Filename + "'", EC);
return;
}
uint64_t FileSize;
if (auto EC = sys::fs::file_size(Filename, FileSize)) {
Err = make_error<StringError>(
Twine("Cannot read log from '") + Filename + "'", EC);
return;
}
std::error_code EC;
sys::fs::mapped_file_region MappedFile(
Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
if (EC) {
Err = make_error<StringError>(
Twine("Cannot read log from '") + Filename + "'", EC);
return;
}
if (auto E = Loader(StringRef(MappedFile.data(), MappedFile.size()),
FileHeader, Records)) {
Err = std::move(E);
return;
}
if (Sort)
std::sort(
Records.begin(), Records.end(),
[](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; });
}
Error llvm::xray::NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader,
std::vector<XRayRecord> &Records) {
// FIXME: Maybe deduce whether the data is little or big-endian using some
// magic bytes in the beginning of the file?
// First 32 bytes of the file will always be the header. We assume a certain
// format here:
//
// (2) uint16 : version
// (2) uint16 : type
// (4) uint32 : bitfield
// (8) uint64 : cycle frequency
// (16) - : padding
//
if (Data.size() < 32)
return make_error<StringError>(
"Not enough bytes for an XRay log.",
std::make_error_code(std::errc::invalid_argument));
if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
return make_error<StringError>(
"Invalid-sized XRay data.",
std::make_error_code(std::errc::invalid_argument));
DataExtractor HeaderExtractor(Data, true, 8);
uint32_t OffsetPtr = 0;
FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
FileHeader.ConstantTSC = Bitfield & 1uL;
FileHeader.NonstopTSC = Bitfield & 1uL << 1;
FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);
if (FileHeader.Version != 1)
return make_error<StringError>(
Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
std::make_error_code(std::errc::invalid_argument));
// Each record after the header will be 32 bytes, in the following format:
//
// (2) uint16 : record type
// (1) uint8 : cpu id
// (1) uint8 : type
// (4) sint32 : function id
// (8) uint64 : tsc
// (4) uint32 : thread id
// (12) - : padding
for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
DataExtractor RecordExtractor(S, true, 8);
uint32_t OffsetPtr = 0;
Records.emplace_back();
auto &Record = Records.back();
Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
Record.CPU = RecordExtractor.getU8(&OffsetPtr);
auto Type = RecordExtractor.getU8(&OffsetPtr);
switch (Type) {
case 0:
Record.Type = RecordTypes::ENTER;
break;
case 1:
Record.Type = RecordTypes::EXIT;
break;
default:
return make_error<StringError>(
Twine("Unknown record type '") + Twine(int{Type}) + "'",
std::make_error_code(std::errc::protocol_error));
}
Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
Record.TSC = RecordExtractor.getU64(&OffsetPtr);
Record.TId = RecordExtractor.getU32(&OffsetPtr);
}
return Error::success();
}
Error llvm::xray::YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader,
std::vector<XRayRecord> &Records) {
// Load the documents from the MappedFile.
YAMLXRayTrace Trace;
Input In(Data);
In >> Trace;
if (In.error())
return make_error<StringError>("Failed loading YAML Data.", In.error());
FileHeader.Version = Trace.Header.Version;
FileHeader.Type = Trace.Header.Type;
FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
FileHeader.CycleFrequency = Trace.Header.CycleFrequency;
if (FileHeader.Version != 1)
return make_error<StringError>(
Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
std::make_error_code(std::errc::invalid_argument));
Records.clear();
std::transform(Trace.Records.begin(), Trace.Records.end(),
std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
return XRayRecord{R.RecordType, R.CPU, R.Type,
R.FuncId, R.TSC, R.TId};
});
return Error::success();
}
|
6214624e0e0477526eefb9d7ace01f4838f0f183
|
[
"C++"
] | 3
|
C++
|
melentyev/llvm
|
70dde8fbf523a40ad43b8482dff9358f9a6d38a9
|
ea1389a014d9245a8336645e8f589e6daeeca7ea
|
refs/heads/master
|
<file_sep>
/*
* PIZZA Shop rest API
*
* Test Mailgun API with Mock
*/
// Dependencies
var helpers = require('./lib/helpers');
var _mailgun = require('./lib/_utils_mailgun');
var _cart = require('./lib/_cart');
// TEST data
var testEmail = '<EMAIL>';
var testArticle = {
'id' : '500',
'name' : '<NAME>',
'mixtureCzech' : 'čokoládový fondant s limetkovo-smetanovou omáčkou a vanilkovou zmrzlinou',
'mixtureEnglish' : 'chocolate fondant with lime-cream sauce and vanilla ice cream',
'price' : 85
};
var testUser = {
'email' : testEmail,
'fullName' : '<NAME>',
'address' : 'Homework 1362, CZ'
};
var emptyCart = _cart.createEmptyCart(testEmail);
emptyCart.cartItems.push(testArticle);
var testCart = _cart.recalculateCart(emptyCart);
console.log(helpers.msg_ok('CART:'));
console.log(testCart);
var testOrder = helpers.createRandomString(20);
var testDate = new Date(Date.now());
var testInvoice = _cart.createInvoice(testOrder, testDate, testUser, testCart);
console.log(helpers.msg_ok('INVOICE:'));
console.log(testInvoice);
var testConfirm = _mailgun.createEmailConfirmation(testInvoice);
console.log(helpers.msg_ok('NOTIFICATION:'));
console.log(testConfirm);
_mailgun.notifyCustomerByEmailMock(testConfirm, function(err){
if (!err){
console.log(helpers.msg_ok("MAILGUN request ended successfully"));
}else{
console.log(helpers.msg_err(err));
}
});
<file_sep>
/*
* PIZZA Shop rest API
*
* Test Success Order
*/
// Dependencies
var helpers = require('./lib/helpers');
var _user_service = require('./lib/Users_service');
var _token_service = require('./lib/tokens_service');
var _shopping_service = require('./lib/shopping_service');
var _checkout_service = require('./lib/checkout_service');
var _mailgun = require('./lib/_utils_mailgun');
var _stripe = require('./lib/_utils_stripe');
var _cart = require('./lib/_cart');
// TEST data
var testUserEmail = '<EMAIL>';
var testUserfullName = 'Homework Test';
var testUserAddress = 'Homework 125, Praha 4';
var testUserPassword = '<PASSWORD>';
_user_service.create(testUserEmail,testUserPassword,testUserfullName,testUserAddress,function(err, errCreateUser){
console.log('USER SERVICE STATUS: ', err);
if (err==200){
_user_service.findByEmail(testUserEmail,function(err,userData){
console.log('FIND USER SERVICE STATUS: ', err);
if (err==200){
console.log('USER DATA: ', userData);
_token_service.create(testUserEmail,testUserPassword,function(err,tokenData){
console.log('TOKEN SERVICE STATUS: ', err);
if (err==200){
console.log('TOKEN CREATED: ', tokenData);
_shopping_service.addToCart(testUserEmail,'100',function(err,userCart){
console.log('CART SERVICE STATUS: ', err);
if (err==200){
console.log('ARTICLE ADDED: ', userCart);
_shopping_service.addToCart(testUserEmail,'105',function(err,userCart){
console.log('CART SERVICE STATUS: ', err);
if (err==200){
console.log('ARTICLE ADDED: ', userCart);
_checkout_service.placeOrder(testUserEmail,function(err,userInvoice){
console.log('CHECKUT SERVICE STATUS: ', err);
if (err==200){
console.log('ORDER PLACED: ', userInvoice);
console.log(helpers.msg_ok('TEST SUCCESFUL'));
}else{
console.log('ORDER ERROR: ', userInvoice);
console.log(helpers.msg_err('TEST FAILED'));
}
});
}else{
console.log('ORDER ERROR: ', userCart);
console.log(helpers.msg_err('TEST FAILED'));
}
});
}else{
console.log('ORDER ERROR: ', userCart);
console.log(helpers.msg_err('TEST FAILED'));
}
});
}else{
console.log('ORDER ERROR: ', tokenData);
console.log(helpers.msg_err('TEST FAILED'));
}
});
}else{
console.log('ORDER ERROR: ', userData);
console.log(helpers.msg_err('TEST FAILED'));
}
});
}else{
console.log('ORDER ERROR: ', errCreateUser);
console.log(helpers.msg_err('TEST FAILED'));
}
});
<file_sep>/*
* PIZZA Shop rest API
*
* 1. New users can be created, their information can be edited, and they can be deleted.
* We should store their name, email address, and street address.
*
* 2. Users can log in and log out by creating or destroying a token.
*
* 3. When a user is logged in, they should be able to GET all the possible menu items
* (these items can be hardcoded into the system).
*
* 4. A logged-in user should be able to fill a shopping cart with menu items
*
* 5. A logged-in user should be able to create an order.
* You should integrate with the Sandbox of Stripe.com to accept their payment.
* Note: Use the stripe sandbox for your testing. Follow this link and click on the "tokens" tab
* to see the fake tokens you can use server-side to confirm the integration is working:
* https://stripe.com/docs/testing#cards
*
* 6. When an order is placed, you should email the user a receipt.
* You should integrate with the sandbox of Mailgun.com for this.
* Note: Every Mailgun account comes with a sandbox email account domain (<EMAIL>)
* that you can send from by default. So, there's no need to setup any DNS for your domain for this task
* https://documentation.mailgun.com/en/latest/faqs.html#how-do-i-pick-a-domain-name-for-my-mailgun-account
*
*/
// Dependecies
var server = require('./lib/server');
// Declare the app
var app = {};
// Initialize the app
app.init = function() {
// Start the server
server.init();
};
// Execute the init Function
app.init();
// Export the app
module.exports = app;
<file_sep>
/*
* PIZZA Shop rest API
*
* Test Email Validation
*/
// Dependencies
var helpers = require('./lib/helpers');
// TEST data
var testEmailGood = '<EMAIL>';
var testEmailFail = '<EMAIL>';
// Tests
var testReultGood = helpers.getValidEmailStringOrFalse(testEmailGood);
var testReultFail = helpers.getValidEmailStringOrFalse(testEmailFail);
console.log(helpers.msg_ok('Good result:'), testReultGood);
console.log(helpers.msg_err('Fail result:'), testReultFail);
var testRegExGood = testEmailGood.match(helpers.emailRegExPattern);
var testRegExFail = testEmailFail.match(helpers.emailRegExPattern);
console.log(helpers.msg_ok('Good result:'), testRegExGood);
console.log(helpers.msg_err('Fail result:'), testRegExFail);
<file_sep>## Startup steps:
1. run command from terminal
node init_env.js
2. update file api\_keys/\_key\_mailgun.json with keys (sandboxid, token_pub, token_sec)
3. update file api\_keys/\_key\_stripe.json with keys (token_pub, token_sec)
4. create folder https and provide files cert.pem and key.pem
5. review and update lib/config.js file
6. run command from terminal
node index.js
7. navigate to localhost:3000
## The APP routes:
* GET host:3000/ : index
* to show landing page
* GET host:3000/account/create
* to create a new user
* GET host:3000/account/edit
* to edit user's data, change password, delete user and user's orders, shopping cart
* GET host:3000/account/deleted
* to notify user about user's account deletion
* GET host:3000/account/history
* to get user's order history
* GET host:3000/session/create
* to login user
* GET host:3000/session/deleted
* to notify user about user has been logged out
* GET host:3000/cart/all
* to get shopping cart content (all items)
* GET host:3000/cart/add
* to add article to shopping cart
* GET host:3000/cart/edit
* to edit article in shopping cart line or delete from shopping cart
* GET host:3000/cart/checkout
* to place order and create invoice
* GET host:3000/cart/payment
* to payment for invoice
* GET host:3000/catalog/all
* offer list
* GET host:3000/ping
* up/down service test
## The API routes:
* POST host:3000/api/tokens - application/json
* body
* email, string
* password, string
* response-body
* email, string
* id, string(20)
* expires, number
* PUT host:3000/api/tokens - application/json
* body
* token, string(20)
* extend, boolean
* response-body
* email, string
* id, string(20)
* expires, number
* DELETE host:3000/api/tokens
* query string
* id, string(20)
* POST host:3000/api/users - application/json
* body
* fullName, string
* email, string
* address, string
* password, string
* PUT host:3000/api/users - application/json
* header
* token, string(20)
* body
* fullName, string
* email, string
* address, string
* password, string
* GET host:3000/api/users - application/json
* header
* token, string(20)
* body
* email, string
* response-body
* fullName, string
* email, string
* address, string
* password, string
* DELETE host:3000/api/users - application/json
* header
* token, string(20)
* query string
* email, string
* GET host:3000/api/offer
* header
* token, string(20)
* response-body
* array[object<catalog>]
* POST host:3000/api/shopping - application/json
* header
* token, string(20)
* body
* id, string(3) [100-122, 500]
* email, string
* response-body
* object<Cart>
* totalPrice, number
* totalCount, number
* cartItems, Array[object<CartItem>]
* id, string(3)
* name, string
* mixtureCzech, string
* mixtureEnglish, string
* price, number
* PUT host:3000/api/shopping - application/json
* header
* token, string(20)
* body
* id, string(3) [100-122, 500]
* index, number [0-n] = order of line in shopping cart
* email, string
* response-body
* object<Cart>
* totalPrice, number
* totalCount, number
* cartItems, Array[object<CartItem>]
* id, string(3)
* name, string
* mixtureCzech, string
* mixtureEnglish, string
* price, number
* GET host:3000/api/shopping
* header
* token, string(20)
* query string
* email, string
* response-body
* object<Cart>
* totalPrice, number
* totalCount, number
* cartItems, Array[object<CartItem>]
* id, string(3)
* name, string
* mixtureCzech, string
* mixtureEnglish, string
* price, number
* DELETE host:3000/api/shopping
* header
* token, string(20)
* query string
* email, string
* index, number [0-n] = order of line in shopping cart
* POST host:3000/api/checkout
* header
* token, string(20)
* body
* email, string
* POST host:3000/api/payment
* header
* token, string(20)
* body
* email, string
* response-body
* object<Invoice>
* POST host:3000/api/orders
* header
* token, string(20)
* body
* email, string
* response-body
* object<Invoice>
* GET host:3000/api/orders
* header
* token, string(20)
* query string
* email, string
* id, string(20)
* response-body
* case
- id == empty
* array[object<Invoice>]
- id == 'last'
* object<Invoice>
- id == valid order string(20)
* object<Invoice>
## The API documentation (POSTMAN):
https://www.getpostman.com/collections/2b52ea559d7b02b6ae8e
https://documenter.getpostman.com/view/2851355/RzZAme6k
## The Assignment (Scenario):
This is the third of several homework assignments you'll receive in this course. In order to receive your certificate of completion (at the end of this course) you must complete all the assignments and receive a passing grade.
How to Turn It In:
1. Create a public github repo for this assignment.
2. Create a new post in the Facebook Group and note "Homework Assignment #3" at the top.
3. In that thread, discuss what you have built, and include the link to your Github repo.
The Assignment (Scenario):
It is time to build a simple frontend for the Pizza-Delivery API you created in Homework Assignment #2. Please create a web app that allows customers to:
1. Signup on the site
2. View all the items available to order
3. Fill up a shopping cart
4. Place an order (with fake credit card credentials), and receive an email receipt
This is an open-ended assignment. You can take any direction you'd like to go with it, as long as your project includes the requirements. It can include anything else you wish as well.
<file_sep>1. Add homework #2 project
2. Refactor router to api routes
3. Add web app routes
4. Add index page (and template functions)
5. Add pages with forms and client javascript
6. Add page with shopping cart
7. Add page with detail of article to edit and delete
8. Add user detail page to edit and delete
9. Add checkout button to shopping cart
10. Add Total count and Total price to shopping cart
11. Add api/orders route for GET ALL, GET ID
12. Add lastOrder to userData -> last open order expire with successful payment
13. Break service.placeOrder to placeInvoice and sendPayment and notifyByEmail
14. Add payment details to checkout pages (faked card number, delivery)
15. Add Orders page with table
15. Add menu/page for listing of user's orders/payments and api routes
|
edba00ce154472c1d4b5f89ac2b05f801ffe2efb
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
ladislavlisy/Node-Master-Class-Homework-Assignment-3
|
a82fab4633d97f817f5bb4168d090e4b7619361c
|
893c8647adc87c2535925cafbcb43a8ba355381c
|
refs/heads/master
|
<repo_name>GoodForOneFare/kudos_ruby<file_sep>/app/controllers/kudos_users_controller.rb
class KudosUsersController < ApplicationController
# GET /kudos_users
# GET /kudos_users.json
def index
@kudos_users = KudosUser.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @kudos_users }
end
end
# GET /kudos_users/1
# GET /kudos_users/1.json
def show
@kudos_user = KudosUser.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @kudos_user }
end
end
# GET /kudos_users/new
# GET /kudos_users/new.json
def new
@kudos_user = KudosUser.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @kudos_user }
end
end
# GET /kudos_users/1/edit
def edit
@kudos_user = KudosUser.find(params[:id])
end
# POST /kudos_users
# POST /kudos_users.json
def create
@kudos_user = KudosUser.new(params[:kudos_user])
respond_to do |format|
if @kudos_user.save
format.html { redirect_to @kudos_user, notice: 'Kudos user was successfully created.' }
format.json { render json: @kudos_user, status: :created, location: @kudos_user }
else
format.html { render action: "new" }
format.json { render json: @kudos_user.errors, status: :unprocessable_entity }
end
end
end
# PUT /kudos_users/1
# PUT /kudos_users/1.json
def update
@kudos_user = KudosUser.find(params[:id])
respond_to do |format|
if @kudos_user.update_attributes(params[:kudos_user])
format.html { redirect_to @kudos_user, notice: 'Kudos user was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @kudos_user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /kudos_users/1
# DELETE /kudos_users/1.json
def destroy
@kudos_user = KudosUser.find(params[:id])
@kudos_user.destroy
respond_to do |format|
format.html { redirect_to kudos_users_url }
format.json { head :no_content }
end
end
end
<file_sep>/app/models/message.rb
class Message < ActiveRecord::Base
belongs_to :posted_by, :class_name => 'KudosUser'
belongs_to :recipient, :class_name => 'KudosUser'
has_many :awards , :class_name => 'Award', :foreign_key => :message_id
end
<file_sep>/app/models/award.rb
class Award < ActiveRecord::Base
belongs_to :message, :class_name => 'Message'
belongs_to :user, :class_name => 'KudosUser'
belongs_to :goal, :class_name => 'CulturalGoal'
end
<file_sep>/app/controllers/messages_controller.rb
class MessagesController < ApplicationController
# GET /messages
# GET /messages.json
def index
# TODO: limit number of initial messages, and add "More" button to base of the timeline
@messages = Message.find(:all, :order => '"messages".id DESC', :limit => 20)
@goals = CulturalGoal.all
# TODO: don't return current user in this list (to prevent self-nomination)
@users = KudosUser.all
@users = Hash[ @users.collect { |user| [ user.id, user ] } ]
@kudos_totals = findMessageAwardTotals( @goals, @messages )
respond_to do |format|
format.html # index.html.erb
format.json { render json: @messages }
end
end
# GET /messages/1
# GET /messages/1.json
def show
@message = Message.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @message }
end
end
# GET /messages/new
# GET /messages/new.json
def new
@message = Message.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @message }
end
end
# GET /messages/1/edit
def edit
@message = Message.find(params[:id])
end
# POST /messages
# POST /messages.json
def create
message_params = params[:message]
# TODO: add erros if recipient/posted_by are not found
recipient = KudosUser.find_by_user_name(message_params[:recipient])
# TODO: add logins and use the session's user ID here
posted_by = KudosUser.find_by_user_name('fred')
content = message_params[:content]
message = Message.new({ :recipient => recipient, :posted_by => posted_by, :content => content })
respond_to do |format|
if message.save
# TODO: error handling for award creation
createAwards(message, posted_by, message_params[:goal_ids])
kudos_totals = findMessageAwardTotals( CulturalGoal.all, [message] )
json_map = {
:message => message,
:kudos_totals => kudos_totals,
:users => { posted_by.id => posted_by, recipient.id => recipient }
}
format.json { render json: json_map, status: :created, location: message }
else
format.json { render json: message.errors, status: :unprocessable_entity }
end
end
end
# PUT /messages/1
# PUT /messages/1.json
def update
@message = Message.find(params[:id])
respond_to do |format|
if @message.update_attributes(params[:message])
format.html { redirect_to @message, notice: 'Message was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @message.errors, status: :unprocessable_entity }
end
end
end
# DELETE /messages/1
# DELETE /messages/1.json
def destroy
@message = Message.find(params[:id])
@message.destroy
respond_to do |format|
format.html { redirect_to messages_url }
format.json { head :no_content }
end
end
def createAwards( message, posted_by, goal_totals )
goal_totals.each do |goal_id, total|
Integer( total ).times {
award = Award.create(
:message => message,
:goal => CulturalGoal.find( goal_id ),
:user => posted_by
).save
}
end
end
def findMessageAwardTotals( goals, messages )
# For each message, create a map with 0 awards per goal
message_totals = {}
messages.each do |message|
goal_map = {}
goals.each do |goal|
goal_map[goal.id] = 0
end
message_totals[message.id] = goal_map
end
# Get an award count for each message+goal
temp_totals = Award.find(:all,
:select => '"awards".message_id, "cultural_goals".id AS goal_id, "cultural_goals".name, count("awards".id) AS kudos_total',
:joins => :goal,
:conditions => [ '"awards".message_id IN (?)', messages ],
:group => '"awards".message_id, "cultural_goals".id',
)
temp_totals.each do |total_info|
message_id = total_info.message_id
goal_id = total_info.goal_id
message_totals[message_id][goal_id] = total_info.kudos_total
end
return message_totals
end
end
<file_sep>/README.md
Kudos by Macadamian - Ruby version
==================================
Kudos is a Twitter/Facebook-like web application that allows employees to nominate one another for "kudos". An employee selects another employee, types a description of what the nominee did to elicit praise, then relates the nominee's actions to a list of corporate values by awarding points to it.
Each message has points assigned based on a list of corporate values. By default, Macadamian's values of _trust_, _learning_, _passion_, _celebrate_, _be intentional_, and _be nutty_ are used, but the code/images can be altered to use custom values.
Customing the application
=========================
(This is still a work in progress)
To customize the look of the application:
Background
----------
* _images/message\_background.png_ - change this to update the image displayed behind each message
Goals
-----
* _seeds.rb_ - add _CulturalGoal_ objects
* _images/goals_ - add images representing your business's ideals
- Ideally, these should all be of uniform height/width
* _messages.css.scss_ - tweak values based on the size of your images, and the length of your ideals' names
* _$goal\_image\_height_ - should be the height of your largest goal image
* _$minimum\_width\_for\_goal\_name\_display_ - should be a best-guess of the minimum width required to display all goal images **and** goal names on one line
* If the user's browser window is below this width, only images will be displayed
* _$message\_min\_height - enough space to display a single line of text **plus** the height of your goal images
Users
-----
* _seeds.rb_ - add _KudosUser_ objects for employees
* _images/users_ - add employee images
* _messages.css.scss_
* _$posted\_by\_image\_width_ - update this value if you wish to display larger user images (left hand side of message)
Authentication
==============
LDAP integration is planned, but not yet implemented.
TODO
====
General
-------
* Don't use jquery.all
AddMessagePanel
---------------
* Validation client side
* Validation server side
Timeline
--------
* Infinite scroll
* Poll for new messages/awards
Model
-----
* Add unique constraints
* Add not null constraints
* Add validation
White labelling
---------------
* Better support for custom posted_by image width/height
* Better support for custom recipient image width/height
Tests
-----
* There are no tests; there should be many
<file_sep>/app/models/kudos_user.rb
class KudosUser < ActiveRecord::Base
has_many :posted_messages, :class_name => 'Message', :foreign_key => :posted_by
has_many :nominations, :class_name => 'Message', :foreign_key => :recipient
has_many :awards, :class_name => 'Award', :foreign_key => :user
end
<file_sep>/app/controllers/awards_controller.rb
class AwardsController < ApplicationController
# GET /messages/:message_id/awards.json
def index
message_id = params[:message_id]
@awards = Award.where( :message_id => message_id )
respond_to do |format|
format.json { render json: @awards }
end
end
# POST /messages/:message_id/awards.json
def create
# TODO: add errors if messsage/goal is not found
message = Message.find( params[:message_id] )
goal = CulturalGoal.find( params[:goal_id] )
# TODO: add logins and use the session's user ID here
posted_by = KudosUser.find_by_user_name('fred')
@award = Award.new( :message => message, :goal => goal, :user => posted_by )
respond_to do |format|
if @award.save
awards = findMessageGoalCounts(message)
format.json { render json: { :award => @award, :goal_totals => awards }, status: :created }
else
format.json { render json: @award.errors, status: :unprocessable_entity }
end
end
end
# DELETE /messages/:message_id/awards/1.json
def destroy
message_id = params[:message_id]
goal_id = params[:goal_id]
@award = Award.where( :message_id => message_id, :goal_id => goal_id )
@award.destroy
respond_to do |format|
format.json { head :no_content }
end
end
def findMessageGoalCounts(message)
# TODO: find out why logging fails with "undefined method 'name' for "message_id":String
ActiveRecord::Base.connection.select_all( """
SELECT
cultural_goals.id AS goal_id, COUNT( awards.id ) AS kudos_total
FROM
cultural_goals
LEFT JOIN awards ON awards.goal_id = cultural_goals.id
AND awards.message_id = :message_id
GROUP BY
cultural_goals.id
""",
'SQL', { 'message_id' => message.id }
)
end
end
<file_sep>/test/unit/helpers/cultural_goals_helper_test.rb
require 'test_helper'
class CulturalGoalsHelperTest < ActionView::TestCase
end
<file_sep>/test/functional/cultural_goals_controller_test.rb
require 'test_helper'
class CulturalGoalsControllerTest < ActionController::TestCase
setup do
@cultural_goal = cultural_goals(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:cultural_goals)
end
test "should get new" do
get :new
assert_response :success
end
test "should create cultural_goal" do
assert_difference('CulturalGoal.count') do
post :create, cultural_goal: @cultural_goal.attributes
end
assert_redirected_to cultural_goal_path(assigns(:cultural_goal))
end
test "should show cultural_goal" do
get :show, id: @cultural_goal
assert_response :success
end
test "should get edit" do
get :edit, id: @cultural_goal
assert_response :success
end
test "should update cultural_goal" do
put :update, id: @cultural_goal, cultural_goal: @cultural_goal.attributes
assert_redirected_to cultural_goal_path(assigns(:cultural_goal))
end
test "should destroy cultural_goal" do
assert_difference('CulturalGoal.count', -1) do
delete :destroy, id: @cultural_goal
end
assert_redirected_to cultural_goals_path
end
end
<file_sep>/app/models/cultural_goal.rb
class CulturalGoal < ActiveRecord::Base
end
<file_sep>/test/unit/helpers/kudos_users_helper_test.rb
require 'test_helper'
class KudosUsersHelperTest < ActionView::TestCase
end
<file_sep>/app/controllers/cultural_goals_controller.rb
class CulturalGoalsController < ApplicationController
# GET /cultural_goals
# GET /cultural_goals.json
def index
@cultural_goals = CulturalGoal.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @cultural_goals }
end
end
# GET /cultural_goals/1
# GET /cultural_goals/1.json
def show
@cultural_goal = CulturalGoal.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @cultural_goal }
end
end
# GET /cultural_goals/new
# GET /cultural_goals/new.json
def new
@cultural_goal = CulturalGoal.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @cultural_goal }
end
end
# GET /cultural_goals/1/edit
def edit
@cultural_goal = CulturalGoal.find(params[:id])
end
# POST /cultural_goals
# POST /cultural_goals.json
def create
@cultural_goal = CulturalGoal.new(params[:cultural_goal])
respond_to do |format|
if @cultural_goal.save
format.html { redirect_to @cultural_goal, notice: 'Cultural goal was successfully created.' }
format.json { render json: @cultural_goal, status: :created, location: @cultural_goal }
else
format.html { render action: "new" }
format.json { render json: @cultural_goal.errors, status: :unprocessable_entity }
end
end
end
# PUT /cultural_goals/1
# PUT /cultural_goals/1.json
def update
@cultural_goal = CulturalGoal.find(params[:id])
respond_to do |format|
if @cultural_goal.update_attributes(params[:cultural_goal])
format.html { redirect_to @cultural_goal, notice: 'Cultural goal was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @cultural_goal.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cultural_goals/1
# DELETE /cultural_goals/1.json
def destroy
@cultural_goal = CulturalGoal.find(params[:id])
@cultural_goal.destroy
respond_to do |format|
format.html { redirect_to cultural_goals_url }
format.json { head :no_content }
end
end
end
|
f3c56a01d3ac53a4ec51306208a98fe3a95985c3
|
[
"Markdown",
"Ruby"
] | 12
|
Ruby
|
GoodForOneFare/kudos_ruby
|
35032abfb529256f0c47c949e8ff117bbc6ca2fb
|
6eb637bc98dfc7e2d5121a1f56799535d015d444
|
refs/heads/main
|
<repo_name>roymckenzie/JSON-QAnon<file_sep>/requirements.txt
beautifulsoup4==4.9.3
PyYAML==5.4.1
soupsieve==2.1
<file_sep>/README.md
# QAnon is a dangerous cult. This archive is for research purposes only, and I do _not_ endorse any material in this repo.
# QAnon Post Dataset
`posts.json` contains all QAnon posts as scraped from https://qposts.online as of Jan 25 2021. The JSON has been dumped with `ensure_ascii=False` so should be UTF-8 but there may be some encoding gotchas I haven't caught (`text` fields contain text with line breaks as literal `\n`). I did my best in terms of avoiding capture glitches/bad logic but I didn't read through all 4k posts so caveat emptor; I make no guarantees of data integrity.
Posts reference images which I have opted not to include in this repo due to their distasteful content; the text is already quite enough and then some. You should be able to download the images with the mirror script below if you so desire; the `file` in `images` refers to the filename of the image as referred to by https://qposts.online at the time of indexing. There are about 800MB of images. I cannot speak to the durability of these image filename references but they will be accurate if you run the extraction yourself (i.e. if the file naming scheme is changed, this script will pick it up).
_N.B.: The script as-is will consolidate links with spaces in the middle (making them invalid) into links without spaces (for example `https:// twitter. com/` becomes `https://twitter.com/`). As far as I can tell, Q's original posts contained these spaces; I elected to remove them for the sake of functioning links. If you want this whitespace left untouched, you can set `KEEP_ORIGINAL_WHITESPACE` to `True` and the script will make no attempts at coercing them into well-formed links._
## Do it Yourself
Took me about two hours for a total mirror on a terrible hotel wifi using a one second pause between requests; yours will probably go much faster on good internet (but remember to be a good netizen and rate limit requests, especially to a non-API. Depending on how low of a profile you want to keep, bump up the `--wait=1` option higher to wait more than one second between each request).
To run your own extraction, mirror the site, update `DIRECTORY` in `collate.py` to point at the HTML location after mirroring, enter a `venv` and install the `requirements.txt`, then let it rip. It will dump the results as a JSON array to `posts.json` (should take a few seconds).
```bash
# repo clone
git clone <EMAIL>:jkingsman/JSON-QAnon.git
cd JSON-QAnon
# setup + installation
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
chmod +x collate.py
# site mirroring
wget --wait=1 --level=inf --recursive --page-requisites --no-parent --convert-links --adjust-extension --no-clobber --restrict-file-names=windows -e robots=off https://qposts.online/
# collation; results in posts.json
# remember to update DIRECTORY if the posts aren't in ./qposts.online/page relative to the script
./collate.py
```
## Schema
Actual JSON schemas give me a headache, so here it is in markdown form. If someone is really desperate for a JSON schema, I can probably scrape something together. This schema assumes all keys are mandatory unless labeled as optional.
The JSON takes the form of an array of `post` objects under the `posts` key. A post consists of:
* `post_metadata`: an object containing misc. information about the post (object)
* `id`: the numerical ID of the post (sequentially up from 1) (integer)
* `author`: the author of the post; usually `Q` or `Anonymous` (string)
* `source`: an object containing information about the post's origin (object)
* `board`: the chan board the post came from (string)
* `site`: one of `4ch`, `8ch`, or `8kun`, indicating the site the post is from (4chan, 8chan, or 8kun) (string)
* `link`: link to the original post (optional) (string)
* `time`: epoch timestamp of posting time (integer/timestamp)
* `text`: the text of the post with newlines delimited by literal `\n` (string, optional)
* `images`: an array of objects indicating images used in the post (object, optional)
* `file`: the name of the image file itself as archived from https://qposts.online (string)
* `name`: the name of the image as it was named when posted to the image board (string)
* `referenced_posts`: an array of objects indicating replied-to posts within Q's post (i.e. `>>8251669`) (object, optional)
* `reference`: the string within the `text` of the main post that referred to this one (string)
* `text`: the text of the referenced post with newlines delimited by literal `\n` (string, optional) (string, optional)
* `images`: an array of objects indicating images used in the post (object, optional)
* `file`: the name of the image file itself as archived from https://qposts.online (string)
* `name`: the name of the image as it was named when posted to the image board (string)
### Debugging
If the `filename` key in `post_metadata`, the metadata will contain the `filename` key which is a string indicating the HTML file that particular post was pulled from; this can be combined with the other commented-out blocks containing `helpful for debugging` which can restrict the parsing to a single post from a single file wich is helpful for debugging extraction/formatting/etc.
## Misc. Analysis Snippets
### Extract all Q posts to file
To extract all of Q and only Q's posts without regard to images, referenced posts, etc., this `jq` command can be used (the `| select(.)` carves out `null` values generated by extracting the non-existent text key from posts with images only):
```
cat posts.json | jq --raw-output '.posts[].text | select(.)' > aggregated.txt
```
### Get top ten most linked-to domains in Q posts (and count of links)
To get the top ten domains, we'll first extract the post body and `grep` for all URL-like structures. Then we'll use `awk` to set both `:` and `/` as field separators and extract the fourth field (the domain). Then we'll use the common idiom of `sort | uniq -c | sort -nr`: `sort` will alphabetically sort the posts so that `uniq -c` can count the number of unique occurrences (in actuality `uniq -c` only provides a count of line repeats, but since it's sorted the number of repeats will be the number of times the unique line occurred) and then `sort -nr` will sort `n`umerically in `r`everse order, giving us occurences listed by descending count. Finally, `head -10` will extract the first ten lines from the results.
```bash
cat posts.json |
jq --raw-output '.posts[].text | select(.)' |
grep -Eo "(http\S*)" |
awk -F[/:] '{print $4}' |
sort | uniq -c | sort -nr |
head -10
```
### Iterate with python
```python
import json
with open('posts.json') as f:
data = json.load(f)
for post in data['posts']:
# do things here
# example of printing all post texts where they exist
if 'text' in post:
print(post['text'])
```
## Fine Print
I provide this data for data analysis use only; the content is distasteful and misleading to put it charitably and I do not endorse it.
The site itself is laid out mostly logically in terms of HTML and formatting so I have high hopes for consistency over time as it pertains to the screen scraping, but should it change dramatically, this extraction script will obviously break. I've tried to lay the script out as modularly as I can so that updates can be made with a reasonable amount of effort but I make no guarantees of durability, nor that I will have time or interest to update the script to stay current, to be brutally honest.
The code in my extraction script is licensed under MIT (and please cite me if my script or its results is utilized as part of academic research -- I'd love to read a preprint!); as the extracted posts are not my content, I cannot license them in any degree.
<file_sep>/collate.py
#!/usr/bin/env python3
import copy
import json
import os
import re
from bs4 import BeautifulSoup
import yaml
# location of 1.htm, 2.htm, etc.
PAGES_DIRECTORY = 'qposts.online/page'
# when False, trim stray whitepaces from links in posts+refs; see explanation in clean_up_raw_text()
KEEP_ORIGINAL_WHITESPACE = False
def extract_metadata_block(meta_container):
"""
Extracts author + tripcode, source site + board, and link if applicable.
Returns an object of what it finds.
"""
collated_metadata = {}
# extract the span with the name+tripcode in it
author_container = meta_container.find('span', 'name')
# extract the bold/strong text -- i.e. the main name
author = author_container.find('strong').getText()
assert len(author) > 0, 'Author name not found!!'
collated_metadata['author'] = author
# remove the main name, leaving only the tripcode if applicable (and strip l/r whitespace)
author_container.find('strong').decompose()
maybe_tripcode = author_container.getText().strip()
if maybe_tripcode:
collated_metadata['tripcode'] = maybe_tripcode
# extract source board + site block
source_container = meta_container.find('span', 'source')
# extract the bold/strong text -- i.e. the board name
board = source_container.find('strong').getText()
assert len(board) > 0, 'Board name not found!!'
collated_metadata['source'] = {}
collated_metadata['source']['board'] = board
# remove the board name, leaving only the site (and maybe link if applicable)
source_container.find('strong').decompose()
# get thread link if we have it
maybe_thread_link = source_container.find('a')
if maybe_thread_link:
collated_metadata['source']['link'] = maybe_thread_link['href']
maybe_thread_link.decompose()
# we've extracted board name and link if we have it; all that's left is the site
site = source_container.getText().strip()
assert site, 'Site not found!!'
collated_metadata['source']['site'] = site
# attach timestamp
collated_metadata['time'] = int(meta_container.find('span', 'time').getText())
# attach id
collated_metadata['id'] = int(meta_container.find('span', 'num').getText())
return collated_metadata
def extract_images(post_block):
"""
Extracts image filename + uploaded image name for all images in a post/reference.
Returns a list of objects containing filename + uploaded name
"""
images_container = post_block.find('div', 'images', recursive=False)
if not images_container:
return None
# well laid out figs + figcaptions make life easy for images + image names
images = images_container.findAll('figure', recursive=False)
return [{
'file': os.path.split(image.find('a')['href'])[1], # filename on disk
'name': image.find('figcaption').getText() # filename as posted
} for image in images]
def extract_body(post_block, is_ref=False):
"""
Extracts the main body text as plaintext less any referenced divs, images, html tags, etc.
Returns a string; newlines indicated by literal \n.
"""
"""
During body extraction, I decompose a number of elements (including divs, which contain post
references) which basically vaporizes them. Since we need the (post) references later to extract
and python is pass by reference*, we need to duplicate the object.
* if you pull an https://xkcd.com/386/ and say something like "ackchyually in python, object
references are passed by value..." I will find you and smack you
"""
post_block_copy = copy.copy(post_block)
# just attempt to find the main text content; some main posts have a div for this, some
# don't, and no references have it so try/catch
try:
content_div = post_block_copy.find('div', 'text')
if content_div:
post_block_copy = content_div
except AttributeError:
pass
# this is random div noise (unlikely) or a referenced post (almost always); regardless, we don't
# want it/them
divs = post_block_copy.findAll('div')
for div in divs:
div.decompose()
# bs4 thinks these tags need a separator when rendering with get_text(); who knows why...
# Unwrapping them seems to solve it. If any other tags that need to be unwrapped pop up, throw
# them in tags_to_unwrap
tags_to_unwrap = ['abbr', 'em']
for tag_to_unwrap in tags_to_unwrap:
instances_to_unwrap = post_block_copy.findAll(tag_to_unwrap)
for instance_to_unwrap in instances_to_unwrap:
instance_to_unwrap.unwrap()
# Get your pitchforks ready. I don't know why bs4 behaves this way but for some reason it's
# throwing separators where there shouldn't be after unwrapping the abbrs but extracting and
# reparsing seems to fix it. I hate it; I don't understand it; it works; it stays.
post_block_copy_duplicate = BeautifulSoup(str(post_block_copy), 'html.parser')
raw_post_text = post_block_copy_duplicate.get_text(separator="\n")
return clean_up_raw_text(raw_post_text)
def extract_references(post_block):
"""
Extracts the referenced posts from the main post block and returns a list of posts, which always
contains the text that referred to it in the original post (e.g. >>123456) and can contain image
objects + text objects.
Returns a list of post objects.
"""
refs = post_block.findAll('div', 'op')
if not refs:
return None
collated_refs = []
for ref in refs:
collated_ref = {}
# the referring text is always the immediately previous sibling of the reference
collated_ref['reference'] = ref.previous_sibling.getText()
# extract reference text if we have it
maybe_text = extract_body(ref, is_ref=True)
if maybe_text:
collated_ref['text'] = clean_up_raw_text(maybe_text)
# extract the reference's image if we have any
maybe_images = extract_images(ref)
if maybe_images:
collated_ref['images'] = maybe_images
collated_refs.append(collated_ref)
return collated_refs
def clean_up_emails(post):
"""
This a dumb way to handle this but the post site uses a server-side email protection script (I
guess for anti-spam) and it's a little overzealous (note this does not show up in the original
Q posts; these are an artifact introduced by the current host I'm scraping from). Thankfully,
usage is minimal so I just wrote a function to slot them in from the known list. If
significantly more posts are added that trip the protection system or it changes (or the
timestamps are changed but I assume those to be immutable) this will need additional TLC.
"""
if post['post_metadata']['time'] == 1526767434:
post['post_metadata']['author'] = 'NowC@mesTHEP@in—-23!!!'
# Q sure liked this link; three separate posts using it
if post['post_metadata']['time'] in [1588693786, 1585242439, 1553795409]:
post['text'] = post['text'].replace('email\xa0protected]',
'https://uscode.house.gov/view.xhtml?path=/prelim@title'
'18/part1/chapter115&edition=prelim')
return post
def clean_up_raw_text(text):
"""
This corrects some minor oddities in spacing/link text. These show up in the original posts
(as far as I can tell) so removing them technically changes the content of original or
referenced posts. If this is an issue, set KEEP_ORIGINAL_WHITESPACE to True and this will be
short-circuited.
"""
if KEEP_ORIGINAL_WHITESPACE:
return text
# eliminate spaces after http://
http_whitespace_regex = re.compile(r"http:\/\/\s+")
text = http_whitespace_regex.sub('http://', text)
# eliminate spaces after https://
https_whitespace_regex = re.compile(r"https:\/\/\s+")
text = https_whitespace_regex.sub('https://', text)
# tuples of find/replace for known bad URLs
misc_spaced_url_corrections = [
('twitter. com', 'twitter.com'),
('theguardian. com', 'theguardian.com'),
]
for search, replacement in misc_spaced_url_corrections:
text = text.replace(search, replacement)
return text
collected_posts = []
# loop through all html files in the directory to be scanned
entry_count = len(os.listdir(PAGES_DIRECTORY))
current_entry = 1
for entry in os.scandir(PAGES_DIRECTORY):
print(f"Processing entry {current_entry} of {entry_count}")
current_entry += 1
# # helpful for debugging -- skip all files but this one
# if entry.name != '1.html':
# continue
# parse the page html
soup = BeautifulSoup(open(entry.path), 'html.parser')
# extract all posts
posts = soup.findAll('div', {'class': 'post', 'data-timestamp': True})
for post in posts:
collated_post = {}
# yank metadata
meta_container = post.find('div', 'meta')
collated_post['post_metadata'] = extract_metadata_block(meta_container)
# # helpful for debugging -- append src file to metadata
# collated_post['post_metadata']['filename'] = entry.name
# # helpful for debugging -- skip all posts but this ID
# # requires scrape_metadata to be appended above
# if collated_post['post_metadata']['id'] != 4939:
# continue
# break out main meat of the post for easier manipulation
post_body = post.find('div', 'message')
# yank images
extracted_images = extract_images(post_body)
if extracted_images:
collated_post['images'] = extracted_images
# yank main post text
extracted_body = extract_body(post_body)
if extracted_body:
collated_post['text'] = extracted_body
# yank referenced posts
referenced_posts = extract_references(post_body)
if referenced_posts:
collated_post['referenced_posts'] = referenced_posts
# clean up emails -- see func comment; this is maximum clowntown
collated_post = clean_up_emails(collated_post)
# attach to big list
collected_posts.append(collated_post)
# sort by date asc
collected_posts.sort(key=lambda post: post['post_metadata']['time'])
# pretty print and dump it
# if you're desperate, removing indent=2 shaves a half meg off
keyed_list = {"posts": collected_posts}
with open('posts.yml', 'w') as outfile:
yaml.dump(keyed_list, outfile, allow_unicode=True)
with open('posts.json', 'w') as outfile:
json.dump(keyed_list, outfile, indent=2, ensure_ascii=False)
|
20fbcc8146fa3ce03e6709716476a351f0969f5f
|
[
"Markdown",
"Python",
"Text"
] | 3
|
Text
|
roymckenzie/JSON-QAnon
|
d1549f8063c41a167449b3556072af1c048b18e7
|
c040cdee04048a6c56178aebf7f52ea41db91e52
|
refs/heads/master
|
<file_sep>class Api::PlacesController < ApplicationController
def index
@places = Place.all
if params[:name_search]
@places = @places.where("name ILIKE ?", "%" + params[:name_search].to_s + "%")
end
@places = @places.order(:id => :asc)
render "index.json.jb"
end
def create
@place = Place.new(
name: params["name"],
address: params["address"],
image: params["image"],
)
@place.save
render "show.json.jb"
end
def show
@place = Place.find_by(id: params["id"])
render "show.json.jb"
end
def update
@place = Place.find_by(id: params["id"])
@place.name = params["name"] || @place.name
@place.address = params["address"] || @place.address
@place.image = params["image"] || @place.image
@place.save
render "show.json.jb"
end
def destroy
@place = Place.find_by(id: params["id"])
@place.destroy
render json: { message: "Place successfully deleted!" }
end
end
|
781e880127116ba049d993ff4d05a582dac61c2d
|
[
"Ruby"
] | 1
|
Ruby
|
fionaian/example_places_app
|
6105eb63690c921b1b1dfac98aec7fbd6c453e93
|
bd2dc9ca615f54434cd015864f035a042588cd81
|
refs/heads/master
|
<repo_name>loudmouse/photo_spotlight<file_sep>/script.js
$(document).ready(function(){
// Start Featured Photographer - Unsplash API
const div = document.getElementById('featured-photographer');
const photog_url = 'https://api.unsplash.com/users/lanceanderson?&client_id=3af8662ba60ee5845668e501d7ecd832331c22e5d9c1b95de45e008c734adea1';
function createNode(element) {
return document.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
fetch(photog_url)
.then((resp) => resp.json())
.then(function(data) {
let photos = data;
let name = photos["name"];
let twitter = photos["twitter_username"];
let instagram = photos["instagram_username"];
let portfolio = photos["portfolio_url"];
let bio = photos["bio"];
let location = photos["location"];
let unsplash = photos["links"]["html"];
let first_name = photos["first_name"];
let name_data = createNode('p'),
twitter_data = createNode('li'),
instagram_data = createNode('li'),
unsplash_data = createNode('li'),
social_ul = createNode('ul'),
social_div = createNode('div'),
portfolio_data = createNode('li'),
location_data = createNode('div'),
bio_data = createNode('p'),
img = createNode('img'),
ul = createNode('ul'),
buttonContainer = createNode('div'),
span = createNode('span');
name_data.className = "featured-name text-center";
twitter_data.className = "featured-twitter";
instagram_data.className = "featured-instagram";
social_ul.className = "social-ul";
social_div.className = "social-div text-center";
portfolio_data.className = "featured-porfolio";
location_data.className = "featured-location text-center";
unsplash_data.className = "featured-unsplash";
bio_data.className = "featured-bio";
img.className = "featured-image";
span.className = "span-item";
ul.className = "featured-ul";
div.className = "profile-div";
buttonContainer.className = "button-container text-center";
img.src = photos["profile_image"]["large"];
name_data.innerHTML = `Featuring:<br>${name}`;
twitter_data.innerHTML = `<a href="https://twitter.com/${twitter}" target="_blank" class="btn btn-primary btn-block" role="button" aria-pressed="true"><i class="fa fa-twitter"></i> Follow ${twitter} on Twitter</a>`;
instagram_data.innerHTML = `<a href="https://www.instagram.com/${instagram}" target="_blank" class="btn btn-primary btn-block" role="button" aria-pressed="true"><i class="fa fa-instagram"></i> Follow ${instagram} on Instagram</a>`;
unsplash_data.innerHTML = `<a href="${unsplash}" target="_blank" class="btn btn-primary btn-block" role="button" aria-pressed="true"><i class="fa fa-camera"></i> View ${first_name}'s Photos on Unsplash</a>`;
portfolio_data.innerHTML = `Porfolio: ${portfolio}`;
location_data.innerHTML = `<i class="fa fa-map-marker"></i>${location}`;
bio_data.innerHTML = `Bio: ${bio}`;
append(div, img);
append(div, name_data);
append(div, location_data);
append(social_ul, twitter_data);
append(social_ul, instagram_data);
append(social_ul, unsplash_data);
append(social_div, social_ul);
append(div, social_div);
append(div, buttonContainer);
append(div, ul);
twitter_data.id = "featured-twitter-button";
var hasTwitter = document.getElementById("featured-twitter-button");
if (twitter === null) {
hasTwitter.style.display = 'none';
}
instagram_data.id = "featured-instagram-button";
var hasInstagram = document.getElementById("featured-instagram-button");
if (instagram === null) {
hasInstagram.style.display = 'none';
}
location_data.id = "featured-location-indicator";
var hasLocation = document.getElementById("featured-location-indicator");
if (location === null) {
hasLocation.style.display = 'none';
}
})
// End Featured Photographer - Unsplash API
// Start Unsplash API for Featured Photos
const ul = document.getElementById('photos');
const url = 'https://api.unsplash.com/collections/3363781/photos?&per_page=12&client_id=3af8662ba60ee5845668e501d7ecd832331c22e5d9c1b95de45e008c734adea1';
function createNode(element) {
return document.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let photos = data;
return photos.map(function(photo) {
let name = photo.user.name;
let unsplashLink = photo.links.html;
let li = createNode('li'),
img = createNode('img'),
span = createNode('span');
li.className = "image-list-item";
img.className = "image-item";
span.className = "span-item";
ul.className = "ul-item";
img.src = photo.urls.small;
span.innerHTML = `<a href="${unsplashLink}" target="_blank"><i class="fa fa-camera"></i> ${name}</a>`;
append(li, img);
append(li, span);
append(ul, li);
})
})
.catch(function(error) {
console.log(error);
});
// END UNSPLASH API
// START TIMER
// Set the date we're counting down to
var countDownDate = new Date("Oct 17, 2018 17:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="countdown-container"
// document.getElementById("countdown-container").innerHTML = days + "d " + hours + "h "
// + minutes + "m " + seconds + "s ";
document.getElementById("sign-up-button").innerHTML = "A winner will be selected in: " + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
// if (distance < 0) {
// clearInterval(x);
// document.getElementById("countdown-container").innerHTML = "EXPIRED";
// }
if (distance < 0) {
clearInterval(x);
document.getElementById("sign-up-button").innerHTML = "Sorry, this giveaway has ended!";
}
}, 1000);
// Set the date we're counting down to
var countDownDateBg = new Date("Dec 5, 2018 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown-container-bg").innerHTML = "EXPIRED";
}
}, 1000);
});
<file_sep>/readme.md
## Purpose
Each week we wanted to feature a photo on a theme from a different photographer. We'd then also share photos from other photographers on that same theme. This first week's feature was **architectural photography**.
---
## Live Site
For a live version, visit: [Artmill Featured Photo Spotlight](https://www.artmill.com/blog/photo-spotlight-architectural-photography/)
---
## Github Repository
To view code for the prototype, visit: [the GitHub repo](https://github.com/loudmouse/photo_spotlight)
---
## Requirements
1. I needed to build a system that once in place could be easily updated each week by a non-technical member of our team.
2. The system would need to automatically display relevant info about the featured photographer such as his or her name, a profile photo, location, and social media links.
3. The system would also need to pull in a collection of similarly themed photos and display those on the page.
---
## My Solution
I built a template for our blog that could be copied and edited in a few places to generate fresh content each week. I chose to use the [Unsplash API](https://unsplash.com/documentation). Unsplash is a website that provides, in their own words, "Beautiful, free photos. Gifted by the world’s most generous community of photographers.".
I used javascript's fetch method to make calls to a couple of Unsplash's API endpoints to pull in the info I needed.
1. I called the `users` endpoint which allowed me to get a user's public profile.
- With this call I was able to access the user's name, profile photo, location, and social media links.
2. I also called the `collections` endpoint which allowed me to retrive a single collection.
- We had curated photos into a collection based on each week's photo theme. I could simply make a call to this endpoint, passing it the `:id` of our collection and I'd access the image in this manner.
I then used javascript to render HTML elements to the page with custom classes. I next used CSS and some Bootstrap to style the HTML that was rendered on page.
---
## Tech Stack
### [Javascript](https://www.javascript.com/)
<!-- The programming language used -->
### [Unsplash API](https://unsplash.com/documentation)
<!-- The programming language used -->
### [Bootstrap](https://getbootstrap.com/)
<!-- The framework used -->
### [HTML](https://www.w3.org/html/)
<!-- The framework used -->
### [CSS](https://developer.mozilla.org/en-US/docs/Web/CSS)
<!-- The framework used -->
---
## Screenshot

|
299e342e5c6f3a3545868544b5c722975bb62855
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
loudmouse/photo_spotlight
|
cef49e4da5978e46faeddbf9cb8317e61572349b
|
cfe336ec65716b3ce7ed8693a0f0b2632d62fdd9
|
refs/heads/master
|
<file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="description" content="Free Bootstrap Theme by BootstrapMade.com">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta name="keywords" content="free website templates, free bootstrap themes, free template, free bootstrap, free website template">
<link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Satisfy|Bree+Serif|Candal|PT+Sans">
<link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<style>
body{
background-image: url('http://i65.tinypic.com/332crup.jpg');
background-size: cover;
}
.end{
background-color:black;
height:74px;
text-align:center
}
</style>
</head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<!--Navigation bar-->
<nav class="navbar navbar-inverse navbar-fixed-top" ><!--color-->
<div class="container-fluid">
<div class="navbar-header">
<button type = "button" class = "navbar-toggle" data-toggle = "collapse" data-target="#nvb">
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">
<span style = "color:white"><span style = "color:red">S</span>outhern<span style = "color:red">S</span>picia</span>
</a>
</div>
<div class = "collapse navbar-collapse" id = "nvb">
<ul class="nav navbar-nav navbar-right" >
<li style="font-family: comic sans ms;font-size: 20px;">
<span style="color: white;">Welcome
<?php
$conn = mysqli_connect('localhost', 'root', '', 'final');
$sql = "select * from member";
$rs = $conn->query($sql);
while($row = $rs->fetch_assoc()){
$a = $_SESSION['mob'];
$b = $_SESSION['pass'];
if($row['mobile'] == $a && $row['pwd'] == $b){
echo $row['first'];
}
}
?>
</span>
</li>
<li style="font-family: comic sans ms;font-size: 20px;"><a href="logout.php"><span>LogOut</span></a></li>
</li>
</ul>
</div>
</div>
</nav>
<a href="http://tinypic.com?ref=264sxsx" target="_blank"><img src="http://i67.tinypic.com/264sxsx.png" border="0" alt="Image and video hosting by TinyPic" style="padding-top: 80px; padding-left: 350px;"></a>
<a href="http://tinypic.com?ref=143446w" target="_blank"><img src="http://i63.tinypic.com/143446w.png" border="0" alt="Image and video hosting by TinyPic" style="padding-top: 0px; padding-left: 350px;"></a>
<a href="http://tinypic.com?ref=25qgffl" target="_blank"><img src="http://i68.tinypic.com/25qgffl.png" border="0" alt="Image and video hosting by TinyPic" style="padding-top: 0px; padding-left: 350px;"></a>
<a href="http://tinypic.com?ref=5md1tf" target="_blank"><img src="http://i63.tinypic.com/5md1tf.png" border="0" alt="Image and video hosting by TinyPic" style="padding-top: 0px; padding-left: 350px;"></a>
<br><br>
</body>
</html>
|
9f7554aa847178fa2ea4ae7a922935431bdda7af
|
[
"PHP"
] | 1
|
PHP
|
adityanair97/Software
|
065a4ef56810dff7f4a913578a2acdda1d236215
|
dedd2f4100f85c9a809fb031bd4de9c23bbae016
|
refs/heads/master
|
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package semana6;
/**
*
* @author usuario
*/
public class semana6 {
private String nombre;
private String apellido;
private String Sexo;
private String direccion;
private String nomMedico;
private String motivoConsul;
private String lugar;
public semana6(String nombre, String apellido, String Sexo, String direccion) {
this.nombre = nombre;
this.apellido = apellido;
this.Sexo = Sexo;
this.direccion = direccion;
}
public semana6(String nomMedico, String motivoConsul) {
this.nomMedico = nomMedico;
this.motivoConsul = motivoConsul;
}
public semana6(String lugar) {
this.lugar = lugar;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public String getSexo() {
return Sexo;
}
public String getDireccion() {
return direccion;
}
public String getNomMedico() {
return nomMedico;
}
public String getMotivoConsul() {
return motivoConsul;
}
public String getLugar() {
return lugar;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package semana6;
/**
*
* @author usuario
*/
public final class cenDeSalud extends semana6{
private int fecha;
public cenDeSalud(int fecha, String lugar) {
super(lugar);
this.fecha = fecha;
}
public final void mostrar3() {
System.out.println("\nCentro de salud\nLugar: "+getLugar()+"\nFecha: "+fecha);
}
}
|
2292e1bc2c31f63747eee2f564946d65f5b23006
|
[
"Java"
] | 2
|
Java
|
Diegojimenez678/actividad-semana6
|
dce4952ddf28055e6ab3957d64ec78b06b50e287
|
2cbfd150a3491614e0a3c6576274454b67a58fa0
|
refs/heads/main
|
<file_sep>// this function finds the first occurrence of a character in a string
function findStartIndexOfPattern(str,char) {
let currentIndex = 99999999
let minIndex = 99999999
for(let k = 0; k < str.length; k++) {
if(char === str[k]) {
currentIndex = k;
if(currentIndex < minIndex){
minIndex = currentIndex;
}
}
}
return minIndex;
}
// this function finds the last occurrence of a character in a string
function findEndIndexOfPattern(str,char) {
let currentIndex = 99999999
let maxIndex = -1;
for(let j = 0; j < str.length; j++) {
if(char === str[j]) {
currentIndex = j;
if(currentIndex > maxIndex)
maxIndex = currentIndex;
}
}
return maxIndex;
}
// If we provide the match function with an input string, which will be our candidate code, and an input pattern, which will be a distracting word, this function will check to see if the pattern is present even in a non-consecutive manner in our candidate code. This function checks to see if the characters in the input string are in the same order as the characters in the pattern, using the above two helper functions.
function match(str,ptn) {
let lastCharMaxIndex = -1
let currentCharMaxIndex = -1
let currentCharMinIndex = -1
let isMatched = true;
lastCharMaxIndex = findEndIndexOfPattern(str,ptn[0]);
for (let i = 1; i < ptn.length; i++) {
currentCharMaxIndex = findEndIndexOfPattern(str,ptn[i]);
currentCharMinIndex = findStartIndexOfPattern(str,ptn[i]);
if (lastCharMaxIndex < currentCharMaxIndex && lastCharMaxIndex < currentCharMinIndex) {
isMatched = true;
}
else {
isMatched = false;
}
lastCharMaxIndex = currentCharMinIndex;
if(isMatched === false)
break;
}
return isMatched;
}
// This validateCode function is the function that ties in the above helper functions to check for the presence of a distracting word in our candidate code in a non-consecutive way, as well as checking if a distracting word is present in a consecutive manner in our candidate code, and whether the candidate code has already been used given an array of existing codes
function validateCode(code, distractingWords, existingCodes) {
let regex = /[^a-zA-Z]/g;
let justLetters = code.replace(regex, "");
if (existingCodes.includes(code)){
return false
} else {
for (let i = 0; i < distractingWords.length; i++){
if (distractingWords[i] === justLetters.toLowerCase() || match(code.toLowerCase(), distractingWords[i])){
return false
}
}
}
return true
}
module.exports = validateCode<file_sep># Desmos Candidate Code Validator
### Language: Javascript
### Testing library: Jest
# To do:
### Pull down repo
### Run 'npm test'
- console will show results of test
- can also check 'lcov-report' directory for index.html file...copy path into browser for more information on tests
|
7e80e6fc021ac457ce48258353d8a46781d2a2b0
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
dr-dolce14/desmos-code-jest
|
078988bf6a4a01f3d788350004708df0b7b5d5b7
|
fd07487e09465e8bb149d8b1038d063993e2b78e
|
refs/heads/master
|
<repo_name>kgalanty/ProductCheckoutRedirect<file_sep>/modules/addons/ProductCheckoutRedirect/templates/lib/DispatcherAPI.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect;
/**
* Dispatch Handler
*/
class DispatcherAPI {
public static function dispatch($controller, $action, $parameters)
{
if (!$action) {
// Default to index if no action specified
$action = 'index';
}
$controller = 'WHMCS\\Module\\Addon\\ProductCheckoutRedirect\\Controllers\\'.ucfirst($controller);
if(class_exists($controller))
{
$controller = new $controller();
}
else
{
return ['error' => 'Controller doesnt exist'];
}
// Verify requested action is valid and callable
if (is_callable(array($controller, $action))) {
$return = $controller->$action($parameters);
return $return;
}
else{
return ['error' => 'Action doesnt exist'];
}
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/Models/Redirs.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\Models;
use Illuminate\Database\Eloquent\Model;
class Redirs extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
public $timestamps = false;
protected $table = 'kg_pids_redir';
protected $fillable = ['pid', 'redirurl'];
public function product()
{
return $this->hasOne(\WHMCS\Product\Product::class, 'id', 'pid')->select(array('id', 'name'));;
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/app/Hooks/ClientAreaFooterOutput.php
<?php
use WHMCS\Database\Capsule as DB;
use WHMCS\Module\Addon\ProductCheckoutRedirect\Models\Redirs;
return function($vars) {
if($vars['action'] != 'complete') return;
$hid = DB::table('tblinvoiceitems')
->join('tblhosting', 'tblhosting.id', '=', 'tblinvoiceitems.relid')
->where('invoiceid', $vars['invoiceid'])
->where('type', 'Hosting')->first(['relid', 'tblhosting.packageid']);
$redirect = Redirs::where('pid', $hid->packageid)->first();
if($redirect)
{
return '<script>$("#btnClientArea").hide();$("#customRedirect").show();$("#btnClientArea2").on("click", function () { $(this).find(".button-text").css("visibility", "hidden"); $(this).find(".preloader").css("visibility", "visible"); window.location = "{$redirect->redirurl}"; });</script><META http-equiv="refresh" content="5;URL='.$redirect->redirurl.'" />';
}
};
<file_sep>/README.md
# Product Checkout Redirect
## Project setup
1. Copy `modules` dir to `main WHMCS dir` so it can integrate with current modules dir.
<file_sep>/modules/addons/ProductCheckoutRedirect/lib/app/Controllers/API.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\app\Controllers;
use WHMCS\Module\Addon\ProductCheckoutRedirect\app\Models\Redirs;
use WHMCS\Module\Addon\ProductCheckoutRedirect\app\Models\Products;
/**
* Admin Area Controller
*/
class API {
/**
* Index action.
*
* @param array $vars Module configuration parameters
*
* @return string
*/
public $params, $input;
public function __construct($params, $input)
{
$this->params = $params;
$this->input = $input;
}
public function indexJSON()
{
$query = Redirs::with(['product'])->get();
$return = [];
foreach($query as $row)
{
$return[] = ['pid' => $row->pid, 'name' => $row->product->name, 'redirurl' => $row->redirurl];
}
return $return;
}
public function storeJSON()
{
try
{
foreach($this->input['payload'] as $row)
{
Redirs::where('pid', $row['pid'])->update(['redirurl' => $row['redirurl']]);
}
return 'success';
}
catch(\Exception $e)
{
return 'error';
}
}
public function getProductsJSON()
{
$products = Products::doesntHave('redir')
->where('name', '<>', '')
->orderBy('name', 'ASC')
->get(['id', 'name']);
$returnProducts = [];
foreach($products as $product)
{
$returnProducts[] = ['pid' => $product->id, 'name' => $product->name];
}
return $products;
}
public function deleteJSON()
{
if($this->input)
{
Redirs::where('pid', $this->input['payload'])->delete();
return 'success';
}
return 'No product to delete';
}
public function addJSON()
{
if($this->input)
{
if(Redirs::create(['pid' => (int)$this->input['pid'], 'redirurl' => $this->input['redirurl']]))
{
return 'success';
}
return 'error';
}
return 'No product to delete';
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/HooksManager.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect;
class HooksManager
{
public static function run()
{
foreach(glob(__DIR__.'/app/Hooks/*.php') as $file)
{
$hookfile = include($file);
add_hook(basename($file, '.php'), 1, $hookfile);
}
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/VueController.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect;
abstract class VueController
{
const COMPONENTSDIR = __DIR__.'/app/Components/';
public $components;
public function __construct()
{
if($this->vueComponents) {
foreach($this->vueComponents as $vc )
{
$component.= file_exists(self::COMPONENTSDIR.$vc.'.vue') ? file_get_contents(self::COMPONENTSDIR.$vc.'.vue') : '';
}
$this->components = $component;
}
}
public function returnComponents()
{
return $this->components;
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/templates/lib/Controllers/Home.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\Controllers;
/**
* Admin Area Controller
*/
class Home {
/**
* Index action.
*
* @param array $vars Module configuration parameters
*
* @return string
*/
public function index($vars)
{
//some logic
return $vars;
}
/**
* Show action.
*
* @param array $vars Module configuration parameters
*
* @return string
*/
public function show($vars)
{
// Get common module parameters
$modulelink = $vars['modulelink']; // eg. addonmodules.php?module=addonmodule
$version = $vars['version']; // eg. 1.0
$LANG = $vars['_lang']; // an array of the currently loaded language variables
// Get module configuration parameters
$configTextField = $vars['Text Field Name'];
$configPasswordField = $vars['Password Field Name'];
$configCheckboxField = $vars['Checkbox Field Name'];
$configDropdownField = $vars['Dropdown Field Name'];
$configRadioField = $vars['Radio Field Name'];
$configTextareaField = $vars['Textarea Field Name'];
return <<<EOF
<h2>Show</h2>
<p>This is the <em>show</em> action output of the sample addon module.</p>
<p>The currently installed version is: <strong>{$version}</strong></p>
<p>
<a href="{$modulelink}" class="btn btn-info">
<i class="fa fa-arrow-left"></i>
Back to home
</a>
</p>
EOF;
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/app/Controllers/Home.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\app\Controllers;
use WHMCS\Module\Addon\ProductCheckoutRedirect\VueController;
/**
* Admin Area Controller
*/
class Home extends VueController
{
/**
* Vue components used in this controller
*/
public $vueComponents = ['AddProduct', 'ProductsTable'];
/**
* Index action.
*
* @param array $vars Module configuration parameters
*
* @return array
*/
public function __construct()
{
parent::__construct();
}
public function index($vars)
{
return $vars;
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/ProductCheckoutRedirect.php
<?php
use WHMCS\Module\Addon\ProductCheckoutRedirect\app\Addon;
use WHMCS\Module\Addon\ProductCheckoutRedirect\Dispatcher;
if (!defined("WHMCS")) {
die("This file cannot be accessed directly");
}
function productcheckoutredirect_config()
{
return Addon::config();
}
function productcheckoutredirect_output($vars)
{
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
$ctrl = isset($_REQUEST['c']) ? $_REQUEST['c'] : 'home';
$dispatcher = new Dispatcher();
$response = $dispatcher->dispatch($ctrl, $action, $vars);
echo $response;
}
function productcheckoutredirect_activate()
{
return Addon::activate();
}
function productcheckoutredirect_deactivate()
{
return Addon::deactivate();
}
function productcheckoutredirect_upgrade()
{
return Addon::upgrade();
}
<file_sep>/modules/addons/ProductCheckoutRedirect/hooks.php
<?php
\WHMCS\Module\Addon\ProductCheckoutRedirect\HooksManager::run();<file_sep>/modules/addons/ProductCheckoutRedirect/lib/app/Addon.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\app;
class Addon
{
public static function config()
{
return [
// Display name for your module
'name' => 'Product Checkout Redirect',
// Description displayed within the admin interface
'description' => 'This module allows to redirect customers to certain adress depending on ordered product.',
// Module author name
'author' => '<NAME>',
'version' => '1.0.0',
];
}
public static function activate()
{
DB::statement("
CREATE TABLE IF NOT EXISTS `kg_pids_redir` (
`pid` int(11) NOT NULL,
`redirurl` varchar(255) NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8");
return [
'status' => 'success',
'description' => 'The module has been successfuly activated.',
];
}
public static function deactivate()
{
return [
'status' => 'success',
'description' => 'The module has been successfuly deactivated.',
];
}
public static function upgrade()
{
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/lib/Models/Products.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect\Models;
use Illuminate\Database\Eloquent\Model;
use \WHMCS\Product\Product;
class Products extends Product
{
public function redir()
{
return $this->hasOne(\WHMCS\Module\Addon\ProductCheckoutRedirect\Models\Redirs::class, 'pid', 'id');
}
}<file_sep>/modules/addons/ProductCheckoutRedirect/templates/lib/Dispatcher.php
<?php
namespace WHMCS\Module\Addon\ProductCheckoutRedirect;
/**
* Dispatch Handler
*/
class Dispatcher {
/**
* Dispatch request.
*
* @param string $action
* @param array $parameters
*
* @return string
*/
private function errorOutput($error)
{
}
private function display($smarty, $tpl)
{
try {
return $smarty->fetch('header.tpl').
$smarty->fetch($tpl.'.tpl').
$smarty->fetch('footer.tpl');
}
catch (\Exception $e)
{
return 'error: No tpl found';
}
}
public function dispatch($controller, $action, $parameters)
{
if (!$action) {
// Default to index if no action specified
$action = 'index';
}
if($_REQUEST['json'])
{
ob_clean();
header('Content-Type: application/json');
echo json_encode(DispatcherAPI::dispatch($controller, $action.'JSON',$parameters));
exit;
}
$controller = 'WHMCS\\Module\\Addon\\ProductCheckoutRedirect\\Controllers\\'.ucfirst($controller);
$smarty = new \Smarty;
$moduleConfig = call_user_func($parameters['module'].'_config');
$smarty->assign('moduleName', $moduleConfig['name']);
$smarty->setTemplateDir(__DIR__.'/../templates');
$smarty->setCompileDir(ROOTDIR.'/templates_c');
if(class_exists($controller))
{
$controller = new $controller();
}
else
{
$smarty->assign('error', 'Controller doesnt exist');
return $this->display($smarty, 'error');
}
// Verify requested action is valid and callable
if (is_callable(array($controller, $action))) {
$return = $controller->$action($parameters);
foreach($return as $k=>$v)
{
$smarty->assign($k, $v);
}
try {
return $smarty->fetch('header.tpl').
$smarty->fetch($action.'.tpl').
$smarty->fetch('footer.tpl');
}
catch (\Exception $e)
{
return 'Error: Template not found.'.$e->getMessage();
}
}
return '<p>Invalid action requested. Please go back and try again.</p>';
}
}
|
37861d1429a4ce684d511320d3d660e8b5287081
|
[
"Markdown",
"PHP"
] | 14
|
PHP
|
kgalanty/ProductCheckoutRedirect
|
51c851343463b7f647996b3f045cf0c977cfe979
|
c927fd2576250e8992cbbb2ff75346677f97215f
|
refs/heads/master
|
<repo_name>jonassuncao/PS-SI-2020-1-Self-Service<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/application/client/response/ClientResponse.java
package com.ufg.inf.ps.selfservice.application.client.response;
import com.ufg.inf.ps.selfservice.domain.client.Client;
import com.ufg.inf.ps.selfservice.domain.client.ClientConstants;
import com.ufg.inf.ps.selfservice.domain.client.CompanyPerson;
import com.ufg.inf.ps.selfservice.domain.client.CompanySupplier;
import com.ufg.inf.ps.selfservice.domain.client.PhysicalPerson;
import com.ufg.inf.ps.selfservice.domain.client.PhysicalSupplier;
import com.ufg.inf.ps.selfservice.domain.client.Supplier;
import com.ufg.inf.ps.selfservice.infra.commons.DomainUtils;
/**
* @author jonathas.assuncao on 17/12/2020
* @project SelfService
*/
public class ClientResponse {
private String nickname;
private String name;
private String username;
private String address;
private String documentWithMask;
private String document;
private String businessAddress;
private String businessName;
private String municipalRegistration;
private String type;
public ClientResponse(Client data) {
load(data);
DomainUtils.ifCast(data, PhysicalPerson.class).ifPresent(this::loadPerson);
DomainUtils.ifCast(data, CompanyPerson.class).ifPresent(this::loadCompany);
DomainUtils.ifCast(data, PhysicalSupplier.class).ifPresent(this::load);
DomainUtils.ifCast(data, CompanySupplier.class).ifPresent(this::load);
}
private void load(Client data) {
username = data.getUsername();
document = data.getDocument();
address = data.getAddress();
name = data.getName();
nickname = data.getNickname();
}
private void loadPerson(PhysicalPerson data) {
documentWithMask = data.getCpf();
type = ClientConstants.PHYSICAL_PERSON;
}
private void loadCompany(CompanyPerson data) {
documentWithMask = data.getCnpj();
type = ClientConstants.COMPANY_PERSON;
}
private void load(PhysicalSupplier data) {
loadPerson(data);
loadSupplier(data);
type = ClientConstants.PHYSICAL_SUPPLIER;
}
private void load(CompanySupplier data) {
loadCompany(data);
loadSupplier(data);
type = ClientConstants.COMPANY_SUPPLIER;
}
private void loadSupplier(Supplier data) {
businessAddress = data.getBusinessAddress();
businessName = data.getBusinessName();
municipalRegistration = data.getMunicipalRegistration();
}
public String getNickname() {
return nickname;
}
public String getName() {
return name;
}
public String getUsername() {
return username;
}
public String getAddress() {
return address;
}
public String getDocument() {
return document;
}
public String getDocumentWithMask() {
return documentWithMask;
}
public String getBusinessAddress() {
return businessAddress;
}
public String getBusinessName() {
return businessName;
}
public String getMunicipalRegistration() {
return municipalRegistration;
}
public String getType() {
return type;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/pager-query.service.ts
import { HttpParams, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { isArray, isBoolean, isDate, isNil, isNumber, isString } from "lodash";
import { Page } from "../models/page.model";
export const TOTAL_COUNT = "X-Total-Count";
@Injectable({
providedIn: "root",
})
export class PagerQueryService {
public response<T>(res: HttpResponse<T>): Page<T> {
const total = Number(res.headers.get(TOTAL_COUNT));
const itens = (res.body as unknown) as T[];
return { items: itens, total };
}
public params(req: any): HttpParams {
let params = new HttpParams();
this.load(req).forEach((value, key) => (params = params.set(key, value)));
return params;
}
public paramsSort(req: any): HttpParams {
let params = new HttpParams();
if (req) {
this.sort(req).forEach((value, key) => (params = params.set(key, value)));
if (req.query) {
params = params.set("q", req.query);
}
}
return params;
}
public load(req: any): Map<string, string> {
let params = new Map<string, string>();
if (req) {
this.extra(req).forEach(
(value, key) => (params = params.set(key, value))
);
this.paginator(req).forEach(
(value, key) => (params = params.set(key, value))
);
this.sort(req).forEach((value, key) => (params = params.set(key, value)));
}
return params;
}
private sort(req: any): Map<string, string> {
const params = new Map<string, string>();
if (req && req.sort) {
const active = req.sort.active;
if (!!active) {
let activeSort = active;
const direction = req.sort.direction;
if (direction) {
activeSort = `${active},${direction}`;
}
params.set("sort", activeSort);
}
}
return params;
}
private extra(req: any): Map<string, string> {
const params = new Map<string, string>();
if (req) {
Object.keys(req).forEach((key) => {
const value = this.convertExtraValue(req[key]);
if (!isNil(value)) {
params.set(key, value);
}
});
}
return params;
}
private convertExtraValue(value: any): string {
if (isNumber(value)) {
return String(value);
} else if (isBoolean(value)) {
return String(value);
} else if (isString(value) && value) {
return value;
} else if (isDate(value)) {
return value.toISOString();
} else if (isArray(value) && value.length > 0) {
return value.join(",");
}
}
private paginator(req: any): Map<string, string> {
const params = new Map<string, string>();
const page = this.pageIndex(req);
if (page) {
params.set("page", String(page));
}
const size = this.pageSize(req);
if (size) {
params.set("size", String(size));
}
return params;
}
private pageIndex(req: any): number {
if (req) {
if (req.paginator) {
return req.paginator.pageIndex;
}
return req.page;
}
return null;
}
private pageSize(req: any): number {
if (req) {
if (req.paginator) {
return req.paginator.pageSize;
}
return req.size;
}
return null;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/errorbuilder/ErrorFactory.java
package com.ufg.inf.ps.selfservice.infra.exception.errorbuilder;
import com.ufg.inf.ps.selfservice.infra.exception.Error;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorCode;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorResponseBuilder;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nCommon;
import com.ufg.inf.ps.selfservice.infra.intercionalization.MessageBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.util.LinkedHashSet;
import java.util.Optional;
import java.util.Set;
/**
* @author jonathas.assuncao on 13/11/2020
* @project pdv
*/
@Component
public class ErrorFactory {
private static final String EXCEPTION_NOT_MAPPED = "Exception not mapped: {}";
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Set<ErrorResponseBuilder<?>> builders = new LinkedHashSet<>();
ErrorFactory() {
builders.add(new InternalAuthenticationServiceExceptionBuilder());
builders.add(new LockedExceptionErrorBuilder());
builders.add(new DisabledExceptionErrorBuilder());
builders.add(new InvalidDataAccessApiUsageErrorBuilder());
builders.add(new BadCredentialsExceptionErrorBuilder());
builders.add(new IllegalArgumentExceptionErrorBuilder());
builders.add(new BindExceptionErrorBuilder());
builders.add(new JwtExceptionErrorBuilder());
builders.add(new SelfServiceErrorBuilder());
}
public ResponseEntity<Error> error(Exception ex, MessageBuilder builder) {
return resolveError(ex, builder).orElse(internalError(ex, builder));
}
private Optional<ResponseEntity<Error>> resolveError(Exception ex, MessageBuilder messageBuilder) {
final Optional<ErrorResponseBuilder<?>> builder = builders.stream().filter(b -> b.accept(ex)).findFirst();
return builder.map(b -> b.call(ex, messageBuilder));
}
private ResponseEntity<Error> internalError(Exception ex, MessageBuilder builder) {
log.warn(EXCEPTION_NOT_MAPPED, ex.getMessage(), ex);
final String message = builder.message(I18nCommon.ERROR_INTERNAL);
final Error error = new Error(ErrorCode.INTERNAL_SERVER_ERROR, message);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/SecurityUtils.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.infra.commons.DomainUtils;
import com.ufg.inf.ps.selfservice.infra.security.SecurityFunctions;
import com.ufg.inf.ps.selfservice.infra.security.SelfServiceDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
/**
* @author guilherme.pacheco
*/
public final class SecurityUtils {
private SecurityUtils() {
super();
}
public static SelfServiceDetails getIdentity() {
return identity().orElseThrow(SecurityFunctions.notAutenthicated());
}
public static Optional<SelfServiceDetails> identity() {
return authentication().flatMap(SecurityUtils::resolveIdentity);
}
private static Optional<SelfServiceDetails> resolveIdentity(Authentication authentication) {
return DomainUtils.ifCast(authentication.getPrincipal(), SelfServiceDetails.class);
}
public static Optional<Authentication> authentication() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication());
}
public static Authentication getAuthentication() {
return authentication().orElseThrow(SecurityFunctions.notAutenthicated());
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/CompanySupplier.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import com.ufg.inf.ps.selfservice.infra.commons.Checker;
import com.ufg.inf.ps.selfservice.infra.exception.SelfServiceException;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nClient;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import java.util.Optional;
/**
* @author jonathas.assuncao on 04/12/2020
* @project SelfService
*/
@Entity
@DiscriminatorValue(ClientConstants.COMPANY_SUPPLIER)
public class CompanySupplier extends CompanyPerson implements Supplier {
private static final long serialVersionUID = 1L;
private String businessAddress;
private String municipalRegistration;
@Enumerated(EnumType.STRING)
private SupplierStatus status;
CompanySupplier() {
super();
}
CompanySupplier(ClientData data) {
super(data);
businessAddress(data.getBusinessAddress());
municipalRegistration(data.getMunicipalRegistration());
setBusinessDocument(data.getDocument());
setStatus(SupplierStatus.REGISTERED);
}
private void municipalRegistration(Optional<String> value) {
final String municipalRegistration = value.orElseThrow(SelfServiceException.supplier(I18nClient.CLIENT_MUNICIPALREGISTRATION_REQUIRED));
setMunicipalRegistration(municipalRegistration);
}
private void businessAddress(Optional<String> value) {
final String address = value.orElseThrow(SelfServiceException.supplier(I18nClient.CLIENT_BUSINESSADDRESS_REQUIRED));
setBusinessAddress(address);
}
@Override
public String getBusinessName() {
return getName();
}
@Override
public String getBusinessAddress() {
return businessAddress;
}
void setBusinessAddress(String businessAddress) {
this.businessAddress = Checker.notBlankTrim(businessAddress, I18nClient.CLIENT_BUSINESSADDRESS_NOTBLANK);
}
@Override
public String getBusinessDocument() {
return getCnpj();
}
void setBusinessDocument(String businessDocument) {
setCnpj(businessDocument);
}
@Override
public String getMunicipalRegistration() {
return municipalRegistration;
}
void setMunicipalRegistration(String municipalRegistration) {
this.municipalRegistration = Checker.notBlankTrim(municipalRegistration, I18nClient.CLIENT_MUNICIPALREGISTRATION_NOTBLANK);
}
@Override
public SupplierStatus getStatus() {
return status;
}
void setStatus(SupplierStatus status) {
this.status = status;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/security/ParamExtractor.java
package com.ufg.inf.ps.selfservice.infra.security;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.handler.DispatcherServletWebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
/**
* @author jonathas.assuncao on 03/12/2020
* @project SelfService
*/
public class ParamExtractor {
public static Optional<String> param(NativeWebRequest request, String requestParam) {
if (WebUtils.containsParam(request, requestParam)) {
String value = request.getParameter(requestParam);
return Optional.ofNullable(value).filter(StringUtils::isNotBlank);
}
return Optional.empty();
}
public static Optional<String> header(NativeWebRequest request, String headerParam) {
if (WebUtils.containsHeader(request, headerParam)) {
String value = request.getHeader(headerParam);
return Optional.ofNullable(value).filter(StringUtils::isNotBlank);
}
return Optional.empty();
}
public static Optional<String> header(HttpServletRequest request, String headerParam) {
return ParamExtractor.header(new DispatcherServletWebRequest(request), headerParam);
}
public static Optional<String> param(HttpServletRequest request, String requestParam) {
return ParamExtractor.param(new DispatcherServletWebRequest(request), requestParam);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/Supplier.java
package com.ufg.inf.ps.selfservice.domain.client;
/**
* @author jonathas.assuncao on 04/12/2020
* @project SelfService
*/
public interface Supplier {
String getBusinessName();
String getBusinessAddress();
String getBusinessDocument();
String getMunicipalRegistration();
SupplierStatus getStatus();
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/forms/form-model.ts
import { AbstractControl } from '@angular/forms';
export type FormModel<T> = {
[P in keyof T]: AbstractControl | T[P] | [T[P] | { value: T[P]; disabled: boolean }, any?];
};
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/ExceptionResolver.java
package com.ufg.inf.ps.selfservice.infra.exception;
import com.ufg.inf.ps.selfservice.infra.exception.errorbuilder.ErrorFactory;
import com.ufg.inf.ps.selfservice.infra.intercionalization.MessageResolver;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
/**
* @author jonathas.assuncao on 12/11/2020
* @project pdv
*/
@Component
public class ExceptionResolver {
private final MessageResolver message;
private final ErrorFactory errorFactory;
public ExceptionResolver(MessageResolver message, ErrorFactory errorFactory) {
this.message = message;
this.errorFactory = errorFactory;
}
public ResponseEntity<Error> resolve(Exception ex) {
return errorFactory.error(ex, message::resolve);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/ErrorCode.java
package com.ufg.inf.ps.selfservice.infra.exception;
/**
* @author guilherme.pacheco
*/
public enum ErrorCode {
INVALID_PARAM("error.invalidParam"),
ACCESS_DENIED("error.accessDenied"),
INVALID_OPERATION("error.invalidOperation"),
INTERNAL_SERVER_ERROR("error.internalServerError");
private final String code;
private ErrorCode(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/forms/error-messages.ts
import { AbstractControl, FormArray, FormGroup } from "@angular/forms";
import { TranslateService } from "@ngx-translate/core";
export class ErrorMessages {
constructor(
private translateService: TranslateService,
private form: FormGroup | FormArray,
private path: string
) {}
public get(field?: string): string[] {
return this.getAbsolute(this.path, field);
}
public getAbsolute(path: string, field?: string): string[] {
if (field) {
const control = this.control(field);
return this.erros(control, path, field);
}
return this.erros(this.form, path);
}
private erros(
control: AbstractControl,
path: string,
field?: string
): string[] {
if (control && control.touched && control.invalid && control.errors) {
return Object.keys(control.errors)
.slice(0, 1)
.map((errorKey) => {
const errorPath = this.pathError(path, field, errorKey);
return this.translateService.instant(
errorPath,
control.getError(errorKey)
);
});
}
return [];
}
private control(path: string): AbstractControl {
let control = null;
path.split(".").forEach((key) => {
if (control) {
control = control.controls[key];
} else {
control = this.form.controls[key];
}
});
return control;
}
private pathError(path: string, field: string, errorKey: string): string {
if (path.indexOf("global") >= 0) {
return `${path}.${errorKey}`;
}
const paths = [path];
if (field) {
paths.push(field);
}
paths.push(errorKey);
return paths.join(".");
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/environments/environment.prod.ts
export const environment = {
production: true,
SERVER_URL: "",
SERVER_API_URL: "/api",
};
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/intercionalization/MessageResolver.java
package com.ufg.inf.ps.selfservice.infra.intercionalization;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @author jonathas.assuncao on 12/11/2020
* @project pdv
*/
@Component
public class MessageResolver {
private static final Locale LOCALE = new Locale("pt", "BR");
@Bean
private MessageSource messageSource() {
Locale.setDefault(LOCALE);
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.addBasenames("classpath:/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
public String resolve(I18nKey key) {
return resolve(key.get());
}
public String resolve(I18nKey key, Object[] params) {
return resolve(key.get(), params);
}
public String resolve(String key, Object[] params) {
return messageSource().getMessage(key, params, LOCALE);
}
public String resolve(String key) {
return messageSource().getMessage(key, null, LOCALE);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/ExceptionAdvice.java
package com.ufg.inf.ps.selfservice.infra.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @author jonathas.assuncao on 12/11/2020
* @project pdv
*/
@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionAdvice {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private ExceptionResolver exceptionResolver;
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Error> runtimeException(RuntimeException ex) {
logException(ex);
return exceptionResolver.resolve(ex);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Error> exception(Exception ex) {
logException(ex);
return exceptionResolver.resolve(ex);
}
private void logException(Throwable ex) {
log.error("Error: {}", ex.getMessage(), ex);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/security/WebUtils.java
package com.ufg.inf.ps.selfservice.infra.security;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.WebRequest;
/**
* @author jonathas.assuncao on 03/12/2020
* @project SelfService
*/
public final class WebUtils {
private WebUtils() {
super();
}
public static boolean containsParam(WebRequest webRequest, String key) {
return StringUtils.isNotBlank(webRequest.getParameter(key));
}
public static boolean containsHeader(WebRequest webRequest, String key) {
return StringUtils.isNotBlank(webRequest.getHeader(key));
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/principal.service.ts
import { Injectable } from "@angular/core";
import { BehaviorSubject, Observable, throwError } from "rxjs";
import {
catchError,
concat,
delay,
map,
mergeMap,
retryWhen,
share,
take,
tap,
} from "rxjs/operators";
import { AuthService } from "./auth.service";
import { ClientService } from "./client.service";
import { TranslateService } from "@ngx-translate/core";
@Injectable({
providedIn: "root",
})
export class PrincipalService {
private client = new BehaviorSubject<any>(null);
constructor(
private authService: AuthService,
private clientService: ClientService,
private translateService: TranslateService
) {}
public identify(force: boolean = false): Observable<Account> {
if (force || !this.client.getValue()) {
if (this.authService.hasToken()) {
return this.load();
}
}
return this.getAccount();
}
public isAuthenticated(): Observable<boolean> {
return this.identify().pipe(map((account) => !!account));
}
public getAccount(): Observable<Account> {
return this.client.asObservable().pipe(share());
}
public get current(): Account {
return this.client.getValue();
}
public logout() {
this.authService.clear();
this.client.next(null);
}
private load(): Observable<Account> {
return this.clientService.get().pipe(
tap(this.loadAccount),
retryWhen((errors) =>
errors.pipe(delay(2000), take(1), concat(this.onError()))
),
catchError(() => this.onError()),
mergeMap(() => this.getAccount())
);
}
private loadAccount = (account: Account) => {
this.client.next(account);
};
private onError(): Observable<never> {
return throwError({
error: {
message: this.translateService.instant("global.error.notAuthenticated"),
},
});
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/errorbuilder/BadCredentialsExceptionErrorBuilder.java
package com.ufg.inf.ps.selfservice.infra.exception.errorbuilder;
import com.ufg.inf.ps.selfservice.infra.exception.Error;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorCode;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorResponseBuilder;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nCommon;
import com.ufg.inf.ps.selfservice.infra.intercionalization.MessageBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
/**
* @author jonathas.assuncao on 08/12/2020
* @project SelfService
*/
public class BadCredentialsExceptionErrorBuilder implements ErrorResponseBuilder<BadCredentialsException> {
@Override
public ResponseEntity<Error> build(BadCredentialsException exception, MessageBuilder messageBuilder) {
String text = messageBuilder.message(I18nCommon.BAD_CREDENTIALS);
Error error = new Error(ErrorCode.INVALID_PARAM, text);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
@Override
public boolean accept(Exception exception) {
return BadCredentialsException.class.isInstance(exception);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/commons/Identification.java
package com.ufg.inf.ps.selfservice.infra.commons;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
/**
* @author jonathas.assuncao on 04/12/2020
* @project SelfService
*/
@MappedSuperclass
public abstract class Identification implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", updatable = false, nullable = false, unique = true)
private UUID id;
protected Identification() {
}
protected Identification(UUID id) {
setId(id);
}
protected void initialize() {
setId(UUID.randomUUID());
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
Optional.ofNullable(id).ifPresent(i -> this.id = i);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return String.format("%s [id=%s]", getClass().getSimpleName(), id);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/SelfServiceException.java
package com.ufg.inf.ps.selfservice.infra.exception;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nKey;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* @author jonathas.assuncao on 12/11/2020
* @project pdv
*/
public class SelfServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
private final transient List<Object> params;
public SelfServiceException(String key, List<Object> params) {
super(key);
this.params = Objects.nonNull(params) ? params : Collections.emptyList();
}
public SelfServiceException(I18nKey key, List<Object> params, Throwable throwable) {
super(key.get(), throwable);
this.params = Objects.nonNull(params) ? params : Collections.emptyList();
}
public SelfServiceException(I18nKey key, List<Object> params) {
this(key.get(), params);
}
public SelfServiceException(I18nKey key) {
this(key, Collections.emptyList());
}
public SelfServiceException(MessageException messageParams) {
this(messageParams.getKey(), messageParams.getParams());
}
public MessageException getMessageException() {
return new MessageException(getMessage(), params);
}
public List<Object> getParams() {
return Collections.unmodifiableList(params);
}
public static Supplier<SelfServiceException> supplier(I18nKey key, Object... args) {
return () -> SelfServiceException.valueOf(key, args);
}
public static SelfServiceException valueOf(I18nKey key, Object... args) {
return new SelfServiceException(key, params(args));
}
public static SelfServiceException valueOf(Throwable throwable, I18nKey key, Object... args) {
return new SelfServiceException(key, params(args), throwable);
}
public static SelfServiceException valueOf(I18nKey key) {
return new SelfServiceException(key);
}
protected static List<Object> params(Object... args) {
return Arrays.stream(args).filter(Objects::nonNull).collect(Collectors.toList());
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/utils/functions.ts
import { AbstractControl } from "@angular/forms";
import { format, isDate } from "date-fns";
import { isBoolean, isNumber, isString } from "lodash";
import { DATE_REGEX } from "./regex";
export function toInteger(value: any): number {
return parseInt(String(value), 10);
}
export function toString(value: any): string {
return value !== undefined && value !== null ? `${value}` : "";
}
export function noBlank(value: any): boolean {
return !!toString(value).length;
}
export function getValueInRange(value: number, max: number, min = 0): number {
return Math.max(Math.min(value, max), min);
}
export function isInteger(value: any): value is number {
return (
typeof value === "number" && isFinite(value) && Math.floor(value) === value
);
}
export function isDefined(value: any): boolean {
return value !== undefined && value !== null;
}
export function padNumber(value: number) {
if (isNumber(value)) {
return `0${value}`.slice(-2);
}
return "";
}
export function regExpEscape(text: string) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
export function sanitize(text: string) {
if (text) {
return text.replace(/[^a-zA-Z0-9]/g, "");
}
return text;
}
export function sort(active: string, direction: "asc" | "desc" = "asc") {
return { active, direction };
}
export function distribute(
value: number,
quantity: number,
precision: number = 2
): number[] {
const quota = Math.trunc((value / quantity) * 100) / 100;
const result = [];
for (let i = 0; i < quantity - 1; i++) {
result.push(fixValue(quota));
}
const leftover = value - quota * quantity + quota;
result.push(fixValue(leftover));
return result;
}
export function fixValue(value: number, precision: number = 2): number {
return Number(value.toFixed(precision));
}
export function calculateLeftover(
quota: number,
total: number,
precision: number = 2
): number {
const quotaTrunc = Number(quota.toFixed(precision)) * 100;
const totalTrunc = Number(total.toFixed(precision)) * 100;
return (
Number(((totalTrunc % quotaTrunc) + quotaTrunc).toFixed(precision)) / 100
);
}
export function convertDate(date: Date): string | null {
return !date ? null : format(date, "YYYY-MM-DD");
}
export function isValidDate(date: any): boolean {
if (isDate(date)) {
return true;
}
if (isString(date) && DATE_REGEX.test(date)) {
return !!Date.parse(date);
}
return false;
}
export function isValidBoolean(value: any): boolean {
if (isBoolean(value)) {
return true;
}
if (isString(value) && ["true", "false"].includes(value.toLowerCase())) {
return true;
}
return false;
}
export function count(word: string, wanted: string): number {
return word.split(wanted).length - 1;
}
export function shadeHexColor(color: string, percent: number) {
const f = parseInt(color.slice(1), 16);
const t = percent < 0 ? 0 : 255;
const p = percent < 0 ? percent * -1 : percent;
// tslint:disable-next-line: no-bitwise
const R = f >> 16;
// tslint:disable-next-line: no-bitwise
const G = (f >> 8) & 0x00ff;
// tslint:disable-next-line: no-bitwise
const B = f & 0x0000ff;
return (
"#" +
(
0x1000000 +
(Math.round((t - R) * p) + R) * 0x10000 +
(Math.round((t - G) * p) + G) * 0x100 +
(Math.round((t - B) * p) + B)
)
.toString(16)
.slice(1)
);
}
export function hasValue(obj: any): boolean {
if (!obj) {
return false;
}
return !!Object.keys(obj)
.map((key) => obj[key])
.find((v) => !!v);
}
export function hasValidator(
control: AbstractControl,
validator: string
): boolean {
try {
return (control.validator(control) || {}).hasOwnProperty(validator);
} catch (e) {
return false;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/api.service.ts
import { HttpClient, HttpParams } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { map, take } from "rxjs/operators";
import { environment } from "src/environments/environment";
import { Page } from "../models/page.model";
import { PagerQueryService } from "./pager-query.service";
@Injectable({
providedIn: "root",
})
export class ApiService {
public readonly baseUrl = environment.SERVER_API_URL;
constructor(
public readonly http: HttpClient,
public readonly pagerQueryService: PagerQueryService
) {}
public get<T>(
url: string,
params: HttpParams = new HttpParams()
): Observable<T> {
return this.http
.get<T>(`${this.baseUrl}${url}`, { params })
.pipe(take(1));
}
public getString(
url: string,
params: HttpParams = new HttpParams()
): Observable<string> {
return this.http
.get<string>(`${this.baseUrl}${url}`, {
params,
responseType: "text" as "json",
})
.pipe(take(1));
}
public page<T>(url: string, req?: any | HttpParams): Observable<Page<T>> {
const params = this.resolveParams(req);
return this.http
.get<T>(`${this.baseUrl}${url}`, { params, observe: "response" })
.pipe(map(this.pagerQueryService.response))
.pipe(take(1));
}
public put<T>(
path: string,
body: any = null,
params: HttpParams = new HttpParams()
): Observable<T> {
return this.http
.put<T>(`${this.baseUrl}${path}`, body, { params })
.pipe(take(1));
}
public patch<T>(
path: string,
body: any = {},
params: HttpParams = new HttpParams()
): Observable<T> {
return this.http
.patch<T>(`${this.baseUrl}${path}`, body, { params })
.pipe(take(1));
}
public post<T>(
path: string,
body: any = {},
params: HttpParams = new HttpParams()
): Observable<T> {
return this.http
.post<T>(`${this.baseUrl}${path}`, body, { params })
.pipe(take(1));
}
public delete<T>(
path: string,
params: HttpParams = new HttpParams()
): Observable<T> {
return this.http
.delete<T>(`${this.baseUrl}${path}`, { params })
.pipe(take(1));
}
private resolveParams(req: any): HttpParams {
if (req instanceof HttpParams) {
return req;
}
return this.pagerQueryService.params(req);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/client.service.ts
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { ApiService } from "./api.service";
@Injectable({
providedIn: "root",
})
export class ClientService {
private url = "/clients";
constructor(private api: ApiService) {}
public get(): Observable<any> {
return this.api.get(this.url);
}
}
<file_sep>/4.Sistema/SelfService/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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.ufg.inf.ps</groupId>
<artifactId>SelfService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SelfService</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.jupiter.version>5.3.0</junit.jupiter.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!-- DataBase -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- JUNIT5 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
<!-- TEST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.9.9</version>
</dependency>
<!-- ASSERT -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- JUNIT5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<!-- MOCKITO -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>2.22.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<file_sep>/README.md

Plataforma para procura e divulgação de prestadores de serviços.
## Membros
* [<NAME>](https://github.com/jonassuncao)
* [<NAME>](https://github.com/f4el)
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/CompanyPerson.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import com.ufg.inf.ps.selfservice.infra.commons.Checker;
import com.ufg.inf.ps.selfservice.infra.commons.DocumentType;
import com.ufg.inf.ps.selfservice.infra.commons.DocumentUtils;
import com.ufg.inf.ps.selfservice.infra.exception.SelfServiceException;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nClient;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nCommon;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import java.text.ParseException;
/**
* @author jonathas.assuncao on 04/12/2020
* @project SelfService
*/
@Entity
@DiscriminatorValue(ClientConstants.COMPANY_PERSON)
public class CompanyPerson extends Client {
private static final long serialVersionUID = 1L;
CompanyPerson() {
super();
}
CompanyPerson(ClientData data) {
super(data);
setCnpj(data.getDocument());
}
public String getCnpj() {
try {
return DocumentType.CNPJ.formatted(super.getDocument());
} catch (ParseException e) {
throw SelfServiceException.valueOf(I18nCommon.DOCUMENT_CNPJ_INVALID, super.getDocument());
}
}
public void setCnpj(String document) {
Checker.notBlankTrim(document, I18nClient.CLIENT_DOCUMENT_NOTBLANK);
Checker.isTrue(DocumentUtils.isCnpj(document), I18nCommon.DOCUMENT_CNPJ_INVALID, document);
super.setDocument(document);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/forms/form-util.ts
import {
AbstractControl,
FormArray,
FormControl,
FormGroup,
ValidatorFn,
} from "@angular/forms";
import { countBy } from "lodash";
import { calculateLeftover } from "../utils/functions";
export function validateAllFormFields(formGroup: FormGroup) {
if (formGroup) {
formGroup.markAllAsTouched();
if (formGroup.controls) {
Object.keys(formGroup.controls).forEach((key) => {
const control = formGroup.get(key);
if (control instanceof FormControl) {
control.markAsTouched();
} else if (control instanceof FormGroup) {
validateAllFormFields(control);
} else if (control instanceof FormArray) {
const array = control as FormArray;
array.controls.forEach((c) => validateAllFormFields(c as FormGroup));
}
});
}
}
}
export function validateAllFormArrayFields(array: FormArray) {
array.controls.forEach((c) => validateAllFormFields(c as FormGroup));
array.markAllAsTouched();
}
export function resetForm(formGroup: FormGroup) {
if (formGroup instanceof FormGroup) {
reset(formGroup);
Object.keys(formGroup.controls).forEach((key) =>
resetControl(formGroup.get(key))
);
}
}
export function resetControl(control: AbstractControl) {
reset(control);
if (control instanceof FormGroup) {
resetForm(control);
} else if (control instanceof FormArray) {
const array = control as FormArray;
array.controls.forEach((c) => resetControl(c as FormGroup));
}
}
function reset(control: AbstractControl) {
control.reset();
control.markAsPristine();
control.markAsUntouched();
}
function validateField(formGroup: FormGroup, field: string) {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched();
control.setErrors({ required: true });
} else if (control instanceof FormGroup) {
this.validateField(control, field);
}
}
export function validationError(formGroup: FormGroup, res: Response) {
if (res && res.status === 400) {
const param = res.json();
if (param && param instanceof Array) {
param.forEach((p) => validateField(formGroup, p.field));
}
}
}
export function maxPercentageValidator(value: number): ValidatorFn {
return (control: AbstractControl) => {
const invalid = value < control.value;
return invalid ? { max: { max: value * 100 + "%" } } : null;
};
}
export function hasAnyValueValidator(error: string, controls?: string[]) {
return (form: FormGroup) => {
const keys = !!controls ? controls : Object.keys(form.controls);
const hasValue = !!keys.find(
(key) => !!form.get(key).value && form.get(key).valid
);
keys.forEach((key) => loadError(form.get(key), !hasValue, error));
};
}
export function uniqueIdValidator(
arrayElement: string,
idField: string,
error: string
) {
return (form: AbstractControl) => {
const array = form.get(arrayElement) as FormArray;
const count = countBy(array.controls.map((c) => c.get(idField).value));
array.controls
.map((c) => c.get(idField))
.forEach((c) => loadError(c, count[c.value] > 1, error));
};
}
export function updateValueAndValidity(
control: AbstractControl,
error: string
) {
if (control.getError(error)) {
control.updateValueAndValidity();
}
}
export function loadError(
control: AbstractControl,
invalid: boolean,
error: string,
value: any = true
) {
if (invalid) {
control.setErrors({ ...control.errors, [error]: value });
} else {
updateValueAndValidity(control, error);
}
}
export function percentagesValidator(
elementArray: string,
percentageField: string
) {
return (form: AbstractControl) => {
const percentages = form.get(elementArray) as FormArray;
const controls = percentages.controls.map((c) => c.get(percentageField));
const invalid =
controls.map((c) => c.value).reduce((a, b) => a + b, 0) !== 1;
controls.forEach((c) => loadError(c, invalid, "sumInvalidPercentage"));
};
}
export function allocatePercentage(
control: AbstractControl[],
percentageField: string
) {
const percentage = percentageByQuota(control);
control.forEach((form) => form.get(percentageField).setValue(percentage));
control[control.length - 1]
.get(percentageField)
.setValue(calculateLeftover(percentage, 1.0));
}
function percentageByQuota(control: AbstractControl[]) {
const quantity = control.length || 1;
return Math.trunc((1 / quantity) * 100) / 100;
}
export function disableControl(control: AbstractControl, disable: boolean) {
if (control) {
if (disable) {
control.disable();
} else {
control.enable();
}
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/interceptors/index.ts
/* "Barrel" of Http Interceptors */
import { HTTP_INTERCEPTORS } from "@angular/common/http";
import { AuthExpiredInterceptor } from "./auth-expired-interceptor";
import { AuthInterceptor } from "./auth-interceptor";
import { ExceptionInterceptor } from "./exception-interceptor";
import { NotificationInterceptor } from "./notification-interceptor";
/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: AuthExpiredInterceptor, multi: true },
{
provide: HTTP_INTERCEPTORS,
useClass: NotificationInterceptor,
multi: true,
},
{ provide: HTTP_INTERCEPTORS, useClass: ExceptionInterceptor, multi: true },
];
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/validation-translate.service.ts
import { Injectable } from "@angular/core";
import { FormArray, FormGroup } from "@angular/forms";
import { ToastController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { ErrorMessages } from "../shared/forms";
@Injectable({
providedIn: "root",
})
export class ValidationTranslateService {
constructor(
private translateService: TranslateService,
private toastController: ToastController
) {}
public errors(
form: FormGroup | FormArray,
path: string = "global.error"
): ErrorMessages {
return new ErrorMessages(this.translateService, form, path);
}
public valid(form: FormGroup) {
form.markAllAsTouched();
this.toastController
.create({
message: this.translate("global.error.invalidFields"),
color: "danger",
buttons: [
{
icon: "close",
role: "cancel",
},
],
duration: 2000,
})
.then((res) => res.present());
}
private translate(key: string): string {
return this.translateService.instant(key);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/commons/FormatUtils.java
package com.ufg.inf.ps.selfservice.infra.commons;
import org.apache.commons.lang3.StringUtils;
import javax.swing.text.MaskFormatter;
import java.text.ParseException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
/**
* @author guilherme.pacheco
*/
public final class FormatUtils {
private FormatUtils() {
super();
}
public static String maskFormat(String mask, Object value) {
try {
return maskFormatter(mask).valueToString(value);
} catch (ParseException ex) {
throw new IllegalArgumentException("Invalid value for mask: " + mask, ex);
}
}
public static MaskFormatter maskFormatter(String mask) {
try {
MaskFormatter formatter = new MaskFormatter(mask);
formatter.setValueContainsLiteralCharacters(false);
return formatter;
} catch (ParseException ex) {
throw new IllegalArgumentException("Invalid mask", ex);
}
}
public static String replace(Map<String, Object> values, String string) {
return Optional.ofNullable(values).map(map -> replaceMapString(map, string)).orElse(string);
}
private static String replaceMapString(Map<String, Object> values, String string) {
for (Entry<String, Object> entry : values.entrySet()) {
String key = String.format("{%s}", entry.getKey());
String value = String.valueOf(entry.getValue());
string = StringUtils.replace(string, key, value);
}
return string;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/crud.service.ts
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
import { ReadService } from './read.service';
export class CrudService<T> extends ReadService<T> {
constructor(protected api: ApiService, protected url: string) {
super(api, url);
}
public create(body: any): Observable<any> {
return this.api.post(this.url, body);
}
public update(body: any): Observable<any> {
return this.api.put(`${this.url}/${body.id}`, body);
}
public updateBody(id: string, body: any): Observable<any> {
return this.api.put(`${this.url}/${id}`, body);
}
public delete(id: string): Observable<any> {
return this.api.delete(`${this.url}/${id}`);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/i18n.service.ts
import {
formatCurrency,
formatDate,
formatPercent,
getCurrencySymbol,
getLocaleNumberSymbol,
getNumberOfCurrencyDigits,
NumberSymbol,
formatNumber,
} from "@angular/common";
import { Injectable } from "@angular/core";
import { TranslateService } from "@ngx-translate/core";
@Injectable({
providedIn: "root",
})
export class I18nService {
private defaultI18nLang = "pt-br";
constructor(private translateService: TranslateService) {
this.translateService.setDefaultLang(this.defaultI18nLang);
this.change(this.defaultI18nLang);
}
public config() {
this.change(this.defaultI18nLang);
}
public change(locale: string) {
this.translateService.use(locale);
}
private get currencySymbol(): string {
return getCurrencySymbol(this.currencyCode, "wide", this.locale);
}
private get currencyCode(): string {
return "BRL";
}
public get currencyDefaultPrecision(): number {
return getNumberOfCurrencyDigits(this.currencyCode);
}
public get symbolNegative(): string {
return getLocaleNumberSymbol(this.locale, NumberSymbol.MinusSign);
}
public get symbolCurrencyGroup(): string {
return getLocaleNumberSymbol(this.locale, NumberSymbol.CurrencyGroup);
}
public get symbolCurrencyDecimal(): string {
return getLocaleNumberSymbol(this.locale, NumberSymbol.CurrencyDecimal);
}
public currency(value: number, digitsInfo?: string) {
return formatCurrency(
value,
this.locale,
this.currencySymbol,
this.currencyCode,
digitsInfo
);
}
public formatNumber(value: number, digitsInfo?: string) {
return formatNumber(value, this.locale, digitsInfo);
}
public percent(value: number, digitsInfo?: string) {
return formatPercent(value, this.locale, digitsInfo);
}
public date(value: string | number | Date, format: string): string {
return formatDate(value, format, this.locale);
}
private get locale() {
return this.translateService.currentLang;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/ClientFactory.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import com.ufg.inf.ps.selfservice.infra.commons.DocumentUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
@Component
class ClientFactory {
private final PasswordEncoder passwordEncoder;
private final ClientChecker clientChecker;
public ClientFactory(PasswordEncoder passwordEncoder, ClientChecker clientChecker) {
this.passwordEncoder = passwordEncoder;
this.clientChecker = clientChecker;
}
public Client build(ClientData data) {
final Client client = factory(data);
client.setPassword(encodePassword(client));
return client;
}
private String encodePassword(Client client) {
clientChecker.checkerPassword(client);
return passwordEncoder.encode(client.getPassword());
}
private Client factory(ClientData data) {
if (isPhysical(data)) {
return isPerson(data) ? new PhysicalPerson(data) : new PhysicalSupplier(data);
}
return isPerson(data) ? new CompanyPerson(data) : new CompanySupplier(data);
}
private boolean isPhysical(ClientData data) {
return DocumentUtils.isCpf(data.getDocument());
}
private boolean isPerson(ClientData data) {
return data.getBusinessAddress().isEmpty() &&
data.getMunicipalRegistration().isEmpty();
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/commons/DocumentValidators.java
package com.ufg.inf.ps.selfservice.infra.commons;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
public final class DocumentValidators {
public static final int CPF_SIZE = 11;
public static final int CNPJ_SIZE = 14;
private static final int DIGIT_MAX = 9;
private static final int BASE_VERIFY = 11;
private static final int VERIFY_DIGITS_SIZE = 2;
private static final int[] WEIGHT_CPF = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};
private static final int[] WEIGHT_CNPJ = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};
private DocumentValidators() {
super();
}
public static boolean isValidCpf(String value) {
return isValid(value, CPF_SIZE, WEIGHT_CPF);
}
public static boolean isValidCnpj(String value) {
return isValid(value, CNPJ_SIZE, WEIGHT_CNPJ);
}
private static boolean isValid(String value, int size, int[] weight) {
if (isInvalid(value, size)) {
return false;
}
String number = value.substring(0, size - VERIFY_DIGITS_SIZE);
int digit1 = digit(number, weight);
int digit2 = digit(number + digit1, weight);
return value.equals(number + digit1 + digit2);
}
private static int digit(String number, int[] weight) {
int sum = 0;
for (int index = number.length() - 1; index >= 0; index--) {
int digito = Integer.parseInt(number.substring(index, index + 1));
sum += digito * weight[weight.length - number.length() + index];
}
sum = BASE_VERIFY - sum % BASE_VERIFY;
return sum > DIGIT_MAX ? 0 : sum;
}
private static boolean isInvalid(String value, int size) {
if (value == null || value.trim().length() != size) {
return true;
}
return hasAllRepeatedDigits(value);
}
private static boolean hasAllRepeatedDigits(String value) {
for (int i = 1; i < value.length(); i++) {
if (value.charAt(i) != value.charAt(0)) {
return false;
}
}
return true;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/modules/admin/home/home.module.ts
import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { HomeRoutingModule } from "./home-routing.module";
import { AboutDetailComponent } from "./pages/about-detail/about-detail.component";
import { ProfileDetailComponent } from "./pages/profile-detail/profile-detail.component";
import { ServiceDetailComponent } from "./pages/service-detail/service-detail.component";
@NgModule({
declarations: [
ServiceDetailComponent,
ProfileDetailComponent,
AboutDetailComponent,
],
imports: [CommonModule, HomeRoutingModule],
})
export class HomeModule {}
<file_sep>/4.Sistema/SelfServiceApp/src/app/interceptors/exception-interceptor.ts
import {
HttpErrorResponse,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { ErrorService } from "../services/error.service";
const STATUS_COMMUNICATION_ERROR = [0, 504];
const STATUS_ERRORS = [400, 401, 500];
@Injectable({
providedIn: "root",
})
export class ExceptionInterceptor implements HttpInterceptor {
constructor(private errorService: ErrorService) {}
public intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error) => {
if (error instanceof HttpErrorResponse) {
const res = error as HttpErrorResponse;
if (STATUS_COMMUNICATION_ERROR.includes(res.status)) {
this.errorService.show({ code: "error.communication" });
}
if (STATUS_ERRORS.includes(res.status)) {
this.errorService.show(res.error);
}
}
return throwError(error);
})
);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/interceptors/auth-expired-interceptor.ts
import {
HttpErrorResponse,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { ToastController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import { AuthService } from "../services/auth.service";
const STATUS_FORBIDDEN = 403;
@Injectable({
providedIn: "root",
})
export class AuthExpiredInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private authService: AuthService,
private toastController: ToastController,
private translateService: TranslateService
) {}
public intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error) => {
if (error instanceof HttpErrorResponse) {
if (error.status === STATUS_FORBIDDEN) {
this.authService.clear();
this.redirectToLogin();
this.authExpired();
}
}
return throwError(error);
})
);
}
private authExpired() {
this.toastController
.create({
message: this.translateService.instant("global.messages.authExpired"),
color: "danger",
buttons: [
{
icon: "close",
role: "cancel",
},
],
duration: 2000,
})
.then((res) => res.present());
}
private redirectToLogin() {
const url = this.router.routerState.snapshot.url;
this.router.navigate(["login"], { queryParams: { redirect: url } });
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/ClientHelper.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import com.ufg.inf.ps.selfservice.application.client.command.CreateClientCommand;
import org.springframework.stereotype.Component;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
@Component
public class ClientHelper {
public ClientData transform(CreateClientCommand command) {
ClientData data = new ClientData();
data.setUsername(command.getUsername());
data.setPassword(command.getPassword());
command.getNickname().ifPresent(data::setNickname);
data.setName(command.getName());
command.getAddress().ifPresent(data::setAddress);
data.setDocument(command.getDocument());
command.getBusinessAddress().ifPresent(data::setBusinessAddress);
command.getMunicipalRegistration().ifPresent(data::setMunicipalRegistration);
return data;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/application/authenticate/command/LoginCommand.java
package com.ufg.inf.ps.selfservice.application.authenticate.command;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import java.io.Serializable;
/**
* @author jonathas.assuncao on 03/12/2020
* @project SelfService
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginCommand implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
LoginCommand() {
super();
}
public LoginCommand(String username, String password) {
setUsername(username);
setPassword(password);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Authentication authentication() {
return new UsernamePasswordAuthenticationToken(getUsername(), getPassword());
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/login.service.ts
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { switchMap } from "rxjs/operators";
import { LoginCommand } from "../models/commands/login.command";
import { AuthService } from "./auth.service";
import { PrincipalService } from './principal.service';
@Injectable()
export class LoginService {
constructor(
private authService: AuthService,
private principalService: PrincipalService
) {}
public login(credentials: LoginCommand): Observable<any> {
return this.authService
.authenticate(credentials)
.pipe(switchMap(() => this.principalService.identify()));
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/errorbuilder/InternalAuthenticationServiceExceptionBuilder.java
package com.ufg.inf.ps.selfservice.infra.exception.errorbuilder;
import com.ufg.inf.ps.selfservice.infra.exception.Error;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorCode;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorResponseBuilder;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nCommon;
import com.ufg.inf.ps.selfservice.infra.intercionalization.MessageBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
/**
* @author jonathas.assuncao on 08/12/2020
* @project SelfService
*/
public class InternalAuthenticationServiceExceptionBuilder implements ErrorResponseBuilder<InternalAuthenticationServiceException> {
@Override
public ResponseEntity<Error> build(InternalAuthenticationServiceException exception, MessageBuilder messageBuilder) {
String message = messageBuilder.message(I18nCommon.INVALID_AUTHENTICATION);
Error error = new Error(ErrorCode.ACCESS_DENIED, message);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
@Override
public boolean accept(Exception exception) {
return InternalAuthenticationServiceException.class.isInstance(exception);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/read.service.ts
import { Observable } from "rxjs";
import { Page } from "../models/page.model";
import { ApiService } from "./api.service";
export class ReadService<T> {
constructor(protected api: ApiService, protected url: string) {}
public getById(id: string): Observable<T> {
return this.api.get<T>(`${this.url}/${id}`);
}
public existsById(id: string): Observable<boolean> {
return this.api.get(`${this.url}/${id}/exists`);
}
public findById(id: string): Observable<T> {
return this.api.get<T>(`${this.url}?id=${id}`);
}
public getAll(req?: any): Observable<T[]> {
const params = this.api.pagerQueryService.params(req);
return this.api.get<T[]>(`${this.url}`, params);
}
public query(req?: any): Observable<Page<T>> {
return this.api.page<T>(this.url, req);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/forms/index.ts
export * from './form-model';
export * from './form-util';
export * from './error-messages';
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/auth.service.ts
import { Injectable } from "@angular/core";
import { JwtHelperService } from "@auth0/angular-jwt";
import { LoadingController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { Observable, of } from "rxjs";
import { delay, finalize, map, switchMap, take } from "rxjs/operators";
import { LoginCommand } from "../models/commands/login.command";
import { ApiService } from "./api.service";
import { TokenStorageService } from "./token-storage.service";
@Injectable({
providedIn: "root",
})
export class AuthService {
private token: string;
private helper = new JwtHelperService();
constructor(
private api: ApiService,
private translateService: TranslateService,
private loadingController: LoadingController,
private tokenStorageService: TokenStorageService
) {
this.loadInitToken();
}
public authenticate(command: LoginCommand): Observable<string> {
return this.api
.post("/authentication", command)
.pipe(map(this.extractAndLoadToken));
}
public getToken() {
return this.token;
}
public hasToken(): boolean {
return !!this.token;
}
public getTokenValue(): { sub: string; auth: string[]; tnt: string } {
return this.helper.decodeToken(this.token);
}
public clear() {
this.token = null;
this.tokenStorageService.clear();
}
private extractAndLoadToken = (res: any): string => {
const token = res.token;
this.tokenStorageService.save(token);
this.loadToken(token);
return token;
};
private loadToken = (token: string) => {
this.token = token;
};
private loadInitToken() {
this.translateService
.get("global.wait")
.subscribe((message) =>
this.loadingController.create({ message }).then(this.loadStorage)
);
}
private loadStorage = (loading: HTMLIonLoadingElement) => {
loading.present();
this.tokenStorageService
.getValue()
.pipe(
switchMap((v) => (v ? of(v).pipe(delay(2000)) : of(v))),
take(1),
finalize(() => loading.dismiss())
)
.subscribe(this.loadToken);
};
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/self-service-service.module.ts
import { NgModule, Optional, SkipSelf } from "@angular/core";
import { ApiService } from "./api.service";
import { AuthService } from "./auth.service";
import { ErrorService } from "./error.service";
import { I18nService } from "./i18n.service";
import { LoginService } from "./login.service";
import { PagerQueryService } from "./pager-query.service";
import { PrincipalService } from "./principal.service";
import { TokenStorageService } from "./token-storage.service";
import { ValidationTranslateService } from "./validation-translate.service";
@NgModule({
providers: [
I18nService,
LoginService,
PagerQueryService,
ValidationTranslateService,
PrincipalService,
LoginService,
AuthService,
ApiService,
ErrorService,
TokenStorageService,
],
})
export class SelfServiceServiceModule {
constructor(@Optional() @SkipSelf() parentModule: SelfServiceServiceModule) {
if (parentModule) {
throw new Error(
"SelfServiceServiceModule has already been loaded. Import SelfServiceServiceModule in the AppModule only."
);
}
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/commons/DocumentUtils.java
package com.ufg.inf.ps.selfservice.infra.commons;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
public final class DocumentUtils {
public static boolean isCpf(String value) {
return type(value).equals(DocumentType.CPF);
}
public static boolean isCnpj(String value) {
return type(value).equals(DocumentType.CNPJ);
}
public static DocumentType type(String value) {
return DocumentType.valueOfByDocumentSize(value);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/interceptors/auth-interceptor.ts
import {
HttpHandler,
HttpInterceptor,
HttpRequest,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { AuthService } from "../services/auth.service";
const Authorization = "Authorization";
const ApplicationJson = "application/json";
const IGNORE_AUTH_PATHS = ["/api/authentication"];
@Injectable({
providedIn: "root",
})
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
public intercept(req: HttpRequest<any>, next: HttpHandler) {
const headersConfig = { Accept: ApplicationJson };
const token = this.authService.getToken();
if (token && !this.isIgnored(req.url)) {
headersConfig[Authorization] = `Bearer ${token}`;
}
const request = req.clone({ setHeaders: headersConfig });
return next.handle(request);
}
private isIgnored(url: string) {
return IGNORE_AUTH_PATHS.includes(url);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/modules/access/access.module.ts
import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
import { SharedModule } from "src/app/shared/shared.module";
import { AccessRoutingModule } from "./access-routing.module";
import { LayoutAccessComponent } from "./layout-access/layout-access.component";
import { LoginComponent } from "./login/login.component";
import { RegisterComponent } from "./register/register.component";
@NgModule({
declarations: [LoginComponent, LayoutAccessComponent, RegisterComponent],
imports: [CommonModule, AccessRoutingModule, SharedModule],
})
export class AccessModule {}
<file_sep>/4.Sistema/SelfServiceApp/src/app/interceptors/notification-interceptor.ts
import {
HttpHandler,
HttpInterceptor,
HttpRequest,
HttpResponse,
} from "@angular/common/http";
import { Injectable } from "@angular/core";
import { ToastController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { tap } from "rxjs/operators";
const STATUS_SUCCESS = [200, 201, 202];
@Injectable({
providedIn: "root",
})
export class NotificationInterceptor implements HttpInterceptor {
constructor(
private toastController: ToastController,
private translateService: TranslateService
) {}
public intercept(req: HttpRequest<any>, next: HttpHandler) {
return next.handle(req).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
const res = event as HttpResponse<any>;
const alertKey = res.headers.get("x-alert");
if (alertKey) {
const alertParam = res.headers.get("x-params") || null;
this.alert(res.status, alertKey, alertParam);
}
}
})
);
}
private alert(status: number, alertKey: string, param: string) {
if (STATUS_SUCCESS.indexOf(status) >= 0) {
this.translateService
.get(alertKey, { param })
.subscribe((res) => this.showSuccess(res));
}
}
private showSuccess(message: any) {
this.toastController
.create({
message,
color: "success",
buttons: [
{
icon: "close",
role: "cancel",
},
],
duration: 2000,
})
.then((res) => res.present());
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/modules/admin/home/home-routing.module.ts
import { NgModule } from "@angular/core";
import { RouterModule, Routes } from "@angular/router";
import { AboutDetailComponent } from "./pages/about-detail/about-detail.component";
import { ProfileDetailComponent } from "./pages/profile-detail/profile-detail.component";
import { ServiceDetailComponent } from "./pages/service-detail/service-detail.component";
const routes: Routes = [
{ path: "", redirectTo: "profile" },
{ path: "profile", component: ProfileDetailComponent },
{ path: "services", component: ServiceDetailComponent },
{ path: "about", component: AboutDetailComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class HomeRoutingModule {}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/ClientConstants.java
package com.ufg.inf.ps.selfservice.domain.client;
/**
* @author jonathas.assuncao on 10/12/2020
* @project SelfService
*/
public final class ClientConstants {
public static final String COMPANY_PERSON = "COMPANY_PERSON";
public static final String COMPANY_SUPPLIER = "COMPANY_SUPPLIER";
public static final String PHYSICAL_PERSON = "PHYSICAL_PERSON";
public static final String PHYSICAL_SUPPLIER = "PHYSICAL_SUPPLIER";
private ClientConstants() {
super();
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/selfservice-missing-translation-handler.ts
import {
MissingTranslationHandler,
MissingTranslationHandlerParams,
} from "@ngx-translate/core";
export class SelfServiceMissingTranslationHandler
implements MissingTranslationHandler {
public handle(params: MissingTranslationHandlerParams) {
return params.key;
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/app.module.ts
import { registerLocaleData } from "@angular/common";
import { HttpClient, HttpClientModule } from "@angular/common/http";
import localePt from "@angular/common/locales/pt";
import { LOCALE_ID, NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { RouteReuseStrategy } from "@angular/router";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { StatusBar } from "@ionic-native/status-bar/ngx";
import { IonicModule, IonicRouteStrategy } from "@ionic/angular";
import { IonicStorageModule } from "@ionic/storage";
import {
MissingTranslationHandler,
TranslateLoader,
TranslateModule,
TranslateService,
} from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { AuthGuard } from "./guards/auth.guard";
import { httpInterceptorProviders } from "./interceptors";
import { SelfServiceServiceModule } from "./services/self-service-service.module";
import { SelfServiceMissingTranslationHandler } from "./services/selfservice-missing-translation-handler";
import { SharedModule } from "./shared/shared.module";
import { LoginGuard } from "src/app/guards/login.guard";
import { LayoutMainComponent } from "./layouts/pages/layout-main/layout-main.component";
registerLocaleData(localePt);
@NgModule({
declarations: [AppComponent, LayoutMainComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
IonicStorageModule.forRoot(),
SharedModule,
AppRoutingModule,
SelfServiceServiceModule,
HttpClientModule,
TranslateModule.forRoot({
useDefaultLang: true,
missingTranslationHandler: {
provide: MissingTranslationHandler,
useClass: SelfServiceMissingTranslationHandler,
},
loader: {
provide: TranslateLoader,
useFactory: (http: HttpClient) =>
new TranslateHttpLoader(
http,
"assets/i18n/",
".json?cb" + new Date().getTime()
),
deps: [HttpClient],
},
}),
],
providers: [
AuthGuard,
LoginGuard,
StatusBar,
SplashScreen,
httpInterceptorProviders,
{
provide: LOCALE_ID,
useFactory: (translate: TranslateService) =>
translate.currentLang || "pt-br",
deps: [TranslateService],
},
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>/4.Sistema/SelfServiceApp/src/app/layouts/pages/layout-main/layout-main.component.ts
import { Component } from "@angular/core";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { StatusBar } from "@ionic-native/status-bar/ngx";
import { Platform } from "@ionic/angular";
import { BehaviorSubject } from "rxjs";
import { PrincipalService } from "../../../services/principal.service";
@Component({
templateUrl: "./layout-main.component.html",
styleUrls: ["./layout-main.component.scss"],
})
export class LayoutMainComponent {
public selectedIndex = new BehaviorSubject(0);
public user: any;
public readonly appPages = [
{
title: "menu.profile",
url: "home/profile",
icon: "mail",
},
{
title: "menu.services",
url: "home/services",
icon: "paper-plane",
},
{
title: "menu.about",
url: "home/about",
icon: "heart",
},
];
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private principalService: PrincipalService
) {
this.initializeApp();
this.principalService.getAccount().subscribe((res) => (this.user = res));
}
public initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
public onChangePage(page: number) {
this.selectedIndex.next(page);
}
public isPage(page: number) {
return page === this.selectedIndex.value;
}
public get folder(): string {
return this.appPages[this.selectedIndex.value].title;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/Client.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import com.ufg.inf.ps.selfservice.infra.commons.Checker;
import com.ufg.inf.ps.selfservice.infra.commons.Identification;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nClient;
import com.ufg.inf.ps.selfservice.infra.security.Credential;
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import java.util.HashMap;
import java.util.UUID;
/**
* @author jonathas.assuncao on 04/12/2020
* @project SelfService
*/
@Entity
@DiscriminatorColumn(name = "type")
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public abstract class Client extends Identification implements Credential {
private static final long serialVersionUID = 1L;
private String username;
private boolean active;
private boolean blocked;
private String password;
private String urlImage;
private String nickname;
private String name;
private String address;
@Type(type = "jsonb")
private HashMap<String, Object> wayPayments = new HashMap<>();
private String document;
Client() {
super();
}
Client(ClientData data) {
super();
setUsername(data.getUsername());
setPassword(data.getPassword());
data.getUrlImage().ifPresent(this::setUrlImage);
data.getNickname().ifPresent(this::setNickname);
setName(data.getName());
data.getAddress().ifPresent(this::setAddress);
setDocument(data.getDocument());
initialize();
}
void setUsername(String username) {
this.username = Checker.notBlankTrim(username, I18nClient.CLIENT_USERNAME_NOTBLANK);
}
void setActive(boolean active) {
this.active = active;
}
void setBlocked(boolean blocked) {
this.blocked = blocked;
}
void setPassword(String password) {
this.password = Checker.notBlankTrim(password, I18nClient.CLIENT_PASSWORD_NOTBLANK);
}
public String getUrlImage() {
return urlImage;
}
void setUrlImage(String urlImage) {
this.urlImage = urlImage;
}
public String getNickname() {
return nickname;
}
void setNickname(String nickname) {
this.nickname = nickname;
}
public String getName() {
return name;
}
void setName(String name) {
this.name = Checker.notBlankTrim(name, I18nClient.CLIENT_NAME_NOTBLANK);
}
public String getAddress() {
return address;
}
void setAddress(String address) {
this.address = address;
}
public String getDocument() {
return document;
}
void setDocument(String document) {
this.document = Checker.notBlankTrim(document, I18nClient.CLIENT_DOCUMENT_NOTBLANK);
}
public HashMap<String, Object> getWayPayments() {
return wayPayments;
}
void setWayPayments(HashMap<String, Object> wayPayments) {
this.wayPayments = wayPayments;
}
void actived() {
active = true;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isActive() {
return active;
}
@Override
public boolean isBlocked() {
return blocked;
}
@Override
public String getPassword() {
return <PASSWORD>;
}
@Override
public UUID getUserId() {
return getId();
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/label-error/label-error.component.ts
import { ChangeDetectionStrategy, Component, Input } from "@angular/core";
@Component({
selector: "app-label-error",
templateUrl: "./label-error.component.html",
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LabelErrorComponent {}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/intercionalization/MessageBuilder.java
package com.ufg.inf.ps.selfservice.infra.intercionalization;
import com.ufg.inf.ps.selfservice.infra.exception.MessageException;
/**
* @author jonathas.assuncao on 13/11/2020
* @project pdv
*/
@FunctionalInterface
public interface MessageBuilder {
String message(String key, Object... args);
default String message(I18nKey key, Object... args) {
return message(key.get(), args);
}
default String message(MessageException message) {
return message(message.getKey(), message.getArrayParams());
}
}<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/authenticate/SelfServiceDetailService.java
package com.ufg.inf.ps.selfservice.domain.authenticate;
import com.ufg.inf.ps.selfservice.domain.client.Client;
import com.ufg.inf.ps.selfservice.domain.client.ClientRepository;
import com.ufg.inf.ps.selfservice.infra.security.SecurityFunctions;
import com.ufg.inf.ps.selfservice.infra.security.SelfServiceDetails;
import com.ufg.inf.ps.selfservice.infra.security.UserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import java.util.Collections;
/**
* @author jonathas.assuncao on 07/12/2020
* @project SelfService
*/
@Component("userDetailsService")
public class SelfServiceDetailService implements UserDetailsService {
private final ClientRepository selfServiceClientStore;
public SelfServiceDetailService(ClientRepository clientRepository) {
this.selfServiceClientStore = clientRepository;
}
@Override
public UserDetails loadUserByUsername(final String username) {
Client user = getUser(username);
UserDetailsChecker.check(user);
return new SelfServiceDetails(user, Collections.emptyList());
}
private Client getUser(String username) {
return selfServiceClientStore.findByUsername(username).orElseThrow(SecurityFunctions.notFound(username));
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/app.component.ts
import { ChangeDetectionStrategy, Component } from "@angular/core";
import { I18nService } from "./services/i18n.service";
@Component({
selector: "app-root",
templateUrl: "app.component.html",
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
constructor(private i18nService: I18nService) {}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/guards/login.guard.ts
import { Injectable } from "@angular/core";
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
} from "@angular/router";
import { Observable, of } from "rxjs";
import { catchError, map, tap } from "rxjs/operators";
import { PrincipalService } from "../services/principal.service";
@Injectable()
export class LoginGuard implements CanActivate {
constructor(
private router: Router,
private principalService: PrincipalService
) {}
public canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
const redirect = route.queryParams.redirect;
return this.isUnauthenticated(redirect);
}
private isUnauthenticated(redirect: string): Observable<boolean> {
return this.principalService.isAuthenticated().pipe(
map((authenticated) => !authenticated),
tap((unauthenticated) => {
if (!unauthenticated) {
if (redirect) {
this.router.navigateByUrl(redirect);
} else {
this.router.navigate(["home"]);
}
}
}),
catchError(() => of(true))
);
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/security/SecurityFunctions.java
package com.ufg.inf.ps.selfservice.infra.security;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.function.Supplier;
/**
* @author jonathas.assuncao on 07/12/2020
* @project SelfService
*/
public final class SecurityFunctions {
private SecurityFunctions() {
super();
}
public static Supplier<UsernameNotFoundException> notFound(String username) {
return () -> new UsernameNotFoundException(String.format("Usuário: %s, não foi encontrado", username));
}
public static Supplier<BadCredentialsException> notAutenthicated() {
return () -> new BadCredentialsException("Usuário não autenticado");
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/guards/auth.guard.ts
import { Injectable } from "@angular/core";
import {
ActivatedRouteSnapshot,
CanActivate,
Route,
Router,
RouterStateSnapshot,
} from "@angular/router";
import { Observable, of } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { PrincipalService } from "../services/principal.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private principalService: PrincipalService
) {}
public canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.isLogged(state.url);
}
public canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> {
return this.canActivate(route, state);
}
public canLoad(route: Route): Observable<boolean> {
return this.isLogged();
}
private isLogged(url?: string): Observable<boolean> {
console.log("askjfnm,sdnbfkmzedr");
return this.principalService.isAuthenticated().pipe(
tap((authenticated) => {
if (!authenticated) {
this.navigateToLogin(url);
}
}),
catchError(() => {
this.navigateToLogin(url);
return of(false);
})
);
}
private navigateToLogin(url: string) {
this.router.navigate(["login"], { queryParams: { redirect: url } });
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/security/SelfServiceDetails.java
package com.ufg.inf.ps.selfservice.infra.security;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.UUID;
/**
* @author jonathas.assuncao on 03/12/2020
* @project SelfService
*/
public class SelfServiceDetails extends User implements Identity {
private static final long serialVersionUID = 1L;
private final UUID userId;
private final String username;
public SelfServiceDetails(Credential user, Collection<? extends GrantedAuthority> authorities) {
super(user.getUsername(), user.getPassword(), authorities);
userId = user.getUserId();
username = user.getUsername();
}
@Override
public UUID getUserId() {
return userId;
}
@Override
public String getUsername() {
return username;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/commons/DocumentValidator.java
package com.ufg.inf.ps.selfservice.infra.commons;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
public interface DocumentValidator {
boolean isValid(String document);
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/response/HeaderMessageBuilder.java
package com.ufg.inf.ps.selfservice.infra.response;
import org.springframework.http.HttpHeaders;
/**
* @author jonathas.assuncao
*/
public final class HeaderMessageBuilder {
public static final String X_ALERT = "x-alert";
public static final String X_PARAMS = "x-params";
HeaderMessageBuilder() {
super();
}
public HttpHeaders createAlert(String message, String param) {
HttpHeaders headers = createAlert(message);
headers.add(X_PARAMS, param);
return headers;
}
public HttpHeaders createAlert(String message) {
HttpHeaders headers = new HttpHeaders();
headers.add(X_ALERT, message);
return headers;
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/exception/errorbuilder/JwtExceptionErrorBuilder.java
package com.ufg.inf.ps.selfservice.infra.exception.errorbuilder;
import com.ufg.inf.ps.selfservice.infra.exception.Error;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorCode;
import com.ufg.inf.ps.selfservice.infra.exception.ErrorResponseBuilder;
import com.ufg.inf.ps.selfservice.infra.intercionalization.I18nCommon;
import com.ufg.inf.ps.selfservice.infra.intercionalization.MessageBuilder;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* @author guilherme.pacheco
*/
final class JwtExceptionErrorBuilder implements ErrorResponseBuilder<JwtException> {
@Override
public ResponseEntity<Error> build(JwtException exception, MessageBuilder messageBuilder) {
Error error = createError(exception, messageBuilder);
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error);
}
private Error createError(JwtException exception, MessageBuilder messageBuilder) {
if (exception instanceof ExpiredJwtException) {
String message = messageBuilder.message(I18nCommon.TOKEN_EXPIRED);
return new Error(ErrorCode.ACCESS_DENIED, message);
}
String message = messageBuilder.message(I18nCommon.TOKEN_INVALID);
return new Error(ErrorCode.ACCESS_DENIED, message);
}
@Override
public boolean accept(Exception exception) {
return JwtException.class.isInstance(exception);
}
}
<file_sep>/4.Sistema/SelfService/src/test/java/com/ufg/inf/ps/selfservice/application/authenticate/AuthenticationResourceITest.java
package com.ufg.inf.ps.selfservice.application.authenticate;
import com.ufg.inf.ps.selfservice.application.authenticate.command.LoginCommand;
import com.ufg.inf.ps.selfservice.core.IntegrationTest;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.ResultActions;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author jonathas.assuncao on 10/12/2020
* @project SelfService
*/
class AuthenticationResourceITest extends IntegrationTest {
@Test
void authenticate_client() throws Exception {
final String username = "<EMAIL>";
final String password = <PASSWORD>";
LoginCommand command = new LoginCommand(username, password);
ResultActions actions = mockMvc().perform(post("/api/authentication")
.contentType(MediaType.APPLICATION_JSON)
.content(json(command)))
.andExpect(status().isOk());
actions.andExpect(jsonPath("$.token").isNotEmpty());
}
@Test
void authenticate_supplier() throws Exception {
final String username = "<EMAIL>";
final String password = <PASSWORD>";
LoginCommand command = new LoginCommand(username, password);
ResultActions actions = mockMvc().perform(post("/api/authentication")
.contentType(MediaType.APPLICATION_JSON)
.content(json(command)))
.andExpect(status().isOk());
actions.andExpect(jsonPath("$.token").isNotEmpty());
}
@Test
void authenticate_wrongUsername() throws Exception {
final String username = "<EMAIL>";
final String password = <PASSWORD>";
LoginCommand command = new LoginCommand(username, password);
ResultActions actions = mockMvc().perform(post("/api/authentication")
.contentType(MediaType.APPLICATION_JSON)
.content(json(command)))
.andExpect(status().isBadRequest());
actions.andExpect(jsonPath("$.code").value("error.invalidParam"));
actions.andExpect(jsonPath("$.message").value("As credenciais informadas estão erradas"));
}
@Test
void authenticate_wrongPassword() throws Exception {
final String username = "<EMAIL>";
final String password = "<PASSWORD>";
LoginCommand command = new LoginCommand(username, password);
ResultActions actions = mockMvc().perform(post("/api/authentication")
.contentType(MediaType.APPLICATION_JSON)
.content(json(command)))
.andExpect(status().isBadRequest());
actions.andExpect(jsonPath("$.code").value("error.invalidParam"));
actions.andExpect(jsonPath("$.message").value("As credenciais informadas estão erradas"));
}
}<file_sep>/4.Sistema/SelfServiceApp/src/app/services/token-storage.service.ts
import { Injectable } from "@angular/core";
import { Storage } from "@ionic/storage";
import { BehaviorSubject, Observable } from "rxjs";
@Injectable({ providedIn: "root" })
export class TokenStorageService {
private readonly key = "token";
private value$ = new BehaviorSubject<string>(undefined);
constructor(private storage: Storage) {
this.storage.get(this.key).then((res) => this.value$.next(res));
}
public getValue(): Observable<string> {
return this.value$.asObservable();
}
public value(): string {
return this.value$.value;
}
public getBearerValue() {
return `Bearer ${this.getValue()}`;
}
public save(token: string) {
if (token) {
this.storage.set(this.key, token);
}
this.value$.next(token);
}
public clear() {
this.storage.remove(this.key);
this.value$.next(null);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/services/error.service.ts
import { Injectable } from "@angular/core";
import { ToastController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
@Injectable({
providedIn: "root",
})
export class ErrorService {
constructor(
private toastController: ToastController,
private translateService: TranslateService
) {}
public show(error: any) {
switch (error.code) {
case "error.communication":
this.communcationError();
break;
case "error.authentication":
this.authenticationError(error);
break;
case "error.accessDenied":
case "error.internalServerError":
this.internalError(error);
break;
case "error.invalidParam":
case "error.invalidOperation":
this.invalidOperation(error);
break;
case "error.multiValidation":
this.multiValidation(error);
break;
case "error.validation":
this.validation(error);
break;
default:
this.unexpectedError();
break;
}
}
private unexpectedError() {
this.translateService.get("error.unexpected").subscribe((value) => {
this.showError(value);
});
}
private validation(error: any) {
if (error.param) {
const body = error.param
.map((p: any) => p.field + ": " + p.message)
.join("<br>");
this.showError(error.message, body);
} else {
this.showError(error.message);
}
}
private multiValidation(error: any) {
if (error.param) {
const messages = error.param as string[];
this.showError(error.message, messages.join("<br>"));
} else {
this.showError(error.message);
}
}
private invalidOperation(error: any) {
this.showError(error.message);
}
private authenticationError(error: any) {
this.translateService.get("error.authentication").subscribe((value) => {
this.showError(value, error.message);
});
}
private communcationError() {
this.translateService
.get(["error.communication", "error.checkConnection"])
.subscribe((res) => {
this.showError(
res["error.communication"],
res["error.checkConnection"]
);
});
}
private internalError(error: any) {
this.showError(error.message);
}
private showError(header: any, message?: any) {
this.toastController
.create({
header,
message,
color: "danger",
buttons: [
{
icon: "close",
role: "cancel",
},
],
duration: 2000,
})
.then((res) => res.present());
}
}
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/infra/security/Credential.java
package com.ufg.inf.ps.selfservice.infra.security;
/**
* @author jonathas.assuncao on 03/12/2020
* @project SelfService
*/
public interface Credential extends Identity {
String getUsername();
boolean isActive();
boolean isBlocked();
String getPassword();
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/shared/utils/regex.ts
export const DATE_REGEX = new RegExp('^([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])');
<file_sep>/4.Sistema/SelfService/src/main/java/com/ufg/inf/ps/selfservice/domain/client/ClientUseCase.java
package com.ufg.inf.ps.selfservice.domain.client;
import com.ufg.inf.ps.selfservice.application.client.ClientData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author jonathas.assuncao on 11/12/2020
* @project SelfService
*/
@Service
public class ClientUseCase {
@Autowired
private ClientFactory clientFactory;
@Autowired
private ClientChecker clientChecker;
@Autowired
private ClientRepository clientRepository;
public Client create(ClientData data) {
Client client = clientFactory.build(data);
clientChecker.check(client);
client.actived();
return clientRepository.save(client);
}
}
<file_sep>/4.Sistema/SelfServiceApp/src/app/modules/access/login/login.component.ts
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
OnInit,
} from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { BehaviorSubject } from "rxjs";
import { finalize } from "rxjs/operators";
import { LoginCommand } from "src/app/models/commands/login.command";
import { LoginService } from "src/app/services/login.service";
import { TokenStorageService } from "src/app/services/token-storage.service";
import { ValidationTranslateService } from "src/app/services/validation-translate.service";
import { ErrorMessages } from "src/app/shared/forms";
import { FormModel } from "../../../shared/forms/form-model";
@Component({
templateUrl: "./login.component.html",
styleUrls: ["./login.component.scss"],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class LoginComponent implements OnInit, OnDestroy {
public form: FormGroup;
public errors: ErrorMessages;
public submitted$ = new BehaviorSubject(false);
private redirect: string;
constructor(
private router: Router,
private formBuilder: FormBuilder,
private loginService: LoginService,
private activatedRoute: ActivatedRoute,
private tokenStorageService: TokenStorageService,
private validationTranslateService: ValidationTranslateService
) {
this.redirect = this.activatedRoute.snapshot.queryParams.redirect;
}
public ngOnInit() {
this.initForm();
}
public ngOnDestroy(): void {
this.submitted$.complete();
}
public onSubmit(form: FormGroup) {
if (form.valid) {
if (!this.submitted$.value) {
this.submitted$.next(true);
this.login(form.value);
}
} else {
this.validationTranslateService.valid(form);
}
}
private initForm() {
this.form = this.formBuilder.group(this.formModel);
this.errors = this.validationTranslateService.errors(this.form);
}
private get formModel(): FormModel<LoginCommand> {
return {
username: [undefined, Validators.required],
password: [undefined, [Validators.required, Validators.minLength(5)]],
};
}
private login(value: any) {
this.tokenStorageService.clear();
this.loginService
.login(value)
.pipe(finalize(() => this.submitted$.next(false)))
.subscribe(this.redirectTo);
}
private redirectTo = () => {
if (this.redirect) {
this.router.navigateByUrl(this.redirect);
} else {
this.router.navigate(["home"]);
}
};
}
|
723b4d339ea61e31e26684c87e2283f9e77cc3e6
|
[
"Markdown",
"Java",
"TypeScript",
"Maven POM"
] | 72
|
Java
|
jonassuncao/PS-SI-2020-1-Self-Service
|
d12ad9eff061fdc1041e8107ab7847d257ad78e9
|
f97150b0eb96a2e2784a911283bf04c6a736f404
|
refs/heads/master
|
<file_sep>#include "KW_renderdriver_sdl2.h"
#include "KW_renderdriver.h"
#include "KW_widget.h"
#include "SDL.h"
#include "SDL_ttf.h"
#include "SDL_image.h"
#include <stdio.h>
typedef struct KWSDL {
SDL_Renderer * renderer;
SDL_Window * window;
} KWSDL;
static void KWSDL_renderCopy(KW_RenderDriver * driver, KW_Texture * texture, const KW_Rect * src, const KW_Rect * dst);
static KW_Texture * KWSDL_renderText(KW_RenderDriver * driver, KW_Font * font, const char * text, KW_Color color, KW_RenderDriver_TextStyle style);
static KW_Font * KWSDL_loadFont(KW_RenderDriver * driver, const char * font, unsigned ptSize);
static KW_Font * KWSDL_createTexture(KW_RenderDriver * driver, KW_Surface * surface);
static KW_Surface * KWSDL_createRGBA32Surface(KW_RenderDriver * driver, unsigned width, unsigned height);
static KW_Texture * KWSDL_loadTexture(KW_RenderDriver * driver, const char * texturefile);
static KW_Surface * KWSDL_loadSurface(KW_RenderDriver * driver, const char * texturefile);
static void KWSDL_getSurfaceExtents(KW_RenderDriver * driver, const KW_Surface * surface, unsigned * width, unsigned * height);
static void KWSDL_getTextureExtents(KW_RenderDriver * driver, KW_Texture * texture, unsigned * width, unsigned * height);
static void KWSDL_releaseTexture(KW_RenderDriver * driver, KW_Texture * texture);
static void KWSDL_releaseFont(KW_RenderDriver * driver, KW_Font * font);
static void KWSDL_blitSurface(KW_RenderDriver * driver, KW_Surface * src, const KW_Rect * srcRect, KW_Surface * dst, const KW_Rect * dstRect);
static void KWSDL_releaseSurface(KW_RenderDriver * driver, KW_Surface * font);
static void KWSDL_setClipRect(KW_RenderDriver * driver, const KW_Rect * clip, int force);
static void KWSDL_getClipRect(KW_RenderDriver * driver, KW_Rect * clip);
struct KW_RenderDriver * KW_CreateSDL2RenderDriver(SDL_Renderer * renderer, SDL_Window * window) {
struct KWSDL * kwsdl = calloc(sizeof(*kwsdl), 1);
struct KW_RenderDriver * rd = calloc(sizeof(*rd), 1);
TTF_Init();
kwsdl->renderer = renderer;
kwsdl->window = window;
rd->renderCopy = KWSDL_renderCopy;
rd->renderText = KWSDL_renderText;
rd->loadFont = KWSDL_loadFont;
rd->createTexture = KWSDL_createTexture;
rd->createSurface = KWSDL_createRGBA32Surface;
rd->loadTexture = KWSDL_loadTexture;
rd->loadSurface = KWSDL_loadSurface;
rd->getSurfaceExtents = KWSDL_getSurfaceExtents;
rd->getTextureExtents = KWSDL_getTextureExtents;
rd->blitSurface = KWSDL_blitSurface;
rd->releaseFont = KWSDL_releaseFont;
rd->releaseSurface = KWSDL_releaseSurface;
rd->releaseTexture = KWSDL_releaseTexture;
rd->setClipRect = KWSDL_setClipRect;
rd->getClipRect = KWSDL_getClipRect;
rd->priv = kwsdl;
return rd;
}
static KW_Texture * KWSDL_createTexture(KW_RenderDriver * driver, KW_Surface * surface) {
KWSDL * kwsdl = (KWSDL *) driver->priv;
SDL_Texture * t = SDL_CreateTextureFromSurface(kwsdl->renderer, (SDL_Surface *)surface);
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);
return t;
}
static KW_Surface * KWSDL_createRGBA32Surface(KW_RenderDriver * driver, unsigned width, unsigned height) {
unsigned rmask, gmask, bmask, amask;
SDL_Surface * s;
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
rmask = 0xff000000;
gmask = 0x00ff0000;
bmask = 0x0000ff00;
amask = 0x000000ff;
#else
rmask = 0x000000ff;
gmask = 0x0000ff00;
bmask = 0x00ff0000;
amask = 0xff000000;
#endif
s = SDL_CreateRGBSurface(0, width, height, 32, rmask, gmask, bmask, amask);
SDL_SetSurfaceBlendMode(s, SDL_BLENDMODE_NONE);
return s;
}
static KW_Font * KWSDL_loadFont(KW_RenderDriver * driver, const char * font, unsigned ptSize) {
TTF_Font * f = TTF_OpenFont(font, ptSize);
(void)driver;
if (f == NULL) {
fprintf(stderr, "KW_RenderDriver_SDL: Could not load font %s: %s\n", font, TTF_GetError());
return NULL;
}
return f;
}
static KW_Surface * KWSDL_loadSurface(KW_RenderDriver * driver, const char * texturefile) {
SDL_Surface * s = IMG_Load(texturefile);
if (s == NULL) {
fprintf(stderr, "KW_RenderDriver_SDL: Could not load texture %s: %s\n", texturefile, IMG_GetError());
return NULL;
}
SDL_SetSurfaceBlendMode(s, SDL_BLENDMODE_NONE);
return s;
}
static void KWSDL_getSurfaceExtents(KW_RenderDriver * driver, const KW_Surface * surface, unsigned * width, unsigned * height) {
(void)driver;
if (width) *width = ((SDL_Surface*)surface)->w;
if (height) *height = ((SDL_Surface*)surface)->h;
}
static void KWSDL_getTextureExtents(KW_RenderDriver * driver, KW_Surface * texture, unsigned * width, unsigned * height) {
int w, h;
(void)driver;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
*width = w; *height = h;
}
static void KWSDL_blitSurface(KW_RenderDriver * driver, KW_Surface * src, const KW_Rect * srcRect, KW_Surface * dst, const KW_Rect * dstRect) {
SDL_Rect s, d;
s.x = srcRect->x; s.y = srcRect->y; s.w = srcRect->w; s.h = srcRect->h;
d.x = dstRect->x; d.y = dstRect->y; d.w = dstRect->w; d.h = dstRect->h;
SDL_BlitSurface((SDL_Surface *) src, &s, (SDL_Surface *) dst, &d);
}
static KW_Texture * KWSDL_loadTexture(KW_RenderDriver * driver, const char * texturefile) {
KWSDL * kwsdl = (KWSDL *) driver->priv;
SDL_Texture * t = IMG_LoadTexture(kwsdl->renderer, texturefile);
if (t == NULL) {
fprintf(stderr, "KW_RenderDriver_SDL: Could not load texture %s: %s\n", texturefile, IMG_GetError());
return NULL;
}
SDL_SetTextureBlendMode(t, SDL_BLENDMODE_BLEND);
return t;
}
static KW_Texture * KWSDL_renderText(KW_RenderDriver * driver, KW_Font * font, const char * text, KW_Color color, KW_RenderDriver_TextStyle style) {
KWSDL * kwsdl = (KWSDL *) driver->priv;
int previousstyle;
SDL_Color sdlcolor;
SDL_Surface * textsurface;
SDL_Texture * ret;
sdlcolor.r = color.r, sdlcolor.g = color.g, sdlcolor.b = color.b, sdlcolor.a = color.a;
if (font == NULL || text == NULL)
return NULL;
previousstyle = TTF_GetFontStyle(font);
TTF_SetFontStyle(font, style);
textsurface = TTF_RenderUTF8_Blended(font, text, sdlcolor);
ret = SDL_CreateTextureFromSurface(kwsdl->renderer, textsurface);
SDL_FreeSurface(textsurface);
TTF_SetFontStyle(font, previousstyle);
return ret;
}
static void KWSDL_releaseTexture(KW_RenderDriver * driver, KW_Texture * texture) {
(void)driver;
SDL_DestroyTexture(texture);
}
static void KWSDL_releaseSurface(KW_RenderDriver * driver, KW_Surface * surface) {
(void)driver;
SDL_FreeSurface(surface);
}
static void KWSDL_releaseFont(KW_RenderDriver * driver, KW_Font * font) {
(void)driver;
TTF_CloseFont(font);
}
static void KWSDL_renderCopy(KW_RenderDriver * driver, KW_Texture * texture, const KW_Rect * src, const KW_Rect * dst) {
KWSDL * kwsdl = (KWSDL *) driver->priv;
SDL_Rect srcRect, dstRect;
if (src) { srcRect.x = src->x; srcRect.y = src->y; srcRect.w = src->w; srcRect.h = src->h; }
if (dst) { dstRect.x = dst->x; dstRect.y = dst->y; dstRect.w = dst->w; dstRect.h = dst->h; }
SDL_RenderCopy(kwsdl->renderer, texture, src ? &srcRect : NULL, dst? &dstRect : NULL);
}
static void KWSDL_setClipRect(KW_RenderDriver * driver, const KW_Rect * clip, int force) {
SDL_Renderer * renderer = ((KWSDL *)driver->priv)->renderer;
SDL_Rect viewport, cliprect;
static SDL_RendererInfo info;
static int isopengl = -1;
cliprect.x = clip->x; cliprect.y = clip->y; cliprect.w = clip->w; cliprect.h = clip->h;
if (isopengl < 0) {
SDL_GetRendererInfo(renderer, &info);
isopengl = (strcmp(info.name, "opengl") >= 0) ? 1 : 0;
}
if (isopengl && !force) {
/* fix for SDL buggy opengl scissor test. See SDL bug 2269.
* Not sure about other renderers. */
SDL_RenderGetViewport(renderer, &viewport);
cliprect.x += viewport.x; cliprect.y -= viewport.y;
}
if (KW_IsRectEmpty((*clip)))
SDL_RenderSetClipRect(renderer, NULL);
else
SDL_RenderSetClipRect(renderer, &cliprect);
}
static void KWSDL_getClipRect(KW_RenderDriver * driver, KW_Rect * clip) {
SDL_Rect c;
SDL_RenderGetClipRect(((KWSDL *)driver->priv)->renderer, &c);
clip->x = c.x; clip->y = c.y; clip->w = c.w; clip->h = c.h;
}
<file_sep>#include "SDL.h"
#include "KW_gui.h"
#include "KW_button.h"
#include "KW_renderdriver_sdl2.h"
int main(int argc, char ** argv) {
/* initialize window and renderer */
KW_RenderDriver * driver;
SDL_Window * window;
SDL_Renderer * renderer;
KW_Surface * set;
KW_GUI * gui;
KW_Font * font;
KW_Rect framegeom, labelgeom;
KW_Widget * frame;
int i = 0;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_CreateWindowAndRenderer(320, 240, 0, &window, &renderer);
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 1);
driver = KW_CreateSDL2RenderDriver(renderer, window);
/* load tileset */
set = KW_LoadSurface(driver, "tileset.png");
/* initialize gui */
gui = KW_Init(driver, set);
font = KW_LoadFont(driver, "Fontin-Regular.ttf", 12);
KW_SetFont(gui, font);
framegeom.x = 10, framegeom.y = 10, framegeom.w = 160, framegeom.h = 120;
labelgeom = framegeom; labelgeom.x = labelgeom.y = 0;
/* create 10 frames and 10 labels */
frame = NULL;
for (i = 0; i < 10; i++) {
frame = KW_CreateButton(gui, frame, "Yay", &framegeom);
}
while (!SDL_QuitRequested()) {
SDL_RenderClear(renderer);
KW_Paint(gui);
SDL_RenderPresent(renderer);
SDL_Delay(1);
}
/* free stuff */
KW_Quit(gui);
TTF_CloseFont(font);
SDL_FreeSurface(set);
TTF_Quit();
SDL_Quit();
return 0;
}
<file_sep>#ifndef KW_FRAME_INTERNAL_H
#define KW_FRAME_INTERNAL_H
#include "SDL.h"
typedef struct KW_Frame {
SDL_Texture * framerender;
} KW_Frame;
KW_Frame * AllocFrame();
void RenderFrame(KW_Widget * widget);
void PaintFrame(KW_Widget * widget);
void DestroyFrame(KW_Widget * widget);
void FrameGeometryChanged(KW_Widget * widget, const KW_Rect * newrect, const KW_Rect * old);
#endif
<file_sep>set(SDL2_BUILDING_LIBRARY TRUE)
find_package(SDL2 REQUIRED)
find_package(SDL2_ttf REQUIRED)
find_package(SDL2_image REQUIRED)
set(API_HEADERS
KW_gui.h
KW_button.h
KW_editbox.h
KW_frame.h
KW_label.h
KW_macros.h
KW_tilerenderer.h
KW_widget.h
KW_scrollbox.h
KW_renderdriver_sdl2.h
KW_renderdriver.h
)
set(LIB_SOURCES
KW_scrollbox_internal.c
KW_scrollbox.c
KW_editbox_internal.c
utf8.c
KW_editbox.c
KW_eventwatcher.c
KW_button.c
KW_label.c
KW_label_internal.c
KW_gui.c
KW_frame.c
KW_frame_internal.c
KW_tilerenderer.c
KW_widget.c
KW_widget_eventhandlers.c
KW_renderdriver.c
KW_renderdriver_sdl2.c
)
include_directories(${SDL2_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR} ${SDL2_TTF_INCLUDE_DIR})
add_library(KiWi SHARED ${LIB_SOURCES} ${API_HEADERS})
target_link_libraries(KiWi ${SDL2_LIBRARIES} ${SDL2_TTF_LIBRARIES} ${SDL2_IMAGE_LIBRARIES})
# Configure install stuff
install(TARGETS KiWi EXPORT KiWiTargets
RUNTIME DESTINATION bin
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
)
install(FILES ${API_HEADERS} DESTINATION include/KiWi)
<file_sep>#ifndef KW_RENDERDRIVER_SDL2
#define KW_RENDERDRIVER_SDL2
struct SDL_Renderer;
struct SDL_Window;
#include "KW_macros.h"
extern DECLSPEC struct KW_RenderDriver * KW_CreateSDL2RenderDriver(struct SDL_Renderer * renderer, struct SDL_Window * window);
#endif
<file_sep>#include "KW_renderdriver.h"
void KW_BlitSurface(KW_RenderDriver * driver, KW_Surface * src, const KW_Rect * srcRect, KW_Surface * dst, const KW_Rect * dstRect) {
driver->blitSurface(driver, src, srcRect, dst, dstRect);
}
KW_Surface * KW_CreateSurface(KW_RenderDriver * driver, unsigned width, unsigned height) {
return driver->createSurface(driver, width, height);
}
void KW_GetSurfaceExtents(KW_RenderDriver * driver, const KW_Surface * surface, unsigned * width, unsigned * height) {
driver->getSurfaceExtents(driver, surface, width, height);
}
void KW_GetTextureExtents(KW_RenderDriver * driver, KW_Texture * texture, unsigned * width, unsigned * height) {
driver->getTextureExtents(driver, texture, width, height);
}
void KW_RenderCopy(KW_RenderDriver * driver, KW_Texture * src, const KW_Rect * clip, const KW_Rect * dstRect) {
driver->renderCopy(driver, src, clip, dstRect);
}
KW_Surface * KW_RenderText(KW_RenderDriver * driver, KW_Font * font, const char * text, KW_Color color, KW_RenderDriver_TextStyle style) {
return driver->renderText(driver, font, text, color, style);
}
KW_Font * KW_LoadFont(KW_RenderDriver * driver, const char * fontFile, unsigned ptSize) {
return driver->loadFont(driver, fontFile, ptSize);
}
KW_Texture * KW_CreateTexture(KW_RenderDriver * driver, KW_Surface * surface) {
return driver->createTexture(driver, surface);
}
KW_Texture * KW_LoadTexture(KW_RenderDriver * driver, const char * file) {
return driver->loadTexture(driver, file);
}
KW_Surface * KW_LoadSurface(KW_RenderDriver * driver, const char * file) {
return driver->loadSurface(driver, file);
}
void KW_ReleaseTexture(KW_RenderDriver * driver, KW_Texture * texture) {
driver->releaseTexture(driver, texture);
}
void KW_ReleaseSurface(KW_RenderDriver * driver, KW_Surface * surface) {
driver->releaseSurface(driver, surface);
}
void KW_ReleaseFont(KW_RenderDriver * driver, KW_Font * font) {
driver->releaseFont(driver, font);
}
void KW_SetClipRect(KW_RenderDriver * driver, const KW_Rect * clip, int force) {
driver->setClipRect(driver, clip, force);
}
void KW_GetClipRect(KW_RenderDriver * driver, KW_Rect * clip) {
driver->getClipRect(driver, clip);
}
<file_sep>#ifndef KW_BUTTON_INTERNAL_H
#define KW_BUTTON_INTERNAL_H
#include "KW_widget.h"
typedef struct KW_Button {
KW_Widget * labelwidget; /* the label inside the button frame */
KW_bool mouseover;
KW_bool clicked;
KW_Texture * normal;
KW_Texture * over;
} KW_Button;
#endif
<file_sep># Find SDL2
find_package(SDL2 REQUIRED)
# Include relevat dirs
include_directories(${SDL2_INCLUDE_DIR} ${SDL2_IMAGE_INCLUDE_DIR} ${SDL2_TTF_INCLUDE_DIR} ${KIWI_INCLUDE_DIR})
# The playground example
add_subdirectory(playground)
# Frame family example
add_subdirectory(frame-family)
# Editbox example
add_subdirectory(editbox)
# Styleswitcher example
#add_subdirectory(styleswitcher)
# Scroll area example
#add_subdirectory(scrollbox)
# Drag widget example
#add_subdirectory(drag)
<file_sep>#include "SDL.h"
#include "KW_gui.h"
#include "KW_button.h"
#include "KW_frame.h"
#include "KW_editbox.h"
#include "KW_label.h"
#include "KW_renderdriver_sdl2.h"
int main(int argc, char ** argv) {
SDL_Window * window;
SDL_Renderer * renderer;
KW_RenderDriver * driver;
KW_Surface * set;
KW_GUI * gui;
KW_Rect framegeom, editgeom, labelgeom, buttongeom;
KW_Widget * frame, * editbx, * label;
KW_Font * fontin, * dejavu;
/* initialize window and renderer, and create a render driver */
SDL_Init(SDL_INIT_EVERYTHING);
SDL_CreateWindowAndRenderer(320, 240, 0, &window, &renderer);
SDL_SetRenderDrawColor(renderer, 100, 100, 200, 1);
driver = KW_CreateSDL2RenderDriver(renderer, window);
/* load tileset */
set = KW_LoadSurface(driver, "tileset.png");
/* initialize gui */
gui = KW_Init(driver, set);
fontin = KW_LoadFont(driver, "Fontin-Regular.ttf", 12);
dejavu = KW_LoadFont(driver, "DejaVuSans.ttf", 12);
KW_SetFont(gui, fontin);
framegeom.x = 10, framegeom.y = 10, framegeom.w = 300, framegeom.h = 220;
frame = KW_CreateFrame(gui, NULL, &framegeom);
buttongeom.x = 120, buttongeom.y = 110, buttongeom.w = 170, buttongeom.h = 30;
KW_CreateButton(gui, frame, "Friendship? Again?!", &buttongeom);
framegeom.w -= 20; framegeom.h = 100;
editgeom.x = 120, editgeom.y = 20, editgeom.w = 150, editgeom.h = 30;
labelgeom.x = 10, labelgeom.y = 20, labelgeom.w = 110, labelgeom.h = 30;
frame = KW_CreateFrame(gui, frame, &framegeom);
editbx = KW_CreateEditbox(gui, frame, "Editbox #1", &editgeom);
KW_SetEditboxFont(editbx, dejavu);
label = KW_CreateLabel(gui, frame, "Type your destiny:", &labelgeom);
KW_SetLabelAlignment(label, KW_LABEL_ALIGN_RIGHT, 0, KW_LABEL_ALIGN_MIDDLE, 0);
editgeom.x = 120, editgeom.y = 50, editgeom.w = 150, editgeom.h = 30;
labelgeom.x = 10, labelgeom.y = 50, labelgeom.w = 110, labelgeom.h = 30;
editbx = KW_CreateEditbox(gui, frame, "Editbox #2", &editgeom);
label = KW_CreateLabel(gui, frame, "Again:", &labelgeom);
KW_SetLabelAlignment(label, KW_LABEL_ALIGN_RIGHT, 0, KW_LABEL_ALIGN_MIDDLE, 0);
while (!SDL_QuitRequested()) {
SDL_RenderClear(renderer);
KW_Paint(gui);
SDL_RenderPresent(renderer);
SDL_Delay(1);
}
/* free stuff */
KW_Quit(gui);
TTF_CloseFont(fontin);
TTF_CloseFont(dejavu);
SDL_FreeSurface(set);
TTF_Quit();
SDL_Quit();
return 0;
}
<file_sep>#ifndef RENDERDRIVER_H
#define RENDERDRIVER_H
/**
* \file KW_renderdriver.h
*
* Declares the RenderDriver API to be implemented to create new Render Drivers
**/
#include "KW_macros.h"
typedef void KW_Texture;
typedef void KW_Font;
typedef void KW_Surface;
typedef struct KW_Rect {
unsigned int x;
unsigned int y;
unsigned int w;
unsigned int h;
} KW_Rect;
#define KW_IsRectEmpty(r) \
(((r.x) > 0) && ((r.y) > 0) && ((r.w) > 0) && ((r.h) > 0))
/**
* \brief Holds a color in the RGBA format
**/
typedef struct KW_Color {
unsigned char r;
unsigned char g;
unsigned char b;
unsigned char a;
} KW_Color;
typedef struct KW_RenderDriver KW_RenderDriver;
/**
* \brief Defines how text should be rendered
**/
typedef enum KW_RenderDriver_TextStyle {
KW_TTF_STYLE_NORMAL = 0x00,
KW_TTF_STYLE_BOLD = 0x01,
KW_TTF_STYLE_ITALIC = 0x02,
KW_TTF_STYLE_UNDERLINE = 0x04,
KW_TTF_STYLE_STRIKETHROUGH = 0x08
} KW_RenderDriver_TextStyle;
/**
* \brief Declares the prototype for a RenderCopy function
* \details A RenderCopy function deals with Textures that are possibly in GPU's RAM.
* It should be able to take a src texture and render it, applying clipping with clipRect
* and scaling with dstRect.
* \param driver the RenderDriver that will render this texture.
* \param src the source texture.
* \param clip the clipping rectangle for the source texture (in pixels)
* \param dstRect the destination rect. If different that clipping rectangle, it should scale to fit.
*/
typedef void (*KW_RenderCopyFunction)(KW_RenderDriver * driver, KW_Texture * src, const KW_Rect * clip, const KW_Rect * dstRect);
/**
* \brief Declares the prototype for a RenderText function.
* \details A RenderText function should be able to receive a font, a textline and a color and
* it should be able to produce a surface (pixeldata in CPU's memory) to be later transformed
* into a texture.
* \param driver the RenderDriver that will render this texture.
* \param font the font to use when rendering text.
* \param color the color that should be used.
* \param style the KW_RenderDriver_TextStyle style to apply.
* \return a KW_Surface to be later used as a texture.
*/
typedef KW_Surface * (*KW_RenderTextFunction)(KW_RenderDriver * driver, KW_Font * font, const char * text, KW_Color color, KW_RenderDriver_TextStyle style);
/**
* \brief Declares the prototype for a LoadFont function.
* \details LoadFont should be able to load a fontFile with the specified point size.
* \param driver the RenderDriver that will render this texture.
* \param fontFile the file containing the font (usually .ttf)
* \return a KW_Font suitable to use with KW_RenderText
*/
typedef KW_Font * (*KW_LoadFontFunction)(KW_RenderDriver * driver, const char * fontFile, unsigned ptSize);
/**
* \brief Declares the prototype for a CreateTexture function.
* \details CreateTexture should be able to create a KW_Texture from a KW_Surface.
* \param driver the RenderDriver that will render this texture.
* \param src the source KW_Surface.
* \return a KW_Texture in suitable to use with KW_RenderCopy
*/
typedef KW_Texture * (*KW_CreateTextureFunction)(KW_RenderDriver * driver, KW_Surface * src);
/**
* \brief Declares the prototype for a LoadTexture function.
* \details LoadTexture should be able to create a KW_Texture from a file.
* \param driver the RenderDriver that will load this texture.
* \param file the file name with the pixeldata.
* \return a KW_Texture suitable to use with KW_RenderCopy
*/
typedef KW_Texture * (*KW_LoadTextureFunction)(KW_RenderDriver * driver, const char * file);
/**
* \brief Declares the prototype for a LoadSurface function.
* \details LoadSurface should be able to create a KW_Surface from a file.
* \param driver the RenderDriver that will load this surface.
* \param file the file name with the pixeldata.
* \return a KW_Surface.
*/
typedef KW_Surface * (*KW_LoadSurfaceFunction)(KW_RenderDriver * driver, const char * file);
typedef void (*KW_ReleaseTextureFunction)(KW_RenderDriver * driver, KW_Texture * texture);
typedef void (*KW_ReleaseSurfaceFunction)(KW_RenderDriver * driver, KW_Surface * surface);
typedef void (*KW_ReleaseFontFunction)(KW_RenderDriver * driver, KW_Font * font);
typedef KW_Surface * (*KW_CreateSurfaceFunction)(KW_RenderDriver * driver, unsigned width, unsigned height);
typedef void (*KW_GetSurfaceExtentsFunction)(KW_RenderDriver * driver, const KW_Surface * surface, unsigned * width, unsigned * height);
typedef void (*KW_GetTextureExtentsFunction)(KW_RenderDriver * driver, KW_Texture * texture, unsigned * width, unsigned * height);
typedef void (*KW_BlitSurfaceFunction)(KW_RenderDriver * driver, KW_Surface * src, const KW_Rect * srcRect, KW_Surface * dst, const KW_Rect * dstRect);
typedef void (*KW_SetClipRectFunction)(KW_RenderDriver * driver, const KW_Rect * clip, int force);
typedef void (*KW_GetClipRectFunction)(KW_RenderDriver * driver, KW_Rect * clip);
struct KW_RenderDriver {
KW_RenderCopyFunction renderCopy;
KW_RenderTextFunction renderText;
KW_LoadFontFunction loadFont;
KW_CreateTextureFunction createTexture;
KW_CreateSurfaceFunction createSurface;
KW_LoadTextureFunction loadTexture;
KW_LoadSurfaceFunction loadSurface;
KW_GetSurfaceExtentsFunction getSurfaceExtents;
KW_GetTextureExtentsFunction getTextureExtents;
KW_BlitSurfaceFunction blitSurface;
KW_ReleaseTextureFunction releaseTexture;
KW_ReleaseSurfaceFunction releaseSurface;
KW_ReleaseFontFunction releaseFont;
KW_SetClipRectFunction setClipRect;
KW_GetClipRectFunction getClipRect;
void * priv;
};
extern DECLSPEC void KW_BlitSurface(KW_RenderDriver * driver, KW_Surface * src, const KW_Rect * srcRect, KW_Surface * dst, const KW_Rect * dstRect);
extern DECLSPEC KW_Surface * KW_CreateSurface(KW_RenderDriver * driver, unsigned width, unsigned height);
extern DECLSPEC void KW_GetSurfaceExtents(KW_RenderDriver * driver, const KW_Surface * surface, unsigned * width, unsigned * height);
extern DECLSPEC void KW_GetTextureExtents(KW_RenderDriver * driver, KW_Texture * texture, unsigned * width, unsigned * height);
extern DECLSPEC void KW_RenderCopy(KW_RenderDriver * driver, KW_Texture * src, const KW_Rect * clip, const KW_Rect * dstRect);
extern DECLSPEC KW_Surface * KW_RenderText(KW_RenderDriver * driver, KW_Font * font, const char * text, KW_Color color, KW_RenderDriver_TextStyle style);
extern DECLSPEC KW_Font * KW_LoadFont(KW_RenderDriver * driver, const char * fontFile, unsigned ptSize);
extern DECLSPEC KW_Texture * KW_CreateTexture(KW_RenderDriver * driver, KW_Surface * surface);
extern DECLSPEC KW_Texture * KW_LoadTexture(KW_RenderDriver * driver, const char * file);
extern DECLSPEC KW_Surface * KW_LoadSurface(KW_RenderDriver * driver, const char * file);
extern DECLSPEC void KW_ReleaseTexture(KW_RenderDriver * driver, KW_Texture * texture);
extern DECLSPEC void KW_ReleaseSurface(KW_RenderDriver * driver, KW_Surface * surface);
extern DECLSPEC void KW_ReleaseFont(KW_RenderDriver * driver, KW_Font * font);
extern DECLSPEC void KW_GetClipRect(KW_RenderDriver * driver, KW_Rect * clip);
extern DECLSPEC void KW_SetClipRect(KW_RenderDriver * driver, const KW_Rect * clip, int force);
#endif
<file_sep>#include "KW_gui.h"
#include "KW_frame.h"
#include "KW_label.h"
#include "KW_renderdriver_sdl2.h"
int main(int argc, char ** argv) {
/* init SDL and SDL_ttf */
KW_RenderDriver * driver;
SDL_Renderer * renderer;
SDL_Window * window;
KW_Surface * set;
KW_GUI * gui;
KW_Font * font;
KW_Widget * frame, * l;
KW_Rect geometry, c;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_CreateWindowAndRenderer(320, 240, 0, &window, &renderer);
SDL_SetRenderDrawColor(renderer, 100, 100, 100, 1);
driver = KW_CreateSDL2RenderDriver(renderer, window);
/* load tileset surface */
set = KW_LoadSurface(driver, "tileset.png");
/* load font */
font = KW_LoadFont(driver, "Fontin-Regular.ttf", 12);
/* init KiWi */
gui = KW_Init(driver, set);
KW_SetFont(gui, font);
/* create a frame and a label on top of it. */
geometry.x = geometry.y = 0; geometry.w = 320; geometry.h = 240;
frame = KW_CreateFrame(gui, NULL, &geometry);
l = KW_CreateLabel(gui, frame, "Label with an icon :)", &geometry);
c.x = 0; c.y = 48; c.w = 24; c.h = 24;
KW_SetLabelIcon(l, &c);
while (!SDL_QuitRequested()) {
SDL_RenderClear(renderer);
KW_Paint(gui);
SDL_Delay(1);
SDL_RenderPresent(renderer);
}
KW_Quit(gui);
KW_ReleaseSurface(driver, set);
return 0;
}
|
3509b10e9f95f349d2b0f05532edd5c5363efb65
|
[
"C",
"CMake"
] | 11
|
C
|
ewmailing/KiWi
|
67afc455cdd1f1ecfd80d2c50bb864a36f2a6138
|
654d6abb6bb25201c14368110af71b74dae14d7b
|
refs/heads/master
|
<repo_name>grootstebozewolf/PandenPerBouwjaar<file_sep>/Kadaster/MainWindow.xaml.cs
using System.Windows;
using ESRI.ArcGIS.Client;
using System.Diagnostics;
using ESRI.ArcGIS.Client.Symbols;
using System.Windows.Media;
namespace Kadaster
{
public partial class MainWindow : Window
{
private DynamicMapServiceLayer bagLayer;
private LayerDrawingOptionsCollection layerDrawingOptionsCollection;
public MainWindow()
{
// License setting and ArcGIS Runtime initialization is done in Application.xaml.cs.
InitializeComponent();
var dynamicLayerInfoCollection = new DynamicLayerInfoCollection();
var dynamicLayerInfo = new DynamicLayerInfo();
dynamicLayerInfoCollection.Add(dynamicLayerInfo);
var layerDrawingOptionsCollection = new LayerDrawingOptionsCollection();
var defaultDrawingOptions = new LayerDrawingOptions();
var simpleRender = new SimpleRenderer();
var classBreaksRenderer = new ClassBreaksRenderer { Field="Bouwjaar" };
var defaultFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 199, 147, 118)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 227, 201, 187)) };
var brownFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 184, 146, 133)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 148, 102, 86)) };
var brownClassBreakInfo = new ClassBreakInfo { MinimumValue = double.MinValue, MaximumValue = 1800, Symbol = brownFillSymbol, Label="Voor 1800" };
var darkbrownFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 106, 73, 62)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 169, 142, 126)) };
var darkbrownClassBreakInfo = new ClassBreakInfo { MinimumValue = 1800, MaximumValue = 1950, Symbol = darkbrownFillSymbol, Label = "1800-1900" };
var graybrownFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 109, 89, 84)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 170, 150, 145)) };
var graybrownClassBreakInfo = new ClassBreakInfo { MinimumValue = 1950, MaximumValue = 1970, Symbol = graybrownFillSymbol, Label = "1950-1970" };
var grayFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 117, 117, 117)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 173, 173, 173)) };
var grayClassBreakInfo = new ClassBreakInfo { MinimumValue = 1970, MaximumValue = 1990, Symbol = grayFillSymbol, Label = "1970-1990" };
var darkgrayFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 80, 80, 80)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 117, 117, 117)) };
var darkgrayClassBreakInfo = new ClassBreakInfo { MinimumValue = 1990, MaximumValue = 2005, Symbol = darkgrayFillSymbol, Label = "1990-2005" };
var blackFillSymbol = new SimpleFillSymbol { BorderBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 0, 0, 0)), Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 80, 80, 80)) };
var blackClassBreakInfo = new ClassBreakInfo { MinimumValue = 2005, MaximumValue = 2013, Symbol = blackFillSymbol, Label = "2005-2013" };
simpleRender.Symbol = defaultFillSymbol;
//classBreaksRenderer.Classes.Add(brownClassBreakInfo);
classBreaksRenderer.Classes.Add(darkbrownClassBreakInfo);
classBreaksRenderer.Classes.Add(graybrownClassBreakInfo);
classBreaksRenderer.Classes.Add(grayClassBreakInfo);
classBreaksRenderer.Classes.Add(darkgrayClassBreakInfo);
classBreaksRenderer.Classes.Add(blackClassBreakInfo);
// classBreaksRenderer.DefaultSymbol = defaultFillSymbol;
defaultDrawingOptions.LayerID = 4;
defaultDrawingOptions.Renderer = classBreaksRenderer;
layerDrawingOptionsCollection.Add(defaultDrawingOptions);
bagLayer = new ArcGISDynamicMapServiceLayer { Url = @"http://services.arcgisonline.nl/arcgis/rest/services/Basisregistraties/BAG/MapServer", VisibleLayers = new int[] { 4 }, LayerDrawingOptions = layerDrawingOptionsCollection, ShowLegend=true, ID = "BAG" };
_map.Layers.Add(bagLayer);
bagLayer.Initialized += new System.EventHandler<System.EventArgs>(bagLayer_Initialized);
}
void bagLayer_Initialized(object sender, System.EventArgs e)
{
Debug.WriteLine("Bag Layer Initialized");
}
private void _map_ExtentChanged(object sender, ExtentEventArgs e)
{
Debug.WriteLine(_map.Extent);
}
}
}
|
5bd378f94a9f31405e20426f44ae60453070dcef
|
[
"C#"
] | 1
|
C#
|
grootstebozewolf/PandenPerBouwjaar
|
336f4980e4004f69fb1b29e95ff8f25afb0d89d6
|
0655c0895b0f1afd424f14f3ae4addc47504b649
|
refs/heads/master
|
<repo_name>zgover/connected-application<file_sep>/ConnectedApplication/app/src/main/java/com/example/zachary/connectedapplication/NetworkConnectivity.java
// <NAME>
// JAV1 - 1608
// NetworkConnectivity
package com.example.zachary.connectedapplication;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkConnectivity {
/**
* MARK: Static Methods
*/
public static boolean online(Context context) {
ConnectivityManager man = (ConnectivityManager) context.getSystemService(
context.CONNECTIVITY_SERVICE
);
NetworkInfo info = man.getActiveNetworkInfo();
// Check if we're connected
if (info != null && info.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
|
1583bd3af6117210da5b600e7f172f291989a1ca
|
[
"Java"
] | 1
|
Java
|
zgover/connected-application
|
dd9cda336e8961cc7b87ea86ba3b047ab9045c95
|
94efd32ec8eb4b01de762bcd386203a178c34b2e
|
refs/heads/master
|
<repo_name>d-german/PolymorphJCCCDemo<file_sep>/UniversalHealthcareViewer/Program.cs
using System;
namespace UniversalHealthcareViewer
{
class Program
{
[STAThread]
static void Main(string[] args)
{
const int documentId = 0;
var viewer = new UniversalViewer(DataSourceFactory.BuildDataSource(documentId));
viewer.DrawPage(1);
}
}
}
<file_sep>/UniversalHealthcareViewer/UniversalViewer.cs
using System;
namespace UniversalHealthcareViewer
{
public class UniversalViewer
{
//DIP
public AbstractDataSource DataSource { get; set; }
public UniversalViewer(AbstractDataSource dataSource)
{
this.DataSource = dataSource;
}
//OCP,LSP,DIP
public void DrawPage(int pageNum)
{
var image = DataSource.GetPage(pageNum);
Console.WriteLine($"Using {DataSource.ToString()} to draw a page with size {image.Size}");
}
}
}
<file_sep>/UniversalHealthcareViewer/DataSourceFactory.cs
namespace UniversalHealthcareViewer
{
public class DataSourceFactory
{
public static AbstractDataSource BuildDataSource(int documentId)
{
AbstractDataSource dataSource = null;
switch (documentId)
{
case 0:
dataSource = new LocalDataSource();
break;
case 1:
dataSource = new RemoteDataSource();
break;
}
return dataSource;
}
}
}
<file_sep>/UniversalHealthcareViewer/AbstractDataSource.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace UniversalHealthcareViewer
{
public abstract class AbstractDataSource
{
//DIP
public string DocumentId { get; set; }
public DateTime CreationDate { get; set; }
public abstract Image GetPage(int pageNum);
public virtual int GetPageCount()
{
return 1;
}
}
public class LocalDataSource : AbstractDataSource
{
public override Image GetPage(int pageNum)
{
string filename;
using (var openFileDialog = new OpenFileDialog())
{
filename = string.Empty;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
filename = openFileDialog.FileName;
}
}
return Image.FromFile(filename);
}
}
public class RemoteDataSource : AbstractDataSource
{
public override Image GetPage(int pageNum)
{
return Image.FromFile($"http://imageService/{pageNum}");
}
}
}
|
4c186436272f9e5fa8f9c0f1872345aad2c503dd
|
[
"C#"
] | 4
|
C#
|
d-german/PolymorphJCCCDemo
|
5a5722c7ff273d0c645cd3f957c7c4d2988db105
|
922cc1d2c813c23a81f5f3c2a0a9fa563c3797dc
|
refs/heads/master
|
<file_sep>#!/bin/bash
if [[ -z "$branch" ]]
echo "\$branch must be set to the current branch"
exit
fi
echo .
echo "Are you sure? This will WIPE your current local commits,"
read -p "and replace them with whatever is at ORIGIN! ... "
# back up to the stash in case of accident
git stash save $branch"_backup_"$(date +"%F_%H-%M-%S")
# Disabled branch backup as it results in a lot of unused branches
#git branch $branch"_backup_"$(date +"%F_%H-%M-%S")
git remote update
git fetch
echo .
echo "type it yourself:"
echo
echo "git reset --hard origin/$branch"
echo .
#git reset --hard origin/$branch
<file_sep>#!/bin/bash
# Convenience script to do a "git --fetch" before pushing
# in order to avoid conflicts
if [[ -z "$branch" ]]
echo "\$branch must be set to the current branch"
exit
fi
if [[ "$branch" == "master" ]]
then
echo "I'm not trusted to push to master, do it manually please"
exit
fi
git fetch --all
echo .
echo "git push origin $branch"
echo .
git push origin $branch
<file_sep>#!/bin/bash
currentdir=$(pwd)
# Setup for microlith
scriptdir=$(basedir $0 2>/dev/null || dirname $0 2>/dev/null)
dirfile="$scriptdir/company/microlith-dir"
fixdir=$( cat $dirfile | grep -v '^#' )
if [[ "$currentdir" == "$fixdir" ]]
then
################# MICROLITH
echo "Microlith diff"
microlith-diff.sh $@
else
################# NORMAL
# Display a visual divider
perl -le'$tr = ("=") x 120; print $tr for 1..2'
# Diff with useful options
git diff --no-prefix --relative --color --histogram $@
echo
git status
fi
<file_sep>#!/bin/bash
# change the author of a ramge of commits
# by default every commit on a branch changes
# you can choose the start commit,
# but the end commit will always be HEAD
# for more control, see https://stackoverflow.com/a/15265846/137948
# Change all commits on the branch
#git filter-branch --commit-filter 'if [ "$GIT_AUTHOR_NAME" = "<NAME>" ]; then
# export GIT_AUTHOR_NAME="<NAME>";
# export GIT_AUTHOR_EMAIL=<EMAIL>;
# export GIT_COMMITTER_NAME="<NAME>";
# export GIT_COMMITTER_EMAIL=<EMAIL>;
#fi;
#git commit-tree "$@"'
# Change only commits in a range.
# Warning: Any commits after this range will also change their SHA1
#commita=$1
#commitb=$2
git filter-branch --force --env-filter "
if git rev-list $1..$2 | grep \$GIT_COMMIT; then
export GIT_AUTHOR_NAME=\"<NAME>\";
export GIT_AUTHOR_EMAIL=<EMAIL>;
export GIT_COMMITTER_NAME=\"<NAME>\";
export GIT_COMMITTER_EMAIL=<EMAIL>;
fi" -- ^$1 HEAD
<file_sep>#!/bin/bash
# Resize images in bulk
# Requires 'convert', part of ImageMagick 6.6.2-6 2012-08-17 Q16 http://www.imagemagick.org
SIZE=$1
EXTENSION=$2
#for i in *.jpg; do convert $i -resize '10%' $(basename $i .jpg).jpg; done
for i in *.$EXTENSION; do convert $i -resize $SIZE $(basename $i .$EXTENSION).jpg; done
<file_sep>#!/bin/bash
set -euo pipefail
# Modify the checkout of a monolithic git repo,
# making it easier to work with.
currentdir=$(pwd)
scriptdir=$(basedir $0 2>/dev/null || dirname $0 2>/dev/null)
datafile="$scriptdir/company/microlith-data"
dirfile="$scriptdir/company/microlith-dir"
fixdir=$( cat $dirfile | grep -v '^#' )
backupdir="/tmp/microlith-backup"
mkdir -p "$backupdir"
# SETUP
if [[ "$currentdir" != "$fixdir" ]]
then
echo "Only permitted in dir: $fixdir"
exit 1
fi
# MAIN
echo "Size:" $(du -hs .)
# Remove unwanted directories
for thisdir in $(cat $datafile)
do
echo "removing: $thisdir"
rm -rf "./$thisdir"
done
# Move .git out of the way
#mv .git ../.git-for-microlith
echo "Size:" $(du -hs .)
echo "Microlith started"
<file_sep>#!/bin/bash
set -euo pipefail
# Revert modifications made to the checkout of a monolithic git repo,
# restoring it ready for a branch to be pushed upstream.
currentdir=$(pwd)
scriptdir=$(basedir $0 2>/dev/null || dirname $0 2>/dev/null)
datafile="$scriptdir/company/microlith-data"
dirfile="$scriptdir/company/microlith-dir"
fixdir=$( cat $dirfile | grep -v '^#' )
backupdir="/tmp/microlith-backup"
# SETUP
if [[ "$currentdir" != "$fixdir" ]]
then
echo "Only permitted in dir: $fixdir"
exit 1
fi
echo "Size:" $(du -hs .)
# Restore the missing directories
for thisdir in $(cat $datafile)
do
echo "restoring: $thisdir"
git checkout "$thisdir"
done
# Put .git back
#mv ../.git-for-microlith ./.git
echo "Size:" $(du -hs .)
echo "Microlith finished"
<file_sep>#!/bin/bash
# strict mode
set -euo pipefail
IFS=$'\n\t'
PACKAGES="
ruby
perl
python3
nginx
youtube-dl
ffmpeg
"
echo "Packages:" $PACKAGES
read -r -p "Are you sure you want to install? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
echo "Very well, continuing box initialisation..."
;;
*)
echo "Aborted."
exit 1
;;
esac
sleep 5
set -vx
for package in $PACKAGES; do
sudo apt -y install $package
done
<file_sep>#!/bin/bash
DDIR="$HOME/a/m/"
transmission-cli --download-dir "$DDIR" $@
<file_sep># Combine all standard (STDOUT) and error (STDERR) streams into one output stream
# so that all output can be piped into a single file
# Required for applications like 'time'
$@ 2>&1
<file_sep>#!/bin/bash
# Diff the current working directory against the branch it was cut from
# i.e. show all the changes on this branch
if [[ -z "$branch" ]]
echo "\$branch must be set to the current branch"
exit
fi
UP=$1
if [[ -z "$UP" ]]
then
UP="master"
fi
git diff $(git merge-base $UP $branch)
<file_sep>#!/bin/bash
perl -le'foreach my $x (0..1000000) { print $x; }' > numbers.txt
head -10000 numbers.txt > 10k
# Save to an audio file on Mac (10k = 2 hours)
say --input-file=10k --file-format=mp4f --output-file=numbers.mp4 --rate=500 --progress
<file_sep>#!/bin/bash
for k in $(seq 1 30); do echo; done
<file_sep>#!/bin/bash
# Automate autosquashing for a 'fixup' commit
#
# See git man pages for commit and rebase for details
#
# Update: This script could be replaced with the built-in command 'git commit --amend'
echo
echo "use this instead: git commit --amend"
echo
exit
############################################
file=$1
if [[ -z "$file" ]]
then
echo "usage: $0 [file]"
exit
fi
echo
echo " Fixing up file $file..."
echo
read -p "Are you sure the last commit to this file has not been pushed? [type Enter to continue or Ctrl-C to abort] "
# get the last commit message for the file
last_commit=$(git log -n1 -- $file | head -5 | tail -1 | sed 's/^\s\+//')
# commit the fixup
git commit -m"fixup! $last_commit" $file
if [[ -n $(echo $(git log --oneline --stat -n2) | LAST=$last_commit perl -lne'$last = $ENV{LAST}; m{fixup! $LAST.+$LAST} && print 1') ]]
then
# The last two commit messages are the fixup and the fixee
# Rebase and squash them automatically
echo
echo "Auto-auto-squashing, please wait..."
echo
sleep 1;
# --autosquash only works with --interactive
# ...so tell vim to save and close immediately
GIT_EDITOR="vim -c ':wq'" git rebase --no-verify --interactive --autosquash HEAD^^
echo
echo "I have committed, rebased and auto-squashed that for you..."
echo " Would you like fries with that?"
echo
else
# It's more complicated...
# Not implemented
#LAST_20=$(echo $(git log --oneline --stat -n20))
#UP_TO_FIXEE=$(echo $LAST_20 | LAST=$last_commit sed 's/')
#if [[ -z $(echo $(git log --oneline --stat -n20) | LAST=$last_commit perl -lne'$last = $ENV{LAST}; m{fixup! $LAST.+$LAST} && print 1') ]]
#then
# # The fixee commit has not been pushed
# # Rebase and squash them
#fi
# Give manual instructions
echo
echo Now...
echo
echo "git rebase -i --autosquash HEAD^^"
echo
fi
<file_sep>#!/bin/bash
# Display all git branches, sorted by last commit date
# and showing the committer's name
REMOTE="${1:-}"
for k in `git branch $REMOTE | grep -v 'no branch' | perl -pe s/^..// | sed 's/.\+ -> //'`; do echo -e `git show --pretty=format:"%Cgreen%ci %Cblue%cr%Creset (%cn)" $k|head -n 1`\\t$k; done | sort
<file_sep>#!/bin/bash
# Convenience script for "git pull --rebase --ff"
if [[ -z "$branch" ]]
echo "\$branch must be set to the current branch"
exit
fi
git fetch --all
# this results in an extra commit
#git pull --ff origin $branch
# this doesn't
#git rebase origin/$branch
# but isn't this better? (and easier to remember)
git pull --ff --rebase origin $branch
<file_sep>#!/bin/bash
set -vx
rbt post $@ `git merge-base master HEAD` `git rev-parse HEAD`
<file_sep>#!/bin/bash
# Convenience script
git stash list|head
<file_sep>#!/bin/bash
# Create a tunnel from localhost:1111 --> $JUMP_HOST --> $APP_SERVER --> $DATABASE_SERVER:3306
# To use it: mysql --host=127.0.0.1 --port=1111 --protocol=tcp
ssh -o TCPKeepAlive=yes -J $USER@$JUMP_HOST $USER@$APP_SERVER -L 1111:$DATABASE_SERVER:3306 -nNT -vvv
<file_sep>#!/bin/bash
# Summarise the sizes of subdirectories
DIR=${1:-.}
du -hs "$DIR"
echo -----------------------------------
du -hs "$DIR"/* | sort -h
<file_sep>#!/bin/bash
# Pretty-prints a JSON-format log file
#export COMMAND='json_pp' # From Perl JSON module. Does not sort keys
export COMMAND='python -mjson.tool' # Sorts keys
perl -lne'$q = "\047"; s/$q/$q\\$q$q/g; $tr = ("=") x 120; print $tr; $s = "echo $q$_$q | $ENV{COMMAND}"; print `$s`' $@
# Explanation:
# * define $q so we can use single quote characters inside the Perl single-quoted command.
# * replace any single quotes in the input data with '\'', which ends the string, escapes a single quote, and begins the string again
# * print a divider
# * compose the command to pretty-print the input data
# * execute the command and print the result
<file_sep>#!/bin/bash
vim $(f $@)
<file_sep>#!/bin/bash
# Example of arrays in Bash
# NICK:IP:TYPE:TIER
NODES=(
"s:1.2.3.4:STAGING:dev"
"n1:5.6.7.8:LIVE:production"
)
for item in "${NODES[@]}" ; do
ORIGINALIFS=$IFS
IFS=':' read -a myarray <<< "$item"
NODE=${myarray[0]}
IP=${myarray[1]}
NODE_TYPE=${myarray[2]}
NODE_TIER=${myarray[3]}
IFS=$ORIGINALIFS
LOWERCASE_TIER=`echo $NODE_TIER | tr '[:upper:]' '[:lower:]'`
# Show variables
echo "node='$NODE', ip='$IP', node_type='$NODE_TYPE', node_tier='$NODE_TIER', lower_tier='$LOWERCASE_TIER'"
done
<file_sep>#!/bin/bash
# Before creating a branch, make sure it hasn't already been created.
#
# Then display the command to create it.
# Artefact ID (AKA issue/ticket)
ART=$1
function usage() {
echo "usage: svnbranch [ART]"
exit 1
}
if [[ -z "$ART" ]]
then
usage
fi
if [[ -z "$SVN" ]]
then
echo "\$SVN must be defined as the path to the subversion repo"
exit
fi
# Quick reference
echo "If you know the branch doesn't exist yet:"
echo "svn copy -m \"[$ART] - Branching trunk\" $SVN/trunk $SVN/branches/$ART"
echo
# Check if branch already exists
echo "Checking if branch already exists..."
echo "svn ls $SVN/branches/ --verbose |grep $ART"
EXISTING_BRANCH=$(svn ls $SVN/branches/ --verbose |grep $ART)
echo
if [[ -n $EXISTING_BRANCH ]]
then
echo "WARNING: Branch $ART already exists, cannot create it:"
echo $EXISTING_BRANCH
exit 1
else
echo "Branch not found, you may create it:"
echo
echo "svn copy -m \"[$ART] - Branching trunk\" $SVN/trunk $SVN/branches/$ART"
#echo "svn checkout $SVN/branches/$ART"
echo
echo "Then type:"
echo "svncheckout $ART foo"
fi
<file_sep>#!/bin/bash
# change the date for a specific commit
usage() {
echo "Usage: $0 [number of commits before head] [date, e.g. \"Thu Oct 04 09:03:10 2018 -0000\"]"
exit
}
N="$1"
if [[ -z "$N" ]]
then
usage
fi
export TARGET_COMMIT=$(git show HEAD~$N --format=%H --no-notes --no-patch)
echo TARGET_COMMIT = $TARGET_COMMIT
D="$2"
if [[ -z "$D" ]]
then
usage
fi
export NEW_DATE="$D"
echo NEW_DATE = "$NEW_DATE"
git filter-branch --force --env-filter \
'#echo GIT_COMMIT = "$GIT_COMMIT"
#echo TARGET_COMMIT = "$TARGET_COMMIT"
if [[ "$GIT_COMMIT" == "$TARGET_COMMIT" ]]
then
export GIT_AUTHOR_DATE="$NEW_DATE"
export GIT_COMMITTER_DATE="$NEW_DATE"
fi' $TARGET_COMMIT^1..HEAD
<file_sep>#!/bin/bash
# for ack config, see ~/.ackrc
ack "$@"
exit $?;
######### ag misses stuff... by design
ag "$@"
exit $?
######################################
echo "use ack and .ackrc instead"
exit
######################################
TERM="$1"
DIR=${2:-.}
set -x
grep -r --color --text "$TERM" $DIR \
| egrep --text -v 'blib|\.git' \
| grep --color --text "$TERM"
#| egrep --text -v '\.js|\.css' \
#| egrep --text -v '/local/' \
<file_sep>#!/bin/bash
docker ps $@ | cut -c-$(tput cols)
<file_sep>#!/bin/bash
# Disable other git hooks before rebasing (if doing a reword),
# as they cause "error: Error building trees".
# may be caused by those hooks performing a fetch
# Disable Ctrl-C, because interrupting this script could
# accidentally leave the git hooks disabled
trap '' 2
# Disable git hooks
echo "disabling git hooks"
mv .git/hooks/post-checkout{,.disabled}
mv .git/hooks/pre-commit{,.disabled}
# Do the rebase
git rebase $@
# Re-enable git hooks
echo "re-enabling git hooks"
mv .git/hooks/post-checkout.disabled .git/hooks/post-checkout
mv .git/hooks/pre-commit.disabled .git/hooks/pre-commit
echo
echo "done"
# Re-enable Ctrl-C
trap 2
<file_sep>#!/bin/bash
# Short version of 'svnbranch' and 'svncheckout' scripts
# if you know what you're doing.
# Artefact ID (AKA issue/ticket)
ART=$1
NAME=$2
if [[ -z "$ART" || -z "$NAME" ]]
then
echo "usage: svnbranchandcheckout branch_name your_short_name"
exit 1;
fi
if [[ -z "$SVN" ]]
then
echo "\$SVN must be defined as the path to the subversion repo"
exit
fi
# Check if branch already exists
echo "Checking if branch already exists..."
echo "svn ls $SVN/branches/ --verbose |grep $ART"
EXISTING_BRANCH=$(svn ls $SVN/branches/ --verbose |grep $ART)
echo
if [[ -n $EXISTING_BRANCH ]]
then
echo "WARNING: Branch $ART already exists, cannot create it."
echo $EXISTING_BRANCH
exit 1
else
# Create branch
echo "Branch not found, creating it..."
echo
echo "svn copy -m \"[$ART] - Branching trunk\" $SVN/trunk $SVN/branches/$ART"
svn copy -m "[$ART] - Branching trunk" $SVN/trunk $SVN/branches/$ART
echo
fi
# Check out branch
if [[ ! -d "_template" ]]
then
echo "Directory _template must exist."
echo "Suggestion for creating:"
echo " cp trunk _template"
echo " find trunk/ -type f |grep -v .svn|xargs rm"
exit
fi
NOW=$(date +'%Y%M%d-%H%M%S')
cd $HOME/dev
rm -rf _random
time cp -rp _template/ _random
mv _random/ $ART
ln -s $ART $NAME
cd $NAME
time svn switch $SVN/branches/$ART
echo
echo "If this has worked, you should see a lot of 'Restored file xxxxx' lines above"
echo "(above the list of files which were changed in this branch)"
echo
<file_sep>#!/bin/bash
# Remove cruft:
#
# 2023-02-11 11:10:48 :: 5681 :: 5681 :: ......
# 2023-02-09 08:16:29 :: 7643 :: ........
# 2023-02-09 08:16:32 :: 13898 :: [[andritzcomp::1675930503]] :: REF[[749584602-4587]] :: RAW[[749584602 :: 6" Horizontal Boring Mill Operator]] ........
# Thu Feb 9 08:16:32 2023 :: 13898 :: .......
# [RULE ID FOUND: CPW6LNB0B51H4JQTMEI9AHNACCGHMA] ......
# 764750402-4587: Fri Feb 10 08:17:52 2023: .......
# YES
# ...truncate...
# [blank lines]
echo "-------------------------------------------------------------------------------------------------------------------------------------------------"
perl -plne's/^[\d\-]+\s[\d:]+\s::\s\d+\s::\s\d+\s::\s//' \
\
| perl -plne's/^[\d\-]+\s[\d:]+\s::\s\d+\s::\s//' \
\
| perl -plne's/\[\[.+\]\]\s//' \
\
| perl -plne's/^\S\S\S\s\S\S\S\s\s?\d+\s[\d:]+\s\d{4}\s::\s\d+\s::\s//' \
\
| perl -plne's/^\[RULE ID FOUND: \S+\]\s//' \
\
| perl -plne's/^\d+-\d+:\s\S\S\S\s\S\S\S\s\s?\d+\s[\d:]+\s\d{4}:\s//' \
\
| sed '/^YES$/d' \
\
| sed '/^$/d' \
\
| perl -plne's/^(.{180}).+/$1... (truncated)/' \
\
| /usr/local/bin/cat
# TODO
# perl -lne'if (/^Ref/) { $ref++ } elsif ($ref && ! /^Ref/) { print "...(+ $ref more Ref lines)"; $ref = 0 }' ; echo; done
<file_sep>#!/bin/bash
# Shortcut for checking if a list of perl files compile
for k in $@
do
perl -Ilib -It/lib -c $k
done
<file_sep>#!/bin/bash
head $@
tail $@
<file_sep>#!/bin/bash
# Convenience script for "git rebase" command
# Calls another convenience script "gitrebase"
NUMBER=$1
if [[ -z $NUMBER ]]
then
echo "usage: rb [number of revisions]"
exit 1
fi
gitrebase --autosquash -i HEAD~$NUMBER
<file_sep>#!/bin/bash
# https://gitlab.com/snippets/1927120
set -eu -o pipefail
if (( $# )) ; then
cat << HELP
Looks for inactive snaps and removes them.
There are no command line options.
You will be asked to confirm before removal.
HELP
echo -n 'Requires curl: ' ; type curl
echo -n 'Requires jq: ' ; type jq
exit 1
fi
BOLD=$'\e[1m'
UNBOLD=$'\e[22m'
function list-snaps {
# According to https://github.com/snapcore/snapd/wiki/REST-API
curl --silent --show-error \
--get --data select=all \
--unix-socket /run/snapd.socket \
http://localhost/v2/snaps
}
function filter-disabled {
jq --raw-output '
.result[] |
select(.status != "active") |
"snap remove --revision=\(.revision|@sh) \(.name|@sh)"
'
}
remove_cmds=$(list-snaps | filter-disabled)
if [ -z "${remove_cmds}" ] ; then
echo No inactive snaps found.
exit 0
fi
echo "${BOLD}To remove:${UNBOLD}"
# -v screens out control characters that might obscure what we're about to sudo
cat -nv <<< "${remove_cmds}"
echo
read -rp "${BOLD}Run these commands with sudo? [yes/no]${UNBOLD} "
case "$REPLY" in
[Yy]*) ;;
*)
echo Cancelling.
exit 1
;;
esac
exec sudo -- bash -es <<< "${remove_cmds}"
<file_sep>#!/bin/bash
# Find files
TERM="$1"
DIR=${2:-.}
set -x
find $DIR -name "$TERM" | egrep -v 'blib|.git'
<file_sep>#!/bin/bash
# Quickly check the syntax of perl modules you've just modified
BRANCH="$1"
for module in `git diff $BRANCH --stat=200,200|grep '.pm '|perl -lane'print$F[0]'|tac`
do
perl -Mdiagnostics -c -I lib -I t/lib $module
done
<file_sep>#!/usr/bin/env python3
# Encrypt a password
# Based on https://stackoverflow.com/a/17992126/117471
import sys
from getpass import getpass
from passlib.hash import sha512_crypt
passwd = input() if not sys.stdin.isatty() else getpass()
#print(sha512_crypt.encrypt(passwd))
print(sha512_crypt.hash(passwd))
<file_sep>#!/bin/bash
# Choose between helper scripts to open text files...
#
# Depends on other helper scripts "vimline" and "vimmod"
if [[ "$2" == "line" ]]
then
# use script for copy-and-pasted filename and line number from error messages
vimline $@
############################################################
elif [[ "$1" =~ "::" ]]
then
# use script to translate module name into filename
vimmod $@
############################################################
else
# assume it's just a filename and use normal vim
vim $@
fi
<file_sep>#!/bin/bash
echo 'unset PERL5LIB; unset PERL_LOCAL_LIB_ROOT; unset PERL_MB_OPT; unset PERL_MM_OPT; eval $(perl -I $HOME/dev/local/lib/perl5 -Mlocal::lib=$HOME/dev/local)'
<file_sep>#!/bin/bash
# Setup ansible host and use it to provision server on DigitalOcean
#
# https://www.digitalocean.com/community/tutorials/how-to-use-ansible-to-automate-initial-server-setup-on-ubuntu-20-04
# https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-ansible-on-ubuntu-20-04
# https://docs.digitalocean.com/reference/doctl/how-to/install/
HOST_IP=${1:-''}
if [[ "$HOST_IP" == "" ]]
then
echo "usage: $0 [Host IP]"
exit 1
fi
sudo apt install -y ansible
...todo...define IP...
echo '[servers] server1 ansible_host=172.16.31.10' \
>> /etc/ansible/hosts
<file_sep>#!/bin/bash
set -euo pipefail
# Diff the microlith, taking account of modifications
currentdir=$(pwd)
scriptdir=$(basedir $0 2>/dev/null || dirname $0 2>/dev/null)
datafile="$scriptdir/company/microlith-data"
dirfile="$scriptdir/company/microlith-dir"
fixdir=$( cat $dirfile | grep -v '^#' )
# SETUP
if [[ "$currentdir" != "$fixdir" ]]
then
echo "Only permitted in dir: $fixdir"
exit 1
fi
if [[ ! -e "$datafile" ]]
then
echo "missing $datafile"
exit 1
fi
# MAIN
# Display a visual divider
perl -le'$tr = ("=") x 120; print $tr for 1..2'
# Build exclusions command
git_exclude=""
git_exclude=":(exclude,top)adcourier.broadbean" # $current_job
for thisdir in $(cat $datafile)
do
git_exclude="$git_exclude :(exclude,top)$thisdir"
done
# Temporarily restore .git
#mv ../.git-for-microlith .git
# Perform diff
git diff --relative --color --histogram $@ -- :/ $git_exclude
#git diff --relative --color --histogram --diff-filter=D $@
echo
# More useful output
git status $@ -- :/ $git_exclude
# Move .git out of the way again
#mv .git ../.git-for-microlith
<file_sep>#!/bin/bash
# https://stackoverflow.com/a/54851251
BASE_DIR="$1"
if [ -z "$BASE_DIR" ]
then
echo "usage: $0 [base_dir]"
exit 1
fi
# Strict mode
set -euo pipefail
function do_sdk {
cd $BASE_DIR
mkdir android-sdk
cd android-sdk
wget https://dl.google.com/android/repository/commandlinetools-linux-6200805_latest.zip
unzip commandlinetools-linux-*_latest.zip
yes | ./tools/bin/sdkmanager --sdk_root=$(pwd) "build-tools;28.0.3" "emulator" "platform-tools" "platforms;android-29" "tools" "cmdline-tools;latest"
}
# Doesn't seem to work
function do_flutter {
cd $BASE_DIR
wget -nc https://storage.googleapis.com/flutter_infra/releases/stable/linux/flutter_linux_v1.12.13+hotfix.8-stable.tar.xz
tar xvf flutter_linux_v1.12.13+hotfix.8-stable.tar.xz
}
function do_flutter2 {
sudo snap install flutter --classic
flutter # updates itself when first run
yes | flutter doctor --android-licences
}
function do_env {
export ANDROID_SDK=$BASE_DIR/android-sdk
export ANDROID_PATH=$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools
export FLUTTER=$BASE_DIR/flutter/bin
export PATH=$PATH:$ANDROID_PATH:$FLUTTER
# source ~/.bashrc
}
# Start
do_sdk
#do_flutter
do_flutter2
do_env
<file_sep>#!/bin/bash
# Take a copy & pasted filename and line number from a Perl error message,
# e.g. "Error occurred at /path/to/some/Module.pm line 82."
# ...and open the file at that line
FILENAME=$1
LINE_NUMBER_WITH_DOT=$3
if [[ -z "$LINE_NUMBER_WITH_DOT" ]]
then
vim $FILENAME
else
LINE_NUMBER=$(echo $LINE_NUMBER_WITH_DOT | sed 's/\.$//')
echo vim $FILENAME +$LINE_NUMBER
vim $FILENAME +$LINE_NUMBER
fi
<file_sep>#!/bin/bash
# Print out the lines from a file, in a random order
FILE=$1
if [[ -z $FILE ]]
then
echo "usage: shuffle [filename]"
exit 1
fi
for i in `cat $FILE`; do echo "$RANDOM $i"; done | sort | sed -r 's/^[0-9]+ //'
<file_sep>#!/bin/bash
zcat $1 | head $2 $3 $4 $5 $6 $7
<file_sep>#!/bin/bash
# Convenience script
echo "Type this:"
echo "git checkout -b $1"
echo "git push -u origin $1"
<file_sep>#!/bin/sh
# Show git tags
git for-each-ref --format="%(taggerdate): [%(refname)] \"%(contents:subject)\" (%(*authorname))" --sort=-taggerdate --count=1000000 refs/tags | sed "s/refs\/tags\///" | tac
<file_sep>#!/bin/bash
blank
blank
blank
<file_sep>#!/bin/bash
vim $(a $@ | cut -d: -f1 | uniq)
<file_sep>#!/bin/bash
zcat $1 | head $2 $3 $4 $5 $6 $7
zcat $1 | tail $2 $3 $4 $5 $6 $7
<file_sep>#!/bin/bash
# Helper script to remember this company's subversion message format
if [[ -z "$ART" ]]
then
echo "please set:"
echo "export ART=artf1234567"
exit 1;
fi
echo "svn commit -m '[$ART] - foo' Filename.pm"
echo
<file_sep>#!/bin/bash
# Catch Ctrl-C and don't do anything (i.e. disable it)
trap '' 2
echo "This is a test. Hit [Ctrl+C] to test it..."
sleep 20
trap 2
<file_sep>#!/bin/bash
# Which stories have been merged since the current branch was cut from master?
if [[ -z "$branch" ]]
then
branch=$1
fi
if [[ -z "$branch" ]]
then
echo "unknown branch"
echo "usage: merged_branches master"
exit 1
fi
git log --oneline $(git merge-base master $branch)..HEAD |grep -i ' Merge'
<file_sep>#!/bin/bash
cat <<EOF | grep -v '#'
## Joplin cheat sheet
joplin # opens UI
#joplin help
joplin config
joplin config -v
#joplin help config
joplin sync
joplin status
joplin ls /
joplin ls -l /
joplin ls -l -s updated_time /
joplin use "Notebook name"
joplin use note_id
joplin ls
joplin ls -l
joplin ls -l -s title
joplin ls -l -s title -r
joplin ls -l -s updated_time
joplin ls -l -s created_time
joplin ls -n 3
joplin ls -t n
joplin ls -t t
joplin ls -t nt
joplin ls -f text
joplin ls -f json | jq .
joplin cat "Note name"
joplin cat note_id
joplin cat -v note_id
joplin tag list
joplin tag list -l
joplin tag list tag_name
joplin tag list -l tag_name
joplin tag add tag_name note_id
joplin tag remove tag_name note_id
joplin tag list tag_name
joplin tag list -l tag_name
joplin tag notetags note_id
#joplin help batch
#joplin help cat
#joplin help config
#joplin help cp
#joplin help done
#joplin help e2ee
#joplin help edit
#joplin help export
#joplin help geoloc
#joplin help import
#joplin help ls
#joplin help mkbook
#joplin help mknote
#joplin help mktodo
#joplin help mv
#joplin help ren
#joplin help rmbook
#joplin help rmnote
#joplin help server
#joplin help set
#joplin help status
#joplin help sync
#joplin help tag
#joplin help todo
#joplin help undone
#joplin help use
#joplin help version
EOF
<file_sep>#!/bin/bash
# Sort unique
sort | uniq -c | sort -h
<file_sep># linux-scripts
Scripts for productivity
An effort has been made to generalise the scripts so they work in different environments, not just for the company they were written.
Scripts which are not included, as they must be written from scratch for each company because they are completely environment-specific:
* *f* - find files in the checked-out source, excluding unwanted directories
* *a* - grep/ack for text in the checked-out source, excluding unwanted files and directories
* *sql* - connect to the local database
* *vimmod* - given a perl module name, translate it into a filename (depending on idiosyncrasies of the source tree) and open that file in vim
<file_sep>#!/bin/bash
# Find and apply a stash by name
TERM="$1"
if [[ -z "$TERM" ]]; then
echo "usage: gitapply [grep string]"
exit
fi
STASH=`git stash list | grep "$TERM" | cut -d: -f1`
if [[ -z "$STASH" ]]; then
echo "Could not find a stash containing the term '$TERM'"
exit
fi
git stash apply $STASH
<file_sep>#!/bin/bash
# Loop over lines, where the lines contain whitespace.
O=$IFS
IFS=$(echo -en "\n\b")
#for f in $(cat playlists.2); do echo "$f" | jq '.contents.singleColumnBrowseResultsRenderer.tabs[].tabRenderer.content.sectionListRenderer.contents[].musicCarouselShelfRenderer.contents[].musicTwoRowItemRenderer.title.runs[] | { name: .text, id: .navigationEndpoint.browseEndpoint.browseId }'; done; IFS=$O
<file_sep>#!/bin/bash
# Easily create an SSH tunnel from localhost --> $JUMP_HOST --> $APP_SERVER --> $DATABASE_SERVER
# Usage:
#
# $ tunnel_wizard
# Non-interactive usage:
#
# $ tunnel_wizard < tunnel_config_file
#
# ...where 'tunnel_config_file' contains for example:
#
# bastion.example.com
# app.example.com
# db.example.com
# 3306
# 7777
# bob
echo "==> SSH tunnel wizard"
read -p "First jump host: " jump_host
read -p " App host: " app_host
read -p " Database host: " db_host
read -p " Database port: " db_port
read -p " Local port: " local_port
read -p " Username: " username
command="ssh -o TCPKeepAlive=yes -J $username@$jump_host $username@$app_host -L $local_port:$db_host:$db_port -nNT"
echo
echo "SSH command:"
echo $command
echo
echo "To connect:"
echo
echo "MYSQL_PWD=<<PASSWORD>> mysql -A --protocol=tcp --host=127.0.0.1 --port=$local_port --user=<USERNAME> --database=<DATABASE_NAME>"
# Note: -A is the same as --no-auto-rehash, it means quicker startup at the expense of auto-completion of table names
echo "or"
echo "PGPASSWORD=<PASSWORD> psql --host localhost --port $local_port --username <USERNAME> --db <DATABASE_NAME>"
echo
echo "Starting tunnel... It will remain open while this process continues to run..."
# Run tunnel command
$($command)
<file_sep>#!/bin/bash
blank
blank
<file_sep>#!/bin/bash
# display a visual marker similar to https://github.com/klange/nyancat
blank
cat `dirname $0`/ansi-art/camel
blank
<file_sep>#!/bin/bash
# Display a code diff in vim, for syntax highlighting
# Also run "svn status" afterwards
DIFF=$(svn diff $@)
if [[ -n "$DIFF" ]]
then
# There are modifications
# -x -p = show function name in diff output
# -x -u = unified diff output
svn diff -x -p $@ | vi -R -
else
echo "No modifications"
fi
# Also display any new files
echo
echo "svn status"
svn status
<file_sep>#!/bin/bash
# Create scrolling text gifs for Slack
# Example usage:
# gif.sh -c white -o onoff.gif 'Have you tried turning it off and on again?'
# Prerequisites:
# * imagemagick brew install imagemagick
# * gifsicle brew install gifsicle
# * 'Arial Black.ttf' font installed
# * Mac OSX
# Adapted from https://gist.github.com/jmhobbs/b6ba8f5d1f816506e5b671c1bd89c723
# Use https://ezgif.com/ to resize gifs to under 128Kb
# so they can be used as emojis in slack
set -euo pipefail
IFS=$'\n\t'
# uncomment to debug:
#set -vx
#contains () {
# local e
# for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
# return 1
#}
contains () {
local e
for e in "${@:2}"
do
if [ "$e" == "$1" ] ; then
return 1
fi
done
return 0
}
usage () {
if [ "$1" != "" ]; then
echo -e "Error: $1\n" >&2
fi
echo "usage: $0 [options] <message>"
echo
echo "Options:"
echo
echo " -h Show this help message"
echo
echo " -o <output.gif> Path to output gif. Default: yolo.gif"
echo
echo " -c <color> Choose color set, valid options are:"
echo " red, orange, yellow, green, blue, purple,"
echo " pink, black, white. Default: blue"
echo
echo " -w Force white text color"
exit 1
}
DEFAULT_FONT='Arial Black.ttf'
# Find our font before we do anything.
FONT_PATH="$(find $HOME/Library/Fonts/ -name $DEFAULT_FONT)"
if [ "$FONT_PATH" == "" ]; then
FONT_PATH="$(find /Library/Fonts/ -name $DEFAULT_FONT)"
fi
if [ "$FONT_PATH" == "" ]; then
usage "Could not find '$DEFAULT_FONT'. Is it installed?"
fi
VALID_COLORS=("red" "orange" "yellow" "green" "blue" "purple" "pink" "black" "white")
COLOR="blue"
OUTPUT="yolo.gif"
FORCE_WHITE_TEXT=0
while getopts ":c:o:hw" opt; do
case $opt in
h)
usage
;;
w)
FORCE_WHITE_TEXT=1
;;
c)
if contains "$OPTARG" "${VALID_COLORS[@]}"; then
COLOR="$OPTARG"
else
usage "Invalid color: $OPTARG"
fi
;;
o)
OUTPUT="$OPTARG"
;;
\?)
usage "Invalid option: -$OPTARG"
;;
:)
usage "Option -$OPTARG requires an argument."
exit 1
;;
esac
done
shift $(($OPTIND - 1))
MESSAGE="$*"
if [ "$MESSAGE" == "" ]; then
usage "A message is required."
fi
case $COLOR in
red)
BACKGROUND="#ef4e65"
FILL="#8c2738"
;;
orange)
BACKGROUND="#f47820"
FILL="#8e4402"
;;
yellow)
BACKGROUND="#f0ce15"
FILL="#947c00"
;;
green)
BACKGROUND="#51bb7b"
FILL="#267048"
;;
blue)
BACKGROUND="#50c6db"
FILL="#01516e"
;;
purple)
BACKGROUND="#8351a0"
FILL="#4e2760"
;;
pink)
BACKGROUND="#e0368c"
FILL="#851252"
;;
black)
BACKGROUND="#5d5e5e"
FILL="#262727"
;;
white)
BACKGROUND="#ffffff"
FILL="#000000"
;;
esac
if [ "$FORCE_WHITE_TEXT" == 1 ]; then
# FILL="#ffffff"
BACKGROUND="#ffffff"
FILL="#000000"
fi
# Make a "unique" prefix for this run
PREFIX="$(head -c 32 /dev/urandom | shasum | cut -b 1-10)"
# Generate image from text input
convert -background "$BACKGROUND" -fill "$FILL" -font "$FONT_PATH" -density 200 -pointsize 100 "label:${MESSAGE}" "/tmp/${PREFIX}_label.png"
# Resize to 128px high
convert -resize x128 "/tmp/${PREFIX}_label.png" "/tmp/${PREFIX}_sized.png"
# Add white space to front and back for empty frames
WIDTH="$(identify -format "%[fx:w]" "/tmp/${PREFIX}_sized.png")"
CANVAS_SIZE=$(($WIDTH + 276)) # 128 PX in front, 148 in back
convert -size ${CANVAS_SIZE}x128 "xc:$BACKGROUND" "/tmp/${PREFIX}_canvas.png"
convert "/tmp/${PREFIX}_canvas.png" "/tmp/${PREFIX}_sized.png" -geometry +128+0 -composite "/tmp/${PREFIX}_padded.png"
# Generate individual frames
OFFSET=0
I=0
LIMIT=$(($CANVAS_SIZE - 128))
while [ $OFFSET -lt $LIMIT ]; do
convert "/tmp/${PREFIX}_padded.png" -crop "128x128+${OFFSET}+0!" "$(printf "/tmp/${PREFIX}_frame_%05d.png" $I)"
I=$(($I + 1))
OFFSET=$(($OFFSET + 10))
done
# Compile to gif
convert -delay 6 -loop 0 +repage "/tmp/${PREFIX}_frame_*.png" "$OUTPUT"
# Smush it
gifsicle --colors 256 -bO "$OUTPUT"
# Clean up!
rm /tmp/${PREFIX}_*.png
<file_sep>#!/bin/bash
# strict mode
set -euo pipefail
IFS=$'\n\t'
REPOS="
send-me-motd
misc-config
linux-scripts
dotfiles
rfobasic
stuff-and-things
college-pascal
ruby-koans-exercises
learning-ruby
python_koans
"
echo "This is intended to run on a new box without anything on yet."
echo "Repos:" $REPOS
read -r -p "Are you sure you want to git clone? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
echo "Very well, continuing box initialisation..."
;;
*)
echo "Aborted."
exit 1
;;
esac
sleep 5
set -vx
mkdir -p ~/dev
cd ~/dev
for repo in $REPOS; do
git clone https://github.com/willsheppard/$repo
done
cd ~
echo "" >> .bashrc
echo "# WS custom setup" >> .bashrc
echo "source ~/dev/dotfiles/.bashrc" >> .bashrc
ln -s dev/dotfiles/.gitconfig .gitconfig
ln -s dev/dotfiles/.vimrc .vimrc
<file_sep>#!/bin/bash
# See docs: http://ss64.com/bash/read.html
#read -p "Are you sure to continue? (Y|N) " -n 1 XT_USER_REPLY
read -p "Are you sure to continue? (Y|N) " XT_USER_REPLY
if [[ ! $XT_USER_REPLY =~ ^[Yy](es)?$ ]]
then
echo
echo "See you next time!"
exit 1
else
echo
echo "Wooho, you're really, really sure"
exit 0
fi
<file_sep>#!/bin/bash
# Check out an SVN branch by copying a cut-down template
# which has had all the files deleted except .svn/*
# Then switch to that branch. This can be done very quickly.
#
# The alternative is to download the entire codebase
# for every branch, which is much slower.
#
# Expects working directory to be ~/dev/
ART=$1
NAME=$2
if [[ -z "$ART" || -z "$NAME" ]]
then
echo "usage: svncheckout branch_name your_short_name"
exit 1;
fi
if [[ -z "$SVN" ]]
then
echo "\$SVN must be defined as the path to the subversion repo"
exit
fi
if [[ ! -d "_template" ]]
then
echo "Directory _template must exist."
echo "Suggestion for creating:"
echo " cp trunk _template"
echo " find trunk/ -type f |grep -v .svn|xargs rm"
exit
fi
NOW=$(date +'%Y%M%d-%H%M%S')
cd $HOME/dev
rm -rf _random
time cp -rp _template/ _random
mv _random/ $ART
ln -s $ART $NAME
cd $NAME
time svn switch $SVN/branches/$ART
echo
echo "If this has worked, you should see a lot of 'Restored file xxxxx' lines above"
echo "(above the list of files which were changed in this branch)"
echo
<file_sep>#!/bin/bash
# Remove color codes
# Linux
#sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
# Mac
sed "s,$(printf '\033')\\[[0-9;]*[a-zA-Z],,g"
<file_sep>#!/bin/bash
export OUTFILE="/tmp/test_out.html"
export TAP_HTML_LIB="$HOME/alt/cpan/tap_html/local/lib/perl5"
export HTML_DISPLAY_LIB="$HOME/alt/cpan/html_display/local/lib/perl5"
PERL5LIB="$TAP_HTML_LIB:$PERL5LIB" \
prove -m -P HTML=outfile:$OUTFILE -lr $@
perl -I $HTML_DISPLAY_LIB -MHTML::Display \
-e 'HTML::Display->new->display(file => $ENV{OUTFILE})'
<file_sep>#!/bin/bash
# Delete files I don't need, to save disk space
# Mac OSX keeps downloading these updates
sudo rm -rf "/Applications/Install macOS Mojave.app"
sudo rm -rf "/Applications/Install macOS Monterey.app"
sudo rm -rf "/Applications/Install macOS Big Sur.app"
sudo rm -rf /Applications/Install\ macOS*
# Homebrew keeps downloading these repos with full history
BREW_DIR="/usr/local/Homebrew/Library/Taps/homebrew"
sudo rm -rf "$BREW_DIR/homebrew-core"
sudo rm -rf "$BREW_DIR/homebrew-cask"
# Use a shallow clone
git clone --depth=1 https://github.com/homebrew/homebrew-core.git "$BREW_DIR/homebrew-core"
git clone --depth=1 https://github.com/homebrew/homebrew-cask.git "$BREW_DIR/homebrew-cask"
<file_sep>#!/bin/bash
set -euo pipefail
IFS=$'\n\t'
PREFIX="foocorp"
APP="fooclient"
MONIKER="${PREFIX}-${APP}"
DB="${PREFIX}_${APP}"
DIR="${PREFIX}${APP}"
# Get hostname from mojo config
HOST=$(grep dbi:mysql /srv/deploy_aws_${DIR}/current/${MONIKER}.production.conf | tail -1 | perl -ne'm/host=(.+?);/ && print $1')
# Test connection
mysql -h $HOST --user=$DB --database=$DB --password -e "show tables"
# Actual dump
mysqldump \
--no-create-db \
--no-tablespaces \
--skip-lock-tables \
--single-transaction \
--complete-insert \
--host=$HOST \
--user=$DB \
--password \
--databases $DB \
> ./$DB.dump.$(date +"%Y-%m-%d_%H%M%S").sql
# Explanation
# --no-create-db: prevents "CREATE DATABASE" command
# --no-create-info: Only dumps data, not schema
# --skip-lock-tables: Prevents "Access denied" error
# --single-transaction: Ensures consistent snapshot
# --complete-insert: Specify column names for inserts
# --no-tablespaces: Prevent error: 'Access denied; you need (at least one of) the PROCESS privilege(s) for this operation'
<file_sep># Tools for `$current_job`
Don't commit these, keep them local because they can't be shared.
|
ea975858b11d6e3ad3b2cf48fd2c1b0d6325c9b9
|
[
"Markdown",
"Python",
"Shell"
] | 71
|
Shell
|
willsheppard/linux-scripts
|
7b2234d26496546b8d97d5a7e6485613d7d67036
|
013c69cd8f280c7873f64cbce160f82712917786
|
refs/heads/master
|
<repo_name>fletsch/trajectory_toolkit<file_sep>/scripts/ekf_evaluation.py
#! /usr/bin/env python
# Imports
import os, sys, inspect
import numpy as np
from trajectory_toolkit.TimedData import TimedData
from trajectory_toolkit.Plotter import Plotter
from trajectory_toolkit import Quaternion
from trajectory_toolkit import Utils
from trajectory_toolkit import RosDataAcquisition
from trajectory_toolkit.VIEvaluator import VIEvaluator
plotRon = True
plotAtt = True
plotPos = True
plotVel = True
plotRor = True
plotYpr = True
plotExt = True
td_filter = TimedData()
td_vicon = TimedData()
td_comp = TimedData(16)
outputFolder = '/home/frederic/Documents/BachelorThesis/ekf_evaluation'
inputPath = '/home/frederic/datasets/vicon_offline/vicon_normal2_2019-07-05-03-14-43.bag'
rovioEvaluator = VIEvaluator()
rovioEvaluator.bag = '/home/frederic/datasets/vicon_offline/vicon_normal2_2019-07-05-03-14-43.bag'
#rovioEvaluator.bag = '/home/frederic/datasets/vicon_offline/vicon_short_2019-06-23-15-10-39.bag'
rovioEvaluator.odomTopic = '/msf_core/odometry'
rovioEvaluator.gtFile = '/home/frederic/datasets/vicon_offline/vicon_normal2_2019-07-05-03-14-43.bag'
#rovioEvaluator.gtFile = '/home/frederic/datasets/vicon_offline/vicon_short_2019-06-23-15-10-39.bag'
rovioEvaluator.gtTopic = '/vrpn_client_1562248578120672780/estimated_transform'
#rovioEvaluator.extraTransformAtt = np.array([1, 0, 0, 0]) #[w x y z]
#rovioEvaluator.extraTransformPos = np.array([0, 0, 0])
rovioEvaluator.startcut = 0
rovioEvaluator.endcut = 0
rovioEvaluator.doCov = False
rovioEvaluator.doNFeatures = 25
rovioEvaluator.doExtrinsics = False
rovioEvaluator.doBiases = False
rovioEvaluator.alignMode = 1
rovioEvaluator.plotLeutiDistances = []
rovioEvaluator.initTimedData(td_filter)
rovioEvaluator.initTimedDataGT(td_vicon)
rovioEvaluator.acquireData()
rovioEvaluator.acquireDataGT()
rovioEvaluator.getAllDerivatives()
rovioEvaluator.alignTime()
rovioEvaluator.alignBodyFrame()
rovioEvaluator.alignInertialFrame()
rovioEvaluator.getYpr()
rovioEvaluator.evaluateSigmaBounds()
#Write output to file !!! apends to file if it already exists
td_filter.writeColsToFile(outputFolder + '/vicon_normal2_2019-07-05-03-14-43', 'pose_ekf', td_filter.getColIDs('pos') + td_filter.getColIDs('ypr'), ' ')
td_vicon.writeColsToFile(outputFolder + '/vicon_normal2_2019-07-05-03-14-43', 'pose_vicon', td_vicon.getColIDs('pos') + td_vicon.getColIDs('ypr') + td_vicon.getColIDs('att'), ' ')
#load complementary filter output and estimate time offset with rotational rate from gyroscope
gyroIDs = [1,2,3]
accIDs = [4,5,6]
orientIDs = [7,8,9,10]
ronCompID = 11
orientAlignedIDs = [12,13,14, 15]
RosDataAcquisition.rosBagLoadImuWithOrientation(inputPath, '/est_states/imu', td_comp, gyroIDs, accIDs, orientIDs)
td_comp.computeNormOfColumns(gyroIDs, ronCompID)
td_comp.applyTimeOffset(td_vicon.getFirstTime()-td_comp.getFirstTime())
to_comp = td_comp.getTimeOffset(ronCompID, td_vicon, td_vicon.getColIDs('ron'))
print('Time offset complementary filter to vicon is: ' + str(to_comp))
#apply rotation part of body alignmet to complementary filter orientation (transformation same as ekf)
# rotation = np.array([0.9999251528730725, -0.0022342581584454853, 0.01197584675309537, 0.0011295294552196493])
# rotated = Quaternion.q_mult(np.kron(np.ones([td_comp.length(),1]),rotation), td_comp.col(orientIDs))
# for i in np.arange(0,3):
# td_comp.setCol(rotated[:,i], orientAlignedIDs[i])
td_comp.writeColsToFile(outputFolder + '/vicon_normal2_2019-07-05-03-14-43', 'attitude_comp', orientIDs, ' ')
if plotPos: # Position plotting
plotterPos = Plotter(-1, [3,1],'Position',['','','time[s]'],['x[m]','y[m]','z[m]'],10000)
if rovioEvaluator.doCov:
plotterPos.addDataToSubplotMultiple(td_filter, 'posSm', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterPos.addDataToSubplotMultiple(td_filter, 'posSp', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterPos.addDataToSubplotMultiple(td_filter, 'pos', [1,2,3], ['r','r','r'], ['','',''])
plotterPos.addDataToSubplotMultiple(td_vicon, 'pos', [1,2,3], ['b','b','b'], ['','',''])
if plotVel: # Velocity plotting
plotterVel = Plotter(-1, [3,1],'Robocentric Velocity',['','','time[s]'],['$v_x$[m/s]','$v_y$[m/s]','$v_z$[m/s]'],10000)
plotterVel.addDataToSubplotMultiple(td_filter, 'vel', [1,2,3], ['r','r','r'], ['','',''])
plotterVel.addDataToSubplotMultiple(td_vicon, 'vel', [1,2,3], ['b','b','b'], ['','',''])
if plotAtt: # Attitude plotting
plotterAtt = Plotter(-1, [4,1],'Attitude Quaternion',['','','','time[s]'],['w[1]','x[1]','y[1]','z[1]'],10000)
plotterAtt.addDataToSubplotMultiple(td_filter, 'att', [1,2,3,4], ['r','r','r','r'], ['','','',''])
plotterAtt.addDataToSubplotMultiple(td_vicon, 'att', [1,2,3,4], ['b','b','b','b'], ['','','',''])
if plotYpr: # Yaw-pitch-roll plotting
plotterYpr = Plotter(-1, [3,1],'Yaw-Pitch-Roll Decomposition',['','','time[s]'],['roll[rad]','pitch[rad]','yaw[rad]'],10000)
if rovioEvaluator.doCov:
plotterYpr.addDataToSubplotMultiple(td_filter, 'yprSm', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterYpr.addDataToSubplotMultiple(td_filter, 'yprSp', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterYpr.addDataToSubplotMultiple(td_filter, 'ypr', [1,2,3], ['r','r','r'], ['','',''])
plotterYpr.addDataToSubplotMultiple(td_vicon, 'ypr', [1,2,3], ['b','b','b'], ['','',''])
if plotRor: # Rotational rate plotting
plotterRor = Plotter(-1, [3,1],'Rotational Rate',['','','time[s]'],['$\omega_x$[rad/s]','$\omega_y$[rad/s]','$\omega_z$[rad/s]'],10000)
plotterRor.addDataToSubplotMultiple(td_filter, 'ror', [1,2,3], ['r','r','r'], ['','',''])
plotterRor.addDataToSubplotMultiple(td_vicon, 'ror', [1,2,3], ['b','b','b'], ['','',''])
if plotRon: # Plotting rotational rate norm
plotterRon = Plotter(-1, [1,1],'Norm of Rotational Rate',['time [s]'],['Rotational Rate Norm [rad/s]'],10000)
plotterRon.addDataToSubplot(td_filter, 'ron', 1, 'r', 'rovio rotational rate norm')
plotterRon.addDataToSubplot(td_vicon, 'ron', 1, 'b', 'vicon rotational rate norm')
if plotExt and rovioEvaluator.doExtrinsics: # Extrinsics Plotting
plotterExt = Plotter(-1, [3,1],'Extrinsics Translational Part',['','','time[s]'],['x[m]','y[m]','z[m]'],10000)
if rovioEvaluator.doCov:
plotterExt.addDataToSubplotMultiple(td_filter, 'extPosSm', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterExt.addDataToSubplotMultiple(td_filter, 'extPosSp', [1,2,3], ['r--','r--','r--'], ['','',''])
plotterExt.addDataToSubplotMultiple(td_filter, 'extPos', [1,2,3], ['r','r','r'], ['','',''])
raw_input("Press Enter to continue...")
|
c8428662849b4f2ec0c92ab6ab8360136625e5d1
|
[
"Python"
] | 1
|
Python
|
fletsch/trajectory_toolkit
|
e8c3e5420a9824d2cf379dce01fa3d4dbe0d3725
|
97f72a0e577789dd40964c6067be4083a4d73413
|
refs/heads/master
|
<file_sep>class Blogger < ApplicationRecord
has_many :posts, dependent: :delete_all
has_many :destinations, through: :posts
validates :name, presence: true, uniqueness: true
validates :bio, length: {minimum: 30}
end
<file_sep>class Destination < ApplicationRecord
has_many :posts, dependent: :delete_all
has_many :bloggers, through: :posts
end
|
7df69d252acdb422d0e3c1fb7350122c36fad3f6
|
[
"Ruby"
] | 2
|
Ruby
|
edhernandez04/Rails-Practice-Code-Challenge-Travelatr-nyc-web-010620
|
97b5cc6f54bef84f339ebf5aa52bea65de6dd81e
|
75be322d6d8773d9e36a1dbee5f842283a4e82a2
|
refs/heads/master
|
<file_sep>define([
'jquery',
'underscore',
'backbone',
'utils/log'
], function($, _, Backbone, Log){
// Payload Model
// payload is the data structure available to the templates via Mustache.
return Backbone.Model.extend({
initialize : function(){
this.set({
buildUrl : function(){
return function(name, render) {return render( "GUPPY" ) }
}
});
}
})
});<file_sep>define([
'jquery',
'underscore',
], function($, _){
return {
// parse the mustache expression's name
parseContext : function(tagName){
return tagName.split('?')[0] || null;
},
// Query based on helper name
// Helpers must start with "?"
// If we can't find anything it's important to return undefined.
query : function(name, context, stack){
var helper = name.split('?')[1];
if(helper && typeof this[helper] === 'function')
return this[helper](context, stack)
},
to_pages : function(context, stack){
var pages = [];
if ( _.isArray(context) )
_.each(context, function(id){
if(stack.pages[id]) pages.push(stack.pages[id])
})
else pages = stack.pages;
return _.map(pages, function(page){
if(stack.page.id === page.id)
page.isActivePage = true;
return page
})
},
to_tags : function(context, stack){
return _.isArray(context)
? _.map(context, function(name){
if(stack._posts.tags[name])
return stack._posts.tags[name]
})
: _.map(stack._posts.tags, function(tag){
return tag
})
},
to_posts : function(context, stack){
return _.map(
_.isArray(context)
? context
: stack._posts.chronological,
function(id) {
if(stack._posts.dictionary[id])
return stack._posts.dictionary[id]
}
)
},
to_categories : function(context, stack){
return _.isArray(context)
? _.map(context, function(name){
if(stack._posts.categories[name])
return stack._posts.categories[name]
})
: _.map(stack._posts.categories, function(cat){
return cat
})
},
// Probably not going to use this since its simple enough to
// call the data structure directly.
posts_collate : function(context, stack){
return stack._posts.collated;
}
}
})
<file_sep>require 'rubygems'
require 'rake'
require 'fileutils'
require './_lib/ruhoh'
Ruhoh.setup
Dir['./_lib/rake/*.rake'].each { |r| load r }<file_sep>define([
'utils/log',
'markdown',
'yaml'
], function(Log, Markdown){
return {
// Matcher for YAML Front Matter
FMregex : /^---\n(.|\n)*---\n/,
// Parse and store the YAML Front Matter from the file.
frontMatter : function(content, file){
var front_matter = this.FMregex.exec(content);
if(!front_matter) Log.parseError(file, "Invalid YAML Front Matter");
front_matter = front_matter[0].replace(/---\n/g, "");
return (jsyaml.load(front_matter) || {});
},
// Internal: Parse content from a file.
// Content in a file is everything below the Front Matter.
//
// content - Required [String] The file contents.
// id - Optional [String] The file id which is the name.
// File extension determines parse method.
//
// Returns: [String] The parsed content.
content : function(content, id){
content = content.replace(this.FMregex, '');
if( id && ['md', 'markdown'].indexOf( id.split('.').pop().toLowerCase() ) !== -1 ){
var converter = new Markdown.Converter();
return converter.makeHtml(content);
}
return content;
}
}
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'utils/log',
'handlebars'
], function($, _, Backbone, Log, Handlebars){
// Partial Model
return Backbone.Model.extend({
generate : function(){
return this.fetch({dataType : "html", cache : false });
},
url : function(){
return this.config.getPath('/_client/partials/', this.get('path'));
},
parse : function(data){
this.set('content', data);
return this.attributes;
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
], function($, _, Backbone){
return Backbone.Router.extend({
routes: {
"" : "home",
"index.html" : "home",
"*page": "page"
},
// Route.navigate() events trigger these route bindings which
// set the page id based on the URL.
// The page change:id event fires,
// triggering preview.generate(): see preview model for bindings.
initialize : function(){
var that = this;
this.bind("route:home", function(){
this.preview.page.clear({silent : true})
this.preview.page.set('path', '_pages/index.md')
}, this)
this.bind("route:page", function(page){
this.preview.page.clear({silent : true})
this.preview.page.set( 'path', (page.split('?path=')[1] || page) );
}, this)
// Hand off all link events to the Router.
$("body").find('a').live("click", function(e){
if( _.isString($(this).attr("href")) )
that.navigate('/'+$(this).attr("href"), {trigger: true});
e.preventDefault();
return false;
});
},
// Public: Start Router.
// Returns: Nothing
start : function(){
Backbone.history.start({
pushState: true,
root: (this.preview.config.get('basePath') || '/')
});
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'utils/parse',
'utils/log',
'yaml',
], function($, _, Backbone, Parse, Log){
// Pages Dictionary is a hash representation of all pages in the app.
// This is used as the primary pages database for the application.
// A page is referenced by its unique id attribute .
// When working with pages you only need to reference its id.
// Valid id nodes are expanded to the full page object via the dictionary.
return Backbone.Model.extend({
initialize : function(attrs){
},
generate : function(){
return this.fetch({dataType : "html", cache : false });
},
url : function(){
return this.config.getDataPath('/_database/pages_dictionary.yml');
},
parse : function(response){
data = jsyaml.load(response);
// Need to append the page id to urls for client-side rendering.
// i.e. We need to tell javascript where the file is.
for(id in data){
data[id]['url'] += ('?path='+ this.config.fileJoin(this.config.get('pagesDirectory'), id))
}
this.set(data);
return this.attributes;
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'utils/parse',
'utils/log',
'yaml',
], function($, _, Backbone, Parse, Log){
// Layout Model
return Backbone.Model.extend({
initialize : function(attrs){
},
generate : function(){
return this.fetch({dataType : "html", cache : false });
},
url : function(){
return this.config.getThemePath('/layouts/'+ this.id +'.html');
},
parse : function(data){
this.set(Parse.frontMatter(data, this.url()));
this.set("content", Parse.content(data));
return this.attributes;
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'models/layout',
'models/config',
'utils/parse',
'utils/log',
'yaml',
], function($, _, Backbone, Layout, Config, Parse, Log){
// Page Model
// Represents a post or page.
return Backbone.Model.extend({
initialize : function(attrs){
this.bind('change:path', function(){
this.set('id', this.get('path').replace(/^_posts\//, '') )
},this)
},
// Public: Fetch a page/post and resolve all template dependencies.
// Template promises are *piped* up to the parent page promise.
// TODO: This probably can be implemented a lot better.
// Returns: jQuery Deferred object. This ensures all despendencies
// are resolved before the generate promise is kept.
generate : function(){
var that = this;
return this.fetch({dataType : "html", cache : false}).pipe(function(){
if(!that.get("layout"))
Log.parseError(that.url(), "Page/Post requires a valid layout setting. (e.g. layout: post)")
that.sub.set("id", that.get("layout"));
return that.sub.generate().pipe(function(){
if(that.sub.get("layout")){
that.master.set("id", that.sub.get("layout"))
return that.master.generate();
}
})
}).fail(function(jqxhr){
Log.loadError(this, jqxhr)
})
},
url : function(){
return this.config.getDataPath(this.get('path'));
},
// Parse the raw page/post file.
parse : function(data){
this.set(Parse.frontMatter(data, this.url()), { silent : true});
this.set("content", Parse.content(data, this.id), { silent : true});
return this.attributes;
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'dictionaries/pages',
'dictionaries/posts',
'models/config',
'models/page',
'models/layout',
'models/payload',
'models/partial',
'collections/partials',
'utils/log',
'mustache',
'helpers',
], function($, _, Backbone,
PagesDictionary, PostsDictionary,
Config, Page, Layout, Payload, Partial,
Partials,
Log, Mustache){
TemplateEngine = "Mustache";
ContentRegex = /\{\{\s*content\s*\}\}/i;
// Preview object builds a preview of a given page/post
//
// There is only ever one preview at any given time.
// page/posts exist as data-structures only.
// Aggrregate data-structures can be built from those objects.
//
// However for the purpose of the _client, the preview
// object is what renders what you see in the browser.
return Backbone.Model.extend({
master : Layout,
sub : Layout,
page : Page,
payload : Payload,
initialize : function(attrs, config){
this.config = config;
this.page = new Page;
this.page.sub = new Layout;
this.page.master = new Layout;
this.payload = new Payload;
this.pagesDictionary = new PagesDictionary;
this.postsDictionary = new PostsDictionary;
this.partials = new Partials;
// Set pointers to a single Config.
this.page.config = this.config,
this.page.sub.config = this.config,
this.page.master.config = this.config,
this.payload.config = this.config,
this.partials.config = this.config,
this.pagesDictionary.config = this.config,
this.postsDictionary.config = this.config;
this.page.bind("change:id", function(){
this.generate();
}, this)
},
generate : function(){
var that = this;
$.when(
this.page.generate(),
this.partials.generate(),
this.pagesDictionary.generate(),
this.postsDictionary.generate()
).done(function(){
that.buildPayload();
that.process();
}).fail(function(jqxhr){
Log.loadError(this, jqxhr)
});
},
// Build the payload.
buildPayload : function(){
this.payload.set({
"config" : this.config.attributes,
"page" : this.page.attributes,
"pages" : this.pagesDictionary.attributes,
"_posts" : this.postsDictionary.attributes,
"ASSET_PATH" : this.config.getThemePath(),
"HOME_PATH" : "/",
"BASE_PATH" : ""
})
},
process : function(){
var output = this.page.sub.get("content")
.replace(ContentRegex, this.page.get("content"));
// An undefined master means the page/post layouts is only one deep.
// This means it expects to load directly into a master template.
if(this.page.master.id){
output = this.page.master.get("content")
.replace(ContentRegex, output);
}
this[TemplateEngine](output);
},
// Public: Process content, sub+master templates then render the result.
//
// TODO: Include YAML Front Matter from the templates.
// Returns: Nothing. The finished preview is rendered in the Browser.
Handlebars : function(output){
var template = Handlebars.compile(output);
$(document).html( template(this.payload.attributes) );
},
// Public: Process content, sub+master templates then render the result.
//
// TODO: Include YAML Front Matter from the templates.
// Returns: Nothing. The finished preview is rendered in the Browser.
Mustache : function(output){
$('body').html(
Mustache.render(
output,
this.payload.attributes,
this.partials.toHash()
)
);
}
});
});<file_sep>define([
'jquery',
'underscore',
'backbone',
'router',
'utils/parse',
'utils/log',
'yaml',
'dictionaries/pages',
'dictionaries/posts',
'models/config',
'models/layout',
'models/page',
'models/payload',
'models/preview',
'models/partial',
'collections/partials',
'handlebars',
'helpers',
'markdown'
], function($, _, Backbone, Router, Parse, Log, yaml,
PagesDictionary, PostsDictionary,
Config, Layout, Page, Payload, Preview, Partial,
Partials,
Handlebars, helpers, Markdown){
var App = {
router : new Router,
// Public: Start the application relative to the site_source.
// The web-server is responsible for passing site_source in the Header.
// Once the site_source folder is known we can load _config.yml and start the app.
//
// Returns: Nothing
start : function(){
var that = this;
$.get('/').pipe(function(a,b,jqxhr){
//that.config = new Config({'site_source' : '/' + jqxhr.getResponseHeader('x-ruhoh-site-source-folder') });
that.config = new Config({'site_source' : '/' });
return that.config.generate();
}).done(function(){
that.preview = that.router.preview = new Preview(null, that.config);
that.router.start();
}).fail(function(jqxhr){
Log.loadError(this, jqxhr)
});
}
}
return App;
});
|
67418a4d4767108340b78148cf1af42879b71606
|
[
"JavaScript",
"Ruby"
] | 11
|
JavaScript
|
digideskio/ruhoh.js
|
c204593e6e3d49c5aa99e931fbc7a4c7d567b8aa
|
34e3bf96ae53f3cc5e93bf3899f7afae143b135e
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace COMP123_M2020_FinalExam
{
public partial class GenerateNameForm : Form
{
public GenerateNameForm()
{
InitializeComponent();
}
private void GenerateNames()
{
Random rand = new Random();
int index = rand.Next(0, FirstNameListBox.Items.Count);
FirstNameTextBox.Text = (string)FirstNameListBox.Items[index];
LastNameTextBox.Text = (string)LastNameListBox.Items[index];
}
private void GenerateNameForm_Load(object sender, EventArgs e)
{
GenerateNames();
}
private void GenerateButton_Click(object sender, EventArgs e)
{
GenerateNames();
Program.character.FirstName = FirstNameTextBox.Text;
Program.character.LastName = LastNameTextBox.Text;
}
private void NextButton_Click(object sender, EventArgs e)
{
this.Hide();
AbilityGeneratorForm abilityGeneratorForm = new AbilityGeneratorForm();
abilityGeneratorForm.Show();
}
}
}
|
0140b439c5d47aebb83ef70bddcc7a32cadb99e4
|
[
"C#"
] | 1
|
C#
|
vermashanu/COMP123-M2020-FinalExam-301100045
|
b62293f810959006a9e669279ebcd38fe1b993f1
|
e508c8d82dc77223067e90d380f99b05539d620a
|
refs/heads/master
|
<file_sep>A itty-bitsy Virtual Machine
<file_sep>use std::fs;
use std::env;
use std::error::Error;
use std::process;
use std::vec::Vec;
fn main() -> Result<(), Box<Error + 'static>> {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
process::exit(1);
}
let filename = &args[1];
let file: String = fs::read_to_string(filename)?.parse()?;
Ok(())
}
<file_sep>[package]
name = "ittyvm"
version = "0.1.0"
authors = ["joaobap <<EMAIL>>"]
[dependencies]
|
6c40d9f8a4a8d9cebe69ad6788f61d43ae6c4e6a
|
[
"Markdown",
"Rust",
"TOML"
] | 3
|
Markdown
|
joaobap/ettyvm
|
8e0ac4bd1aa657e64860c56d2826ff7a0902e49a
|
edf52fc4abec5475a71845d6d104e87708057040
|
refs/heads/dev
|
<file_sep><?php
require 'vendor/autoload.php';
use Location\Coordinate;
use Location\Distance\Vincenty;
$coord1 = new Coordinate(49.378518, 32.152849);
$coord2 = new Coordinate(49.426007, 32.094617);
$calculator = new Vincenty();
echo '<h1> Дом <--------> Geekhub </h1>';
echo '<br>';
echo '<br>';
echo 'Растояние между двумя кординатами : ', $calculator->getDistance($coord1, $coord2), ' метров';
//=====================================================
echo '<br>';
echo '<br>';
echo '<br>';
echo '<=====================================================================>';
echo '<br>';
echo '<br>';
use Temperature\Factory\DefaultFactory as TemperatureFactory;
$factory = new TemperatureFactory();
$temper = $factory->build(88, 'F');
echo 'Температура в: ', $temper, ' = ', $temper->convert('C')->setPrecision(2);
?>
|
4925ef69a76aef4e4c8789b37b8131ab1dee5017
|
[
"PHP"
] | 1
|
PHP
|
JeniaTr/Home-work-1
|
4b399b8c344ecd16e55d586b47ef226f1e76fece
|
dc886d1ad2358a7f870743e58389b74492210a2a
|
refs/heads/master
|
<repo_name>samuelpacheco/projetoPHP<file_sep>/alterar.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Alterar clientes</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
</head>
<body>
<?php
include 'conexao.php';
if(empty($_GET['id'])) {
echo 'erro 404 - produto nao encontrado';
exit;
}
$id = $_GET['id'];
if(!empty($_POST)) {
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$obs = $_POST['obs'];
$cadastrar = mysqli_query($conexao, "UPDATE clientes SET nome = '$nome', empresa = '$empresa', obs = '$obs' WHERE id = '$id'") or die(mysqli_error($conexao));
if($cadastrar) {
echo 'Cliente alterado com sucesso';
} else {
echo 'Cliente nao foi alterado';
}
}
$query = mysqli_query($conexao, "SELECT id, nome, empresa, obs FROM clientes WHERE id = '$id'") or die(mysqli_error($conexao));
$cliente = mysqli_fetch_assoc($query);
?>
<h1>Alterar clientes</h1>
<form action="" method="POST" class="col-xs-6">
<label>Nome</label><input class="form-control" type="text" name='nome' value="<?php echo $cliente['nome'] ?>"><br/>
<label>Empresa</label><input class="form-control" type="text" name='empresa' value="<?php echo $cliente['empresa'] ?>"><br/>
<label>Obs</label><textarea class="form-control" name="obs"><?php echo $cliente['obs'] ?></textarea><br/>
<input class="btn btn-primary" type="submit" value="Alterar">
</form>
</body>
</html>
<file_sep>/excluir.php
<?php
include 'conexao.php';
if(empty($_POST['id'])) {
echo 'erro 404 - produto nao encontrado';
exit;
}
$id = $_POST['id'];
$query = mysqli_query($conexao, "DELETE from clientes WHERE id = '$id'");
if($query) {
echo "Produto excluido com sucesso. <a href='HTTP://127.0.0.1/projetoPHP'>VOLTAR</a>";
} else {
echo 'deu um erro ao excluir o produto';
}<file_sep>/index.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Listagem de clientes</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous">
</head>
<body>
<?php
include 'conexao.php';
$query = mysqli_query($conexao, 'SELECT id, nome, empresa, obs FROM clientes');
$clientes = array();
while($cliente = mysqli_fetch_assoc($query)) {
array_push($clientes, $cliente);
}
?>
<h1>Listar clientes</h1>
<table class="table table-striped table-bordered">
<tr>
<td>ID</td><td>Nome</td><td>Empresa</td><td>Obs</td><td></td>
</tr>
<?php
foreach($clientes as $cliente) {?>
<tr>
<td><?php echo $cliente['id'] ?></td>
<td><?php echo $cliente['nome'] ?></td>
<td><?php echo $cliente['empresa'] ?></td>
<td><?php echo $cliente['obs'] ?></td>
<td><a class="btn btn-primary btn-xs" href="alterar.php?id=<?php echo $cliente['id'] ?>">Alterar</a>
<form action="excluir.php" method="POST">
<input type="hidden" name="id" value="<?php echo $cliente['id'] ?>">
<input type="submit" class="btn btn-danger btn-xs" value="excluir" onclick="confirm('Voce deseja mesmo exlcuir?')">
</form>
</td>
</tr>
<?php
} ?>
</table>
</body>
</html><file_sep>/cadastrar.php
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Cadastrar de clientes</title>
<body>
<?php
if(!empty($_POST)) {
include 'conexao.php';
$nome = $_POST['nome'];
$empresa = $_POST['empresa'];
$obs = $_POST['obs'];
$cadastrar = mysqli_query($conexao, "INSERT INTO clientes (nome, empresa, obs) VALUES('$nome', '$empresa', '$obs')") or die(mysqli_error($conexao));
if($cadastrar) {
echo 'Cliente cadastrado com sucesso';
} else {
echo 'Cliente nao foi cadastrado';
}
}
?>
<h1>Cadastrar clientes</h1>
<form action="" method="POST">
<label>Nome</label><input type="text" name='nome'><br/>
<label>Empresa</label><input type="text" name='empresa'><br/>
<label>Obs</label><textarea name="obs"></textarea><br/>
<input type="submit" value="Cadastrar">
</form>
</body>
</html><file_sep>/conexao.php
<?php
$conexao = mysqli_connect('localhost', 'root', '');
mysqli_select_db($conexao, 'projeto');
|
b4ed1488ca4aedf5ca72b68c472193c7f967890a
|
[
"PHP"
] | 5
|
PHP
|
samuelpacheco/projetoPHP
|
c765c3bffb932f4310f1d82a0a5e6f0989e13c92
|
fc4e3b02650db3cce783ae6e980a2d0a91cbcb5c
|
refs/heads/master
|
<file_sep>#include "include/csv.h"
CSV::CSV(char* file)
{
this->file = file;
}
string CSV::read_line(uint number){
this->ifs.clear();
this->ifs.open(file);
string line;
for (uint i=0;i<number;i++)
{
getline(ifs,line);
}
this->ifs.close();
return line;
}
string CSV::read_file(){
this->ifs.clear();
this->ifs.open(file);
string line;
string full;
while (ifs.good())
{
getline (ifs,line);
full+=line + "\n";
}
this->ifs.close();
return full;
}
string CSV::read_data(uint number, uint column){
string line = read_line(number);
string data;
string::iterator i;
uint aux=0;
i=line.begin();
for(;;){
if (*i==','){
aux++;
if(aux == column){
return data;
}
data = "";
if (i<line.end()){
i++;
}
}
else{
data += *i;
if (i<line.end()){
i++;
}
else{
return data;
}
}
}
}
void CSV::write_line(uint cant,bool sobrescribir,char* texto, ...){
this->ofs.clear();
if(sobrescribir){
this->ofs.open(file);
}
else{
this->ofs.open(file,ios::app);
}
va_list columns;
string line = texto;
va_start(columns, texto);
for(uint i = 0; i<cant-1; i++){
line+=",";
line+=va_arg(columns,char*);
}
this->ofs << line << endl;
this->ofs.close();
va_end(columns);
}
void CSV::clean(){
std::ofstream ofs(file);
ofs.close();
}
void CSV::write(char* text){
ofs.open (file);
ofs << text;
ofs.close();
}
<file_sep>#include "include/note.h"
#include "ui_note.h"
#include <QMouseEvent>
#include <QMessageBox>
Note::Note(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Note)
{
ui->setupUi(this);
Qt::WindowFlags flags = 0;
flags |= Qt::FramelessWindowHint;
this->setWindowFlags(flags);
QSizeGrip *g = new QSizeGrip(this);
g->setStyleSheet("background-color:0;");
ui->verticalLayout->addWidget(g, 0, Qt::AlignBottom | Qt::AlignRight);
ui->note_text->setFrameShape(QFrame::NoFrame);
QString note;
csv = new CSV("notes.csv");
note = (const char*)csv->read_file().c_str();
ui->note_text->setPlainText(note);
}
Note::~Note()
{
delete ui;
}
void Note::set_content(char* content){
this->_content = content;
}
char* Note::content(){
return this->_content;
}
void Note::on_btn_add_clicked()
{
Note *n = new Note;
n->show();
}
void Note::on_btn_close_clicked()
{
if(ui->note_text->toPlainText().size()<1){
this->close();
return;
}
if(QMessageBox::question(this, tr("Close"), tr("Close this Note?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton) == QMessageBox::Yes){
char* content = (char*)ui->note_text->toPlainText().toStdString().c_str();
csv->write(content);
this->close();
}
}
void Note::mousePressEvent(QMouseEvent* event)
{
if(event->button() == Qt::LeftButton)
{
_is_moving = true;
_last_point = event->globalPos();
}
}
void Note::mouseMoveEvent(QMouseEvent* event)
{
if( event->buttons().testFlag(Qt::LeftButton) && _is_moving)
{
this->move(this->pos() + (event->globalPos() - _last_point));
_last_point = event->globalPos();
}
}
void Note::mouseReleaseEvent(QMouseEvent* event)
{
if(event->button() == Qt::LeftButton)
{
_is_moving = false;
}
}
void Note::on_pushButton_clicked()
{
if(ui->note_text->toPlainText().size()<1){
return;
}
if(QMessageBox::question(this, tr("Clear"), tr("Clear the contents of this Note?"), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton) == QMessageBox::Yes){
ui->note_text->setPlainText("");
csv->write("");
}
}
<file_sep>#include <iostream>
#include <string>
#include <fstream>
#include <cstdarg>
typedef unsigned int uint;
using namespace std;
class CSV
{
public:
ifstream ifs;
ofstream ofs;
char* file;
CSV(char*);
string read_line(uint);
string read_data(uint,uint);
void write_line(uint,bool,char*, ...);
string read_file();
void clean();
void write(char*);
};
<file_sep>[Notes]
=====
Notes is a sticky note application for writing down things to remember.
Lista de cambios pendientes:
```
+ Persistencia.
+ Quitar css del menu contextual (Click Derecho).
+ Agregar un scrollbar elegante.
+ Opcion de cambiar la tipografia.
+ Opcion de cambiar el color de fondo.
+ Movimiento de la ventana.
```
|
4ec8d39f6aa60dd185fa7e21f6b2f6afeb18c278
|
[
"Markdown",
"C++"
] | 4
|
C++
|
ranfis/notes
|
c39c049c00fe4fcbf4381d27f44c09748f76656d
|
18dfcf38b272836361727b9ac6b4a0a47a4d948e
|
refs/heads/master
|
<file_sep>import logger from 'winston';
import net from 'net';
import { EventEmitter } from 'events';
class TCPServer extends EventEmitter {
constructor(config) {
super();
this.config = config;
this.authed = false;
}
start() {
logger.info('Starting TCP server ...');
this.server = net.createServer(socket => this.onClientConnected(socket));
this.addListeners();
}
addListeners() {
this.server.on('error', error => {
logger.error('Error', error);
// throw error;
});
this.server.listen(this.config.port, () => {
const address = this.server.address();
logger.info(`Server listening on ${address.address}:${address.port}`);
});
}
/**
* Client connected
*/
onClientConnected(socket) {
// if (this.socket) {
// return;
// }
this.socket = socket;
// this.socket.setTimeout(0);
const clientName = this.clientName();
logger.info(`${clientName} connected!`);
this.socket.on('data', this.onClientData.bind(this));
this.socket.on('error', error => {
logger.error(`${clientName} errored.`, error);
this.onClientDisconnected();
});
// this.socket.on('close', (hasError) => {
// logger.info(`${clientName} terminated`, hasError);
// // this.onClientDisconnected();
// });
this.socket.on('timeout', () => {
logger.info(`${clientName} timed out.`);
this.onClientDisconnected();
});
this.socket.on('end', () => {
logger.info(`${clientName} disconnected.`);
this.onClientDisconnected();
});
}
/**
* Client data reveived
*/
onClientData(data) {
const clientName = this.clientName();
// Get the message string and trim new line characters
const message = data.toString().replace(/[\n\r]*$/, '');
if (this.config.debug) {
logger.info(`${clientName}: ${message}`);
}
// Authentication
if (!this.authed) {
if (message === `PASS ${this.config.password}`) {
logger.info(`${clientName} logged in.`);
this.socket.write('200\r\n'); // OK
this.authed = true;
} else {
this.socket.write('401\r\n'); // Unauthorized
}
return;
}
// Make sure the password is never exposed
if (message.startsWith('PASS')) {
logger.warn('Password was sent when already authed ...');
return;
}
// Emit data event
this.emit('data', message);
}
/**
* Client disconnected
*/
onClientDisconnected() {
logger.info(`Cleaning up client (${this.clientName()}).`);
this.socket.destroy();
this.socket = null;
this.authed = false;
}
/**
* Client name
*/
clientName() {
return 'UT';
}
}
export default TCPServer;
<file_sep># discord-reporter
UT99 Reporter Bot for [Discord](https://discordapp.com).
This is very WIP and far from finished, so use at your own risk.
## Installation
Node.js v6.x or newer is required.
Install dependencies using `npm install`.
```bash
npm install
npm run build
npm run start
```
Or `npm run serve` to start the bot while monitoring for changes (handy while developing).
## Configuration
Create a config.json that looks like this:
```json
{
"token": "DISCORD_BOT_TOKEN",
"channel": "CHANNEL_ID",
"password": "<PASSWORD>",
"port": 5000,
"prefix": "."
}
```
## TODO
All the things ...
## Contributions
I'm are open for suggestions. Please feel free to contribute or open a new issue to post your ideas.
|
bf9baa1d56d8b8bfa95cd06eb378f99f29596b9d
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
sn3p/discord-reporter
|
ea5785f330680d6b158210c108295f11f5a96ff0
|
d1fbc7d4e1799750ffb6a00cb2480e0b95e80f43
|
refs/heads/main
|
<repo_name>unusPanda/leetcode-java<file_sep>/子数组最大平均数I.java
public class 子数组最大平均数I {
// 需要整数相除得转类型
public static double findMaxAverage(int[] nums, int k) {
if (nums.length == 1) {
return nums[0];
}
int n = nums.length - k;
int[] tempK = new int[k];
for (int i = 0; i < k; i++) {
tempK[i] = nums[i];
}
int tempSum = 0;
for (int i : tempK) {
tempSum += i;
}
double tempAverage = (double) tempSum / k;
// double tempAverage = Arrays.stream(tempK).average().getAsDouble();
double result = tempAverage;
for (int i = 0; i < n; i++) {
tempAverage += (double) nums[i + k] / k - (double) nums[i] / k;
if (tempAverage > result) {
result = tempAverage;
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1, 12, -5, -6, 50, 3};
int b = 4;
findMaxAverage(a, b);
}
}
<file_sep>/二叉树的锯齿形层序遍历.java
import java.util.ArrayList;
import java.util.List;
public class 二叉树的锯齿形层序遍历 {
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> oneFloor = new ArrayList<>();
oneFloor.add(root.val);
result.add(oneFloor);
while (true){
List<Integer> eFloor = new ArrayList<>();
eFloor.add(root.right.val);
eFloor.add(root.left.val);
break;
}
return null;
}
private void leftProcess(TreeNode root , List<Integer> result){
if (root == null){
return;
}
result.add(root.val);
leftProcess(root.left ,result);
leftProcess(root.right,result);
}
private void rigthProcess(TreeNode root , List<Integer> result){
if (root == null){
return;
}
result.add(root.val);
rigthProcess(root.left ,result);
rigthProcess(root.right,result);
}
}
<file_sep>/距离顺序排列矩阵单元格.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class 距离顺序排列矩阵单元格 {
int R;
int C;
int length;
public static int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] result = new int[R*C][2];
int maxSize = Math.max(r0, R - 1 - r0) + Math.max(c0, C - 1 - c0);
List<List<int[]>> barrel = new ArrayList<>(maxSize+1);
for (int i = 0; i < maxSize; i++) {
barrel.add(new ArrayList<>());
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
int tempLength = countLength(R, C, r0, c0);
barrel.get(tempLength).add(new int[]{i,j});
}
}
for (int i = 0; i < R+C; i++) {
List<int[]> item = barrel.get(i);
for (int[] ints : item) {
}
}
return null;
}
private static int countLength(int R, int C, int r0, int c0){
return Math.abs(R - r0)+ Math.abs(C - c0);
}
public static void main(String[] args) {
allCellsDistOrder(3,4,1,3);
}
}
<file_sep>/Dota2参议院.java
import com.sun.source.doctree.LiteralTree;
import org.w3c.dom.ls.LSOutput;
import java.util.*;
public class Dota2参议院 {
public String predictPartyVictory(String senate) {
int sLength = senate.length();
Queue<Integer> rQueue = new LinkedList<>();
Queue<Integer> dQueue = new LinkedList<>();
for (int i = 0; i < senate.length(); i++) {
if (senate.charAt(i) == 'R') {
rQueue.offer(i);
}
else {
dQueue.offer(i);
}
}
while (true){
if (dQueue.isEmpty()) {
return "Radiant";
}
else if (rQueue.isEmpty()) {
return "Dire";
}
else {
if (dQueue.peek() < rQueue.peek()) {
rQueue.poll();
int tempD = dQueue.remove();
tempD += sLength;
dQueue.offer(tempD);
}else {
dQueue.poll();
int tempD = rQueue.remove();
tempD += sLength;
rQueue.offer(tempD);
}
}
}
}
public static void main(String[] args) {
Dota2参议院 a = new Dota2参议院();
System.out.println(a.predictPartyVictory("DR"));
}
}
<file_sep>/分发糖果.java
public class 分发糖果 {
// public int candy(int[] ratings) {
// if (ratings == null || ratings.length == 0) {
// return 0;
// }
// if (ratings.length == 1) {
// return 1;
// }
// int[] left = new int[ratings.length];
// int[] right = new int[ratings.length];
// for (int i = 1; i < ratings.length; i++) {
// if (ratings[i - 1] < ratings[i]) {
// left[i] = left[i - 1] + 1;
// }
// }
// for (int i = ratings.length - 2; i >= 0; i--) {
// if (ratings[i] > ratings[i + 1]) {
// right[i] = right[i + 1] + 1;
// }
// }
// int result = ratings.length;
// for (int i = 0; i < ratings.length; i++) {
// result += Math.max(left[i], right[i]);
// }
// return result;
// }
public static int candy(int[] ratings) {
if (ratings == null || ratings.length == 0)
return 0;
if (ratings.length == 1)
return 1;
int[] intS = new int[ratings.length];
// 从左往右迭代 两两元素对比 如果右边的分值大 就把右边的元素设置为左边元素+1
for (int i = 1; i < ratings.length; i++) {
if (ratings[i - 1] < ratings[i])
intS[i] = intS[i - 1] + 1;
}
// 从右往左迭代 两两元素对比 如果左边的分值大 而且左边的糖果少 就把左边的元素值设置为右元素+1
for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1])
if (intS[i] <= intS[i + 1])
intS[i] = intS[i + 1] + 1;
}
// 每个人最少一个糖果,再把多分的糖果加起来
int result = ratings.length;
for (int i = 0; i < ratings.length; i++)
result += intS[i];
return result;
}
public static void main(String[] args) {
int[] a = {1, 0, 2};
System.out.println(candy(a));
}
}
<file_sep>/单词规律.java
import java.util.HashMap;
import java.util.Map;
public class 单词规律 {
public static boolean wordPattern(String pattern, String s) {
char[] patternChars = pattern.toCharArray();
String[] sStrings = s.split(" ");
Map characterStringMap = new HashMap();
if (pattern.length() != sStrings.length) {
return false;
}
for (int i = 0; i < sStrings.length; i++) {
if (characterStringMap.containsKey(patternChars[i])) {
if (!characterStringMap.get(patternChars[i]).equals(sStrings[i]))
return false;
} else if (characterStringMap.containsKey(sStrings[i])) {
if (!characterStringMap.get(sStrings[i]).equals(patternChars[i]))
return false;
} else {
characterStringMap.put(patternChars[i], sStrings[i]);
characterStringMap.put(sStrings[i], patternChars[i]);
}
}
return true;
}
public static void main(String[] args) {
System.out.println(wordPattern("abba", "dog cat cat dog"));
}
}
<file_sep>/关于stream的效率问题.java
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class 关于stream的效率问题 {
public static void main(String[] args) {
// for (int j = 1; j < 10; j++) {
// int[] a = new int[(int) (1000 * Math.pow(10, j))];
//
// for (int i = 0; i < 1000 * j; i++) {
// a[i] = i;
// }
// Stopwatch stopwatch1 = new Stopwatch();
// int sum = 0;
// for (int i : a) {
// sum += i;
// }
// double res1 = (double) sum / a.length;
// System.out.println("stopwatch1 " + j + " " + stopwatch1.elapsedTime());
//
// Stopwatch stopwatch2 = new Stopwatch();
// double res2 = Arrays.stream(a).average().getAsDouble();
// System.out.println("stopwatch2 " + j + " " + stopwatch2.elapsedTime());
// }
// 1000的指数幂递增
// for (int j = 0; j < 10; j++) {
// List<Integer> a = new ArrayList<>();
//
// for (int i = 0; i < 1000 * Math.pow(10, j); i++) {
// a.add(i);
// }
// Stopwatch stopwatch1 = new Stopwatch();
// int sum = 0;
// for (int i : a) {
// sum += i;
// }
// double res1 = (double) sum / a.size();
//// System.out.println("stopwatch1 " + j + " " + stopwatch1.elapsedTime());
// double p = stopwatch1.elapsedTime();
// Stopwatch stopwatch2 = new Stopwatch();
// double res2 = a.stream().mapToLong(a::get).average().getAsDouble();
//// System.out.println("stopwatch2 " + j + " " + stopwatch2.elapsedTime());
// double k = stopwatch2.elapsedTime();
// a = null;
// System.out.println("流和for循环的时间差 " + j + " " + (k - p));
// 100000000 这个量级 加 10000000 递增
// for (int j = 0; j < 10; j++) {
// List<Integer> a = new ArrayList<>();
//
// for (int i = 0; i < 100000000 + (10000000 * j); i++) {
// a.add(i);
// }
// Stopwatch stopwatch1 = new Stopwatch();
// int sum = 0;
// for (int i : a) {
// sum += i;
// }
// double res1 = (double) sum / a.size();
//// System.out.println("stopwatch1 " + j + " " + stopwatch1.elapsedTime());
// double p = stopwatch1.elapsedTime();
// Stopwatch stopwatch2 = new Stopwatch();
// double res2 = a.stream().mapToLong(a::get).average().getAsDouble();
//// System.out.println("stopwatch2 " + j + " " + stopwatch2.elapsedTime());
// double k = stopwatch2.elapsedTime();
// a = null;
// System.out.println("流和for循环的时间差 " + j + " " + (k - p));
// }
// 100000000 这个量级恒定
// for (int j = 0; j < 100; j++) {
// List<Integer> a = new ArrayList<>();
//
// for (int i = 0; i < 100000000; i++) {
// a.add(i);
// }
// Stopwatch stopwatch1 = new Stopwatch();
// int sum = 0;
// for (int i : a) {
// sum += i;
// }
// double res1 = (double) sum / a.size();
// double p = stopwatch1.elapsedTime();
//
// Stopwatch stopwatch2 = new Stopwatch();
// double res2 = a.stream().mapToLong(a::get).average().getAsDouble();
//// System.out.println("stopwatch2 " + j + " " + stopwatch2.elapsedTime());
// double k = stopwatch2.elapsedTime();
//
// System.out.println("流和for循环的时间差 " + j + " " + (k - p));
//
// a = null;
// stopwatch1 = null;
// stopwatch2 = null;
// System.gc();
// }
// 数量级指数递增,每个量级算平均值
// for (int q = 0; q < 6; q++) {
// double n = 1000 * Math.pow(10, q);
// double[] temp = new double[100];
// for (int j = 0; j < 100; j++) {
// List<Integer> a = new ArrayList<>();
// for (int i = 0; i < n; i++) {
// a.add(i);
// }
//
// Stopwatch stopwatch1 = new Stopwatch();
// int sum = 0;
// for (int i : a) {
// sum += i;
// }
// double res1 = (double) sum / a.size();
// double p = stopwatch1.elapsedTime();
//
// Stopwatch stopwatch2 = new Stopwatch();
// double res2 = a.stream().mapToLong(a::get).average().getAsDouble();
// double k = stopwatch2.elapsedTime();
//
// temp[j] = k - p;
//
// }
// double average = Arrays.stream(temp).average().getAsDouble();
// System.out.println("数量级为1000 * 10^" + q + " 平均时间差为 " + average);
// }
System.out.println(LocalDateTime.now());
// 指数递增上限为4 重复次数为1000
for (int q = 0; q < 5; q++) {
double n = 1000 * Math.pow(10, q);
double[] temp = new double[10000];
for (int j = 0; j < 10000; j++) {
List<Integer> a = new ArrayList<>();
for (int i = 0; i < n; i++) {
a.add(i);
}
Stopwatch stopwatch1 = new Stopwatch();
int sum = 0;
for (int i : a) {
sum += i;
}
double res1 = (double) sum / a.size();
double p = stopwatch1.elapsedTime();
Stopwatch stopwatch2 = new Stopwatch();
double res2 = a.stream().mapToLong(a::get).average().getAsDouble();
double k = stopwatch2.elapsedTime();
temp[j] = k - p;
}
double average = Arrays.stream(temp).average().getAsDouble();
System.out.println("数量级为1000 * 10^" + q + " 平均时间差为 " + average);
}
System.out.println(LocalDateTime.now());
}
}
<file_sep>/README.md
# leetcode-java
用java写的leetcode题解 用于总结经验 以及日后复习
<file_sep>/分发饼干.java
import java.util.Arrays;
public class 分发饼干 {
// public static int findContentChildren(int[] g, int[] s) {
// Arrays.sort(g);
// Arrays.sort(s);
// int length = Math.min(g.length, s.length);
// int res = 0;
// for (int i = 0, j = 0; i < g.length && j < s.length; i++, j++) {
// while (j < s.length) {
// if (g[i] <= s[j]) {
// res++;
// break;
// } else {
// j++;
// }
// }
// }
// return res;
// }
public static int findContentChildren(int[] g, int[] s) {
if (g == null || s == null || g.length == 0 || s.length == 0) {
return 0;
}
Arrays.sort(g);
Arrays.sort(s);
int res = 0, i = 0, j = 0;
while (!(i < g.length || j < s.length)) {
while (j < s.length) {
if (g[i] <= s[j]) {
res++;
i++;
j++;
break;
} else {
j++;
}
}
}
return res;
}
public static void main(String[] args) {
int[] a = {1, 2, 3}, b = {3};
findContentChildren(a, b);
}
}
<file_sep>/单调递增的数字.java
import java.util.Arrays;
public class 单调递增的数字 {
public static int monotoneIncreasingDigits(int N) {
char[] chars = String.valueOf(N).toCharArray();
int i = 1;
while (i < chars.length && chars[i-1] <= chars[i]){
i++;
}
if (i < chars.length) {
while (i > 0 && chars[i - 1] > chars[i]) {
chars[i - 1] -= 1;
i -= 1;
}
for (i += 1; i < chars.length ; i++) {
chars[i] = '9';
}
}
return Integer.parseInt(new String(chars));
}
public static void main(String[] args) {
System.out.println( monotoneIncreasingDigits(332));
}
}
|
8a6aec9e27497b965d39eb2a347744caf4e96d28
|
[
"Markdown",
"Java"
] | 10
|
Java
|
unusPanda/leetcode-java
|
c67e034a296c07467f974ea4cd9fe6950bd84be1
|
f4e30439b2f346f43eb0fcd54068fa3f63f22571
|
refs/heads/master
|
<file_sep># bulletinboard
If you're a feeling down or need that extra push to achieve your dreams. Motivation Board web application lets you post 'wiseful' messages and see them. Don't procrastinate and start be motivated now!


# The Assignment
Bulletin Board Application Create a website that allows people to post messages to a page. A message consists of a title and a body. The site should have two pages:
The first page shows people a form where they can add a new message.
The second page shows each of the messages people have posted. Make sure there's a way to navigate the site so users can access each page.
Messages must be stored in a postgres database.
<file_sep>/*Bulletin Board Application Create a website that allows people to post messages to a page. A message consists of a title and a body. The site should have two pages:
The first page shows people a form where they can add a new message.
The second page shows each of the messages people have posted. Make sure there's a way to navigate the site so users can access each page.
Messages must be stored in a postgres database. Create a "messages" table with three columns: column name / column data type:
id: serial primary key
title: text
body: text*/
const fs = require('fs')
const express = require('express')
const pg = require ('pg')
const pug = require('pug')
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.set('views', './src/views');
app.set('view engine', 'pug');
var connectionString = 'postgres://' + process.env.POSTGRES_USER + ':' + process.env.POSTGRES_PASSWORD + '@localhost/bulletinboard';
// connection string. Anyone can use this app, no need for username and password.
const server = app.listen(8080, () => {
console.log('server has started at ', server.address().port)
}); // application is listens to the request. And everytime the browser goes to localhost:8080 it will print out "Server has started at".
// The first page shows people a form where they can add a new message.
app.get('/', (req, res) => {
res.render('index')
});
app.post('/', (req, res) => {
var title = req.body.title;
var body = req.body.message;
// the application will connect to the sql database
pg.connect(connectionString, function(err, client, done) {
client.query('insert into messages (title, body) values (\'' + title + '\', \'' + body +'\')', function(err) {
if(err) {
throw err;
}
}); // the database is connected. The values which are inserted in the form will be inserted to the SQL messages table.
done();
res.redirect('/bulletinboard'); // after submitting the page gets redirected to the bulletinboard
});
});
/*The second page shows each of the messages people have posted.
Make sure there's a way to navigate the site so users can access each page.*/
app.get('/bulletinboard', (req, res) => {
pg.connect(connectionString, function (err, client, done) {
client.query('select * from messages', function (err, result) {
if (err) {
throw err;
} // we request all the rows from table messages
var messages = result.rows; // table is assigned to variable messages.
res.render('messages', {messages: messages});
done();
pg.end();
});
});
});
|
3a4c1b313e3930a4770fc859f24f469b69d6086f
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
stewylam/bulletinboard
|
5f6f247eaaddfd806db0d619ceed4a88cdd7fab1
|
920e69351d1ec48ae5714311fbc974433cd10f6c
|
refs/heads/master
|
<repo_name>VictorSDelpiu/Sprint-Challenge-React-Wars<file_sep>/starwars/src/components/StarWarsList.js
import React from "react";
import styled from 'styled-components';
const StyledDiv = styled.div``;
const StyledP = styled.p`
opacity: 1
color: black;
font-weight: bold;
`;
const StyledSection = styled.section`
display: inline-block;
padding: 12rem;
background: lightblue;
width: 100px;
height: auto;
margin-bottom: 20px;
border: 2px dashed purple;
`;
const StyledHead = styled.h2`
font-size: 1.35rem;
max-width: 100%;
text-decoration: underline;
:hover {
color: blue;
}
`;
export function StarWarsList (props) {
return (
<StyledDiv className="App">
<StyledSection>
<StyledHead className="characterName">{props.charName}</StyledHead>
<StyledP>Height: {props.height}</StyledP>
<StyledP>{props.hair_color}</StyledP>
<StyledP>{props.gender}</StyledP>
</StyledSection>
</StyledDiv>
)
};
export default StarWarsList;
|
b92cc6c161a806d2ac17492d3c92455bbf1c51fe
|
[
"JavaScript"
] | 1
|
JavaScript
|
VictorSDelpiu/Sprint-Challenge-React-Wars
|
e93b529bb696adc3e49285c2342436f1402526c0
|
4fdac228c9969dd4fb70f669ab6a2918a8547d9e
|
refs/heads/master
|
<file_sep>'use strict';
/**
* @ngdoc overview
* @name passcardApp
* @description
* # passcardApp
*
* Main module of the application.
*/
angular
.module('passcardApp', []);
var downloadPDF, drawLine, drawRoundRect, format2c, generatePasscard, joinArray2d, joinNoSeparator, overwriteArray2d, overwritePasswordArray, pwchars, random, randomChar, randomCharArray, randomCharArray2d;
sjcl.random.addEventListener("progress", function(progress) {
return $("#seedProgressBar").css("width", "" + (100.0 * progress));
});
random = function(min, max) {
return min + (Math.abs(sjcl.random.randomWords(1)[0]) % (max - min + 1));
};
pwchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!§$%&/()#*.-+=';
randomChar = function() {
return pwchars[random(0, pwchars.length - 1)];
};
randomCharArray = function(length) {
var i, j, ref, results;
results = [];
for (i = j = 1, ref = length; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
results.push(randomChar());
}
return results;
};
randomCharArray2d = function(xLength, yLength) {
var i, j, ref, results;
results = [];
for (i = j = 1, ref = xLength; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
results.push(randomCharArray(yLength));
}
return results;
};
joinNoSeparator = function(array) {
var elem, j, len, ret;
ret = "";
for (j = 0, len = array.length; j < len; j++) {
elem = array[j];
ret += elem;
}
return ret;
};
joinArray2d = function(array) {
var inner;
return joinNoSeparator((function() {
var j, len, results;
results = [];
for (j = 0, len = array.length; j < len; j++) {
inner = array[j];
results.push(joinNoSeparator(inner));
}
return results;
})());
};
overwritePasswordArray = function(array) {
var elem, inner, j, len, results;
results = [];
for (j = 0, len = array.length; j < len; j++) {
inner = array[j];
results.push(elem = randomChar());
}
return results;
};
overwriteArray2d = function(array) {
var inner, j, len, results;
results = [];
for (j = 0, len = array.length; j < len; j++) {
inner = array[j];
results.push(overwritePasswordArray(inner));
}
return results;
};
drawRoundRect = function(ctx, x, y, width, height, options) {
var bottomLeftRound, bottomRightRound, fill, oldFillStyle, oldStroke, radius, stroke, topLeftRound, topRightRound;
if (options == null) {
options = {};
}
if (typeof options !== "object") {
throw "Options must be an object";
}
radius = options.radius != null ? options.radius : 5;
stroke = options.stroke != null ? options.stroke : true;
fill = options.fill != null ? options.fill : false;
topLeftRound = options.topLeftRound != null ? options.topLeftRound : true;
topRightRound = options.topRightRound != null ? options.topRightRound : true;
bottomLeftRound = options.bottomLeftRound != null ? options.bottomLeftRound : true;
bottomRightRound = options.bottomRightRound != null ? options.bottomRightRound : true;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
if (topRightRound) {
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
} else {
ctx.lineTo(x + width, y);
ctx.lineTo(x + width, y + radius);
}
ctx.lineTo(x + width, y + height - radius);
if (bottomRightRound) {
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
} else {
ctx.lineTo(x + width, y + height);
ctx.lineTo(x + width - radius, y + height);
}
ctx.lineTo(x + radius, y + height);
if (bottomLeftRound) {
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
} else {
ctx.lineTo(x, y + height);
ctx.lineTo(x, y + height - radius);
}
ctx.lineTo(x, y + radius);
if (topLeftRound) {
ctx.quadraticCurveTo(x, y, x + radius, y);
} else {
ctx.lineTo(x, y + height);
ctx.lineTo(x, y + height - radius);
}
ctx.closePath();
oldStroke = ctx.strokeStyle;
if (typeof stroke === "string") {
ctx.strokeStyle = stroke;
}
if (stroke) {
ctx.stroke();
}
if (typeof stroke === "string") {
ctx.strokeStyle = oldStroke;
}
oldFillStyle = ctx.fillStyle;
if (typeof fill === "string") {
ctx.fillStyle = fill;
}
if (fill) {
ctx.fill();
}
if (typeof fill === "string") {
return ctx.fillStyle = oldFillStyle;
}
};
drawLine = function(ctx, x, y, toX, toY, color) {
var oldStroke;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(toX, toY);
ctx.closePath();
oldStroke = ctx.strokeStyle;
if (typeof color === "string") {
ctx.strokeStyle = color;
}
ctx.stroke();
if (typeof color === "string") {
return ctx.strokeStyle = oldStroke;
}
};
format2c = function(d) {
if (d < 10) {
return " " + d.toString();
} else {
return "" + d.toString();
}
};
downloadPDF = function(instancesPerPage, imageData) {
var colspacing, height, offsetX, offsetY, pdf, rowspacing, width;
if (instancesPerPage <= 0) {
throw "instancesPerPage must be > 0";
}
pdf = new jsPDF();
width = 90;
height = 45;
offsetX = 10;
offsetY = 10;
rowspacing = 15;
colspacing = 15;
pdf.addImage(imageData, 'JPEG', offsetX, offsetY, width, height);
if (instancesPerPage >= 2) {
pdf.addImage(imageData, 'JPEG', offsetX, offsetY + height + rowspacing, width, height);
}
if (instancesPerPage >= 3) {
pdf.addImage(imageData, 'JPEG', offsetX, offsetY + 2 * (height + rowspacing), width, height);
}
if (instancesPerPage >= 4) {
pdf.addImage(imageData, 'JPEG', offsetX, offsetY + 3 * (height + rowspacing), width, height);
}
return pdf.save("Passcard.pdf");
};
generatePasscard = function() {
var canvas, col, colWidth, ctx, hashFont, hashLabel, hashLabelFont, hideHash, hr, hseparatorIndices, j, k, l, leftHeaderFont, lineX, lineY, numCols, numRows, offsetX, offsetY, passwordFont, passwordHash, passwords, pwbody, ref, ref1, ref2, row, rowHeight, scaleFactor, styleColor, topHeaderFont, vseparatorIndices, x, y;
$("#progressBarRow").css("display", "none");
hr = $("#headerRow");
pwbody = $("#pwtablebody");
canvas = document.getElementById('targetCanvas');
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FFF";
ctx.fillRect(0, 0, canvas.width, canvas.height);
scaleFactor = 2.4;
ctx.scale(scaleFactor, scaleFactor);
vseparatorIndices = [4, 10, 15, 21];
hseparatorIndices = [3, 6, 9, 12];
rowHeight = 16;
colWidth = 18;
numRows = 13;
numCols = 26;
offsetX = -2;
offsetY = 15;
hideHash = false;
passwords = randomCharArray2d(numRows, numCols);
passwordHash = sjcl.codec.base64.fromBits(sjcl.hash.sha256.hash(joinArray2d(passwords)));
topHeaderFont = 'bold 12pt monospace';
leftHeaderFont = 'bold 12pt monospace';
passwordFont = '<PASSWORD>';
hashLabelFont = 'normal 10pt monospace';
hashFont = 'italic 10pt monospace';
styleColor = "#3200ff";
drawRoundRect(ctx, offsetX + 2 * colWidth - 4, offsetY - 14, numCols * colWidth - 2, rowHeight, {
fill: styleColor,
stroke: styleColor,
bottomLeftRound: false,
bottomRightRound: false
});
ctx.font = topHeaderFont;
ctx.fillStyle = '#FFF';
for (col = j = 1, ref = numCols; 1 <= ref ? j <= ref : j >= ref; col = 1 <= ref ? ++j : --j) {
x = offsetX + ((col + 1) * colWidth);
y = offsetY;
ctx.fillText(String.fromCharCode(64 + col), x, y);
if (vseparatorIndices.indexOf(col) !== -1) {
x = x + colWidth - 4;
drawLine(ctx, x, y, x, y + (numRows * rowHeight), styleColor);
}
}
for (row = k = 1, ref1 = numRows; 1 <= ref1 ? k <= ref1 : k >= ref1; row = 1 <= ref1 ? ++k : --k) {
ctx.fillStyle = '#FFF';
x = offsetX;
y = offsetY + (row * rowHeight);
ctx.font = leftHeaderFont;
drawRoundRect(ctx, x + 0.5 * colWidth - 2, y - rowHeight + 3, 1.2 * colWidth, 0.85 * rowHeight, {
fill: styleColor,
stroke: styleColor,
bottomRightRound: false,
topRightRound: false
});
ctx.fillText(format2c(row), x + 0.5 * colWidth, y);
ctx.font = passwordFont;
ctx.fillStyle = '#000';
if (vseparatorIndices.indexOf(row) !== -1) {
lineX = offsetX + 2 * colWidth - 6;
lineY = offsetY + ((row - 1) * rowHeight) + 2;
drawLine(ctx, lineX, lineY, lineX + (numCols * colWidth), lineY, styleColor);
}
for (col = l = 1, ref2 = numCols; 1 <= ref2 ? l <= ref2 : l >= ref2; col = 1 <= ref2 ? ++l : --l) {
x = offsetX + ((col + 1) * colWidth);
ctx.fillText(passwords[row - 1][col - 1], x, y);
}
}
if (!hideHash) {
ctx.fillStyle = styleColor;
x = offsetX + 3 * colWidth;
y = offsetY + ((1 + numRows) * rowHeight) + 5;
ctx.font = hashLabelFont;
hashLabel = "SHA256:";
ctx.fillText(hashLabel, x, y);
ctx.fillStyle = "#000";
ctx.font = hashFont;
ctx.fillText(passwordHash, x + 60, y);
}
overwriteArray2d(passwords);
$("a#downloadImgLink").attr("href", canvas.toDataURL("image/png"));
$("a#downloadPDF1Link").click(function() {
return downloadPDF(1, canvas.toDataURL("image/jpeg"));
});
$("a#downloadPDF2Link").click(function() {
return downloadPDF(2, canvas.toDataURL("image/jpeg"));
});
$("a#downloadPDF3Link").click(function() {
return downloadPDF(3, canvas.toDataURL("image/jpeg"));
});
return $("a#downloadPDF4Link").click(function() {
return downloadPDF(4, canvas.toDataURL("image/jpeg"));
});
};
sjcl.random.addEventListener("seeded", generatePasscard);
if (sjcl.random.isReady()) {
generatePasscard();
}
sjcl.random.startCollectors();
// ---
// generated by coffee-script 1.9.2<file_sep># Passcard
Create shareable, secure password cards that you can carry around.
|
d6463057a4723c549bc12a3a47b032bea81b3e3a
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
ulikoehler/Passcard
|
92b1bd5519e677b5198e261afc76e352726a95f8
|
de6f515f393ea018a91f0215e5c2895c0e71bc3c
|
refs/heads/master
|
<repo_name>DreamerWay/Sort<file_sep>/ComparisonSort/BubbleSort/BubbleSort.cpp
/*******************************************************************************
*
* FileName : BubbleSort.cpp
* Comment : 冒泡排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/04
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void BubbleSort_1(int array[],int len)
{
int i=0,j=0;
int tmp=0;
for(i=0;i<len;i++)
for(j=1;j<len-i;j++) //注意len-i,每一趟将最大值滚到最右边
{
if(array[j-1]>array[j])
{
tmp=array[j-1];
array[j-1]=array[j];
array[j]=tmp;
}
}
}
void BubbleSort_2(int array[],int len)
{
int i=0,j=0;
int tmp=0;
int flag=false; //添加flag,主要是为了防止出现已经都有序情况下算法还去做无用功
for(i=0;i<len;i++)
{
for(j=1;j<len-i;j++)
{
if(array[j-1]>array[j])
{
tmp=array[j-1];
array[j-1]=array[j];
array[j]=tmp;
flag=true;
}
}
if(flag==false)
break;
}
}
void BubbleSort_3(int array[],int len)
{
int i=0,j=0;
int tmp=0;
int true_len=len;
//该实现方法主要是考虑这样一种情况
//如果数组靠右边的一部分已经有序,只需要找到最后无序的位置,第二遍遍历到这个位置即可
while(true_len>0)
{
i=true_len;
true_len=0;
for(j=1;j<i;j++)
{
if(array[j-1]>array[j])
{
tmp=array[j-1];
array[j-1]=array[j];
array[j]=tmp;
true_len=j;
}
}
}
}
//上边冒泡排序算法需要在每次遍历的时候进行很多次交换操作,影响效率
//进行一趟遍历的最终目的是找出最大的那个数并放到最右边的位置
//我们可以在遍历的时候用一个“指针”始终指向最大值位置,一趟遍历结束后
//再进行一次交换,将最大值换到最右边,这事实上就是选择排序
void SelectSort(int array[],int len)
{
int i=0,j=0;
int tmp=0;
int p_max=0;
for(i=0;i<len;i++)
{
p_max=len-i-1;
for(j=0;j<len-i-1;j++)
{
if(array[j]>array[p_max])
p_max=j;
}
if(p_max!=len-i-1)
{
tmp=array[p_max];
array[p_max]=array[len-i-1];
array[len-i-1]=tmp;
}
}
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
BubbleSort_1(test1,10);
Print(test1,10);
int test2[10]={0};
srand((unsigned)time(NULL)+1);
for(i = 0; i < 10;i++ )
test2[i]=rand()%20;
Print(test2,10);
BubbleSort_2(test2,10);
Print(test2,10);
int test3[10]={0};
srand((unsigned)time(NULL)+2);
for(i = 0; i < 10;i++ )
test3[i]=rand()%20;
Print(test3,10);
BubbleSort_3(test3,10);
Print(test3,10);
int test4[10]={0};
srand((unsigned)time(NULL)+3);
for(i = 0; i < 10;i++ )
test4[i]=rand()%20;
Print(test4,10);
SelectSort(test4,10);
Print(test4,10);
return 0;
}<file_sep>/ComparisonSort/QuickSort/QuickSort.cpp
/*******************************************************************************
*
* FileName : QuickSort.cpp
* Comment : 三种方法实现快速排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/03
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//方法1采用最出名的双向填坑方法,以第一个元素为“主元”将数组分割,然后递归排序
void QuickSort_1(int array[],int l,int r)
{
if(l<r)
{
int i=l,j=r;
int v=array[l];
while (i<j)
{
//从右到左
while(j>i && array[j]>= v)
j--;
if(j>i)
array[i++]=array[j];
//从左到右
while(i<j && array[i]<v)
i++;
if(i<j)
array[j--]=array[i];
}
array[i]=v; // 注意不要忘了这一行
//递归排序分割后的左右子数组
if(i-1>l)
QuickSort_1(array,l,i-1);
if(i+1<r)
QuickSort_1(array,i+1,r);
}
}
//方法2采用单向循环的方法,以最后一个元素为“主元”
void QuickSort_2(int array[],int l,int r)
{
if(l<r)
{
int i=l-1,j=l; //注意i的初始值为l-1
int v=array[r];
int tmp=0;
//从左到右遍历数组进行分割
for(j=l;j<r;j++)
{
if(array[j]<=v)
{
i++;
tmp=array[i];
array[i]=array[j];
array[j]=tmp;
}
}
//将“主元”换到中间位置达到分割目的
i++;
tmp=array[i];
array[i]=array[r];
array[r]=tmp;
//递归调用
if(i-1>l)
QuickSort_2(array,l,i-1);
if(i+1<r)
QuickSort_2(array,i+1,r);
}
}
//方法3采用三数取中方法,先将左中右三个位置中按大小处于中间位置的元素
//换到最左边,以这个中间大小的元素值为“主元”,这种方法主要是考虑“主元”
//对排序效率的影响
void QuickSort_3(int array[],int l,int r)
{
if(l<r)
{
int m=(l+r)/2;
int tmp=0;
//下边的3个if功能就是取出中间大小的元素放到最左边
if(array[l]<array[m])
{
tmp=array[l];
array[l]=array[m];
array[m]=tmp;
}
if(array[r]<array[m])
{
tmp=array[r];
array[r]=array[m];
array[m]=tmp;
}
if(array[r]<array[l])
{
tmp=array[r];
array[r]=array[l];
array[l]=tmp;
}
//以新的最左边的元素作为“主元”
int i=l,j=r;
int v=array[l];
while(i<j)
{
while(j>i && array[j]>=v)
j--;
if(j>i)
array[i++]=array[j];
while(i<j && array[i]<v)
i++;
if(i<j)
array[j--]=array[i];
}
array[i]=v;
if(i-1>l)
QuickSort_3(array,l,i-1);
if(i+1<r)
QuickSort_3(array,i+1,r);
}
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
QuickSort_1(test1,0,9);
Print(test1,10);
int test2[10]={0};
srand((unsigned)time(NULL)+1);
for(i = 0; i < 10;i++ )
test2[i]=rand()%20;
Print(test2,10);
QuickSort_2(test2,0,9);
Print(test2,10);
int test3[10]={0};
srand((unsigned)time(NULL)+2);
for(i = 0; i < 10;i++ )
test3[i]=rand()%20;
Print(test3,10);
QuickSort_3(test3,0,9);
Print(test3,10);
return 0;
}
<file_sep>/ComparisonSort/MergeSort/MergeSort.cpp
/*******************************************************************************
*
* FileName : MergeSort.cpp
* Comment : 归并排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/05
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//归并排序的核心思想是将原始数组一分为二,如果这两个排序好之后,将其有序合并则原始
//数组排序完成,这个过程递归执行,将原始数组不断分割,最终完成排序
//在其他的实现方法中merge()合并有序数列时分配临时数组,但是过多的new操作会非常费时
//下边的实现方法在MergeSort()中new一个临时数组,后面的操作都共用这一个临时数组
void merge(int array[],int l,int mid,int r,int tmp[])
{
int i=l,j=mid+1;
int k=0;
while(i<=mid && j<=r)
{
if(array[i]<array[j])
tmp[k++]=array[i++];
else
tmp[k++]=array[j++];
}
while(i<=mid)
tmp[k++]=array[i++];
while(j<=r)
tmp[k++]=array[j++];
//将tmp中排序好的元素放到原来元素在数组中的对应位置
for(i=0;i<k;i++)
{
array[l+i]=tmp[i];
}
}
void mergesort(int array[],int l,int r,int tmp[])
{
if(l>=r) return;
int mid=(l+r)/2;
mergesort(array,l,mid,tmp);
mergesort(array,mid+1,r,tmp);
merge(array,l,mid,r,tmp);
}
void MergeSort(int array[],int len)
{
int *p=new int[len];
mergesort(array,0,len-1,p);
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
MergeSort(test1,10);
Print(test1,10);
return 0;
}
<file_sep>/UncomparisonSort/RadixSort/RadixSort.cpp
/*******************************************************************************
*
* FileName : RadixSort.cpp
* Comment : 基数排序(低位版)
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/09
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//基数排序思想见:http://www.cnblogs.com/sun/archive/2008/06/26/1230095.html
//计算数组中元素最大位数
int MaxBit(int array[],int len)
{
int d=1;
int* p_tmp=new int[len];
for(int i=0;i<len;i++)
{
p_tmp[i]=array[i];
}
for(i=0;i<len;i++)
{
int p=1;
while(p_tmp[i]/10 != 0)
{
p++;
p_tmp[i]/=10;
}
if(p>d)
d=p;
}
delete [] p_tmp;
return d;
}
//
void RadixSort(int array[],int len)
{
int maxbit=MaxBit(array,len);
int* p_countArray=new int[10]; //每一位范围为0~9,所以大小为10
int* p_sortArray=new int[len]; //保存某一遍排好序的元素
int i=0,j=0,k=0;
int radix=1;
//内部包含一个CountingSort过程
for(i=0;i<maxbit;i++)
{
for(j=0;j<10;j++)
p_countArray[j]=0;
for(j=0;j<len;j++)
{
k=(array[j]/radix)%10;
p_countArray[k]++;
}
for(j=1;j<10;j++)
p_countArray[j]+=p_countArray[j-1];
for(j=len-1;j>=0;j--)
{
k=(array[j]/radix)%10;
p_countArray[k]--;
p_sortArray[p_countArray[k]]=array[j];
}
//将一趟排好序的数组复制回原数组
for(j=0;j<len;j++)
array[j]=p_sortArray[j];
radix*=10; //扩大十倍从而取更高位数字并排序
}
delete [] p_countArray;
delete [] p_sortArray;
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
RadixSort(test1,10);
Print(test1,10);
return 0;
}<file_sep>/UncomparisonSort/CountingSort/CountingSort.cpp
/*******************************************************************************
*
* FileName : CountingSort
* Comment : 计数排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/06
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//计数排序的思想见:http://www.cnblogs.com/developerY/p/3166462.html
const int MAX_VALUE=20; //待排序数组中元素值范围限定为0~20
void CountingSort(int array[],int len)
{
int count_len=MAX_VALUE+1;
int * p_countArray=new int[count_len]; //新申请一个数组,大小为元素(最大值+1)
for(int i=0;i<count_len;i++) //将新申请的数组各个元素初始化为0
p_countArray[i]=0;
for(i=0;i<len;i++) //将待排序数组中的元素放入到新数组中,按照元素值等价为位置的原则
{
p_countArray[array[i]]++;
}
for(i=1;i<count_len;i++) //确定不比该位置上数据大的数据个数=该位置值加上前一位置值
p_countArray[i]+=p_countArray[i-1];
int* p_sortArray=new int[len]; //新申请一个临时存放已排序好的元素的数组
for(i=len-1;i>=0;i--) //倒序遍历是为了保证稳定性
{
p_countArray[array[i]]--; //减一的原因是在p_sortArray中从0位置开始存放元素,保持与原来数组一致
p_sortArray[p_countArray[array[i]]]=array[i];
}
for(i=0;i<len;i++) //将排序完成后的数组复制回原数组
array[i]=p_sortArray[i];
//释放新申请的空间
delete [] p_countArray;
delete [] p_sortArray;
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
CountingSort(test1,10);
Print(test1,10);
return 0;
}
<file_sep>/UncomparisonSort/BucketSort/BucketSort.cpp
/*******************************************************************************
*
* FileName : BucketSort.cpp
* Comment : 桶排序(下边的实现是最简单的一种方法,各个元素不同,一个桶只有一个元素)
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/09
*
*******************************************************************************/
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
//桶排序原理见:http://hxraid.iteye.com/blog/647759
void BucketSort(int array[],int len)
{
int bucket_num=len;
int* p_bucketArray=new int[bucket_num];
for(int i=0;i<bucket_num;i++) //初始化bucket元素值为-1
p_bucketArray[i]=-1;
for(i=0;i<len;i++)
p_bucketArray[array[i]]=array[i];
int j=0;
for(i=0;i<bucket_num;i++)
{
if(p_bucketArray[i]!=-1)
{
if(j<len)
{
array[j]=p_bucketArray[i];
j++;
}
}
}
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={9,7,0,2,5,4,1,6,8,3};
Print(test1,10);
BucketSort(test1,10);
Print(test1,10);
return 0;
}<file_sep>/ComparisonSort/InsertSort/InsertSort.cpp
/*******************************************************************************
*
* FileName : InsertSort.cpp
* Comment : 插入排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/05
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//插入排序思想:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的子序列中的适当
//位置,直到全部记录插入完成为止
void InsertSort_1(int array[],int len)
{
int i=0,j=0;
int v=0;
//循环从数组第二个元素开始,因为array[0]作为最初已排序部分
for(i=1;i<len;i++)
{
v=array[i]; //v为待排序的元素
//将v与已排序元素从大到小比较,寻找v应插入的位置
for(j=i-1;j>=0;j--)
{
if(array[j]>v)
array[j+1]=array[j];
else
break;
}
array[j+1]=v;
}
}
//该实现方法在寻找插入位置的过程中,顺便用交换操作将待排序元素交换
//到待插入的位置
void InsertSort_2(int array[],int len)
{
int i=0,j=0;
int v=0;
int tmp=0;
for(i=1;i<len;i++)
{
v=array[i];
for(j=i-1;j>=0;j--)
{
if(array[j]>v)
{
tmp=array[j];
array[j]=array[j+1];
array[j+1]=tmp;
}
}
}
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
InsertSort_1(test1,10);
Print(test1,10);
int test2[10]={0};
srand((unsigned)time(NULL)+1);
for(i = 0; i < 10;i++ )
test2[i]=rand()%20;
Print(test2,10);
InsertSort_2(test2,10);
Print(test2,10);
return 0;
}
<file_sep>/ComparisonSort/HeapSort/HeapSort.cpp
/*******************************************************************************
*
* FileName : HeapSort.cpp
* Comment : 堆排序
* Version : 1.0
* Author : <EMAIL>
* Date : 2014/06/06
*
*******************************************************************************/
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
//下边的交换函数采用的是不用额外数据交换两个数
void Swap(int &a, int &b)
{
if (a != b) //这个判断主要是防止当a==b时结果使a与b都为0
{
a ^= b;
b ^= a;
a ^= b;
}
}
//从position位置上元素开始调整,使其满足大顶堆,递归调整左右子节点
void Adjust(int array[],int position,int len)
{
int i=position;
int max_position;
while(i<=(len-2)/2)
{
max_position=2*i+1;
if((max_position+1)<len && array[max_position+1]>array[max_position])
max_position+=1;
if(array[i]<array[max_position])
{
Swap(array[i],array[max_position]);
i=max_position;
}
else
break; //这个break很重要,不要把上边i=max_position放到if外边
}
}
void HeapSort(int array[],int len)
{
int k=0;
//只需要建len-1次大顶堆,将堆顶的最大值不断交换到后边的len-1位置完成排序
for(int i=0;i<len-1;i++)
{
k=len-1-i;//k代表建好大顶堆后需要交换的最新位置
for(int j=(k-1)/2;j>=0;j--)
Adjust(array,j,k+1);
Swap(array[0],array[k]);
}
}
void Print(int array[],int length)
{
//print the array in the form:1->2->3->0
for(int i=0;i<length;i++)
{
if(i<length-1)
cout<<array[i]<<"->";
else
cout<<array[i]<<endl;
}
}
int main()
{
int test1[10]={0};
srand((unsigned)time(NULL));
for(int i = 0; i < 10;i++ )
test1[i]=rand()%20;
Print(test1,10);
HeapSort(test1,10);
Print(test1,10);
return 0;
}
<file_sep>/README.md
Sort
====
The basic sort algorithm include the ComparisonSort and UncomparisonSort
|
fc5e7ba7a66824541c5dd92cb568d9c2c72ba86a
|
[
"Markdown",
"C++"
] | 9
|
C++
|
DreamerWay/Sort
|
e7035eaec71e4c18c9fcb6c98fba66bbeb878974
|
c3dd0ab849b1c5436541f7546896936202650bcc
|
refs/heads/master
|
<repo_name>saidev-t-rajan/flickr-photo-search<file_sep>/spec/models/flickr_spec.rb
require 'rails_helper'
describe Flickr do
response_hash = {"rsp"=>{ "stat"=>"ok",
"photos"=>{ "page"=>"1",
"pages"=>"240680",
"perpage"=>"100",
"total"=>"24067966",
"photo"=>[{ "id"=>"1",
"owner"=>"2",
"secret"=>"3",
"server"=>"4",
"farm"=>"5",
"title"=>"First Photo",
"ispublic"=>"1",
"isfriend"=>"0",
"isfamily"=>"0"},
{ "id"=>"2",
"owner"=>"3",
"secret"=>"4",
"server"=>"5",
"farm"=>"6",
"title"=>"Second Photo",
"ispublic"=>"1",
"isfriend"=>"0",
"isfamily"=>"0"}]}}}
response_hash_no_photos = {"rsp"=>{"stat"=>"ok", "photos"=>{"page"=>"1", "pages"=>"0", "perpage"=>"100", "total"=>"0"}}}
response_hash_fail = {"rsp"=>{"stat"=>"fail", "err"=>{"code"=>"100", "msg"=>"Error message from flickr"}}}
before do
@flickr = Flickr.new
end
describe 'search' do
it 'should generate the correct search uri' do
allow(@flickr).to receive_messages(response_hash: response_hash)
@flickr.search "some free text"
expect(@flickr.uri.to_s).to eq("https://api.flickr.com/services/rest/?api_key=#{FLICKR_API_KEY}&method=flickr.photos.search&text=some%20free%20text")
end
it 'should return a array of photos if succesful' do
allow(@flickr).to receive_messages(response_hash: response_hash)
photos = @flickr.search "some free text"
expect(@flickr.error).to be_nil
expect(photos.all? {|photo| photo.class.name == 'Photo'}).to be true
end
it 'should return a empty array if unsuccesful and set error' do
allow(@flickr).to receive_messages(response_hash: nil)
photos = @flickr.search "some free text"
expect(@flickr.error).to eq("Something went wrong, please try again")
expect(photos).to be_empty
end
it 'should return a empty array if status fail in response and set error returned by flickr api' do
allow(@flickr).to receive_messages(response_hash: response_hash_fail)
photos = @flickr.search "some free text"
expect(@flickr.error).to eq("Error message from flickr")
expect(photos).to be_empty
end
it 'should return a empty array if no photos are returned and set error message' do
allow(@flickr).to receive_messages(response_hash: response_hash_no_photos)
photos = @flickr.search "some free text"
expect(@flickr.error).to eq("There are no photos that match your search")
expect(photos).to be_empty
end
end
end
<file_sep>/app/models/flickr.rb
class Flickr
attr_accessor :error, :uri
def search( free_text )
# Refer https://www.flickr.com/services/api/flickr.photos.search.html for uri generation
@uri = URI(URI.encode("https://api.flickr.com/services/rest/?api_key=#{FLICKR_API_KEY}&method=flickr.photos.search&text=#{free_text}"))
if response_hash
if response_hash['rsp']['stat'] == 'ok'
if response_hash['rsp']['photos']['photo']
return response_hash['rsp']['photos']['photo'].map{ |photo| Photo.new(photo) }
else
self.error = "There are no photos that match your search"
end
elsif response_hash['rsp']['stat'] == 'fail'
self.error = response_hash['rsp']['err']['msg']
end
else
self.error = "Something went wrong, please try again"
end
[]
end
def response_hash
Hash.from_xml( Net::HTTP.get(uri) )
end
end
<file_sep>/spec/features/photos_spec.rb
require 'rails_helper'
describe "Photos page" do
it "should have search box" do
visit root_path
expect(page).to have_content('Search Flickr for photos')
expect(page).to have_css('input[type="text"]')
expect(page).to have_css('input[type="submit"]')
end
it "should show 12 photos when searched" do
visit root_path
fill_in 'search', with: "lake"
click_button "Search"
expect(page).to have_selector('.thumbnail', count: 12)
expect(page.first('.thumbnail')).to have_xpath("//img")
end
it "should have pagination" do
visit root_path
fill_in 'search', with: "lake"
click_button "Search"
expect(page).to have_selector('div.pagination')
end
it "should set modal src to larger image url when thumbnail is clicked on", :js do
visit root_path
fill_in 'search', with: "lake"
click_button "Search"
first("img").click
expect(first(".thumbnail")['data-imgpath']).to eq(find(".modal-dialog").find("img")['src'])
end
end<file_sep>/config/initializers/flickr_keys.rb
FLICKR_API_KEY = Rails.env.production? ? ENV['FLICKR_API_KEY'] : FLICKR_API_KEY_DEVELOPMENT<file_sep>/spec/models/photo_spec.rb
require 'rails_helper'
describe Photo do
before do
@photo = Photo.new({'id' => '1', 'secret' => '2', 'server' => '3', 'farm' => '4'})
end
it "should respond to 'id'" do
expect(@photo).to respond_to(:id)
end
it "should respond to 'secret'" do
expect(@photo).to respond_to(:secret)
end
it "should respond to 'server'" do
expect(@photo).to respond_to(:server)
end
it "should respond to 'farm'" do
expect(@photo).to respond_to(:farm)
end
it "should generate the correct small url for photo" do
expect(@photo.url_small).to eq("https://farm4.staticflickr.com/3/1_2_q.jpg")
end
it "should generate the correct large url for photo" do
expect(@photo.url_large).to eq("https://farm4.staticflickr.com/3/1_2_c.jpg")
end
end
<file_sep>/spec/controllers/photos_controller_spec.rb
require 'rails_helper'
describe PhotosController do
response_hash = {"rsp"=>{ "stat"=>"ok",
"photos"=>{ "page"=>"1",
"pages"=>"240680",
"perpage"=>"100",
"total"=>"24067966",
"photo"=>[{ "id"=>"1",
"owner"=>"2",
"secret"=>"3",
"server"=>"4",
"farm"=>"5",
"title"=>"First Photo",
"ispublic"=>"1",
"isfriend"=>"0",
"isfamily"=>"0"},
{ "id"=>"2",
"owner"=>"3",
"secret"=>"4",
"server"=>"5",
"farm"=>"6",
"title"=>"Second Photo",
"ispublic"=>"1",
"isfriend"=>"0",
"isfamily"=>"0"}]}}}
describe 'GET search' do
it 'should return a array of posts' do
Flickr.any_instance.stub(:response_hash).and_return(response_hash)
get :search, search: 'Some free text'
expect(assigns(:photos).all? {|photo| photo.class.name == 'Photo'}).to be true
end
end
describe 'GET index' do
it 'should have a 200 status response' do
get :index
expect(response.status).to eq(200)
end
end
end
<file_sep>/app/assets/javascripts/photos.js
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function() {
$('a.thumbnail').click(function(e) {
e.preventDefault();
var imgPath = $(this).data('imgpath');
$('#photo-modal img').attr('src', imgPath);
$("#photo-modal").modal('show');
});
$('img').on('click', function() {
$("#photo-modal").modal('hide')
});
});<file_sep>/app/models/photo.rb
class Photo
attr_reader :id, :secret, :server, :farm
def initialize( attributes = {} )
@id = attributes['id']
@secret = attributes['secret']
@server = attributes['server']
@farm = attributes['farm']
end
# Refer https://www.flickr.com/services/api/misc.urls.html for url generation
def url_small
"https://farm#{farm}.staticflickr.com/#{server}/#{id}_#{secret}_q.jpg"
end
def url_large
"https://farm#{farm}.staticflickr.com/#{server}/#{id}_#{secret}_c.jpg"
end
end
<file_sep>/app/controllers/photos_controller.rb
class PhotosController < ApplicationController
def index
end
def search
if session[:searched].blank? || session[:searched][:search] != params[:search]
flickr = Flickr.new
session[:searched] = { search: params[:search], photos: flickr.search(params[:search]) }
end
@photos = session[:searched][:photos].paginate(page: params[:page], per_page: 12)
flash.now[:error] = flickr.error if flickr && flickr.error
render :index
end
end
|
1ec442b2992ec4a27d88f319497704d33d8fa0a7
|
[
"JavaScript",
"Ruby"
] | 9
|
Ruby
|
saidev-t-rajan/flickr-photo-search
|
8ed914159a7957c8a24620f92fe9f4bcddd3f6dc
|
4f61daef067d55d178c0c95824d828463806a786
|
refs/heads/main
|
<file_sep>import React, { Component } from 'react';
import { Grid, Cell } from 'react-mdl';
import Education from './education';
import Experience from './experience';
import Skills from './skills';
class Resume extends Component {
render() {
return(
<div>
<Grid>
<Cell col={4}>
<div style={{textAlign: 'center'}}>
<img
src="https://www.shareicon.net/data/128x128/2017/07/11/888365_cookie_512x512.png"
alt="avatar"
style={{height: '200px'}}
/>
</div>
<h2 style={{paddingTop: '2em'}}><NAME></h2>
<h4 style={{color: 'grey'}}>Software Engineer</h4>
<hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/>
<hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/>
<h5>Location</h5>
<p>Metuchen, New Jersey</p>
<h5>Email</h5>
<p><EMAIL></p>
<hr style={{borderTop: '3px solid #833fb2', width: '50%'}}/>
</Cell>
<Cell className="resume-right-col" col={8}>
<h2>Education</h2>
<Education
startYear={2017}
endYear={2021}
schoolName="Rutgers University"
schoolDescription="Bachelor of Science, Computer Science"
/>
<h2>Experience</h2>
<Experience
startYear={2020}
endYear={2020}
jobName="3M Health Information Systems"
jobTitle="Software Engineering Intern"
jobDescription="Implemented full-stack features for CodeAssist, an NLP-enabled medical coding
software that allows for team managers to analyze productivity of team members."
/>
<Experience
startYear={2019}
endYear={2021}
jobName="<NAME> - New Brunswick Computing Services"
jobTitle="Level 2 Help Desk Consultant"
jobDescription="Answered phone calls from the university community of students, faculty, and employees to
provide them with computing support."
/>
<hr style={{borderTop: '3px solid #e22947'}} />
<h2>Skills</h2>
<Skills
skill="Java"
progress={100}
/>
<Skills
skill="HTML/CSS"
progress={80}
/>
<Skills
skill="JavaScript"
progress={50}
/>
<Skills
skill="React"
progress={25}
/>
</Cell>
</Grid>
</div>
)
}
}
export default Resume;
|
099f3959dfdc16847396459b4c89bded009f1b6f
|
[
"JavaScript"
] | 1
|
JavaScript
|
harshhp12/harshpatel.io
|
2e27cfd4a0fef3827cb3410a3072a81ce8cbdb1f
|
fb1d6339f8cfd4756141ae0ab9de05e435740e74
|
refs/heads/master
|
<repo_name>pranaysondkar/ParkMe<file_sep>/app/src/main/java/com/parkme/BookingActiivity.java
package com.parkme;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Objects;
public class BookingActiivity extends AppCompatActivity {
FirebaseFirestore mLocation = FirebaseFirestore.getInstance();
private static final String TAG = "BookingActiivity";
String locID;
String latlngName;
String Title;
String Address;
GeoPoint geoPoint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking_actiivity);
loadSlots();
}
private void loadSlots() {
TextView mLocationTitle = (TextView) findViewById(R.id.location_title);
final TextView mLocationAddres = (TextView) findViewById(R.id.location_address);
Log.d(TAG, "Load Slots");
Bundle bundle = getIntent().getExtras();
assert bundle != null;
final String location_data = bundle.getString("locFromMap");
mLocationTitle.setText(location_data);
mLocation.collection("Location").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
locID = document.getId();
latlngName = document.getString("latlngName");
Title = document.getString("Title");
Address = document.getString("Address");
geoPoint = document.getGeoPoint("geoLatLng");
//Log.d(TAG,"Location title from firebase:" +locID);
assert location_data != null;
if (location_data.equals(locID)){
Log.d(TAG,"Location same hai");
Log.d(TAG, "location name" + locID);
Log.d(TAG,"Title:"+ latlngName);
Log.d(TAG,"Address:" + Address);
mLocationAddres.setText(Address);
Log.d(TAG, "geoPoint:"+ geoPoint);
}
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
}
}
|
0904868b40dd774ebba75037d680189a774455d8
|
[
"Java"
] | 1
|
Java
|
pranaysondkar/ParkMe
|
ac336d031f0584968d509d1803cb8ad6b286dd1c
|
08256b379827cf69850e3f73bd99ab49a6063875
|
refs/heads/master
|
<file_sep>\name{benford}
\alias{benford}
\title{Benford's analysis
}
\description{
Benford's analysis makes use of a statistic property of natural data sets called Benford's Law. Benford’s Law (also called “first digit phenomenon”) is a statistical phenomenon that describes the frequency of a given integer, from 1 to 9, to be in the first significant digit in the numbers of a large data set. The Benford’s law has been most practically used to detect fraud or rounding errors in real world numbers. This is possible by examining departures in the frequencies of individual digits from those predicted by Benford. This only makes sense once it is established (often empirically) that
the data follow the law under normal circumstances (Sambridge et al., 2011). This is true because human pseudo-random productions are in many ways different from true randomness (Nickerson, 2002). As a consequence, fabricated data might fit to the Benford’s Law to a lesser extent than genuine data (Banks and Hill, 1974; Gauvrit et al., 2017).
Benford package is able to analyze the frequence of the first, second, first-two and first-three digits in large data sets.
}
\usage{
benford(x, plot = FALSE, mode = 1)
}
\arguments{
\item{x}{
A numeric vector with the data set numbers to be analyzed
}
\item{plot}{
A logic that control whether the resulting first digit distribution and the Benford's distribution would be ploted
}
\item{mode}{
A numeric value (1, 2, 12 or 123) to select, respectively, first digit, second digit, first-two digits or first-three digits analysis
}
}
\value{
LIST countaining:
1. Named vector with three elements: the Chi Square test p value (p), the root mean square deviation (RMSD) from the Benford's distribution, and the log of the likelihhod of the first digit distribution in relation to the Benford's distribution;
2. Matrix, with three columns, countaining the first digits ([,1]), the frequency counts of the first digit in the data set ([,2]) and the frequency count of the first digit in a classic Benford's distribution ([,3])
}
\references{
<NAME>, <NAME>. 1974. The apparent magnitude of number scaled by random production. J. Exp. Psychol. 102:353–376. <http://content.apa.org/journals/xge/102/2/353>.
<NAME>. 1938. The Law of Anomalous Numbers. Proc. Am. Philos. Soc. 78:551–572. <http://www.jstor.org/stable/984802>.
<NAME>, <NAME>, <NAME>-P. 2017. Generalized Benford’s Law as a Lie Detector. Adv. Cogn. Psychol. 13:121–127. <http://ac-psych.org/en/download-pdf/id/214>.
<NAME>. 2021. Inconsistencies in countries COVID-19 data
revealed by Benford’s law. Model Assisted Statistics and Applications 16 (2021) 73–79. <http://dx.doi.org/10.3233/MAS-210517>
<NAME>. 2002. The production and perception of randomness. Psychol. Rev. 109:330–357. <http://doi.apa.org/getdoi.cfm?doi=10.1037/0033-295X.109.2.330>.
<NAME>, <NAME>, <NAME>. 2011. Benford’s Law of First Digits: From Mathematical Curiosity to Change Detector. Asia Pacific Math. Newsl. 1:1–5.
}
\author{
<NAME>, Ph.D.
Department of Biotechnology
Federal University of Bahia, Brazil
}
\note{
RMSD and likelihood are not formal statistic tests, so it may be evaluated only in a comparative way. To perform analysis in order to get to absolute conclusion on the veracity of the data set, Chi square p value is more trustable.
For first-two and first-three digits analysis, the number of observation in the data set must be large enough to permit good Chi-square calculation. Otherwise, benford will return a warning message.
}
\examples{
#Computer generated random data do not conform to the benford law
result <- benford(seq(1,10000)+rnorm(10000,0,100), TRUE)
#Natural data set, countaining the number of daily new cases of COVID-19 in Switzerland
##conform to the Benford' Law
result <- benford(switz.data, TRUE)
##conform to second digit analysis of the Benford' Law
result <- benford(switz.data, TRUE, 2)
}
\keyword{ Benford's analysis }
\keyword{ Benford's Law }
<file_sep>####################################################
benford <- function(x, plot=FALSE, mode=1) {
x <- x[which(!is.na(x))]
dist <- abs(x)
if(max(dist)/min(dist) < 1000) {
print("Benford's analysis perform better when the analyzed data set ranges for more than
three orders of magnitude than when it ranges for just one or two orders of magnitude (Fewster, 2009).")
}
if(mode == 1) {
first <- as.integer(sapply(strsplit(as.character(dist),""), `[[`, 1))
n <- c(1:9)
benford_dist <- log10(1+1/n)
first <- first[which(first!=0)]
xlab <- "First digit"
} else if(mode == 2) {
dist <- dist[dist>=10]
first <- as.integer(sapply(strsplit(as.character(dist),""), `[[`, 2))
n <- c(0:9)
benford_dist <- NULL
for(d in c(0:9)){
benford_dist[d+1] <- sum(log10(1+1/(10*c(1:9)+d)))
}
xlab <- "Second digit"
} else if(mode == 12) {
dist <- dist[dist>=10]
first <- as.integer(paste(sapply(strsplit(as.character(dist),""), `[[`, 1),
sapply(strsplit(as.character(dist),""), `[[`, 2),
sep=""))
n <- c(10:99)
benford_dist <- log10(1+1/n)
first <- first[which(first!=0)]
xlab <- "first-two digits"
} else if(mode == 123){
dist <- dist[dist>=100]
first <- as.integer(paste(sapply(strsplit(as.character(dist),""), `[[`, 1),
sapply(strsplit(as.character(dist),""), `[[`, 2),
sapply(strsplit(as.character(dist),""), `[[`, 3),
sep=""))
n <- c(100:999)
benford_dist <- log10(1+1/n)
first <- first[which(first!=0)]
xlab <- "first-three digits"
} else {
print("Mode must be 1 for first digit analysis, 2 for second digit, 3 for
the third digit or 12 for first-two and 123 for first-three digits analysis")
}
### Compute RMSD, Likelihood and Chi-square for each country
benford.data <- NULL
benford_hist <- hist(first, breaks=c(n-.5,max(n+.5)),
right=F, plot=F)
benford_counts <- benford_hist$counts / length(first)
rmsd <- sqrt(mean((benford_counts - benford_dist)^2, na.mr=T))
chisq <- chisq.test(matrix(c(benford_hist$counts, benford_dist * length(first)),
ncol=2, byrow=F))
likelihood <- sum(dnorm(benford_counts, mean=benford_dist, sd=sd(benford_counts), log=T))
chart <- matrix(c(n=1:length(benford_dist), data=benford_hist$counts, benford=benford_dist*length(first)),
ncol=3)
if(plot == T) {
if(max(chart[,3]) >= max(chart[,2])){
ymax <- max(chart[,3])*1.05 } else {
ymax <- max(chart[,2])*1.05
}
plot(chart[,1], chart[,2], type="h", ylim=c(0,ymax),
main=paste("p =", round(chisq[[3]],4)), xlab=xlab,
ylab="counts")
points(chart[,1], chart[,3], col="red")
lines(chart[,1], chart[,3], col="red")
}
exit <- list(c(p=chisq[[3]], RMSD=rmsd, LogLikelihood=likelihood), chart)
return(exit)
}
<file_sep>\name{switz.data}
\alias{switz.data}
\docType{data}
\title{
Number of daily new cases of COVID-19 in Switzerland
}
\description{
A data set with the number of new cases of COVID-19 in Switzerland. A natural data set that conform very well to the Benford's law
}
\usage{data("switz.data")}
\format{
A numeric vector with 383 observations.
\describe{
\item{\code{x}}{a numeric vector}
}
}
\source{
Our World in Data COVID-19 project: https://ourworldindata.org/coronavirus-data
}
\references{
<NAME>, <NAME>, <NAME>, <NAME>. 2020. Coronavirus Pandemic (COVID-19). https://ourworldindata.org/coronavirus.}
\examples{
data(switz.data)
## maybe str(switz.data) ; plot(switz.data) ...
}
\keyword{datasets}
|
4a7e9a22a50840443b7dfd9ffcb012a1278d1851
|
[
"R"
] | 3
|
R
|
cran/benford
|
81b4cb2b210105daa584322811136dcdcd88c028
|
ecb91358bc3c2484c288b8bc9c24be7daeff61eb
|
refs/heads/master
|
<repo_name>LuoxDev/CookAid<file_sep>/app/src/main/java/be/pxl/project/cookaid/SearchRecipeAdapter.java
package be.pxl.project.cookaid;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.List;
public class SearchRecipeAdapter extends ArrayAdapter<Recipe> {
public SearchRecipeAdapter(@NonNull Context context, int resource, int textViewResourceId, @NonNull List<Recipe> objects) {
super(context, resource, textViewResourceId, objects);
}
@NonNull
@Override
public View getView(int position, @NonNull View convertView, @NonNull final ViewGroup parent) {
final Recipe recipe = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
final TextView cardTextView = convertView.findViewById(R.id.helloText);
cardTextView.setText(recipe.getName());
final long ONE_MEGABYTE = 1024 * 1024;
StorageReference storageReference = FirebaseStorage.getInstance().getReference();
storageReference.child(recipe.getUri()).getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
@Override
public void onSuccess(byte[] bytes) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Drawable drawable = new BitmapDrawable(parent.getResources(), bitmap);
cardTextView.setBackground(drawable);
}
});
return convertView;
}
}
<file_sep>/app/src/main/java/be/pxl/project/cookaid/LikedRecipeHolder.java
package be.pxl.project.cookaid;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class LikedRecipeHolder extends RecyclerView.ViewHolder {
TextView recipeName;
TextView recipeLevel;
ImageView recipeImage;
public LikedRecipeHolder(View itemView) {
super(itemView);
recipeName = itemView.findViewById(R.id.recipe_name);
recipeLevel = itemView.findViewById(R.id.recipe_level);
recipeImage = itemView.findViewById(R.id.recipe_image);
}
}
|
02cbc7a3ecd615f66c3fbf3c5b4513b332187b81
|
[
"Java"
] | 2
|
Java
|
LuoxDev/CookAid
|
5338970761996d92ea6693ffc813f6afdcf565f0
|
5a3422ea2bfc860f99b0235c68207de0ed6ed3d8
|
refs/heads/master
|
<file_sep>var zmq = require('..')
, router = zmq.socket('router')
, req = zmq.socket('req')
, should = require('should')
, tcp = 'tcp://127.0.0.1:3000';
describe('socket reconnect', function() {
it('should reconnect', function(done) {
var reqs = {a: 0, b: 0, c: 0, d: 0, e: 0};
router.on('message', function(source, _, envelope, data) {
// increments reqs flag on req
reqs[data]++;
router.send([source, '', 'ACK', data]);
if (data == 'c') {
router.unbind(tcp);
setTimeout(router.bindSync.bind(router, tcp), 15);
}
});
router.bindSync(tcp);
req
.connect(tcp)
.monitor(1)
.on('message', function(topic, data) {
// increments reqs flag on router res
reqs[data]++;
});
var delay = 0;
Object.keys(reqs).forEach(function(key) {
setTimeout(function() {
req.send(['REQ', key]);
}, delay += 5);
});
var assert = function() {
// delay the test until every req get a response
if(reqs.e !== 2)
return setTimeout(assert, delay += 5);
reqs.should.eql({a: 2, b: 2, c: 2, d: 2, e: 2});
done();
};
setTimeout(assert, delay += 5);
});
});
|
b3c98fd37ab921e66d1c8edca3d1fd41ed84bb77
|
[
"JavaScript"
] | 1
|
JavaScript
|
yamsellem/zeromq.node
|
17c3994753187206bc2d2cc730e18b79b4d52abf
|
98e909844708a7b084e7754f69fb78ef5cec5500
|
refs/heads/master
|
<file_sep>package data_types;
import java.util.*;
public class Message_data extends Base_data
{
// Default constructor
public Message_data()
{
super();
m_type = Tcp_message_type.Message;
m_recipiants = new Vector<String>();
m_sender = "";
m_message = "";
m_have_attachment = false;
m_filename = "";
m_file_contents = "";
}
// Required for Serializable
private static final long serialVersionUID = 21L;
// Who is receiving this message
public List<String> m_recipiants;
// Who sent the message in question
public String m_sender;
// Message contents. Will be formatted in UTF8 to allow for emoji
// Simple formatting will be handled by using HTML tags in the string
// https://stackoverflow.com/questions/4769076/how-to-make-font-bold-in-java-dialogue-box
public String m_message;
// do we have a attachment
public boolean m_have_attachment;
// Filename for attached file
public String m_filename;
// String version of a attached file
// Want a byte array here. Not sure the Java class
public String m_file_contents;
// This should probably go into UI
public void Serialize_file(String filename)
{
// trim filename and assign to m_filename
// read byte contents of the file and assign to m_file_contents
// If we are successful set m_have_attachement = true;
}
// This should probably go into the UI
public void Deserialize_file(String path)
{
// create file with m_filename at path
// copy bytes from m_file_contents into file
}
// Prints out the contents of the message
public String toString()
{
String rep = super.toString();
rep += "\n To:";
Iterator<String> it = m_recipiants.iterator();
while(it.hasNext())
{
rep += "\n " + it.next();
}
rep += "\n From: " + m_sender;
rep += "\n Message: " + m_message;
if(m_have_attachment)
{
rep += "\n Attachment: " + m_filename;
// Do we want contents?
}
return rep;
}
}
<file_sep>package client;
public class Poll_vote
{
}
<file_sep>package testing;
import client.Main_page;
import data_types.*;
public class Client_receiver extends Main_page
{
public void Data_received(Base_data data)
{
System.out.println(data.toString());
}
public void Send_data(Base_data data)
{
m_tcp.Send_data(data);
}
}
<file_sep>package testing;
import server.Database_manager;
import data_types.*;
public class Server_receiver extends Database_manager
{
public void Data_received(Base_data data)
{
System.out.println(data.toString());
}
public void Send_data(Base_data data)
{
m_tcp.Send_data(data);
}
}
<file_sep>package client;
public class Poll_view
{
}
<file_sep>package client;
public class Poll_create
{
}
<file_sep>package server;
import java.util.ArrayList;
import java.util.List;
// NEW -RB
// TO DO:
// 1 - Add a list of users who already voted. Have poll_element keep track of who voted for that element
// then if the user votes again, remove the old vote and cast a new vote.
// 2 - Add a creator role, which that creator can remove elements and the poll.
// 3 - Add a timer for ending poll
//
public class Poll_server
{
String poll_id;
List<Poll_element> poll_contents;
/**
* Creates a Poll with a name, and creates an empty content list.
* @param name the id/name/title of the Poll
*/
public Poll_server(String name) {
this.poll_id = name;
this.poll_contents = new ArrayList<Poll_element>();
}
/**
* Adds an string item into the poll option.
* Will create a poll element to keep track of votes for the item
* @param item the item being added to the poll
*/
public void add_item(String item) {
Poll_element element = new Poll_element(item);
this.poll_contents.add(element);
}
/**
* Casts a vote to the item being voted on
* @param item the item a vote is being added to
*/
public void add_vote(String item) {
for(Poll_element element : poll_contents) {
if(item == element.getItem()) {
element.addVote();
break;
}
}
}
/**
* Gets the id/name/title of the poll
* @return the id/name/title of the poll
*/
public String getID() {
return poll_id;
}
/**
* Gets the list of all the elements of the poll.
* @return the list of poll elements, as poll_element
*/
public List<Poll_element> getContent() {
return poll_contents;
}
}
<file_sep>package tcp_bridge;
import java.net.*;
import java.io.*;
import java.util.*;
import server.Database_manager;
import data_types.*;
//This will do any Client Specific actions we decide
//we need for the bridge
public class Tcp_server_side
{
// Initialize the server
public void Init()
{
try
{
m_server = new ServerSocket(1129);
}
catch(IOException e)
{
System.out.println("Error creating server:" + e);
}
Socket client_socket = null;
ObjectInputStream is;
Base_data data;
//String str;
try
{
client_socket = m_server.accept();
is = new ObjectInputStream(client_socket.getInputStream());
while(true)
{
try
{
data = (Base_data)is.readObject();
System.out.println(data);
Message_data mess = (Message_data)data;
System.out.println(mess);
//str = (String)is.readObject();
//System.out.println(str);
}
catch(ClassNotFoundException e)
{
System.out.println("class not found" + e);
}
}
}
catch(BindException e)
{
System.out.println("error binding");
}
catch(IOException e)
{
System.out.println("IO error");
}
//m_run = true;
//loop();
}
// Register a class to receive all the data that comes from the server
public void Register_reciver(Database_manager callback)
{
m_callback_class = callback;
}
// Send a data message
public void Send_data(Base_data data)
{
}
private void loop()
{
if(m_run)
{
check_for_incoming_connection();
check_clients_alive();
check_client_messages();
// Call loop with a timer
// or just loop?
// is this going to be event based?
// -- probably should be for server messages
}
}
// Called in a loop to see if server has a new client
// multiple connections?
private void check_for_incoming_connection()
{
}
private void check_clients_alive()
{
for(int i = 0; i < m_client_connections.size(); i++)
{
if(!m_client_connections.get(i).Is_connected())
{
// Close connection
// delete from list
}
}
}
private void check_client_messages()
{
for(int i = 0; i < m_client_connections.size(); i++)
{
// Check for messages and pass to server
// emit a signal?
}
}
private boolean m_run;
private ServerSocket m_server;
private List<Tcp_bridge> m_client_connections;
// Sends messages to this class with Data_received(Base_data data)
private Database_manager m_callback_class;
}
<file_sep>package tcp_bridge;
import client.Main_page;
import java.io.*;
import data_types.*;
// This will do any Client Specific actions we decide
// we need for the bridge
public class Tcp_client_side extends Tcp_bridge
{
// Initialize the client
public void Init()
{
if(open_connection("192.168.1.5", 1129))
{
// TODO: this should probably be in bridge
ObjectOutputStream os = null;
//DataInputStream is = null;
try
{
os = new ObjectOutputStream(m_socket.getOutputStream());
//is = new DataInputStream(m_socket.getInputStream());
}
catch(IOException e)
{
System.out.println("io exception on stream open");
return;
}
try
{
Message_data data = new Message_data();
data.m_message = "hello world";
System.out.println(data);
os.writeObject(data);
//os.flush();
//String str = "Test String";
//os.writeObject(str);
}
catch(IOException e)
{
System.out.println("problem sending message");
}
}
}
// Register a class to receive all the data that comes from the server
public void Register_reciver(Main_page callback)
{
m_callback_class = callback;
}
// Sends messages to this class with Data_received(Base_data data)
private Main_page m_callback_class;
}
|
880e3d1e0dff9441dffba5048fb1739fc43a973c
|
[
"Java"
] | 9
|
Java
|
thestaledorito/WeGroup
|
35febd49b7be86c28efbdf8e0e906e9dbf59f319
|
19840fb2911bef39d742ec70aa85b3f216a8bdf1
|
refs/heads/master
|
<repo_name>christopherlolney/DiscordBot<file_sep>/bot.js
const auth = require('./auth.json');
const Discord = require('discord.js');
const client = new Discord.Client();
const GphApiClient = require('giphy-js-sdk-core')
const giphyClient = GphApiClient(auth.GphApiClient) //make this private
const ytdl = require('ytdl-core');
const streamOptions = {
seek: 0,
volume: .5
};
/*
npm install discord.io,ytdl-core, giphy-js-sdk-core
*/
client.on('ready', () => {
console.log('I am ready!');
console.log("starting bot :" + new Date());
});
client.on('message', message => {
if (message.toString().substring(0, 1) == '$') {
console.log(message.author + ": " + new Date());
var args = message.toString().substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch (cmd) {
case 'ping':
message.channel.send("Hello " + message.author + " yes I am indeed alive");
break;
case 'srs':
message.channel.send("(ಠ_ಠ)");
break;
case 'help': //TODO encode for formatting
message.channel.send("Ask me to do something with $\nThis is what I know how to do:\n" +
"ping - see if I am functioning\n" +
"groups - see a list of groups who are playing and find their message codes\n" +
"message - followed by a message code to message everyone in a dnd game\n" +
"end - End a dnd session in style (need to be in voice channle to work)\n" +
"begone - kick me out of a voice channel(need to be in voice channle to work)\n" +
"coins - throw money at people in voice chat\n" +
"roll - Roll some dice example($roll 2d20)\n" +
"dance - time to boogie!\n" +
"oof - oof in voice chat\n" +
"play - play a single youTube video in voice chat at half volume\n"
);
break;
case 'groups': //TODO encode for formatting
message.channel.send("Here are all of the groups currently playing Dungeons and Dragons:\n" +
"Out of the Abyss: oota\n" +
"Tyranny of Dragons: tod\n" +
"Dead in Thay: dit\n"
);
break;
case 'message': //TODO encode for formatting
var group = args[0]
message.channel.send(findGroup(group.toString().trim()) + gatherMessage(args));
break;
case 'end':
playAudio("roundabout.mp3", message);
break;
case 'begone':
playAudio("begoneThot.mp3", message);
break;
case 'coins':
playAudio("coins.wav", message);
break;
case 'awaken':
playAudio("awaken.mp3", message);
case 'oof':
playAudio("roblox-death-sound_1.mp3", message);
break;
case 'roll': //TODO REformat results and add math modifiers
var roll = args[0]
var dice = roll.toString().substring(0).split('d');
var results = "";
if (dice[1] > 0 && dice[0] > 0) {
for (var i = 0; i < dice[0]; i++) {
results = results + "(**" + getRandomInt(dice[1]) + "**)";
}
message.channel.send({
embed: {
color: 039600,
description: results
}
});
} else {
message.channel.send("Go ahead and double check those numbers");
}
break;
case 'dance':
giphyClient.random('gifs', {
"tag": "skeleton dance"
}).then((response) => {
message.channel.send(response.data.url)
}).catch((err) => {
console.log(err);
})
break;
case 'memes':
giphyClient.random('gifs', {
"tag": "memes"
}).then((response) => {
message.channel.send(response.data.url)
}).catch((err) => {
console.log(err);
})
break;
case 'giph':
var tag;
for (var i = 0; i < args.length; i++) {
if(i==0){
tag = args[i];
}else{
tag = tag + " " + args[i];
}
}
giphyClient.random('gifs', {
"tag": tag
}).then((response) => {
message.channel.send(response.data.url)
}).catch((err) => {
console.log(err);
})
break;
case 'stool': //TODO add color to encoding
message.channel.send({
embed: {
image: {
url: "https://media.giphy.com/media/8FVaTy8b06Qpm7dtWY/giphy.gif"
}
}
});
break;
case 'play':
if (message.member.voiceChannel != null) {
var url = args[0]
var voiceChannel = message.member.voiceChannel;
voiceChannel.join().then(connection => {
const stream = ytdl(url, {
filter: 'audioonly'
});
const dispatcher = connection.playStream(stream, streamOptions);
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err));
} else {
message.channel.send("Could not Find user's current voice channel");
}
break;
}
}
if (message.content.includes("406615325006626836")) {
console.log(message.author + ": " + new Date());
message.channel.send('Use $help to see what I can do')
}
if (message.toString() == ("<:jeffery:405525238034464778>")) {
console.log(message.author + ": " + new Date());
message.channel.send({
embed: {
image: {
url: "https://media.giphy.com/media/yr7n0u3qzO9nG/giphy.gif"
}
}
});
}
});
//TODO Pull these methods out into another file
function gatherMessage(args) {
var message = "";
for (var i = 1; i <= args.length - 1; i++) {
message = (message + " " + args[i]);
}
return message;
}
function findGroup(group) { //TODO make this a DB
var players;
switch (group) {
case 'oota':
players = "(<@!196099263271403529>, <@!196315459186982912>, <@!244532654089830410>, <@!199541321289957376>, <@!201190399119851520>, <@!204585276897624064>, <@!187396555840552960>)";
break;
case 'tod':
players = "(<@!196315459186982912>, <@!196099263271403529>, <@!199541321289957376>, <@!218554560363364352>, <@!310820323924639744>, <@!244532654089830410>)";
break;
case 'dit':
players = "(<@!196099263271403529>, <@!196315459186982912>, <@!199541321289957376>, <@!218554560363364352>, <@!310820323924639744>, <@!392873864842969109>)";
break;
}
return players;
}
function playAudio(fileName, message) {
if (message.member.voiceChannel != null) {
var voiceChannel = message.member.voiceChannel;
voiceChannel.join().then(connection => {
const dispatcher = connection.playFile('./music/' + fileName);
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err));
} else {
message.channel.send("Could not Find user's current voice channel");
}
}
function getRandomInt(max) {
min = Math.ceil(1);
max = Math.floor(max);
return Math.floor(Math.random() * ((max + 1) - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
client.login(auth.token);
|
9e4ba45889a40c22504f22a50f1d2def7209edb3
|
[
"JavaScript"
] | 1
|
JavaScript
|
christopherlolney/DiscordBot
|
a5011d0c3143b787168cc71c0df7a8c7d47f13de
|
b77512f0bbb2ddb4cabc0532c99af07243522d29
|
refs/heads/master
|
<file_sep><?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Klasemen extends REST_Controller
{
function __construct($config = 'rest')
{
parent::__construct($config);
$this->load->database();
$this->load->model('Klasemen_model', 'klasemen');
}
public function index_get()
{
$id = $this->get('id');
if ($id === null) {
$klasemen = $this->klasemen->getKlasemen();
} else {
$klasemen = $this->klasemen->getKlasemen($id);
}
if ($klasemen) {
$this->response([
'status' => true,
'data' => $klasemen
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'id not found'
], REST_Controller::HTTP_NOT_FOUND);
}
// $id = $this->get('id');
// if ($id == '') {
// $klasemen = $this->db->get('klasemen')->result();
// } else {
// $this->db->where('id', $id);
// $klasemen = $this->db->get('klasemen')->result();
// }
// $this->response($klasemen, 200);
}
public function index_delete()
{
$id = $this->delete('id');
if ($id === null) {
$this->response([
'status' => false,
'message' => 'provide an id'
], REST_Controller::HTTP_BAD_REQUEST);
} else {
if ($this->klasemen->deleteKlasemen($id) > 0) {
// ok
$this->response([
'status' => true,
'id' => $id,
'message' => 'deleted.'
], REST_Controller::HTTP_NO_CONTENT);
} else {
// id not found
$this->response([
'status' => false,
'message' => 'id not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
public function index_post()
{
$data = [
'name' => $this->post('name'),
'p' => $this->post('p'),
'w' => $this->post('w'),
'd' => $this->post('d'),
'l' => $this->post('l'),
'f' => $this->post('f'),
'a' => $this->post('a'),
'gd' => $this->post('gd'),
'pts' => $this->post('pts')
];
if ($this->klasemen->createKlasemen($data) > 0) {
$this->response([
'status' => true,
'message' => 'new klasemen has been created.'
], REST_Controller::HTTP_CREATED);
} else {
$this->response([
'status' => false,
'message' => 'failed to create new data!'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
public function index_put()
{
$id = $this->put('id');
$data = [
'name' => $this->put('name'),
'p' => $this->put('p'),
'w' => $this->put('w'),
'd' => $this->put('d'),
'l' => $this->put('l'),
'f' => $this->put('f'),
'a' => $this->put('a'),
'gd' => $this->put('gd'),
'pts' => $this->put('pts')
];
if ($this->klasemen->updateKlasemen($data, $id) > 0) {
$this->response([
'status' => true,
'message' => 'new klasemen has been updated.'
], REST_Controller::HTTP_NO_CONTENT);
} else {
$this->response([
'status' => false,
'message' => 'failed to update data!'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Oct 18, 2019 at 05:07 PM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `uts`
--
-- --------------------------------------------------------
--
-- Table structure for table `klasemen`
--
CREATE TABLE `klasemen` (
`id` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`p` int(11) NOT NULL,
`w` int(11) NOT NULL,
`d` int(11) NOT NULL,
`l` int(11) NOT NULL,
`f` int(11) NOT NULL,
`a` int(11) NOT NULL,
`gd` int(11) NOT NULL,
`pts` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `klasemen`
--
INSERT INTO `klasemen` (`id`, `name`, `p`, `w`, `d`, `l`, `f`, `a`, `gd`, `pts`) VALUES
(1, 'Liverpool', 8, 8, 0, 0, 20, 6, 14, 24),
(2, 'Manchester City', 8, 5, 1, 2, 27, 9, 18, 16),
(3, 'Arsenal', 8, 4, 3, 1, 13, 11, 2, 15),
(4, 'Leicester City', 8, 4, 2, 2, 14, 7, 7, 14),
(5, 'Chelsea', 8, 4, 2, 2, 18, 14, 4, 14),
(6, 'Crystal Palace', 8, 4, 2, 2, 8, 8, 0, 14),
(7, 'Burnley', 8, 3, 3, 2, 11, 9, 2, 12),
(8, 'West Ham United', 8, 3, 3, 2, 11, 11, 0, 12),
(9, 'Tottenham Hotspur', 8, 3, 2, 3, 14, 12, 2, 11),
(10, 'AFC Bournemouth', 8, 3, 2, 3, 13, 13, 0, 11);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `klasemen`
--
ALTER TABLE `klasemen`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `klasemen`
--
ALTER TABLE `klasemen`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.7.9
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 18, 2019 at 03:22 AM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `rent`
--
-- --------------------------------------------------------
--
-- Table structure for table `price`
--
CREATE TABLE `price` (
`id` int(11) NOT NULL,
`name` varchar(256) NOT NULL,
`category` varchar(256) NOT NULL,
`price` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `price`
--
INSERT INTO `price` (`id`, `name`, `category`, `price`) VALUES
(1, 'Tenda Double Layer Kap 2 org', 'Tenda', 17000),
(2, 'Tenda Double Layer Kap 3-4 org', 'Tenda', 19000),
(3, 'Tenda Bestway Kap 4-5', 'Tenda', 22000),
(4, 'Tenda Consina Kap 4 org', 'Tenda', 25000),
(5, 'Tenda Great Outdoor Kap 4-5 org', 'Tenda', 25000),
(6, 'Tenda Dhaulagiri 4 org Ultralight', 'Tenda', 30000),
(7, 'Tenda Great Outdoor Kap 5-6 org', 'Tenda', 35000),
(8, 'Tenda Great Outdoor Kap 6-8 org', 'Tenda', 35000),
(9, 'Tas Carrier 70-80 L', 'Carrier', 12500),
(10, 'Tas Carrier 60 L', 'Carrier', 10000),
(11, 'Tas Carrier 50 L', 'Carrier', 7500),
(12, 'Cover Bag', 'Other', 2500),
(13, 'Sepatu Trekking', 'Sepatu', 15000),
(14, 'Sandal Trekking', 'Sandal', 5000),
(15, 'Hammock', 'Other', 5000),
(16, 'Jacket', 'Jacket', 10000),
(17, 'Flysheet', 'Other', 7500),
(18, '<NAME>', 'Other', 4000),
(19, '<NAME>', 'Cooking Set', 5000),
(20, 'Nesting / Panci', 'Cooking Set', 5000),
(21, 'Sleeping Bag', 'Other', 5000),
(22, 'Trekking Pole', 'Other', 6000),
(23, 'Matras', 'Other', 2500),
(24, 'Gaiter', 'Other', 4000),
(25, 'Headlamp / Senter', 'Lighting', 4000),
(26, 'Lampu Tenda', 'Lighting', 4000),
(27, 'Jerigen Lipat 5L', 'Other', 3000),
(28, 'Kompas', 'Other', 2500),
(29, 'Pisau Lipat', 'Other', 2500),
(30, 'hasjvd', 'sajkd', 123123);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `price`
--
ALTER TABLE `price`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `price`
--
ALTER TABLE `price`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
class Klasemen_model extends CI_Model
{
public function getKlasemen($id = null)
{
if ($id === null) {
return $this->db->get('klasemen')->result_array();
} else {
return $this->db->get_where('klasemen', ['id' => $id])->result_array();
}
}
public function deleteKlasemen($id)
{
$this->db->delete('klasemen', ['id' => $id]);
return $this->db->affected_rows();
}
public function createKlasemen($data)
{
$this->db->insert('klasemen', $data);
return $this->db->affected_rows();
}
public function updateKlasemen($data, $id)
{
$this->db->update('klasemen', $data, ['id' => $id]);
return $this->db->affected_rows();
}
}
<file_sep># Langkah - langkah rest CodeIgniter
1. Fork repository
2. Clone repository
3. Paste di htdocs
4. Import database uts.sql
5. Jalankan rest di localhost http://localhost/rest/api/klasemen
6. Sementara hanya bisa method GET
# Langkah - langkah rest NodeJS
1. Fork repository
2. Clone repository
3. Paste di manapun
4. Masuk folder NodeJS
5. Klik kanan git bash ketik node index
6. Import database rent.sql
7. Jalankan rest di localhost http://localhost:3000/api/price
8. rest NodeJS adalah restful jadi bisa untuk method GET, POST, PUT, DELETE
|
7816656a3a5f6e4ce890e08ac38e52c8de9ccb72
|
[
"Markdown",
"SQL",
"PHP"
] | 5
|
PHP
|
bayufajariyanto/rest
|
2f4a29a535b34830bc8688312f8acad0a8d98546
|
11dddca3846f09b193d8f9fc00b756aae87554ae
|
refs/heads/master
|
<repo_name>Adarsh2412/PythonTest<file_sep>/calculator.py
#function calculator is defined
def calculator(first_number,second_number,operation):
if(operation=='add'):#if input is add, then we will add the numbers
return first_number+second_number
elif(operation=='subtract'):#if input is subtract, then we will subtract the numbers
return first_number-second_number
else:#if input is not add or subtract, then error should be returned
return "error"
first=(int)(input("Enter first number: "))
second=(int)(input("Enter second number: "))
symbol=input("Enter the operation-add or subtract: ")
answer=calculator(first,second,symbol)
if(answer=="error"):#if returned value is 'error' then that means, wrong symbol input
print("Please check the operation entered, as there seems to be invalid input, the symbol you entered is "+symbol+" ,it should be add or subtract")
else:
print("Answer is "+str(answer))
|
72f7d883179235c6b63b10925ebb973df6a238b4
|
[
"Python"
] | 1
|
Python
|
Adarsh2412/PythonTest
|
1453e9acdd61ff3895c58da9f164dab187b5c8ee
|
e477d102f87af8e76414b671162d5c8b3057e74d
|
refs/heads/master
|
<repo_name>IvoJongmans/Vue.js-Checkout<file_sep>/README.md
# Vue.js-Checkout
My first Vue.JS project
#I've started to build a checkout page with Vue.js
<file_sep>/script.js
var app = new Vue({
el: "#app",
data: {
fname: "",
lname: "",
email: "",
nb: "No",
city: ""
},
computed: {
fullname: function(){
if(this.fname && this.lname){
return this.fname + " " + this.lname;
}
},
datetoday: function(){
return new Date();
},
},
methods: {
resetForm: function(){
this.fname = "";
this.lname = "";
this.email = "";
this.city = ""
this.nb = "No";
}
}
});
|
9c27d1e1a281b57c5b73c0bc4c3a77498a5285f1
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
IvoJongmans/Vue.js-Checkout
|
e203f93caf8d2858844e85924fa05990aebb4b22
|
5729e5a1c9693f3bee75ab5066342efc000d741a
|
refs/heads/master
|
<file_sep>activate_this = '/var/www/one/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import sys
sys.path.insert(0, '/var/www/one')
from one import app as application
<file_sep>from flask import Flask
app = Flask(__name__)
from flaskext.markdown import Markdown
Markdown(app)
import one.views
|
dd1579937bd35c0f0cb438f3ef1e539766caafdd
|
[
"Python"
] | 2
|
Python
|
handledeck/one
|
3fdd2fd2aed773b25b0eb0b613818b59d6b04ad9
|
c8e7986af29c9bebb4d8877859c6ed0057607e49
|
refs/heads/master
|
<file_sep>var net = require('net')
var server = net.createServer();
var fs = require('fs')
var globalConf = require('./config')
server.listen(globalConf.port,'127.0.0.1');
server.on('listening',function(){
console.log('服务器已启动')
})
server.on('connection',function(socket){
console.log('有新的连接')
socket.on('data',function(data){
var url = data.toString().split('\r\n')[0].split(' ')[1]
console.log(url)
try{
var dataFile = fs.readFileSync(globalConf.baseUrl+url)
socket.write("HTTP/1.1 200OK\r\n\r\n")
socket.write(dataFile)
} catch{
socket.write('HTTP/1.1 404NotFound\r\n\r\n<html><body><p>404Not Found</p></body></html>')
}
socket.end()
})
})
|
0c86951aae12b896cf5c9e9d2c3018cf843a9935
|
[
"JavaScript"
] | 1
|
JavaScript
|
Keithcaiqian/studyNode-littleServer
|
8fc47f66375137401fab14915ae83d793249951f
|
e50d057649d4062979761ef3c36275f5391896d4
|
refs/heads/master
|
<repo_name>mfix22/calendarx<file_sep>/calendarx.d.ts
import * as React from 'react';
export type DateLike = Date | string | number;
export type Event =
| { date: DateLike }
| { startDate: DateLike; endDate: DateLike };
export type View = 'year' | 'month' | 'week' | 'day';
export type ButtonPropsGetter = (props?: {
onClick?: () => void;
}) => {
role: string;
'aria-label': string;
onClick: () => void;
};
export type Day = {
date: Date;
events: Event[];
isToday: boolean;
isSame: (view: View) => boolean;
};
export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export type JumpUnit =
| View
| 'years'
| 'y'
| 'months'
| 'M'
| 'weeks'
| 'w'
| 'days'
| 'd';
export type Properties = {
date: Date;
days: Day[][];
headers: string[];
view: View;
numDays: number;
jump: (n: number, v?: JumpUnit) => void;
goToNext: (n?: number) => void;
goToPrev: (n?: number) => void;
goToToday: () => void;
goToDate: (date: DateLike) => void;
getPrevButtonProps: ButtonPropsGetter;
getNextButtonProps: ButtonPropsGetter;
getTodayButtonProps: ButtonPropsGetter;
setNumDays: (numDays: number) => void;
};
export interface Options {
initialDate?: DateLike;
initialNumDays?: number;
date?: DateLike;
numDays?: number;
events?: Event[];
weekStartsOn?: Weekday;
headers?: string[];
}
export interface Props extends Options {
children: (properties: Properties) => React.ReactNode;
}
export function Calendar(props: Props): React.ReactNode;
export function useCalendar(options?: Options): Properties;
export namespace Calendar {
function useCalendar(options?: Options): Properties;
const days: {
SUNDAY: 0;
MONDAY: 1;
TUESDAY: 2;
WEDNESDAY: 3;
THURSDAY: 4;
FRIDAY: 5;
SATURDAY: 6;
};
const defaultProps: {
events: Event[];
headers: string[];
initialNumDays: number;
weekStartsOn: Weekday;
};
const views: {
DAY: 'day';
WEEK: 'week';
MONTH: 'month';
YEAR: 'year';
};
}
<file_sep>/test/util.test.js
import moment from 'moment'
import { add, isSame } from '../src/util'
function getDateKey(date) {
return date.toISOString().split('T')[0]
}
describe('add', () => {
const initialDate = moment('2019-02-18', 'YYYY-MM-DD')
test.each([
['years', '2020-02-18'],
['year', '2020-02-18'],
['y', '2020-02-18'],
['months', '2019-03-18'],
['month', '2019-03-18'],
['M', '2019-03-18'],
['weeks', '2019-02-25'],
['week', '2019-02-25'],
['w', '2019-02-25'],
['days', '2019-02-19'],
['day', '2019-02-19'],
['d', '2019-02-19'],
['random value', '2019-02-18'],
])('add(2019-02-18, 1, %s) === %s', (type, result) => {
expect(add(initialDate, 1, type).toISOString().split('T')[0]).toBe(result)
})
test.each([
['2019-02-18', 'day', true],
['2019-02-19', 'day', false],
['2019-02-19', 'week', true],
['2019-02-24', 'week', false],
['2019-02-19', 'week', false, 2],
['2019-02-28', 'month', true],
['2019-03-01', 'month', false],
['2019-07-09', 'year', true],
['2020-07-09', 'year', false],
])('isSame(2019-02-18, %s, %s) === %s', (compareDate, precision, result, weekStartsOn = 0) => {
const d1 = moment('2019-02-18', 'YYYY-MM-DD').toDate()
const d2 = moment(compareDate, 'YYYY-MM-DD').toDate()
expect(isSame(d1, d2, precision, weekStartsOn)).toBe(result)
})
describe.each(['day', 'week', 'month', 'year'])('%s', (view) => {
Array.from({ length: 367 }).forEach((_, i) => {
const date = moment('2018-01-01', 'YYYY-MM-DD').add(i, 'days')
const day = getDateKey(date.toDate())
test(`${i}) add(${day}, 1, ${view})`, () => {
const result = getDateKey(add(date, 1, view))
const exp = getDateKey(moment(date.add(1, view)).toDate())
expect(result).toBe(exp)
})
})
})
})
<file_sep>/README.md
<h1 align="center">📅 <code>Calendarx</code></h1>
> Your go-to, prescribed, Calendar component for React
Calendarx is a state container that makes creating custom calendar components a breeze. With a simple API, Calendarx makes it easy to display days and events, change views, and advance between the months, weeks, and days.
[](https://www.npmjs.org/package/calendarx)
[](https://bundlephobia.com/result?p=rexrex)
[](https://github.com/prettier/prettier)
[](#contributors)
[](http://makeapullrequest.com)
[](https://github.com/facebook/jest)
---
## Getting Started
```sh
yarn add calendarx
```
or
```sh
npm install calendarx
```
## Example Usage
```javascript
import { Calendar } from 'calendarx'
import { Row, Column, Events } from './components'
const events = [{ date: new Date(), id: 'birthday-1' }] // optional
export default () => (
<Calendar events={events}>
{({ days, date, goToNext, goToPrev, goToToday }) => (
<div>
<Row>
<span>{date.toDateString()}</span>
<button onClick={() => goToPrev()}><</button>
<button onClick={goToToday}>Today</button>
<button onClick={() => goToNext()}>></button>
</Row>
{days.map((week, i) => (
<Row key={i}>
{week.map((day, j) => (
<Column key={j}>
{day.events.map((event) => (
<Event isToday={day.isToday} key={event.id} {...event} />
))}
</Column>
))}
</Row>
))}
</div>
)}
</Calendar>
)
```
or use as a React hook:
```js
import { useCalendar } from 'calendarx'
export default MyCalendar() {
const { days } = useCalendar(options)
// ...
}
```
for an **Advanced** example, check out:
[](https://codesandbox.io/s/q7x1mpy5xj)
## Props
| Name | Default | Type | Description |
| :-------------------------- | :------------------------------------------------------------------------------- | :----------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **`children`** | `undefined` | `Function` | Render prop component. See [docs below](#render-props) for the options passed |
| `initialDate`, `date` | `new Date()` | `Date`, `String`, `Number`, `Moment` | `initialDate` sets the initial state of `date` for uncontrolled usage, otherwise use `date` for controlled usage. Used as the date to center the calendar around |
| `initialNumDays`, `numDays` | `35` | `Number` | Number of days the calendar should display. If `numDays` > 10, this will be raised to the next multiple of 7. Use `initialNumDays` for uncontrolled usage, `numDays` for controlled |
| `events` | `[]` | `Array<{ date: DateLike } , { startDate: DateLike, endDate: DateLike }>` | Events passed into the calendar. These objects will be injected into the correct array by date. Use `date` for an event on a specific date, and `startDate` combined with `endDate` for events spanning multiple dates |
| `weekStartsOn` | `0` | `Number[0-6]` | Weekday to start the week on. Sunday (0) - Saturday (6) |
| `headers` | `['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']` | `String[]` | Replace the headers that get passed to `children`, for convience |
| `render` | `undefined` | `Function` | Optional, same as `children` |
**Note**: the `Calendarx` days grid will adapt depending on the number of days that are specified
in `numDays`. For example, if 4 is passed in, the first column will start with your `initialDate`. If 7 is passed in (anything <10), the calendar will align itself to the beginning of the week. If `10 < numDays < 365` (the default is 35), the calendar will align to include the entire month and potentially parts of the previous/next month in order to align the grid with your start of the week (default is Sunday).
## Children Properties
The following will be passed to your `props.children` or `props.render` function:
| Option | Type | Description |
| :---------- | :-------------------------------------------------------------- | :--------------------------------------------------------------------------------- |
| `days` | `Day[][]` | 2-dimensional grid of objects representing each calendar day |
| `date` | `Date` | Current `date` state |
| `view` | `String{'year','month','week','day'}` | View according to `numDays`. `day` if <=4, `week` if <= 10, month < 365, or `year` |
| `jump` | `Function(n: Number, units: {'years','months','weeks','days'})` | Function to jump a specific amount of time |
| `goToNext` | `Function()` | Sets `date` state to next date according to `numDays/view` |
| `goToToday` | `Function()` | Set the `date` state to today |
| `goToPrev` | `Function()` | Same as `goToNext`, but in reverse |
| `goToDate` | `Function(date: DateLike)` | Set `date` state to arbitrary date |
## Types
### `Day`
This object contains the following fields/getters:
- `date`: `Date`
- `events`: `Event[]`
- `isToday`: `Boolean`
- `isSame(unit: 'year'|'month'|'week'|'day'): Boolean`: `Function`
### `Event`
`Event`s will include the other properties you pass alongside `date` in your `events` prop.
## Contributing
Please do! If you have ideas, bug fixes, or examples to showcase, please [submit a PR/issue](https://github.com/mfix22/calendarx/pulls).
1. `yarn`
2. Make your changes
3. `yarn test`
4. Push a [PR](https://github.com/mfix22/calendarx/pulls)
## Contributors
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->
<table><tr><td align="center"><a href="https://www.buymeacoffee.com/fix"><img src="https://avatars0.githubusercontent.com/u/8397708?v=4" width="100px;" alt="<NAME>"/><br /><sub><b><NAME></b></sub></a><br /><a href="https://github.com/mfix22/calendarx/commits?author=mfix22" title="Code">💻</a></td><td align="center"><a href="https://github.com/filipemir"><img src="https://avatars2.githubusercontent.com/u/13949291?v=4" width="100px;" alt="Filipe"/><br /><sub><b>Filipe</b></sub></a><br /><a href="https://github.com/mfix22/calendarx/commits?author=filipemir" title="Code">💻</a></td></tr></table>
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
## License
[MIT](https://github.com/mfix22/calendarx/blob/master/LICENSE)
## Inspiration 💫
This project was inspired by <NAME>'s [CLNDR](http://kylestetz.github.io/CLNDR/).
<file_sep>/index.d.ts
export function useCalendar({ initialDate, initialNumDays, date: dateProp, numDays: numDaysProp, events, weekStartsOn, headers: headersProp, }?: {
initialNumDays: number;
events: any[];
weekStartsOn: number;
headers: string[];
}): {
date: any;
days: any;
headers: any;
view: string;
numDays: any;
jump: any;
goToNext: any;
goToPrev: any;
goToToday: any;
goToDate: any;
getPrevButtonProps: any;
getNextButtonProps: any;
getTodayButtonProps: any;
setNumDays: any;
};
export function Calendar(props: any): any;
export namespace Calendar {
export { DEFAULTS as defaultProps };
export { useCalendar };
export { DAYS as days };
export { VIEWS as views };
}
export default Calendar;
declare namespace DEFAULTS {
export const initialNumDays: number;
export const events: any[];
import weekStartsOn = DAYS.SUNDAY;
export { weekStartsOn };
export { HEADERS as headers };
}
declare namespace DAYS {
const SUNDAY: number;
const MONDAY: number;
const TUESDAY: number;
const WEDNESDAY: number;
const THURSDAY: number;
const FRIDAY: number;
const SATURDAY: number;
}
declare namespace VIEWS {
const DAY: string;
const WEEK: string;
const MONTH: string;
const YEAR: string;
}
declare const HEADERS: string[];
<file_sep>/.github/CONTRIBUTING.md
If you have ideas, bug fixes, or examples to showcase, please submit a PR/issue.
## Steps:
1. `yarn`
2. Make your changes
3. `yarn build && yarn test`
4. Push a [PR](https://github.com/mfix22/calendarx/pulls)
|
88127cb376ad0f468c6f8f58320fd1dc37a07dd3
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 5
|
TypeScript
|
mfix22/calendarx
|
08c199f6a694a7f442630a6b70798c376dac8170
|
8759f96945312ab8d48f34072cf9f81f94c3f21d
|
refs/heads/master
|
<file_sep># flexboxdemo
test some flexbox style
try some css styles of flex box.
including display, box-orient and so on
use css3 style overwrite
<file_sep>/**
* Created by piggy on 2015/5/26.
*/
+function ($) {
'use strict';
var Tab = function(element) {
this.element = $(element);
}
Tab.VERSION = "1.0.0";
Tab.prototype.show = function() {
var $this = this.element;
console.log("$this is: ", $this);
var target = $this.data("target");
var $td = $this.parent().find(".backcolors");
console.log("td is: " , $td);
if($this.hasClass("backColors")) return; // this is active
var previous = "";
}
function plugin(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data("judy.tab");
if(!data) {
data = new Tab(this);
$this.data("judy.tab", data);
}
if(typeof option === "string")
data[option]();
})
}
var old = $.fn.tab;
$.fn.tab = plugin;
$.fn.tab.Constructor = Tab;
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
var changeTabs = function(e) {
e.preventDefault();
plugin.call($(this), "show");
}
$(document).on("click.myTab", '[data-toggle="tab"]', changeTabs());
}(jQuery)
|
f0ea051e0afb21773b18d48d5f6a3742a9db32e5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
judy0326/flexboxdemo
|
a90f11de14a026a343e91e08ab2f10cab36a41bf
|
9e78ed85b8442060a4e83f5d546df99598086472
|
refs/heads/master
|
<repo_name>mihuie/db_app<file_sep>/app/forms.py
from flask.ext.wtf import Form
from wtforms.fields import TextField
# other fields include PasswordField
from wtforms.validators import Required, Email
class EmailPasswordForm(Form):
username = TextField('Username', validators=[Required()])
email = TextField('Email', validators=[Required(), Email()])
|
c7bb7dd18038935c019a45b509f7fee28393d8d6
|
[
"Python"
] | 1
|
Python
|
mihuie/db_app
|
b3087571e07457e708fad51613a533afe6c5375c
|
f0fe23898341d674a6dd4f5ba79f15f0dec9f169
|
HEAD
|
<file_sep>$(function() {
var g_vid_yt_user;
var g_vid_date;
var g_vid_offset = 1;
var g_vid_perpage = 25;
var g_dateVideoGroupTemplate = $('#video-date-group-template').html();
var g_videoItemTemplate = $('#video-item-template').html();
var g_filterFunc = function(duration, likes) {
if (duration < 15 && likes < parseInt($('#short-video-threshold').val(), 10)) return true;
if (duration >= 15 && likes < parseInt($('#long-video-threshold').val(), 10)) return true;
return false;
};
var g_savedUsers = {
get: function(userName) {
var users = $.localStorage.get('users') || [];
for (var i = 0; i < users.length; i++) {
if (users[i].name == userName) {
return users[i];
}
}
return null;
},
update: function(userInfo) {
var users = $.localStorage.get('users') || [];
var found = false;
for (var i = 0; i < users.length; i++) {
if (users[i].name == userInfo.name) {
users[i] = userInfo;
found = true;
}
}
if (!found) {
users.push(userInfo);
}
$.localStorage.set('users', users);
},
remove: function(userName) {
var users = $.localStorage.get('users') || [];
for (var i = 0; i < users.length; i++) {
if (users[i].name == userName) {
users.splice(i, 1);
break;
}
}
$.localStorage.set('users', users);
},
display: function() {
var users = $.localStorage.get('users') || [];
var list = $('.yt-user-tag-list');
list.empty();
users.forEach(function(user) {
var loadFunc = function() { loadVideos(user); return false; };
var closeFunc = function() { g_savedUsers.remove(user.name); g_savedUsers.display(); return false; };
var item = tag('li', {'class': 'yt-user-tag'});
item.append(tag('a', {'class': 'value', href: '#', text: user.name, click: loadFunc}));
item.append(tag('a', {'class': 'close', href: '#', text: 'x', click: closeFunc}));
list.append(item);
});
}
};
function tag(name, attrs){
return $("<" + name + ">", attrs);
}
function sum(a) {
return Array.prototype.reduce.call(a, function(pv, cv) { return pv + cv; }, 0);
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function foldVideoItem(it) {
$('.video-thumbnail', it).hide();
$('.video-description', it).hide();
$('.expand-tag', it).show();
}
function expandVideoItem(it) {
$('.video-thumbnail', it).show();
$('.video-description', it).show();
$('.expand-tag', it).hide();
}
function applyFilter(filterFunc, context) {
if (!context) {
context = $('.video-item');
}
context.each(function(i, it) {
var duration = $('.video-meta-duration', it).text();
duration = sum(duration.split().map(function(v) {
var result = parseInt(v, 10);
if (v.indexOf('h') >= 0) {
result *= 60;
}
return result;
}));
var likes = $('.video-meta-likes', it).text();
if (likes != '') {
likes = likes.replace('[+]', '');
likes = parseInt(likes, 10);
}
var dislikes = $('.video-meta-dislikes', it).text();
if (dislikes != '') {
dislikes = dislikes.replace('[-]', '');
dislikes = parseInt(dislikes, 10);
}
var views = parseInt($('.video-meta-views', it).text(), 10);
var comments = parseInt($('.video-meta-comments', it).text(), 10);
var favorites = parseInt($('.video-meta-favorites', it).text(), 10);
//console.log(duration+' '+ likes+' '+ dislikes+' '+ views+' '+ comments+' '+ favorites);
if (filterFunc && filterFunc(duration, likes, dislikes, views, comments, favorites)) {
foldVideoItem(it);
} else {
expandVideoItem(it);
}
});
}
function loadVideoStats(video_id, t) {
var url = 'https://gdata.youtube.com/feeds/api/videos/' + video_id + '?v=2&alt=json';
$.ajax({url: url, dataType: "json"}).done(function(data) {
var e = data.entry;
var stats = {
views: e.yt$statistics.viewCount,
favorites: e.yt$statistics.favoriteCount,
comments: (e.gd$comments ? e.gd$comments.gd$feedLink.countHint : ''),
likes: (e.yt$rating ? e.yt$rating.numLikes : ''),
dislikes: (e.yt$rating ? e.yt$rating.numDislikes : '')
};
var likes = stats.likes;
var dislikes = stats.dislikes;
if (likes != '' && likes != '0') {
likes = '+' + likes;
}
if (dislikes != '' && dislikes != '0') {
dislikes = '-' + dislikes;
}
var ul = $('.video-meta ul', t);
ul.append(tag('li', {'class': 'video-meta-likes', title: 'Likes', text: likes}));
ul.append(tag('li', {'class': 'video-meta-dislikes', title: 'Dislikes', text: dislikes}));
applyFilter(g_filterFunc, t);
});
}
function appendVideos(video_infos) {
video_infos.forEach(function(vi) {
var lastGroup = $('.video-date-group:last-child');
var lastDate = $('.date', lastGroup).text();
if (lastDate != vi.published) {
var t = $(Mustache.render(g_dateVideoGroupTemplate, {date: vi.published}));
$('.date', t).click(function() {
$(this).next().toggle(); // toggle '.videos'
return false;
});
t.appendTo('.video-entries');
}
var view = $.extend({}, vi);
var duration = '';
var dur = parseInt(view.duration, 10);
if (dur > 3600) {
duration += Math.ceil(dur/3600) + 'h ';
}
duration += Math.ceil(dur%3600/60) + 'm ';
view.duration = duration;
var t = $(Mustache.render(g_videoItemTemplate, view));
$('.expand-tag', t).click(function() {
expandVideoItem(t);
return false;
});
loadVideoStats(vi.video_id, t);
$('.videos', lastGroup).show().append(t);
});
}
function loadVideos(userInfo) {
$('.video-entries').empty();
if (userInfo) {
$('#yt-user-selection-box').val(userInfo.name);
$('#short-video-threshold').val(userInfo.shortThreshold);
$('#long-video-threshold').val(userInfo.longThreshold);
} else {
var user = $('#yt-user-selection-box').val();
var shortThreshold = $('#short-video-threshold').val();
var longThreshold = $('#long-video-threshold').val();
userInfo = {'name': user, 'shortThreshold': shortThreshold, 'longThreshold': longThreshold};
}
g_vid_yt_user = userInfo;
g_vid_date = null;
g_vid_offset = 1;
g_vid_perpage = 50;
loadMoreVideos();
}
function loadMoreVideos() {
var url = 'https://gdata.youtube.com/feeds/api/users/' + g_vid_yt_user.name
+ '/uploads?alt=json&start-index=' + g_vid_offset + '&max-results=' + g_vid_perpage;
$.ajax({url: url, dataType: "json"}).done(function(data) {
var video_infos = data.feed.entry.map(function(e) {
var vid = e.id.$t;
return {
video_id: vid.substring(vid.lastIndexOf('/') + 1),
published: e.published.$t.substring(0, 10),
title: e.media$group.media$title.$t,
description: e.media$group.media$description.$t,
comments: (e.gd$comments ? e.gd$comments.gd$feedLink.countHint : ''),
url: e.media$group.media$content[0].url,
duration: e.media$group.media$content[0].duration,
thumbnail: e.media$group.media$thumbnail[0].url
};
});
appendVideos(video_infos);
g_savedUsers.update(g_vid_yt_user);
g_savedUsers.display();
$('.load-more-wrapper').show();
g_vid_offset += g_vid_perpage;
});
}
var ytUser = getParameterByName('user');
$('#yt-user-selection-box').val(ytUser);
$("#yt-user-selection-box").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#load-videos").click();
}
});
var shortThreshold = getParameterByName('short-threshold');
var longThreshold = getParameterByName('long-threshold');
$('#short-video-threshold').val(shortThreshold);
$('#long-video-threshold').val(longThreshold);
$('#short-video-threshold, #long-video-threshold')
.keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
applyFilter(g_filterFunc);
}
})
.blur(function() {
applyFilter(g_filterFunc);
});
g_savedUsers.display();
$('#load-videos').click(function() {
loadVideos();
return false;
});
$('#load-more').click(function() {
loadMoreVideos();
return false;
});
});
|
da37868d76d0c60fb67f39d96b15f7bde907980f
|
[
"JavaScript"
] | 1
|
JavaScript
|
vsg/youtube-browser
|
fd20e0e41be5e06956a7ac2b8bcbd495ced589d2
|
7f6049ac7d44146996f887da9d9477b0a007ebc0
|
refs/heads/master
|
<repo_name>ankored33/starry-stars<file_sep>/main.rb
require 'sinatra'
require 'sinatra/reloader'
require 'uri'
require 'json'
require 'net/http'
get "/" do
stars = Stars.new("https://anond.hatelabo.jp/20171019123120")
stars.parseJsonToHash
@num = stars.nomal_stars.length
erb :index
end
class Stars
def initialize(url = "")
@url = url
end
def parseJsonToHash
uri = URI.parse("http://s.hatena.com/entry.json?uri=#{URI.escape(@url)}")
json = Net::HTTP.get(uri)
@hash = JSON.parse(json)
end
def setStars
self.parseJsonToHash
@nomal_stars = @hash["entries"][0]["stars"]
@colored_stars = @hash["entries"][0]["colored_stars"]
end
attr_accessor :nomal_stars, :colored_stars
end
=begin
起動コマンド
bundle exec ruby main.rb -p $PORT -o $IP
=end
|
1dfcf0c912f06e00501428eba271c330e1b792d4
|
[
"Ruby"
] | 1
|
Ruby
|
ankored33/starry-stars
|
f76b49af172fd5d63da03b8404c1974b63c9b53e
|
2bc9facae87e89a1f0a46d331f714b79cf78ba2b
|
refs/heads/main
|
<file_sep>import torch
import torchvision
import argparse
from box import BoundingBox
from getbatch import getBatch
from wrapper import Wrapper
def parserArgs():
parser = argparse.ArgumentParser()
parser.add_argument('-s', type=str, help="")
parser.add_argument('-d', type=str, help="annotations path")
parser.add_argument('-i', type=str, help="images path")
parser.add_argument('-b', type=int, help="batch size")
parser.add_argument('--pic', type=str, help="image path for test", default=None)
parser.add_argument('--save', type=str, help="save path for .pth and png files")
parser.add_argument('--test', action="store_true", help="tests recognition on entire dataset")
parser.add_argument('--max-iter', type=int, help="maximum int of iterations")
parser.add_argument('-c', action='store_true', help="loading weights from checkpoint")
parser.add_argument('-p', type=str, help="path to checkpoint")
parser.add_argument('-lr', type=float, help="learning rate")
args = parser.parse_args()
return args
class Trainer():
def __init__(self, args, **kwargs):
self.batchgen = getBatch(an_path=args.d, im_path=args.i)
self.wrapper = Wrapper(checkpoint=args.c, checkpoint_path=args.p, lr=args.lr)
self.box = BoundingBox()
self.batch_size = args.b
self.resize = torchvision.transforms.Resize((224,224))
def createBox(self, path, coords, count=None, fname=None):
self.box.createImage(path, coords, count, fname)
def testPic(self, data):
data = self.resize(data)
print(data[None,...].shape)
return self.wrapper.test(x=data[None,...].cuda())[0]
def test(self):
data = []
target = []
tensor = self.batchgen.getTest()
path = tensor['image']
data.append(self.resize(tensor['imageTensor'].cuda()))
target.append(tensor['data'].cuda())
self.path = path
data = torch.stack(data)
target = torch.stack(target)
self.test_path = tensor['image']
return self.wrapper.test(x=data, target=target)
def train(self):
data = []
target = []
for i in range(0, self.batch_size):
tensor = self.batchgen.getNext()
path = tensor['image']
data.append(self.resize(tensor['imageTensor'].cuda()))
target.append(tensor['data'].cuda())
self.path = path
data = torch.stack(data)
target = torch.stack(target)
return self.wrapper.train(x=data, target=target)
args = parserArgs()
mod = Trainer(args)
if(not args.test and args.pic is None):
i = 0
while(i < 100000):
hit, loss, out, target = mod.train()
if( i % 1000 == 0 ):
print("##################################################################################################################")
print()
print( "Iteration: " + str(i) )
print()
print("IoU: " + str(hit) + " %", "Loss: " + str(loss))
print("Out: " + str(out.data))
print("Target: " + str(target.data))
print()
print()
mod.wrapper.save_stat(i, args.save)
path = args.save + "/image" + str(i) + ".png"
mod.createBox(path=mod.path, coords=[out, target], count=i)
i += 1
elif(args.test and args.pic is not None):
image = mod.batchgen.getPicByPath(args.pic)
image.cuda()
out = mod.testPic(image)
mod.createBox(path=args.pic, coords=[out, out], fname="/storage/brno6/home/jakubsekula/test/testimage.png")
else:
i = 0
average = 0
while(i < len(mod.batchgen.annotations.keys()) - 0):
hit, out, target = mod.test()
average += hit
print("IoU: {:.2f}".format(hit) + " %", mod.test_path)
i += 1
print()
print()
average = float(average/len(mod.batchgen.annotations.keys()))
print("Dataset average hit IoU: {:.2f}".format(average) + " %")
<file_sep>from os import listdir
from os import getcwd
import matplotlib.pyplot as plt
import cv2
import torch
import numpy as np
import random
from pathlib import Path
from torchvision.io import read_image
from torchvision.utils import draw_bounding_boxes
from torchvision import transforms
import xml.etree.ElementTree as ET
class getBatch():
def __init__(self, an_path, im_path):
self.annotation_path = an_path
self.iterator = 0
self.images_path = im_path
self.files = listdir(self.annotation_path)
print("found " + str(len(self.files)) + " files")
print("Getting coords ...")
self.annotations = {}
for grfile in self.files:
tree = ET.parse(self.annotation_path + grfile)
root = tree.getroot()
array = []
array.append(int(root[4][5][0].text.strip()))
array.append(int(root[4][5][1].text.strip()))
array.append(int(root[4][5][2].text.strip()))
array.append(int(root[4][5][3].text.strip()))
#[xmin, ymin, xmax, ymax]
inner = {}
inner['data'] = torch.tensor(array).to(torch.float32)
img_path = self.annotation_path + grfile.split('.')[0] + ".png"
inner['image'] = img_path.replace("annotations", "images")
self.annotations[grfile.split(".")[0][4:]] = inner
self.prepareMatrix()
def prepareMatrix(self):
for im in self.annotations.keys():
image = cv2.imread(self.images_path+"Cars"+im+".png")
transformer = transforms.ToTensor()
image = transformer(image)
self.annotations[im]['imageTensor'] = image
return image
def getPicByPath(self, path):
image = cv2.imread(path)
transformer = transforms.ToTensor()
image = transformer(image)
return image
def getTest(self):
index = self.iterator
self.iterator += 1
return self.annotations[str(index)]
def getNext(self):
index = random.randint(0, len(self.annotations.keys()) - 10)
return self.annotations[str(index)]
<file_sep>import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
class BoundingBox():
def __init__(self):
...
def countCoords(self, out, target):
#xmin,ymin,xmax,ymax
width = target[2] - target[0]
height = target[3] - target[1]
green = [target[0], target[1], width, height]
width = out[2] - out[0]
height = out[3] - out[1]
red = [out[0], out[1], width, height]
return green, red
def createImage(self, path, coords, count=0, fname=None):
green, red = self.countCoords(coords[0], coords[1])
im = Image.open(path)
fig, ax = plt.subplots()
ax.imshow(im)
rect = patches.Rectangle((green[0], green[1]), green[2], green[3], linewidth=1, edgecolor='r', facecolor='none')
rect2 = patches.Rectangle((red[0], red[1]), red[2], red[3], linewidth=1, edgecolor='green', facecolor='none')
ax.add_patch(rect)
ax.add_patch(rect2)
if fname == None:
plt.savefig(fname="/storage/brno6/home/jakubsekula/test/trn_" + str(count) + ".png")
else:
plt.savefig(fname=fname)
plt.close()<file_sep># License-plate-detection #
### easy license plate detection ###
This license plate detection was trained using https://www.kaggle.com/andrewmvd/car-plate-detection dataset.
Dataset consist of 433 car license plate images and they
<file_sep>from torch import nn
import torchvision
import torch
from getbatch import getBatch
class AlexNet(nn.Module):
def __init__(self, checkpoint, checkpoint_path):
super(AlexNet, self).__init__()
self.net = torchvision.models.alexnet(pretrained=False, num_classes=4)
if(checkpoint):
self.net.load_state_dict(torch.load(checkpoint_path))
self.net.eval()
print("Loaded")
self.net.cuda()
self.net.eval()
def forward(self, x, **kwargs):
return self.net(x)<file_sep>import torch
from shapely.geometry import Polygon
from net import AlexNet as Alex
class Wrapper():
def __init__(self, checkpoint, checkpoint_path, lr):
self.net = Alex(checkpoint, checkpoint_path)
self.optimizer = torch.optim.Adam(list(self.net.parameters()), lr=lr)
def area(self, a, b):
#xmin, ymin, xmax, ymax
polygon = Polygon([(a[0], a[1]), (a[2],a[1]), (a[2],a[3]), (a[0], a[3])])
other_polygon = Polygon([(b[0], b[1]), (b[2],b[1]), (b[2],b[3]), (b[0], b[3])])
intersection = polygon.intersection(other_polygon)
union = polygon.union(other_polygon)
return intersection.area / union.area * 100
#def test(self, x, target):
# with torch.no_grad():
# out = self.net.forward(x)
# return self.area(out[0], target[0]), out[0], target[0]
def test(self, x):
with torch.no_grad():
out = self.net.forward(x)
return out
def train(self, x, target):
self.optimizer.zero_grad()
out = self.net.forward(x)
lossfce = torch.nn.MSELoss()
loss = lossfce(out, target)
loss.backward()
self.optimizer.step()
return self.area(out[31], target[31]), loss, out[31], target[31]
def save_stat(self, i, path):
torch.save(self.net.net.state_dict(), path + "/checkpoint_" + str(i) + ".pth")<file_sep>#!/bin/bash
#PBS -N myFirstJob
#PBS -q gpu -l select=1:mem=20gb:ngpus=1:scratch_local=3gb:cl_adan=True
#PBS -m ae
# The 4 lines above are options for scheduling system: job will run 1 hour at maximum, 1 machine with 4 processors + 4gb RAM memory + 10gb scratch memory are requested, email notification will be sent when the job aborts (a) or ends (e)
# define a DATADIR variable: directory where the input files are taken from and where output will be copied to
DATADIR=/storage/brno6/home/jakubsekula/
# append a line to a file "jobs_info.txt" containing the ID of the job, the hostname of node it is run on and the path to a scratch directory
# this information helps to find a scratch directory in case the job fails and you need to remove the scratch directory manually
echo "$PBS_JOBID is running on node `hostname -f` in a scratch directory $SCRATCHDIR" >> $DATADIR/jobs/jobs_info.txt
# test if scratch directory is set
# if scratch directory is not set, issue error message and exit
test -n "$SCRATCHDIR" || { echo >&2 "Variable SCRATCHDIR is not set!"; exit 1; }
# copy input file "h2o.com" to scratch directory
# if the copy operation fails, issue error message and exit
#cp -r /storage/brno6/home/jakubsekula/HWR.2021-03-29/ $SCRATCHDIR || { echo >&2 "Error while copying input file(s)!"; exit 2; }
$DATADIR/train_specific.sh
#clean the SCRATCH directory
clean_scratch
<file_sep>import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
im = Image.open('/storage/brno6/home/jakubsekula/License-plate-detection/dataset/images/Cars0.png')
# Create figure and axes
fig, ax = plt.subplots()
# Display the image
ax.imshow(im)
# Create a Rectangle patch
rect = patches.Rectangle((0, 0), 500, 266, linewidth=1, edgecolor='r', facecolor='none')
# Add the patch to the Axes
ax.add_patch(rect)
plt.savefig('test.png')
|
b5df62bc2e9a10650fa5c11d96821ee938d30a8a
|
[
"Markdown",
"Python",
"Shell"
] | 8
|
Python
|
JakubSekula/License-plate-detection
|
fe5040ac00ea566a7eee99dfb35ddff94f1dd496
|
d6fdd8c8f895438ced134337838eaf1599a21d46
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import NewTodoForm from './NewTodoForm';
import Todo from './Todo';
import { v4 as uuid } from 'uuid';
import './TodoList.css';
export default class TodoList extends Component {
constructor(props) {
super(props);
this.state = {
todos: [],
};
}
addTodo = (todo) => {
let newTodo = {
...todo,
done: false,
id: uuid(),
created: new Date(),
};
this.setState((st) => ({ todos: [...st.todos, newTodo] }));
};
editTodo = (editedTodo) => {
const todos = this.state.todos.map((todo) => {
if (todo.id === editedTodo.id) {
return {
...todo,
text: editedTodo.text,
priority: editedTodo.priority,
};
}
return todo;
});
this.setState({ todos });
};
removeTodo = (id) => {
this.setState((st) => ({
todos: st.todos.filter((todo) => todo.id !== id),
}));
};
toggleDone = (id) => {
this.setState((st) => ({
todos: st.todos.map((todo) => {
if (todo.id === id) return { ...todo, done: !todo.done };
else return todo;
}),
}));
};
render() {
const list = this.state.todos.map((todo) => (
<Todo
key={todo.id}
id={todo.id}
text={todo.text}
priority={todo.priority}
done={todo.done}
created={todo.created}
editTodo={this.editTodo}
remove={() => this.removeTodo(todo.id)}
toggle={() => this.toggleDone(todo.id)}
/>
));
return (
<div className="TodoList">
<h1>Todos</h1>
<NewTodoForm addTodo={this.addTodo} />
<div className="TodoList-table">{list}</div>
</div>
);
}
}
<file_sep>import React, { Component } from 'react';
import './NewTodoForm.css';
export default class NewTodoForm extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
priority: '',
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleSubmit = (e) => {
e.preventDefault();
this.props.addTodo(this.state);
this.setState({
text: '',
priority: '',
});
};
render() {
return (
<form className="NewTodoForm" onSubmit={this.handleSubmit}>
<input
type="text"
name="text"
title="Todo text"
placeholder="Todo"
value={this.state.text}
onChange={this.handleChange}
/>
<input
type="number"
name="priority"
title="Todo priority"
placeholder="Priority"
value={this.state.priority}
onChange={this.handleChange}
/>
<button>Add</button>
</form>
);
}
}
<file_sep>import React, { Component } from 'react';
import './Todo.css';
import './NewTodoForm.css';
export default class Todo extends Component {
constructor(props) {
super(props);
this.state = {
text: this.props.text,
priority: this.props.priority,
id: this.props.id,
editing: false,
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
handleSubmit = (e) => {
e.preventDefault();
this.props.editTodo(this.state);
this.setState({
editing: false,
});
};
startEdit = () => {
this.setState({
editing: true,
});
};
render() {
const compClass = this.props.done ? 'done' : 'notdone';
const editForm = (
<form className="Todo-EditTodoForm" onSubmit={this.handleSubmit}>
<input
type="text"
name="text"
title="Todo text"
placeholder="Todo"
value={this.state.text}
onChange={this.handleChange}
/>
{/* <label for="priority">Priority:</label>
<select
id="priority"
name="priority"
title="Todo priority"
value={this.state.priority}
onChange={this.handleChange}
>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select> */}
<input
type="number"
name="priority"
min="1"
max="3"
title="Todo priority"
placeholder="Priority"
value={this.state.priority}
onChange={this.handleChange}
/>
<button>Edit</button>
</form>
);
const todoBody = (
<div className="Todo-body">
<div
className={`Todo-checkbox ${compClass}`}
onClick={this.props.toggle}
/>
<div className={`Todo-text ${compClass}`} onClick={this.props.toggle}>
{this.props.text}
</div>
<div className="Todo-button Todo-edit" onClick={this.startEdit}>
Edit
</div>
<div className="Todo-button Todo-remove" onClick={this.props.remove}>
Remove
</div>
</div>
);
return (
<div className="Todo">{this.state.editing ? editForm : todoBody}</div>
);
}
}
<file_sep>import React, { Component } from 'react'
import './NewTodoForm.css'
export default class NewTodoForm extends Component {
constructor(props) {
super(props)
this.state = {
text: this.props.text,
priority: this.props.priority,
id: this.props.id
}
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
}
handleSubmit = e => {
e.preventDefault();
this.props.editTodo(this.state)
}
render() {
return (
<form className='NewTodoForm'
onSubmit={this.handleSubmit}>
<input
type="text"
name="text"
title="Todo text"
placeholder="Todo"
value={this.state.text}
onChange={this.handleChange}
/>
<input
type="number"
name="priority"
min="1"
max="3"
title="Todo priority"
placeholder="Priority"
value={this.state.priority}
onChange={this.handleChange}
/>
<button>Edit</button>
</form>
)
}
}
|
94499b7a67f0d49faef2266f4786e288e68b8fa4
|
[
"JavaScript"
] | 4
|
JavaScript
|
zaharano/cra-todos
|
375fbe0a1f2c2cd6f6e0b6ae8ecd448de2ef4e8f
|
0cee01773ddb87b90ff8d17f15622cb1e0eeebb6
|
refs/heads/master
|
<repo_name>marcosjmarin/practica1-pav2<file_sep>/src/app/app.component.ts
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular ' + VERSION.major;
text = 'Listado Articulos';
bandera = true;
articulos: any[] = [
{
id: 2,
nombre: '<NAME>',
puntaje: 5
},
{
id: 5,
nombre: '<NAME>',
puntaje: 3
}
];
mostrarBoton(): void {
this.bandera = !this.bandera;
}
onPuntajeClicked(mensaje: string): void {
this.text = 'Lista de Artículos - ' + mensaje;
}
}
<file_sep>/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { PUNTAJEComponent } from './puntaje/puntaje.component';
import { DetalleComponent } from './detalle/detalle/detalle.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [
AppComponent,
HelloComponent,
PUNTAJEComponent,
DetalleComponent,
BrowserModule,
FormsModule,
RouterModule.forRoot([
//{ path: 'articulos', component: ListaArticulosComponent },
{ path: 'articulo/:id', component: DetalleComponent }
//{ path: 'inicio', component: InicioComponent },
//{ path: '', redirectTo: 'inicio', pathMatch: 'full' },
//{ path: '**', component: PaginaNoEncontradaComponent }
])
],
bootstrap: [AppComponent]
})
export class AppModule {}
<file_sep>/src/app/puntaje/puntaje.component.ts
import {
Component,
OnChanges,
Input,
Output,
EventEmitter
} from '@angular/core';
@Component({
selector: 'app-puntaje',
templateUrl: './puntaje.component.html',
styleUrls: ['./puntaje.component.css']
})
export class PUNTAJEComponent implements OnChanges {
@Input() puntaje: number = 4;
puntajeAncho: number;
@Output() puntajeClicked: EventEmitter<string> = new EventEmitter<string>();
constructor() {}
ngOnChanges(): void {
this.puntajeAncho = (this.puntaje * 68) / 5;
}
onClick(): void {
this.puntajeClicked.emit('El puntaje es: ' + this.puntaje);
}
}
<file_sep>/README.md
# practica1-pav2
[Edit on StackBlitz ⚡️](https://stackblitz.com/edit/practica1-pav2)
|
fdb05037e03abd4a230c19a1ecdd97e1bac86416
|
[
"Markdown",
"TypeScript"
] | 4
|
TypeScript
|
marcosjmarin/practica1-pav2
|
511f63de37077421027f80a7fd2e69885c9ea67c
|
daaecd65257c3bae60ad96f067ab84b3691bf0db
|
refs/heads/master
|
<file_sep>'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}])
.filter('mapUrl', function() {
return function(e) {
var str = "";
for (var i=0;i<e.length;i++) {
str += typeof e[i].name === 'undefined' ||
e[i].name.localeCompare('') === 0 ?
e[i].latitude + ',' + e[i].longitude + '%7C' :
e[i].name + '%7C';
}
str = str.replace(/ /g, '%20');
return str.replace(/%7C$/, '');
};
});
<file_sep># magic-map
#### A dynamic POI map
An AngularJS proof of concept of app. It uses the static Google Maps API to dynamically load and unload pins for POIs.
|
85cdc0b965aef565c822e347c54850b313b06fd5
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
paulmatthews/magic-map
|
77dcb98301ebd6f87dca3381d495a5f7c4dd0e36
|
80c29cb8b4bb20818411a28389140c9a9dafd74c
|
refs/heads/main
|
<file_sep># gocourse
Teste e aprendizado na linguagem GO (GoLang)
|
6c8e61b1806c3ac585902f7e3b234b1a9f95b59d
|
[
"Markdown"
] | 1
|
Markdown
|
ilustregiuli/gocourse
|
5ee7a06dff93821ee4db1977f4835b8a01c85fed
|
7b20cab732c3ff7a815f38bf803dcbc31f3e9796
|
refs/heads/master
|
<file_sep>package id.fdl.tugas3;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.textfield.TextInputLayout;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import id.fdl.tugas3.room.KreditNasabah;
import id.fdl.tugas3.room.KreditNasabahViewModel;
public class KreditNasabahUpdateFragment extends Fragment {
private KreditNasabahViewModel kreditNasabahViewModel;
private TextInputLayout textInputNameLayout;
private String name;
private TextInputLayout textInputNorekLayout;
private int norek;
private TextInputLayout textInputJumlahTagihanLayout;
private double jumlahTagihan;
private TextInputLayout textInputTanggalJatuhTempo;
private String tanggalJatuhTempo;
private Button roomSaveButton;
private static final String ID = "ID";
private static final String NAME = "NAME";
private static final String NOREK = "NOREK";
private static final String JUMLAH_TAGIHAN = "JUMLAH_TAGIHAN";
private static final String TANGGAL_JATUH_TEMPO = "TANGGAL_JATUH_TEMPO";
private int id;
private String nameFromDialog;
private int norekFromDialog;
private double jumlahTagihanFromDialog;
private Date tanggalJatuhTempoFromDialog;
public static KreditNasabahUpdateFragment newInstance(int id, String name, int norek, double jumlahTagihan, String tanggalJatuhTempo){
Bundle args = new Bundle();
args.putInt(ID, id);
args.putString(NAME, name);
args.putInt(NOREK, norek);
args.putDouble(JUMLAH_TAGIHAN, jumlahTagihan);
args.putString(TANGGAL_JATUH_TEMPO, tanggalJatuhTempo);
KreditNasabahUpdateFragment kreditNasabahUpdateFragment = new KreditNasabahUpdateFragment();
kreditNasabahUpdateFragment.setArguments(args);
return kreditNasabahUpdateFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
kreditNasabahViewModel = new ViewModelProvider(requireActivity()).get(KreditNasabahViewModel.class);
if (getArguments().containsKey(ID)){
id = getArguments().getInt(ID);
nameFromDialog = getArguments().getString(NAME);
norekFromDialog = getArguments().getInt(NOREK);
jumlahTagihanFromDialog = getArguments().getDouble(JUMLAH_TAGIHAN);
tanggalJatuhTempoFromDialog = new Date(getArguments().getLong(TANGGAL_JATUH_TEMPO));
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.room_user_input, container, false);
textInputNameLayout = view.findViewById(R.id.textInputNameLayout);
textInputNameLayout.getEditText().setText(nameFromDialog);
textInputNorekLayout = view.findViewById(R.id.textInputNorekLayout);
textInputNorekLayout.getEditText().setText(norekFromDialog);
textInputJumlahTagihanLayout = view.findViewById(R.id.textInputJumlahTagihanLayout);
textInputJumlahTagihanLayout.getEditText().setText((int) jumlahTagihanFromDialog);
textInputTanggalJatuhTempo = view.findViewById(R.id.textInputTanggalJatuhTempo);
textInputTanggalJatuhTempo.getEditText().setText(dateToString(tanggalJatuhTempoFromDialog));
roomSaveButton = view.findViewById(R.id.roomSaveButton);
roomSaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name = textInputNameLayout.getEditText().getText().toString();
norek = Integer.valueOf(textInputNorekLayout.getEditText().getText().toString());
jumlahTagihan = Double.valueOf(textInputJumlahTagihanLayout.getEditText().getText().toString());
tanggalJatuhTempo = textInputTanggalJatuhTempo.getEditText().getText().toString();
KreditNasabah kreditNasabah = new KreditNasabah();
kreditNasabah.id = id;
kreditNasabah.name = name;
kreditNasabah.norek = norek;
kreditNasabah.jumlahTagihan = jumlahTagihan;
kreditNasabah.tanggalJatuhTempo = tanggalJatuhTempo;
kreditNasabahViewModel.update(kreditNasabah);
backToRoomFragment();
}
});
return view;
}
private void backToRoomFragment(){
requireActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.container_every_day, RoomFragment.newInstance())
.commitNow();
}
private Date toDate(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.parse(date);
}
private String dateToString(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(date);
}
}
<file_sep>package id.fdl.tugas3;
import android.view.View;
import id.fdl.tugas3.room.KreditNasabah;
public interface KreditNasabahClickableCallback {
void onClick(View view, KreditNasabah kreditNasabah);
}
<file_sep>package id.fdl.tugas3.notification;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import id.fdl.tugas3.R;
public class NotificationAlarmFragment extends Fragment {
public static final String ALARM_ACTION
= "ALARM_ACTION";
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private final int PENDING_INTENT_CODE = 1111;
public View rootView;
public Button alarmButton;
private BroadcastReceiver alarmBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(ALARM_ACTION))
Toast.makeText(requireActivity(), "Toas trigger by alarm via Pending Intent", Toast.LENGTH_SHORT).show();
}
};
public static NotificationAlarmFragment newInstance(){ return new NotificationAlarmFragment();}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.notification_alarm_fragment, container, false);
alarmButton = rootView.findViewById(R.id.fire_alarm);
alarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
fireAlarm();
}
});
return rootView;
}
@Override
public void onStart() {
super.onStart();
requireActivity().registerReceiver(alarmBroadcastReceiver, new IntentFilter(ALARM_ACTION));
}
@Override
public void onStop() {
requireActivity().unregisterReceiver(alarmBroadcastReceiver);
super.onStop();
}
private void fireAlarm(){
AlarmManager alarmMgr = (AlarmManager)requireActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ALARM_ACTION);
PendingIntent alarmIntent = PendingIntent.getBroadcast(requireActivity(), 0, intent, 0);
// reepeat every 1 minutes
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 1, alarmIntent);
}
}
<file_sep>package id.fdl.tugas3;
import android.content.Context;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class RoomActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_everyday);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_every_day, RoomFragment.newInstance())
.commitNow();
}
}
}
<file_sep>package id.fdl.tugas3.room;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import java.util.Date;
@Entity
public class KreditNasabah {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "name")
public String name;
@ColumnInfo(name = "norek")
public int norek;
@ColumnInfo(name = "tanggal_jatuh_tempo")
public String tanggalJatuhTempo;
@ColumnInfo(name = "jumlah_tagihan")
public double jumlahTagihan;
}
<file_sep>package id.fdl.tugas3;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_everyday);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_every_day, RoomMainFragment.newInstance())
.commitNow();
}
}
public void goToRoom(View view){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container_every_day, RoomFragment.newInstance())
.commitNow();
}
}
|
0e47274c7bafffed86b1e19eb3abfb2502eca42f
|
[
"Java"
] | 6
|
Java
|
fdl27/tugas3
|
d78e9e2d7fd0e90c52e07c3449e8cd08cf4358ea
|
49f8233a23ccc87614d08f6a4e32673f5c176ba6
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python3
# Created by: <NAME>
# Created on: Sep 2021
# This program multiplies each whole number that goes up to the users number
def main():
# This function multiplies each whole number that goes up to the users number
counter = 1
the_product = 1
# Input
integer_a_s = input("Enter a positive number: ")
print("")
# Process and Output
try:
integer_a_i = int(integer_a_s)
while counter <= integer_a_i:
the_product = the_product * counter
counter = counter + 1
print(
"The product of all positive numbers from 1 to {0} is {1}.".format(
integer_a_s, the_product
)
)
except Exception:
print("Invalid input.")
print("\nDone.")
if __name__ == "__main__":
main()
|
3e6f94688beac0b210cd4f4fd089cf5dfc5605d3
|
[
"Python"
] | 1
|
Python
|
Michael-Zagon/ICS3U-Unit4-02-Python
|
62534e1548b6d8da43b4211e5e0801d8b58ec98d
|
4e2c37696ee449c9c66d5acef801cb6a68ad46c0
|
refs/heads/master
|
<repo_name>MarinaFedorenko/NIX-Module-2<file_sep>/tasks_data/src/main/java/nix/data/ListOfDates.java
package nix.data;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class ListOfDates {
public static void task(List<String> dates){
Pattern regex1 = Pattern.compile("/\\d{2}/");
Pattern regex2 = Pattern.compile("-\\d{2}-");
List<String> result = dates.stream()
.filter(c->{
String r = c.replaceAll(regex1.toString(), "");
String m = c.replaceAll(regex2.toString(), "");
return !r.equals(c) || !m.equals(c);
})
.collect(Collectors.toList());
System.out.println(result);
}
}
<file_sep>/README.md
# NIX-Module-2
|
607e4f99748ebbc975f6437aa101ee66d340616f
|
[
"Markdown",
"Java"
] | 2
|
Java
|
MarinaFedorenko/NIX-Module-2
|
3c6fbd21d1979e6a29433ea73d389cf762bb4f32
|
4721c38b9815a1f99d9a0ad9f58a2b00ac5e5cfe
|
refs/heads/master
|
<file_sep>var nskana = (function() {
var spot = null;
var spotMarkers = {};
var map = null;
var selected = "";
var largemap = true;
/*-----------------------------------------*/
// Load spot.json
function getSpotDefaultData() {
$.ajax({
url: 'spot.json',
async: false,
dataType: 'json'
}).success(function(data) {
console.log('spot.json read successuly!');
spot = data;
}).error(function(data,text,err) {
console.log('spot.json read error!: ' + text);
});
}
// Create my_spot.json
var w = new $.Deferred;
function setSpotData() {
window.requestFileSystem(LocalFileSystem.PERSISTENT,
0,
gotFS,
function(evt) { console.log('E gotFS'); w.reject('E'); });
return w.promise();
}
function gotFS(fileSystem) {
console.log('gotFS!');
fileSystem.root.getFile('my_spot.json',
{ create: true, exclusive: false },
gotFileEntry,
function(evt) { w.reject('E'); });
}
function gotFileEntry(fileEntry) {
console.log('gotFileEntry!!');
fileEntry.createWriter(gotFileWriter,
function(evt) {
console.log("E gotFileWriter");
w.reject('E');
});
}
function gotFileWriter(writer) {
var string = JSON.stringify(spot);
writer.onwriteend = function(evt) {
console.log('OnTruncated!!');
writer.seek(0);
writer.onwriteend = function(evt) {
console.log('OnWriteEnd!!');
w.resolve();
};
writer.write(string);
w.resolve();
};
writer.onerror = function(evt) {
console.log('OnError!');
w.reject('E');
};
writer.onabort = function(evt) {
console.log('OnAbort');
w.reject('E');
};
writer.onwrite = function(evt) {
console.log('OnWrite!');
};
writer.truncate(0);
console.log('my_spot.json was written!!');
}
// Checking if my_spot.json exists.
var d = new $.Deferred;
function getSpotData() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
checkData,
function(evt) {
console.log('E checkData!');
d.reject('E');
});
return d.promise();
}
function checkData(fileSystem) {
var reader = fileSystem.root.createReader();
reader.readEntries(function(entries){
var i;
for ( i = 0; i< entries.length; i++){
}
},function(){ });
fileSystem.root.getFile('my_spot.json',
{ create: false, exclusive: false },
checkSavedFileEntry,
function(evt) {
console.log('E checkSavedFileEntry!');
console.log("my_spot doesn't exists!");
d.reject('E');
});
}
function checkSavedFileEntry(fileEntry) {
console.log('checkMyFileEntry!!');
fileEntry.file(checkFile,
function(evt) {
console.log('E checkFile!');
d.reject('E');
});
}
function checkFile(file) {
console.log('checkFile!');
var checker = new FileReader();
checker.onerror = function(evt) {
console.log('onError!');
d.reject('E'); };
checker.onabort = function(evt) {
console.log('onAbort!');
d.reject('E'); };
checker.onloadstart = function(evt) {
console.log('onStart!'); };
checker.onloadend = function(evt) {
console.log('OnLoadEnd!');
if (evt.target.result == null) {
console.log("my_spot file content doesn't exists!");
d.reject('E');
}else {
console.log('MY_SPOT file exists!');
spot = JSON.parse(evt.target.result);
d.resolve();
}
};
checker.readAsText(file);
console.log('my_spot file was read as Text!!');
}
/*-----------------------------------------*/
// Side Bar Provider.
function buildSpotList() {
for ( category in spot.categories ){
// Create Category
$("#spot_categories").append(
$('<li data-role="collapsible" data-inset="false" data-iconpos="right">').append(
$('<h3>').text(spot.categories[category].name),
$('<ul data-role="listview" id="'+ spot.categories[category].id +'">')
.listview().listview('refresh')
).collapsible().collapsible('refresh')
).listview().listview('refresh');
}
// Create MIDOKORO in Category
for ( i in spot.lists ){
var categoryset = spot.lists[i].category.split(',');
for ( j in categoryset ){
$("#"+categoryset[j]).append('<li><a href="index.html">' + spot.lists[i].title + '</a></li>');
$("#"+categoryset[j]).listview().listview('refresh');
$(document).on("click", "#"+ categoryset[j]+" li", function(event) {
selected = $(this).text();
$("#spotpanel").panel("close");
window.scrollTo(0,0);
});
}
}
}
/*--------------------------------------------*/
// Map Provider
function createMap() {
var KANAGAWA = new plugin.google.maps.LatLng(
spot.map.center.lat, spot.map.center.lng);
var map_button = document.getElementById('map-button');
map_button.addEventListener('click', onMapBtnClicked, false);
var div = document.getElementById('map_canvas');
map = plugin.google.maps.Map.getMap(div,
{'controls': { 'myLocationButton': true },
'camera': {'latLng': KANAGAWA, 'zoom': spot.map.zoomlevel }});
map.addEventListener(plugin.google.maps.event.MAP_READY, onMapReady);
$("#spotpanel").on('panelbeforeopen',function(){
});
$("#spotpanel").on('panelclose',function(){
map.setVisible(true);
spotMarkers[selected].getPosition(function(selected_latlng){
map.moveCamera({ 'target':selected_latlng, 'tilt':0, 'zoom':16 });
});
spotMarkers[selected].showInfoWindow();
for (k in spot.lists) {
if (selected == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(spot.lists[k].description);
$('#spot-howtogetthere').text(spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio("refresh");
}else {
$('#spot-check').prop("checked",false).checkboxradio("refresh");
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
map.setVisible(true);
buildSpotList();
}
function onMapReady(map) {
for (i in spot.lists) {
var motto_manabitai_basyo = new plugin.google.maps.LatLng(
spot.lists[i].position.lat, spot.lists[i].position.lng);
var opts = {};
opts['position'] = motto_manabitai_basyo;
opts['title'] = spot.lists[i].title;
opts['snippet'] = spot.lists[i].name;
if (spot.lists[i].status == 'checked') {
opts['icon'] = 'www/res/icons/green.png';
}else {
opts['icon'] = 'www/res/icons/red.png';
}
map.addMarker(opts, function(marker) {
spotMarkers[marker.getTitle()] = marker;
marker.addEventListener(
plugin.google.maps.event.MARKER_CLICK, function() {
$('#spot-name').text("");
$('#spot-description').text("");
$('#spot-howtogetthere').text("");
$('#spot-check').checkboxradio('disable');
$('#spot-check').checkboxradio('refresh');
marker.showInfoWindow();
for (k in spot.lists) {
if (marker.getTitle() == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(spot.lists[k].description);
$('#spot-howtogetthere').text(spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio('refresh');
}else{
$('#spot-check').prop("checked",false).checkboxradio('refresh');
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
marker.addEventListener(
plugin.google.maps.event.INFO_CLICK, function() {
for (k in spot.lists) {
if (marker.getTitle() == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(spot.lists[k].description);
$('#spot-howtogetthere').text(spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio('refresh');
}else{
$('#spot-check').prop("checked",false).checkboxradio('refresh');
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
});
}
var contentheight = $(window).height() - $('#map-header').height() - $('#map-footer').height();
divmap.style.height = contentheight / 2 + 'px';
map.refreshLayout();
}
// Register Event Listener (Right Button on Header)
function onMapBtnClicked() {
if ( largemap ) {
var divmap = document.getElementById('map_canvas');
var contentheight = $(window).height() - $('#map-header').height() - $('#map-footer').height();
divmap.style.height = contentheight + 'px';
map.refreshLayout();
largemap = false;
$("#map-button").text("小さな地図").button('refresh');
}else{
var divmap = document.getElementById('map_canvas');
var contentheight = $(window).height() - $('#map-header').height() - $('#map-footer').height();
divmap.style.height = contentheight / 2 + 'px';
map.refreshLayout();
largemap = true;
$("#map-button").text("大きな地図").button('refresh');
}
}
// Register Event Listener ( ITTA CheckBox )
function onFlipDisabled() {
$('#spot-check').checkboxradio('disable');
}
function onFlipChanged() {
$('#spot-check').on('change', function(evt) {
var val = $('#spot-check').prop("checked");
var name = $('#spot-name').text();
if (val == true) {
for (i in spot.lists) {
if (spot.lists[i].name == name) {
spot.lists[i].status = 'checked';
var marker = spotMarkers[spot.lists[i].title];
if (marker != null) {
console.log('green!');
marker.remove();
var motto_manabitai_basyo = new plugin.google.maps.LatLng(
spot.lists[i].position.lat,
spot.lists[i].position.lng);
var opts = {};
opts['position'] = motto_manabitai_basyo;
opts['title'] = spot.lists[i].title;
opts['snippet'] = spot.lists[i].name;
if (spot.lists[i].status == 'checked') {
opts['icon'] =
'www/res/icons/green.png';
}else {
opts['icon'] =
'www/res/icons/red.png';
}
map.addMarker(opts, function(marker) {
spotMarkers[marker.getTitle()] = marker;
marker.addEventListener(
plugin.google.maps.event.MARKER_CLICK, function() {
$('#spot-name').text("");
$('#spot-description').text("");
$('#spot-howtogetthere').text("");
$('#spot-check').checkboxradio('disable');
$('#spot-check').checkboxradio('refresh');
marker.showInfoWindow();
for (k in spot.lists) {
if (marker.getTitle() == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(
spot.lists[k].description);
$('#spot-howtogetthere').text(
spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio('refresh');
}else{
$('#spot-check').prop("checked",false).checkboxradio('refresh');
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
marker.addEventListener(
plugin.google.maps.event.INFO_CLICK, function() {
for (k in spot.lists) {
if (marker.getTitle() == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(
spot.lists[k].description);
$('#spot-howtogetthere').text(
spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio('refresh');
}else{
$('#spot-check').prop("checked",false).checkboxradio('refresh');
}
var imageset = spot.lists[k].image.split(',');
for ( var img_index in imageset ){
var image_tag = "<img src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
});
console.log('greened!');
}
}
}
}else{
for (i in spot.lists) {
if (spot.lists[i].name == name) {
spot.lists[i].status = 'unchecked';
var marker = spotMarkers[spot.lists[i].title];
if (marker != null) {
console.log('red!');
marker.remove();
var motto_manabitai_basyo = new plugin.google.maps.LatLng(
spot.lists[i].position.lat,
spot.lists[i].position.lng);
var opts = {};
opts['position'] = motto_manabitai_basyo;
opts['title'] = spot.lists[i].title;
opts['snippet'] = spot.lists[i].name;
if (spot.lists[i].status == 'checked') {
opts['icon'] =
'www/res/icons/green.png';
}else {
opts['icon'] =
'www/res/icons/red.png';
}
map.addMarker(opts, function(marker) {
spotMarkers[marker.getTitle()] = marker;
marker.addEventListener(
plugin.google.maps.event.MARKER_CLICK, function() {
marker.showInfoWindow();
});
marker.addEventListener(
plugin.google.maps.event.INFO_CLICK, function() {
for (k in spot.lists) {
if (marker.getTitle() == spot.lists[k].title) {
$('#spot-name').text(spot.lists[k].name);
$('#spot-description').text(
spot.lists[k].description);
$('#spot-howtogetthere').text(
spot.lists[k].howtogetthere);
$('#spot-check').checkboxradio('enable');
if (spot.lists[k].status == 'checked') {
$('#spot-check').prop("checked",true).checkboxradio('refresh');
}else{
$('#spot-check').prop("checked",false).checkboxradio('refresh');
}
// Set Images and Captions
var imageset = spot.lists[k].image.split(',');
var captionset = spot.lists[k].caption.split(',');
$('.image_contents').remove();
$('.image_captions').remove();
for ( var img_index in imageset ){
var image_tag = "<img class=\"image_contents\" src=\"" + imageset[img_index] + "\" />";
$('#images').append(image_tag);
var caption_tag = "<p class=\"image_captions\" >" + captionset[img_index] + "</p><br class=\"image_captions\" />";
$('#images').append(caption_tag);
}
}
}
});
});
console.log('reded!');
}
}
}
}
setSpotData();
});
}
function Api() {
}
Api.prototype.go = function() {
getSpotDefaultData();
getSpotData()
.then(createMap,createMap)
.then(onFlipDisabled())
.then(onFlipChanged());
};
var kana = {
create: function() {
return new Api();
}
};
return kana;
})();
<file_sep>##android リリースビルド手順
### アイコンを作成する
1. cd platforms/android/res
2. drawableフォルダ以下のすべてのPNGファイルを変更する
### リリースビルド用のパスワードを作成する
1. cd platforms/android
2. keytool -genkey -v -keystore app.keystore -alias app -keyalg RSA -keysize 2048 -validity 10000
3. 質問に答える
4. パスワードを入力する
###リリースビルドを作成する
1. release-signing.propertiesファイルを作成する
2. storeFile=app.keystoreと入力
3. storeType=jksと入力
4. keyAlias=appと入力
5. cordova build android —-release
6. platforms/android/build/outputs/apk/android-relase.apkができていることを確認する
###リリースビルドを再作成する
1. cordova build android —-release
2. platforms/android/build/outputs/apk/android-relase.apkができていることを確認する
<file_sep>旧東海道戸塚宿めぐり(Totsuka Meguri)
=======================================
まさかりを滝壺に落としたら、偶然魔物に当たって退治したことになってお姫様が現れ、という日本昔話的伝説の残る「まさかりが淵」など旧東海道戸塚宿周辺の史跡の場所が分かるアプリです。
Snapshot
========

Support Platform
================
* iOS/iPhone
* Android
License
==================================
アプリのソースコードと画像のライセンスはMIT Licenseです。
Copyright (c) 2014 <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.
Notice
======
アプリ内の説明文は戸塚見知楽会の著作物です。本リポジトリには含まれません。
HowToBuild
==========
Step1: Install [cordova](http://cordova.apache.org)
Step2: Create your app
> $ cordova create "directory name" "reverse domain-style identifier" "app title"
Step2: Install following platforms to cordova
> $ cordova platform add ios
> $ cordova platform add android
Step3: Install following plugins to cordova
* org.apache.cordova.console 0.2.11 "Console"
* org.apache.cordova.device 0.2.12 "Device"
* org.apache.cordova.dialogs 0.2.10 "Notification"
* org.apache.cordova.file 1.3.1 "File"
* org.apache.cordova.file-transfer 0.4.6 "File Transfer"
* org.apache.cordova.splashscreen 0.3.3 "Splashscreen"
* org.apache.cordova.statusbar 0.1.8 "StatusBar"
* plugin.google.maps 1.2.2 "phonegap-googlemaps-plugin"
Step4: Put all the files in this repository into your app directory
Step5: Rename spot.json.default to spot.json
Step6: Edit spot.json
* map center position latlng
* map zoomlevel
* spot title
* spot name
* spot position
* spot status { checked or unchecked }
* spot image
* spot description
* hot to get the spot
Step7: Edit config.xml ( please use config.xml.default as reference )
<file_sep>##android リリースビルド手順
### アイコンを作成する
1. cd platforms/android/res
2. drawableフォルダ以下のすべてのPNGファイルを変更する
### リリースビルド用のパスワードを作成する
1. cd platforms/android/ant-build
2. keytool -genkey -v -keystore app.keystore -alias app -keyalg RSA -keysize 2048 -validity 10000
3. 質問に答える
4. パスワードを入力する
###リリースビルドを作成する
1. cordova build android —-release
2. cd platforms/android/ant-build/
3. platforms/android/ant-build/MainActivity-release.unsigned.apkができていることを確認する
4. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore app.keystore MainActivity-release.unsigned.apk MainActivity.apk
5. リリースビルド用のパスワードを入力する(何も表示されません)
6. C:¥¥user¥<your name>¥AppData¥Local¥Android¥sdk¥build-tools¥21.1.2¥zipalign -v 4 MainActivity-release-unsigned.apk MainActivity.apk
###リリースビルドを再作成する
1. cd platforms/android/ant-build
2. ls -all
3. MainActivity.apkがあることを確認しあれば rm MainActivity.apk を実行しMainActivity.apkを削除する
4. cordova build android —-release
5. cd platforms/android/ant-build
6. ls -all
7. MainActivity-release-unsigned.apkができていて、今日の日付になっていることを確認する
8. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore app.keystore MainActivity-release.unsigned.apk MainActivity.apk
9. リリースビルド用のパスワードを入力する(何も表示されません)
10. C:¥¥user¥<your name>¥AppData¥Local¥Android¥sdk¥build-tools¥21.1.2¥zipalign -v 4 MainActivity-release-unsigned.apk MainActivity.apk <file_sep>## 1: 開発環境を作る
### 1.1: Javaをインストールする
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
JDKのバージョン7をインストールする
OSが32ビットならjdk-7u79-windows-i586.exeをダウンロードし手順に従ってインストール
OSが64ビットならjdk-7u79-windows-x64.exeをダウンロードし手順に従ってインストール
### 1.2: Antをインストールする
http://ant.apache.org/bindownload.cgi
apache-ant-1.9.5-bin.zipを任意のフォルダに解凍する
詳細はこちら:http://www.javadrive.jp/ant/install/index1.html
ANT_HOMEとPATHを設定する
詳細はこちら:http://www.javadrive.jp/ant/install/index2.html
### 1.3: Androidをインストールする
https://developer.android.com/sdk/index.html
DOWNLOAD ANDROID STUDIO FOR windowsをクリックし手順に従ってインストール
### 1.4: 必要なライブラリをインストールする
Androidstudioを起動
Configureを選択
SDKマネージャを選択
Tools以下の下記をインストール
+ Android SDK Tools 24.1.2
+ Android SDK Platform-tools 22
+ Android SDK Build-tools 21.1.2
+ Android SDK Build-tools 19.1
+ Android SDK Build-tools 19
Android 5.1.1(API22)以下の下記をインストール
+ Documentation for Android SDK 22
+ SDK Platform 22
+ Samples for SDK 22
+ Android TV ARM EABI v7a System Image 22
+ Android TV Intel x86 Atom Sytem Image 22
+ ARM EABI v7a System Image
+ Intel x86 Atom_64 System Image
+ Intel x86 Atom System Image
+ Google APIs
+ Google APIs ARM EABI v7a System Image
+ Google APIs Intel x86 Atom_64 System Image
+ Google APIs Intel x86 Atom System Image
Android 5.0.1(API21)以下の下記をインストール
+ SDK Platform 21
+ ARM EABI v7a System Image 21
+ Google APIs 21
+ Google APIs Intel x86 Atom System Image 21
+ Sources for Android SDK 21
Android 4.4.2(API19)以下の下記をインストール
+ SDK Platform 19
+ Samples for SDK 19
+ ARM EABI v7a System Image 19
+ Intel x86 Atom System Image 19
+ Google APIs(x86 System Image) 19
+ Google APIs (ARM System Image) 19
+ Sources for Android SDK 19
Extra以下の下記をインストール
+ Android Support Registory 12
+ Android Support Library 12
+ Google Repository 16
+ Google USB Driver
+ Intel x86 Emulator Accelerator(HAXM installer)
### 1.5: git/gitBASHをインストールする
https://msysgit.github.io
Welcomeページでネクストボタンをクリック
ライセンスを確認しネクストボタンをクリック
インストールフォルダを確認しネクストボタンをクリック
Gitbash Here を選択しネクストボタンをクリック
後は全てネクストボタンをクリックしインストールする
### 1.6: Node.jsをインストールする
https://nodejs.org/download/
Windows installerをクリックし手順に従ってインストール
### 1.7: Cordovaをインストールする
コマンドプロンプトを開く
次のコマンドを実行
C:\>npm install -g cordova
### 1.8: サンプルアプリで確認する
gitBASHを開いて次のコマンドを実行
$ cordova create hello com.example.hello HelloWorld
$ cd hello
$ cordova platform add android
$ cordova build
$ cordova emulate android
### 1.9: サンプルアプリを実機で確認する
アンドロイド実機の「端末情報」を選択
ビルド番号を7回連続でタップ
開発者オプションが表示される
USBデバッグにチェックを入れる
端末のVIDとPIDを確認する
詳細はこちら:http://note.chiebukuro.yahoo.co.jp/detail/n128056
android_winusb.infを編集する
詳細はこちら:http://note.chiebukuro.yahoo.co.jp/detail/n128056
ドライバのインストール
署名なしのドライバをインストールする方法詳細はこちら:http://www.teradas.net/archives/9922/
$ cordova run android
## 2: GoogleMapを利用するための準備をする
### 2.1: SHA-1を確認する
SHA-1を確認する
コマンドプロンプトを開く
Android SDK Platform-toolsとAndroid SDK Build-toolsフォルダにパスが通っていることを確認する
JAVAのbinフォルダ(WindowsならC:\Program Files\Java\jre7\binなど)にパスが通っている事を確認する
次のコマンドを実行する
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android keypass android
SHA-1と表示されている部分をコピーする
### 2.2: キーを登録する
googleのアカウントを作成する
下記URLにアクセスする
https://code.google.com/apis/console/?noredirect#project:867507542052:access
画面左のAPI Access をクリック
画面下のCreate New Android Key をクリック
SHA-1を入力する
":"を入力する
任意のAPIキー(com.sample.myapp)を入力する
## 3:戸塚アプリを作る
### 3.1: プロジェクトを作る
アプリ名を決める
<App Name> (例えばHello)
次のコマンドを実行する
cordova create <App Name> com.example.app “app”
### 3.2: android対応にする
次のコマンドを実行(App NamgeがHelloの場合はcd Hello)
cd <App Name>
cordova platform add android
### 3.3: googlemapプラグインをインストールする
cordova plugin add plugin.google.maps --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE"
### 3.4: ソースをダウンロードする
git clone https://github.com/masa8/totsuka_meguri.git
### 3.5: ソースをコピーする
index.htmlとspot.jsをwww以下にコピーする
### 3.6: ビルド、実行する
cordova build android
cordova run android
## 4:戸塚アプリを修正する
### 4.1:コンテンツを修正する
spot.jsonを任意に修正する
史跡を追加する
カテゴリを追加する
タイトルを追加する
名前を追加する
位置を追加する
画像を追加する
説明を追加する
行き方を追加する
### 4.2: ビルド、実行する
次のコマンドを実行する
cordova build android
cordova run android
|
7d9bd044f452050ce9ccd848aabb49fbd52a4339
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
masa8/totsuka_meguri
|
b8bd5b218fec6e964efb348073d4ce42fe026ae9
|
59e223a9022710c4737bd24d06c54ad2ee4efb9b
|
refs/heads/master
|
<repo_name>AccXite/local-weather-app<file_sep>/src/app/WeaterService/IWeatherService.ts
import { ICurrentWeather } from '../interfaces';
import { Observable } from 'rxjs';
export interface IWeatherService {
getCurrentWeather(city: string, country: string): Observable<ICurrentWeather>;
}
<file_sep>/src/app/WeaterService/weather.service.fake.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Observable, Subject, BehaviorSubject, of } from 'rxjs';
import { ICurrentWeather } from '../interfaces';
import { map } from 'rxjs/operators';
import { IWeatherService } from './IWeatherService';
import { HttpClientTestingModule } from '@angular/common/http/testing';
@Injectable({
providedIn: 'root',
})
export class WeatherServiceFake implements IWeatherService {
private fakeWeather: ICurrentWeather = {
city: 'Bursa',
country: 'TR',
date: 1485789600,
image: '',
temperature: 280.32,
description: 'light intensity drizzle',
};
// constructor(private httpClient: HttpClientTestingModule) {}
getCurrentWeather(
search: string | number,
country?: string
): Observable<ICurrentWeather> {
return of(this.fakeWeather);
}
}
|
e5e1fbe707b5fca6634d5e5baee34f3a8cfa4766
|
[
"TypeScript"
] | 2
|
TypeScript
|
AccXite/local-weather-app
|
267da7701d45d95d64936da809f21b15de235aa5
|
45910d4ff1664607e67b677626c99323e9799218
|
refs/heads/main
|
<repo_name>Dannyyny/Emojee<file_sep>/Emojee/Controllers/EmojeeViewController.swift
//
// EmojeeViewController.swift
// Emojee
//
// Created by <NAME> on 3/30/21.
//
import UIKit
import Firebase
class EmojeeViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var computerButton: UIButton!
@IBOutlet weak var friendButton: UIButton!
@IBOutlet weak var helpButton: UIButton!
@IBOutlet weak var logOutButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.hidesBackButton = true
}
@IBAction func logOutButtonPressed(_ sender: UIButton) {
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
<file_sep>/Emojee/Constants.swift
//
// Constants.swift
// Emojee
//
// Created by <NAME> on 3/31/21.
//
struct Constants {
static let appName = "Emojee"
static let registerSegue = "RegisterToMainPage"
static let loginSegue = "LoginToMainPage"
static let cellIdentifier = "ReusableCell"
}
<file_sep>/Emojee/Controllers/CustomCollectionViewCell.swift
//
// CustomCollectionViewCell.swift
// Emojee
//
// Created by <NAME> on 4/7/21.
//
import UIKit
class CustomCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
<file_sep>/Emojee/Controllers/RegisterViewController.swift
//
// RegisterViewController.swift
// Emojee
//
// Created by <NAME> on 3/30/21.
//
import UIKit
import Firebase
class RegisterViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var emailTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
@IBOutlet weak var registerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
registerButton.layer.cornerRadius = 20
emailTextfield.layer.cornerRadius = 10
passwordTextfield.layer.cornerRadius = 10
}
@IBAction func registerButtonPressed(_ sender: UIButton) {
if let email = emailTextfield.text, let password = passwordTextfield.text {
Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { authResult, error in
if let e = error {
print(e.localizedDescription)
} else {
// navigate to the EmojeeViewContrller
self.performSegue(withIdentifier: Constants.registerSegue, sender: self)
}
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
//extension UIViewController {
// class func loadFromNib() -> Self {
// return self.init(nibName: String(describing: self), bundle: nil)
// }
//}
<file_sep>/README.md
# Emojee
Description:
This project is to create an iOS application which includes an authentication page,
allowed user to register and log in using their own account.
And the users can save their favorite emojees and also share with their friends.
How it looks like:

<file_sep>/Emojee/Controllers/FriendViewController.swift
//
// FriendViewController.swift
// Emojee
//
// Created by <NAME> on 4/1/21.
//
import UIKit
class FriendViewController: UIViewController {
let emojees = ["1","2","3","4","5","6","7","8","9","10",
"11","12","13","14","15","16","17","18","19","20",
"21","22","23","24","25","26","27","28","29","30",
"31","32","33","34","35","36","37","38","39","40",
"41","42","43","44","45","46","47","48","49","50",
]
@IBOutlet weak var sendToFriendPressed: UIButton!
@IBOutlet weak var topImage: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
sendToFriendPressed.layer.cornerRadius = 20
}
}
extension FriendViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return emojees.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! FriendPageCell
cell.emojeeImageView.image = UIImage(named: emojees[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedCell = collectionView.cellForItem(at: indexPath) as! FriendPageCell
topImage.image = selectedCell.emojeeImageView.image
}
}
/*
extension UIImageView {
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { [weak self] in
self?.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
extension String {
func image() -> UIImage? {
let size = CGSize(width: 100, height: 100)
UIGraphicsBeginImageContextWithOptions(size, false, 0);
UIColor.clear.set()
let stringBounds = (self as NSString).size(withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 75)])
let originX = (size.width - stringBounds.width)/2
let originY = (size.height - stringBounds.height)/2
print(stringBounds)
let rect = CGRect(origin: CGPoint(x: originX, y: originY), size: size)
UIRectFill(rect)
(self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 75)])
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
<file_sep>/Emojee/Controllers/ComputerViewController.swift
//
// ComputerViewController.swift
// Emojee
//
// Created by <NAME> on 4/7/21.
//
import UIKit
class ComputerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var tableView: UITableView!
let dataModel = generate2DArrayofColor(withRows: 20, itemInEachRow: 15)
override func viewDidLoad() {
super.viewDidLoad()
favoriteButton.layer.cornerRadius = 20
tableView.delegate = self
tableView.dataSource = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tcell", for: indexPath)
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let tableViewCell = cell as? CustomTableViewCell {
tableViewCell.setCollectionViewDelegate(delegate: self, forRow: indexPath.row)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
extension ComputerViewController: UICollectionViewDelegate, UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataModel[collectionView.tag].count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ccell", for: indexPath) as? CustomCollectionViewCell {
let imageName = dataModel[collectionView.tag][indexPath.row]
cell.imageView?.image = UIImage(named: "\(imageName).png")
cell.layer.cornerRadius = cell.bounds.height / 2.0
//cell.toggleSelected()
return cell
}
return UICollectionViewCell()
}
}
// helper function
func generate2DArrayofColor(withRows: Int, itemInEachRow: Int) -> [[Int]] {
let numberOfRows = withRows
let numberOfItemsInEachRow = itemInEachRow
var color2DArray = [[Int]]()
for _ in 1...numberOfRows {
var singleArray = [Int]()
for _ in 1...numberOfItemsInEachRow {
singleArray.append(Int(arc4random_uniform(50) + 1))
}
color2DArray.append(singleArray)
}
return color2DArray
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
<file_sep>/Emojee/Controllers/EmojeeCollectionViewCell.swift
//
// EmojeeCollectionViewCell.swift
// Emojee
//
// Created by <NAME> on 4/7/21.
//
import UIKit
class EmojeeCollectionViewCell: UICollectionViewCell {
}
<file_sep>/Emojee/Controllers/WelcomeViewController.swift
//
// ViewController.swift
// Emojee
//
// Created by <NAME> on 3/25/21.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var signInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
signUpButton.layer.cornerRadius = 30
signInButton.layer.cornerRadius = 30
}
@IBAction func SignUpButton(_ sender: UIButton) {
//let secondVC = SecondViewController()
//self.present(secondVC, animated: true, completion: nil)
//self.performSegue(withIdentifier: "toSecondPage", sender: self)
}
@IBAction func LoginButton(_ sender: UIButton) {
//self.performSegue(withIdentifier: "toSecondPage", sender: self)
}
}
<file_sep>/Emojee/Controllers/CustomTableViewCell.swift
//
// CustomTableViewCell.swift
// Emojee
//
// Created by <NAME> on 4/7/21.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var collectionView: UICollectionView!
func setCollectionViewDelegate<D: UICollectionViewDelegate & UICollectionViewDataSource>(delegate: D, forRow row: Int){
collectionView.delegate = delegate
collectionView.dataSource = delegate
collectionView.tag = row
collectionView.reloadData()
}
}
<file_sep>/Emojee/Controllers/FriendPageCell.swift
//
// FriendPageCell.swift
// Emojee
//
// Created by <NAME> on 4/8/21.
//
import UIKit
class FriendPageCell: UICollectionViewCell {
@IBOutlet weak var emojeeImageView: UIImageView!
}
<file_sep>/Emojee/Controllers/LoginViewController.swift
//
// LoginViewController.swift
// Emojee
//
// Created by <NAME> on 3/30/21.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var emailTextfield: UITextField!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var passwordTextfield: UITextField!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
emailTextfield.layer.cornerRadius = 10
passwordTextfield.layer.cornerRadius = 10
loginButton.layer.cornerRadius = 20
}
@IBAction func loginPressed(_ sender: UIButton) {
if let email = emailTextfield.text, let password = <PASSWORD>Textfield.text {
Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { authResult, error in
if let e = error {
print(e.localizedDescription)
} else {
// navigate to the EmojeeViewContrller
self.performSegue(withIdentifier: Constants.loginSegue, sender: self)
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
ac4a135d33b4840ab6a53de88fd18749a3f8f44b
|
[
"Swift",
"Markdown"
] | 12
|
Swift
|
Dannyyny/Emojee
|
5df83471d044a6a71039d853af44cd96c45ffe24
|
2256aa3b1a7ebbfc2298bbd8e078a6beeb649e55
|
refs/heads/main
|
<file_sep>import { Route, BrowserRouter as Router, Switch } from "react-router-dom";
import "./App.css";
import Login from "./Login";
import Singup from "./Signup";
import Timeline from "./Timeline";
import Explore from "./Explore";
import Profile from "./Profile";
import Post from "./Post";
function App() {
return (
<Router>
<div className="App">
<Switch>
<Route exact path="/">
<Login />
</Route>
<Route path="/signup">
<Singup />
</Route>
<Route path="/timeline">
<Timeline />
</Route>
<Route path="/explore">
<Explore />
</Route>
<Route path="/profile/:name">
<Profile />
</Route>
<Route path="/post/:id">
<Post />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
<file_sep>import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import "firebase/storage";
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "instaa-gram.firebaseapp.com",
projectId: "instaa-gram",
storageBucket: "instaa-gram.appspot.com",
messagingSenderId: "710080663677",
appId: "1:710080663677:web:e2cb238abfd6df032ba114",
};
firebase.initializeApp(firebaseConfig);
const database = firebase.firestore();
const projectAuth = firebase.auth();
const projectStorage = firebase.storage();
const timestamp = firebase.firestore.FieldValue.serverTimestamp;
export { database, projectAuth, timestamp, projectStorage };
<file_sep>import { useEffect, useState, useRef } from "react";
import { Redirect } from "react-router";
import { projectAuth, projectStorage, database, timestamp } from "./firebase";
import "./Timeline.css";
import { Link } from "react-router-dom";
import { motion } from "framer-motion";
const Timeline = () => {
const ref = useRef();
const [isPending, setIsPending] = useState(false);
const [deleteModel, setDeleteModel] = useState(false);
const [model, setModel] = useState(false);
const [user, setUser] = useState(projectAuth.currentUser);
const [file, setFile] = useState(null);
const [fileError, setFileError] = useState(null);
const [postId, setPostId] = useState(null);
const [postPath, setPostPath] = useState(null);
let filePath = null;
let url = null;
const [post, setPost] = useState("");
const [singlePost, setSinglePost] = useState(null);
const [posts, setPosts] = useState(null);
const [comment, setComment] = useState("");
const type = ["image/jpeg", "image/png"];
const [commentId, setCommentId] = useState(null);
const [deleteCommentModel, setDeleteCommentModel] = useState(false);
const reset = () => {
ref.current.value = "";
};
useEffect(() => {
const unsub = projectAuth.onAuthStateChanged((user) => {
setUser(user);
});
return unsub;
}, []);
useEffect(() => {
if (user) {
database
.collection("post")
.orderBy("createdAt", "desc")
.where("userId", "==", user.uid)
.onSnapshot((snap) => {
let results = [];
snap.docs.forEach((doc) => {
doc.data().createdAt && results.push({ ...doc.data(), id: doc.id });
});
setPosts(results);
});
}
}, [user]);
const changeHandler = (e) => {
setFileError(null);
const selected = e.target.files[0];
if (selected && type.includes(selected.type)) {
setFileError(null);
setFile(selected);
} else {
setFileError("please select png or jpg image");
}
};
const uploadImage = async () => {
filePath = `post/${user.uid}/${file.name}`;
const storageRef = projectStorage.ref(filePath);
try {
const res = await storageRef.put(file);
url = await res.ref.getDownloadURL();
} catch (err) {
console.log(err.message);
}
};
if (!user) return <Redirect to="/"></Redirect>;
return (
<div className="container">
{deleteCommentModel && (
<div className="del-model-overlay">
<motion.div
className="delete-container"
initial={{ opacity: 0, scale: 1.2 }}
animate={{ opacity: 1, scale: 1 }}
>
<h5
style={{
borderBottom: "1px solid rgba(0, 0, 0, 0.39)",
color: "red",
fontWeight: "bold",
}}
onClick={async () => {
const delComments = singlePost.comments.filter((comment) => {
return comment.id !== commentId;
});
database
.collection("post")
.doc(postId)
.update({ comments: delComments });
setDeleteCommentModel(false);
}}
>
Delete
</h5>
<h5 onClick={() => setDeleteCommentModel(false)}>Cancel</h5>
</motion.div>
</div>
)}
{deleteModel && (
<div className="del-model-overlay">
<motion.div
className="delete-container"
initial={{ opacity: 0, scale: 1.2 }}
animate={{ opacity: 1, scale: 1 }}
>
<Link to={`/post/${postId}`}>
<h5 style={{ borderBottom: "1px solid rgba(0, 0, 0, 0.39)" }}>
Go to post
</h5>
</Link>
<h5
style={{
borderBottom: "1px solid rgba(0, 0, 0, 0.39)",
color: "red",
fontWeight: "bold",
}}
onClick={async () => {
setDeleteModel(false);
await database.collection("post").doc(postId).delete();
const storageRef = projectStorage.ref(postPath);
await storageRef.delete();
}}
>
Delete post
</h5>
<h5 onClick={() => setDeleteModel(false)}>Cancel</h5>
</motion.div>
</div>
)}
{model && (
<div
className="model-overlay"
onClick={(e) => {
if (e.target.className === "model-overlay") {
setModel(false);
}
}}
>
<motion.div
className="model-container"
initial={{ opacity: 0, y: -100 }}
animate={{ opacity: 1, y: 0 }}
transition={{ type: "just" }}
>
<div className="model-top">
<h3>Create post</h3>
<span
className="material-icons-outlined close-post"
onClick={() => {
setModel(false);
}}
>
close
</span>
</div>
<div className="model-center-send">
<div className="model-user">
<span className="material-icons-outlined">account_circle</span>
<span>{user.displayName}</span>
</div>
<textarea
className="caption"
cols="30"
rows="10"
required
placeholder={`What's on your mind, ${user.displayName}?`}
onChange={(e) => {
setPost(e.target.value);
}}
></textarea>
<input type="file" onChange={changeHandler} />
<div>
<span className="error">{fileError}</span>
</div>
{!isPending && (
<button
className="login-btn"
onClick={async (e) => {
e.preventDefault();
if (file) {
setIsPending(true);
if (!fileError) {
await uploadImage();
await database.collection("post").add({
userId: user.uid,
userName: user.displayName,
imgUrl: url,
createdAt: timestamp(),
comments: [],
filePath: filePath,
post: post,
});
}
setIsPending(false);
setModel(false);
setFile(null);
}
}}
>
Post
</button>
)}
{isPending && (
<button
disabled
style={{ cursor: "not-allowed", opacity: ".5" }}
className="login-btn"
>
Posting...
</button>
)}
</div>
</motion.div>
</div>
)}
<nav>
<div className="logo">
<h3 style={{ fontFamily: "cursive", cursor: "pointer" }}>
InstaClone
</h3>
</div>
<div className="search-container">
<input type="text" placeholder="Search" />
<i className="fas fa-search search"></i>
</div>
<div className="nav-icons">
<i
className="far fa-plus-square"
onClick={() => {
setModel(true);
}}
></i>
<Link to="/explore">
<i className="far fa-compass"></i>
</Link>
<i className="far fa-heart"></i>
<Link to={`/profile/${user.displayName}`}>
<i className="far fa-user-circle"></i>
</Link>
</div>
</nav>
<div className="timeline-grid">
{posts && (
<div className="timeline">
{posts.map((post) => (
<motion.div
className="single-post"
key={post.id}
initial={{ opacity: 0, scale: 0.8 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ type: "just" }}
>
<div
style={{ display: "flex", justifyContent: "space-between" }}
>
<div style={{ margin: "1rem" }} className="model-user">
<span className="material-icons-outlined">
account_circle
</span>
<span>{post.userName}</span>
</div>
<span
style={{ margin: "1rem", cursor: "pointer", color: "gray" }}
className="material-icons-outlined"
onClick={() => {
setDeleteModel(true);
setPostId(post.id);
setPostPath(post.filePath);
}}
>
more_horiz
</span>
</div>
<div className="timeline-img-container">
<img src={post.imgUrl} alt="" />
</div>
<div>
<div className="post-icons">
<div className="left-icons">
<i className="far fa-heart"></i>
<i
className="far fa-comment"
onClick={() => {
const input =
document.querySelector(".comment-input");
input.focus();
}}
></i>
<i className="far fa-paper-plane"></i>
</div>
<i className="far fa-bookmark"></i>
</div>
<div>
<span style={{ fontSize: "15px", marginLeft: "1rem" }}>
Be the first to{" "}
<span style={{ fontWeight: "bold" }}>like this</span>
</span>
</div>
<div style={{ margin: ".5rem 1rem", fontSize: ".9rem" }}>
<span style={{ fontWeight: "bold" }}>{post.userName}</span>{" "}
<span>{post.post}</span>
<Link
style={{ textDecoration: "none" }}
to={`/post/${post.id}`}
>
<span
style={{
color: "grey",
margin: ".3rem 0",
display: "block",
}}
>
View all comments
</span>
</Link>
</div>
{post.comments.map((comment) => (
<motion.div
className="single-model-comment"
key={comment.id}
style={{
margin: ".5rem 1rem",
fontSize: ".9rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
>
<div>
<span style={{ fontWeight: "bold" }}>
{comment.username}
</span>{" "}
<span>{comment.comment}</span>
</div>
{user && user.uid === comment.userId && (
<span
className="material-icons-outlined del-comment"
onClick={() => {
setCommentId(comment.id);
setPostId(post.id);
setDeleteCommentModel(true);
database
.collection("post")
.doc(post.id)
.onSnapshot((snap) => {
setSinglePost({ ...snap.data(), id: snap.id });
});
}}
>
more_horiz
</span>
)}
</motion.div>
))}
<form
type="reset"
onSubmit={async (e) => {
e.preventDefault();
const newComments = {
username: user.displayName,
comment: comment,
userId: user.uid,
id: Math.floor(Math.random() * 100000000000000),
};
await database
.collection("post")
.doc(post.id)
.update({ comments: [...post.comments, newComments] });
reset();
setComment("");
}}
className="comment-container"
>
<input
className="comment-input"
value={comment}
ref={ref}
type="text"
placeholder="Add a comment..."
onChange={(e) => {
setComment(e.target.value);
}}
/>
<button type="submit" onClick={reset}>
Post
</button>
</form>
</div>
</motion.div>
))}
</div>
)}
{posts && !posts.length && (
<div style={{ textAlign: "center" }}>there is no posts yet</div>
)}
</div>
</div>
);
};
export default Timeline;
<file_sep>import loginImg from "./imgs/instagram-login.png";
import "./Login.css";
import { Link } from "react-router-dom";
import { projectAuth } from "./firebase";
import { useState } from "react";
import { useHistory } from "react-router";
const Login = () => {
const history = useHistory();
const [email, setEmail] = useState("<EMAIL>");
const [password, setPassword] = useState("<PASSWORD>");
const [error, setError] = useState(null);
const [isPending, setIsPending] = useState(false);
const handleLogin = async (e) => {
e.preventDefault();
setIsPending(true);
setError(null);
try {
const res = await projectAuth.signInWithEmailAndPassword(email, password);
if (!res) {
throw new Error("Could not complete login");
}
setError(null);
history.push("/timeline");
} catch (err) {
console.log(err.message);
setError(err.message);
}
setIsPending(false);
};
return (
<div>
<div className="login">
<img src={loginImg} alt="" />
<div className="log-container">
<form onSubmit={handleLogin} className="login-form">
<h1 style={{ marginBottom: "2.5rem", fontFamily: "cursive" }}>
InstaClone
</h1>
<input
type="email"
required
placeholder="Email address"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<input
type="<PASSWORD>"
required
placeholder="<PASSWORD>"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
/>
{!isPending && <button className="login-btn">Log in</button>}
{isPending && (
<button
disabled
style={{ cursor: "not-allowed", opacity: ".5" }}
className="login-btn"
>
loading...
</button>
)}
<span className="error">{error}</span>
</form>
<div className="dont-have">
<span>
Don't have an account?
<Link className="signup-link" to="/signup">
{" "}
Sign up
</Link>
</span>
</div>
</div>
</div>
</div>
);
};
export default Login;
|
695833806d24903b56093a02bcef4e07ef201683
|
[
"JavaScript"
] | 4
|
JavaScript
|
EslamFoda/instagram-clone
|
4a49006eaa0dfaabff7a11ba667e1b701bf927bb
|
f33d329dd8803772b2ea71f39537708a4d508c27
|
refs/heads/master
|
<repo_name>shubh4197/Books-Comments<file_sep>/src/app/add/add.component.ts
import { Component, OnInit } from '@angular/core';
import {DataServiceService} from '../data-service.service';
import {User} from "../user.modal";
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
name:string="";
price:number=0;
author:string="";
id:number=0;
newUser:User;
constructor(private Data: DataServiceService) { }
ngOnInit() {
}
addition(){
this.newUser=new User(this.Data.user.length,this.name,this.price,this.author);
console.log(this.newUser);
this.Data.add(this.newUser);
}
}
<file_sep>/src/app/comments/comments.modal.ts
export class Comments{
name:string=""
comments:string="";
constructor(name,comments){
this.name=name;
this.comments=comments;
}
}<file_sep>/src/app/data-service.service.ts
import { Injectable } from '@angular/core';
import { User} from './user.modal'
@Injectable({
providedIn: 'root'
})
export class DataServiceService {
static add(newUser: User) {
throw new Error("Method not implemented.");
}
user:User[]=[];
constructor() { }
add(value){
this.user.push(value);
console.log(this.user);
}
edit(index,value){
this.user[index]=value;
}
}
<file_sep>/src/app/view/view.component.ts
import { Component, OnInit } from '@angular/core';
import { DataServiceService } from '../data-service.service';
import {Comments} from "../comments/comments.modal"
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-view',
templateUrl: './view.component.html',
styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
name:string="";
price:number=0;
author:string="";
comments:Comments[]=[];
index:number=0
constructor(private Data:DataServiceService,private route:ActivatedRoute) {}
ngOnInit() {
this.index=parseInt(this.route.snapshot.paramMap.get('id'))
this.name=this.Data.user[this.index].name;
this.price=this.Data.user[this.index].price;
this.author=this.Data.user[this.index].Author;
this.comments=this.Data.user[this.index].comments;
}
}
<file_sep>/src/app/comments/comments.component.ts
import { Component, OnInit } from '@angular/core';
import { DataServiceService } from '../data-service.service';
import { ActivatedRoute } from '@angular/router';
import {Comments} from "./comments.modal";
@Component({
selector: 'app-comments',
templateUrl: './comments.component.html',
styleUrls: ['./comments.component.css']
})
export class CommentsComponent implements OnInit {
name:string="";
comment:string="";
index:number=0;
constructor(private Data:DataServiceService,private route:ActivatedRoute) { }
ngOnInit() {
this.index=parseInt(this.route.snapshot.paramMap.get('id'));
}
addComments()
{
this.Data.user[this.index].comments.push(new Comments(this.name,this.comment));
console.log(this.Data.user);
}
}
<file_sep>/src/app/user.modal.ts
import {Comments} from "./comments/comments.modal";
export class User{
name:string;
price:number;
Author:string;
id:number=0;
comments:Comments[]=[];
constructor(id,name,price,author)
{ this.id=id;
this.name=name;
this.price=price;
this.Author=author;
}
}<file_sep>/src/app/edit/edit.component.ts
import { Component, OnInit } from '@angular/core';
import {DataServiceService} from '../data-service.service';
import { ActivatedRoute } from '@angular/router';
import {User} from "../user.modal";
@Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
index:number;
name:string="";
price:number=0;
author:string="";
use:User;
constructor(private Data:DataServiceService,private route:ActivatedRoute) { }
ngOnInit() {
this.index=parseInt(this.route.snapshot.paramMap.get('id'));
console.log(this.index);
}
edith(){
console.log("ok");
this.use=new User(this.index,this.name,this.price,this.author);
this.Data.user[this.index] = this.use;
}
}
|
4810403dcf7d0cf1d0f0d4f86f4f0435e9d7ce50
|
[
"TypeScript"
] | 7
|
TypeScript
|
shubh4197/Books-Comments
|
626650da13a1f001758114ac43ec1a71acfc8677
|
85877e630a6bd94e245bc8233afdb897e5098639
|
refs/heads/master
|
<repo_name>PedroIlustre/royal_fight<file_sep>/Royal/action.php
<?php
namespace Royal;
interface action {
public function sword_attack();
public function spear_attack();
}
<file_sep>/Royal/Knight.php
<?php
namespace Royal;
class Knight implements action
{
private $id;
private $name;
private $life_points;
private $knights_already_dueled;
/**
* Knight constructor.
* @param $id
*/
public function __construct($id)
{
$this->id = $id;
$this->life_points = 100;
}
/**
* @return mixed
*/
public function getKnightsAlreadyDueled()
{
return $this->knights_already_dueled;
}
/**
* @param mixed $knights_already_dueled
*/
public function setKnightsAlreadyDueled($knights_already_dueled = null)
{
if($knights_already_dueled != null){
$this->knights_already_dueled[] = $knights_already_dueled;
} else {
$this->knights_already_dueled = null;
}
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getLifePoints()
{
return $this->life_points;
}
/**
* @param mixed $life_points
*/
public function setLifePoints($life_points)
{
$this->life_points = $life_points;
}
public function sword_attack()
{
return(rand(0, 9));
}
public function spear_attack()
{
return(rand(0, 15));
}
public function receive_attack($attack){
$this->setLifePoints($this->getLifePoints() - $attack);
}
}<file_sep>/index.php
<?php
use Royal\{Tournament,Knight};
spl_autoload_register(function ($class) {
require_once($class . '.php');
});
echo 'The king\'s tournament';
echo '<br>';
echo '<br>';
if(count($_POST) == 0){
echo 'Insert the number of contenders:';
echo '<form action="index.php" method="POST">';
echo '<input type="text" name="num_knights">';
echo '<br>';
echo '<br>';
echo '<input type="submit" value="Let the games begin">';
echo '</form>';
} else {
$num_knights = $_POST['num_knights'];
$obj_tournament = new Tournament($num_knights);
$winner = $obj_tournament->getWinner();
array_walk($winner, function ($knight,$k){
echo '<pre>The winner is: '.$knight->getName();
echo '<pre>His life points were: '.$knight->getLifePoints();
});
}
<file_sep>/Royal/Tournament.php
<?php
namespace Royal;
class Tournament
{
private $winner;
/**
* Tournament constructor.
* @param $number_of_competitors
*/
public function __construct($number_of_competitors)
{
$arr_obj_knights =array();
for($i=0;$i < $number_of_competitors;$i++){
$obj_knight = new Knight($i+1);
$obj_knight->setName($this->randomName());
$arr_obj_knights[] = $obj_knight;
}
$winner = $this->death_match($arr_obj_knights, 0);
$this->setWinner($winner);
}
/**
* @return mixed
*/
public function getWinner()
{
return $this->winner;
}
/**
* @param mixed $winner
*/
public function setWinner($winner)
{
$this->winner = $winner;
}
private function randomName() : string {
$names = array(
'Sebastian',
'Napoleon',
'Augustus',
'Pedro',
'Aquila',
);
return $names[rand ( 0 , count($names) -1)];
}
private function death_match(array $arr_obj_knights, $i){
if(count($arr_obj_knights) == 1){
return $arr_obj_knights;
}
#All survivor knights fight against each other
foreach($arr_obj_knights as $k => $knight){
if($knight->getLifePoints() > 0){
$this->round($knight, $arr_obj_knights);
$knight->setKnightsAlreadyDueled();
} else {
# Dead Night
unset($arr_obj_knights[$k]);
}
}
$i++;
return $this->death_match($arr_obj_knights, $i);
}
private function round (object $knight, array $arr_obj_knights) : void{
foreach($arr_obj_knights as $k => $adversary) {
if($arr_obj_knights[$k]->getId() == $knight->getId()){
continue;
}
$already_dueled = false;
if($knight->getKnightsAlreadyDueled())
$already_dueled = in_array($adversary->getId(),$knight->getKnightsAlreadyDueled());
if($adversary->getId() != $knight->getId() && !($already_dueled))
{
$adversary->receive_attack($knight->sword_attack());
$knight->setKnightsAlreadyDueled($adversary->getId());
if($adversary->getLifePoints() > 0){
$knight->receive_attack($adversary->sword_attack());
$adversary->setKnightsAlreadyDueled($knight->getId());
}
}
}
}
}
|
284d0cb1d0cfdac9a8808cadbb343c2e9f9be1da
|
[
"PHP"
] | 4
|
PHP
|
PedroIlustre/royal_fight
|
81ddbc29cee3ffb460b015f1bdb76c4bfb6f9cfa
|
6474cf1b1e5da3dd482c9cc4626b7db89f21ba3b
|
refs/heads/master
|
<file_sep>'use strict';
const express = require('express');
const fs = require('fs');
const https = require('https');
const pug = require('pug');
const uuid = require('node-uuid');
const md5 = require('md5');
const TextHistory = require('text-history');
//const testFile = fs.readFileSync('./test_files/test1.txt');
let resourceHistories = {};
let options = {
key: fs.readFileSync('/home/bill/.ssh/key.pem'),
cert: fs.readFileSync('/home/bill/.ssh/cert.pem')
};
let app = express();
app.set('view engine', 'pug');
app.use(express.static('test/public'));
app.set('etag', 'strong'); // use strong etags
app.get('/dynamic.html', function (req, res) {
let date = new Date().toString();
let responseBody = '<h1>' + date + '</h1>';
// if there isn't a resource history yet
if (resourceHistories[req.route.path] === undefined) {
resourceHistories[req.route.path] = TextHistory(md5);
}
let id = resourceHistories[req.route.path].addVersion(responseBody);
res.header('ETag', `"${id}"`);
let matchingEtag = req.headers['if-none-match'] === undefined
? undefined
: firstMatchingEtag(req.headers['if-none-match'], resourceHistories[req.route.path]);
// if etag wasn't in the header or there wasn't any matching etag
if (matchingEtag === undefined) {
return res.end(resourceHistories[req.route.path].lastVersion);
}
// client has a cached version of the page
else {
let patches = resourceHistories[req.route.path].getPatches(matchingEtag);
res.header('IM', 'json');
res.header('Delta-Base', `"${matchingEtag}"`);
console.log(JSON.stringify(patches));
res.status(226).json(patches);
}
});
function firstMatchingEtag(etagsHeader, resourceHistory) {
let etags = etagsHeader.split(', ');
// remove quotes from etag
let etagsWithoutQuotes = etags.map(etag => etag.replace( /^"|"$/g, '' ));
// gets etag that exists in the resource history
return etagsWithoutQuotes.find(etag => resourceHistory.hasVersion(etag));
}
https.createServer(options, app).listen(8000);
<file_sep>'use strict';
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service_worker.js').then(function(reg) {
console.log(':^)', reg);
setInterval(getDynamic, 5000);
}).catch(function(err) {
console.log(':^(', err);
});
}
else {
console.log('service worker not supported');
}
function getDynamic() {
$.ajax('https://localhost:8000/dynamic.html').then((response, status, jqXHR) => {
console.log(response);
//console.log(jqXHR.getAllResponseHeaders());
});
}<file_sep># delta-cache
Library for partially caching dynamic resources on the web - only page changes are sent
<file_sep>'use strict';
const https = require('https');
const fs = require('fs');
const diff_match_patch = require('./diff_match_patch');
const diff = new diff_match_patch.diff_match_patch();
let cache;
function getDynamicFile() {
let options = {
host: 'localhost',
port: 8000,
path: '/dynamic.html'
};
if (cache !== undefined) {
options.headers = {
'Delta-Version': cache.version
}
}
let req = https.get(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
req.end();
//console.log(res.headers);
if (res.headers['delta-version'] !== undefined) {
if (res.headers['delta-patch'] === 'true') {
console.log(data);
data = diff.patch_apply(JSON.parse(data), cache.data)[0];
}
//console.log(data);
cache = {
version: res.headers['delta-version'],
data: data
};
}
});
});
}
setInterval(getDynamicFile, 3000);
|
796261fb9bc18d4bacd1594b1b98dab2d7e213b5
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
wmsmacdonald/delta-cache
|
4e6e015560ca52c5d397002866b7bc2abc8ad14b
|
56dba064a1b63d9a14cab5a0d4c195ab65e5d53f
|
refs/heads/master
|
<repo_name>linstar4067/khepera<file_sep>/SimulationServer/Simulation/Sensors/ProximitySensor.cpp
#include "ProximitySensor.h"
#include "../Math/MathLib.h"
#include "../Entities/LinearEnt.h"
//#include <iostream>
void ProximitySensor::updateState(const SimEntMap::const_iterator& firstEntity,
const SimEntMap::const_iterator& lastEntity)
{
Point rangeBeg(_robot->getCenter());
float sensorAngle = _robot->getDirectionAngle() - _placingAngle;
rangeBeg.translate((_robot->getRadius()) * cos(sensorAngle), (_robot->getRadius()) * sin(sensorAngle));
std::vector<Point> rangeEnds(_beams, Point(rangeBeg));
for (int i = 0; i < _beams; i++)
rangeEnds[i].translate(_range * cos(sensorAngle + _rangeAngle / 2 - i * _rangeAngle / (_beams - 1)),
_range * sin(sensorAngle + _rangeAngle / 2 - i * _rangeAngle / (_beams - 1)));
double minDetection = _range; // no detection
for (SimEntMap::const_iterator it = firstEntity; it != lastEntity; it++)
{
if (it->second->getID() != _robot->getID())
{
for (int i = 0; i < _beams; i++)
{
int shape = it->second->getShapeID();
if (shape == SimEnt::KHEPERA_ROBOT || shape == SimEnt::CIRCLE)
{
CircularEnt* entity = dynamic_cast<CircularEnt*>(it->second);
Point& center = entity->getCenter();
double radius = entity->getRadius();
Point orth_proj = orthogonalProjection(center, rangeBeg, rangeEnds[i]);
double dist_from_line = orth_proj.getDistance(center);
if (dist_from_line == radius && orth_proj.isBetween(rangeBeg, rangeEnds[i]))
minDetection = min(minDetection, rangeBeg.getDistance(orth_proj));
else if (dist_from_line < EPS)
minDetection = min(minDetection, rangeBeg.getDistance(orth_proj) - radius);
else if (dist_from_line < radius)
{
double k = radius / dist_from_line;
float touchAngle = (float)acos(dist_from_line / radius);
Point projOnCircle(center.getX() + orth_proj.getXDiff(center) * k,
center.getY() + orth_proj.getYDiff(center) * k);
float directionAngle = (float)acos(projOnCircle.getXDiff(center) / radius)
* sign(projOnCircle.getYDiff(center));
Point left(center);
left.translate(radius * cos(directionAngle + touchAngle),
radius * sin(directionAngle + touchAngle));
Point right(center);
right.translate(radius * cos(directionAngle - touchAngle),
radius * sin(directionAngle - touchAngle));
if (left.isBetween(rangeBeg, rangeEnds[i]))
minDetection = min(minDetection, rangeBeg.getDistance(left));
if (right.isBetween(rangeBeg, rangeEnds[i]))
minDetection = min(minDetection, rangeBeg.getDistance(right));
}
}
else if (shape == SimEnt::LINE)
{
LinearEnt* line = dynamic_cast<LinearEnt*>(it->second);
// check if ends of linear entity are between ends of current beam
Point temp = rangeEnds[i] - rangeBeg;
double beg_cross = (line->getBeg() - rangeBeg).cross(temp);
double end_cross = (line->getEnd() - rangeBeg).cross(temp);
if (beg_cross && end_cross && sign(beg_cross) != sign(end_cross))
{
// check if ends of current beam are between ends of linear ent
Point temp2 = line->getEnd() - line->getBeg();
double beg2_cross = (rangeBeg - line->getBeg()).cross(temp2);
double end2_cross = (rangeEnds[i] - line->getBeg()).cross(temp2);
if (beg2_cross && end2_cross && sign(beg2_cross) != sign(end2_cross))
minDetection = min(minDetection, _range * (beg2_cross / (beg2_cross - end2_cross)));
}
}
}
}
}
_state = (float)(1 - minDetection / _range);
//std::cout << "minDet: " << minDetection << ", sensor state: " << _state << std::endl;
}<file_sep>/SimulationServer/Simulation/Sensors/ProximitySensor.h
#ifndef PROXIMITY_SENSOR_H
#define PROXIMITY_SENSOR_H
#include "Sensor.h"
class ProximitySensor : public Sensor
{
public:
ProximitySensor(double range, float rangeAngle, float placingAngle)
: Sensor(Sensor::PROXIMITY, range, rangeAngle, placingAngle) {}
ProximitySensor(std::ifstream& file, bool readBinary) : Sensor(file, readBinary, Sensor::PROXIMITY) {}
ProximitySensor(const ProximitySensor& other) : Sensor(other) {}
void updateState(const SimEntMap::const_iterator& firstEntity,
const SimEntMap::const_iterator& lastEntity);
};
#endif<file_sep>/SimulationServer/DllInterface.cpp
#include "DllInterface.h"
#include <ctime>
Simulation* createSimulation(char* fileName, bool readBinary)
{
std::ifstream file(fileName);
Simulation* simulation = new Simulation(file, readBinary);
simulation->start();
return simulation;
}
void removeSimulation(Simulation* simulation)
{
delete simulation;
}
Simulation* cloneSimulation(Simulation* simulation)
{
return new Simulation(*simulation);
}
void updateSimulation(Simulation* simulation, int steps)
{
simulation->update((unsigned int)steps);
}
int getRobotCount(Simulation* simulation)
{
return simulation->getIdsByShape(SimEnt::KHEPERA_ROBOT).size();
}
bool fillRobotsIdArray(Simulation* simulation, int* idArray, int arrLength)
{
std::vector<int> robotIds = simulation->getIdsByShape(SimEnt::KHEPERA_ROBOT);
for (int i = 0; i < arrLength; i++)
idArray[i] = robotIds[i];
return robotIds.size() <= (unsigned int)arrLength;
}
KheperaRobot* getRobot(Simulation* simulation, int robotId)
{
SimEnt* entity = simulation->getEntity(robotId);
if (entity != NULL && entity->getShapeID() == SimEnt::KHEPERA_ROBOT)
return dynamic_cast<KheperaRobot*>(entity);
else
return NULL;
}
int getSensorCount(KheperaRobot* robot)
{
return robot->getSensorCount();
}
float getSensorState(KheperaRobot* robot, int sensorNumber)
{
float sensorState;
return robot->getSensorState(sensorNumber, sensorState) ? sensorState : -1;
}
void setRobotSpeed(KheperaRobot* robot, double leftMotor, double rightMotor)
{
robot->setLeftMotorSpeed(leftMotor);
robot->setRightMotorSpeed(rightMotor);
}
int getXCoord(KheperaRobot* robot)
{
return robot->getCenter().getX();
}
int getYCoord(KheperaRobot* robot)
{
return robot->getCenter().getY();
}
void moveRandom(Simulation* simulation, KheperaRobot* robot)
{
srand(time(NULL));
int x = rand() % (simulation->getWorldWidth() - 1) + 1;
int y = rand() % (simulation->getWorldHeight() - 1) + 1;
robot->getCenter().setCoords(x, y);
simulation->update();
}<file_sep>/SimulationServer/DllInterface.h
#ifdef _WIN32
#define DLL_PUBLIC __declspec(dllexport)
#endif
#if defined(__unix__) || defined(__APPLE__)
#define DLL_PUBLIC __attribute__ ((visibility ("default")))
#endif
#include "Simulation/Simulation.h"
// Simulation object management
extern "C" DLL_PUBLIC Simulation* createSimulation(char* fileName, bool readBinary);
extern "C" DLL_PUBLIC void removeSimulation(Simulation* simulation);
extern "C" DLL_PUBLIC Simulation* cloneSimulation(Simulation* simulation);
extern "C" DLL_PUBLIC void updateSimulation(Simulation* simulation, int steps);
extern "C" DLL_PUBLIC int getRobotCount(Simulation* simulation);
extern "C" DLL_PUBLIC bool fillRobotsIdArray(Simulation* simulation, int* idArray, int arrLength);
// Robot object management
extern "C" DLL_PUBLIC KheperaRobot* getRobot(Simulation* simulation, int robotId);
extern "C" DLL_PUBLIC int getSensorCount(KheperaRobot* robot);
extern "C" DLL_PUBLIC float getSensorState(KheperaRobot* robot, int sensorNumber);
extern "C" DLL_PUBLIC void setRobotSpeed(KheperaRobot* robot, double leftMotor, double rightMotor);
extern "C" DLL_PUBLIC void moveRandom(Simulation* simulation, KheperaRobot* robot);
// extern "C" DLL_PUBLIC int getXCoord(KheperaRobot* robot);
// extern "C" DLL_PUBLIC int getYCoord(KheperaRobot* robot);
|
ce04580f03eb7276388cd7b917eec6749b6b5304
|
[
"C",
"C++"
] | 4
|
C++
|
linstar4067/khepera
|
4e85f5a04ddef5946f1e398e0026c73cef666e68
|
65d84638be9db435873e362fa79093c9799b337f
|
refs/heads/master
|
<repo_name>domnministru/themoviedb<file_sep>/src/pages/Tv/TvShow.js
import React, {Component} from "react";
class TvShow extends Component {
render() {
return(
<div className="tv_show-page">
<h1>Tv Show Page</h1>
</div>
)
}
}
export default TvShow;<file_sep>/src/components/SearchField.js
import React, {Component} from "react";
class SearchField extends Component {
render() {
return (
<div className="container">
<div className="row">
<form className="col s12">
<div className="row">
<div className="input-field col s12">
<i className="material-icons prefix">search</i>
<textarea id="icon_prefix2" className="materialize-textarea" placeholder="Search..."/>
</div>
</div>
</form>
</div>
</div>
)
}
}
export default SearchField;<file_sep>/src/App.js
import React from "react";
import {BrowserRouter, Route} from "react-router-dom";
import Home from "./pages/Home/Home";
import Header from "./layouts/Header";
import Footer from "./layouts/Footer";
import TvShow from "./pages/Tv/TvShow";
import Movie from "./pages/Movies/Movie";
import TvShows from "./pages/Tv/TvShows";
import Movies from "./pages/Movies/Movies";
import Person from "./pages/People/Person";
import People from "./pages/People/People";
import Discover from "./pages/Discover/Discover";
const App = () => {
return (
<BrowserRouter>
<Header/>
<main className="main">
<Route path="/" exact component={Home}/>
<Route path="discover" exact component={Discover}/>
<Route path="/movie" exact component={Movies}/>
<Route path="/movie/:id" component={Movie}/>
<Route path="/tv" exact component={TvShows}/>
<Route path="/tv/:id" component={TvShow}/>
<Route path="/person" exact component={People}/>
<Route path="/person/:id" component={Person}/>
</main>
<Footer/>
</BrowserRouter>
)
};
export default App;
<file_sep>/src/cred.js
export const KEY = '51ea826115cfcaddd047494d3cfabe38';<file_sep>/src/components/Nav.js
import React, {Component} from "react";
import {Link} from "react-router-dom";
import { ReactComponent as Logo } from "../img/logo.svg";
class Nav extends Component {
render() {
return (
<nav className="nav-extended">
<div className="container">
<div className="nav-wrapper">
<Link to="/" className="brand-logo"><Logo/></Link>
<a href="#" data-target="mobile-demo" className="sidenav-trigger">
<i className="material-icons">menu</i>
</a>
<ul id="nav-mobile" className="right hide-on-med-and-down">
<li><Link to="/signIn">Sign In</Link></li>
<li><Link to="/signUp">Sign Up</Link></li>
</ul>
</div>
<div className="nav-content">
<ul className="tabs tabs-transparent">
<li className="tab"><Link to="/buy">Buy Tickets</Link></li>
<li className="tab"><Link to="/discover">Discover</Link></li>
<li className="tab"><Link to="/movie">Movies</Link></li>
<li className="tab"><Link to="/tv">Tv Shows</Link></li>
<li className="tab"><Link to="/person">People</Link></li>
</ul>
</div>
<ul className="sidenav" id="mobile-demo">
<li><Link to="/signIn">Sign In</Link></li>
<li><Link to="/signUp">Sign Up</Link></li>
</ul>
</div>
</nav>
)
}
}
export default Nav;<file_sep>/src/const.js
export const BASE_URL = `https://api.themoviedb.org/3/`;
export const IMG_URL = `https://image.tmdb.org/t/p/`;
export const YTB_URL = `https://www.youtube.com/watch?v=`;
//Image Scaling | backdrop | logo | profile | poster |
export const W45 = "w45";// | | + | + | |
export const W92 = "w92";// | | + | | + |
export const W154 = "w154";// | | + | | + |
export const W185 = "w185";// | | + | + | + |
export const W300 = "w300";// | + | + | | |
export const W342 = "w342";// | | | | + |
export const W500 = "w500";// | | + | | + |
export const W780 = "w780";// | + | | | + |
export const W1280 = "w1280";// | + | | | |
export const H632 = "h632";// | | | + | |
export const ORIGINAL = "original";//| + | + | + | + |
|
ad61b4f9c9bd969bca77bb4bbd4a451155a27ff7
|
[
"JavaScript"
] | 6
|
JavaScript
|
domnministru/themoviedb
|
0e3ec058f36ceeb20828a696cc19d632eb2cbeb6
|
f93a1b424c0948edab7d1f3bd172b32de457286f
|
refs/heads/master
|
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: sys_cdd.php 228 2013-06-25 06:57:20Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
$oparray = array('prescan', 'scan', 'report', 'index');
$op = in_array($_GET['op'], $oparray) ? $_GET['op'] : 'index';
if($op == 'prescan') {
if(C::t('#discuz_security#discuz_security_cdd')->count_status(0) > 0) {
cpmsg($csslang['sys_cdd_scan_unend'], 'action='.PARAM_URL, 'error');
}
$scanlist = list_dir(DISCUZ_ROOT, array('php'), array(DISCUZ_ROOT.'data'));
foreach($scanlist as $file) {
$data = array(
'path' => $file,
'scaned' => 0,
);
C::t('#discuz_security#discuz_security_cdd')->insert($data);
}
cpmsg($csslang['sys_cdd_prescan_end'], 'action='.PARAM_URL, 'succeed');
} elseif($op == 'scan') {
$unscan = C::t('#discuz_security#discuz_security_cdd')->count_status(0);
$file = C::t('#discuz_security#discuz_security_cdd')->fetch_one(0);
if($file) {
cdd_matchd($file['path']);
C::t('#discuz_security#discuz_security_cdd')->update_status($file['id'], 1);
cpmsg($file['path'].$csslang['sys_cdd_scan_redirect'].$unscan, 'action='.PARAM_URL.'&cp=sys_cdd&op=scan', 'loading');
} else {
$logdir = DISCUZ_ROOT.'./data/log/';
$logs = array();
$message = "<h2>".$csslang['sys_cdd_scan_danger']."</h2>";
$logs = get_logs($logdir, 'cdd_scan_danger');
$logs = fmt_logs($logs);
$logs = today_logs($logs);
$message .= implode('<br/>', $logs);
$message .= "<br/><h2>".$csslang['sys_cdd_scan_warning']."</h2>";
$logs = get_logs($logdir, 'cdd_scan_warning');
$logs = fmt_logs($logs);
$logs = today_logs($logs);
$message .= implode('<br/>', $logs);
$date = date('Y-m-d H:i:s');
include libfile('function/mail');
sendmail('<EMAIL>', "$date CDD Report @".$_G['setting']['bbname'], $message);
cpmsg($csslang['sys_cdd_scan_end'], 'action='.PARAM_URL, 'succeed');
}
} elseif($op == 'report') {
C::t('#discuz_security#discuz_security_cdd')->delete_scaned();
$logdir = DISCUZ_ROOT.'./data/log/';
$logs = array();
$logs = get_logs($logdir, 'cdd_scan_danger');
$logs = fmt_logs($logs);
$logs = today_logs($logs);
$wlogs = array();
$wlogs = get_logs($logdir, 'cdd_scan_warning');
$wlogs = fmt_logs($wlogs);
$wlogs = today_logs($wlogs);
showtableheader();
showtablerow('class="header"', array('class="td23"','class="td23"','class="td23"','class="td24"','class="td24"','class="td24"', ''), array(
$csslang['sys_cdd_scan_level'],
$csslang['sys_cdd_scan_report_time'],
$csslang['sys_cdd_scan_report_file'],
$csslang['sys_cdd_scan_report_filemodtime'],
$csslang['sys_cdd_scan_report_code'],
$csslang['sys_cdd_scan_report_rule'],
));
foreach($logs as $logrow) {
$log = explode("\t", $logrow);
showtablerow('', array('class="highlight"', 'class="smallefont"', 'class="smallefont"', 'class="bold"', 'class="smallefont"', 'class="smallefont"'), array(
$csslang['sys_cdd_scan_danger'],
$log[1],
$log[5],
$log[6],
$log[7],
$log[8]
));
}
foreach($wlogs as $logrow) {
$log = explode("\t", $logrow);
showtablerow('', array('', 'class="smallefont"', 'class="smallefont"', 'class="bold"', 'class="smallefont"', 'class="smallefont"'), array(
$csslang['sys_cdd_scan_warning'],
$log[1],
$log[5],
$log[6],
$log[7],
$log[8]
));
}
showtablefooter();
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_banip.php 198 2013-05-29 02:44:43Z lucashen $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_discuz_security_banip extends discuz_table {
public function __construct() {
$this->_table = 'plugin_discuz_security_banip';
$this->_pk = 'ip';
parent::__construct();
}
public function update_by_ip() {
global $_G;
$data = array(
'ip' => $_G['clientip'],
'count' => 1,
'lastupdate' => TIMESTAMP,
);
if(!DB::insert($this->_table, daddslashes($data), false, false, true)) {
return DB::query("UPDATE ".DB::table($this->_table)." SET count = count + 1, lastupdate = '".TIMESTAMP."' WHERE ip = '{$_G['clientip']}'");
}
return true;
}
public function fetch_range($start, $perPage = '50', $orderBy = '') {
$orderSql = !$orderBy ? '' : " ORDER BY $orderBy DESC ";
$limitSql = DB::limit($start, $perPage);
$return = DB::fetch_all("SELECT * FROM %t %i %i", array($this->_table, $orderSql, $limitSql));
return $return;
}
public function fetch_count() {
return DB::result_first("SELECT COUNT(*) FROM %t", array($this->_table));
}
public function truncate() {
return DB::query("TRUNCATE ".DB::table($this->_table));
}
public function delete_by_ip($ip) {
$ip = daddslashes($ip);
if(empty($ip)) return false;
if(is_array($ip)) {
$ip = implode("','", $ip);
}
$ip = "'".$ip."'";
return DB::delete($this->_table, "ip IN ($ip)");
}
public function sum_by_ip($ip = '') {
$where = '1';
if($ip != '') {
$where = "ip IN (".dimplode($ip).")";
}
return DB::result_first("SELECT SUM(count) FROM %t WHERE %i", array($this->_table, $where));
}
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: function_system.php 228 2013-06-25 06:57:20Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
/**
* 检测插件状态是否正版 和新版
*/
function check_plugins() {
$pluginarray = C::t('common_plugin')->fetch_all_data();
$plugins = $errarry = $newarray = $nowarray = array();
if(!$pluginarray) {
cpmsg('plugin_not_found', '', 'error');
}
if(empty($_G['cookie']['addoncheck_plugin'])) {
$addonids = array();
foreach($pluginarray as $row) {
if(ispluginkey($row['identifier'])) {
$addonids[] = $row['identifier'].'.plugin';
}
}
$checkresult = dunserialize(cloudaddons_upgradecheck($addonids));
savecache('addoncheck_plugin', $checkresult);
dsetcookie('addoncheck_plugin', 1, 3600);
}
foreach($pluginarray as $row) {
$addonid = $row['identifier'].'.plugin';
if(isset($checkresult[$addonid])) {
list($return, $newver, $sysver) = explode(':', $checkresult[$addonid]);
$result[$row['identifier']]['result'] = $return;
if($sysver) {
if($sysver > $row['version']) {
$result[$row['identifier']]['result'] = 2;
$result[$row['identifier']]['newver'] = $sysver;
} else {
$result[$row['identifier']]['result'] = 1;
}
} elseif($newver) {
$result[$row['identifier']]['newver'] = $newver;
}
}
$plugins[$row['identifier']] = $row['name'].' '.$row['version'];
}
foreach($result as $id => $row) {
if($row['result'] == 0) {
$errarray[] = '<a href="'.ADMINSCRIPT.'?action=cloudaddons&id='.$id.'.plugin" target="_blank">'.$plugins[$id].'</a>';
} elseif($row['result'] == 2) {
$newarray[] = '<a href="'.ADMINSCRIPT.'?action=cloudaddons&id='.$id.'.plugin" target="_blank">'.$plugins[$id].($row['newver'] ? ' -> '.$row['newver'] : '').'</a>';
}
}
if(!$newarray && !$errarray) {
cpmsg('plugins_validator_noupdate', '', 'error');
} else {
showtableheader();
if($newarray) {
showtitle('plugins_validator_newversion');
foreach($newarray as $row) {
showtablerow('class="hover"', array(), array($row));
}
}
if($errarray) {
showtitle('plugins_validator_error');
foreach($errarray as $row) {
showtablerow('class="hover"', array(), array($row));
}
}
showtablefooter();
}
}
/**
* 检查目录php执行权限
* @return int 0-读写错误;1-url可以执行php存在风险;2-url不可执行php不存在风险
*/
function check_dir() {
global $_G;
$checkdir = DISCUZ_ROOT.'./data/';
$checkfile = md5(TIMESTAMP).'.php';
$checkpath = $checkdir.$checkfile;
$checkurl = $_G['siteurl'].'/data/';
$rand = rand(1,10);
if($fp = @fopen($checkpath, 'a')) {
@flock($fp, 2);
fwrite($fp, "<?PHP echo $rand; exit;?>");
fclose($fp);
$num = dfsockopen($checkurl.$checkfile);
if((int)$num == $rand) {
$result = 1;
} else {
$result = 2;
}
@unlink($checkpath);
} else {
$result = 0;
}
return $result;
}
/**
* 遍历目录
* @param $filter array 遍历文件的扩展名。
* @param $remove array 移除不遍历的文件夹名
* @return array 文件列表
*/
function list_dir($dir, $filter = '', $remove = '') {
$result = array();
if(is_dir($dir)) {
$file_dir = scandir($dir);
foreach($file_dir as $file) {
if($file == '.'||$file == '..') {
continue;
} elseif(is_dir($dir.$file)) {
if(!in_array($dir.$file, $remove)) {
$result = array_merge($result, list_dir($dir.$file.'/', $filter, $remove));
}
} else {
$ext = end(explode('.', $file));
if(in_array($ext, $filter)) {
array_push($result, $dir.$file);
}
}
}
}
return $result;
}
function cdd_matchd($filepath) {
$contents = file_get_contents($filepath);
$rules = array();
$ruledir = DS_ROOT.'./misc/cdd_rule.php';
$ruleadddir = DS_ROOT.'./misc/cdd_ruleext.php';
$rules = array();
$rules = cdd_getrule($ruledir);
if(file_exists($ruleadddir)) {
$ruleadd = cdd_getrule($ruleadddir);
is_array($ruleadd) && $rules = array_merge($rules, $ruleadd);
}
$high_risk = false;
foreach($rules as $key => $val) {
foreach($val as $rule) {
$val_tmp = $match = array();
$func_match = 'preg_match';
if($key == '2' && strpos($rule, '<==>') !== false) {
$val_tmp = explode('<==>', $rule);
$rule = $val_tmp['0'];
$func_match = 'preg_match_all';
}
if($func_match(trim($rule), $contents, $match)) {
if($key == '2' && $val_tmp['1']) {
foreach($match['1'] as $val) {
if(@preg_match(trim(str_replace('\\1', $val, $val_tmp['1'])), $contents, $match)) {
$high_risk = true;
runlog('cdd_scan_danger', "\t".$filepath."\t".date("Y-m-d H:i:s", filemtime($filepath))."\t".$match[0]."\t".$rule);
break;
} else {
continue;
}
}
} else {
if(in_array($key, array('0', '1'))) {
runlog('cdd_scan_danger', "\t".$filepath."\t".date("Y-m-d H:i:s", filemtime($filepath))."\t".$match[0]."\t".$rule);
$high_risk = true;
break;
} else {
runlog('cdd_scan_warning', "\t".$filepath."\t".date("Y-m-d H:i:s", filemtime($filepath))."\t".$match[0]."\t".$rule);
}
}
}
}
}
return $high_risk;
}
function cdd_getrule($ruledir) {
$rules = $risks = array();
$rules = file_get_contents($ruledir);
empty($rules) ? exit('Can\'t find file: '.$ruledir.'.') : $rules = explode('<rule>', $rules);
$rules = str_replace(array(",\r\n", ",\r"), ",\n", $rules);
foreach($rules as $key => $val) {
$risks[$key] = array_filter(explode(",\n", $val), 'trim');
}
return $risks;
}
function get_logs($logdir = '', $action) {
$dir = opendir($logdir);
$files = array();
while($entry = readdir($dir)) {
$files[] = $entry;
}
closedir($dir);
if($files) {
sort($files);
$logfile = $action;
$logfiles = array();
$ym = '';
foreach($files as $file) {
if(strpos($file, $logfile) !== FALSE) {
if(substr($file, 0, 6) != $ym) {
$ym = substr($file, 0, 6);
}
$logfiles[$ym][] = $file;
}
}
if($logfiles) {
$lfs = array();
foreach($logfiles as $ym => $lf) {
$lastlogfile = $lf[0];
unset($lf[0]);
$lf[] = $lastlogfile;
$lfs = array_merge($lfs, $lf);
}
$lastkey = count($lfs) - 1;
$lastlog = $lfs[$lastkey];
krsort($lfs);
$logs = file($logdir.$lastlog);
return $logs;
}
return False;
}
return False;
}
function fmt_logs($logs) {
$logs = array_reverse($logs);
$newlogs = array();
foreach($logs as $logrow) {
if(empty($logrow[1])) continue;
$newlogs[] = $logrow;
}
return $newlogs;
}
function today_logs($logs) {
$newlogs = array();
foreach($logs as $logrow) {
$log = explode("\t", $logrow);
$date = explode(" ", $log[1]);
$date = dmktime($date[0]);
$now = time();
if($now - $date < 86400) {
$newlogs[] = $logrow;
} else {
break;
}
}
return $newlogs;
}
?><file_sep><?php
$lang = array
(
'hsk_name' => '视频中心',
'hsk_vod_list' => '视频数据',
'hsk_album_list' => '专辑数据',
'hsk_vod_sort' => '视频类别',
'hsk_vod_order' => '排序依据',
'hsk_vod_dateline' => '最新发布',
'hsk_vod_views' => '点播最多',
'hsk_vod_ding' => '被顶最多',
'hsk_vod_valuate' => '得分最高',
'hsk_vod_polls' => '评论最多',
'hsk_vod_price' => '消费参数',
'hsk_vod_all' => '全部',
'hsk_vod_price_yes' => '仅收费',
'hsk_vod_price_no' => '仅免费',
'hsk_vod_address' => '地区',
'hsk_vod_years' => '年代',
'hsk_vod_language' => '语言',
'hsk_vod_limits' => '提取数量',
'hsk_vod_style' => '模板风格',
'hsk_vod_pheight' => '封面高度',
'hsk_vod_pwidth' => '封面宽度',
'hsk_subject_lan' => '标题长度',
'hsk_nofindtmp' => '没有找到模板文件,请选择别的模板风格!',
'hsk_vinfo_lan' => '描述长度',
'hsk_vod_update' => '更新时间',
'hsk_album_style' => '专辑类型',
'hsk_userlist' => '用户专辑',
'hsk_desklist' => '公共专辑',
'hsk_hotuser' => '播客达人',
'hsk_user_new' => '最新播客',
'hsk_user_share' => '分享视频最多',
'hsk_user_list' => '专辑最多',
'hsk_user_hots' => '最热点达人',
'hsk_user_width' => '头像宽度',
'hsk_user_height' => '头像高度',
'hsk_tv_list' => '剧集数据',
'hsk_tv_total' => '全集剧',
'hsk_tv_update' => '同步更新剧',
'hsk_tv_update1' => '更新到',
'hsk_tv_update2' => '集全',
'hsk_actors' => '演员数据',
'hsk_actorf' => '导演数据',
'hsk_actorid' => '演员Aid值',
);
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: sys_limit.php 205 2013-05-29 08:16:16Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
$hasRedis = extension_loaded('redis');
if(!$_G['cache']['plugin']['discuz_security']['islimit'] || !$hasRedis) {
cpmsg(lang('plugin/discuz_security', 'sys_limit_check'));
}
$oparray = array('allban','allsession','history');
$op = in_array($_GET['op'], $oparray) ? $_GET['op'] : 'allban';
$limiturl = DS_URL.'&cp=sys_limit&op='.$op;
$r = new Redis();
$r->pconnect($_G['cache']['plugin']['discuz_security']['limitRedisHost'], $_G['cache']['plugin']['discuz_security']['limitRedisPort']);
$r->auth($_G['cache']['plugin']['discuz_security']['limitRedisPass']);
if($op == 'allban') {
adminlog('LIMIT');
if(empty($_GET['unban']) && empty($_GET['white']) && empty($_GET['black']) && empty($_GET['unwhite'])) {
showtableheader(lang('plugin/discuz_security', 'sys_limit_black'), 'nobottom');
echo '<tr><td>ip</td><td>'.$csslang['sys_limit_operation'].'</td></tr>';
$ips = $r->sMembers('ip.black');
foreach($ips as $ip) {
echo '<tr><td>'.$ip.'</td><td><a href="'.$limiturl.'&unban=1&ip='.$ip.'">'.$csslang['sys_limit_remove'].'</a>  </td></tr>';
}
showtablefooter();
showtableheader($csslang['sys_limit_white'], 'nobottom');
echo '<tr><td>ip</td><td>'.$csslang['sys_limit_operation'].'</td></tr>';
$ips = $r->sMembers('ip.white');
foreach($ips as $ip) {
echo '<tr><td>'.$ip.'</td><td><a href="'.$limiturl.'&unwhite=1&ip='.$ip.'">'.$csslang['sys_limit_remove'].'</a>  </td></tr>';
}
showtablefooter();
$ips = $r->zRange('banIP', 0, -1, true);
$ipsCount = count($ips);
showtableheader($csslang['sys_limit_ban_now'].$ipsCount, 'nobottom');
echo '<tr><td>'.$csslang['sys_limit_ipaddress'].'</td><td>'.$csslang['sys_limit_banned_num'].'</td><td>'.$csslang['sys_limit_first_banned'].'</td><td>'.$csslang['sys_limit_last_banned'].'</td><td>'.$csslang['sys_limit_remove'].'</td></tr>';
foreach($ips as $ip => $score) {
$firstTime = date(DATE_RFC822, $r->hGet('banTime', 'first.'.$ip));
$lastTime = $r->hGet('banTime', 'last.'.$ip) ? date(DATE_RFC822, $r->hGet('banTime', 'last.'.$ip)) : 'NULL';
echo "<tr><td>$ip</td><td>$score</td><td>$firstTime</td><td>$lastTime</td><td>";
echo $limiturl."&unban=1&ip=$ip\">".$csslang['.sys_limit_unban']."</a>  ";
echo $limiturl."&white=1&ip=$ip\">".$csslang['sys_limit_addwhite']."</a>";
echo $limiturl."&black=1&ip=$ip\">".$csslang['sys_limit_addblack']."</a>";
echo '</td></tr>';
}
showtablefooter();
}
if($_GET['unban'] == 1) {
$unbanIp = $_GET['ip'];
$firstTime = $r->hGet('banTime', 'first.'.$unbanIp);
$lastTime = $r->hGet('banTime', 'last.'.$unbanIp);
$r->lPush('unBanIpLog', $unbanIp.'::'.date($csslang['sys_limit_dateformat'], $firstTime).'::'.date($csslang['sys_limit_dateformat'], $lastTime));
$r->zDelete('banIP', $unbanIp);
$r->hDel('banTime', 'first.'.$unbanIp);
$r->hDel('banTime', 'last.'.$unbanIp);
$r->sRem('ip.black', $unbanIp);
cpmsg($csslang['sys_limit_remove_succeed']);
}
if($_GET['white'] == 1) {
$whiteIp = $_GET['ip'];
$firstTime = $r->hGet('banTime', 'first.'.$whiteIp);
$lastTime = $r->hGet('banTime', 'last.'.$whiteIp);
$r->lPush('unBanIpLog', $whiteIp.'::'.date($csslang['sys_limit_dateformat'], $firstTime).'::'.date($csslang['sys_limit_dateformat'], $lastTime));
$r->zDelete('banIP', $whiteIp);
$r->hDel('banTime', 'first.'.$whiteIp);
$r->hDel('banTime', 'last.'.$whiteIp);
$r->sRem('ip.black', $whiteIp);
}
if($_GET['black'] == 1) {
$blackIp = $_GET['ip'];
$r->sAdd('ip.black', $blackIp);
}
if($_GET['unwhite'] == 1) {
$whiteIp = $_GET['ip'];
$r->sRem('ip.white', $whiteIp);
cpmsg($csslang['sys_limit_remove_succeed']);
}
} elseif($op == 'allsession') {
adminlog('LIMIT');
$today=date('Ymd');
echo '<strong>'.$csslang['sys_limit_todayip'].'</strong>';
echo $r->zSize('dayIpCount:'.$today),'<br>';
$allSess = $r->keys('sid:*');
$allSessCount = count($allSess);
showtableheader($csslang['sys_limit_activity_now'].$allSessCount, 'nobottom');
echo '<tr><td>'.$csslang['sys_limit_ipaddress'].'</td><td>'.$csslang['sys_limit_session_num'].'</td><td>'.$csslang['sys_limit_session_low'].'</td></tr>';
foreach($allSess as $_sess) {
$_ip = explode(':', $_sess);
$ip = $_ip[1];
$sessCount = $r->zSize('sid:'.$ip);
$lowScoreSessCount=$r->zCount('sid:'.$ip, 0, 1);
echo "<tr><td>$ip</td><td>$sessCount</td><td>$lowScoreSessCount</td></tr>";
}
showtablefooter();
} elseif($op == 'history') {
adminlog('LIMIT');
$thisPage = (int) $_GET['page'];
$num = $r->lsize('unBanIpLog');
$perPage = 20;
echo multi($num, $perPage, $thisPage, $url);
$thisPage == 1 ? $start = 1 : $start = $thisPage * $perPage;
$stop = $start + $perPage - 1;
$allHis = $r->lRange('unBanIpLog', $start, $stop);
showtableheader($csslang['sys_limit_banlog'], 'nobottom');
echo '<tr><td>'.$csslang['sys_limit_ipaddress'].'</td><td>'.$csslang['sys_limit_first_banned'].'</td><td>'.$csslang['sys_limit_last_banned'].'</td></tr>';
foreach($allHis as $_his) {
$_row = explode('::', $_his);
$ip = $_row[0];
$firstTime = $_row[1];
$lastTime = $_row[2];
echo "<tr><td>$ip</td><td>$firstTime</td><td>$lastTime</td></tr>";
}
showtablefooter();
}
?>
<file_sep><?php
/*
* $Id: 2013/8/30 16:20:06 table_forum_post_ext.php <NAME> $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_forum_post_ext extends table_forum_post
{
private static $_tableid_tablename = array();
private $_pre_cache_keyd = '';
public function __construct() {
$this->_table = 'forum_post';
$this->_pk = 'pid';
$this->_pre_cache_keyd = 'indb';
$this->_cache_ttl = 86400;
parent::__construct();
}
public static function get_tablename($tableid, $primary = 0) {
list($type, $tid) = explode(':', $tableid);
if(!isset(self::$_tableid_tablename[$tableid])) {
if($type == 'tid') {
self::$_tableid_tablename[$tableid] = self::getposttablebytid($tid, $primary);
} else {
self::$_tableid_tablename[$tableid] = self::getposttable($type);
}
}
return self::$_tableid_tablename[$tableid];
}
public function insert($tableid, $data, $return_insert_id = false, $replace = false, $silent = false) {
if(memory('check')) {
if($data['first'] == 1) {
$this->store_cache($data['tid'], 1, $this->_cache_ttl, $this->_pre_cache_keyd.'tp_');
$data['position'] = 1;
return DB::insert(self::get_tablename($tableid), $data, $return_insert_id, $replace, $silent);
} else {
$failed = false;
for($i = 0;$i < 3;$i ++) {
if($failed == true || !($maxposition = $this->fetch_cache($data['tid'], $this->_pre_cache_keyd.'tp_'))) {
$maxposition = self::fetch_maxposition_by_tid($tableid, $data['tid']);
}
$this->store_cache($data['tid'], $maxposition + 1, $this->_cache_ttl, $this->_pre_cache_keyd.'tp_');
$data['position'] = $maxposition + 1;
if($return = DB::insert(self::get_tablename($tableid), $data, $return_insert_id, $replace, true)) {
return $return;
}
$i == 1 && $failed = true;
}
showmessage('System is busy, please try again later.');
}
}
$i = 0;
while(1) {
if($rt = DB::insert(self::get_tablename($tableid), $data, $return_insert_id, $replace, true)) {
break;
}
$i ++;
if($i == 3) showmessage('System is busy, please try again later.');
}
$maxposition = self::fetch_maxposition_by_tid($tableid, $data['tid']);
self::update($tableid, $data['pid'], array('position'=>$maxposition + 1));
return $rt;
}
}
<file_sep><?php
$blockclass = array(
'name' => lang('block/hskvcenter', 'hsk_name'),
);
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_cdd.php 224 2013-06-21 02:52:00Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_discuz_security_cdd extends discuz_table {
public function __construct() {
$this->_table = 'plugin_discuz_security_cdd';
$this->_pk = 'id';
parent::__construct();
}
public function count_status($status) {
return DB::result_first("SELECT count(id) FROM %t WHERE scaned='%d'", array($this->_table, $status));
}
public function fetch_one($status) {
return DB::fetch_first("SELECT id, path FROM %t WHERE scaned='%d' LIMIT 1", array($this->_table, $status));
}
public function update_status($id, $status) {
DB::update($this->_table, array('scaned' => $status), "id=$id");
}
public function delete_scaned() {
DB::query("DELETE FROM %t WHERE scaned='%d'", array($this->_table, 1));
}
}
?><file_sep><?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class block_hotuser {
function block_hotuser() {}
function name() {
return lang('block/hskvcenter', 'hsk_name');
}
function blockclass() {
return array('hotuser', lang('block/hskvcenter', 'hsk_hotuser'));
}
function fields() {
return array();
}
var $setting = array();
function getsetting() {
global $_G;
$settings = array(
'orders' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_order'),
'type' => 'select',
'value' => array(
array('dateline', lang('block/hskvcenter', 'hsk_user_new')),
array('shares', lang('block/hskvcenter', 'hsk_user_share')),
array('ablists', lang('block/hskvcenter', 'hsk_user_list')),
array('hots', lang('block/hskvcenter', 'hsk_user_hots')),
)
),
'pwidth' => array(
'title' => lang('block/hskvcenter', 'hsk_user_width'),
'type' => 'text',
'default' => '50'
),
'pheight' => array(
'title' => lang('block/hskvcenter', 'hsk_user_height'),
'type' => 'text',
'default' => '50'
),
'limits' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_limits'),
'type' => 'text',
'default' => '10'
),
'styleids' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_style'),
'type' => 'select',
'value' => $this->getstylelist()
),
);
return $settings;
}
function getstylelist(){
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/hsk_style.inc.php';
if(file_exists($file)){
@require $file;
}
$newarray = array();
//生成数组
foreach($xml_list['hotuser'] as $key=>$val){
$newarray[] = array($key, $val);
}
//print_r($newarray);dexit();
//检查自定义模板
$block_folder= DISCUZ_ROOT.'source/plugin/hsk_vcenter/block/';
$fp=opendir($block_folder);
$rules_list = $rules_in = array();
while(false != $file = readdir($fp))
{
if($file!='.' && $file!='..' && substr($file,-8)=='.inc.php' && substr($file,0,9)!='hsk_style'){
$file = substr($file, 0, -8);
$newarray[] = array($file, $file);
}
}
return $newarray;
}
function getsort(){
if(file_exists(DISCUZ_ROOT.'./data/hskcenter/_sort.inc.php')){
@require DISCUZ_ROOT.'./data/hskcenter/_sort.inc.php';
$newarray[] = array('0', lang('block/hskvcenter', 'hsk_vod_all'));
foreach($_SORT as $datarow){
if($datarow['sup'] == 0){
$newarray_arr = array($datarow['sid'], $datarow['sort']);
$newarray[] = $newarray_arr;
}
}
return $newarray;
}else{
return array();
}
}
function cookparameter($parameter) {
return $parameter;
}
function getdata($style, $parameter) {
global $_G;
$returndata = array('html' => '', 'data' => '');
$parameter = $this->cookparameter($parameter);
$orders = !empty($parameter['orders']) ? $parameter['orders'] : 0;
$limits = intval($parameter['limits']) ? intval($parameter['limits']) : 10;
$pwidth = intval($parameter['pwidth']) ? intval($parameter['pwidth']) : 50;
$pheight = intval($parameter['pheight']) ? intval($parameter['pheight']) : 50;
//附加
$styleids = !empty($parameter['styleids']) ? $parameter['styleids'] : 1;
$orders = in_array($orders, array('dateline', 'shares', 'ablists', 'hots')) ? $orders : 'shares';
$query = DB::query("SELECT m.shares, m.ablists, m.hots, mm.username, mm.uid FROM ".DB::table('vgallery_member')." m LEFT JOIN ".DB::table('common_member')." mm ON mm.uid=m.mid where m.shares>0 ORDER BY m.$orders DESC limit $limits");
while($data = DB::fetch($query)) {
$list[] = array(
'uid' => $data['uid'],
'picture' => avatar($data['uid'], 'middle', true, false, false, $_G['setting']['ucenterurl']),
'link' => $this->sendurl($data['uid']),
'username' => $data['username'],
'shares' => $data['shares'],
'ablists' => $data['ablists'],
'hots' => $data['hots'],
);
}
$html = $this->send_html($styleids, $list, $pwidth, $pheight);
return array('html' => $html, 'data' => null);
}
function send_html($styleid, $data, $width, $height) {
if(intval($styleid)){
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/hsk_style_'.$styleid.'.inc.php';
}else{
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/'.$styleid.'.inc.php';
}
if(!$styleid)return false;
if(file_exists($file)){
@require $file;
}else{
showmessage($styleid.lang('block/hskvcenter', 'hsk_nofindtmp'));
return false;
}
$html_header = $_XMLS['header'];
$html_footer = $_XMLS['footer'];
$html_looper = $_XMLS['loop'];
$search_key = array('/{UID}/', '/{PICTURE}/', '/{LINK}/', '/{USERNAME}/', '/{SHARES}/', '/{ABLISTS}/', '/{HOTS}/', '/{PWIDTH}/', '/{PHEIGHT}/');
$i=0;
foreach($data as $v) {
$replac_key = array($v['uid'], $v['picture'], $v['link'], $v['username'], $v['shares'], $v['ablists'], $v['hots'], $width, $height);
$html_tmp = trim(preg_replace($search_key, $replac_key, $html_looper));
$html .= $html_tmp;
$i++;
}
$html = $html_header.$html.$html_footer;
//print_r($html);dexit();
return $html;
}
function getpicture($img, $remote=0){
global $_G;
if($remote){
$img = $_G['setting']['ftp']['attachurl'].$img;
}else{
if(substr($img,0,7) != 'http://'){
$thepicurl = DISCUZ_ROOT.$img;
if(!file_exists("$thepicurl") || !$img){
$img = './source/plugin/hsk_vcenter/images/noimages.gif';
}
}
}
return $img;
}
function sendurl($vid){
global $_G;
$hp = $_G['cache']['plugin']['hsk_vcenter']['openhtml'];
if($hp){
return "author-".$vid."-0-0-1.html";
}else{
return "plugin.php?id=hsk_vcenter:hsk_vcenter&mod=author&mid=".$vid;
}
}
}
?><file_sep><?php
!defined('IN_DISCUZ') && exit('Access Denied');
!defined('IN_ADMINCP') && exit('Access Denied');
showtableheader(lang("plugin/dsu_amupper","list_h1"));
$limit = 40;
$num = C::t('#dsu_amupper#plugin_dsuamupper')->count();
$page = max(1, intval($_GET['page']));
$start_limit = ($page - 1) * $limit;
$url = "admin.php?action=plugins&operation=config&identifier=dsu_amupper&pmod=list";
$multipage = multi($num, $limit, $page, $url);
$result_all = C::t('#dsu_amupper#plugin_dsuamupper')->range($start_limit,$limit);
showsubtitle(array('', lang("plugin/dsu_amupper",'list_t1'), lang("plugin/dsu_amupper",'list_t2'), lang("plugin/dsu_amupper",'list_t3'), lang("plugin/dsu_amupper",'list_t4')));
foreach($result_all as $k=>$result){
if($result['uname']){
$result['uname'] = "<a href='home.php?mod=space&uid={$result['uid']}&do=profile' TARGET='viewer'>{$result['uname']}</a>({$result['uid']})";
}else{
$result['uname'] = "<a href='home.php?mod=space&uid={$result['uid']}&do=profile' TARGET='viewer'>UID:{$result['uid']}</a>";
}
showtablerow('', array(' ', ' ', ' ', ' '), array('', $result['uname'], $result['addup'], $result['cons'], dgmdate($result['lasttime'],'Y-m-d H:m:s',$_G['setting']['timeoffset'])));
}
showtablerow('', array(' ', ' ', ' ', ' '), array('', '', '', '', $multipage));
showtablefooter();
?><file_sep>--
1,forum_thread 其它页面,只要满页也缓存 fetch_all_by_tid_range_position,fetch_all_common_viewthread_by_tid,fetch_all_search
--
2,forum_post 改造 insert $maxposition 查主库 把当前页面的缓存删除
--
3,forum_post 分表优化 唯一ID生成; pid,tableid,tid,authorid 索引
4,好友,文章索引优化
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_banip.php 136 2013-05-13 09:13:53Z lucashen $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_common_member_status_child extends table_common_member_status {
public function result_lastpost() {
global $_G;
return DB::result_first("SELECT lastpost FROM %t WHERE uid = %d", array($this->_table, $_G['uid']));
}
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: lang_template.php 28113 2012-02-22 09:25:55Z svn_project_zhangjie $
*
* Translated to Thai by jaideejung007
*/
$lang = array (
'no_simplemobiletype' => 'แบบที่ 1',
'nomobiletype' => 'คอมพิวเตอร์',
'simplemobiletype' => 'แบบที่ 2',
'favorite' => 'บุ๊คมาร์ก',
'my_posts' => 'โพสต์ของฉัน',
'new_pm' => 'ข้อความส่วนตัวใหม่',
'waptitle' => 'โทรศัพท์มือถือ',
'login_mobile' => 'ลงชื่อเข้าใช้ → {$_G[setting][bbname]} ผ่านทางโทรศัพท์มือถือ',
'login_mobile_join' => 'พบประสบการณ์ใหม่ๆ กับการเข้าชมเว็บไซต์ของเราผ่านทางโทรศัพท์มือถือได้ง่ายๆ สะดวกสบาย ติดตามความเคลื่อนไหวของเราได้ทุกที่ ทุกเวลา',
'mobile_favorite' => 'เพิ่มบุ๊คมาร์กได้อย่างรวดเร็ว',
'mobile_favorite_comment' => 'เข้าชมเว็บไซต์ของเราผ่านทางโทรศัพท์มือถือเลือกชมเนื้อหาที่คุณชื่นชอบและเพิ่มบุ๊คมาร์กหรือบุ๊คมาร์คสิ่งที่คุณต้องการได้อย่างรวดเร็ว ง่ายดาย ทุกที่ทุกเวลา',
'mobile_other_1' => 'รับและส่งข้อความส่วนตัวได้ตลอกเวลา ร่วมสนทนากับเพื่อนๆไม่ว่าจะสนทนาส่วนตัวหรือจะสนทนาด้วยกันหลายๆคน',
'mobile_pm' => 'รับ,ส่งข้อความและร่วมสนทนากับเพื่อนๆ',
'mobile_viewthread' => 'ติดตามความเคลื่อนไหวในเว็บบอร์ด',
'mobile_viewthread_comment' => 'ติดตามความเคลื่อนไหวในเว็บบอร์ดผ่านทางโทรศัพท์มือถือได้ทุกที่ทุกเวลา และสามารถโพสต์ใหม่และตอบกลับกระทู้ที่ต้องการได้อย่างรวดเร็ว',
'continue' => 'ดำเนินการต่อไป',
'goback' => 'ย้อนกลับ',
'message_forward_mobile' => 'คลิกเพื่อข้ามไปหน้าถัดไป',
'favorite_delete' => 'ยกเลิกบุ๊คมาร์ก',
'index_members' => 'สมาชิก',
'index_today' => 'วันนี้',
'my_favorites_forums' => 'บอร์ดโปรดของฉัน',
'online' => 'ออนไลน์',
'sourceimagesize' => 'ขนาดต้นฉบับ',
'forum_posts' => 'โพสต์',
'group' => 'คลับ',
'post_newthreaddebate' => 'โต้วาที',
'post_newthreadpoll' => 'โพล',
'post_newthreadreward' => 'รางวัล',
'send_threads' => 'ส่ง',
'thread_digest' => 'สำคัญ',
'thread_recommend' => 'แนะนำ',
'thread_sticky' => 'ปักหมุด',
'threadsort' => 'หมวดหมู่ข้อมูล',
'threadtype' => 'ประเภทกระทู้',
'viewnewthread' => 'กระทู้ใหม่',
'admin_threadtopicadmin_error' => 'ไม่สามารถดำเนินการจัดการผ่านการแสดงผลบนโทรศัพท์มือถือ',
'expiry' => 'กำหนดเวลา<span class="xg2">(0 คือตลอดไป | 1 คือหนึ่งวัน)</span>',
'mod_message_goto_admincp' => 'ไม่สามารถดำเนินการผ่านการแสดงผลบนโทรศัพท์มือถือ กรุณาใช้การแสดงผลบนคอมพิวเตอร์',
'result' => 'ผลลัพธ์การค้นหา',
'join_thread' => 'ตอบกระทู้',
'required' => 'ต้องระบุ',
'send_special_activity_error' => 'ไม่สามารถ<strong>จัดกิจกรรม</strong>ผ่านการแสดงผลบนโทรศัพท์มือถือ',
'send_special_trade_error' => 'ไม่สามารถ<strong>ขายสินค้า</strong>ผ่านการแสดงผลบนโทรศัพท์มือถือ',
'threadsort_error' => 'ไม่สามารถดำเนินการผ่านการแสดงผลบนโทรศัพท์มือถือ กรุณาใช้การแสดงผลบนคอมพิวเตอร์',
'threadsort_calendar' => 'รูปแบบวันที่: 2010-12-01',
'post_poll_options' => 'ตัวเลือกโพล',
'admin_close_expire_comment' => '<span class="xg1">เลือกรูปแบบวันที่: 2010-12-01 10:50</span>',
'admin_delthread_confirm' => 'คุณแน่ใจหรือว่าต้องการลบ?',
'topicadmin_mobile_mod' => 'ดำเนินการรูปแบบโทรศัพท์มือถือ',
'admin_banpost_confirm' => 'คุณต้องการป้องกันการดำเนินการ',
'admin_delpost_confirm' => 'คุณแน่ใจหรือไม่ว่าต้องการลบข้อความตอบกลับนี้?',
'admin_warn_confirm' => 'คุณต้องการดำเนินการแจ้งเตือน',
'attach_nopermission_login' => 'คุณจำเป็นต้อง<a href="member.php?mod=logging&action=login">ลงชื่อเข้าใช้</a>ก่อนจึงจะสามารถดูและดาวน์โหลดไฟล์แนบได้ หากยังไม่มีบัญชีหรือยังไม่ได้เป็นสมาชิก กรุณา<a href="member.php?mod={$_G[setting][regname]}" title="ลงทะเบียนใหม่">{$_G[setting][reglinkname]}</a>',
'attachlist' => 'รายการไฟล์แนบ',
'ban_member' => 'แบน',
'digest' => '<span class="xi1">สำคัญ</span>',
'forum_views' => 'ดู',
'send_pm' => 'ส่งข้อความ',
'thread_show_all' => 'ดูทั้งหมด',
'thread_show_author' => 'เจ้าของเท่านั้น',
'activity_mod' => 'ไม่สามารถจัดการกิจกรรมผ่านการแสดงผลบนโทรศัพท์มือถือ',
'poll_msg_allwvote_user' => 'คุณต้อง<a href="member.php?mod=logging&action=login">ลงชื่อเข้าใช้</a>ก่อนจึงจะสามารถโหวตได้',
'resolved' => 'ได้รับการแก้ไข',
'unresolved' => 'ไม่สามารถแก้ไขได้',
'trade_mod' => 'ไม่สามารถจัดการสินค้าผ่านการแสดงผลบนโทรศัพท์มือถือ',
'my_favorites_thread' => 'กระทู้โปรดของฉัน',
'return_forum' => 'กลับไปที่บอร์ด',
'title_memcp_favorite' => 'บุ๊คมาร์ก',
'back' => 'ย้อนกลับ',
'chatpm' => 'สนทนาเป็นกลุ่ม',
'chatpm_author' => 'ผู้สนับสนุน',
'pm_totail' => 'สนทนา',
'pm_with' => 'และ',
'user_mobile_pm_error' => 'ไม่สามารถดำเนินการข้อความส่วนตัวผ่านการแสดงผลบนโทรศัพท์มือถือ กรุณากลับไปที่<a href="home.php?mod=space&do=pm&filter=privatepm">ข้อความส่วนตัวของฉัน</a>',
'basic_information' => 'ข้อมูลพื้นฐาน',
'favorite_description_default' => 'บุ๊คมาร์ก',
'favorite_forum_confirm' => 'เพิ่มบอร์ดนี้: ',
'favorite_thread_confirm' => 'เพิ่มในบุ๊คมาร์ก: ',
'user_mobile_pm_comment' => 'หลังจากที่ส่งข้อความส่วนตัว ระบบจะกลับไปยังหน้าก่อนหน้านี้',
'reset' => 'ตั้งค่าใหม่',
'reg_username' => '<PASSWORD>้องมีความยาวอย่างน้อย 3 ตัวอักษร สูงสุด 15 ตัวอักษร',
);
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: lang_cornerbanner.php by <NAME> at sources.ru
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$lang = array
(
'cornerbanner_name' => 'Coin inférieur droit de la publicité globales',
'cornerbanner_desc' => 'Montrer le chemin: s\'affiche sur le coin inférieur droit de la page La page en cours avec plusieurs pages les bannières publicitaires en premier le système sélectionnera au hasard un de l\'exposition..<br />Analyse des valeurs: La capacité de montrer clairement position sur la page, donc le le prix fort comme un page, le plus approprié pour la publicité commerciale ou de types de marques de promotion publicitaire.',
'cornerbanner_index' => 'Accueil',
'cornerbanner_fids' => 'Emplacement dans le forum',
'cornerbanner_fids_comment' => 'Forum ensemble un forum pour la publicité, quand la publicité de la gamme avec "Forum" efficaces',
'cornerbanner_groups' => 'Emplacement dans le classement du Groupe',
'cornerbanner_groups_comment' => 'Régler le Groupe publicitaire annonce, quand la publicité de la gamme avec "Groupe" est effective',
'cornerbanner_animator' => 'Effets Animations',
'cornerbanner_animator_comment' => 'Réglez s\'il faut afficher l\'affichage d\'animation',
'cornerbanner_category' => 'Portail des canaux Emplacement',
'cornerbanner_category_comment' => 'Jeu de chaînes publicitaires annonce, quand la publicité de la gamme avec un "portail" est effective',
'cornerbanner_disableclose' => 'Close advertising link',//'关闭广告的链接',
'cornerbanner_disableclose_comment' => 'If you want the Advertising can not be closed, you can disable to show the Close link',//'如果广告代码中已内置关闭操作,可以关闭系统预置的关闭链接',
'cornerbanner_show' => 'Show',//'显示',
'cornerbanner_hidden' => 'Hide',//'隐藏',
);
<file_sep><?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class block_albumlist {
function block_albumlist() {}
function name() {
return lang('block/hskvcenter', 'hsk_name');
}
function blockclass() {
return array('albumlist', lang('block/hskvcenter', 'hsk_album_list'));
}
function fields() {
return array();
}
var $setting = array();
function getsetting() {
global $_G;
$settings = array(
'sids' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_sort'),
'type' => 'select',
'value' => $this->getsort()
),
'orders' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_order'),
'type' => 'select',
'value' => array(
array('id', lang('block/hskvcenter', 'hsk_vod_dateline')),
array('views', lang('block/hskvcenter', 'hsk_vod_views')),
array('chk_up', lang('block/hskvcenter', 'hsk_vod_ding')),
array('valuate', lang('block/hskvcenter', 'hsk_vod_valuate')),
array('polls', lang('block/hskvcenter', 'hsk_vod_polls')),
array('updateline', lang('block/hskvcenter', 'hsk_vod_update')),
)
),
'prices' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_price'),
'type' => 'select',
'value' => array(
array('0', lang('block/hskvcenter', 'hsk_vod_all')),
array('1', lang('block/hskvcenter', 'hsk_vod_price_yes')),
array('2', lang('block/hskvcenter', 'hsk_vod_price_no')),
)
),
'albums' => array(
'title' => lang('block/hskvcenter', 'hsk_album_style'),
'type' => 'select',
'value' => array(
array('0', lang('block/hskvcenter', 'hsk_vod_all')),
array('1', lang('block/hskvcenter', 'hsk_userlist')),
array('2', lang('block/hskvcenter', 'hsk_desklist')),
)
),
'limits' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_limits'),
'type' => 'text',
'default' => '10'
),
'styleids' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_style'),
'type' => 'select',
'value' => $this->getstylelist()
),
'pwidth' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_pwidth'),
'type' => 'text',
'default' => '90'
),
'pheight' => array(
'title' => lang('block/hskvcenter', 'hsk_vod_pheight'),
'type' => 'text',
'default' => '72'
),
'subject_lan' => array(
'title' => lang('block/hskvcenter', 'hsk_subject_lan'),
'type' => 'text',
'default' => '12'
),
'vinfo_lan' => array(
'title' => lang('block/hskvcenter', 'hsk_vinfo_lan'),
'type' => 'text',
'default' => '80'
),
);
return $settings;
}
function getstylelist(){
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/hsk_style.inc.php';
if(file_exists($file)){
@require $file;
}
$newarray = array();
//生成数组
foreach($xml_list['albumlist'] as $key=>$val){
$newarray[] = array($key, $val);
}
//print_r($newarray);dexit();
//检查自定义模板
$block_folder= DISCUZ_ROOT.'source/plugin/hsk_vcenter/block/';
$fp=opendir($block_folder);
$rules_list = $rules_in = array();
while(false != $file = readdir($fp))
{
if($file!='.' && $file!='..' && substr($file,-8)=='.inc.php' && substr($file,0,9)!='hsk_style'){
$file = substr($file, 0, -8);
$newarray[] = array($file, $file);
}
}
return $newarray;
}
function getsort(){
if(file_exists(DISCUZ_ROOT.'./data/hskcenter/_sort.inc.php')){
@require DISCUZ_ROOT.'./data/hskcenter/_sort.inc.php';
$newarray[] = array('0', lang('block/hskvcenter', 'hsk_vod_all'));
foreach($_SORT as $datarow){
if($datarow['sup'] == 0){
$newarray_arr = array($datarow['sid'], $datarow['sort']);
$newarray[] = $newarray_arr;
}
}
return $newarray;
}else{
return array();
}
}
function cookparameter($parameter) {
return $parameter;
}
function getdata($style, $parameter) {
global $_G;
$returndata = array('html' => '', 'data' => '');
$parameter = $this->cookparameter($parameter);
$sids = intval($parameter['sids']) ? intval($parameter['sids']) : 0;
$orders = !empty($parameter['orders']) ? $parameter['orders'] : 0;
$prices = intval($parameter['prices']) ? intval($parameter['prices']) : 0;
$limits = intval($parameter['limits']) ? intval($parameter['limits']) : 10;
//附加
$pwidth = intval($parameter['pwidth']) ? intval($parameter['pwidth']) : 90;
$pheight = intval($parameter['pheight']) ? intval($parameter['pheight']) : 72;
$subject_lan= intval($parameter['subject_lan']) ? intval($parameter['subject_lan']) : 12;
$styleids = !empty($parameter['styleids']) ? $parameter['styleids'] : 1;
$vinfo_lan = intval($parameter['vinfo_lan']) ? intval($parameter['vinfo_lan']) : 80;
$albums = intval($parameter['albums']) ? intval($parameter['albums']) : 0;
//处理SQL段
if($prices==1){
$price_sql = " AND v.price=0";
}elseif($prices==2){
$price_sql = " AND v.price>0";
}else{
$price_sql = null;
}
$orders = in_array($orders, array('id', 'views', 'chk_up', 'polls', 'valuate', 'updateline')) ? $orders : 'id';
$areadatalist = $sortdata = $sortdatatids = array();
$sql = ($sids ? " AND v.fid='$sids'" : null)
.$price_sql
.($albums ? " AND v.album='$albums'" : " AND v.album in(1,2)");
$query = DB::query("SELECT v.id, v.vsubject, v.purl, v.vsum, v.abtotal, v.uid, v.views, v.polls, v.valuate, v.remote, v.vinfo, m.username FROM ".DB::table('vgallerys')." v LEFT JOIN ".DB::table('common_member')." m ON m.uid=v.uid where v.audit=1 $sql ORDER BY v.$orders DESC limit $limits");
while($data = DB::fetch($query)) {
$data['vinfo'] = str_replace(chr(13).chr(10), "", $data['vinfo']);
$data['vinfo'] = dhtmlspecialchars($data['vinfo']);
$list[] = array(
'id' => $data['id'],
'uid' => $data['uid'],
'subject' => $data['vsubject'],
'subjectc' => cutstr($data['vsubject'], $parameter['subject_lan'], '..'),
'picture' => $this->getpicture($data['purl'], $data['remote']),
'link' => $this->sendurl($data['id']),
'username' => $data['username'],
'vsum' => $data['vsum'],
'abtotal' => $data['abtotal'],
'views' => $data['views'],
'polls' => $data['polls'],
'valuate' => $data['valuate'],
'infodesc' => cutstr($data['vinfo'], $parameter['vinfo_lan'], '..'),
);
}
$html = $this->send_html($styleids, $list, $pwidth, $pheight);
return array('html' => $html, 'data' => null);
}
function send_html($styleid, $data, $width, $height) {
if(intval($styleid)){
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/hsk_style_'.$styleid.'.inc.php';
}else{
$file = DISCUZ_ROOT.'./source/plugin/hsk_vcenter/block/'.$styleid.'.inc.php';
}
if(!$styleid)return false;
if(file_exists($file)){
@require $file;
}else{
showmessage($styleid.lang('block/hskvcenter', 'hsk_nofindtmp'));
return false;
}
$html_header = $_XMLS['header'];
$html_footer = $_XMLS['footer'];
$html_looper = $_XMLS['loop'];
$search_key = array('/{VID}/', '/{SUBJECT}/', '/{SUBJECTC}/', '/{PICTURE}/', '/{VSUM}/', '/{ABTOTAL}/', '/{VIEWS}/', '/{POLLS}/', '/{VALUATE}/', '/{PWIDTH}/', '/{PHEIGHT}/', '/{LINK}/', '/{SUMMARY}/', '/{USERNAME}/', '/{UID}/');
$i=0;
foreach($data as $v) {
$replac_key = array($v['id'], $v['subject'], $v['subjectc'], $v['picture'], $v['vsum'], $v['abtotal'], $v['views'], $v['polls'], $v['valuate'], $width, $height, $v['link'], $v['infodesc'], $v['username'], $v['uid']);
$html_tmp = trim(preg_replace($search_key, $replac_key, $html_looper));
$html .= $html_tmp;
$i++;
}
$html = $html_header.$html.$html_footer;
//print_r($html);dexit();
return $html;
}
function getpicture($img, $remote=0){
global $_G;
if($remote){
$img = $_G['setting']['ftp']['attachurl'].$img;
}else{
if(substr($img,0,7) != 'http://'){
$thepicurl = DISCUZ_ROOT.$img;
if(!file_exists("$thepicurl") || !$img){
$img = './source/plugin/hsk_vcenter/images/noimages.gif';
}
}
}
return $img;
}
function sendurl($vid){
global $_G;
$hp = $_G['cache']['plugin']['hsk_vcenter']['openhtml'];
if($hp){
return "dlist-".$vid."-0-0-1.html";
}else{
return "plugin.php?id=hsk_vcenter:hsk_vcenter&mod=ablist&vid=".$vid;
}
}
}
?><file_sep>ARABIC Language Pack
for Discuz! X2.5 (c) 2001-2099 Comsenz Inc.
MultiLingual version by <NAME>, codersclub.org
by <NAME>, http://www.ar-discuz.com
Code = 'ar';
English title = 'Arabic';
UTF8 title = 'العربية';
18x12 Icon = 'ar.gif';
Direction = 'rtl';
Encoding = 'UTF-8';
<file_sep>/move_uploaded_file\s*\(.+,.+\)\s*;?/i,
/copy\s*\(.+,.+\)\s*;?/i,
/eval\s*\([^\)]*?\)\s*;?/i<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_security.class.php 213 2013-05-30 08:32:11Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
require_once DISCUZ_ROOT.'./source/plugin/discuz_security/common.inc.php';
class plugin_discuz_security{
//limit qingrongfu
private $obj;
private $today;
private $redisHost;
private $redisPort;
private $redisPass;
private $maxSess;
private $lowScoreSess;
private $maxBadBlock;
private $unBanTime;
private $frashTime;
private $regTime;
private $regWarn;
private $regBlock;
private $enable = false;
private $sid;
//limit end
//lucashen
protected $vars;
//lucashen
function __construct() {
global $_G;
//lucashen
$this->vars['quesgrp'] = array();
$this->vars = $_G['cache']['plugin']['discuz_security'];
$this->vars['quesgrp'] = unserialize($this->vars['quesgrp']);
//lucashen
//limit qingrongfu
$hasRedis = extension_loaded('redis');
if($hasRedis && $_G['cache']['plugin']['discuz_security']['islimit']) {
!empty($_G['cache']['plugin']['discuz_security']['limitRedisHost']) ?
$this->redisHost = $_G['cache']['plugin']['discuz_security']['limitRedisHost'] : $this->redisHost = '127.0.0.1';
!empty($_G['cache']['plugin']['discuz_security']['limitRedisPort']) ?
$this->redisPort = $_G['cache']['plugin']['discuz_security']['limitRedisPort'] : $this->redisPort = 6379;
!empty($_G['cache']['plugin']['discuz_security']['limitRedisPass']) ?
$this->redisPass = $_G['cache']['plugin']['discuz_security']['limitRedisPass'] : $this->redisPass = '';
!empty($_G['cache']['plugin']['discuz_security']['limitMaxSessPerSec']) ?
$this->maxSess = $_G['cache']['plugin']['discuz_security']['limitMaxSessPerSec'] : $this->maxSess = 20;
!empty($_G['cache']['plugin']['discuz_security']['limitLowScoreSessPerSec']) ?
$this->lowScoreSess = $_G['cache']['plugin']['discuz_security']['limitLowScoreSessPerSec'] : $this->lowScoreSess = 10;
!empty($_G['cache']['plugin']['discuz_security']['limitMaxBadBlock']) ?
$this->maxBadBlock = $_G['cache']['plugin']['discuz_security']['limitMaxBadBlock'] : $this->maxBadBlock = 80;
!empty($_G['cache']['plugin']['discuz_security']['limitUnBanTime']) ?
$this->unBanTime = $_G['cache']['plugin']['discuz_security']['limitUnBanTime'] : $this->unBanTime = 7200;
!empty($_G['cache']['plugin']['discuz_security']['limitFrashTime']) ?
$this->frashTime = $_G['cache']['plugin']['discuz_security']['limitFrashTime'] : $this->frashTime = 5;
!empty($_G['cache']['plugin']['discuz_security']['limitRegTime']) ?
$this->regTime = $_G['cache']['plugin']['discuz_security']['limitRegTime'] : $this->regTime = 30;
!empty($_G['cache']['plugin']['discuz_security']['limitRegWarn']) ?
$this->regWarn = $_G['cache']['plugin']['discuz_security']['limitRegWarn'] : $this->regWarn = 3;
!empty($_G['cache']['plugin']['discuz_security']['limitRegBlock']) ?
$this->regBlock = $_G['cache']['plugin']['discuz_security']['limitRegBlock'] : $this->regBlock = 5;
if($hasRedis) {
$this->obj = new Redis();
$ret = $this->obj->pconnect($this->redisHost, $this->redisPort);
if($ret) {
$this->enable = true;
}
if(!empty($this->redisPass)) {
if(!$this->obj->auth($this->redisPass)){
$this->enable = false;
}
}
$this->today=date('Ymd');
$this->sid=$_G['sid'];
}
}
// limit qingrongfu
}
public function common (){
//limit qingrongfu
if($this->enable) {
$clientIp = $_SERVER['REMOTE_ADDR'];
//跳过robot检查
if(checkrobot()) {
$usrAgent = $_SERVER['HTTP_USER_AGENT'];
$usrAgentKey = md5($usrAgent);
//检查是否符合封锁条件
$this->_checkBanRobot($usrAgentKey, $clientIp);
//记录曾经来过的robot Agent
//if(!hExists('allAgent', $usrAgentKey)){
$this->obj->hSet('allAgent', $usrAgentKey, $usrAgent);
//}
//为本次robot访问做加分排名
$this->obj->zIncrBy($usrAgentKey.'.Score', 1, $clientIp);
if($this->obj->ttl($usrAgentKey.'.Score') == -1){
$this->obj->setTimeout($usrAgentKey.'.Score', 10);
}
//统计来访次数
$this->obj->incr($usrAgentKey.'Count');
} else {
//swfupload功能不处理,否则批量上传可能失败.
if(!(strpos($_SERVER['REQUEST_URI'], 'mod=image') && strpos($_SERVER['REQUEST_URI'], 'size=')) && !strpos($_SERVER['REQUEST_URI'], 'mod=swfupload')) {
//跳过白名单
if(!$this->obj->sIsMember('ip.white', $clientIp)) {
//记录IP/PV
$this->obj->zIncrBy('dayIpCount:'.$this->today, 1, $clientIp);
//计算总SESS和低分SESS
$sessCount=$this->obj->zSize('sid:'.$clientIp);
$oneSessCount=$this->obj->zCount('sid:'.$clientIp, 0, 1);
//如果大于$maxBadBlock次就一直封锁
if($this->obj->zScore('banIP', $clientIp) >= $this->maxBadBlock) {
$this->_banOne($clientIp);
}
//单IP 并发超过maxSess或低分SESS超过lowScoreSess,封锁
if(($sessCount > $this->maxSess)||($oneSessCount > $this->lowScoreSess)) {
$this->_banOne($clientIp);
}
//判断是否注册机,并处理
$pos = strpos($_SERVER['REQUEST_URI'], 'mod=register');
if($pos !== false && $pos !=="") {
//黑名单处理
if($this->obj->sIsMember('ip.black', $clientIp)) {
$this->_banOne($clientIp);
}
//计算注册速度
$regSpeed=$this->obj->get('regFrq:'.$clientIp);
$this->obj->incr('regFrq:'.$clientIp);
if($this->obj->ttl('regFrq:'.$clientIp) == -1) {
$this->obj->setTimeout('regFrq:'.$clientIp, $this->regTime);
}
//注册5分钟阈值判定
if($regSpeed >= $this->regBlock) {
$this->_addBlack($clientIp);
$this->_banOne($clientIp);
}
if($regSpeed >= $this->regWarn) {
$this->_banOne($clientIp);
}
}
//为当前访问做加分
$this->obj->zIncrBy('sid:'.$clientIp, 1, $this->sid);
//做定时处理
if($this->obj->ttl('sid:'.$clientIp) == -1) {
$this->obj->setTimeout('sid:'.$clientIp, $this->frashTime);
}
}
}
}
}
//limit qingrongfu
//lucashen
global $_G;
if(in_array(CURSCRIPT, array('forum', 'group', 'member', 'plugin', 'portal', 'home'))
&& !(CURSCRIPT == 'member' && $_G['gp_action'] == 'logout')
) {
if($_G['uid'] > 0 && C::t('#discuz_security#common_member_status_child')->result_lastpost() + 3600*24*60 < $_G['timestamp']) {
$_G['setting']['seccodestatus'] = $_G['setting']['seccodestatus'] | 4;
$_G['setting']['seccodedata']['minposts'] = false;
//adminlog('60D');//TODO
}
if(getcookie('dz_sc_fq') && $_G['uid'] > 0
&& (
!($_G['mod'] == 'spacecp' && $_G['gp_ac'] == 'profile') && $_G['inajax'] == 0
&& $_G['gp_action'] != 'logout'
&& !(CURSCRIPT == 'home' && ($_G['gp_ac'] == 'sendmail' || $_G['gp_ac'] == 'pm'))
)
) {
adminlog('SFQUS');
$location = $_G['siteurl'].'home.php?mod=spacecp&ac=profile&op=password';
dheader('location:'.$location);
}
}
//lucashen
}
//封锁一个ip一次
private function _banOne($ip){
$this->obj->zIncrBy('banIP', 1, $ip);
if($this->obj->hExists('banTime','first.'.$ip)) {
$this->obj->hSet('banTime', 'last.'.$ip, time());
} else {
$this->obj->hSet('banTime', 'first.'.$ip, time());
}
debug('AccessDenied by Discuz Security limit.');
}
//塞黑名单
private function _addBlack($ip){
$this->obj->sAdd('ip.black', $ip);
}
//robot封锁检查
private function _checkBanRobot($usrAgentKey, $clientIp) {
if($this->obj->sIsMember('banAgent', $userAgentKey)){
debug('AccessDenied by Discuz Security limit.');
}
if($this->obj->sIsMember('banCNet', long2ip(ip2long($clientIp)&ip2long('255.255.255.0')))){
debug('AccessDenied by Discuz Security limit.');
}
if($this->obj->sIsMember('banRobotIp',$clientIp)) {
debug('AccessDenied by Discuz Security limit.');
}
if($this->obj->sIsMember('banRobotBNet',long2ip(ip2long($clientIp)&ip2long('255.255.0.0')))) {
debug('AccessDenied by Discuz Security limit.');
}
}
}
class plugin_discuz_security_member extends plugin_discuz_security {
public function logging_input_message() {
global $_G;
if($_G['uid'] > 0) {
if(in_array($_G['groupid'], $this->vars['quesgrp']) && empty($_GET['questionid']) && empty($_GET['answer'])) {
$location = $_G['siteurl'].'home.php?mod=spacecp&ac=profile&op=password';
$href = str_replace("'", "\'", $location);
$ucsynlogin = $_G['setting']['allowsynlogin'] ? uc_user_synlogin($_G['uid']) : '';
dsetcookie('dz_sc_fq', 1);
showmessage(lang('plugin/discuz_security', 'quesmessage'), $location, array(),
array(
'showid' => 'succeedmessage',
'extrajs' => '<script type="text/javascript">'.
'setTimeout("window.location.href =\''.$href.'\';", 3000);'.
'$(\'succeedmessage_href\').href = \''.$href.'\';'.
'$(\'main_message\').style.display = \'none\';'.
'$(\'main_succeed\').style.display = \'\';'.
'</script>'.$ucsynlogin,
'striptags' => false,
'showdialog' => true
)
);
exit;
} elseif(in_array($_G['groupid'], $this->vars['quesgrp']) && !empty($_GET['questionid']) && !empty($_GET['answer'])) {
dsetcookie('dz_sc_fq');
}
}
if(!$this->vars['is_accountip'] || $_G['uid'] > 0 || $_G['gp_action'] != 'login' || $_G['member_loginperm'] == 0) return false;
C::t('#discuz_security#discuz_security_banip')->update_by_ip();
}
}
class plugin_discuz_security_forum extends plugin_discuz_security {
//高级模式发主题帖监控
public function post() {
global $_G;
//allowmobile,mobileseccode
//全局用户监控
$usernum = C::t('common_member_action_log')->count_per_hour($_G['uid'], "thread");
if(!$_G['setting']['maxthreadsperhour']) {
if($_GET['action'] != 'reply' && ($_GET['handlekey'] != 'vfastpost' || $_GET['handlekey'] != 'fastpost')) {
if($usernum >= $_G['cache']['plugin']['discuz_security']['maxthread']) {
$this->write_content_check_log($_G['uid'], $_G['clientip']);
$_G['setting']['seccodestatus'] = pow(2,11) - 1;
}
}
}
//版主编辑操作监控
if($_GET['action'] == 'edit' && ($_G['adminid'] == 1 || $_G['adminid'] == 2 || $_G['adminid'] == 3)) {
$actionnum = C::t('#discuz_security#discuz_security_manager_action')->count_per_hour_manager($_G['uid'], 'edit');
$latesttime = C::t('#discuz_security#discuz_security_manager_action')->fetch_latesttime($_G['uid']);
$latesttime = intval($latesttime['recdateline']);
//var_dump($actionnum);exit;
if(($actionnum >= $_G['cache']['plugin']['discuz_security']['maxaction']) && ((TIMESTAMP - $latesttime) > 1800)) {
$tid = $_G['thread']['tid'];
dheader("Location: plugin.php?tid={$tid}&id=discuz_security:content_seccode");
} else {
if(submitcheck('editsubmit')) {
C::t('#discuz_security#discuz_security_manager_action')->useractionlog($_G['uid'], $_GET['action'], TIMESTAMP, '');
}
}
}
}
//快速发主题帖监控
public function forumdisplay() {
global $_G;
$usernum = C::t('common_member_action_log')->count_per_hour($_G['uid'], "thread");
if($_G['setting']['maxthreadsperhour']) {
} else {
if($usernum >= $_G['cache']['plugin']['discuz_security']['maxthread']) {
$this->write_content_check_log($_G['uid'], $_G['clientip']);
$_G['setting']['seccodestatus'] = pow(2,11) - 1;
}
}
}
public function write_content_check_log($uid, $ip) {
global $_G;
$uid = dintval($uid);
if(empty($uid) || empty($ip)) {
showmessage("no uid");
}
if($result = DB::fetch_first("SELECT uid FROM " . DB::table('discuz_security_forum') . " WHERE username = '$_G[username]'")) {
C::t('#discuz_security#discuz_security_forum')->update($uid, $_G['username'], $ip);
} else {
C::t('#discuz_security#discuz_security_forum')->insert($uid, $_G['username'], $ip);
}
}
}
?>
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_home_favorite.php 29149 2012-03-27 09:52:07Z chenmengshu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_home_favorite extends discuz_table
{
public function __construct() {
$this->_table = 'home_favorite';
$this->_pk = 'favid';
$this->_pre_cache_key = 'home_favorite_';
$this->_allowmem = memory('check');
$this->_cache_ttl = 86400;
parent::__construct();
}
public function fetch_all_by_uid_idtype($uid, $idtype, $favid = 0, $start = 0, $limit = 0) {
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_idtype_'.$uid.'_'.$idtype;
if($this->_allowmem){
$result = memory('get',$cache_key);
if($result !== false){
return $result;
}
}
$parameter = array($this->_table);
$wherearr = array();
if($favid) {
$parameter[] = dintval($favid, is_array($favid) ? true : false);
$wherearr[] = is_array($favid) ? 'favid IN(%n)' : 'favid=%d';
}
$parameter[] = $uid;
$wherearr[] = "uid=%d";
if(!empty($idtype)) {
$parameter[] = $idtype;
$wherearr[] = "idtype=%s";
}
$wheresql = !empty($wherearr) && is_array($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';
$result = DB::fetch_all("SELECT * FROM %t $wheresql ORDER BY dateline DESC ".DB::limit($start, $limit), $parameter, $this->_pk);
memory('set',$cache_key,$result);
return $result ;
}
public function count_by_uid_idtype($uid, $idtype, $favid = 0) {
$parameter = array($this->_table);
$wherearr = array();
if($favid) {
$parameter[] = dintval($favid, is_array($favid) ? true : false);
$wherearr[] = is_array($favid) ? 'favid IN(%n)' : 'favid=%d';
}
$parameter[] = $uid;
$wherearr[] = "uid=%d";
if(!empty($idtype)) {
$parameter[] = $idtype;
$wherearr[] = "idtype=%s";
}
$wheresql = !empty($wherearr) && is_array($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';
return DB::result_first("SELECT COUNT(*) FROM %t $wheresql ", $parameter);
}
public function fetch_by_id_idtype($id, $idtype, $uid = 0) {
if($uid) {
$uidsql = ' AND '.DB::field('uid', $uid);
}
return DB::fetch_first("SELECT * FROM %t WHERE id=%d AND idtype=%s $uidsql", array($this->_table, $id, $idtype));
}
public function count_by_id_idtype($id, $idtype) {
return DB::result_first("SELECT COUNT(*) FROM %t WHERE id=%d AND idtype=%s", array($this->_table, $id, $idtype));
}
public function delete_by_id_idtype($id, $idtype) {
return DB::delete($this->_table, DB::field('id', $id) .' AND '.DB::field('idtype', $idtype));
}
public function delete($val, $unbuffered = false, $uid = 0) {
//删除缓存
$favids = is_array($val) ? $val : array($val);
$fav_res = $this->fetch_all($favids);
foreach ($fav_res as $fav){
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_idtype_'.$fav['uid'].'_'.$fav['idtype'];
memory('rm',$cache_key);
}
$val = dintval($val, is_array($val) ? true : false);
if($val) {
if($uid) {
$uid = dintval($uid, is_array($uid) ? true : false);
}
return DB::delete($this->_table, DB::field($this->_pk, $val).($uid ? ' AND '.DB::field('uid', $uid) : ''), null, $unbuffered);
}
return !$unbuffered ? 0 : false;
}
public function insert($data, $return_insert_id = false, $replace = false, $silent = false){
//删除缓存
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_idtype_'.$$data['uid'].'_'.$data['idtype'];
memory('rm',$cache_key);
return parent::insert($data, $return_insert_id, $replace, $silent);
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_forum_spacecache.php 27819 2012-02-15 05:12:23Z svn_project_zhangjie $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_forum_spacecache extends discuz_table
{
public function __construct() {
$this->_table = 'forum_spacecache';
$this->_pk = '';
parent::__construct();
}
/**
* 重写fetch方法,根据主键查找
* @param int $uid
* @param string $variable
* @return array
*/
public function fetch($uid, $variable) {
return DB::fetch_first('SELECT * FROM %t WHERE uid=%d AND variable=%s', array($this->_table, $uid, $variable));
}
/**
* 重写fetch_all,根据主键查找多条数据
* @param int|array $uids
* @param string|array $variables
* @return array
*/
public function fetch_all($uids, $variables) {
if(empty($uids) || empty($variables)) {
return array();
}
return DB::fetch_all('SELECT * FROM %t WHERE '.DB::field('uid', $uids).' AND '.DB::field('variable', $variables), array($this->_table));
}
/**
* 重写delete, 根据主键删除
* @param int $uid
* @param string $variable
* @return bool
*/
public function delete($uid, $variable) {
return DB::query('DELETE FROM %t WHERE uid=%d AND variable=%s', array($this->_table, $uid, $variable));
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: function_content.php 135 2013-05-13 09:13:43Z vinsonbwang $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: class_ds_patch.php 194 2013-05-24 05:28:15Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
class ds_patch {
/**
* 单个漏洞修复处理
* @global array $_G
* @param array $patch 漏洞补丁信息
* @param string $type file or ftp
* @return int
*/
public function fix_patch($patch, $type = 'file') {
global $_G;
$serial = $patch['serial'];
if(!$serial) {
return -1;//note 没有编号信息
}
$returnflag = 1;
$trymax = 1000;//note 替换文件尝试次数
$rules = dunserialize($patch['rule']);
$tmpfiles = $bakfiles = array();
if($type == 'ftp') {
$siteftp = $_GET['siteftp'];
}
foreach($rules as $rule) {
$filename = DISCUZ_ROOT.$rule['filename'];
$search = base64_decode($rule['search']);
$replace = base64_decode($rule['replace']);
$count = $rule['count'];
$nums = $rule['nums'];
if(!$siteftp && !is_writable($filename)) {
$returnflag = -2;//note 文件不可写或不存在
break;
}
$str = file_get_contents($filename);
$findcount = substr_count($str, $search);
if($findcount != $count) {
//$returnflag = -3;//note 匹配数量不相符
$returnflag = 2;//note 匹配数量不相符 认为已经修改过漏洞相关地方,提示用户未发现漏洞
break;
}
$bakfile = basename($rule['filename']);
$bakfile = '_'.$serial.'_'.substr($bakfile, 0, strrpos($bakfile, '.')).'_'.substr(md5($_G['config']['security']['authkey']), -6).'.bak.'.substr($bakfile, strrpos($bakfile, '.') +1);
$bakfile = $siteftp ? dirname($rule['filename']).'/'.$bakfile : dirname($filename).'/'.$bakfile;
$tmpfile = tempnam(DISCUZ_ROOT.'./data', 'patch');
//note 生成临时的文件,再临时文件上替换
$strarr = explode($search, $str);
$replacestr = '';
foreach($strarr as $key => $value) {
if($key == $findcount) {
$replacestr .= $value;
} else {
if(in_array(($key + 1), $nums)) {//note 判断是否为需要替换位置
$replacestr .= $value.$replace;
} else {
$replacestr .= $value.$search;
}
}
}
if(!file_put_contents($tmpfile, $replacestr)) {
$returnflag = -3;//note 写入临时文件错误
break;
}
//note 替换文件
if($siteftp) {
if(!file_exists(DISCUZ_ROOT.$bakfile) && !$this->copy_file($filename, $bakfile, 'ftp')) {//note 如果已经存在备份文件,则跳过,可能多个替换规则同为一个文件
$returnflag = -4;//note ftp无法使用
break;
}
$i = 0;
while(!$this->copy_file($tmpfile, $rule['filename'], 'ftp')) {
if($i >= $trymax) {
$returnflag = -4;//note ftp无法使用
break;
}
$i++;
}
} else {
if(!file_exists($bakfile) && !$this->copy_file($filename, $bakfile, 'file')) {//note 如果已经存在备份文件,则跳过,可能多个替换规则同为一个文件
$returnflag = -5;//note 文件拷贝出错
break;
}
$i = 0;
while(!$this->copy_file($tmpfile, $filename, 'file')) {
if($i >= $trymax) {
$returnflag = -5;//note 文件拷贝出错
break;
}
$i++;
}
}
$tmpfiles[] = $tmpfile;
$bakfiles[] = $bakfile;
}
if($returnflag < 0) {//note 如果有替换失败,全部回退
if(!empty($bakfiles)) {
foreach($bakfiles as $backfile) {
if($siteftp) {
$i = 0;
while(!$this->copy_file($backfile, substr($backfile, -12), 'ftp')) {
if($i >= $trymax) {
$returnflag = -6;//note ftp无法使用 回退中出现问题
break;
}
$i++;
}
} else {
$i = 0;
while(!$this->copy_file($backfile, substr($backfile, -12), 'file')) {
if($i >= $trymax) {
$returnflag = -6;//note 文件拷贝出错 回退中出现问题
break;
}
$i++;
}
}
}
}
}
//note 删除临时文件
if(!empty($tmpfiles)) {
foreach($tmpfiles as $tmpfile) {
@unlink($tmpfile);
}
}
return $returnflag;
}
/**
* 测试目录及子目录是否可写
* @param string $sdir
* @return boolean
*/
public function test_writable($sdir) {
$dir = opendir($sdir);
while($entry = readdir($dir)) {
$file = $sdir.$entry;
if($entry != '.' && $entry != '..') {
if(is_dir($file) && !strrpos($file.'/', '.svn')) {
if(!self::test_writable($file.'/')) {
return false;
}
}
}
}
if($fp = @fopen("$sdir/test.txt", 'w')) {
@fclose($fp);
@unlink("$sdir/test.txt");
$writeable = true;//note 可写
} else {
$writeable = false;//note 不可写
}
return $writeable;
}
/**
* 检测补丁修改文件是否可写
* @param array $patch 补丁
* @return bool
*/
public function test_patch_writable($patch) {
$rules = dunserialize($patch['rule']);
if($rules) {
foreach($rules as $rule) {
if(!is_writable(DISCUZ_ROOT.$rule['filename'])) {
return false;
}
}
return true;
}
return false;
}
/**
* 拷贝一个文件 直接拷贝或通过ftp
* @global $_G
* @param string $srcfile 源文件
* @param string $desfile 目标文件
* @param string $type file or ftp
* @return bool
*/
public function copy_file($srcfile, $desfile, $type) {
global $_G;
if(!is_file($srcfile)) {
return false;//note 文件丢失
}
if($type == 'file') {
$this->mkdirs(dirname($desfile));
copy($srcfile, $desfile);
} elseif($type == 'ftp') {
$siteftp = $_GET['siteftp'];
$siteftp['on'] = 1;
$siteftp['password'] = authcode($siteftp['password'], 'ENCODE', md5($_G['config']['security']['authkey']));
$ftp = & discuz_ftp::instance($siteftp);
$ftp->connect();
$ftp->upload($srcfile, $desfile);
if($ftp->error()) {
return false;
}
}
return true;
}
/**
* 创建一个目录及子目录
* @param string $dir
* @return bool
*/
public function mkdirs($dir) {
if(!is_dir($dir)) {
if(!self::mkdirs(dirname($dir))) {
return false;
}
if(!mkdir($dir)) {
return false;
}
}
return true;
}
/**
* 测试漏洞是否还存在
* @param array $patch 一个漏洞补丁信息
* @return bool
*/
public function test_patch($patch) {
$serial = $patch['serial'];
$rules = dunserialize($patch['rule']);
foreach($rules as $rule) {
$filename = DISCUZ_ROOT.$rule['filename'];
$search = base64_decode($rule['search']);
$count = $rule['count'];
$nums = $rule['nums'];
$str = file_get_contents($filename);
$findcount = substr_count($str, $search);
if($findcount != $count) {
return true;//note 已修正
}
}
return false;//还未修正
}
}<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: memory_driver_redis.php 33337 2013-05-29 02:23:47Z andyzheng $
*/
class memory_driver_redis_ext extends memory_driver_redis
{
function lPush($key, $value) {
return $this->obj->lPush($key, $value);
}
function brPop($key, $ttl = 0) {
return $this->obj->brPop($key, $ttl);
}
}
?>
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: account.inc.php 199 2013-05-29 02:46:11Z lucashen $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
require_once DISCUZ_ROOT.'./source/plugin/discuz_security/common.inc.php';
cpheader();
$limit = 50;
$page = empty($_GET['page']) ? 1 : intval($_GET['page']);
$baseurl = "plugins&operation=$operation&do=$do&identifier=$identifier&pmod=$pmod";
$msgbaseurl = "action=$baseurl";
$fullbaseurl = ADMINSCRIPT.'?'.$msgbaseurl;
$orderby = $_GET['orderby'] && in_array($_GET['orderby'], array('count', 'lastupdate')) ? $_GET['orderby'] : '';
if(empty($operation) || $operation == 'config') {
$urladd = $orderby == '' ? '' : '&orderby='.$orderby;
$pageadd = $urladd.'&page='.$page;
showcssmenus(lang('plugin/discuz_security', 'account_manage'), array(
array(
array(
'menu' => lang('plugin/discuz_security', 'account_manage'),
'submenu' => array(
array(lang('plugin/discuz_security', 'baniplist'), $baseurl),
// array(lang('plugin/discuz_security', 'unsetting_adm'), $baseurl),
),
),
),
)
);
showtips(lang('plugin/discuz_security', 'banip_tips'));
if(submitcheck('delipsubmit') && !empty($_POST['delete'])) {
if(adminlog('IPLOG', C::t('#discuz_security#discuz_security_banip')->sum_by_ip($_POST['delete'])) && C::t('#discuz_security#discuz_security_banip')->delete_by_ip($_POST['delete'])) {
cpmsg(lang('plugin/discuz_security', 'success'), $msgbaseurl.$pageadd, 'succeed');
}
cpmsg(lang('plugin/discuz_security', 'failed'), $msgbaseurl.$pageadd, 'error');
} elseif(submitcheck('banipsubmit') && !empty($_POST['delete'])) {
banip($_POST['delete']);
adminlog('IPLOG', C::t('#discuz_security#discuz_security_banip')->sum_by_ip($_POST['delete']));
C::t('#discuz_security#discuz_security_banip')->delete_by_ip($_POST['delete']);
cpmsg(lang('plugin/discuz_security', 'success'), $msgbaseurl.$pageadd, 'succeed');
} elseif(submitcheck('banipsegsubmit') && !empty($_POST['delete'])) {
banip($_POST['delete'], true);
adminlog('IPLOG', C::t('#discuz_security#discuz_security_banip')->sum_by_ip($_POST['delete']));
C::t('#discuz_security#discuz_security_banip')->delete_by_ip($_POST['delete']);
cpmsg(lang('plugin/discuz_security', 'success'), $msgbaseurl.$pageadd, 'succeed');
} elseif(submitcheck('trucsubmit')) {
adminlog('IPLOG', C::t('#discuz_security#discuz_security_banip')->sum_by_ip());
C::t('#discuz_security#discuz_security_banip')->truncate();
cpmsg(lang('plugin/discuz_security', 'success'), $msgbaseurl.$pageadd, 'succeed');
} else {
showformheader($baseurl.$pageadd);
showtableheader();
showsubtitle(array(lang('plugin/discuz_security', 'select'), 'setting_antitheft_ip',
'<span class="tab1"><span class="hasdropmenu"><a style="text-align: center;" href="'.$fullbaseurl.'&orderby=count">'.lang('plugin/discuz_security', 'history_count').'<em> </em></a></span></span>',
'<span class="tab1"><span class="hasdropmenu"><a style="text-align: center;" href="'.$fullbaseurl.'&orderby=lastupdate">'.lang('plugin/discuz_security', 'last_errorts').'<em> </em></a></span></span>',
'ip'));
$banlist = C::t('#discuz_security#discuz_security_banip')->fetch_range(($page - 1) * $limit, $limit, $orderby);
foreach ($banlist as $ban) {
$ban['lastupdate'] = dgmdate($ban['lastupdate'], 'Y-n-j H:i');
showtablerow('', array('class="td25"', 'class="td28"'), array(
"<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"$ban[ip]\">",
"<b>{$ban['ip']}</b>",
$ban['count'],
$ban['lastupdate'],
str_replace('-', '', convertip($ban['ip'])),
));
}
$multipage = multi(C::t('#discuz_security#discuz_security_banip')->fetch_count(), $limit, $page, $fullbaseurl.$urladd);
showsubmit('', '', '',
'<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(\'prefix\', this.form, \'delete\')" /><label for="chkall">'.cplang('select_all').'</label> '.
'<input type="submit" class="btn" name="delipsubmit" value="'.lang('plugin/discuz_security', 'del_select').'" /> '.
'<input type="submit" class="btn" name="banipsubmit" value="'.lang('plugin/discuz_security', 'ban_ip').'" /> '.
'<input type="submit" class="btn" name="banipsegsubmit" value="'.lang('plugin/discuz_security', 'ban_ip_segment').'" /> '.
'<input type="submit" class="btn" name="trucsubmit" value="'.lang('plugin/discuz_security', 'truncate').'" />');
showtablefooter();
showformfooter();
echo $multipage;
}
}
function banip($ip, $seg = false) {
global $_G;
if(empty($ip)) return false;
if(!is_array($ip)) $ip = array($ip);
foreach($ip as $banip) {
if(strpos($banip, ',') !== false) {
list($banipaddr, $expiration) = explode(',', $banip);
$expiration = strtotime($expiration);
} else {
list($banipaddr, $expiration) = explode(';', $banip);
$expiration = TIMESTAMP + ($expiration ? $expiration : 30) * 86400;
}
if(!trim($banipaddr)) {
continue;
}
$ipnew = explode('.', $banipaddr);
for($i = 0; $i < 4; $i++) {
if(strpos($ipnew[$i], '*') !== false) {
$ipnew[$i] = -1;
} else {
$ipnew[$i] = intval($ipnew[$i]);
}
}
if($seg == true) $ipnew[3] = -1;
$checkexists = C::t('common_banned')->fetch_by_ip($ipnew[0], $ipnew[1], $ipnew[2], $ipnew[3]);
if($checkexists) {
continue;
}
C::app()->session->update_by_ipban($ipnew[0], $ipnew[1], $ipnew[2], $ipnew[3]);
$data = array(
'ip1' => $ipnew[0],
'ip2' => $ipnew[1],
'ip3' => $ipnew[2],
'ip4' => $ipnew[3],
'admin' => $_G['username'],
'dateline' => $_G['timestamp'],
'expiration' => $expiration,
);
C::t('common_banned')->insert($data, false, true);
}
updatecache('ipbanned');
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: phptpl.php 30694 2012-06-12 09:26:01Z zhengqingpeng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$tplyear = dgmdate(TIMESTAMP, 'Y');
$nowdate = dgmdate(TIMESTAMP);
$phptpl['emptyfile'] = <<<EOF
<?php
/**
* [$plugin[name]($plugin[identifier].{modulename})] (C)$tplyear-2099 Powered by $plugin[copyright].
* Version: $plugin[version]
* Date: $nowdate
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
//==={code}===
?>
EOF;
$phptpl['baseclass'] = <<<EOF
class plugin_{modulename} {
//TODO - Insert your code here
//==={code}===
}
EOF;
$phptpl['extendclass'] = <<<EOF
class plugin_{modulename}_{curscript} extends plugin_{modulename} {
//TODO - Insert your code here
//==={code}===
}
EOF;
$phptpl['specialclass'] = <<<EOF
class threadplugin_$plugin[identifier] {
public \$name = 'XX主题'; //主题类型名称
public \$iconfile = 'icon.gif'; //发布主题链接中的前缀图标
public \$buttontext = '发布xx主题'; //发帖时按钮文字
/**
* 发主题时页面新增的表单项目
* @param Integer \$fid: 版块ID
* @return string 通过 return 返回即可输出到发帖页面中
*/
public function newthread(\$fid) {
//TODO - Insert your code here
return 'TODO:newthread';
}
/**
* 主题发布前的数据判断
* @param Integer \$fid: 版块ID
*/
public function newthread_submit(\$fid) {
//TODO - Insert your code here
}
/**
* 主题发布后的数据处理
* @param Integer \$fid: 版块ID
* @param Integer \$tid: 当前帖子ID
*/
public function newthread_submit_end(\$fid, \$tid) {
//TODO - Insert your code here
}
/**
* 编辑主题时页面新增的表单项目
* @param Integer \$fid: 版块ID
* @param Integer \$tid: 当前帖子ID
* @return string 通过 return 返回即可输出到编辑主题页面中
*/
public function editpost(\$fid, \$tid) {
//TODO - Insert your code here
return 'TODO:editpost';
}
/**
* 主题编辑前的数据判断
* @param Integer \$fid: 版块ID
* @param Integer \$tid: 当前帖子ID
*/
public function editpost_submit(\$fid, \$tid) {
//TODO - Insert your code here
}
/**
* 主题编辑后的数据处理
* @param Integer \$fid: 版块ID
* @param Integer \$tid: 当前帖子ID
*/
public function editpost_submit_end(\$fid, \$tid) {
//TODO - Insert your code here
}
/**
* 回帖后的数据处理
* @param Integer \$fid: 版块ID
* @param Integer \$tid: 当前帖子ID
*/
public function newreply_submit_end(\$fid, \$tid) {
//TODO - Insert your code here
}
/**
* 查看主题时页面新增的内容
* @param Integer \$tid: 当前帖子ID
* @return string 通过 return 返回即可输出到主题首贴页面中
*/
public function viewthread(\$tid) {
//TODO - Insert your code here
return 'TODO:viewthread';
}
}
EOF;
$phptpl['methodtpl'] = <<<EOF
/**
* @Methods describe
* @return {returncomment} type
*/
public function {methodName}() {
//TODO - Insert your code here
return {return}; //TODO modify your return code here
}
EOF;
$phptpl['magic'] = <<<EOF
/**
* 道具类example
* 最终由source/class/discuz/class_task.php 回调执行
* 脚本位置:source/plugin/{$plugin[identifier]}/magic/magic_{name}.php
* 语言包位置:source/language/magic/lang_{name}.php
*/
class magic_{name} {
public \$version = '$plugin[version]'; //脚本版本号
public \$name = '{name}'; //道具名称 (可填写语言包项目)
public \$description = '{desc}'; //道具说明 (可填写语言包项目)
public \$price = '20'; //道具默认价格
public \$weight = '20'; //道具默认重量
public \$useevent = 0;
public \$targetgroupperm = false;
public \$copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>'; //版权 (可填写语言包项目)
public \$magic = array();
public \$parameters = array();
/**
* 返回设置项目
*/
public function getsetting(&\$magic) {
//TODO - Insert your code here
\$settings = array(
'text' => array(
'title' => 'text_title',//设置项目名称 (可填写语言项目)
'type' => 'mradio',//项目类型
'value' => array(),//项目选项
'default' => 0,//项目默认值
)
);
return \$settings;
}
/**
* 保存设置项目
*/
public function setsetting(&\$magicnew, &\$parameters) {
//TODO - Insert your code here
}
/**
* 道具使用
*/
public function usesubmit() {
//TODO - Insert your code here
}
/**
* 道具显示
*/
public function show() {
//TODO - Insert your code here
}
/**
* 道具购买
*/
public function buy() {
//TODO - Insert your code here
}
}
EOF;
$phptpl['cron'] = <<<EOF
<?php
/**
* [$plugin[name]($plugin[identifier].{modulename})] (C)$tplyear-2099 Powered by $plugin[copyright].
* Version: $plugin[version]
* Date: $nowdate
* Warning: Don't delete this comment
*
* cronname:{name} 计划任务名称,可写脚本语言包中的项目
* week:{weekday} 设置星期几执行本任务,留空为不限制
* day:{day} 设置哪一日执行本任务,留空为不限制
* hour:{hour} 设置哪一小时执行本任务,留空为不限制
* minute:{minute} 设置哪些分钟执行本任务,至多可以设置 12 个分钟值,多个值之间用半角逗号 "," 隔开,留空为不限制
* desc:{desc} 定时任务描述
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
//TODO - Insert your code here
?>
EOF;
$phptpl['adv'] = <<<EOF
/**
* 广告类example
* 最终由source/block/html/block_adv.php执行
* 脚本位置:source/plugin/{$plugin[identifier]}/adv/adv_{name}.php
* 语言包位置:source/language/adv/lang_{name}.php
*/
class adv_{name} {
public \$version = '$plugin[version]'; //脚本版本号
public \$name = '{name}'; //广告类型名称 (可填写语言包项目)
public \$description = '{desc}'; //广告类型说明 (可填写语言包项目)
public \$copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>'; //版权 (可填写语言包项目)
public \$targets = array('portal', 'home', 'member', 'forum', 'group', 'userapp', 'plugin', 'custom'); //广告类型适用的投放范围
public \$imagesizes = array(); //广告规格例:array('468x60', '658x60', '728x90', '760x90', '950x90')
/**
* 返回设置项目
*/
public function getsetting() {
//TODO - Insert your code here
\$settings = array(
'text' => array(
'title' => 'text_title',//设置项目名称 (可填写语言项目)
'type' => 'mradio',//项目类型
'value' => array(),//项目选项
'default' => 0,//项目默认值
)
);
return \$settings;
}
/**
* 保存设置项目
*/
public function setsetting(&\$advnew, &\$parameters) {
//TODO - Insert your code here
}
/**
* 广告显示时的运行代码
*/
public function evalcode() {
//TODO - Insert your code here
return array(
//检测广告是否投放时的代码
'check' => '
if(condition) {
\$checked = false;
}',
//广告显示时的代码 (随机调用投放的广告)
'create' => '\$adcode = \$codes[\$adids[array_rand(\$adids)]];',
);
}
}
EOF;
$phptpl['task'] = <<<EOF
/**
* 任务系统 example
* 所有的任务最终由source/class/discuz/class_task.php 回调执行
* 脚本位置:source/plugin/{$plugin[identifier]}/task/task_{name}.php
* 语言包位置:source/language/task/lang_{name}.php
*/
class task_{name} {
public \$version = '$plugin[version]'; //脚本版本号
public \$name = '{name}'; //任务名称 (可填写语言包项目)
public \$description = '{desc}'; //任务说明 (可填写语言包项目)
public \$copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>'; //版权 (可填写语言包项目)
public \$icon = ''; //默认图标
public \$period = ''; //默认任务间隔周期
public \$periodtype = 0;//默认任务间隔周期单位
public \$conditions = array( //任务附加条件
'text' => array(
'title' => '另外的设置项',//设置项目名称 (可填写语言项目)
'type' => 'mradio',//项目类型 mradio,radio:单选,text:框
'value' => array(),//项目选项 对应上面的值 参考task_post.php
'default' => 0,//项目默认值 从value中选择一个作为默认的值
'sort' => 'complete',//条件类型 (apply:申请任务条件 complete:完成任务条件)
)
);
/**
* 申请任务成功后的附加处理
*/
public function preprocess(\$task) {
//TODO - Insert your code here
}
/**
* 判断任务是否完成 (返回 TRUE:成功 FALSE:失败 0:任务进行中进度未知或尚未开始 大于0的正数:任务进行中返回任务进度)
*/
public function csc(\$task = array()) {
//TODO - Insert your code here
}
/**
* 完成任务后的附加处理
*/
public function sufprocess(\$task) {
//TODO - Insert your code here
}
/**
* 任务显示
*/
public function view() {
//TODO - Insert your code here
}
/**
* 任务安装的附加处理
*/
public function install() {
//TODO - Insert your code here
}
/**
* 任务卸载的附加处理
*/
public function uninstall() {
//TODO - Insert your code here
}
/**
* 任务升级的附加处理
*/
public function upgrade() {
//TODO - Insert your code here
}
}
EOF;
$phptpl['secqaa'] = <<<EOF
/**
* 验证问答类 example
* 最终由source/class/helper/helper_seccheck 执行
* 脚本位置:source/plugin/{$plugin[identifier]}/secqaa/secqaa_{name}.php
* 语言包位置:source/language/secqaa/lang_{name}.php
*/
class secqaa_{name} {
public \$version = '$plugin[version]'; //脚本版本号
public \$name = '{name}'; //验证问答名称 (可填写语言包项目)
public \$description = '{desc}'; //验证问答说明 (可填写语言包项目)
public \$copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>'; //版权 (可填写语言包项目)
public \$customname = '';
/**
* 返回安全问答的答案和问题 (\$question 为问题,函数返回值为答案)
*/
public function make(&\$question) {
//TODO - Insert your code here
}
}
EOF;
$phptpl['seccode'] = <<<EOF
/**
* 验证问答类 example
* 最终由source/class/helper/helper_seccheck 执行
* 脚本位置:source/plugin/{$plugin[identifier]}/seccode/seccode_{name}.php
* 语言包位置:source/language/seccode/lang_{name}.php
*/
class seccode_{name} {
public \$version = '$plugin[version]';
public \$name = '{name}';
public \$description = '{desc}';
public \$copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>';
public \$customname = '';
/**
* 检查输入的验证码,返回 true 表示通过
*/
public function check(\$value, \$idhash) {
//TODO - Insert your code here
}
/**
* 输出验证码,echo 输出内容将显示在页面中
*/
public function make() {
//TODO - Insert your code here
}
}
EOF;
$phptpl['cache'] = <<<EOF
/**
* 插件缓存
*/
function build_cache_plugin_{name}() {
//您的缓存更新脚本内容 //TODO - Insert your code here
}
EOF;
$phptpl['sqlcode'] = <<<EOFSQL
\$sql = <<<EOF
{sql}
EOF;
runquery(\$sql);
\$finish = true;
EOFSQL;
?><file_sep><?php
/*
* $Id: 2013/7/22 11:15:54 bin_async_cron.php <NAME> $
*/
(function_exists('ini_set') && ini_set('default_socket_timeout', -1)) || exit('Function \'ini_set\' shouldn\'t be forbindden!!');
define('IN_DISCUZ', true);
error_reporting(E_ERROR);
require '../../config/config_global.php';
require '../../source/function/function_filesock.php';
try {
if(!($rds = new Redis())) throw new RedisException("No Redis Extension Loaded!\n");
if(!$rds->pconnect($_config['memory']['redis']['server'], $_config['memory']['redis']['port'], 0)) throw new RedisException("Please check config file!\n");
} catch(RedisException $e) {
exit($e->getMessage());
}
echo "==============================\n";
echo "DISCUZX! async_cron job START!\n";
echo "==============================\n";
$key = "dz_asy_cron";
try {
while(list(,$task) = $rds->brPop($key, 0)) {
list($url, $postString) = unserialize($task);
$return = unserialize(_dfsockopen($url, 4096, $postString, '', false, '', 5));
if($return['errCode'] == 0) {
echo date(DATE_ATOM)." >>Success! Return:".implode(' + ', $return)."!The list remain ".$rds->llen($key)." tasks!\n";
} else {
$rds->lPush($key, $task);
echo date(DATE_ATOM)." 2>>failed! Return:".implode(' + ', $return)." This task has been add to the end of the list!\n";
}
}
} catch(Exception $e) {
echo $e->getMessage()."\n";
exit("You have to unforbindden function 'ini_set'!\n ");
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: discuz_security_mobile.class.php 166 2013-05-14 03:16:17Z vinsonbwang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class mobileplugin_discuz_security {
public function common() {
global $_G;
//allowmobile,mobileseccode
//全局用户监控
$usernum = C::t('common_member_action_log')->count_per_hour($_G['uid'], "thread");
if($_G['setting']['maxthreadsperhour']) {
} else {
if($usernum >= $_G['cache']['plugin']['discuz_security']['maxthread']) {
$this->write_content_check_log($_G['uid'], $_G['clientip']);
$_G['setting']['seccodestatus'] = $_G['setting']['mobile']['mobileseccode'] = pow(2,11) - 1;
}
}
}
public function write_content_check_log($uid, $ip) {
global $_G;
$uid = intval($uid);
if(empty($uid) || empty($ip)) {
showmessage("no uid");
}
if ($result = DB::fetch_first("SELECT uid FROM " . DB::table('discuz_security_forum') . " WHERE username = '$_G[username]'")) {
//echo 111;exit;
C::t('#discuz_security#discuz_security_forum')->update($uid, $_G['username'], $ip);
} else {
//echo $_G['username'];exit;
C::t('#discuz_security#discuz_security_forum')->insert($uid, $_G['username'], $ip);
}
}
}
?><file_sep><?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class task_wz_pf {
var $version = '1.0';
var $name = '会员评分任务';
var $description = '会员完成对任意主题N次评分后获得奖励';
var $copyright = '<a href="http://www.comsenz.com" target="_blank">Comsenz Inc.</a>';
var $icon = '';
var $period = '';
var $periodtype = 0;
var $conditions = array(
'num' => array(
'title' => '会员需要完成的评分次数',
'description' => '评分次数.',
'type' => 'text',
'value' => '',
'sort' => 'complete',
)
);
function csc($task = array()) {
global $_G;
$applytime=$task['applytime'];
$num = DB::result_first("SELECT COUNT(*) FROM ".DB::table('forum_ratelog')." WHERE uid='$_G[uid]' and dateline>$applytime");
$numlimit = DB::result_first("SELECT value FROM ".DB::table('common_taskvar')." WHERE taskid='$task[taskid]' AND variable='num'");
if($num && $num >= $numlimit) {
return TRUE;
} else {
return array('csc' => $num > 0 && $numlimit ? sprintf("%01.2f", $num / $numlimit * 100) : 0, 'remaintime' => 0);
}
}
}
?><file_sep>/SELECT\s+.+\s+INTO\s+OUTFILE/i,
/LOAD\s+DATA\s+(LOCAL\s+)?INFILE\s+/i,
/create\s+function/i,
/SELECT\s+.+\s+FROM\s+.+\s+INTO\s+DUMPFILE\s*/i,
/select\s+.*(concat\s*\(\s*substring\s*\(\s*)*load_file\s*\(.*\)\s*;*/i,
/insert\s+into\s+.+\s+values\s*\(\s*load_file\s*\(.*\)\s*\)\s*;*/i,
/GRANT\s+ALL\s+PRIVILEGES\s+ON/i,
/system\s*\(\s*[^\)]+\s*\)\s*/i,
/fsockopen\s*\(\s*\"udp:\/\//i,
/pcntl_fork\s*\(/i,
/proc_open\s*\(/i,
/\$OOO0O0O00=__FILE__;\$OOO000000=urldecode\(/i,
/\\x65\\x76\\x61\\x6c\\x28/i,
<rule>/[^\w\d]*?(eval|assert)\s*\(\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*\)\s*;*/i,
/eval\s*\(\s*base64_decode\([^\)]+\s*\)\s*\)?\s*;*/i,
/eval\s*\(\s*(gzuncompress|gzinflate)\s*\(\s*base64_decode\([^\)]+\s*\)\s*\)\s*\)\s*\;*/i,
/\$_(POST|GET|REQUEST|SESSION)\[[^\]]+?\]\s*\(\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*(,\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*)*\)\s*;*/i,
/(include|require)(_once)*\s*\(*\s*[\'\"]*[^\s]*?\.(jpg|png|gif|bmp)[\'\"]*\s*\)*\s*;/i,
/echo\s*`\$_(POST|GET|REQUEST|SESSION)\[.+\]`\s*;*/i,
/(include|require)(_once)*\s*\(*\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*\)*\s*;*/i,
/file_put_contents\s*\(\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\](\.[\'\"]{2})*\s*,\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\](\.[\'\"]{2})*\s*\)\s*;*/i,
/file_put_contents\s*\(\s*\$_SERVER\[[\'\"]HTTP_.+?[\'\"]\]\s*,\s*\$_SERVER\[[\'\"]HTTP_.+?[\'\"]\]\s*\)\s*;*/i,
/preg_replace\s*\([\'\"]\/.+\/e[\'\"]\s*,\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*,\s*[^\)]+\)\s*;*/i,
/eval\s*\(str_rot13\s*\([\'\"]riny\([^\)]+\);[\'\"]\s*\)\s*\)\s*;*/i,
<rule>/(\$[^\s]+)\s*=\s*base64_decode\([^\)]+\)\s*;*/i<==>/(eval|gzinflate)\s*\(\s*\\1\s*\)\s*;*/i,
/(\$[^\s]+)\s*=\s*\$_(POST|GET|REQUEST|SESSION)\[.+?\]\s*;*/i<==>/fwrite\s*\([^,]+\s*,\s*(stripslashes\s*\()*?\\1\)*?\s*\)\s*;*/i,
/(\$[^\s]+)\s*=\s*fsockopen\s*\(/i<==>/fwrite\s*\(\s*\\1/i<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: function_common.php 206 2013-05-29 08:16:46Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
function showcssmenus($title, $menus = array(), $right = '', $replace = array()) {
if(empty($menus)) {
$s = '<div class="itemtitle">'.$right.'<h3>'.cplang($title, $replace).'</h3></div>';
} elseif(is_array($menus)) {
$s = '<div class="itemtitle">'.$right.'<h3>'.cplang($title, $replace).'</h3><ul class="tab1">';
foreach($menus as $k => $menu) {
if(is_array($menu[0])) {
$s .= '<li id="addjs'.$k.'" class="'.($menu[1] ? 'current' : 'hasdropmenu').'" onmouseover="dropmenu(this);"><a href="#"><span>'.cplang($menu[0]['menu']).'<em> </em></span></a><div id="addjs'.$k.'child" class="dropmenu" style="display:none;">';
if(is_array($menu[0]['submenu'])) {
foreach($menu[0]['submenu'] as $submenu) {
$s .= $submenu[1] ? '<a href="'.ADMINSCRIPT.'?action='.$submenu[1].'" class="'.($submenu[2] ? 'current' : '').'" onclick="'.$submenu[3].'">'.cplang($submenu[0]).'</a>' : '<a><b>'.cplang($submenu[0]).'</b></a>';
}
}
$s .= '</div></li>';
} else {
$s .= '<li'.($menu[2] ? ' class="current"' : '').'><a href="'.(!$menu[4] ? ADMINSCRIPT.'?action='.$menu[1] : $menu[1]).'"'.(!empty($menu[3]) ? ' target="_blank"' : '').'><span>'.cplang($menu[0]).'</span></a></li>';
}
}
$s .= '</ul></div>';
}
echo !empty($menus) ? '<div class="floattop" style="top:30px;">'.$s.'</div>' : $s;
echo '<div class="floattopempty"></div>';
}
function adminlog($action, $cum = 1, $type = 'total', $ver = '21') {
if($type == 'total') {
$action = $action.$ver;
}
return C::t('#discuz_security#discuz_security_adminlog')->update_by_action($action, $cum, $type);
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: common.inc.php 199 2013-05-29 02:46:11Z lucashen $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
//插件路径
define(DS_ROOT, DISCUZ_ROOT.'/source/plugin/discuz_security/');
//插件后台URL
$pmod = $_GET['pmod'];
$identifier = $_GET['identifier'];
define(PARAM_URL, "plugins&operation=config&do=$do&identifier=$identifier&pmod=$pmod");
define(DS_URL, ADMINSCRIPT."?action=".PARAM_URL);
//包含通用函数
require_once DS_ROOT.'./function/function_common.php';
//语言包数组
$csslang = $scriptlang['discuz_security'];
?><file_sep>
<?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_forum_hotreply_number extends discuz_table {
public function __construct() {
$this->_table = 'forum_hotreply_number';
$this->_pk = 'pid';
$this->_pre_cache_key = 'forum_hotreply_number_';
$this->_allowmem = memory('check');
$this->_cache_ttl = 86400;
parent::__construct();
}
public function fetch_all_by_pids($pids) {
return parent::fetch_all($pids);
//return DB::fetch_all('SELECT * FROM %t WHERE '.DB::field('pid', $pids), array($this->_table), 'pid');
}
public function fetch_all_by_tid_total($tid, $limit = 5) {
//加缓存
$cache_key = $this->_pre_cache_key.'fetch_all_by_tid_total_'.$tid.'_'.$limit;
if($this->_allowmem){
$result = memory('get',$cache_key);
if( $result !== false){
return $result;
}
}
$result = DB::fetch_all('SELECT * FROM %t WHERE tid=%d ORDER BY total DESC LIMIT %d', array($this->_table, $tid, $limit), 'pid');
memory('set',$cache_key,$result);
return $result;
}
public function fetch_by_pid($pid) {
return parent::fetch($pid);
//return DB::fetch_first('SELECT * FROM %t WHERE pid=%d', array($this->_table, $pid));
}
public function update_num($pid, $typeid) {
$typename = $typeid == 1 ? 'support' : 'against';
return DB::query('UPDATE %t SET '.$typename.'='.$typename.'+1, total=total+1 WHERE pid=%d', array($this->_table, $pid));
}
public function delete_by_tid($tid) {
if(empty($tid)) {
return false;
}
//删除缓存
$cache_key = $this->_pre_cache_key.'fetch_all_by_tid_total_'.$tid.'_10';
memory('rm',$cache_key);
return DB::query('DELETE FROM %t WHERE tid IN (%n)', array($this->_table, $tid));
}
public function delete_by_pid($pids) {
if(empty($pids)) {
return false;
}
return DB::query('DELETE FROM %t WHERE '.DB::field('pid', $pids), array($this->_table));
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: Restful.php 31472 2012-08-31 08:18:07Z zhengqingpeng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class Cloud_Service_Client_Restful_ext extends Cloud_Service_Client_Restful{
protected function _callMethod($method, $args, $isBatch = false) {
$this->errorCode = 0;
$this->errorMessage = '';
$url = $this->_url;
$avgDomain = explode('.', $method);
switch ($avgDomain[0]) {
case 'site':
$url = 'http://api.discuz.qq.com/site_cloud.php';
break;
case 'qqgroup':
$url = 'http://api.discuz.qq.com/site_qqgroup.php';
break;
case 'connect':
$url = 'http://api.discuz.qq.com/site_connect.php';
break;
case 'security':
$url = 'http://api.discuz.qq.com/site_security.php';
break;
default:
$url = $this->_url;
}
$params = array();
$params['sId'] = $this->_sId;
$params['method'] = $method;
$params['format'] = strtoupper($this->_format);
$params['sig'] = $this->_generateSig($params, $method, $args);
$params['ts'] = $this->_ts;
$postData = $this->_createPostData($params, $args);
if ($isBatch) {
$this->_batchParams[] = $postData;
return true;
} else {
$utilService = Cloud::loadClass('Service_Util');
$postString = $utilService->httpBuildQuery($postData, '', '&');
if($avgDomain[0] == 'security' && defined('ASYNCTASK') && ASYNCTASK == true) return self::_callAsync($url, $postString);
$result = $this->_postRequest($url, $postString);
if ($this->_debug) {
$this->_message('receive data ' . dhtmlspecialchars($result) . "\n\n");
}
return $this->_parseResponse($result);
}
}
static public function _callAsync($url, $postString) {
$key = "dz_asy_cron";
$aryapi = array($url, $postString);
$rds = memory_driver_redis::instance();
return $rds->lPush($key, $aryapi);
}
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: install.php 227 2013-06-25 06:56:23Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$sql = <<<EOF
DROP TABLE IF EXISTS cdb_plugin_discuz_security_banip;
CREATE TABLE cdb_plugin_discuz_security_banip (
`ip` char(15) NOT NULL DEFAULT '',
`count` smallint(5) unsigned NOT NULL DEFAULT '0',
`lastupdate` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ip`)
) TYPE=InnoDB;
DROP TABLE IF EXISTS `cdb_plugin_discuz_security_forum`;
CREATE TABLE `cdb_plugin_discuz_security_forum` (
`uid` mediumint(8) NOT NULL,
`username` varchar(15) NOT NULL,
`dateline` int(10) NOT NULL,
`lastip` char(15) NOT NULL,
KEY `id` (`uid`,`username`,`dateline`,`lastip`)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS `cdb_plugin_discuz_security_manager_action`;
CREATE TABLE `cdb_plugin_discuz_security_manager_action` (
`uid` mediumint(8) NOT NULL,
`username` varchar(15) NOT NULL,
`action` char(25) NOT NULL,
`dateline` int(10) NOT NULL,
`recdateline` int(10) NOT NULL,
KEY `uid` (`uid`)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS `cdb_plugin_discuz_security_adminlog`;
CREATE TABLE `cdb_plugin_discuz_security_adminlog` (
`key` char(10) NOT NULL,
`value` mediumint(8) unsigned NOT NULL DEFAULT '0',
`lastupdate` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`key`)
) ENGINE=InnoDB;
DROP TABLE IF EXISTS `cdb_plugin_discuz_security_cdd`;
CREATE TABLE `cdb_plugin_discuz_security_cdd` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`path` varchar(255) NOT NULL,
`scaned` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
EOF;
runquery($sql);
$finish = TRUE;
?>
<file_sep><?php
/*
* $Id: 2013/8/6 13:53:07 table_forum_threadaddviews_ext.php <NAME> $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_forum_threadaddviews_ext extends table_forum_threadaddviews {
public function __construct() {
$this->_table = 'forum_threadaddviews';
$this->_pk = 'tid';
$this->_pre_cache_key = 'addviews_';
$this->_cache_ttl = 0;
parent::__construct();
}
public function update_by_tid($tid) {
if($this->_allowmem) {
return memory('inc', $this->_pre_cache_key.$tid, '', $this->_cache_ttl);
}
return DB::query('UPDATE %t SET `addviews`=`addviews`+1 WHERE tid=%d', array($this->_table, $tid));
}
public function fetch_all_order_by_tid($start = 0, $limit = 0) {//
if($this->_allowmem) {
return array();
}
return DB::fetch_all('SELECT * FROM %t ORDER BY tid'.DB::limit($start, $limit), array($this->_table), $this->_pk);
}
public function fetch($tid) {
if($this->_allowmem) {
$ret = array('tid'=>$tid, 'addviews'=>0);
$n = memory('get', $this->_pre_cache_key.$tid);
$ret['addviews'] = (int)$n;
return $ret;
}
return parent::fetch($tid);
}
public function fetch_all($tids) {
if($this->_allowmem) {
$ret = array();
if(is_array($tids) || array($tids)) {
$_val = array();
foreach($tids as $v) {
$_val[] = $this->_pre_cache_key.$v;
}
$n = memory('get', $_val);
if(is_array($n)) {
foreach($n as $k=>$v) {
$ret[str_replace($this->_pre_cache_key, '', $k)] = array('addviews' => $v);
}
}
}
return $ret;
}
return parent::fetch_all($tids);
}
public function insert($data, $return_insert_id = false, $replace = false) {
if($this->_allowmem) {
return memory('set', $this->_pre_cache_key.$data['tid'], 1, $this->_cache_ttl);
}
return parent::insert($data, $return_insert_id, $replace);
}
public function update($val, $data) {
if($this->_allowmem) {
return memory('set', $this->_pre_cache_key.$val, $data['addviews'], $this->_cache_ttl);
}
return parent::update($val, $data);
}
public function delete($val) {
if($this->_allowmem) {
if(is_array($val) || array($val)) {
$_val = array();
foreach($val as $k => $v) {
$_val[$k] = $this->_pre_cache_key.$v;
}
}
return memory('rm', $_val);
}
return parent::delete($val);
}
}
?>
<file_sep><?php
$charset = strtolower(CHARSET);
if($_G['config']['output']['language'] == 'zh_cn'){
define(HSK_LANG, "sc_{$charset}");
}else{
define(HSK_LANG, "tc_{$charset}");
}
include DISCUZ_ROOT.'./source/admincp/hsk/language/'.HSK_LANG.'.lang.php';
$GLOBALS['admincp_actions_normal'][] = 'hsk';
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: content_seccode.inc.php 165 2013-05-14 02:54:54Z vinsonbwang $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
global $_G;
if(submitcheck('seccode_submit', 0, 1)) {
$url = 'forum.php?mod=viewthread&tid='.$_GET['url_tid'];
C::t('#discuz_security#discuz_security_manager_action')->useractionlog($_G['uid'], '', TIMESTAMP, TIMESTAMP);
showmessage(lang('plugin/discuz_security', 'content_success'), $url);
} else {
include template('discuz_security:content_seccode');
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: content_global.inc.php 209 2013-05-29 09:31:39Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
$limit = 20;
$page = dintval($_GET['page']) ? dintval($_GET['page']) : 1;
$orderby = 'dateline';
$mes = $csslang['content_gtips'];//技巧提示内容
showtips('', $id = 'tips', $display = TRUE, $mes);
if(submitcheck('content_delete') && !empty($_POST['d_content_delete'])) {
if(C::t('#discuz_security#discuz_security_forum')->delete_by_uid($_POST['d_content_delete'])) {
adminlog('PTMZT', count($_POST['d_content_delete']));
cpmsg($csslang['content_delete_success'], $msgbaseurl.$pageadd, 'succeed');
}
cpmsg($csslang['content_delete_failed'], $msgbaseurl.$pageadd, 'error');
}
showformheader(PARAM_URL.'&cp=content_global','submit');
showtableheader();
showtablerow('class="header"', array('class="td23"','class="td23"','class="td23"','class="td24"', ''), array(
'',
$csslang['content_uid'],
$csslang['content_username'],
$csslang['content_dateline'],
$csslang['content_ip'],
));
$content_list = C::t('#discuz_security#discuz_security_forum')->fetch(($_GET['page'] - 1) * $limit, $limit, $orderby);
foreach($content_list as $content_global) {
$content_global['dateline'] = dgmdate($content_global['dateline'], 'Y-n-j H:i');
showtablerow('', array('class="td23"','class="td23"','class="td24"', ''), array(
"<input class=\"checkbox\" type=\"checkbox\" name=\"d_content_delete[]\" value=\"$content_global[uid]\">",
$content_global['uid'],
$content_global['username'],
$content_global['dateline'],
$content_global['lastip'],
));
}
$multipage = multi(C::t('#discuz_security#discuz_security_forum')->count(), $limit, $page, DS_URL.'&cp=content_global');
showsubmit('', '', '',
'<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(\'prefix\', this.form, \'delete\')" /><label for="chkall">'.$csslang['content_selectall'].'</label> '.
'<input type="submit" class="btn" name="content_delete" value="'.$csslang['content_delete'].'" />');
showtablefooter();
showformfooter();
echo $multipage;
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: sys_checkdir.php 205 2013-05-29 08:16:16Z qingrongfu $
*/
adminlog('CKDIR');
switch (check_dir()) {
case 0:
$msg = $csslang['sys_dir_io_error'];
break;
case 1:
$msg = $csslang['sys_dir_can_read'];
break;
case 2:
$msg = $csslang['sys_dir_cant_read'];
break;
default:
$msg = '';
}
cpmsg($msg);
?><file_sep>ENGLISH Language Pack
for Discuz! X2.5 (c) 2001-2099 Comsenz Inc.
MultiLingual version by <NAME>, codersclub.org
Translated by <NAME>, codersclub.org
Code = 'en';
English title = 'English';
UTF8 title = 'English';
18x12 Icon = 'en.gif';
Direction = 'ltr';
Encoding = 'UTF-8';
<file_sep><?php
/*
* $Id: 2013/9/12 11:18:12 table_common_session_ext.php <NAME> $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_common_session_ext extends table_common_session
{
public $rds = null;
public function __construct() {
global $_G;
$this->rds = new Redis();
$this->rds->pconnect($_G['config']['memory']['redis']['server'], $_G['config']['memory']['redis']['port']);
$this->_table = 'common_session';
$this->_pk = 'sid';
parent::__construct();
}
public function _rdskey($sid, $uid = 0, $fid = 0, $invisible = 0, $ip = '') {
if(empty($sid)) return '';
$uid = $uid == 0 ? '' : $uid;
return "sR:s_$sid:u_$uid:f_$fid:i_$invisible:p_$ip";
}
public function _rdskey_gnr($var) {
return $this->_rdskey($var['sid'], $var['uid'], $var['fid'], $var['invisible'], "{$var['ip1']}.{$var['ip2']}.{$var['ip3']}.{$var['ip4']}");
}
public function _rdscput($key, $value, $sec = 600) {
$value = serialize($value);
return $this->rds->setex($key, $sec, $value);
}
public function _rdscget($key) {
$rt = $this->rds->get($key);
$rt = unserialize($rt);
if(empty($rt)) return false;
return $rt;
}
public function insert($data, $return_insert_id = false, $replace = false, $silent = false) {
$key = $this->_rdskey_gnr($data);
return $this->rds->hMset($key, $data);
}
public function fetch($sid, $ip = false, $uid = false) {
if(empty($sid)) {
return array();
}
$key = $this->rds->keys("sR:s_$sid*");
if(empty($key)) return array();
$session = $this->rds->hGetAll($key[0]);
if($session && $ip !== false && $ip != "{$session['ip1']}.{$session['ip2']}.{$session['ip3']}.{$session['ip4']}") {
$session = array();
}
if($session && $uid !== false && $uid != $session['uid']) {
$session = array();
}
return $session;
}
public function fetch_member($ismember = 0, $invisible = 0, $start = 0, $limit = 0) {
$keyu = $keyi = '';
$return = array();//按lastactivity来
if($ismember === 1) {
$keyu = 'u_[1-9]*:';
} elseif($ismember === 2) {
$keyu = 'u_:';
}
if($invisible === 1) {
$keyi = 'i_1:';
} elseif($invisible === 2) {
$keyi = 'i_0:';
}
$keyc = "sRc:fm:$ismember:$invisible:$start:$limit";
if(($return = $this->_rdscget($keyc)) !== false) return $return;
$key = $this->rds->keys("sR:*$keyu*$keyi*");
if(empty($key) || !is_array($key)) return array();
$key = $this->limit($key, $start, $limit);
foreach($key as $v) {
$return[] = $this->rds->hGetAll($v);
}
$this->_rdscput($keyc, $return);
return $return;
}
public function count_invisible($type = 1) {
return (int)$this->rds->hGet('sR:status', "c_i_t$type");
}
public function count($type = 0) {
return (int)$this->rds->hGet('sR:status', "c_t$type");
}
public function delete_by_session($session, $onlinehold, $guestspan) {//
if(!empty($session) && is_array($session)) {
//$onlinehold = time() - $onlinehold;
//$guestspan = time() - $guestspan;
$key = $this->rds->keys("sR:s_{$session['sid']}*");
!empty($key) && $this->rds->delete($key);
//$key1 = $this->rds->keys("<KEY>session['ip1']}.{$session['ip2']}.{$session['ip3']}.{$session['ip4']}");
//if(!empty($key1) && is_array($key1)) {
// foreach($key1 as $k=>&$v) {
// if($this->rds->hget($v, 'lastactivity') <= $guestspan) unset($key1[$k]);
// }
// !empty($key1) && $this->rds->delete($key1);
//
//}
if($session['uid'] != 0) $key2 = $this->rds->keys("sR:*u_{$session['uid']}*");
!empty($key2) && $this->rds->delete($key2);
}
}
public function fetch_by_uid($uid) {
if(empty($uid)) return false;
$key = $this->rds->keys("<KEY>
if(empty($key)) return false;
return $this->rds->hGetAll($key[0]);
}
public function limit($array, $start = 0, $limit = 0) {
$return = array();
if(empty($array) || !is_array($array)) return $return;
return $limit == 0 && $start == 0 ? $array : ($limit == 0 ? array_slice($array, 0, $start) : array_slice($array, $start, $limit));
}
public function fetch_all_by_uid($uids, $start = 0, $limit = 0) {
$data = $keysa = array();
$uidsc = md5(implode(':', $uids));
$keyc = "sRc:fabu:$uidsc:$start:$limit";
if(($data = $this->_rdscget($keyc)) !== false) return $data;
$keys = $this->rds->keys("sR:s_*u_[1-9]*");
if(empty($keys) || !is_array($keys)) return $data;
foreach($keys as $v) {
preg_match('/sR.+:u_(\d+):/', $v, $match);
$uid = $match[1];
if(in_array($uid, $uids)) {
$keysa[] = $v;
}
}
$keysa = $this->limit($keysa, $start, $limit);
foreach($keysa as $v) {
$data[] = $this->rds->hGetAll($v);
}
$this->_rdscput($keyc, $data);
return $data;
}
public function update_by_ipban($ip1, $ip2, $ip3, $ip4) {
$ip1 = intval($ip1);
$ip2 = intval($ip2);
$ip3 = intval($ip3);
$ip4 = intval($ip4);
$keys = $this->rds->keys("sR:s_*:p_*-1*");
if(!empty($keys) && is_array($keys)) {
foreach($keys as $v) {
$this->rds->hSet($v, 'groupid', 6);
}
}
$keys = $this->rds->keys("sR:s_*:p_$ip1.$ip2.$ip3.$ip4");
if(!empty($keys) && is_array($keys)) {
foreach($keys as $v) {
$this->rds->hSet($v, 'groupid', 6);
}
}
return true;
}
public function update_max_rows($max_rows) {
return true;
}
public function clear() {
return $this->rds->flushAll();
}
public function count_by_fid($fid) {
$rt = unserialize($this->rds->hGet('sR:status', "c_b_f"));
return (int)$rt[$fid];
}
public function fetch_all_by_fid($fid, $limit = 12) {
$return = array();
$keys = $this->rds->keys("sR:s_*u_[1-9]*:f_$fid:i_0*");
if(empty($keys) || !is_array($keys)) return array();
$keys = $this->limit($keys, 0, $limit);
foreach($keys as $v) {
$return[] = $this->rds->hGetAll($v);
}
return $return;
}
public function update_by_uid($uid, $data){
$oldkey = $this->rds->keys("sR:*u_$uid*");
if(empty($oldkey) || !is_array($oldkey)) return 0;
$newkey = $this->_rdskey_gnr($data);
if($oldkey[0] != $newkey) $this->rds->rename($oldkey[0], $newkey);
return $this->rds->hMset($newkey, $data);
}
public function update($var, $data) {//目前只考虑var为sid的情况
$oldkey = $this->rds->keys("sR:s_$var*");
if(empty($oldkey) || !is_array($oldkey)) return 0;
$newkey = $this->_rdskey_gnr($data);
if($oldkey[0] != $newkey) $this->rds->rename($oldkey[0], $newkey);
return $this->rds->hMset($newkey, $data);
}
public function count_by_ip($ip) {
if(empty($ip)) return false;
$key = $this->rds->keys("<KEY>
if(empty($key)) return 0;
return count($key);
}
public function fetch_all_by_ip($ip, $start = 0, $limit = 0) {
if(empty($ip)) return false;
$ip = explode('.', $ip);
$key = $this->rds->keys("sR:*:p_{$ip[0]}.{$ip[1]}.{$ip[2]}*");
if(empty($key)) return array();
$return = array();
$key = $this->limit($key, $start, $limit);
foreach($key as $v) {
$return[] = $this->rds->hGetAll($v);
}
return $return;
}
}
?>
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_home_follow_feed.php 28364 2012-02-28 07:31:23Z zhengqingpeng $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_home_follow_feed extends discuz_table
{
private $_ids = array();
private $_cids = array();
private $_tids = array();
private $_archiver_table = 'home_follow_feed_archiver';
public function __construct() {
$this->_table = 'home_follow_feed';
$this->_pk = 'feedid';
parent::__construct();
}
/**
*
* 根据用户ID获取指定用户的动态信息
* @param mixed $uids:单个uid或者uid数组或者不限制uid
* @param integer $start: 从$start开始取值
* @param integer $limit: 获取的记录数
* @return 返回关注的内容列表同时产生cids列表
*/
public function fetch_all_by_uid($uids = 0, $archiver = false, $start = 0, $limit = 0) {
//主页的首页缓存
if($this->_allowmem && $start == 0 && !empty($uids) && count($uids) == 1 ){
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$uids[0].'_'.intval($archiver);
$result = memory('get',$cache_key);
if($result !== false){
return $result;
}
}
$data = array();
$parameter = array($archiver ? $this->_archiver_table : $this->_table);
$wherearr = array();
if(!empty($uids)) {
$uids = dintval($uids, true);
$wherearr[] = is_array($uids) && $uids ? 'uid IN(%n)' : 'uid=%d';
$parameter[] = $uids;
}
$wheresql = !empty($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';
$query = DB::query("SELECT * FROM %t $wheresql ORDER BY dateline DESC ".DB::limit($start, $limit), $parameter);
while($row = DB::fetch($query)) {
$data[$row['feedid']] = $row;
$this->_tids[$row['tid']] = $row['tid'];
}
if($this->_allowmem && $start == 0 && !empty($uids) && count($uids) == 1 ){
memory('set',$cache_key,$data);
}
return $data;
}
public function fetch_all_by_dateline($dateline, $glue = '>=') {
$glue = helper_util::check_glue($glue);
return DB::fetch_all("SELECT * FROM %t WHERE dateline{$glue}%d ORDER BY dateline", array($this->_table, $dateline), $this->_pk);
}
public function fetch_by_feedid($feedid, $archiver = false) {
return DB::fetch_first("SELECT * FROM %t WHERE feedid=%d", array($archiver ? $this->_archiver_table : $this->_table, $feedid));
}
public function count_by_uid_tid($uid, $tid, $archiver = false) {
return DB::result_first('SELECT COUNT(*) FROM %t WHERE uid=%d AND tid=%d', array($archiver ? $this->_archiver_table : $this->_table, $uid, $tid));
}
/**
*
* 获取关注用户的Feed总数
* @param array $uids: uid数组
* @param integer $dateline: 从什么时间开始
* @param integer $archiver: 是否是存档表
* @return 返回给定条件的Feed总数
*/
public function count_by_uid_dateline($uids = array(), $dateline = 0, $archiver = 0) {
$count = 0;
$parameter = array($archiver ? $this->_archiver_table : $this->_table);
$wherearr = array();
if(!empty($uids)) {
$uids = dintval($uids, true);
$wherearr[] = is_array($uids) && $uids ? 'uid IN(%n)' : 'uid=%d';
$parameter[] = $uids;
}
if($dateline) {
$wherearr[] = "dateline>%d";
$parameter[] = $dateline;
}
$wheresql = !empty($wherearr) && is_array($wherearr) ? ' WHERE '.implode(' AND ', $wherearr) : '';
$count = DB::result_first("SELECT COUNT(*) FROM %t $wheresql", $parameter);
return $count;
}
public function insert($data, $return_insert_id = false, $replace = false, $silent = false){
//删除缓存
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$data['uid'].'_0';
memory('rm',$cache_key);
parent::insert($data, $return_insert_id, $replace, $silent);
}
public function insert_archiver($data) {
if(!empty($data) && is_array($data)) {
//删除缓存
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$data['uid'].'_1';
memory('rm',$cache_key);
return DB::insert($this->_archiver_table, $data, false, true);
}
return 0;
}
public function delete_by_feedid($feedid, $archiver = false) {
$feedid = dintval($feedid, true);
if($feedid) {
//删除缓存
$feed = $this->fetch($feedid);
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$feed['uid'].'_'.intval($archiver);
memory('rm',$cache_key);
return DB::delete($archiver ? $this->_archiver_table : $this->_table, DB::field('feedid', $feedid));
}
return 0;
}
public function delete_by_uid($uids) {
$uids = dintval($uids, true);
$delnum = 0;
if($uids) {
//删除缓存
foreach ($uids as $uid){
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$uid.'_0';
memory('rm',$cache_key);
$cache_key = $this->_pre_cache_key.'fetch_all_by_uid_'.$uid.'_1';
memory('rm',$cache_key);
}
$delnum = DB::delete($this->_table, DB::field('uid', $uids));
$delnum += DB::delete($this->_archiver_table, DB::field('uid', $uids));
}
return $delnum;
}
public function get_ids() {
return $this->_ids;
}
public function get_tids() {
return $this->_tids;
}
public function get_cids() {
return $this->_cids;
}
}
?><file_sep>#DISCUZX 扩展框架DXEXTEND
http://www.discuz.net/thread-3334048-1-1.html
#SESSION机制优化扩展
http://www.discuz.net/thread-3457864-1-1.html
#InnoDB数据库补丁
http://www.discuz.net/thread-3330856-1-1.html
#discuz-redis 扩展 轻松快速分页 避免分页瓶颈
http://www.discuz.net/thread-3340731-1-1.html
#云存储通用接口
http://www.discuz.net/thread-3399569-1-1.html
#帖子点击数缓存即时更新
http://www.discuz.net/thread-3409742-1-1.html
#云上报/计划任务异步机制方案
http://www.discuz.net/thread-3369042-1-1.html
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_banip.php 136 2013-05-13 09:13:53Z lucashen $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_discuz_security_adminlog extends discuz_table {
public function __construct() {
$this->_table = 'plugin_discuz_security_adminlog';
$this->_pk = 'key';
parent::__construct();
}
public function update_by_action($action, $cum, $type) {
$cum = intval($cum);
$data = array(
'key' => $action,
'value' => $cum,
'lastupdate' => TIMESTAMP,
);
if(!DB::insert($this->_table, daddslashes($data), false, false, true)) {
if($type == 'total') {
return DB::query("UPDATE ".DB::table($this->_table)." SET `value` = `value` + $cum, lastupdate = '".TIMESTAMP."' WHERE `key` = '".daddslashes($action)."'");
} elseif ($type == 'radio') {
return DB::query("UPDATE ".DB::table($this->_table)." SET `value` = '$cum', lastupdate = '".TIMESTAMP."' WHERE `key` = '".daddslashes($action)."'");
}
}
return true;
}
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: sys_plugins.php 205 2013-05-29 08:16:16Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
adminlog('PUCHK');
check_plugins();
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: config_global_default.php 34020 2013-09-22 05:48:16Z nemohou $
*/
$_config = array();
// ---------------------------- CONFIG DB ----------------------------- //
// ---------------------------- 数据库相关设置---------------------------- //
/**
* 数据库主服务器设置, 支持多组服务器设置, 当设置多组服务器时, 则会根据分布式策略使用某个服务器
* @example
* $_config['db']['1']['dbhost'] = 'localhost'; // 服务器地址
* $_config['db']['1']['dbuser'] = 'root'; // 用户
* $_config['db']['1']['dbpw'] = 'root';// 密码
* $_config['db']['1']['dbcharset'] = 'gbk';// 字符集
* $_config['db']['1']['pconnect'] = '0';// 是否持续连接
* $_config['db']['1']['dbname'] = 'x1';// 数据库
* $_config['db']['1']['tablepre'] = 'pre_';// 表名前缀
*
* $_config['db']['2']['dbhost'] = 'localhost';
* ...
*
*/
$_config['db'][1]['dbhost'] = 'localhost';
$_config['db'][1]['dbuser'] = 'root';
$_config['db'][1]['dbpw'] = 'root';
$_config['db'][1]['dbcharset'] = 'utf8';
$_config['db'][1]['pconnect'] = 0;
$_config['db'][1]['dbname'] = 'ultrax';
$_config['db'][1]['tablepre'] = 'pre_';
/**
* 数据库从服务器设置( slave, 只读 ), 支持多组服务器设置, 当设置多组服务器时, 系统根据每次随机使用
* @example
* $_config['db']['1']['slave']['1']['dbhost'] = 'localhost';
* $_config['db']['1']['slave']['1']['dbuser'] = 'root';
* $_config['db']['1']['slave']['1']['dbpw'] = 'root';
* $_config['db']['1']['slave']['1']['dbcharset'] = 'gbk';
* $_config['db']['1']['slave']['1']['pconnect'] = '0';
* $_config['db']['1']['slave']['1']['dbname'] = 'x1';
* $_config['db']['1']['slave']['1']['tablepre'] = 'pre_';
* $_config['db']['1']['slave']['1']['weight'] = '0'; //权重:数据越大权重越高
*
* $_config['db']['1']['slave']['2']['dbhost'] = 'localhost';
* ...
*
*/
$_config['db']['1']['slave'] = array();
//启用从服务器的开关
$_config['db']['slave'] = false;
/**
* 数据库 分布部署策略设置
*
* @example 将 common_member 部署到第二服务器, common_session 部署在第三服务器, 则设置为
* $_config['db']['map']['common_member'] = 2;
* $_config['db']['map']['common_session'] = 3;
*
* 对于没有明确声明服务器的表, 则一律默认部署在第一服务器上
*
*/
$_config['db']['map'] = array();
/**
* 数据库 公共设置, 此类设置通常对针对每个部署的服务器
*/
$_config['db']['common'] = array();
/**
* 禁用从数据库的数据表, 表名字之间使用逗号分割
*
* @example common_session, common_member 这两个表仅从主服务器读写, 不使用从服务器
* $_config['db']['common']['slave_except_table'] = 'common_session, common_member';
*
*/
$_config['db']['common']['slave_except_table'] = '';
/**
* 内存服务器优化设置
* 以下设置需要PHP扩展组件支持,其中 memcache 优先于其他设置,
* 当 memcache 无法启用时,会自动开启另外的两种优化模式
*/
//内存变量前缀, 可更改,避免同服务器中的程序引用错乱
$_config['memory']['prefix'] = 'discuz_';
/* reids设置, 需要PHP扩展组件支持, timeout参数的作用没有查证 */
$_config['memory']['redis']['server'] = '';
$_config['memory']['redis']['port'] = 6379;
$_config['memory']['redis']['pconnect'] = 1;
$_config['memory']['redis']['timeout'] = 0;
$_config['memory']['redis']['requirepass'] = '';
/**
* 是否使用 Redis::SERIALIZER_IGBINARY选项,需要igbinary支持,windows下测试时请关闭,否则会出>现错误Reading from client: Connection reset by peer
* 支持以下选项,默认使用PHP的serializer
* [重要] 该选项已经取代原来的 $_config['memory']['redis']['igbinary'] 选项
* Redis::SERIALIZER_IGBINARY =2
* Redis::SERIALIZER_PHP =1
* Redis::SERIALIZER_NONE =0 //则不使用serialize,即无法保存array
*/
$_config['memory']['redis']['serializer'] = 1;
$_config['memory']['memcache']['server'] = ''; // memcache 服务器地址
$_config['memory']['memcache']['port'] = 11211; // memcache 服务器端口
$_config['memory']['memcache']['pconnect'] = 1; // memcache 是否长久连接
$_config['memory']['memcache']['timeout'] = 1; // memcache 服务器连接超时
$_config['memory']['apc'] = 1; // 启动对 apc 的支持
$_config['memory']['xcache'] = 1; // 启动对 xcache 的支持
$_config['memory']['eaccelerator'] = 1; // 启动对 eaccelerator 的支持
$_config['memory']['wincache'] = 1; // 启动对 wincache 的支持
// 服务器相关设置
$_config['server']['id'] = 1; // 服务器编号,多webserver的时候,用于标识当前服务器的ID
// 附件下载相关
//
// 本地文件读取模式; 模式2为最节省内存方式,但不支持多线程下载
// 1=fread 2=readfile 3=fpassthru 4=fpassthru+multiple
$_config['download']['readmod'] = 2;
// 是否启用 X-Sendfile 功能(需要服务器支持)0=close 1=nginx 2=lighttpd 3=apache
$_config['download']['xsendfile']['type'] = 0;
// 启用 nginx X-sendfile 时,论坛附件目录的虚拟映射路径,请使用 / 结尾
$_config['download']['xsendfile']['dir'] = '/down/';
// 页面输出设置
$_config['output']['charset'] = 'utf-8'; // 页面字符集
$_config['output']['forceheader'] = 1; // 强制输出页面字符集,用于避免某些环境乱码
$_config['output']['gzip'] = 0; // 是否采用 Gzip 压缩输出
$_config['output']['tplrefresh'] = 1; // 模板自动刷新开关 0=关闭, 1=打开
$_config['output']['language'] = 'zh_cn'; // 页面语言 zh_cn/zh_tw
$_config['output']['staticurl'] = 'static/'; // 站点静态文件路径,“/”结尾
$_config['output']['ajaxvalidate'] = 0; // 是否严格验证 Ajax 页面的真实性 0=关闭,1=打开
$_config['output']['iecompatible'] = 0; // 页面 IE 兼容模式
// COOKIE 设置
$_config['cookie']['cookiepre'] = 'discuz_'; // COOKIE前缀
$_config['cookie']['cookiedomain'] = ''; // COOKIE作用域
$_config['cookie']['cookiepath'] = '/'; // COOKIE作用路径
// 站点安全设置
$_config['security']['authkey'] = 'asdfasfas'; // 站点加密密钥
$_config['security']['urlxssdefend'] = true; // 自身 URL XSS 防御
$_config['security']['attackevasive'] = 0; // CC 攻击防御 1|2|4|8
$_config['security']['querysafe']['status'] = 1; // 是否开启SQL安全检测,可自动预防SQL注入攻击
$_config['security']['querysafe']['dfunction'] = array('load_file','hex','substring','if','ord','char');
$_config['security']['querysafe']['daction'] = array('@','intooutfile','intodumpfile','unionselect','(select', 'unionall', 'uniondistinct');
$_config['security']['querysafe']['dnote'] = array('/*','*/','#','--','"');
$_config['security']['querysafe']['dlikehex'] = 1;
$_config['security']['querysafe']['afullnote'] = 0;
$_config['admincp']['founder'] = '1'; // 站点创始人:拥有站点管理后台的最高权限,每个站点可以设置 1名或多名创始人
// 可以使用uid,也可以使用用户名;多个创始人之间请使用逗号“,”分开;
$_config['admincp']['forcesecques'] = 0; // 管理人员必须设置安全提问才能进入系统设置 0=否, 1=是[安全]
$_config['admincp']['checkip'] = 1; // 后台管理操作是否验证管理员的 IP, 1=是[安全], 0=否。仅在管理员无法登陆后台时设置 0。
$_config['admincp']['runquery'] = 0; // 是否允许后台运行 SQL 语句 1=是 0=否[安全]
$_config['admincp']['dbimport'] = 1; // 是否允许后台恢复论坛数据 1=是 0=否[安全]
/**
* 系统远程调用功能模块
*/
// 远程调用: 总开关 0=关 1=开
$_config['remote']['on'] = 0;
// 远程调用: 程序目录名. 出于安全考虑,您可以更改这个目录名, 修改完毕, 请手工修改程序的实际目录
$_config['remote']['dir'] = 'remote';
// 远程调用: 通信密钥. 用于客户端和本服务端的通信加密. 长度不少于 32 位
// 默认值是 $_config['security']['authkey'] 的 md5, 您也可以手工指定
$_config['remote']['appkey'] = md5($_config['security']['authkey']);
// 远程调用: 开启外部 cron 任务. 系统内部不再执行cron, cron任务由外部程序激活
$_config['remote']['cron'] = 0;
// $_GET|$_POST的兼容处理,0为关闭,1为开启;开启后即可使用$_G['gp_xx'](xx为变量名,$_GET和$_POST集合的所有变量名),值为已经addslashes()处理过
$_config['input']['compatible'] = 1;
//开启后台插件开发模块 用来开发插件
$_config['plugindeveloper'] = 1;
//discuz-redis 扩展 轻松快速分页 避免分页瓶颈
$_config['extend']['discuz_redis']['on'] = 0;//1为启动,0为停止
$_config['discuz_redis']['server'] = '127.0.0.1';
$_config['discuz_redis']['port'] = 6379;
$_config['discuz_redis']['pconnect'] = 1;
$_config['discuz_redis']['auth'] = '';
$_config['discuz_redis']['db'] = '0';
//云存储通用接口
$_config['extend']['storage']['curstorage'] = '';//为空则不启用 支持upyun,aliyun,qiniu 三种云存储
$_config['extend']['storage']['upyun']['bucket'] = 'dztest';
$_config['extend']['storage']['upyun']['username'] = 'dzuser';
$_config['extend']['storage']['upyun']['password'] = '<PASSWORD>';
$_config['extend']['storage']['upyun']['attachurl'] = 'http://dztest.b0.upaiyun.com';
$_config['extend']['storage']['aliyun']['access_id'] = '';
$_config['extend']['storage']['aliyun']['access_key'] = '';
$_config['extend']['storage']['aliyun']['access_host'] = NULL;
$_config['extend']['storage']['aliyun']['bucket'] = 'discuzbucket';
$_config['extend']['storage']['aliyun']['attachurl'] = 'http://discuzbucket.oss.aliyuncs.com';
$_config['extend']['storage']['qiniu']['accesskey'] = '';
$_config['extend']['storage']['qiniu']['secretkey'] = '';
$_config['extend']['storage']['qiniu']['attachurl'] = 'http://discuztest.qiniudn.com';
$_config['extend']['storage']['qiniu']['bucket'] = 'discuztest';
//end
//云上报/计划任务异步机制方案
$_config['extend']['asynctask']['on'] = 0;
$_config['remote']['on'] = '1';
$_config['remote']['cron'] = '1';
//-----------------------------------------------------------------------
// Multi-Lingual support by <NAME>
//-----------------------------------------------------------------------
// "icon" - flag image file name;
// "name" - language name in NATIONAL language;
// "title" - language name in ENGLISH language;
// "dir" - text direction:
// 'ltr' (Left To Right)
// 'rtl' (Right To Left), i.e for Arabic, Hebrew, Urdu, etc.
//-----------------------------------------------------------------------
//
// Enabled Language List:
$_config['languages'] = array(
'ar' => array('icon'=>'ar.gif', 'name'=>'العربية', 'title'=>'Arabic', 'dir'=>'rtl', 'code'=>'ar-AE'),
'de' => array('icon'=>'de.gif', 'name'=>'Deutsch', 'title'=>'German', 'dir'=>'ltr', 'code'=>'de-DE'),
'en' => array('icon'=>'en.gif', 'name'=>'English', 'title'=>'English', 'dir'=>'ltr', 'code'=>'en-GB'),
'es' => array('icon'=>'es.gif', 'name'=>'Español', 'title'=>'Spanish', 'dir'=>'ltr', 'code'=>'es-ES'),
'fr' => array('icon'=>'fr.gif', 'name'=>'Français', 'title'=>'French', 'dir'=>'ltr', 'code'=>'fr-FR'),
'kr' => array('icon'=>'kr.gif', 'name'=>'한국어', 'title'=>'Korean', 'dir'=>'ltr', 'code'=>'ko-KO'),
'pl' => array('icon'=>'pl.gif', 'name'=>'Polski', 'title'=>'Polish', 'dir'=>'ltr', 'code'=>'pl-PL'),
'ru' => array('icon'=>'ru.gif', 'name'=>'Русский', 'title'=>'Russian', 'dir'=>'ltr', 'code'=>'ru-RU'),
'zh-cn' => array('icon'=>'zh.gif', 'name'=>'简体中文', 'title'=>'Simplified Chinese', 'dir'=>'ltr', 'code'=>'zh-CN'),
'tc' => array('icon'=>'tw.gif', 'name'=>'繁體中文', 'title'=>'Traditional Chinese', 'dir'=>'ltr', 'code'=>'zh-TW'),
'th' => array('icon'=>'th.gif', 'name'=>'ภาษาไทย', 'title'=>'Thai', 'dir'=>'ltr', 'code'=>'th-TH'),
'tr' => array('icon'=>'tr.gif', 'name'=>'Türkçe', 'title'=>'Turkish', 'dir'=>'ltr', 'code'=>'tr-TR'),
'vn' => array('icon'=>'vn.gif', 'name'=>'Tiếng Việt', 'title'=>'Vietnamese', 'dir'=>'ltr', 'code'=>'vi-VN'),
);
$_config['detect_language'] = true; // Auto-detect user language: true|false
$_config['enable_multilingual'] = true; // Enable/Disable multi-lingual feature
?>
<file_sep><?php
//cronname:sys_limit_cron
//week:
//day:
//hour:
//minute:0,5,10,15,20,25,30,35,40,45,50,55
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
loadcache('plugin');
$hasRedis = extension_loaded('redis');
if($_G['cache']['plugin']['discuz_security']['islimit'] && $hasRedis && $_G['cache']['plugin']['discuz_security']['limitRedisHost']
&& $_G['cache']['plugin']['discuz_security']['limitRedisPort']) {
//连接Redis
$r = new Redis();
$r->pconnect($_G['cache']['plugin']['discuz_security']['limitRedisHost'], $_G['cache']['plugin']['discuz_security']['limitRedisPort']);
if(!empty($_G['cache']['plugin']['discuz_security']['limitRedisPass'])) {
$r->auth($_G['cache']['plugin']['discuz_security']['limitRedisPass']);
}
$banIps = $r->hGetAll('banTime');
if(!empty($banIps)) {
foreach ($banIps as $k => $v) {
if(($k[0] == 'f')&&!$r->hExists('banTime', 'last.'.substr($k,6))) {
$ip = substr($k, 6);
$now = time();
$firstTime = $v;
if(($now - $firstTime) >= 3600) {
$r->lPush('unBanIpLog', $ip.'::'.date(lang('plugin/discuz_security', 'sys_limit_dateformat'),$firstTime).'::'.date(lang('plugin/discuz_security', 'sys_limit_dateformat'),$lastTime));
$r->zDelete('banIP', $ip);
$r->hDel('banTime', 'first.'.$ip);
$r->hDel('banTime', 'last.'.$ip);
$r->sRem('ip.black', $ip);
}
}
if($k[0] == 'l') {
$now = time();
$lastTime = $v;
$ip = substr($k, 5);
$firstTime = $r->hGet('banTime', 'first.'.$ip);
if(($now - $lastTime) >= 7200) {
$r->lPush('unBanIpLog', $ip.'::'.date(lang('plugin/discuz_security', 'sys_limit_dateformat'),$firstTime).'::'.date(lang('plugin/discuz_security', 'sys_limit_dateformat'),$lastTime));
$r->zDelete('banIP', $ip);
$r->hDel('banTime', 'first.'.$ip);
$r->hDel('banTime', 'last.'.$ip);
$r->sRem('ip.black', $ip);
}
}
}
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: lang_avatar.php 27449 2012-02-01 05:32:35Z zhangguosheng $
* Translated to Thai by jaideejung007
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$lang = array
(
'avatar_name' => 'เปลี่ยนรูปประจำตัว',
'avatar_desc' => 'กิจกรรมนี้สำหรับสมาชิกที่ยังไม่ได้อัพโหลดรูปประจำตัว ทำการอัพโหลดรูปประจำตัว เข้าร่วมกิจกรรมนี้ แล้วคุณจะได้รับรางวัล สำหรับสมาชิกที่อัพโหลดรูปประจำตัวไว้ก่อนแล้ว สามารถเข้าร่วมและรับรางวัลได้ทันที',
'avatar_view' => '<strong>คำแนะนำในการเข้าร่วมกิจกรรมนี้: </strong>
<ul>
<li>1. <a href="home.php?mod=spacecp&ac=avatar" target="_blank">เปิดหน้าต่างใหม่เพื่ออัพโหลดรูปประจำตัว</a></li>
<li>2. อัพโหลดรูปประจำตัวของคุณ</li>
</ul>',
);
<file_sep><?php
/*
* $Id: 2013/10/8 15:02:06 discuz_database_ext.php <NAME> $
*/
class discuz_database_ext extends discuz_database {
public static $_ext_table = array('common_member_grouppm', 'forum_threaddisablepos', 'common_process', 'common_visit', 'common_session', 'forum_postposition');
public static function count_all($table) {
$linkId = 1;
if(!empty(self::$db->config['map']) && !empty(self::$db->config['map'][$table])) {
$linkId = self::$db->config['map'][$table];
}
$dbname = self::$db->config[$linkId]['dbname'];
$table = self::$db->table_name($table);
self::$db->select_db('information_schema');
$count = self::$db->result(mysql_query("SELECT TABLE_ROWS FROM `TABLES` WHERE TABLE_SCHEMA = '$dbname' AND TABLE_NAME = '$table'", self::$db->curlink));
self::$db->select_db($dbname);
return $count;
}
public static function result_first($sql, $arg = array(), $silent = false) {
if(preg_match("/^select\s+count\(\*\)\s+/i", $sql)) {
$sql_a = preg_match("/%[a-zA-Z]+/i", $sql) ? self::format($sql, $arg) : $sql;
if(preg_match("/(where\s+1\s*)+$/i", $sql_a) || !preg_match("/where/i", $sql_a)) {
preg_match("/FROM\s+[`]?(\w+)[`]?/i", $sql_a, $match);
global $_G;
$table = str_replace($_G['config']['db'][1]['tablepre'], '', $match[1]);
if(!in_array($table, self::$_ext_table)) {
return self::count_all($table);
}
}
}
$res = self::query($sql, $arg, $silent, false);
$ret = self::$db->result($res, 0);
self::$db->free_result($res);
return $ret;
}
}
<file_sep>INSERT INTO `pre_common_word_type` (`id`, `typename`) VALUES
(1, '政治'),
(2, '广告');
INSERT INTO `pre_common_word` (`id`, `admin`, `type`, `find`, `replacement`, `extra`) VALUES
(3, 'admin', 1, 'fuck', '****', ''),
(6, 'admin', 1, '性爱', '**', ''),
(7, 'admin', 1, '法轮', '**', ''),
(8, 'admin', 1, 'falundafa', '*********', ''),
(9, 'admin', 1, 'falun', '*****', ''),
(10, 'admin', 0, '江泽民', '{MOD}', ''),
(12, 'admin', 1, '操你妈', '***', ''),
(14, 'admin', 1, 'ovc', '****', ''),
(15, 'admin', 1, 'OVC', '****', ''),
(20, 'admin', 1, 'Ovc', '***', ''),
(22, 'admin', 1, 'shop33945123', '***', ''),
(24, 'admin', 0, '胡锦涛', '{MOD}', ''),
(26, 'admin', 0, '太子党', '{MOD}', ''),
(27, 'admin', 1, '法轮功', '***', ''),
(28, 'admin', 1, '李洪志', '***', ''),
(30, 'admin', 1, '真善忍', '***', ''),
(31, 'admin', 1, '新唐人', '***', ''),
(32, 'admin', 1, '肉棍', '***', ''),
(33, 'admin', 1, '淫靡', '***', ''),
(34, 'admin', 1, '淫水', '***', ''),
(35, 'admin', 1, '六四事件', '***', ''),
(36, 'admin', 1, '迷药', '***', ''),
(37, 'admin', 1, '迷魂药', '***', ''),
(38, 'admin', 1, '窃听器', '***', ''),
(39, 'admin', 1, '六合彩', '***', ''),
(40, 'admin', 1, '买卖枪支', '***', ''),
(41, 'admin', 1, '退党', '***', ''),
(42, 'admin', 1, '麻醉药', '***', ''),
(43, 'admin', 1, '麻醉乙醚', '***', ''),
(44, 'admin', 1, '短信群发器', '***', ''),
(45, 'admin', 1, '帝国之梦', '***', ''),
(46, 'admin', 1, '毛一鲜', '***', ''),
(47, 'admin', 1, '黎阳评', '***', ''),
(48, 'admin', 1, '色情服务', '***', ''),
(49, 'admin', 1, '对日强硬', '***', ''),
(50, 'admin', 1, '出售枪支', '***', ''),
(51, 'admin', 1, '摇头丸', '***', ''),
(52, 'admin', 1, '西藏天葬', '***', ''),
(53, 'admin', 1, '鬼村', '***', ''),
(54, 'admin', 1, '军长发威', '***', ''),
(55, 'admin', 1, 'PK黑社会', '***', ''),
(57, 'admin', 1, '枪决女犯', '***', ''),
(58, 'admin', 1, '投毒杀人', '***', ''),
(59, 'admin', 1, '强硬发言', '***', ''),
(60, 'admin', 1, '出售假币', '***', ''),
(61, 'admin', 1, '监听王', '***', ''),
(62, 'admin', 1, '昏药', '***', ''),
(63, 'admin', 1, '侦探社北', '***', ''),
(64, 'admin', 1, '麻醉钢枪', '***', ''),
(65, 'admin', 1, '反华', '***', ''),
(66, 'admin', 0, '官商勾结', '{MOD}', ''),
(67, 'admin', 1, '升达毕业证', '***', ''),
(68, 'admin', 1, '手机复制', '***', ''),
(69, 'admin', 1, '戴海静', '***', ''),
(70, 'admin', 1, '自杀手册', '***', ''),
(71, 'admin', 1, '自杀指南', '***', ''),
(72, 'admin', 1, '张小平', '***', ''),
(73, 'admin', 1, '佳静安定片', '***', ''),
(74, 'admin', 1, '蒙汗药粉', '***', ''),
(75, 'admin', 1, '古方米香', '***', ''),
(76, 'admin', 1, '强效失意药', '***', ''),
(77, 'admin', 1, '东方迷魂', '***', ''),
(78, 'admin', 1, '迷歼药', '***', ''),
(79, 'admin', 1, '透视眼镜', '***', ''),
(80, 'admin', 1, '远程偷拍', '***', ''),
(81, 'admin', 1, '自制手枪', '***', ''),
(82, 'admin', 1, '子女任职名单', '***', ''),
(83, 'admin', 1, '激情小电影', '***', ''),
(84, 'admin', 1, '黄色小电影', '***', ''),
(85, 'admin', 1, '色情小电影', '***', ''),
(86, 'admin', 0, '天鹅之旅', '{MOD}', ''),
(87, 'admin', 0, '盘古乐队', '{MOD}', ''),
(88, 'admin', 1, '高校暴乱', '***', ''),
(89, 'admin', 1, '高校群体事件', '***', ''),
(90, 'admin', 1, '大学骚乱', '***', ''),
(91, 'admin', 1, '高校骚乱', '***', ''),
(92, 'admin', 1, '催情药', '***', ''),
(93, 'admin', 1, '扫肩神药', '***', ''),
(94, 'admin', 1, '春药', '***', ''),
(95, 'admin', 1, '窃听器材', '***', ''),
(96, 'admin', 1, '身份证生成器', '***', ''),
(97, 'admin', 1, '枪决现场', '***', ''),
(98, 'admin', 1, '出售手枪', '***', ''),
(99, 'admin', 1, '麻醉枪', '***', ''),
(100, 'admin', 1, '办理证件', '***', ''),
(101, 'admin', 1, '办理文凭', '***', ''),
(102, 'admin', 0, '疆独', '{MOD}', ''),
(103, 'admin', 0, '藏独', '{MOD}', ''),
(104, 'admin', 0, '高干子弟', '{MOD}', ''),
(105, 'admin', 1, '高干子女', '***', ''),
(106, 'admin', 1, '枪支弹药', '***', ''),
(107, 'admin', 1, '血腥图片', '***', ''),
(108, 'admin', 1, '反政府', '***', ''),
(109, 'admin', 1, '禁书', '***', ''),
(110, 'admin', 0, '无界浏览器', '{MOD}', ''),
(111, 'admin', 1, '无界', '***', ''),
(112, 'admin', 1, '特码', '***', ''),
(113, 'admin', 0, '自由门', '{MOD}', ''),
(114, 'admin', 1, '反共', '***', ''),
(115, 'admin', 0, '共产党', '{MOD}', ''),
(116, 'admin', 0, '中共中央', '{MOD}', ''),
(117, 'admin', 1, '成人片', '***', ''),
(118, 'admin', 1, '成人电影', '***', ''),
(119, 'admin', 1, '换妻', '***', ''),
(120, 'admin', 1, '拉萨暴动', '***', ''),
(121, 'admin', 1, '喇嘛', '***', ''),
(122, 'admin', 1, '蒙汗药', '***', ''),
(123, 'admin', 1, '手机监听', '***', ''),
(124, 'admin', 1, '监听器', '***', ''),
(125, 'admin', 1, '出售手机卡复制器', '***', ''),
(126, 'admin', 1, '三唑仑', '***', ''),
(127, 'admin', 1, '迷昏药', '***', ''),
(128, 'admin', 1, '打猎好帮手', '***', ''),
(129, 'admin', 1, '射网枪', '***', ''),
(130, 'admin', 1, '正宗赵氏微型手枪', '***', ''),
(131, 'admin', 1, '灭火枪', '***', ''),
(132, 'admin', 1, '出售气枪', '***', ''),
(133, 'admin', 1, '微型手枪', '***', ''),
(134, 'admin', 1, '破拆枪', '***', ''),
(135, 'admin', 1, '电动枪', '***', ''),
(136, 'admin', 1, '针孔摄象机', '***', ''),
(137, 'admin', 1, '针孔摄像机', '***', ''),
(138, 'admin', 1, '梓健特药', '***', ''),
(139, 'admin', 1, '乙醚', '***', ''),
(140, 'admin', 1, '迷幻药', '***', ''),
(141, 'admin', 1, '出售春药', '***', ''),
(142, 'admin', 1, '性药', '***', ''),
(143, 'admin', 1, '出售军用手枪', '***', ''),
(145, 'admin', 1, '代开发票', '***', ''),
(146, 'admin', 1, '手机教你制做原子弹', '***', ''),
(147, 'admin', 1, '淫秽色情', '***', ''),
(148, 'admin', 1, '公安部专项', '***', ''),
(149, 'admin', 1, '中国高干子弟最新名单', '***', ''),
(150, 'admin', 1, '让国人愤怒的第二代身份证', '***', ''),
(151, 'admin', 1, '办假证', '***', ''),
(152, 'admin', 1, '孙悟空和雅典娜的故事', '***', ''),
(153, 'admin', 1, '两岸才子对话', '***', ''),
(154, 'admin', 1, '先烈纷纷打来电话', '***', ''),
(155, 'admin', 1, '拉登说中国全球唯一绝对不能惹的国家', '***', ''),
(158, 'admin', 1, 'fldfh', '***', ''),
(159, 'admin', 1, 'zhenshanren', '***', ''),
(160, 'admin', 1, '突破网络封锁', '***', ''),
(161, 'admin', 0, '无界浏览', '{MOD}', ''),
(162, 'admin', 1, '自由网', '***', ''),
(163, 'admin', 1, '破网工具', '***', ''),
(165, 'admin', 1, '退出共产党', '***', ''),
(166, 'admin', 0, '九评', '{MOD}', ''),
(169, 'admin', 1, '9评共', '***', ''),
(170, 'admin', 1, '高莺莺', '***', ''),
(171, 'admin', 1, '曾道人', '***', ''),
(173, 'admin', 1, '豪江', '***', ''),
(177, 'admin', 0, '上访', '{MOD}', ''),
(178, 'admin', 1, '诉讼集团', '***', ''),
(179, 'admin', 1, '对越反击战', '***', ''),
(180, 'admin', 1, '对越自卫反击战', '***', ''),
(181, 'admin', 1, '退役军人', '***', ''),
(184, 'admin', 0, '瓮安', '{MOD}', ''),
(185, 'admin', 1, '鸡王', '******', ''),
(186, 'admin', 1, 'K粉', '*****', ''),
(187, 'admin', 1, '冰毒', '*****', ''),
(188, 'admin', 1, '麻古', '****', ''),
(193, 'admin', 1, '氯胺酮', '****', ''),
(194, 'admin', 1, '海洛因', '****', ''),
(195, 'admin', 1, 'cocain', '****', ''),
(196, 'admin', 1, 'heroine', '****', ''),
(198, 'admin', 1, '大麻', '****', ''),
(202, 'admin', 1, '抵制', '****', ''),
(208, 'admin', 1, '财力物力', '****', ''),
(209, 'admin', 1, '恶搞公安部领导', '****', ''),
(211, 'admin', 1, '女警执行死刑', '****', ''),
(212, 'admin', 1, '四川仁寿警方冲击省人大抓上访者', '****', ''),
(213, 'admin', 1, '公安机关处理邪教问题知识手册', '****', ''),
(214, 'admin', 1, '借第二代身份证攻击我党和政府', '****', ''),
(215, 'admin', 1, '医院聘民警当副院长防医闹', '****', ''),
(216, 'admin', 1, '原湖北黄石民警吴幼明', '****', ''),
(217, 'admin', 1, '湖南省公安厅副厅长偷情酿血案', '****', ''),
(218, 'admin', 1, '充当涉毒场所保护伞', '****', ''),
(220, 'admin', 1, '警察滥用职权', '****', ''),
(221, 'admin', 1, '警察特权', '****', ''),
(222, 'admin', 1, '罚款黑幕', '****', ''),
(223, 'admin', 1, '警察知法犯法', '****', ''),
(224, 'admin', 1, '警民冲突', '****', ''),
(225, 'admin', 1, '警察开枪', '****', ''),
(226, 'admin', 1, '黑恶势力保护伞', '****', ''),
(228, 'admin', 1, '保钓', '****', ''),
(229, 'admin', 0, '游行', '{MOD}', ''),
(230, 'admin', 0, '示威', '{MOD}', ''),
(231, 'admin', 0, '钓鱼岛', '{MOD}', ''),
(232, 'admin', 1, '中国民间保钓联合会', '****', ''),
(233, 'admin', 1, '爱国者同盟', '****', ''),
(234, 'admin', 1, '中华抗日同盟', '****', ''),
(235, 'admin', 1, '李义强', '****', ''),
(236, 'admin', 1, '王锦思', '****', ''),
(237, 'admin', 1, '冯锦华', '****', ''),
(238, 'admin', 0, '童增', '{MOD}', ''),
(239, 'admin', 1, '就业歧视', '****', ''),
(240, 'admin', 1, '乙肝携带者', '****', ''),
(241, 'admin', 1, '乙肝NGO工作者', '****', ''),
(242, 'admin', 1, '金戈铁马', '****', ''),
(243, 'admin', 1, '乙肝歧视', '****', ''),
(244, 'admin', 1, 'hbv', '****', ''),
(245, 'admin', 1, '乙肝维权', '****', ''),
(246, 'admin', 1, '乙肝战友', '****', ''),
(248, 'admin', 1, '集体签名', '****', ''),
(249, 'admin', 1, '小阳', '****', ''),
(250, 'admin', 1, '乙肝检测', '****', ''),
(251, 'admin', 1, '乙肝筛选', '****', ''),
(252, 'admin', 1, '非法拆毁', '****', ''),
(254, 'admin', 1, '勾结奸商', '****', ''),
(255, 'admin', 1, '强拆当地居民房', '****', ''),
(256, 'admin', 0, '暴力拆迁', '{MOD}', ''),
(257, 'admin', 1, '非法征用', '****', ''),
(258, 'admin', 1, '霸占土地', '****', ''),
(259, 'admin', 1, '买断工龄', '****', ''),
(260, 'admin', 1, '买断职工', '****', ''),
(261, 'admin', 1, '找农总行', '****', ''),
(262, 'admin', 1, '找建总行', '****', ''),
(263, 'admin', 1, '找工总行', '****', ''),
(264, 'admin', 1, '代办员', '****', ''),
(265, 'admin', 1, '遗留问题', '****', ''),
(266, 'admin', 1, '业主维权', '****', ''),
(267, 'admin', 1, '侵害业主正当权益', '****', ''),
(268, 'admin', 1, '违反购房合同', '****', ''),
(269, 'admin', 1, '征集业主意见', '****', ''),
(270, 'admin', 1, '散散步', '****', ''),
(271, 'admin', 1, '联合签名', '****', ''),
(272, 'admin', 1, '抵制变电站', '****', ''),
(273, 'admin', 1, '反对磁悬浮', '****', ''),
(274, 'admin', 1, '香港六合彩', '****', ''),
(275, 'admin', 1, '香港总彩', '****', ''),
(276, 'admin', 1, '六合采', '****', ''),
(277, 'admin', 1, '六和采', '****', ''),
(278, 'admin', 1, '香港赛马会', '****', ''),
(279, 'admin', 1, '香港白小姐', '****', ''),
(280, 'admin', 1, '香港惠泽社群', '****', ''),
(281, 'admin', 1, '香港曾道人', '****', ''),
(282, 'admin', 1, '香港黄大仙', '****', ''),
(283, 'admin', 1, '码中特', '****', ''),
(285, 'admin', 1, 'liuhecai', '****', ''),
(286, 'admin', 1, '六合彩券', '****', ''),
(287, 'admin', 1, '六星合彩', '****', ''),
(288, 'admin', 1, '香港六星合彩', '****', ''),
(289, 'admin', 1, '六星合彩公司', '****', ''),
(290, 'admin', 1, '六合菜', '****', ''),
(291, 'admin', 1, '一字解特码', '****', ''),
(292, 'admin', 1, '报码聊天', '****', ''),
(293, 'admin', 1, '6合彩', '****', ''),
(294, 'admin', 1, '香港6合彩', '****', ''),
(295, 'admin', 1, '香港6合彩公司', '****', ''),
(296, 'admin', 1, '最快报码室', '****', ''),
(298, 'admin', 0, '胡温', '{MOD}', ''),
(299, 'admin', 1, '胡瘟', '****', ''),
(300, 'admin', 1, '瘟家', '****', ''),
(301, 'admin', 1, '温夫人', '****', ''),
(302, 'admin', 1, '温公子', '****', ''),
(303, 'admin', 1, '胡公子', '****', ''),
(304, 'admin', 1, '温宝宝', '****', ''),
(305, 'admin', 1, '温云松', '****', ''),
(306, 'admin', 1, '胡海峰', '****', ''),
(307, 'admin', 1, '江家帮', '****', ''),
(308, 'admin', 1, '江系', '****', ''),
(309, 'admin', 1, '胡系', '****', ''),
(310, 'admin', 1, '江派', '****', ''),
(311, 'admin', 0, '江胡', '{MOD}', ''),
(312, 'admin', 1, '胡主席', '****', ''),
(314, 'admin', 1, '胡总书记', '****', ''),
(315, 'admin', 0, '团派', '{MOD}', ''),
(316, 'admin', 1, '红色贵族', '****', ''),
(317, 'admin', 1, '人马', '****', ''),
(318, 'admin', 0, '中共', '{MOD}', ''),
(319, 'admin', 1, '北京帮', '****', ''),
(320, 'admin', 1, '共铲党', '****', ''),
(321, 'admin', 1, '共残党', '****', ''),
(322, 'admin', 1, '共惨党', '****', ''),
(323, 'admin', 1, '共chan党', '****', ''),
(324, 'admin', 0, '权斗', '{MOD}', ''),
(328, 'admin', 1, '内斗', '****', ''),
(331, 'admin', 1, '引咎辞职', '****', ''),
(334, 'admin', 1, '权力分配', '****', ''),
(335, 'admin', 1, '胡紧套', '****', ''),
(336, 'admin', 1, '胡紧掏', '****', ''),
(337, 'admin', 1, '瘟家鸨', '****', ''),
(338, 'admin', 1, '瘟假鸨', '****', ''),
(345, 'admin', 1, '毛贼东', '****', ''),
(346, 'admin', 1, '毛厕洞', '****', ''),
(347, 'admin', 1, '毛厕东', '****', ''),
(348, 'admin', 0, '台湾独立', '{MOD}', ''),
(350, 'admin', 0, '陈水扁', '{MOD}', ''),
(351, 'admin', 0, '国民党', '{MOD}', ''),
(353, 'admin', 0, '泛蓝', '{MOD}', ''),
(354, 'admin', 1, '泛绿', '****', ''),
(355, 'admin', 1, '公投', '****', ''),
(356, 'admin', 1, '蓝营', '****', ''),
(357, 'admin', 1, '绿营', '****', ''),
(361, 'admin', 1, '大选', '****', ''),
(362, 'admin', 1, '独派', '****', ''),
(363, 'admin', 1, '台军', '****', ''),
(364, 'admin', 1, '立委', '****', ''),
(365, 'admin', 0, '吕秀莲', '{MOD}', ''),
(368, 'admin', 1, '台海危机', '****', ''),
(369, 'admin', 1, '国语运动', '****', ''),
(371, 'admin', 1, '机要费', '****', ''),
(372, 'admin', 1, '倒扁', '****', ''),
(373, 'admin', 1, '马营', '****', ''),
(374, 'admin', 1, '国民大会', '****', ''),
(375, 'admin', 1, '总统府', '****', ''),
(376, 'admin', 1, '行政院', '****', ''),
(377, 'admin', 1, '立法院', '****', ''),
(378, 'admin', 1, '司法院', '****', ''),
(380, 'admin', 1, '监察院', '****', ''),
(381, 'admin', 1, '左营海军军官学校', '****', ''),
(382, 'admin', 1, '冈山空军官学校', '****', ''),
(383, 'admin', 1, '风山陆军军官学校', '****', ''),
(384, 'admin', 1, '工蜂六型多管火箭系统', '****', ''),
(385, 'admin', 1, '天剑二型飞弹', '****', ''),
(386, 'admin', 1, '天剑一型飞弹', '****', ''),
(387, 'admin', 1, '宪兵司令部', '****', ''),
(388, 'admin', 1, '联合后', '****', ''),
(389, 'admin', 1, '勤司领部', '****', ''),
(390, 'admin', 1, '参谋本部', '****', ''),
(392, 'admin', 1, '彭湖', '****', ''),
(394, 'admin', 1, '台中', '****', ''),
(396, 'admin', 1, '竹联帮', '****', ''),
(397, 'admin', 1, '四海帮', '****', ''),
(398, 'admin', 1, '牛埔帮', '****', ''),
(399, 'admin', 1, '大湖帮', '****', ''),
(400, 'admin', 1, '十三兄弟帮', '****', ''),
(401, 'admin', 1, '七贤帮', '****', ''),
(402, 'admin', 1, '西北帮', '****', ''),
(403, 'admin', 1, '十二煞星帮', '****', ''),
(404, 'admin', 1, '铁鹰帮竹林联盟', '****', ''),
(405, 'admin', 1, '台湾间谍', '****', ''),
(406, 'admin', 1, '统独光谱', '****', ''),
(407, 'admin', 1, '二二八事件', '****', ''),
(408, 'admin', 1, '台独党纲', '****', ''),
(409, 'admin', 1, '台独党', '****', ''),
(410, 'admin', 1, '立法委员', '****', ''),
(411, 'admin', 1, '制作原子弹 -新闻', '****', ''),
(417, 'admin', 1, '黄跳跳', '****', ''),
(418, 'admin', 1, '中创网赚', '***', ''),
(429, 'admin', 0, '台独', '{MOD}', ''),
(430, 'admin', 1, '针刺事件', '****', ''),
(431, 'admin', 1, '国家囚徒', '****', ''),
(432, 'admin', 1, '改革历程', '****', ''),
(433, 'admin', 1, '五七之声', '****', ''),
(434, 'admin', 1, '往事微痕', '****', ''),
(436, 'admin', 1, '五七二特刊', '*****', ''),
(437, 'admin', 1, '赵紫阳的事来和理想', '****', ''),
(438, 'admin', 1, '零八宪章', '****', ''),
(439, 'admin', 1, '零八宪章与中国变革', '***', ''),
(440, 'admin', 1, '天安门时报', '****', ''),
(441, 'admin', 1, '劳改', '**', ''),
(442, 'admin', 1, '共用的墓碑', '*****', ''),
(443, 'admin', 1, '兰大一家人', '*****', ''),
(444, 'admin', 1, '一万封信', '****', ''),
(446, 'admin', 1, '伊吉莱提感想', '******', ''),
(447, 'admin', 1, '听说西藏', '****', ''),
(448, 'admin', 1, '西藏骚乱', '****', ''),
(449, 'admin', 1, '西域', '**', ''),
(451, 'admin', 1, '新法轮', '***', ''),
(452, 'admin', 1, '西苑风月', '****', ''),
(453, 'admin', 1, '达赖喇嘛', '****', ''),
(454, 'admin', 1, '历史的震撼', '*****', ''),
(455, 'admin', 1, '疆独打砸抢烧', '*********', ''),
(456, 'admin', 1, '达赖反恐事件', '**********', ''),
(457, 'admin', 1, '红都女皇江青胎死腹中', '**********', ''),
(458, 'admin', 1, '反击右派运动与劳动教养', '***********', ''),
(459, 'admin', 1, '镇压反革命与三大改造', '**********', ''),
(460, 'admin', 1, '达赖喇嘛复兴之路', '********', ''),
(461, 'admin', 1, '六四事件中的戒严部队', '***', ''),
(462, 'admin', 1, '天安门血腥清场内幕', '***', ''),
(464, 'admin', 1, '六四日记', '****', ''),
(466, 'admin', 1, '六四事件民间白皮书', '***', ''),
(467, 'admin', 1, '五一九文萃序', '****', ''),
(468, 'admin', 1, '中国政治体制改革总方向', '****', ''),
(469, 'admin', 1, '胡锦涛与刘晓波的对峙', '***', ''),
(470, 'admin', 1, '中国政治体制改革为何停止', '****', ''),
(471, 'admin', 1, '胡锦涛走向个人崇拜', '***', ''),
(472, 'admin', 1, '中南海厚黑学', '***', ''),
(473, 'admin', 1, '从柏林墙到天安门', '***', ''),
(474, 'admin', 1, '大国沉沦-写给中国的备忘录', '***', ''),
(475, 'admin', 1, '在如来佛掌中-张苏荪和他的时代', '***', ''),
(477, 'admin', 0, '中南海', '{MOD}', ''),
(478, 'admin', 0, '赵紫阳', '{MOD}', ''),
(479, 'admin', 1, 'GCD', '***', ''),
(481, 'admin', 0, '腐败', '{MOD}', ''),
(482, 'admin', 0, '垮台', '{MOD}', ''),
(483, 'admin', 1, '垮 台', '* *', ''),
(484, 'admin', 0, '推翻', '{MOD}', ''),
(487, 'admin', 1, '红军', '***', ''),
(491, 'admin', 1, '翻墙', '****', ''),
(492, 'admin', 1, '刘晓波', '***', ''),
(504, 'admin', 1, '贾佳辉', '***', ''),
(505, 'admin', 1, '佳辉', '**', ''),
(511, 'admin', 1, 'taourl', '****', ''),
(512, 'admin', 1, '茉莉花', '***', ''),
(514, 'admin', 1, 'GOOYO', '***', ''),
(515, 'admin', 1, 'http://uuz.cc', '***', ''),
(516, 'admin', 1, 'taobaocdn.com', '***', ''),
(518, 'admin', 1, 'gojy.us', '***', ''),
(519, 'admin', 1, '科学上网', '', ''),
(549, 'admin', 1, 'taobao.com', '本论坛禁止广告', ''),
(553, 'admin', 1, '小姐', '**', ''),
(555, 'admin', 0, '薄熙来', '{MOD}', ''),
(557, 'admin', 0, '王立军', '{MOD}', ''),
(559, 'admin', 0, '陈光诚', '{MOD}', ''),
(561, 'admin', 1, '菲律宾', '**', ''),
(562, 'admin', 1, '纪委', '**', ''),
(563, 'admin', 1, '立案', '**', ''),
(564, 'admin', 1, '广隶', '**', ''),
(565, 'admin', 1, '尼尔', '**', ''),
(566, 'admin', 1, '英国商人', '**', ''),
(567, 'admin', 1, '英国保姆', '**', ''),
(568, 'admin', 1, '徐明', '**', ''),
(569, 'admin', 1, '薄瓜瓜', '**', ''),
(570, 'admin', 1, '谷开来', '**', ''),
(571, 'admin', 1, '王丽娟', '**', ''),
(572, 'admin', 1, '大力王', '**', ''),
(573, 'admin', 1, '王立jun', '**', ''),
(574, 'admin', 1, 'wanglijun', '**', ''),
(575, 'admin', 1, '叛逃', '**', ''),
(576, 'admin', 1, '来俊臣', '**', ''),
(577, 'admin', 1, '篡党', '**', ''),
(578, 'admin', 1, '王丽娟护士长', '**', ''),
(579, 'admin', 1, '温相', '**', ''),
(580, 'admin', 1, '盲人律师', '**', ''),
(581, 'admin', 1, '朝阳医院', '**', ''),
(582, 'admin', 1, '自行离开', '**', ''),
(583, 'admin', 0, '骆家辉', '{MOD}', ''),
(584, 'admin', 1, '政治庇护', '**', ''),
(585, 'admin', 1, '滕彪', '**', ''),
(588, 'admin', 1, '政治', '**', ''),
(589, 'admin', 1, '天朝', '**', ''),
(590, 'admin', 1, 'VPN', '***', ''),
(591, 'admin', 1, '林俊', '**', ''),
(601, 'admin', 1, 'av女优', '***', ''),
(602, 'admin', 1, '草榴', '**', ''),
(603, 'admin', 1, 'caoliu', '**', ''),
(604, 'admin', 1, 'cao榴', '**', ''),
(605, 'admin', 1, '艹榴', '**', ''),
(606, 'admin', 1, 'huang网', '**', ''),
(608, 'admin', 1, '翻qiang', '**', ''),
(609, 'admin', 1, 'fanqiang', '**', ''),
(610, 'admin', 1, 'fan墙', '**', ''),
(611, 'admin', 1, '李双江', '***', ''),
(612, 'admin', 1, '李天一', '***', ''),
(613, 'admin', 0, '强奸', '{MOD}', ''),
(614, 'admin', 1, '李冠丰', '***', ''),
(615, 'admin', 0, '有ぷ小姐', '{MOD}', ''),
(616, 'admin', 0, '吴邦国', '{MOD}', ''),
(617, 'admin', 0, '温家宝', '{MOD}', ''),
(618, 'admin', 0, '贾庆林', '{MOD}', ''),
(619, 'admin', 0, '李长春', '{MOD}', ''),
(620, 'admin', 0, '习近平', '{MOD}', ''),
(621, 'admin', 0, '李克强', '{MOD}', ''),
(622, 'admin', 0, '贺国强', '{MOD}', ''),
(623, 'admin', 0, '周永康', '{MOD}', ''),
(624, 'admin', 0, '胡哥', '{MOD}', ''),
(625, 'admin', 0, '涛哥', '{MOD}', ''),
(626, 'admin', 0, '习哥', '{MOD}', ''),
(627, 'admin', 0, '胡总', '{MOD}', ''),
(628, 'admin', 0, '温总', '{MOD}', ''),
(629, 'admin', 0, '锦涛', '{MOD}', ''),
(630, 'admin', 0, '邦国', '{MOD}', ''),
(631, 'admin', 0, '阿胡', '{MOD}', ''),
(632, 'admin', 0, '阿温', '{MOD}', ''),
(633, 'admin', 0, '习总', '{MOD}', ''),
(634, 'admin', 0, 'HuJintao', '{MOD}', ''),
(635, 'admin', 0, 'wubangguo', '{MOD}', ''),
(636, 'admin', 0, 'wenjiabao', '{MOD}', ''),
(637, 'admin', 0, 'jiaqinglin', '{MOD}', ''),
(638, 'admin', 0, 'lichangchun', '{MOD}', ''),
(639, 'admin', 0, 'xijinping', '{MOD}', ''),
(640, 'admin', 0, 'likeqiang', '{MOD}', ''),
(641, 'admin', 0, 'heguoqiang', '{MOD}', ''),
(642, 'admin', 0, 'zhouyongkang', '{MOD}', ''),
(643, 'admin', 0, '总书记', '{MOD}', ''),
(644, 'admin', 0, '主席', '{MOD}', ''),
(645, 'admin', 0, '总理', '{MOD}', ''),
(646, 'admin', 0, '常委', '{MOD}', ''),
(647, 'admin', 0, '中共领导', '{MOD}', ''),
(648, 'admin', 0, '书记', '{MOD}', ''),
(649, 'admin', 0, '毛泽东', '{MOD}', ''),
(650, 'admin', 0, '邓小平', '{MOD}', ''),
(651, 'admin', 0, '李鹏', '{MOD}', ''),
(652, 'admin', 0, '朱镕基', '{MOD}', ''),
(653, 'admin', 0, '杨尚昆', '{MOD}', ''),
(654, 'admin', 0, '胡耀邦', '{MOD}', ''),
(655, 'admin', 0, '周恩来', '{MOD}', ''),
(656, 'admin', 0, '华国锋', '{MOD}', ''),
(657, 'admin', 0, '薄一波', '{MOD}', ''),
(658, 'admin', 0, '李先念', '{MOD}', ''),
(659, 'admin', 0, '刘少奇', '{MOD}', ''),
(660, 'admin', 0, '许嘉璐', '{MOD}', ''),
(661, 'admin', 0, '曾庆红', '{MOD}', ''),
(662, 'admin', 0, '钱其琛', '{MOD}', ''),
(663, 'admin', 0, '习仲勋', '{MOD}', ''),
(664, 'admin', 0, '杨白冰', '{MOD}', ''),
(665, 'admin', 0, '姚依林', '{MOD}', ''),
(666, 'admin', 0, '叶剑英', '{MOD}', ''),
(667, 'admin', 0, '于永波', '{MOD}', ''),
(668, 'admin', 0, '张万年', '{MOD}', ''),
(669, 'admin', 0, '盛华仁', '{MOD}', ''),
(670, 'admin', 0, '石秀诗', '{MOD}', ''),
(671, 'admin', 0, '宋法棠', '{MOD}', ''),
(672, 'admin', 0, '宋平', '{MOD}', ''),
(673, 'admin', 0, '宋任穷', '{MOD}', ''),
(674, 'admin', 0, '苏振华', '{MOD}', ''),
(675, 'admin', 0, '孙大光', '{MOD}', ''),
(676, 'admin', 0, '谭绍文', '{MOD}', ''),
(677, 'admin', 0, '唐家璇', '{MOD}', ''),
(678, 'admin', 0, '滕文生', '{MOD}', ''),
(679, 'admin', 0, '伍绍组', '{MOD}', ''),
(680, 'admin', 0, '吴仪', '{MOD}', ''),
(681, 'admin', 0, '迟浩田', '{MOD}', ''),
(682, 'admin', 0, '吴学谦', '{MOD}', ''),
(683, 'admin', 0, '吴德', '{MOD}', ''),
(684, 'admin', 0, '乌兰夫', '{MOD}', ''),
(685, 'admin', 0, '尉健行', '{MOD}', ''),
(686, 'admin', 0, '陈云', '{MOD}', ''),
(687, 'admin', 0, '方毅', '{MOD}', ''),
(688, 'admin', 0, '田纪云', '{MOD}', ''),
(689, 'admin', 0, '汪东兴', '{MOD}', ''),
(690, 'admin', 0, '汪恕诚', '{MOD}', ''),
(691, 'admin', 0, '汪啸风', '{MOD}', ''),
(692, 'admin', 0, '王光英', '{MOD}', ''),
(693, 'admin', 0, '王汉斌', '{MOD}', ''),
(694, 'admin', 0, '王克', '{MOD}', ''),
(695, 'admin', 0, '王茂林', '{MOD}', ''),
(696, 'admin', 0, '王瑞林', '{MOD}', ''),
(697, 'admin', 0, '王顺生', '{MOD}', ''),
(698, 'admin', 0, '王选', '{MOD}', ''),
(699, 'admin', 0, '王震', '{MOD}', ''),
(700, 'admin', 0, '王忠禹', '{MOD}', ''),
(701, 'admin', 0, '王卓辉', '{MOD}', ''),
(702, 'admin', 0, '姬鹏飞', '{MOD}', ''),
(703, 'admin', 0, '韦国清', '{MOD}', ''),
(704, 'admin', 0, '彭德怀', '{MOD}', ''),
(705, 'admin', 0, '邓力群', '{MOD}', ''),
(706, 'admin', 0, '宋德福', '{MOD}', ''),
(707, 'admin', 0, '李岚清', '{MOD}', ''),
(708, 'admin', 0, '黄菊', '{MOD}', ''),
(709, 'admin', 0, '蒋毛', '{MOD}', ''),
(710, 'admin', 0, '耀邦', '{MOD}', ''),
(711, 'admin', 0, '紫阳', '{MOD}', ''),
(712, 'admin', 0, '瑞环', '{MOD}', ''),
(713, 'admin', 0, '尚昆', '{MOD}', ''),
(714, 'admin', 0, '恩来', '{MOD}', ''),
(715, 'admin', 0, '小平同志', '{MOD}', ''),
(716, 'admin', 0, '邓公', '{MOD}', ''),
(717, 'admin', 0, '刘sq', '{MOD}', ''),
(718, 'admin', 0, '毛邓', '{MOD}', ''),
(719, 'admin', 0, '少奇', '{MOD}', ''),
(720, 'admin', 0, 'zhurongji', '{MOD}', ''),
(721, 'admin', 0, 'DengXiaoping', '{MOD}', ''),
(722, 'admin', 0, 'JiangZemin', '{MOD}', ''),
(723, 'admin', 0, 'LiPeng', '{MOD}', ''),
(724, 'admin', 0, 'MaoZedong', '{MOD}', ''),
(725, 'admin', 0, 'huangju', '{MOD}', ''),
(726, 'admin', 0, '蛤蟆', '{MOD}', ''),
(727, 'admin', 0, '李月鸟', '{MOD}', ''),
(728, 'admin', 0, '二月鸟', '{MOD}', ''),
(729, 'admin', 0, '老毛头', '{MOD}', ''),
(730, 'admin', 0, '小矮', '{MOD}', ''),
(731, 'admin', 0, '江氏', '{MOD}', ''),
(732, 'admin', 0, '胡爷爷', '{MOD}', ''),
(733, 'admin', 0, '九头金猪', '{MOD}', ''),
(734, 'admin', 0, '九常萎', '{MOD}', ''),
(735, 'admin', 0, '王岐山', '{MOD}', ''),
(736, 'admin', 0, '回良玉', '{MOD}', ''),
(737, 'admin', 0, '刘淇', '{MOD}', ''),
(738, 'admin', 0, '刘云山', '{MOD}', ''),
(739, 'admin', 0, '刘延东', '{MOD}', ''),
(740, 'admin', 0, '李源潮', '{MOD}', ''),
(741, 'admin', 0, '汪洋', '{MOD}', ''),
(742, 'admin', 0, '张高丽', '{MOD}', ''),
(743, 'admin', 0, '张德江', '{MOD}', ''),
(744, 'admin', 0, '俞正声', '{MOD}', ''),
(745, 'admin', 0, '徐才厚', '{MOD}', ''),
(746, 'admin', 0, '郭伯雄', '{MOD}', ''),
(747, 'admin', 0, '何勇', '{MOD}', ''),
(748, 'admin', 0, '令计划', '{MOD}', ''),
(749, 'admin', 0, '王沪宁', '{MOD}', ''),
(750, 'admin', 0, '张惠新', '{MOD}', ''),
(751, 'admin', 0, '马馼', '{MOD}', ''),
(752, 'admin', 0, '孙忠同', '{MOD}', ''),
(753, 'admin', 0, '干以胜', '{MOD}', ''),
(754, 'admin', 0, '张毅', '{MOD}', ''),
(755, 'admin', 0, '黄树贤', '{MOD}', ''),
(756, 'admin', 0, '李玉赋', '{MOD}', ''),
(757, 'admin', 0, '令狐安', '{MOD}', ''),
(758, 'admin', 0, '杜学芳', '{MOD}', ''),
(759, 'admin', 0, '吴玉良', '{MOD}', ''),
(760, 'admin', 0, '吴毓萍', '{MOD}', ''),
(761, 'admin', 0, '邱学强', '{MOD}', ''),
(762, 'admin', 0, '张军', '{MOD}', ''),
(763, 'admin', 0, '张纪南', '{MOD}', ''),
(764, 'admin', 0, '屈万祥', '{MOD}', ''),
(765, 'admin', 0, '蔡继华', '{MOD}', ''),
(766, 'admin', 0, '王伟', '{MOD}', ''),
(767, 'admin', 0, '于起龙', '{MOD}', ''),
(768, 'admin', 0, '马志鹏', '{MOD}', ''),
(769, 'admin', 0, '王为璐', '{MOD}', ''),
(770, 'admin', 0, '王正福', '{MOD}', ''),
(771, 'admin', 0, '王立英', '{MOD}', ''),
(772, 'admin', 0, '王华庆', '{MOD}', ''),
(773, 'admin', 0, '王寿祥', '{MOD}', ''),
(774, 'admin', 0, '王忠民', '{MOD}', ''),
(775, 'admin', 0, '王和民', '{MOD}', ''),
(776, 'admin', 0, '王俊莲', '{MOD}', ''),
(777, 'admin', 0, '王洪章', '{MOD}', ''),
(778, 'admin', 0, '王莉莉', '{MOD}', ''),
(779, 'admin', 0, '支树平', '{MOD}', ''),
(780, 'admin', 0, '仁青加', '{MOD}', ''),
(781, 'admin', 0, '仇保兴', '{MOD}', ''),
(782, 'admin', 0, '勾清明', '{MOD}', ''),
(783, 'admin', 0, '巴特尔', '{MOD}', ''),
(784, 'admin', 0, '邓天生', '{MOD}', ''),
(785, 'admin', 0, '叶青纯', '{MOD}', ''),
(786, 'admin', 0, '田力普', '{MOD}', ''),
(787, 'admin', 0, '冯寿淼', '{MOD}', ''),
(788, 'admin', 0, '年福纯', '{MOD}', ''),
(789, 'admin', 0, '朱明国', '{MOD}', ''),
(790, 'admin', 0, '朱保成', '{MOD}', ''),
(791, 'admin', 0, '刘玉亭', '{MOD}', ''),
(792, 'admin', 0, '刘春良', '{MOD}', ''),
(793, 'admin', 0, '刘晓榕', '{MOD}', ''),
(794, 'admin', 0, '安立敏', '{MOD}', ''),
(795, 'admin', 0, '许云昭', '{MOD}', ''),
(796, 'admin', 0, '许达哲', '{MOD}', ''),
(797, 'admin', 0, '孙宝树', '{MOD}', ''),
(798, 'admin', 0, '孙思敬', '{MOD}', ''),
(799, 'admin', 0, '杜鹃', '{MOD}', ''),
(800, 'admin', 0, '杜恒岩', '{MOD}', ''),
(801, 'admin', 0, '李刚', '{MOD}', ''),
(802, 'admin', 0, '李熙', '{MOD}', ''),
(803, 'admin', 0, '李小雪', '{MOD}', ''),
(804, 'admin', 0, '李立国', '{MOD}', ''),
(805, 'admin', 0, '李汉柏', '{MOD}', ''),
(806, 'admin', 0, '李延芝', '{MOD}', ''),
(807, 'admin', 0, '李金章', '{MOD}', ''),
(808, 'admin', 0, '李法泉', '{MOD}', ''),
(809, 'admin', 0, '李适时', '{MOD}', ''),
(810, 'admin', 0, '李清印', '{MOD}', ''),
(811, 'admin', 0, '杨士秋', '{MOD}', ''),
(812, 'admin', 0, '杨传升', '{MOD}', ''),
(813, 'admin', 0, '杨利民', '{MOD}', ''),
(814, 'admin', 0, '杨建亭', '{MOD}', ''),
(815, 'admin', 0, '沈德咏', '{MOD}', ''),
(816, 'admin', 0, '宋育英', '{MOD}', ''),
(817, 'admin', 0, '张汝成', '{MOD}', ''),
(818, 'admin', 0, '张建平', '{MOD}', ''),
(819, 'admin', 0, '张研农', '{MOD}', ''),
(820, 'admin', 0, '张铁健', '{MOD}', ''),
(821, 'admin', 0, '陈希', '{MOD}', ''),
(822, 'admin', 0, '陈文清', '{MOD}', ''),
(823, 'admin', 0, '陈训秋', '{MOD}', ''),
(824, 'admin', 0, '陈际瓦', '{MOD}', ''),
(825, 'admin', 0, '陈新权', '{MOD}', ''),
(826, 'admin', 0, '陈冀平', '{MOD}', ''),
(827, 'admin', 0, '邵明立', '{MOD}', ''),
(828, 'admin', 0, '邵琪伟', '{MOD}', ''),
(829, 'admin', 0, '范印华', '{MOD}', ''),
(830, 'admin', 0, '欧泽高', '{MOD}', ''),
(831, 'admin', 0, '尚勇', '{MOD}', ''),
(832, 'admin', 0, '金书波', '{MOD}', ''),
(833, 'admin', 0, '金道铭', '{MOD}', ''),
(834, 'admin', 0, '项宗西', '{MOD}', ''),
(835, 'admin', 0, '赵铁锤', '{MOD}', ''),
(836, 'admin', 0, '胡玉敏', '{MOD}', ''),
(837, 'admin', 0, '段录定', '{MOD}', ''),
(838, 'admin', 0, '祝春林', '{MOD}', ''),
(839, 'admin', 0, '姚增科', '{MOD}', ''),
(840, 'admin', 0, '贺邦靖', '{MOD}', ''),
(841, 'admin', 0, '袁贵仁', '{MOD}', ''),
(842, 'admin', 0, '徐斌', '{MOD}', ''),
(843, 'admin', 0, '徐天亮', '{MOD}', ''),
(844, 'admin', 0, '徐敬业', '{MOD}', ''),
(845, 'admin', 0, '奚国华', '{MOD}', ''),
(846, 'admin', 0, '高武生', '{MOD}', ''),
(847, 'admin', 0, '郭永平', '{MOD}', ''),
(848, 'admin', 0, '郭炎炎', '{MOD}', ''),
(849, 'admin', 0, '黄作兴', '{MOD}', ''),
(850, 'admin', 0, '曹康泰', '{MOD}', ''),
(851, 'admin', 0, '符强', '{MOD}', ''),
(852, 'admin', 0, '董君舒', '{MOD}', ''),
(853, 'admin', 0, '蒋文兰', '{MOD}', ''),
(854, 'admin', 0, '傅成玉', '{MOD}', ''),
(855, 'admin', 0, '傅雯娟', '{MOD}', ''),
(856, 'admin', 0, '解学智', '{MOD}', ''),
(857, 'admin', 0, '解振华', '{MOD}', ''),
(858, 'admin', 0, '臧胜业', '{MOD}', ''),
(859, 'admin', 0, '臧献甫', '{MOD}', ''),
(860, 'admin', 0, '雒树刚', '{MOD}', ''),
(861, 'admin', 0, '王勇', '{MOD}', ''),
(862, 'admin', 0, '刘亚洲', '{MOD}', ''),
(863, 'admin', 0, '梁光烈', '{MOD}', ''),
(864, 'admin', 0, '马凯', '{MOD}', ''),
(865, 'admin', 0, '孟建柱', '{MOD}', ''),
(866, 'admin', 0, '戴秉国', '{MOD}', ''),
(867, 'admin', 0, '路甬祥', '{MOD}', ''),
(868, 'admin', 0, '乌云其木格', '{MOD}', ''),
(869, 'admin', 0, '韩启德', '{MOD}', ''),
(870, 'admin', 0, '华建敏', '{MOD}', ''),
(871, 'admin', 0, '周铁农', '{MOD}', ''),
(872, 'admin', 0, '李建国', '{MOD}', ''),
(873, 'admin', 0, '司马义•铁力瓦尔地', '{MOD}', ''),
(874, 'admin', 0, '蒋树声', '{MOD}', ''),
(875, 'admin', 0, '陈昌智', '{MOD}', ''),
(876, 'admin', 0, '严隽琪', '{MOD}', ''),
(877, 'admin', 0, '桑国卫', '{MOD}', ''),
(878, 'admin', 0, '廖晖', '{MOD}', ''),
(879, 'admin', 0, '杜青林', '{MOD}', ''),
(880, 'admin', 0, '帕巴拉•格列朗杰', '{MOD}', ''),
(881, 'admin', 0, '白立忱', '{MOD}', ''),
(882, 'admin', 0, '陈奎元', '{MOD}', ''),
(883, 'admin', 0, '阿不来提•阿不都热西', '{MOD}', ''),
(884, 'admin', 0, '李兆焯', '{MOD}', ''),
(885, 'admin', 0, '黄孟复', '{MOD}', ''),
(886, 'admin', 0, '董建华', '{MOD}', ''),
(887, 'admin', 0, '张梅颖', '{MOD}', ''),
(888, 'admin', 0, '张榕明', '{MOD}', ''),
(889, 'admin', 0, '钱运录', '{MOD}', ''),
(890, 'admin', 0, '孙家正', '{MOD}', ''),
(891, 'admin', 0, '李金华', '{MOD}', ''),
(892, 'admin', 0, '郑万通', '{MOD}', ''),
(893, 'admin', 0, '邓朴方', '{MOD}', ''),
(894, 'admin', 0, '万钢', '{MOD}', ''),
(895, 'admin', 0, '林文漪', '{MOD}', ''),
(896, 'admin', 0, '厉无畏', '{MOD}', ''),
(897, 'admin', 0, '罗富和', '{MOD}', ''),
(898, 'admin', 0, '陈宗兴', '{MOD}', ''),
(899, 'admin', 0, '王志珍', '{MOD}', ''),
(900, 'admin', 0, '何厚铧', '{MOD}', ''),
(901, 'admin', 0, '杜德印', '{MOD}', ''),
(902, 'admin', 0, '郭金龙', '{MOD}', ''),
(903, 'admin', 0, '阳安江', '{MOD}', ''),
(904, 'admin', 0, '刘胜玉', '{MOD}', ''),
(905, 'admin', 0, '黄兴国', '{MOD}', ''),
(906, 'admin', 0, '邢元敏', '{MOD}', ''),
(907, 'admin', 0, '刘云耕', '{MOD}', ''),
(908, 'admin', 0, '韩正', '{MOD}', ''),
(909, 'admin', 0, '冯国勤', '{MOD}', ''),
(910, 'admin', 0, '陈光国', '{MOD}', ''),
(911, 'admin', 0, '黄奇帆', '{MOD}', ''),
(912, 'admin', 0, '张云川', '{MOD}', ''),
(913, 'admin', 0, '陈全国', '{MOD}', ''),
(914, 'admin', 0, '刘德旺', '{MOD}', ''),
(915, 'admin', 0, '袁纯清', '{MOD}', ''),
(916, 'admin', 0, '王君', '{MOD}', ''),
(917, 'admin', 0, '薛延忠', '{MOD}', ''),
(918, 'admin', 0, '胡春华', '{MOD}', ''),
(919, 'admin', 0, '任亚平', '{MOD}', ''),
(920, 'admin', 0, '王珉', '{MOD}', ''),
(921, 'admin', 0, '陈政高', '{MOD}', ''),
(922, 'admin', 0, '岳福洪', '{MOD}', ''),
(923, 'admin', 0, '孙政才', '{MOD}', ''),
(924, 'admin', 0, '王儒林', '{MOD}', ''),
(925, 'admin', 0, '王国发', '{MOD}', ''),
(926, 'admin', 0, '吉炳轩', '{MOD}', ''),
(927, 'admin', 0, '王宪魁', '{MOD}', ''),
(928, 'admin', 0, '王巨禄', '{MOD}', ''),
(929, 'admin', 0, '罗志军', '{MOD}', ''),
(930, 'admin', 0, '梁保华', '{MOD}', ''),
(931, 'admin', 0, '李学勇', '{MOD}', ''),
(932, 'admin', 0, '张连珍', '{MOD}', ''),
(933, 'admin', 0, '赵洪祝', '{MOD}', ''),
(934, 'admin', 0, '吕祖善', '{MOD}', ''),
(935, 'admin', 0, '乔传秀', '{MOD}', ''),
(936, 'admin', 0, '张宝顺', '{MOD}', ''),
(937, 'admin', 0, '王三运', '{MOD}', ''),
(938, 'admin', 0, '王明方', '{MOD}', ''),
(939, 'admin', 0, '孙春兰', '{MOD}', ''),
(940, 'admin', 0, '黄小晶', '{MOD}', ''),
(941, 'admin', 0, '梁绮萍', '{MOD}', ''),
(942, 'admin', 0, '苏荣', '{MOD}', ''),
(943, 'admin', 0, '吴新雄', '{MOD}', ''),
(944, 'admin', 0, '傅克诚', '{MOD}', ''),
(945, 'admin', 0, '姜异康', '{MOD}', ''),
(946, 'admin', 0, '姜大明', '{MOD}', ''),
(947, 'admin', 0, '刘伟', '{MOD}', ''),
(948, 'admin', 0, '卢展工', '{MOD}', ''),
(949, 'admin', 0, '郭庚茂', '{MOD}', ''),
(950, 'admin', 0, '叶冬松', '{MOD}', ''),
(951, 'admin', 0, '李鸿忠', '{MOD}', ''),
(952, 'admin', 0, '王国生', '{MOD}', ''),
(953, 'admin', 0, '罗清泉', '{MOD}', ''),
(954, 'admin', 0, '周强', '{MOD}', ''),
(955, 'admin', 0, '徐守盛', '{MOD}', ''),
(956, 'admin', 0, '胡彪', '{MOD}', ''),
(957, 'admin', 0, '欧广源', '{MOD}', ''),
(958, 'admin', 0, '黄华华', '{MOD}', ''),
(959, 'admin', 0, '黄龙云', '{MOD}', ''),
(960, 'admin', 0, '卫留成', '{MOD}', ''),
(961, 'admin', 0, '罗保铭', '{MOD}', ''),
(962, 'admin', 0, '钟文', '{MOD}', ''),
(963, 'admin', 0, '郭声琨', '{MOD}', ''),
(964, 'admin', 0, '马飚', '{MOD}', ''),
(965, 'admin', 0, '马铁山', '{MOD}', ''),
(966, 'admin', 0, '刘奇葆', '{MOD}', ''),
(967, 'admin', 0, '蒋巨峰', '{MOD}', ''),
(968, 'admin', 0, '陶武先', '{MOD}', ''),
(969, 'admin', 0, '栗战书', '{MOD}', ''),
(970, 'admin', 0, '赵克志', '{MOD}', ''),
(971, 'admin', 0, '白恩培', '{MOD}', ''),
(972, 'admin', 0, '秦光荣', '{MOD}', ''),
(973, 'admin', 0, '王学仁', '{MOD}', ''),
(974, 'admin', 0, '张庆黎', '{MOD}', ''),
(975, 'admin', 0, '向巴平措', '{MOD}', ''),
(976, 'admin', 0, '白玛赤林', '{MOD}', ''),
(977, 'admin', 0, '赵乐际', '{MOD}', ''),
(978, 'admin', 0, '赵正永', '{MOD}', ''),
(979, 'admin', 0, '马中平', '{MOD}', ''),
(980, 'admin', 0, '陆浩', '{MOD}', ''),
(981, 'admin', 0, '刘伟平', '{MOD}', ''),
(982, 'admin', 0, '冯健身', '{MOD}', ''),
(983, 'admin', 0, '强卫', '{MOD}', ''),
(984, 'admin', 0, '骆惠宁', '{MOD}', ''),
(985, 'admin', 0, '白玛', '{MOD}', ''),
(986, 'admin', 0, '王正伟', '{MOD}', ''),
(987, 'admin', 0, '张春贤', '{MOD}', ''),
(988, 'admin', 0, '艾力更•依明巴海', '{MOD}', ''),
(989, 'admin', 0, '努尔•白克力', '{MOD}', ''),
(990, 'admin', 0, '艾斯海提•克里木拜', '{MOD}', ''),
(991, 'admin', 0, '曾荫权', '{MOD}', ''),
(992, 'admin', 0, '曾钰成', '{MOD}', ''),
(993, 'admin', 0, '崔世安', '{MOD}', ''),
(994, 'admin', 0, '刘焯华', '{MOD}', ''),
(995, 'admin', 0, '王胜俊', '{MOD}', ''),
(996, 'admin', 0, '万鄂湘', '{MOD}', ''),
(997, 'admin', 0, '江必新', '{MOD}', ''),
(998, 'admin', 0, '熊选国', '{MOD}', ''),
(999, 'admin', 0, '南英', '{MOD}', ''),
(1000, 'admin', 0, '景汉朝', '{MOD}', ''),
(1001, 'admin', 0, '张建南', '{MOD}', ''),
(1002, 'admin', 0, '杨洁篪', '{MOD}', ''),
(1003, 'admin', 0, '张志军', '{MOD}', ''),
(1004, 'admin', 0, '吕国增', '{MOD}', ''),
(1005, 'admin', 0, '曹建明', '{MOD}', ''),
(1006, 'admin', 0, '崔天凯', '{MOD}', ''),
(1007, 'admin', 0, '傅莹', '{MOD}', ''),
(1008, 'admin', 0, '宋涛', '{MOD}', ''),
(1009, 'admin', 0, '翟隽', '{MOD}', ''),
(1010, 'admin', 0, '胡正跃', '{MOD}', ''),
(1011, 'admin', 0, '吴海龙', '{MOD}', ''),
(1012, 'admin', 0, '刘振民', '{MOD}', ''),
(1013, 'admin', 0, '程国平', '{MOD}', ''),
(1014, 'admin', 0, '张平', '{MOD}', ''),
(1015, 'admin', 0, '朱之鑫', '{MOD}', ''),
(1016, 'admin', 0, '彭森', '{MOD}', ''),
(1017, 'admin', 0, '孙志刚', '{MOD}', ''),
(1018, 'admin', 0, '徐宪平', '{MOD}', ''),
(1019, 'admin', 0, '张晓强', '{MOD}', ''),
(1020, 'admin', 0, '杜鹰', '{MOD}', ''),
(1021, 'admin', 0, '穆虹', '{MOD}', ''),
(1022, 'admin', 0, '刘铁男', '{MOD}', ''),
(1023, 'admin', 0, '苏波', '{MOD}', ''),
(1024, 'admin', 0, '王庆云', '{MOD}', ''),
(1025, 'admin', 0, '杜玉波', '{MOD}', ''),
(1026, 'admin', 0, '鲁昕', '{MOD}', ''),
(1027, 'admin', 0, '李卫红', '{MOD}', ''),
(1028, 'admin', 0, '杜占元', '{MOD}', ''),
(1029, 'admin', 0, '郝平', '{MOD}', ''),
(1030, 'admin', 0, '刘利民', '{MOD}', ''),
(1031, 'admin', 0, '顾海良', '{MOD}', ''),
(1032, 'admin', 0, '林蕙青', '{MOD}', ''),
(1033, 'admin', 0, '张来武', '{MOD}', ''),
(1034, 'admin', 0, '陈小娅', '{MOD}', ''),
(1035, 'admin', 0, '曹健林', '{MOD}', ''),
(1036, 'admin', 0, '王伟中', '{MOD}', ''),
(1037, 'admin', 0, '郭向远', '{MOD}', ''),
(1038, 'admin', 0, '王志学', '{MOD}', ''),
(1039, 'admin', 0, '苗圩', '{MOD}', ''),
(1040, 'admin', 0, '陈求发', '{MOD}', ''),
(1041, 'admin', 0, '杨学山', '{MOD}', ''),
(1042, 'admin', 0, '刘利华', '{MOD}', ''),
(1043, 'admin', 0, '姜成康', '{MOD}', ''),
(1044, 'admin', 0, '朱宏任', '{MOD}', ''),
(1045, 'admin', 0, '杨晶', '{MOD}', ''),
(1046, 'admin', 0, '杨传堂', '{MOD}', ''),
(1047, 'admin', 0, '吴仕民', '{MOD}', ''),
(1048, 'admin', 0, '丹珠昂奔', '{MOD}', ''),
(1049, 'admin', 0, '罗黎明', '{MOD}', ''),
(1050, 'admin', 0, '李小满', '{MOD}', ''),
(1051, 'admin', 0, '刘京', '{MOD}', ''),
(1052, 'admin', 0, '杨焕宁', '{MOD}', ''),
(1053, 'admin', 0, '刘金国', '{MOD}', ''),
(1054, 'admin', 0, '孟宏伟', '{MOD}', ''),
(1055, 'admin', 0, '张新枫', '{MOD}', ''),
(1056, 'admin', 0, '蔡安季', '{MOD}', ''),
(1057, 'admin', 0, '陈智敏', '{MOD}', ''),
(1058, 'admin', 0, '陈炳德', '{MOD}', ''),
(1059, 'admin', 0, '李继耐', '{MOD}', ''),
(1060, 'admin', 0, '廖锡龙', '{MOD}', ''),
(1061, 'admin', 0, '常万全', '{MOD}', ''),
(1062, 'admin', 0, '靖志远', '{MOD}', ''),
(1063, 'admin', 0, '吴胜利', '{MOD}', ''),
(1064, 'admin', 0, '许其亮', '{MOD}', ''),
(1065, 'admin', 0, '郝明金', '{MOD}', ''),
(1066, 'admin', 0, '罗平飞', '{MOD}', ''),
(1067, 'admin', 0, '姜力', '{MOD}', ''),
(1068, 'admin', 0, '窦玉沛', '{MOD}', ''),
(1069, 'admin', 0, '孙绍骋', '{MOD}', ''),
(1070, 'admin', 0, '曲淑辉', '{MOD}', ''),
(1071, 'admin', 0, '吴爱英', '{MOD}', ''),
(1072, 'admin', 0, '张苏军', '{MOD}', ''),
(1073, 'admin', 0, '郝赤勇', '{MOD}', ''),
(1074, 'admin', 0, '赵大程', '{MOD}', ''),
(1075, 'admin', 0, '韩享林', '{MOD}', ''),
(1076, 'admin', 0, '张彦珍', '{MOD}', ''),
(1077, 'admin', 0, '谢旭人', '{MOD}', ''),
(1078, 'admin', 0, '廖晓军', '{MOD}', ''),
(1079, 'admin', 0, '李勇', '{MOD}', ''),
(1080, 'admin', 0, '王军', '{MOD}', ''),
(1081, 'admin', 0, '张少春', '{MOD}', ''),
(1082, 'admin', 0, '朱光耀', '{MOD}', ''),
(1083, 'admin', 0, '刘红薇', '{MOD}', ''),
(1084, 'admin', 0, '王保安', '{MOD}', ''),
(1085, 'admin', 0, '胡静林', '{MOD}', ''),
(1086, 'admin', 0, '刘建华', '{MOD}', ''),
(1087, 'admin', 0, '尹蔚民', '{MOD}', ''),
(1088, 'admin', 0, '李智勇', '{MOD}', ''),
(1089, 'admin', 0, '杨志明', '{MOD}', ''),
(1090, 'admin', 0, '王晓初', '{MOD}', ''),
(1091, 'admin', 0, '何宪', '{MOD}', ''),
(1092, 'admin', 0, '胡晓义', '{MOD}', ''),
(1093, 'admin', 0, '信长星', '{MOD}', ''),
(1094, 'admin', 0, '张建国', '{MOD}', ''),
(1095, 'admin', 0, '袁彦鹏', '{MOD}', ''),
(1096, 'admin', 0, '徐绍史', '{MOD}', ''),
(1097, 'admin', 0, '贠小苏', '{MOD}', ''),
(1098, 'admin', 0, '徐德明', '{MOD}', ''),
(1099, 'admin', 0, '汪民', '{MOD}', ''),
(1100, 'admin', 0, '甘藏春', '{MOD}', ''),
(1101, 'admin', 0, '孙志辉', '{MOD}', ''),
(1102, 'admin', 0, '胡存智', '{MOD}', ''),
(1103, 'admin', 0, '周生贤', '{MOD}', ''),
(1104, 'admin', 0, '潘岳', '{MOD}', ''),
(1105, 'admin', 0, '张力军', '{MOD}', ''),
(1106, 'admin', 0, '吴晓青', '{MOD}', ''),
(1107, 'admin', 0, '周建', '{MOD}', ''),
(1108, 'admin', 0, '李干杰', '{MOD}', ''),
(1109, 'admin', 0, '胡保林', '{MOD}', ''),
(1110, 'admin', 0, '李盛霖', '{MOD}', ''),
(1111, 'admin', 0, '李家祥', '{MOD}', ''),
(1112, 'admin', 0, '翁孟勇', '{MOD}', ''),
(1113, 'admin', 0, '高宏峰', '{MOD}', ''),
(1114, 'admin', 0, '冯正霖', '{MOD}', ''),
(1115, 'admin', 0, '徐祖远', '{MOD}', ''),
(1116, 'admin', 0, '马军胜', '{MOD}', ''),
(1117, 'admin', 0, '陈雷', '{MOD}', ''),
(1118, 'admin', 0, '鄂竟平', '{MOD}', ''),
(1119, 'admin', 0, '董力', '{MOD}', ''),
(1120, 'admin', 0, '矫勇', '{MOD}', ''),
(1121, 'admin', 0, '周英', '{MOD}', ''),
(1122, 'admin', 0, '胡四一', '{MOD}', ''),
(1123, 'admin', 0, '刘宁', '{MOD}', ''),
(1124, 'admin', 0, '陈小江', '{MOD}', ''),
(1125, 'admin', 0, '陈德铭', '{MOD}', ''),
(1126, 'admin', 0, '高虎城', '{MOD}', ''),
(1127, 'admin', 0, '姜增伟', '{MOD}', ''),
(1128, 'admin', 0, '钟山', '{MOD}', ''),
(1129, 'admin', 0, '蒋耀平', '{MOD}', ''),
(1131, 'admin', 0, '傅自应', '{MOD}', ''),
(1132, 'admin', 0, '崇泉', '{MOD}', ''),
(1133, 'admin', 0, '王超', '{MOD}', ''),
(1134, 'admin', 0, '房爱卿', '{MOD}', ''),
(1135, 'admin', 0, '仇鸿', '{MOD}', ''),
(1136, 'admin', 0, '俞建华', '{MOD}', ''),
(1137, 'admin', 0, '李荣灿', '{MOD}', ''),
(1138, 'admin', 0, '蔡武', '{MOD}', ''),
(1139, 'admin', 0, '欧阳坚', '{MOD}', ''),
(1140, 'admin', 0, '赵少华', '{MOD}', ''),
(1141, 'admin', 0, '李洪峰', '{MOD}', ''),
(1142, 'admin', 0, '杨志今', '{MOD}', ''),
(1143, 'admin', 0, '王文章', '{MOD}', ''),
(1144, 'admin', 0, '单霁翔', '{MOD}', ''),
(1145, 'admin', 0, '高树勋', '{MOD}', ''),
(1146, 'admin', 0, '陈竺', '{MOD}', ''),
(1147, 'admin', 0, '张茅', '{MOD}', ''),
(1148, 'admin', 0, '黄洁夫', '{MOD}', ''),
(1149, 'admin', 0, '王国强', '{MOD}', ''),
(1150, 'admin', 0, '马晓伟', '{MOD}', ''),
(1151, 'admin', 0, '陈啸宏', '{MOD}', ''),
(1152, 'admin', 0, '刘谦', '{MOD}', ''),
(1153, 'admin', 0, '尹力', '{MOD}', ''),
(1154, 'admin', 0, '李斌', '{MOD}', ''),
(1155, 'admin', 0, '赵白鸽', '{MOD}', ''),
(1156, 'admin', 0, '江帆', '{MOD}', ''),
(1157, 'admin', 0, '王培安', '{MOD}', ''),
(1158, 'admin', 0, '崔丽', '{MOD}', ''),
(1159, 'admin', 0, '杨玉学', '{MOD}', ''),
(1160, 'admin', 0, '席小平', '{MOD}', ''),
(1161, 'admin', 0, '周小川', '{MOD}', ''),
(1162, 'admin', 0, '胡晓炼', '{MOD}', ''),
(1163, 'admin', 0, '刘士余', '{MOD}', ''),
(1164, 'admin', 0, '马德伦', '{MOD}', ''),
(1165, 'admin', 0, '易纲', '{MOD}', ''),
(1166, 'admin', 0, '杜金富', '{MOD}', ''),
(1167, 'admin', 0, '李东荣', '{MOD}', ''),
(1168, 'admin', 0, '郭庆平', '{MOD}', ''),
(1169, 'admin', 0, '金琦', '{MOD}', ''),
(1170, 'admin', 0, '刘家义', '{MOD}', ''),
(1171, 'admin', 0, '董大胜', '{MOD}', ''),
(1172, 'admin', 0, '余效明', '{MOD}', ''),
(1173, 'admin', 0, '石爱中', '{MOD}', ''),
(1174, 'admin', 0, '孙宝厚', '{MOD}', ''),
(1175, 'admin', 0, '安国', '{MOD}', ''),
(1176, 'admin', 0, '侯凯', '{MOD}', ''),
(1177, 'admin', 0, '黄淑和', '{MOD}', ''),
(1178, 'admin', 0, '邵宁', '{MOD}', ''),
(1179, 'admin', 0, '黄丹华', '{MOD}', ''),
(1180, 'admin', 0, '金阳', '{MOD}', ''),
(1181, 'admin', 0, '孟建民', '{MOD}', ''),
(1182, 'admin', 0, '强卫东', '{MOD}', ''),
(1183, 'admin', 0, '盛光祖', '{MOD}', ''),
(1184, 'admin', 0, '李克农', '{MOD}', ''),
(1185, 'admin', 0, '王松鹤', '{MOD}', ''),
(1186, 'admin', 0, '鲁培军', '{MOD}', ''),
(1187, 'admin', 0, '吕滨', '{MOD}', ''),
(1188, 'admin', 0, '孙毅彪', '{MOD}', ''),
(1189, 'admin', 0, '肖捷', '{MOD}', ''),
(1190, 'admin', 0, '钱冠林', '{MOD}', ''),
(1191, 'admin', 0, '王力', '{MOD}', ''),
(1192, 'admin', 0, '宋兰', '{MOD}', ''),
(1193, 'admin', 0, '冯惠敏', '{MOD}', ''),
(1194, 'admin', 0, '周伯华', '{MOD}', ''),
(1195, 'admin', 0, '付双建', '{MOD}', ''),
(1196, 'admin', 0, '甘霖', '{MOD}', ''),
(1197, 'admin', 0, '王东峰', '{MOD}', ''),
(1198, 'admin', 0, '钟攸平', '{MOD}', ''),
(1199, 'admin', 0, '杨刚', '{MOD}', ''),
(1200, 'admin', 0, '蒲长城', '{MOD}', ''),
(1201, 'admin', 0, '魏传忠', '{MOD}', ''),
(1202, 'admin', 0, '刘平均', '{MOD}', ''),
(1203, 'admin', 0, '孙大伟', '{MOD}', ''),
(1204, 'admin', 0, '王炜', '{MOD}', ''),
(1205, 'admin', 0, '纪正昆', '{MOD}', ''),
(1206, 'admin', 0, '张沁荣', '{MOD}', ''),
(1207, 'admin', 0, '张纲', '{MOD}', ''),
(1208, 'admin', 0, '项玉章', '{MOD}', ''),
(1209, 'admin', 0, '蔡赴朝', '{MOD}', ''),
(1210, 'admin', 0, '张海涛', '{MOD}', ''),
(1211, 'admin', 0, '田进', '{MOD}', ''),
(1212, 'admin', 0, '张丕民', '{MOD}', ''),
(1213, 'admin', 0, '李伟', '{MOD}', ''),
(1214, 'admin', 0, '焦利', '{MOD}', ''),
(1215, 'admin', 0, '王庚年', '{MOD}', ''),
(1216, 'admin', 0, '王求', '{MOD}', ''),
(1217, 'admin', 0, '柳斌杰', '{MOD}', ''),
(1218, 'admin', 0, '蒋建国', '{MOD}', ''),
(1219, 'admin', 0, '李东东', '{MOD}', ''),
(1220, 'admin', 0, '邬书林', '{MOD}', ''),
(1221, 'admin', 0, '阎晓宏', '{MOD}', ''),
(1222, 'admin', 0, '孙寿山', '{MOD}', ''),
(1223, 'admin', 0, '宋明昌', '{MOD}', ''),
(1224, 'admin', 0, '于再清', '{MOD}', ''),
(1225, 'admin', 0, '段世杰', '{MOD}', ''),
(1226, 'admin', 0, '杨树安', '{MOD}', ''),
(1227, 'admin', 0, '冯建中', '{MOD}', ''),
(1228, 'admin', 0, '肖天', '{MOD}', ''),
(1229, 'admin', 0, '蔡振华', '{MOD}', ''),
(1230, 'admin', 0, '吴齐', '{MOD}', ''),
(1231, 'admin', 0, '骆琳', '{MOD}', ''),
(1232, 'admin', 0, '杨元元', '{MOD}', ''),
(1233, 'admin', 0, '王德学', '{MOD}', ''),
(1234, 'admin', 0, '孙华山', '{MOD}', ''),
(1235, 'admin', 0, '梁嘉琨', '{MOD}', ''),
(1236, 'admin', 0, '周福启', '{MOD}', ''),
(1237, 'admin', 0, '黄毅', '{MOD}', ''),
(1238, 'admin', 0, '付建华', '{MOD}', ''),
(1239, 'admin', 0, '王树鹤', '{MOD}', ''),
(1240, 'admin', 0, '彭建勋', '{MOD}', ''),
(1241, 'admin', 0, '黄玉治', '{MOD}', ''),
(1242, 'admin', 0, '马建堂', '{MOD}', ''),
(1243, 'admin', 0, '张为民', '{MOD}', ''),
(1244, 'admin', 0, '罗兰', '{MOD}', ''),
(1245, 'admin', 0, '谢鸿光', '{MOD}', ''),
(1246, 'admin', 0, '许宪春', '{MOD}', ''),
(1247, 'admin', 0, '李强', '{MOD}', ''),
(1248, 'admin', 0, '郑京平', '{MOD}', ''),
(1249, 'admin', 0, '徐一帆', '{MOD}', ''),
(1250, 'admin', 0, '贾治邦', '{MOD}', ''),
(1251, 'admin', 0, '祝列克', '{MOD}', ''),
(1252, 'admin', 0, '张建龙', '{MOD}', ''),
(1253, 'admin', 0, '印红', '{MOD}', ''),
(1254, 'admin', 0, '孙扎根', '{MOD}', ''),
(1255, 'admin', 0, '陈述贤', '{MOD}', ''),
(1256, 'admin', 0, '张永利', '{MOD}', ''),
(1257, 'admin', 0, '李玉光', '{MOD}', ''),
(1258, 'admin', 0, '贺化', '{MOD}', ''),
(1259, 'admin', 0, '杨铁军', '{MOD}', ''),
(1260, 'admin', 0, '肖兴威', '{MOD}', ''),
(1261, 'admin', 0, '鲍红', '{MOD}', ''),
(1262, 'admin', 0, '甘绍宁', '{MOD}', ''),
(1263, 'admin', 0, '杜一力', '{MOD}', ''),
(1264, 'admin', 0, '王志发', '{MOD}', ''),
(1265, 'admin', 0, '杜江', '{MOD}', ''),
(1266, 'admin', 0, '祝善忠', '{MOD}', ''),
(1267, 'admin', 0, '吴文学', '{MOD}', ''),
(1268, 'admin', 0, '王作安', '{MOD}', ''),
(1269, 'admin', 0, '齐晓飞', '{MOD}', ''),
(1270, 'admin', 0, '蒋永坚', '{MOD}', ''),
(1271, 'admin', 0, '张乐斌', '{MOD}', ''),
(1272, 'admin', 0, '陈进玉', '{MOD}', ''),
(1273, 'admin', 0, '陈鹤良', '{MOD}', ''),
(1274, 'admin', 0, '方宁', '{MOD}', ''),
(1275, 'admin', 0, '王明明', '{MOD}', ''),
(1276, 'admin', 0, '焦焕成', '{MOD}', ''),
(1277, 'admin', 0, '高翔', '{MOD}', ''),
(1278, 'admin', 0, '鉴保卫', '{MOD}', ''),
(1279, 'admin', 0, '李宝荣', '{MOD}', ''),
(1280, 'admin', 0, '尚晓汀', '{MOD}', '');
INSERT INTO `pre_common_word` (`id`, `admin`, `type`, `find`, `replacement`, `extra`) VALUES
(1281, 'admin', 0, '于永水', '{MOD}', ''),
(1282, 'admin', 0, '李海峰', '{MOD}', ''),
(1283, 'admin', 0, '赵阳', '{MOD}', ''),
(1284, 'admin', 0, '许又声', '{MOD}', ''),
(1285, 'admin', 0, '马儒沛', '{MOD}', ''),
(1286, 'admin', 0, '任启亮', '{MOD}', ''),
(1287, 'admin', 0, '宋大涵', '{MOD}', ''),
(1288, 'admin', 0, '安建', '{MOD}', ''),
(1289, 'admin', 0, '袁曙宏', '{MOD}', ''),
(1290, 'admin', 0, '郜风涛', '{MOD}', ''),
(1291, 'admin', 0, '胡可明', '{MOD}', ''),
(1292, 'admin', 0, '白春礼', '{MOD}', ''),
(1293, 'admin', 0, '江绵恒', '{MOD}', ''),
(1294, 'admin', 0, '施尔畏', '{MOD}', ''),
(1295, 'admin', 0, '李家洋', '{MOD}', ''),
(1296, 'admin', 0, '李静海', '{MOD}', ''),
(1297, 'admin', 0, '詹文龙', '{MOD}', ''),
(1298, 'admin', 0, '丁仲礼', '{MOD}', ''),
(1299, 'admin', 0, '阴和俊', '{MOD}', ''),
(1300, 'admin', 0, '方新', '{MOD}', ''),
(1301, 'admin', 0, '李志刚', '{MOD}', ''),
(1302, 'admin', 0, '邓麦村', '{MOD}', ''),
(1303, 'admin', 0, '何岩', '{MOD}', ''),
(1304, 'admin', 0, '曹效业', '{MOD}', ''),
(1305, 'admin', 0, '谭铁牛', '{MOD}', ''),
(1306, 'admin', 0, '潘教峰', '{MOD}', ''),
(1307, 'admin', 0, '邓勇', '{MOD}', ''),
(1308, 'admin', 0, '周济', '{MOD}', ''),
(1309, 'admin', 0, '潘云鹤', '{MOD}', ''),
(1310, 'admin', 0, '旭日干', '{MOD}', ''),
(1311, 'admin', 0, '谢克昌', '{MOD}', ''),
(1312, 'admin', 0, '干勇', '{MOD}', ''),
(1313, 'admin', 0, '樊代明', '{MOD}', ''),
(1314, 'admin', 0, '张玉台', '{MOD}', ''),
(1315, 'admin', 0, '刘世锦', '{MOD}', ''),
(1316, 'admin', 0, '侯云春', '{MOD}', ''),
(1317, 'admin', 0, '卢中原', '{MOD}', ''),
(1318, 'admin', 0, '韩俊', '{MOD}', ''),
(1319, 'admin', 0, '何家成', '{MOD}', ''),
(1320, 'admin', 0, '洪毅', '{MOD}', ''),
(1321, 'admin', 0, '周文彰', '{MOD}', ''),
(1322, 'admin', 0, '韩康', '{MOD}', ''),
(1323, 'admin', 0, '杨文明', '{MOD}', ''),
(1324, 'admin', 0, '杨克勤', '{MOD}', ''),
(1325, 'admin', 0, '陈建民', '{MOD}', ''),
(1326, 'admin', 0, '刘玉辰', '{MOD}', ''),
(1327, 'admin', 0, '赵和平', '{MOD}', ''),
(1328, 'admin', 0, '张友民', '{MOD}', ''),
(1329, 'admin', 0, '修济刚', '{MOD}', ''),
(1330, 'admin', 0, '阴朝民', '{MOD}', ''),
(1331, 'admin', 0, '郑国光', '{MOD}', ''),
(1332, 'admin', 0, '许小峰', '{MOD}', ''),
(1333, 'admin', 0, '宇如聪', '{MOD}', ''),
(1334, 'admin', 0, '矫梅燕', '{MOD}', ''),
(1335, 'admin', 0, '刘实', '{MOD}', ''),
(1336, 'admin', 0, '于新文', '{MOD}', ''),
(1337, 'admin', 0, '刘明康', '{MOD}', ''),
(1338, 'admin', 0, '蔡鄂生', '{MOD}', ''),
(1339, 'admin', 0, '郭利根', '{MOD}', ''),
(1340, 'admin', 0, '王兆星', '{MOD}', ''),
(1341, 'admin', 0, '阎庆民', '{MOD}', ''),
(1342, 'admin', 0, '周慕冰', '{MOD}', ''),
(1343, 'admin', 0, '尚福林', '{MOD}', ''),
(1344, 'admin', 0, '桂敏杰', '{MOD}', ''),
(1345, 'admin', 0, '庄心一', '{MOD}', ''),
(1346, 'admin', 0, '姚刚', '{MOD}', ''),
(1347, 'admin', 0, '刘新华', '{MOD}', ''),
(1348, 'admin', 0, '姜洋', '{MOD}', ''),
(1349, 'admin', 0, '朱从玖', '{MOD}', ''),
(1350, 'admin', 0, '吴利军', '{MOD}', ''),
(1351, 'admin', 0, '吴定富', '{MOD}', ''),
(1352, 'admin', 0, '李克穆', '{MOD}', ''),
(1353, 'admin', 0, '魏迎宁', '{MOD}', ''),
(1354, 'admin', 0, '杨明生', '{MOD}', ''),
(1355, 'admin', 0, '周延礼', '{MOD}', ''),
(1356, 'admin', 0, '袁力', '{MOD}', ''),
(1357, 'admin', 0, '陈文辉', '{MOD}', ''),
(1358, 'admin', 0, '王旭东', '{MOD}', ''),
(1359, 'admin', 0, '史玉波', '{MOD}', ''),
(1360, 'admin', 0, '王禹民', '{MOD}', ''),
(1361, 'admin', 0, '王野平', '{MOD}', ''),
(1362, 'admin', 0, '戴相龙', '{MOD}', ''),
(1363, 'admin', 0, '孙小系', '{MOD}', ''),
(1364, 'admin', 0, '李克平', '{MOD}', ''),
(1365, 'admin', 0, '王毅', '{MOD}', ''),
(1366, 'admin', 0, '郑立中', '{MOD}', ''),
(1367, 'admin', 0, '孙亚夫', '{MOD}', ''),
(1368, 'admin', 0, '叶克冬', '{MOD}', ''),
(1369, 'admin', 0, '陈元丰', '{MOD}', ''),
(1370, 'admin', 0, '龙明彪', '{MOD}', ''),
(1371, 'admin', 0, '李亚飞', '{MOD}', ''),
(1372, 'admin', 0, '王晨', '{MOD}', ''),
(1373, 'admin', 0, '王国庆', '{MOD}', ''),
(1374, 'admin', 0, '王仲伟', '{MOD}', ''),
(1375, 'admin', 0, '钱小芊', '{MOD}', ''),
(1376, 'admin', 0, '董云虎', '{MOD}', ''),
(1377, 'admin', 0, '冯希望', '{MOD}', ''),
(1378, 'admin', 0, '杨冬权', '{MOD}', ''),
(1379, 'admin', 0, '段东升', '{MOD}', ''),
(1380, 'admin', 0, '李明华', '{MOD}', ''),
(1381, 'admin', 0, '李和平', '{MOD}', ''),
(1382, 'admin', 0, '杨继波', '{MOD}', ''),
(1383, 'admin', 0, '王学军', '{MOD}', ''),
(1384, 'admin', 0, '王石奇', '{MOD}', ''),
(1385, 'admin', 0, '许 杰', '{MOD}', ''),
(1386, 'admin', 0, '王耀东', '{MOD}', ''),
(1387, 'admin', 0, '张彭发', '{MOD}', ''),
(1388, 'admin', 0, '张恩玺', '{MOD}', ''),
(1389, 'admin', 0, '徐令义', '{MOD}', ''),
(1390, 'admin', 0, '聂振邦', '{MOD}', ''),
(1391, 'admin', 0, '郄建伟', '{MOD}', ''),
(1392, 'admin', 0, '任正晓', '{MOD}', ''),
(1393, 'admin', 0, '张桂凤', '{MOD}', ''),
(1394, 'admin', 0, '杨兵', '{MOD}', ''),
(1395, 'admin', 0, '曾丽瑛', '{MOD}', ''),
(1396, 'admin', 0, '张保振', '{MOD}', ''),
(1397, 'admin', 0, '何泽华', '{MOD}', ''),
(1398, 'admin', 0, '李克明', '{MOD}', ''),
(1399, 'admin', 0, '张辉', '{MOD}', ''),
(1400, 'admin', 0, '潘家华', '{MOD}', ''),
(1401, 'admin', 0, '李兵', '{MOD}', ''),
(1402, 'admin', 0, '孙照华', '{MOD}', ''),
(1403, 'admin', 0, '陆明', '{MOD}', ''),
(1404, 'admin', 0, '刘延国', '{MOD}', ''),
(1405, 'admin', 0, '刘赐贵', '{MOD}', ''),
(1406, 'admin', 0, '王飞', '{MOD}', ''),
(1407, 'admin', 0, '周茂平', '{MOD}', ''),
(1408, 'admin', 0, '陈连增', '{MOD}', ''),
(1409, 'admin', 0, '张宏声', '{MOD}', ''),
(1410, 'admin', 0, '王宏', '{MOD}', ''),
(1411, 'admin', 0, '李春先', '{MOD}', ''),
(1412, 'admin', 0, '王春峰', '{MOD}', ''),
(1413, 'admin', 0, '李维森', '{MOD}', ''),
(1414, 'admin', 0, '宋超智', '{MOD}', ''),
(1415, 'admin', 0, '闵宜仁', '{MOD}', ''),
(1416, 'admin', 0, '张荣久', '{MOD}', ''),
(1417, 'admin', 0, '吴兆琪', '{MOD}', ''),
(1418, 'admin', 0, '李朋德', '{MOD}', ''),
(1419, 'admin', 0, '王昌顺', '{MOD}', ''),
(1421, 'admin', 0, '夏兴华', '{MOD}', ''),
(1422, 'admin', 0, '徐建洲', '{MOD}', ''),
(1423, 'admin', 0, '苏和', '{MOD}', ''),
(1424, 'admin', 0, '王渝次', '{MOD}', ''),
(1425, 'admin', 0, '张绳华', '{MOD}', ''),
(1426, 'admin', 0, '董保华', '{MOD}', ''),
(1427, 'admin', 0, '童明康', '{MOD}', ''),
(1428, 'admin', 0, '顾玉才', '{MOD}', ''),
(1429, 'admin', 0, '宋新潮', '{MOD}', ''),
(1430, 'admin', 0, '吴浈', '{MOD}', ''),
(1431, 'admin', 0, '李东海', '{MOD}', ''),
(1432, 'admin', 0, '李继平', '{MOD}', ''),
(1433, 'admin', 0, '边振甲', '{MOD}', ''),
(1434, 'admin', 0, '吴刚', '{MOD}', ''),
(1435, 'admin', 0, '于文明', '{MOD}', ''),
(1436, 'admin', 0, '李大宁', '{MOD}', ''),
(1437, 'admin', 0, '马建中', '{MOD}', ''),
(1438, 'admin', 0, '王志勇', '{MOD}', ''),
(1439, 'admin', 0, '邓先宏', '{MOD}', ''),
(1440, 'admin', 0, '方上浦', '{MOD}', ''),
(1441, 'admin', 0, '王小奕', '{MOD}', ''),
(1442, 'admin', 0, '李超', '{MOD}', ''),
(1443, 'admin', 0, '姜伟新', '{MOD}', ''),
(1444, 'admin', 0, '陈大卫', '{MOD}', ''),
(1445, 'admin', 0, '齐骥', '{MOD}', ''),
(1446, 'admin', 0, '郭允冲', '{MOD}', ''),
(1447, 'admin', 0, '李秉仁', '{MOD}', ''),
(1448, 'admin', 0, '唐凯', '{MOD}', ''),
(1449, 'admin', 0, '韩长斌', '{MOD}', ''),
(1450, 'admin', 0, '危朝安', '{MOD}', ''),
(1451, 'admin', 0, '张桃林', '{MOD}', ''),
(1452, 'admin', 0, '牛盾', '{MOD}', ''),
(1453, 'admin', 0, '高鸿宾', '{MOD}', ''),
(1454, 'admin', 0, '陈晓华', '{MOD}', ''),
(1455, 'admin', 0, '梁田庚', '{MOD}', ''),
(1456, 'admin', 0, '张玉香', '{MOD}', ''),
(1457, 'admin', 0, '陈萌山', '{MOD}', ''),
(1458, 'admin', 0, '于康震', '{MOD}', ''),
(1459, 'admin', 0, '杨绍品', '{MOD}', ''),
(1460, 'admin', 0, '何立峰', '{MOD}', ''),
(1461, 'admin', 0, '谢建华', '{MOD}', ''),
(1462, 'admin', 0, '杨栋梁', '{MOD}', ''),
(1463, 'admin', 0, '散襄军', '{MOD}', ''),
(1464, 'admin', 0, '史莲喜', '{MOD}', ''),
(1465, 'admin', 0, '崔津渡', '{MOD}', ''),
(1466, 'admin', 0, '苟利军', '{MOD}', ''),
(1467, 'admin', 0, '段春华', '{MOD}', ''),
(1468, 'admin', 0, '只升华', '{MOD}', ''),
(1469, 'admin', 0, '张俊芳', '{MOD}', ''),
(1470, 'admin', 0, '熊建平', '{MOD}', ''),
(1471, 'admin', 0, '李文喜', '{MOD}', ''),
(1472, 'admin', 0, '王治平', '{MOD}', ''),
(1473, 'admin', 0, '任学锋', '{MOD}', ''),
(1474, 'admin', 0, '李泉山', '{MOD}', ''),
(1475, 'admin', 0, '肖怀远', '{MOD}', ''),
(1476, 'admin', 0, '张元龙', '{MOD}', ''),
(1477, 'admin', 0, '邢明军', '{MOD}', ''),
(1478, 'admin', 0, '李亚力', '{MOD}', ''),
(1479, 'admin', 0, '李润兰', '{MOD}', ''),
(1480, 'admin', 0, '王宝弟', '{MOD}', ''),
(1481, 'admin', 0, '王世新', '{MOD}', ''),
(1482, 'admin', 0, '王文华', '{MOD}', ''),
(1483, 'admin', 0, '俞海潮', '{MOD}', ''),
(1484, 'admin', 0, '陈质枫', '{MOD}', ''),
(1485, 'admin', 0, '饶子和', '{MOD}', ''),
(1486, 'admin', 0, '刘长喜', '{MOD}', ''),
(1487, 'admin', 0, '何荣林', '{MOD}', ''),
(1488, 'admin', 0, '曹小红', '{MOD}', ''),
(1489, 'admin', 0, '张大宁', '{MOD}', ''),
(1490, 'admin', 0, '田惠光', '{MOD}', ''),
(1491, 'admin', 0, '陈永川', '{MOD}', ''),
(1492, 'admin', 0, '刘琨', '{MOD}', ''),
(1493, 'admin', 0, '殷一璀', '{MOD}', ''),
(1494, 'admin', 0, '吴志明', '{MOD}', ''),
(1495, 'admin', 0, '沈红光', '{MOD}', ''),
(1496, 'admin', 0, '杨晓渡', '{MOD}', ''),
(1497, 'admin', 0, '江勤宏', '{MOD}', ''),
(1498, 'admin', 0, '杨雄', '{MOD}', ''),
(1499, 'admin', 0, '屠光绍', '{MOD}', ''),
(1500, 'admin', 0, '丁薛祥', '{MOD}', ''),
(1501, 'admin', 0, '徐麟', '{MOD}', ''),
(1502, 'admin', 0, '杨振武', '{MOD}', ''),
(1503, 'admin', 0, '周禹鹏', '{MOD}', ''),
(1504, 'admin', 0, '王培生', '{MOD}', ''),
(1505, 'admin', 0, '杨定华', '{MOD}', ''),
(1506, 'admin', 0, '蔡达峰', '{MOD}', ''),
(1507, 'admin', 0, '郑惠强', '{MOD}', ''),
(1508, 'admin', 0, '唐登杰', '{MOD}', ''),
(1509, 'admin', 0, '胡延照', '{MOD}', ''),
(1510, 'admin', 0, '艾宝俊', '{MOD}', ''),
(1511, 'admin', 0, '沈骏', '{MOD}', ''),
(1512, 'admin', 0, '沈晓明', '{MOD}', ''),
(1513, 'admin', 0, '赵雯', '{MOD}', ''),
(1514, 'admin', 0, '周太彤', '{MOD}', ''),
(1515, 'admin', 0, '王新奎', '{MOD}', ''),
(1516, 'admin', 0, '李良园', '{MOD}', ''),
(1517, 'admin', 0, '钱景林', '{MOD}', ''),
(1518, 'admin', 0, '吴幼英', '{MOD}', ''),
(1519, 'admin', 0, '周汉民', '{MOD}', ''),
(1520, 'admin', 0, '蔡威', '{MOD}', ''),
(1521, 'admin', 0, '高小玫', '{MOD}', ''),
(1522, 'admin', 0, '张轩', '{MOD}', ''),
(1523, 'admin', 0, '何事忠', '{MOD}', ''),
(1524, 'admin', 0, '马正其', '{MOD}', ''),
(1525, 'admin', 0, '范照兵', '{MOD}', ''),
(1526, 'admin', 0, '刘光磊', '{MOD}', ''),
(1527, 'admin', 0, '陈存根', '{MOD}', ''),
(1528, 'admin', 0, '翁杰明', '{MOD}', ''),
(1529, 'admin', 0, '吴政隆', '{MOD}', ''),
(1530, 'admin', 0, '梁冬春', '{MOD}', ''),
(1531, 'admin', 0, '徐鸣', '{MOD}', ''),
(1532, 'admin', 0, '余远牧', '{MOD}', ''),
(1533, 'admin', 0, '陈雅棠', '{MOD}', ''),
(1534, 'admin', 0, '胡健康', '{MOD}', ''),
(1535, 'admin', 0, '王洪华', '{MOD}', ''),
(1536, 'admin', 0, '郑洪', '{MOD}', ''),
(1537, 'admin', 0, '卢晓钟', '{MOD}', ''),
(1538, 'admin', 0, '艾智泉', '{MOD}', ''),
(1539, 'admin', 0, '童小平', '{MOD}', ''),
(1540, 'admin', 0, '谭栖伟', '{MOD}', ''),
(1541, 'admin', 0, '刘学普', '{MOD}', ''),
(1542, 'admin', 0, '凌月明', '{MOD}', ''),
(1543, 'admin', 0, '陈和平', '{MOD}', ''),
(1544, 'admin', 0, '吴家农', '{MOD}', ''),
(1545, 'admin', 0, '刘隆铸', '{MOD}', ''),
(1546, 'admin', 0, '谢小军', '{MOD}', ''),
(1547, 'admin', 0, '王孝询', '{MOD}', ''),
(1548, 'admin', 0, '于学信', '{MOD}', ''),
(1549, 'admin', 0, '彭永辉', '{MOD}', ''),
(1550, 'admin', 0, '孙甚林', '{MOD}', ''),
(1551, 'admin', 0, '杨天怡', '{MOD}', ''),
(1552, 'admin', 0, '陈贵云', '{MOD}', ''),
(1553, 'admin', 0, '王长寿', '{MOD}', ''),
(1554, 'admin', 0, '付志方', '{MOD}', ''),
(1555, 'admin', 0, '杨崇勇', '{MOD}', ''),
(1556, 'admin', 0, '赵勇', '{MOD}', ''),
(1557, 'admin', 0, '梁滨', '{MOD}', ''),
(1558, 'admin', 0, '张彦欣', '{MOD}', ''),
(1559, 'admin', 0, '刘永瑞', '{MOD}', ''),
(1560, 'admin', 0, '聂辰席', '{MOD}', ''),
(1561, 'admin', 0, '张越', '{MOD}', ''),
(1562, 'admin', 0, '景春华', '{MOD}', ''),
(1563, 'admin', 0, '柳宝全', '{MOD}', ''),
(1564, 'admin', 0, '宋长瑞', '{MOD}', ''),
(1565, 'admin', 0, '侯志奎', '{MOD}', ''),
(1566, 'admin', 0, '王增力', '{MOD}', ''),
(1567, 'admin', 0, '马兰翠', '{MOD}', ''),
(1568, 'admin', 0, '黄荣', '{MOD}', ''),
(1569, 'admin', 0, '赵曙光', '{MOD}', ''),
(1570, 'admin', 0, '宋恩华', '{MOD}', ''),
(1571, 'admin', 0, '张和', '{MOD}', ''),
(1572, 'admin', 0, '孙士彬', '{MOD}', ''),
(1573, 'admin', 0, '龙庄伟', '{MOD}', ''),
(1574, 'admin', 0, '孙瑞彬', '{MOD}', ''),
(1575, 'admin', 0, '尹亚力', '{MOD}', ''),
(1576, 'admin', 0, '高喜同', '{MOD}', ''),
(1577, 'admin', 0, '赵文鹤', '{MOD}', ''),
(1578, 'admin', 0, '王玉梅', '{MOD}', ''),
(1579, 'admin', 0, '田向利', '{MOD}', ''),
(1580, 'admin', 0, '段惠军', '{MOD}', ''),
(1581, 'admin', 0, '丛斌', '{MOD}', ''),
(1582, 'admin', 0, '孔小均', '{MOD}', ''),
(1583, 'admin', 0, '武四海', '{MOD}', ''),
(1584, 'admin', 0, '王刚', '{MOD}', ''),
(1585, 'admin', 0, '安云昉', '{MOD}', ''),
(1586, 'admin', 0, '李小鹏', '{MOD}', ''),
(1587, 'admin', 0, '胡苏平', '{MOD}', ''),
(1588, 'admin', 0, '高建民', '{MOD}', ''),
(1589, 'admin', 0, '李政文', '{MOD}', ''),
(1590, 'admin', 0, '汤涛', '{MOD}', ''),
(1591, 'admin', 0, '李兆前', '{MOD}', ''),
(1592, 'admin', 0, '陈川平', '{MOD}', ''),
(1593, 'admin', 0, '聂春玉', '{MOD}', ''),
(1594, 'admin', 0, '申联彬', '{MOD}', ''),
(1595, 'admin', 0, '杜玉林', '{MOD}', ''),
(1596, 'admin', 0, '杨安和', '{MOD}', ''),
(1597, 'admin', 0, '靳善忠', '{MOD}', ''),
(1598, 'admin', 0, '安焕晓', '{MOD}', ''),
(1599, 'admin', 0, '郭海亮', '{MOD}', ''),
(1600, 'admin', 0, '王雅安', '{MOD}', ''),
(1601, 'admin', 0, '朱明', '{MOD}', ''),
(1602, 'admin', 0, '牛仁亮', '{MOD}', ''),
(1603, 'admin', 0, '刘维佳', '{MOD}', ''),
(1604, 'admin', 0, '张建欣', '{MOD}', ''),
(1605, 'admin', 0, '任润厚', '{MOD}', ''),
(1606, 'admin', 0, '陈永奇', '{MOD}', ''),
(1607, 'admin', 0, '郭良孝', '{MOD}', ''),
(1608, 'admin', 0, '周然', '{MOD}', ''),
(1609, 'admin', 0, '李雁红', '{MOD}', ''),
(1610, 'admin', 0, '李潭生', '{MOD}', ''),
(1611, 'admin', 0, '令政策', '{MOD}', ''),
(1612, 'admin', 0, '卫小春', '{MOD}', ''),
(1613, 'admin', 0, '刘滇生', '{MOD}', ''),
(1614, 'admin', 0, '王宁', '{MOD}', ''),
(1615, 'admin', 0, '阎沁生', '{MOD}', ''),
(1616, 'admin', 0, '邢云', '{MOD}', ''),
(1617, 'admin', 0, '潘逸阳', '{MOD}', ''),
(1618, 'admin', 0, '张力', '{MOD}', ''),
(1619, 'admin', 0, '韩志然', '{MOD}', ''),
(1620, 'admin', 0, '乌兰', '{MOD}', ''),
(1621, 'admin', 0, '李佳', '{MOD}', ''),
(1622, 'admin', 0, '苻太增', '{MOD}', ''),
(1623, 'admin', 0, '王素毅', '{MOD}', ''),
(1624, 'admin', 0, '吴合春', '{MOD}', ''),
(1625, 'admin', 0, '曹征海', '{MOD}', ''),
(1626, 'admin', 0, '赵双连', '{MOD}', ''),
(1627, 'admin', 0, '连辑', '{MOD}', ''),
(1628, 'admin', 0, '郭启俊', '{MOD}', ''),
(1629, 'admin', 0, '布小林', '{MOD}', ''),
(1630, 'admin', 0, '刘新乐', '{MOD}', ''),
(1631, 'admin', 0, '赵黎平', '{MOD}', ''),
(1632, 'admin', 0, '常海', '{MOD}', ''),
(1633, 'admin', 0, '雷•额尔德尼', '{MOD}', ''),
(1634, 'admin', 0, '罗啸天', '{MOD}', ''),
(1635, 'admin', 0, '郝益东', '{MOD}', ''),
(1636, 'admin', 0, '云秀梅', '{MOD}', ''),
(1637, 'admin', 0, '柳秀', '{MOD}', ''),
(1638, 'admin', 0, '赵忠', '{MOD}', ''),
(1639, 'admin', 0, '呼尔查', '{MOD}', ''),
(1640, 'admin', 0, '杭桂林', '{MOD}', ''),
(1641, 'admin', 0, '云峰', '{MOD}', ''),
(1642, 'admin', 0, '伏来旺', '{MOD}', ''),
(1643, 'admin', 0, '韩振祥', '{MOD}', ''),
(1644, 'admin', 0, '娜仁', '{MOD}', ''),
(1645, 'admin', 0, '董恒宇', '{MOD}', ''),
(1646, 'admin', 0, '郑福田', '{MOD}', ''),
(1647, 'admin', 0, '牛广明', '{MOD}', ''),
(1648, 'admin', 0, '肖黎声', '{MOD}', ''),
(1649, 'admin', 0, '杨成旺', '{MOD}', ''),
(1650, 'admin', 0, '陈毅民', '{MOD}', ''),
(1651, 'admin', 0, '王唯众', '{MOD}', ''),
(1652, 'admin', 0, '张成寅', '{MOD}', ''),
(1653, 'admin', 0, '李峰', '{MOD}', ''),
(1654, 'admin', 0, '许卫国', '{MOD}', ''),
(1655, 'admin', 0, '曾维', '{MOD}', ''),
(1656, 'admin', 0, '徐德', '{MOD}', ''),
(1657, 'admin', 0, '龚世萍', '{MOD}', ''),
(1658, 'admin', 0, '杨新华', '{MOD}', ''),
(1659, 'admin', 0, '仲跻权', '{MOD}', ''),
(1660, 'admin', 0, '王琼', '{MOD}', ''),
(1661, 'admin', 0, '刘国强', '{MOD}', ''),
(1662, 'admin', 0, '闫丰', '{MOD}', ''),
(1663, 'admin', 0, '胡晓华', '{MOD}', ''),
(1664, 'admin', 0, '朱绍毅', '{MOD}', ''),
(1665, 'admin', 0, '李万才', '{MOD}', ''),
(1666, 'admin', 0, '滕卫平', '{MOD}', ''),
(1667, 'admin', 0, '冯韧', '{MOD}', ''),
(1668, 'admin', 0, '董万德', '{MOD}', ''),
(1669, 'admin', 0, '张行湘', '{MOD}', ''),
(1670, 'admin', 0, '张成伦', '{MOD}', ''),
(1671, 'admin', 0, '赵新良', '{MOD}', ''),
(1672, 'admin', 0, '张毓茂', '{MOD}', ''),
(1673, 'admin', 0, '姜笑琴', '{MOD}', ''),
(1674, 'admin', 0, '王植时', '{MOD}', ''),
(1675, 'admin', 0, '张传庆', '{MOD}', ''),
(1676, 'admin', 0, '贺旻', '{MOD}', ''),
(1677, 'admin', 0, '孙桂芬', '{MOD}', ''),
(1678, 'admin', 0, '金国生', '{MOD}', ''),
(1679, 'admin', 0, '张安顺', '{MOD}', ''),
(1680, 'admin', 0, '李申学', '{MOD}', ''),
(1681, 'admin', 0, '马俊清', '{MOD}', ''),
(1682, 'admin', 0, '金振吉', '{MOD}', ''),
(1683, 'admin', 0, '高广滨', '{MOD}', ''),
(1684, 'admin', 0, '荀凤栖', '{MOD}', ''),
(1685, 'admin', 0, '黄燕明', '{MOD}', ''),
(1686, 'admin', 0, '竺延风', '{MOD}', ''),
(1687, 'admin', 0, '房俐', '{MOD}', ''),
(1688, 'admin', 0, '常跃', '{MOD}', ''),
(1689, 'admin', 0, '王守臣', '{MOD}', ''),
(1690, 'admin', 0, '陈伟根', '{MOD}', ''),
(1691, 'admin', 0, '王祖继', '{MOD}', ''),
(1692, 'admin', 0, '聂文权', '{MOD}', ''),
(1693, 'admin', 0, '刘润璞', '{MOD}', ''),
(1694, 'admin', 0, '包秦', '{MOD}', ''),
(1695, 'admin', 0, '杨绍明', '{MOD}', ''),
(1696, 'admin', 0, '车秀兰', '{MOD}', ''),
(1697, 'admin', 0, '周化辰', '{MOD}', ''),
(1698, 'admin', 0, '王云岫', '{MOD}', ''),
(1699, 'admin', 0, '王化文', '{MOD}', ''),
(1700, 'admin', 0, '陈伦', '{MOD}', ''),
(1701, 'admin', 0, '林炎志', '{MOD}', ''),
(1702, 'admin', 0, '别胜学', '{MOD}', ''),
(1703, 'admin', 0, '徐学海', '{MOD}', ''),
(1704, 'admin', 0, '常显玉', '{MOD}', ''),
(1705, 'admin', 0, '任凤霞', '{MOD}', ''),
(1706, 'admin', 0, '薛康', '{MOD}', ''),
(1707, 'admin', 0, '赵吉光', '{MOD}', ''),
(1708, 'admin', 0, '支建华', '{MOD}', ''),
(1709, 'admin', 0, '王尔智', '{MOD}', ''),
(1710, 'admin', 0, '杜宇新', '{MOD}', ''),
(1711, 'admin', 0, '杜家毫', '{MOD}', ''),
(1712, 'admin', 0, '盖如垠', '{MOD}', ''),
(1713, 'admin', 0, '刘国中', '{MOD}', ''),
(1714, 'admin', 0, '赵克非', '{MOD}', ''),
(1715, 'admin', 0, '黄建盛', '{MOD}', ''),
(1716, 'admin', 0, '宋凤鸣', '{MOD}', ''),
(1717, 'admin', 0, '徐泽洲', '{MOD}', ''),
(1718, 'admin', 0, '张效廉', '{MOD}', ''),
(1719, 'admin', 0, '韩学键', '{MOD}', ''),
(1720, 'admin', 0, '程幼东', '{MOD}', ''),
(1721, 'admin', 0, '孙尧', '{MOD}', ''),
(1722, 'admin', 0, '吕维峰', '{MOD}', ''),
(1723, 'admin', 0, '于莎燕', '{MOD}', ''),
(1724, 'admin', 0, '孙永波', '{MOD}', ''),
(1725, 'admin', 0, '徐广国', '{MOD}', ''),
(1726, 'admin', 0, '李海涛', '{MOD}', ''),
(1727, 'admin', 0, '孔令学', '{MOD}', ''),
(1728, 'admin', 0, '赵杰', '{MOD}', ''),
(1729, 'admin', 0, '刘东辉', '{MOD}', ''),
(1730, 'admin', 0, '王东华', '{MOD}', ''),
(1731, 'admin', 0, '陈述涛', '{MOD}', ''),
(1732, 'admin', 0, '符凤春', '{MOD}', ''),
(1733, 'admin', 0, '胡世英', '{MOD}', ''),
(1734, 'admin', 0, '申立国', '{MOD}', ''),
(1735, 'admin', 0, '刘海生', '{MOD}', ''),
(1736, 'admin', 0, '王利民', '{MOD}', ''),
(1737, 'admin', 0, '王涛志', '{MOD}', ''),
(1738, 'admin', 0, '何小平', '{MOD}', ''),
(1739, 'admin', 0, '洪袁舒', '{MOD}', ''),
(1740, 'admin', 0, '赵雨森', '{MOD}', ''),
(1741, 'admin', 0, '陶夏新', '{MOD}', ''),
(1742, 'admin', 0, '孙东生', '{MOD}', ''),
(1743, 'admin', 0, '李继纯', '{MOD}', ''),
(1744, 'admin', 0, '曾玉康', '{MOD}', ''),
(1745, 'admin', 0, '郭晓华', '{MOD}', ''),
(1746, 'admin', 0, '张成秀', '{MOD}', ''),
(1747, 'admin', 0, '朱善璐', '{MOD}', ''),
(1748, 'admin', 0, '石泰峰', '{MOD}', ''),
(1749, 'admin', 0, '弘强', '{MOD}', ''),
(1750, 'admin', 0, '李云峰', '{MOD}', ''),
(1751, 'admin', 0, '杨卫泽', '{MOD}', ''),
(1752, 'admin', 0, '杨新力', '{MOD}', ''),
(1753, 'admin', 0, '黄莉新', '{MOD}', ''),
(1754, 'admin', 0, '李笃信', '{MOD}', ''),
(1755, 'admin', 0, '蒋宏坤', '{MOD}', ''),
(1756, 'admin', 0, '李小敏', '{MOD}', ''),
(1757, 'admin', 0, '张卫国', '{MOD}', ''),
(1758, 'admin', 0, '何权', '{MOD}', ''),
(1759, 'admin', 0, '史和平', '{MOD}', ''),
(1760, 'admin', 0, '曹卫星', '{MOD}', ''),
(1761, 'admin', 0, '徐南平', '{MOD}', ''),
(1762, 'admin', 0, '樊金龙', '{MOD}', ''),
(1763, 'admin', 0, '周珉', '{MOD}', ''),
(1764, 'admin', 0, '张九汉', '{MOD}', ''),
(1765, 'admin', 0, '陈凌孚', '{MOD}', ''),
(1766, 'admin', 0, '黄因慧', '{MOD}', ''),
(1767, 'admin', 0, '陈宝田', '{MOD}', ''),
(1768, 'admin', 0, '包国新', '{MOD}', ''),
(1769, 'admin', 0, '程崇庆', '{MOD}', ''),
(1770, 'admin', 0, '周健民', '{MOD}', ''),
(1771, 'admin', 0, '刘立仁', '{MOD}', ''),
(1772, 'admin', 0, '李全林', '{MOD}', ''),
(1773, 'admin', 0, '柏苏宁', '{MOD}', ''),
(1774, 'admin', 0, '张艳', '{MOD}', ''),
(1775, 'admin', 0, '赵龙', '{MOD}', ''),
(1776, 'admin', 0, '丁解民', '{MOD}', ''),
(1777, 'admin', 0, '朱龙生', '{MOD}', ''),
(1778, 'admin', 0, '仇中文', '{MOD}', ''),
(1779, 'admin', 0, '夏宝龙', '{MOD}', ''),
(1780, 'admin', 0, '任泽民', '{MOD}', ''),
(1781, 'admin', 0, '陈敏尔', '{MOD}', ''),
(1782, 'admin', 0, '王辉忠', '{MOD}', ''),
(1783, 'admin', 0, '黄坤明', '{MOD}', ''),
(1784, 'admin', 0, '葛慧君', '{MOD}', ''),
(1785, 'admin', 0, '茅临生', '{MOD}', ''),
(1786, 'admin', 0, '蔡奇', '{MOD}', ''),
(1787, 'admin', 0, '林恺俊', '{MOD}', ''),
(1788, 'admin', 0, '陈加元', '{MOD}', ''),
(1789, 'admin', 0, '龚正', '{MOD}', ''),
(1790, 'admin', 0, '毛光烈', '{MOD}', ''),
(1791, 'admin', 0, '王建满', '{MOD}', ''),
(1792, 'admin', 0, '郑继伟', '{MOD}', ''),
(1793, 'admin', 0, '陈德荣', '{MOD}', ''),
(1794, 'admin', 0, '张鸿铭', '{MOD}', ''),
(1795, 'admin', 0, '王永明', '{MOD}', ''),
(1796, 'admin', 0, '吴国华', '{MOD}', ''),
(1797, 'admin', 0, '程渭山', '{MOD}', ''),
(1798, 'admin', 0, '姚民声', '{MOD}', ''),
(1799, 'admin', 0, '金德水', '{MOD}', ''),
(1800, 'admin', 0, '厉志海', '{MOD}', ''),
(1801, 'admin', 0, '盛昌黎', '{MOD}', ''),
(1802, 'admin', 0, '徐冠巨', '{MOD}', ''),
(1803, 'admin', 0, '王永昌', '{MOD}', ''),
(1804, 'admin', 0, '陈艳华', '{MOD}', ''),
(1805, 'admin', 0, '黄旭明', '{MOD}', ''),
(1806, 'admin', 0, '徐辉', '{MOD}', ''),
(1807, 'admin', 0, '姚克', '{MOD}', ''),
(1808, 'admin', 0, '冯明光', '{MOD}', ''),
(1809, 'admin', 0, '孙金龙', '{MOD}', ''),
(1810, 'admin', 0, '段敦厚', '{MOD}', ''),
(1811, 'admin', 0, '余欣荣', '{MOD}', ''),
(1812, 'admin', 0, '徐立全', '{MOD}', ''),
(1813, 'admin', 0, '臧世凯', '{MOD}', ''),
(1814, 'admin', 0, '王宾宜', '{MOD}', ''),
(1815, 'admin', 0, '詹夏来', '{MOD}', ''),
(1816, 'admin', 0, '王秀芳', '{MOD}', ''),
(1817, 'admin', 0, '文可芝', '{MOD}', ''),
(1818, 'admin', 0, '黄海嵩', '{MOD}', ''),
(1819, 'admin', 0, '唐承沛', '{MOD}', ''),
(1820, 'admin', 0, '倪发科', '{MOD}', ''),
(1821, 'admin', 0, '谢广祥', '{MOD}', ''),
(1822, 'admin', 0, '花建慧', '{MOD}', ''),
(1823, 'admin', 0, '梁卫国', '{MOD}', ''),
(1824, 'admin', 0, '任海深', '{MOD}', ''),
(1825, 'admin', 0, '文海英', '{MOD}', ''),
(1826, 'admin', 0, '胡连松', '{MOD}', ''),
(1827, 'admin', 0, '朱先发', '{MOD}', ''),
(1828, 'admin', 0, '郭万清', '{MOD}', ''),
(1829, 'admin', 0, '朱维芳', '{MOD}', ''),
(1830, 'admin', 0, '张俊', '{MOD}', ''),
(1831, 'admin', 0, '汪国才', '{MOD}', ''),
(1832, 'admin', 0, '田维谦', '{MOD}', ''),
(1833, 'admin', 0, '郑牧民', '{MOD}', ''),
(1834, 'admin', 0, '王鹤龄', '{MOD}', ''),
(1835, 'admin', 0, '刘光复', '{MOD}', ''),
(1836, 'admin', 0, '张学平', '{MOD}', ''),
(1837, 'admin', 0, '沈素琍', '{MOD}', ''),
(1838, 'admin', 0, '李宏塔', '{MOD}', ''),
(1839, 'admin', 0, '赵韩', '{MOD}', ''),
(1840, 'admin', 0, '李卫华', '{MOD}', ''),
(1841, 'admin', 0, '王启敏', '{MOD}', ''),
(1842, 'admin', 0, '苏树林', '{MOD}', ''),
(1843, 'admin', 0, '朱生岭', '{MOD}', ''),
(1844, 'admin', 0, '张昌平', '{MOD}', ''),
(1845, 'admin', 0, '袁荣祥', '{MOD}', ''),
(1846, 'admin', 0, '唐国忠', '{MOD}', ''),
(1847, 'admin', 0, '杨岳', '{MOD}', ''),
(1848, 'admin', 0, '于伟国', '{MOD}', ''),
(1849, 'admin', 0, '陈桦', '{MOD}', ''),
(1850, 'admin', 0, '姜信治', '{MOD}', ''),
(1851, 'admin', 0, '徐谦', '{MOD}', ''),
(1852, 'admin', 0, '王美香', '{MOD}', ''),
(1853, 'admin', 0, '袁锦贵', '{MOD}', ''),
(1854, 'admin', 0, '庄先', '{MOD}', ''),
(1855, 'admin', 0, '马潞生', '{MOD}', ''),
(1856, 'admin', 0, '张广敏', '{MOD}', ''),
(1857, 'admin', 0, '叶双瑜', '{MOD}', ''),
(1858, 'admin', 0, '苏增添', '{MOD}', ''),
(1859, 'admin', 0, '张志南', '{MOD}', ''),
(1860, 'admin', 0, '倪岳峰', '{MOD}', ''),
(1861, 'admin', 0, '洪捷序', '{MOD}', ''),
(1862, 'admin', 0, '张燮飞', '{MOD}', ''),
(1863, 'admin', 0, '叶家松', '{MOD}', ''),
(1864, 'admin', 0, '叶继革', '{MOD}', ''),
(1865, 'admin', 0, '郭振家', '{MOD}', ''),
(1866, 'admin', 0, '邓力平', '{MOD}', ''),
(1867, 'admin', 0, '鹿心社', '{MOD}', ''),
(1868, 'admin', 0, '张裔炯', '{MOD}', ''),
(1869, 'admin', 0, '陈达恒', '{MOD}', ''),
(1870, 'admin', 0, '刘上洋', '{MOD}', ''),
(1871, 'admin', 0, '舒晓琴', '{MOD}', ''),
(1872, 'admin', 0, '凌成兴', '{MOD}', ''),
(1873, 'admin', 0, '赵智勇', '{MOD}', ''),
(1874, 'admin', 0, '莫建成', '{MOD}', ''),
(1875, 'admin', 0, '郑水成', '{MOD}', ''),
(1876, 'admin', 0, '史文清', '{MOD}', ''),
(1877, 'admin', 0, '王文涛', '{MOD}', ''),
(1878, 'admin', 0, '孙刚', '{MOD}', ''),
(1879, 'admin', 0, '熊盛文', '{MOD}', ''),
(1880, 'admin', 0, '洪礼和', '{MOD}', ''),
(1881, 'admin', 0, '谢茹', '{MOD}', ''),
(1882, 'admin', 0, '朱虹', '{MOD}', ''),
(1883, 'admin', 0, '姚木根', '{MOD}', ''),
(1884, 'admin', 0, '胡幼桃', '{MOD}', ''),
(1885, 'admin', 0, '谭晓林', '{MOD}', ''),
(1886, 'admin', 0, '胡振鹏', '{MOD}', ''),
(1887, 'admin', 0, '姚亚平', '{MOD}', ''),
(1888, 'admin', 0, '魏小琴', '{MOD}', ''),
(1889, 'admin', 0, '陈安众', '{MOD}', ''),
(1890, 'admin', 0, '朱秉发', '{MOD}', ''),
(1891, 'admin', 0, '魏民', '{MOD}', ''),
(1892, 'admin', 0, '朱张才', '{MOD}', ''),
(1893, 'admin', 0, '汤建人', '{MOD}', ''),
(1894, 'admin', 0, '刘晓庄', '{MOD}', ''),
(1895, 'admin', 0, '郑小燕', '{MOD}', ''),
(1896, 'admin', 0, '李华栋', '{MOD}', ''),
(1897, 'admin', 0, '肖光明', '{MOD}', ''),
(1898, 'admin', 0, '王仁元', '{MOD}', ''),
(1899, 'admin', 0, '王军民', '{MOD}', ''),
(1900, 'admin', 0, '焉荣竹', '{MOD}', ''),
(1901, 'admin', 0, '王敏', '{MOD}', ''),
(1902, 'admin', 0, '柏继民', '{MOD}', ''),
(1903, 'admin', 0, '南兵军', '{MOD}', ''),
(1904, 'admin', 0, '李群', '{MOD}', ''),
(1905, 'admin', 0, '高晓兵', '{MOD}', ''),
(1906, 'admin', 0, '孙守刚', '{MOD}', ''),
(1907, 'admin', 0, '孙伟', '{MOD}', ''),
(1908, 'admin', 0, '才利民', '{MOD}', ''),
(1909, 'admin', 0, '贾万志', '{MOD}', ''),
(1910, 'admin', 0, '黄胜', '{MOD}', ''),
(1911, 'admin', 0, '郭兆信', '{MOD}', ''),
(1912, 'admin', 0, '王随莲', '{MOD}', ''),
(1913, 'admin', 0, '鲍志强', '{MOD}', ''),
(1914, 'admin', 0, '崔曰臣', '{MOD}', ''),
(1915, 'admin', 0, '刘玉功', '{MOD}', ''),
(1916, 'admin', 0, '温孚江', '{MOD}', ''),
(1917, 'admin', 0, '连承敏', '{MOD}', ''),
(1918, 'admin', 0, '尹慧敏', '{MOD}', ''),
(1919, 'admin', 0, '乔延春', '{MOD}', ''),
(1920, 'admin', 0, '齐乃贵', '{MOD}', ''),
(1921, 'admin', 0, '王志民', '{MOD}', ''),
(1922, 'admin', 0, '赵玉兰', '{MOD}', ''),
(1923, 'admin', 0, '张传林', '{MOD}', ''),
(1924, 'admin', 0, '李德强', '{MOD}', ''),
(1925, 'admin', 0, '栗甲', '{MOD}', ''),
(1926, 'admin', 0, '王新陆', '{MOD}', ''),
(1927, 'admin', 0, '王乃静', '{MOD}', ''),
(1928, 'admin', 0, '李克', '{MOD}', ''),
(1929, 'admin', 0, '孔玉芳', '{MOD}', ''),
(1930, 'admin', 0, '李新民', '{MOD}', ''),
(1931, 'admin', 0, '刘怀廉', '{MOD}', ''),
(1932, 'admin', 0, '连维良', '{MOD}', ''),
(1933, 'admin', 0, '颜纪雄', '{MOD}', ''),
(1934, 'admin', 0, '尹晋华', '{MOD}', ''),
(1935, 'admin', 0, '毛万春', '{MOD}', ''),
(1937, 'admin', 0, '史济春', '{MOD}', ''),
(1938, 'admin', 0, '秦玉海', '{MOD}', ''),
(1939, 'admin', 0, '张大卫', '{MOD}', ''),
(1940, 'admin', 0, '徐济超', '{MOD}', ''),
(1941, 'admin', 0, '刘满仓', '{MOD}', ''),
(1942, 'admin', 0, '陈雪枫', '{MOD}', ''),
(1943, 'admin', 0, '赵建才', '{MOD}', ''),
(1944, 'admin', 0, '王菊梅', '{MOD}', ''),
(1945, 'admin', 0, '王文超', '{MOD}', ''),
(1946, 'admin', 0, '刘新民', '{MOD}', ''),
(1947, 'admin', 0, '张程锋', '{MOD}', ''),
(1948, 'admin', 0, '铁代生', '{MOD}', ''),
(1949, 'admin', 0, '储亚平', '{MOD}', ''),
(1950, 'admin', 0, '曹维新', '{MOD}', ''),
(1951, 'admin', 0, '蒋笃运', '{MOD}', ''),
(1952, 'admin', 0, '连子恒', '{MOD}', ''),
(1953, 'admin', 0, '王训智', '{MOD}', ''),
(1954, 'admin', 0, '靳绥东', '{MOD}', ''),
(1955, 'admin', 0, '邓永俭', '{MOD}', ''),
(1956, 'admin', 0, '王平', '{MOD}', ''),
(1957, 'admin', 0, '李英杰', '{MOD}', ''),
(1958, 'admin', 0, '龚立群', '{MOD}', ''),
(1959, 'admin', 0, '梁静', '{MOD}', ''),
(1960, 'admin', 0, '张亚忠', '{MOD}', ''),
(1961, 'admin', 0, '高体健', '{MOD}', ''),
(1962, 'admin', 0, '张秉义', '{MOD}', ''),
(1963, 'admin', 0, '杨松', '{MOD}', ''),
(1964, 'admin', 0, '苏晓云', '{MOD}', ''),
(1965, 'admin', 0, '张昌尔', '{MOD}', ''),
(1966, 'admin', 0, '李宪生', '{MOD}', ''),
(1967, 'admin', 0, '黄先耀', '{MOD}', ''),
(1968, 'admin', 0, '侯长安', '{MOD}', ''),
(1969, 'admin', 0, '李春明', '{MOD}', ''),
(1970, 'admin', 0, '吴永文', '{MOD}', ''),
(1971, 'admin', 0, '张岱梨', '{MOD}', ''),
(1972, 'admin', 0, '汪金玉', '{MOD}', ''),
(1973, 'admin', 0, '尹汉宁', '{MOD}', ''),
(1974, 'admin', 0, '阮成发', '{MOD}', ''),
(1975, 'admin', 0, '范锐平', '{MOD}', ''),
(1976, 'admin', 0, '郭生练', '{MOD}', ''),
(1977, 'admin', 0, '田承忠', '{MOD}', ''),
(1978, 'admin', 0, '赵斌', '{MOD}', ''),
(1979, 'admin', 0, '段轮一', '{MOD}', ''),
(1980, 'admin', 0, '张通', '{MOD}', ''),
(1981, 'admin', 0, '郭有明', '{MOD}', ''),
(1982, 'admin', 0, '刘友凡', '{MOD}', ''),
(1983, 'admin', 0, '任世茂', '{MOD}', ''),
(1984, 'admin', 0, '蒋大国', '{MOD}', ''),
(1985, 'admin', 0, '罗辉', '{MOD}', ''),
(1986, 'admin', 0, '周洪宇', '{MOD}', ''),
(1987, 'admin', 0, '林志慧', '{MOD}', ''),
(1988, 'admin', 0, '范兴元', '{MOD}', ''),
(1989, 'admin', 0, '李佑才', '{MOD}', ''),
(1990, 'admin', 0, '郑楚光', '{MOD}', ''),
(1991, 'admin', 0, '周宜开', '{MOD}', ''),
(1992, 'admin', 0, '仇小乐', '{MOD}', ''),
(1993, 'admin', 0, '吴秀凤', '{MOD}', ''),
(1994, 'admin', 0, '郑心穗', '{MOD}', ''),
(1995, 'admin', 0, '陈柏槐', '{MOD}', ''),
(1996, 'admin', 0, '涂勇', '{MOD}', ''),
(1997, 'admin', 0, '王树华', '{MOD}', ''),
(1998, 'admin', 0, '梅克保', '{MOD}', ''),
(1999, 'admin', 0, '黄建国', '{MOD}', ''),
(2000, 'admin', 0, '于来山', '{MOD}', ''),
(2001, 'admin', 0, '杨泰波', '{MOD}', ''),
(2002, 'admin', 0, '杨忠民', '{MOD}', ''),
(2003, 'admin', 0, '陈润儿', '{MOD}', ''),
(2004, 'admin', 0, '李微微', '{MOD}', ''),
(2005, 'admin', 0, '路建平', '{MOD}', ''),
(2006, 'admin', 0, '郭开朗', '{MOD}', ''),
(2007, 'admin', 0, '陈肇雄', '{MOD}', ''),
(2008, 'admin', 0, '刘力伟', '{MOD}', ''),
(2009, 'admin', 0, '徐明华', '{MOD}', ''),
(2010, 'admin', 0, '韩永文', '{MOD}', ''),
(2011, 'admin', 0, '李江', '{MOD}', ''),
(2012, 'admin', 0, '谢勇', '{MOD}', ''),
(2013, 'admin', 0, '陈叔红', '{MOD}', ''),
(2014, 'admin', 0, '蔡力峰', '{MOD}', ''),
(2015, 'admin', 0, '肖雅瑜', '{MOD}', ''),
(2016, 'admin', 0, '刘莲玉', '{MOD}', ''),
(2017, 'admin', 0, '蒋作斌', '{MOD}', ''),
(2018, 'admin', 0, '孙在田', '{MOD}', ''),
(2019, 'admin', 0, '石玉珍', '{MOD}', ''),
(2020, 'admin', 0, '袁隆平', '{MOD}', ''),
(2021, 'admin', 0, '阳宝华', '{MOD}', ''),
(2022, 'admin', 0, '王汀明', '{MOD}', ''),
(2023, 'admin', 0, '刘晓', '{MOD}', ''),
(2024, 'admin', 0, '魏文彬', '{MOD}', ''),
(2025, 'admin', 0, '谭仲池', '{MOD}', ''),
(2026, 'admin', 0, '何报翔', '{MOD}', ''),
(2027, 'admin', 0, '龚建明', '{MOD}', ''),
(2028, 'admin', 0, '武吉海', '{MOD}', ''),
(2029, 'admin', 0, '王晓琴', '{MOD}', ''),
(2030, 'admin', 0, '杨维刚', '{MOD}', ''),
(2031, 'admin', 0, '欧阳斌', '{MOD}', ''),
(2032, 'admin', 0, '朱小丹', '{MOD}', ''),
(2033, 'admin', 0, '肖志恒', '{MOD}', ''),
(2034, 'admin', 0, '王荣', '{MOD}', ''),
(2035, 'admin', 0, '李玉妹', '{MOD}', ''),
(2036, 'admin', 0, '林雄', '{MOD}', ''),
(2037, 'admin', 0, '梁伟发', '{MOD}', ''),
(2038, 'admin', 0, '周镇宏', '{MOD}', ''),
(2039, 'admin', 0, '徐少华', '{MOD}', ''),
(2040, 'admin', 0, '张广宁', '{MOD}', ''),
(2041, 'admin', 0, '刘联华', '{MOD}', ''),
(2042, 'admin', 0, '雷于蓝', '{MOD}', ''),
(2043, 'admin', 0, '宋海', '{MOD}', ''),
(2044, 'admin', 0, '林木声', '{MOD}', ''),
(2045, 'admin', 0, '刘昆', '{MOD}', ''),
(2046, 'admin', 0, '招玉芳', '{MOD}', ''),
(2047, 'admin', 0, '陈云贤', '{MOD}', ''),
(2048, 'admin', 0, '钟阳胜', '{MOD}', ''),
(2049, 'admin', 0, '王宁生', '{MOD}', ''),
(2050, 'admin', 0, '邓维龙', '{MOD}', ''),
(2051, 'admin', 0, '陈用志', '{MOD}', ''),
(2052, 'admin', 0, '陈小川', '{MOD}', ''),
(2054, 'admin', 0, '汤炳权', '{MOD}', ''),
(2055, 'admin', 0, '王珣章', '{MOD}', ''),
(2056, 'admin', 0, '周天鸿', '{MOD}', ''),
(2057, 'admin', 0, '姚志彬', '{MOD}', ''),
(2058, 'admin', 0, '温兰子', '{MOD}', ''),
(2059, 'admin', 0, '温思美', '{MOD}', ''),
(2060, 'admin', 0, '徐尚武', '{MOD}', ''),
(2061, 'admin', 0, '杨懂', '{MOD}', ''),
(2062, 'admin', 0, '于迅', '{MOD}', ''),
(2063, 'admin', 0, '蒋定之', '{MOD}', ''),
(2064, 'admin', 0, '肖若海', '{MOD}', ''),
(2065, 'admin', 0, '许俊', '{MOD}', ''),
(2066, 'admin', 0, '陈辞', '{MOD}', ''),
(2067, 'admin', 0, '楼阳生', '{MOD}', ''),
(2068, 'admin', 0, '刘鼎兴', '{MOD}', ''),
(2069, 'admin', 0, '谭力', '{MOD}', ''),
(2070, 'admin', 0, '姜斯宪', '{MOD}', ''),
(2071, 'admin', 0, '林方略', '{MOD}', ''),
(2072, 'admin', 0, '陈成', '{MOD}', ''),
(2073, 'admin', 0, '符跃兰', '{MOD}', ''),
(2074, 'admin', 0, '李国梁', '{MOD}', ''),
(2075, 'admin', 0, '李秀领', '{MOD}', ''),
(2076, 'admin', 0, '符桂花', '{MOD}', ''),
(2077, 'admin', 0, '符兴', '{MOD}', ''),
(2078, 'admin', 0, '毕志强', '{MOD}', ''),
(2079, 'admin', 0, '康耀红', '{MOD}', ''),
(2080, 'admin', 0, '陈国舜', '{MOD}', ''),
(2081, 'admin', 0, '张力夫', '{MOD}', ''),
(2082, 'admin', 0, '陈海波', '{MOD}', ''),
(2083, 'admin', 0, '张海国', '{MOD}', ''),
(2084, 'admin', 0, '邱德群', '{MOD}', ''),
(2085, 'admin', 0, '赵莉莎', '{MOD}', ''),
(2086, 'admin', 0, '王路', '{MOD}', ''),
(2087, 'admin', 0, '陈莉', '{MOD}', ''),
(2088, 'admin', 0, '王宇田', '{MOD}', ''),
(2089, 'admin', 0, '王应际', '{MOD}', ''),
(2090, 'admin', 0, '李应济', '{MOD}', ''),
(2091, 'admin', 0, '史贻云', '{MOD}', ''),
(2092, 'admin', 0, '李文潮', '{MOD}', ''),
(2093, 'admin', 0, '李金早', '{MOD}', ''),
(2094, 'admin', 0, '沈北海', '{MOD}', ''),
(2095, 'admin', 0, '车荣福', '{MOD}', ''),
(2096, 'admin', 0, '温卡华', '{MOD}', ''),
(2097, 'admin', 0, '陈武', '{MOD}', ''),
(2098, 'admin', 0, '石生龙', '{MOD}', ''),
(2099, 'admin', 0, '黄道伟', '{MOD}', ''),
(2100, 'admin', 0, '余远辉', '{MOD}', ''),
(2101, 'admin', 0, '周新建', '{MOD}', ''),
(2102, 'admin', 0, '吴恒', '{MOD}', ''),
(2103, 'admin', 0, '刘新文', '{MOD}', ''),
(2104, 'admin', 0, '莫永清', '{MOD}', ''),
(2105, 'admin', 0, '覃瑞祥', '{MOD}', ''),
(2106, 'admin', 0, '荣仕星', '{MOD}', ''),
(2107, 'admin', 0, '文明', '{MOD}', ''),
(2108, 'admin', 0, '崔智友', '{MOD}', ''),
(2109, 'admin', 0, '陈章良', '{MOD}', ''),
(2110, 'admin', 0, '杨道喜', '{MOD}', ''),
(2111, 'admin', 0, '林念修', '{MOD}', ''),
(2112, 'admin', 0, '高雄', '{MOD}', ''),
(2113, 'admin', 0, '李康', '{MOD}', ''),
(2114, 'admin', 0, '梁胜利', '{MOD}', ''),
(2115, 'admin', 0, '王跃飞', '{MOD}', ''),
(2116, 'admin', 0, '林国强', '{MOD}', ''),
(2117, 'admin', 0, '蒋济雄', '{MOD}', ''),
(2118, 'admin', 0, '李达球', '{MOD}', ''),
(2119, 'admin', 0, '蒋培兰', '{MOD}', ''),
(2120, 'admin', 0, '黄格胜', '{MOD}', ''),
(2121, 'admin', 0, '彭钊', '{MOD}', ''),
(2122, 'admin', 0, '李彬', '{MOD}', ''),
(2123, 'admin', 0, '苏道俨', '{MOD}', ''),
(2124, 'admin', 0, '李崇禧', '{MOD}', ''),
(2125, 'admin', 0, '魏宏', '{MOD}', ''),
(2126, 'admin', 0, '黄新初', '{MOD}', ''),
(2127, 'admin', 0, '柯尊平', '{MOD}', ''),
(2128, 'admin', 0, '王怀臣', '{MOD}', ''),
(2129, 'admin', 0, '钟勉', '{MOD}', ''),
(2130, 'admin', 0, '李春城', '{MOD}', ''),
(2131, 'admin', 0, '李登菊', '{MOD}', ''),
(2132, 'admin', 0, '王少雄', '{MOD}', ''),
(2133, 'admin', 0, '叶万勇', '{MOD}', ''),
(2134, 'admin', 0, '陈光志', '{MOD}', ''),
(2135, 'admin', 0, '黄小祥', '{MOD}', ''),
(2136, 'admin', 0, '黄彦蓉', '{MOD}', ''),
(2137, 'admin', 0, '张作哈', '{MOD}', ''),
(2138, 'admin', 0, '李成云', '{MOD}', ''),
(2139, 'admin', 0, '陈文华', '{MOD}', ''),
(2140, 'admin', 0, '于伟', '{MOD}', ''),
(2141, 'admin', 0, '郭永祥', '{MOD}', ''),
(2142, 'admin', 0, '张东升', '{MOD}', ''),
(2143, 'admin', 0, '王宇坤', '{MOD}', ''),
(2144, 'admin', 0, '彭渝', '{MOD}', ''),
(2145, 'admin', 0, '杨志文', '{MOD}', ''),
(2146, 'admin', 0, '晏永和', '{MOD}', ''),
(2147, 'admin', 0, '吴正德', '{MOD}', ''),
(2148, 'admin', 0, '陈杰', '{MOD}', ''),
(2149, 'admin', 0, '陈次昌', '{MOD}', ''),
(2150, 'admin', 0, '解洪', '{MOD}', ''),
(2151, 'admin', 0, '曾清华', '{MOD}', ''),
(2152, 'admin', 0, '张雨东', '{MOD}', ''),
(2153, 'admin', 0, '黄润秋', '{MOD}', ''),
(2154, 'admin', 0, '刘道平', '{MOD}', ''),
(2155, 'admin', 0, '方小方', '{MOD}', ''),
(2156, 'admin', 0, '吴果行', '{MOD}', ''),
(2157, 'admin', 0, '王富玉', '{MOD}', ''),
(2158, 'admin', 0, '王晓东', '{MOD}', ''),
(2159, 'admin', 0, '龙超云', '{MOD}', ''),
(2160, 'admin', 0, '李军', '{MOD}', ''),
(2161, 'admin', 0, '张群山', '{MOD}', ''),
(2162, 'admin', 0, '黄康生', '{MOD}', ''),
(2163, 'admin', 0, '崔亚东', '{MOD}', ''),
(2164, 'admin', 0, '谌贻琴', '{MOD}', ''),
(2165, 'admin', 0, '石晓', '{MOD}', ''),
(2166, 'admin', 0, '宋璇涛', '{MOD}', ''),
(2167, 'admin', 0, '孙永春', '{MOD}', ''),
(2168, 'admin', 0, '禄智明', '{MOD}', ''),
(2169, 'admin', 0, '蒙启良', '{MOD}', ''),
(2170, 'admin', 0, '孙国强', '{MOD}', ''),
(2171, 'admin', 0, '辛维光', '{MOD}', ''),
(2172, 'admin', 0, '刘晓凯', '{MOD}', ''),
(2173, 'admin', 0, '谢庆生', '{MOD}', ''),
(2174, 'admin', 0, '唐世礼', '{MOD}', ''),
(2175, 'admin', 0, '傅传耀', '{MOD}', ''),
(2176, 'admin', 0, '顾久', '{MOD}', ''),
(2177, 'admin', 0, '陈华祥', '{MOD}', ''),
(2178, 'admin', 0, '袁周', '{MOD}', ''),
(2179, 'admin', 0, '周忠良', '{MOD}', ''),
(2180, 'admin', 0, '刘鸿庥', '{MOD}', ''),
(2181, 'admin', 0, '陈海峰', '{MOD}', ''),
(2182, 'admin', 0, '孔令中', '{MOD}', ''),
(2183, 'admin', 0, '左定超', '{MOD}', ''),
(2184, 'admin', 0, '武鸿麟', '{MOD}', ''),
(2185, 'admin', 0, '谢晓尧', '{MOD}', ''),
(2186, 'admin', 0, '李纪恒', '{MOD}', ''),
(2187, 'admin', 0, '罗正富', '{MOD}', ''),
(2188, 'admin', 0, '杨应楠', '{MOD}', ''),
(2189, 'admin', 0, '仇和', '{MOD}', ''),
(2190, 'admin', 0, '张田欣', '{MOD}', ''),
(2191, 'admin', 0, '孟苏铁', '{MOD}', ''),
(2192, 'admin', 0, '孔垂柱', '{MOD}', ''),
(2193, 'admin', 0, '高峰', '{MOD}', ''),
(2194, 'admin', 0, '曹建方', '{MOD}', ''),
(2195, 'admin', 0, '顾朝曦', '{MOD}', ''),
(2196, 'admin', 0, '和段琪', '{MOD}', ''),
(2197, 'admin', 0, '江巴吉才', '{MOD}', ''),
(2198, 'admin', 0, '程映萱', '{MOD}', ''),
(2199, 'admin', 0, '李春林', '{MOD}', ''),
(2200, 'admin', 0, '杨建甲', '{MOD}', ''),
(2201, 'admin', 0, '杨保建', '{MOD}', ''),
(2202, 'admin', 0, '白保兴', '{MOD}', ''),
(2203, 'admin', 0, '管国忠', '{MOD}', ''),
(2204, 'admin', 0, '马开贤', '{MOD}', ''),
(2205, 'admin', 0, '曾华', '{MOD}', ''),
(2206, 'admin', 0, '罗黎辉', '{MOD}', ''),
(2207, 'admin', 0, '顾伯平', '{MOD}', ''),
(2208, 'admin', 0, '郝鹏', '{MOD}', ''),
(2209, 'admin', 0, '杨金山', '{MOD}', ''),
(2210, 'admin', 0, '巴桑顿珠', '{MOD}', ''),
(2211, 'admin', 0, '吴英杰', '{MOD}', ''),
(2212, 'admin', 0, '崔玉英', '{MOD}', ''),
(2213, 'admin', 0, '洛桑江村', '{MOD}', ''),
(2214, 'admin', 0, '尹德明', '{MOD}', ''),
(2215, 'admin', 0, '公保扎西', '{MOD}', ''),
(2216, 'admin', 0, '秦宜智', '{MOD}', ''),
(2217, 'admin', 0, '齐扎拉', '{MOD}', ''),
(2218, 'admin', 0, '多吉泽仁', '{MOD}', ''),
(2219, 'admin', 0, '德吉', '{MOD}', ''),
(2220, 'admin', 0, '丁业现', '{MOD}', ''),
(2221, 'admin', 0, '格桑次仁', '{MOD}', ''),
(2222, 'admin', 0, '董明俊', '{MOD}', ''),
(2223, 'admin', 0, '次仁', '{MOD}', ''),
(2224, 'admin', 0, '宋善礼', '{MOD}', ''),
(2225, 'admin', 0, '多吉', '{MOD}', ''),
(2226, 'admin', 0, '武金辉', '{MOD}', ''),
(2227, 'admin', 0, '尼玛次仁', '{MOD}', ''),
(2228, 'admin', 0, '张跃平', '{MOD}', ''),
(2229, 'admin', 0, '马如龙', '{MOD}', ''),
(2230, 'admin', 0, '阿登', '{MOD}', ''),
(2231, 'admin', 0, '新杂•单增曲扎', '{MOD}', ''),
(2232, 'admin', 0, '桑顶•多吉帕姆•德庆曲珍', '{MOD}', ''),
(2233, 'admin', 0, '金毅明', '{MOD}', ''),
(2234, 'admin', 0, '刘庆慧', '{MOD}', ''),
(2235, 'admin', 0, '罗松多吉', '{MOD}', ''),
(2236, 'admin', 0, '索朗卓玛', '{MOD}', ''),
(2237, 'admin', 0, '央金', '{MOD}', ''),
(2238, 'admin', 0, '王侠', '{MOD}', ''),
(2239, 'admin', 0, '娄勤俭', '{MOD}', ''),
(2240, 'admin', 0, '李锦斌', '{MOD}', ''),
(2241, 'admin', 0, '宋洪武', '{MOD}', ''),
(2242, 'admin', 0, '孙清云', '{MOD}', ''),
(2243, 'admin', 0, '江泽林', '{MOD}', ''),
(2244, 'admin', 0, '程兵', '{MOD}', ''),
(2245, 'admin', 0, '魏民洲', '{MOD}', ''),
(2246, 'admin', 0, '胡悦', '{MOD}', ''),
(2247, 'admin', 0, '姚引良', '{MOD}', ''),
(2248, 'admin', 0, '朱静芝', '{MOD}', ''),
(2249, 'admin', 0, '郑小明', '{MOD}', ''),
(2250, 'admin', 0, '吴登昌', '{MOD}', ''),
(2251, 'admin', 0, '景俊海', '{MOD}', ''),
(2252, 'admin', 0, '李金柱', '{MOD}', ''),
(2253, 'admin', 0, '罗振江', '{MOD}', ''),
(2254, 'admin', 0, '李晓东', '{MOD}', ''),
(2255, 'admin', 0, '黄玮', '{MOD}', ''),
(2256, 'admin', 0, '张道宏', '{MOD}', ''),
(2257, 'admin', 0, '张迈曾', '{MOD}', ''),
(2258, 'admin', 0, '白阿莹', '{MOD}', ''),
(2259, 'admin', 0, '吴前进', '{MOD}', ''),
(2260, 'admin', 0, '桂维民', '{MOD}', ''),
(2261, 'admin', 0, '张生朝', '{MOD}', ''),
(2262, 'admin', 0, '周一波', '{MOD}', ''),
(2263, 'admin', 0, '王晓安', '{MOD}', ''),
(2264, 'admin', 0, '李冬玉', '{MOD}', ''),
(2265, 'admin', 0, '李进权', '{MOD}', ''),
(2266, 'admin', 0, '姚增战', '{MOD}', ''),
(2267, 'admin', 0, '刘永富', '{MOD}', ''),
(2268, 'admin', 0, '罗笑虎', '{MOD}', ''),
(2269, 'admin', 0, '刘立军', '{MOD}', ''),
(2270, 'admin', 0, '陆武成', '{MOD}', ''),
(2271, 'admin', 0, '陈知庶', '{MOD}', ''),
(2272, 'admin', 0, '吴德刚', '{MOD}', ''),
(2273, 'admin', 0, '泽巴足', '{MOD}', ''),
(2274, 'admin', 0, '咸辉', '{MOD}', ''),
(2275, 'admin', 0, '郝远', '{MOD}', ''),
(2276, 'admin', 0, '张晓兰', '{MOD}', ''),
(2277, 'admin', 0, '虞海燕', '{MOD}', ''),
(2278, 'admin', 0, '李建华', '{MOD}', ''),
(2279, 'admin', 0, '张开勋', '{MOD}', ''),
(2280, 'admin', 0, '嘉木样•洛桑久美•图丹却吉尼玛', '{MOD}', ''),
(2281, 'admin', 0, '马尚英', '{MOD}', ''),
(2282, 'admin', 0, '孙效东', '{MOD}', ''),
(2283, 'admin', 0, '崔玉琴', '{MOD}', ''),
(2284, 'admin', 0, '周多明', '{MOD}', ''),
(2285, 'admin', 0, '李永军', '{MOD}', ''),
(2286, 'admin', 0, '侯生华', '{MOD}', ''),
(2287, 'admin', 0, '黄选平', '{MOD}', ''),
(2288, 'admin', 0, '栗震亚', '{MOD}', ''),
(2289, 'admin', 0, '张世珍', '{MOD}', ''),
(2290, 'admin', 0, '马国瑜', '{MOD}', ''),
(2291, 'admin', 0, '张景辉', '{MOD}', ''),
(2292, 'admin', 0, '石晶', '{MOD}', ''),
(2293, 'admin', 0, '王建军', '{MOD}', ''),
(2294, 'admin', 0, '穆东升', '{MOD}', ''),
(2295, 'admin', 0, '徐福顺', '{MOD}', ''),
(2296, 'admin', 0, '骆玉林', '{MOD}', ''),
(2297, 'admin', 0, '吉狄马加', '{MOD}', ''),
(2298, 'admin', 0, '多杰热旦', '{MOD}', ''),
(2299, 'admin', 0, '齐玉', '{MOD}', ''),
(2300, 'admin', 0, '张书领', '{MOD}', ''),
(2301, 'admin', 0, '王小青', '{MOD}', ''),
(2302, 'admin', 0, '苏宁', '{MOD}', ''),
(2303, 'admin', 0, '邓本太', '{MOD}', ''),
(2304, 'admin', 0, '王令浚', '{MOD}', ''),
(2305, 'admin', 0, '高云龙', '{MOD}', ''),
(2306, 'admin', 0, '张光荣', '{MOD}', ''),
(2307, 'admin', 0, '马顺清', '{MOD}', ''),
(2308, 'admin', 0, '何挺', '{MOD}', ''),
(2309, 'admin', 0, '张建民', '{MOD}', ''),
(2310, 'admin', 0, '沈何', '{MOD}', ''),
(2311, 'admin', 0, '桑杰', '{MOD}', ''),
(2312, 'admin', 0, '郭汝琢', '{MOD}', ''),
(2313, 'admin', 0, '刘春耀', '{MOD}', ''),
(2314, 'admin', 0, '昂毛', '{MOD}', ''),
(2315, 'admin', 0, '曹文虎', '{MOD}', ''),
(2316, 'admin', 0, '蔡德贵', '{MOD}', ''),
(2317, 'admin', 0, '陈资全', '{MOD}', ''),
(2318, 'admin', 0, '鲍义志', '{MOD}', ''),
(2319, 'admin', 0, '仁青安杰', '{MOD}', ''),
(2320, 'admin', 0, '李忠保', '{MOD}', ''),
(2321, 'admin', 0, '马志伟', '{MOD}', ''),
(2322, 'admin', 0, '马长庆', '{MOD}', ''),
(2323, 'admin', 0, '李选生', '{MOD}', ''),
(2324, 'admin', 0, '韩玉贵', '{MOD}', ''),
(2325, 'admin', 0, '崔波', '{MOD}', ''),
(2326, 'admin', 0, '徐松南', '{MOD}', ''),
(2327, 'admin', 0, '齐同生', '{MOD}', ''),
(2328, 'admin', 0, '刘慧', '{MOD}', ''),
(2329, 'admin', 0, '杨春光', '{MOD}', ''),
(2330, 'admin', 0, '苏德良', '{MOD}', ''),
(2331, 'admin', 0, '蔡国英', '{MOD}', ''),
(2332, 'admin', 0, '王志宏', '{MOD}', ''),
(2333, 'admin', 0, '马三刚', '{MOD}', ''),
(2334, 'admin', 0, '陈绪国', '{MOD}', ''),
(2335, 'admin', 0, '郝林海', '{MOD}', ''),
(2336, 'admin', 0, '李锐', '{MOD}', ''),
(2337, 'admin', 0, '姚爱兴', '{MOD}', ''),
(2338, 'admin', 0, '赵小平', '{MOD}', ''),
(2339, 'admin', 0, '屈冬玉', '{MOD}', ''),
(2340, 'admin', 0, '左军', '{MOD}', ''),
(2341, 'admin', 0, '马瑞文', '{MOD}', ''),
(2342, 'admin', 0, '冯炯华', '{MOD}', ''),
(2343, 'admin', 0, '张小素', '{MOD}', ''),
(2344, 'admin', 0, '马秀芬', '{MOD}', ''),
(2345, 'admin', 0, '何学清', '{MOD}', ''),
(2346, 'admin', 0, '刘天贵', '{MOD}', ''),
(2347, 'admin', 0, '肖云刚', '{MOD}', ''),
(2348, 'admin', 0, '李淑芬', '{MOD}', ''),
(2349, 'admin', 0, '马国权', '{MOD}', ''),
(2350, 'admin', 0, '陈守信', '{MOD}', ''),
(2351, 'admin', 0, '袁汉民', '{MOD}', ''),
(2352, 'admin', 0, '解孟林', '{MOD}', ''),
(2353, 'admin', 0, '张乐琴', '{MOD}', ''),
(2354, 'admin', 0, '安纯人', '{MOD}', ''),
(2355, 'admin', 0, '朱玉华', '{MOD}', ''),
(2356, 'admin', 0, '韩勇', '{MOD}', ''),
(2357, 'admin', 0, '彭勇', '{MOD}', ''),
(2358, 'admin', 0, '黄卫', '{MOD}', ''),
(2359, 'admin', 0, '肖开提•依明', '{MOD}', ''),
(2360, 'admin', 0, '努尔兰•阿不都满金', '{MOD}', ''),
(2361, 'admin', 0, '库热西•买合苏提', '{MOD}', ''),
(2362, 'admin', 0, '尔肯江吐拉洪', '{MOD}', ''),
(2363, 'admin', 0, '宋爱荣', '{MOD}', ''),
(2364, 'admin', 0, '朱海仑', '{MOD}', ''),
(2365, 'admin', 0, '白志杰', '{MOD}', ''),
(2366, 'admin', 0, '胡伟', '{MOD}', ''),
(2367, 'admin', 0, '钱智', '{MOD}', ''),
(2368, 'admin', 0, '靳诺', '{MOD}', ''),
(2369, 'admin', 0, '贾帕尔•阿比布拉', '{MOD}', ''),
(2370, 'admin', 0, '铁力瓦尔迪•阿不都热西提', '{MOD}', ''),
(2371, 'admin', 0, '艾尔肯.吐尼亚孜', '{MOD}', ''),
(2372, 'admin', 0, '史大刚', '{MOD}', ''),
(2373, 'admin', 0, '朱昌杰', '{MOD}', ''),
(2374, 'admin', 0, '张国梁', '{MOD}', ''),
(2375, 'admin', 0, '乔吉甫', '{MOD}', ''),
(2376, 'admin', 0, '阿勒布斯拜•拉合木', '{MOD}', ''),
(2377, 'admin', 0, '马明成', '{MOD}', ''),
(2378, 'admin', 0, '黄昌元', '{MOD}', ''),
(2379, 'admin', 0, '柳耀华', '{MOD}', ''),
(2380, 'admin', 0, '柯赛江•赛力禾加', '{MOD}', ''),
(2381, 'admin', 0, '柯丽', '{MOD}', ''),
(2382, 'admin', 0, '刘晏良', '{MOD}', ''),
(2383, 'admin', 0, '买买提江•艾买提', '{MOD}', ''),
(2384, 'admin', 0, '阿不都力提甫•阿不都热依木', '{MOD}', ''),
(2385, 'admin', 0, '热孜万•艾拜', '{MOD}', ''),
(2386, 'admin', 0, '买买提艾山•托乎达力', '{MOD}', ''),
(2387, 'admin', 0, '阿尤甫•铁衣甫', '{MOD}', ''),
(2388, 'admin', 0, '巴代', '{MOD}', ''),
(2389, 'admin', 0, '林瑞麟', '{MOD}', ''),
(2390, 'admin', 0, '曾俊华', '{MOD}', ''),
(2391, 'admin', 0, '黄仁龙', '{MOD}', ''),
(2392, 'admin', 0, '俞宗怡', '{MOD}', ''),
(2393, 'admin', 0, '曾德成', '{MOD}', ''),
(2394, 'admin', 0, '李少光', '{MOD}', ''),
(2395, 'admin', 0, '谭志源', '{MOD}', '');
INSERT INTO `pre_common_word` (`id`, `admin`, `type`, `find`, `replacement`, `extra`) VALUES
(2396, 'admin', 0, '周一岳', '{MOD}', ''),
(2397, 'admin', 0, '陈家强', '{MOD}', ''),
(2398, 'admin', 0, '孙明扬', '{MOD}', ''),
(2399, 'admin', 0, '林郑月娥', '{MOD}', ''),
(2400, 'admin', 0, '苏锦梁', '{MOD}', ''),
(2401, 'admin', 0, '郑汝桦', '{MOD}', ''),
(2402, 'admin', 0, '张建宗', '{MOD}', ''),
(2403, 'admin', 0, '邱腾华', '{MOD}', ''),
(2404, 'admin', 0, '夏佳理', '{MOD}', ''),
(2405, 'admin', 0, '岑浩辉', '{MOD}', ''),
(2406, 'admin', 0, '陈丽敏', '{MOD}', ''),
(2407, 'admin', 0, '谭伯源', '{MOD}', ''),
(2408, 'admin', 0, '张国华', '{MOD}', ''),
(2409, 'admin', 0, '张裕', '{MOD}', ''),
(2410, 'admin', 0, '刘仕尧', '{MOD}', ''),
(2411, 'admin', 0, '冯文庄', '{MOD}', ''),
(2412, 'admin', 0, '何永安', '{MOD}', ''),
(2413, 'admin', 0, '何超明', '{MOD}', ''),
(2414, 'admin', 0, '白英伟', '{MOD}', ''),
(2415, 'admin', 0, '耿惠昌', '{MOD}', ''),
(2416, 'admin', 0, '董海舟', '{MOD}', ''),
(2417, 'admin', 0, '樊守志', '{MOD}', ''),
(2418, 'admin', 0, '王光亚', '{MOD}', ''),
(2419, 'admin', 0, '谢伏瞻', '{MOD}', ''),
(2420, 'admin', 0, '宁吉喆', '{MOD}', ''),
(2421, 'admin', 0, '田学斌', '{MOD}', ''),
(2422, 'admin', 0, '黄守宏', '{MOD}', ''),
(2423, 'admin', 0, '王伟光', '{MOD}', ''),
(2424, 'admin', 0, '李慎明', '{MOD}', ''),
(2425, 'admin', 0, '朱佳木', '{MOD}', ''),
(2426, 'admin', 0, '高全立', '{MOD}', ''),
(2427, 'admin', 0, '武寅', '{MOD}', ''),
(2428, 'admin', 0, '李扬', '{MOD}', ''),
(2429, 'admin', 0, '李秋芳', '{MOD}', ''),
(2430, 'admin', 0, '黄浩涛', '{MOD}', ''),
(2431, 'admin', 0, '陈宜瑜', '{MOD}', ''),
(2432, 'admin', 0, '朱道本', '{MOD}', ''),
(2433, 'admin', 0, '朱作言', '{MOD}', ''),
(2434, 'admin', 0, '王杰', '{MOD}', ''),
(2435, 'admin', 0, '沈文庆', '{MOD}', ''),
(2436, 'admin', 0, '孙家广', '{MOD}', ''),
(2437, 'admin', 0, '傅兴国', '{MOD}', ''),
(2438, 'admin', 0, '夏勇', '{MOD}', ''),
(2439, 'admin', 0, '闻荣友', '{MOD}', ''),
(2440, 'admin', 0, '杜永胜', '{MOD}', ''),
(2441, 'admin', 0, '李景田', '{MOD}', ''),
(2442, 'admin', 0, '陈宝生', '{MOD}', ''),
(2443, 'admin', 0, '孙庆聚', '{MOD}', ''),
(2444, 'admin', 0, '李书磊', '{MOD}', ''),
(2445, 'admin', 0, '张伯里', '{MOD}', ''),
(2446, 'admin', 0, '徐伟新', '{MOD}', ''),
(2447, 'admin', 0, '欧阳淞', '{MOD}', ''),
(2448, 'admin', 0, '曲青山', '{MOD}', ''),
(2449, 'admin', 0, '李忠杰', '{MOD}', ''),
(2450, 'admin', 0, '龙新民', '{MOD}', ''),
(2451, 'admin', 0, '吕世光', '{MOD}', ''),
(2452, 'admin', 0, '冷溶', '{MOD}', ''),
(2453, 'admin', 0, '杨胜群', '{MOD}', ''),
(2454, 'admin', 0, '李捷', '{MOD}', ''),
(2455, 'admin', 0, '董宏', '{MOD}', ''),
(2456, 'admin', 0, '陈晋', '{MOD}', ''),
(2457, 'admin', 0, '赵胜轩', '{MOD}', ''),
(2458, 'admin', 0, '周本顺', '{MOD}', ''),
(2459, 'admin', 0, '沈跃跃', '{MOD}', ''),
(2460, 'admin', 0, '王尔乘', '{MOD}', ''),
(2461, 'admin', 0, '王秦丰', '{MOD}', ''),
(2462, 'admin', 0, '王京清', '{MOD}', ''),
(2463, 'admin', 0, '蔡名照', '{MOD}', ''),
(2464, 'admin', 0, '翟卫华', '{MOD}', ''),
(2465, 'admin', 0, '孙志军', '{MOD}', ''),
(2466, 'admin', 0, '朱维群', '{MOD}', ''),
(2467, 'admin', 0, '全哲洙', '{MOD}', ''),
(2468, 'admin', 0, '黄跃金', '{MOD}', ''),
(2469, 'admin', 0, '尤兰田', '{MOD}', ''),
(2470, 'admin', 0, '陈喜庆', '{MOD}', ''),
(2471, 'admin', 0, '斯塔', '{MOD}', ''),
(2472, 'admin', 0, '叶小文', '{MOD}', ''),
(2473, 'admin', 0, '邵鸿', '{MOD}', ''),
(2474, 'admin', 0, '王京治', '{MOD}', ''),
(2475, 'admin', 0, '袁廷华', '{MOD}', ''),
(2476, 'admin', 0, '王家瑞', '{MOD}', ''),
(2477, 'admin', 0, '陈凤翔', '{MOD}', ''),
(2478, 'admin', 0, '李进军', '{MOD}', ''),
(2479, 'admin', 0, '何毅亭', '{MOD}', ''),
(2480, 'admin', 0, '施芝鸿', '{MOD}', ''),
(2481, 'admin', 0, '潘盛洲', '{MOD}', ''),
(2482, 'admin', 0, '裘援平', '{MOD}', ''),
(2483, 'admin', 0, '陈锡文', '{MOD}', ''),
(2484, 'admin', 0, '唐仁健', '{MOD}', ''),
(2485, 'admin', 0, '王东明', '{MOD}', ''),
(2486, 'admin', 0, '吴知论', '{MOD}', ''),
(2487, 'admin', 0, '王峰', '{MOD}', ''),
(2488, 'admin', 0, '何建中', '{MOD}', ''),
(2489, 'admin', 0, '张崇和', '{MOD}', ''),
(2490, 'admin', 0, '项兆伦', '{MOD}', ''),
(2491, 'admin', 0, '王世明', '{MOD}', ''),
(2492, 'admin', 0, '孙淦', '{MOD}', ''),
(2493, 'admin', 0, '孟学农', '{MOD}', ''),
(2494, 'admin', 0, '杨衍银', '{MOD}', ''),
(2495, 'admin', 0, '俞贵麟', '{MOD}', ''),
(2496, 'admin', 0, '邵旭军', '{MOD}', ''),
(2497, 'admin', 0, '姚志平', '{MOD}', ''),
(2498, 'admin', 0, '李宝善', '{MOD}', ''),
(2499, 'admin', 0, '衣俊卿', '{MOD}', ''),
(2500, 'admin', 0, '曹清', '{MOD}', ''),
(2501, 'admin', 0, '徐振寰', '{MOD}', ''),
(2502, 'admin', 0, '马培华', '{MOD}', ''),
(2503, 'admin', 0, '陈秀榕', '{MOD}', ''),
(2504, 'admin', 0, '张鸣起', '{MOD}', ''),
(2505, 'admin', 0, '倪健民', '{MOD}', ''),
(2506, 'admin', 0, '陈荣书', '{MOD}', ''),
(2507, 'admin', 0, '陆昊', '{MOD}', ''),
(2508, 'admin', 0, '王晓', '{MOD}', ''),
(2509, 'admin', 0, '贺军科', '{MOD}', ''),
(2510, 'admin', 0, '卢雍政', '{MOD}', ''),
(2511, 'admin', 0, '罗梅', '{MOD}', ''),
(2512, 'admin', 0, '汪鸿雁', '{MOD}', ''),
(2513, 'admin', 0, '周长奎', '{MOD}', ''),
(2514, 'admin', 0, '陈至立', '{MOD}', ''),
(2515, 'admin', 0, '宋秀岩', '{MOD}', ''),
(2516, 'admin', 0, '孟晓驷', '{MOD}', ''),
(2517, 'admin', 0, '赵实', '{MOD}', ''),
(2518, 'admin', 0, '汪纪戎', '{MOD}', ''),
(2519, 'admin', 0, '徐莉莉', '{MOD}', ''),
(2520, 'admin', 0, '唐晓青', '{MOD}', ''),
(2521, 'admin', 0, '洪天慧', '{MOD}', ''),
(2522, 'admin', 0, '甄砚', '{MOD}', ''),
(2523, 'admin', 0, '邓中翰', '{MOD}', ''),
(2524, 'admin', 0, '卢锡城', '{MOD}', ''),
(2525, 'admin', 0, '冯长根', '{MOD}', ''),
(2526, 'admin', 0, '刘玠', '{MOD}', ''),
(2527, 'admin', 0, '沈岩', '{MOD}', ''),
(2528, 'admin', 0, '陈赛娟', '{MOD}', ''),
(2529, 'admin', 0, '赵沁平', '{MOD}', ''),
(2530, 'admin', 0, '秦大河', '{MOD}', ''),
(2531, 'admin', 0, '袁家军', '{MOD}', ''),
(2532, 'admin', 0, '唐启升', '{MOD}', ''),
(2533, 'admin', 0, '程东红', '{MOD}', ''),
(2534, 'admin', 0, '共产', '{MOD}', ''),
(2535, 'admin', 0, '共党', '{MOD}', ''),
(2536, 'admin', 0, '共军', '{MOD}', ''),
(2537, 'admin', 0, '党干部', '{MOD}', ''),
(2538, 'admin', 0, 'gcd', '{MOD}', ''),
(2539, 'admin', 0, '终共', '{MOD}', ''),
(2540, 'admin', 0, '党组织', '{MOD}', ''),
(2541, 'admin', 0, '共非', '{MOD}', ''),
(2542, 'admin', 0, '蚣党', '{MOD}', ''),
(2543, 'admin', 0, 'dang啊', '{MOD}', ''),
(2544, 'admin', 0, '共匪', '{MOD}', ''),
(2545, 'admin', 0, '党员', '{MOD}', ''),
(2546, 'admin', 0, '某党', '{MOD}', ''),
(2547, 'admin', 0, '什么GD', '{MOD}', ''),
(2548, 'admin', 0, '产党', '{MOD}', ''),
(2549, 'admin', 0, '共------匪', '{MOD}', ''),
(2550, 'admin', 0, '执政党', '{MOD}', ''),
(2551, 'admin', 0, '共产主义', '{MOD}', ''),
(2552, 'admin', 0, '共产共妻', '{MOD}', ''),
(2553, 'admin', 0, '供产主义', '{MOD}', ''),
(2554, 'admin', 0, '阿党', '{MOD}', ''),
(2555, 'admin', 0, '姓“共”', '{MOD}', ''),
(2556, 'admin', 0, '档天下', '{MOD}', ''),
(2557, 'admin', 0, '伟光正', '{MOD}', ''),
(2558, 'admin', 0, '入裆', '{MOD}', ''),
(2559, 'admin', 0, '裆禁', '{MOD}', ''),
(2560, 'admin', 0, '优秀裆员', '{MOD}', ''),
(2561, 'admin', 0, '裆的领倒', '{MOD}', ''),
(2562, 'admin', 0, '感谢裆', '{MOD}', ''),
(2563, 'admin', 0, '中共查禁', '{MOD}', ''),
(2564, 'admin', 0, '中共官员', '{MOD}', ''),
(2565, 'admin', 0, '中共谎言', '{MOD}', ''),
(2566, 'admin', 0, '中共祭祖', '{MOD}', ''),
(2567, 'admin', 0, '中共拒异', '{MOD}', ''),
(2568, 'admin', 0, '中共恐惧', '{MOD}', ''),
(2569, 'admin', 0, '中共两会后', '{MOD}', ''),
(2570, 'admin', 0, '中共流氓', '{MOD}', ''),
(2571, 'admin', 0, '中共内斗', '{MOD}', ''),
(2572, 'admin', 0, '中共十七大', '{MOD}', ''),
(2573, 'admin', 0, '中共太子', '{MOD}', ''),
(2574, 'admin', 0, '中共统治', '{MOD}', ''),
(2575, 'admin', 0, '中共亡', '{MOD}', ''),
(2576, 'admin', 0, '中共王朝', '{MOD}', ''),
(2577, 'admin', 0, '中共小丑', '{MOD}', ''),
(2578, 'admin', 0, '中共邪恶', '{MOD}', ''),
(2579, 'admin', 0, '中共元老', '{MOD}', ''),
(2580, 'admin', 0, '中央大换血', '{MOD}', ''),
(2581, 'admin', 0, '中央黑幕', '{MOD}', ''),
(2582, 'admin', 0, '共产万岁', '{MOD}', ''),
(2583, 'admin', 0, '共钱共妻', '{MOD}', ''),
(2584, 'admin', 0, '共产专搞', '{MOD}', ''),
(2585, 'admin', 0, 'GD将亡', '{MOD}', ''),
(2586, 'admin', 0, '这样的党', '{MOD}', ''),
(2587, 'admin', 0, '档内为官', '{MOD}', ''),
(2588, 'admin', 0, '挡~~中~~~~~yang', '{MOD}', ''),
(2589, 'admin', 0, '党跟朝廷', '{MOD}', ''),
(2590, 'admin', 0, '中共当局', '{MOD}', ''),
(2591, 'admin', 0, '中共独枭', '{MOD}', ''),
(2592, 'admin', 0, '中共监狱', '{MOD}', ''),
(2593, 'admin', 0, '中共特务', '{MOD}', ''),
(2594, 'admin', 0, '中共政权', '{MOD}', ''),
(2595, 'admin', 0, '中共走狗', '{MOD}', ''),
(2596, 'admin', 0, '对裆负责', '{MOD}', ''),
(2597, 'admin', 0, '中共八老', '{MOD}', ''),
(2598, 'admin', 0, '共党聚财', '{MOD}', ''),
(2599, 'admin', 0, '灭共', '{MOD}', ''),
(2600, 'admin', 0, '灭党', '{MOD}', ''),
(2601, 'admin', 0, '亡党', '{MOD}', ''),
(2602, 'admin', 0, '我裆', '{MOD}', ''),
(2603, 'admin', 0, '退gong', '{MOD}', ''),
(2604, 'admin', 0, '美国之音', '{MOD}', ''),
(2605, 'admin', 0, '乌有之乡', '{MOD}', ''),
(2606, 'admin', 0, '东森新闻网', '{MOD}', ''),
(2607, 'admin', 0, '东森电视', '{MOD}', ''),
(2608, 'admin', 0, '亚洲时报', '{MOD}', ''),
(2609, 'admin', 0, '今日美国', '{MOD}', ''),
(2610, 'admin', 0, '亚洲周刊', '{MOD}', ''),
(2611, 'admin', 0, 'BBC中文网 ', '{MOD}', ''),
(2612, 'admin', 0, '美国CNN', '{MOD}', ''),
(2613, 'admin', 0, '华盛顿邮报', '{MOD}', ''),
(2614, 'admin', 0, '苹果日报', '{MOD}', ''),
(2615, 'admin', 0, '文汇报', '{MOD}', ''),
(2616, 'admin', 0, '中国禁闻', '{MOD}', ''),
(2617, 'admin', 0, '中国公民新闻网', '{MOD}', ''),
(2618, 'admin', 0, '中国时讯网', '{MOD}', ''),
(2619, 'admin', 0, '舆论监督网', '{MOD}', ''),
(2620, 'admin', 0, '西藏网', '{MOD}', ''),
(2621, 'admin', 0, '西藏论坛', '{MOD}', ''),
(2622, 'admin', 0, '人民报', '{MOD}', ''),
(2623, 'admin', 0, '云力态网', '{MOD}', ''),
(2624, 'admin', 0, '动太网', '{MOD}', ''),
(2625, 'admin', 0, '复兴论坛', '{MOD}', ''),
(2626, 'admin', 0, '中国社会论坛', '{MOD}', ''),
(2627, 'admin', 0, '问题论坛', '{MOD}', ''),
(2628, 'admin', 0, '钓yu岛', '{MOD}', ''),
(2629, 'admin', 0, 'DiaoyuIsland', '{MOD}', ''),
(2630, 'admin', 0, '尖阁列岛', '{MOD}', ''),
(2631, 'admin', 0, '靖国神社', '{MOD}', ''),
(2632, 'admin', 0, '青海玉树', '{MOD}', ''),
(2633, 'admin', 0, '福建南平', '{MOD}', ''),
(2634, 'admin', 0, '法国巴黎', '{MOD}', ''),
(2635, 'admin', 0, '耶路撒冷', '{MOD}', ''),
(2636, 'admin', 0, '银龙岛', '{MOD}', ''),
(2637, 'admin', 0, '人民大会堂', '{MOD}', ''),
(2638, 'admin', 0, 'tiananmen', '{MOD}', ''),
(2639, 'admin', 0, '西乌旗', '{MOD}', ''),
(2640, 'admin', 0, '喀什', '{MOD}', ''),
(2641, 'admin', 0, '乌市', '{MOD}', ''),
(2642, 'admin', 0, '藏南', '{MOD}', ''),
(2643, 'admin', 0, '哈巴罗夫斯克', '{MOD}', ''),
(2644, 'admin', 0, '石河子', '{MOD}', ''),
(2645, 'admin', 0, '突厥', '{MOD}', ''),
(2646, 'admin', 0, '突尼斯', '{MOD}', ''),
(2647, 'admin', 0, '福建南平实验小学', '{MOD}', ''),
(2648, 'admin', 0, '台海', '{MOD}', ''),
(2649, 'admin', 0, '缅甸果敢', '{MOD}', ''),
(2650, 'admin', 0, '潮州', '{MOD}', ''),
(2651, 'admin', 0, '新塘', '{MOD}', ''),
(2652, 'admin', 0, '乌兹别克斯坦', '{MOD}', ''),
(2653, 'admin', 0, '珍宝岛', '{MOD}', ''),
(2654, 'admin', 0, '秦城监狱', '{MOD}', ''),
(2655, 'admin', 0, '六部口', '{MOD}', ''),
(2656, 'admin', 0, '南沙海域', '{MOD}', ''),
(2657, 'admin', 0, '南沙群岛', '{MOD}', ''),
(2658, 'admin', 0, '曾母暗沙', '{MOD}', ''),
(2659, 'admin', 0, 'Nanshaislands', '{MOD}', ''),
(2660, 'admin', 0, '潮州古巷', '{MOD}', ''),
(2661, 'admin', 0, '安元鼎', '{MOD}', ''),
(2662, 'admin', 0, '玉泉山别墅', '{MOD}', ''),
(2663, 'admin', 0, '古乡镇枫', '{MOD}', ''),
(2664, 'admin', 0, '城管', '{MOD}', ''),
(2665, 'admin', 0, '公检法', '{MOD}', ''),
(2666, 'admin', 0, '强拆队员', '{MOD}', ''),
(2667, 'admin', 0, '拆迁员', '{MOD}', ''),
(2668, 'admin', 0, '司法警官', '{MOD}', ''),
(2669, 'admin', 0, '谍报官', '{MOD}', ''),
(2670, 'admin', 0, '警方', '{MOD}', ''),
(2671, 'admin', 0, '5毛', '{MOD}', ''),
(2672, 'admin', 0, '官员', '{MOD}', ''),
(2673, 'admin', 0, '毛奴', '{MOD}', ''),
(2674, 'admin', 0, '西奴', '{MOD}', ''),
(2675, 'admin', 0, '毛粉', '{MOD}', ''),
(2676, 'admin', 0, '毛佐', '{MOD}', ''),
(2677, 'admin', 0, '毛左', '{MOD}', ''),
(2678, 'admin', 0, '官二代', '{MOD}', ''),
(2679, 'admin', 0, '军二代', '{MOD}', ''),
(2680, 'admin', 0, '当官的', '{MOD}', ''),
(2681, 'admin', 0, '当权者', '{MOD}', ''),
(2682, 'admin', 0, '政要人物', '{MOD}', ''),
(2683, 'admin', 0, '官园', '{MOD}', ''),
(2684, 'admin', 0, '特权利益者', '{MOD}', ''),
(2685, 'admin', 0, '官僚', '{MOD}', ''),
(2686, 'admin', 0, '贪官', '{MOD}', ''),
(2687, 'admin', 0, '反革命', '{MOD}', ''),
(2688, 'admin', 0, '走资派', '{MOD}', ''),
(2689, 'admin', 0, '资改叛徒', '{MOD}', ''),
(2690, 'admin', 0, '右势力', '{MOD}', ''),
(2691, 'admin', 0, '左势力', '{MOD}', ''),
(2692, 'admin', 0, '反动势力', '{MOD}', ''),
(2693, 'admin', 0, '敌对势力', '{MOD}', ''),
(2694, 'admin', 0, '档员', '{MOD}', ''),
(2695, 'admin', 0, '胡系人马', '{MOD}', ''),
(2696, 'admin', 0, '胡人马', '{MOD}', ''),
(2697, 'admin', 0, '江人马', '{MOD}', ''),
(2698, 'admin', 0, '胡派人马', '{MOD}', ''),
(2699, 'admin', 0, '江派人马', '{MOD}', ''),
(2700, 'admin', 0, '江系人马', '{MOD}', ''),
(2701, 'admin', 0, '胡江', '{MOD}', ''),
(2702, 'admin', 0, '上海帮', '{MOD}', ''),
(2703, 'admin', 0, '卖国贼', '{MOD}', ''),
(2704, 'admin', 0, '钉子户', '{MOD}', ''),
(2705, 'admin', 0, '灵道', '{MOD}', ''),
(2706, 'admin', 0, '红二代', '{MOD}', ''),
(2707, 'admin', 0, '毛教徒', '{MOD}', ''),
(2708, 'admin', 0, '清华帮', '{MOD}', ''),
(2709, 'admin', 0, '污吏', '{MOD}', ''),
(2710, 'admin', 0, '异议人士', '{MOD}', ''),
(2711, 'admin', 0, '被关访民', '{MOD}', ''),
(2712, 'admin', 0, '温氏家族', '{MOD}', ''),
(2713, 'admin', 0, '异见人士', '{MOD}', ''),
(2714, 'admin', 0, '利益集团', '{MOD}', ''),
(2715, 'admin', 0, '汉奸', '{MOD}', ''),
(2716, 'admin', 0, '信访干部', '{MOD}', ''),
(2717, 'admin', 0, '鹰派', '{MOD}', ''),
(2718, 'admin', 0, '受贿官员', '{MOD}', ''),
(2719, 'admin', 0, '台湾总统', '{MOD}', ''),
(2720, 'admin', 0, '胡家帮', '{MOD}', ''),
(2721, 'admin', 0, '兵贩子', '{MOD}', ''),
(2722, 'admin', 0, '政治流氓', '{MOD}', ''),
(2723, 'admin', 0, '政治新星', '{MOD}', ''),
(2724, 'admin', 0, '右派', '{MOD}', ''),
(2725, 'admin', 0, '官爷们', '{MOD}', ''),
(2726, 'admin', 0, '井茶', '{MOD}', ''),
(2727, 'admin', 0, '独立候选人', '{MOD}', ''),
(2728, 'admin', 0, '暴民', '{MOD}', ''),
(2729, 'admin', 0, '兵痞', '{MOD}', ''),
(2730, 'admin', 0, '军代表', '{MOD}', ''),
(2731, 'admin', 0, '世界蒙古人联合会', '{MOD}', ''),
(2732, 'admin', 0, '独立台湾会', '{MOD}', ''),
(2733, 'admin', 0, '蒙古教育文化基金会', '{MOD}', ''),
(2734, 'admin', 0, '蒙古牧民联合会', '{MOD}', ''),
(2735, 'admin', 0, '蒙古之友', '{MOD}', ''),
(2736, 'admin', 0, '21世纪中国基金会', '{MOD}', ''),
(2737, 'admin', 0, '冤民大同盟', '{MOD}', ''),
(2738, 'admin', 0, '上访军', '{MOD}', ''),
(2739, 'admin', 0, '塔利班', '{MOD}', ''),
(2740, 'admin', 0, '台湾民主联盟', '{MOD}', ''),
(2741, 'admin', 0, '台湾团结联盟', '{MOD}', ''),
(2742, 'admin', 0, '台盟', '{MOD}', ''),
(2743, 'admin', 0, '红客联盟', '{MOD}', ''),
(2744, 'admin', 0, '民主促进委员会', '{MOD}', ''),
(2745, 'admin', 0, '九三学社', '{MOD}', ''),
(2746, 'admin', 0, '西藏青年大会', '{MOD}', ''),
(2747, 'admin', 0, '建国党', '{MOD}', ''),
(2748, 'admin', 0, '大赦国际', '{MOD}', ''),
(2749, 'admin', 0, '恐怖组织', '{MOD}', ''),
(2750, 'admin', 0, '世界维吾尔大会', '{MOD}', ''),
(2751, 'admin', 0, '世维会', '{MOD}', ''),
(2752, 'admin', 0, '维吾尔在线', '{MOD}', ''),
(2753, 'admin', 0, '东土耳其斯坦', '{MOD}', ''),
(2754, 'admin', 0, '东突', '{MOD}', ''),
(2755, 'admin', 0, '文革小组', '{MOD}', ''),
(2756, 'admin', 0, '文化革命小组', '{MOD}', ''),
(2757, 'admin', 0, '藏青会', '{MOD}', ''),
(2758, 'admin', 0, '四人帮', '{MOD}', ''),
(2759, 'admin', 0, '造反派', '{MOD}', ''),
(2760, 'admin', 0, '亲民党', '{MOD}', ''),
(2761, 'admin', 0, '社民党', '{MOD}', ''),
(2762, 'admin', 0, '北约', '{MOD}', ''),
(2763, 'admin', 0, '台联', '{MOD}', ''),
(2764, 'admin', 0, '第三党', '{MOD}', ''),
(2765, 'admin', 0, '国命党', '{MOD}', ''),
(2766, 'admin', 0, '红客三人组', '{MOD}', ''),
(2767, 'admin', 0, '藏传佛教', '{MOD}', ''),
(2768, 'admin', 0, '劳动党', '{MOD}', ''),
(2769, 'admin', 0, '泛蓝联盟', '{MOD}', ''),
(2770, 'admin', 0, '工人党', '{MOD}', ''),
(2771, 'admin', 0, '戴梦得', '{MOD}', ''),
(2772, 'admin', 0, '蚁力神', '{MOD}', ''),
(2773, 'admin', 0, '民主自由党', '{MOD}', ''),
(2774, 'admin', 0, '中国网民党', '{MOD}', ''),
(2775, 'admin', 0, '中国民主党', '{MOD}', ''),
(2776, 'admin', 0, '西藏流亡政府', '{MOD}', ''),
(2777, 'admin', 0, '拆迁办', '{MOD}', ''),
(2778, 'admin', 0, '中国独立党', '{MOD}', ''),
(2779, 'admin', 0, '中国过渡政府', '{MOD}', ''),
(2780, 'admin', 0, '驻京办', '{MOD}', ''),
(2781, 'admin', 0, '中国革命党', '{MOD}', ''),
(2782, 'admin', 0, '第三道路党', '{MOD}', ''),
(2783, 'admin', 0, '带路党', '{MOD}', ''),
(2784, 'admin', 0, '三股势力', '{MOD}', ''),
(2785, 'admin', 0, '中国社会进步党', '{MOD}', ''),
(2786, 'admin', 0, '民主促进会', '{MOD}', ''),
(2787, 'admin', 0, '地下教会', '{MOD}', ''),
(2788, 'admin', 0, '伊斯兰祈祷团', '{MOD}', ''),
(2789, 'admin', 0, '维族人', '{MOD}', ''),
(2790, 'admin', 0, '藏族人', '{MOD}', ''),
(2791, 'admin', 0, '新疆人', '{MOD}', ''),
(2792, 'admin', 0, '维人', '{MOD}', ''),
(2793, 'admin', 0, '藏人', '{MOD}', ''),
(2794, 'admin', 0, '回族人', '{MOD}', ''),
(2795, 'admin', 0, '蒙古族', '{MOD}', ''),
(2796, 'admin', 0, '回族', '{MOD}', ''),
(2797, 'admin', 0, '藏族', '{MOD}', ''),
(2798, 'admin', 0, '维吾尔族', '{MOD}', ''),
(2799, 'admin', 0, '维族', '{MOD}', ''),
(2800, 'admin', 0, '穆斯林', '{MOD}', ''),
(2801, 'admin', 0, '伊斯兰', '{MOD}', ''),
(2802, 'admin', 0, '回民', '{MOD}', ''),
(2803, 'admin', 0, '达斡尔族', '{MOD}', ''),
(2804, 'admin', 0, '维吾尔族人', '{MOD}', ''),
(2805, 'admin', 0, '中央办公厅', '{MOD}', ''),
(2806, 'admin', 0, '中央组织部', '{MOD}', ''),
(2807, 'admin', 0, '中央宣传部', '{MOD}', ''),
(2808, 'admin', 0, '中央统战部', '{MOD}', ''),
(2809, 'admin', 0, '中央对外联络部', '{MOD}', ''),
(2810, 'admin', 0, '中央政法委', '{MOD}', ''),
(2811, 'admin', 0, '中央政策研究室', '{MOD}', ''),
(2812, 'admin', 0, '中央台办', '{MOD}', ''),
(2813, 'admin', 0, '中央外宣办', '{MOD}', ''),
(2814, 'admin', 0, '中央外事办', '{MOD}', ''),
(2815, 'admin', 0, '中央编办', '{MOD}', ''),
(2816, 'admin', 0, '中央综治委', '{MOD}', ''),
(2817, 'admin', 0, '中央精神文明建设委', '{MOD}', ''),
(2818, 'admin', 0, '中央精神文明建指委', '{MOD}', ''),
(2819, 'admin', 0, '中央党校', '{MOD}', ''),
(2820, 'admin', 0, '《人民日报》社', '{MOD}', ''),
(2821, 'admin', 0, '《求是》杂志社', '{MOD}', ''),
(2822, 'admin', 0, '中央警卫局', '{MOD}', ''),
(2823, 'admin', 0, '中央文献研究室', '{MOD}', ''),
(2824, 'admin', 0, '中央党史研究室', '{MOD}', ''),
(2825, 'admin', 0, '中央编译局', '{MOD}', ''),
(2826, 'admin', 0, '中央直属机关工委', '{MOD}', ''),
(2827, 'admin', 0, '中央国家机关工委', '{MOD}', ''),
(2828, 'admin', 0, '中央档案馆', '{MOD}', ''),
(2829, 'admin', 0, '国家档案局', '{MOD}', ''),
(2830, 'admin', 0, '中央保密办', '{MOD}', ''),
(2831, 'admin', 0, '国家保密局', '{MOD}', ''),
(2832, 'admin', 0, '中央密码工作领导小组办', '{MOD}', ''),
(2833, 'admin', 0, '国家密码管理局', '{MOD}', ''),
(2834, 'admin', 0, '中组部', '{MOD}', ''),
(2835, 'admin', 0, '中宣部', '{MOD}', ''),
(2836, 'admin', 0, '全国人民代表大会', '{MOD}', ''),
(2837, 'admin', 0, '中华人民共和国主席', '{MOD}', ''),
(2838, 'admin', 0, '国务院', '{MOD}', ''),
(2839, 'admin', 0, '最高人民法院', '{MOD}', ''),
(2840, 'admin', 0, '最高人民检察院', '{MOD}', ''),
(2841, 'admin', 0, '人大', '{MOD}', ''),
(2842, 'admin', 0, '高法', '{MOD}', ''),
(2843, 'admin', 0, '高检', '{MOD}', ''),
(2844, 'admin', 0, '外交部', '{MOD}', ''),
(2845, 'admin', 0, '国防部', '{MOD}', ''),
(2846, 'admin', 0, '发改委', '{MOD}', ''),
(2847, 'admin', 0, '教育部', '{MOD}', ''),
(2848, 'admin', 0, '科学技术部', '{MOD}', ''),
(2849, 'admin', 0, '公安部', '{MOD}', ''),
(2850, 'admin', 0, '安全部', '{MOD}', ''),
(2851, 'admin', 0, '监察部', '{MOD}', ''),
(2852, 'admin', 0, '民政部', '{MOD}', ''),
(2853, 'admin', 0, '司法部', '{MOD}', ''),
(2854, 'admin', 0, '财政部', '{MOD}', ''),
(2855, 'admin', 0, '铁道部', '{MOD}', ''),
(2856, 'admin', 0, '水利部', '{MOD}', ''),
(2857, 'admin', 0, '农业部', '{MOD}', ''),
(2858, 'admin', 0, '商务部', '{MOD}', ''),
(2859, 'admin', 0, '文化部', '{MOD}', ''),
(2860, 'admin', 0, '卫生部', '{MOD}', ''),
(2861, 'admin', 0, '审计署', '{MOD}', ''),
(2862, 'admin', 0, '省委', '{MOD}', ''),
(2863, 'admin', 0, '省政府', '{MOD}', ''),
(2864, 'admin', 0, '省政协', '{MOD}', ''),
(2865, 'admin', 0, '省人大', '{MOD}', ''),
(2866, 'admin', 0, '省人民政府', '{MOD}', ''),
(2867, 'admin', 0, '自治区人民政府', '{MOD}', ''),
(2868, 'admin', 0, '自治区党委', '{MOD}', ''),
(2869, 'admin', 0, '自治区人大', '{MOD}', ''),
(2870, 'admin', 0, '自治区政协', '{MOD}', ''),
(2871, 'admin', 0, '市人大', '{MOD}', ''),
(2872, 'admin', 0, '市人民政府', '{MOD}', ''),
(2873, 'admin', 0, '市人民政协', '{MOD}', ''),
(2874, 'admin', 0, '司法厅', '{MOD}', ''),
(2875, 'admin', 0, '法制办公室', '{MOD}', ''),
(2876, 'admin', 0, '法院', '{MOD}', ''),
(2877, 'admin', 0, '检察院', '{MOD}', ''),
(2878, 'admin', 0, '司法局', '{MOD}', ''),
(2879, 'admin', 0, '公安局', '{MOD}', ''),
(2880, 'admin', 0, '司法体系', '{MOD}', ''),
(2881, 'admin', 0, '宪法', '{MOD}', ''),
(2882, 'admin', 0, '民法', '{MOD}', ''),
(2883, 'admin', 0, '刑法', '{MOD}', ''),
(2884, 'admin', 0, '婚姻法', '{MOD}', ''),
(2885, 'admin', 0, '劳动合同法', '{MOD}', ''),
(2886, 'admin', 0, '司法', '{MOD}', ''),
(2887, 'admin', 0, '司法独立', '{MOD}', ''),
(2888, 'admin', 0, '呼喊派', '{MOD}', ''),
(2889, 'admin', 0, '门徒会', '{MOD}', ''),
(2890, 'admin', 0, '全范围教会', '{MOD}', ''),
(2891, 'admin', 0, '灵灵教', '{MOD}', ''),
(2892, 'admin', 0, '新约教会', '{MOD}', ''),
(2893, 'admin', 0, '观音法门', '{MOD}', ''),
(2894, 'admin', 0, '主神教', '{MOD}', ''),
(2895, 'admin', 0, '被立王', '{MOD}', ''),
(2896, 'admin', 0, '三班仆人派', '{MOD}', ''),
(2897, 'admin', 0, '灵仙真佛宗', '{MOD}', ''),
(2898, 'admin', 0, '天父的女儿', '{MOD}', ''),
(2899, 'admin', 0, '达米宣教会', '{MOD}', ''),
(2900, 'admin', 0, '宣教会', '{MOD}', ''),
(2901, 'admin', 0, '奥修教', '{MOD}', ''),
(2902, 'admin', 0, '和平教团运动', '{MOD}', ''),
(2903, 'admin', 0, '造物者世界教会', '{MOD}', ''),
(2904, 'admin', 0, '人民圣殿教', '{MOD}', ''),
(2905, 'admin', 0, '圣徒会', '{MOD}', ''),
(2906, 'admin', 0, '撒旦崇拜教', '{MOD}', ''),
(2907, 'admin', 0, '基亚班巴圣灵降临', '{MOD}', ''),
(2908, 'admin', 0, '大卫教派', '{MOD}', ''),
(2909, 'admin', 0, '少年撒旦教', '{MOD}', ''),
(2910, 'admin', 0, '太阳圣殿教', '{MOD}', ''),
(2911, 'admin', 0, '奥姆真理教', '{MOD}', ''),
(2912, 'admin', 0, '黑魔教', '{MOD}', ''),
(2913, 'admin', 0, '圣约书教会', '{MOD}', ''),
(2914, 'admin', 0, '天尊会', '{MOD}', ''),
(2915, 'admin', 0, '摄理教', '{MOD}', ''),
(2916, 'admin', 0, '万民教', '{MOD}', ''),
(2917, 'admin', 0, '神灵协会', '{MOD}', ''),
(2918, 'admin', 0, '养生益智功', '{MOD}', ''),
(2919, 'admin', 0, '日月气功', '{MOD}', ''),
(2920, 'admin', 0, '呼喊教', '{MOD}', ''),
(2921, 'admin', 0, '全能神', '{MOD}', ''),
(2922, 'admin', 0, '李堂堂', '{MOD}', ''),
(2923, 'admin', 0, '黄瑶', '{MOD}', ''),
(2924, 'admin', 0, '陈绍基', '{MOD}', ''),
(2925, 'admin', 0, '许宗衡', '{MOD}', ''),
(2926, 'admin', 0, '冯其福', '{MOD}', ''),
(2927, 'admin', 0, '刘忠敏', '{MOD}', ''),
(2928, 'admin', 0, '余良伟', '{MOD}', ''),
(2929, 'admin', 0, '陈盛兴', '{MOD}', ''),
(2930, 'admin', 0, '葛雄', '{MOD}', ''),
(2931, 'admin', 0, '宋勇', '{MOD}', ''),
(2932, 'admin', 0, '龙小乐', '{MOD}', ''),
(2933, 'admin', 0, '陈昭方', '{MOD}', ''),
(2934, 'admin', 0, '黄松有', '{MOD}', ''),
(2935, 'admin', 0, '康日新', '{MOD}', ''),
(2936, 'admin', 0, '何再贵', '{MOD}', ''),
(2937, 'admin', 0, '程海波', '{MOD}', ''),
(2938, 'admin', 0, '吕亦才', '{MOD}', ''),
(2939, 'admin', 0, '萧晓鹏', '{MOD}', ''),
(2940, 'admin', 0, '王禹帆', '{MOD}', ''),
(2941, 'admin', 0, '李胜林', '{MOD}', ''),
(2942, 'admin', 0, '逯军', '{MOD}', ''),
(2943, 'admin', 0, '刘友君', '{MOD}', ''),
(2944, 'admin', 0, '戴国森', '{MOD}', ''),
(2945, 'admin', 0, '王华元', '{MOD}', ''),
(2946, 'admin', 0, '邓宗生', '{MOD}', ''),
(2947, 'admin', 0, '刘登新', '{MOD}', ''),
(2948, 'admin', 0, '文强', '{MOD}', ''),
(2949, 'admin', 0, '乌小青', '{MOD}', ''),
(2950, 'admin', 0, '王新', '{MOD}', ''),
(2951, 'admin', 0, '陈少勇', '{MOD}', ''),
(2952, 'admin', 0, '郑少东', '{MOD}', ''),
(2953, 'admin', 0, '相怀珠', '{MOD}', ''),
(2954, 'admin', 0, '孙淑义', '{MOD}', ''),
(2955, 'admin', 0, '蔡志强', '{MOD}', ''),
(2956, 'admin', 0, '陈光明', '{MOD}', ''),
(2957, 'admin', 0, '徐强', '{MOD}', ''),
(2958, 'admin', 0, '米凤君', '{MOD}', ''),
(2959, 'admin', 0, '陈希同', '{MOD}', ''),
(2960, 'admin', 0, '陈良宇', '{MOD}', ''),
(2961, 'admin', 0, '王守业', '{MOD}', ''),
(2962, 'admin', 0, '马玉福', '{MOD}', ''),
(2963, 'admin', 0, '刘志军', '{MOD}', ''),
(2964, 'admin', 0, '吴向忠', '{MOD}', ''),
(2965, 'admin', 0, '刘志华', '{MOD}', ''),
(2966, 'admin', 0, '段义和', '{MOD}', ''),
(2967, 'admin', 0, '陶驷驹', '{MOD}', ''),
(2968, 'admin', 0, '秦裕', '{MOD}', ''),
(2969, 'admin', 0, '周金伙', '{MOD}', ''),
(2970, 'admin', 0, '金人庆', '{MOD}', ''),
(2971, 'admin', 0, '李宝金', '{MOD}', ''),
(2972, 'admin', 0, '崔济哲', '{MOD}', ''),
(2973, 'admin', 0, '李志强', '{MOD}', ''),
(2974, 'admin', 0, '罗泽勤', '{MOD}', ''),
(2975, 'admin', 0, '王宝森', '{MOD}', ''),
(2976, 'admin', 0, '郑建源', '{MOD}', ''),
(2977, 'admin', 0, '陈石勇', '{MOD}', ''),
(2978, 'admin', 0, '葛政', '{MOD}', ''),
(2979, 'admin', 0, '庄少勤', '{MOD}', ''),
(2980, 'admin', 0, '李向东', '{MOD}', ''),
(2981, 'admin', 0, '梅端杰', '{MOD}', ''),
(2982, 'admin', 0, '陈小同', '{MOD}', ''),
(2983, 'admin', 0, '聂元梓', '{MOD}', ''),
(2984, 'admin', 0, '严晓玲', '{MOD}', ''),
(2985, 'admin', 0, '方寿威', '{MOD}', ''),
(2986, 'admin', 0, '田亚维', '{MOD}', ''),
(2987, 'admin', 0, '盛雪', '{MOD}', ''),
(2988, 'admin', 0, '郭飞雄', '{MOD}', ''),
(2989, 'admin', 0, '傅怡彬', '{MOD}', ''),
(2990, 'admin', 0, '郭泉', '{MOD}', ''),
(2991, 'admin', 0, '林保华', '{MOD}', ''),
(2992, 'admin', 0, '李登辉', '{MOD}', ''),
(2993, 'admin', 0, '洪哲胜', '{MOD}', ''),
(2994, 'admin', 0, '游锡堃', '{MOD}', ''),
(2995, 'admin', 0, '泓志', '{MOD}', ''),
(2996, 'admin', 0, '闳志', '{MOD}', ''),
(2997, 'admin', 0, '赖昌星', '{MOD}', ''),
(2998, 'admin', 0, '荭志', '{MOD}', ''),
(2999, 'admin', 0, '紅志', '{MOD}', ''),
(3000, 'admin', 0, '李宏治', '{MOD}', ''),
(3001, 'admin', 0, '紅智', '{MOD}', ''),
(3002, 'admin', 0, '虹志', '{MOD}', ''),
(3003, 'admin', 0, '李洪之', '{MOD}', ''),
(3004, 'admin', 0, '李大师', '{MOD}', ''),
(3005, 'admin', 0, 'hongzhili', '{MOD}', ''),
(3006, 'admin', 0, '转轮圣王', '{MOD}', ''),
(3007, 'admin', 0, '转轮法王', '{MOD}', ''),
(3008, 'admin', 0, '红志', '{MOD}', ''),
(3009, 'admin', 0, '红智', '{MOD}', ''),
(3010, 'admin', 0, '李弘志', '{MOD}', ''),
(3011, 'admin', 0, '李鸿志', '{MOD}', ''),
(3012, 'admin', 0, '李宏智', '{MOD}', ''),
(3013, 'admin', 0, '朱成虎', '{MOD}', ''),
(3014, 'admin', 0, '宋志标', '{MOD}', ''),
(3015, 'admin', 0, '蒋公', '{MOD}', ''),
(3016, 'admin', 0, '金将军', '{MOD}', ''),
(3017, 'admin', 0, '本•拉登', '{MOD}', ''),
(3018, 'admin', 0, '李录', '{MOD}', ''),
(3019, 'admin', 0, '张铭', '{MOD}', ''),
(3020, 'admin', 0, '熊炜', '{MOD}', ''),
(3021, 'admin', 0, '熊焱', '{MOD}', ''),
(3022, 'admin', 0, '李淑贤', '{MOD}', ''),
(3023, 'admin', 0, '刘刚', '{MOD}', ''),
(3024, 'admin', 0, '王正云', '{MOD}', ''),
(3025, 'admin', 0, '郑旭光', '{MOD}', ''),
(3026, 'admin', 0, '马少方', '{MOD}', ''),
(3027, 'admin', 0, '杨涛', '{MOD}', ''),
(3028, 'admin', 0, '王治新', '{MOD}', ''),
(3029, 'admin', 0, '王超华', '{MOD}', ''),
(3030, 'admin', 0, '王有才', '{MOD}', ''),
(3031, 'admin', 0, '张志清', '{MOD}', ''),
(3032, 'admin', 0, '苏晓康', '{MOD}', ''),
(3033, 'admin', 0, '柴玲', '{MOD}', ''),
(3034, 'admin', 0, '翟伟民', '{MOD}', ''),
(3035, 'admin', 0, '封从德', '{MOD}', ''),
(3036, 'admin', 0, '刘宾雁', '{MOD}', ''),
(3037, 'admin', 0, 'dzl教授', '{MOD}', ''),
(3038, 'admin', 0, '顾顺章', '{MOD}', ''),
(3039, 'admin', 0, '傅申奇', '{MOD}', ''),
(3040, 'admin', 0, '鲍彤', '{MOD}', ''),
(3041, 'admin', 0, '艾青之子', '{MOD}', ''),
(3042, 'admin', 0, '艾未未', '{MOD}', ''),
(3043, 'admin', 0, '胡风', '{MOD}', ''),
(3044, 'admin', 0, '张宏良', '{MOD}', ''),
(3045, 'admin', 0, '顾准', '{MOD}', ''),
(3046, 'admin', 0, '高行健', '{MOD}', ''),
(3047, 'admin', 0, '胡星斗', '{MOD}', ''),
(3048, 'admin', 0, '林轻舟', '{MOD}', ''),
(3049, 'admin', 0, '胡绩伟', '{MOD}', ''),
(3050, 'admin', 0, '方励芝', '{MOD}', ''),
(3051, 'admin', 0, '冉云飞', '{MOD}', ''),
(3052, 'admin', 0, '任百鸣', '{MOD}', ''),
(3053, 'admin', 0, '任畹町', '{MOD}', ''),
(3054, 'admin', 0, '邵家健', '{MOD}', ''),
(3055, 'admin', 0, '司马晋', '{MOD}', ''),
(3056, 'admin', 0, '司马璐', '{MOD}', ''),
(3057, 'admin', 0, '焦国标', '{MOD}', ''),
(3058, 'admin', 0, '张志新', '{MOD}', ''),
(3059, 'admin', 0, '李凤智', '{MOD}', ''),
(3060, 'admin', 0, '吴宏达', '{MOD}', ''),
(3061, 'admin', 0, '吴弘达', '{MOD}', ''),
(3062, 'admin', 0, '李志绥', '{MOD}', ''),
(3063, 'admin', 0, '杜导斌', '{MOD}', ''),
(3064, 'admin', 0, '童屹', '{MOD}', ''),
(3065, 'admin', 0, '汪达林', '{MOD}', ''),
(3066, 'admin', 0, '王炳章', '{MOD}', ''),
(3067, 'admin', 0, '何德普', '{MOD}', ''),
(3068, 'admin', 0, '王军涛', '{MOD}', ''),
(3069, 'admin', 0, '王希哲', '{MOD}', ''),
(3070, 'admin', 0, '李必丰', '{MOD}', ''),
(3071, 'admin', 0, '何清涟', '{MOD}', ''),
(3072, 'admin', 0, '司徒华', '{MOD}', ''),
(3073, 'admin', 0, '林培瑞', '{MOD}', ''),
(3074, 'admin', 0, '滕兴善', '{MOD}', ''),
(3075, 'admin', 0, '江诗信', '{MOD}', ''),
(3076, 'admin', 0, '蒋彦永', '{MOD}', ''),
(3077, 'admin', 0, '蒋正华', '{MOD}', ''),
(3078, 'admin', 0, '崔英杰', '{MOD}', ''),
(3079, 'admin', 0, '吴幼明', '{MOD}', ''),
(3080, 'admin', 0, '吴学灿', '{MOD}', ''),
(3081, 'admin', 0, '吴学璨', '{MOD}', ''),
(3082, 'admin', 0, '程铁军', '{MOD}', ''),
(3083, 'admin', 0, '吴基伟', '{MOD}', ''),
(3084, 'admin', 0, '吴立红', '{MOD}', ''),
(3085, 'admin', 0, '吴方城', '{MOD}', ''),
(3086, 'admin', 0, '吴百益', '{MOD}', ''),
(3087, 'admin', 0, '翁国维', '{MOD}', ''),
(3088, 'admin', 0, '李泽楷', '{MOD}', ''),
(3089, 'admin', 0, '温如春', '{MOD}', ''),
(3090, 'admin', 0, '魏新生', '{MOD}', ''),
(3091, 'admin', 0, '涂运普', '{MOD}', ''),
(3092, 'admin', 0, '万晓东', '{MOD}', ''),
(3093, 'admin', 0, '万延海', '{MOD}', ''),
(3094, 'admin', 0, '汪精卫', '{MOD}', ''),
(3095, 'admin', 0, '汪岷', '{MOD}', ''),
(3096, 'admin', 0, '汪棋生', '{MOD}', ''),
(3097, 'admin', 0, '王策', '{MOD}', ''),
(3098, 'admin', 0, '王笃若', '{MOD}', ''),
(3099, 'admin', 0, '王明', '{MOD}', ''),
(3100, 'admin', 0, '王书金', '{MOD}', ''),
(3101, 'admin', 0, '王通智', '{MOD}', ''),
(3102, 'admin', 0, '王秀丽', '{MOD}', ''),
(3103, 'admin', 0, '王怡', '{MOD}', ''),
(3104, 'admin', 0, '费良勇', '{MOD}', ''),
(3105, 'admin', 0, '曹长青', '{MOD}', ''),
(3106, 'admin', 0, '姬胜德', '{MOD}', ''),
(3107, 'admin', 0, '姚立法', '{MOD}', ''),
(3108, 'admin', 0, '班禅', '{MOD}', ''),
(3109, 'admin', 0, '昂山素季', '{MOD}', ''),
(3110, 'admin', 0, '皇甫平', '{MOD}', ''),
(3111, 'admin', 0, '耿庆国', '{MOD}', ''),
(3112, 'admin', 0, '玉山江', '{MOD}', ''),
(3113, 'admin', 0, '高勤荣', '{MOD}', ''),
(3114, 'admin', 0, '昂山素姬', '{MOD}', ''),
(3115, 'admin', 0, '张勤德', '{MOD}', ''),
(3116, 'admin', 0, '冯迎春', '{MOD}', ''),
(3117, 'admin', 0, '任建新', '{MOD}', ''),
(3118, 'admin', 0, '郭国汀', '{MOD}', ''),
(3119, 'admin', 0, '邵长良', '{MOD}', ''),
(3120, 'admin', 0, '十世班禅', '{MOD}', ''),
(3121, 'admin', 0, '史久武', '{MOD}', ''),
(3122, 'admin', 0, '史效虎', '{MOD}', ''),
(3123, 'admin', 0, '史啸虎', '{MOD}', ''),
(3124, 'admin', 0, '游精佑', '{MOD}', ''),
(3125, 'admin', 0, '宋美龄', '{MOD}', ''),
(3126, 'admin', 0, '宋书元', '{MOD}', ''),
(3127, 'admin', 0, '宋万年', '{MOD}', ''),
(3128, 'admin', 0, '苏绍智', '{MOD}', ''),
(3129, 'admin', 0, '苏铁山', '{MOD}', ''),
(3130, 'admin', 0, '孙连桂', '{MOD}', ''),
(3131, 'admin', 0, '孙雪东', '{MOD}', ''),
(3132, 'admin', 0, '汤光中', '{MOD}', ''),
(3133, 'admin', 0, '汤海雯', '{MOD}', ''),
(3134, 'admin', 0, '汤海文', '{MOD}', ''),
(3135, 'admin', 0, '唐捷', '{MOD}', ''),
(3136, 'admin', 0, '王洪文', '{MOD}', ''),
(3137, 'admin', 0, '张春桥', '{MOD}', ''),
(3138, 'admin', 0, '江青', '{MOD}', ''),
(3139, 'admin', 0, '姚文元', '{MOD}', ''),
(3140, 'admin', 0, '林彪', '{MOD}', ''),
(3141, 'admin', 0, '林立果', '{MOD}', ''),
(3142, 'admin', 0, '李云鹤', '{MOD}', ''),
(3143, 'admin', 0, '黄琦', '{MOD}', ''),
(3144, 'admin', 0, '杜宪', '{MOD}', ''),
(3145, 'admin', 0, '薛飞', '{MOD}', ''),
(3146, 'admin', 0, '钱尧志', '{MOD}', ''),
(3147, 'admin', 0, '朱蒙', '{MOD}', ''),
(3148, 'admin', 0, '李禄', '{MOD}', ''),
(3149, 'admin', 0, '李天笑', '{MOD}', ''),
(3150, 'admin', 0, '刘凤钢', '{MOD}', ''),
(3151, 'admin', 0, '卢雪松', '{MOD}', ''),
(3152, 'admin', 0, '马加爵', '{MOD}', ''),
(3153, 'admin', 0, '聂树斌', '{MOD}', ''),
(3154, 'admin', 0, '郭起真', '{MOD}', ''),
(3155, 'admin', 0, '黄中奇', '{MOD}', ''),
(3156, 'admin', 0, '顾文选', '{MOD}', ''),
(3157, 'admin', 0, '张锡锟', '{MOD}', ''),
(3158, 'admin', 0, '林昭', '{MOD}', ''),
(3159, 'admin', 0, '任大熊', '{MOD}', ''),
(3160, 'admin', 0, '沈元', '{MOD}', ''),
(3161, 'admin', 0, '刘奇弟', '{MOD}', ''),
(3162, 'admin', 0, '贺永增', '{MOD}', ''),
(3163, 'admin', 0, '敖乃松', '{MOD}', ''),
(3164, 'admin', 0, '李曰垓', '{MOD}', ''),
(3165, 'admin', 0, '何家栋', '{MOD}', ''),
(3166, 'admin', 0, '张丕林', '{MOD}', ''),
(3167, 'admin', 0, '伊力哈木', '{MOD}', ''),
(3168, 'admin', 0, '土赫提', '{MOD}', ''),
(3169, 'admin', 0, '王力雄', '{MOD}', ''),
(3170, 'admin', 0, '马英九', '{MOD}', ''),
(3171, 'admin', 0, '连战', '{MOD}', ''),
(3172, 'admin', 0, '宋楚瑜', '{MOD}', ''),
(3173, 'admin', 0, '蒋经国', '{MOD}', ''),
(3174, 'admin', 0, '蒋介石', '{MOD}', ''),
(3175, 'admin', 0, '水扁', '{MOD}', ''),
(3176, 'admin', 0, '江炳坤', '{MOD}', ''),
(3177, 'admin', 0, '王金平', '{MOD}', ''),
(3178, 'admin', 0, '蒋光头', '{MOD}', ''),
(3179, 'admin', 0, '达赖', '{MOD}', ''),
(3180, 'admin', 0, '喇嘛尊者', '{MOD}', ''),
(3181, 'admin', 0, '桑东仁波切', '{MOD}', ''),
(3182, 'admin', 0, '格桑平措', '{MOD}', ''),
(3183, 'admin', 0, '平措旺杰', '{MOD}', ''),
(3184, 'admin', 0, '丹增曲杰', '{MOD}', ''),
(3185, 'admin', 0, '次旺仁增', '{MOD}', ''),
(3186, 'admin', 0, '嘉日多玛', '{MOD}', ''),
(3187, 'admin', 0, '比次仁', '{MOD}', ''),
(3188, 'admin', 0, '拉顿德通', '{MOD}', ''),
(3189, 'admin', 0, '嘎玛群培', '{MOD}', ''),
(3190, 'admin', 0, '王千源', '{MOD}', ''),
(3191, 'admin', 0, '热比娅', '{MOD}', ''),
(3192, 'admin', 0, '热比压', '{MOD}', ''),
(3193, 'admin', 0, '热比亚', '{MOD}', ''),
(3194, 'admin', 0, '姜玉国', '{MOD}', ''),
(3195, 'admin', 0, '冉建新', '{MOD}', ''),
(3196, 'admin', 0, '汪辜', '{MOD}', ''),
(3197, 'admin', 0, '关小忠', '{MOD}', ''),
(3198, 'admin', 0, '张舟', '{MOD}', ''),
(3199, 'admin', 0, '阎明复', '{MOD}', ''),
(3200, 'admin', 0, '昝爱宗', '{MOD}', ''),
(3201, 'admin', 0, '周小舟', '{MOD}', ''),
(3202, 'admin', 0, '林名昭者', '{MOD}', ''),
(3203, 'admin', 0, '李庄', '{MOD}', ''),
(3204, 'admin', 0, '林前利', '{MOD}', ''),
(3205, 'admin', 0, '李承晚', '{MOD}', ''),
(3206, 'admin', 0, '宋祖英', '{MOD}', ''),
(3207, 'admin', 0, '杨一刀', '{MOD}', ''),
(3208, 'admin', 0, '耳光乐队', '{MOD}', ''),
(3209, 'admin', 0, '薛锦波', '{MOD}', ''),
(3210, 'admin', 0, '六.四', '{MOD}', ''),
(3211, 'admin', 0, '陆月肆日', '{MOD}', ''),
(3212, 'admin', 0, '陆肆', '{MOD}', ''),
(3213, 'admin', 0, '陆四', '{MOD}', ''),
(3214, 'admin', 0, 'sixfour', '{MOD}', ''),
(3215, 'admin', 0, '六肆', '{MOD}', ''),
(3216, 'admin', 0, '4-Jun', '{MOD}', ''),
(3217, 'admin', 0, '4thJune', '{MOD}', ''),
(3218, 'admin', 0, '本月的4日', '{MOD}', ''),
(3219, 'admin', 0, '六点四事件', '{MOD}', ''),
(3220, 'admin', 0, '坦克男', '{MOD}', ''),
(3221, 'admin', 0, '挡坦克', '{MOD}', ''),
(3222, 'admin', 0, '写在六四', '{MOD}', ''),
(3223, 'admin', 0, '六四华诞', '{MOD}', ''),
(3224, 'admin', 0, '六四来了', '{MOD}', ''),
(3225, 'admin', 0, '64深夜', '{MOD}', ''),
(3226, 'admin', 0, '第三十八军', '{MOD}', ''),
(3227, 'admin', 0, '天安门事件', '{MOD}', ''),
(3228, 'admin', 0, '6.3事件', '{MOD}', ''),
(3229, 'admin', 0, '八九年春天', '{MOD}', ''),
(3230, 'admin', 0, '75事件', '{MOD}', ''),
(3231, 'admin', 0, 'ML花', '{MOD}', ''),
(3232, 'admin', 0, '梅花革命', '{MOD}', ''),
(3233, 'admin', 0, '牡丹花革命', '{MOD}', ''),
(3234, 'admin', 0, '金达莱', '{MOD}', ''),
(3235, 'admin', 0, '映山红革命', '{MOD}', ''),
(3236, 'admin', 0, '茉滤花', '{MOD}', ''),
(3237, 'admin', 0, '牡丹花事件', '{MOD}', ''),
(3238, 'admin', 0, '刺玫瑰革命', '{MOD}', ''),
(3239, 'admin', 0, '周末花', '{MOD}', ''),
(3240, 'admin', 0, '周末茉莉', '{MOD}', ''),
(3241, 'admin', 0, '花革命', '{MOD}', ''),
(3242, 'admin', 0, '花行动', '{MOD}', ''),
(3243, 'admin', 0, '盐色革命', '{MOD}', ''),
(3244, 'admin', 0, '颜色革命', '{MOD}', ''),
(3245, 'admin', 0, '北韩', '{MOD}', ''),
(3246, 'admin', 0, '苏联', '{MOD}', ''),
(3247, 'admin', 0, '终国', '{MOD}', ''),
(3248, 'admin', 0, '政权', '{MOD}', ''),
(3249, 'admin', 0, '胡温政权', '{MOD}', ''),
(3250, 'admin', 0, '红色高棉', '{MOD}', ''),
(3251, 'admin', 0, '体制', '{MOD}', ''),
(3252, 'admin', 0, '三权分立', '{MOD}', ''),
(3253, 'admin', 0, '君主立宪', '{MOD}', ''),
(3254, 'admin', 0, '民主共和', '{MOD}', ''),
(3255, 'admin', 0, '封建社会', '{MOD}', ''),
(3256, 'admin', 0, '奴隶社会', '{MOD}', ''),
(3257, 'admin', 0, '奴隶制度', '{MOD}', ''),
(3258, 'admin', 0, '封建制度', '{MOD}', ''),
(3259, 'admin', 0, '人民民主专政', '{MOD}', ''),
(3260, 'admin', 0, '无产阶级专政', '{MOD}', ''),
(3261, 'admin', 0, '人民代表大会', '{MOD}', ''),
(3262, 'admin', 0, '民主协商制', '{MOD}', ''),
(3263, 'admin', 0, '多党合作', '{MOD}', ''),
(3264, 'admin', 0, '中国教育', '{MOD}', ''),
(3265, 'admin', 0, '区域自治', '{MOD}', ''),
(3266, 'admin', 0, '钟国', '{MOD}', ''),
(3267, 'admin', 0, '必亡国', '{MOD}', ''),
(3268, 'admin', 0, '瓷器国', '{MOD}', ''),
(3269, 'admin', 0, '江西抚州爆炸', '{MOD}', ''),
(3270, 'admin', 0, '螺蛳湾强拆', '{MOD}', ''),
(3271, 'admin', 0, '新塘事件', '{MOD}', ''),
(3272, 'admin', 0, '爆发游行', '{MOD}', ''),
(3273, 'admin', 0, '割命', '{MOD}', ''),
(3274, 'admin', 0, '大规模抗议', '{MOD}', ''),
(3275, 'admin', 0, '怒烧警车', '{MOD}', ''),
(3276, 'admin', 0, '20thgeming', '{MOD}', ''),
(3277, 'admin', 0, '20thge命', '{MOD}', ''),
(3278, 'admin', 0, '格ming', '{MOD}', ''),
(3279, 'admin', 0, '格命', '{MOD}', ''),
(3280, 'admin', 0, '拆迁自焚', '{MOD}', ''),
(3281, 'admin', 0, '血房地图', '{MOD}', ''),
(3282, 'admin', 0, '保钓游行', '{MOD}', ''),
(3283, 'admin', 0, '学生静坐', '{MOD}', ''),
(3284, 'admin', 0, '校园静坐', '{MOD}', ''),
(3285, 'admin', 0, '天鹅绒革命', '{MOD}', ''),
(3286, 'admin', 0, '天鹅绒行动', '{MOD}', ''),
(3287, 'admin', 0, '拆迁', '{MOD}', ''),
(3288, 'admin', 0, '强拆', '{MOD}', ''),
(3289, 'admin', 0, '强制拆迁', '{MOD}', ''),
(3290, 'admin', 0, '强迁', '{MOD}', ''),
(3291, 'admin', 0, '强征', '{MOD}', ''),
(3292, 'admin', 0, '鎮壓', '{MOD}', ''),
(3293, 'admin', 0, '虐杀', '{MOD}', ''),
(3294, 'admin', 0, '剥削', '{MOD}', ''),
(3295, 'admin', 0, '封锁', '{MOD}', ''),
(3296, 'admin', 0, '屠杀', '{MOD}', ''),
(3297, 'admin', 0, '镇压', '{MOD}', ''),
(3298, 'admin', 0, '要禁', '{MOD}', ''),
(3299, 'admin', 0, '釒真压', '{MOD}', ''),
(3300, 'admin', 0, '关押', '{MOD}', ''),
(3301, 'admin', 0, '野蛮执法', '{MOD}', ''),
(3302, 'admin', 0, '喇嘛游行', '{MOD}', ''),
(3303, 'admin', 0, '全民直选', '{MOD}', ''),
(3304, 'admin', 0, '群众示威', '{MOD}', ''),
(3305, 'admin', 0, '黑衣游行', '{MOD}', ''),
(3306, 'admin', 0, '群体事件', '{MOD}', ''),
(3307, 'admin', 0, '绝食抗暴', '{MOD}', ''),
(3308, 'admin', 0, '绝食抗议', '{MOD}', ''),
(3309, 'admin', 0, '退团', '{MOD}', ''),
(3310, 'admin', 0, '黑保安', '{MOD}', ''),
(3311, 'admin', 0, '黑监狱', '{MOD}', ''),
(3312, 'admin', 0, '黑砖窑', '{MOD}', ''),
(3313, 'admin', 0, '奴隷集団', '{MOD}', ''),
(3314, 'admin', 0, '奴役童工', '{MOD}', ''),
(3315, 'admin', 0, '戒严', '{MOD}', ''),
(3316, 'admin', 0, '舆论反制', '{MOD}', ''),
(3317, 'admin', 0, '新闻封锁', '{MOD}', ''),
(3318, 'admin', 0, '一党专政', '{MOD}', ''),
(3319, 'admin', 0, '出动坦克', '{MOD}', ''),
(3320, 'admin', 0, '抢钱', '{MOD}', ''),
(3321, 'admin', 0, '截访', '{MOD}', ''),
(3322, 'admin', 0, '军警镇压', '{MOD}', ''),
(3323, 'admin', 0, '党禁', '{MOD}', ''),
(3324, 'admin', 0, '警察殴打', '{MOD}', ''),
(3325, 'admin', 0, '洗瑙', '{MOD}', ''),
(3326, 'admin', 0, '器官黑幕', '{MOD}', ''),
(3327, 'admin', 0, '报禁', '{MOD}', ''),
(3328, 'admin', 0, '维稳', '{MOD}', ''),
(3329, 'admin', 0, '压榨百姓血汗钱', '{MOD}', ''),
(3330, 'admin', 0, '玩弄老百姓', '{MOD}', ''),
(3331, 'admin', 0, '逼着老百姓', '{MOD}', ''),
(3332, 'admin', 0, '群体灭绝', '{MOD}', ''),
(3333, 'admin', 0, '侵占', '{MOD}', ''),
(3334, 'admin', 0, '欺诈', '{MOD}', ''),
(3335, 'admin', 0, '欺负百姓', '{MOD}', ''),
(3336, 'admin', 0, '欺压百姓', '{MOD}', ''),
(3337, 'admin', 0, '提供保护伞', '{MOD}', ''),
(3338, 'admin', 0, '强行拖走', '{MOD}', ''),
(3339, 'admin', 0, '上天上人间', '{MOD}', ''),
(3340, 'admin', 0, '包二奶', '{MOD}', ''),
(3341, 'admin', 0, '吃拿卡要', '{MOD}', ''),
(3342, 'admin', 0, '公款挥霍', '{MOD}', ''),
(3343, 'admin', 0, '以权谋私', '{MOD}', ''),
(3344, 'admin', 0, '索贿', '{MOD}', ''),
(3345, 'admin', 0, '受贿', '{MOD}', ''),
(3346, 'admin', 0, '公款旅游', '{MOD}', ''),
(3347, 'admin', 0, '外逃', '{MOD}', ''),
(3348, 'admin', 0, '煽动', '{MOD}', ''),
(3349, 'admin', 0, '做戏', '{MOD}', ''),
(3350, 'admin', 0, '特权', '{MOD}', ''),
(3351, 'admin', 0, '大墩闹事', '{MOD}', ''),
(3352, 'admin', 0, '防民之口胜于防川', '{MOD}', ''),
(3353, 'admin', 0, '欺压老百姓', '{MOD}', ''),
(3354, 'admin', 0, '把人民当猪养', '{MOD}', ''),
(3355, 'admin', 0, '把人民当猪宰', '{MOD}', ''),
(3356, 'admin', 0, '把人民当猪卖', '{MOD}', ''),
(3357, 'admin', 0, '一中一台', '{MOD}', ''),
(3358, 'admin', 0, '岛内“独派”', '{MOD}', ''),
(3359, 'admin', 0, '台读', '{MOD}', ''),
(3360, 'admin', 0, '台毒', '{MOD}', ''),
(3361, 'admin', 0, '台du', '{MOD}', ''),
(3362, 'admin', 0, '蒙古独立', '{MOD}', ''),
(3363, 'admin', 0, '四川独立', '{MOD}', ''),
(3364, 'admin', 0, '新疆独立', '{MOD}', ''),
(3365, 'admin', 0, '西藏独立', '{MOD}', ''),
(3366, 'admin', 0, '蒙独', '{MOD}', ''),
(3367, 'admin', 0, '声援西藏', '{MOD}', ''),
(3368, 'admin', 0, '东北独立', '{MOD}', ''),
(3369, 'admin', 0, '决战在西藏', '{MOD}', ''),
(3370, 'admin', 0, '西藏抗暴', '{MOD}', ''),
(3371, 'admin', 0, '西藏正义', '{MOD}', ''),
(3372, 'admin', 0, '反攻大陆', '{MOD}', ''),
(3373, 'admin', 0, '台湾共和国', '{MOD}', ''),
(3374, 'admin', 0, '暴政', '{MOD}', ''),
(3375, 'admin', 0, '不民主', '{MOD}', ''),
(3376, 'admin', 0, '执法不严', '{MOD}', ''),
(3377, 'admin', 0, '清政府', '{MOD}', ''),
(3378, 'admin', 0, '不讲民主', '{MOD}', ''),
(3379, 'admin', 0, '失职', '{MOD}', ''),
(3380, 'admin', 0, '河蟹', '{MOD}', ''),
(3381, 'admin', 0, '滥印货币', '{MOD}', ''),
(3382, 'admin', 0, '货币泛滥', '{MOD}', ''),
(3383, 'admin', 0, '权利运用', '{MOD}', ''),
(3384, 'admin', 0, '腐朽的国家', '{MOD}', ''),
(3385, 'admin', 0, '反人类', '{MOD}', ''),
(3386, 'admin', 0, '道貌岸然', '{MOD}', ''),
(3387, 'admin', 0, '专权', '{MOD}', ''),
(3388, 'admin', 0, '已经腐朽', '{MOD}', ''),
(3389, 'admin', 0, '黑暗', '{MOD}', ''),
(3390, 'admin', 0, '动荡', '{MOD}', ''),
(3391, 'admin', 0, '暴力', '{MOD}', ''),
(3392, 'admin', 0, '非法', '{MOD}', ''),
(3393, 'admin', 0, '强制', '{MOD}', ''),
(3394, 'admin', 0, '野蛮', '{MOD}', ''),
(3395, 'admin', 0, '办黑案', '{MOD}', ''),
(3396, 'admin', 0, '收黑钱', '{MOD}', ''),
(3397, 'admin', 0, '独裁', '{MOD}', ''),
(3398, 'admin', 0, '党天下', '{MOD}', ''),
(3399, 'admin', 0, '专制', '{MOD}', ''),
(3400, 'admin', 0, '阴险', '{MOD}', ''),
(3401, 'admin', 0, '东亚病夫', '{MOD}', ''),
(3402, 'admin', 0, '愚化', '{MOD}', ''),
(3403, 'admin', 0, '声讨', '{MOD}', ''),
(3404, 'admin', 0, '悲惨', '{MOD}', ''),
(3405, 'admin', 0, '误国', '{MOD}', ''),
(3406, 'admin', 0, '没有民主', '{MOD}', ''),
(3407, 'admin', 0, '国将不国', '{MOD}', ''),
(3408, 'admin', 0, '昧着良心', '{MOD}', ''),
(3409, 'admin', 0, '傀儡', '{MOD}', ''),
(3410, 'admin', 0, '傀垒', '{MOD}', ''),
(3411, 'admin', 0, '杀光', '{MOD}', ''),
(3412, 'admin', 0, '占领', '{MOD}', ''),
(3413, 'admin', 0, '笑贫不笑娼', '{MOD}', ''),
(3414, 'admin', 0, '亡国', '{MOD}', ''),
(3415, 'admin', 0, '讨伐', '{MOD}', ''),
(3416, 'admin', 0, '突破', '{MOD}', ''),
(3417, 'admin', 0, '人渣', '{MOD}', ''),
(3418, 'admin', 0, '清算', '{MOD}', ''),
(3419, 'admin', 0, '驱逐', '{MOD}', ''),
(3420, 'admin', 0, '生不如死', '{MOD}', ''),
(3421, 'admin', 0, '搜刮', '{MOD}', ''),
(3422, 'admin', 0, '内忧外患', '{MOD}', ''),
(3423, 'admin', 0, '碾死', '{MOD}', ''),
(3424, 'admin', 0, '丧失人性', '{MOD}', ''),
(3425, 'admin', 0, '赤化', '{MOD}', ''),
(3426, 'admin', 0, '目田', '{MOD}', ''),
(3427, 'admin', 0, '起义', '{MOD}', ''),
(3428, 'admin', 0, '无法无天', '{MOD}', ''),
(3429, 'admin', 0, '最无能的', '{MOD}', ''),
(3430, 'admin', 0, '没有良心', '{MOD}', ''),
(3431, 'admin', 0, '邪教', '{MOD}', ''),
(3432, 'admin', 0, '法西斯', '{MOD}', ''),
(3433, 'admin', 0, '一党执政', '{MOD}', ''),
(3434, 'admin', 0, '权力斗争', '{MOD}', ''),
(3435, 'admin', 0, '一D独大', '{MOD}', ''),
(3436, 'admin', 0, '一党专制', '{MOD}', ''),
(3437, 'admin', 0, '一谠砖政', '{MOD}', ''),
(3438, 'admin', 0, '汉奸辈出', '{MOD}', ''),
(3439, 'admin', 0, '瘟神当权', '{MOD}', ''),
(3440, 'admin', 0, '极权', '{MOD}', ''),
(3441, 'admin', 0, '共奴', '{MOD}', ''),
(3442, 'admin', 0, '一党独大', '{MOD}', ''),
(3443, 'admin', 0, '纳粹', '{MOD}', ''),
(3444, 'admin', 0, '贪腐', '{MOD}', ''),
(3445, 'admin', 0, '抚拜', '{MOD}', ''),
(3446, 'admin', 0, '地位不稳', '{MOD}', ''),
(3447, 'admin', 0, '改朝换代', '{MOD}', ''),
(3448, 'admin', 0, '下台', '{MOD}', ''),
(3449, 'admin', 0, '被撤销', '{MOD}', ''),
(3450, 'admin', 0, '投降', '{MOD}', ''),
(3451, 'admin', 0, '会垮的', '{MOD}', ''),
(3452, 'admin', 0, '需要重组', '{MOD}', ''),
(3453, 'admin', 0, '必亡', '{MOD}', ''),
(3454, 'admin', 0, '要完了', '{MOD}', ''),
(3455, 'admin', 0, '无药可救', '{MOD}', ''),
(3456, 'admin', 0, '早点亡了', '{MOD}', ''),
(3457, 'admin', 0, '衰亡', '{MOD}', ''),
(3458, 'admin', 0, '无药可治', '{MOD}', ''),
(3459, 'admin', 0, '推倒重来', '{MOD}', ''),
(3460, 'admin', 0, '堕落', '{MOD}', ''),
(3461, 'admin', 0, '国富民穷', '{MOD}', ''),
(3462, 'admin', 0, '体制歪', '{MOD}', ''),
(3463, 'admin', 0, '法律沦陷', '{MOD}', ''),
(3464, 'admin', 0, '陷入内乱', '{MOD}', ''),
(3465, 'admin', 0, '灭亡', '{MOD}', ''),
(3466, 'admin', 0, '天灭', '{MOD}', ''),
(3467, 'admin', 0, '完岁', '{MOD}', ''),
(3468, 'admin', 0, '坚持不到', '{MOD}', ''),
(3469, 'admin', 0, '党风日下', '{MOD}', ''),
(3470, 'admin', 0, '仇视', '{MOD}', ''),
(3471, 'admin', 0, '打到', '{MOD}', ''),
(3472, 'admin', 0, '渗透', '{MOD}', ''),
(3473, 'admin', 0, '赶下去', '{MOD}', ''),
(3474, 'admin', 0, '倒台', '{MOD}', ''),
(3475, 'admin', 0, '全盘否定', '{MOD}', ''),
(3476, 'admin', 0, '暴动', '{MOD}', ''),
(3477, 'admin', 0, '暴動', '{MOD}', ''),
(3478, 'admin', 0, '静坐', '{MOD}', ''),
(3479, 'admin', 0, '靜坐', '{MOD}', ''),
(3480, 'admin', 0, '自焚', '{MOD}', '');
INSERT INTO `pre_common_word` (`id`, `admin`, `type`, `find`, `replacement`, `extra`) VALUES
(3481, 'admin', 0, '暴乱', '{MOD}', ''),
(3482, 'admin', 0, '请愿', '{MOD}', ''),
(3483, 'admin', 0, '骚乱', '{MOD}', ''),
(3484, 'admin', 0, '抗暴', '{MOD}', ''),
(3485, 'admin', 0, '颠覆', '{MOD}', ''),
(3486, 'admin', 0, '动乱', '{MOD}', ''),
(3487, 'admin', 0, '民运', '{MOD}', ''),
(3488, 'admin', 0, '去tam抗议', '{MOD}', ''),
(3489, 'admin', 0, '绝食', '{MOD}', ''),
(3490, 'admin', 0, '残杀', '{MOD}', ''),
(3491, 'admin', 0, '闹事', '{MOD}', ''),
(3492, 'admin', 0, '流亡', '{MOD}', ''),
(3493, 'admin', 0, '聚众', '{MOD}', ''),
(3494, 'admin', 0, '爆炸', '{MOD}', ''),
(3495, 'admin', 0, '党內斗', '{MOD}', ''),
(3496, 'admin', 0, '官奸勾结', '{MOD}', ''),
(3497, 'admin', 0, '社会乱了', '{MOD}', ''),
(3498, 'admin', 0, '变态的社会', '{MOD}', ''),
(3499, 'admin', 0, '悲哀的国度', '{MOD}', ''),
(3500, 'admin', 0, '流氓国度', '{MOD}', ''),
(3501, 'admin', 0, '可笑的国度', '{MOD}', ''),
(3502, 'admin', 0, '万恶的社会', '{MOD}', ''),
(3503, 'admin', 0, '官官相护', '{MOD}', ''),
(3504, 'admin', 0, '伟大的国度', '{MOD}', ''),
(3505, 'admin', 0, '畸形的社会', '{MOD}', ''),
(3506, 'admin', 0, '神奇的国度', '{MOD}', ''),
(3507, 'admin', 0, '祸国殃民', '{MOD}', ''),
(3508, 'admin', 0, '变态的中国', '{MOD}', ''),
(3509, 'admin', 0, '合法的流氓', '{MOD}', ''),
(3510, 'admin', 0, '合法的强盗', '{MOD}', ''),
(3511, 'admin', 0, '治人的国度', '{MOD}', ''),
(3512, 'admin', 0, '恶心的国度', '{MOD}', ''),
(3513, 'admin', 0, '窝囊中国', '{MOD}', ''),
(3514, 'admin', 0, '神气的国度', '{MOD}', ''),
(3515, 'admin', 0, '政坛腐败', '{MOD}', ''),
(3516, 'admin', 0, '毒裁', '{MOD}', ''),
(3517, 'admin', 0, '奇怪的国家', '{MOD}', ''),
(3518, 'admin', 0, '毒才', '{MOD}', ''),
(3519, 'admin', 0, '独菜', '{MOD}', ''),
(3520, 'admin', 0, '警匪一家', '{MOD}', ''),
(3521, 'admin', 0, '贪腐成性', '{MOD}', ''),
(3522, 'admin', 0, '官商交逼', '{MOD}', ''),
(3523, 'admin', 0, '练zhong功', '{MOD}', ''),
(3524, 'admin', 0, '猫时代', '{MOD}', ''),
(3525, 'admin', 0, 'china(拆哪?)', '{MOD}', ''),
(3526, 'admin', 0, '鸡娣屁', '{MOD}', ''),
(3527, 'admin', 0, '鸡的屁', '{MOD}', ''),
(3528, 'admin', 0, '道德沦丧', '{MOD}', ''),
(3529, 'admin', 0, '附庸主义', '{MOD}', ''),
(3530, 'admin', 0, '多党执政', '{MOD}', ''),
(3531, 'admin', 0, '官逼民反', '{MOD}', ''),
(3532, 'admin', 0, '请愿书', '{MOD}', ''),
(3533, 'admin', 0, '朝廷威武', '{MOD}', ''),
(3534, 'admin', 0, '爱朝廷', '{MOD}', ''),
(3535, 'admin', 0, '正义法院', '{MOD}', ''),
(3536, 'admin', 0, '官宦之家', '{MOD}', ''),
(3537, 'admin', 0, '一国两党', '{MOD}', ''),
(3538, 'admin', 0, '民主自由', '{MOD}', ''),
(3539, 'admin', 0, '狗屁GDP', '{MOD}', ''),
(3540, 'admin', 0, '昏官贪官', '{MOD}', ''),
(3541, 'admin', 0, '不能治官', '{MOD}', ''),
(3542, 'admin', 0, '改变体制', '{MOD}', ''),
(3543, 'admin', 0, '什么世道', '{MOD}', ''),
(3544, 'admin', 0, '社会不公', '{MOD}', ''),
(3545, 'admin', 0, '政治改革', '{MOD}', ''),
(3546, 'admin', 0, '富不与官争', '{MOD}', ''),
(3547, 'admin', 0, '毛时代', '{MOD}', ''),
(3548, 'admin', 0, '政府的恩典', '{MOD}', ''),
(3549, 'admin', 0, '民主阵线', '{MOD}', ''),
(3550, 'admin', 0, '非法集资', '{MOD}', ''),
(3551, 'admin', 0, '九贫', '{MOD}', ''),
(3552, 'admin', 0, '驱逐马列', '{MOD}', ''),
(3553, 'admin', 0, '掐死花朵', '{MOD}', ''),
(3554, 'admin', 0, '社会民主', '{MOD}', ''),
(3555, 'admin', 0, '安乐掉', '{MOD}', ''),
(3556, 'admin', 0, '圣政', '{MOD}', ''),
(3557, 'admin', 0, '师父法身', '{MOD}', ''),
(3558, 'admin', 0, '制造战争', '{MOD}', ''),
(3559, 'admin', 0, '多党选举', '{MOD}', ''),
(3560, 'admin', 0, '民主宪政', '{MOD}', ''),
(3561, 'admin', 0, '谁是新中国', '{MOD}', ''),
(3562, 'admin', 0, '天助天下百姓', '{MOD}', ''),
(3563, 'admin', 0, '四个坚持', '{MOD}', ''),
(3564, 'admin', 0, '四项原则', '{MOD}', ''),
(3565, 'admin', 0, '苏东解体', '{MOD}', ''),
(3566, 'admin', 0, '泰国政变', '{MOD}', ''),
(3567, 'admin', 0, '西藏信息中心', '{MOD}', ''),
(3568, 'admin', 0, '西藏基金会', '{MOD}', ''),
(3569, 'admin', 0, '西部律师', '{MOD}', ''),
(3570, 'admin', 0, '五四讲话', '{MOD}', ''),
(3571, 'admin', 0, '五中全会', '{MOD}', ''),
(3572, 'admin', 0, '促谐诉讼', '{MOD}', ''),
(3573, 'admin', 0, '我们要公义', '{MOD}', ''),
(3574, 'admin', 0, '我们要公平', '{MOD}', ''),
(3575, 'admin', 0, '文字狱', '{MOD}', ''),
(3576, 'admin', 0, '天佑中华', '{MOD}', ''),
(3577, 'admin', 0, '超越红墙', '{MOD}', ''),
(3578, 'admin', 0, '万古天门今已开', '{MOD}', ''),
(3579, 'admin', 0, '台湾意识', '{MOD}', ''),
(3580, 'admin', 0, '史垢国垢', '{MOD}', ''),
(3581, 'admin', 0, '权力监督', '{MOD}', ''),
(3582, 'admin', 0, '鱼民正厕', '{MOD}', ''),
(3583, 'admin', 0, '五不搞', '{MOD}', ''),
(3584, 'admin', 0, '5不搞', '{MOD}', ''),
(3585, 'admin', 0, '国家无奈', '{MOD}', ''),
(3586, 'admin', 0, '猫论', '{MOD}', ''),
(3587, 'admin', 0, '贪官奸商', '{MOD}', ''),
(3588, 'admin', 0, '官场', '{MOD}', ''),
(3589, 'admin', 0, '纪检何在', '{MOD}', ''),
(3590, 'admin', 0, '检察何在', '{MOD}', ''),
(3591, 'admin', 0, '人大何在', '{MOD}', ''),
(3592, 'admin', 0, '政协何在', '{MOD}', ''),
(3593, 'admin', 0, '旧社会', '{MOD}', ''),
(3594, 'admin', 0, '市政管理', '{MOD}', ''),
(3595, 'admin', 0, '中国民主', '{MOD}', ''),
(3596, 'admin', 0, '雪山狮子', '{MOD}', ''),
(3597, 'admin', 0, '棺棺相护', '{MOD}', ''),
(3598, 'admin', 0, '文革', '{MOD}', ''),
(3599, 'admin', 0, '官媒', '{MOD}', ''),
(3600, 'admin', 0, '反革命暴乱', '{MOD}', ''),
(3601, 'admin', 0, '515事件', '{MOD}', ''),
(3602, 'admin', 0, '国民的审判', '{MOD}', ''),
(3603, 'admin', 0, '十八大', '{MOD}', ''),
(3604, 'admin', 0, '无界限浏览', '{MOD}', ''),
(3605, 'admin', 0, '国家的囚徒', '{MOD}', ''),
(3606, 'admin', 0, '中国事务', '{MOD}', ''),
(3607, 'admin', 0, '家在仙宫不在尘', '{MOD}', ''),
(3608, 'admin', 0, '强国论坛', '{MOD}', ''),
(3609, 'admin', 0, '亲共行动', '{MOD}', ''),
(3610, 'admin', 0, '亲共来源', '{MOD}', ''),
(3611, 'admin', 0, '请用文明来说服我', '{MOD}', ''),
(3612, 'admin', 0, '天葬', '{MOD}', ''),
(3613, 'admin', 0, '强盗警察', '{MOD}', ''),
(3614, 'admin', 0, '流氓警察', '{MOD}', ''),
(3615, 'admin', 0, '隐蔽税种', '{MOD}', ''),
(3616, 'admin', 0, '高价药', '{MOD}', ''),
(3617, 'admin', 0, '领导自杀', '{MOD}', ''),
(3618, 'admin', 0, '权利寻租', '{MOD}', ''),
(3619, 'admin', 0, '权力寻租', '{MOD}', ''),
(3620, 'admin', 0, '官官相互', '{MOD}', ''),
(3621, 'admin', 0, '支持长平', '{MOD}', ''),
(3622, 'admin', 0, '江力挺俞', '{MOD}', ''),
(3623, 'admin', 0, '民猪', '{MOD}', ''),
(3624, 'admin', 0, '歌功颂德', '{MOD}', ''),
(3625, 'admin', 0, '北京当局', '{MOD}', ''),
(3626, 'admin', 0, '天怒', '{MOD}', ''),
(3627, 'admin', 0, '反社会', '{MOD}', ''),
(3628, 'admin', 0, '学潮', '{MOD}', ''),
(3629, 'admin', 0, '草菅人命', '{MOD}', ''),
(3630, 'admin', 0, '上层的贪法', '{MOD}', ''),
(3631, 'admin', 0, '贪官字弟', '{MOD}', ''),
(3632, 'admin', 0, '逍遥法外', '{MOD}', ''),
(3633, 'admin', 0, '因言获罪', '{MOD}', ''),
(3634, 'admin', 0, '拆迁条例', '{MOD}', ''),
(3635, 'admin', 0, '抵制中国货', '{MOD}', ''),
(3636, 'admin', 0, '强盗逻辑', '{MOD}', ''),
(3637, 'admin', 0, '全民游行', '{MOD}', ''),
(3638, 'admin', 0, '“中修”', '{MOD}', ''),
(3639, 'admin', 0, '“九 一八”', '{MOD}', ''),
(3640, 'admin', 0, '官僚体制', '{MOD}', ''),
(3641, 'admin', 0, '暴力抗法', '{MOD}', ''),
(3642, 'admin', 0, '罢免官员', '{MOD}', ''),
(3643, 'admin', 0, '大陆当局', '{MOD}', ''),
(3644, 'admin', 0, '网络革命宣言', '{MOD}', ''),
(3645, 'admin', 0, '一国2党', '{MOD}', ''),
(3646, 'admin', 0, '狗屁政府', '{MOD}', ''),
(3647, 'admin', 0, '拆迁队', '{MOD}', ''),
(3648, 'admin', 0, '对抗拆迁', '{MOD}', ''),
(3649, 'admin', 0, 'fu中国ck', '{MOD}', ''),
(3650, 'admin', 0, '警匪一家亲', '{MOD}', ''),
(3651, 'admin', 0, '金家王朝', '{MOD}', ''),
(3652, 'admin', 0, '国M档', '{MOD}', ''),
(3653, 'admin', 0, '实现名嘱', '{MOD}', ''),
(3654, 'admin', 0, '流血的革命', '{MOD}', ''),
(3655, 'admin', 0, '喝血社会', '{MOD}', ''),
(3656, 'admin', 0, '城管猛于虎', '{MOD}', ''),
(3657, 'admin', 0, '被朝廷屏蔽', '{MOD}', ''),
(3658, 'admin', 0, '拆迁猛于虎', '{MOD}', ''),
(3659, 'admin', 0, 'zf100年', '{MOD}', ''),
(3660, 'admin', 0, '该死的XX委', '{MOD}', ''),
(3661, 'admin', 0, 'guo富min穷', '{MOD}', ''),
(3662, 'admin', 0, '天朝执政者', '{MOD}', ''),
(3663, 'admin', 0, '腐而不败', '{MOD}', ''),
(3664, 'admin', 0, '现政下台', '{MOD}', ''),
(3665, 'admin', 0, '裆说的话', '{MOD}', ''),
(3666, 'admin', 0, '解散政协', '{MOD}', ''),
(3667, 'admin', 0, '国耻日', '{MOD}', ''),
(3668, 'admin', 0, '传法之路', '{MOD}', ''),
(3669, 'admin', 0, '国殇日', '{MOD}', ''),
(3670, 'admin', 0, '硬冥领倒', '{MOD}', ''),
(3671, 'admin', 0, '以江为首', '{MOD}', ''),
(3672, 'admin', 0, '民主墙', '{MOD}', ''),
(3673, 'admin', 0, '内情真相', '{MOD}', ''),
(3674, 'admin', 0, '拉萨骚乱', '{MOD}', ''),
(3675, 'admin', 0, '民变', '{MOD}', ''),
(3676, 'admin', 0, 'Z政D', '{MOD}', ''),
(3677, 'admin', 0, '宪法35条', '{MOD}', ''),
(3678, 'admin', 0, '公开信', '{MOD}', ''),
(3679, 'admin', 0, '太子行贿', '{MOD}', ''),
(3680, 'admin', 0, '解放大陆', '{MOD}', ''),
(3681, 'admin', 0, '光复大陆', '{MOD}', ''),
(3682, 'admin', 0, '无介', '{MOD}', ''),
(3683, 'admin', 0, '台湾国', '{MOD}', ''),
(3684, 'admin', 0, '修炼之歌', '{MOD}', ''),
(3685, 'admin', 0, '正邪大决战', '{MOD}', ''),
(3686, 'admin', 0, '洗脑班', '{MOD}', ''),
(3687, 'admin', 0, '殃视', '{MOD}', ''),
(3688, 'admin', 0, '影子俱乐部', '{MOD}', ''),
(3689, 'admin', 0, '舆论钳制', '{MOD}', ''),
(3690, 'admin', 0, '正法时期', '{MOD}', ''),
(3691, 'admin', 0, '正派民运', '{MOD}', ''),
(3692, 'admin', 0, '政府软弱', '{MOD}', ''),
(3693, 'admin', 0, '政治风波', '{MOD}', ''),
(3694, 'admin', 0, '政治局', '{MOD}', ''),
(3695, 'admin', 0, '中俄密约', '{MOD}', ''),
(3696, 'admin', 0, '中国之春', '{MOD}', ''),
(3697, 'admin', 0, '中华联邦政府', '{MOD}', ''),
(3698, 'admin', 0, '周刊纪事', '{MOD}', ''),
(3699, 'admin', 0, '追查迫害法', '{MOD}', ''),
(3700, 'admin', 0, '自由写作奖', '{MOD}', ''),
(3701, 'admin', 0, '宗教压迫', '{MOD}', ''),
(3702, 'admin', 0, '宪章', '{MOD}', ''),
(3703, 'admin', 0, '宪政', '{MOD}', ''),
(3704, 'admin', 0, '消业论', '{MOD}', ''),
(3705, 'admin', 0, '新闻法', '{MOD}', ''),
(3706, 'admin', 0, '新闻管制', '{MOD}', ''),
(3707, 'admin', 0, '新闻通气会', '{MOD}', ''),
(3708, 'admin', 0, '新闻自由', '{MOD}', ''),
(3709, 'admin', 0, '新闻监督法', '{MOD}', ''),
(3710, 'admin', 0, '信息封锁', '{MOD}', ''),
(3711, 'admin', 0, '信仰自由', '{MOD}', ''),
(3712, 'admin', 0, '学生与警察', '{MOD}', ''),
(3713, 'admin', 0, '学员器官', '{MOD}', ''),
(3714, 'admin', 0, '学院暴动', '{MOD}', ''),
(3715, 'admin', 0, '学生运动', '{MOD}', ''),
(3716, 'admin', 0, '一边一国', '{MOD}', ''),
(3717, 'admin', 0, '伊斯兰运动', '{MOD}', ''),
(3718, 'admin', 0, '暴力恐怖', '{MOD}', ''),
(3719, 'admin', 0, '以身护法', '{MOD}', ''),
(3720, 'admin', 0, '以血护法', '{MOD}', ''),
(3721, 'admin', 0, '灭汉', '{MOD}', ''),
(3722, 'admin', 0, '政治恶棍', '{MOD}', ''),
(3723, 'admin', 0, '迫害大法', '{MOD}', ''),
(3724, 'admin', 0, '迫害法', '{MOD}', ''),
(3725, 'admin', 0, '海外渗透', '{MOD}', ''),
(3726, 'admin', 0, '劳工通讯', '{MOD}', ''),
(3727, 'admin', 0, '公民常识读本', '{MOD}', ''),
(3728, 'admin', 0, '信访报告', '{MOD}', ''),
(3729, 'admin', 0, '冤案录', '{MOD}', ''),
(3730, 'admin', 0, '权利游戏', '{MOD}', ''),
(3731, 'admin', 0, '中南海斗争', '{MOD}', ''),
(3732, 'admin', 0, '高层权利斗争', '{MOD}', ''),
(3733, 'admin', 0, '东宫小朝廷', '{MOD}', ''),
(3734, 'admin', 0, '中南海秘闻', '{MOD}', ''),
(3735, 'admin', 0, '中南海内斗', '{MOD}', ''),
(3736, 'admin', 0, '中南海内幕', '{MOD}', ''),
(3737, 'admin', 0, '中南海浓云密布', '{MOD}', ''),
(3738, 'admin', 0, '最淫官员', '{MOD}', ''),
(3739, 'admin', 0, '胡曾联手', '{MOD}', ''),
(3740, 'admin', 0, '瓮安暴乱', '{MOD}', ''),
(3741, 'admin', 0, '瓮安骚乱', '{MOD}', ''),
(3742, 'admin', 0, '两个中国', '{MOD}', ''),
(3743, 'admin', 0, '瓦解专制', '{MOD}', ''),
(3744, 'admin', 0, '西藏运动', '{MOD}', ''),
(3745, 'admin', 0, '网络管制', '{MOD}', ''),
(3746, 'admin', 0, '伪民运', '{MOD}', ''),
(3747, 'admin', 0, '伪政府', '{MOD}', ''),
(3748, 'admin', 0, '土匪政府', '{MOD}', ''),
(3749, 'admin', 0, '盐论自由', '{MOD}', ''),
(3750, 'admin', 0, '台湾狗', '{MOD}', ''),
(3751, 'admin', 0, '国共两党', '{MOD}', ''),
(3752, 'admin', 0, '利益链条', '{MOD}', ''),
(3753, 'admin', 0, '夜话紫禁城', '{MOD}', ''),
(3754, 'admin', 0, '雪山上的狮子旗', '{MOD}', ''),
(3755, 'admin', 0, '共和国之怒', '{MOD}', ''),
(3756, 'admin', 0, '毛匪', '{MOD}', ''),
(3757, 'admin', 0, '三独鼎立', '{MOD}', ''),
(3758, 'admin', 0, '闹独立', '{MOD}', ''),
(3759, 'admin', 0, '第五代政治团体', '{MOD}', ''),
(3760, 'admin', 0, '政变', '{MOD}', ''),
(3761, 'admin', 0, '反党', '{MOD}', ''),
(3762, 'admin', 0, '九之平', '{MOD}', ''),
(3763, 'admin', 0, '自由之门', '{MOD}', ''),
(3764, 'admin', 0, '权力交接', '{MOD}', ''),
(3765, 'admin', 0, 'Tibetan', '{MOD}', ''),
(3766, 'admin', 0, '官官相副', '{MOD}', ''),
(3767, 'admin', 0, '维吾尔族大会', '{MOD}', ''),
(3768, 'admin', 0, '打砸抢', '{MOD}', ''),
(3769, 'admin', 0, '七大军区', '{MOD}', ''),
(3770, 'admin', 0, '多党制', '{MOD}', ''),
(3771, 'admin', 0, '生活在新闻联播', '{MOD}', ''),
(3772, 'admin', 0, '十声笑', '{MOD}', ''),
(3773, 'admin', 0, 'GFW', '{MOD}', ''),
(3774, 'admin', 0, '潮州讨薪', '{MOD}', ''),
(3775, 'admin', 0, '失业灭掉70', '{MOD}', ''),
(3776, 'admin', 0, '地藏法门', '{MOD}', ''),
(3777, 'admin', 0, '密教经典', '{MOD}', ''),
(3778, 'admin', 0, '川川要命', '{MOD}', ''),
(3779, 'admin', 0, '拆了我房子', '{MOD}', ''),
(3780, 'admin', 0, '国必亡', '{MOD}', ''),
(3781, 'admin', 0, '拉登的遗嘱', '{MOD}', ''),
(3782, 'admin', 0, '敏感词', '{MOD}', ''),
(3783, 'admin', 0, '诺贝尔和平奖', '{MOD}', ''),
(3784, 'admin', 0, '清场内幕', '{MOD}', ''),
(3785, 'admin', 0, '维基解密', '{MOD}', ''),
(3786, 'admin', 0, '寂静之音', '{MOD}', ''),
(3787, 'admin', 0, '12种新大傻', '{MOD}', ''),
(3788, 'admin', 0, 'ip代理地址', '{MOD}', ''),
(3789, 'admin', 0, '天国现状', '{MOD}', ''),
(3790, 'admin', 0, '音画梦醒', '{MOD}', ''),
(3791, 'admin', 0, '真智慧真慈悲', '{MOD}', ''),
(3792, 'admin', 0, '四个伟大', '{MOD}', ''),
(3793, 'admin', 0, '潘名冠扶鸾', '{MOD}', ''),
(3794, 'admin', 0, '祈祷彼岸乐土', '{MOD}', ''),
(3795, 'admin', 0, '谣言和假象', '{MOD}', ''),
(3796, 'admin', 0, '民粹主义', '{MOD}', ''),
(3797, 'admin', 0, '慧律法师', '{MOD}', ''),
(3798, 'admin', 0, '归向真神耶稣', '{MOD}', ''),
(3799, 'admin', 0, '妖魔化民主', '{MOD}', ''),
(3800, 'admin', 0, '勿令沾湿勿令散乱', '{MOD}', ''),
(3801, 'admin', 0, '《六月之初》', '{MOD}', ''),
(3802, 'admin', 0, '提头自首案', '{MOD}', ''),
(3803, 'admin', 0, '心静如水舍得笑', '{MOD}', ''),
(3804, 'admin', 0, '防火墙之父', '{MOD}', ''),
(3805, 'admin', 0, '躲猫猫死去', '{MOD}', ''),
(3806, 'admin', 0, '官僚政治', '{MOD}', ''),
(3807, 'admin', 0, '蒋匪', '{MOD}', ''),
(3808, 'admin', 0, '政治走势', '{MOD}', ''),
(3809, 'admin', 0, 'Adaptation', '{MOD}', ''),
(3810, 'admin', 0, '利益链', '{MOD}', ''),
(3811, 'admin', 0, '瓷做的瓜子', '{MOD}', ''),
(3812, 'admin', 0, '福音时报', '{MOD}', ''),
(3813, 'admin', 0, '戒严学校', '{MOD}', ''),
(3814, 'admin', 0, '强拆者头颅', '{MOD}', ''),
(3815, 'admin', 0, '六木森森', '{MOD}', ''),
(3816, 'admin', 0, '如何翻墙', '{MOD}', ''),
(3817, 'admin', 0, '网络封锁', '{MOD}', ''),
(3818, 'admin', 0, '棚户区被强拆', '{MOD}', ''),
(3819, 'admin', 0, '5.23事件', '{MOD}', ''),
(3820, 'admin', 0, '去你的体制', '{MOD}', ''),
(3821, 'admin', 0, '本拉登遗书', '{MOD}', ''),
(3822, 'admin', 0, '抚州的爆炸', '{MOD}', ''),
(3823, 'admin', 0, '人渣的政府', '{MOD}', ''),
(3824, 'admin', 0, '枉法联盟', '{MOD}', ''),
(3825, 'admin', 0, '莫非D土', '{MOD}', ''),
(3826, 'admin', 0, '青天白日旗', '{MOD}', ''),
(3827, 'admin', 0, '晴天白日旗', '{MOD}', ''),
(3828, 'admin', 0, '中华民国', '{MOD}', ''),
(3829, 'admin', 0, '孤立越南', '{MOD}', ''),
(3830, 'admin', 0, '联合执政', '{MOD}', ''),
(3831, 'admin', 0, '万税', '{MOD}', ''),
(3832, 'admin', 0, '税赋猛于虎', '{MOD}', ''),
(3833, 'admin', 0, '瘟官', '{MOD}', ''),
(3834, 'admin', 0, '当官命短', '{MOD}', ''),
(3835, 'admin', 0, '“党的教育”', '{MOD}', ''),
(3836, 'admin', 0, '返公大陆', '{MOD}', ''),
(3837, 'admin', 0, '统一大陆', '{MOD}', ''),
(3838, 'admin', 0, '绝食就反贪', '{MOD}', ''),
(3839, 'admin', 0, '干部腐败', '{MOD}', ''),
(3840, 'admin', 0, '狗税务', '{MOD}', ''),
(3841, 'admin', 0, '谁还信政府', '{MOD}', ''),
(3842, 'admin', 0, 'du裁的dang', '{MOD}', ''),
(3843, 'admin', 0, '民主泉喷', '{MOD}', ''),
(3844, 'admin', 0, '党的后代', '{MOD}', ''),
(3845, 'admin', 0, '特权体制', '{MOD}', ''),
(3846, 'admin', 0, '红歌违规', '{MOD}', ''),
(3847, 'admin', 0, '不统不独不武', '{MOD}', ''),
(3848, 'admin', 0, '轮流执政', '{MOD}', ''),
(3849, 'admin', 0, '祸害台湾', '{MOD}', ''),
(3850, 'admin', 0, '磁鳝组织', '{MOD}', ''),
(3851, 'admin', 0, '与民争利', '{MOD}', ''),
(3852, 'admin', 0, '公款', '{MOD}', ''),
(3853, 'admin', 0, '执政派', '{MOD}', ''),
(3854, 'admin', 0, '税如牛毛', '{MOD}', ''),
(3855, 'admin', 0, '贪官太多', '{MOD}', ''),
(3856, 'admin', 0, '税多如牛毛', '{MOD}', ''),
(3857, 'admin', 0, '现代清朝', '{MOD}', ''),
(3858, 'admin', 0, '三公消费', '{MOD}', ''),
(3859, 'admin', 0, '假帐分央府', '{MOD}', ''),
(3860, 'admin', 0, '珠明洞观音', '{MOD}', ''),
(3861, 'admin', 0, '毛思想', '{MOD}', ''),
(3862, 'admin', 0, '强拆民房', '{MOD}', ''),
(3863, 'admin', 0, 'tianandoor事件', '{MOD}', ''),
(3864, 'admin', 0, 'tiananprotest', '{MOD}', ''),
(3865, 'admin', 0, '蒙牛阿拉', '{MOD}', ''),
(3866, 'admin', 0, '逐毛', '{MOD}', ''),
(3867, 'admin', 0, '讨伐中宣部', '{MOD}', ''),
(3868, 'admin', 0, '党富民贫', '{MOD}', ''),
(3869, 'admin', 0, '海外特务', '{MOD}', ''),
(3870, 'admin', 0, '胡家天下', '{MOD}', ''),
(3871, 'admin', 0, '维权诗集', '{MOD}', ''),
(3872, 'admin', 0, '台湾大劫难', '{MOD}', ''),
(3873, 'admin', 0, '两个凡是', '{MOD}', ''),
(3874, 'admin', 0, '去中国化', '{MOD}', ''),
(3875, 'admin', 0, '军政勾结', '{MOD}', ''),
(3876, 'admin', 0, '没有XXX就没有XXX', '{MOD}', ''),
(3877, 'admin', 0, '延安换妻', '{MOD}', ''),
(3878, 'admin', 0, '公费嫖鸡', '{MOD}', ''),
(3879, 'admin', 0, '政警工头', '{MOD}', ''),
(3880, 'admin', 0, '末世拍案惊奇', '{MOD}', ''),
(3881, 'admin', 0, '资本主义', '{MOD}', ''),
(3882, 'admin', 0, '专政', '{MOD}', ''),
(3883, 'admin', 0, '反动派', '{MOD}', ''),
(3884, 'admin', 0, '某国特色', '{MOD}', ''),
(3885, 'admin', 0, '以权换钱', '{MOD}', ''),
(3886, 'admin', 0, '青天白日满地红', '{MOD}', ''),
(3887, 'admin', 0, '暴利强拆', '{MOD}', ''),
(3888, 'admin', 0, '越反越腐', '{MOD}', ''),
(3889, 'admin', 0, '无官不贪', '{MOD}', ''),
(3890, 'admin', 0, '全民皆贪', '{MOD}', ''),
(3891, 'admin', 0, '结盟纪委', '{MOD}', ''),
(3892, 'admin', 0, '权利的垄断', '{MOD}', ''),
(3893, 'admin', 0, '官场之黑', '{MOD}', ''),
(3894, 'admin', 0, '假人办假案', '{MOD}', ''),
(3895, 'admin', 0, '一群土匪', '{MOD}', ''),
(3896, 'admin', 0, '要求见尸体', '{MOD}', ''),
(3897, 'admin', 0, '永州枪击', '{MOD}', ''),
(3898, 'admin', 0, '握权法', '{MOD}', ''),
(3899, 'admin', 0, '照旧腐败', '{MOD}', ''),
(3900, 'admin', 0, '腐败奢华', '{MOD}', ''),
(3901, 'admin', 0, '世道真操蛋', '{MOD}', ''),
(3902, 'admin', 0, '谋取利益', '{MOD}', ''),
(3903, 'admin', 0, '法在哪里', '{MOD}', ''),
(3904, 'admin', 0, '膨胀的权力', '{MOD}', ''),
(3905, 'admin', 0, '地方政府', '{MOD}', ''),
(3906, 'admin', 0, '边腐边升', '{MOD}', ''),
(3907, 'admin', 0, '警察被黑打', '{MOD}', ''),
(3908, 'admin', 0, '法权勾结', '{MOD}', ''),
(3909, 'admin', 0, '撒谎的CCTV', '{MOD}', ''),
(3910, 'admin', 0, '违法勾当', '{MOD}', ''),
(3911, 'admin', 0, 'dictatorship', '{MOD}', ''),
(3912, 'admin', 0, 'RedCorner', '{MOD}', ''),
(3913, 'admin', 0, '炸药奖', '{MOD}', ''),
(3914, 'admin', 0, '瘟肿无能', '{MOD}', ''),
(3915, 'admin', 0, '瘟神当道', '{MOD}', ''),
(3916, 'admin', 0, '牺牲国民', '{MOD}', ''),
(3917, 'admin', 0, '上海人民共和园', '{MOD}', ''),
(3918, 'admin', 0, '权力之争', '{MOD}', ''),
(3919, 'admin', 0, '执政能力', '{MOD}', ''),
(3920, 'admin', 0, '天安门通讯', '{MOD}', ''),
(3921, 'admin', 0, '封杀网民', '{MOD}', ''),
(3922, 'admin', 0, '窃国60年', '{MOD}', ''),
(3923, 'admin', 0, '自焚伪案', '{MOD}', ''),
(3924, 'admin', 0, 'exynos', '{MOD}', ''),
(3925, 'admin', 0, '碎尸', '{MOD}', ''),
(3926, 'admin', 0, '冰恋', '{MOD}', ''),
(3927, 'admin', 0, '吃人', '{MOD}', ''),
(3928, 'admin', 0, '游行日本', '{MOD}', ''),
(3929, 'admin', 0, 'riben', '{MOD}', ''),
(3930, 'admin', 0, 'rihuo', '{MOD}', ''),
(3931, 'admin', 0, 'diaoyudao', '{MOD}', ''),
(3932, 'admin', 0, 'diaoyu', '{MOD}', ''),
(3933, 'admin', 0, '网络兼职', '{MOD}', ''),
(3934, 'admin', 0, '幼交', '{MOD}', ''),
(3935, 'admin', 1, '天{5}安{5}门', '{MOD}', '');
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_forum_poststick.php 27806 2012-02-15 03:20:46Z svn_project_zhangjie $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_forum_poststick extends discuz_table
{
public function __construct() {
$this->_table = 'forum_poststick';
$this->_pk = '';
parent::__construct();
}
public function insert($data, $return_insert_id = false, $replace = false, $silent = false){
//删除缓存
$cache_key = $this->_table.'_fetch_all_by_tid'.$data['tid'];
memory('rm',$cache_key);
return parent::insert($data, $return_insert_id, $replace, $silent);
}
/**
* 通过tid获取置顶回帖列表
* @param int $tid
* @return array
*/
public function fetch_all_by_tid($tid) {
//note 由于主键为tid,pid所以,使用tid查询时,pid不会重复
$cache_key = $this->_table.'_fetch_all_by_tid'.$tid;
if(memory('check')){//从缓存中获取
$result = memory('get',$cache_key);
if( $result !== false){
return $result;
}
}
$result = DB::fetch_all('SELECT * FROM %t WHERE tid=%d ORDER BY dateline DESC', array($this->_table, $tid), 'pid');
//缓存
memory('set',$cache_key,$result,86400);
return $result;
}
/**
* 通过pid获取
* @param int $pid
* @return array
*/
public function count_by_pid($pid) {
return DB::result_first('SELECT count(*) FROM %t WHERE pid=%d ', array($this->_table, $pid));
}
/**
* 通过pid删除回帖置顶记录
* @param int|array $pids
* @return bool
*/
public function delete_by_pid($pids) {
if(empty($pids)) {
return false;
}
//删除缓存
//获取tid
loadcache('posttableids');
$posttableids = !empty($_G['cache']['posttableids']) ? ($posttableid !== false && in_array($posttableid, $_G['cache']['posttableids']) ? array($posttableid) : $_G['cache']['posttableids']): array('0');
$thread = array();
foreach ($posttableids as $tableid){
if(empty($thread)){
$thread = C::t('forum_post')->fetch($tableid, $pid);
}else{
break;
}
}
$cache_key = $this->_table.'_fetch_all_by_tid'.$thread['tid'];
memory('rm',$cache_key);
return DB::query('DELETE FROM %t WHERE '.DB::field('pid', $pids), array($this->_table));
}
/**
* 通过tid删除回帖置顶记录
* @param int|array $tids
* @return bool
*/
public function delete_by_tid($tids) {
if(empty($tids)) {
return false;
}
foreach ($tids as $tid){
//删除缓存
$cache_key = $this->_table.'_fetch_all_by_tid'.$tid;
memory('rm',$cache_key);
}
return DB::query('DELETE FROM %t WHERE '.DB::field('tid', $tids), array($this->_table));
}
/**
* 通过主键删除置顶记录
* @param int $tid
* @param int $pid
* @return bool
*/
public function delete($tid, $pid) {
//删除缓存
$cache_key = $this->_table.'_fetch_all_by_tid'.$tid;
memory('rm',$cache_key);
return DB::query('DELETE FROM %t WHERE tid=%d AND pid=%d', array($this->_table, $tid, $pid));
}
/**
* 统计指定主题的回帖置顶数
* @param int $tid
* @return int
*/
public function count_by_tid($tid) {
return DB::result_first('SELECT COUNT(*) FROM %t WHERE tid=%d', array($this->_table, $tid));
}
}
?><file_sep>discuzx3.1
==========
1,MyISAM改成InnoDB
=
2,加了几个主键,加了几个索引
=
3,mediumint(8) 改成 int(11)
=
4,DAO层加了点cache ; 去掉了apc,xcache,eaccelerator,wincache,只剩下常用的redis,memcache
=
5,home_follow_feed 添加了 pid 以便点击广播 跳转到 对应的楼层
=
插件开发辅助工具 http://youdiscuzpath/develop.php
=
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_manager_action.php 209 2013-05-29 09:31:39Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_discuz_security_manager_action extends discuz_table
{
public function __construct() {
$this->_table = 'plugin_discuz_security_manager_action';
$this->_pk = 'uid';
parent::__construct();
}
public function insert($uid, $username, $action, $dateline, $recdateline) {
if(($uid = dintval($uid))) {
$username = daddslashes($username);
$action = daddslashes($action);
$dateline = intval($dateline);
$recdateline = intval($recdateline);
$base = array(
'uid' => $uid,
'username' => (string)$username,
'action' => (string)$action,
'dateline' => (string)$dateline,
'recdateline' => (string)$recdateline,
);
parent::insert($base, false, true);
}
}
public function fetch($start, $limit, $orderby) {
$start = intval($start);
$limit = intval($limit);
$orderby = daddslashes($orderby);
$ordersql = !$orderby ? '' : " ORDER BY $orderby DESC ";
$limitsql = DB::limit($start, $limit);
$return = DB::fetch_all("SELECT * FROM %t group by username %i %i", array($this->_table, $ordersql, $limitsql));
return $return;
}
public function count_per_hour_manager($uid, $type) {
$uid = intval($uid);
$type = daddslashes($type);
return DB::result_first('SELECT COUNT(*) FROM %t WHERE dateline>%d AND action=%d AND uid=%s', array($this->_table, TIMESTAMP - 3600, getuseraction($type), $uid));
}
/**
* 版主操作日志
*/
public function useractionlog($uid, $action, $dateline, $recdateline) {
$uid = intval($uid);
$action = addslashes($action);
$dateline = intval($dateline);
$recdateline = intval($recdateline) ? intval($recdateline) : 0;
if(empty($uid)) {
return false;
}
$action = $action ? $this->getuseraction($action) : '';
$result = DB::fetch_first("SELECT username FROM " . DB::table('common_member') . " WHERE uid = '$uid'");
$maxdatelineisnull = C::t('#discuz_security#discuz_security_manager_action')->fetch_latesttime($uid);
if(is_null($maxdatelineisnull['recdateline'])){
$recdateline = TIMESTAMP;
}
C::t('#discuz_security#discuz_security_manager_action')->insert($uid, $result['username'], $action, $dateline, $recdateline);
return true;
}
public function fetch_latesttime($uid) {
$uid = intval($uid);
$return = DB::fetch_first("SELECT max(recdateline) as recdateline FROM %t WHERE uid=%d LIMIT 1", array($this->_table, $uid));
return $return;
}
/**
* 得到用户操作的代码或代表字符,参数为数字返回字符串,参数为字符串返回数字
* @param string/int $var
* @return int/string 注意:如果失败返回false,请使用===判断,因为代码0代表tid
*/
public function getuseraction($var) {
$value = false;
//操作代码
$ops = array('edit','delete');
if(is_numeric($var)) {
$value = isset($ops[$var]) ? $ops[$var] : false;
} else {
$value = array_search($var, $ops);
}
return $value;
}
public function count() {
return DB::result_first("SELECT COUNT(*) FROM %t WHERE recdateline!=0 group by username", array($this->_table));
}
public function delete_by_uid($uid) {
if(is_array($uid)) {
$uid = implode("','", $uid);
} else {
$uid = intval($uid);
}
$uid = "'".$uid."'";
$return = DB::delete($this->_table, "uid IN ($uid)");
return $return;
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: lang_email.php by <NAME> at
* polish language pack by kaaleth ( <EMAIL> )
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$lang = array
(
'hello' => 'Cześć',//'你好',
'moderate_member_invalidate' => 'Odrzuć',//'否决',
'moderate_member_delete' => 'Usuń',//'删除',
'moderate_member_validate' => 'Akceptuj',//'通过',
'get_passwd_subject' => 'Odzyskiwanie hasła',//'取回密码说明',
'get_passwd_message' => '
<p>{username},
Ta wiadomość została wysłana ze strony {bbname}.</p>
<p>Otrzymałeś tą wiadomość, ponieważ ten adres Email został zarejestrowany
na konto użytkownika naszego forum, który wysłał prośbę o odzyskanie hasła.</p>
<p>
----------------------------------------------------------------------<br />
<strong>Ważne!</strong><br />
----------------------------------------------------------------------</p>
<p>Jeśli to nie Ty odwiedzasz nasze forum lub nie przeprowadziłeś żadnej zmiany,
proszę zignorować tą wiadomość.</p>
<p>
----------------------------------------------------------------------<br />
<strong>Instrukcja odzyskiwania hasła</strong><br />
----------------------------------------------------------------------</p>
</p>
Link z prośbą o odzyskanie hasła jest ważny tylko i wyłącznie przez 3 dni od momentu dostarczenia tej wiadomośc:<br />
<a href="{siteurl}member.php?mod=getpasswd&uid={uid}&id={idstring}" target="_blank">{siteurl}member.php?mod=getpasswd&uid={uid}&id={idstring}</a>
<br />
(Jeśli nie działa, proszę skopiować link do pola adresu w przeglądarce internetowej.)</p>
<p>Po otwarciu strony, proszę wprowadzić nowe hasło i potwierdzić formularz. Dopiero wtedy będziesz
mógł uzyskać dostęp do konta wpisując swoje nowe hasło.
Pamiętaj, że hasło możesz zmienić kiedykolwiek podczas edycji własnego konta.</p>
<p>Żądanie zostało wysłane z adresu IP: {clientip}</p>
<p>
Z poważaniem,<br />
</p>
<p>{bbname} management team.
{siteurl}</p>',
'email_verify_subject' => 'Weryfikacja adresu Email',//'Email 地址验证',
'email_verify_message' => '
<p>{username},<br />
Ta wiadomość została wysłana z serwisu {bbname}.</p>
<p>Otrzymałeś tą wiadomość, ponieważ Twój adres Email został zarejestrowany na naszym forum lub
ktoś z użytkowników przez pomyłkę wprowadził błędny podczas edycji konta.
Jeśli to nie Ty odwiedzasz nasze forum lub nie przeprowadziłeś żadnej zmiany,
proszę zignorować tą wiadomość.</p>
<br />
----------------------------------------------------------------------<br />
<strong>Instrucje aktywacji konta</strong><br />
----------------------------------------------------------------------<br />
<br />
<p>Jeśli jesteś nowy na forum lub dokonałeś zmian w swoim profilu, proszę zastosować się do poniższych instrukcji.
Wymagamy weryfikacji Twojego adres Email. Operacja zapobiega niechcianym wiadomościom SPAM oraz innym operacjom.</p>
<p>Aby aktywować konto, kliknij na poniższy odnośnik:<br />
<a href="{url}" target="_blank">{url}</a>
<br />
(Jeśli nie działa, proszę skopiować link do pola adresu w przeglądarce internetowej.)</p>
<p>Dziękujemy za wizytę. Mamy nadzieję, że będziesz z nami szczęśliwy!</p>
<p>
Z poważaniem,<br />
Ekipa {bbname} .<br />
{siteurl}</p>',
'email_register_subject' => 'Rejestracja na forum',//'论坛注册地址',
'email_register_message' => '<br />
<p>Ta wiadomość została wysłana z serwisu {bbname}.</p>
<p>Otrzymałeś tą wiadomość, ponieważ Twój adres Email został zarejestrowany w serwisie {bbname}.
Jeśli nie chcesz odwiedzać naszego forum lub wycofać się z rejestracji,
proszę zignorować tą wiadomość.</p>
<br />
----------------------------------------------------------------------<br />
<strong>Instrukcje rejestracji nowego konta</strong><br />
----------------------------------------------------------------------<br />
<br />
<p>Wygląda na to, że zostałeś nowym użytkownikiem serwisu {bbname} lub dokonałeś zmian w swoim aktualnym koncie.
Każda operacja mająca na celu zmianę danych chroniących Twoje konto, będzie wymagać wcześniejszego potwierdzenia.</p>
<p>Link ważny jest przez kolejne 3 dni od momentu jego wysłania. Po upływie tego czasu, możesz poprosić o nowy link aktywacyjny. Aby dokończyć proces rejestracji, proszę kliknąć w poniższy odnośnik. <br />
<a href="{url}" target="_blank">{url}</a>
<br />
(Jeśli nie działa, proszę skopiować link do pola adresu w przeglądarce internetowej.)</p>
<p>Dziękujemy za wizytę.Thank you for your visit. Do zobaczenia!</p>
<p>
Z poważaniem,<br />
Ekipa {bbname} .<br />
{siteurl}</p>',
'add_member_subject' => 'Zostałeś dodany jako nowy użytkownik',//'您被添加成为会员',
'add_member_message' => '
{newusername},
<p>Ta wiadomość została wysłana z serwisu {bbname}.</p><br />
<br />
Witaj,
Przedstawiam się jako {adminusername} i jestem jednym z administratorów w serwisie {bbname}.<br />
Otrzymałeś tą wiadomość, ponieważ specjalnie dla Ciebie zostało utworzone nowe konto<br />
na naszym forum, do którego przypisaliśmy właśnie ten adres Email.<br />
<br />
----------------------------------------------------------------------<br />
Ważne!<br />
----------------------------------------------------------------------<br />
<br />
Jeśli nie jesteś zainteresowany członkostwem na naszym forum, proszę zignorować tą wiadomość.<br />
<br />
----------------------------------------------------------------------<br />
Informacje dotyczące konta<br />
----------------------------------------------------------------------<br />
<br />
Nazwa forum: {bbname}<br />
Adres forum: {siteurl}<br />
<br />
Użytkownik: {newusername}<br />
Hasło: {newpassword}<br />
<br />
Od teraz możesz użyć swojego konta by zalogować się na naszym forum, życzę przyjemności podczas Twoich odwiedzin!<br />
<br />
<br />
<br />
Sincerely yours,<br />
<br />
{bbname} management team.<br />
{siteurl}',
'birthday_subject' => 'Happy Birthday to you!',//'祝您生日快乐',
'birthday_message' => '<br />
{username},<br />
This letter was sent from the {bbname}.<br />
<br />
You have received this message, because of this email address is registered in our forum {bbname}.<br />
In accordance with the information in your profile, today is your Birthday.<br />
Forum management team have pleased to congratulate you with your Birthday,
and sincerely wish you a happy birthday!<br />
<br />
If you are not a member of our forum, or have no birthday today, may be a mistake occure.<br />
Check for your email address and birthday in your profile.<br />
This message will not be sent to this e-mail address, please ignore this message.<br />
<br />
<br />
<p>
Z poważaniem,<br />
Ekipa {bbname} .<br />
{siteurl}</p>',
'email_to_friend_subject' => '{$_G[member][username]} polecił Tobie temat: $thread[subject]',//'{$_G[member][username]} 推荐给您: $thread[subject]',
'email_to_friend_message' => '<br />
Ta wiadomość została wysłana przez {$_G[member][username]} ze strony {$_G[setting][bbname]}.<br />
<br />
Otrzymałeś tą wiadomość, ponieważ użytkownik {$_G[member][username]}<br />
ze strony {$_G[setting][bbname]} polecił Ci tę zawartość używając przycisku "poleć znajomym".<br />
Polecamy przejrzenie wiadomości.<br />
Jeśli nie jesteś zainteresowany, proszę zignorować tą wiadomość.<br />
Ta wiadomość została wysłana dobrowolnie.<br />
<br />
----------------------------------------------------------------------<br />
Treść wiadomości<br />
----------------------------------------------------------------------<br />
<br />
$message<br />
<br />
----------------------------------------------------------------------<br />
Koniec wiadomości<br />
----------------------------------------------------------------------<br />
<br />
Proszę pamiętać, że wiadomość została wysłana przez użytkownika naszego forum, który skorzystał z przycisku "poleć znajomym".<br />
Ekipa forum nie odpowiada za treść umieszczoną w tej zawartości.<br />
<br />
<br />
Witaj na {$_G[setting][bbname]}<br />
$_G[siteurl]',
'email_to_invite_subject' => 'Twój znajomy {$_G[member][username]} zaprasza Cię do rejestracji na {$_G[setting][bbname]}',//'您的朋友 {$_G[member][username]} 发送 {$_G[setting][bbname]} 论坛注册邀请码给您',
'email_to_invite_message' => '<br />
$sendtoname,<br />
Ta wiadomość została wysłana od {$_G[member][username]} z forum {$_G[setting][bbname]}.<br />
<br />
Otrzymałeś tą wiadomość, ponieważ została ona wysłana przez {$_G[member][username]} z {bbname} .<br />
Ta wiadomość zawiera kod zaproszenia, który upoważnia Cię do rejestracji na naszym forum,<br />
and said additionally the following.<br />
<br />
!!! If you are not interested in this, please ignore this message.<br />
You do not need to unsubscribe or other further action.<br />
<br />
----------------------------------------------------------------------<br />
Start of original message<br />
----------------------------------------------------------------------<br />
<br />
$message<br />
<br />
----------------------------------------------------------------------<br />
End of the original message<br />
----------------------------------------------------------------------<br />
<br />
Please note that this letter was initiated by the user.<br />
Forum management team is not responsible for such messages.<br />
<br />
Welcome to {$_G[setting][bbname]}
$_G[siteurl]',
'moderate_member_subject' => 'Audit results to inform the user',//'用户审核结果通知',
'moderate_member_message' => '<br />
<p>{username},
This letter was sent from the {bbname}.</p>
<p>You have received this message, because of every new user registration
at our forum require to verify registered email address by site administrator.
After the manual verification you will be notified about the audition results.</p>
<br />
----------------------------------------------------------------------<br />
<strong>Registration info and audit results</strong><br />
----------------------------------------------------------------------<br />
<br />
User Name: {username}<br />
Registration time: {regdate}<br />
Submission time: {submitdate}<br />
Submit number: {submittimes}<br />
Registration reason: {message}<br />
<br />
Audit Results: {modresult}<br />
Audit time: {moddate}<br />
Audit Manager: {adminusername}<br />
Administrator Message: {remark}<br />
<br />
----------------------------------------------------------------------<br />
<strong>Audit results explanation</strong><br />
----------------------------------------------------------------------<br />
<p>Approved: Your registration has been approved, you have become an official user of {bbname}.</p>
<p>Rejected: Your registration information is incomplete, or does not meet some our requirements.
You can send a message to administrator, <a href="home.php?mod=spacecp&ac=profile" target="_blank">complete your registration information</a>, and then submit again.</p>
<p>Deleted: Your request for registration does not meet our requirements,
or number of new registrations exceed our possibilities.
Your request is completely rejected, your account removed from the database.
It can not be used for log in or submitted for re-examine, please understand.</p>
<br />
<br />
Sincerely yours,<br />
<br />
{bbname} management team.<br />
{siteurl}',
'adv_expiration_subject' => 'Your site ad will be {day} days after the due, Please timely processing',//'您站点的广告将于 {day} 天后到期,请及时处理',
'adv_expiration_message' => 'The following ads on your site will be expired {day} days, please deal with:<br /><br />{advs}',//'您站点的以下广告将于 {day} 天后到期,请及时处理:<br /><br />{advs}',
'invite_payment_email_message' => '
Thank you for using the {bbname}, ({siteurl}), Your order {orderid} has been paid completed, Order has been validated.<br />
<br />----------------------------------------------------------------------<br />
Here is what you get the invitation code
<br />----------------------------------------------------------------------<br />
{codetext}
<br />----------------------------------------------------------------------<br />
Important!
<br />----------------------------------------------------------------------<br />',
);
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: content.inc.php 155 2013-05-14 02:05:19Z vinsonbwang $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
require_once(DISCUZ_ROOT.'./source/plugin/discuz_security/common.inc.php');
require_once (DS_ROOT.'./function/function_content.php');
loadcache('plugin');
showcssmenus($csslang['content_title'], array(
array(array('menu' => $csslang['content_global'], 'submenu' => array(
array($csslang['content_global'], PARAM_URL.'&cp=content_global'),
))),
array(array('menu' => $csslang['content_banzhu'], 'submenu' => array(
array($csslang['content_banzhu'], PARAM_URL.'&cp=content_manager'),
))),
));
$cparray = array('content_global', 'content_manager', 'content_mobile');
$cp = !in_array($_GET['cp'], $cparray) ? 'content_global' : $_GET['cp'];
require_once DS_ROOT.'./module/content/'.$cp.'.inc.php';
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: table_discuz_security_forum.php 209 2013-05-29 09:31:39Z qingrongfu $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_discuz_security_forum extends discuz_table
{
public function __construct() {
$this->_table = 'plugin_discuz_security_forum';
$this->_pk = 'uid';
parent::__construct();
}
public function insert($uid, $username, $ip) {
if(($uid = dintval($uid))) {
$username = daddslashes($username);
$ip = daddslashes($ip);
$base = array(
'uid' => $uid,
'username' => (string)$username,
'dateline' => TIMESTAMP,
'lastip' => (string)$ip,
);
parent::insert($base, false, true);
}
}
public function update($uid, $username, $ip) {
$uid = intval($uid);
$username = daddslashes($username);
$ip = daddslashes($ip);
DB::query('UPDATE %t SET uid=%d, username=%s, dateline=%d, lastip=%s WHERE username=%s', array($this->_table, $uid, $username, TIMESTAMP, $ip, $username));
}
public function fetch($start, $limit, $orderby) {
$start = intval($start);
$limit = intval($limit);
$orderby = daddslashes($orderby);
$ordersql = !$orderby ? '' : " ORDER BY $orderby DESC ";
$limitsql = DB::limit($start, $limit);
$return = DB::fetch_all("SELECT * FROM %t %i %i", array($this->_table, $ordersql, $limitsql));
return $return;
}
public function delete_by_uid($uid) {
if(is_array($uid)) {
$uid = implode("','", $uid);
} else {
$uid = "'".$uid."'";
}
$return = DB::delete($this->_table, "uid IN ($uid)");
return $return;
}
public function count() {
return DB::result_first("SELECT COUNT(*) FROM %t", array($this->_table));
}
}
?><file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: install.php 199 2013-05-29 02:46:11Z lucashen $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
$sql = '';
$sql .= <<<EOF
CREATE TABLE IF NOT EXISTS `cdb_plugin_discuz_security_adminlog` (
`key` char(10) NOT NULL,
`value` mediumint(8) unsigned NOT NULL DEFAULT '0',
`lastupdate` int(10) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`key`)
) ENGINE=MyISAM;
CREATE TABLE IF NOT EXISTS `cdb_plugin_discuz_security_cdd` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`path` varchar(255) NOT NULL,
`scaned` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
EOF;
runquery($sql);
$finish = true;
<file_sep><?php
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
if($_GET['formhash'] != FORMHASH) {
exit(json_encode(array('status'=>0,'message'=>lang('undefined_action'),'checkin'=>0)));
}
if($_G['uid']){
$thisvars = $_G['cache']['plugin']['dsu_amupper'];
$thisvars['offset'] = $_G['setting']['timeoffset'];
$thisvars['gids'] = (array)unserialize($thisvars['gids']);
$thisvars['today'] = dgmdate($_G['timestamp'],'Ymd',$thisvars['offset']);
$thisvars['uid'] = C::t('#dsu_amupper#plugin_dsuamupper')->fetch($_G['uid']);
$this_time = istoday($thisvars['uid']['lasttime']);
$this_Hs = isH($thisvars['uid']['lasttime']);
$this_H = $this_Hs['return'];
$ptjfname = $_G['setting']['extcredits'][$thisvars['ptjf']]['title'];
}else{
exit(json_encode(array('status'=>0,'message'=>'没有登录!','checkin'=>0)));
}
if(!in_array($_G['groupid'],$thisvars['gids'])){
exit(json_encode(array('status'=>0,'message'=>'你所在的组暂时不支持签到!','checkin'=>0)));
}
//普通奖励积分的计算与是否连续签到的判断
if($this_time == -1 || $thisvars['sz']){
//昨天打卡了或者默认允许连续打卡
$cons = $thisvars['uid']['cons']=="" ? 0 : $thisvars['uid']['cons'] + 1 ;
$addup = $thisvars['uid']['addup'] + 1 ;
}elseif($this_time == 0){
//今天打过卡了
$cons = $thisvars['uid']['cons'];
$addup = $thisvars['uid']['addup'];
}else{
//断断续续打卡
$cons = 0;
$addup = $thisvars['uid']['addup'] + 1 ;
}
if($this_time <> 0){
if(dsucheckformulacredits($thisvars['ptgs'])){
$amu_formula = str_replace("leiji",$addup,$thisvars['ptgs']);
$amu_formula = str_replace("lianxu",$cons,$amu_formula);
@eval("\$pt = $amu_formula;");
$pt = empty($thisvars['ptmax']) ? intval($pt) : intval(min($pt, $thisvars['ptmax']));
$amu_formula_n = str_replace("leiji",$addup + 1,$thisvars['ptgs']);
$amu_formula_n = str_replace("lianxu",$cons + 1,$amu_formula_n);
@eval("\$pt_n = $amu_formula_n;");
$pt_n = empty($thisvars['ptmax']) ? intval($pt_n) : intval(min($pt_n, $thisvars['ptmax']));
}else{
$pt = $pt_n = 1;
}
//获取特殊奖励配置情况
$tsarr = C::t('#dsu_amupper#plugin_dsuamupperc')->fetch_all_by_g_id();
$data_f2a =dstripslashes($tsarr);
$next_old='';
if($tsarr && $thisvars['ms'] == 3){
//有特殊奖励(不循环)
foreach ($data_f2a as $id => $result){
if(($_G['groupid'] == $result['usergid']|| $result['usergid'] <= '0') && $cons == $result['days']){
$teshu[$id] = $result;
$tsmsg[] = array('title'=>$_G['setting']['extcredits'][$result['extcredits']]['title'], 'reward'=>$result['reward']);
}
}
}
//有特殊奖励(循环)
if($tsarr && $thisvars['ms'] == 4){
foreach ($data_f2a as $id => $result){
$yushu = $cons % $result['days'];
if(($_G['groupid'] == $result['usergid']|| $result['usergid'] <= '0') && $yushu == 0 && $cons > 0){
$teshu[$id] = $result;
$tsmsg[] = array('title'=>$_G['setting']['extcredits'][$result['extcredits']]['title'], 'reward'=>$result['reward']);
}
$next = $result['days'] - ($cons % $result['days']);
$cons_next = $cons + $next;
}
}
if(file_exists(DISCUZ_ROOT.'./data/tid_amupper.lock')) {
exit(json_encode(array('status'=>0,'message'=>'非法提交数据','checkin'=>0)));
}else{
$jiangliba = 0;
if( $this_time < 0 && $thisvars['uid']['time'] <> dgmdate($_G['timestamp'],'Ymd', $_G['setting']['timeoffset'])){
switch ($thisvars['ms']){
case 1:
//关闭插件
break;
case 2:
//无特殊奖励
if( $addup==1 && $cons==0 ){
$return_msg = '签到成功 获得奖励'.$ptjfname.'+'.$pt.',明日签到将获得'.$ptjfname.'+'.$pt_n;
}else{
$return_msg = '连续签到'.$cons.'天,获得奖励 '.$ptjfname.'+'.$pt.',明日签到将获得'.$ptjfname.'+'.$pt_n;
}
break;
//特殊奖励
case 3:
case 4:
if($tsmsg){
foreach($tsmsg as $v){
$tsmsg2 .=$v['title'].' +'.$v['reward'];
}
$return_msg = '特殊奖励: 您已连续签到'.$cons.'天,获得特殊奖励 '.$tsmsg2.','.$ptjfname.' +'.$pt.'。明日签到将获得'.$ptjfname.'+'.$pt_n;
}else{
if( $addup==1 && $cons==0 ){
$return_msg = '签到成功 获得奖励'.$ptjfname.' +'.$pt.',明日签到将获得'.$ptjfname.'+'.$pt_n;
}else{
$return_msg = '连续签到'.$cons.'天,获得奖励 '.$ptjfname.' +'.$pt.',明日签到将获得'.$ptjfname.'+'.$pt_n;
}
}
break;
}
//关掉发帖功能
// if($thisvars['ft']){
// $subject = str_replace("time",dgmdate($_G['timestamp'],'Y-m-d',$thisvars['offset']),$thisvars['bt']);
// $today = dgmdate($_G['timestamp'],'Ymd',$thisvars['offset']);
// }
if(!empty($thisvars['uid'])){
$update_data = array(
'addup'=>intval($addup),
'cons'=>intval($cons),
'lasttime'=>intval($_G['timestamp']),
'time'=>intval($today),
'allow'=>intval($arr['allow']),
);
C::t('#dsu_amupper#plugin_dsuamupper')->update($_G['uid'],$update_data);
}else{
$insert_data = array(
'uid'=>intval($_G['uid']),
'uname'=>dhtmlspecialchars("'".addslashes($_G['username'])."'"),
'addup'=>intval($addup),
'cons'=>intval($cons),
'lasttime'=>intval($_G['timestamp']),
'time'=>intval($today),
'allow'=>intval($arr['allow']),
);
C::t('#dsu_amupper#plugin_dsuamupper')->insert($insert_data);
}
$jiangliba = 1;
//删除统计缓存
$nt1 = dgmdate($_G['timestamp'],'i',$_G['setting']['timeoffset']);
$nt2 = dgmdate($_G['timestamp'],'s',$_G['setting']['timeoffset']);
$nt = $nt1*60 + $nt2;
$Htime =$_G['timestamp'] - $nt;
$mem_key = 'plugin_dsuamupper::count_by_lasttime'.$Htime.'>=';
memory('rm',$mem_key);
if($jiangliba == 1){
switch ($thisvars['ms']){
case 1:
//关闭插件
break;
case 2:
//无特殊奖励
updatemembercount($_G['uid'], array("extcredits{$thisvars['ptjf']}" => $pt), true,'',0);
break;
case 3:
//特殊奖励(N)非循环
if(is_array($teshu)){
foreach ($teshu as $id => $result){
updatemembercount($_G['uid'], array("extcredits{$result['extcredits']}" => $result['reward']), true,'',0);
}
}
updatemembercount($_G['uid'], array("extcredits{$thisvars['ptjf']}" => $pt), true,'',0);
break;
case 4:
//特殊奖励(Y)循环
if(is_array($teshu)){
foreach ($teshu as $id => $result){
updatemembercount($_G['uid'], array("extcredits{$result['extcredits']}" => $result['reward']), true,'',0);
}
}
updatemembercount($_G['uid'], array("extcredits{$thisvars['ptjf']}" => $pt), true,'',0);
break;
}
}
}
}
}elseif($this_time == 0 && $this_H){
//今天连续打卡&整点打卡
$Hreward = rand($this_Hs['minreward'],$this_Hs['maxreward']);
$return_msg = '整点签到成功! 获得额外奖励'.$ptjfname.'+'.$Hreward;
C::t('#dsu_amupper#plugin_dsuamupper')->update($_G['uid'],array('lasttime'=> $_G['timestamp']));
updatemembercount($_G['uid'], array("extcredits{$thisvars['ptjf']}" => $Hreward), true,'',0);
}
if($return_msg){
if(defined('VIP_INITED')) vip::hooks('sign');
dsetcookie('dsu_amuppered', $_G['uid'], 3600);
dsetcookie('dsu_amupper', 0, 1);
if($arr['allow'] && $arr['pid']){
$url = "forum.php?mod=redirect&goto=findpost&ptid={$arr['allow']}&pid={$arr['pid']}";
if($thisvars['autogo'] && empty($_GET['nojump'])){ //打卡后调到到指定位置
exit(json_encode(array('status'=>1,'message'=>$return_msg,'checkin'=>1)));
}else{
exit(json_encode(array('status'=>1,'message'=>$return_msg,'checkin'=>1)));
}
}else{
exit(json_encode(array('status'=>1,'message'=>$return_msg,'checkin'=>1)));
}
}else{
dsetcookie('dsu_amuppered', $_G['uid'], 600);
dsetcookie('dsu_amupper', 0, 1);
exit(json_encode(array('status'=>0,'message'=>'您已签到完毕,今日已无需再次签到!','checkin'=>0)));
}
///自定义函数区
function istoday($time){
global $_G;
$time = empty($time) ? 0 : $time ;
$today = dgmdate($_G['timestamp'],'Ymd', $_G['setting']['timeoffset']);
$yesterday = dgmdate($_G['timestamp']-3600*24,'Ymd',$_G['setting']['timeoffset']);
$lastday = dgmdate($time,'Ymd',$_G['setting']['timeoffset']);
$days = $lastday - $today;
if($lastday == $yesterday){$days = -1;}
return $days ;
}
function isH($time){
global $_G;
include_once 'source/plugin/dsu_amupper/config.php';
if($pperconfig['max'] && $pperconfig['minreward'] && $pperconfig['maxreward']){
$nt1 = dgmdate($_G['timestamp'],'i',$_G['setting']['timeoffset']);
$nt2 = dgmdate($_G['timestamp'],'s',$_G['setting']['timeoffset']);
$nt = $nt1*60 + $nt2;
$Htime =$_G['timestamp'] - $nt;
$Hnum = C::t('plugin_dsuamupper')->count_by_lasttime($Htime);
$time = empty($time) ? 0 : $time ;
$nowtime = dgmdate($_G['timestamp'],'H',$_G['setting']['timeoffset']);
$last = dgmdate($time,'H',$_G['setting']['timeoffset']);
$H = $pperconfig;
$H['ok'] = 1;
$H['return'] = $last + 1 > $nowtime ? 0 : 1;
$H['return'] = $Hnum < $pperconfig['max'] ? $H['return'] : 0;
}
return $H;
}
function dsucheckformulsyntax($formula, $operators, $tokens) {
$var = implode('|', $tokens);
$operator = implode('', $operators);
$operator = str_replace(
array('+', '-', '*', '/', '(', ')', '{', '}', '\''),
array('\+', '\-', '\*', '\/', '\(', '\)', '\{', '\}', '\\\''),
$operator
);
if(!empty($formula)) {
if(!preg_match("/^([$operator\.\d\(\)]|(($var)([$operator\(\)]|$)+))+$/", $formula) || !is_null(eval(preg_replace("/($var)/", "\$\\1", $formula).';'))){
return false;
}
}
return true;
}
function dsucheckformulacredits($formula) {
return dsucheckformulsyntax(
$formula,
array('+', '-', '*', '/', ' '),
array('lianxu', 'leiji')
);
}
?>
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: sys_fakeip.php 205 2013-05-29 08:16:16Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
require_once DS_ROOT.'./class/class_ds_patch.php';
$oparray = array('patch','restore','index');
$op = in_array($_GET['op'], $oparray) ? $_GET['op'] : 'index';
$fakeipurl = PARAM_URL.'&cp=sys_fakeip&op=';
if ($op == 'patch') {
if(submitcheck('patchsubmit')) {
$rules = $rule = array();
$rules['serial'] = 'sys_fackip';
$rule1['filename'] = './source/class/discuz/discuz_application.php';
$rule1['search'] = 'JGlwID0gJF9TRVJWRVJbJ1JFTU9URV9BRERSJ107';
$rule1['replace'] = 'JHJlYWxpcCA9ICRfU0VSVkVSWydSRU1PVEVfQUREUiddOw==';
$rule1['count'] = 1;
$rule1['nums'] = array(1);
$rule2['filename'] = './source/class/discuz/discuz_application.php';
$rule2['search'] = 'cmV0dXJuICRpcDs=';
$rule2['replace'] = 'cmV0dXJuICRyZWFsaXA7';
$rule2['count'] = 1;
$rule2['nums'] = array(1);
$rules['rule'] = serialize(array($rule1, $rule2));
$patch = new ds_patch();
$result = $patch->fix_patch($rules);
if($result < 0) {
$msg = $csslang['sys_fakeip_error_'.abs($result)];
} else {
adminlog('FKIP', 1, 'radio');
$msg = $csslang['sys_fakeip_success_'.abs($result)];
}
} elseif (submitcheck('restoresubmit')) {
$rules = $rule = array();
$rules['serial'] = 'sys_fackip';
$rule1['filename'] = './source/class/discuz/discuz_application.php';
$rule1['replace'] = 'JGlwID0gJF9TRVJWRVJbJ1JFTU9URV9BRERSJ107';
$rule1['search'] = 'JHJlYWxpcCA9ICRfU0VSVkVSWydSRU1PVEVfQUREUiddOw==';
$rule1['count'] = 1;
$rule1['nums'] = array(1);
$rule2['filename'] = './source/class/discuz/discuz_application.php';
$rule2['replace'] = 'cmV0dXJuICRpcDs=';
$rule2['search'] = 'cmV0dXJuICRyZWFsaXA7';
$rule2['count'] = 1;
$rule2['nums'] = array(1);
$rules['rule'] = serialize(array($rule1, $rule2));
$patch = new ds_patch();
$result = $patch->fix_patch($rules);
if($result < 0) {
$msg = $csslang['sys_fakeip_error_'.abs($result)];
} else {
adminlog('FKIP', 0, 'radio');
$msg = $csslang['sys_fakeip_restore_'.abs($result)];
}
} elseif (submitcheck('checksubmit')) {
$rules = $rule = array();
$rules['serial'] = 'sys_fackip';
$rule1['filename'] = './source/class/discuz/discuz_application.php';
$rule1['search'] = 'JGlwID0gJF9TRVJWRVJbJ1JFTU9URV9BRERSJ107';
$rule1['replace'] = 'JHJlYWxpcCA9ICRfU0VSVkVSWydSRU1PVEVfQUREUiddOw==';
$rule1['count'] = 1;
$rule1['nums'] = array(1);
$rule2['filename'] = './source/class/discuz/discuz_application.php';
$rule2['search'] = 'cmV0dXJuICRpcDs=';
$rule2['replace'] = 'cmV0dXJuICRyZWFsaXA7';
$rule2['count'] = 1;
$rule2['nums'] = array(1);
$rules['rule'] = serialize(array($rule1, $rule2));
$patch = new ds_patch();
$result = $patch->test_patch($rules);
if($result) {
$msg = $csslang['sys_fakeip_success_2'];
} else {
$msg = $csslang['sys_fakeip_restore_2'];
}
}
cpmsg($msg);
} else {
showtableheader();
showtitle($csslang['sys_fakeip']);
showtablerow('', array(), array($csslang['sys_fakeip_tip']));
showtablefooter();
showformheader($fakeipurl.'patch');
showsubmit('', '', '',
'<input type="submit" class="btn" name="patchsubmit" value="'.$csslang['sys_fakeip_patch'].'" /> '.
'<input type="submit" class="btn" name="restoresubmit" value="'.$csslang['sys_fakeip_restore'].'" /> '.
'<input type="submit" class="btn" name="checksubmit" value="'.$csslang['sys_fakeip_check'].'" />'
);
showformfooter();
}
<file_sep><?php
/**
* [Discuz!] (C)2001-2099 Comsenz Inc.
* This is NOT a freeware, use is subject to license terms
*
* $Id: system.inc.php 223 2013-06-21 02:45:05Z qingrongfu $
*/
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
exit('Access Denied');
}
require_once DISCUZ_ROOT.'./source/plugin/discuz_security/common.inc.php';
require_once DS_ROOT.'./function/function_system.php';
loadcache('plugin');
showcssmenus(lang('plugin/discuz_security', 'sys_safe'), array(
array(array('menu' => $csslang['sys_junior'], 'submenu' => array(
array( $csslang['sys_plugins'], PARAM_URL.'&cp=sys_plugins'),
array( $csslang['sys_checkdir'], PARAM_URL.'&cp=sys_checkdir'),
array( $csslang['sys_fakeip'], PARAM_URL.'&cp=sys_fakeip'),
))),
array(array('menu' => $csslang['sys_limit'], 'submenu' => array(
array($csslang['sys_limit_banned'], PARAM_URL.'&cp=sys_limit&op=allban'),
array($csslang['sys_limit_activity'], PARAM_URL.'&cp=sys_limit&op=allsession'),
array($csslang['sys_limit_history'], PARAM_URL.'&cp=sys_limit&op=history'),
))),
array(array('menu' => $csslang['sys_cdd'], 'submenu' => array(
array($csslang['sys_cdd_prescan'], PARAM_URL.'&cp=sys_cdd&op=prescan'),
array($csslang['sys_cdd_scan'], PARAM_URL.'&cp=sys_cdd&op=scan'),
array($csslang['sys_cdd_scan_report'], PARAM_URL.'&cp=sys_cdd&op=report'),
))),
));
$cp = empty($_GET['cp']) ? null : $_GET['cp'];
if(!$cp) {
showtableheader();
showtitle($csslang['sys_plugins']);
showtablerow('', array(), array($csslang['sys_plugins_tips']));
showtitle($csslang['sys_limit']);
showtablerow('', array(), array($csslang['sys_limit_tips']));
showtitle($csslang['sys_cdd']);
showtablerow('', array(), array($csslang['sys_cdd_tips']));
showtablerow('', array(), array($csslang['sys_cdd_tips_1']));
showtablerow('', array(), array($csslang['sys_cdd_tips_2']));
showtablerow('', array(), array($csslang['sys_cdd_tips_3']));
showtablefooter();
} elseif($cp == 'sys_plugins') {
require_once DS_ROOT.'./module/system/'.$cp.'.php';
} elseif($cp == 'sys_limit') {
require_once DS_ROOT.'./module/system/'.$cp.'.php';
} elseif($cp == 'sys_checkdir') {
require_once DS_ROOT.'./module/system/'.$cp.'.php';
} elseif($cp == 'sys_fakeip') {
require_once DS_ROOT.'./module/system/'.$cp.'.php';
} elseif($cp == 'sys_cdd') {
require_once DS_ROOT.'./module/system/'.$cp.'.php';
}
?><file_sep><?php
/*
* $Id: 2013/6/24 13:04:17 table_common_member_ext.php <NAME> $
*/
if(!defined('IN_DISCUZ')) {
exit('Access Denied');
}
class table_common_member_ext extends table_common_member
{
public function split($splitnum, $iscron = false) {
loadcache('membersplitdata');
@set_time_limit(0);
discuz_database_safecheck::setconfigstatus(0);
$dateline = TIMESTAMP - 7776000;//60*60*24*90
$temptablename = DB::table('common_member_temp___');
if(!DB::fetch_first("SHOW TABLES LIKE '$temptablename'")) {
DB::query("CREATE TABLE $temptablename (`uid` int(10) NOT NULL DEFAULT 0,PRIMARY KEY (`uid`)) ENGINE=MYISAM;");
}
$splitnum = max(1, intval($splitnum));
//if(!DB::result_first('SELECT COUNT(*) FROM '.$temptablename)) {
if(!DB::fetch_first('SELECT * FROM '.$temptablename.' LIMIT 1')) {
DB::query('INSERT INTO '.$temptablename.' (`uid`) SELECT ms.uid AS uid FROM %t mc, %t ms WHERE mc.posts<5 AND ms.lastvisit<%d AND mc.uid=ms.uid ORDER BY ms.lastvisit LIMIT %d', array('common_member_count', 'common_member_status', $dateline, $splitnum));
}
//if(DB::result_first('SELECT COUNT(*) FROM '.$temptablename)) {
if(DB::fetch_first('SELECT * FROM '.$temptablename.' LIMIT 1')) {
if(!$iscron && getglobal('setting/memberspliting') === null) {
$this->switch_keys('disable');
}
$uidlist = DB::fetch_all('SELECT uid FROM '.$temptablename, null, 'uid');
$uids = dimplode(array_keys($uidlist));
$movesql = 'REPLACE INTO %t SELECT * FROM %t WHERE uid IN ('.$uids.')';
$deletesql = 'DELETE FROM %t WHERE uid IN ('.$uids.')';
if(DB::query($movesql, array('common_member_archive', 'common_member'), false, true)) {
DB::query($deletesql, array('common_member'), false, true);
}
if(DB::query($movesql, array('common_member_profile_archive', 'common_member_profile'), false, true)) {
DB::query($deletesql, array('common_member_profile'), false, true);
}
if(DB::query($movesql, array('common_member_field_forum_archive', 'common_member_field_forum'), false, true)) {
DB::query($deletesql, array('common_member_field_forum'), false, true);
}
if(DB::query($movesql, array('common_member_field_home_archive', 'common_member_field_home'), false, true)) {
DB::query($deletesql, array('common_member_field_home'), false, true);
}
if(DB::query($movesql, array('common_member_status_archive', 'common_member_status'), false, true)) {
DB::query($deletesql, array('common_member_status'), false, true);
}
if(DB::query($movesql, array('common_member_count_archive', 'common_member_count'), false, true)) {
DB::query($deletesql, array('common_member_count'), false, true);
}
DB::query('DROP TABLE '.$temptablename);
$membersplitdata = getglobal('cache/membersplitdata');
$zombiecount = $membersplitdata['zombiecount'] - $splitnum;
if($zombiecount < 0) {
$zombiecount = 0;
}
savecache('membersplitdata', array('membercount' => $membersplitdata['membercount'], 'zombiecount' => $zombiecount, 'dateline' => TIMESTAMP));
C::t('common_setting')->delete('memberspliting');
return true;
} else {
DB::query('DROP TABLE '.$temptablename);
if(!$iscron) {
$this->switch_keys('enable');
C::t('common_member_profile')->optimize();
C::t('common_member_field_forum')->optimize();
C::t('common_member_field_home')->optimize();
}
return false;
}
}
}
<file_sep><?php
/*
* $Id: 2013/9/12 11:15:08 bin_session_cron.php <NAME> $
*/
(function_exists('ini_set') && ini_set('default_socket_timeout', -1)) || exit('Function \'ini_set\' shouldn\'t be forbindden!!');
define('IN_DISCUZ', true);
error_reporting(E_ERROR);
require '../../config/config_global.php';
try {
if(!($rds = new Redis())) throw new RedisException("No Redis Extension Loaded!\n");
if(!$rds->pconnect($_config['memory']['redis']['server'], $_config['memory']['redis']['port'])) throw new RedisException("Please check config file!\n");
} catch(RedisException $e) {
exit($e->getMessage());
}
echo "DISCUZX! session_cron job START!\n";
try {
while(1) {
$ts = microtime(true);
$invisible0 = $invisible1 = $count1 = $count2 = $count0 = 0;
$fidct = array();
$keys = $rds->keys("sR:s_*");
if(!empty($keys) && is_array($keys)) {
foreach($keys as $v) {
$data = $rds->hGetAll($v);
$onlinehold = time() - 900;
if($data['lastactivity'] < $onlinehold) $rds->delete($v);
if($data['invisible'] == 0) $invisible0 ++;
if($data['invisible'] == 1) $invisible1 ++;
if($data['uid'] == 0) $count2 ++;
if($data['uid'] > 0) $count1 ++;
$count0 ++;
if($data['fid'] != 0) $fidct[$data['fid']] ++;
usleep(500);
}
}
$rt = array(
'c_i_t0' => $invisible0,
'c_i_t1' => $invisible1,
'c_t1' => $count1,
'c_t2' => $count2,
'c_t0' => $count0,
'c_b_f' => serialize($fidct),
);
$rds->hMset('sR:status', $rt);
$break = microtime(true) - $ts;
echo date(DATE_ATOM)." exectime:$break s\n";
sleep(5);
}
} catch(RedisException $e) {
exit("You have to unforbindden function 'ini_set'!\n ");
}
|
414df374be8b88d605d9ef40aed52126da1c5dc0
|
[
"Markdown",
"SQL",
"Text",
"PHP"
] | 62
|
PHP
|
tronslirr/discuzx
|
688fc613897b5db728e2c8346f59a19c24d84cac
|
7942984ab7c9f443474883ca310935cc802fc975
|
refs/heads/master
|
<file_sep>#include <string>
#include <vector>
#include <tuple>
#include <iostream>
#include "ModelName.h"
using namespace std;
ModelName::ModelName()
{
this->mType = NAME;
this->mBeginTag = "<name>";
this->mEndTag = "</name>";
}
void ModelName::FormatData()
/**
implemented formating for name
*/
{
if(this->vDataItem.empty())
{
cout<<"warning: a model name was not parsed since it has not enough arugments"<<endl;
return;
}
//combine name strings if the name contains spaces
string combinedname;
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); ++it)
{
combinedname += *it;
}
//save
tName NewData = std::make_tuple(0,combinedname);
this->vName.push_back(NewData);
#ifdef DEBUG
//check saved model data
for(auto j : this->vName)
{
cout<<"tuple data: "<<std::get<TNAME_NAME>(j)<<endl;
}
#endif
}
<file_sep>// adapted from MD5 Loader Demo By <NAME>
#ifndef QUAT_H
#define QUAT_H
#include "Vec.h"
#define QUAT_X 0
#define QUAT_Y 1
#define QUAT_Z 2
#define QUAT_W 3
class Quat{
public:
float _quat[4];
Quat();
Quat( float x, float y, float z, float w );
Quat( Vec a, float w ); //a = {x,y,z}
Quat( const Quat & q );
Quat & operator = ( const Quat & q );
Quat operator - ( const Quat & q ) const;
Quat & operator -= ( const Quat & q );
Quat operator + ( const Quat & q ) const;
Quat & operator += ( const Quat & q );
Quat operator * ( const Quat & q ) const;
Quat & operator *= ( const Quat & q );
inline float & operator [] ( int i ){ return _quat[i]; };
inline float operator [] ( int i ) const{ return _quat[i]; };
void AxisAngleDegree( const float axis[], float angle );
void AxisAngleDegreeVector( const Vec & v, float angle );
void SetTranslation( const float a [] );
float Length() const;
float LengthSquared() const;
void NormalizeQuatCurrent();
Quat NormalizeQuat() const;
Quat Log() const; //log(q) = log ||q|| + v/||v|| * arccos(a/||v||)
Quat Pow( float t );
void ToMatrixRot( float mat[] ) const; //gets rotation 4x4 matrix
void ToMatrixTrans( float mat[] ) const; //gets translation 4x4 matrix
inline Quat Conjugate() const { return Quat(-_quat[0], -_quat[1], -_quat[2], _quat[3]); }
Quat Negate() const; //negative version
};
Quat Scale( float s, const Quat q); // s*q
Quat ScaleAdd( float s, const Quat q1, const Quat q2 ); //s*q1 + q2
Quat InterpolateSlerp(const Quat & q1, const Quat & q2, float t); //spherical linear interpolation
Quat InterpolateBasic( const Quat q1, const Quat q2, float r ); // (1-r) * q1 + r * q2
#endif
<file_sep>#ifndef MODELVERTICE_H
#define MODELVERTICE_H
#include "ModelData.h"
#include <vector>
#include <sstream>
#include <tuple>
#include <string>
///access index of data
#define TVERTICE_ID 0
#define TVERTICE_X 1
#define TVERTICE_Y 2
#define TVERTICE_Z 3
using namespace std;
///data tuple definition
typedef tuple<int, float,float,float> tVertice;
///container for vertices data
class ModelVertice: ModelData
{
public:
ModelVertice();
vector< tVertice > vVertice; ///container of formatted data
void FormatData(); ///formats vertices
};
#endif
<file_sep>#ifndef ANIMATIONMANAGER_H
#define ANIMATIONMANAGER_H
#include "DOMNode.h"
#include "Clock.h"
#include "ModelAbstraction.h"
#include "AnimationParse.h"
#include "ModelPool.h"
#include <vector>
#include <string>
using namespace std;
/// manages models based on clock trigger and parsed animation DOM tree
class AnimationManager : public Clock, public ModelPool
{
private:
/// storage for animation
vector<tAnimation> vAnimation;
public:
AnimationManager();
~AnimationManager();
void AddAnimation(tAnimation animation); /// adds animation
bool RemoveAnimation(tAnimation animation); /// removes animations according to matching animation name
tAnimation GetAnimation(string name); /// gets animation from matching name
void TickAction(string a); /// implement function to update models based on clock trigger
};
#endif
<file_sep>#ifndef LIGHTING_H
#define LIGHTING_H
#include <string>
#include "ModelAbstraction.h"
#include "Interpolate.h"
using namespace std;
///inherits transformation functionality from ModelAbstraction
class Lighting: public ModelAbstraction, public Interpolate
{
private:
int NumLight;
string LightType;
bool bFunctional;
float LightAmbiance[4] = {0,0,0,1};
float LightDiffuse[4] = {1,1,1,1};
float LightSpecular[4] = {1,1,1,1};
float LightPosition[4] = {0,0,0,1};
float LightDirection[4] = {0,0,1,0};
float LightExponent = 0;
float LightCutoff = 180;
float LightAttenConst = 1;
float LightAttenLinear = 0;
float LightAttenQuadratic = 0;
public:
static int TotalNumLight;
Lighting();
void TurnOn();
void TurnOff();
void SetLightParam(float amb[], float spec[], float dif[], float pos[]);
void SetLightParamSpot(float dir[], float exp, float cutoff);
void SetLightAttenuation(string type, float att);
void SetLightAmbient(float[]);
void SetLightSpecular(float[]);
void SetLightDiffuse(float[]);
void SetLightPosition(float[]);
void SetLightDirection(float[]);
void SetLightExponent(float[]);
void SetLightCutoff(float[]);
void SetType(string type); ///sets lighting type (optional)
string GetType();
void Draw();
void FormatAction();
void FormatData();
void AddCurve(int steps, float ctrlpoint1[], float ctrlpoint2[], float ctrlpoint3[], float ctrlpoint4[]); /// redirects this to Iterpolate class
};
#endif
<file_sep>#include <sstream>
#include <string>
#include <vector>
#include "ModelData.h"
void ModelData::SetData(string input)
/** separate data items into a vector of strings and calls formating function in a derived class
@param input single lined string data to be separated
*/
{
stringstream Ss;
Ss.str(input);
string temp;
//seperate each data item
while (Ss>>temp)
{
this->vDataItem.push_back(temp);
temp.clear();
}
this->FormatData(); //format data
}
<file_sep>#include <iostream>
#include <cmath>
#include "ModelPool.h"
#include "ModelAbstraction.h"
#include "AnimationManager.h"
#include "AnimationParse.h"
#include "TrajectoryParse.h"
#include "CurvePath.h"
using namespace std;
int main(int argc, char** argv)
{
if(argc < 3)
{
cout<<"not enough arguments: <curve path> <animation path>"<<endl;
return -1;
}
TrajectoryParse curveparser;
vector<CurvePath *> vpCurve = curveparser.GetTrajectories(argv[1]);
AnimationParse animationparser;
vector<tAnimation> vAnimation = animationparser.GetAnimations(argv[2]);
//create animation manager
AnimationManager manager;
vector<ModelAbstraction*> * worldmodels = new vector<ModelAbstraction*>();
manager.SetModelSource(worldmodels);
//test model adding
for(auto i : vpCurve)
{
manager.AddModel(i);
}
ModelAbstraction * querymodel = manager.GetModel("curve1");
if(querymodel == NULL)
cout<<"model not found"<<endl;
else
cout<<querymodel->Name<<" found"<<endl;
//test animation adding
for(auto i : vAnimation)
{
manager.AddAnimation(i);
}
tAnimation queryanimation = manager.GetAnimation("CurveRun1");
cout<<std::get<TANIMATION_NAME>(queryanimation)<<", "<<std::get<TANIMATION_TIME>(queryanimation)<<endl;
manager.SetFps(30.0);
/// runs the clock
manager.Run();
while(true){
/// runs clock if fps is valid and clock is not paused
manager.Tick();
}
return 0;
}
<file_sep>#ifndef PARAMETRICCURVE_H
#define PARAMETRICCURVE_H
///provides ability to trace out position of a cubic bezier curve using forward differencing. Taken from pp.365-367 of Chapter 8 of Advanced 3D Game Programming with DirectX 10.0 by <NAME>
class ParametricCurve
{
private:
int mCurrentStep;
int mTotalStep;
float mControlPoints[4][3]; /// bezier control points
float mPoint[3];
float mDPoint[3];
float mDDPoint[3];
float mDDDPoint[3];
float mBezierBasis[4][4] = {{-1,3,-3,1}, {3,-6,3,0}, {-3,3,0,0}, {1,0,0,0}}; /// bezier basis matrix
bool bStarted;
public:
ParametricCurve();
void SetParameter(int steps, float control1[], float control2[], float control3[], float control4[]); ///sets control points for the curve
void Increment();
void GetCurrent(float*& out);
void Start(); ///initialize the curved
bool Done(); ///see if the curve had reached the en
bool Started();
};
#endif
<file_sep>#include <iostream>
#include "DOMParse.h"
#include "DOMNode.h"
using namespace std;
int main(int argc, char** argv)
{
if(argc < 2)
{
cout<<"need DOM file"<<endl;
}
DOMParse parser;
DOMNode* root = parser.GetDOM(argv[1]);
if(root != NULL)
root->PrintBreadth();
}
<file_sep>#include "AnimationParse.h"
#include "DOMNode.h"
#include "DOMParse.h"
#include <vector>
#include <iostream>
#include <tuple>
#include <stdlib.h>
#include <string>
using namespace std;
AnimationParse::AnimationParse()
{
}
AnimationParse::~AnimationParse()
{
}
vector<tAnimation> AnimationParse::GetAnimations(string path)
/**
Parses and returns a camera path
*/
{
//output vector of animation
vector<tAnimation> vAnimation;
//DOM parse
DOMNode * pDOM = this->GetDOM(path);
if(pDOM == NULL)
{
cout<<"DOM not parsed"<<endl;
return vAnimation;
}
//stores found animations
vector<DOMNode *> * pvpDOM = new vector<DOMNode *>();
//find nodes having animation
this->FindAnimation(pvpDOM, pDOM);
for(auto i : *pvpDOM)
{
tAnimation NewAnimation;
for(auto j : i->Children)
{
if(j->Type == "name")
{
std::get<TANIMATION_NAME>(NewAnimation) = j->Data;
}
else if(j->Type == "time")
{
std::get<TANIMATION_TIME>(NewAnimation) = atof(j->Data.c_str());
}
else if(j->Type == "action")
{
std::get<TANIMATION_ACTION>(NewAnimation) = j->Data;
}
else if(j->Type == "subject")
{
std::get<TANIMATION_SUBJECT>(NewAnimation) = j->Data;
}
else if(j->Type == "extra")
{
std::get<TANIMATION_EXTRA>(NewAnimation) = j->Data;
}
}
vAnimation.push_back(NewAnimation);
}
return vAnimation;
}
void AnimationParse::FindAnimation(vector<DOMNode *> * pvpDOM, DOMNode * node)
{
if(node->Type == "animation")
{
pvpDOM->push_back(node);
}
for(auto i : node->Children)
{
this->FindAnimation(pvpDOM, i);
}
return;
}
<file_sep>#ifndef MATRIXMATH_H
#define MATRIXMATH_H
#define PI 3.14159265359
///methods for matrix arithmetic in column major format
namespace MatrixMath{
bool InvertMatrix(const float m[16], float invOut[16]); /// provides matrix inversion, from http://stackoverflow.com/questions/1148309/inverting-a-4x4-matrix
void Mat4x4Mult4x1(float FourByOne[], float FourbyFour[], float out[]); /// provides 4x4 * 4x1 matrix operation
void Mat1x4Mult4x4(float FourByOne[], float FourbyFour[], float out[]); /// provides 1x4 * 4x4 matrix operation
void Mat4x4Mult4x4(float Left[], float Right[], float out[]); /// provides 4x4 * 4x4 matrix operation
void Mat4x4Transpose(float in[], float out[]); /// transposes 4x4 matrix
void Mat4x4Normalize(float in[], float out[]); /// normalizes transformation matrix
void Mat4x1Normalize(float in[], float out[]);
void PrintMat4x4(float in[]);
void PrintMat4x1(float in[]);
void GetMat4x4Identity(float out[]);
void GetMat4x4Rotation(float in[], float r[]);
void NormalizeScalingMat4x4(float in[], float out[]);
void InvertTranslateMat4x4(float in[], float out[]);
void InvertTranslateZMat4x4(float in[], float out[]);
void InvertRotateMat4x4(float in[], float out[]);
}
#endif
<file_sep>#include "ParametricCurve.h"
#include "CurvePath.h"
#include <iostream>
#include <vector>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
using namespace std;
CurvePath::CurvePath()
{
}
CurvePath::~CurvePath()
{
}
void CurvePath::Draw()
{
//incrementing logic
if(this->GetKeepIncrementing() == true)
{
this->Increment();
//save new position
float pos[3];
this->GetPosition(pos);
// this->PrintPosition();
this->ApplyTranslate(pos);
}
// glBegin(GL_POINTS);
// glColor3f(1,1,1);
// // position is actually transformed using ModelTransform's ApplyTranslate in Increment function
// glVertex3f(0,0,0);
// glEnd();
}
void CurvePath::FormatAction()
{
int count = 0;
for(auto i: vAction)
{
if(count == 0)
{
if(i == "curve_increment")
{
this->SetKeepIncrementing(true);
}
else if(i == "curve_stopincrement")
{
this->SetKeepIncrementing(false);
}
}
}
}
void CurvePath::AddCurve(int steps, float ctrlpoint1[], float ctrlpoint2[], float ctrlpoint3[], float ctrlpoint4[])
{
Interpolate::AddCurve(steps, ctrlpoint1, ctrlpoint2, ctrlpoint3, ctrlpoint4);
}
<file_sep>#ifndef CURVEDATA_H
#define CURVEDATA_H
#include "ModelData.h"
#include <vector>
#include <tuple>
typedef tuple<int, float,float,float, float,float,float, float,float,float, float,float,float> tCurveControl;
#define TCURVECONTROL_STEP 0
#define TCURVECONTROL_PT1_X 1
#define TCURVECONTROL_PT1_Y 2
#define TCURVECONTROL_PT1_Z 3
#define TCURVECONTROL_PT2_X 4
#define TCURVECONTROL_PT2_Y 5
#define TCURVECONTROL_PT2_Z 6
#define TCURVECONTROL_PT3_X 7
#define TCURVECONTROL_PT3_Y 8
#define TCURVECONTROL_PT3_Z 9
#define TCURVECONTROL_PT4_X 10
#define TCURVECONTROL_PT4_Y 11
#define TCURVECONTROL_PT4_Z 12
///stores control points for bezier curve
class CurveData : public ModelData
{
public:
vector<tCurveControl> vCurveControl; ///storage for bezier curve control points
CurveData();
void FormatData();
void ClearData();
};
#endif
<file_sep>#include "CurveData.h"
#include <vector>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
CurveData::CurveData()
{
this->mType = CURVE;
//ignore these tags for current version of implementation
this->mBeginTag = "<curve>";
this->mEndTag = "</curve>";
}
void CurveData::FormatData()
{
if(this->vDataItem.size()%13 != 0)
{
cout<<"number of Curve control point arguments not valid"<<endl;
return;
}
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); )
{
tCurveControl NewControlPoint;
std::get<TCURVECONTROL_STEP>(NewControlPoint) = atoi((*it).c_str());
std::get<TCURVECONTROL_PT1_X>(NewControlPoint) = atof((*(it+1)).c_str());
std::get<TCURVECONTROL_PT1_Y>(NewControlPoint) = atof((*(it+2)).c_str());
std::get<TCURVECONTROL_PT1_Z>(NewControlPoint) = atof((*(it+3)).c_str());
std::get<TCURVECONTROL_PT2_X>(NewControlPoint) = atof((*(it+4)).c_str());
std::get<TCURVECONTROL_PT2_Y>(NewControlPoint) = atof((*(it+5)).c_str());
std::get<TCURVECONTROL_PT2_Z>(NewControlPoint) = atof((*(it+6)).c_str());
std::get<TCURVECONTROL_PT3_X>(NewControlPoint) = atof((*(it+7)).c_str());
std::get<TCURVECONTROL_PT3_Y>(NewControlPoint) = atof((*(it+8)).c_str());
std::get<TCURVECONTROL_PT3_Z>(NewControlPoint) = atof((*(it+9)).c_str());
std::get<TCURVECONTROL_PT4_X>(NewControlPoint) = atof((*(it+10)).c_str());
std::get<TCURVECONTROL_PT4_Y>(NewControlPoint) = atof((*(it+11)).c_str());
std::get<TCURVECONTROL_PT4_Z>(NewControlPoint) = atof((*(it+12)).c_str());
this->vCurveControl.push_back(NewControlPoint);
it += 13;
}
#ifdef DEBUG
//check saved model data
for(auto j : this->vCurveControl)
{
cout<<"tuple data: "<<std::get<TCURVECONTROL_STEP>(j)<<", "<<std::get<TCURVECONTROL_PT1_Z>(j)<<", "<<std::get<TCURVECONTROL_PT4_Z>(j)<<endl;
}
#endif
}
void CurveData::ClearData()
{
this->vDataItem.clear();
this->vCurveControl.clear();
}
<file_sep>/// @author <NAME> #63461081 EECE478 2014 Spring
//flag set to bypass initialization problem with GLUT
#define GLUT_DISABLE_ATEXIT_HACK
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdlib.h>
#include <string>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <iostream>
#include <cmath>
#include <time.h>
#include "ModelPool.h"
#include "ModelAbstraction.h"
#include "AnimationManager.h"
#include "AnimationParse.h"
#include "TrajectoryParse.h"
#include "CurvePath.h"
#include "CityParse.h"
#include "Lighting.h"
#include "LightingParse.h"
#include <vector>
using namespace std;
///global variables for mouse and key states, transformations, model entity
namespace glut_global
{
AnimationManager * pmanager;
AnimationParse * panimationparser;
//camera entity
ModelAbstraction* pCameraEntityRotate;
ModelAbstraction* pCameraTranslate;
///transformation variables
float vCamRotX = 0;
float vCamRotY = 0;
float vCamRotOldX = 0;
float vCamRotOldY = 0;
float vScale = 0;
float vScaleOld = 0;
float vTransX = 0;
float vTransY = 0;
float vTransZ = 0;
///saves transformations of the model
float vModelTranslation[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelScaling[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelRotation[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
///mouse and key states
int vMouseOldX;
int vMouseOldY;
int vMouseDx = 0;
int vMouseDy = 0;
bool bMouseLeftDown = false;
bool bKeyShiftDown = false;
bool bKeyWDown = false;
bool bKeyADown = false;
bool bKeySDown = false;
bool bKeyDDown = false;
bool bKeyQDown = false;
bool bKeyCDown = false;
bool bKeyVDown = false;
///window dimensions
int vWidth;
int vHeight;
}
using namespace glut_global;
void myIdle()
{
bool ticked = pmanager->Tick();
if(ticked == true)
{
cout<<"time: "<<pmanager->GetTime()<<" s"<<endl;
glutPostRedisplay();
}
}
void fKeyboardDown(unsigned char key, int x, int y)
/**
QWASDCV key down detection
*/
{
if(key == 'w')
bKeyWDown = true;
if(key == 'a')
bKeyADown = true;
if(key == 's')
bKeySDown = true;
if(key == 'd')
bKeyDDown = true;
if(key == 'q')
bKeyQDown = !bKeyQDown; // toggle only for switching models
if(key == 'c')
bKeyCDown = true;
if(key == 'v')
bKeyVDown = true;
glutPostRedisplay();
}
void fKeyboardUp(unsigned char key, int x, int y)
/**
WASDCV key up detection
*/
{
if(key == 'w')
bKeyWDown = false;
if(key == 'a')
bKeyADown = false;
if(key == 's')
bKeySDown = false;
if(key == 'd')
bKeyDDown = false;
if(key == 'c')
bKeyCDown = false;
if(key == 'v')
bKeyVDown = false;
glutPostRedisplay();
}
void fMouseDown(int button, int state, int x, int y)
/**
mouse down and up detection
*/
{
vMouseOldX = x;
vMouseOldY = y;
bMouseLeftDown = (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN);
//detect shift key is pressed
int mod = glutGetModifiers();
bKeyShiftDown = (mod == GLUT_ACTIVE_SHIFT);
if(!bMouseLeftDown) // reset mouse delta when left mouse is up
{
vMouseDx = 0;
vMouseDy = 0;
}
glutPostRedisplay();
}
void fMouseMotion(int x, int y)
/**
calculate left mouse delta and shift key state
*/
{
//detect shift key is pressed
int mod = glutGetModifiers();
//bKeyShiftDown = (mod == GLUT_ACTIVE_SHIFT);
if(bMouseLeftDown)
{
vMouseDx = x - vMouseOldX;
vMouseDy = y - vMouseOldY;
#ifdef DEBUG
cout<<"left mouse: "<< vMouseDx <<", "<< vMouseDy <<endl;
#endif
}
glutPostRedisplay();
}
void reshape(int width, int height)
/**
resize window and set perspective parameters
*/
{
vWidth = width;
vHeight = height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(100, (float)width / height, 1, 10000);
glMatrixMode(GL_MODELVIEW);
}
void display(void)
/**
basic order of drawing operation:
1.push current model/projection
a.model
i.translate transform
ii.rotate transform
iii.scale transform
b.projection
i.apply projection transform
2.draw object
3.pop restore previous model/projection
*/
{
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1, 1, 1);
glPushMatrix();
//reset matrix
glLoadIdentity();
//additional translation from WASDCV (forward,left,back,right,up,down) keys
vTransX = 0;
vTransY = 0;
vTransZ = 0;
//delta when key is down
vTransZ += (bKeyWDown)? 0.3: 0;
vTransX += (bKeyADown)? 0.3: 0;
vTransZ += (bKeySDown)? -0.3: 0;
vTransX += (bKeyDDown)? -0.3: 0;
vTransY += (bKeyCDown)? -0.3: 0;
vTransY += (bKeyVDown)? 0.3: 0;
//apply translation
float DeltaTranslate[3]={0,0,0};
DeltaTranslate[0] = vTransX;
DeltaTranslate[1] = vTransY;
DeltaTranslate[2] = vTransZ;
//apply rotation transform if only left mouse is down
float DeltaRotate[3]={0,0,0};
if(bMouseLeftDown && !bKeyShiftDown)
{
//get rotation delta
vCamRotY = vMouseDx/1.f;
vCamRotX = vMouseDy/1.f;
DeltaRotate[0] = vCamRotX - vCamRotOldX;
DeltaRotate[1] = vCamRotY - vCamRotOldY;
DeltaRotate[2] = 0;
//update rotation delta
vCamRotOldX = vCamRotX;
vCamRotOldY = vCamRotY;
}
else //reset rotation delta when left mouse is up
{
vCamRotY = 0;
vCamRotX = 0;
vCamRotOldY = 0;
vCamRotOldX = 0;
}
//scale object and avoid negative scaling
float DeltaScale[3] = {0,0,0};
if(bMouseLeftDown && bKeyShiftDown)
{
//get delta
vScale = -vMouseDy/3000.f;
for(int j = 0; j < 3; j++)
{
DeltaScale[j] = vScale-vScaleOld;
}
vScaleOld = vScale;
}
else
{
vScale = 0;
vScaleOld = 0;
}
//apply transforms to camera
pCameraTranslate->ApplyDeltaTranslate(DeltaTranslate);
pCameraEntityRotate->ApplyDeltaRotate(DeltaRotate);
pCameraEntityRotate->ApplyDeltaScale(DeltaScale);
pCameraEntityRotate->DrawCascade();
//revert state model stack
glPopMatrix();
//setup projection for text overlay
glMatrixMode(GL_PROJECTION);
//save state projection stack
glPushMatrix();
glLoadIdentity();
// apply parallel projection transform for text display
gluOrtho2D(0.0, vWidth, 0.0, vHeight);
glMatrixMode(GL_MODELVIEW);
//save state model stack
glPushMatrix();
glLoadIdentity();
// Draw text at bottom right
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glRasterPos2i(vWidth-70, 20);
string name = "<NAME>";
for(int i = 0; i < name.length(); i++)
{
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, name[i]);
}
//revert state model stack
glPopMatrix();
glMatrixMode(GL_PROJECTION);
//revert state projection stack
glPopMatrix();
glutSwapBuffers();
}
void init (void)
/**
setup background colour
setup projection transformation
setup vertex buffer and load model vertex
*/
{
glClearColor (0.3, 0.3, 0.3, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
}
void fExit()
{
cout<<"exited program"<<endl;
}
/*
* Declare initial window size, position, and display mode
* (single buffer and RGBA). Open window with "hello"
* in its title bar. Call initialization routines.
* Register callback function to display graphics.
* Enter main loop and process events.
*/
int main(int argc, char** argv)
{
if(argc < 5)
{
cout<<"not enough arguments: <curve path> <animation path> <city path> <light path>"<<endl;
return -1;
}
//boilerplate
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Assignment 1");
//initialize glew for vertex shader
GLenum err = glewInit();
if(GLEW_OK != err)
{
cout<<"glew init failed"<<endl;
return -1;
}
glEnable(GL_POLYGON_SMOOTH);
glEnable(GL_TEXTURE_2D);
glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glutReshapeFunc(reshape);
init();
//set callback functions
glutIdleFunc(myIdle);
glutDisplayFunc(display);
glutMouseFunc(fMouseDown);
glutMotionFunc(fMouseMotion);
glutKeyboardFunc(fKeyboardDown);
glutKeyboardUpFunc(fKeyboardUp);
//exit callback
atexit(fExit);
//initialize camera stand and camera
pCameraEntityRotate = new ModelAbstraction();
pCameraEntityRotate->Name = "camerarotate";
pCameraTranslate = new ModelAbstraction();
pCameraTranslate->Name = "camera";
pCameraEntityRotate->AddChild(pCameraTranslate);
float trans[] = {0,0,-40};
pCameraTranslate->ApplyDeltaTranslate(trans);
//parse city
CityParse cityparser;
vector<ModelAbstraction *> vcitymodel = cityparser.ParseCity(argv[3]);
//parse curve
TrajectoryParse parser;
vector<CurvePath *> vCurve = parser.GetTrajectories(argv[1]);
//parse animation
AnimationParse animationparser;
vector<tAnimation> vAnimation = animationparser.GetAnimations(argv[2]);
panimationparser = &animationparser;
//parse lights
LightingParse lightparser;
vector<Lighting*> vlights = lightparser.GetLightings(argv[4]);
//create animation manager
AnimationManager manager;
pmanager = &manager;
//add models to world and sync model pool to each object
manager.AddModel(pCameraEntityRotate);
pCameraEntityRotate->SetModelPool(manager.GetModelPool());
manager.AddModel(pCameraTranslate);
pCameraTranslate->SetModelPool(manager.GetModelPool());
for(auto i: vCurve)
{
manager.AddModel(i);
i->SetModelPool(manager.GetModelPool());
}
for(auto i: vcitymodel)
{
manager.AddModel(i);
i->SetModelPool(manager.GetModelPool());
}
for(auto i: vlights)
{
manager.AddModel(i);
i->SetModelPool(manager.GetModelPool());
}
//add animations
for(auto i : vAnimation)
{
manager.AddAnimation(i);
}
//set up fps and run clock
manager.SetFps(30.0);
manager.Run();
//run gl loop
glutMainLoop();
return 0;
}
<file_sep>#include "DOMParse.h"
#include "DOMNode.h"
#include "DOMMatcher.h"
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
DOMParse::DOMParse()
{
//initialize DOM types to find
tDOMMatcher MatchAnimation;
std::get<TDOMMATCHER_TYPE>(MatchAnimation) = "animation";
std::get<TDOMMATCHER_STARTTAG>(MatchAnimation) = "<animation>";
std::get<TDOMMATCHER_ENDTAG>(MatchAnimation) = "</animation>";
tDOMMatcher MatchTime;
std::get<TDOMMATCHER_TYPE>(MatchTime) = "time";
std::get<TDOMMATCHER_STARTTAG>(MatchTime) = "<time>";
std::get<TDOMMATCHER_ENDTAG>(MatchTime) = "</time>";
tDOMMatcher MatchAction;
std::get<TDOMMATCHER_TYPE>(MatchAction) = "action";
std::get<TDOMMATCHER_STARTTAG>(MatchAction) = "<action>";
std::get<TDOMMATCHER_ENDTAG>(MatchAction) = "</action>";
tDOMMatcher MatchName;
std::get<TDOMMATCHER_TYPE>(MatchName) = "name";
std::get<TDOMMATCHER_STARTTAG>(MatchName) = "<name>";
std::get<TDOMMATCHER_ENDTAG>(MatchName) = "</name>";
tDOMMatcher MatchCurve;
std::get<TDOMMATCHER_TYPE>(MatchCurve) = "curve";
std::get<TDOMMATCHER_STARTTAG>(MatchCurve) = "<curve>";
std::get<TDOMMATCHER_ENDTAG>(MatchCurve) = "</curve>";
tDOMMatcher MatchData;
std::get<TDOMMATCHER_TYPE>(MatchData) = "data";
std::get<TDOMMATCHER_STARTTAG>(MatchData) = "<data>";
std::get<TDOMMATCHER_ENDTAG>(MatchData) = "</data>";
tDOMMatcher MatchTranslation;
std::get<TDOMMATCHER_TYPE>(MatchTranslation) = "translation";
std::get<TDOMMATCHER_STARTTAG>(MatchTranslation) = "<translation>";
std::get<TDOMMATCHER_ENDTAG>(MatchTranslation) = "</translation>";
tDOMMatcher MatchScale;
std::get<TDOMMATCHER_TYPE>(MatchScale) = "scale";
std::get<TDOMMATCHER_STARTTAG>(MatchScale) = "<scale>";
std::get<TDOMMATCHER_ENDTAG>(MatchScale) = "</scale>";
tDOMMatcher MatchRotation;
std::get<TDOMMATCHER_TYPE>(MatchRotation) = "rotation";
std::get<TDOMMATCHER_STARTTAG>(MatchRotation) = "<rotation>";
std::get<TDOMMATCHER_ENDTAG>(MatchRotation) = "</rotation>";
tDOMMatcher MatchSubject;
std::get<TDOMMATCHER_TYPE>(MatchSubject) = "subject";
std::get<TDOMMATCHER_STARTTAG>(MatchSubject) = "<subject>";
std::get<TDOMMATCHER_ENDTAG>(MatchSubject) = "</subject>";
tDOMMatcher MatchExtra;
std::get<TDOMMATCHER_TYPE>(MatchExtra) = "extra";
std::get<TDOMMATCHER_STARTTAG>(MatchExtra) = "<extra>";
std::get<TDOMMATCHER_ENDTAG>(MatchExtra) = "</extra>";
tDOMMatcher MatchControlpoint;
std::get<TDOMMATCHER_TYPE>(MatchControlpoint) = "controlpoint";
std::get<TDOMMATCHER_STARTTAG>(MatchControlpoint) = "<controlpoint>";
std::get<TDOMMATCHER_ENDTAG>(MatchControlpoint) = "</controlpoint>";
tDOMMatcher MatchLight_Ambient;
std::get<TDOMMATCHER_TYPE>(MatchLight_Ambient) = "light_ambient";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Ambient) = "<light_ambient>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Ambient) = "</light_ambient>";
tDOMMatcher MatchLight_Specular;
std::get<TDOMMATCHER_TYPE>(MatchLight_Specular) = "light_specular";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Specular) = "<light_specular>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Specular) = "</light_specular>";
tDOMMatcher MatchLight_Diffuse;
std::get<TDOMMATCHER_TYPE>(MatchLight_Diffuse) = "light_diffuse";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Diffuse) = "<light_diffuse>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Diffuse) = "</light_diffuse>";
tDOMMatcher MatchLight_Position;
std::get<TDOMMATCHER_TYPE>(MatchLight_Position) = "light_position";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Position) = "<light_position>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Position) = "</light_position>";
tDOMMatcher MatchLight_Direction;
std::get<TDOMMATCHER_TYPE>(MatchLight_Direction) = "light_direction";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Direction) = "<light_direction>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Direction) = "</light_direction>";
tDOMMatcher MatchLight_Exponent;
std::get<TDOMMATCHER_TYPE>(MatchLight_Exponent) = "light_exponent";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Exponent) = "<light_exponent>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Exponent) = "</light_exponent>";
tDOMMatcher MatchLight_Cutoff;
std::get<TDOMMATCHER_TYPE>(MatchLight_Cutoff) = "light_cutoff";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Cutoff) = "<light_cutoff>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Cutoff) = "</light_cutoff>";
tDOMMatcher MatchLighting;
std::get<TDOMMATCHER_TYPE>(MatchLighting) = "lighting";
std::get<TDOMMATCHER_STARTTAG>(MatchLighting) = "<lighting>";
std::get<TDOMMATCHER_ENDTAG>(MatchLighting) = "</lighting>";
tDOMMatcher MatchLight_Turnon;
std::get<TDOMMATCHER_TYPE>(MatchLight_Turnon) = "light_turnon";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Turnon) = "<light_turnon>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Turnon) = "</light_turnon>";
tDOMMatcher MatchLight_Turnoff;
std::get<TDOMMATCHER_TYPE>(MatchLight_Turnoff) = "light_turnoff";
std::get<TDOMMATCHER_STARTTAG>(MatchLight_Turnoff) = "<light_turnoff>";
std::get<TDOMMATCHER_ENDTAG>(MatchLight_Turnoff) = "</light_turnoff>";
vDOMMatcher.push_back(MatchAnimation);
vDOMMatcher.push_back(MatchTime);
vDOMMatcher.push_back(MatchAction);
vDOMMatcher.push_back(MatchName);
vDOMMatcher.push_back(MatchCurve);
vDOMMatcher.push_back(MatchData);
vDOMMatcher.push_back(MatchTranslation);
vDOMMatcher.push_back(MatchScale);
vDOMMatcher.push_back(MatchRotation);
vDOMMatcher.push_back(MatchSubject);
vDOMMatcher.push_back(MatchExtra);
vDOMMatcher.push_back(MatchControlpoint);
vDOMMatcher.push_back(MatchLight_Ambient);
vDOMMatcher.push_back(MatchLight_Specular);
vDOMMatcher.push_back(MatchLight_Diffuse);
vDOMMatcher.push_back(MatchLight_Position);
vDOMMatcher.push_back(MatchLight_Direction);
vDOMMatcher.push_back(MatchLight_Exponent);
vDOMMatcher.push_back(MatchLight_Cutoff);
vDOMMatcher.push_back(MatchLighting);
vDOMMatcher.push_back(MatchLight_Turnon);
vDOMMatcher.push_back(MatchLight_Turnoff);
}
DOMNode * DOMParse::GetDOM(string path)
/**
Parses DOM and returns root
*/
{
DOMNode * root = new DOMNode;
ifstream ifs;
stringstream Ss;
//open model file
ifs.open(path.c_str(), ifstream::in);
if(!ifs.is_open())
{
cout<<"error opening file: "<<path<<endl;
return NULL;
}
string line;
int LineNum = 0;
//remove parsed lines with #comments
while (getline(ifs, line))
{
size_t found = line.find("#");
if(found == std::string::npos){
Ss<<line<<" "; // save remaining lines to a single lined buffer and add space to ensure data separation
}
}
line = Ss.str();
//parse
this->NestedDOM(root, line);
//null if empty
if(root->Children.size() == 0)
{
cout<<"empty parse file"<<endl;
return NULL;
}
return root;
}
void DOMParse::NestedDOM(DOMNode * parent, string line)
{
if(this->vDOMMatcher.empty())
return;
int LineNum = 0;
string linetemp = line;
size_t SmallestFoundStartTag = 999999;
tDOMMatcher CurrentMatcher = this->vDOMMatcher.at(0);
//try to find the tag that appears first
for(auto i : this->vDOMMatcher)
{
string TempStartTag = std::get<TDOMMATCHER_STARTTAG>(i);
size_t TempFoundStartTag = linetemp.find(TempStartTag);
if(TempFoundStartTag != std::string::npos)
{
if(TempFoundStartTag < SmallestFoundStartTag)
{
SmallestFoundStartTag = TempFoundStartTag;
CurrentMatcher = i;
}
}
}
if(SmallestFoundStartTag == 999999)
return;
if(linetemp == "")
return;
string Type = std::get<TDOMMATCHER_TYPE>(CurrentMatcher);
string starttag = std::get<TDOMMATCHER_STARTTAG>(CurrentMatcher);
string endtag = std::get<TDOMMATCHER_ENDTAG>(CurrentMatcher);
size_t FoundStartTag;
size_t FoundEndTag;
size_t SavedFoundStartTag = std::string::npos;
size_t SavedFoundEndTag;
//save the number of occurances of start tag before 1st end tag
int occurrencesStart = 0;
int occurrencesEnd = 0;
size_t start = 0;
size_t end = 0;
int occurrencesStartOld = occurrencesStart;
int occurrencesEndOld = occurrencesEnd;
//match number of start tags to number of end tags
while (occurrencesStart != occurrencesEnd || occurrencesEnd == 0)
{
//find end tag first
FoundEndTag = linetemp.find(endtag, end);
if(FoundEndTag != std::string::npos)
{
end = FoundEndTag + endtag.length();
occurrencesEnd++;
SavedFoundEndTag = FoundEndTag;
}
occurrencesStart = 0;
start = 0;
//find start tag
do
{
FoundStartTag = linetemp.substr(0, SavedFoundEndTag).find(starttag,start);
if(FoundStartTag != std::string::npos)
{
occurrencesStart++;
start = FoundStartTag + starttag.length();
}
}while(FoundStartTag != std::string::npos);
//see if DOM is invalid and return
if(occurrencesEndOld == occurrencesEnd && occurrencesStartOld == occurrencesStart)
{
return;
}
occurrencesStartOld = occurrencesStart;
occurrencesEndOld = occurrencesEnd;
}
//get 1st start tag
SavedFoundStartTag = linetemp.substr(0, SavedFoundEndTag).find(starttag);
//find <tags> and </tags> defined in DOMMatcher
if(SavedFoundStartTag != std::string::npos)
{
if(SavedFoundEndTag != std::string::npos)
{
//when found begin and end tags, extract string
string SubString = linetemp.substr(SavedFoundStartTag + starttag.length(),SavedFoundEndTag-(SavedFoundStartTag + starttag.length()));
//creates a DOM object and attach to parent node
DOMNode * NewNode = new DOMNode;
parent->AddChild(NewNode);
NewNode->Data = SubString;
NewNode->Type = Type;
//search for nested DOM
this->NestedDOM(NewNode, SubString);
//continue search on remaining string before it
string unsearchedbefore = linetemp.substr(0, SavedFoundStartTag);
this->NestedDOM(parent, unsearchedbefore);
//continue search on remaining string after it
string unsearchedafter = linetemp.substr(SavedFoundEndTag + endtag.length(), std::string::npos);
this->NestedDOM(parent, unsearchedafter);
}
}
return;
}
<file_sep>#ifndef MAT_H
#define MAT_H
#include "Vec.h"
///column major matrix
class Mat{
public:
float * _mat; // mat data
Vec _dim; //mat dimension
int _size; //overall mat size
Mat(); //default 4x4 matrix
void ResizeInt( int count, int dim [] );
void ResizeVec( const Vec & v );
Mat & operator = ( const Mat & m ); //copy
Mat operator * ( const Mat & m ) const; //matrix multiplication, up to 2D mat for now
Mat operator + ( const Mat & m ) const; //element add
Mat operator - ( const Mat & m ) const; //element subtract
float & operator ()( int m, int n ); //accessor
float operator ()( int m, int n ) const; //accessor
void SetFromVec( const Vec & v, bool column = true); //convert from a Vec, default is a column vector
bool GetVec( Vec & v, int index, bool column = true ) const; //get a particular column or row of the current Mat
bool GetSubMat( Mat & m, int row, int col, int sizerow, int sizecol ) const; //get a sub Mat
void TransposeCurrent();
Mat Transpose() const;
};
#endif
<file_sep>#ifndef CLOCK_H
#define CLOCK_H
#include <string>
#include <chrono>
using namespace std;
/// provides timing and triggering ability
class Clock
{
private:
float Fps;
float FpsActual;
float AutoDuration; /// stores how many milliseconds between consecutive frames
float AutoDurationScaled;
float TimeSinceStart; ///current time not counting paused time in milliseconds
chrono::high_resolution_clock::time_point TimePrev;
chrono::high_resolution_clock::time_point Time;
bool bRunning; ///flag indicating if clock is running
float ClockScale;
public:
Clock();
bool SetFps(float fps); /// sets frames per second
bool Tick(); /// runs clock if fps is valid and clock is not paused
void Run(); /// runs the clock
void Pause(); /// pauses the clock
float GetFps();
void SetClockScale(float);
bool IsRunning();
float GetTime(); /// get current time in milliseconds
virtual void TickAction(string a){}; /// implementation method called after each clock Tick success
};
#endif
<file_sep>#ifndef ANIMATIONPARSE_H
#define ANIMATIONPARSE_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include "DOMParse.h"
#include "DOMNode.h"
///accesoor index for animation information
#define TANIMATION_NAME 0
#define TANIMATION_TIME 1
#define TANIMATION_ACTION 2
#define TANIMATION_SUBJECT 3
#define TANIMATION_EXTRA 4
/// storage for animation information
typedef tuple<string,float,string,string,string> tAnimation;
using namespace std;
///parses Animation input file and returns animation entities
class AnimationParse : public DOMParse
{
private:
///helper function to find all animations in DOM
void FindAnimation(vector<DOMNode *> * pvpDOM, DOMNode * node);
public:
AnimationParse();
~AnimationParse();
vector<tAnimation> GetAnimations(string path); ///factory function to generate animation entities from input animation file
};
#endif
<file_sep>/**
<NAME>
#63461081
Info:
Convert .obj file to custom file format
.obj file need have vertex and texture coordinates
This generates custom file format having vertices, face normals, triangles, texture coordinates, and 1 reference to 1 texture image per object having the name as object_name.ppm
*/
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <cmath>
#include <tuple>
using namespace std;
typedef tuple<int,int,int, int, int, float,float,float,float,float,float> tTriangleData;
int main(int argc, char** argv)
{
if(argc<4)
{
cout<<"need: <input .obj file> <output file name> <object name>"<<endl;
return 0;
}
fstream input;
fstream output;
input.open (argv[1], std::fstream::in);
output.open (argv[2], std::fstream::out | std::fstream::trunc);
string current;
stringstream ss;
vector<vector<float> > vTexturecoord;
vector<vector<float> > vVertex;
vector<vector<float> > vNormal;
vector<tTriangleData> vTriangle;
vector<string> vTextureName;
int objectCount = 0;
int triangleCount = 0;
while (getline(input, current))
{
ss.flush();
//ignore comments
size_t found = current.find("#");
if(found != std::string::npos)
{
continue;
}
//ignore object name
found = current.find("g ");
if(found != std::string::npos)
{
ss << current.substr(found + 2, string::npos)<<endl;
string name;
ss >> name;
vTextureName.push_back(name);
objectCount++;
continue;
}
//vertices
found = current.find("v ");
if(found != std::string::npos)
{
ss<<current.substr(found + 2, string::npos)<<endl;
//save vertex to vector
vector<float> vertex;
float temp;
for(int i = 0; i < 3; i ++)
{
ss >> temp;
vertex.push_back(temp);
}
vVertex.push_back(vertex);
continue;
}
//texture coordinates
found = current.find("vt ");
if(found != std::string::npos)
{
//save texture coordinates to vector
vector<float> texture;
ss<<current.substr(found + 3, string::npos)<<endl;
float texturedata;
for(int i = 0; i < 3; i ++)
{
ss >> texturedata;
texture.push_back(texturedata);
}
vTexturecoord.push_back(texture);
continue;
}
//triangles
found = current.find("f ");
if(found != std::string::npos)
{
string triangle;
triangle = current.substr(found + 2, string::npos);
//format '/' delimited triangle data: vertex/texturecoord
int vertIndex[3];
int textIndex[3];
sscanf(triangle.c_str(),"%d/%d %d/%d %d/%d",&vertIndex[0],&textIndex[0],&vertIndex[1],&textIndex[1],&vertIndex[2],&textIndex[2]);
//write vertice indexes to output file
for(int i = 0; i < 3; i++)
{
//convert index to 0 based
vertIndex[i]--;
textIndex[i]--;
}
triangleCount++;
//compute the triangle normal from vertices
float vec1[3];
float vec2[3];
vector<float> temp1 = vVertex.at(vertIndex[0]);
vector<float> temp2 = vVertex.at(vertIndex[1]);
vector<float> temp3 = vVertex.at(vertIndex[2]);
for(int i = 0; i < 3; i++)
{
vec1[i] = temp2.at(i) - temp1.at(i);
vec2[i] = temp3.at(i) - temp1.at(i);
}
//cross product
float norm[3];
norm[0] = vec1[1]*vec2[2] - vec1[2]*vec2[1];
norm[1] = vec1[2]*vec2[0] - vec1[0]*vec2[2];
norm[2] = vec1[0]*vec2[1] - vec1[1]*vec2[0];
//normalize normals and save to vector
vector<float> normalData;
float mag = sqrt(pow(norm[0],2) + pow(norm[1],2) + pow(norm[2],2));
for(int i = 0; i < 3; i++)
{
norm[i] = norm[i]/mag;
normalData.push_back(norm[i]);
if(isnan(norm[i]))
cout<<"Warning: NaN in object: "<<objectCount<<" triangle: "<<triangleCount<<" vec1: "<<vec1[i]<<" vec2: "<<vec2[i]<<endl;
}
vNormal.push_back(normalData);
//save triangle to vector
//vertice indices
tTriangleData data;
std::get<0>(data) = vertIndex[0];
std::get<1>(data) = vertIndex[1];
std::get<2>(data) = vertIndex[2];
//normal index (same as triangle index)
std::get<3>(data) = triangleCount-1;
//texture index (same as object index)
std::get<4>(data) = objectCount-1;
//texture coodinates
std::get<5>(data) = vTexturecoord.at(textIndex[0]).at(0);
std::get<6>(data) = vTexturecoord.at(textIndex[0]).at(1);
std::get<7>(data) = vTexturecoord.at(textIndex[1]).at(0);
std::get<8>(data) = vTexturecoord.at(textIndex[1]).at(1);
std::get<9>(data) = vTexturecoord.at(textIndex[2]).at(0);
std::get<10>(data) = vTexturecoord.at(textIndex[2]).at(1);
vTriangle.push_back(data);
continue;
}
}
//write building name and texture file
output<<"<name>"<<argv[3]<<"</name>"<<endl;
//write texture names
output<<"<textures>"<<endl;
for(auto i : vTextureName)
{
output<< i <<".ppm"<<endl;
}
output<<"</textures>"<<endl;
//write vertices
output<<"<vertices>"<<endl;
for(auto i : vVertex)
{
for(auto j : i)
{
output<< j << " ";
}
output<<endl;
}
output<<"</vertices>"<<endl;
//write computed face normals
output<<"<normals>"<<endl;
for(auto i : vNormal)
{
for(auto j : i)
{
output<< j <<" ";
}
output<<endl;
}
output<<"</normals>"<<endl;
//write triangles
output<<"<triangles>"<<endl;
for(auto i : vTriangle)
{
output<< std::get<0>(i) <<" ";
output<< std::get<1>(i) <<" ";
output<< std::get<2>(i) <<" ";
output<< std::get<3>(i) <<" ";
output<< std::get<4>(i) <<" ";
output<< std::get<5>(i) <<" ";
output<< std::get<6>(i) <<" ";
output<< std::get<7>(i) <<" ";
output<< std::get<8>(i) <<" ";
output<< std::get<9>(i) <<" ";
output<< std::get<10>(i) <<" ";
output<<endl;
}
output<<"</triangles>"<<endl;
input.close();
output.close();
return 0;
}
<file_sep>#include "ModelParse.h"
#include "ModelData.h"
#include "ModelName.h"
#include "ModelTexture.h"
#include "ModelVertice.h"
#include "ModelNormal.h"
#include "ModelTriangle.h"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
ModelParse::ModelParse()
{
}
ModelParse::~ModelParse()
/**
delete any allocated data
*/
{
for(auto i : vModelData)
{
delete i;
}
}
ModelEntity * ModelParse::GetEntity(string path)
/**
Parses and returns a model entity for the input model file
@param path model file path
@return ModelEntity an entity holding formatted data and also provides methods to draw triangles
*/
{
ifstream ifs;
stringstream Ss;
//open model file
ifs.open(path.c_str(), ifstream::in);
if(!ifs.is_open())
{
cout<<"error opening file: "<<path<<endl;
return NULL;
}
//creates containers for basic model data
ModelName * cModelName = new ModelName();
ModelTexture * cModelTexture = new ModelTexture();
ModelVertice * cModelVertice = new ModelVertice();
ModelNormal * cModelNormal = new ModelNormal();
ModelTriangle * cModelTriangle = new ModelTriangle();
//prepares to extract data using loop
vModelData.push_back((ModelData*)cModelName);
vModelData.push_back((ModelData*)cModelTexture);
vModelData.push_back((ModelData*)cModelVertice);
vModelData.push_back((ModelData*)cModelNormal);
vModelData.push_back((ModelData*)cModelTriangle);
string line;
int LineNum = 0;
//remove parsed lines with #comments
while (getline(ifs, line))
{
size_t found = line.find("#");
if(found == std::string::npos){
Ss<<line<<" "; // save remaining lines to a single lined buffer and add space to ensure data separation
}
}
this->bEmpty = true;
//find <tags> and </tags> defined in ModelData and extract string to ModelData
line.clear();
while (getline(Ss, line))
{
for(auto i : vModelData)
{
size_t FoundStartTag = line.find(i->mBeginTag);
if(FoundStartTag != std::string::npos)
{
size_t FoundEndTag = line.find(i->mEndTag);
if(FoundEndTag != std::string::npos)
{
//when found begin and end tags, extract string
string SubString = line.substr(FoundStartTag + i->mBeginTag.length(),FoundEndTag-(FoundStartTag + i->mBeginTag.length()));
i->SetData(SubString); // call derived ModelData classes to format and save data
this->bEmpty = false;
}
}
}
}
//if can't find tags, return
if(this->bEmpty)
{
return NULL;
}
//creates a model entity and save parsed data
ModelEntity * output = new ModelEntity();
output->Initialize(cModelName, cModelTexture, cModelVertice, cModelNormal, cModelTriangle);
//truncate path to the model folder path
string Folder = "/";
unsigned found = path.rfind(Folder);
if(found!=std::string::npos)
{
path = path.substr(0,found+1);
}
output->ModelFilePath = path;
//null pointers
cModelName = NULL;
cModelTexture = NULL;
cModelVertice = NULL;
cModelNormal = NULL;
cModelTriangle = NULL;
vModelData.clear();
return output;
}
<file_sep>#ifndef MODELNORMAL_H
#define MODELNORMAL_H
#include "ModelData.h"
#include <vector>
#include <sstream>
#include <tuple>
///access index to tuple
#define TNORMAL_ID 0
#define TNORMAL_X 1
#define TNORMAL_Y 2
#define TNORMAL_Z 3
using namespace std;
///tuple definition
typedef tuple<int, float,float,float> tNormal;
///container for triangle normals
class ModelNormal: ModelData
{
public:
ModelNormal();
vector< tNormal > vNormal; ///container for formatted data
void FormatData(); ///formats data
};
#endif
<file_sep>src_files := $(wildcard ./src/*.cpp)
src_files_obj2custom := $(wildcard ./obj2custom/*.cpp)
inc_dir:=./src
out := ./build
lib:= -lGL -lGLU -lGLEW -lglut
$(shell mkdir -p $(out))
#modelviewer project for assignment 1
modelviewer:
g++ -std=c++0x test/assign1.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/ModelViewer
#assignment 2 utility
obj2cutom:
g++ -std=c++0x $(src_files_obj2custom) -o $(out)/obj2custom
#test for city file parsing
cityparse:
g++ -std=c++0x test/CityParseTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/CityParseTest
#test for multiple model loading
multiplemodel:
g++ -std=c++0x test/MultipleModelTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/MultipleModelTest
#test for parametric curve
parametriccurve:
g++ -g -std=c++0x test/CurveTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/ParametricCurveTest
#test for camera motion with parametric curve
camerapath:
g++ -g -std=c++0x test/CameraPathTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/CameraPathTest
#test for curve parsing
curveparse:
g++ -g -std=c++0x test/CurveParse.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/CurveParseTest
#test for curve drawing
curvedraw:
g++ -g -std=c++0x test/CurveTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/CurveDraw
#test for DOM parse
domparse:
g++ -g -std=c++0x test/DOMParseTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/DOMParseTest
#test for curve parse using DOM and curve drawing
curveparsedraw:
g++ -g -std=c++0x test/CurveParseDraw.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/CurveParseDrawTest
#test for animation parsing
animationparsetest:
g++ -g -std=c++0x test/AnimationParseTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/AnimationParseTest
#test for animation manager
animationmanager:
g++ -g -std=c++0x test/AnimationManagerTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/AnimationManagerTest
#test for animation manager with drawing
animationmanagerdraw:
g++ -g -std=c++0x test/AnimationManagerDraw.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/AnimationManagerDrawTest
#test for image capture
recordertest:
g++ -g -std=c++0x test/RecorderTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/RecorderTest
#test for image capture
matrixmathtest:
g++ -g -std=c++0x test/MatrixMathTest.cpp $(src_files) -I$(inc_dir) $(lib) -o $(out)/MatrixMathTest
<file_sep>#include "MatrixMath.h"
#include <iostream>
using namespace MatrixMath;
using namespace std;
int main()
{
float in1[] = {3, 6, 7, 2, 5, 9, 12, 3, 45, 5, 23, 33, 6, 7, 12, -4};
float in2[] = {-34, 55, 13, 45, -7, 5, 34, 33.4, 8, 9, 12, 20, -16, 39, 50, 70};
float out[16];
Mat4x4Mult4x4(in1, in2, out);
cout<<"Multiplication result:"<<endl;
PrintMat4x4(out);
cout<<"Inverse of in1 result:"<<endl;
float inv[16];
InvertMatrix(in1, inv);
PrintMat4x4(inv);
cout<<"normalize inv(in1) result:"<<endl;
float norm[16];
Mat4x4Normalize(inv, norm);
PrintMat4x4(norm);
return 0;
}
<file_sep>#include <string>
#include <vector>
#include <tuple>
#include <iostream>
#include "ModelNormal.h"
using namespace std;
ModelNormal::ModelNormal()
{
this->mType = NORMAL;
this->mBeginTag = "<normals>";
this->mEndTag = "</normals>";
}
void ModelNormal::FormatData()
/**
implemented formating for normals
*/
{
int i = 0;
//convert data to expected format
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); ++it)
{
tNormal NewData = std::make_tuple(i, atof((*it).c_str()), atof((*(it+1)).c_str()), atof((*(it+2)).c_str()) );
this->vNormal.push_back(NewData);
it += 2;
i++;
}
#ifdef DEBUG
//check saved model data
for(auto j : this->vNormal)
{
cout<<"tuple data: "<<std::get<TNORMAL_X>(j)<<", "<<std::get<TNORMAL_Y>(j)<<", "<<std::get<TNORMAL_Z>(j)<<endl;
}
#endif
}
<file_sep>#ifndef DOMMATCHER_H
#define DOMMATCHER_H
#include <tuple>
#define TDOMMATCHER_TYPE 0
#define TDOMMATCHER_STARTTAG 1
#define TDOMMATCHER_ENDTAG 2
using namespace std;
typedef tuple<string,string,string> tDOMMatcher;
#endif
<file_sep>#ifndef MODELABSTRACTION_H
#define MODELABSTRACTION_H
#include <vector>
#include <string>
#include "ModelTransform.h"
#include "ModelPool.h"
using namespace std;
///provides ability to attach entities in a hierarchy and inherits entity transforms from ModelTransform and ability to access other models from ModelPool
class ModelAbstraction : public ModelTransform, public ModelPool
{
private:
vector<ModelAbstraction*> vChild;
ModelAbstraction * Parent;
ModelAbstraction * pCamera; ///root node for rendering using world to eye transform from the camera
ModelAbstraction * pLookatTarget; ///target entity to lookat to
ModelAbstraction * pMoveToTarget;
public:
vector<string> vAction; ///storage for received action
string Name; /// storage for model identifier
ModelAbstraction();
void DrawModel(); ///updates model view transforms and calls implementable draw method
virtual void Draw(); ///implementable draw function
virtual void Action( string input ); ///implementable action function
virtual void FormatAction(){}; ///implementable action formatting
void AddChild( ModelAbstraction * child );
void RemoveChild( ModelAbstraction * child );
void AddParent( ModelAbstraction * parent );
void RemoveParent();
void UpdateParentTransform(); ///gets the parent transform if it exists
void GetWorldToEntityTransform( float out[] );
void UpdateWorldToCameraTransform(); //updates and gets transforms from world (root node) to camera
void DrawCascade(); /// draws this and all children entities in this hierarchy
bool SetLookatTarget( ModelAbstraction * ); ///sets the entity to look at
void LookAtTarget(); ///rotates to face set lookat target
bool GetTargetToCurrentTransform( ModelAbstraction * target, float out[] );
void SetCamera( ModelAbstraction * cam );
void MoveToTarget(); ///moves to target location
void SetMoveToTarget( ModelAbstraction * ); ///sets target to move to
};
#endif
<file_sep>#include "Clock.h"
#include <chrono>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
Clock::Clock()
{
this->Fps = -1;
this->bRunning = false;
this->TimeSinceStart = 0;
this->ClockScale = 1;
}
bool Clock::SetFps(float fps)
{
if(fps <= 0)
return false;
this->Fps = fps;
//milliseconds per frame
this->AutoDuration = (float)1.0/fps*1000;
this->AutoDurationScaled = this->AutoDuration / this->ClockScale;
return true;
}
bool Clock::Tick()
{
if(this->Fps <= 0)
return false;
if(this->bRunning == false)
return false;
//get duration between previous tick and now in milliseconds
this->Time = chrono::high_resolution_clock::now();
auto diff = this->Time - this->TimePrev;
auto duration = chrono::duration<double,milli>(diff).count();
//test if this tick is complete with clock scaling adjustment
if(duration < this->AutoDurationScaled)
return false;
//calculate fps
this->FpsActual = 1.0/(duration/1000)/this->ClockScale;
cout<<"Time Scale: "<<this->ClockScale<< " Time Scaled FPS: "<<this->FpsActual<<endl;
//save runnning time
this->TimeSinceStart += duration*this->ClockScale;
//tick complete
this->TimePrev = this->Time;
//fire message of tick completion
stringstream ss;
ss << this->TimeSinceStart;
this->TickAction(ss.str());
return true;
}
void Clock::Run()
{
this->bRunning = true;
this->TimePrev = chrono::high_resolution_clock::now();
}
void Clock::Pause()
{
this->bRunning = false;
}
float Clock::GetFps()
{
return this->Fps;
}
bool Clock::IsRunning()
{
return this->bRunning;
}
float Clock::GetTime()
{
return this->TimeSinceStart;
}
void Clock::SetClockScale(float val)
{
if(val<= 0)
return;
this->ClockScale = val;
this->AutoDurationScaled = this->AutoDuration / this->ClockScale;
}
<file_sep>#include "Vec.h"
#include <string.h>
#include <math.h>
#include <stdexcept>
Vec::Vec(){
_dim = 3;
_vec = new float [_dim];
memset( _vec, 0, sizeof(float)*_dim );
}
Vec::Vec(int dim){
_dim = dim;
_vec = new float [_dim];
memset( _vec, 0, sizeof(float)*_dim );
}
Vec::Vec(const Vec & v){
_vec = new float[v._dim];
_dim = v._dim;
//copy data
memcpy( _vec, v._vec, sizeof(float)*_dim );
}
Vec & Vec::operator=(const Vec & v)
{
_vec = new float[v._dim];
_dim = v._dim;
//copy data
memcpy( _vec, v._vec, sizeof(float)*_dim );
return *this;
}
Vec::~Vec(){
if( _dim == 1 || _dim == 0 )
delete _vec;
else if( _dim > 1 )
delete [] _vec;
_vec = NULL;
}
void Vec::SetDim(int dim){
if( _dim != dim ){
float * newVec = new float[dim];
memset( newVec, 0, sizeof(float)*dim );
memcpy( newVec, _vec, sizeof(float)*_dim );
//delete old vector
if( _dim == 1 || _dim == 0 )
delete _vec;
else if(_dim > 1)
delete [] _vec;
_vec = newVec;
newVec = NULL;
_dim = dim;
}
}
Vec Vec::operator + (const Vec & v) const{
if( _dim != v._dim )
throw Exception( "Vec::operator+(): dimension not match" );
Vec newVec( _dim );
float * a = _vec;
float * b = v._vec;
float * c = newVec._vec;
for( int i = 0; i < _dim; i++ ){
*c = *a + *b;
a++;
b++;
c++;
}
return newVec;
}
Vec Vec::operator - (const Vec & v) const{
if( _dim != v._dim )
throw Exception( "Vec::operator-(): dimension not match" );
Vec newVec( _dim );
float * a = _vec;
float * b = v._vec;
float * c = newVec._vec;
for( int i = 0; i < _dim; i++ ){
*c = *a - *b;
a++;
b++;
c++;
}
return newVec;
}
float Vec::Dot(const Vec & v) const{
if( _dim != v._dim )
throw Exception( "Vec::Dot(): dimension not match" );
float * a = _vec;
float * b = v._vec;
float out = 0;
for( int i = 0; i < _dim; i++ ){
out += (*a) * (*b);
a++;
b++;
}
return out;
}
Vec Vec::Cross(const Vec & v) const{
if( _dim != v._dim )
throw Exception( "Vec::Cross(): dimension not match" );
if( _dim != 3 )
throw Exception( "Vec::Cross(): dimension should be 3" );
Vec newVec(_dim);
newVec._vec[0] = _vec[1]*v._vec[2] - _vec[2]*v._vec[1];
newVec._vec[1] = -1.0f * (_vec[0]*v._vec[2] - _vec[2]*v._vec[0]);
newVec._vec[2] = _vec[0]*v._vec[1] - _vec[1]*v._vec[0];
return newVec;
}
float Vec::Magnitude() const{
float out = 0;
const float * a = (const float *) _vec;
for( int i = 0; i < _dim; i++ ){
out += (*a)*(*a);
a++;
}
return sqrt(out);
}
void Vec::NormalizeCurrent(){
Vec v = Normalize();
*this = v;
}
Vec Vec::Normalize() const {
Vec v( *this );
float mag = this->Magnitude();
if( mag == 0 ){
throw Exception( "Vec::Normalize(): magnitude is 0" );
return v;
}
float * a = v._vec;
for( int i = 0; i < v._dim; i++ ){
*a = *a/mag;
a++;
}
return v;
}
void Vec::SetFromArray(int dim, float array [] ) {
SetDim( dim );
for( int i = 0; i < dim; i++ ){
_vec[i] = array[i];
}
}
void Vec::GetArray(int & dim, float * & array ) const {
dim = _dim;
array = new float[dim];
for( int i = 0; i < dim; i++ ){
array[i] = _vec[i];
}
}
Vec ScaleVec( float s, const Vec v ){
Vec a;
a = v;
for( int i = 0; i < v._dim; i++ ){
a[i] = s * a[i];
}
return a;
}
Vec ScaleVecAdd( float s, const Vec v1, const Vec v2 ){
Vec a = ScaleVec( s, v1 );
return a + v2;
}
<file_sep>#include "MatrixMath.h"
#include <iostream>
#include <cmath>
using namespace std;
bool MatrixMath::InvertMatrix(const float m[16], float invOut[16])
{
double inv[16], det;
int i;
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
return false;
det = 1.0 / det;
float invOutTemp[16];
//get the row major matrix result
for (i = 0; i < 16; i++)
invOutTemp[i] = inv[i] * det;
MatrixMath::Mat4x4Transpose(invOutTemp, invOut);
return true;
}
void MatrixMath::Mat4x4Mult4x1(float FourByOne[], float FourbyFour[], float out[])
{
// for each column
for(int i = 0; i < 4; i++)
{
float sum = 0;
// for each row
for(int j = 0; j < 4; j++)
{
sum += (FourByOne[j] * FourbyFour[i + j*4]);
}
out[i] = sum;
}
}
void MatrixMath::Mat1x4Mult4x4(float Onebyfour[], float FourbyFour[], float out[])
{
// for each row
for(int i = 0; i < 4; i++)
{
float sum = 0;
// for each column
for(int j = 0; j < 4; j++)
{
sum += (Onebyfour[j] * FourbyFour[i*4 + j]);
}
out[i] = sum;
}
}
void MatrixMath::Mat4x4Mult4x4(float Left[], float Right[], float out[])
{
// for each column in Right
for(int i = 0; i < 4; i++)
{
// for each row in Left
for(int j = 0; j < 4; j++)
{
float sum = 0;
// compute dot product of row and column
for(int k = 0; k < 4; k++)
{
sum += Left[j + k*4] * Right[i*4 + k];
}
out[i + j*4] = sum;
}
}
}
void MatrixMath::Mat4x4Transpose(float in[], float out[])
{
//for each output column
for(int i = 0; i < 4; i++)
{
//for each output row
for(int j = 0; j < 4; j++)
{
out[i*4+j] = in[j*4+i];
}
}
}
void MatrixMath::Mat4x4Normalize(float in[], float out[])
{
float factor = in[15];
for(int i = 0; i < 16; i++)
{
out[i] = in[i]/factor;
}
}
void MatrixMath::Mat4x1Normalize(float in[], float out[])
{
float factor = in[3];
for(int i = 0; i < 4; i++)
{
out[i] = in[i]/factor;
}
}
void MatrixMath::PrintMat4x4(float in[])
{
//for each row
for(int i = 0; i < 4; i++)
{
//for each column
for(int j = 0; j < 4; j++)
{
cout<<in[j + i*4]<<" ";
}
cout<<endl;
}
cout<<endl;
}
void MatrixMath::PrintMat4x1(float in[])
{
//for each row
for(int i = 0; i < 4; i++)
{
cout<<in[i]<<", ";
}
cout<<endl;
}
void MatrixMath::GetMat4x4Identity(float out[])
{
for(int i = 0; i <16; i++)
out[i] = 0;
out[0] = 1;
out[5] = 1;
out[10] = 1;
out[15] = 1;
}
void MatrixMath::GetMat4x4Rotation(float in[], float r[])
{
//normalize scaling
float sx = sqrt(pow(in[0],2) + pow(in[4],2) + pow(in[8],2));
float sy = sqrt(pow(in[1],2) + pow(in[5],2) + pow(in[9],2));
float sz = sqrt(pow(in[2],2) + pow(in[6],2) + pow(in[10],2));
float mat3x3[3][3];
//each row
for(int i = 0; i < 3; i++)
{
//each column
for(int j = 0; j < 3; j++)
{
if(j == 0)
mat3x3[i][j] = in[i+j*4]/sx;
else if(j == 1)
mat3x3[i][j] = in[i+j*4]/sy;
else if(j == 2)
mat3x3[i][j] = in[i+j*4]/sz;
}
}
//rx
r[0] = atan2(mat3x3[3][2], mat3x3[3][3])*180/PI;
//ry
r[1] = atan2(-mat3x3[3][1], sqrt(pow(mat3x3[3][2],2) + pow(mat3x3[3][3],2)))*180/PI;
//rz
r[2] = atan2(mat3x3[2][1], mat3x3[1][1])*180/PI;
}
void MatrixMath::NormalizeScalingMat4x4(float in[], float out[])
{
//normalize scaling
float sx = sqrt(pow(in[0],2) + pow(in[4],2) + pow(in[8],2));
float sy = sqrt(pow(in[1],2) + pow(in[5],2) + pow(in[9],2));
float sz = sqrt(pow(in[2],2) + pow(in[6],2) + pow(in[10],2));
for(int i = 0; i < 16; i++)
out[i] = in[i];
//each row
for(int i = 0; i < 3; i++)
{
//each column
for(int j = 0; j < 3; j++)
{
if(j == 0)
out[i+j*4] = in[i+j*4]/sx;
else if(j == 1)
out[i+j*4] = in[i+j*4]/sy;
else if(j == 2)
out[i+j*4] = in[i+j*4]/sz;
}
}
}
void MatrixMath::InvertTranslateMat4x4(float in[], float out[])
{
for(int i = 0; i < 12; i++)
{
out[i] = in[i];
}
for(int i = 12; i < 15; i++)
{
out[i] = -1*in[i];
}
out[15] = in[15];
}
void MatrixMath::InvertTranslateZMat4x4(float in[], float out[])
{
for(int i = 0; i < 14; i++)
{
out[i] = in[i];
}
out[14] = -1*in[14];
out[15] = in[15];
}
void MatrixMath::InvertRotateMat4x4(float in[], float out[])
{
for(int i = 0; i < 16; i++)
out[i] = in[i];
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
out[j+i*4] = in[i+j*4];
}
}
}
<file_sep>#include <iostream>
#include "DOMNode.h"
#include "AnimationParse.h"
#include "DOMParse.h"
#include <vector>
using namespace std;
int main(int argc, char** argv)
{
if(argc < 2)
{
cout<<"need DOM file"<<endl;
}
AnimationParse parser;
vector<tAnimation> vAnimation = parser.GetAnimations(argv[1]);
cout<<"number of animations: "<<vAnimation.size()<<endl;
for(auto i : vAnimation)
{
cout<<std::get<TANIMATION_NAME>(i)<<", "<<std::get<TANIMATION_TIME>(i)<<", "<<std::get<TANIMATION_ACTION>(i)<<", "<<std::get<TANIMATION_SUBJECT>(i)<<", "<<std::get<TANIMATION_EXTRA>(i)<<endl;
}
return 0;
}
<file_sep>#include "ModelAbstraction.h"
#include "ModelTransform.h"
#include "MatrixMath.h"
#include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <cmath>
#include "MatrixMath.h"
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
using namespace std;
ModelAbstraction::ModelAbstraction()
{
this->pLookatTarget = NULL;
this->pMoveToTarget = NULL;
this->pCamera = NULL;
this->Parent = NULL;
}
void ModelAbstraction::DrawModel()
{
//grabs world to eye transform from camera
float worldtoeye[16];
float worldtoeyeInv[16];
if(this->pCamera != NULL)
{
this->pCamera->GetWorldtoCamTransform(worldtoeye);
//saves world to eye transform
this->SetWorldtoCamTransform(worldtoeye);
}
this->MoveToTarget();
//sets rotation orientation to look at set target
this->LookAtTarget();
//grabs parent transform
this->UpdateParentTransform();
//update model view transformations
this->ApplyTransform();
//draw model
this->Draw();
}
void ModelAbstraction::Draw()
{
}
void ModelAbstraction::Action(string input)
{
// cout<<this->Name<<" received action trigger:"<<input<<endl;
stringstream Ss;
Ss.str(input);
string temp;
//separate items to vector
while (Ss>>temp)
{
this->vAction.push_back(temp);
temp.clear();
}
string actiontype = "";
int count = 0;
int actionsize = this->vAction.size();
for(auto i : this->vAction)
{
if(count == 0)
{
actiontype = i;
break;
}
}
if(actiontype == "draw")
{
this->DrawModel();
}
else if(actiontype == "transform_addchild")
{
//add a child model
if(this->vAction.size() < 2)
{
return;
}
//combine str if spaced name was separated
string combinestr;
for(int i = 1; i < this->vAction.size(); i++)
{
combinestr += this->vAction.at(i);
}
// cout<<"finding model: "<<combinestr<<endl;
ModelAbstraction * model = this->GetModel(combinestr);
if(model != NULL)
{
// cout<<"model found"<<endl;
this->AddChild(model);
}
}
else if(actiontype == "transform_addparent")
{
if(this->vAction.size() < 2)
{
return;
}
//combine str if spaced name was separated
string combinestr;
for(int i = 1; i < this->vAction.size(); i++)
{
combinestr += this->vAction.at(i);
}
// cout<<"finding model: "<<combinestr<<endl;
ModelAbstraction * model = this->GetModel(combinestr);
if(model != NULL)
{
// cout<<"model found"<<endl;
this->AddParent(model);
}
}
else if(actiontype == "transform_removeparent")
{
this->RemoveParent();
}
else if(actiontype == "transform_delta_translate")
{
//translate model
if(this->vAction.size() < 4)
{
return;
}
float nums[4];
for(int i = 1; i < 4; i++)
{
nums[i-1] = atof(this->vAction.at(i).c_str());
}
this->ApplyDeltaTranslate(nums);
}
else if(actiontype == "transform_abs_translate")
{
//translate model
if(this->vAction.size() < 4)
{
return;
}
float nums[4];
for(int i = 1; i < 4; i++)
{
nums[i-1] = atof(this->vAction.at(i).c_str());
}
this->ApplyTranslate(nums);
}
else if(actiontype == "lookat")
{
//lookats to target entity's orientation
if(this->vAction.size() < 2)
{
return;
}
//combine str if spaced name was separated
string combinestr;
for(int i = 1; i < this->vAction.size(); i++)
{
combinestr += this->vAction.at(i);
}
ModelAbstraction * model = this->GetModel(combinestr);
this->SetLookatTarget(model);
}
else if(actiontype == "transform_moveto")
{
//move to target entity
if(this->vAction.size() < 2)
{
return;
}
//combine str if spaced name was separated
string combinestr;
for(int i = 1; i < this->vAction.size(); i++)
{
combinestr += this->vAction.at(i);
}
ModelAbstraction * model = this->GetModel(combinestr);
this->SetMoveToTarget(model);
}
else if(actiontype == "transform_moveto_detach")
{
//stop moving to a target entity
this->SetMoveToTarget(NULL);
}
else
{
//call implementable method in derived class
this->FormatAction();
}
//clear the action
this->vAction.clear();
}
void ModelAbstraction::AddChild(ModelAbstraction* child)
{
if(child == NULL)
return;
//check if it's already a child
for(auto i : this->vChild)
{
if(i == child)
{
return;
}
}
//get world coodinate of the current object
float entitypos[4];
if(this->Parent == NULL)
{
this->GetTranslate(entitypos);
}
else
{
float entitytoworld[16];
this->GetCombinedTransform(entitytoworld);
float origin[4] = {0,0,0,1};
MatrixMath::Mat4x4Mult4x1(origin,entitytoworld,entitypos);
}
//get world coodinate of the target object
float targetpos[4];
if(child->Parent == NULL)
{
child->GetTranslate(targetpos);
}
else
{
float targettoworld[16];
child->GetCombinedTransform(targettoworld);
float origin[4] = {0,0,0,1};
MatrixMath::Mat4x4Mult4x1(origin,targettoworld,targetpos);
}
//save relative position into target child
float offset[4];
for(int i = 0; i < 3; i++)
{
offset[i] = targetpos[i] - entitypos[i];
}
// cout<<"offset"<<endl;
// MatrixMath::PrintMat4x1(offset);
ModelAbstraction * temp = child;
//save absolute offset to child
child->ApplyTranslate(offset);
//add this child
this->vChild.push_back(child);
//remove it from parent
child->RemoveParent();
child->Parent = this;
}
void ModelAbstraction::RemoveChild(ModelAbstraction* child)
{
auto i = this->vChild.begin();
while (i != this->vChild.end())
{
if(*i == child)
{
(*i)->Parent = NULL;
this->vChild.erase(i);
return;
}
}
}
void ModelAbstraction::AddParent(ModelAbstraction* parent)
{
if(parent != NULL)
parent->AddChild(this);
}
void ModelAbstraction::RemoveParent()
{
if(this->Parent != NULL)
{
//get world coodinate of the object and save it
float entitytoworld[16];
this->GetCombinedTransform(entitytoworld);
float origin[4] = {0,0,0,1};
float offset[4];
MatrixMath::Mat4x4Mult4x1(origin,entitytoworld,offset);
this->ApplyTranslate(offset);
// cout<<"offset:"<<endl;
// MatrixMath::PrintMat4x1(offset);
//add this to root world
ModelAbstraction * root = this;
bool foundroot = false;
while(foundroot == false)
{
if(root->Parent == NULL)
foundroot = true;
else
root = root->Parent;
}
if(root == this->Parent)
return;
ModelAbstraction * oldparent = this->Parent;
root->AddChild(this);
oldparent->RemoveChild(this);
this->ApplyTransform();
}
}
void ModelAbstraction::UpdateParentTransform()
{
float ParentTransform[16];
if(this->Parent == NULL)
{
MatrixMath::GetMat4x4Identity(ParentTransform);
this->SetParentTransform(ParentTransform);
}
else
{
this->Parent->GetCombinedTransform(ParentTransform);
this->SetParentTransform(ParentTransform);
}
}
void ModelAbstraction::GetWorldToEntityTransform(float worldtoentity[])
{
//search for root node
bool foundroot = false;
ModelAbstraction * current = this;
vector<ModelAbstraction *> sequence;
sequence.push_back(current);
while(foundroot == false)
{
if(current->Parent == NULL)
{
//found
foundroot = true;
}
else
{
//save current node to list and continue search
current = current->Parent;
sequence.push_back(current);
}
}
current = NULL;
//get transformations from starting node to root node
float temp[16];
float temp2[16];
MatrixMath::GetMat4x4Identity(worldtoentity);
for(int i = 0; i < sequence.size(); i++)
{
// //testing
// sequence[i]->GetLocalTransform(temp);
// float out[16];
// float out2[16];
// MatrixMath::NormalizeScalingMat4x4(temp,out2);
// MatrixMath::InvertRotateMat4x4(out2,out);
// MatrixMath::InvertTranslateMat4x4(out,out2);
// MatrixMath::Mat4x4Mult4x4(worldtoentity,out2,temp2);
// for(int j = 0; j < 16; j++)
// worldtoentity[j] = temp2[j];
sequence[i]->InvertTransform();
sequence[i]->ApplyTransform();
sequence[i]->GetLocalTransform(temp);
//concatenate transforms
MatrixMath::Mat4x4Mult4x4(worldtoentity,temp,temp2);
for(int j = 0; j < 16; j++)
worldtoentity[j] = temp2[j];
//invert back
sequence[i]->InvertTransform();
sequence[i]->ApplyTransform();
}
}
void ModelAbstraction::UpdateWorldToCameraTransform()
{
if(this->pCamera == NULL || this != this->pCamera)
return;
float transform[16];
this->GetCombinedTransform(transform);
float transformtarget[16];
if(this->pLookatTarget != NULL)
this->pLookatTarget->GetCombinedTransform(transformtarget);
else
MatrixMath::GetMat4x4Identity(transformtarget);
float cameratransform[16];
glPushMatrix();
glLoadIdentity();
//set camera transform with glulookat
gluLookAt(transform[12], transform[13], transform[14],
transformtarget[12], transformtarget[13], transformtarget[14],
0, 1, 0);
glGetFloatv(GL_MODELVIEW_MATRIX, cameratransform);
glPopMatrix();
this->pCamera->SetWorldtoCamTransform(cameratransform);
}
void ModelAbstraction::DrawCascade()
{
//update and draw current entity
this->DrawModel();
//do the same for children
for(auto i : this->vChild)
{
if( i != NULL)
{
i->DrawCascade();
}
}
}
bool ModelAbstraction::SetLookatTarget(ModelAbstraction * target)
{
this->pLookatTarget = target;
}
bool ModelAbstraction::GetTargetToCurrentTransform(ModelAbstraction * target, float out[])
{
if(target == NULL)
return false;
float TargetToWorldNormScale[16];
float WorldToCurrentNormScale[16];
float TargetToWorld[16];
target->GetCombinedTransform(TargetToWorld);
//normalize scaling
MatrixMath::NormalizeScalingMat4x4(TargetToWorld, TargetToWorldNormScale);
// if(this == this->pCamera)
// {
// cout<<"targettoworld:"<<endl;
// MatrixMath::PrintMat4x4(TargetToWorldNormScale);
// }
float WorldToCurrent[16];
this->GetWorldToEntityTransform(WorldToCurrent);
//normalize scaling
MatrixMath::NormalizeScalingMat4x4(WorldToCurrent, WorldToCurrentNormScale);
// if(this == this->pCamera)
// {
// cout<<"WorldToCurrent:"<<endl;
// MatrixMath::PrintMat4x4(WorldToCurrentNormScale);
// }
float TargetToCurrent[16];
//concatenate transforms to get target to current entity's transform
MatrixMath::Mat4x4Mult4x4(WorldToCurrentNormScale,TargetToWorldNormScale,TargetToCurrent);
// cout<<"TargetToCurrent_before_normalize:"<<endl;
// MatrixMath::PrintMat4x4(TargetToCurrent);
MatrixMath::Mat4x4Normalize(TargetToCurrent, out);
return true;
}
void ModelAbstraction::SetCamera(ModelAbstraction * cam)
{
this->pCamera = cam;
}
void ModelAbstraction::LookAtTarget()
{
if(this->pLookatTarget!=NULL)
{
float TargetToCurrent[16];
//get relative transform to target
this->GetTargetToCurrentTransform(this->pLookatTarget, TargetToCurrent);
// if(this == this->pCamera)
// {
// cout<<"targettocurrent:"<<endl;
// MatrixMath::PrintMat4x4(TargetToCurrent);
// }
//get offset to target
float targetorigin[4] = {0,0,0,1};
float offset[4];
MatrixMath::Mat1x4Mult4x4(targetorigin, TargetToCurrent, offset);
// if(this == this->pCamera)
// {
// cout<<"offset:"<<endl;
// MatrixMath::PrintMat4x1(offset);
// }
//rotate to face target entity
float rotate[4] = {0,0,0,0};
if(abs(offset[2])>0.01)
{
float ry;
float rx;
ry = -90 + atan2(offset[2],offset[0])*180/PI;
rx = -90 + atan2(offset[2],offset[1])*180/PI;
if(ry > 180)
ry = ry - 360;
else if(ry < -180)
ry = 360 + ry;
if(rx > 180)
rx = rx - 360;
else if(rx < -180)
rx = 360 + rx;
rotate[0] = rx;
rotate[1] = ry;
}
// if(this == this->pCamera)
// {
// cout<<"rotation:"<<endl;
// MatrixMath::PrintMat4x1(rotate);
// }
//reorient entity's rotation
this->SetTransformMode(1);
this->ApplyDeltaRotate(rotate);
this->ApplyTransform();
}
}
void ModelAbstraction::SetMoveToTarget(ModelAbstraction * target)
{
if(target!=NULL)
{
this->RemoveParent();
this->pMoveToTarget = target;
}
else
{
this->pMoveToTarget = NULL;
}
}
void ModelAbstraction::MoveToTarget()
{
if(this->pMoveToTarget == NULL)
return;
float TargetToWorld[16];
this->pMoveToTarget->GetCombinedTransform(TargetToWorld);
//get offset to target
float targetorigin[4] = {0,0,0,1};
float targetpos[4];
MatrixMath::Mat4x4Mult4x1(targetorigin, TargetToWorld, targetpos);
// cout<<"BusShelter world transform"<<endl;
// MatrixMath::PrintMat4x4(TargetToWorld);
float CurrentToWorld[16];
float currentpos[4];
this->GetCombinedTransform(CurrentToWorld);
MatrixMath::Mat4x4Mult4x1(targetorigin, CurrentToWorld, currentpos);
// cout<<"current world transform"<<endl;
// MatrixMath::PrintMat4x4(CurrentToWorld);
float offset[3];
float fraction[3];
for(int i = 0; i < 3; i++)
{
offset[i] = targetpos[i] - currentpos[i];
fraction[i] = offset[i]*1/10;
}
this->ApplyDeltaTranslate(fraction);
// this->ApplyDeltaTranslate(offset);
}
<file_sep>#include <tuple>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include "ModelName.h"
#include "ModelEntity.h"
#include "ModelTexture.h"
#include "ModelVertice.h"
#include "ModelNormal.h"
#include "ModelTriangle.h"
#include "ModelAbstraction.h"
#include "PPM.hpp"
using namespace std;
//comparator functions for item IDs (vertices,normals,texture,etc) in our tuple
bool ModelEntity::fSortTriangleDetailByVec1(const tTriangleDetail& A, const tTriangleDetail& B)
{
return std::get<TTRIANGLEDETAIL_VEC1ID>(A) < std::get<TTRIANGLEDETAIL_VEC1ID>(B);
}
bool ModelEntity::fSortTriangleDetailByVec2(const tTriangleDetail& A, const tTriangleDetail& B)
{
return std::get<TTRIANGLEDETAIL_VEC2ID>(A) < std::get<TTRIANGLEDETAIL_VEC2ID>(B);
}
bool ModelEntity::fSortTriangleDetailByVec3(const tTriangleDetail& A, const tTriangleDetail& B)
{
return std::get<TTRIANGLEDETAIL_VEC3ID>(A) < std::get<TTRIANGLEDETAIL_VEC3ID>(B);
}
bool ModelEntity::fSortTriangleDetailByNorm(const tTriangleDetail& A, const tTriangleDetail& B)
{
return std::get<TTRIANGLEDETAIL_NORMID>(A) < std::get<TTRIANGLEDETAIL_NORMID>(B);
}
bool ModelEntity::fSortTriangleDetailByText(const tTriangleDetail& A, const tTriangleDetail& B)
{
return std::get<TTRIANGLEDETAIL_TEXTID>(A) < std::get<TTRIANGLEDETAIL_TEXTID>(B);
}
void ModelEntity::GetUpdatedVertices(float*& data, int& num)
/**
@param data 1D array of updated vertices for all triangles
@param num array size
*/
{
//number of coordinates from all vertices
num = this->vtTriangleDetail.size()*9;
#ifdef DEBUG
cout<<"vertex coord count: "<<num<<endl;
#endif
//removes old data
if(data != NULL)
{
delete data;
}
//assign processed triangle data to the array
data = new float[num];
for(auto i : this->vtTriangleDetail)
{
*data = std::get<TTRIANGLEDETAIL_VEC1X>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Y>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Z>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2X>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Y>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Z>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3X>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Y>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Z>(i);
data++;
}
data -= num;
}
void ModelEntity::GetUpdatedNormals(float*& data, int& num)
/**
@param data 1D array of updated normals for all triangles
@param num array size
*/
{
//number of coordinates from all vertices
num = this->vtTriangleDetail.size()*3;
#ifdef DEBUG
cout<<"normal coord count: "<<num<<endl;
#endif
//removes old data
if(data != NULL)
{
delete data;
}
//assign processed triangle data to the array
data = new float[num];
for(auto i : this->vtTriangleDetail)
{
*data = std::get<TTRIANGLEDETAIL_NORMX>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(i);
data++;
}
data -= num;
}
void ModelEntity::GetUpdatedTextureCoords(float*& data, int& num)
/**
@param data 1D array of updated texture coordinates for all triangles
@param num array size
*/
{
//number of coordinates from all vertices
num = this->vtTriangleDetail.size()*6;
#ifdef DEBUG
cout<<"texture coord count: "<<num<<endl;
#endif
//removes old data
if(data != NULL)
{
delete data;
}
//assign processed triangle data to the array
data = new float[num];
for(auto i : this->vtTriangleDetail)
{
*data = std::get<TTRIANGLEDETAIL_TEXT1>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT2>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT3>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT4>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT5>(i);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT6>(i);
data++;
}
data -= num;
}
void ModelEntity::UpdateInterleavedArray()
/**
updates interleaved render data buffers according to texture
*/
{
//sort triangle by texture id
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByText);
vector<tTriangleDetail>::iterator itDetail1 = this->vtTriangleDetail.begin();
vector<tTriangleDetail>::iterator itDetail2 = this->vtTriangleDetail.begin();
int bufnum;
//copy data into rendering buffers for each specfic texture
while(itDetail2 != this->vtTriangleDetail.end())
{
//find where texture changes and start copying
if(std::get<TTRIANGLEDETAIL_TEXTID>(*itDetail1) != std::get<TTRIANGLEDETAIL_TEXTID>(*itDetail2))
{
int datanum = (itDetail2 - itDetail1)*24;
float * data = new float[datanum];
//copy data into buffer
while(itDetail1 != itDetail2)
{
*data = std::get<TTRIANGLEDETAIL_VEC1X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT1>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT2>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT3>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT4>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT5>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT6>(*itDetail1);
data++;
itDetail1++;
}
//get texture id of the current data
bufnum = std::get<TTRIANGLEDETAIL_TEXTID>(*(itDetail1-1));
//save number of data
this->pNumRenderData[bufnum] = datanum;
data -= datanum;
//deallocate previous data
if(this->pRenderData[bufnum]!=NULL)
{
delete [] this->pRenderData[bufnum];
}
//save the texture id
this->vTexturePassId.push_back(bufnum);
//save render data
this->pRenderData[bufnum] = data;
data = NULL;
}
else
{
itDetail2++;
}
}
//copy the last portion
int datanum = (this->vtTriangleDetail.end() - itDetail1)*24;
float * data;
if(datanum > 0)
{
data = new float[datanum];
while(itDetail1 != this->vtTriangleDetail.end())
{
*data = std::get<TTRIANGLEDETAIL_VEC1X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC1Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT1>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT2>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC2Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT3>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT4>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3X>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Y>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_VEC3Z>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMX>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMY>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT5>(*itDetail1);
data++;
*data = std::get<TTRIANGLEDETAIL_TEXT6>(*itDetail1);
data++;
itDetail1++;
}
//get texture id of the current data
bufnum = std::get<TTRIANGLEDETAIL_TEXTID>(*(itDetail1-1));
//save number of data
this->pNumRenderData[bufnum] = datanum;
data -= datanum;
//dellocate previous data
if(this->pRenderData[bufnum]!= NULL)
{
delete [] this->pRenderData[bufnum];
}
//save the texture id
this->vTexturePassId.push_back(bufnum);
//save render data
this->pRenderData[bufnum] = data;
data = NULL;
}
}
void ModelEntity::Initialize(ModelName *a, ModelTexture *b, ModelVertice *c, ModelNormal *d, ModelTriangle *e)
{
this->cModelName = a;
this->cModelTexture = b;
this->cModelVertice = c;
this->cModelNormal = d;
this->cModelTriangle = e;
//set ModelAbstraction name
if(this->cModelName->vName.empty() == false)
{
tName tname = this->cModelName->vName.at(0);
this->Name = std::get<1>(tname); // some problem with getting DEFINES in ModelName.h
#ifdef DEBUG
cout<<"model name: "<<this->Name<<endl;
#endif
}
}
void ModelEntity::Update()
/**
Links triangles to vertices, normals, and textures to generate updated triangle data
*/
{
this->vtTriangleDetail.clear();
//copy IDs of basic data and texture coordinates
for(auto i : cModelTriangle->vTriangle)
{
tTriangleDetail detail;
std::get<TTRIANGLEDETAIL_ID>(detail) = std::get<TTRIANGLE_ID>(i);
std::get<TTRIANGLEDETAIL_VEC1ID>(detail) = std::get<TTRIANGLE_VEC1ID>(i);
std::get<TTRIANGLEDETAIL_VEC2ID>(detail) = std::get<TTRIANGLE_VEC2ID>(i);
std::get<TTRIANGLEDETAIL_VEC3ID>(detail) = std::get<TTRIANGLE_VEC3ID>(i);
std::get<TTRIANGLEDETAIL_NORMID>(detail) = std::get<TTRIANGLE_NORMID>(i);
std::get<TTRIANGLEDETAIL_TEXTID>(detail) = std::get<TTRIANGLE_TEXTID>(i);
std::get<TTRIANGLEDETAIL_TEXT1>(detail) = std::get<TTRIANGLE_TEXT1>(i);
std::get<TTRIANGLEDETAIL_TEXT2>(detail) = std::get<TTRIANGLE_TEXT2>(i);
std::get<TTRIANGLEDETAIL_TEXT3>(detail) = std::get<TTRIANGLE_TEXT3>(i);
std::get<TTRIANGLEDETAIL_TEXT4>(detail) = std::get<TTRIANGLE_TEXT4>(i);
std::get<TTRIANGLEDETAIL_TEXT5>(detail) = std::get<TTRIANGLE_TEXT5>(i);
std::get<TTRIANGLEDETAIL_TEXT6>(detail) = std::get<TTRIANGLE_TEXT6>(i);
this->vtTriangleDetail.push_back(detail);
}
//sort triangles by 1st vertex
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByVec1);
//assign values when IDs match
vector<tVertice>::iterator itVertice = this->cModelVertice->vVertice.begin();
vector<tTriangleDetail>::iterator itDetail = this->vtTriangleDetail.begin();
while(itVertice != this->cModelVertice->vVertice.end() && itDetail != this->vtTriangleDetail.end())
{
if(std::get<TVERTICE_ID>(*itVertice) == std::get<TTRIANGLEDETAIL_VEC1ID>(*itDetail))
{
std::get<TTRIANGLEDETAIL_VEC1X>(*itDetail) = std::get<TVERTICE_X>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC1Y>(*itDetail) = std::get<TVERTICE_Y>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC1Z>(*itDetail) = std::get<TVERTICE_Z>(*itVertice);
itDetail++;
}
else
{
itVertice++;
}
}
//sort triangles by 2nd vertex
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByVec2);
//assign values when IDs match
itVertice = this->cModelVertice->vVertice.begin();
itDetail = this->vtTriangleDetail.begin();
while(itVertice != this->cModelVertice->vVertice.end() && itDetail != this->vtTriangleDetail.end())
{
if(std::get<TVERTICE_ID>(*itVertice) == std::get<TTRIANGLEDETAIL_VEC2ID>(*itDetail))
{
std::get<TTRIANGLEDETAIL_VEC2X>(*itDetail) = std::get<TVERTICE_X>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC2Y>(*itDetail) = std::get<TVERTICE_Y>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC2Z>(*itDetail) = std::get<TVERTICE_Z>(*itVertice);
itDetail++;
}
else
{
itVertice++;
}
}
//sort triangles by 3rd vertex
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByVec3);
//assign values when IDs match
itVertice = this->cModelVertice->vVertice.begin();
itDetail = this->vtTriangleDetail.begin();
while(itVertice != this->cModelVertice->vVertice.end() && itDetail != this->vtTriangleDetail.end())
{
if(std::get<TVERTICE_ID>(*itVertice) == std::get<TTRIANGLEDETAIL_VEC3ID>(*itDetail))
{
std::get<TTRIANGLEDETAIL_VEC3X>(*itDetail) = std::get<TVERTICE_X>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC3Y>(*itDetail) = std::get<TVERTICE_Y>(*itVertice);
std::get<TTRIANGLEDETAIL_VEC3Z>(*itDetail) = std::get<TVERTICE_Z>(*itVertice);
itDetail++;
}
else
{
itVertice++;
}
}
//sort triangles by normal
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByNorm);
//assign values when IDs match
vector<tNormal>::iterator itNormal = this->cModelNormal->vNormal.begin();
itDetail = this->vtTriangleDetail.begin();
while(itNormal != this->cModelNormal->vNormal.end() && itDetail != this->vtTriangleDetail.end())
{
if(std::get<TNORMAL_ID>(*itNormal) == std::get<TTRIANGLEDETAIL_NORMID>(*itDetail))
{
std::get<TTRIANGLEDETAIL_NORMX>(*itDetail) = std::get<TNORMAL_X>(*itNormal);
std::get<TTRIANGLEDETAIL_NORMY>(*itDetail) = std::get<TNORMAL_Y>(*itNormal);
std::get<TTRIANGLEDETAIL_NORMZ>(*itDetail) = std::get<TNORMAL_Z>(*itNormal);
itDetail++;
}
else
{
itNormal++;
}
}
//sort triangles by texture
std::sort(this->vtTriangleDetail.begin(), this->vtTriangleDetail.end(), fSortTriangleDetailByText);
//assign values when IDs match
vector<tTexture>::iterator itTexture = this->cModelTexture->vTexture.begin();
itDetail = this->vtTriangleDetail.begin();
while(itTexture != this->cModelTexture->vTexture.end() && itDetail != this->vtTriangleDetail.end())
{
if(std::get<TTEXTURE_ID>(*itTexture) == std::get<TTRIANGLEDETAIL_TEXTID>(*itDetail))
{
std::get<TTRIANGLEDETAIL_TEXTNAME>(*itDetail) = std::get<TTEXTURE_NAME>(*itTexture);
itDetail++;
}
else
{
itTexture++;
}
}
//update rendering buffer
this->UpdateInterleavedArray();
}
void ModelEntity::LoadRenderBuffer()
/**
link updated render data to buffers
*/
{
for(auto i : this->vTexturePassId)
{
glBindBuffer(GL_ARRAY_BUFFER, this->pRbo[i]);
glBufferData(GL_ARRAY_BUFFER, this->pNumRenderData[i]*sizeof(GLfloat), this->pRenderData[i], GL_STATIC_DRAW);
}
}
void ModelEntity::Draw()
/**
Draw what's linked to the VBO, NBO, TBO
*/
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//texture switching
for(auto i : vTexturePassId)
{
glBindTexture(GL_TEXTURE_2D, pTextureID[i]);
glBindBuffer(GL_ARRAY_BUFFER, this->pRbo[i]);
glVertexPointer(3, GL_FLOAT, 8*sizeof(GLfloat), 0);
glNormalPointer(GL_FLOAT, 8*sizeof(GLfloat), (void*)(3*sizeof(GLfloat)));
glTexCoordPointer(2, GL_FLOAT, 8*sizeof(GLfloat), (void*)(6*sizeof(GLfloat)));
glDrawArrays(GL_TRIANGLES, 0, this->pNumRenderData[i]*3);
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
ModelEntity::ModelEntity()
/**
Creates a vertex buffer object. Initializes vertex data pointer
*/
{
this->pRbo = NULL;
this->pTextureID = NULL;
this->pRenderData = NULL;
this->pNumRenderData = NULL;
this->vNumTextureImg = 0;
}
void ModelEntity::CleanUp()
/**
Delete pointer data
*/
{
glDeleteBuffers(this->vNumTextureImg, this->pRbo);
for(int i = 0; i < this->vNumTextureImg; i++)
{
if(this->pRenderData[i] != NULL)
{
delete [] this->pRenderData[i];
this->pRenderData[i] = NULL;
}
}
this->vNumTextureImg = 0;
if(this->pRenderData != NULL)
{
delete [] pRenderData;
pRenderData = NULL;
}
if(this->pTextureID != NULL)
{
glDeleteTextures(this->vNumTextureImg,this->pTextureID);
delete [] this->pTextureID;
this->pTextureID = NULL;
}
if(this->pRbo != NULL)
{
delete [] this->pRbo;
this->pRbo = NULL;
}
if(this->pNumRenderData != NULL)
{
delete [] this->pNumRenderData;
this->pNumRenderData = NULL;
}
this->vTexturePassId.clear();
}
ModelEntity::~ModelEntity()
/**
Deallocates memory
*/
{
this->CleanUp();
}
void ModelEntity::LoadTextureFiles()
/**
Load texture image files and bind to OpenGL
*/
{
//delete previous data
this->CleanUp();
//get number of files to load
this->vNumTextureImg = this->cModelTexture->vTexture.size();
this->pTextureID = new GLuint[this->vNumTextureImg];
//initialize render buffers
this->pRbo = new GLuint[this->vNumTextureImg];
glGenBuffers(this->vNumTextureImg, this->pRbo);
//initilize arrays for rendering interleaved vertices, normals, texture coordinates for specific textures
this->pNumRenderData = new int[this->vNumTextureImg];
this->pRenderData = new float*[this->vNumTextureImg];
for(int i = 0; i < this->vNumTextureImg; i++)
{
this->pRenderData[i] = NULL;
}
//generate texture holders
glGenTextures(this->vNumTextureImg,this->pTextureID);
//texture counter
int j = 0;
//load each texture into opengl
for(auto i : this->cModelTexture->vTexture)
{
//get texture from file
string FileName = this->ModelFilePath + std::get<TTEXTURE_NAME>(i);
int width;
int height;
GLubyte * ImgData = PPM::Read(FileName, width, height);
//bind texture to current texture holder
glBindTexture(GL_TEXTURE_2D, this->pTextureID[j]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//pass texture to openGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, ImgData);
//let opengl automatically build mipmap
glGenerateMipmap(GL_TEXTURE_2D);
//delte image data
delete [] ImgData;
ImgData = NULL;
j++;
}
}
<file_sep>#ifndef RECORDER_H
#define RECORDER_H
#include <string>
#include "ModelAbstraction.h"
using namespace std;
class Recorder : public ModelAbstraction
{
private:
bool IsRecording;
int PosX;
int PosY;
int Width;
int Height;
string OutputPath;
unsigned char * pImage;
int ImageCount;
public:
Recorder();
void SetImageParam(int posx, int posy, int width, int height);
void SetImageParamSize(int w, int h);
void SetImageParamPosition(int x, int y);
void SetOutputPath(string path);
void Start();
void End();
void SaveImage();
void FormatAction(); ///implemented method from ModelAbstraction for recording
};
#endif
<file_sep>#ifndef MODEL_ENTITY_H
#define MODEL_ENTITY_H
#include <vector>
#include <tuple>
#include <string>
#include "ModelName.h"
#include "ModelTexture.h"
#include "ModelVertice.h"
#include "ModelNormal.h"
#include "ModelTriangle.h"
#include "ModelAbstraction.h"
#include "PPM.hpp"
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
///index for accessing triangle data tuple
#define TTRIANGLEDETAIL_ID 0
#define TTRIANGLEDETAIL_VEC1ID 1
#define TTRIANGLEDETAIL_VEC2ID 2
#define TTRIANGLEDETAIL_VEC3ID 3
#define TTRIANGLEDETAIL_NORMID 4
#define TTRIANGLEDETAIL_TEXTID 5
#define TTRIANGLEDETAIL_VEC1X 6
#define TTRIANGLEDETAIL_VEC1Y 7
#define TTRIANGLEDETAIL_VEC1Z 8
#define TTRIANGLEDETAIL_VEC2X 9
#define TTRIANGLEDETAIL_VEC2Y 10
#define TTRIANGLEDETAIL_VEC2Z 11
#define TTRIANGLEDETAIL_VEC3X 12
#define TTRIANGLEDETAIL_VEC3Y 13
#define TTRIANGLEDETAIL_VEC3Z 14
#define TTRIANGLEDETAIL_NORMX 15
#define TTRIANGLEDETAIL_NORMY 16
#define TTRIANGLEDETAIL_NORMZ 17
#define TTRIANGLEDETAIL_TEXTNAME 18
#define TTRIANGLEDETAIL_TEXT1 19
#define TTRIANGLEDETAIL_TEXT2 20
#define TTRIANGLEDETAIL_TEXT3 21
#define TTRIANGLEDETAIL_TEXT4 22
#define TTRIANGLEDETAIL_TEXT5 23
#define TTRIANGLEDETAIL_TEXT6 24
using namespace std;
///definition of data tuple
typedef tuple<int, int,int,int, int, int, float,float,float,float,float,float,float,float,float, float,float,float, string, float,float,float,float,float,float> tTriangleDetail;
///This class is a container of basic model data. It also provides functions to link basic data to generate triangle vertices and draw vertices. It can be used after OpenGL initilization functions are called.
class ModelEntity : public ModelAbstraction{
private:
static bool fSortTriangleDetailByVec1(const tTriangleDetail&, const tTriangleDetail&);
static bool fSortTriangleDetailByVec2(const tTriangleDetail&, const tTriangleDetail&);
static bool fSortTriangleDetailByVec3(const tTriangleDetail&, const tTriangleDetail&);
static bool fSortTriangleDetailByNorm(const tTriangleDetail&, const tTriangleDetail&);
static bool fSortTriangleDetailByText(const tTriangleDetail&, const tTriangleDetail&);
GLuint * pTextureID; ///texture object names
int vNumTextureImg; ///texture file count
GLuint * pRbo; ///render buffer object names
float ** pRenderData; ///render buffers
int * pNumRenderData; ///number of data in specific buffer
vector<int> vTexturePassId; ///holder of texture id, used for opengl texture name and buffer name lookup
public:
ModelEntity();
~ModelEntity();
string ModelFilePath; ///model file path
ModelName * cModelName; ///stored formatted data from parsing
ModelTexture * cModelTexture;
ModelVertice * cModelVertice;
ModelNormal * cModelNormal;
ModelTriangle * cModelTriangle;
vector< tTriangleDetail > vtTriangleDetail; //stores processed triangle data after calling Update()
void GetUpdatedVertices(float*& data, int& num);
void GetUpdatedNormals(float*& data, int& num);
void GetUpdatedTextureCoords(float*& data, int& num);
void UpdateInterleavedArray(); ///helper function to create 1D array of interleaved vertices, normals, texture coordinates
void Initialize(ModelName *, ModelTexture *, ModelVertice *, ModelNormal *, ModelTriangle *);
void Update(); //sortes and matches formatted data to create processed triangles
void Draw(); ///draws model using data linked to VBO
void LoadRenderBuffer(); ///bind render data to buffer objects
void LoadTextureFiles(); ///load texture files
void CleanUp(); ///deallocate pointers
};
#endif
<file_sep>#include <tuple>
#include <cmath>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include "ModelTransform.h"
using namespace std;
ModelTransform::ModelTransform()
{
}
void ModelTransform::ApplyTransform()
{
float data[3];
for(auto i : vTransformQueue)
{
for(int j = 0; j < 3; j++)
data[j] = std::get<TRANSFORMQUEUE_DATA>(i)[j];
//translate absolute
if(std::get<TRANSFORMQUEUE_TYPE>(i) == TRANSFORMTYPE_TRANSLATE_ABS)
{
glPushMatrix();
glLoadIdentity();
glTranslatef(data[0], data[1], data[2]);
glGetFloatv(GL_MODELVIEW_MATRIX,this->vModelTranslation);
glPopMatrix();
}
//rotate absolute
else if(std::get<TRANSFORMQUEUE_TYPE>(i) == TRANSFORMTYPE_ROTATE_ABS)
{
//start of object rotation transform
glPushMatrix();
glLoadIdentity();
if(TransformMode == 0)
{
glRotatef(data[2],0,0,1);
glRotatef(data[1],0,1,0);
glRotatef(data[0],1,0,0);
}
else
{
glRotatef(data[0],1,0,0);
glRotatef(data[1],0,1,0);
glRotatef(data[2],0,0,1);
}
// glRotatef(abs(data[0]),data[0],0,0);
// glRotatef(abs(data[1]),0,data[1],0);
// glRotatef(abs(data[2]),0,0,data[2]);
glGetFloatv(GL_MODELVIEW_MATRIX,this->vModelRotation);
glPopMatrix();
}
//scale absolute
else if(std::get<TRANSFORMQUEUE_TYPE>(i) == TRANSFORMTYPE_SCALE_ABS)
{
float DeltaScale[3];
for(int k = 0; k < 3; k++)
{
DeltaScale[k] = data[k];
DeltaScale[k] = DeltaScale[k]<0? 0: DeltaScale[k];
}
//start of object scaling transform
glPushMatrix();
glLoadIdentity();
//apply scaling
glScalef(DeltaScale[0],DeltaScale[1],DeltaScale[2]);
//lastly, save the new scaling transform
glGetFloatv(GL_MODELVIEW_MATRIX,this->vModelScaling);
glPopMatrix();
}
//clean up data in queue
delete [] std::get<TRANSFORMQUEUE_DATA>(i);
}
this->vTransformQueue.clear();
//combine transformations
glPushMatrix();
glLoadIdentity();
//lastly, apply local transform
glMultMatrixf(this->vModelTranslation);
glMultMatrixf(this->vModelScaling);
glMultMatrixf(this->vModelRotation);
//save local transformation
glGetFloatv(GL_MODELVIEW_MATRIX,this->vModelAllTransform);
glPopMatrix();
glLoadIdentity();
//apply parent transform
glMultMatrixf(vModelParentTransform);
//apply local transform
glMultMatrixf(vModelAllTransform);
//save this combined transform
glGetFloatv(GL_MODELVIEW_MATRIX,this->vModelCombinedTransform);
glLoadIdentity();
//apply world to eye transform
glMultMatrixf(this->vWorldtoCamTransform);
//apply combined world to entity transformation
glMultMatrixf(this->vModelCombinedTransform);
}
void ModelTransform::ApplyDeltaScale(float scale[])
{
for(int i = 0; i < 3; i++)
{
this->ModelScale[i] += scale[i];
if(this->ModelScale[i] < 0)
this->ModelScale[i] = 0;
}
//uses absolute scaling
this->PutInTransformQueue(TRANSFORMTYPE_SCALE_ABS, this->ModelScale);
// this->PutInTransformQueue(TRANSFORMTYPE_SCALE, scale);
}
void ModelTransform::ApplyScale(float scale[])
{
for(int i = 0; i < 3; i++)
{
this->ModelScale[i] = scale[i];
if(this->ModelScale[i] < 0)
this->ModelScale[i] = 0;
}
this->PutInTransformQueue(TRANSFORMTYPE_SCALE_ABS, this->ModelScale);
}
void ModelTransform::ApplyDeltaRotate(float rotate[])
{
for(int i = 0; i < 3; i++)
{
this->ModelRotate[i] += rotate[i];
}
//uses absolute rotate
this->PutInTransformQueue(TRANSFORMTYPE_ROTATE_ABS, this->ModelRotate);
}
void ModelTransform::ApplyRotate(float rotate[])
{
for(int i = 0; i < 3; i++)
{
this->ModelRotate[i] = rotate[i];
}
this->PutInTransformQueue(TRANSFORMTYPE_ROTATE_ABS, this->ModelRotate);
}
void ModelTransform::ApplyDeltaTranslate(float translate[])
{
for(int i = 0; i < 3; i++)
{
this->ModelTranslate[i] += translate[i];
}
//uses absolute translate
this->PutInTransformQueue(TRANSFORMTYPE_TRANSLATE_ABS, this->ModelTranslate);
}
void ModelTransform::ApplyTranslate(float translate[])
{
for(int i = 0; i < 3; i++)
{
this->ModelTranslate[i] = translate[i];
}
this->PutInTransformQueue(TRANSFORMTYPE_TRANSLATE_ABS, this->ModelTranslate);
}
void ModelTransform::PutInTransformQueue(int type, float input [])
{
TransformQueue a;
float * data = new float[3];
std::get<TRANSFORMQUEUE_TYPE>(a) = type;
for(int i = 0; i < 3; i++)
{
data[i] = input[i];
}
std::get<TRANSFORMQUEUE_DATA>(a) = data;
data = NULL;
this->vTransformQueue.push_back(a);
}
void ModelTransform::InitializeOrientation(float scale[], float rotate[], float translate[])
{
for(int i = 0; i < 3; i++)
{
this->ModelRotate[i] = rotate[i];
this->ModelTranslate[i] = translate[i];
this->ModelScale[i] = scale[i];
}
this->ApplyScale(scale);
this->ApplyRotate(rotate);
this->ApplyTranslate(translate);
}
void ModelTransform::SetParentTransform(float matrix[])
{
for(int i = 0; i < 16; i++)
{
this->vModelParentTransform[i] = matrix[i];
}
}
void ModelTransform::GetCombinedTransform(float out[])
{
for(int i = 0; i < 16; i++)
out[i] = this->vModelCombinedTransform[i];
}
void ModelTransform::GetParentTransform(float out[])
{
for(int i = 0; i < 16; i++)
out[i] = this->vModelParentTransform[i];
}
void ModelTransform::GetScale(float out[])
{
for(int i = 0; i < 3; i++)
out[i] = this->ModelScale[i];
}
void ModelTransform::GetTranslate(float out[])
{
for(int i = 0; i < 3; i++)
out[i] = this->ModelTranslate[i];
}
void ModelTransform::GetRotate(float out[])
{
for(int i = 0; i < 3; i++)
out[i] = this->ModelRotate[i];
}
void ModelTransform::SetWorldtoCamTransform(float in[])
{
for(int i = 0; i < 16; i++)
this->vWorldtoCamTransform[i] = in[i];
}
void ModelTransform::GetWorldtoCamTransform(float out[])
{
for(int i = 0; i < 16; i++)
out[i] = this->vWorldtoCamTransform[i];
}
void ModelTransform::GetLocalTransform(float out[])
{
for(int i = 0; i < 16; i++)
out[i] = this->vModelAllTransform[i];
}
void ModelTransform::InvertTransform()
{
for(int i = 0; i < 3; i++)
{
this->ModelTranslate[i] = -1*this->ModelTranslate[i];
this->ModelRotate[i] = -1*this->ModelRotate[i];
}
this->ApplyScale(this->ModelScale);
this->ApplyRotate(this->ModelRotate);
this->ApplyTranslate(this->ModelTranslate);
}
void ModelTransform::SetTransformMode(int val)
{
this->TransformMode = val;
}
void ModelTransform::SetLookatTransform(float in[])
{
for(int i = 0; i < 16; i++)
this->vModelLookat[i] = in[i];
}
<file_sep>///@author <NAME>
///Dual Quaternion port from Java (<NAME>)
#ifndef DUALQUAT_H
#define DUALQUAT_H
#include <stdexcept>
#include "Quat.h"
#include "Vec.h"
#include "DualScalar.h"
class DualQuat{
public:
//store quaternions: A (real = rotation) + eB (dual = translation)
Quat _A;
Quat _B;
DualQuat();
DualQuat(Quat & a, Quat & b);
DualQuat(Vec A, float a, Vec B, float b);
DualQuat(DualQuat & a);
void SetIdentity(); // identity dual quaternion 1 + e0
void SetZero(); // dual quaternion 0 + e0
void SetQuats(Quat & a, Quat & b); // a + eb
void SetQuatsVecs(Vec A, float a, Vec B, float b); //A+a + e(B+b)
void SetArray(float a []);
void GetArray(float a []) const;
DualQuat & operator = ( const DualQuat & q ); //copy
DualQuat operator + ( const DualQuat & q ) const;
DualQuat & operator += ( const DualQuat & q );
DualQuat operator - ( const DualQuat & q ) const;
DualQuat & operator -= ( const DualQuat & q );
DualQuat operator * ( const DualQuat & q ) const; // non-transitive multiplication q1 * q2 = (q1._A*q2._A, q1._A*q2._B + q1._B*q2._A)
DualQuat inline Conjugate() const{ Quat a (_A.Conjugate()); Quat b (_B.Conjugate()); DualQuat q ( a, b); return q; } // calculates q^-1
void inline SetConjugate(){ _A = _A.Conjugate(); _B = _B.Conjugate(); } //sets conjugate for current dual quaternion
Quat GetReal() const;
Quat GetDual() const;
void SetReal( const Quat & q );
void SetDual( const Quat & q );
float GetVal( int index ) const;
DualScalar MagnitudeSquared() const; // ||q||^2 = q * q^-1
DualScalar Magnitude() const; // ||q|| = sqrt(q * q^-1)
DualQuat Normalize() const; // normalize to ||q|| = 1+ e*0
void NormalizeCurrent(); // normalize to ||q|| = 1+ e*0
DualQuat Invert() const; //gets inverse where q^-1 * q = q * q^-1 = 1 + e0
DualQuat PowFloat(double e) const; ///Raises the supplied quaternion to the power e according to euler's formula, this applies to unit quaternions. q = [ cos(theta/2), sin(theta/2)Screwaxis ] + eps [ -alpha/2*sin(theta/2), sin(theta/2)Moment + alpha/2*cos(theta/2)Screwaxis ]
float GetScrewParameters( Vec & screwaxix, Vec & moment, Vec & angles ); // returns norm of _A._quat's x,y,z
void SetScrewParameters( Vec & screwaxis, Vec & moment, float theta, float alpha );
void GetRigidTransform( float a [] ) const; //convert to rigid transform in a column major array representing 4x4 mat
void SetTranslation( const float a [] ); //set translation quaternion by provided array (x,y,z)
void AxisAngleDegree( const float axis[], float angle ); // sets rotation quaternion by provided axis and angle
void AxisAngleDegreeVector( const Vec & v, float angle );
class Exception : public std::runtime_error {
public:
Exception(const std::string &msg): std::runtime_error(msg) { }
};
};
DualQuat ScaleAddDualScalar( const DualScalar & s, const DualQuat & q1, const DualQuat & q2 ); // returns ( s.a*q1.a + q2.a, s.a*q1.b + q2.b + s.b * q1.a )
DualQuat ScaleAddFloat( float s, const DualQuat & q1, const DualQuat & q2 ); // returns s*q1 + q2
DualQuat ScaleDualScalar( const DualScalar & s, const DualQuat & q ); //( s.a*q1.a, s.a*q.b + s.b * q.a )
DualQuat ScaleFloat( float s, const DualQuat & q ); //s*q
DualQuat InterpolateSclerp( const DualQuat & q1, const DualQuat & q2, float t ); ///Screw Linear Interpolate. q = q1*(q1^-1 q2)^t. For the shortest distance, q1 and q2 should have the same orientation.
#endif
<file_sep>#include "Lighting.h"
#include "Interpolate.h"
#include <cstring>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
using namespace std;
int Lighting::TotalNumLight = 0;
Lighting::Lighting()
{
//check if total lights count is exceeded
if(Lighting::TotalNumLight+1 >= GL_MAX_LIGHTS)
{
this->bFunctional = false;
}
else
{
//increment total count of lights
this->NumLight = Lighting::TotalNumLight + 1;
Lighting::TotalNumLight++;
this->bFunctional = true;
}
}
void Lighting::TurnOn()
{
if(this->bFunctional == false)
return;
glEnable(GL_LIGHT0 + this->NumLight);
}
void Lighting::TurnOff()
{
if(this->bFunctional == false)
return;
glDisable(GL_LIGHT0 + this->NumLight);
}
void Lighting::SetLightParam(float amb[], float spec[], float dif[], float pos[])
{
for(int i = 0; i < 4; i++)
{
this->LightAmbiance[i] = amb[i];
this->LightSpecular[i] = spec[i];
this->LightDiffuse[i] = dif[i];
this->LightPosition[i] = pos[i];
}
}
void Lighting::SetLightParamSpot(float dir[], float exponent, float cutoff)
{
for(int i = 0; i < 4; i++)
{
this->LightDirection[i] = dir[i];
}
this->LightExponent = exponent;
this->LightCutoff = cutoff;
}
void Lighting::SetLightAttenuation(string type, float att)
{
if(strcmp(type.c_str(),"CONSTANT") == 0)
{
this->LightAttenConst = att;
}
else if(strcmp(type.c_str(),"LINEAR") == 0)
{
this->LightAttenLinear = att;
}
else if(strcmp(type.c_str(),"QUADRATIC") == 0)
{
this->LightAttenQuadratic = att;
}
}
void Lighting::SetType(string type)
{
this->LightType = type;
}
string Lighting::GetType()
{
return this->LightType;
}
void Lighting::Draw()
{
float LightAmbianceInterpolate[4];
float LightSpecularInterpolate[4];
float LightDiffuseInterpolate[4];
for(int i = 0; i < 4; i++)
{
LightAmbianceInterpolate[i] = this->LightAmbiance[i];
LightSpecularInterpolate[i] = this->LightSpecular[i];
LightDiffuseInterpolate[i] = this->LightDiffuse[i];
}
//get interpolated values if set
if(Interpolate::GetActivated() == true)
{
//increment interpolation
if(this->GetKeepIncrementing() == true)
{
this->Increment();
float pos[3];
this->GetPosition(pos);
// calculate intensities based on interpolated values
for(int i = 0; i < 3; i++)
{
LightAmbianceInterpolate[i] = pos[0] * LightAmbianceInterpolate[i];
LightSpecularInterpolate[i] = pos[1] * LightSpecularInterpolate[i];
LightDiffuseInterpolate[i] = pos[2] * LightDiffuseInterpolate[i];
}
}
}
glLightfv(GL_LIGHT0 + this->NumLight, GL_SPOT_DIRECTION, this->LightDirection);
glLightfv(GL_LIGHT0 + this->NumLight, GL_SPOT_EXPONENT, &this->LightExponent);
glLightfv(GL_LIGHT0 + this->NumLight, GL_SPOT_CUTOFF, &this->LightCutoff);
glLightfv(GL_LIGHT0 + this->NumLight, GL_CONSTANT_ATTENUATION, &this->LightAttenConst);
glLightfv(GL_LIGHT0 + this->NumLight, GL_LINEAR_ATTENUATION, &this->LightAttenLinear);
glLightfv(GL_LIGHT0 + this->NumLight, GL_QUADRATIC_ATTENUATION, &this->LightAttenQuadratic);
glLightfv(GL_LIGHT0 + this->NumLight, GL_AMBIENT, LightAmbianceInterpolate);
glLightfv(GL_LIGHT0 + this->NumLight, GL_SPECULAR, LightSpecularInterpolate);
glLightfv(GL_LIGHT0 + this->NumLight, GL_DIFFUSE, LightDiffuseInterpolate);
glLightfv(GL_LIGHT0 + this->NumLight, GL_POSITION, this->LightPosition);
}
void Lighting::FormatAction()
{
int count = 0;
int size = vAction.size();
if(size < 1)
return;
float* data = new float[size];
string action = vAction[0];
#ifdef DEBUG
cout<<action<<endl;
cout<<"actionsize: "<<size<<endl;
#endif
for(int i = 0; i < size-1; i++)
{
data[i] = atof(vAction[i+1].c_str());
}
if(action == "light_ambient")
{
this->SetLightAmbient(data);
}
else if(action == "light_specular")
{
this->SetLightSpecular(data);
}
else if(action == "light_diffuse")
{
this->SetLightDiffuse(data);
}
else if(action == "light_position")
{
this->SetLightPosition(data);
}
else if(action == "light_direction")
{
this->SetLightDirection(data);
}
else if(action == "light_exponent")
{
this->SetLightExponent(data);
}
else if(action == "light_cutoff")
{
this->SetLightCutoff(data);
}
else if(action == "light_atten_linear")
{
this->SetLightAttenuation("LINEAR", data[0]);
}
else if(action == "light_atten_quadratic")
{
this->SetLightAttenuation("QUADRATIC", data[0]);
}
else if(action == "light_atten_constant")
{
this->SetLightAttenuation("CONSTANT", data[0]);
}
else if(action == "light_turnon")
{
this->TurnOn();
}
else if(action == "light_turnoff")
{
this->TurnOff();
}
else if(action == "light_interpolate")
{
if(size-1 == 0 || (size-1)%13 != 0)
return;
int div = size/13;
for(int j = 0; j < div; j++)
{
float steps = data[j*13];
float ctrlpoint1[3];
float ctrlpoint2[3];
float ctrlpoint3[3];
float ctrlpoint4[3];
for(int i = 0; i < 3; i++)
{
ctrlpoint1[i] = data[j*13 + 1+i];
ctrlpoint2[i] = data[j*13 + 4+i];
ctrlpoint3[i] = data[j*13 + 7+i];
ctrlpoint4[i] = data[j*13 + 10+i];
}
Interpolate::AddCurve(steps, ctrlpoint1, ctrlpoint2, ctrlpoint3, ctrlpoint4);
}
Interpolate::SetActivated(true);
Interpolate::SetKeepIncrementing(true);
}
delete [] data;
}
void Lighting::SetLightAmbient(float in[])
{
for(int i = 0; i < 4; i++)
{
this->LightAmbiance[i] = in[i];
}
}
void Lighting::SetLightSpecular(float in[])
{
for(int i = 0; i < 4; i++)
{
this->LightSpecular[i] = in[i];
}
}
void Lighting::SetLightDiffuse(float in[])
{
for(int i = 0; i < 4; i++)
{
this->LightDiffuse[i] = in[i];
}
}
void Lighting::SetLightPosition(float in[])
{
for(int i = 0; i < 4; i++)
{
this->LightPosition[i] = in[i];
}
}
void Lighting::SetLightDirection(float in[])
{
for(int i = 0; i < 4; i++)
{
this->LightDirection[i] = in[i];
}
}
void Lighting::SetLightExponent(float in[])
{
this->LightExponent = in[0];
}
void Lighting::SetLightCutoff(float in[])
{
this->LightCutoff = in[0];
}
void Lighting::AddCurve(int steps, float ctrlpoint1[], float ctrlpoint2[], float ctrlpoint3[], float ctrlpoint4[])
{
Interpolate::AddCurve(steps, ctrlpoint1, ctrlpoint2, ctrlpoint3, ctrlpoint4);
}
<file_sep>#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include "CityParse.h"
#include "ModelParse.h"
#include "ModelEntity.h"
#include "ModelAbstraction.h"
CityParse::CityParse()
{
}
vector<ModelAbstraction*> CityParse::ParseCity(string path)
{
vector<ModelAbstraction*> vpEntity;
ifstream ifs;
stringstream Ss;
///open model file
ifs.open(path.c_str(), ifstream::in);
if(!ifs.is_open())
{
cout<<"error opening file: "<<path<<endl;
return vpEntity;
}
string line;
int LineNum = 0;
///remove #comments
while (getline(ifs, line))
{
size_t found = line.find("#");
if(found != std::string::npos){
continue;
}
///skip empty line
if(line.size()==0){
continue;
}
///record line
Ss<<line<<" "; // save remaining lines to a single lined buffer and add space to ensure data separation
string entitypath;
float scale[3];
float rotate[3];
float translate[3];
Ss>>entitypath;
for(int i = 0; i < 3; i++)
{
Ss>>scale[i];
}
for(int i = 0; i < 3; i++)
{
Ss>>rotate[i];
}
for(int i = 0; i < 3; i++)
{
Ss>>translate[i];
}
//extract path to the top level city folder and add it to each building model path
string folder = "/";
unsigned foundfolder = path.rfind(folder);
if(foundfolder!=std::string::npos)
{
entitypath = path.substr(0,foundfolder+1) + entitypath;
}
#ifdef DEBUG
cout<<"model path: "<<entitypath<<endl;
cout<<"scale: "<<scale[0]<<","<<scale[1]<<","<<scale[2]<<endl;
cout<<"rotate: "<<rotate[0]<<","<<rotate[1]<<","<<rotate[2]<<endl;
cout<<"translate: "<<translate[0]<<","<<translate[1]<<","<<translate[2]<<endl;
#endif
//generate new entity
ModelEntity * newentity;
newentity = cModelParse.GetEntity(entitypath);
newentity->InitializeOrientation(scale,rotate,translate);
//load model information and textures and do initial update
newentity->LoadTextureFiles();
//do an initial update of triangle data
newentity->Update();
//update data in buffers to be rendered
newentity->LoadRenderBuffer();
vpEntity.push_back(newentity);
newentity = NULL;
}
return vpEntity;
}
<file_sep>#include "LightingParse.h"
#include "Lighting.h"
#include "ModelData.h"
#include <vector>
#include <iostream>
LightingParse::LightingParse()
{
}
LightingParse::~LightingParse()
{
}
vector<Lighting *> LightingParse::GetLightings(string path)
/**
Parses and returns a camera path
*/
{
//output vector of curves
vector<Lighting *> vpLighting;
//DOM parse
DOMNode * pDOM = this->GetDOM(path);
if(pDOM == NULL)
{
cout<<"DOM not parsed"<<endl;
return vpLighting;
}
//stores found curves
vector<DOMNode *> * pvpDOM = new vector<DOMNode *>();
//find nodes having a curve
this->FindLighting(pvpDOM, pDOM);
for(auto i : *pvpDOM)
{
Lighting * NewLighting = new Lighting;
string actiondata;
for(auto j : i->Children)
{
if(j->Type == "name")
{
NewLighting->Name = j->Data;
}
else
{
//set other lighting properties using Lighting's action parsing
actiondata = j->Type + " " + j->Data;
NewLighting->Action(actiondata);
}
}
vpLighting.push_back(NewLighting);
NewLighting = NULL;
}
return vpLighting;
}
void LightingParse::FindLighting(vector<DOMNode *> * pvpDOM, DOMNode * node)
{
if(node->Type == "lighting")
{
pvpDOM->push_back(node);
}
for(auto i : node->Children)
{
this->FindLighting(pvpDOM, i);
}
}
<file_sep>///OpenGL needs to be initialized before using this class
#ifndef CITYPARSE_H
#define CITYPARSE_H
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include "ModelParse.h"
#include "ModelAbstraction.h"
class CityParse
{
private:
ModelParse cModelParse; ///factory to generate model
vector<ModelAbstraction*> vEntity;///temporary storage for produced models
public:
CityParse();
vector<ModelAbstraction*> ParseCity(string path); /// parses city file and returns a vector of entities
};
#endif
<file_sep>3dviewer
========
Project for the 3D computer graphics course, implemented with OpenGL glut library. Expected product is creation of a building model from Vancouver region and creative rendering of building, environment with camera movement.
## Progress ##
part 1: Model entity class for storing model data and transformation hierarchy
part 2: converter utility from .obj file from modelling software to custom format for the course
part 3: Implemented lighting, parametric curve, animation manager, clock, model pool, xml parser, scene graph rendering
Implement extra rendering effects (shadow, animation) in near future
## Production ##
A created model screenshots: https://www.behance.net/gallery/20140226-Sea-Island-Station/14890125
A sample video of animation scene created with this engine: http://youtu.be/KPcf5DIqKU0
## Documentation ##
run doxygen doxyconfig
## Running ##
Animation Scene:
Required files: city file, animation file, motionpath file, lighting file, model files
1. extract model files from testcase/models/ to testcase/city1/ folder
2. create an outputimage/ folder to store captured images
3. make recordertest
4. run using: build/RecorderTest testcase/motionpaths/curvetest1.xml testcase/animation/animationparse.xml testcase/city1/funland.city testcase/lighting/lighting.xml norecord outputimage/
Model Converter:
1. make obj2custom
2. run using build/obj2custom inputObjPath outputFilePath outputObjectName
<file_sep>#ifndef MODELPARSE_H
#define MODELPARSE_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
#include "ModelData.h"
#include "ModelName.h"
#include "ModelTexture.h"
#include "ModelVertice.h"
#include "ModelNormal.h"
#include "ModelTriangle.h"
#include "ModelEntity.h"
using namespace std;
///parses model input file and returns a model entity
class ModelParse
{
private:
bool bEmpty;
///container to hold parsed data types such as vertices, textures, triangles, normals, and model name
vector< ModelData * > vModelData;
public:
ModelParse();
~ModelParse();
ModelEntity * GetEntity(string path); ///factory function to generate model entity from input model file
};
#endif
<file_sep>#include <string>
#include <tuple>
#include <iostream>
#include <vector>
#include "ModelTexture.h"
using namespace std;
ModelTexture::ModelTexture()
{
this->mType = TEXTURE;
this->mBeginTag = "<textures>";
this->mEndTag = "</textures>";
}
void ModelTexture::FormatData()
/**
implemented formating for texture
*/
{
int i = 0;
//convert data to expected format
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); ++it)
{
tTexture NewData = std::make_tuple(i, (string)*it);
this->vTexture.push_back(NewData);
i++;
}
#ifdef DEBUG
//check saved model data
for(auto j : this->vTexture)
{
cout<<"tuple data: "<<std::get<TTEXTURE_NAME>(j)<<endl;
}
#endif
}
<file_sep>#ifndef LIGHTINGPARSE_H
#define LIGHTINGPARSE_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include "DOMParse.h"
#include "DOMNode.h"
#include "ModelData.h"
using namespace std;
class Lighting;
///parses Lighting input file and returns lighting entities
class LightingParse : public DOMParse
{
private:
vector<ModelData*> vModelData; ///container to hold parsed data types
void FindLighting(vector<DOMNode *> * pvpDOM, DOMNode * node); ///helper function to find all lightings in DOM
public:
LightingParse();
~LightingParse();
vector<Lighting*> GetLightings(string path); ///factory function to generate lighting entities from input lighting file
};
#endif
<file_sep>#include "TrajectoryParse.h"
#include "CurveData.h"
#include "ModelData.h"
#include <vector>
#include <iostream>
TrajectoryParse::TrajectoryParse()
{
}
TrajectoryParse::~TrajectoryParse()
{
}
vector<CurvePath *> TrajectoryParse::GetTrajectories(string path)
/**
Parses and returns a camera path
*/
{
//output vector of curves
vector<CurvePath *> vpCurvePath;
//DOM parse
DOMNode * pDOM = this->GetDOM(path);
if(pDOM == NULL)
{
cout<<"DOM not parsed"<<endl;
return vpCurvePath;
}
//stores found curves
vector<DOMNode *> * pvpDOM = new vector<DOMNode *>();
//find nodes having a curve
this->FindCurve(pvpDOM, pDOM);
for(auto i : *pvpDOM)
{
CurvePath * NewCurvePath = new CurvePath;
for(auto j : i->Children)
{
if(j->Type == "name")
{
NewCurvePath->Name = j->Data;
}
else if(j->Type == "controlpoint")
{
string curvecontrol = j->Data;
//creates a container for bezier curve data
CurveData * pCurveData = new CurveData();
// call derived ModelData classes to format and save data
pCurveData->SetData(curvecontrol);
//creates a curve path with given control points
this->InitializeCurve(NewCurvePath, pCurveData);
vpCurvePath.push_back(NewCurvePath);
delete pCurveData;
pCurveData = NULL;
NewCurvePath = NULL;
}
}
}
return vpCurvePath;
}
void TrajectoryParse::InitializeCurve(CurvePath * pCurve, CurveData * pCurveData)
{
for(auto i : pCurveData->vCurveControl)
{
int steps = std::get<TCURVECONTROL_STEP>(i);
float ctrlpoint1[3];
float ctrlpoint2[3];
float ctrlpoint3[3];
float ctrlpoint4[3];
ctrlpoint1[0] = std::get<TCURVECONTROL_PT1_X>(i);
ctrlpoint1[1] = std::get<TCURVECONTROL_PT1_Y>(i);
ctrlpoint1[2] = std::get<TCURVECONTROL_PT1_Z>(i);
ctrlpoint2[0] = std::get<TCURVECONTROL_PT2_X>(i);
ctrlpoint2[1] = std::get<TCURVECONTROL_PT2_Y>(i);
ctrlpoint2[2] = std::get<TCURVECONTROL_PT2_Z>(i);
ctrlpoint3[0] = std::get<TCURVECONTROL_PT3_X>(i);
ctrlpoint3[1] = std::get<TCURVECONTROL_PT3_Y>(i);
ctrlpoint3[2] = std::get<TCURVECONTROL_PT3_Z>(i);
ctrlpoint4[0] = std::get<TCURVECONTROL_PT4_X>(i);
ctrlpoint4[1] = std::get<TCURVECONTROL_PT4_Y>(i);
ctrlpoint4[2] = std::get<TCURVECONTROL_PT4_Z>(i);
pCurve->AddCurve(steps, ctrlpoint1, ctrlpoint2, ctrlpoint3, ctrlpoint4);
}
}
void TrajectoryParse::FindCurve(vector<DOMNode *> * pvpDOM, DOMNode * node)
{
if(node->Type == "curve")
{
pvpDOM->push_back(node);
}
for(auto i : node->Children)
{
this->FindCurve(pvpDOM, i);
}
}
<file_sep>#ifndef DOMPARSE_H
#define DOMPARSE_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
#include <string>
#include "DOMMatcher.h"
#include "DOMNode.h"
using namespace std;
///parses Trajectory input file and returns CurvePath entities
class DOMParse
{
private:
vector<tDOMMatcher> vDOMMatcher; ///DOM types to register a match
void NestedDOM(DOMNode * node, string input); ///helper function to get nested data
public:
DOMParse();
DOMNode * GetDOM(string path); ///factory function to generate DOM tree
};
#endif
<file_sep>#ifndef DOMNODE_H
#define DOMNODE_H
#include <string>
#include <vector>
using namespace std;
class DOMNode
{
public:
DOMNode();
~DOMNode();
string Type;
DOMNode * Parent;
vector<DOMNode *> Children;
string Data; ///parsed data
void AddChild(DOMNode * node);
void Print();
void PrintBreadth();
};
#endif
<file_sep>#ifndef MODELNAME_H
#define MODELNAME_H
#include "ModelData.h"
#include <vector>
#include <sstream>
#include <tuple>
#include <string>
///access index of tuple
#define TNAME_ID 0;
#define TNAME_NAME 1;
using namespace std;
///tuple definition
typedef tuple<int,string> tName;
///container for model name
class ModelName: ModelData
{
public:
ModelName();
vector<tName> vName; ///formatted data
void FormatData(); ///saves parsed data to tuple
};
#endif
<file_sep>#ifndef MODELTRIANGLE_H
#define MODELTRIANGLE_H
#include "ModelData.h"
#include <vector>
#include <sstream>
#include <tuple>
///access index of data
#define TTRIANGLE_ID 0
#define TTRIANGLE_VEC1ID 1
#define TTRIANGLE_VEC2ID 2
#define TTRIANGLE_VEC3ID 3
#define TTRIANGLE_NORMID 4
#define TTRIANGLE_TEXTID 5
#define TTRIANGLE_TEXT1 6
#define TTRIANGLE_TEXT2 7
#define TTRIANGLE_TEXT3 8
#define TTRIANGLE_TEXT4 9
#define TTRIANGLE_TEXT5 10
#define TTRIANGLE_TEXT6 11
using namespace std;
///tuple data definition
typedef tuple<int, int,int,int, int, int, float,float,float,float,float,float> tTriangle;
///container for triangle data
class ModelTriangle: ModelData
{
public:
ModelTriangle();
vector< tTriangle > vTriangle; ///container for formatted triangle data
void FormatData(); ///formats triangle data
};
#endif
<file_sep>#ifndef MODELTEXTURE_H
#define MODELTEXTURE_H
#include "ModelData.h"
#include <vector>
#include <sstream>
#include <tuple>
///access index of data
#define TTEXTURE_ID 0
#define TTEXTURE_NAME 1
using namespace std;
///tuple definition
typedef tuple<int, string> tTexture;
///container for model texture
class ModelTexture: ModelData
{
public:
ModelTexture();
vector< tTexture > vTexture; ///container for model texture
void FormatData(); ///formats texture names
};
#endif
<file_sep>#ifndef MODELORIENTATION_H
#define MODELORIENTATION_H
#include <vector>
#include <tuple>
using namespace std;
///stores transforms to be applied
typedef tuple<int,float*> TransformQueue;
#define TRANSFORMQUEUE_TYPE 0
#define TRANSFORMQUEUE_DATA 1
#define TRANSFORMTYPE_TRANSLATE 0
#define TRANSFORMTYPE_ROTATE 1
#define TRANSFORMTYPE_SCALE 2
#define TRANSFORMTYPE_TRANSLATE_ABS 3
#define TRANSFORMTYPE_ROTATE_ABS 4
#define TRANSFORMTYPE_SCALE_ABS 5
///provides transformation abilities and cascades transform from parent hierarchy
class ModelTransform
{
private:
float ModelScale[3] = {1,1,1};
float ModelTranslate[3] = {0,0,0};
float ModelRotate[3] = {0,0,0};
float vModelTranslation[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; ///local transform matrices
float vModelScaling[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelRotation[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelAllTransform[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelLookat[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float vModelParentTransform[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; ///parent transform matrix
float vModelCombinedTransform[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
vector<TransformQueue> vTransformQueue;
void PutInTransformQueue(int, float[]);
float vWorldtoCamTransform[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1}; ///stores world to camera transformation
int TransformMode = 0;
public:
ModelTransform();
void ApplyScale(float scale[]);
void ApplyRotate(float rotate[]);
void ApplyTranslate(float translate[]);
void ApplyDeltaScale(float scale[]);
void ApplyDeltaRotate(float rotate[]);
void ApplyDeltaTranslate(float translate[]);
void ApplyTransform(); ///applies transformations in queue
void InitializeOrientation(float scale[], float rotate[], float translate[]);
void SetParentTransform(float matrix[]);
void GetCombinedTransform(float out[]); ///returns combined transform of current entity
void GetParentTransform(float out[]);
void GetScale(float out[]);
void GetTranslate(float out[]);
void GetRotate(float out[]);
void SetWorldtoCamTransform(float[]); ///sets the world to eye transform
void GetWorldtoCamTransform(float[]); ///gets the world to eye transform
void GetLocalTransform(float out[]);
void InvertTransform();
void SetTransformMode(int);
void SetLookatTransform(float in[]);
};
#endif
<file_sep>#ifndef TRAJECTORYPARSE_H
#define TRAJECTORYPARSE_H
#include <string>
#include <fstream>
#include <vector>
#include <iostream>
#include "CurvePath.h"
#include "CurveData.h"
#include "ModelData.h"
#include "DOMParse.h"
#include "DOMNode.h"
using namespace std;
///parses Trajectory input file and returns CurvePath entities
class TrajectoryParse : public DOMParse
{
private:
bool bEmpty;
vector< ModelData * > vModelData; ///container to hold parsed data types
void FindCurve( vector< DOMNode * > * pvpDOM, DOMNode * node ); ///helper function to find all curves in DOM
void InitializeCurve(CurvePath * pCurve, CurveData * pCurveData); ///helper function to intialize curves to control points
public:
TrajectoryParse();
~TrajectoryParse();
vector<CurvePath *> GetTrajectories(string path); ///factory function to generate CurvePath entities from input Trajectory file
};
#endif
<file_sep>#include "Recorder.h"
#include "ModelAbstraction.h"
#include "PPM.hpp"
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;
Recorder::Recorder()
{
this->ImageCount = 0;
this->IsRecording = false;
this->PosX = 0;
this->PosY = 0;
this->Width = 1280;
this->Height = 720;
this->pImage = new unsigned char[this->Width*this->Height*3];
}
void Recorder::SetOutputPath(string path)
{
this->OutputPath = path;
}
void Recorder::Start()
{
if(this->IsRecording == false)
{
this->IsRecording = true;
}
cout<<"start recording.."<<endl;
}
void Recorder::End()
{
this->IsRecording = false;
cout<<"end recording.."<<endl;
}
void Recorder::SetImageParam(int posx, int posy, int width, int height)
{
this->Width = width;
this->Height = height;
this->PosX = posx;
this->PosY = posy;
this->pImage = new unsigned char[width*height*3];
}
void Recorder::SetImageParamSize(int width, int height)
{
this->Width = width;
this->Height = height;
this->pImage = new unsigned char[width*height*3];
}
void Recorder::SetImageParamPosition(int posx, int posy)
{
this->PosX = posx;
this->PosY = posy;
}
void Recorder::SaveImage()
{
if(this->IsRecording == false)
return;
glReadPixels(this->PosX, this->PosY, this->Width, this->Height, GL_RGB, GL_UNSIGNED_BYTE, pImage);
//flip image vertically
unsigned char * forward = pImage;
unsigned char * reverse = pImage + (this->Width * this->Height -1 )*3;
//storage for swapping pixels
unsigned char temp[3];
for(int i = 0; i < this->Height/2* this->Width; i++)
{
for(int j = 0; j < 3; j++)
{
temp[j] = *(reverse + j);
*(reverse + j) = *(forward + j);
*(forward + j) = temp[j];
}
forward += 3;
reverse -= 3;
}
//write to file
char imagename[16];
char* pimagename = imagename;
sprintf(pimagename,"%016d",this->ImageCount);
string imagestr(pimagename);
string filepath = this->OutputPath + imagestr+".ppm";
cout<<"image file path: "<<filepath<<endl;
PPM::Write(filepath, this->pImage, this->Width, this->Height);
this->ImageCount++;
}
void Recorder::FormatAction()
{
int count = 0;
if(this->vAction.empty())
return;
//get action type
string actiontype = this->vAction[0];
if(actiontype == "recorder_start")
{
this->Start();
}
else if(actiontype == "recorder_end")
{
this->End();
}
else if(actiontype == "recorder_imagesize")
{
if(this->vAction.size() < 3)
return;
int w = atof(this->vAction[1].c_str());
int h = atof(this->vAction[2].c_str());
if(w == 0.0 || h == 0.0)
return;
//resize output image
this->SetImageParamSize(w, h);
}
else if(actiontype == "recorder_imageposition")
{
if(this->vAction.size() < 3)
return;
int x = atof(this->vAction[1].c_str());
int y = atof(this->vAction[2].c_str());
if(x == 0.0 || y == 0.0)
return;
//reposition output image
this->SetImageParamPosition(x, y);
}
}
<file_sep>#include "AnimationManager.h"
#include "ModelPool.h"
#include <vector>
#include <string>
#include <stdlib.h>
using namespace std;
AnimationManager::AnimationManager()
{
}
AnimationManager::~AnimationManager()
{
}
void AnimationManager::AddAnimation(tAnimation animation)
{
this->vAnimation.push_back(animation);
}
bool AnimationManager::RemoveAnimation(tAnimation animation)
{
string name = std::get<TANIMATION_NAME>(animation);
auto it = this->vAnimation.begin();
bool removed = false;
while(it != this->vAnimation.end())
{
if(std::get<TANIMATION_NAME>(*it) == name)
{
this->vAnimation.erase(it);
removed = true;
}
else
{
it++;
}
}
return removed;
}
tAnimation AnimationManager::GetAnimation(string name)
{
tAnimation output;
for(auto i : this->vAnimation)
{
if(std::get<TANIMATION_NAME>(i) == name)
{
output = i;
break;
}
}
return output;
}
void AnimationManager::TickAction(string a)
{
// add stuff here to update models based on clock update
// can call ModelAbstraction->Action method to update model
string actiondata = "";
vector<tAnimation>::iterator it = this->vAnimation.begin();
while(it != this->vAnimation.end())
{
//compare time
if(std::get<TANIMATION_TIME>(*it) <= this->GetTime()/1000)
{
if(std::get<TANIMATION_SUBJECT>(*it) == "clock")
{
//set clock parameters
if(std::get<TANIMATION_ACTION>(*it) == "clock_setfps")
{
this->SetFps(atof(std::get<TANIMATION_EXTRA>(*it).c_str()));
}
else if(std::get<TANIMATION_ACTION>(*it) == "clock_setscale")
{
this->SetClockScale(atof(std::get<TANIMATION_EXTRA>(*it).c_str()));
}
this->vAnimation.erase(it);
}
else
{
//get the right model
ModelAbstraction * match = this->GetModel(std::get<TANIMATION_SUBJECT>(*it));
if(match != NULL)
{
actiondata = std::get<TANIMATION_ACTION>(*it) + " " + std::get<TANIMATION_EXTRA>(*it);
//send data to model
match->Action(actiondata);
}
this->vAnimation.erase(it);
}
}
else
{
++it;
}
}
}
<file_sep>#include "TrajectoryParse.h"
#include <iostream>
#define DEBUG
int main(int argc, char** argv)
{
if(argc < 2)
{
cout<<"need trajectory file"<<endl;
}
TrajectoryParse parser;
vector<CurvePath *> vCurve = parser.GetTrajectories(argv[1]);
if(vCurve.empty())
return -1;
cout<<"number of curves: "<<vCurve.size()<<endl;
cout<<"current position: "<<endl;
int curvecount = 0;
for(auto i : vCurve)
{
cout<<"curve number: "<<curvecount<<endl;
for(int j = 0; j < 45; j++)
{
i->Increment();
i->PrintPosition();
}
curvecount++;
break;
}
}
<file_sep>#ifndef CURVEPATH_H
#define CURVEPATH_H
#include "ParametricCurve.h"
#include "ModelAbstraction.h"
#include "Interpolate.h"
#include <vector>
using namespace std;
class CurvePath : private Interpolate, public ModelAbstraction
{
private:
public:
CurvePath();
~CurvePath();
void Draw(); /// draws the current position as a point
void FormatAction(); /// implemented method derived from ModelAbstraction to react to animation events
void AddCurve(int steps, float ctrlpoint1[], float ctrlpoint2[], float ctrlpoint3[], float ctrlpoint4[]); /// redirects this to Iterpolate class
};
#endif
<file_sep>#include <vector>
#include <GL/glew.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include "CityParse.h"
#include "ModelAbstraction.h"
#define GLUT_DISABLE_ATEXIT_HACK
int main(int argc, char** argv)
{
if(argc < 2)
cout<<"input not valid"<<endl;
//boilerplate
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Assignment 1");
//initialize glew for vertex shader
GLenum err = glewInit();
if(GLEW_OK != err)
{
cout<<"glew init failed"<<endl;
return -1;
}
CityParse cCityParse;
vector<ModelAbstraction*> vpEntity;
vpEntity = cCityParse.ParseCity(argv[1]);
for(auto& i : vpEntity)
{
delete i;
i = NULL;
}
return 0;
}
<file_sep>#ifndef VEC_H
#define VEC_H
#include <stdexcept>
#include <string>
class Vec {
public:
Vec(); // default 3D vector
Vec(int dim); // set vector with certain dimension
Vec(const Vec & v); // copy vector
~Vec();
float * _vec; // vector data
int _dim; // vector dimension
void SetDim(int); //resize dimension and preserve existing data if possible
Vec & operator = (const Vec & v);
Vec operator + (const Vec & v) const;
Vec operator - (const Vec & v) const;
inline float & operator [] ( int i ){ return _vec[i]; };
inline float operator [] ( int i ) const{ return _vec[i]; };
float Dot(const Vec & v) const;
Vec Cross(const Vec & v) const;
float Magnitude() const;
void NormalizeCurrent(); //normalize current vec
Vec Normalize() const; //return a normalize vec
void SetFromArray(int dim, float array[] ); //copy from array
void GetArray(int & dim, float * & array ) const; //copy to array
class Exception : public std::runtime_error {
public:
Exception(const std::string &msg): std::runtime_error(msg) { }
};
};
Vec ScaleVec(float s, const Vec v); //s * v
Vec ScaleVecAdd(float s, const Vec v1, const Vec v2);//s * v1 + v2
#endif
<file_sep>#include <vector>
#include <tuple>
#include <string>
#include <iostream>
#include "ModelVertice.h"
using namespace std;
ModelVertice::ModelVertice()
{
this->mType = VERTICE;
this->mBeginTag = "<vertices>";
this->mEndTag = "</vertices>";
}
void ModelVertice::FormatData()
/**
implemented formating for vertice
*/
{
int i = 0;
//convert data to expected format
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); ++it)
{
tVertice NewData = std::make_tuple(i, atof((*it).c_str()),atof((*(it+1)).c_str()),atof((*(it+2)).c_str()));
this->vVertice.push_back(NewData);
it += 2;
i++;
}
#ifdef DEBUG
//check saved model data
for(auto j : this->vVertice)
{
cout<<"tuple data: "<<std::get<TVERTICE_X>(j)<<", "<<std::get<TVERTICE_Y>(j)<<", "<<std::get<TVERTICE_Z>(j)<<endl;
}
#endif
}
<file_sep>#include "DOMNode.h"
#include <iostream>
using namespace std;
DOMNode::DOMNode()
{
this->Parent = NULL;
this->Type.clear();
this->Data.clear();
}
DOMNode::~DOMNode()
{
for(auto i : this->Children)
{
if(i != NULL)
{
delete i;
}
i = NULL;
}
this->Children.clear();
}
void DOMNode::AddChild(DOMNode * node)
{
this->Children.push_back(node);
}
void DOMNode::Print()
{
cout<<this->Type<<": ";
cout<<this->Data<<endl;
}
void DOMNode::PrintBreadth()
{
for(auto i : this->Children)
{
i->Print();
}
for(auto i : this->Children)
{
i->PrintBreadth();
}
}
<file_sep>#include "Mat.h"
#include <math.h>
#include <string.h>
#include <iostream>
using namespace std;
Mat::Mat(){
// sets up default 4x4 dimension
int dim[2] = { 4, 4 };
ResizeInt( 2, dim );
}
void Mat::ResizeInt( int count, int dim [] ){
if( count == 0 ){
_size = 0;
delete [] _mat;
_mat = new float [ 0 ];
return;
}else{
//set mat dimension
_dim.SetDim(count);
_size = 1;
for( int i = 0; i < count; i++ ){
_size *= dim[i];
_dim[i] = dim[i];
}
_mat = new float [ _size ];
for( int i = 0; i < _size; i++ ){
_mat[i] = 0;
}
}
}
void Mat::ResizeVec( const Vec & v ){
float * dim;
int count;
v.GetArray( count, dim );
int * dim_int = new int[count];
for(int i = 0; i < count; i++ ){
dim_int[i] = floor(dim[i] + 0.5);
}
ResizeInt( count, dim_int );
}
Mat & Mat::operator = ( const Mat & m ){
_size = m._size;
_dim = m._dim;
_mat = new float [ _size ];
memcpy( _mat, m._mat, sizeof(float)*_size );
}
Mat Mat::operator * ( const Mat & m ) const{
Mat a;
if( (int)_dim[1] != (int)m._dim[0] ){
//size mismatch
cout<<"mismatch"<<endl;
return a;
}else{
//new mat size after multiplication
int dim[2];
dim[0] = _dim[0];
dim[1] = m._dim[1];
a.ResizeInt( 2, dim );
//row index
for( int i = 0; i < (int)a._dim[0]; i++){
//column index
for( int j = 0; j < (int)a._dim[1]; j++){
// for( int x = 0; x < (int)_dim[1]; x++){
// a( i, j ) += (*this)( i, x ) * m( x, j );
// }
for( int x = 0; x < (int)_dim[1]; x++){
a._mat[ j * (int)a._dim[0] + i ] += _mat[ i + x * (int)_dim[0] ] * m._mat[ x + j * (int)m._dim[0] ];
}
}
}
return a;
}
}
Mat Mat::operator + ( const Mat & a ) const{
Mat m;
int dim[2];
if( _dim[0] != a._dim[0] || _dim[1] != a._dim[1] ){
m.ResizeInt( 0, dim );
return m;
}else{
dim[0] = _dim[0];
dim[1] = _dim[1];
m.ResizeInt( 2, dim );
for( int j = 0; j < _dim[1]; j++ ){
for( int i = 0; i < _dim[0]; i++ ){
m( i, j ) = (*this)( i, j ) + a( i, j );
}
}
return m;
}
}
Mat Mat::operator - ( const Mat & a ) const{
Mat m;
int dim[2];
if( _dim[0] != a._dim[0] || _dim[1] != a._dim[1] ){
m.ResizeInt( 0, dim );
return m;
}else{
dim[0] = _dim[0];
dim[1] = _dim[1];
m.ResizeInt( 2, dim );
for( int j = 0; j < _dim[1]; j++ ){
for( int i = 0; i < _dim[0]; i++ ){
m( i, j ) = (*this)( i, j ) - a( i, j );
}
}
return m;
}
}
float & Mat::operator ()( int m, int n ){
if( m >= (int)_dim[0] || n >= (int)_dim[1] ){
return _mat[0];
}else{
return _mat[ m + n * (int)_dim[0] ];
}
}
float Mat::operator ()( int m, int n ) const{
if( m >= (int)_dim[0] || n >= (int)_dim[1] ){
return NAN;
}else{
return _mat[ m + n * (int)_dim[0] ];
}
}
void Mat::SetFromVec( const Vec & v, bool column ){
int dim[2];
int len = v._dim;
if( column == true ){
dim[0] = len;
dim[1] = 1;
ResizeInt( 2, dim );
}else{
dim[0] = 1;
dim[1] = len;
ResizeInt( 2, dim );
}
for( int i = 0; i < len; i++ ){
_mat[i] = v[i];
}
}
bool Mat::GetVec( Vec & v, int index, bool column ) const{
if( column == true ){
if( index >= _dim[1] ){
return false;
}
v.SetDim( _dim[0] );
for( int i = 0; i < _dim[0]; i++ ){
v[i] = (*this)( i, index );
}
}else{
if( index >= _dim[0] ){
return false;
}
v.SetDim( _dim[1] );
for( int i = 0; i < _dim[1]; i++ ){
v[i] = (*this)( index, i );
}
}
return true;
}
bool Mat::GetSubMat( Mat & m, int row, int col, int sizerow, int sizecol ) const{
if( row >= _dim[0] || col >= _dim[1] || row + sizerow - 1 >= _dim[0] || col + sizecol - 1 >= _dim[1] ){
return false;
}
int dim[2];
dim[0] = sizerow;
dim[1] = sizecol;
m.ResizeInt( 2, dim );
for(int j = 0; j < sizecol; j++){
for(int i = 0; i < sizerow; i++){
m( i, j ) = (*this)( row + i, col + j );
}
}
return true;
}
void Mat::TransposeCurrent(){
(*this) = Transpose();
}
Mat Mat::Transpose() const{
Mat m;
int dim[2];
dim[0] = _dim[1];
dim[1] = _dim[0];
m.ResizeInt( 2, dim );
for( int j = 0; j < dim[1]; j++ ){
for( int i = 0; i < dim[0]; i++ ){
m( i, j ) = (*this)( j, i );
}
}
return m;
}
<file_sep>#include "DualQuat.h"
#include "Vec.h"
#include <iostream>
#include <math.h>
using namespace std;
DualQuat::DualQuat(){
SetIdentity();
}
DualQuat::DualQuat( Quat & a, Quat & b ){
SetQuats( a, b );
}
DualQuat::DualQuat( Vec A, float a, Vec B, float b ){
SetQuatsVecs( A, a, B, b );
}
DualQuat::DualQuat( DualQuat & a ){
SetQuats( a._A, a._B );
}
void DualQuat::SetIdentity(){
_A._quat[0] = 0;
_A._quat[1] = 0;
_A._quat[2] = 0;
_A._quat[3] = 1;
_B._quat[0] = 0;
_B._quat[1] = 0;
_B._quat[2] = 0;
_B._quat[3] = 0;
}
void DualQuat::SetZero(){
_A._quat[0] = 0;
_A._quat[1] = 0;
_A._quat[2] = 0;
_A._quat[3] = 0;
_B._quat[0] = 0;
_B._quat[1] = 0;
_B._quat[2] = 0;
_B._quat[3] = 0;
}
void DualQuat::SetQuats( Quat & a, Quat & b ){
_A = a;
_B = b;
}
void DualQuat::SetQuatsVecs( Vec A, float a, Vec B, float b ){
if(A._dim < 3 || B._dim < 3){
SetIdentity();
cout<<"vector dimension less than 3"<<endl;
}else{
_A._quat[0] = A._vec[0];
_A._quat[1] = A._vec[1];
_A._quat[2] = A._vec[2];
_A._quat[3] = a;
_B._quat[0] = B._vec[0];
_B._quat[1] = B._vec[1];
_B._quat[2] = B._vec[2];
_B._quat[3] = b;
}
}
void DualQuat::SetArray( float a [] ){
_A = Quat( a[0], a[1], a[2], a[3] );
_B = Quat( a[4], a[5], a[6], a[7] );
}
void DualQuat::GetArray( float a [] ) const{
for( int i = 0; i < 4; i++){
a[i] = _A._quat[i];
}
for( int i = 0; i < 4; i++){
a[i+4] = _B._quat[i];
}
}
DualQuat & DualQuat::operator = ( const DualQuat & q )
{
_A = q._A;
_B = q._B;
return *this;
}
DualQuat DualQuat::operator + ( const DualQuat & q ) const{
DualQuat d;
//add component-wise
for( int i = 0; i < 4; i++ ){
d._A._quat[i] = _A._quat[i] + q._A._quat[i];
d._B._quat[i] = _B._quat[i] + q._B._quat[i];
}
return d;
}
DualQuat & DualQuat::operator += ( const DualQuat & q ){
//add component-wise
for( int i = 0; i < 4; i++ ){
_A._quat[i] = _A._quat[i] + q._A._quat[i];
_B._quat[i] = _B._quat[i] + q._B._quat[i];
}
return *this;
}
DualQuat DualQuat::operator - ( const DualQuat & q ) const{
DualQuat d;
//add component-wise
for( int i = 0; i < 4; i++ ){
d._A._quat[i] = _A._quat[i] - q._A._quat[i];
d._B._quat[i] = _B._quat[i] - q._B._quat[i];
}
return d;
}
DualQuat & DualQuat::operator -= ( const DualQuat & q ){
//add component-wise
for( int i = 0; i < 4; i++ ){
_A._quat[i] = _A._quat[i] - q._A._quat[i];
_B._quat[i] = _B._quat[i] - q._B._quat[i];
}
return *this;
}
DualQuat DualQuat::operator * ( const DualQuat & q ) const{
Quat a;
Quat b;
a = _A * q._A;
b = ( _A * q._B ) + ( _B * q._A );
DualQuat d(a, b);
return d;
}
Quat DualQuat::GetReal() const{
return Quat( _A._quat[0], _A._quat[1], _A._quat[2], _A._quat[3] );
}
Quat DualQuat::GetDual() const{
return Quat( _B._quat[0], _B._quat[1], _B._quat[2], _B._quat[3] );
}
void DualQuat::SetReal( const Quat & q ){
_A = q;
}
void DualQuat::SetDual( const Quat & q ){
_B = q;
}
float DualQuat::GetVal( int index ) const{
if( index < 0 || index > 7 ){
return NAN;
}else{
if( index < 4 ){
return _A._quat[ index ];
}else{
return _B._quat[ index - 4 ];
}
}
}
DualScalar DualQuat::MagnitudeSquared() const {
float a = 0;
float b = 0;
DualQuat q;
q = *this;
q = q.Conjugate();
DualQuat p;
p = (*this) * q;
a = p._A.LengthSquared();
b = p._B.LengthSquared();
DualScalar d( a, b );
return d;
}
DualScalar DualQuat::Magnitude() const {
DualScalar s;
s = MagnitudeSquared();
s._a = sqrt(s._a);
s._b = sqrt(s._b);
return s;
}
DualQuat DualQuat::Normalize() const {
DualQuat q;
q.NormalizeCurrent();
// DualScalar n;
// n = Magnitude();
// n = n.Invert();
// q = ScaleDualScalar( n, q );
return q;
}
void DualQuat::NormalizeCurrent() {
DualScalar n;
n = Magnitude();
n = n.Invert();
(*this) = ScaleDualScalar( n, (*this) );
}
DualQuat DualQuat::Invert() const {
DualScalar s;
s = MagnitudeSquared();
s = s.Invert();
DualQuat q;
q = Conjugate();
q = ScaleDualScalar( s, q );
return q;
}
DualQuat InterpolateSclerp( const DualQuat & q1, const DualQuat & q2, float t) {
DualQuat q;
//q1^-1 * q2
q = q1.Conjugate() * q2;
// double d = q1.a * q2.a + q1.A.dot(q2.A);
// if (d < 0) {
// scale(-1);
// }
q = q.PowFloat(t);
q = q1 * q;
return q;
}
DualQuat DualQuat::PowFloat(double e) const {
DualQuat d;
d = *this;
Vec screwaxis;
Vec moment;
Vec angles;
double normA = d.GetScrewParameters( screwaxis, moment, angles );
// pure translation
if ( normA < 1e-15 ) {
for( int i = 0; i < 3; i++ ){
d._B._quat[i] *= e;
}
d.NormalizeCurrent();
return d;
}else{
// exponentiate
double theta = angles[0] * e;
double alpha = angles[1] * e;
// convert back
d.SetScrewParameters( screwaxis, moment, theta, alpha );
return d;
}
}
float DualQuat::GetScrewParameters(Vec & screwaxis, Vec & moment, Vec & angles ) {
angles.SetDim(2);
moment.SetDim(3);
screwaxis.SetDim(3);
//get quat A.x, A.y, A.z
Vec q_A;
q_A.SetDim(3);
for( int i = 0; i < 3; i++ ){
q_A[i] = _A._quat[i];
}
//get quat B.x, B.y, B.z
Vec q_B;
q_B.SetDim(3);
for( int i = 0; i < 3; i++ ){
q_B[i] = _B._quat[i];
}
float normA = q_A.Magnitude();
// pure translation
if (normA < 1e-15) {
screwaxis = q_B.Normalize();
for( int i = 0; i < 3; i++ ){
moment[i] = 0;
}
angles[0] = 0;
angles[1] = 2 * q_B.Magnitude();
return normA;
} else {
screwaxis = q_A.Normalize();
angles[0] = 2 * atan2( normA, _A._quat[3] );
// if (angles[0] > Math.PI / 2) {
// angles[0] -= Math.PI;
// }
angles[1] = -2 * _B._quat[3] / normA;
Vec m1 = ScaleVec( 1.0 / normA, q_B );
Vec m2 = ScaleVec( _A._quat[3] * _B._quat[3] / (normA * normA), screwaxis );
moment = m1 + m2;
return normA;
}
}
void DualQuat::SetScrewParameters(Vec & screwaxis, Vec & moment, float theta, float alpha) {
float cosa = cos( theta / 2 );
float sina = sin( theta / 2 );
_A._quat[3] = cosa;
for( int i = 0; i < 3; i++ ){
_A._quat[i] = sina * screwaxis[i];
}
_B._quat[3] = -alpha / 2 * sina;
for( int i = 0; i < 3; i++ ){
_B._quat[i] = sina * moment[i] + alpha / 2 * cosa * screwaxis[i];
}
NormalizeCurrent();
}
void DualQuat::GetRigidTransform( float trans [] ) const{
trans[0] = _A._quat[3] * _A._quat[3] + _A._quat[0] * _A._quat[0] - _A._quat[1] * _A._quat[1] - _A._quat[2] * _A._quat[2];
trans[4] = 2*(_A._quat[0]*_A._quat[1]- _A._quat[3]*_A._quat[2]);
trans[8] = 2*(_A._quat[0]*_A._quat[2]+ _A._quat[3]*_A._quat[1]);
trans[1] = 2*(_A._quat[0]*_A._quat[1]+ _A._quat[3]*_A._quat[2]);
trans[5] = _A._quat[3]*_A._quat[3] - _A._quat[0]*_A._quat[0] + _A._quat[1]*_A._quat[1] -_A._quat[2]*_A._quat[2];;
trans[9] = 2*(_A._quat[1]*_A._quat[2]- _A._quat[3]*_A._quat[0]);
trans[2] = 2*(_A._quat[0]*_A._quat[2]- _A._quat[3]*_A._quat[1]);
trans[6] = 2*(_A._quat[1]*_A._quat[2]+ _A._quat[3]*_A._quat[0]);
trans[10] = _A._quat[3]*_A._quat[3] - _A._quat[0]*_A._quat[0] - _A._quat[1]*_A._quat[1] + _A._quat[2]*_A._quat[2];
// trans[12] = 2*(_A._quat[3]*_B._quat[0] - _A._quat[0]*_B._quat[3] + _A._quat[1]*_B._quat[2] - _A._quat[2]*_B._quat[1]);
// trans[13] = 2*(_A._quat[3]*_B._quat[1] - _A._quat[0]*_B._quat[2] - _A._quat[1]*_B._quat[3] +_A._quat[2]*_B._quat[0]);
// trans[14] = 2*(_A._quat[3]*_B._quat[2] + _A._quat[0]*_B._quat[1] - _A._quat[1]*_B._quat[0] - _A._quat[2]*_B._quat[3]);
trans[12] = 2 * _B._quat[0];
trans[13] = 2 * _B._quat[1];
trans[14] = 2 * _A._quat[2];
trans[15] = 1;
trans[3] = 0;
trans[7] = 0;
trans[11] = 0;
}
void DualQuat::SetTranslation( const float trans [] ){
_B.SetTranslation( trans );
}
// void DualQuat::SetTranslation(const float axis [], float angle, const float trans [] ){
// AxisAngleDegree( axis, angle );
// Mat m_rot[16];
// ToMatrixRot( m_rot );
// //get diplacement
// int dim_trans[2];
// dim_trans[0] = 4;
// dim_trans[1] = 1;
// Mat m_trans;
// m_trans.ResizeInt( 2, dim_trans );
// m_trans( 0, 0 ) = trans[0];
// m_trans( 1, 0 ) = trans[1];
// m_trans( 2, 0 ) = trans[2];
// m_trans( 3, 0 ) = 1;
// Mat m_displace;
// m_displace = m_rot * m_trans;
// m_displace.TransposeCurrent();
// Mat m_trans_dif;
// m_trans_dif = m_trans - m_displace;
// _B.SetTranslation( a );
// }
void DualQuat::AxisAngleDegree( const float axis[], float angle ){
_A.AxisAngleDegree( axis, angle );
}
void DualQuat::AxisAngleDegreeVector( const Vec & v, float angle ){
_A.AxisAngleDegreeVector( v, angle );
}
DualQuat ScaleAddDualScalar( const DualScalar & s, const DualQuat & q1, const DualQuat & q2 ) {
float a = s.GetReal();
float b = s.GetDual();
Quat A = ScaleAdd( a, q1._A, q2._A );
Quat B = ScaleAdd( a, q1._B, q2._B );
for( int i = 0; i < 4; i++ ){
B._quat[i] += b * q1._A._quat[i];
}
DualQuat d( A, B );
return d;
}
DualQuat ScaleAddFloat( float s, const DualQuat & q1, const DualQuat & q2 ) {
Quat A = ScaleAdd( s, q1._A, q2._A );
Quat B = ScaleAdd( s, q1._B, q2._B );
DualQuat d( A, B );
return d;
}
DualQuat ScaleDualScalar(const DualScalar & s, const DualQuat & q ) {
float a = s.GetReal();
float b = s.GetDual();
Quat A = Scale( a, q._A );
Quat B = Scale( a, q._B );
Quat B2 = Scale( b, q._A );
B = B + B2;
DualQuat d( A, B );
return d;
}
DualQuat ScaleFloat( float s, const DualQuat & q ) {
Quat A = Scale( s, q._A );
Quat B = Scale( s, q._B );
DualQuat d( A, B );
return d;
}
<file_sep>#include <math.h>
#include <stdexcept>
#include <iostream>
using namespace std;
#include "Quat.h"
#include "Vec.h"
Quat::Quat(){
_quat[0] = 0.0f;
_quat[1] = 0.0f;
_quat[2] = 0.0f;
_quat[3] = 1.0f;
}
Quat::Quat( float x, float y, float z, float w ){
_quat[0] = x;
_quat[1] = y;
_quat[2] = z;
_quat[3] = w;
}
Quat::Quat( Vec v, float w ){
_quat[0] = v._vec[0];
_quat[1] = v._vec[1];
_quat[2] = v._vec[2];
_quat[3] = w;
}
Quat::Quat( const Quat & q ){
_quat[0] = q[0];
_quat[1] = q[1];
_quat[2] = q[2];
_quat[3] = q[3];
}
Quat & Quat::operator = ( const Quat & q ) {
for( int i = 0; i < 4; i++ ){
_quat[i] = q._quat[i];
}
return *this;
}
Quat Quat::operator - ( const Quat & q ) const{
Quat r = *this;
for( int i = 0; i < 4; i++ ){
r._quat[i] -= q._quat[i];
}
return r;
}
Quat & Quat::operator -= ( const Quat & q ) {
for( int i = 0; i < 4; i++ ){
_quat[i] -= q._quat[i];
}
return *this;
}
Quat Quat::operator + ( const Quat & q ) const{
Quat r = *this;
for( int i = 0; i < 4; i++ ){
r._quat[i] += q._quat[i];
}
return r;
}
Quat & Quat::operator += ( const Quat & q ) {
for( int i = 0; i < 4; i++ ){
_quat[i] += q._quat[i];
}
return *this;
}
Quat Quat::operator * ( const Quat & q ) const{
Quat r;
r._quat[3] = _quat[3] * q._quat[3] - _quat[0] * q._quat[0] - _quat[1] * q._quat[1] - _quat[2] * q._quat[2];
r._quat[0] = _quat[3] * q._quat[0] + _quat[0] * q._quat[3] + _quat[1] * q._quat[2] - _quat[2] * q._quat[1];
r._quat[1] = _quat[3] * q._quat[1] - _quat[0] * q._quat[2] + _quat[1] * q._quat[3] + _quat[2] * q._quat[0];
r._quat[2] = _quat[3] * q._quat[2] + _quat[0] * q._quat[1] - _quat[1] * q._quat[0] + _quat[2] * q._quat[3];
return r;
}
Quat & Quat::operator *= ( const Quat & q ) {
float w = _quat[3] * q._quat[3] - _quat[0] * q._quat[0] - _quat[1] * q._quat[1] - _quat[2] * q._quat[2];
float x = _quat[3] * q._quat[0] + _quat[0] * q._quat[3] + _quat[1] * q._quat[2] - _quat[2] * q._quat[1];
float y = _quat[3] * q._quat[1] - _quat[0] * q._quat[2] + _quat[1] * q._quat[3] + _quat[2] * q._quat[0];
float z = _quat[3] * q._quat[2] + _quat[0] * q._quat[1] - _quat[1] * q._quat[0] + _quat[2] * q._quat[3];
_quat[0] = x;
_quat[1] = y;
_quat[2] = z;
_quat[3] = w;
return *this;
}
void Quat::AxisAngleDegree( const float axis[], float angle ){
Vec v;
v._vec[0] = axis[0];
v._vec[1] = axis[1];
v._vec[2] = axis[2];
v.NormalizeCurrent();
double radians = (angle/180.0f)*3.14159265f;
double sinehalf = sin( double(radians/2.0f) );
_quat[0] = v._vec[0] * sinehalf;
_quat[1] = v._vec[1] * sinehalf;
_quat[2] = v._vec[2] * sinehalf;
_quat[3] = (float)cos( double(radians/2.0f) );
}
void Quat::AxisAngleDegreeVector( const Vec & v, float angle ){
if(v._dim < 3)
throw("Quat::AxisAngleVector(): vector dimension < 3");
float axis[3];
axis[0] = v._vec[0];
axis[1] = v._vec[1];
axis[2] = v._vec[2];
this->AxisAngleDegree( axis, angle );
}
void Quat::SetTranslation( const float a [] ){
_quat[0] = a[0]/2; //dx
_quat[1] = a[1]/2; //dy
_quat[2] = a[2]/2; //dz
_quat[3] = 0;
}
float Quat::Length() const{
return (float)sqrt( LengthSquared() );
}
float Quat::LengthSquared() const{
return (float) double(_quat[0]*_quat[0] + _quat[1]*_quat[1] + _quat[2]*_quat[2] + _quat[3]*_quat[3]);
}
void Quat::NormalizeQuatCurrent(){
float len = Length();
if( len == 0 )
throw("Quat::Normalize(): can't divide by length 0");
_quat[0] /= len;
_quat[1] /= len;
_quat[2] /= len;
_quat[3] /= len;
}
Quat Quat::NormalizeQuat() const{
Quat q = *this;
q.NormalizeQuatCurrent();
return q;
}
Quat Quat::Log() const{
Quat q;
//set a of quat
float q_len = this->Length();
q._quat[3] = log( q_len );
//copy x,y,z of quat into vec
Vec v;
v.SetDim(3);
for( int i = 0; i < 3; i++ ){
v[i] = _quat[i];
}
//get v/||v||
float v_len = v.Magnitude();
v.NormalizeCurrent();
//get arccos(a/||v||)
float m = acos( _quat[3] / q_len );
v = ScaleVec( m, v );
//set x,y,z of quat
for( int i = 0; i < 3; i++ ){
q._quat[i] = v[i];
}
return q;
}
Quat Quat::Pow( float t ){
Quat result = (*this); //copy
//i,j,k components
Vec v;
v._vec[0] = _quat[0];
v._vec[1] = _quat[1];
v._vec[2] = _quat[2];
v.NormalizeCurrent();
float len = this->Length();
double alpha = acos( double(_quat[3]) / len ); // original angle
double beta = t * alpha; // new angle
double coeff = pow(len, t);
result._quat[3] = coeff * cos( beta );
for( int i = 0; i < 3; i++ ){
result._quat[i] = coeff * v._vec[i] * sin( beta );
}
// if ( fabs(double(_quat[3])) < 0.9999 ) {
// float alpha = (float)acos(double(_quat[3]));
// float newAlpha = alpha*t;
// result._quat[3] = (float)cos( double(newAlpha) );
// float fact = float( sin(double(newAlpha))/sin(double(alpha)) );
// result._quat[0] *= fact;
// result._quat[1] *= fact;
// result._quat[2] *= fact;
// }
return result;
}
void Quat::ToMatrixRot( float mat[] ) const{
// column 1
mat[ 0] = 1.0f - 2.0f * ( _quat[1] * _quat[1] + _quat[2] * _quat[2] );
mat[ 1] = 2.0f * (_quat[0] * _quat[1] + _quat[2] * _quat[3]);
mat[ 2] = 2.0f * (_quat[0] * _quat[2] - _quat[1] * _quat[3]);
mat[ 3] = 0.0f;
// column 2
mat[ 4] = 2.0f * ( _quat[0] * _quat[1] - _quat[2] * _quat[3] );
mat[ 5] = 1.0f - 2.0f * ( _quat[0] * _quat[0] + _quat[2] * _quat[2] );
mat[ 6] = 2.0f * (_quat[2] * _quat[1] + _quat[0] * _quat[3] );
mat[ 7] = 0.0f;
// column 3
mat[ 8] = 2.0f * ( _quat[0] * _quat[2] + _quat[1] * _quat[3] );
mat[ 9] = 2.0f * ( _quat[1] * _quat[2] - _quat[0] * _quat[3] );
mat[10] = 1.0f - 2.0f * ( _quat[0] * _quat[0] + _quat[1] * _quat[1] );
mat[11] = 0.0f;
// column 4
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1.0f;
}
void Quat::ToMatrixTrans( float mat[] ) const{
for( int i = 0; i < 12; i++ ){
mat[i] = 0;
}
mat[12] = 2 * _quat[0];
mat[13] = 2 * _quat[1];
mat[14] = 2 * _quat[2];
mat[15] = 1;
}
Quat Quat::Negate() const {
return Quat( -_quat[0], -_quat[1], -_quat[2], -_quat[3] );
}
Quat InterpolateBasic( const Quat q1, const Quat q2, float r ){
Quat q;
for( int i = 0 ; i < 4; i++) {
q._quat[i] = (1-r) * q1._quat[i] + r * q2._quat[i];
}
return q;
}
Quat Scale( float s, const Quat q ){
return Quat( s * q._quat[0], s * q._quat[1], s * q._quat[2], s * q._quat[3] );
}
Quat ScaleAdd( float s, const Quat q1, const Quat q2 ){
return Quat( s * q1._quat[0] + q2._quat[0], s * q1._quat[1] + q2._quat[1], s * q1._quat[2] + q2._quat[2], s * q1._quat[3] + q2._quat[3] );
}
Quat InterpolateSlerp( const Quat & q1, const Quat & q2, float t ){
Quat result, p2 = q2;
//q2 = q1 * result
//result = conj(q1)*q2
//omega = half angle between the 2 quaternions
float cosOmega = q1._quat[3]*q2._quat[3] + q1._quat[0]*q2._quat[0] + q1._quat[1]*q2._quat[1] + q1._quat[2]*q2._quat[2];
//inverted case
if ( cosOmega < 0.0f ) {
p2._quat[0] = -p2._quat[0];
p2._quat[1] = -p2._quat[1];
p2._quat[2] = -p2._quat[2];
p2._quat[3] = -p2._quat[3];
cosOmega = -cosOmega;
}
float k0, k1;
if ( cosOmega > 0.99999f ) {
k0 = 1.0f - t;
k1 = t;
}
else {
float sinOmega = (float)sqrt( double(1.0f - cosOmega*cosOmega) );
float omega = (float)atan2( double(sinOmega), double(cosOmega) );
float invSinOmega = 1.0f/sinOmega;
k0 = float( sin(double((1.0f - t)*omega)) )*invSinOmega;
k1 = float( sin(double(t*omega)) )*invSinOmega;
}
for ( int i=0; i < 4; i++ )
result[i] = q1[i]*k0 + p2[i]*k1;
return result;
}
<file_sep>#include <vector>
#include <tuple>
#include <iostream>
#include <string>
#include "ModelTriangle.h"
using namespace std;
ModelTriangle::ModelTriangle()
{
this->mType = TRIANGLE;
this->mBeginTag = "<triangles>";
this->mEndTag = "</triangles>";
}
void ModelTriangle::FormatData()
/**
implemented formating for Triangles
*/
{
int i = 0;
//convert data to expected format
for(std::vector<string>::iterator it = this->vDataItem.begin(); it != vDataItem.end(); ++it)
{
tTriangle NewData;
std::get<TTRIANGLE_ID>(NewData) = i;
std::get<TTRIANGLE_VEC1ID>(NewData) = atoi((*it).c_str());
std::get<TTRIANGLE_VEC2ID>(NewData) = atoi((*(it+1)).c_str());
std::get<TTRIANGLE_VEC3ID>(NewData) = atoi((*(it+2)).c_str());
std::get<TTRIANGLE_NORMID>(NewData) = atoi((*(it+3)).c_str());
std::get<TTRIANGLE_TEXTID>(NewData) = atoi((*(it+4)).c_str());
std::get<TTRIANGLE_TEXT1>(NewData) = atof((*(it+5)).c_str());
std::get<TTRIANGLE_TEXT2>(NewData) = atof((*(it+6)).c_str());
std::get<TTRIANGLE_TEXT3>(NewData) = atof((*(it+7)).c_str());
std::get<TTRIANGLE_TEXT4>(NewData) = atof((*(it+8)).c_str());
std::get<TTRIANGLE_TEXT5>(NewData) = atof((*(it+9)).c_str());
std::get<TTRIANGLE_TEXT6>(NewData) = atof((*(it+10)).c_str());
this->vTriangle.push_back(NewData);
it += 10;
i++;
}
#ifdef DEBUG
//check saved model data
for(auto j : this->vTriangle)
{
cout<<"tuple data: "<<std::get<TTRIANGLE_VEC1ID>(j)<<", "<<std::get<TTRIANGLE_VEC2ID>(j)<<", "<<std::get<TTRIANGLE_VEC3ID>(j)<<", "<<std::get<TTRIANGLE_NORMID>(j)<<", "<<std::get<TTRIANGLE_TEXTID>(j)<<", "<<std::get<TTRIANGLE_TEXT1>(j)<<", "<<std::get<TTRIANGLE_TEXT2>(j)<<", "<<std::get<TTRIANGLE_TEXT3>(j)<<", "<<std::get<TTRIANGLE_TEXT4>(j)<<", "<<std::get<TTRIANGLE_TEXT5>(j)<<", "<<std::get<TTRIANGLE_TEXT6>(j)<<endl;
}
#endif
}
<file_sep>#ifndef MODELDATA_H
#define MODELDATA_H
#include <string>
#include <sstream>
#include <vector>
using namespace std;
///type of data, might be useful later on
enum eDataType
{
NAME = 0,
TEXTURE,
VERTICE,
NORMAL,
TRIANGLE,
CURVE
};
///acts as a helper class to the parser. It provides matching DOM tags and separates data to be used by derived classes
class ModelData{
protected:
vector<string> vDataItem; ///contains separated data to be accessed by derived class
public:
string mBeginTag; ///start tag for parsing
string mEndTag; ///end tag for parsing
eDataType mType; //type of stored data
void SetData(string input); ///seperates space delimited input string into a vector of strings in vDataItem
virtual void FormatData()=0; ///function to save data to specific format
virtual ~ModelData(){};
virtual void ClearData(){};
};
#endif
|
632fc98dd6ed4a984a9edf0b648abe50b2455c57
|
[
"Markdown",
"Makefile",
"C++"
] | 66
|
C++
|
bilbil/3dviewer
|
a23717e7ea94e1c60b9ad1969eb90654c1baf47a
|
d7bf78f8063c2e49ef41fc84e30724d1b6a71e3b
|
refs/heads/master
|
<file_sep>#from hspice import HSPICEFile
#from uwi import UWIFile
#from psf import PSFFile
from touchstone import TouchstoneFile
from citi import CITIFile<file_sep>#!/users/micas/bmachiel/python/epd-6.1-1-rh5-x86/bin/python
import wxversion
wxversion.ensureMinimal('2.8')
import os
import re
import wx
import wx.xrc as xrc
import numpy as np
from circuit import Circuit, Subcircuit, Signal
from datasource import DataSource, DataFile
from plot import PlotView, Trace
import pywave_xrc
from pywave_xrc import xrcMainFrame, get_resources
from xh_searchctrl import SearchCtrlXmlHandler
import plugins
pywave_path = os.path.dirname(os.path.abspath(__file__))
def __init_resources():
pywave_xrc.__res = xrc.EmptyXmlResource()
pywave_xrc.__res.Load(os.path.join(pywave_path, 'pywave.xrc'))
pywave_xrc.__init_resources = __init_resources
class MyMainFrame(xrcMainFrame):
def __init__(self, parent):
# add the wxSearchCtrl XML handler
get_resources().AddHandler(SearchCtrlXmlHandler())
# Initialize the frame
super(MyMainFrame, self).__init__(parent)
images_path = os.path.join(pywave_path, 'images')
self.image_list = wx.ImageList(16, 16)
circuit_image = wx.Image(os.path.join(images_path, 'circuit.png'))
subcircuit_image = wx.Image(os.path.join(images_path, 'subcircuit.png'))
self.image_list.Add(circuit_image.ConvertToBitmap())
self.image_list.Add(subcircuit_image.ConvertToBitmap())
self.fileTreeCtrl.AssignImageList(self.image_list)
self.filterSearchCtrl.ShowCancelButton(1)
self.open_files = []
self.data_source_counter = 1
self.views = []
self.statusBar = xrc.XRCCTRL(self, "statusBar")
self.OpenNewPlotView()
# data_source, item = self.open_file('tests/lcmodel.ac0')
# if item is not None:
# self.fileChoice.SetSelection(item)
# self._populate_tree(data_source.get_circuit())
def OnChoice_fileChoice(self, evt):
self._save_tree_state()
data_source = evt.GetClientData()
self._populate_tree(data_source.get_circuit())
def _populate_tree(self, circuit):
# remove old entries
self.fileTreeCtrl.DeleteAllItems()
self.signalListBox.Clear()
# fill up with new entries
self.fileTreeCtrl.AddRoot(circuit.name, image=0, data=wx.TreeItemData(circuit))
root_item = self.fileTreeCtrl.GetRootItem()
circuit.tree_item_id = root_item
self._add_subcircuits(root_item, circuit)
self._restore_tree_state()
# update sweep list
sweep_set = circuit._sweep_set
if sweep_set is None:
circuit.get_signals()[0].get_values()
sweep_set = circuit._sweep_set
self.sweepListCtrl.ClearAll()
for i, name in enumerate(sweep_set._names):
self.sweepListCtrl.InsertColumn(i, name)
if len(sweep_set._points) > 1:
for i, sweep_point in enumerate(sweep_set._points):
row = ["%4g" % item for item in sweep_point]
self.sweepListCtrl.Append(row)
self.sweepListCtrl.Select(0)
def _add_subcircuits(self, parent_item, circuit):
for subckt in circuit.get_subcircuits():
subckt_item = self.fileTreeCtrl.AppendItem(parent_item, subckt.name,
image=1,
data=wx.TreeItemData(subckt))
subckt.tree_item_id = subckt_item
self._add_subcircuits(subckt_item, subckt)
def _restore_tree_state(self):
root_item = self.fileTreeCtrl.GetRootItem()
self._restore_item_state(root_item)
circuit = self.fileTreeCtrl.GetItemPyData(root_item)
if circuit.selected is None:
circuit.selected = self.fileTreeCtrl.GetItemPyData(root_item)
self.fileTreeCtrl.SelectItem(self.fileTreeCtrl.GetSelection(), False)
# toggle selection to trigger refresh of signal list box
self.fileTreeCtrl.SelectItem(circuit.selected.tree_item_id, True)
def _restore_item_state(self, item):
# recurse
if self.fileTreeCtrl.ItemHasChildren(item):
child, cookie = self.fileTreeCtrl.GetFirstChild(item)
while True:
self._restore_item_state(child)
if child == self.fileTreeCtrl.GetLastChild(item):
break
child, cookie = self.fileTreeCtrl.GetNextChild(item, cookie)
# restore state
circuit = self.fileTreeCtrl.GetItemPyData(item)
if circuit.is_open():
self.fileTreeCtrl.Expand(item)
else:
self.fileTreeCtrl.Collapse(item)
def _save_tree_state(self):
if not self.fileTreeCtrl.IsEmpty():
root_item = self.fileTreeCtrl.GetRootItem()
self._save_item_state(root_item)
circuit = self.fileTreeCtrl.GetItemPyData(root_item)
selected_item = self.fileTreeCtrl.GetSelection()
circuit.selected = self.fileTreeCtrl.GetItemPyData(selected_item)
def _save_item_state(self, item):
# recurse
if self.fileTreeCtrl.ItemHasChildren(item):
child, cookie = self.fileTreeCtrl.GetFirstChild(item)
while True:
self._save_item_state(child)
if child == self.fileTreeCtrl.GetLastChild(item):
break
child, cookie = self.fileTreeCtrl.GetNextChild(item, cookie)
# save state
circuit = self.fileTreeCtrl.GetItemPyData(item)
circuit._opened = self.fileTreeCtrl.IsExpanded(item)
circuit.tree_item_id = None
def OnTree_sel_changed_fileTreeCtrl(self, evt):
selection = self.fileTreeCtrl.GetSelection()
if selection:
subcircuit = self.fileTreeCtrl.GetItemData(selection).GetData()
# restore filter string
self.filterSearchCtrl.SetValue(subcircuit._filter_regex)
# update signal list
self._update_signal_list(subcircuit, subcircuit._filter_regex)
def _update_signal_list(self, circuit, regex):
signals = circuit.get_signals()
try:
re_signals = re.compile(regex)
except:
return
self.signalListBox.Clear()
for signal in signals:
if re_signals.match(signal.name):
item = self.signalListBox.Append(signal.name, signal)
def open_file(self, file_path):
if file_path in self.open_files:
raise FileAlreadyOpen()
data_source = open_data_file(file_path)
data_source.number = self.data_source_counter
self.data_source_counter += 1
self.open_files.append(file_path)
item = self.fileChoice.Append("{1} [{0}] ".format(data_source.number,
data_source.name),
data_source)
return data_source, item
def OnListbox_dclick_signalListBox(self, evt):
signal = evt.GetClientData()
plot_view = self.viewNotebook.GetCurrentPage()
selected_sweep = self.sweepListCtrl.GetFirstSelected()
if selected_sweep == -1:
sweep_point = None
else:
sweep_point = signal.get_circuit()._sweep_set._points[selected_sweep]
plot_view.add_plot(signal, sweep_point)
def OpenNewPlotView(self):
plotView = PlotView(self.viewNotebook)
self.viewNotebook.AddPage(plotView, "plot view")
self.viewNotebook.ChangeSelection(self.viewNotebook.GetPageCount() - 1)
def OnText_filterSearchCtrl(self, evt):
subcircuit = self.fileTreeCtrl.GetItemPyData(self.fileTreeCtrl.GetSelection())
subcircuit._filter_regex = self.filterSearchCtrl.GetValue()
self._update_signal_list(subcircuit, subcircuit._filter_regex)
def OnSearchctrl_cancel_btn_filterSearchCtrl(self, evt):
self.filterSearchCtrl.Clear()
self.OnText_filterSearchCtrl(None)
# File menu
def OnMenu_fileOpenMenuItem(self, evt):
# retrieve path where currently selected data file is located
path = None
selection = self.fileChoice.GetSelection()
if selection != wx.NOT_FOUND:
data_source = self.fileChoice.GetClientData(selection)
if issubclass(type(data_source), DataFile):
path = os.path.dirname(data_source.file_path)
# create file open dialog
filedialog = wx.FileDialog(self,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE,
wildcard="All files (*.*)|*|HSPICE files (*.tr*, *.ac*, *.sw0, *.ft*)|*.ac*|Touchstone files (*.s*p)|*.s*p")
if path:
filedialog.SetDirectory(path)
filedialog.ShowModal()
filenames = filedialog.GetFilenames()
item = None
if filenames:
filepaths = filedialog.GetPaths()
for i, filename in enumerate(filenames):
try:
data_source, item = self.open_file(filepaths[i])
except FileAlreadyOpen:
d = wx.MessageDialog(self, "File is already open", "Alert", wx.OK)
d.ShowModal()
d.Destroy()
self._save_tree_state()
if item is not None:
self.fileChoice.SetSelection(item)
self._populate_tree(data_source.get_circuit())
def OnMenu_fileReloadMenuItem(self, evt):
selection = self.fileChoice.GetSelection()
data_source = self.fileChoice.GetClientData(selection)
if data_source.changed():
data_source.reload()
self._populate_tree(data_source.get_circuit())
def OnMenu_fileCloseMenuItem(self, evt):
selection = self.fileChoice.GetSelection()
if selection == wx.NOT_FOUND:
return
data_source = self.fileChoice.GetClientData(selection)
self.open_files.remove(data_source.file_path)
# TODO: remove all plots from the plot views
self.fileChoice.Delete(selection)
if self.fileChoice.GetCount() > 0:
new_selection = (selection - 1) % self.fileChoice.GetCount()
print new_selection
self.fileChoice.SetSelection(new_selection)
data_source = self.fileChoice.GetClientData(new_selection)
self._populate_tree(data_source.get_circuit())
else:
self.fileTreeCtrl.DeleteAllItems()
self.signalListBox.Clear()
self.data_source_counter = 1
def OnMenu_exitMenuItem(self, evt):
wx.Exit()
# View menu
def OnMenu_viewNewMenuItem(self, evt):
self.OpenNewPlotView()
def OnMenu_viewCloseMenuItem(self, evt):
currentPlotViewIndex = self.viewNotebook.GetSelection()
self.viewNotebook.RemovePage(currentPlotViewIndex)
if self.viewNotebook.GetPageCount() == 0:
self.OpenNewPlotView()
def OnMenu_viewRenameMenuItem(self, evt):
currentPlotViewIndex = self.viewNotebook.GetSelection()
currentName = self.viewNotebook.GetPageText(currentPlotViewIndex)
d = wx.TextEntryDialog(self, "Enter new name", "Rename plot view", currentName, wx.OK | wx.CANCEL)
d.ShowModal()
d.Destroy()
self.viewNotebook.SetPageText(currentPlotViewIndex, d.GetValue())
# Help menu
def OnMenu_aboutMenuItem(self, evt):
aboutInfo = wx.AboutDialogInfo()
aboutInfo.SetName("pyWave")
aboutInfo.SetDescription("a waveform viewer")
aboutInfo.AddDeveloper("<NAME>")
aboutInfo.SetVersion("alpha")
wx.AboutBox(aboutInfo)
# Toolbar buttons map to menu items
def OnTool_fileOpenTool(self, evt):
self.OnMenu_fileOpenMenuItem(evt)
def OnTool_fileReloadTool(self, evt):
self.OnMenu_fileReloadMenuItem(evt)
def OnTool_fileCloseTool(self, evt):
self.OnMenu_fileCloseMenuItem(evt)
def OnTool_viewNewTool(self, evt):
self.OnMenu_viewNewMenuItem(evt)
def OnTool_viewCloseTool(self, evt):
self.OnMenu_viewCloseMenuItem(evt)
def open_data_file(file_path):
print DataFile.__subclasses__()
for subclass in DataFile.__subclasses__():
if subclass.test(file_path):
return subclass(file_path)
class FileAlreadyOpen(Exception):
pass
class MyApp(wx.App):
def OnInit(self):
# Display the frame
self.frame = MyMainFrame(None)
self.frame.Center()
self.frame.Show(1)
return True
def main():
import sys
from optparse import OptionParser
usage = "usage: %prog [options] <file>"
parser = OptionParser(usage=usage)
parser.add_option("-d", "--debug",
action="store_true", dest="verbose", default=False,
help="print debug output")
(options, args) = parser.parse_args()
app = MyApp()
app.MainLoop()
<file_sep>import wx
import wx.xrc as xrc
class SearchCtrlXmlHandler(xrc.XmlResourceHandler):
def __init__(self):
xrc.XmlResourceHandler.__init__(self)
# Standard styles
self.AddWindowStyles()
# Custom styles
def CanHandle(self, node):
return self.IsOfClass(node, 'wxSearchCtrl')
# Process XML parameters and create the object
def DoCreateResource(self):
assert self.GetInstance() is None
w = wx.SearchCtrl(self.GetParentAsWindow(),
self.GetID(),
self.GetText('value'),
self.GetPosition(),
self.GetSize(),
self.GetStyle())
self.SetupWindow(w)
return w<file_sep>import wx
import numpy as np
# Chaco imports
from enthought.enable.wx_backend.api import Window
#from enthought.enable.wx.image import Window
from enthought.chaco.api import ArrayPlotData, Plot, OverlayPlotContainer
from enthought.chaco.api import PlotLabel, Legend
from enthought.chaco.api import add_default_grids, add_default_axes
from enthought.chaco.api import create_line_plot, create_scatter_plot
from enthought.chaco.tools.api import PanTool, ZoomTool, LegendTool
from enthought.chaco.tools.api import TraitsTool, DragZoom
from circuit import SignalClient
class Trace(SignalClient):
"""Class representing a single trace in a PlotView"""
def __init__(self, signal, plot, color, sweep_point):
SignalClient.__init__(self)
self.signal = signal
self.signal.add_client(self)
self.sweep_point = sweep_point
self._plot = plot
self._group = None # trace is part of a group? (sweeps)
sweep_set = sweep_point._sweep_set
if len(sweep_set._points) > 1:
suffix = " ["
for i, name in enumerate(sweep_set._names):
suffix += "%s=%g" % (name, sweep_point[i]) + ", "
suffix = suffix[:-2] + "]"
else:
suffix = ""
prefix = "[%d] " % signal.get_circuit().get_data_source().number
self.label = prefix + signal.full_name + suffix
self.index_label = signal.get_independent_signal().full_name + suffix
self.color = color
self.line_style = 'solid'
self.line_width = 1
self.marker = 'circle'
self.marker_size = 10
self.marker_color = color
def update_signal(self, signal):
print "update_signal:", signal
def set_label(self, label):
self.label = label
def get_indices(self):
return self.signal.get_independent_signal().get_values(self.sweep_point)
def get_values(self):
return self.signal.get_values(self.sweep_point)
def destroy(self):
self.signal.remove_client(self)
class TraceGroup(list):
"""Class representing a set of Traces (sweeped, for example)"""
def __init__(self, *args, **kwargs):
self.traces = []
def rainbow(self):
# colour traces in this group as rainbow
pass
class PlotView(wx.Panel):
def __init__(self, parent, id=-1, **kwargs):
wx.Panel.__init__(self, parent, id=id, **kwargs)
self.statusBar = self.GetTopLevelParent().statusBar
self.container = OverlayPlotContainer(padding = 50, fill_padding = True,
bgcolor = "lightgray", use_backbuffer=True)
self.legend = Legend(component=self.container, padding=10, align="ur")
#self.legend.tools.append(LegendTool(self.legend, drag_button="right"))
self.container.overlays.append(self.legend)
self.plot_window = Window(self, component=self.container)
self.container.tools.append(TraitsTool(self.container))
self.firstplot = True
self._palette = ['red', 'blue', 'green', 'purple', 'yellow']
self._current_palette_index = 0
self._traces = []
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.plot_window.control, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
def _next_color(self):
if self._current_palette_index == len(self._palette):
self._current_palette_index = 0
self._current_palette_index += 1
return self._palette[self._current_palette_index - 1]
def add_plot(self, signal, sweep_point=None):
## waveform = signal.get_waveform()
## x = waveform.get_x()[-1][0].tolist()
## y = np.real(waveform.get_y()[0].tolist())
if sweep_point is None:
sweep_point = signal.get_circuit()._sweep_set._points[0]
trace = Trace(signal, self, self._next_color(), sweep_point)
x_name = trace.index_label
y_name = trace.label
x = trace.get_indices()
y = trace.get_values()
if type(y[0]) == complex:
y = [value.real for value in y]
#print x_name, len(x)
#print y_name, len(y)
#print x
#print y
if self.firstplot:
self.plotdata = ArrayPlotData()
self.plotdata.set_data(x_name, x)
self.plotdata.set_data(y_name, y)
plot = Plot(self.plotdata)
plot.padding = 1
plot.bgcolor = "white"
plot.border_visible = True
add_default_grids(plot)
add_default_axes(plot)
plot.tools.append(PanTool(plot))
# The ZoomTool tool is stateful and allows drawing a zoom
# box to select a zoom region.
zoom = CustomZoomTool(plot)
plot.overlays.append(zoom)
# The DragZoom tool just zooms in and out as the user drags
# the mouse vertically.
dragzoom = DragZoom(plot, drag_button="right")
plot.tools.append(dragzoom)
#~ # Add a legend in the upper right corner, and make it relocatable
#~ self.legend = Legend(component=plot, padding=10, align="ur")
#~ self.legend.tools.append(LegendTool(self.legend, drag_button="right"))
#~ plot.overlays.append(self.legend)
#~ self.legend.plots = {}
self.firstplot = False
self.container.add(plot)
self.plot = plot
else:
self.plotdata.set_data(x_name, x)
self.plotdata.set_data(y_name, y)
#self.plot.plot(self.plotdata.list_data())
pl = self.plot.plot( (x_name, y_name), name=trace.label, type="line",
color=trace.color, line_style=trace.line_style,
line_width=trace.line_width, marker=trace.marker,
marker_size=trace.marker_size, marker_color=trace.marker_color)
self.legend.plots[trace.label] = pl
self.Refresh()
#~ def ChangeCursor(self, event):
#~ self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_BULLSEYE))
#~ def UpdateStatusBar(self, event):
#~ if event.inaxes:
#~ x, y = event.xdata, event.ydata
#~ self.statusBar.SetStatusText(( "x= " + str(x) +
#~ " y=" + str(y) ),
#~ 0)
class CustomZoomTool(ZoomTool):
def __init__(self, component=None):
ZoomTool.__init__(self, component, tool_mode="range", always_on=True,
drag_button='right')
def normal_right_down(self, event):
self._original_x = event.x
self._original_y = event.y
return ZoomTool.normal_right_down(self, event)
def selecting_mouse_move(self, event):
if abs(event.x - self._original_x) > abs(event.y - self._original_y):
self.axis = 'index'
else:
self.axis = 'value'
return ZoomTool.selecting_mouse_move(self, event)
<file_sep>from pywave.datasource import DataFile
from pywave.circuit import Circuit, Subcircuit, Signal
import numpy as np
import pywave.signaltype as type
from HSpiceOutput import HSPICEOutput
from HSpiceOutput import type as htype
types = {}
types[htype.t] = type.t
types[htype.f] = type.f
types[htype.V] = type.V
types[htype.C] = type.T
types[htype.Vm] = type.Vm
types[htype.Vr] = type.Vr
types[htype.Vi] = type.Vi
types[htype.Vp] = type.Vp
types[htype.I] = type.I
types[htype.Im] = type.Im
types[htype.Ir] = type.Ir
types[htype.Ii] = type.Ii
types[htype.Ip] = type.Ip
types[htype.I1] = type.I
types[htype.S11] = type.Spar
types[htype.S21] = type.Spar
types[htype.S12] = type.Spar
types[htype.S22] = type.Spar
types[htype.Spar] = type.Spar
types[htype.Noise] = type.default
types[htype.param] = type.default
types[htype.Stability] = type.default
types[htype.NF] = type.default
types[htype.Zin] = type.default
types[htype.Power] = type.Power
types[htype.sweep] = type.default
class HSPICEFile(DataFile):
"""Class to represent binary (post=1) HSPICE output (ac0, tr0, hb0, ss0, ls0, ...)"""
@staticmethod
def extensions():
raise NotImplementedError
@staticmethod
def test(file_path):
try:
hspo = HSPICEOutput(file_path, True)
del hspo
return True
except:
return False
def __init__(self, file_path):
DataFile.__init__(self, file_path)
self.hspo = HSPICEOutput(self.file_path, True)
# build hierarcical signal list
self.circuit = Circuit(self.hspo.title, self)
indep_name = self.hspo.signalnames[0]
indep_type = self.hspo.get_signal_type(0)
indep_signal = Signal(indep_name, indep_name, None, indep_type)
indep_signal._set_parent(self.circuit)
for i in range(len(self.hspo.get_signal_names()[1:])):
signal_name = self.hspo.get_signal_name(i+1)
signal_type = types[self.hspo.get_signal_type(i+1)]
currentSubckt = self.circuit
if signal_type == type.V:
node_name = signal_name[2:-1]
levels = node_name.split(".")
if len(levels) > 1:
for level in levels[:-1]:
try:
currentSubckt = currentSubckt[level]
except:
newSubckt = Subcircuit(level)
currentSubckt.add_subcircuit(newSubckt)
currentSubckt = newSubckt
signal = Signal("v(" + levels[-1] + ")", signal_name, indep_signal, signal_type)
else:
signal = Signal(signal_name, signal_name, indep_signal, signal_type)
currentSubckt.add_signal(signal)
def get_sweep_names(self):
return self.hspo.get_sweep_names()
def get_sweep_data(self):
return self.hspo.get_sweep_data()
def get_data(self, signal):
signal_index = self.hspo.get_signal_index(signal.full_name)
return self.hspo.get_signal(signal_index)
# def reload(self):
# self.hspo = HSPICEOutput(self.file_path, True)
# indep_name = self.hspo.signalnames[0]
# indep_type = self.hspo.get_signal_type(0)
# indep_signal = Signal(indep_name, indep_name, None, indep_type)
# indep_signal._set_parent(self.circuit)
# for i in range(len(self.hspo.get_signal_names()[1:])):
# signal_name = self.hspo.get_signal_name(i+1)
# signal_type = types[self.hspo.get_signal_type(i+1)]
# print signal_name
# self.circuit.update_clients()
<file_sep>from pywave.datasource import DataFile
from pywave.circuit import Circuit, Subcircuit, Signal, SweepSet
from pywave import signaltype
from nport import citi
class CITIFile(DataFile):
"""Class to represent CITI files"""
@staticmethod
def extensions():
raise NotImplementedError
@staticmethod
def test(file_path):
try:
citifile = citi.read(file_path)
del citifile
return True
except:
return False
def __init__(self, file_path):
DataFile.__init__(self, file_path)
self._citi = citi.read(self.file_path, True)
self.rootItem = None
# build hierarchical signal list
self.circuit = Circuit("CITI", self)
indep_name = "frequency"
indep_type = signaltype.f
indep_signal = Signal(indep_name, indep_name, None, indep_type)
indep_signal._set_parent(self.circuit)
for i in range(self._citi.ports):
for j in range(self._citi.ports):
signal_name = "S(%d,%d)" % (i + 1, j + 1)
signal_type = signaltype.Spar
signal = Signal(signal_name, signal_name, indep_signal, signal_type)
signal._data_source_info['port1'] = i + 1
signal._data_source_info['port2'] = j + 1
self.circuit.add_signal(signal)
def get_data(self, signal):
if signal.get_independent_signal() is None:
return [self._citi.freqs.tolist()]
else:
port1 = signal._data_source_info['port1']
port2 = signal._data_source_info['port2']
return [self._citi.get_parameter(port1, port2).tolist()]
<file_sep>#!/bin/env python
from setuptools import setup
from subprocess import Popen, PIPE
# write the git version to pywave/version.py
# based on version.py by <NAME> <<EMAIL>>
# http://dcreager.net/2010/02/10/setuptools-git-version-numbers/
try:
p = Popen(['git', 'describe', '--abbrev=4'],
stdout=PIPE, stderr=PIPE)
p.stderr.close()
line = p.stdout.readlines()[0]
version = line.strip()[1:]
except:
print("A problem occured while trying to run git. "
"Version information is unavailable!")
version = 'unknown'
version_file = open('pywave/version.py', 'w')
version_file.write("__version__ = '%s'\n" % version)
version_file.close()
setup(
name='pywave',
version=version,
packages=['pywave', 'pywave.plugins'],
scripts=['scripts/pywave'],
package_dir={'pywave': 'pywave'},
package_data={'pywave': ['pywave.xrc', 'images/*.png']},
requires=['wx', 'enthought.enable', 'enthought.chaco', 'numpy', 'nport'],
provides=['pywave'],
#test_suite='nose.collector',
author="<NAME>",
author_email="<EMAIL>",
description="A modular waveform viewer",
license="GPL",
keywords="HSPICE touchstone citi",
url="https://github.com/bmachiel/pywave",
)
<file_sep>import os
class DataSource(object):
"""Base class for sources that hold waveform data"""
def __init__(self):
self.circuit = None
self.name = None
self.number = None
def get_sweep_names(self):
"""Return a list of the names of the sweep variables"""
return []
def get_sweep_data(self):
"""Return all combinations of sweep variables"""
return [[]]
def get_data(self, name):
"""Return an ..."""
raise NotImplementedError
def get_circuit(self):
"""Return the top level circuit"""
return self.circuit
class DataFile(DataSource):
"""Base class for files that hold waveform data"""
@staticmethod
def extensions():
"""Return a regex that matches the filename extensions supported by this class"""
raise NotImplementedError
@staticmethod
def test(filename):
"""Test whether the given file is supported by this class"""
raise NotImplementedError
def __init__(self, file_path):
DataSource.__init__(self)
self.file_path = os.path.abspath(file_path)
self.file_date = os.path.getmtime(self.file_path)
self.name = os.path.basename(file_path)
def changed(self):
"""Test whether the file has changed since it was last loaded"""
return os.path.getmtime(self.file_path) != self.file_date
def reload(self):
"""Reload the file from disk and update all plots"""
new_datafile = type(self)(self.file_path)
new_circuit = new_datafile.get_circuit()
self.circuit.update(new_circuit)
self.file_date = os.path.getmtime(self.file_path)
self.circuit.update_clients()
<file_sep>
try:
from version import __version__
except ImportError:
__version__ = 'unknown (package not built using setuptools)'
import circuit
import datasource
import plot
import plugins
import pywave
import signaltype
import xh_searchctrl
<file_sep>#!/bin/sh
PYTHONPATH=$PWD/pywave:$PYTHONPATH XRCEDPATH=$PWD/xrced xrced pywave/pywave.xrc
<file_sep>import signaltype
import numpy as np
class Circuit(dict):
def __init__(self, title, data_source):
dict.__init__(self)
self.name = title
self._data_source = data_source
self._subcircuits = []
self._signals = []
self._opened = True
self.tree_item_id = None
self.selected = None
self._sweep_set = None
self._filter_regex = ''
def add_subcircuit(self, subcircuit):
self._subcircuits.append(subcircuit)
self[subcircuit.name] = subcircuit
subcircuit._set_parent(self)
def add_signal(self, signal):
self._signals.append(signal)
self[signal.name] = signal
signal._set_parent(self)
def get_data_source(self):
return self._data_source
def get_subcircuits(self):
return self._subcircuits
def get_signal(self, full_name):
separator = '.'
levels = full_name.split(".")
return NotImplementedError
def get_signals(self):
return self._signals
def update(self, new_circuit):
"""Update this circuit to the data in new_circuit"""
old_data_source = self._data_source
self._data_source = new_datafile
self._data_source.number = new_circuit._data_source.number
self.update_sweep_set(new_circuit.get_sweep_set())
self.update_subcircuit(new_circuit)
def update_sweep_set(self, new_sweep_set):
pass
def update_subcircuit(self, new_subcircuit):
"""Update the given circuit with the new data held in new_circuit"""
for new_subckt in new_circuit.get_subcircuits():
try:
subckt = circuit[new_subckt.name]
self.update_subcircuit(subckt, new_subckt)
except KeyError:
circuit.add_subcircuit(new_subckt)
# TODO: remove subcircuits that have disappeared
for new_signal in new_circuit.get_signals():
try:
signal = circuit[new_signal.name]
signal._values = {}
except KeyError:
circuit.add_signal(new_signal)
# TODO: remove signals that have disappeared
def update_clients(self):
for subcircuit in self.get_subcircuits():
subcircuit.update_clients()
for signal in self.get_signals():
signal.update_clients()
def is_open(self):
return self._opened
def open(self):
self._opened = True
def close(self):
self._opened = False
class Child(object):
def __init__(self):
self._parent = None
def get_circuit(self):
try:
return self.get_parent().get_circuit()
except AttributeError:
return self.get_parent()
def get_parent(self):
return self._parent
def _set_parent(self, parent):
self._parent = parent
class Subcircuit(Circuit, Child):
def __init__(self, name):
Circuit.__init__(self, name, None)
Child.__init__(self)
self._parent = None
self._opened = False
class Signal(Child):
"""Class representing a dependent or independent signal"""
def __init__(self, name, full_name, independent_signal,
signal_type=signaltype.default):
Child.__init__(self)
self.name = name
self.full_name = full_name
self._indep_signal = independent_signal
self._values = {}
# self._waveform = None
self._traces = []
self.type = signal_type
self._data_source_info = {}
# dict where the DataSource can store information
self._clients = []
# list of clients referencing this Signal
def __repr__(self):
return "%s %s" % (self.__class__, self.full_name)
def _load_data(self):
data_source = self.get_circuit().get_data_source()
if self.get_circuit()._sweep_set is None:
sweep_names = data_source.get_sweep_names()
sweep_data = data_source.get_sweep_data()
self.get_circuit()._sweep_set = SweepSet(sweep_names)
for point in sweep_data:
self.get_circuit()._sweep_set.add_point(point)
data = data_source.get_data(self)
for i, row in enumerate(data):
sweep_point = self.get_circuit()._sweep_set._points[i]
self._values[sweep_point] = row
def add_client(self, client):
"""Make this Signal aware of client"""
self._clients.append(client)
def remove_client(self, client):
"""Remove client from the list of clients this Signal is aware of"""
self._clients.remove(client)
def is_referenced(self):
return len(self._clients) > 0
def update_clients(self):
"""Make all clients update this signal"""
if self._clients:
self._load_data()
for client in self._clients:
client.update_signal(self)
def get_independent_signal(self):
"""Return the independent signal this signal is a function of"""
return self._indep_signal
def get_values(self, sweep_point=None):
if self.get_circuit()._sweep_set is None:
self._load_data()
if sweep_point is None:
sweep_point = self.get_circuit()._sweep_set._points[0]
if sweep_point not in self._values:
self._load_data()
return self._values[sweep_point]
class SignalClient(object):
"""Class representing objects that reference a Signal"""
def __init__(self):
pass
def update_signal(self, signal):
"""Do whatever is needed when a signal has changed"""
raise NotImplementedError
class SweepSet(object):
"""Class representing a set of sweeped parameters"""
def __init__(self, names):
self._names = tuple(names)
self._points = []
def add_point(self, values):
assert len(values) == len(self._names)
self._points.append(SweepPoint(self, values))
def find_point(self, values):
for point in self._points:
if tuple(point) == values:
return point
return None
def __repr__(self):
repr = " ".join("%8s" % name for name in self._names) + "\n"
repr += "+--------+" + ("-" * 8 + "+") * (len(self._names) - 1)
for point in self._points:
repr += "\n" + " ".join("%8g" % value for value in point)
return repr
class SweepPoint(tuple):
"""Class representing one sample in a SweepSet"""
def __new__(cls, sweep_set, *args, **kwargs):
return tuple.__new__(cls, *args, **kwargs)
def __init__(self, sweep_set, *args, **kwargs):
self._sweep_set = sweep_set
def __eq__(self, other):
return self._sweep_set == other._sweep_set and tuple.__eq__(self, other)
def __ne__(self, other):
return self._sweep_set != other._sweep_set or tuple.__ne__(self, other)
# def __repr__(self):
# return "%s %s in %s" % (self.__class__, tuple.__repr__(self), self._sweep_set)
def __repr__(self):
repr = " ".join("%8s" % name for name in self._sweep_set._names) + "\n"
repr += "+--------+" + ("-" * 8 + "+") * (len(self._sweep_set._names) - 1)
repr += "\n" + " ".join("%8g" % value for value in self)
return repr
#~ class Waveform(self):
#~ def __init__(self):
<file_sep>
class SignalUnit():
def __init__(self, symbol, description):
self.symbol = symbol
self.description = description
def __repr__(self):
return self.symbol
s = SignalUnit('s', 'seconds')
Hz = SignalUnit('Hz', 'hertz')
V = SignalUnit('V', 'volts')
A = SignalUnit('A', 'amperes')
degC = SignalUnit('deg C', 'degrees Celcius')
deg = SignalUnit('deg', 'degrees')
rad = SignalUnit('rad', 'radians')
Ohm = SignalUnit('Ohm', 'ohms')
W = SignalUnit('W', 'watts')
none = SignalUnit('', 'no unit')
<file_sep>import unit
class SignalType():
def __init__(self, symbol, description, unit):
self.symbol = symbol
self.description = description
self.unit = unit
def unit(self):
return self.unit
def __repr__(self):
return self.symbol
t = SignalType('t', 'time', unit.s)
f = SignalType('f', 'frequency', unit.Hz)
V = SignalType('V', 'voltage', unit.V)
T = SignalType('C', 'degrees Celcius', unit.degC)
Vm = SignalType('Vm', 'magnitude of voltage', unit.V)
Vr = SignalType('Vr', 'real part of voltage', unit.V)
Vi = SignalType('Vi', 'imaginary part of voltage', unit.V)
Vp = SignalType('Vp', 'phase of voltage', unit.deg)
I = SignalType('I', 'current', unit.A)
Im = SignalType('Im', 'magnitude of current', unit.A)
Ir = SignalType('Ir', 'real part of current', unit.A)
Ii = SignalType('Ii', 'imaginary part of current', unit.A)
Ip = SignalType('Ip', 'phase of current', unit.deg)
Spar = SignalType('S', 'S parameter', unit.none)
#Noise = SignalType('Noise', 'noise', unit.none)
#param = SignalType('param', 'parameter', unit.none)
#Stability = SignalType('Stability', 'stability factor', unit.none)
#NF = SignalType('NF', 'noise figure', unit.none)
#Zin = SignalType('Zin', 'input impedance', unit.Ohm)
Power = SignalType('Power', 'power', unit.W)
#sweep = SignalType('sweep', 'sweep variable', unit.none)
default = SignalType('', 'default', unit.none)
<file_sep>from pywave.datasource import DataFile
from pywave.circuit import Circuit, Subcircuit, Signal, SweepSet
from pywave import signaltype
from nport import touchstone
class TouchstoneFile(DataFile):
"""Class to represent Touchstone files"""
@staticmethod
def extensions():
raise NotImplementedError
@staticmethod
def test(file_path):
try:
tstone = touchstone.read(file_path)
del tstone
return True
except:
return False
def __init__(self, file_path):
DataFile.__init__(self, file_path)
self._touchstone = touchstone.read(self.file_path, True)
self.rootItem = None
# build hierarchical signal list
self.circuit = Circuit("Touchstone", self)
indep_name = "frequency"
indep_type = signaltype.f
indep_signal = Signal(indep_name, indep_name, None, indep_type)
indep_signal._set_parent(self.circuit)
for i in range(self._touchstone.ports):
for j in range(self._touchstone.ports):
signal_name = "S(%d,%d)" % (i + 1, j + 1)
signal_type = signaltype.Spar
signal = Signal(signal_name, signal_name, indep_signal, signal_type)
signal._data_source_info['port1'] = i + 1
signal._data_source_info['port2'] = j + 1
self.circuit.add_signal(signal)
def get_data(self, signal):
if signal.get_independent_signal() is None:
return [self._touchstone.freqs.tolist()]
else:
port1 = signal._data_source_info['port1']
port2 = signal._data_source_info['port2']
return [self._touchstone.get_parameter(port1, port2).tolist()]
<file_sep>import os
from pywave.datasource import DataFile
from pywave.circuit import Circuit, Subcircuit, Signal, SweepSet
import pywave.signaltype as type
from pycircuit.post.cds import PSFResultSet
types = {}
class PSFFile(DataFile):
"""Class to represent Cadence PSF files"""
@staticmethod
def extensions():
raise NotImplementedError
@staticmethod
def test(file_path):
dir, file = os.path.split(file_path)
try:
prs = PSFResultSet(dir)
del prs
return True
except:
return False
def __init__(self, file_path):
DataFile.__init__(self, file_path)
dir, file = os.path.split(file_path)
self.name = dir.split(os.sep)[-1]
self.prs = PSFResultSet(dir)
self.rootItem = None
# build hierarchical signal list
self.circuit = Circuit(self.name, self)
self.circuit._sweep_set = SweepSet([])
self.circuit._sweep_set.add_point([])
for key in self.prs.keys():
currentSubckt = Subcircuit(key)
self.circuit.add_subcircuit(currentSubckt)
result = self.prs[key]
top_circuit = currentSubckt
for name in result.keys():
currentSubckt = top_circuit
levels = str(name).split(".")
if len(levels) > 1:
for level in levels[:-1]:
try:
currentSubckt = currentSubckt[level]
except:
newSubckt = Subcircuit(level)
currentSubckt.add_subcircuit(newSubckt)
currentSubckt = newSubckt
signal_full_name = str(key) + "___" + str(name)
try:
indep_type = types['unknown']
except KeyError:
indep_type = type.default
indep_name = 'unknown'
indep_full_name = signal_full_name + "____XValues"
indep_signal = Signal(indep_name, indep_full_name, None, indep_type)
indep_signal._set_parent(self.circuit)
try:
signal_type = types['unknown']
except KeyError:
signal_type = type.default
signal = Signal(levels[-1], signal_full_name, indep_signal, signal_type)
indep_signal._data_source_info['values'] = signal
signal._data_source_info['set'] = key
currentSubckt.add_signal(signal)
def get_sweep_names(self):
return []
def get_sweep_data(self):
return [[]]
def get_data(self, signal):
if signal.get_independent_signal() is None:
values = signal._data_source_info['values']
dep_signal = values
else:
dep_signal = signal
set = dep_signal._data_source_info['set']
result = self.prs[set]
waveform = result[dep_signal.name]
if signal.get_independent_signal() is None:
return waveform.get_x()
else:
return waveform.get_y()
|
477a95449de0497891baf6e261ea29abbc73fbb7
|
[
"Python",
"Shell"
] | 15
|
Python
|
Milateef/pywave
|
801f9491bd825738b07c963db7e9f3e5f7438978
|
0bc721e5e352154cad92ff5145303441aa7eaeec
|
refs/heads/master
|
<file_sep>import React from 'react'
import {
FaTwitter,
FaStackOverflow,
FaInstagram,
FaEnvelope,
FaGithub,
} from 'react-icons/fa'
import Avatar from '../Avatar'
import ExternalLink from '../ExternalLink'
// import background from '../../images/background.jpg'
import './AboutMe.scss'
const Name = () => <h2 className="name"><NAME></h2>
const Detail = () => (
<div className="detail">
<div>A Software Engineer</div>
<div className="of-what">
<span className="and">&</span> <span>Infinite Learner</span>
</div>
</div>
)
const SocialLink = ({ url, children }) => (
<ExternalLink url={url}>{children}</ExternalLink>
)
const Social = () => (
<div className="social">
<SocialLink url="https://twitter.com/dance2die">
<FaTwitter />
</SocialLink>
<SocialLink url="https://github.com/dance2die">
<FaGithub />
</SocialLink>
<SocialLink url="https://www.instagram.com/dance2die/">
<FaInstagram />
</SocialLink>
<SocialLink url="https://stackoverflow.com/users/4035/sung-m-kim?tab=profile">
<FaStackOverflow />
</SocialLink>
<SocialLink url="mailto:<EMAIL>?Subject=Hey">
<FaEnvelope />
</SocialLink>
</div>
)
function AboutMe() {
return (
<div className="about-me">
<Avatar />
<Name />
<Detail />
<Social />
</div>
)
}
export default AboutMe
<file_sep>/**
* SEO component that queries for data with
* Gatsby's useStaticQuery React hook
*
* See: https://www.gatsbyjs.org/docs/use-static-query/
*/
import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import { useStaticQuery, graphql } from 'gatsby'
import favicon16 from '../images/favicon16.png'
import favicon32 from '../images/favicon32.png'
import seoImage from '../images/avatar-seo.jpg'
function SEO({ lang = 'en', keywords = [] }) {
// const { site } = useStaticQuery(
// graphql`
// query {
// site {
// siteMetadata {
// defaultTitle: title
// titleTemplate
// defaultDescription: description
// url
// twitterUsername
// }
// }
// }
// `
// )
const seo = {
title: `Sung M. Kim (aka dance2die)'s Home Page`,
description: `Hi, I am <NAME> (a.k.a dance2die) and this is my home 🏡 page.
You can find out about my background and interests as well as contact info.`,
image: seoImage,
url: 'https://sungkim.co',
titleTemplate: '%s · aka dance2die',
twitterUsername: '@dance2die',
keywords: 'sung m. kim, dance2die, home',
}
// https://www.gatsbyjs.org/docs/add-seo-component/
return (
<Helmet
htmlAttributes={{ lang }}
titleTemplate={seo.titleTemplate}
link={[
{
rel: 'icon',
type: 'image/png',
sizes: '16x16',
href: `${favicon16}`,
},
{
rel: 'icon',
type: 'image/png',
sizes: '32x32',
href: `${favicon32}`,
},
]}
>
<meta name="description" content={seo.description} />
<meta name="keywords" content={seo.keywords} />
<meta name="image" content={seo.image} />
<meta property="og:url" content={seo.url} />
<meta property="og:title" content={seo.title} />
<meta property="og:description" content={seo.description} />
<meta property="og:image" content={seo.image} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:creator" content={seo.twitterUsername} />
<meta name="twitter:title" content={seo.title} />
<meta name="twitter:description" content={seo.description} />
<meta name="twitter:image" content={seo.image} />
</Helmet>
)
}
// SEO.defaultProps = {
// lang: `en`,
// meta: [],
// keywords: [],
// description: null,
// title: null,
// image: null,
// }
// SEO.propTypes = {
// lang: PropTypes.string,
// meta: PropTypes.arrayOf(PropTypes.object),
// keywords: PropTypes.arrayOf(PropTypes.string),
// description: PropTypes.string,
// title: PropTypes.string.isRequired,
// image: PropTypes.string,
// }
export default SEO
<file_sep>import React from 'react'
import { OutboundLink } from 'gatsby-plugin-google-analytics'
function ExternalLink({ url, ...rest }) {
// For rel="noreferrer", refer to
// https://developers.google.com/web/tools/lighthouse/audits/noopener#recommendations
return (
<OutboundLink
href={url}
target="_blank"
rel="noopener noreferrer"
{...rest}
/>
)
}
export default ExternalLink
<file_sep>import Avatar from './Image'
export default Avatar
<file_sep>import React from 'react'
import Layout from '../components/layout'
// import Image from '../components/image'
import SEO from '../components/seo'
import AboutMe from '../components/AboutMe'
import Description from '../components/Description'
const IndexPage = () => (
<Layout>
<SEO keywords={['<NAME>', 'dance2die', 'home']} />
<AboutMe />
<Description />
</Layout>
)
export default IndexPage
<file_sep>import React from 'react'
import PropTypes from 'prop-types'
export default function HTML(props) {
return (
<html {...props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{props.headComponents}
<script
dangerouslySetInnerHTML={{
__html: `
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0]
if (d.getElementById(id)){ return }
js = d.createElement(s); js.id = id
js.onload = function(){
// remote script has loaded
}
js.src = 'https://koala-snippet.s3.us-east-2.amazonaws.com/bundle.prod.min.js'
fjs.parentNode.insertBefore(js, fjs)
}(document, 'script', 'koala-script'))
`,
}}
/>
</head>
<body {...props.bodyAttributes}>
{props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: props.body }}
/>
{props.postBodyComponents}
</body>
</html>
)
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
|
cb7ee6a9c2a3d7079ed1d8c3d14ee1ce06c03734
|
[
"JavaScript"
] | 6
|
JavaScript
|
dance2die/landing-page-v4
|
307ca088f45ccecbfb70b3cd14be03ac4d822db4
|
da7dc3d907edcd670c1dca71e0158c398827eafb
|
refs/heads/master
|
<repo_name>changsin/MapApp<file_sep>/MapApp/Model/LocData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Runtime.Serialization;
namespace MapApp.Model
{
[KnownType(typeof(MapApp.Model.LocData))]
[DataContractAttribute]
public class LocData
{
/// Latitude: +-90
[XmlAttribute("lat")]
// [DataMember()]
public double Latitude { get; set; }
/// Longitude: +-180
[XmlAttribute("lon")]
//[DataMember()]
public double Longitude { get; set; }
[XmlArray("ImageDataList")]
//[DataMember()]
public List<ImageData> ImageDataList { get; set; }
public LocData(double lat, double lon)
{
Latitude = lat;
Longitude = lon;
}
public LocData(double lat, double lon, List<ImageData> list)
{
Latitude = lat;
Longitude = lon;
if (null != list)
{
ImageDataList = new List<ImageData>(list);
}
}
public LocData() { }
}
}
<file_sep>/MapApp/Model/LocDataList.cs
using System.Collections.ObjectModel;
namespace MapApp.Model
{
public class LocDataList : ObservableCollection<LocData>
{
public LocDataList()
: base()
{
}
}
}
<file_sep>/MapApp/ShapeHelper.cs
using System;
using System.Collections.Generic;
using Windows.Foundation;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace MapApp
{
internal static class ShapeHelper
{
/// <summary>
/// Calculates all the line segments that are within a rectangle. We need to clip the line
/// segment into pieces as really large lines end up becoming blurry due to rendering
/// limitations in Windows 8.
/// </summary>
/// <param name="pixels">List of points that form a path.</param>
/// <param name="rect">Rectangle to clip lines to.</param>
/// <returns>A list of Line segments clipped to the rectangle.</returns>
public static List<Polyline> IntersectionLines(IList<Point> pixels, Rect rect, Brush stroke, double strokeThickness, DoubleCollection dashSequence)
{
var lines = new List<Polyline>();
var topLeft = new Point(rect.Left, rect.Top);
var topRight = new Point(rect.Right, rect.Top);
var bottomRight = new Point(rect.Right, rect.Bottom);
var bottomLeft = new Point(rect.Left, rect.Bottom);
for (int i = 0; i < pixels.Count - 1; i++)
{
var points = new PointCollection();
if (rect.Contains(pixels[i]))
{
points.Add(pixels[i]);
}
var p = Intersection(pixels[i], pixels[i + 1], topLeft, topRight);
if (p.HasValue)
{
points.Add(p.Value);
}
p = Intersection(pixels[i], pixels[i + 1], topRight, bottomRight);
if (p.HasValue)
{
points.Add(p.Value);
}
p = Intersection(pixels[i], pixels[i + 1], bottomRight, bottomLeft);
if (p.HasValue)
{
points.Add(p.Value);
}
p = Intersection(pixels[i], pixels[i + 1], bottomLeft, topLeft);
if (p.HasValue)
{
points.Add(p.Value);
}
if (rect.Contains(pixels[i + 1]))
{
points.Add(pixels[i + 1]);
}
if (points.Count >= 2)
{
var line = new Polyline()
{
Stroke = stroke,
StrokeThickness = strokeThickness,
StrokeDashCap = PenLineCap.Round,
Points = points
};
if (dashSequence != null)
{
DoubleCollection dc = new DoubleCollection();
foreach (var d in dashSequence)
{
dc.Add(d);
}
line.StrokeDashArray = dc;
}
lines.Add(line);
}
}
return lines;
}
/// <summary>
/// Calculates intersection - if any - of two lines
/// </summary>
/// <param name="otherLine"></param>
/// <returns>Intersection or null</returns>
/// <remarks>Taken from http://tog.acm.org/resources/GraphicsGems/gemsii/xlines.c </remarks>
public static Point? Intersection(Point start, Point end, Point start2, Point end2)
{
var a1 = end.Y - start.Y;
var b1 = start.X - end.X;
var c1 = end.X * start.Y - start.X * end.Y;
// Compute r3 and r4.
var r3 = a1 * start2.X + b1 * start2.Y + c1;
var r4 = a1 * end2.X + b1 * end2.Y + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 != 0 && r4 != 0 && Math.Sign(r3) == Math.Sign(r4))
{
return null; // DONT_INTERSECT
}
/* Compute a2, b2, c2 */
var a2 = end2.Y - start2.Y;
var b2 = start2.X - end2.X;
var c2 = end2.X * start2.Y - start2.X * end2.Y;
/* Compute r1 and r2 */
var r1 = a2 * start.X + b2 * start.Y + c2;
var r2 = a2 * end.X + b2 * end.Y + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 != 0 && r2 != 0 && Math.Sign(r1) == Math.Sign(r2))
{
return (null); // DONT_INTERSECT
}
/* Line segments intersect: compute intersection point.
*/
var denom = a1 * b2 - a2 * b1;
if (denom == 0)
{
return null; //( COLLINEAR );
}
var offset = denom < 0 ? -denom / 2 : denom / 2;
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
var num = b1 * c2 - b2 * c1;
var x = (num < 0 ? num - offset : num + offset) / denom;
num = a2 * c1 - a1 * c2;
var y = (num < 0 ? num - offset : num + offset) / denom;
return new Point(x, y);
}
}
}
<file_sep>/MapApp/Model/ImageData.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace MapApp.Model
{
public class ImageData
{
public string ImageString { get; set; }
public ImageData(string dataString)
{
ImageString = dataString;
}
public ImageData() { }
}
}
<file_sep>/MapApp/CustomMapPolygon.cs
using Bing.Maps;
using System.Collections.Generic;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Shapes;
namespace MapApp
{
public class CustomMapPolygon : Panel
{
#region Private Properties
private Map _map;
private LocationCollection _locations;
private Polygon _basePolygon;
#endregion
#region Constructor
public CustomMapPolygon(Map map)
{
_map = map;
this.Width = _map.ActualWidth;
this.Height = _map.ActualHeight;
_locations = new LocationCollection();
//Update position when map view or size changes
_map.ViewChanged += (s, e) =>
{
UpdatePolygon();
};
_map.SizeChanged += (s, e) =>
{
this.Width = _map.ActualWidth;
this.Height = _map.ActualHeight;
UpdatePolygon();
};
}
#endregion
#region Public Properties
public LocationCollection Locations
{
get { return _locations; }
set
{
_locations = value;
UpdatePolygon();
}
}
private Brush _fill;
public Brush Fill
{
get
{
return _fill;
}
set
{
_fill = value;
UpdatePolygon();
}
}
private Brush _stroke;
public Brush Stroke
{
get
{
return _stroke;
}
set
{
_stroke = value;
UpdatePolygon();
}
}
private DoubleCollection _dashSequence;
public DoubleCollection StrokeDashArray
{
get { return _dashSequence; }
set
{
_dashSequence = value;
UpdatePolygon();
}
}
private double _strokeThickness;
public double StrokeThickness
{
get
{
return _strokeThickness;
}
set
{
_strokeThickness = value;
UpdatePolygon();
}
}
#endregion
#region Private Methods
private void UpdatePolygon()
{
this.Children.Clear();
IList<Point> pixels = new List<Point>();
//Convert Locations into pixels
if (_map.TryLocationsToPixels(_locations, pixels))
{
var points = new PointCollection();
foreach (var p in pixels)
{
points.Add(p);
}
var _basePolygon = new Polygon();
_basePolygon.StrokeDashCap = PenLineCap.Round;
_basePolygon.Fill = _fill;
_basePolygon.Points = points;
this.Children.Add(_basePolygon);
//Close the polygon
var px = new List<Point>();
px.AddRange(pixels);
px.Add(pixels[0]);
//Calculate Line segments
var lines = ShapeHelper.IntersectionLines(px, new Rect(0, 0, _map.ActualWidth, _map.ActualHeight), Stroke, StrokeThickness, StrokeDashArray);
foreach (var l in lines)
{
this.Children.Add(l);
}
}
}
#endregion
}
}<file_sep>/MapApp/MainPage.xaml.cs
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.Linq;
//using System.Runtime.InteropServices.WindowsRuntime;
//using Windows.Foundation;
//using Windows.Foundation.Collections;
//using Windows.UI.Xaml;
//using Windows.UI.Xaml.Controls;
//using Windows.UI.Xaml.Controls.Primitives;
//using Windows.UI.Xaml.Data;
//using Windows.UI.Xaml.Input;
//using Windows.UI.Xaml.Media;
//using Windows.UI.Xaml.Navigation;
//using Bing.Maps;
//using BingMapsRESTService.Common.JSON;
//using Windows.Devices.Geolocation;
//using System.Runtime.Serialization.Json;
//using System.Threading.Tasks;
using Bing.Maps;
using BingMapsRESTService.Common.JSON;
using Windows.Devices.Geolocation;
using Windows.Storage;
using Windows.Storage.Streams; // IRandomAccessStream
using Windows.Storage.Pickers; // PickerLocationId
using Windows.UI.Xaml.Media.Imaging; // BitmapImage
using Windows.Foundation; // Point
using System.Collections.Generic; //List
using Windows.Data.Xml.Dom;
using System.IO;
using System;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using MapApp.Model;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MapApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private MapShapeLayer m_routeLayer;
private MapLayer m_mapLayer;
private List<BitmapImage> listImage = new List<BitmapImage>();
public MainPage()
{
this.InitializeComponent();
myMap.RightTapped += myMap_RightTapped;
m_routeLayer = new MapShapeLayer();
myMap.ShapeLayers.Add(m_routeLayer);
m_mapLayer = new MapLayer();
myMap.Children.Add(m_mapLayer);
MapShapeLayer shapeLayer = new MapShapeLayer();
MapPolygon polygon = new MapPolygon();
polygon.Locations = new LocationCollection() { new Bing.Maps.Location(44, -107), new Bing.Maps.Location(44, -110), new Bing.Maps.Location(46, -110), new Bing.Maps.Location(46, -107) };
polygon.FillColor = Windows.UI.Colors.Red;
shapeLayer.Shapes.Add(polygon);
myMap.ShapeLayers.Add(shapeLayer);
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
// Every time the load route button is clicked we want to clear the previous
// route.
m_mapLayer.Children.Clear();
m_routeLayer.Shapes.Clear();
//playRouteBtn.Content = PlayRouteText;
//mRoutePlaybackTimer.Stop();
//LoadGPXFile();
loadLocData();
}
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
var fileSavePicker = new FileSavePicker();
fileSavePicker.FileTypeChoices.Add(".tmm", new List<string>{ ".tmm", ".gpx" });
fileSavePicker.DefaultFileExtension = ".tmm";
//fileSavePicker.SuggestedFileName = “i08.jpg”;
fileSavePicker.SettingsIdentifier = "savePicker";
var fileToSave = await fileSavePicker.PickSaveFileAsync();
if (null != fileToSave)
{
IRandomAccessStream sessionRandomAccess = await fileToSave.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream sessionOutputStream = sessionRandomAccess.GetOutputStreamAt(0);
// var serializer = new XmlSerializer(typeof(ObservableCollection<LocData>), new Type[] { typeof(LocData) });
var serializer = new XmlSerializer(typeof(ObservableCollection<LocData>), new Type[] { typeof(LocData) });
//Using DataContractSerializer , look at the cat-class
//var sessionSerializer = new DataContractSerializer(typeof(List<object>), new Type[] { typeof(T) });
//sessionSerializer.WriteObject(sessionOutputStream.AsStreamForWrite(), _data);
ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
var locDataList = await viewModel.GetLocData();
//Using XmlSerializer , look at the Dog-class
serializer.Serialize(sessionOutputStream.AsStreamForWrite(), locDataList);
sessionRandomAccess.Dispose();
await sessionOutputStream.FlushAsync();
sessionOutputStream.Dispose();
}
}
private async void loadLocData()
{
ViewModel.MainViewModel viewModel = new ViewModel.MainViewModel();
var gpxRoutePoints = await viewModel.LoadLocData("test");
MapPolyline route = new MapPolyline();
route.Color = Windows.UI.Colors.Red;
route.Width = 5;
route.Locations = gpxRoutePoints;
m_routeLayer.Shapes.Add(route);
Pushpin startPin = new Pushpin();
startPin.Text = "S";
m_mapLayer.Children.Add(startPin);
MapLayer.SetPosition(startPin, gpxRoutePoints[0]);
Pushpin endPin = new Pushpin();
endPin.Text = "E";
m_mapLayer.Children.Add(endPin);
MapLayer.SetPosition(endPin, gpxRoutePoints[gpxRoutePoints.Count - 1]);
LocationRect bestRouteView = new LocationRect(gpxRoutePoints);
myMap.SetView(bestRouteView);
}
/// <summary>
/// Displays a FilePicker to the user and after they select the file
/// it is loaded and displayed on the map.
/// </summary>
private async void LoadGPXFile()
{
FileOpenPicker fileOpenPicker = new FileOpenPicker();
fileOpenPicker.FileTypeFilter.Add(".gpx");
StorageFile gpxFile = await fileOpenPicker.PickSingleFileAsync();
if (gpxFile != null)
{
XmlDocument gpxDoc = await XmlDocument.LoadFromFileAsync(gpxFile);
XmlNodeList pointNodes = gpxDoc.GetElementsByTagName("trkpt");
LocationCollection gpxRoutePoints = new LocationCollection();
foreach (IXmlNode node in pointNodes)
{
XmlNamedNodeMap attributes = node.Attributes;
try
{
IXmlNode latitudeAttribute = attributes.GetNamedItem("lat");
double latitude = double.Parse(latitudeAttribute.InnerText);
IXmlNode longitudeAttribute = attributes.GetNamedItem("lon");
double longitude = double.Parse(longitudeAttribute.InnerText);
gpxRoutePoints.Add(new Location(latitude, longitude));
}
catch
{
// Most likely if these values don't exist in the file it is
// formatted incorrectly or corrupt. In a real app we would
// display some kind of error message to the user.
}
}
MapPolyline route = new MapPolyline();
route.Color = Windows.UI.Colors.Red;
route.Width = 5;
route.Locations = gpxRoutePoints;
m_routeLayer.Shapes.Add(route);
Pushpin startPin = new Pushpin();
startPin.Text = "S";
m_mapLayer.Children.Add(startPin);
MapLayer.SetPosition(startPin, gpxRoutePoints[0]);
Pushpin endPin = new Pushpin();
endPin.Text = "E";
m_mapLayer.Children.Add(endPin);
MapLayer.SetPosition(endPin, gpxRoutePoints[gpxRoutePoints.Count - 1]);
LocationRect bestRouteView = new LocationRect(gpxRoutePoints);
myMap.SetView(bestRouteView);
//mMarkerPin.Visibility = Visibility.Collapsed;
//mMapLayer.Children.Add(mMarkerPin);
}
}
/// <summary>
/// Converts a byte-array (containing a bitmap) to an ImageSource that can be assigned to an Image-control.
/// </summary>
/// <param name="arrImageBytes">The byte-array with the picture.</param>
/// <param name="intOffset">If the array contains a header that needs to be stripped off, pass its length here, otherwise pass 0.</param>
/// <returns>An ImageSource object that can be assigned to i.e. an Image-control.</returns>
public static async Task<BitmapImage> BitmapImageFromByteArray(
byte[] arrImageBytes,
int intOffset
)
{
//Exit, if the array is empty
if (arrImageBytes == null || arrImageBytes.GetUpperBound(0) < 1) return null;
System.IO.MemoryStream msImage = new System.IO.MemoryStream();
msImage.Write(arrImageBytes, intOffset, arrImageBytes.Length - intOffset);
////WinForms:
//System.Drawing.Image img = System.Drawing.Image.FromStream(msImage);
IRandomAccessStream randomAccessStream = msImage.AsRandomAccessStream();
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(randomAccessStream);
return bitmapImage;
//BitmapImage bitmapImage = new BitmapImage();
//bitmapImage.DecodePixelHeight = 100;// decodePixelHeight.Text;
//bitmapImage.DecodePixelWidth = 100;// decodePixelWidth.Text;
//WPF:
//return new BmpBitmapDecoder(msImage, BitmapCreateOptions.None, BitmapCacheOption.Default).Frames[0];
}
async void myMap_RightTapped(object sender, Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
{
const int C_WIDTH = 100;
const int C_HEIGHT = 100;
Point ptClick = e.GetPosition(myMap);
Location locClick = new Location();
Location locRT = new Location();
Location locLB = new Location();
Location locRB = new Location();
myMap.TryPixelToLocation(ptClick, out locClick);
myMap.TryPixelToLocation(new Point(ptClick.X + C_WIDTH, ptClick.Y), out locRT);
myMap.TryPixelToLocation(new Point(ptClick.X, ptClick.Y + C_HEIGHT), out locLB);
myMap.TryPixelToLocation(new Point(ptClick.X + C_WIDTH, ptClick.Y + C_HEIGHT), out locRB);
var locations = new LocationCollection()
{
locClick,
locLB,
locRB,
locRT,
};
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".gif");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".bmp");
var files = await openPicker.PickMultipleFilesAsync();
if (null != files)
{
foreach (StorageFile file in files)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
//// convert into byte array then Int64 string to save into xml file
//DataReader dataReader = new DataReader(fileStream);
//await dataReader.LoadAsync((uint)fileStream.Size);
//byte[] imageBytes = new byte[dataReader.UnconsumedBufferLength];
//dataReader.ReadBytes(imageBytes);
//string imageString = Convert.ToBase64String(imageBytes);
// to convert back to byte array
//Convert.FromBase64String(imageString);
/*
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(fileStream);
var transform = new global::Windows.Graphics.Imaging.BitmapTransform();
var pixelData = await decoder.GetPixelDataAsync(decoder.BitmapPixelFormat,
decoder.BitmapAlphaMode,
transform,
Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation,
Windows.Graphics.Imaging.ColorManagementMode.ColorManageToSRgb);
var pixels = pixelData.DetachPixelData();
*/
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = 100;// decodePixelHeight.Text;
bitmapImage.DecodePixelWidth = 100;// decodePixelWidth.Text;
await bitmapImage.SetSourceAsync(fileStream);
//Image1.Source = bitmapImage;
ImageBrush ibrush = new ImageBrush();
ibrush.Stretch = Stretch.Fill;
//Windows.UI.Xaml.Media.Imaging.BitmapImage image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("C:\\Users\\changlee\\pictures\\rope.jpg"));
// Windows.UI.Xaml.Media.Imaging.BitmapImage image = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new System.Uri("ms-appx:///Assets/MonumentValley.jpg", System.UriKind.Absolute));
ibrush.ImageSource = bitmapImage;
//Image image = new Image();
//image.Source = bitmapImage;
//image.Width = 100;
//image.Height = 100;
//image.Margin = new Thickness((double)point.X, (double)point.Y, 0, 0);
//myMap.Children.Add(image);
var cp = new CustomMapPolygon(myMap)
{
Locations = locations,
Fill = ibrush, //fillBrush,
Stroke = new SolidColorBrush(Color.FromArgb(150, 0, 255, 0)),
StrokeThickness = 5,
StrokeDashArray = new DoubleCollection { 2, 4 }
};
myMap.Children.Add(cp);
}
}
}
}
async protected override void OnNavigatedTo(NavigationEventArgs e)
{
Geolocator geo = new Geolocator();
geo.DesiredAccuracy = PositionAccuracy.Default;
var currentPosition = await geo.GetGeopositionAsync();
Bing.Maps.Location loc = new Bing.Maps.Location()
{
Latitude = currentPosition.Coordinate.Latitude,
Longitude = currentPosition.Coordinate.Longitude
};
TimeSpan timeSpan = new TimeSpan(0, 0, 2);
myMap.SetView(
loc, // location
13, // zoom level
timeSpan);//true); //show animations)
}
private async void ShowMessage(string message)
{
MessageDialog dialog = new MessageDialog(message);
await dialog.ShowAsync();
}
private async Task<Response> GetResponse(Uri uri)
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
var response = await client.GetAsync(uri);
using (var stream = await response.Content.ReadAsStreamAsync())
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
return ser.ReadObject(stream) as Response;
}
}
private void ClearMap()
{
myMap.Children.Clear();
m_routeLayer.Shapes.Clear();
//Clear the geocode results ItemSource
GeocodeResults.ItemsSource = null;
//Clear the route instructions
RouteResults.DataContext = null;
}
private void ClearMapBtn_Click(object sender, RoutedEventArgs e)
{
ClearMap();
}
private async void GeocodeBtn_Click(object sender, RoutedEventArgs e)
{
ClearMap();
string query = GeocodeTbx.Text;
if (!string.IsNullOrWhiteSpace(query))
{
//Create the request URL for the Geocoding service
Uri geocodeRequest = new Uri(
string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}",
query, myMap.Credentials));
//Make a request and get the response
Response r = await GetResponse(geocodeRequest);
if (r != null &&
r.ResourceSets != null &&
r.ResourceSets.Length > 0 &&
r.ResourceSets[0].Resources != null &&
r.ResourceSets[0].Resources.Length > 0)
{
LocationCollection locations = new LocationCollection();
int i = 1;
foreach (BingMapsRESTService.Common.JSON.MyLocation l
in r.ResourceSets[0].Resources)
{
//Get the location of each result
Bing.Maps.Location location = new Bing.Maps.Location(l.MyPoint.Coordinates[0], l.MyPoint.Coordinates[1]);
//Create a pushpin each location
Pushpin pin = new Pushpin()
{
Tag = l.Name,
Text = i.ToString()
};
i++;
//Add a tapped event that will display the name of the location
pin.Tapped += (s, a) =>
{
var p = s as Pushpin;
ShowMessage(p.Tag as string);
};
//Set the location of the pushpin
MapLayer.SetPosition(pin, location);
//Add the pushpin to the map
myMap.Children.Add(pin);
//Add the coordinates of the location to a location collection
locations.Add(location);
}
//Set the map view based on the location collection
myMap.SetView(new LocationRect(locations));
//Pass the results to the item source of the GeocodeResult ListBox
GeocodeResults.ItemsSource = r.ResourceSets[0].Resources;
}
else
{
ShowMessage("No Results found.");
}
}
else
{
ShowMessage("Invalid Geocode Input.");
}
}
private void GeocodeResultSelected(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
if (listBox.SelectedItems.Count > 0)
{
//Get the Selected Item
var item = listBox.Items[listBox.SelectedIndex] as BingMapsRESTService.Common.JSON.MyLocation;
//Get the items location
Bing.Maps.Location location = new Bing.Maps.Location(item.MyPoint.Coordinates[0], item.MyPoint.Coordinates[1]);
//Zoom into the location
myMap.SetView(location, 18);
}
}
private async void RouteBtn_Click(object sender, RoutedEventArgs e)
{
ClearMap();
string from = FromTbx.Text;
string to = ToTbx.Text;
if (!string.IsNullOrWhiteSpace(from))
{
if (!string.IsNullOrWhiteSpace(to))
{
//Create the Request URL for the routing service
Uri routeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0={0}&wp.1={1}&rpo=Points&key={2}", from, to, myMap.Credentials));
//Make a request and get the response
Response r = await GetResponse(routeRequest);
if (r != null &&
r.ResourceSets != null &&
r.ResourceSets.Length > 0 &&
r.ResourceSets[0].Resources != null &&
r.ResourceSets[0].Resources.Length > 0)
{
Route route = r.ResourceSets[0].Resources[0] as Route;
//Get the route line data
double[][] routePath = route.RoutePath.Line.Coordinates;
LocationCollection locations = new LocationCollection();
for (int i = 0; i < routePath.Length; i++)
{
if (routePath[i].Length >= 2)
{
locations.Add(new Bing.Maps.Location(routePath[i][0],
routePath[i][1]));
}
}
//Create a MapPolyline of the route and add it to the map
MapPolyline routeLine = new MapPolyline()
{
Color = Colors.Blue,
Locations = locations,
Width = 5
};
m_routeLayer.Shapes.Add(routeLine);
//Add start and end pushpins
Pushpin start = new Pushpin()
{
Text = "S",
Background = new SolidColorBrush(Colors.Green)
};
myMap.Children.Add(start);
MapLayer.SetPosition(start,
new Bing.Maps.Location(route.RouteLegs[0].ActualStart.Coordinates[0],
route.RouteLegs[0].ActualStart.Coordinates[1]));
Pushpin end = new Pushpin()
{
Text = "E",
Background = new SolidColorBrush(Colors.Red)
};
myMap.Children.Add(end);
MapLayer.SetPosition(end,
new Bing.Maps.Location(route.RouteLegs[0].ActualEnd.Coordinates[0],
route.RouteLegs[0].ActualEnd.Coordinates[1]));
//Set the map view for the locations
myMap.SetView(new LocationRect(locations));
//Pass the route to the Data context of the Route Results panel
RouteResults.DataContext = route;
}
else
{
ShowMessage("No Results found.");
}
}
else
{
ShowMessage("Invalid 'To' location.");
}
}
else
{
ShowMessage("Invalid 'From' location.");
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
int count = myMap.Children.Count;
}
private async void writeGPX(string filename)
{
XmlDocument doc = new XmlDocument();
//StorageFile file = await StorageFile.GetFileFromPathAsync(filename);
//using (Stream fileStream = await file.OpenStreamForWriteAsync())
//{
// fileStream.as
// doc.SaveToFileAsync(fileStream);
//}
//StorageFile file = await StorageFile.GetFileFromPathAsync(filename);
//using (StorageStreamTransaction fileStream = await file.OpenTransactedWriteAsync())
//{
// doc.Save(fileStream);
//}
//Windows.Storage.StorageFolder sf = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync("GPX", CreationCollisionOption.OpenIfExists);
Windows.Storage.StorageFolder sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("GPX", CreationCollisionOption.OpenIfExists);
StorageFile st = await sf.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
await doc.SaveToFileAsync(st);
}
/*
//public static async Task<byte[]> GetPhotoBytesAsync(BitmapImage bitmapImage)
public static async Task<byte[]> GetPhotoBytesAsync(WriteableBitmap writeableBitmap)
{
if (writeableBitmap == null)
return new byte[0] { };
//WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapImage);
//Stream stream = writeableBitmap.PixelBuffer.AsStream();
byte[] pixels = new byte[stream.Length];
await stream.ReadAsync(pixels, 0, pixels.Length);
ConvertToRGBA(writeableBitmap.PixelHeight, writeableBitmap.PixelWidth, pixels);
InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
var imsWriter = ims.OpenWrite();
await Task.Factory.StartNew(() => stream.CopyTo(imsWriter));
stream.Flush();
stream.Dispose();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, ims);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)writeableBitmap.PixelWidth, (uint)writeableBitmap.PixelHeight, 96, 96, pixels);
await encoder.FlushAsync();
stream = ims.OpenRead();
byte[] pixeBuffer = new byte[ims.Size];
await stream.ReadAsync(pixeBuffer, 0, pixeBuffer.Length);
stream.Flush();
stream.Dispose();
ims.GetOutputStreamAt(0).FlushAsync().Start();
return pixeBuffer;
}
*/
private static void ConvertToRGBA(int pixelHeight, int pixelWidth, byte[] pixels)
{
if (pixels == null)
return;
int offset;
for (int row = 0; row < (uint)pixelHeight; row++)
{
for (int col = 0; col < (uint)pixelWidth; col++)
{
offset = (row * (int)pixelWidth * 4) + (col * 4);
byte B = pixels[offset];
byte G = pixels[offset + 1];
byte R = pixels[offset + 2];
byte A = pixels[offset + 3];
// convert to RGBA format for BitmapEncoder
pixels[offset] = R; // Red
pixels[offset + 1] = G; // Green
pixels[offset + 2] = B; // Blue
pixels[offset + 3] = A; // Alpha
}
}
}
}
class MemoryRandomAccessStream : IRandomAccessStream
{
private Stream m_InternalStream;
public MemoryRandomAccessStream(Stream stream)
{
this.m_InternalStream = stream;
}
public MemoryRandomAccessStream(byte[] bytes)
{
this.m_InternalStream = new MemoryStream(bytes);
}
public IInputStream GetInputStreamAt(ulong position)
{
this.m_InternalStream.Seek((long)position, SeekOrigin.Begin);
return this.m_InternalStream.AsInputStream();
}
public IOutputStream GetOutputStreamAt(ulong position)
{
this.m_InternalStream.Seek((long)position, SeekOrigin.Begin);
return this.m_InternalStream.AsOutputStream();
}
public ulong Size
{
get { return (ulong)this.m_InternalStream.Length; }
set { this.m_InternalStream.SetLength((long)value); }
}
public bool CanRead
{
get { return true; }
}
public bool CanWrite
{
get { return true; }
}
public IRandomAccessStream CloneStream()
{
throw new NotSupportedException();
}
public ulong Position
{
get { return (ulong)this.m_InternalStream.Position; }
}
public void Seek(ulong position)
{
this.m_InternalStream.Seek((long)position, 0);
}
public void Dispose()
{
this.m_InternalStream.Dispose();
}
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
{
var inputStream = this.GetInputStreamAt(0);
return inputStream.ReadAsync(buffer, count, options);
}
public Windows.Foundation.IAsyncOperation<bool> FlushAsync()
{
var outputStream = this.GetOutputStreamAt(0);
return outputStream.FlushAsync();
}
public Windows.Foundation.IAsyncOperationWithProgress<uint, uint> WriteAsync(IBuffer buffer)
{
var outputStream = this.GetOutputStreamAt(0);
return outputStream.WriteAsync(buffer);
}
}
}
<file_sep>/MapApp/Model/ILocDataProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapApp.Model
{
public interface ILocDataProvider
{
Task<LocDataList> GetData();
}
}
<file_sep>/MapApp/ViewModel/MainViewModel.cs
using GalaSoft.MvvmLight;
using MapApp.Model;
using System.Threading.Tasks;
using Bing.Maps;
using BingMapsRESTService.Common.JSON;
namespace MapApp.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
ILocDataProvider m_locDataProvider = null;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
////}
m_locDataProvider = new LocDataProvider();
}
public async Task<LocDataList> GetLocData()
{
return await m_locDataProvider.GetData();
}
public async Task<LocationCollection> LoadLocData(string loc)
{
LocationCollection gpxRoutePoints = new LocationCollection();
var dataList = await m_locDataProvider.GetData();
foreach(LocData data in dataList)
{
gpxRoutePoints.Add(new Location(data.Latitude, data.Longitude));
}
return gpxRoutePoints;
}
}
}<file_sep>/MapApp/Model/LocDataProvider.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapApp.Model
{
/// <summary>
/// Latitude: +-90
/// Longitude: +-180
/// </summary>
public class LocDataProvider : ILocDataProvider
{
public async Task<LocDataList> GetData()
{
// Simulate by returning a data item
var data = new LocDataList();
data.Add(new LocData(10, -100));
List<ImageData> list = new List<ImageData>();
list.Add(new ImageData("TestingTestg"));
data.Add(new LocData(11, -101, list));
data.Add(new LocData(12, -102));
data.Add(new LocData(13, -103));
data.Add(new LocData(14, -104));
data.Add(new LocData(15, -105));
return data;
}
}
}
|
73a2b62d0575bf062eb1f6c1898db2a5816c444a
|
[
"C#"
] | 9
|
C#
|
changsin/MapApp
|
c03efd73ce8bddf494dcebec571a4534e99d4f36
|
dff786422281330924a687564f6c0465fe97998d
|
refs/heads/main
|
<repo_name>Michael734999/weather-journal-app<file_sep>/README.md
<h1>Weather Journal App</h1>
<p>
I created this weather journal app using:
<ul>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>NodeJS</li>
<li>Express and Async JavaScript</li>
</ul>
This was a very fun project and I enjoyed building it a lot. I gained a lot of new skills throughout the build of this project.
</p>
<p>
The port that I used on the server-end was port 3000.
</p><file_sep>/weather/js/app.js
// API Key and baseURL
const apiKey = '&appid=fd3b8e623e6b404f3f9ef2e2d9d6018e&units=metric';
const apiUrl = 'https://api.openweathermap.org/data/2.5/weather?q=';
// Get date
let d = new Date();
let newDate = d.getMonth() + 1 + '.' + d.getDate() + '.' + d.getFullYear();
// Get UI elements by id
const generate = document.getElementById('generate');
// add eventListener to content
generate.addEventListener('click', generateWeather);
// Create the function generate weather using nested promises
function generateWeather(e) {
let zip = document.getElementById('zip').value;
let feelings = document.getElementById('feelings').value;
getWeather(apiUrl, zip, apiKey)
.then(function(dataW) {
console.log(dataW);
postData('/weather', {
name: dataW.name,
mainly: dataW.weather[0].main,
date: newDate,
temp: dataW.main.temp,
feelings: feelings,
})
// .then(() => {
// getData('/all')
// })
.then(() => {
updateUI()
});
});
}
// Get the data from weather api
const getWeather = async(apiUrl, zip, apiKey) => {
const response = await fetch(apiUrl + zip + apiKey);
try {
const dataW = await response.json();
console.log(dataW);
return dataW;
} catch (error) {
console.log("error", error);
}
};
// POST ROUTE
const postData = async(url = '', data = {}) => {
// console.log(data);
const response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
try {
const newData = await response.json();
console.log(newData);
return newData;
} catch (error) {
console.log("error", error);
}
}
// GET ROUT
const getData = async(url = '') => {
const request = await fetch(url);
try {
const all = await request.json();
// console.log(all);
// return all;
} catch (error) {
console.log("error", error);
}
};
// Update the UI
const updateUI = async() => {
const request = await fetch('/all');
try {
const allData = await request.json();
document.getElementById('name').innerHTML = 'Weather in ' + allData['name'];
document.getElementById('mainly').innerHTML = 'Mainly ' + allData['mainly'];
document.getElementById('date').innerHTML = 'Date: ' + allData['date'];
document.getElementById('temp').innerHTML = allData['temp'] + '°C';
document.getElementById('content').innerHTML = 'I feel ' + allData['feelings'];
} catch (error) {
console.log("error", error);
}
};
|
141dc8046198ebbd7daa6159f44e47351e9a32a5
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Michael734999/weather-journal-app
|
96c9f802a6a6df43bd57fa624c5b400ce73c3832
|
e90f4b44e16bb540a6c1568eda098380dc0a17ad
|
refs/heads/master
|
<file_sep># each key can hold multiple values
# combine dictionaries with lists
dict_list = {
"Bob": [1,2,3],
"Chuck": [4,5,6],
"Stan": [7,8,9]
}
print(dict_list["Bob"])
print(dict_list["Bob"][1])
# combine dictionaries with other dictionaries
dict_list = {
"Bob": {'age': 67, 'state': 'OK'},
"Chuck": {'age': 56, 'state': 'AL'},
"Stan": {'age': 60, 'state': 'MO'}
}
print(dict_list['Chuck']['age'])
print(dict_list['Chuck']['state'], dict_list['Bob']['state'])
<file_sep>import md5
# salt means adding some characters randomly and concatenating those with the password before run through md5
# first, import the module, then generate a salt randomly:
import os, binascii
salt = binascii.b2a_hex(os.urandom(15))
# The function called os.urandom() returns a string of bytes. The number of bytes is equal to the parameter provided.
# This string isn't a normal alphanumeric string, so we turn it into a string using the function b2a_hex(),
# which will turn the value into a normal alphanumeric string. This new random string will be our salt.
username = request.form['username']
email = request.form['email']
password = request.form['password']
salt = binascii.b2a_hex(os.urandom(15))
hashed_pw = md5.new(password + salt).hexdigest()
insert_query = "INSERT INTO users (username, email, password, salt, created_at, updated_at)
VALUES (:username, :email, :hashed_pw, :salt, NOW(), NOW())"
query_data = { 'username': username, 'email': email, 'hashed_pw': hashed_pw, 'salt': salt}
mysql.query_db(insert_query, query_data)
# when authenticating:
email = request.form['email']
password = request.form['password']
user_query = "SELECT * FROM users WHERE users.email = :email LIMIT 1"
query_data = {'email': email}
user = mysql.query_db(user_query, query_data)
if len(user) != 0:
encrypted_password = md5.new(password + user[0]['salt']).hexdigest()
if user[0]['password'] == encrypted_password:
# this means we have a successful login!
else:
# invalid password!
else:
# invalid email!
<file_sep>const Product = require('../models/product');
module.exports = {
getProducts(req, res, next) {
Product.fetchAll()
.then(products => {
res.render('shop/product-list', {
prods: products,
pageTitle: 'All Products',
path: '/products'
});
})
.catch(err => console.log(err));
},
getProduct(req, res, next) {
const prodId = req.params.productId;
Product.findById(prodId)
.then((product) => {
res.render('shop/product-detail', {
product: product,
pageTitle: product.title,
path: '/products'
});
})
.catch(err => console.log(err));
},
getIndex(req, res, next) {
Product.fetchAll()
.then(products => {
res.render('shop/index', {
prods: products,
pageTitle: 'Shop',
path: '/'
});
})
.catch(err => console.log(err));
},
getCart(req, res, next) {
req.user
.getCart()
.then(products => {
res.render('shop/cart', {
path: '/cart',
pageTitle: 'Your Cart',
products: products
});
})
.catch(err => console.log(err))
},
postCart(req, res, next) {
const prodId = req.body.productId;
Product.findById(prodId)
.then(product => {
return req.user.addToCart(product);
}).then(result => {
console.log(result);
res.redirect('/cart');
}).catch(err => {
console.log(err);
})
},
postCartDeleteProduct(req, res, next) {
const prodId = req.body.productId;
req.user.deleteItemFromCart(prodId)
.then(result => {
res.redirect('/cart');
})
.catch(err => console.log(err));
},
postOrder(req, res, next) {
let fetchedCart;
req.user.addOrder()
.then(result => {
res.redirect('/orders');
})
.catch(err => console.log(err));
},
getOrders(req, res, next) {
req.user.getOrders()
.then(orders => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders',
orders: orders
});
})
.catch(err => console.log(err));
},
}
<file_sep>
let beegee = {};
const bgProto = Object.getPrototypeOf(beegee);
const objectBase = Object.prototype;
let arr = [];
const arrProto = Object.getPrototypeOf(arr);
const arrayBase = Array.prototype
function Circle(radius) {
this.radius = radius;
}
const circleBase = Circle.prototype;
let c1 = new Circle(1);
let c2 = new Circle(1);
const c1Proto = Object.getPrototypeOf(c1);
const c2Proto = Object.getPrototypeOf(c2);
console.log(bgProto);
console.log(objectBase);
console.log(arrProto);
console.log(arrayBase);
console.log(c1Proto);
console.log(c2Proto);
console.log(circleBase);
const protoEquality = c1Proto === c2Proto;
console.log(protoEquality);
// in order to save memory, we can eliminate the methods from the Object and write them into their prototype, so they are still accessible but no longer take in memory...
Circle.prototype.draw = function() {
console.log("draw");
}
console.log("c1 details: ", c1); // draw method does not show
console.log("the c1 instance keys are: ", Object.keys(c1)); // does not show either
for (let key in c1) { // draw method shows, the loop gets the instance and prototype properties!
console.log("this is a c1 prototype key: ", key);
}
console.log("is draw an instance member? ", c1.hasOwnProperty('draw')); // hasOwnProperty only accesses instance members
// So in JS we have to types of members:
// 1. instance members
// 2. prototype members
// knowing this, and knowing that some members are writeable, we can change the behavior of a member at prototype level like so:
// 1) look at the property descriptor:
const circleProto = Object.getPrototypeOf(circleBase);
console.log(circleProto);
const toStringDescr = Object.getOwnPropertyDescriptor(circleProto, 'toString');
console.log(toStringDescr); // toString is writeable!
// 2) change the behavior by re-writing it and accessing an instance property:
Circle.prototype.toString = function () {
return "Circle has a radius of " + this.radius;
}
console.log(c1.toString()); // it works!!!
// notice the order in which we modify the prototype does not matter, c1 was created before, yet, still captured the prototype's new implementation
<file_sep>pos = "* "
neg = " *"
for i in range (0,8):
if i % 2 == 0:
output = neg * 4
else:
output = pos * 4
print output
<file_sep>const mongoose = require('mongoose');
const User = mongoose.model('User'); //getter
//make methods to control access to our user information - Restful routing
module.exports = {
index(request, response) {
response.render('index');
},
new(request, response) {
response.render('new_user_form')
},
show(request, response) {
//retrieves single resource (User.findOne())
},
create(request,response) {
//create new user in DB with form method='post'
User.create(request.body)
.then(user => {
//send an email to validate or confirm registration
//in this case, just render dashbord
response.redirect(`/users/${user._id}`)
})
.catch(error => {
//handle validation errors
});
},
update(request, response) {},
edit(request, response) {},
destroy(request, response) {},
logout(request, response) {},
};
<file_sep>function numSort(arr){
if (arr.length % 2 > 0){
arr.push(0);
}
var middle = arr.length/2;
var arrR = [];
var arrL = [];
for (i = 0; i < arr.length; i++){
if (i < middle){
arrR.push(arr[i]);
}
else{
arrL.push(arr[i]);
}
}
document.getElementById('result1').innerHTML = arrR;
document.getElementById('result2').innerHTML = arrL;
}
numSort([7,3,5,1,8,9,3,5,6,3,8,4,2]);
<file_sep>def typical(test):
if type(test) == int:
if test >= 100:
print "That's a big number"
else:
print "That's a small number"
elif type(test) == str:
if len(test) >= 50:
print "Long sentence"
else:
print "Short sentnce"
elif type(test) == list:
if len(test) >= 10:
print "Big list"
else:
print "Short list"
else:
print "Nothing to see here!"
typical(['we','can','do','this','cuz','we','are','good','and','we','believe','in','ourselves']) <file_sep>// Classes allow us to create 'blueprints' for objects
// In Angular 2 we use classes a lot. For example to create Components, Services, Directives, Pipes, ...
// How to create a class
class Car {
engineName: string;
gears: number;
private speed: number;
constructor(speed: number) {
this.speed = speed || 0;
}
accelerate(): void {
this.speed++;
}
throttle():void {
this.speed--;
}
getSpeed():void {
console.log(this.speed);
}
static numberOfWheels(): number {
return 4;
}
}
// Instantiate (create) an object from a class
let car = new Car(5);
car.accelerate();
car.getSpeed();
console.log(Car.numberOfWheels());
// public properties engineName and gears are not needed to instantiate in this case because they are not part of the constructor
// speed is required to instantiate because it is part of the constructor. However, it is marked as private thus only accessible from within the class
// an example of this internal access it the getSpeed() method that console.logs it. this method is called a getter
// other methods like accelerate() and throttle() modify the private attribute speed, another example of internal access.
// static methods are called as such because they do not require to be called for an instance of the clas.
// they are available as general functionality and could be used by calling Car.numberOfWheels(), so, directly from the class prototype.<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^test$', views.test) #coming from main/urls.py, if url is first_app/test --as indicated by '^test$', meaning it ends with test, it will go to look for 'test' method in views file --as indicated by views.test
]<file_sep>function fahrenheitToCelsius(fDegrees){
var cDegrees = (5/9) * (fDegrees - 32);
console.log(cDegrees +" degrees celsius");
}
fahrenheitToCelsius(100);<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from .models import Merchandise
# Create your views here.
merchandise = [{
'id' : '1',
'name' : '<NAME>',
'price' : 19.99
},{
'id' : '2',
'name' : '<NAME>',
'price' : 29.99
},{
'id' : '3',
'name' : '<NAME>',
'price' : 4.99
},{
'id' : '4',
'name' : '<NAME>',
'price' : 49.99
}]
def index(request):
context = {
'merch' : merchandise
}
return render(request, 'amadon/index.html', context)
def buy(request, idx):
article_id = idx
article_qty = float(request.POST['qty'])
for article in merchandise:
if article['id'] == article_id:
article_price = article['price']
request.session['quantity'] = int(article_qty)
request.session['total'] = article_qty * article_price
return redirect('/amadon/checkout')
def checkout(request):
if 'rolling_total' not in request.session:
request.session['rolling_total'] = 0
request.session['rolling_total'] += request.session['total']
if 'quantity_total' not in request.session:
request.session['quantity_total'] = 0
request.session['quantity_total'] += request.session['quantity']
return redirect('/amadon/thanks')
def thanks(request):
context = {
'total' : request.session['total'],
'quantity' : request.session['quantity'],
'rolling_total' : request.session['rolling_total'],
'quantity_total' : request.session['quantity_total']
}
return render(request, "amadon/checkout.html", context)
def reset(request):
print "deleting session data"
# for key in request.session.keys():
del request.session['rolling_total']
del request.session['quantity_total']
# del request.session['total']
return redirect('/amadon/checkout')<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-16 22:05
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('created_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 739000))),
('updated_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 739000))),
],
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('created_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 739000))),
('updated_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 739000))),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='books', to='reviews.Author')),
],
),
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField()),
('rating', models.IntegerField()),
('created_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 740000))),
('updated_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 740000))),
('book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='reviews.Book')),
],
),
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('first_name', models.CharField(max_length=255)),
('last_name', models.CharField(max_length=255)),
('email', models.CharField(max_length=255)),
('password', models.CharField(max_length=255)),
('username', models.CharField(max_length=255)),
('created_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 724000))),
('updated_at', models.DateTimeField(default=datetime.datetime(2018, 8, 16, 17, 5, 38, 724000))),
],
),
migrations.AddField(
model_name='review',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to='reviews.User'),
),
]
<file_sep>list_1 = [41,54]
list_2 = [65,23]
print list_1 + list_2
#the following runs top code, til it hits an error then switches to code 2
try:
print "hello"
print list_1[0] + list_2[2]
print "hello"
except IndexError:
print "second block"
print list_1[1] + list_2[1]
print "goodbye"
print [0 for i in range (0,50)]
print [None for i in range (0,50)]
print [i for i in range (0,50)]
i,j = (1,2), [3,4] #here, two variables are being declared at the same time. one is a tuple and the other an object
try:
i[1] = 42 #this is a 'tuple' and these you can't go in and change them.
except TypeError: #can specify kind of error to run except
print "type type type"
except IndexError: #can specify kind of error to run except
print "index index index"
except: #can leave error type open to catch others in case not caught before
print "any kind of error"
num = 1,2,3 #this sets num as a tuple. could have also written num = (1,2,3)
print num
num1, num2, num3 = 4,5,6
print num2
#i,j = 1,2,3 #cannot assign 3 values into 2 variables
#print j
#(i,j) = (1,2,3)
#print j
key, value = "AP" #assigns one letter per variable
print key, value
our_list = ['michael','raphael']
for val in enumerate(our_list): #enumerate returns a list with an automatic counter
print val #what enumerate does is create tuples: (counter, 'value')
for idx,value in enumerate(our_list):
print value, idx
<file_sep>from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def start_index():
return render_template('indexa.html', username = "Dunno")
@app.route('/usersa/<username>')
def show_user_profile(username):
print username
return render_template('usersa.html')
app.run(debug=True)
#this passes data from the client to the server through the URL<file_sep># range creates an iterable of numbers, starting from the lower limit up to and not including the upper limit
r = range(1,4)
for i in r:
print(i)
print('---------')
# for works with any iterable
for l in "abc":
print(l)
print('---------')
# adding steps
for n in range(1,11,2):
print(n)
print('---------')
# for loops with conditions
vowels = 0
consonants = 0
word = "supercalifragilisticexpialidocious is the magic word"
for i in word:
if i.lower() in 'aeiou':
vowels = vowels + 1
elif i == " ":
pass
else:
consonants = consonants + 1
print("There are {} vowels".format(vowels))
print("There are {} consonants".format(consonants))
<file_sep>known_users = ['Alice','Bob','Claire','Emma','Fred','Georgie','Harry']
def check_user(name):
if name in known_users:
print("User recognized")
return (True, name)
else:
print("User not recognized")
return (False, name)
def remove_req(name):
req = input("Would you like to be removed from the list? (Y/N) ").strip().upper()
if req == "Y":
known_users.remove(name)
message = "OK, you have been removed."
print(message)
return (True, name)
else:
message = "OK, you're still on the list."
print(message)
return (False, name)
def add_req(name):
req = input("Would you like to be added to the list? (Y/N) ").strip().upper()
if req == "Y":
known_users.append(name)
message = "OK, you have been added."
print(message)
return(True, name)
else:
message = "OK, goodbye!"
print(message)
return (False, name)
while True:
print("Hi! My name is Travis")
name = input("What is your name? ").strip().capitalize()
user = check_user(name)
if user[0]:
print("Hello {}".format(user[1]))
req = remove_req(name)
else:
print("I haven't met you yet, {}!".format(user[1]))
req = add_req(name)
<file_sep>'use strict';
// proof that js can take in much more arguments than it processes, without breaking
function f(x, y) {
console.log(x, y)
return toArray(arguments);
// function to Array declared later
}
// console.log(f(1, 3, 5, 7, 0, 8));
// convert a list of arguments to an array
function toArray(objects) {
return Array.prototype.slice.call(objects);
}
// using forEach and try-catch
function getPersons(ids) {
const result = [];
ids.forEach(id => {
try {
const person = getPerson(id);
result.push(person);
} catch (error) {
console.log(error);
}
});
return result;
}
function getPerson(id) {
if (id < 0) {
throw new Error ('ID must not be negative: ' + id);
}
return { id: id }; // normally retrieved from db
}
const person_ids = f(1, 4, 0, -6, 9);
console.log(
getPersons(person_ids)
);
<file_sep><!doctype HTML>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>HTML Basics</title>
<meta name="description" content="Description content: The text here describes what the webpage is about. It's what will show up in search results for search engines like
google under the title of the webpage. It's important that this is relevant
to your page and well written!", "width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<>
<h1>Heading for the whole page</h1>
<h2>An important header</h2>
<h3>A header</h3>
<h4>Another header</h4>
<h5>Less important header</h5>
<h6>Least important header</h6>
<p>So yeah, there are six levels for headers and then there's paragraph --this-- for written content.</p>
<p>Next up, images. Images is a standalone tag. You can use this for page elements or for background images. Two required attributes of images are src --source-- and alt --stands for alternate, and used to describe the image in a few words--. When not using CSS, other required attributes are hight and width.</p>
<img src="https://speeddating.tn/wp-content/uploads/2017/09/dating-5-quick-cheap-couples-costumes-for-the-couple-whos-literally-broke-af.jpg" alt="Friendly alien" height=100 width=150>
<p>Another type of tag is a link. Link tags are "a" tags. The openning of the "a" tag requires the href attribute that tells it where the link should go. Inside the openning and closing tags you write the text that'll appear as link.</p>
<a href="https://futurism.com">Explore</a>
<p>Next up, lists. There are ordered and unordered lists. The only difference between them is the "o" or "u" in the tag.</p>
<h4>Things to do if aliens visit you:</h4>
<ol>
<li>Say hello with a hand gesture</li>
<li>Smile</li>
<li>Wait</li>
</ol>
<h4>Signs that aliens trully exist:</h4>
<ul>
<li>Recurring dreams about aliens</li>
<li>Daydream about aliens</li>
<li>Spaceship lands on your roof</li>
</ul>
<p>The other type of tag is the table. Organized in columns and tables, the th tags are for columns and the tr tags are for rows. Each row has td tags for the data. See below!!</p>
<table>
<thead>
<th>Ship</th>
<th>Capacity</th>
<th>Velocity</th>
</thead>
<tbody>
<tr>
<td>ACHP</td>
<td>8 aliens</td>
<td>4000 mph</td>
</tr>
<tr>
<td>Demigod</td>
<td>6 aliens</td>
<td>20000 mph</td>
</tr>
<tr>
<td>Star8</td>
<td>8 aliens</td>
<td>8800 mph</td>
</tr>
<tr>
<td>RoxPK</td>
<td>2 aliens</td>
<td>12000 mph</td>
</tr>
</tbody>
</table>
<p>Tags are responsible for all data exchange between front and back end. They take an input, send it to the back end to be processed and return a response. The form tag two attributes: action and method, that decide where information gets sent and how it gets sent respectively.</p>
<p>Form element can take different shapes. Can contain input, text fiel, label elements, for example. See examples below:</p>
<p>Attributes within the form labels help link them. Example: a "for" attribute in one form will link with an "id" attribute in another form. the "type" attribute designates the type of data for the expected input. Example: text. The "name" attribute is used to send front end data to the back end.</p>
<p>The input form element to capture a user name's name or email address:</p>
<form>
<label for='first name'>First name:</label>
<input type='text' id='first name' name='first name'>
<label for='last name'>Last name:</label>
<input type='text' id='last name' name='last name'>
<label for='email'>email:</label>
<input type='text' id='email' name='email'>
</form>
<p>For a password field:</p>
<form>
<label for='password'>Password:</label>
<input type='<PASSWORD>' id='<PASSWORD>' name='<PASSWORD>'>
<p>For a "choose one" list of options, the type to use is "radio":</p>
<label for='male'>Male</label>
<input type='radio' id='male' name='gender' value='male'>
<label for='female'>Female</label>
<input type='radio' id='female' name='gender' value='female'>
</form>
<p>For drop down menus, the form changes, use "select" tag with "option" child tags:</p>
<form>
<select name='gender'>
<option value='blank'></option>
<option value='male'>Male</option>
<option value='female'>Female</option>
</select>
</form>
<p>For a list from which you can pick multiple choices, use same "lable + input" combination and use type = checkboxes:</p>
<form>
<label for='blue'>Blue</label>
<input type='checkbox' id='blue' name='color' value='blue'>
<label for='red'>Red</label>
<input type='checkbox' id='red' name='color' value='red'>
<label for='yellow'>Yellow</label>
<input type='checkbox' id='yellow' name='color' value='yellow'>
<label for='green'>Green</label>
<input type='checkbox' id='green' name='color' value='green'>
<label for='purple'>Purple</label>
<input type='checkbox' id='purple' name='color' value='purple'>
</form>
<p>To create a text area where user can enter free form text, there's the "textarea" tag:</p>
<form>
<textarea id='freeform'></textarea>
</form>
<p>There is a form to pass data to the back-end without displaying this field on the webpage. Useful for validations and to pass along data. This is the same "input" tag with "hidden" type (not shows of course).</p>
<form>
<input type='hidden' name='id' value='7'>
</form>
<p>To create a submit button, use "input" and "submit" type:</p>
<form>
<input type='submit' value='submit'>
</form>
<p>The "label + input" pair may be coded differently from above to take this shape:</p>
<p>Please register:</p>
<form>
<label>
Name:<input type='text' id='name' name='name'>
</label>
</form>
<p>Semantic coding means using tags that are specific for the element within the website's structure. Example, instead of using more generic div and span, use header, nav, section, article, aside, footer.</p>
</body>
</html><file_sep>our_list = [1,2,3,4,5]
jackson = ['a','b','c',1,2,3,'do','re','mi',True,False]
print(len(jackson))
print(jackson[4])
print(jackson[-4])
print(jackson[3:6])
print(jackson[:len(jackson):2])
print(jackson[::3])
print(jackson[::-1])
# embedded lists
emb_list = [1,2,3,[4,5,6],7,8,9]
print(emb_list[3])
print(emb_list[3][0])
list_of_lists = [[1,2,3],[4,5,6],[7,8,9]]
print(list_of_lists[0])
print(list_of_lists[1])
print(list_of_lists[2])
print(list_of_lists[1][1])
print(list_of_lists[2][1])
# slicing lists
print(list_of_lists[1][1:])<file_sep>
// JS Module -- 6//17/18
// 1- With a function, change all numbers in an array to string 'big'
function numToBig(arr){
for (var i = 0; i < arr.length; i++){
arr[i] = 'big';
}
return arr;
}
numToBig([6,2,-8,4,-5,1]);
// 2- Create a function that prints the lowest value in the array and returns the highest
function hiLo(arr){
max = arr[0];
min = arr[0];
for(var i = 0; i < arr.length; i++){
if(arr[i] < min){
min = arr[i];
}
else if(arr[i] > max){
max = arr[i];
}
}
console.log(min);
return max;
}
hiLo([76,34,56,4,3,56,2,-2,76,4,9]);
// 3- Create a function that prints the second to last value of an array and returns the first odd value
function specific(arr){
console.log(arr[arr.length-2]);
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 !==0){
return arr[i];
}
}
}
specific([6,3,5,7,2]);
// 4- Create a function that doubles the value of all numbers within an array
function doubleUp(arr){
for(var i = 0; i < arr.length; i++){
arr[i] = arr[i]*2;
}
return arr;
}
doubleUp([7,2,-3,5,-7,2]);
// 5- Create a function that replaces the last value with the total of positive numbers within an array
function countPositivesAndReplaceLastValue(arr){
var count = 0;
for(var i = 0; i < arr.length; i++){
if(arr[i] > 0){
count = count + 1;
}
}
arr.pop();
arr.push(count);
return arr;
}
countPositivesAndReplaceLastValue([-6,3,7,-2,7,-2,5,-4]);
// 6- Create a function that prints "That's odd!" when it sees 3 odd numbers in a row and prints "Even more so!" when it sees 3 even numbers in a row
function oddEvener(arr){
var countN = 0;
var countP = 0;
for(var i = 0; i < arr.length; i++){
if(arr[i] < 0){
countN = countN + 1;
countP = 0;
}
else if(arr[i] > 0){
countN = 0;
countP = countP + 1;
}
if(countN >= 3){
console.log("That's odd!");
}
else if(countP >= 3){
console.log("Even more so!");
}
}
}
oddEvener([7,3,-4,7,5,2,5,8,5,3,-6,-8,3,2,2,4,-6,-5,-6,7,-5,-3,-3,-5,7,4,4,6,-6,4,5,-75,54,-5,2,9]);
// 7- Write a function that adds 1 to all odd-indexed numbers within an array, then prints out each element and returns the modified arr
function addOneToOddIndexedNumbersWithinAnArray(arr){
for(var i = 0; i < arr.length; i++){
if(i % 2 !== 0){
arr[i] = arr[i] + 1;
}
console.log(arr[i]);
}
return arr;
}
addOneToOddIndexedNumbersWithinAnArray([7,3,-4,7,5,2,5,-6,4,5,-75,54,-5,2,9]);
// 8- Write a function that replaces each string within an array with it's length
function stringToLength(arr){
for(var i = 0; i < arr.length; i++){
arr[i] = arr[i].length;
}
return arr;
}
stringToLength(['awesome', 'dojo', 'student', 'exam', 9, 'apple']);
// 9- Write a function that, without altering the original array, creates a new one with all indexes replaced with the number 7, except for the first index which remains intact
function increaseBySevenExceptForFirst(arr){
var newArr = [];
newArr.push(arr[0]);
for(var i = 1; i < arr.length; i++){
newArr.push(arr[i]+7);
}
console.log(arr);
return newArr;
}
increaseBySevenExceptForFirst([3,3,-4,7,5,2,5,-6,4,5,-75,54,-5,2,9]);
// 10- Reverse an array without creating a temporary newArr
function swapArr(arr){
for(var i = 0; i < arr.length/2; i++){
var temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
return arr;
}
swapArr([1,2,3,4,5,6,7]);
// 11- Write a function that converts all non-negative values to negative values
function tNeg(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] > 0){
arr[i] = -arr[i];
}
}
return arr;
}
tNeg([3,3,-4,7,5,2,5,-6,4,5,-75,54,-5,2,9]);
// 12- Write a function that prints "yummy" every time a value equals "food", then print "I'm hungry" once
function theHungryArr(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] == 'food'){
console.log('yummy');
}
}
console.log("I'm hungry");
}
theHungryArr(['alchemy', 'magic', 'inhibitor', 'food', 'computer']);
// 13- Swap only even indexed values with their counterparts at the opposite side of the spectrum
function evenIndexBlackHole(arr){
for(var i = 0; i < arr.length/2; i+=2){
var temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
return arr;
}
evenIndexBlackHole([1,2,3,4,5,6,7]);
// 14- Write a function that multiplies all values within the array by a given number
function theGoldenRatio(arr, Y){
for(var i = 0; i < arr.length; i++){
arr[i] = arr[i] * Y;
}
return arr;
}
theGoldenRatio([1,2,3,4,5], 1.618);
<file_sep># filter creates a list of elements which return true in a boolean test
my_list = range(-5,5)
less_than_zero = list(filter(lambda x: x < 0, my_list))
print less_than_zero<file_sep>function personMaker(name, items){
//the below is the same as "const person = { name: name }" this is a syntactic sugar of ES6
//so here we create an object
const person = { name };
//and add attributes on the fly
person.items = items;
//eventually we return the object
return person;
}
const person1 = personMaker('Bob', ['key','sandwich','tickets']);
const person2 = personMaker('Jerry', ['phone','money','ring']);
console.log(person1);
console.log(person2);
//the following function will have two instances interact, with the target being one of them, the one acted on.
//target is defined as, or needs to comform with the following:
// an object, that has a variable called items and 'items' is an array
function take(item, target) {
//make sure that target conforms with the structure its required to have (object with a variable called items which is an array)
//ways in which this can be done:
//1. see if it is an arry... this will return object because arrays are objects
// console.log(typeof target.items);
//2. use 'instanceof' Array object
// console.log(target.items instanceof Array);
//3. best weay is to use method of the Array object 'isArray'
// console.log(Array.isArray(target.items));
//if target.items is an array, we want to do something, so first we guard our function by starting out with an 'if statemet', a guard statement.
// notice that in guard statements we want to capture what it is "not", and let pass everything else:
if(!target || !Array.isArray(target.items)) {
console.log('target does not have items array');
}
for (let index = 0; index < target.items.length; index++) {
if (item === target.items[index]) {
// we found it, do something
// ['item1','item2','item3']
// slice // makes a copy of the content
// splice // removes the element from the array -> this is the one we want in this case
target.items.splice(index,1);
return true;
}
}
return false;
}
take('key', person1);
console.log(person1);
console.log(person2);
// IN PART ii, WE REFACTOR THIS CODE SO WE CAN HAVE PERSON2 TAKE AN ITEM FROM PERSON1 AND HAVE IT APPEAR IN THEIR ITEM LIST<file_sep>class NameField {
constructor(name) {
const field = document.createElement('li');
field.textContent = name;
const nameListHook = document.querySelector('#names');
nameListHook.appendChild(field);
}
}
// this refers to the what calls the method. In the example below, this is referring to the button that, when clicked, calls the method addName()
// this also refers to the instance of the object the code is found in
// to prove it, console.log(this) both in the constructor and in the addName() method and you'll see...
// so, this refers to what is executing the code
// with properties, this makes it available within the class, example, this.names
// with functions too, this makes methods available within the class, example, this.addName()
// class NameGenerator {
// constructor() {
// const btn = document.querySelector('button');
// this.names = ['Max', 'Manu', 'Anna'];
// this.currentName = 0;
// console.log(this);
// btn.addEventListener('click', this.addName);
// }
// addName() {
// console.log(this);
// const name = new NameField(this.names[this.currentName]);
// this.currentName++;
// if (this.currentName >= this.names.length) {
// this.currentName = 0;
// }
// }
// }
// to the rescue, .bind()
// 'bind()' tells js what this refers to when we are executing the code.
// used in the constructor within the button reference, we are binding 'this' context to the constructor, the instance of tthe object, and not the button that calls the method.
// it is telling js... this, when called by addName, means the class, not the button
class NameGenerator {
constructor() {
const btn = document.querySelector('button');
this.names = ['Max', 'Manu', 'Anna'];
this.currentName = 0;
console.log(this);
btn.addEventListener('click', this.addName.bind(this));
}
addName() {
console.log(this);
const name = new NameField(this.names[this.currentName]);
this.currentName++;
if (this.currentName >= this.names.length) {
this.currentName = 0;
}
}
}
const gen = new NameGenerator();
<file_sep>from flask import Flask, render_template, request, redirect, session, flash
app = Flask(__name__)
app.secret_key = "validation"
@app.route('/')
def index():
return render_template("index.html")
@app.route('/result', methods=['POST'])
def display():
if len(request.form['name']) < 2:
flash("Please enter your name")
if len(request.form['comment']) > 120:
flash("Please limit comment to 120 characters")
if "_flashes" in session:
return redirect("/")
name = request.form['name']
location = request.form['locations']
language = request.form['languages']
comment = request.form['comment']
return render_template("result.html", name = name, location = location, language = language, comment = comment)
app.run(debug=True)
<file_sep># import flask
from flask import Flask, render_template
# import the connector function
from mysqlconnection import MySQLConnector
# create the flask app
app = Flask(__name__)
# connect and store the connection in 'mysql' variable, note we pass the database name to the function as an argument
mysql = MySQLConnector(app, 'world')
# we run a query with query_db() function and print to results in Terminal, we ask only for the first country on the list
# print mysql.query_db("SELECT * FROM country")[0]
# we run a second query and ask for the name of that first country
# print mysql.query_db("SELECT * FROM country")[0]['Name']
# we can create some flask to display country information in an html
@app.route('/countries')
def countries():
countries = mysql.query_db("SELECT country.Name AS Country, city.Name AS Capital FROM country JOIN city ON country.Capital = city.ID;")
return render_template("countries.html", all_countries=countries)
app.run(debug=True)<file_sep>function printReturn(arr){
var max = arr[0];
var min = arr[0];
for(var i = 0; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
if(arr[i] < min){
min = arr[i];
}
}
console.log(min);
return max;
}
console.log(printReturn([7,2,9,6,4,2,4,6,7,2,1,0,34]));<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from .forms import RegistrationForm, LoginForm
from .models import UserManager, User
# Create your views here.
def index(request):
regform = RegistrationForm()
loginform = LoginForm()
context = {
'regform':regform,
'loginform':loginform
}
return render(request, "formtest/index.html", context)
# # This is the method that is running in response to that form submission
# def register(request):
# # Confirm that the HTTP verb was a POST
# if request.method == "POST":
# # Bind the POST data to an instance of our RegisterForm
# bound_form = RegistrationForm(request.POST)
# # Now test that bound_form using built-in methods!
# # *************************
# print bound_form.is_valid() # True or False, based on the validations that were set!
# print bound_form.errors # Any errors in this form as a dictionary
# # *************************
# # We send messages along with request so they print in the screen wherever we've structured the messages div
# messages.error(request, bound_form.errors)
# return redirect('index')
def register(request):
if request.method != 'POST':
return redirect('/')
else:
context = {
'first_name':request.POST['first_name'],
'last_name':request.POST['last_name'],
'email':request.POST['email'],
'username':request.POST['username'],
'password':request.POST['<PASSWORD>'],
'confirm_password':request.POST['confirm_password']
}
result = User.objects.RegistrationValidator(context)
for message in result[1]:
if result[0] == True:
messages.success(request, message)
else:
messages.error(request, message)
return redirect('/')
def login(request):
if request.method != 'POST':
return redirect('/')
username = request.POST['username']
password = request.POST['<PASSWORD>']
result = User.objects.LoginValidator(username, password)
if result[0]:
request.session['logged_user'] = result[1]
request.session['user'] = User.objects.get(id=request.session['logged_user']).first_name
return redirect('/')
else:
for message in result[1]:
messages.error(request, message)
return redirect('/')
return redirect("/")
def logout(request):
for key in request.session.keys():
del request.session[key]
return redirect('/')
<file_sep>for(var i = 1; i <=98; i++){
console.log("Don't Worry, Be Happy!");
}<file_sep>var year = 2016;
while( year > 0 ){
if( year % 4 == 0 ){
console.log(year);
}
year--;
}<file_sep>const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const reg = new RegExp('\\.js$', 'i');
// path method returns a string array
// use this if the process launches from root dir
// const models_path = path.resolve('server/models')
// use this in almost any situation
const models_path = path.join(__dirname, '../models');
mongoose.connect('mongodb://localhost:27017/books', {useNewUrlParser:true});
mongoose.connection.on('connected', () => console.log("MongoDB connected to Books App"));
// read models directory in synchronous way, so it blocks until we have the information. one of the few instances we do synchronous codes in js
// because the files generated with these models are necessary for other pieces of the application and will throw errors
// because path returns a string array, we do forEach to read each file in the url
fs.readdirSync(models_path).forEach(file => {
if (reg.test(file)) {
require(path.join(models_path, file));
}
});<file_sep>// not block level scope like other languages.
// global and local scopes are JS
function moo() {
a = 1;
}
// throws error = undefined
// console.log(a)
for (var i = 0; i < 5; i++) {
var j = 5;
}
// this prints
console.log(i);
console.log(j);
// for loops happen at a global level and i and j are global variables
// scope chain:
// knowing that functions create scope within which local variables are declared, an inportant concept is scope chain.
// functions access to variables depends on the structure of the code. Lexically read.
// First, functions look inside themselves, then at more global scope, etc..
// variables declared below the function in other functions are not available to it.
// example
function foo() {
console.log(myVar);
}
function goo() {
const myVar = 1;
foo();
}
// goo() // throw error myVar is not defined
// however, the following works:
function doom() {
const myVar = "temple";
function room() {
console.log(myVar);
}
room();
}
doom();
// and this is an example of functions looking at more and more global scope until it finds the variable:
const Y = "bye";
function hi() {
function bye() {
console.log(Y);
}
bye();
}
hi();
<file_sep>def push_front(arr,val):
arr.append(val)
print len(arr)
print arr
arr[0], arr[1], arr[2], arr[3], arr[4] = arr[4], arr[0], arr[1], arr[2], arr[3]
print arr
push_front([1,2,3,4],5) <file_sep>const Product = require('../models/product');
const Order = require('../models/order');
module.exports = {
getProducts(req, res, next) {
Product.find()
// .select('title price -_id') // we can be selective about data we retrieve from db with .select and passing fields as args, excluding explicitly with the minus sign when we also want to do that
// .populate('userId') // we would use this to populate the entire object info of the embedded object
// .populate('userId', 'name') // we can be selective about what data we retrieve with populate, example, only the name
.then(products => {
console.log(products);
res.render('shop/product-list', {
prods: products,
pageTitle: 'All Products',
path: '/products'
});
})
.catch(err => console.log(err));
},
getProduct(req, res, next) {
const prodId = req.params.productId;
Product.findById(prodId)
.then((product) => {
res.render('shop/product-detail', {
product: product,
pageTitle: product.title,
path: '/products'
});
})
.catch(err => console.log(err));
},
getIndex(req, res, next) {
Product.find()
.then(products => {
res.render('shop/index', {
prods: products,
pageTitle: 'Shop',
path: '/'
});
})
.catch(err => console.log(err));
},
getCart(req, res, next) {
req.user
.populate('cart.items.productId') // populate takes the path within the User schema of what we want to populate
.execPopulate() // we do this in order to get a promise from .populate()
.then(user => {
const products = user.cart.items;
res.render('shop/cart', {
path: '/cart',
pageTitle: 'Your Cart',
products: products
});
})
.catch(err => console.log(err))
},
postCart(req, res, next) {
const prodId = req.body.productId;
Product.findById(prodId)
.then(product => {
return req.user.addToCart(product);
}).then(result => {
console.log(result);
res.redirect('/cart');
}).catch(err => {
console.log(err);
})
},
postCartDeleteProduct(req, res, next) {
const prodId = req.body.productId;
req.user.deleteItemFromCart(prodId)
.then(result => {
res.redirect('/cart');
})
.catch(err => console.log(err));
},
postOrder(req, res, next) {
req.user
.populate('cart.items.productId')
.execPopulate()
.then(user => {
const products = user.cart.items.map(i => {
return {quantity: i.quantity, product: {...i.productId._doc}} // with the spread operator and ._doc mongoose syntax, we are able to pull all and only the product details into the product field of the cart
});
const order = new Order({
user: {
name: req.user.name,
userId: req.user
},
products: products
});
return order.save();
})
.then(result => {
req.user.clearCart();
})
.then(() => {
res.redirect('/orders');
})
.catch(err => console.log(err));
},
getOrders(req, res, next) {
Order.find({'user.userId': req.user._id})
.then(orders => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders',
orders: orders
});
})
.catch(err => console.log(err));
},
}
<file_sep>const grades = [60,55,80,90,99,92,75,72];
// how do we summarize data from an array? use .reduce()
function sum(x, y) {
return x + y;
}
const total = grades.reduce(sum);
console.log(total);
const average = total / grades.length;
console.log(average);
// reduce function first parameter is the accumulator, second is the value that is mixed with it according to what the callback function instructs
function groupByGrade(acc, grade) {
// destructure acc into key value pairs from a to f with default count of 0
// reduce function below will initialize this as an empty object, so all grade levels will be at default value, then aggregation will begin
const {a = 0, b = 0, c = 0, d = 0, f = 0} = acc;
if (grade >= 90) {
return { ...acc, a: a + 1 };
} else if (grade >= 80) {
return { ...acc, b: b + 1 };
} else if (grade >= 70) {
return { ...acc, c: c + 1 };
} else if (grade >= 60) {
return { ...acc, d: d + 1};
} else {
return { ...acc, f: f + 1 };
}
}
// an empty object is passed through the reduce funtion as second parameter, which is taken by the first accumulator value. Being an empty object, this is the starting point for our grades accumulation
const letterGradeCount = grades.reduce(groupByGrade, {});
console.log(total, average, letterGradeCount);
// exercise
const reviews = [4.5, 4.0, 5.0, 2.0, 1.0, 5.0, 3.0, 4.0, 1.0, 5.0, 4.5, 3.0, 2.5, 2.0];
function groupByRating(acc, rating) {
const count = acc[rating] || 0;
return {...acc, [rating]: count + 1};
}
const reviewCount = reviews.reduce(groupByRating, {});
console.log(reviewCount);
const numbers = [2, 4, 4, 3];
const sumNumbers = numbers.reduce(addUp);
function addUp(acc, n) {
return acc + n;
}
console.log(sumNumbers);
function groupBy(acc, n) {
const count = acc[n] || 0;
return {...acc, [n]: count + 1};
}
const groupedN = numbers.reduce(groupBy, {});
console.log(groupedN);
<file_sep>function addition(){
var sum = 0;
for(var i = -30; i <= 30; i++){
if(i % 2 !== 0){
sum = sum + i;
}
}
console.log(sum);
}
addition();<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
def welcome(request):
return render(request, 'survey/welcome.html')
def start(request):
return render(request, 'survey/survey_form.html')
def process(request):
if request.method == 'POST':
request.session['name'] = request.POST['name']
request.session['location'] = request.POST['location']
request.session['language'] = request.POST['language']
request.session['comment'] = request.POST['comment']
# context = {
# 'name':request.session['name'],
# 'location':request.session['location'],
# 'language':request.session['language'],
# 'comment':request.session['comment']
# }
return redirect("/survey/show")
else:
return render(request, 'survey/survey_form.html')
def show(request):
context = {
'name':request.session['name'],
'location':request.session['location'],
'language':request.session['language'],
'comment':request.session['comment']
}
return render(request, 'survey/capture.html', context)
<file_sep># sort orders values, reverse=True is also possible
my_list = [10,65,98,35,77,2]
print my_list.sort()
<file_sep>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { HttpService } from '../../http.service';
import { map, switchMap } from 'rxjs/operators';
import { Book } from 'src/app/models/book';
@Component({
selector: 'app-book-detail',
templateUrl: './book-detail.component.html',
styleUrls: ['./book-detail.component.css']
})
export class BookDetailComponent implements OnInit {
@Input() book: Book;
@Output() bookEdit = new EventEmitter<Book>();
books: Book[];
constructor(
private _httpService: HttpService,
private route: ActivatedRoute,
) { }
ngOnInit() {
// this is wrong because we are nesting observables:
// this.route.paramMap.subscribe(params => {
// const book_id = params.get('_id');
// this._httpService.getBook(book_id)
// .subscribe(data => this.book = data);
// });
// this solves the observable nesting problem using pipe:
// this.route.paramMap.pipe(
// // we are getting the book id from the route
// map(params => params.get('_id')),
// // receive content from map, switch focus from map observable to another observable, the book coming back from service
// switchMap(_id => this._httpService.getBook(_id))
// )
// .subscribe(data => this.book = data);
// this is how we implement resolve and avoid undefined errors when loading:
this.book = this.route.snapshot.data.book as Book;
}
editBook(book: Book, form: NgForm): void {
console.log('got the update request for ', book);
this._httpService.editBook(book)
.subscribe(data => {console.log('updated book', data);
this.book = null;
});
}
hideEdit(): void {
this.book = null;
}
deleteBook(_id: number): void {
this.book = null;
this._httpService.deleteBook(_id)
.subscribe(data => {
for (let i = 0; i < this.books.length; i++) {
if (this.books[i]._id === data._id) {
this.books.splice(i, 1);
}
}
});
}
}
<file_sep>$(document).ready(function(){
$('img').hover(
function(){
var oriSrc = $(this).attr('src');
var altSrc = $(this).attr('alt-src')
$(this).attr('src', altSrc);
$(this).attr('alt-src', oriSrc);
}, function(){
var oriBack = $(this).attr('alt-src');
var altBack = $(this).attr('src');
$(this).attr('src', oriBack); $(this).attr('alt-src', altBack);
});
})<file_sep>from flask import Flask, render_template, session, request, redirect
import random
app = Flask(__name__)
app.secret_key = "earnmoneyninja"
@app.route("/")
def index():
session['earnings'] = 0
session['activity'] = []
session['messages'] = []
return render_template("index.html")
@app.route("/earn", methods=['POST'])
def earn():
print request.form['activity']
if request.form['activity'] == "Farm":
earns = random.randint(10,20)
session['activity'].append("Farm")
elif request.form['activity'] == "Cave":
earns = random.randint(5,10)
session['activity'].append("Cave")
elif request.form['activity'] == "House":
earns = random.randint(2,5)
session['activity'].append("House")
elif request.form['activity'] == "Casino":
earns = random.randint(-50,50)
session['activity'].append("Casino")
else:
earns = 0
session['earnings'] += earns
message = "Earned {} golds from the {}!".format(earns,request.form['activity'])
session['messages'].append(message)
return render_template("index.html", earnings=session['earnings'], messages=session['messages'], earns=earns)
@app.route("/clear")
def clearSession():
session.clear()
return redirect("/")
app.run(debug=True)<file_sep>#declare a class and give it a name
class User(object):
#the __init__ method is called every time an object is created
def __init__(self, name, email):
#set some instance variables, these are the attributes
self.name = name
self.email = email
self.logged = False
#this is a method we create to help a user log in
def login(self):
self.logged = True
print self.name + " is logged in."
return self
#now create an instance of the class
#the parameters are passed throuth the __init__ method
new_user = User("Helen","<EMAIL>")
print new_user.email
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from datetime import datetime
# Create your models here.
class UserManager(models.Manager):
def basic_validator(self, postData):
errors = {}
if len(postData['first_name']) < 2:
errors["first_name"] = "First name should be more than 2 characters"
if len(postData['last_name']) < 2:
errors["last_name"] = "Last name should be more than 2 characters"
if len(postData['email']) < 8:
errors["email"] = "Email should be more than 8 characters"
if len(postData['password']) < 8:
errors["password"] = "Password should be more than 8 characters"
return errors
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now())
objects = UserManager
<file_sep>import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../http.service';
import { Book } from '../../models/book';
@Component({
selector: 'app-book-list',
templateUrl: './book-list.component.html',
styleUrls: ['./book-list.component.css']
})
export class BookListComponent implements OnInit {
book = new Book(); // this is the book referenced in the html and to which [(ngForm)] is binding
books: Book[] = [];
selectedBook: Book;
filter: Book = new Book();
constructor(private _httpService: HttpService) {}
ngOnInit() {
this.getBooks();
}
getBooks(): void {
this._httpService.getBooks()
.subscribe(books => {
this.books = books;
console.log('these books are back from subscription', books);
});
}
getBook(book: Book): void {
this.selectedBook = this.selectedBook === book ? null : book;
}
onCreate(book: Book): void {
this.books.push(book);
// another way of doing the above is with a reassignment, but it is more resource intensive
// this.books = [...this.books, book];
}
clearFilter(): void {
this.filter = new Book();
}
onEvent(event: Event): void {
// this is a way to control the click event
event.stopPropagation();
}
onDelete(_id: number): void {
console.log('got request to delete book: ', _id);
this._httpService.deleteBook(_id)
.subscribe(data => {
this.books = this.books.filter(book => book._id !== data._id);
});
}
}
<file_sep>function evenOdd(arr){
var count_eve = 0;
var count_odd = 0;
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 == 0){
count_eve++;
count_odd = 0;
if(count_eve >= 3){
console.log("even more so!");
}
}
if(arr[i] % 2 !== 0){
count_eve = 0;
count_odd++;
if(count_odd >= 3){
console.log("that's odd!");
}
}
}
}
evenOdd([2,5,3,6,3,5,65,4,3,5,6,4,4,5,6,345,9,54,3,45,65,9]);<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styles: [`
* {
color: dodgerblue;
}
`]
})
export class ServersComponent implements OnInit {
allowNewServer = false;
serverCreationStatus = '';
serverCreated = false;
serverName = '';
servers: string[] = [];
constructor() {
// methods in the constructor exist at the moment angular creates this component
setTimeout(() => {
this.allowNewServer = true;
}, 3000);
}
ngOnInit() {
}
onServerCreate() {
this.servers.push(this.serverName);
this.serverCreationStatus = 'has been successfully created!';
this.serverCreated = true;
}
onNameServer(event: Event) {
this.serverName = (<HTMLInputElement>event.target).value;
}
}
<file_sep>import {Circle, Square} from "./module.js";
const c = new Circle(3);
const s = new Square(10);
c.draw();
s.draw()<file_sep>def about(name, age, likes):
sentence = "Meet {}! They are {} years old and like {}.".format(name, age, likes)
return sentence
print(about("Jack", 23, "programming"))
# in the above example,
# parameters are the variables that the function is waiting to get: name, age, likes
# arguments are the values passed through the parameters: 'Jack', 23, 'programming'
# because these are passed in the same order expected by the function, they are called positional parameters
# we could pass parameters in any order we like only if we made it clear which value is being assigned to each parameter
# we do this with key word arguments (kwargs)
print(about(age = 40, likes = "coding", name = "Tom"))
# we can get away with not passing all of the arguments if we had default values
def about(name, age, likes = "Python"):
sentence = "Meet {}! They are {} years old and like {}.".format(name, age, likes)
return sentence
print(about("John", 32))
# DEFAULT PARAMETERS MUST GO At THE END
# if you want all of the parameters to have default values, the function is going to work
def about(name = "John", age = 30, likes = "Python"):
sentence = "Meet {}! They are {} years old and like {}.".format(name, age, likes)
return sentence
print(about())
<file_sep>array = [1,2,3]
myfile = open("folder/numbers.txt", "w")
for num in array:
myfile.write(str(num) + "\n")
myfile.close()<file_sep>def multiplication(n1, n2):
return n1 * n2
user_input_1 = float(input("Enter a number: "))
user_input_2 = float(input("Enter another number: "))
print(multiplication(user_input_1, user_input_2))
<file_sep>//array destructuring
let input = [1,2];
let [first, second] = input;
console.log(first);
console.log(second);
//swapping
[first, second] = [second, first];
console.log(first);
console.log(second);
//as function parameters
function destructure([one, two]:[number, number]) {
console.log[one];
console.log[two];
}
destructure([600, 900]);
//grouping
let [digit, ...rest] = [1,2,3,4];
console.log(digit);
console.log(rest);
//cherrypicking
let arr_1 = [1000,2000,3000,4000];
let [item_1] = arr_1;
console.log[item_1];
let [,item_a,,item_b] = arr_1;
console.log(item_a);
console.log(item_b);
//spread is opposite to destructuring:
let nums1 = [1,2,3];
let nums2 = [4,5,6];
let nums3 = [0, ...nums1, ...nums2, 7, 8];
<file_sep>#you can pass a bundle of arguments through a variable by using the "splat" operator or asterisk. This operator works as a .join() and creates a tuple out of the bundled arguments and is assigned to a parameter
def varArgs(arg1, *args):
print "Got " + arg1 + " and " + ", ".join(args)
print str(type(args))
varArgs("one")
varArgs("one","two")
varArgs("one","two","three")
varArgs("one","two","three","four")
<file_sep>"use strict";
// prototypal inheritance creates a prototype chain
// easy to unserstand and uses functionality JS natively offers
const Person = {
init: function(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
return this;
},
full_name: function() {
return this.first_name + " " + this.last_name;
}
};
// style # 1 of creating an object whose prototype points to the Person object by using the Object.create() function:
// step 1: link prototype of bob to Person
const bob = Object.create(Person);
// step 2: populate bob's parameters
bob.init("Bob", "Jones");
console.log("prototype of bob is: ", Object.getPrototypeOf(bob));
console.log("bob is: ", bob);
// step 3: you can now use full_name property
console.log(bob.full_name());
// style # 2 of creating the object (the most verbose one)
const jim = Object.create(Person, {
first_name: {
value: "Jim"
},
last_name: {
value: "Johnson"
}
});
console.log(jim.full_name());
// style # 3 of creating the object, probably preferred
function PersonFactory(first_name, last_name) {
const person = Object.create(Person);
person.first_name = first_name;
person.last_name = last_name;
return person;
}
const jon = PersonFactory("Jon", "Boomer");
console.log(jon.full_name());
// how do we inherit?
// with the prototype method, just keep adding to the prototype chain!
const Professional = Object.create(Person, {
init: {
value: function(honorific, first_name, last_name) {
this.honorific = honorific;
this.first_name = first_name;
this.last_name = last_name;
return this;
}
},
professional_name: {
value: function() {
return this.honorific + " " + this.first_name + " " + this.last_name;
}
}
});
Professional.work = function() {
return "Working!";
};
console.log("a professional is ", Professional);
const manolo = Object.create(Professional);
manolo.init("Dr.", "Manuel", "Briz");
console.log("manolo is ", manolo);
console.log(Professional === Object.getPrototypeOf(manolo));
console.log(manolo.work());
console.log(manolo.full_name());
console.log(manolo.professional_name());
const keys = Object.getOwnPropertyNames(manolo);
console.log(keys);
for (let props in manolo) {
console.log("the props are: ", props);
}
console.log("the keys are ", Object.keys(manolo));
console.log("the values are ", Object.values(manolo));
<file_sep>"use strict";
// function constructors and the new keyword is the pseudo-classical implementation of oop in JS
// in JS, call this "the constructor pattern"
// the class will describe the behavior of the object via member functions and the state of it via properties
// we can mimic this with a function constructor
function Person(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
this.fullName = function() {
return this.first_name + " " + this.last_name;
};
}
// the following code will throw that 'this' is undefined, as seen previously when calling context is global under strict mode:
// let dude = Person('Jose', 'Briz');
// console.log(dude)
// using the 'new' keyword implements the pseudo-classical OOP
let dude = new Person("Jose", "Briz");
console.log(dude);
// does something similar, but not equal to:
let dude1 = {};
Person.call(dude1, "Mikel", "Briz");
console.log(dude1);
console.log(dude.fullName());
console.log(dude1.fullName());
// Prototypical chain
// dude prototype points to Person;
let dudeP = Object.getPrototypeOf(dude);
console.log(dudeP);
// Person prototype points to the construtor Function:
let protoP = Object.getPrototypeOf(Person);
console.log(protoP.toString());
console.log(dudeP === protoP, ", the dude prototype and person prototype are not the same");
// Prototypes of dude prototype and Person prototype are Object
let dudeP1 = Object.getPrototypeOf(dudeP);
console.log(dudeP1);
let protoP1 = Object.getPrototypeOf(protoP);
console.log(protoP1);
console.log(dudeP1 === protoP1, ", at this point, both point to the same prototype");
// all prototypes go back to null
let dudeP2 = Object.getPrototypeOf(dudeP1);
console.log(dudeP2)
let protoP2 = Object.getPrototypeOf(protoP1);
console.log(protoP2);
// and null is an object
console.log(typeof null);
// adding methods to the parent's prototype makes them available to the children. this saves memory
Person.prototype.greet = function() {
return "Hello, my name is " + this.fullName();
}
console.log(dude.greet());
// console.log(dude1.greet()); // not available when 'new' was not used!!
// typically, putting the member functions on the prototype are the way to go
// however, these are all public and are mutable from the outside
// if you want private properties, need to add them to the body
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.messages import constants as messages
from datetime import datetime
from time import strftime
from .models import *
# Create your views here.
def index(request):
return render(request, "users/index.html")
def users(request):
users = User.objects.all()
context = {
'users':users
}
return render(request, "users/users.html", context)
def new(request):
return render(request, "users/register.html")
def process(request):
User.objects.create(
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
password=request.POST['<PASSWORD>'],
)
return redirect('/users')
def show(request, id):
context = {
'user':User.objects.get(id=id)
}
return render(request, "users/user.html", context)
def edit(request, id):
request.session['user_id'] = id
user = User.objects.get(id=id)
request.session['first_name'] = user.first_name
request.session['last_name'] = user.last_name
request.session['email'] = user.email
context = {
'first_name':user.first_name,
'last_name':user.last_name,
'email':user.email
}
return render(request, "users/update.html", context)
def editing(request, id):
user = User.objects.get(id=id)
if len(request.POST['first_name']) == 0:
user.first_name = request.session['first_name']
else:
user.first_name=request.POST['first_name']
if len(request.POST['last_name']) == 0:
user.last_name = request.session['last_name']
else:
user.last_name=request.POST['last_name']
if len(request.POST['email']) == 0:
user.email = request.session['email']
else:
user.email=request.POST['email']
# if request.POST['password'] == []:
# error
# else:
user.password = request.POST['password']
user.updated_at = datetime.now()
user.save()
for key in request.session.keys():
del request.session[key]
return redirect('/users')
def delete(request, id):
user = User.objects.get(id=id)
user.delete()
return redirect('/users')
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8000;
// we import our middleware with require
const logger = require('./server/middleware/logger');
const app = express();
app
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs');
// see what our middleware module is
// console.log("logger is",logger);
// where we create middleware matters
// we console.log(request.body) here and appears undefined. If we do below bodyParser, see what happens
app
.use((request,response,next) => {
// console.log(request.body);
next();
})
.use(bodyParser.urlencoded({extended:true}))
// we'll build middleware in a module, inside server/middleware directory. Modularizing the server is good practice!
//middleware created in a module:
.use(logger)
// creating middleware here
.use((request,response,next) => {
// console.log(next);
// console.log(request.body);
//needs the next() invocation in order to finish it's loop, otherwise we see the spinning wheel in the browser
next();
});
// the above doesn't do anything, it is just an illustration of what middleware is. It is a function with a request, a response and next. with next being a function that indicates Node.js that middleware is done running this pice of middleware.
// because middleware calls can be asynchronous, middleware is designed so that we need to indicate we're done with next();
// if we don't call next, we'll wait inside the function until we time out.
// it is important to note that all middleware is going to process all request and responses so any 'app.use' we bring into the server will act
// STATE: middleware makes decisions. Example is the body-parser middleware .urlencoded({extended:true}). State is created and preserved through functions:
function stateful(doStuff, ...options) {
return function(request, response, next) {
console.log('inside stateful middleware', doStuff, options);
//check if express already has a method before including it, because we do not want to override it
console.log(request.doStuff)
if(doStuff) {
request.doStuff = true;
} else {
// error handling done by returning next with an error message
// we need to handle them, otherwise they are displayed to user.
// in order to handle errors, we write error-handling middleware.
// error handling middleware usually done at the bottom... so see bottom of server....
return next(new Error('do stuff was false'));
}
next();
};
}
app.use(stateful(false, false, 'whatever'));
const names = ['Jack','Jill','John','Jos']
app.get('/', (req,res) => {
res.render('index');
});
app.post('/names', (req,res) => {
// console.log(req.body);
names.push(req.body.name);
res.render('names',{name:req.body.name, names});
// res.redirect('/');
});
app.get('/names/:name_id', (req,res) => {
// console.log(req);
// console.log(req.params);
// console.log(req.params.name_id);
res.send(names[req.params.name_id]);
});
// ERROR HANDLING MIDDLEWARE
// ehm takes 4 arguments:
app.use(function(error, request, response, next) {
console.log(error.message);
next(error);
})
app.use(function(error, request, response, next) {
response.send(error.message);
next();
})
app.listen(port, () => console.log(`Express server listening on port ${port}`));
<file_sep># create a file in a folder
# the w mode overrides content, if any
myfile = open("folder/friends.txt", "w")
# write content into the file
myfile.write("Mike")
myfile.write("\nDrago")
# close the file so we can open it and see the contents
myfile.close()
# the apend mode is used to write new content without overriding existing
myfile = open("folder/friends.txt", "a")
myfile.write("\nTammy")
myfile.close()
<file_sep>from flask import Flask, request, redirect, render_template, session, flash
from mysqlconnection import MySQLConnector
app = Flask (__name__)
mysql = MySQLConnector(app,'friends')
@app.route('/')
def get_friends():
query = "SELECT * FROM friends"
friends = mysql.query_db(query)
return render_template('index.html', friends = friends)
@app.route('/add', methods=['POST'])
def add_friend():
data = {
'first_name': request.form['first_name'],
'last_name': request.form['last_name'],
'email': request.form['email']
}
query = "INSERT INTO friends (first_name, last_name, email, created_at, updated_at) VALUES (:first_name, :last_name, :email, NOW(), NOW())"
mysql.query_db(query,data)
return redirect('/')
app.run(debug=True)
<file_sep>#Part 1
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
for pair in students:
print pair['first_name'], pair['last_name']
#Part 2
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name': 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
for types in users:
print types
for key,person in enumerate(users[types],1):
print key,"-",person['first_name'],person['last_name'],"-",len(person['first_name'])+len(person['last_name'])
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-23 22:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login_reg', '0002_auto_20180812_1438'),
]
operations = [
migrations.RenameField(
model_name='user',
old_name='fname',
new_name='password',
),
migrations.RemoveField(
model_name='user',
name='lname',
),
migrations.RemoveField(
model_name='user',
name='pword',
),
migrations.RemoveField(
model_name='user',
name='uname',
),
migrations.AddField(
model_name='user',
name='first_name',
field=models.CharField(default='Jose', max_length=45),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='last_name',
field=models.CharField(default='Briz', max_length=45),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='username',
field=models.CharField(default='jb1234123', max_length=45),
preserve_default=False,
),
migrations.AlterField(
model_name='user',
name='created_at',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(max_length=45),
),
migrations.AlterField(
model_name='user',
name='updated_at',
field=models.DateTimeField(auto_now=True),
),
]
<file_sep>$(document).ready(function(){
document.getElementsByTagName("audio")[0].play();
});
<file_sep>export * from './books.resolve';
<file_sep>function f() {
const message = `I'm inside function f!`
return message;
}
console.log(f());
//returns the string
function g() {
const num_var = 10;
return function h() {
const new_num = num_var + 1;
return new_num;
}
}
var t = g();
console.log(t());
//returns 11
function a() {
let a = 1;
a = 2;
let b = z();
a = 3;
return b;
function z() {
return a;
}
}
console.log(a());
//returns 2!
//variable capturing quirks
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 100 * i);
}
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 100 * i);
})(i);
}
//advantages of using let, one of them is that it is block scoped and another is that it creates its own instance if for each iteration if used within a for loop, thus simplyfying the examples above:
for (let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 100 * i)
}
//scoping
//let is a block scoped variable, but it can be re-declared on a function-scoped variable
function conditional(condition, x) {
if (condition) {
let x = 100
return x;
}
return x;
}
console.log(conditional(false, 0));
console.log(conditional(true, 0));
//shadowing is re-declaring with a different name in a nested function:
function sumMatrix(matrix: number[][]) {
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
var currentRow = matrix[i];
for (let i = 0; i < currentRow.length; i++) {
sum += currentRow[i];
}
}
return sum;
}
//array destructuring
let input = [1,2];
let [first, second] = input;
console.log(first);
console.log(second);
//swapping
[first, second] = [second, first];
console.log(first);
console.log(second);
//as function parameters
function destructure([one, two]:[number, number]) {
console.log[one];
console.log[two];
}
destructure([600, 900]);
//grouping
let [digit, ...rest] = [1,2,3,4];
console.log(digit);
console.log(rest);
//cherrypicking
let arr_1 = [1000,2000,3000,4000];
let [item_1] = arr_1;
console.log[item_1];
let [,item_a,,item_b] = arr_1;
console.log(item_a);
console.log(item_b);
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-assignment1',
templateUrl: './assignment1.component.html',
styles: [`
* {
color: dodgerblue;
}
`]
})
export class Assignment1Component implements OnInit {
userName = '';
constructor() { }
ngOnInit() {
}
resetUser(event: Event) {
this.userName = '';
}
}
<file_sep>import folium
import pandas
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
html = """<h4>Volcano information:</h4>
Height: %s m
"""
map = folium.Map((45,-115), width="50%", height="50%", zoom_start=2, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
# stylize the popup with an html element, using iFrame folioum method
for lt, ln, ele in zip(lat, lon, elev):
iframe = folium.IFrame(html=html % str(ele), width=200, height=100)
fg.add_child(folium.Marker(location=(lt, ln), popup=folium.Popup(iframe), icon=folium.Icon(color="darkgreen")))
map.add_child(fg)
map.save("Volcanoes2.html")<file_sep>console.log(typeof "a");
console.log(typeof 1);
console.log(typeof false);
console.log(typeof {});
console.log(typeof undefined);
console.log(typeof null); // incorrectly prints object, can't be reversed
// dynamically typed language:
// js is dynamical as data type can change and applied at runtime
// statically typed language needs data type specification beforehand
// difference between null and undefined:
// js sets type undefined to uninitialized variables
var a;
console.log(a);
// null is set by programmers, not js engine
var b = null;
console.log(b);
// this is a subtle but important distinction
// a similarity is that both null and undefined are values
// outside of JS, null is absence of value
// this is true because values are same
console.log(undefined == null);
console.log(0 == "");
console.log(1 == "1");
console.log(String(1) === "1");
// this is false because they are not so the same in every respect (type and value)
console.log(undefined === null);
console.log(0 === "");
console.log(1 === "1");
// all these are false, except the last one
console.log(false == "false");
console.log("false" == false);
console.log(Boolean("false") === false);
console.log(false === Boolean("false"));
console.log(String(false) === "false");
// everything compared to NaN is false, even NaN...
console.log(NaN == NaN);
console.log(NaN === NaN);
// NaN type is number
console.log(typeof NaN);
// check if value of a variable is NaN:
var n = NaN;
console.log(a !== a);
// use this trick because NaN is the only value of all JS that is NOT equal to itself.
// any other method of checking for NaN is inconsistent.
<file_sep>function yourBirthday(a,b){
if(a == 10 && b == 8 || a == 8 && b == 10){
console.log("How did you know?");
}
else{
console.log("Just another day.");
}
}
yourBirthday(10,8);<file_sep># dictionaries are made up of key:value pairs
# dictionaries are not indexed, so it's an unordered collection of key:values
students = {'Alice':25,'Bob':27,'Claire':17,'Dan':21,'Emma':22}
# keys are strings or previously declared variables
# retrieve a value by key:
print(students['Dan'])
# add a key,value pair:
students["Fred"] = 25
print(students)
# value reassignment:
students['Dan'] = 22
print(students['Dan'])
# remove from dictionary
del students['Fred']
print(students)
# get the dictionary keys, the returned format is iterable but not subscriptable, meaning, you can't just grab an individual element
print(students.keys())
# to get an individual key from an iterable structure, assign them to a variable using the list() method
st_keys = list(students.keys())
print(st_keys[2])
# get the dictionary values, returns iterable / non-subscriptable format
print(students.values())
# by making a list, it becomes subscriptable
st_values = list(students.values())
print(st_values[3])
# get the dictionary items
print(students.items())
st_items = list(students.items())
# make a list of tuples from the key,values
print(st_items)<file_sep># ask user for name
name = input('Hi, what is your name? ').strip()
# ask user for age
age = input('What is your age? ').strip()
# ask user for city
city = input('What city do you live in? ').strip()
# ask user what they enjoy
joy = input('What do you enjoy to do? ').strip()
# create output text
output = 'Hello, %s! I see you live in %s and that you enjoy %s!' % (name, city, joy)
output2 = 'Hi people, {} is {} years old. He comes from {} and enjoys {}.'.format(name,age,city,joy)
# print output to screen
print(output)
print(output2)<file_sep># tuples are immutable types, like strings
# structure: comma separated list; in practice they are wrapped in parentheses to make it more clear what you're doing
# they are iterable, so we can select indexes and slices
our_tuple = 1,2,3,'a','b','c'
print(type(our_tuple))
print(our_tuple[3])
print(our_tuple[3:len(our_tuple)])
# immutable means they cannot be changed after they are created. Just like you can't change a letter in a word without having to recreate the whole word
# convert other data types to tuples:
list1 = ['a', 'b', 1]
list1 = tuple(list1)
print(list1)
# tuples support multiple assignment from other data types:
a,b,c = 1,2,3
print(a)
print(b)
print(c)
a,b,c = [6,7,8]
print(a)
print(b)
print(c)
a,b,c = "369"
print(a)
print(b)
print(c)
<file_sep>from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('route/<username>/<id>')
def show_username_profile(username, id):
print username
print id
return render_template("users.html")
app.run(debug=True)
#can pass as many variables as needed in the URL as long as they do so as parameters to the route handler function
<file_sep>students = {
"male": ["Bob", "Harry", "Lenin"],
"female": ["Barb", "Harriet", "Loren"]
}
for gen in students:
print(gen)
print('---------')
for gen in students.keys():
print(gen)
print('---------')
for gen in students.keys(): # gen becomes key1, then key2
for name in students[gen]: # name becomes each name of the list belonging to dict[key1 or 2]
print(name) # do something with each name
print('---------')
for gen in students.keys(): # gen becomes key1, then key2
for name in students[gen]: # name becomes each name of the list belonging to
if "a" in name: # iterate name in search for "a"
print(name) # do something with each name that returns true
print('---------')
<file_sep># import flask
from flask import Flask, render_template, request, redirect
# import the connector function
from mysqlconnection import MySQLConnector
# create the flask app
app = Flask(__name__)
# connect and store the connection in 'mysql' variable, note we pass the database name to the function as an argument
mysql = MySQLConnector(app, 'users')
# create first flask to display all users in index.html
@app.route('/')
def users():
users = mysql.query_db("SELECT * FROM users;")
return render_template("index.html", all_users=users)
# create a route to a function that sends you to an update user html with a form:
@app.route('/users/update/<user_id>')
def update_request(user_id):
query = "SELECT * FROM users WHERE users.id = :specific_id;"
data = { 'specific_id': user_id }
user = mysql.query_db(query,data)
print user
return render_template('update.html', user=user)
# once information is updated, submit will route to the function that updates the database:
@app.route('/users/user_update/<user_id>', methods=['POST'])
def update_user(user_id):
new_email = request.form['email']
new_password = request.form['<PASSWORD>']
query = "UPDATE users SET users.email = :specified_email, users.password = :specified_password WHERE users.id = :user_id"
data = {
'specified_email':new_email,
'specified_password':<PASSWORD>,
'user_id':user_id
}
mysql.query_db(query,data)
return redirect('/')
# create a route to a function that asks if sure to delete user, we can create an html that asks if you're sure
@app.route('/users/delete/<user_id>')
def delete_request(user_id):
query = "SELECT * FROM users WHERE users.id = :specific_id;"
data = { 'specific_id': user_id }
user = mysql.query_db(query,data)
print user
return render_template('confirm.html', user=user)
# create a route to a function that deletes the users...
@app.route('/users/delete_now/<user_id>')
def delete_user(user_id):
query = "DELETE FROM users WHERE users.id = :specified_id"
data = {
'specified_id':user_id
}
mysql.query_db(query,data)
return redirect('/')
# index.html already has a form to create a new user. Create a route to a function that writes the query to achieve that...
@app.route('/users/new', methods=['POST'])
def create_user():
first_name = request.form['fname']
last_name = request.form['lname']
email = request.form['email']
password = request.form['pword']
query = "INSERT INTO `users`.`users` (`first_name`, `last_name`, `email`, `password`, `created_at`, `updated_at`) VALUES (:first_name, :last_name, :email, :password, NOW(), NOW());"
data = {
'first_name':first_name,
'last_name':last_name,
'email':email,
'password':<PASSWORD>
}
mysql.query_db(query,data)
return redirect('/')
app.run(debug=True)<file_sep>var num = 0;
while(num <= 60){
if(num % 6 == 0){
console.log(num);
}
num++;
}<file_sep>//require mongoose
const mongoose = require('mongoose');
//require path to build the path to this directory
const path = require('path');
//require fs to read directory
const fs = require('fs');
//this regulatr expression will help us with fs when we look into the directory in search only for js files; the \\ escapes the . so it is read as a .; the 'i' means case insensitive
const reg = new RegExp('\\.js$', 'i');
//the following gives us an absolute path to the models directory:
const modelsPath = path.resolve('server', 'models');
//get rid of deprecation warning when using promises:
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/authors_books', { useNewUrlParser: true });
mongoose.connection.on('connected', () => console.log('MongoDB connected'));
//we'll read our directory, and we want this process to block until we're sure the information we need is available. If we don't specify .readdirSync, the .readdir is asynchronous and would cause an error
//the forEach will give us each file that is found in this directory, but want to make sure that what we require is actually a .js file and only a .js file, so we use the RegExp we constructed above
fs.readdirSync(modelsPath).forEach(file => {
if (reg.test(file)) {
require(path.join(modelsPath, file));
}
});
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-14 22:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user_dashboard', '0007_auto_20180814_1651'),
]
operations = [
migrations.RemoveField(
model_name='message',
name='message_from',
),
migrations.RemoveField(
model_name='message',
name='message_to',
),
migrations.AddField(
model_name='message',
name='user_from',
field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, related_name='messages_sent', to='user_dashboard.User'),
preserve_default=False,
),
migrations.AddField(
model_name='message',
name='user_to',
field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, related_name='messages_received', to='user_dashboard.User'),
preserve_default=False,
),
]
<file_sep>function modArray(arr){
var newArr = [arr[0]];
for(var i = 1; i < arr.length; i++){
newArr.push(arr[i] + 7);
}
console.log(newArr);
}
modArray([3,3,3,3,3,3,3,3]);<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
import random
import string
# Create your views here.
counter = 0
def index(request):
request.session['random_word'] = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(14)])
# print request.session['random_word']
if 'counter' not in request.session:
request.session['counter'] = 0
request.session['counter'] += 1
# print request.session['counter']
context = {1:{'random_word' : request.session['random_word']}, 2:{'counter' : request.session['counter']}}
return render(request, "random_word/index.html", context)
def generate(request):
if request.method == 'POST':
return redirect('/random_word')
def reset(request):
if request.method == 'GET':
for key in request.session.keys():
del request.session[key]
return redirect('/random_word')
<file_sep>l = {'item1':"apple", 'item2':"banana", 'item3':8}
# print only values
for v in l.values():
print(v)
# print only keys
for k in l.keys():
print(k)
# print keys and values
for k,v in l.items():
print(k,v)
# print key value pairs as tuples
for items in l.items():
print(items)
# print enumerated list of values
for values in enumerate(l.values()):
print(values)
# print enumerated list of keys
for keys in enumerate(l.keys()):
print(keys)
# print enumerated list of item tuples
for iterations in enumerate(l.items()):
print(iterations)
<file_sep>
//predict the outcome of:
function a(){
console.log('hello');
return 15;
}
x = a();
console.log('x is ', x);
function a(n){
console.log('n is ', n);
return n+15;
}
x = a(3);
console.log('x is ', x);
function a(n){
console.log('n is ', n);
y = n*2;
return y;
}
x = a(3) + a(5);
console.log('x is ', x);
//predict the outcome of:
function a(x,y){
return 5;
}
console.log(5,5);
function a(x,y){
z = []
z.push(x);
z.push(y);
z.push(5);
console.log(z);
return z;
}
b = a(2,2)
console.log(b);
console.log(a(6,8));
function a(x){
z = [];
z.push(x);
z.pop();
z.push(x);
z.push(x);
return z;
}
y = a(2);
y.push(5);
console.log(y);
function a(x){
if(x[0] <x [1]) {
return true;
}
else {
return false;
}
}
b = a([2,3,4,5]);
console.log(b);
function a(x){
for(var i=0; i<x.length; i++){
if(x[i] > 0){
x[i] = "Coding";
}
}
return x;
}
console.log(a([1,2,3,4]));
function a(x){
for(var i=0; i<x.length; i++){
if(x[i] > 5){
x[i] = "Coding";
}
else if(x[i] < 0){
x[i] = "Dojo";
}
}
return x;
}
console.log(a([5,7,-1,4]));
function a(x){
if(x[0] > x[1]) {
return x[1];
}
return 10;
}
b = a([5,10])
console.log(b);
function sum(x){
sum = 0;
for(var i=0; i<x.length; i++){
sum = sum + x[i];
console.log(sum);
}
return sum;
}
sum([6,2,8,3,0]);
function a(){
return 4;
}
console.log(a()+a());
function a(b){
return b;
}
console.log(a(2)+a(4));
function a(b){
console.log(b);
return b*3;
}
console.log(a(3));
function a(b){
return b*4;
console.log(b);
}
console.log(a(10));
function a(b){
if(b<10) {
return 2;
}
else {
return 4;
}
console.log(b);
}
console.log(a(15));
function a(b,c){
return b*c;
}
console.log(10,3);
console.log( a(3,10) );
function a(b){
for(var i=0; i<10; i++){
console.log(i);
}
return i;
}
console.log(3);
console.log(4);
function a(){
for(var i=0; i<10; i++){
i = i +2;
console.log(i);
}
}
a();
function a(b,c){
for(var i=b; i<c; i++) {
console.log(i);
}
return b*c;
}
a(0,10);
console.log(a(0,10));
function a(){
for(var i=0; i<10; i++){
for(var j=0; j<10; j++){
console.log(j);
}
console.log(i);
}
}
function a(){
for(var i=0; i<10; i++){
for(var j=0; j<10; j++){
console.log(i,j);
}
console.log(j,i);
}
}
a();
z = 10;
function a(){
z = 15;
console.log(z);
}
console.log(z);
z = 10;
function a(){
z = 15;
console.log(z);
}
a();
console.log(z);
z = 10;
function a(){
z = 15;
console.log(z);
return z;
}
z = a();
console.log(z);
//1- Return a given array after converting all negative values to zero
function negNone(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] < 0){
arr[i] = 0;
}
}
document.getElementById("1").innerHTML = arr;
return arr;
}
negNone([-4,5,6,2,-3,7]);
//2- Return an array after dropping the first index and inserting zero at the end
function dropZero(arr){
arr.shift(arr[0]);
arr.push(0);
document.getElementById("2").innerHTML = arr;
return arr;
}
dropZero ([1,2,3]);
//3- Given an array, return an array with values in reversed order
function revArray(arr){
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.unshift(arr[i]);
}
document.getElementById("3").innerHTML = newArr;
return newArr;
}
revArray([1,2,3,4]);
//4- Create a function that changes a given array to list each original element twice, retaining the original order. Have the function return a new array.
function seeDouble(arr){
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.push(arr[i],arr[i]);
}
document.getElementById("4").innerHTML = newArr;
return newArr;
}
seeDouble([1,2,3]);
<file_sep># python has something called a ternary operator as an alternative to if statements
# syntax is: 'do this' if condition is true, else 'do that'
#example:
print('Coding Dojo' if stacks >= 3 else 'You are not Coding Dojo!')
<file_sep>
function Person(name, items){
if (!(this instanceof Person)) {
console.log(name, 'is not an instance of Person');
return new Person(name, items);
}
// const person = { name }; // we don't seem to need this
this.name = name;
this.items = items;
// this.take = take // we no longer need it here
}
// we attach the take method through the 'prototype' methodology and it is now a global method for Person-type objects
Person.prototype.take = function take(item, target) {
if(!target || !Array.isArray(target.items)) {
console.log('target does not have items array');
}
for (let index = 0; index < target.items.length; index++) {
if (item === target.items[index]) {
target.items.splice(index,1);
console.log(target.name+"'s "+item+" was taken by "+this.name)
this.items.push(item);
console.log("now "+this.name+" has the "+item)
return true;
}
}
return false;
}
const person1 = new Person('Bob', ['key','sandwich','tickets']);
const person2 = new Person('Jerry', ['phone','money','ring']);
//create an object that conforms to the interface, even though it is not a person...
const backpack = {
items: ['compass','map','trailmix']
};
console.log(backpack)
person1.take('trailmix',backpack)
console.log(backpack)
// because backpack is not a person, it does not have person's methods, but it can borrow them
// we could give it the ability by doing this, but we don't want backpack to have the ability all the time though
// backpack.take = Person.prototype.take;
// backpack.take('tickets',person1);
// because a function is an object in js, backpack can intercept the take call from a person and momentarily use the ability
Person.prototype.take.call(backpack, "tickets", person1);
// this works because .take is a function and .call() is a method of the function.
// .call() method can accept arguments
// the first argument is the owner object. by writing .call(backpack), we are asserting that backpack will own the take method in the current run.
// it is like saying that backpack is 'this', like so:
// this.take === backpcak.take
// the rest of the arguments will feed the take function:
// backpack.take("tickets", person1)
console.log(backpack);
// the same can be achieved with .apply() instead of .call()
// only difference is that it takes an array that is passed through as function's arguments
Person.prototype.take.apply(backpack, ["phone", person2])
console.log(backpack);
<file_sep>//function requires passed object to have at least one parameter called label and does not care about the rest:
function printLabel(labelledObj: {label: string}) {
console.log(labelledObj.label);
}
let myObj = {
size: 10,
label: "Size 10",
};
printLabel(myObj);
//we can re-write the above using an interface to describe the requirement of having a label property that is a string:
interface LabelledValue {
label: string;
}
function printLabel2(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj2 = {
size: 11,
label: "Size 11",
};
printLabel2(myObj2);
//optional properties with ?
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color:"white", area:100};
if (config.color) {
newSquare.color = config.color
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color:"black"});
console.log(mySquare);
//read only properties
interface Point {
readonly x: number;
readonly y: number;
}
// after assigning values to them, they cannot be reassigned:
let p1: Point = {x:10, y:20};
let p2: Point = {x:12, y: 14};
// p1.x = 5; shows error!
let numy: number[] = [1,2,3,4];
let readNumy: ReadonlyArray<number> = numy;
// readNumy[0] = 9; shows an error
console.log(readNumy);
//you can override a read only array to start over:
numy = readNumy as number[];
console.log(readNumy);
//excess properties and workaround
interface shapeConfig {
color?: string;
width?: number;
}
function createShape(config: shapeConfig): {color: string; area: number} {
let newShape = {color:"white", area:100};
if (config.color) {
newShape.color = config.color
}
if (config.width) {
newShape.area = config.width * config.width;
}
return newShape;
}
// let myShape = createShape({color:"red", opacity:0.5}); would give an error until we include an assertion:
let myShape = createShape({color:"red", opacity:0.5} as shapeConfig);
//intefrace for functions: created with the call signature:
interface searchFunc {
(source: string, subString: string):boolean;
}
let mySearch: searchFunc;
mySearch = function(src, sub) {
let result = src.search(sub);
return result > -1;
}
//indexable types
interface stringArray {
[index:number]: string;
}
let myArray: stringArray;
myArray = ['Bob', 'Fred'];
let myStr = myArray[0]; //will return the string value
//readonly indexable types
interface readOnlyArray {
readonly [index:number] : string;
}
let theArray:readOnlyArray = ['Bob', 'George', 'Mallory'];
// theArray[2] = 'Stan'; error!
//class types
//can describe parameters and methods implemented in the class
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime (d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {};
}
//interfaces describe the public side of the class
<file_sep>// different kinds of functions
// pure function -- creates and returns a value based only on input parameters and causes no side effects
// -- must have input parameters
// -- must no use any stateful values
// -- must return a value based only on input parameters
// -- must not cause any side effects: when code causes change outside of itself; example: saving something to a DB or writing to a file or making changes to what is seen on a web app
// -- simply return a value based on input parameters and methods run inside the function
// impure function -- procedure
// example:
let counter = 0;
function increment() {
couter++;
}
// -- does not need input parameters
// -- depends on stateful values, the counter
// -- does not return anything, does not even have inputs
// -- has side effects, it changes the value of the counter
// -- this one breaks all the rules, but function is impure if breaks only one
// -- a better description of this one is a procedure
// reasons to use pure functions:
// -- reusable
// -- composable - can be combined to create new functions
// -- easy to test
// -- always produce the same result
// -- and more
// about state:
// functional programming should eliminate state as much as possible
// and tightly controlling state when it is needed
<file_sep>function getFromDB(callback) {
var data;
var process = setTimeout(function(){
if (typeof(callback)=='function'){
data = [{name:'Todd'},{name:'Michael'},{name:'Portia'}];
callback(data);
}
},3000);
return data
};
function request() {
var data = getFromDB(myCallback);
console.log(data, "synchronous");
};
function myCallback(data) {
// console.log(data, "asynchronous");
for (var i = 0; i < data.length; i++) {
console.log(data[i].name);
}
};
request();
console.log('Hello');
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect, HttpResponse
from django.contrib import messages
from datetime import datetime
from django.db.models import Count
from .models import *
# Create your views here.
def index(request):
return render (request,'reviews/index.html')
def register(request):
if request.method != 'POST':
return redirect('/')
else:
context = {
'first_name':request.POST['first_name'],
'last_name':request.POST['last_name'],
'email':request.POST['email'],
'username':request.POST['username'],
'password':request.POST['password'],
'password_confirm':request.POST['password_confirm']
}
result = User.objects.ValidateRegistration(context)
for message in result[1]:
if result[0] == True:
messages.success(request, message)
else:
messages.error(request, message)
return redirect('/')
def login(request):
if request.method != 'POST':
return redirect('/')
username = request.POST['username']
password = request.POST['<PASSWORD>']
result = User.objects.LoginValidator(username, password)
if result[0]:
request.session['logged_user'] = result[1]
request.session['user'] = User.objects.get(id=request.session['logged_user']).first_name
return redirect('books')
else:
for message in result[1]:
messages.error(request, message)
return redirect('/')
return redirect("/")
def logout(request):
for key in request.session.keys():
del request.session[key]
return redirect('/')
def add(request):
if 'logged_user' not in request.session:
return redirect('/')
else:
context = {
'authors':Author.objects.all()
}
return render (request, "reviews/add.html", context)
def add_review(request):
if request.method != 'POST':
return redirect('/')
else:
context = {
'title':request.POST['title'],
'author':request.POST['author_list'],
'author_first_name':request.POST['author_first_name'],
'author_last_name':request.POST['author_last_name'],
'review_content':request.POST['review_content'],
'rating':request.POST['rating'],
'logged_user':request.session['logged_user']
}
print context
result = Review.objects.AddReviewValidator(context)
if result[0] == False:
for message in result[1]:
messages.error(request, message)
else:
messages.success(request, result[1][0])
return redirect('add')
def books(request):
reviews = Review.objects.all().order_by('-id')
latest = reviews[:3]
other = reviews[3:]
context = {
'latest':latest,
'other':other
}
print other
return render(request,'reviews/books.html', context)
def book_page(request, id):
book = Book.objects.get(id=id)
context = {
'book':book,
'reviews':book.reviews.all().order_by('-id')
}
return render(request, 'reviews/reviews.html', context)
def new_review(request, id):
if request.method != 'POST':
return redirect('/')
else:
context = {
'book_id':id,
'review_content':request.POST['review_content'],
'rating':request.POST['rating'],
'logged_user':request.session['logged_user']
}
print context
result = Review.objects.NewReviewValidator(context)
if result[0] == False:
for message in result[1]:
messages.error(request, message)
else:
messages.success(request, result[1][0])
return redirect('book_page', id)
def users(request, id):
users = User.objects.annotate(review_count=Count('reviews'))
user = users.get(id=id)
context = {
'user':user,
'reviews':user.reviews.all().order_by('-id')
}
return render(request, 'reviews/user.html', context) <file_sep>"use strict";
// call(), apply(), and bind() are three ways to stabilize 'this'
// call() can also pass in parameters if the function working with takes parameters, with first parameter being whatever you want 'this' to be:
function a(b, c, d) {
console.log(this);
console.log(b);
console.log(c);
console.log(d);
}
a.call(1, 2, 3, 4);
// apply() is also a function available to a function, difference is that the parameters are an array:
a.apply(5, [6, 7, 8]);
// use cases: use call unless the function takes a variable number of parameters
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
const tot = sum.call(null, 1,2,3,4);
console.log(tot);
const arr = [30,60,90,120,150,180,210,240,270,300,330,360];
const arrTot = sum.apply(null, arr);
console.log(arrTot);
// use of bind() is with function expressions:
// whatever we pass through bind() as parameter anchors 'this' for any time the function is called
// note: only works with function expressions because bind() assigns the meaning of "this" to the variable
const f = function() {
console.log(this);
}.bind(1);
f();
const check3 = {
check3This: function() {
console.log(this);
const checkOther = function() {
console.log(this);
}.bind(this);
checkOther();
}
}
check3.check3This();
<file_sep>from flask import Flask, render_template, request, redirect, session, flash
app=Flask(__name__)
app.secret_key = "awesomesecret"
@app.route("/")
def hello():
if 'users' not in session:
session['users'] = []
session['counter'] = 0
return render_template('index.html')
@app.route("/user", methods=['POST'])
def addUser():
user = {
"first_name": request.form['fname'],
"last_name": request.form['lname'],
"email": request.form['email'],
"id": request.form['counter']
}
#validation example:
if len(user['first_name']) < 2:
flash("First name must be longer than one character")
if len(user['last_name']) < 2:
flash("Last name must be longer than one character")
#check to see if there have been flashes in the session:
if "_flashes" in session:
return redirect("/")
#handling of variables:
session['user'] = user
session['counter'] += 1
print session['user']['first_name']
session['users'].append(user)
print session['users']
return redirect("/")
@app.route("/user/<id>")
def showUser(id):
for user in session['users']:
if user['id'] == id:
one_user = user
return render_template('user.html', user=one_user)
@app.route("/clear")
def clearSession():
session.clear()
return redirect("/")
app.run(debug=True, port=8888 )<file_sep>from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/")
def index():
ninja_turtles = [
"Leonardo", "Michelangelo", "Raphael", "Donatello"
]
return render_template("index.html", name="Ninja Turtles", turtles=ninja_turtles)
@app.route("/dictionary")
def each():
ninja_dict = [
{"name":"Leonardo","color":"blue","type":"turtle"},
{"name":"Michelangelo","color":"orange","type":"turtle"},
{"name":"Raphael","color":"red","type":"turtle"},
{"name":"Donatello","color":"purple","type":"turtle"},
{"name":"April","color":"pink","type":"human"}
]
return render_template("dictionary.html", turtles=ninja_dict)
@app.route("/action_turtle", methods=["POST"])
def action_turtle():
print request.form
# print request.form['name']
# print request.form['value']
# return "Hello {}".format(request.form['name'])
app.run(debug=True)<file_sep>function reverse(arr){
for(var i = 0; i < arr.length/2; i++){
var temp = arr[i];
arr[i] = arr[arr.length-i-1];
arr[arr.length-i-1] = temp;
}
console.log(arr);
}
reverse([1,2,3,4,5,6,7,8,9]);<file_sep>const performance = require('perf_hooks').performance;
function addUpTo(n) {
return n * (n+1) / 2;
}
let t1 = performance.now();
tot = addUpTo(100);
let t2 = performance.now();
console.log(tot);
console.log(`Time elapsed: ${(t2 - t1)/1000} seconds`);<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-14 13:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_dashboard', '0002_auto_20180812_2212'),
]
operations = [
migrations.AddField(
model_name='user',
name='user_profile',
field=models.CharField(default='user', max_length=255),
preserve_default=False,
),
]
<file_sep>word = 'supercalifragilisticexpialidocious'
penultimate = word[-2]
print(penultimate)
# slizing with index
# we want to get 'cali'
segment1 = word[word.index('cal'):word.index('fra')]
print(segment1)
# we want to get 'docious'
segment2 = word[word.index('do'):]
print(segment2)
word2 = "antidisestablishmentarianism"
answer = word2[word2.index('esta'):word2.index('aria')]
print(answer)<file_sep>#!c:\users\josebr~1\desktop\coding~1\codes\jbcodi~1\python~1\myenvi~1\python2django\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
<file_sep># get user email address
email = input("What is your email address? ").strip()
# slice out user name
username = email[:email.index("@")]
# slice domain name
domain = email[email.index("@") + 1:]
# format message
message = "Your username is {} and your domain name is {}.".format(username, domain)
# display output message
print(message)<file_sep>from __future__ import unicode_literals
from django.db import models
from datetime import datetime
from django.contrib import messages
import bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def ValidateRegistration(self, context):
errors = []
#validate if there are blank fields
if context['first_name'] == "":
errors.append("Please enter a first name")
if context['last_name'] == "":
errors.append("Please enter a last name")
if context['email'] == "":
errors.append("Please enter an email")
if context['username'] == "":
errors.append("Please enter a username")
if context['password'] == "":
errors.append("Please enter a password")
if len(errors) != 0:
return (False, errors)
else:
#more validations start
#validate if passwords match
if context['password'] != context['password_confirm']:
errors.append("Passwords don't match")
if len(errors) != 0:
return (False, errors)
else:
#validate email format:
if not EMAIL_REGEX.match(context['email']):
errors.append("Please use a valid email address")
#validate lengths of username and password
if len(context['username']) < 8:
errors.append("Please enter a username, at least 8 characters expected")
if len(context['password']) < 8:
errors.append("Please enter a password, at least 8 characters expected")
#validate if email already exists
email_exists = self.filter(email=context['email'])
if len(email_exists) != 0:
errors.append("Email already exists")
#validate if username alreagy exists
username_exists = self.filter(username=context['username'])
if len(username_exists) != 0:
errors.append("Username already exists")
#more validations end
if len(errors) != 0:
return (False, errors)
else:
#send data to database
self.create(
first_name = context['first_name'],
last_name = context['last_name'],
email = context['email'],
username = context['username'],
password = bcrypt.hashpw(context['password'].encode(), bcrypt.gensalt())
)
errors.append("User has been created")
return (True, errors)
def LoginValidator(self, username, password):
errors = []
if username == "":
errors.append("Please enter a username")
if password == "":
errors.append("Please enter a password")
if len(errors) != 0:
return (False, errors)
else:
logging_user = self.filter(username=username)
if len(logging_user) == 0:
errors.append("Username does not exist")
else:
user = logging_user[0]
user_password = <PASSWORD>
if bcrypt.checkpw(password.encode(), user_password.encode()):
return (True, user.id)
else:
errors.append("Password does not match")
return (False, errors)
class ReviewManager(models.Manager):
def AddReviewValidator(self, context):
messages = []
if context['title'] == "":
messages.append("Please enter a book title")
if context['author'] == 'author' and context['author_first_name'] == "":
messages.append("Please select author or enter a new one")
if context["review_content"] == "":
messages.append("Please write a review")
if len(context['review_content']) < 8:
messages.append("Please make your review at least 8 characters")
if context['rating'] == '*':
messages.append("Please select a star rating")
if len(messages) > 0:
return (False, messages)
else:
if context['author'] == 'author':
Author.objects.create(first_name=context['author_first_name'], last_name=context['author_last_name'])
Book.objects.create(title=context['title'], author=Author.objects.last())
else:
author = context['author']
Book.objects.create(title=context['title'], author=Author.objects.get(id=author))
Review.objects.create(user=User.objects.get(id=context['logged_user']),book=Book.objects.last(),content=context['review_content'],rating=context['rating'])
messages.append("Review successfully created!")
return (True, messages)
def NewReviewValidator(self, context):
messages = []
if context["review_content"] == "":
messages.append("Please write a review")
if len(context['review_content']) < 8:
messages.append("Please make your review at least 8 characters")
if context['rating'] == '*':
messages.append("Please select a star rating")
if len(messages) > 0:
return (False, messages)
else:
Review.objects.create(user=User.objects.get(id=context['logged_user']),book=Book.objects.get(id=context['book_id']),content=context['review_content'],rating=context['rating'])
messages.append("Review successfully created!")
return (True, messages)
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
password = models.CharField(max_length=255)
username = models.CharField(max_length=255)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
objects = UserManager()
def __repr__(self):
return "<{} {}>".format(self.first_name, self.last_name)
class Author(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __repr__(self):
return "<{} {}>".format(self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Author, related_name="books")
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
def __repr__(self):
return "<{}>".format(self.title)
class Review(models.Model):
user = models.ForeignKey(User, related_name="reviews")
book = models.ForeignKey(Book, related_name="reviews")
content = models.TextField()
rating = models.IntegerField()
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
objects = ReviewManager()
def __repr__(self):
return "<{} {}>".format(self.user, self.book)
<file_sep>name = "zen"
last = "coder"
print name
print "my name is " + name
print "my name is", name
print "my name is {} {}".format(name, last)
#STRING METHODS
#string.count(substring) return number of occurrences
string = "take me out to the ball game"
print (string.count('e'))
#string.endswith(substring) returns boolean
string = "made my day"
print (string.endswith('y'))
#string.find(substring) returns index of first occurrence of the substring within the string
string = "the cat in the hat"
print (string.find(' c'))
#string.isalnum(substring) returns boolean after checking if all characters are alphanumeric and string length > 0
numli = "this1254"
print numli.isalnum()
numli = "this 1254"
print numli.isalnum()
#string.join(list) returns a string that is all strings within our set concatenated
string = "mojo"
list = ['grass', 'banjo', 'truck', 'manure']
print string.join(list)
list = [1,2,3]
print string.join(str(list)) #str() converting int to str so it can concatenate with the string
music = ["tool", "teebee", "noisia", "mastodon"]
print " ".join(music)
print "-".join(music)
#string.split() returns a list of values split at a given character. default is split at every space
space_odd = "enough willi nilli"
print space_odd.split()
print space_odd.split('i')
socks_out = [2,5,8,3,6]
print str(socks_out).split()
#LISTS
my_list = ['documents','envelops','pens']
print my_list[0]
print my_list[1]
print my_list[2]
for items in my_list:
print items
#ACCESSING LIST ITEMS
#(list).append(<new_element>)
x = [1,2,3,4]
x.append(99)
print x
#getting specific with :
#lists are returned between brackets []. Use : to separate start and end index.
#If either start or end index are left blank, it is implied you start at very first or end at very last
list_x = [1,2,3,4,5,6,7,8,9,10]
print list_x[:] # will display entire list because both ends left blank
print list_x[3:] # will print from index[3] to the end
print list_x[:3] # will print from index[0] to but not including index[3]
print list_x[3:5] # will print index[3] and index[4]
print len(list_x) # will print the length of the list
#BUILT-IN FUNCTIONS FOR SEQUENCES
sequence = ('first', 'second', 'third', 'last') #enumerate creates numbered list from a list
for each, item in enumerate(sequence):
print (each, item)
for each, item in enumerate(sequence,100):
print (each, item)
my_numbers = [1,2,3,4,5]
def my_function(n):
return n*2
new_numbers = (map(my_function, my_numbers)) #map applies a function to all items in an input list
print new_numbers
print min(my_numbers) #get min or max
print max(my_numbers)
unsorted = [654,35,6,4376,23,765,234,765,23,4]
print sorted(unsorted) #sorts the list
#LIST BUILT-IN METHODS
my_list = ['ready','to','rumble']
my_list.append('today')
print my_list
their_list = ['hell','yeah']
our_list = my_list.extend(their_list)
mix_list = my_list.append(their_list)
print our_list #prints None
print mix_list #prints None
print my_list #prints the extended and appended their_list in my_list
print my_list.pop() #prints the extracted last element, which is the object last appended
print my_list.pop(1) #popped the index=1 element from the list!
print string
print string.index('o')
#CONDITIONAL EXPRESSIONS: IF
year = 2017
if year == 2019:
print "next year"
elif year == 2018:
print "this year"
else:
print "not interested"
#LOOPS
#for loop... for <counter> in <sequence or range>
my_array = ['rock',2,['paper','scissors'],False]
for i in my_array:
print i
for i in range (100,105): #note it will not include last one
print i
#while loop .... while <expression>
count = 0
while count < 5:
print count
count += 1
#LOOP CONTROL
#break exits the loop
for val in "string":
if val == "i":
break
print val
#continue does not execute but loops back to top with the next index
for val in "shtring":
if val == "h":
continue
print val
#pass is used to make program not even go into whatever code follows, but does not break the flow either. Used during development phase, often not used in final version.
<file_sep>
function Person(name, items){
if (!(this instanceof Person)) {
console.log(name, 'is not an instance of Person');
return new Person(name, items);
}
// const person = { name }; // we don't seem to need this
this.name = name;
this.items = items;
// this.take = take // we no longer need it here
}
// we attach the take method through the 'prototype' methodology and it is now a global method for Person-type objects
Person.prototype.take = function take(item, target) {
if(!target || !Array.isArray(target.items)) {
console.log('target does not have items array');
}
for (let index = 0; index < target.items.length; index++) {
if (item === target.items[index]) {
target.items.splice(index,1);
console.log(target.name+"'s "+item+" was taken by "+this.name)
this.items.push(item);
console.log("now "+this.name+" has the "+item)
return true;
}
}
return false;
}
const person1 = new Person('Bob', ['key','sandwich','tickets']);
const person2 = new Person('Jerry', ['phone','money','ring']);
console.log(person1);
console.log(person2);
person2.take('key', person1);
person1.take('money', person2);
console.log(person1);
console.log(person2);
// BECAUSE THE TAKE METHOD CONFORMS WITH RULES OF AN INTERFACE: THAT IT'S AN OBJECT WITH ITEMS AND ITEMS ARE AN ARRAY, WE CAN IMPLEMENT IT IN NON-PERSONS AS WELL AS LONG AS THEY CONFORM TO THIS SAME INTERFACE SEE LESSON 5<file_sep>def string_length(s):
if (isinstance(s, str)):
return(len(s))
else:
return("Sorry, parameter needs to be a string")
user_input = "7"
user_input_2 = 7
def string_len(s):
if type(s) == str:
return(len(s))
else:
return("Sorry, parameter needs to be a string")
print(string_len(user_input))
print(string_len(user_input_2))<file_sep># class MathDojo(object):
# def __init__(self):
# self.output = 0
# def add(self, *nums):
# self.output += sum(nums)
# return self
# def subtract(self, *nums):
# self.output -= sum(nums)
# return self
# def result(self):
# print self.output
# MathDojo().add(2).add(2,5).subtract(3,2).result()
class MathDojov2(object):
def __init__(self):
self.output = 0
def add(self, *nums):
arr = list(nums)
for item in arr:
if type(item) == int:
self.output += item
else:
self.output += sum(item)
return self
def subtract(self, *nums):
arr = list(nums)
for item in arr:
if type(item) == int:
self.output -= item
else:
self.output -= sum(item)
return self
def result(self):
print self.output
MathDojov2().add([1],3,4).add([3, 5, 7, 8], [2, 4.3, 1.25]).subtract(2, (2,3), [1.1, 2.3]).result()
<file_sep># this is the library used to work with dates and times
from datetime import datetime
# example of calculation of time since...
delta = datetime.now() - datetime(1900, 12, 31)
# return number of days between dates
print(delta.days)
# display today's date
today = datetime.now()
print(today.date())
# methods available
print(dir(datetime))
# create a datetime object:
then = datetime(1950, 12,31, 12, 1, 1, 8908)
print(then)
# create a datetime object from string:
new_date = datetime.strptime("2018-10-08", "%Y-%m-%d").date()
print(new_date)
# another example, notice we mimic the structure of the numeric data provided with the format indicated in second param
new_datetime = datetime.strptime("2018/10/08 13:04", "%Y/%m/%d %H:%M")
print(new_datetime)
# convert datetime object into a string
# use strftime = string from time
my_year = new_datetime.strftime("%Y")
my_date = new_datetime.strftime("%m/%Y")
print(my_year)
print(my_date)
print(new_date.year)
print(new_date.month)
print(new_date.day)<file_sep># get sentence from user
original = input("Please enter a sentence here: ").strip().lower()
# split sentence into words
words = original.split()
# for each word, look for vowel index
def vowel_index(word):
vowel_index = 0
for letter in word:
if letter not in "aeiou":
vowel_index = vowel_index + 1
else:
return vowel_index
# word conversion
def convert_words(word, index):
new_word = ""
if index == 0:
new_word = word + "yay"
else:
new_word = word[index:] + word[:index] + "ay"
return new_word
# create new word array
word_arr = []
for word in words:
i = vowel_index(word)
w = convert_words(word, i)
word_arr.append(w)
# stick words back together
pig_sentence = " ".join(word_arr).capitalize()
# output the final string
print(pig_sentence)
<file_sep>var myNumber = 42;
var myName = "Jose";
console.log('my name is ',myName,' and my number is ',myNumber);
var temp = myNumber;
var myNumber = myName;
var myName = temp;
console.log('my name is ',myName,' and my number is ',myNumber);
var temp = myNumber;
var myNumber = myName;
var myName = temp;
console.log('my name is ',myName,' and my number is ',myNumber);
<file_sep>for(var i = 0; i <= 100; i++){
if( i % 5 == 0 ){
console.log("coding");
}
if( i % 10 == 0 ){
console.log("dojo");
}
else{
console.log( i );
}
}<file_sep>"use strict";
// in the constructor pattern, inheritance is implemented with 'extend'
function Person(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
}
Person.prototype.full_name = function() {
return this.first_name + " " + this.last_name;
};
function Professional(honorific, first_name, last_name) {
Person.call(this, first_name, last_name);
this.honorific = honorific;
}
// we add inheritance by copying Person prototype to Professional prototype:
Professional.prototype = Object.create(Person.prototype);
// we can add methods to the Professional prototype
Professional.prototype.professional_name = function() {
return this.honorific + " " + this.first_name + " " + this.last_name;
};
// we can now implement
const prof = new Professional("Dr", "Manuel", "Briz");
console.log(prof);
console.log(prof.full_name());
console.log(prof.professional_name());
<file_sep>// immutably adding an object to an object array
const meals = [
{id: 1, description: 'Breakfast', calories: 420},
{id: 2, description: 'Lunch', calories: 520},
];
const meal = {id: 3, description: 'Snack', calories: 180};
const updatedMeals = [...meals, meal];
// console.log(updatedMeals);
// how to immutably alter values in an array? Use .map()
const numbers = [1,2,3];
function double(number) {
return number * 2;
}
const doubledNumbers = numbers.map(double);
// console.log(doubledNumbers);
function modifyMeal(meal) {
if (meal.id === 2) {
return {
...meal,
description: 'Linner'
};
}
return meal;
}
const updateMealDescription = updatedMeals.map(modifyMeal);
// console.log(updateMealDescription);
// how to remove an item from an array in an immutable way? Use .filter()
const filteredMeals = updatedMeals.filter(function(meal) {
return meal.id !== 2;
});
// console.log(filteredMeals);
const friends = ['Alfred', 'Monik'];
const newFriend = 'Ralf';
const updatedFriends = [...friends, newFriend];
console.log(updatedFriends);
function getLength(friend) {
return friend.length;
}
const nameLengths = updatedFriends.map(getLength);
console.log(nameLengths);
const filteredFriends = updatedFriends.filter(function(friend) {
return friend.length < 6;
});
console.log(filteredFriends);
<file_sep>//Given a name, return the initials
function getInitials(e){
var arr = e.split(" ");
//console.log(arr.length);
var initials = [];
for (i = 0; i < arr.length; i++){
initials.push(arr[i][0]);
}
//console.log(initials);
for (j = 0; j < initials.length; j++){
document.getElementById('demo').innerHTML += initials[j];
}
}
getInitials("<NAME>");
<file_sep>def get_length(arg):
return len(arg)
user_input = input("Enter a word or phrase: ")
print(get_length(user_input))<file_sep>module.exports = {
age(person) {
return person.age + 10;
}
};
<file_sep>def division(a, b):
try:
return a/b
except:
return 0
array = [-2,-1,0,1,2]
for n in array:
print(division(1, n))
# using the exception name. this is preferable because it helps specify an expected error type. if different type of error occurs, then we'll get to see it and handle it
def fool_proof_division(a, b):
try:
return a/b
except ZeroDivisionError:
return 0
for i in array:
print(fool_proof_division(1, i))<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^users$', views.users),
url(r'^users/new$', views.new),
url(r'^process$', views.process),
url(r'^users/(?P<id>\d+)$', views.show),
url(r'^users/(?P<id>\d+)/edit$', views.edit),
url(r'^users/(?P<id>\d+)/editing$', views.editing),
url(r'^users/(?P<id>\d+)/delete$', views.delete),
]<file_sep>class Pizza {
constructor(radius,slices) {
this.radius = radius;
this._slices = slices;
};
get slices() {
return this._slices;
};
set slices(slices) {
this._slices = slices
};
};
// the attribute this._slices uses _ to differentiate between the parameter slices and the attribute slices so we can use get and set as we've done here. The use of _ is not required but it's convention.
const pie = new Pizza(12,6);
console.log(pie.slices); // we use get
pie.slices = 12; // we use set
console.log(pie.slices);
// custom getters: we can create custom getters like so:
class Circle {
constructor(x,y,radius) {
this.x = x;
this.y = y;
this.radius = radius;
};
get diameter() {
return this.radius*2;
};
};
const circle9 = new Circle(6,3,2);
console.log(circle9.diameter);
<file_sep>// Load the express module and store it in the variable express (Where do you think this comes from?)
const express = require("express");
// console.log("Let's find out what express is", express);
// invoke express and store the result in the variable app
const app = express();
// console.log("Let's find out what app is", app);
// use app's get method and pass it the base route '/' and a callback
app.get('/', function(request, response) {
// just for fun, take a look at the request and response objects
// console.log("The request object", request);
// console.log("The response object", response);
// use the response object's .send() method to respond with an h1
response.send("<h1>Hello Express</h1>");
});
// the following will be used to handle requests for static content; now all static files like js and css need to be here
app.use(express.static(__dirname + "/static"));
console.log(__dirname);
// ejs is a templating engine. need to download via terminal comman 'npm install ejs'
// next, tell express we are going to use ejs
// This sets the location where express will look for the ejs views
app.set('views', __dirname + '/views');
// Now lets set the view engine itself so that express knows that we are using ejs as opposed to another templating engine like jade
app.set('view engine', 'ejs');
//example of middleware; a request to render information from a database
app.get('/users', function(request, response) {
//hard-coded user data
var users_array = [
{name:'Michael', email:'<EMAIL>'},
{name:'Jay', email:'<EMAIL>'},
{name:'Brendan', email:'<EMAIL>'},
{name:'Andrew', email:'<EMAIL>'},
];
response.render('users', {users: users_array})
});
// tell the express app to listen on port 8000, always put this at the end of your server.js file
app.listen(8000, function() {
console.log("listening on port 8000");
})<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core import serializers
from django.shortcuts import render, HttpResponse, redirect
from .models import Note
# Create your views here.
def index(request):
return render(request, "ajax_post/index.html")
def note(request):
Note.objects.create(content=request.POST['content'])
notes = Note.objects.all().order_by('-id')
context = {
'notes':notes
}
return render(request, 'ajax_post/notes.html', context)<file_sep>from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import MySQLConnector
app = Flask(__name__)
app.secret_key = "emailvalid1234"
mysql = MySQLConnector(app, 'email_validation')
@app.route("/")
def index():
if 'emails' not in session:
session['emails'] = []
return render_template('index.html')
@app.route('/validate', methods=['POST'])
def validate():
email_check = request.form['email']
query = "SELECT * FROM emails"
data = {"specified":email_check}
all_emails = mysql.query_db(query,data)
#print all_emails
counter = 0
for email in all_emails:
if email_check == email['email']:
session['emails'].append(email)
counter += 1
else:
continue
if counter == 0:
flash(u'Email not in our database, try again!', 'lead')
return render_template("index.html")
else:
flash('Yep! {} is in our database'.format(email_check))
query = "INSERT INTO `email_validation`.`matches` (`email`, `created_at`, `updated_at`) VALUES (:specified_email, NOW(), NOW());"
data = {'specified_email':email_check}
mysql.query_db(query,data)
return redirect('/success')
@app.route('/success')
def success():
query = "SELECT * FROM matches"
matches = mysql.query_db(query)
return render_template("success.html", email_matches=matches)
app.run(debug=True)
<file_sep>//functions take type annotations
function greeter(person: string) {
return `Hello ${person}`;
}
let user = "<NAME>";
document.body.innerHTML = greeter(user);
//interfaces help shape the data inputs by grouping parameters and methods; ? makes parameters optional
interface Person {
firstName: string;
lastName: string;
age?: number;
}
function greeting(person: Person) {
return `Hello, ${person.firstName} ${person.lastName}`;
}
let user2 = {firstName: "Jane", lastName: "Dammit"};
document.body.innerHTML = greeting(user2);
//classes work same as in ES6, are a shorthand for prototype OO
class Student {
fullName: string;
constructor(public firstName: string, public lastName: string, public middleName?: string) {
this.fullName = firstName + " " + middleName + " " + lastName;
}
}
interface Dude {
firstName: string;
lastName: string;
}
function sayHello(student: Dude) {
return `Hello, ${student.firstName} ${student.lastName}`;
}
let user3 = new Student("Bob", "Corker");
document.body.innerHTML = sayHello(user3);
<file_sep>const color = require('colors');
const db = require('./mysql'); // with promisify
const database = require('./database'); // as object
const date = new Date([2018, 09, 21]);
const queryDate = (() => {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return [year, month, day].join('-');
})();
const queryScript = "SELECT cash_buyer, 3_month_mean as month_3, dec1_mean, dec2_mean, dec3_mean FROM primary_aluminium WHERE date = '"+ queryDate + "'";
// console.log(color.white(queryDate));
// console.log(color.white(queryScript));
const prices = function() {
db.query(queryScript, function(err, result) {
if (err) console.error(color.red(err.message))
// console.log(color.yellow(result[0]));
const {cash_buyer, month_3, dec1, dec2, dec3} = result[0];
return result[0];
});
}
const settlement = prices().then(result);
// async function settle() {
// try {
// const settle = await db.query(queryScript);
// return settle;
// } catch (err) {
// console.error(color.red(err.message))
// }
// };
// const settlement = settle();
settlement.then(function(value) {
console.log(value);
});
console.log(settlement);
<file_sep>#an object
me = {
"name":"Jose",
"last":"Briz"
}
#a list
my_list = [me,1,2,3,4,5]
print my_list[0]["name"] # me object is the first element, co can call it and an element inside it as dictionary
my_list[0]["last"] = "Lom"
print me
#slicing:
list_x = [1,2,3,4,5,6,7,8,9,10]
print list_x[:] # will display entire list because both ends left blank
print list_x[3:] # will print from index[3] to the end
print list_x[:3] # will print from index[0] to but not including index[3]
print list_x[3:5] # will print index[3] and index[4]
#common list methods:
#.append <list>.append(<new_element>), new element is an object with its own index
#.extend <list>.extend(<new_element>), new element values are in sequence with original, each with an index
#.pop <list>.pop(index), specify index and pop removes that element from the sequence
#.index <list>.index(value), specify a value within the list and .index returns its position within the list
#common list objects:
#enumerate(sequence) will create a numbered list
#.enumerate(sequence,n) will start the numbering at specified 'n'
#map(function,squence) applies the function to every item in the sequence
#my_list = [some sequence]
#def my_function():
#map(my_function,my_list)
#min(sequence) returns minimum value in a given sequence
#sorted(sequence) sorts the values in a given sequence<file_sep>const book_router = require('./book.routes');
const router = require('express').Router();
module.exports = router
.use('/books', book_router);
// this book_router is creating the resource portion of the route
// /resource/books
// book.routes.js creates the last bit of the route
// /resource/books/:book_id (when necessary)
// if there were more routes, could create
// author.routes.js, for example
<file_sep>import unittest
from underscore import Underscore
class UnderscoreTest(unittest.TestCase):
def setUp(self):
# create an instance of the Underscore module we created
self.case_study = Underscore()
# initialize a list to run our tests on
self.test_list = [1,2,3,4,5]
def testMap(self):
return self.
def testReduce(self):
pass
def testFind(self):
pass
def testFilter(self):
pass
def testReject(self):
pass
if __name__ == "__main__":
unittest.main()
<file_sep>import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appHostBindingHighlight]'
})
export class HostBindingHighlightDirective {
// as a parameter we pass the property we want to access.
// since it is a style property, we use it and then do camelCase for the DOM style we want to modify
// the backgroundAlter name is something we come up with
// then we provide an initial value with =
@HostBinding('style.backgroundColor') backgroundAlter = 'transparent';
@HostListener('mouseenter') mouseenter(eventData: Event) {
this.backgroundAlter = 'purple';
}
@HostListener('mouseleave') mouseleave(eventData: Event) {
this.backgroundAlter = 'transparent';
}
}
<file_sep>
// constructor function
function personMaker(name, items){
const person = { name };
person.items = items;
// make the take function available to the person
person.take = take
// take function
function take(item, target) {
if(!target || !Array.isArray(target.items)) {
console.log('target does not have items array');
}
for (let index = 0; index < target.items.length; index++) {
if (item === target.items[index]) {
// remove item from target
target.items.splice(index,1);
console.log(target.name+"'s "+item+" was taken by "+person.name)
// assign item to person doing the action
person.items.push(item);
console.log("now "+person.name+" has the "+item)
return true;
}
}
return false;
}
return person;
}
// instances of personMaker
const person1 = personMaker('Bob', ['key','sandwich','tickets']);
const person2 = personMaker('Jerry', ['phone','money','ring']);
console.log(person1.name, person1.items);
console.log(person2.name, person2.items);
person2.take('key', person1);
person1.take('money', person2);
console.log(person1.name, person1.items);
console.log(person2.name, person2.items);
// THE TAKE METHOD IS ATTACHED TO EVERY PERSON, SO IT IS A REPETITIVE TRAIT THAT COULD BE STREAMLINED SO IT OCCUPIES LESS MEMORY. IN ORDER TO NOT REPEAT FUNCTIONS, WE COULD REFACTOR THE CODE SO 'TAKE' IS A GLOBAL CAPABILITY AVAILABLE TO OBJECTS MEETING THE TARGET CRITERIA (THAT ARE OBJECTS WITH AN ITEM CALLED ITEMS THAT IS AN ARRAY)
// SEE IT REFACTORED ON PART 3<file_sep>import math
dir(math)
#a module is a single file
#file name: arithmetic.py
# def add(x, y):
# return x + y
# def multiply(x, y):
# return x * y
# def subtract(x, y):
# return x - y
#we can import the arithmentic module:
# import arithmetic
# print arithmetic.add(5, 8)
# print arithmetic.subtract(10, 5)
# print arithmetic.multiply(12, 6)
#a package is a collection of modules, or a directory of multiple packages and modules
# from my_package.subdirectory import my_functions
# sample_project
# |_____ python_file.py
# |_____ my_modules
# |_____ __init__.py
# |_____ test_module.py
# |_____ another_module.py
# |_____ third_module.py
# the __init__.py file MUST be part of the package; it can be empty. But has to be there because it indicates that the directory containing it is a Python package, so it can be imported the way a module is imported.
# to import, for example, the test_module, we write:
# from my_modules import test_module
# or
# import my_modules.test_module
# the __init__.py file also decides which modules this package will export as an API, while keeping the others internal. This is achieved by overriding the __all__ variable like so:
# __init__.py:
# __all__ = ["test_module"]<file_sep>//remember this means the context
function Person(name) {
this.name = name;
};
//create an instance of Person
const timmy = new Person('Timmy');
console.log(timmy);
console.log(timmy.name);
//assign a new method to the Person class
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name}`);
};
timmy.sayHello();
//new create a new class that inherits from Person class
function Parent(name) {
Person.call(this, name);
};
const tommy = new Parent("Tommy");
console.log(tommy);
console.log(tommy.name);
// tommy.sayHello();
//and that's it! the method .call() of inheritance only inherits the properties; nothing from the prototype chain
//to fix that, we work at prototype level:
//1. first we make parent prototype equal Person prototype, but leaving it like this would override the whole Parent class
//2. so additionally we make the Parent prototype constructor equal the Parent prototype function...
Parent.prototype = Object.create(Person.prototype);
Parent.prototype.constructor = Parent;
//these functions need to be run above the definition of tommy, we'll continue in next tab....
<file_sep>from flask import Flask, session, render_template, request,redirect
app = Flask(__name__)
app.secret_key = "crypticdecript"
@app.route("/")
def index():
if "count" in session:
session["count"] += 1
else:
session["count"] = 1
if session["count"] > 1:
image = "friendly.png"
else:
image = "scary.jpg"
return render_template("counter.html", count=session['count'], image=image)
@app.route("/clear")
def clearSession():
session.clear()
return redirect("/")
app.run(debug=True)
<file_sep>a = ['magical unicorns',19,'hello',98.98,'world']
def function_alchemy(a):
words = []
nums = []
for i in a:
if type(i) == str:
words.append(i)
if type(i) != str and type(i) != bool:
nums.append(i)
style = type(a[0])
if all(type(i)==int for i in a):
print "The list you entered is of integer type."
elif all(type(i)==str for i in a):
print "The list you entered is of string type"
else:
print "The list you entered is of mixed type."
if words != []:
print "String: "+ " ".join(words)
if nums != []:
print "Sum:", sum(nums)
function_alchemy(a)
<file_sep>// Here is an example of delegation
// function leadBootcamp's outcome is console.log of some outcome. The outcome is actually the return of another function.
// how it does it:
// 1. leaderBootcamp takes two arguments: language and leader.
// 2. initializes a variable called outcome that calls a function with name = leader argument that accepts an argument and this argument has been passed on through the language argument.
// to summarize:
// This is a function that just prints the result of another list of instructions
function printResult(doSomething) {
var result = doSomething(); // store the return value of the callback parameter
console.log(result); // print the result!
}
printResult(function returnFive(){ return 5 }) // this should print "5"
// we used this type of delegation in es6_card_deck_assignment.js to name and assign worth to the cards
// now, to the example:
function leadBootcamp(language, leader){
var outcome = leader(language);
console.log(outcome);
}
function Mike(language){
var languages={
'javascript':'successful leader',
'PHP':'successful leader',
'Python':'successful leader',
'Ruby':'successful leader',
}
if(languages[language]){
return languages[language];
}
else {
return "maybe not yet";
}
}
function Charlie(language){
var languages={
'javascript':'successful leader',
'PHP':'successful leader',
'Python':'successful leader',
'Ruby':'successful leader',
}
if(languages[language]){
return languages[language];
}
else {
return "maybe not yet";
}
}
function Jimmy(language){
var languages={
'javascript':'successful leader',
'PHP':'successful leader',
'Python':'successful leader',
'Ruby':'successful leader',
'iOS':'successful leader',
'java_android':'successful leader',
}
if(languages[language]){
return languages[language];
}
else {
return "maybe not yet";
}
}
leadBootcamp('java_android', Mike);
leadBootcamp('java_android', Charlie);
leadBootcamp('java_android', Jimmy);
<file_sep>// Sets
// set data structure is like an array except there are no duplicate items and values are in no particular order.
// their use is to detect the presence of an item
// es6 has a builtin set item, but does not contain all the methods available to sets
function mySet() {
// this collection will hold the set
let collection = [];
// this method will check for the presence of an element
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method returns all the values in the set
this.values = function() {
return collection;
};
// this method will add an element ot the set
this.add = function(element) {
if(!this.has(element)) {
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)) {
index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method returns the size of the collection
this.size = function() {
return collection.length;
};
// this method returns the union of two sets
this.union = function(otherSet) {
const unionSet = new mySet();
const firstSet = this.values();
const secondSet = otherSet.values();
firstSet.forEach(function(e) {
unionSet.add(e);
});
secondSet.forEach(function(e) {
unionSet.add(e);
});
return unionSet;
};
// this method returns elements that two sets have in common
this.intersection = function(otherSet) {
const intersectionSet = new mySet();
const firstSet = this.values();
firstSet.forEach(function(e) {
if(otherSet.has(e)) {
intersectionSet.add(e);
}
});
return intersectionSet;
};
// this method returns the difference of two sets as a new set
this.difference = function(otherSet) {
const differenceSet = new mySet();
const firstSet = this.values();
firstSet.forEach(function(e) {
if(!otherSet.has(e)) {
differenceSet.add(e);
}
});
return differenceSet;
};
// this method tests if the set is a subset of another set
// every is an existing array method in js
this.subset = function(otherSet) {
const firstSet = this.values();
return firstSet.every(function(value) {
return otherSet.has(value);
});
};
}
const setA = new mySet();
const setB = new mySet();
setA.add('a')
setB.add('b')
setB.add('c')
setB.add('a')
setB.add('d')
console.log(setA.subset(setB));
console.log(setA.intersection(setB).values());
console.log(setB.difference(setA).values());
setC = setA.union(setB);
console.log(setC.values());<file_sep>// partial application: assigning a fixed value to one or some parameters of a general formula as you use it, specialize it on something
const greet = (greeting, name) => `${greeting} ${name}!`;
const greeting = 'Hello';
const name = 'Mike';
console.log(greet(greeting, name));
// rest of the example used Ramda library<file_sep>def selection_sort(arr):
min = arr[0]
for i in range(0,len(arr)):
for j in range(i,len(arr)):
min = arr[i]
if arr[j] < min:
arr[i], arr[j] = arr[j], arr[i]
print arr
selection_sort([6,5,4,3,2,1])
<file_sep>// used to copy an object and spread its contents within the enclosure of the new one
const me = {
name: 'Jose',
age: '44',
hobbies: ['Music', 'Coding'],
greet() {
console.log('Hello, I\'m ' + this.name);
}
}
const miniMe = {...me, age: 3};
console.log(me, miniMe);
me.greet();
const hobbies = [...me.hobbies];
console.log(hobbies);<file_sep>// classical and prototypical inheritance
// in js we don't have classes, so prototypical inheritance applies
// a prototype is a parent of another object
// every object (except one, the root object) has a parent or prototype and it inherits all the members defined in its prototype
let x = {};
console.log(Object.getPrototypeOf(x));
// js looks for properties from ground up, from the element it goes up the prototype chain to find the member being called
let arr = [];
console.log(Object.getPrototypeOf(arr));
let arrProto = Object.getPrototypeOf(arr)
let arrAll = Object.getPrototypeOf(arrProto);
console.log(arrAll);
// voila! the prototype of array is object
<file_sep>me ={
"name":"Jose",
"age":"43",
"country of birth":"US",
"favorite language":"python"
}
for key,data in me.iteritems():
print "My {} is {}".format(key,data)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-14 21:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user_dashboard', '0006_auto_20180814_1439'),
]
operations = [
migrations.RenameField(
model_name='comment',
old_name='comment',
new_name='content',
),
migrations.RenameField(
model_name='message',
old_name='message',
new_name='content',
),
migrations.RemoveField(
model_name='message',
name='user',
),
migrations.AddField(
model_name='message',
name='message_from',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='messages_from', to='user_dashboard.User'),
preserve_default=False,
),
migrations.AddField(
model_name='message',
name='message_to',
field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, related_name='messages_to', to='user_dashboard.User'),
preserve_default=False,
),
]
<file_sep>$(document).ready(function(){
for(var i = 1; i < 600; i++){
$('.pokemon').append("<img src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/"+i+".png' alt='"+i+"'>");
}
$('.pokemon').on('click','img',function(){
var which = $(this).attr('alt')
$.get("https://pokeapi.co/api/v2/pokemon/"+which+"/", function(res){
console.log(res);
$('.details').html('');
var name = (res.forms[0].name);
var image = (res.sprites['front_default']);
var height = res.height;
var weight = res.weight;
var type_str = "";
type_str += "<h4>Types</h4>";
type_str += "<ul>";
for(var i = 0; i < res.types.length; i++){
type_str += "<li>"+res.types[i].type.name+"</li>";
}
type_str += "</ul>";
var able_str = "";
able_str += "<h4>Abilities</h4>"
able_str += "<ul>"
for(var i = 0; i < res.abilities.length; i++){
able_str += "<li>"+res.abilities[i].ability.name+"</li>"
}
able_str += "</ul>"
$('.details').append("<h2>"+name+"</h2>");
$('.details').append("<img src="+image+" alt="+name+">");
$('.details').append(type_str);
$('.details').append(able_str);
$('.details').append("<p>height: "+height+" weight: "+weight+"</p>");
})
})
$('button').click(function(){
$('.details').html('');
})
})<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-14 14:51
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('user_dashboard', '0003_user_user_profile'),
]
operations = [
migrations.CreateModel(
name='Comments',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comment', models.TextField(max_length=1000)),
('created_at', models.DateTimeField(default=datetime.datetime.now)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('comment', models.TextField(max_length=2000)),
('created_at', models.DateTimeField(default=datetime.datetime.now)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='user_dashboard.User')),
],
),
migrations.AddField(
model_name='comments',
name='message',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='user_dashboard.Message'),
),
migrations.AddField(
model_name='comments',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='user_dashboard.User'),
),
]
<file_sep>c = 10
d = 5
# not
if c > d:
print('it worked')
else:
print("it didn't")
if not c > d:
print('it worked')
else:
print("it didn't")
# or
if c > 10 or d > 1:
print('it worked')
else:
print("it didn't")
# and
if c >= 10 and d > 1:
print('it worked')
else:
print("it didn't")
# not and and
if not (c > 10 and d > 1):
print('it worked')
else:
print("it didn't")
# not and or
if not (c > 10 or d > 1):
print('it worked')
else:
print("it didn't")
# more advanced example
c = 6
d = 2
if (c > 5 and d > 5) or (c > 1 and d > 1):
print('it worked')
else:
print("it didn't")
<file_sep>const mysql = require('mysql');
class Database {
constructor (config) {
this.connection = mysql.createConnection(config);
}
query(query, args) {
return new Promise((resolve, reject) => {
this.connection.query(query, args, (err, data) => {
if (err) return reject(err);
resolve(data);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err) return reject(err);
resolve();
});
});
}
}
module.exports = Database;<file_sep>// object literals
const circle = {
radius: 1,
location: {
x: 1,
y: 1
},
draw: function() {
console.log(`drawing radius of ${this.radius} centered at (${this.location.x}, ${this.location.y}).`);
}
};
circle.draw();
<file_sep>print "Hello World!"
x = "hello python"
print x
y = 42
print y
# comment
""" comment"""
'''comment'''
# several ways to concatenate: with + and with , notice the difference in output between the two!
def say_hello(name):
if name:
print 'hello, ' + name + ', from the function argument'
print 'hello, ',name,', from the function argument'
else:
print 'no name'
say_hello('chang')
# curly brackets and .format() method of concatenation
# step 1: create variables; step 2: concatenate with .format() function
my_name = "Zen"
my_lastname = "Coder"
print 'My name is {} {}'.format(my_name, my_lastname)
# String Methods
# Methods are functions we can run on a string. The most common ones are:
x = "Hello World"
print x.upper() #prints variable with all uppercase letters
y = x.count('lo') #count number of occurrences of specified string
print y
z = x.endswith('y')
print z
idx = x.find('e')
print idx
boo = x.isalnum() #checks if string length > 0 and all alphanumeric
print boo #similar methods are: .isdigit() .isalpha() .islower() .isupper()
people = ['chang','cheng','chong','li','chung']
print "-".join(people) # notice the list of items to be joined goes in the parenth and the joiner element goes before
print " ".join(people)
joiner = " "
print joiner.join(people)
joined = joiner.join(people)
print joined.split(" ") # to split, do exactly the opposite! splitter goes in the parenthesis
splitter = " "
print joined.split(splitter)
# List Operations
vegetables = ['lettuce', 'tomato', 'onion']
fruits = ['apples', 'oranges', 'dades']
salad = fruits + vegetables
print salad
meal = 3 * vegetables
print meal
#diet = salad - fruits # this does not work because - is an unsupported operand of a list
#menu = vegetables + fruits[2] #this does not work because fruits[2] not a string according to the error, but we can use it to get inside the list and retrieve the string on index [2]. This is because it cannot do list operation between list and a single item. For that, there are other methds.... see below...
change = fruits[2]
print change
# List built-in methods
# append()
diet = []
diet = vegetables.append('more lettuce')
print diet
var = [1,2,3,4,5]
var.append(99)
print var
var.append('only')
print var
print vegetables
vegetables.append('only')
print vegetables
#extend() -- adds values of a second sequence to a given sequence
cars = ['volvo', 'mercedes']
vehicles = ['motorcycle', 'tricycle']
print cars.extend(['motorcycle', 'tricycle'])
#pop()
#index()
# List built-in functions
#len(sequence)
my_list = [1, "zen", True]
print len(my_list)
#enumerate(sequence)
#loop over a list and have an automatic counter:
food = ['milk', 'apple', 'broccoli', 'ice cream']
for counter, value in enumerate(food,1):
print counter
food = ['milk', 'rice', 'popcorn', 'tomato']
counter_list = list(enumerate(food,1))
print (counter_list)
#map(function, sequence)
#min(sequence)
#sorted(sequence)<file_sep>// CHALLENGE: do a counter without using global variables!
function count(){
var counter = 0;
function innerCount(){
return ++counter;
}
return innerCount;
}
outCount = count();
//'counter' is undefined because it is an inner variable
// console.log(counter);
//'function innerCount' is undefined because it is an inner function
// console.log(innerCount);
//so, how can we access the inner variables and functions if we don't want to use global variables and functions??
//notice this will reference the inner function
console.log(count());
//notice this will reference the inner function too because the variable is set to equal the function
console.log(outCount);
//here we get the results, as we run the variable-function
//it works, although we are using inner functions, because innerCount 'remembers' the context it is created in, so remembers the local variable 'counter'
console.log(outCount());
console.log(outCount());
console.log(outCount());
console.log(outCount());
<file_sep># import folium for mapping
# import pandas to read file
import folium
import pandas
# get data from the file
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
# to get the titles of the colums:
# print(data.columns)
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
# create the map features where volcanoes will be appendend
map = folium.Map((45,-115), width="50%", height="50%", zoom_start=2, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
# iterate through two or more lists at the same time with zip()
for lt, ln, ele in zip(lat, lon, elev):
fg.add_child(folium.Marker(location=(lt, ln), popup="Elevation: " + str(ele) + " m", icon=folium.Icon(color="darkgreen")))
map.add_child(fg)
map.save("Volcanoes.html")
<file_sep>temperatures = [10, -20, -289, 100]
def c_to_f(c):
if c < -273.15:
return "That temperature makes no sense!"
else:
f = c * 9/5 + 32
with open("temperatures.txt", "a") as temps:
temps.write(str(f) + "\n")
return f
for t in temperatures:
print(c_to_f(t))
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login and Registration</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class=flashes>
{% for category, message in messages %}
<p class="{{ category }}">{{ message }}</p>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<fieldset>
<legend>Registration</legend>
<form action="/register" method="post">
<input type="text" name="fname" placeholder="First Name">
<input type="text" name="lname" placeholder="Last Name">
<input type="text" name="email" placeholder="Email">
<input type="text" name="pword" placeholder="<PASSWORD>">
<input type="submit">
</form>
</fieldset>
<fieldset>
<legend>Login</legend>
<form action="/login" method="post">
<input type="text" name="email" placeholder="Email">
<input type="text" name="pword" placeholder="<PASSWORD>">
<input type="submit">
</form>
</fieldset>
</div>
</body>
</html><file_sep>function orderSupplies(item, callback) {
let warehouse;
const deliveryTime = Math.random() * 3000;
setTimeout(() => {
warehouse = {
paint: {
product: 'Neon green paint',
directions: () => { return 'mix it'}
},
brush: {
product: 'Horsehair brush',
directions: () => { return 'start painting!' }
}
};
callback(warehouse[item]);
}, deliveryTime);
};
function receivedItem(item) {
let items = [];
items.push(item);
console.log(items.length)
};
orderSupplies('paint', receivedItem);
orderSupplies('brush', receivedItem);
<file_sep>def insertion(arr):
for i in range(0,len(arr)):
# print "i loop :",arr[i]
num = arr[i]
for j in range(i-1,-1,-1):
# print "j loop :",arr[j]
ber = arr[j]
if num < ber:
arr[i] = arr[j]
arr[j] = num
print arr
insertion([3,2,1,0])
<file_sep>#NESTING
# dictionaries can nest lists and tuples
context = {
'questions': [
{ 'id': 1, 'content': 'Why is there a light in the fridge and not in the freezer?'},
{ 'id': 2, 'content': 'Why don\'t sheep shrink when it rains?'},
{ 'id': 3, 'content': 'Why are they called apartments when they are all stuck together?'},
{ 'id': 4, 'content': 'Why do cars drive on the parkway and park on the driveway?'}
]
}
#RETRIEVE data at different levels:
# for data in context.iterkeys():
# print data
# for data in context.itervalues():
# print data
for data in context.iteritems():
print data
for data in context.items():
print data
#ITERATE elements with a for loop
for key, data in context.items():
# print data
for value in data:
print "Question #", value["id"], ": ", value["content"]
print "----"
#LISTS FROM DICTIONARIES
data ={"house":"Haus","cat":"Katze","red":"rot"}
print data.items()
#[('house', 'Haus'), ('cat', 'Katze'), ('red', 'rot')]
print data.keys()
#['house', 'cat', 'red']
print data.values()
#['Haus', 'Katze', 'rot']
#DICTIONARIES FROM LISTS
#zip() like a zipper, it combines one list as key and the other as value, in order, returns list of tuple pairs [('key','value'),('key','value') ...etc]
#dict() converts the zip() tuples into a real dictionary { "key":"value","key":"value" ..etc}
#example:
#from lists:
dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
countries = ["Italy", "Germany", "Spain", "USA"]
#zip() creates tuples
country_specialities = zip(countries, dishes)
print country_specialities
#Result is...
#[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'hamburger')]
#dict() creates dictionaries
country_specialities_dict = dict(country_specialities)
print country_specialities_dict
#Result is...
#{'Germany': 'sauerkraut', 'Spain': 'paella', 'Italy': 'pizza', 'USA': 'hamburger'}
#zip() would write off superfluous keys or values
countries = ["Italy", "Germany", "Spain", "USA", "Switzerland"]
dishes = ["pizza", "sauerkraut", "paella", "hamburger"]
country_specialities = zip(countries,dishes)
print country_specialities
#Result is...
#[('Italy', 'pizza'), ('Germany', 'sauerkraut'), ('Spain', 'paella'), ('USA', 'hamburger')]
#...no Switzerland
<file_sep>const person = { name: "Jose" };
const objectBase = Object.getPrototypeOf(person);
let descriptor = Object.getOwnPropertyDescriptor(objectBase, "toString");
// access the prototype
console.log(objectBase);
// access the properties of base object methods
console.log(descriptor);
// we can configure the properties of objects we create
Object.defineProperty(person, "name", {
writable: false,
enumerable: true,
configurable: false
});
// configurable: we could delete it
delete person.name;
// writable: we can override its value
person.name = "Bob";
console.log(person.name);
// enumerable: it will appear in object traverse
for (key in person) {
console.log(key);
}
<file_sep>"use strict";
// in JS, this is determined by the calling context
// the way a function is called.
// the calling object.
// if there is no calling context as in the case of a named function that gets called at runtime, the calling context is global.
// if using "strict", calling context would be undefined
const obj = {
name: "Objecto",
theThis: function() {
console.log(this);
}
}
obj.theThis(); // = the object itself
console.log(obj); // === proof that it is the object itself
const func = obj.theThis;
// func(); // = object global
// because func called theThis within the global object, this is the global object.
// on the contrary, if this is called within the object, this is the object.
// this becomes the global context when called within functions even if inside an object:
const check = {
checkThis: function() {
console.log("first log ", this);
function checkOther() {
console.log("second log", this);
}
checkOther();
}
}
check.checkThis(); // returns 'check' on first console.log and the global object on the second console.log, not the object check
// a solution is to anchor this in another variable:
const check1 = {
check1This: function() {
const self = this;
console.log(self);
function checkOther() {
console.log(self);
}
checkOther();
}
}
check1.check1This();
// function call() stabilizes the context of this by passing this as paramenter, thus making 'this' the caller...
const check2 = {
check2This: function() {
console.log(this);
function checkOther() {
console.log(this);
}
checkOther.call(this);
}
}
check2.check2This();
<file_sep># string methods follow the string you want to act on
# strings are immutable data types, so any method ran on them is view only
"hello".count("e")
text = 'hello world'
counter = text.count('e')
upcase = text.upper()
lowcase = text.lower()
capital = text.capitalize()
title = text.title()
print(counter, upcase, lowcase, capital, title)
#check if all is lowercase
text.islower()
#check if is uppercase
text.isupper()
#check if title case
text.istitle()
# if all is letters, if spaces it returns false
text.isalpha()
# if contains only numbers
text.isdigit()
# if contains only alphanumeric characters
text.isalnum()
# search for pieces of text
greeting = "happy birthday"
ind = greeting.index("birthday")
print(ind)
# the return is the index where the string "birthday" starts
fin = greeting.find("i")
print(fin)
# difference between find() and index() is that find() returns -1 if not found and index() throws an error
# remove certain characters or whitespaces with strip()
way = " baby I love your way "
yaw = way.strip()
print(yaw)
y = "00000happy birthday0000"
z = y.strip("0")
print(z)
# clean only left or right hand side:
z = y.lstrip("0")
print(z)
z = y.rstrip("0")
print(z)
#join
a = "ready"
b = "set"
c = "go"
d = "!"
separator = "-"
e = separator.join([a,b,c]) + d
print(e)<file_sep>function previousLengths(arr){
var newArr = [arr[0]];
for(var i = 1; i < arr.length; i++){
newArr.push(arr[i].length);
}
console.log(newArr);
}
previousLengths(["you", "me", "we"]);
function previousLengths(arr){
for(var i = arr.length - 1; i > 0; i--){
arr[i] = arr[i-1].length;
}
return(arr);
}
previousLengths(["you", "me", "we"])<file_sep># if you know the value of what you want to remove:
list1 = ['Bob', 'Mirna', 'Chuck', 'Gertrudis']
list1.remove('Mirna')
print(list1)
# remove targets the first occurrence only. therefore, sometimes you want an alternative...
# if you want to remove by index number:
list2 = ['Bob', 'Mirna', 'Chuck', 'Gertrudis']
del list2[0]
print(list2)
# remove slices
list3 = ['Bob', 'Mirna', 'Chuck', 'Gertrudis']
del list3[0:2]
print(list3)
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { Book } from './models/book';
@Injectable({
providedIn: 'root'
})
export class HttpService {
books$ = new BehaviorSubject<Book[]>([]);
constructor(private _http: HttpClient) { }
getBooks(): Observable<Book[]> {
console.log('service knows, so making server call');
this._http.get<Book[]>('/books')
.subscribe(data => this.books$.next(data));
return this.books$;
}
createBook(book: Book): Observable<Book> {
console.log('http service got a request to create book', book);
return this._http.post<Book>('/books', book);
}
editBook(book: Book): Observable<Book> {
return this._http.put<Book>(`/books/${book._id}`, book);
}
deleteBook(_id: number): Observable<Book> {
console.log('service got delte request for', _id);
return this._http.delete<Book>(`./books/${_id}`);
}
getBook(_id: string): Observable<Book> {
return this._http.get<Book>(`./books/${_id}`);
}
}
<file_sep>//function requires passed object to have at least one parameter called label and does not care about the rest:
function printLabel(labelledObj) {
console.log(labelledObj.label);
}
var myObj = {
size: 10,
label: "Size 10"
};
printLabel(myObj);
function printLabel2(labelledObj) {
console.log(labelledObj.label);
}
var myObj2 = {
size: 11,
label: "Size 11"
};
printLabel2(myObj2);
function createSquare(config) {
var newSquare = { color: "white", area: 100 };
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
var mySquare = createSquare({ color: "black" });
console.log(mySquare);
// after assigning values to them, they cannot be reassigned:
var p1 = { x: 10, y: 20 };
var p2 = { x: 12, y: 14 };
// p1.x = 5; shows error!
var numy = [1, 2, 3, 4];
var readNumy = numy;
// readNumy[0] = 9; shows an error
console.log(readNumy);
//you can override a read only array to start over:
numy = readNumy;
console.log(readNumy);
<file_sep>// naming convention is for Classes and Object Constructors to be capitalized and singular
function Person(name,age){
var privateVariable = "this is private";
var privateMethod = function(){
console.log(this);
}
this.name = name;
this.age = age;
this.greet = function(){
console.log("Sayonara, my name is "+this.name+" and I am "+this.age+" years old");
console.log("My private variable is "+privateVariable)
privateMethod();
}
}
var eliza = new Person("Eliza",40);
// eliza.greet();
// the greet includes the privateMethod, which instead of printing the instance's attributes and methods, prints the computer's...see why below...
// console.log(privateVariable)
// undefined because initialization of var is local
// if we try to console.log the privateVariable from within the function, 'this' will be confused for the browser window
// this is because 'this' is interpreted as the parent of the context we're in
// a solution is to assign 'this' instance to a variable
function Personus(name,age){
var self = this
var privateVariable = "THIS is private";
var privateMethod = function(){
console.log("This is a private method for "+self.name);
console.log(self);
}
this.name = name;
this.age = age;
this.greet = function(){
console.log("Sayonara, my name is "+this.name+" and I am "+this.age+" years old");
// and we can access the attributes within the constructor
console.log("Also, my private variable is "+privateVariable);
// as well as the methods within the constructor
privateMethod();
}
}
var joe = new Personus("Joe",55)
joe.greet();
// now joe's greet includes a detail of his attributes and methods
<file_sep>import { Directive, HostListener, HostBinding } from '@angular/core';
@Directive({
selector: '[appDropdown]'
})
export class DropdownDirective {
// with HostBinding we dynamically attach the directive to the element that carries this directive's tag
@HostBinding('class.open') isOpen = false;
// with HostListener we listen for a click event, then we name our function toggleOpen
@HostListener('click') toggleOpen() {
this.isOpen = !this.isOpen;
}
}
<file_sep>const express = require('express');
const path = require('path');
const rootDir = require('../utils/path');
const router = express.Router();
const users = [];
router.get('/', (req, res, next) => {
console.log('hit the root route');
res.render('index', {pageTitle: 'User Form'});
})
router.post('/new', (req, res, next) => {
users.push(req.body);
res.redirect('/users');
})
router.get('/users', (req, res, next) => {
console.log('hit the users route');
res.render('users', {pageTitle: 'Users', users: users});
})
module.exports = router;<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^login$', views.login),
url(r'^register$', views.register),
url(r'^logout$', views.logout, name="logout"),
url(r'^books$', views.books, name="books"),
url(r'^books/add$', views.add, name="add"),
url(r'^add_review$', views.add_review, name="add_review"),
url(r'^books/(?P<id>\d+)$', views.book_page, name="book_page"),
url(r'^books/(?P<id>\d+)/new_review$', views.new_review, name="new_review"),
url(r'^users/(?P<id>\d+)$', views.users, name="users"),
]
<file_sep>from flask import Flask, render_template, request, redirect, session, flash
# import the Connector function
from mysqlconnection import MySQLConnector
app = Flask(__name__)
# connect and store the connection in "mysql"; note that you pass the database name to the function
mysql = MySQLConnector(app, 'users')
# an example of running a query
print mysql.query_db("SELECT * FROM users")
@app.route("/")
def index():
users = mysql.query_db("SELECT * FROM users")
return render_template('index.html', all_users = users)
@app.route("/create")
def create():
return render_template("create.html")
@app.route("/add_users", methods=["POST"])
def add_users():
first_name = request.form["first_name"]
last_name = request.form["last_name"]
email = request.form["email"]
password = request.form["<PASSWORD>"]
query = "INSERT INTO `users`.`users` (`first_name`, `last_name`, `email`, `password`, `created_at`, `updated_at`) VALUES (:field_one,:field_two,:field_three,:field_four, now(), now());"
data = {
"field_one":first_name,
"field_two":last_name,
"field_three":email,
"field_four":password
}
result = mysql.query_db(query,data)
return redirect('/')
@app.route("/users/<user_id>")
def show(user_id):
query = "SELECT * FROM users.users WHERE id = :specific_id"
data = {
"specific_id":user_id
}
users = mysql.query_db(query,data)
return render_template("show.html", users=users[0])
@app.route("/users/edit/<user_id>")
def edit(user_id):
query = "SELECT * FROM users.users WHERE id = :specific_id"
data = {
"specific_id":user_id
}
users = mysql.query_db(query,data)
return render_template("edit.html", users=users[0])
@app.route("/update_users/<user_id>", methods=["POST"])
def udate(user_id):
first_name = request.form["first_name"]
last_name = request.form["last_name"]
email = request.form["email"]
password = request.form["password"]
query = "UPDATE `users`.`users` SET `first_name`=:field_one, `last_name`=:field_two, `email`=:field_three, `password`=:<PASSWORD>, `updated_at`=now() WHERE `id` = :specific_id"
data = {
"specific_id":user_id,
"field_one":first_name,
"field_two":last_name,
"field_three":email,
"field_four":password
}
users = mysql.query_db(query,data)
return redirect("/users/{}".format(user_id))
@app.route('/users/delete/<user_id>')
def delete_request(user_id):
query = "SELECT * FROM users WHERE users.id = :specific_id;"
data = { 'specific_id': user_id }
user = mysql.query_db(query,data)
return render_template('confirm.html', user=user)
# create a route to a function that deletes the users...
@app.route('/users/delete_now/<user_id>')
def delete_user(user_id):
query = "DELETE FROM users WHERE users.id = :specified_id"
data = {
'specified_id':user_id
}
mysql.query_db(query,data)
return redirect('/')
app.run(debug=True)<file_sep>#Draw Stars Pt.1
def draw_stars(arr):
for i in arr:
print "*"*i
draw_stars([4, 6, 1, 3, 5, 7, 25])
#Part 2
def draw_any(arr):
for i in arr:
if type(i) == int:
print i * "*"
elif type(i) == str:
print len(i) * i.lower()[0]
draw_any([4, "Tom", 1, "Michael", 5, 7, "<NAME>"]) <file_sep># while loops run while a condition is True
# the following won't run:
while False:
print("Hello")
# while with conditions
x = 0
while x < 10:
if x % 2 == 0:
print(x + 1)
x = x + 1
# populate a list
L = []
while len(L) < 3:
name = input("Please enter a name: ").strip().capitalize()
L.append(name)
print("Sorry, list is full, look %s" % L)
<file_sep>const Author = require('mongoose').model('Author');
const Book = require('mongoose').model('Book');
module.exports = {
index(request, response) {
Book.find({})
.populate('author')
.then(books => {
console.log({books});
response.render('books/index', {books});
})
.catch(console.log);
},
show(request, response) {
},
edit(request, response) {
Book.find({})
.then(books => {
console.log({books});
response.render('books/new', {books});
})
.catch(console.log);
},
new(request, response) {
},
update(request, response) {
},
create(request, response) {
Book.create(request.body)
.then(book => {
console.log('created book', book);
return Author.findById(book.author)
.then(author => {
author.books.push(book.id);
return author.save()
});
})
.then(() => response.redirect('/books'))
.catch(error => {
const errors = Object.keys(error.errors)
.map(key=>error.errors[key].messages);
response.render('books/new', {errors});
});
},
destroy(request, response) {
Book.findByIdAndRemove(request.params.book_id)
.then()
.catch()
},
}; <file_sep># import a flask class from the flask framework
# the class includes all the prototypes that are needed to write web apps with python
from flask import Flask
# create variable to store the flask object instance/flask application
# when script is run, python assigns the name "main" to the script
app = Flask(__name__)
@app.route('/')
def home():
return "Website home page here!"
@app.route('/about')
def about():
return "Website about goes here!"
# this is true when we execute the script:
if __name__ == "__main__":
app.run(debug=True)
<file_sep>import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appFadeout]'
})
export class FadoutDirective {
@HostBinding('style.opacity') opacityLevel = 1;
@HostListener('click') opacityFade(eventData: Event) {
const fader = setInterval(() => {
if (this.opacityLevel < 0.01) {
clearInterval(fader);
} else {
this.opacityLevel = this.opacityLevel - 0.01;
}
}, 10);
}
}
<file_sep>$('document').ready(function(){
for(var i = 0; i < 6 ; i++){
$('.container').append("<div class='box'></div>")
}
})<file_sep># ODD EVEN
def odd_even(n):
for i in range (1,n):
if i%2 == 0:
print "Number is "+ str(i) +". This is an even number."
else:
print "Number is "+ str(i) +". This is an odd number."
odd_even(21) #will print up to 20 instead of 2000 to save space
# MULTIPLY
def multiply(a,x):
for val in a:
new_list.append(val*x)
print new_list
return new_list
# HACKER CHALLENGE
def layered_multiples(arr):
layered_list = []
for n in new_list:
hack_list = []
counter = 0
while counter < n:
hack_list.append(1)
counter = counter + 1
layered_list.append(hack_list)
print layered_list
new_list = []
layered_multiples(multiply([2,4,5],3))
<file_sep>import { Component, OnInit, Input, ContentChild, ViewChild, ElementRef, AfterContentInit, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-server-element',
templateUrl: './server-element.component.html',
styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit, AfterContentInit, AfterViewInit {
@Input() element: {type: string, name: string, content: string};
@ContentChild('paragraph') paragraph: ElementRef;
@ViewChild('header') header: ElementRef;
constructor() { }
// the following logs will help explain when data becomes available for the change detection methods:
// also remember the difference between the ContentInit cycle and the ViewInit cycle.
// see app.component.html for more info about the Content cycle.
ngOnInit() {
console.log('Init: this is the content cycle [ ' + this.paragraph.nativeElement.textContent + ' ] from on init');
console.log('Init: this is the view cycle [ ' + this.header.nativeElement.textContent + ' ] from on init');
}
// at the end of the content init cycle...
ngAfterContentInit(): void {
console.log('AfterContent: this is the content cycle [ ' + this.paragraph.nativeElement.textContent + ' ] from after content init');
console.log('AfterContent: this is the view cycle [ ' + this.header.nativeElement.textContent + ' ] from after content init');
}
// at the end of the view init cycle...
// DOM element values are only available from afterViewInit...
ngAfterViewInit(): void {
console.log('AfterView: this is the content cycle [ ' + this.paragraph.nativeElement.textContent + ' ] from after view init');
console.log('AfterView: this is the view cycle [ ' + this.header.nativeElement.textContent + ' ] from after view init');
}
}
<file_sep>"use strict";
// what are function closures?
// closeres are references to variables a function needs to run its process.
// this means:
// 1. closure can refer to variables in outer scopes
// 2. it can refer to those outer variables even after a return statement that deletes them...
function sayHello(name) {
const text = "Hello " + name;
return function() {
console.log(text);
};
}
const greet = sayHello("Dude");
greet();
// the return statement inside SayHello deletes the 'text' variable but the greet function keeps it in closure because it still needs it.
// closure is whatever value is in the variables currently in use.
// example:
var foo = [];
for (var i = 0; i < 10; i++) {
foo[i] = function() {
return i;
};
}
console.log(foo[0]());
console.log(foo[1]());
console.log(foo[2]());
let moo = [];
for (let j = 0; j < 10; j++) {
moo[j] = function() {
return j;
};
}
console.log(moo[1]());
console.log(moo[2]());
console.log(moo[0]());
// notice the behavior of var is different from let because var is a global variable. By the time foo functions are called, the global variable i is already at 10.
// see how an immediateily invoked function can also help us achieve that by creating a local variable to serve as closure:
var choo = [];
for (var idx = 0; idx < 10; idx++) {
(function() {
var y = idx;
choo[idx] = function() {
return y;
};
})();
}
console.log(choo[1]());
console.log(choo[2]());
console.log(choo[0]());
// using IIFE, but cleaner, we can do the following:
var yoo = [];
for (var x = 0; x < 10; x++) {
(function(y) {
yoo[y] = function() {
return y;
};
})(x);
}
console.log(yoo[1]());
console.log(yoo[6]());
console.log(yoo[0]());
// x loops from 0 to 10. As it does, x value is passed by value through the y variable and the snapshots of each are kept by the yoo[y] function as its closure.
<file_sep>#super() is used to change parental default settings for the specified child class
#the syntax is: super(childClassName, self).parent_method()
#do so by calling the parent's __init__ method
#example, suppose there is a Human object and you want to modify at the sub-class level...
# from human import Human
# class Wizard(Human):
# def __init__(self):
# super(Wizard, self).__init__() # use super to call the Human __init__ method
# self.intelligence = 10 # every wizard starts off with 10 intelligence
# def heal(self):
# self.health += 10
# class Ninja(Human):
# def __init__(self):
# super(Ninja, self).__init__() # use super to call the Human __init__ method
# self.stealth = 10 # every Ninja starts off with 10 stealth
# def steal(self):
# self.stealth += 5
# class Samurai(Human):
# def __init__(self):
# super(Samurai, self).__init__() # use super to call the Human __init__ method
# self.strength = 10 # every Samurai starts off with 10 strength
# def sacrifice(self):
# self.health -= 5
<file_sep>import { Directive, HostBinding, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appCustomHighlight]'
})
export class CustomHighlightDirective {
@Input() initialColor = 'transparent';
@Input() highlightColor = 'cyan';
@HostBinding('style.backgroundColor') backgroundAlter = this.initialColor;
@HostListener('mouseenter') mouseenter(eventData: Event) {
this.backgroundAlter = this.highlightColor;
}
@HostListener('mouseleave') mouseleave(eventData: Event) {
this.backgroundAlter = this.initialColor;
}
}
<file_sep>arr = [3,4,5,6]
arr[0], arr[1] = arr[1], arr[0]
print arr<file_sep>word_list = ['hello','world','my','name','is','Anna']
def cherry_pick(word_list, which):
new_list = []
for word in word_list:
for char in word:
if char.count('o') > 0:
new_list.append(word)
print new_list
cherry_pick(word_list,'o')
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-15 17:22
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_dashboard', '0009_auto_20180814_1718'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 15, 12, 22, 39, 642000)),
),
migrations.AlterField(
model_name='message',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 15, 12, 22, 39, 642000)),
),
migrations.AlterField(
model_name='user',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 15, 12, 22, 39, 641000)),
),
migrations.AlterField(
model_name='user',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 15, 12, 22, 39, 641000)),
),
]
<file_sep>table = [1,2,3,4,5,6,7,8,9,10,11,12]
row = "x "
for item in table:
row += '{} '.format(item)
print row
for i in range (1,13):
row = [item*i for item in range (1, len(table)+1)]
formater = ""
for item in row:
formater += "{} ".format(item)
print formater<file_sep>from django.conf.urls import url
import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^new$', views.new, name='new'),
url(r'^grad$', views.grad, name='grad'),
url(r'^user/(?P<id>)\d+$', views.show, name='show'),
]
<file_sep>from animal import Animal
class Dragon(Animal):
def __init__(self, name):
super(Dragon, self).__init__(name)
self.health = 170
def fly(self):
self.health -= 10
return self
def displayHealth(self):
print "I am a Dragon"
super(Dragon, self).displayHealth()
return self
dragon1 = Dragon("Albathorth")
dragon1.fly().displayHealth().fly().displayHealth()<file_sep>"use strict";
// examples of section 15, but using intermediate function technique
function extend(Child, Parent) {
// this copies the prototype members unto the child prototype
Child.prototype = Object.create(Parent.prototype);
// the sets the child constructor to correctly point to it and not to the parent constructor
Child.prototype.constructor = Child;
}
// create master constructor
function Person(fn, ln) {
this.fn = fn;
this.ln = ln;
}
Person.prototype.full_name = function() {
return this.fn + " " + this.ln;
};
// start a prototypical chain
function Professional(hn, fn, ln) {
Person.call(this, fn, ln);
this.hn = hn;
}
extend(Professional, Person);
// add another strata to the chain
const manolo = new Professional("Dr.", "Manolo", "Briz");
console.log(manolo.full_name());
<file_sep>// factory function
function createCircle(radius) {
return {
radius,
location: {
x: 1,
y: 1
},
draw: function() {
console.log(
`drawing radius of ${this.radius} centered at (${this.location.x}, ${
this.location.y
}).`
);
}
};
}
const circle1 = createCircle(1);
circle1.draw();
console.log(circle1.radius);
// Constructor function
function Circle(radius) {
this.radius = radius;
this.location = { x: 1, y: 1 };
this.draw = function() {
console.log(
`drawing radius of ${this.radius} centered at (${this.location.x}, ${
this.location.y
}).`
);
};
}
const circle2 = new Circle(1);
circle2.draw();
// access the function that created the object
console.log(circle1.constructor);
console.log(circle2.constructor);
console.log(circle1.constructor.constructor);
console.log(circle2.constructor.constructor);
// you could use the Function constructor to create any object, since all constructors extend the mother Function:
// just pass the parameters, properties and methods as strings through the Function parameters:
const CircleF = new Function(
"radius",
` this.radius = radius;
this.location = { x: 1, y: 1 };
this.draw = function() {
console.log(
"draw"
);
};
`
);
const circleF1 = new CircleF(1);
console.log(circleF1);
// what does new operator do?
// uses the call() method and takes what "this" will mean as first parameter and then the object parametrs
Circle.call({}, 1);
// an alternative is to use .apply(). Use it when passing parameters as an array
Circle.apply({}, [1]);
<file_sep>//require all needed functionality and initialize the app
const express = require('express');
const path = require('path');
const color = require('colors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const flash = require('express-flash');
const port = process.env.PORT || 8000;
const app = express();
//build the app
app
.use(express.static(path.join(__dirname, 'static')))
.use(bodyParser.urlencoded({extended:true}))
.use(session({
secret: 'yayuser',
resave: false,
saveUninitialized: flase,
cookie: {secure:true}
}))
.use(flash())
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req,res) => {
User.find({})
.then((db_users) => {
users = db_users;
console.log(color.yellow(db_users));
res.render('index',{users});
})
.catch((error) => {
const errors = Object.keys(error.errors)
.map(key=>error.errors[key].message);
console.log(color.red(errors));
res.render('some_page', {errors})
})
})
.post('/users',(req,res) => {
console.log(color.white(req.body))
let user = new User(req.body);
user.save()
.then((saved) => {
console.log(color.yellow(saved));
res.redirect('/');
})
.catch((error) => {
// const errors = Object.keys(error.errors)
// .map(key => error.errors[key].message);
// console.log(color.red(errors));
for (let key in error.errors) {
req.flash('registration', error.errors[key].message);
}
res.redirect('/');
})
})
.listen(port, () => {
console.log(`listening on port ${port}`);
});
//connect to mongodb and a database in particular
mongoose.connect('mongodb://localhost:27017/basic_mongoose', { useNewUrlParser:true });
mongoose.connection.on('connected', ()=>console.log('Mongoose connected'));
//extract Schema object constructor from the mongoose object
const {Schema} = mongoose;
//create a new instance of Schema and provide it with structure, note it takes a JSON object as parameter
const userSchema = new Schema({
first_name: {type: String, required: true, minlength: 1},
last_name: {type: String, required: true, minlength: 1},
email: {type: String, required: true, minlength: 1},
age: {type: Number, required: true, min: 0}
});
//set this schema in our Models as 'User'
mongoose.model('User', userSchema);
//retrieve the 'User' schema from our Models
const User = mongoose.model('User');
//if working in same document, can simplify above two lines with:
//const User = mongoose.model('User', userSchema);
<file_sep>"use strict";
let string = "The moon is 36 gray! Is it?";
function charCount(str) {
let obj = {};
for (let char of str) {
char = char.toLowerCase();
if (!isAlphaNumeric(char)) {
continue;
} else {
obj[char] = ++obj[char] || 1;
}
}
return obj;
}
function isAlphaNumeric(char) {
const code = char.charCodeAt(0);
if (!(code > 47 && code <58) && // if numeric (0-9)
!(code > 64 && code < 91) && // if alpha (A-Z)
!(code >96 && code << 123)) { // if alpha (a-z)
return false;
}
return true;
}
let solution = charCount(string);
console.log(solution);
<file_sep>films = {
"The Magicians": [3,5],
"Homecoming": [18,5],
"Sabrina": [15,5],
"The Others": [12,5]
}
movies = list(films.keys())
def welcome():
print("Here are our movies: %s " % movies)
movie = input("What movie would you like to watch? ").strip().title()
selection = check_movie(movie)
return selection
def goodbye():
print("Goodbye!")
return(False)
def check_movie(movie):
if movie in films:
return(True, movie)
else:
print("We don't have that film.")
goodbye()
def check_age(age, movie):
if age >= films[movie][0]:
print("Appropriate movie for your age!")
return(True, movie)
else:
print("This is not a movie that's appropriate for your age")
goodbye()
def check_tickets(movie):
if films[movie][1] > 0:
print("Excellent, have %s tickets left, enjoy the movie!" % films[movie][1])
films[movie][1] = films[movie][1] - 1
return(True, movie)
else:
print("Sorry, that one sold out!")
goodbye()
while True:
selection = welcome()
if selection[0]:
age = int(input("What is your age? ").strip())
appropriate = check_age(age, selection[1])
if appropriate[0]:
availability = check_tickets(selection[1])
else:
goodbye()
<file_sep>var person = {
name: "Jose",
age: 43,
location: "OKC",
ability: function(){console.log("play bass")},
drive: true
}
//1. get a the name by pulling from the object's name key, using dot notation
// console.log(person.name);
//2. get the name again using another notation
// console.log(person['name']);
//3. change the content inside the name key
// person.name = "Jones";
// console.log(person);
//4. execute the function under key ability:
// person.ability();
//5. loop through the contents of the array
// for(var key in person){
// console.log(key);
// };
//6. but if you want to see the contents of each key...
// for(var key in person){
// console.log(person[key]);
// };
//7. print both the key and content at the same time:
for(var key in person){
console.log(key," : ",person[key]);
}
// console.log(person);<file_sep>music = ["Abba", "<NAME>", "<NAME>", "The Beatles"]
print music
print ' '.join(music)
<file_sep>import random
# to create a class with methods, we need a constructor
# the constructor method is a function called __init__ that takes an argument called self
# self is what we use to create to the specific instance of the class when we write the class code
# inside the code, when it is run, self is replaced by the object's name
# constructor functions can take other parameters
class Pound:
def __init__(self, rare=False):
self.value = 1.00
self.color = "gold"
self.num_edges = 1
self.diameter = 22.50 # mm
self.thickness = 3.15 # mm
self.heads = True
self.rare = rare
if self.rare:
self.value = self.value * 1.25
def __del__(self):
print("Coin spent")
def rust(self):
self.color = "greenish"
def clean(self):
self.color = "gold"
def flip(self):
heads_options = [True, False]
self.heads = random.choice(heads_options)
coin1 = Pound()
coin2 = Pound(rare=True)
print(coin1.value)
print(coin2.value)
coin1.rust()
print(coin1.color)
coin1.flip()
print(coin1.heads)
# to destroy a coin
del coin1
print(coin1)<file_sep>from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import MySQLConnector
#import bcrypt
from flask.ext.bcrypt import Bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
#create the bcrypt object
bcrypt = Bcrypt(app)
app.secret_key = "regisvalid1234"
mysql = MySQLConnector(app,'the_wall')
@app.route('/')
def index():
return render_template("index.html")
#REGISTRATION
@app.route('/register', methods=['POST'])
def register():
#receive data
#validate data
valid = True
#if not valid
#flash error message and redirect to index
if len(request.form['fname']) < 1:
valid = False
flash("Please enter a full first name")
if len(request.form['lname']) < 1:
valid = False
flash("Please enter a full last name")
if len(request.form['email']) < 5:
valid = False
flash("Please enter a full email")
if not EMAIL_REGEX.match(request.form['email']):
valid = False
flash("Invalid email address!")
if len(request.form['pword']) < 8:
valid = False
flash("Please make password at least 8 characters long")
if valid != True:
return redirect ('/')
#if valid
#create query
query = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `password`, `created_at`, `updated_at`) VALUES (:fname, :lname, :email, :pword, now(), now());"
#build dictionary with form data
data = {
'fname':request.form['fname'],
'lname':request.form['lname'],
'email':request.form['email'],
'pword':bcrypt.generate_password_hash(request.form['pword'])
}
#store it to db
mysql.query_db(query,data)
#flash success message
flash("Successfully registered!")
return redirect('/')
#LOGIN
@app.route('/login', methods=['POST'])
def login():
#receive data
#validate data
valid = True
#if not valid
#flash error message and redirect to index
if len(request.form['email']) < 5:
valid = False
flash("Please enter a full email")
if not EMAIL_REGEX.match(request.form['email']):
valid = False
flash("Invalid email address!")
if len(request.form['pword']) < 8:
valid = False
flash("Please make password at least 8 characters long")
if valid != True:
return redirect ('/')
#valid
else:
#create query
query = "SELECT * FROM users WHERE email = :email"
#build dictionary
data = {
'email':request.form['email']
}
#get user information from database
users = mysql.query_db(query,data)
#validate credentials
#if user exists, db will return a dictionary with the information
if len(users) > 0:
user = users[0]
password = request.form['pword']
bcrypt.check_password_hash(users[0]['password'], password)
#validate password by comparing with input with that in the db
if password == users[0]['password']:
session['user_id'] = user['id']
flash("Succesful login, user id:{}".format(session['user_id']))
return render_template('wall.html')
else:
flash("Please check credentials")
#if user does not exist
else:
flash("Email does not exist")
return redirect('/')
@app.route('/welcome')
def welcome():
user = mysql.query_db("SELECT * FROM users WHERE id = {}".format(session['user_id']))[0]
return render_template("wall.html", user=user)
app.run(debug=True)<file_sep>function prevIndex(arr){
for(var i = arr.length - 1; i > 0; i--){
arr[i] = arr[i-1].length;
}
console.log(arr);
}
prevIndex(['algo', 'rithm', 'rhythm', 'oglamh', 'hello']);<file_sep>//1
function printAverage(x){
sum = 0;
for(i = 0; i < x.length; i++){
sum = sum + x[i];
}
return sum/x.length;
}
y = printAverage([1,2,3]);
console.log(y); // should log 2
y = printAverage([2,5,8]);
console.log(y); // should log 5
//2
function returnOddArray(){
arr = [];
for(i = 1; i <= 255; i++){
if(i % 2 !== 0){
arr.push(i);
}
}
return arr;
}
y = returnOddArray();
console.log(y); // should log [1,3,5,...,253,255]
//3
function squareValue(x){
for(i = 0; i < x.length; i++){
x[i] = x[i] * x[i];
}
return x;
}
y = squareValue([1,2,3]);
console.log(y); // should log [1,4,9]
y = squareValue([2,5,8]);
console.log(y); // should log [4,25,64]
function a(x){
for(var i=0; i<x.length; i++){
if(x[i] > 5){
x[i] = "Coding";
}
else if(x[i] < 0){
x[i] = "Dojo";
}
// return x;
}
return x;
}
console.log(a([5,7,-1,4]));
function a(x){
for(var i=0; i<x.length; i++){
if(x[i] > 0){
x[i] = "Coding"
}
}
return x
}
console.log(a([1,2,3,4]))<file_sep>import math #this is done in order to access the math library
# container for data that belongs together. think of them as a list of related items that cannot be changed once Python submits it to memory.
tuple_1 = ('dance','trance','disco','edm','trap','house')
#you can access their value via index and for loops
print tuple_1[3]
for genre in tuple_1:
print genre #access the values
for genre in range (0,len(tuple_1)):
print genre #access the indexes
# add new values to a tuple, it's possible!
tuple_1 = tuple_1 + ("drum and bass",)
print tuple_1
print len(tuple_1)
tuple_1 = tuple_1[:3] + ("techno",) + tuple_1[5:] #this replaces value at indexes 3 & 4
print tuple_1
print len(tuple_1) #notice we lose length because of the above
# TUPLE FUNCTIONS
#len()
print "first word is " + str(len(tuple_1[0])) + " letters long"
print "second word is " + str(len(tuple_1[1])) + " letters long"
#max()
#sum()
#min()
tuple_2 = (1,6,3,9,2,7,4)
print "max of tuple_2 is ",max(tuple_2)
print "sum of tuple_2 is ",sum(tuple_2)
print "min of tuple_2 is ",min(tuple_2)
print "average of tuple_2 is ",sum(tuple_2)/len(tuple_2)
#enumerate()
styles_1 = []
styles_2 = []
for genre in enumerate(tuple_1):
styles_1.append(genre)
styles_2.extend(genre)
print "appended list of genre: ",styles_1
print "extended list of genre: ",styles_2
def multiplier(n):
return n*2
#functions and tuples...
#map()
print "multiplying every value of tuple_2 by 2 with a function and map method: ",map(multiplier,tuple_2)
#sorted()
print "sorted tuple_2: ",sorted(tuple_2)
#RETURN VALUES AS TUPLES
#If you return values as tuples, it is easy to do math operations on them
#example:
#returns
def circle_area(r):
c = 2 * math.pi * r
a = math.pi * r * r
return (c,a)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from django.core import serializers
import json
from .models import Note
# Create your views here.
def index(request):
context ={
'notes':Note.objects.all().order_by('id')
}
return render(request, 'ajax_notes/index.html', context)
# if you wanted to return html, you could do the following, and it would return details of the first note, for example:
# return HttpResponse(context['notes'][0].__dict__.__str__())
def create_note(request):
print request.is_ajax()
# ^^^^^this above tells us if the request that is coming in is from the form submission or from the jQuery route!
# now we know the data written in the form is coming to here serialized via javascript
context = {
'title' : request.POST['title'],
'content' : request.POST['content']
}
result,note = Note.objects.CreateNote(context)
if result == True:
note = Note.objects.get(id=note)
note_id = note.id
title = note.title
content = note.content
context={'id':note_id,'title':title,'content':content}
return render(request, 'ajax_notes/_note.html', context)
# return HttpResponse(note.__dict__.__str__())
else:
json_messages = json.dumps(note)
# print json_messages
# print note
# return HttpResponse(note)
return HttpResponse(json_messages,content_type="application/json")
def delete_note(request, id):
note = Note.objects.get(id=id)
note.delete()
return redirect('index')
def edit_note(request, id):
note = Note.objects.get(id=id)
if request.POST['title'] == "":
note.title = note.title
else:
note.title = request.POST['title']
if request.POST['content'] == "":
note.content = note.content
else:
note.content = request.POST['content']
note.save()
return redirect('index')<file_sep>var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
}
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
//class implements an interface
var Student = /** @class */ (function () {
function Student(name, age) {
this.name = name;
this.age = age;
}
return Student;
}());
var student = new Student('Bob', 5);
console.log(student);
//class inheritance with a default value
var Senior = /** @class */ (function (_super) {
__extends(Senior, _super);
function Senior(name, age) {
if (age === void 0) { age = 18; }
return _super.call(this, name, age) || this;
}
return Senior;
}(Student));
var tammy = new Senior('Tammy');
console.log(tammy);
var Junior = /** @class */ (function (_super) {
__extends(Junior, _super);
function Junior(name, age) {
if (age === void 0) { age = 15; }
return _super.call(this, name, age) || this;
}
Junior.prototype.sayHello = function (name) {
console.log("Hello " + name + ", from " + this.name);
};
return Junior;
}(Student));
var george = new Junior('Geo');
george.sayHello(tammy.name);
<file_sep>function map(arr,callback) {
results = []
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
results.push(callback(item,item));
}
return results
}
function addTwo(num1) {
result = num1 + 2;
return result;
}
function multiplier(num1, num2) {
result = num1 * num2;
return result;
}
function timesTwo(num) {
result = num * 2;
return result;
}
arr = [3,6,7,10];
let operation1 = map(arr,addTwo);
let operation2 = map(arr,multiplier);
let operation3 = map(arr,timesTwo);
console.log("operation 1:", operation1)
console.log("operation 2:", operation2)
console.log("operation 3:", operation3)
// instead of:
let operation4 = map(arr, function(num){
let result = num * 3;
return result;
})
// ES6 functions:
let operation4a = map(arr,(element) => element * 3)
console.log("operation 4:", operation4)
console.log("operation 4a:", operation4a)
console.log("operation 1a:", map(arr,(num)=>num+2));
console.log("operation 2a:", map(arr,(num)=>num*num));
console.log("operation 3a:", map(arr,(num)=>num*2));
<file_sep>import md5
#when user is being created
@app.route('users/create', methods=['POST'])
def create_user():
username = request.form['username']
email = request.form['email']
password = <PASSWORD>(request.form['password']).<PASSWORD>()
insert_query = "INSERT INTO users (username, email, password, created_at, updated_at) VALUES (:username, :email, :password, NOW(), NOW())"
query_data = {'username':username, 'email':email, 'password':<PASSWORD>}
mysql.query_db(insert_query, query_data)
#when existing user is logging in
email = request.form['email']
password = <PASSWORD>(request.form['password']).<PASSWORD>()
user_query = "SELECT * FROM users WHERE users.email = :email AND users.password = :<PASSWORD>"
query_data = {'email':email, 'password':<PASSWORD>}
mysql.query_db(user_query, query_data)
# do the necessary logic to login if the user exists, otherwise redirect to login page with error message<br>
<file_sep>import folium
import pandas
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
def color_generator(elevation):
color = "red"
if elevation < 1000:
color = "green"
return color
elif 1000 <= elevation < 3000:
color = "orange"
return color
else:
return color
map = folium.Map((45,-115), zoom_start=5, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
for lt, ln, ele in zip(lat, lon, elev):
fg.add_child(folium.CircleMarker(location=(lt, ln), radius=6, popup=str(ele) + " m", fill_color=color_generator(ele), color='grey',fill_opacity=0.7))
# create a python file with the world.json file to add geojson polygon layer to the map. Use classic open() python method and pass required parameters. .read() is used where Folium needs to get a string instead of a file as input data.
fg.add_child(folium.GeoJson(data=(open('world.json', 'r', encoding='utf-8-sig').read())))
map.add_child(fg)
map.save("Volcanoes5.html")<file_sep>function celsiusToFahrenheit(cDegrees){
var fDegrees = (9/5) * cDegrees + 32;
console.log(fDegrees +" degrees fahrenheit");
}
celsiusToFahrenheit(37);<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class User(models.Model): #we are extending the Model class that is built into Django
first_name = models.CharField(max_length=50) #assigning the type of data, just like in MySQL
last_name = models.CharField(max_length=50)
date_of_birth = models.DateField()
# created_at = models.DateTimeField(auto_now_add=True)
# updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.first_name + " " + self.last_name
class Career(models.Model):
title = models.CharField(max_length=255)
year_graduation = models.DateField()
user = models.ForeignKey(User, related_name="users")
def __str__(self):
return self.title + " " + self.year_graduation
<file_sep>import folium
map = folium.Map((14.6261887,-90.5626019), width="50%", height="50%", zoom_start=2, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
# add multiple locations with a for loop
locations = [
{
'key':(44.97399,-93.2299172),
'val': "Born here in 1974"
},
{
'key':(14.6357891,-90.5149832),
'val': "Grew up here until 2006"
},
{
'key':(29.8168824,-95.681492),
'val': "Lived here since between 2008 and 2017"
},
{
'key':(25.6718497,-80.3820902),
'val': "Lived here for a bit in 2017"
},
{
'key':(19.0399944,-98.3330542),
'val': "Lived here for a bit in 2016"
},
{
'key':(35.6189578,-97.4742407),
'val': "Lived here since 2017"
}
]
for loc in locations:
fg.add_child(folium.Marker(loc['key'], popup=loc['val'], icon=folium.Icon(color="green")))
map.add_child(fg)
map.save("Map2.html")<file_sep>from flask import Flask, render_template, session, redirect
app = Flask(__name__)
app.secret_key = "rencreepy"
@app.route("/")
def index():
#if count already exists, add 1, else, create a count starting with 1
if "count" in session:
session["count"] += 1
else:
session["count"] = 1
#initialize an empty array once
if "names" not in session:
session["names"] = []
session["names"].append("<NAME>!")
#can also create dictionaries
if "contacts" not in session:
session["contacts"] = []
session["contacts"].append({"name":"Ruppert", "property":"vacant lot"})
return render_template("index.html", count = session['count'], names = session['names'], contacts = session['contacts'])
@app.route("/clear")
def clearSession():
session.clear()
return redirect("/")
app.run(debug=True)<file_sep>import unittest
# this is used when you want to assert the truth of falsity of a solution that is passed through unittest:
class TruthTest(unittest.TestCase):
def test_assert_true(self):
my_value = 5
self.assertTrue(my_value)
def test_assert_false(self):
my_value = 5
self.assertFalse(my_value)
if __name__ == "__main__":
unittest.main()
my_value=5<file_sep>import folium
import pandas
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
def color_generator(elevation):
color = "red"
if elevation < 1000:
color = "green"
return color
elif 1000 <= elevation < 3000:
color = "orange"
return color
else:
return color
map = folium.Map((45,-115), zoom_start=5, tiles="Mapbox Bright")
fgv = folium.FeatureGroup(name="Volcanoes")
for lt, ln, ele in zip(lat, lon, elev):
fgv.add_child(folium.CircleMarker(location=(lt, ln), radius=6, popup=str(ele) + " m", fill_color=color_generator(ele), color='grey',fill_opacity=0.7))
fgp = folium.FeatureGroup(name="Population")
fgp.add_child(folium.GeoJson(data=(open('world.json', 'r', encoding='utf-8-sig').read()), style_function=lambda x: {'fillColor':'green' if x['properties']['POP2005'] < 10000000 else 'orange' if 10000000 <= x['properties']['POP2005'] < 20000000 else 'red'}))
map.add_child(fgv)
map.add_child(fgp)
# order matters, add the LayerControl() after the FeatureGroup has been added for it to work.
# what LayerControl does is looks for layers added to map through the add_child method
# so that we can add and remove layers independently, we create feature groups independently
map.add_child(folium.LayerControl())
map.save("Volcanoes6.html")<file_sep>"use strict";
// count characters of a string
let string = "The moon is 36 gray";
function charCount(str) {
let obj = {};
for (let i = 0; i < str.length; i++) {
if (str[i] === " " || !isNaN(Number(str[i]))) {
console.log("not a string");
continue;
} else {
if (!(str[i].toLowerCase() in obj)) {
obj[str[i].toLowerCase()] = 1;
} else {
obj[str[i]]++;
}
}
}
return obj;
}
let solution = charCount(string);
console.log(solution);
<file_sep>list_one = ['celery','carrots','bread','milk']
list_two = ['celery','carrots','bread','cream']
def list_compare(a,b):
if set(a) == set(b):
print "Lists are equal"
else:
print "Lists are not equal"
list_compare(list_one, list_two)
<file_sep>// case 1
// console.log("Start");
// function sayHello(name) {
// setTimeout(function() {console.log("Bye Baby!")}, 2000);
// setTimeout(function() {console.log("Hello", name)}, 1000);
// };
// sayHello("Domino")
// console.log("End");
// case 2
// synchronous
// function getThingsFromDB(query) {
// const data = ['thing 1','thing 2','thing 3','thing 4','thing 5'];
// return data;
// };
// const things = getThingsFromDB('select * from things;');
// console.log(things);
// asynchronous
// this one returns undefined because we have only called the function but need a callback to set the action to perform once the data is available
// function getThingsFromDB(query) {
// setTimeout(function() {
// const data = ['thing 1','thing 2','thing 3','thing 4','thing 5'];
// return data;
// }, 3000);
// };
// // this is the function call...
// const things = getThingsFromDB('select * from things;');
// console.log(things);
// asynchronous pt 2
// we now tell it what to do once data is available, with a callback
function getThingsFromDB(query, callback) {
setTimeout(function() {
const data = ['thing 1','thing 2','thing 3','thing 4','thing 5'];
console.log(callback.toString())
callback(data);
}, 3000);
};
function map(arr,callback) {
results = []
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
console.log(callback.toString())
results.push(callback(item));
}
return results
}
const things = getThingsFromDB('select * from things', (response) => {console.log('running anon func in the future! with data:', response);
const results = map(response, (thing) => `${thing} from the dastabase`);
console.log("results with map:", results);
});
// 'response' is what we want back from the getThingsFromDB function, so we pass on as argument
// 'data' is what the getTingsFromDb function will produce, so basically 'response' = 'data'.
// using different names to illustrate the information flow
// 'callback' is the anonymous function coded as in ES6 ... ()=>{}.
// we make the callback(); call from inside the timeout method so we are instructing js on what to do once the data is available
// summary: 1. we call function now; 2. function will run but takes time to return; 3. in order for there to be an instruction of what to do with the data, we provide it through the callback; 4. data arrives, the callback runs and returns a response; 5. we can do whatever we need to do with the response
<file_sep>def returning(p):
return p
def printing(p):
print(p)
hi = returning("9")
printing(returning("8") + hi)<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from datetime import datetime
from time import strftime
# Create your views here.
def index(request):
time = datetime.now()
context1 = {1:{"date": time.strftime('%A, %b %d %Y')},2:{"time": time.strftime('%H:%M:%S')}}
print context1
return render(request, 'time_display/index.html', context1)
<file_sep>#declare a class with class className (parameter):
class User(object):
pass
#the parameter object means that class User inherits from object class.
#we can make instances --objects-- of this class:
helen = User()
mikel = User()
#think of class as blueprint and objects as versions of the blueprint
#classes include:
# Attributes - characteristics they have, shared by all instances of the class. example, they have a name and email
# Methods - actions an object can perform. a function that belongs to a class. example, users can purchase
#objects have two important features:
# storage of information
# ability to execute some logic
<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.welcome),
url(r'^start$', views.start),
url(r'^process$', views.process),
url(r'^show$', views.show)
]
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { ServerComponent } from './server/server.component';
import { ServersComponent } from './servers/servers.component';
import * as fromAlerts from './alerts';
import * as fromAssignments from './assignments/';
@NgModule({
declarations: [
AppComponent,
ServerComponent,
ServersComponent,
...fromAlerts.components,
...fromAssignments.components,
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>function navArray(arr){
var next_last = arr[arr.length - 2];
console.log(next_last);
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 !== 0){
return arr[i];
}
}
}
console.log(navArray([6,4,8,3,5,8,7]));<file_sep>function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
function Shape(color) {
this.color = color;
}
Shape.prototype.duplicate = function() {
console.log("duplicate shape");
};
function Circle(radius, color) {
Shape.call(this, color); // super constructor
this.radius = radius;
}
extend(Circle, Shape);
Circle.prototype.draw = function() {
console.log("draw");
};
Circle.prototype.duplicate = function() {
console.log("duplicate circle");
};
function Square(size, color) {
Shape.call(this, color);
this.size = size;
}
extend(Square, Shape);
Square.prototype.duplicate = function() {
console.log("duplicate square");
};
const shapes = [new Circle(1, "red"), new Square(10, "blue")];
// we have overridden duplicate method, so we are able to do this...
// polymorphism in action:
for (let shape of shapes) {
shape.duplicate();
}
<file_sep>function intercept(M, B){
var X = 0;
var Y = M * X + B;
console.log(Y);
}
intercept(3,5);<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="main"),
url(r'^login$', views.login, name="login"),
url(r'^login_process$', views.login_process, name="login_process"),
url(r'^register$', views.register, name="registration"),
url(r'^register_process$', views.register_process, name="registration_process"),
url(r'^users/(?P<id>\d+)$', views.show, name="show"),
url(r'^users/(?P<id>\d+)/edit$', views.edit, name="edit"),
url(r'^users/editing/(?P<id>\d+)$', views.editing, name="editing"),
url(r'^users/updating_pw/(?P<id>\d+)$', views.updating_pw, name="updating_pw"),
url(r'^users/(?P<id>\d+)/update$', views.update, name="update"),
url(r'^users/add$', views.add, name="add"),
url(r'^add_process$', views.add_process, name="add_process"),
url(r'^users/dashboard$', views.dashboard, name="dashboard"),
url(r'^users/(?P<id>\d+)/delete$', views.delete, name="delete"),
url(r'^logout$', views.logout, name="logout"),
url(r'^message/(?P<id>\d+)$', views.message, name="message"),
url(r'^comment/(?P<u_id>\d+)/(?P<m_id>\d+)$', views.comment, name="comment"),
]
<file_sep># use single quotes to have a quote embedded in a string
message = 'John said to me "I will see you later"'
# use triple double or single quotes for long strings
long_message = '''this long message this long message,
this long message this long message'''
<file_sep>const R = require('ramda');
const color = require('colors');
// function composition: making new functions out of other functions by combining the logic of the other functions
const mySentence = "Hello divine world";
const myWordList = mySentence.split(' ');
console.log(myWordList);
const myWordCount = myWordList.length;
console.log(myWordCount);
// using functional composition with Ramda
const sentence = "Hello divine little world";
const wordList = R.split(' ', sentence);
console.log(wordList);
const wordCount = R.length(wordList);
console.log(color.green(wordCount));
// combining the two operations in one line
const composedWordCount = R.length(R.split(' ', sentence));
console.log(color.magenta(composedWordCount));
// applying functional composition with Ramda's R.compose
// compose combines the functions from right to left; the output of right is the input of left
const countWords = R.compose(R.length, R.split);
console.log(color.yellow(countWords(' ', sentence)));
// using partial application to simplify parameters of countWords:
const countWords2 = R.compose(R.length, R.split(' '));
console.log(color.blue(countWords2(sentence)));
// similar to R.compose is R.pipe, but this one combines the functions from left to right
const countWords3 = R.pipe(R.split(' '), R.length);
console.log(color.red(countWords3(sentence)));
<file_sep>// Implementation Detail
const _radius = new WeakMap();
const _size = new WeakMap();
// Public Interface
export class Circle {
constructor(radius) {
_radius.get(this, radius);
}
draw() {
console.log("drawing a circle with radius " + _radius.get(this));
}
}
export class Square {
constructor(size) {
_size.get(this, size);
}
draw() {
console.log("drawing a square of size " + _size.get(this));
}
}
<file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpService } from '../../http.service';
import { Book } from '../../models/book';
@Component({
selector: 'app-book-new',
templateUrl: './book-new.component.html',
styleUrls: ['./book-new.component.css']
})
export class BookNewComponent implements OnInit {
@Output() createBook = new EventEmitter<Book>();
book = new Book(); // this is the book referenced in the html and to which [(ngForm)] is binding
constructor(
private _httpService: HttpService,
private router: Router,
) { }
ngOnInit() {
}
onSubmit(event: Event, form: NgForm): void {
console.log('printing book form', form.value);
this._httpService.createBook(form.value)
.subscribe(() => {
this.createBook.emit(form.value);
// this.books.push(data); this line is being replaced with the emitter, so parent pushes to book list
this.book = new Book();
form.reset();
this.router.navigateByUrl('/');
}, error => {
console.log(error);
});
}
}
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8000;
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
const names = ['Jack','Jill','John','Jos']
app.get('/', (req,res) => {
res.render('index');
});
app.post('/names', (req,res) => {
console.log(req.body);
names.push(req.body.name);
res.redirect('/');
});
app.get('/names/:name_id', (req,res) => {
console.log(req);
console.log(req.params);
console.log(req.params.name_id);
res.send(names[req.params.name_id]);
});
app.listen(port, () => console.log(`Express server listening on port ${port}`));
<file_sep>import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Recipe } from '../recipe.model';
@Component({
selector: 'app-recipe-list',
templateUrl: './recipe-list.component.html',
styleUrls: ['./recipe-list.component.css']
})
export class RecipeListComponent implements OnInit {
@Output() recipeSelection = new EventEmitter<Recipe>();
recipes: Recipe[] = [
new Recipe(
'Cold Turkey',
'Just prepare and let it sit on the countertop',
'https://www.flamingo.ca/wp-content/uploads/2018/04/flamingo-Dinde_B-631x495.png'),
new Recipe(
'Hot Cocoa',
'Boiled water with fresh cocoa powder',
'http://cdn.shopify.com/s/files/1/0014/7125/0476/products/c105-cocoa-powder-alkalised-10-12-dutch-process-2_600x.png?v=1533145949'),
];
constructor() { }
ngOnInit() {
}
onSelectedRecipe(recipe: Recipe): void {
this.recipeSelection.emit(recipe);
}
}
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-17 19:07
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviews', '0003_auto_20180817_1113'),
]
operations = [
migrations.AlterField(
model_name='author',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 805000)),
),
migrations.AlterField(
model_name='author',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 805000)),
),
migrations.AlterField(
model_name='book',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 806000)),
),
migrations.AlterField(
model_name='book',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 806000)),
),
migrations.AlterField(
model_name='review',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 807000)),
),
migrations.AlterField(
model_name='review',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 807000)),
),
migrations.AlterField(
model_name='user',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 791000)),
),
migrations.AlterField(
model_name='user',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 14, 7, 40, 791000)),
),
]
<file_sep>user_input = input("Enter a number: ")
print(int(user_input) ** 2)
# alternative syntax
user_input2 = int(input("Enter another number: "))
print(user_input2 ** 3)
<file_sep># default parameter value can be set
def converter(fahr, cel=9/5):
return (fahr -32) / cel
fahrenheit = float(input("Enter temp in Fahrenheit: "))
print(converter(fahrenheit))
# if you want to override the default value, enter a second parameter, like
print(converter(4, 3))
<file_sep>table = [50,100,150,200,250]
num_table = enumerate(table,1)
print list(num_table)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=45)
content = models.TextField(max_length=2000)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __repr__(self):
return "<{}>".format(self.title)
<file_sep>SELECT leaders.first_name, leaders.last_name, friends.first_name AS friend_first_name, friends.last_name AS friend_last_name
FROM friendships
JOIN users AS leaders ON friendships.user_id = leaders.id
JOIN users AS friends ON friendships.friend_id = friends.id;
<file_sep>import { AlertsComponent } from './alerts.component';
import { SuccessComponent } from './successAlert/success.component';
import { WarningComponent } from './warningAlert/warning.component';
export const components: any[] = [ AlertsComponent, SuccessComponent, WarningComponent ];
export * from './alerts.component';
export * from './successAlert/success.component';
export * from './warningAlert/warning.component';
<file_sep>const array = [99,78,54,22];
// no callback
function each(array) {
const newArray = [];
for (let index = 0; index < array.length; index++) {
const square = array[index] * array[index];
console.log(index, array[index], square);
}
return newArray;
}
const results = each(array);
// with empty callback
function each2(array, callback) {
const newArray2 = [];
console.log(callback.toString())
for (let index = 0; index < array.length; index++) {
const square = array[index] * array[index];
console.log(index, array[index], square);
}
return newArray2;
}
const results2 = each2(array, function(){});
// with callback that does something
function each3(array, callback) {
const newArray3 = [];
console.log(callback.toString())
for (let index = 0; index < array.length; index++) {
callback(array[index], index, array);
}
return newArray3;
}
const results3 = each3(array, function(element){
const square = element * element;
console.log(element, square);
});
// callback cycle: it is customary to pass the current element, current index and full array to the callback even if it is not received just in case the callback function changes to one that does need that information
function each4(array, callback) {
const newArray4 = [];
console.log(callback.toString())
for (let index = 0; index < array.length; index++) {
const element = callback(array[index], index, array);
console.log('from callback ',element)
newArray4.push(element)
}
return newArray4;
}
const results4 = each4(array, function(element){
const square = element * element;
console.log('in callback',element, square);
return square
});
console.log(results4, array);
// end result
function each5(array, callback) {
const newArray5 = [];
for (let index = 0; index < array.length; index++) {
const element = callback(array[index], index, array);
newArray5.push(element)
}
return newArray5;
}
const results5 = each5(array, function(element) {
const square = element * element;
return square
});
console.log(results5, array);
const results6 = each5(array, function(num1, num2) {
const addition = num1 + num2;
return addition
});
console.log(results6, array)
<file_sep>$(document).ready(function(){
var counter = $('.counter').attr('alt-attr')
if(counter > 1){
$('#fromjquery').append('<img src="img/friendly.png"')
}
else[
$('#fromjquery').append('<img src="img/scary.jpg"')
]
// $('#fromjquery').html('<p>'+counter+'</p>')
})<file_sep>// 1- return accumulated sum of numbers up to n
function sigma(n){
var acc = 0;
for(var i = 1; i <= n; i++){
acc = acc + i;
}
return acc;
}
sigma(5);
// 2- returns factorial
function factorial(n){
var acc = 1;
for(var i = 2; i <= n; i++){
acc = acc * i;
}
return acc;
}
factorial(5);
// 3- returns fibonacci progression up to nth iteration
function f(n){
var fib = [0,1];
for(var i = 2; i <= n; i++){
fib.push(fib[i-2]+fib[i-1]);
}
return fib[n];
}
f(8);
// 4- return second to last element of an array, or nul if array too short
function eitherSecondToLastOrNull(arr){
if(arr.length < 2){
return 'nul';
}
else{
return arr[arr.length-2];
}
}
eitherSecondToLastOrNull([1,2,3,4,5,6,7,8]);
// 5- return nth to last element of an array, or nul if array too short
function nthToLast(arr, Y){
if(arr.length-Y < 0){
return 'nul';
}
else{
return arr[arr.length-Y];
}
}
nthToLast([5,2,3,6,4,9,7],3);
// 6- return the second largest number within an array
function secondLargest(arr){
if(arr.length == 1){
return arr.length;
}
else{
var max = arr[0];
var maxer = arr[0];
for(var i = 0; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
else if(arr[i] > maxer && arr[i] < max){
maxer = arr[i];
}
}
}
return maxer;
}
secondLargest([7,4,3,2,5,6,3,32,7,5,90,2,3,54,35,76,23,4,6,34,5,65,4,0]);
// 7- change the array to return elements twice, keep original order
function duplicate(arr){
var n = arr.length;
for(var i = 0; i < n; i++){
var temp = arr.pop()
arr.unshift(temp,temp);
}
return arr;
}
duplicate([1,2,3]);
// 8- fibonacci using recursion
function fib(n){
if(n == 0 || n == 1){
return n;
}
else{
return fib(n-2) + fib(n-1);
}
}
fib(8);
<file_sep># __init__ method will create objects with individuality as each will have a unique placement in memory and attribute and method parameters will be set as they are created
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.logged = False
user1 = User("<NAME>", "<EMAIL>")
print user1.name
print user1.email
print user1.logged
#notice logged was inherited, the name and email parameters are passed through __init__, self is still implicit
# user2 = User()
#we cannot do this anymore because __init__ is expecting the name and email parameters<file_sep>import random
n = 20 #doing 20 tosses, not 5000 to save space
heads = []
tails = []
print "Starting the program..."
output = ""
for i in range(1,n+1):
output += "Attempt #{}: ".format(i)
toss = random.randint(0,1)
if toss == 0:
heads.append(1)
output += "Throwing a coin... It's head!"
else:
tails.append(1)
output += "Throwing a coin... It's tail!"
output += " ... Got {} head(s) so far and {} tail(s) so far".format(sum(heads),sum(tails))+"\n"
output += "Ending program now, you got a total of {} heads and {} tails!".format(sum(heads),sum(tails))
print output<file_sep>const admin_router = require('./admin');
const shop_router = require('./shop');
const router = require('express').Router();
module.exports = router
.use('/admin', admin_router)
.use(shop_router)<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^posts$', views.posts, name="posts"),
]
<file_sep>import folium
import pandas
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
name = list(data['NAME'])
html = """
Volcano name:<br>
<a href="https://www.google.com/search?q=%%22%s%%22" target="_blank">%s</a><br>
Height: %s m
"""
def color_generator(elevation):
color = "red"
if elevation < 1000:
color = "green"
return color
elif 1000 <= elevation < 3000:
color = "orange"
return color
else:
return color
map = folium.Map((45,-115), zoom_start=5, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
# stylize the popup with an html element, using iFrame folioum method
for lt, ln, ele, name in zip(lat, lon, elev, name):
iframe = folium.IFrame(html=html % (name, name, str(ele)), width=200, height=100)
fg.add_child(folium.Marker(location=(lt, ln), popup=folium.Popup(iframe), icon=folium.Icon(color=color_generator(ele))))
map.add_child(fg)
map.save("Volcanoes3.html")<file_sep>function Cat(catName){
this.name = catName;
this.getName = function(){
return this.name
};
}
// create a Cat instance
var ruffini = new Cat("Ruffini");
var deborah = new Cat("Deborah")
// access and print instance private method
console.log(ruffini.getName());
// add method to the cat prototype
Cat.prototype.sayHi = function(){
console.log("meow")
}
ruffini.sayHi();
// add an attribute to the cat prototype
Cat.prototype.legs = 4;
// we can access the properties
console.log(ruffini.legs);
// we can print the object
console.log(ruffini)
// we can modify the instance's properties without modifying the prototype
ruffini.legs = 3;
console.log(ruffini.legs);
// we can modify the prototype's properties without modifying the instance's properties
// .__proto__ is how we access the prototype and change its inheritance!
ruffini.__proto__.legs++;
var barry = new Cat("Barry");
console.log("Ruffini has "+ruffini.legs+" legs;", "Barry has "+barry.legs+" legs;", "Deborah has "+deborah.legs+" legs!");
// deborah's legs were also changed through inheritance because they have not been actually set for the instance
<file_sep>for count in range(0, 3):
print 'counter is ',count
for letter in "kurtzweil":
print letter
string = 'kurtzweil'
for index in range (0,len(string)):
print index
x = 3
y = x
while y > 0:
print y
y = y - 1
else:
print "last else statement"
x = 10
y = x
while y > -10:
if y == 0:
print "zero"
elif y == -9:
print "my lucky number"
elif y == 6 or y == -6:
pass
else:
print "its ",y,"nono,"
y = y - 1
x = [1,2,3,4]
x += [2]
print x
<file_sep>{% extends './layout.html' %}
{% block title %}Book Reviews{% endblock %}
{% block body %}
<!-- displays a list of the three most recent reviews, each book title is a link to all of the book's reviews -->
<!-- each reviewer name is a link to the user information page-->
<!-- displays links to other book reviews-->
<div class="container">
<div class="row">
<div class="col d-flex justify-content-end">
<a href="{% url 'add' %}">Write a review</a>
<a href="{% url 'books' %}">Home</a>
<a href="/logout">Logout</a>
</div>
</div>
<div class="row">
<div class="col">
<h2>{{ book.title }}</h2>
<h5><span class="font-weight-light">Author:</span> {{ book.author.first_name }} {{ book.author.last_name }}</h5>
</div>
</div>
<div class="row">
<div class="col">
<h3>Reviews:</h3>
<hr>
{% for review in reviews %}
<p class="mb-0">Rating: {{ review.rating }}</p>
<div class="d-flex align-items-center">
<p class="mb-0"><a href="/users/{{ review.user.id }}" class="nested_link">{{ review.user.first_name }} {{ review.user.last_name }}</a> wrote: <span class="font-italic">{{ review.content }}</span></p>
</div>
<p class="mt-0">{{ review.created_at|date }}</p>
<hr>
{% endfor %}
</div>
<div class="col">
<h3>Add a review:</h3>
<form action="/books/{{ book.id }}/new_review" method="POST" class="form-group">{% csrf_token %}
<div class="form-row">
<div class="col-3">
<label for="review" class="col-form-label">Review:</label>
</div>
<div class="col d-flex">
<textarea class="flex-fill" name="review_content"></textarea>
</div>
</div>
<div class="form-row">
<div class="col-3">
<label for="rating" class="col-form-label">Star Rating:</label>
</div>
<div class="col">
<select name="rating">
<option value="*">*</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<div class="d-flex justify-content-center">
<button type="submit" class="btn btn-primary">Add Book Review</button>
</div>
</form>
<div class="col">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags == "error" %} class="text-white bg-warning" {% elif message.tags == "success" %} class="text-white bg-success" {% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}<file_sep>
// constructor function, we now use "this"
function Person(name, items){
// we create a guard statement for those cases in which Person instances are not created using "new Person"
if (!(this instanceof Person)) {
console.log(name, 'is not an instance of Person');
// in the following line, we create the Person instance using "new" in case it was not done so...
return new Person(name, items);
}
const person = { name };
// added this attribute
this.name = name;
this.items = items;
this.take = take
function take(item, target) {
if(!target || !Array.isArray(target.items)) {
console.log('target does not have items array');
}
for (let index = 0; index < target.items.length; index++) {
if (item === target.items[index]) {
target.items.splice(index,1);
console.log(target.name+"'s "+item+" was taken by "+this.name)
this.items.push(item);
console.log("now "+this.name+" has the "+item)
return true;
}
}
return false;
}
// when we use new, we don't have to return anything, so we comment out the below return statement, can just delete it
// return person;
}
// instances of Person we now make them using "new"
const person1 = new Person('Bob', ['key','sandwich','tickets']);
const person2 = new Person('Jerry', ['phone','money','ring']);
console.log(person1);
console.log(person2);
person2.take('key', person1);
person1.take('money', person2);
console.log(person1);
console.log(person2);
// NOW THAT WE REFACTORED TO "THIS" AND "NEW", WE CAN MAKE TAKE A GLOBAL METHOD.... SEE PART 4<file_sep>from flask import Flask, render_template, session, request, redirect
app = Flask(__name__)
app.secret_key = "ThisKeyIsSecret"
@app.route("/")
def index():
return render_template("index.html")
@app.route("/users", methods=["POST"])
def create_user():
print request.form
session['name'] = request.form["name"]
session['email'] = request.form["email"]
return redirect('/success')
# return render_template("success.html", name=name, email=email)
#session allows for 'persistent data storage' that is written during the request / response cycle
#this data is called 'state', it 'outlives' the process that generated it by getting it in writing in a dictionary
#developers keep state data to help them solve problems down the line
#cookies are packets of information stored in a small file in client's hard drive. this information is hashed, encrypted
@app.route("/success")
def show_user():
# return render_template("success.html", name=session['name'], email=session['email'])
# streamlined return command once we have applied session in our template....
return render_template("success.html")
app.run(debug=True)<file_sep>function printx(x){
console.log(x);
}
printx('nine');<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-game-control',
templateUrl: './game-control.component.html',
styleUrls: ['./game-control.component.css']
})
export class GameControlComponent {
n;
evens: number[] = [];
odds: number[] = [];
startGame() {
this.n = setInterval(() => {
const number = this.generateNumber(100);
if (number % 2 === 0) {
console.log(number, 'even');
this.evens.push(number);
} else {
console.log(number, 'odd');
this.odds.push(number);
}
}, 600);
}
stopGame() {
clearInterval(this.n);
}
generateNumber(max): number {
return Math.floor(Math.random() * Math.floor(max));
}
clearGame(): void {
this.evens = [];
this.odds = [];
}
}
<file_sep>const stringArray = ['1','2','3','4','5'];
const mixedArray = ['1','apple','2','3','sugar','4','5','horse'];
// each function: prints array data
function each(array,callback) {
for ( let index = 0; index < array.length; index++) {
callback(array[index], index);
};
};
each(stringArray, function(element, index) {
console.log(`from our anonymous function! element: ${element} | index: ${index}`)
});
each(stringArray, namedFunction);
function namedFunction(item) {
console.log(`from our named function! element: ${item}`);
};
// map function: returns a new array of transformed data by passing each element of the original array into a function
// we don't need the array and we don't need the function, all we need to do is build the infrastructure
function map(array, callback) {
let newArray = [];
for (let element = 0; element < array.length; element++) {
newArray.push(callback(array[element], element));
};
return newArray;
};
// now we decide to use 'map' with a specified array and a specified function
let results = map(stringArray, function(response) {
return parseInt(response,10);
});
console.log(results)
// filter function: receives an array of information and the callback function decides if it wants to accept it and put it in a new array
// at this point, we don't need to know either the array or the callback with the conditionals but we build the infrastructure
function filter(array, callback) {
const filteredArray = [];
for (let element = 0; element < array.length; element++) {
if (callback(array[element],element)) { //we are passing element although we don't need to; js doesn't break
filteredArray.push(array[element]);
};
};
return filteredArray;
};
let mixup = map(mixedArray, function(response) {
return parseInt(response,10);
});
console.log(mixup); // this returns NaNs because some of the elements are not numbers, so we can use the filter function now
mixup = filter(mixup, function(response) { // along with response, we can pass on other arguments and it won't matter 'cuz js.
// console.log(isNaN(response));
return !isNaN(response);
});
mixup = filter(mixup, function(response) {
return response % 2 === 0;
});
console.log(mixup);
// reject function: works like filter, but instead of pushing results that match a criteria, they pus results that do not match
// remember, first we build the infrastructure, then worry about the array and parent function
function reject(array, callback) {
const newArray = [];
for ( let index = 0; index < array.length; index++) {
if (!(callback(array[index]))) { //if it returns from the callback, does not push it to newArray
newArray.push(array[index]);
};
};
return newArray
};
let solution = map(mixedArray, function(response) {
return parseInt(response,10);
});
console.log(solution);
solution = reject(solution, function(response) {
return isNaN(response);
});
console.log(solution);
// find function: will see if an element is part of an array
function find(array, callback) {
for ( let idx = 0; idx < array.length; idx++ ) {
if (callback(array[idx], idx)) {
return (array[idx]);
};
};
};
let exists = find(mixedArray, function(response) {
return response === '4';
});
console.log(exists);
// reduce function: takes an array of values and reduces it to a single value
// in this function, memo is the summation of the result of the callback, and it is an optinal parameter. If it is not passed, returns undefined, so we do something...
function reduce(array, callback, memo) {
const results = [].concat(array);
if (memo === undefined) {
memo = results.pop(); // we made a copy of the array above so that the original one does not get destroyed by this operation
};
for (let index = 0; index < array.length; index++) {
memo = callback(memo, array[index], index);
};
return memo;
};
results = reduce(results, add);
function add(num1, num2) {
return num1 + num2;
};
console.log(results);
<file_sep>from flask import Flask, render_template, session, flash, request, redirect
import re
email_regex = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = "validation"
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user', methods=['POST'])
def user():
#validations
if len(request.form['first_name']) < 2:
flash("Enter full name", 'error')
if len(request.form['last_name']) < 2:
flash("Enter full last name", 'error')
if len(request.form['password']) < 8:
flash("Password minimum is 8 characters", 'security')
if not email_regex.match(request.form['email']):
flash("Invalid email address!", 'error')
if request.form['password'] != request.form['confirm_password']:
flash("Passwords don't match", 'error')
if "_flashes" in session:
return redirect("/")
#end validations
name = "{} {}".format(request.form['first_name'], request.form['last_name'])
email = request.form['email']
return render_template('user.html',name=name,email=email)
app.run(debug=True)<file_sep>#create a class
class Person(object):
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
self.health = 100
self.stealth = 10
def introduce(self):
print "hello, my name is {}".format(self.name)
def display(self):
print self.__dict__
person1 = Person("Mom", 63, 140) #this passes the arguments through Person's __init__ function
person2 = Person("Dad", 71, 160)
person1.introduce()
person1.display()
print person1.__dict__
#create a subclass called Ninja
#we need to pass name, age, and height cuz the parent's init has them, but we can refactor them to prepare for the parameters of the child...
class Ninja(Person):
def __init__(self, ninja_name, ninja_age, ninja_height):
super(Ninja, self).__init__(ninja_name, ninja_age, ninja_height)
self.stealth = 100
self.attack = 30
self.defense = 10
ninja1 = Ninja("Johiro", 30, 170)
ninja1.introduce()
ninja1.display()
class Coder(Person):
def __init__(self, coder_name, coder_age, coder_height):
super(Coder, self).__init__(coder_name, coder_age, coder_height)
self.favorite_language = 'Python'
coder1 = Coder("Helen", 11, 140)
coder1.introduce()
coder1.display()<file_sep>$(document).ready(() => {
var socket = io.connect();
console.log('welcome to socket', socket)
});<file_sep>import { RecipesComponent } from './recipes.component';
import { RecipeDetailComponent } from './recipe-detail/recipe-detail.component';
import { RecipeListComponent } from './recipe-list/recipe-list.component';
import { RecipeItemComponent } from './recipe-list/recipe-item/recipe-item.component';
export const components: any[] = [ RecipesComponent, RecipeDetailComponent, RecipeListComponent, RecipeItemComponent ];
export * from './recipes.component';
export * from './recipe-detail/recipe-detail.component';
export * from './recipe-list/recipe-list.component';
export * from './recipe-list/recipe-item/recipe-item.component';
<file_sep>for i in range (0,11): #declare counter and set range
if i % 2 == 0: #condition statement: is even if reminder of i/2 is zero
print i #what to do if condition is satisfied
for i in range (5,51): #declare counter and set range
if i % 5 == 0: #condition statement: is multiple of five if remainder of i/5 is zero
print i #what to do if condition is satisfied
a = [1, 2, 5, 10, 255, 3] #declare variable and assign a list of numbers as its value
num = sum(a) #use a built-in function to perform the task
print num #output result
a = [1, 2, 5, 10, 255, 3] #declare variable and assign a list of numbers as its value
num = sum(a) #use built in function to add the numbers
print num/len(a) #output: divide sum by number of items on the list to get the average<file_sep>words = "It's thanksgiving day. It's my birthday,too!"
print words.find("day")
print words.replace("day", "month")
x = [2,54,-2,7,12,98]
print max(x)
print min(x)
x = ["hello",2,54,-2,7,12,98,"world"]
print x[0]
print x[-1]
y = [x[0], x[-1]]
print y
items = [19,2,54,-2,7,12,98,32,10,-3,6]
items.sort()
print items
first_half = items[:len(items)/2]
second_half = items[len(items)/2:]
print first_half
print second_half
second_half.insert(0,first_half)
print second_half<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django import forms
# Create your models here.
class User(models.Model):
first_name=models.CharField(max_length=45)
last_name=models.CharField(max_length=45)
email=models.EmailField(max_length=45)
password=models.CharField(max_length=45)
crated_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
class Leads(models.Model):
first_name=models.CharField(max_length=45)
last_name=models.CharField(max_length=45)
email=models.EmailField(max_length=45)
crated_at=models.DateField(auto_now=False)
crated_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
<file_sep>
//1- Return a given array after converting all negative values to zero
function negNone(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] < 0){
arr[i] = 0;
}
}
document.getElementById("1").innerHTML = arr;
return arr;
}
negNone([-4,5,6,2,-3,7]);
//2- Return an array after dropping the first index and inserting zero at the end
function dropZero(arr){
arr.shift(arr[0]);
arr.push(0);
document.getElementById("2").innerHTML = arr;
return arr;
}
dropZero ([1,2,3]);
//3- Given an array, return an array with values in reversed order
function revArray(arr){
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.unshift(arr[i]);
}
document.getElementById("3").innerHTML = newArr;
return newArr;
}
revArray([1,2,3,4]);
//4- Create a function that changes a given array to list each original element twice, retaining the original order. Have the function return a new array.
function seeDouble(arr){
var newArr = [];
for(var i = 0; i < arr.length; i++){
newArr.push(arr[i],arr[i]);
}
document.getElementById("4").innerHTML = newArr;
return newArr;
}
seeDouble([1,2,3]);
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from django.core.exceptions import ImproperlyConfigured
# Create your views here.
def index(request):
return HttpResponse("it's alive!")
class Users(View):
def get(self, request):
# Get type view logic here!copy
# (for REST this would be show all users)
return render(request,'index.html')
def post(self, request):
# Post type view logic here!
# (for REST this would be create a new user)
return render(request,'index.html')
#this example renders a different footer, depending on class
class ExampleView(View):
footerText = "Fake Copyright 2016, Blob the Blob"
def get(self,request):
context = {
'footer':self.footerText
}
return render(request, 'views/index.html', context)
class ExtendExample(ExampleView):
footerText = "Fake Copyright 2017"
<file_sep>import { Resolve, ActivatedRouteSnapshot} from '@angular/router';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import { HttpService } from '../http.service';
import { Book } from '../models/book';
@Injectable()
export class BookResolve implements Resolve<Book> {
constructor(private _httpService: HttpService) { }
// resolves the information from the activated route and then loads route component associated with the route
// we need to tell angular app that we're using resolve by importing in app.module.ts
// we need to also include resolve in the routing module
// lastly, on the component, modify so that it uses resolve
resolve(route: ActivatedRouteSnapshot): Observable<Book> {
return this._httpService.getBook(route.paramMap.get('_id'));
}
}
<file_sep>import { ShoppingListComponent } from './shopping-list.component';
import { ShoppingEditComponent } from './shopping-edit/shopping-edit.component';
export const components: any[] = [ ShoppingListComponent, ShoppingEditComponent ];
export * from './shopping-list.component';
export * from './shopping-edit/shopping-edit.component';
<file_sep>const canEat = {
eat: function() {
this.hunger--;
console.log("eating");
}
};
const canWalk = {
walk: function() {
console.log("walking");
}
};
const canSwim = {
swim: function() {
console.log("swimming");
}
};
const person = Object.assign({}, canEat, canWalk);
console.log(person);
// or we can do this
function Dog() {}
Object.assign(Dog.prototype, canEat, canWalk);
let d = new Dog();
console.log(Object.getPrototypeOf(d));
function Goldfish() {}
Object.assign(Goldfish.prototype, canEat, canSwim);
const gg = new Goldfish();
gg.eat()
gg.swim()
<file_sep>function negConvert(arr){
for(var i = 0; i < arr.length; i++){
if(arr[i] > 0){
arr[i] = arr[i] * -1;
}
}
console.log(arr);
}
negConvert([-5,5,-5,-5,5,-5,5,-5,5]);<file_sep>import { Component, OnInit, EventEmitter, Output, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
@Output() createdServer = new EventEmitter<{name: string, content: string}>();
@Output() createdBlueprint = new EventEmitter<{name: string, content: string}>();
@ViewChild('serverNameInput') serverNameInput: ElementRef;
@ViewChild('serverContentInput') serverContentInput: ElementRef;
constructor() { }
ngOnInit() {
}
onAddServer() {
this.createdServer.emit({
name: this.serverNameInput.nativeElement.value,
content: this.serverContentInput.nativeElement.value
});
}
onAddBlueprint() {
this.createdBlueprint.emit({
name: this.serverNameInput.nativeElement.value,
content: this.serverContentInput.nativeElement.value
});
}
}
<file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-success',
template: `
<h6>Success!</h6>
<p>Content</p>
`,
styles: [`
* {
color: green;
}
`]
})
export class SuccessComponent {}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from datetime import datetime
from time import strftime
# Create your views here.
def index(request):
return render(request, 'session_words/index.html')
def add_word(request):
print request.POST
try:
request.POST['color']
color = request.POST['color']
except KeyError:
color = 'black'
try:
request.POST['font']
size = request.POST['font']
except KeyError:
size = 'small'
date = datetime.now().strftime('%A, %b %d %Y')
time = datetime.now().strftime('%H:%M:%S')
new_word = {
'word' : request.POST['word'],
'class' : color,
'size' : size,
'date' : date,
'time' : time
}
try:
request.session['words']
except KeyError:
request.session['words'] = []
word_list = request.session['words']
word_list.append(new_word)
request.session['words'] = word_list
return redirect('/session_words')
def reset(request):
print "got to session words reset method"
request.session.clear()
return redirect('/session_words')<file_sep>function drawPokemon(){
for(var i = 100; i <= 250; i++){
$('.container').append('<img src="http://pokeapi.co/media/sprites/pokemon/'+i+'.png" alt="pokemon">')
}
}
$(document).ready(function(){
drawPokemon();
});<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.core import serializers
from .models import User
# Create your views here.
def fetch(request):
return render(request, 'demo_1/fetch.html')
def all_json(request):
users = User.objects.all()
users_json = serializers.serialize("json", users)
return HttpResponse(users_json, content_type="application/json")
def all_html(request):
user_fetch = User.objects.all()
return render(request, "demo_1/all.html", {'users':user_fetch})
def find(request):
return render(request, "demo_1/find.html")
def find_process(request):
users = User.objects.filter(first_name__startswith=request.POST['name_start'])
print users
return render(request, "demo_1/all.html", {'users':users})
def create(request):
return render(request, "demo_1/new.html")
def create_process(request):
User.objects.create(
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
age=request.POST['age']
)
users = User.objects.all().order_by('-id')
return render(request, "demo_1/all.html", {'users':users})
<file_sep>$(document).ready(function(){
//talk to the api and get the names of the first 10 characters
for(var i = 0; i < 10; i++){
$.get('https://swapi.co/api/people/'+i, function(res){
//once we get response, display the name in a business card
console.log(res);
var id = res.url.split("/")[5]; //this grabs the id # of the character
var htmlStr = `
<div data-id="${id}">
<h1>${res.name}</h1>
</div>
`;
$('.starpeople').append(htmlStr);
}, 'json');
}
$('.starpeople').on('click', 'div', function(){
var idx = $(this).attr('data-id');
$.get('https://swapi.co/api/people/'+idx, function(person){
$('.charac').html('<ul><li>'+person.height+'</li><li>'+person.mass+'</li></ul>')
}, 'json');
});
});<file_sep>import { Assignment1Component } from './assignment1/assignment1.component';
import { Assignment2Component } from './assignment2/assignment2.component';
export const components: any[] = [ Assignment1Component, Assignment2Component, ];
export * from './assignment1/assignment1.component';
export * from './assignment2/assignment2.component';
<file_sep># unpacking means taking a list and making each element an individual parameter that is passed through the function
# args are packed and unpacked with *
my_list = [1,2,3,4]
# a packed list
print(my_list)
# an unpacked list
print(*my_list)
# any iterable data type can be unpacked (incl strings)
my_string = "abcde"
print(my_string)
print(*my_string)
# make a sum function that takes any number of numbers and adds them
def adder(*nums):
total = 0
for num in nums:
total = total + num
return total
print(adder(1,2,3,4,5,6,7,8))
print(adder(1,2,3,4,5))
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.messages import constants as messages
from .models import Blog
# Create your views here.
def index(request):
return HttpResponse('working on validations')
def update(request):
errors = Blog.objects.basic_validator(request.POST)
if len(errors):
for tag, error in errors.iteritems():
messages.error(request, error, extra_tags=tag)
return redirect('/blog/edit/'+id)
else:
blog = Blog.objects.get(id = id)
blog.name = request.POST['name']
blog.desc = request.POST['desc']
blog.save()
return redirect('/blogs')<file_sep># with is the preferred method for writing files instead of the traditional one
# traditional
myfile = open("file.txt", "w")
myfile.write("Hello again!")
myfile.close()
# with
with open("file2.txt", "w") as myfile2:
myfile2.write("Hi there!")
# no need to close<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-22 14:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('formtest', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='username',
field=models.CharField(default='herozero12', max_length=45),
preserve_default=False,
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(max_length=45),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(max_length=45),
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(max_length=45),
),
]
<file_sep>import folium
import pandas
data = pandas.read_csv("Volcanoes.txt", delimiter=",")
lat = list(data['LAT'])
lon = list(data['LON'])
elev = list(data['ELEV'])
def color_generator(elevation):
color = "red"
if elevation < 1000:
color = "green"
return color
elif 1000 <= elevation < 3000:
color = "orange"
return color
else:
return color
map = folium.Map((45,-115), zoom_start=5, tiles="Mapbox Bright")
fg = folium.FeatureGroup(name="map_features")
# stylize the popup with an html element, using iFrame folioum method
for lt, ln, ele in zip(lat, lon, elev):
fg.add_child(folium.CircleMarker(location=(lt, ln), radius=6, popup=str(ele) + " m", fill_color=color_generator(ele), color='grey',fill_opacity=0.7))
map.add_child(fg)
map.save("Volcanoes4.html")<file_sep>#Make any needed changes in MathDojo in order to support tuples of values in addition to lists and singletons.
class MathDojo(object):
def __init__(self):
self.output = 0
def add(self, *numbers):
self.list = list(numbers)
for item in self.list:
if type(item) == int:
self.output += item
else:
self.output += sum(item)
return self
def subtract(self, *numbers):
self.list = list(numbers)
for item in self.list:
if type(item) == int:
self.output -= item
else:
self.output -= sum(item)
return self
def result(self):
print self.output
md = MathDojo()
md.add([1],3,4).add([3,5,7,8], [2,4.3,1.25]).subtract(2,(2,3),[1.1,2.3]).subtract((2,3)).result()
<file_sep>"use strict";
const performance = require("perf_hooks").performance;
// are there duplicates?
// accept a variable length array and check if duplicates
// frequency counter solution:
function findDupCount(arr) {
let o = {};
for (let n of arr) {
if (o[n]) {
return true;
} else {
o[n] = 1;
}
}
return false;
}
const array = [1, 2, 3, 2];
const t1 = performance.now();
const result = findDupCount(array);
const t2 = performance.now();
console.log(result);
console.log(`Time elapsed: ${(t2 - t1) / 1000} seconds`);
// another frequency counter solution - slower:
function findDupCount2(arr) {
let obj = {};
for (let i in arr) {
obj[arr[i]] = (obj[arr[i]] || 0) + 1;
}
for (let key in obj) {
if (obj[key] > 1) return true;
}
return false;
}
const t3 = performance.now();
const result2 = findDupCount2(array);
const t4 = performance.now();
console.log(result);
console.log(`Time elapsed: ${(t4 - t3) / 1000} seconds`);
<file_sep># placing an asterisk before a parameter name means the variable will be passed a number of arguments
def varargs1(arg1, *others):
print "Got "+arg1+" and "+", ".join(others)
varargs1("one")
varargs1("one, two")
varargs1("one, two, three")
# what * does is join the rest of the arguments into a tuple
def varargs2(arg1, *others):
print "restOfArg is of " + str(type(others))
print arg1+", "+", ".join(others)
varargs2("one", "two", "three")
# OUTPUT: restOfArg is of <type 'tuple'>
# what .join does is make a string list out of the other arguments<file_sep>import { Directive, HostBinding, Input, HostListener } from '@angular/core';
@Directive({
selector: '[appCustomHighlightWithInitAlternative]'
})
export class CustomHighlightWithInitAlternativeDirective {
@Input() initialColor = 'cyan';
@Input() highlightColor: string;
@HostBinding('style.backgroundColor') backgroundAlter = this.initialColor;
@HostListener('mouseenter') mouseenter(eventData: Event) {
this.backgroundAlter = this.highlightColor;
}
@HostListener('mouseleave') mouseleave(eventData: Event) {
this.backgroundAlter = this.initialColor;
}
}
<file_sep>export class Ingredient {
constructor(public name: string, public amount: number) {}
}
// the above code does exactly what we usually do with OOP, but it is so common that Typescript provides a short way of doing it, as shown.
// export class Ingredient {
// public name: string;
// public amount: number;
// constructor(name: string, amount: number) {
// this.name = name;
// this.amount = amount;
// }
// }
<file_sep># classes are templates and instances of classes are objecs
# classes are made up of variables (states) and functions (methods)
# each variable type in Python is its own class. Example, string class, number class, list class, dictionary class
# recap:
# classes are just templates
# we instantiate a class to make an object
# objects are made of two things: they have states and they have behaviors
# to create states we use class variables
# to create behaviors we use methods (or functions that belong to classes)
# simple class
# class <Name>:
# states
# class with methods:
# class <Name>:
# def __init__(self, **kwargs)
# self.kwargs
# def methods
# class inheritance: creating sub-classes from one parent class
# see example in 4_class_inheritance
# class polymorphism: when behavior differs within a class because objects might behave differently from parent and siblings
# to do this, we override class methods inside specific instances
# see example in 5_class_polymorphism - Five_Pence(coin), where we override the rust() and clean() methods.<file_sep>import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
newServerName = '';
newServerContent = '';
@Output() createdServer = new EventEmitter<{name: string, content: string}>();
@Output() createdBlueprint = new EventEmitter<{name: string, content: string}>();
constructor() { }
ngOnInit() {
}
onAddServer() {
this.createdServer.emit({name: this.newServerName, content: this.newServerContent});
}
onAddBlueprint() {
this.createdBlueprint.emit({name: this.newServerName, content: this.newServerContent});
}
}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
import random
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def index(request):
if 'earnings' not in request.session:
request.session['earnings'] = 0
request.session['activity'] = []
request.session['messages'] = []
request.session['earns'] = 0
context = {
'earnings' : request.session['earnings'],
'messages' : request.session['messages'],
}
return render(request, "ninja_gold/index.html", context)
def earn(request):
print request.POST['activity']
if request.POST['activity'] == "Farm":
earns = random.randint(10,20)
request.session['activity'].append("Farm")
elif request.POST['activity'] == "Cave":
earns = random.randint(5,10)
request.session['activity'].append("Cave")
elif request.POST['activity'] == "House":
earns = random.randint(2,5)
request.session['activity'].append("House")
elif request.POST['activity'] == "Casino":
earns = random.randint(-50,50)
request.session['activity'].append("Casino")
else:
earns = 0
request.session['earnings'] += earns
message = "Earned {} golds from the {}!".format(earns,request.POST['activity'])
messages = request.session['messages']
messages.append(message)
request.session['messages'] = messages
request.session['earns'] = earns
return redirect('/ninja_gold')
def clear(request):
for key in request.session.keys():
del request.session[key]
return redirect("/ninja_gold")
<file_sep>from django.conf.urls import url,
from . import views
# option 1
urlpatterns = [
url(r'^$', views.ExtendExample.as_view(), name = 'index'),
]
# option2
# urlpatterns = [
# url(r'^$', views.ExtendExample.as_view(footerText="bananaPhone"), name = 'index'),
# ]
<file_sep>// Implementation Detail
const _radius = new WeakMap();
const _size = new WeakMap();
// Public Interface
class Circle {
constructor(radius) {
_radius.get(this, radius);
}
draw() {
console.log("drawing a circle with radius " + _radius.get(this));
}
}
class Square {
constructor(size) {
_size.get(this, size);
}
draw() {
console.log("drawing a square of size " + _size.get(this));
}
}
module.exports.Circle = Circle;
module.exports.Square = Square;
<file_sep>
# reduce performs a computation on a list and returns the result.
# it applies a rolling computation to sequential pairs of values in a list.
from functools import reduce
my_list = [1,2,3,4,5]
product = reduce((lambda x, y: x * y), my_list)
print product
<file_sep>#DICTIONARIES
#Recap: lists are [a,b,c] tuples are (a,b,c)
#dictionaries are { "key":"value", "key":"value" }
#keys must be unique
#creating dictionaries:
#a) literal notation:
weekend = {"Sun": "Sunday", "Sat": "Saturday"}
#b) create an empty dictionary then add values:
capitals = {}
capitals["svk"] = "Bratislava"
capitals["deu"] = "Berlin"
capitals["dnk"] = "Copenhagen"
#accessing values:
print weekend["Sun"]
print capitals["svk"]
#FOR LOOPS accessing values with for loops
#to print all keys
for data in capitals:
print data
#another way to print all keys
for key in capitals.iterkeys():
print key
#to print the values
for val in capitals.itervalues():
print val
#to print all keys and values
for key,data in capitals.iteritems():
print key, " = ", data
#practice...
name = {"sw":"S<NAME>", "mp":"<NAME>"}
for key, value in name:
print key, value
name = {"sw":"S<NAME>", "mp":"<NAME>"}
print name.items()
for temp in name.items():
print temp
for key, value in name.items():
print key, value
#.items() is a library method that does something similar to what enumerate() does globally. it converts item's key:value pairs into a tuple.
my_people = [
{"name":"mikel", "food":"fast"},
{"name":"helen", "food":"asian"},
{"name":"johanna", "food":"asian"},
{"name":"jose", "food":"asian"},
]
for i in my_people:
print i
if i['food'] == 'asian':
print i['name']
<file_sep>//object destructuring
//create variables t.a and t.b without declaration
let t = {
a: "Hank",
b: 12,
c: "Tank",
};
let {a,b} = t;
console.log(a);
console.log(b);
//assignment without declaration, needs surrounding ()
({a,b} = {a:"baz", b:101});
console.log(a,b);
//that does not affect t
console.log(t);
//create variable for remaining items
let rex = {
h: "stomach",
g: 4,
j: "paws"
}
let {h, ...remaining} = rex;
console.log(h);
console.log(remaining);
//default values
function newObject(
wholeObject: {
name: string,
age?: number,
}
let {}
)
//spread with objects:
let foodStuff = {food: "spicy", pricey: "$$", noisy: true};
let foodSearch = {...foodStuff, food:"rich"};
<file_sep>from math import sqrt
n = input("Maximum number? ")
n = int(n) + 1
for a in range (1,n):
for b in range (a,n):
c_square = a**2 + b**2
c = int(sqrt(c_square))
if ((c_square-c**2) == 0):
print(a,b,c)
<file_sep>import md5 #imports md5 module to generate a hash
#make up a password:
password = '<PASSWORD>'
#encrypt the password provided as a 32 character string:
hashed_password = md5.new(password).hexdigest()
#for demonstration purposes, print the hashed passord:
print hashed_password
# has is the same all the time, thus making it viable to check passwords upon log-in.
<file_sep># for loop operation
list = [1, 3, 6]
for i in list:
c = i + 10
print(c)
# read a file and perform operations with its contents
myfile = open('fruits.txt')
content = myfile.read()
myfile.close()
content = content.splitlines()
for fruit in content:
print(len(fruit) * 100)
# conditional returns
mylist = [1,2,3,4,5]
for num in mylist:
if num > 2:
print(num)
# list operations
temps = [10, -20, 100]
def cel_to_fahr(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
for temp in temps:
print(cel_to_fahr(temp))<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from datetime import datetime
import bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your models here.
class UserManager(models.Manager):
def validator(self, fname, lname, email, uname, pword):
errors = []
email_exists = self.filter(email=email)
if len(email_exists) != 0:
errors.append("Email already exists")
uname_exists = self.filter(uname=uname)
if len(uname_exists) != 0:
errors.append("Username already exists")
if len(fname) < 1:
errors.append("Please enter first name, more than 1 character expected")
if len(lname) < 1:
errors.append("Please enter last name, more than 1 character expected")
if not EMAIL_REGEX.match(email):
errors.append("Please use a valid email address")
if len(uname) < 8:
errors.append("Please enter a username, at least 8 characters expected")
if len(pword) < 8:
errors.append("Please enter a password, at least 8 characters expected")
return errors
def LoginValidator(self, uname, pword):
errors = []
if uname == "":
errors.append("Please enter a username address")
if pword == "":
errors.append("Please enter a password")
if len(errors) != 0:
return (False, errors)
else:
#because you are in the manager, no need for User.objects.filter()
#user filter instead of get to avoid getting errors in there are multiple or none
users = self.filter(uname=uname)
if len(users) == 0:
errors.append("Username does not exist")
else:
user = users[0]
u_pword = user.pword
if bcrypt.checkpw(pword.encode(), u_pword.encode()):
return (True, user.id)
else:
errors.append("Password does not match")
return (False, errors)
def UserUpdateValidator(self, id, fname, lname, email, uname):
errors = []
email_exists = self.filter(email=email)
if len(email_exists) != 0:
email_user = email_exists[0].id
if str(email_user) != str(id):
errors.append("Email already exists! You may not need to update this, leave blank if so.")
uname_exists = self.filter(uname=uname)
if len(uname_exists) != 0:
uname_user = uname_exists[0].id
if str(uname_user) != str(id):
errors.append("Username already exists! You may not need to update this, leave blank if so.")
if len(fname) < 1:
errors.append("Please enter first name, more than 1 character expected")
if len(lname) < 1:
errors.append("Please enter last name, more than 1 character expected")
if not EMAIL_REGEX.match(email):
errors.append("Please use a valid email address")
if len(uname) < 8:
errors.append("Please enter a valid username, at least 8 characters expected")
return errors
def PasswordValidator(self, id, pword, pword_confirm):
errors = []
if pword == "":
errors.append("Please enter a password")
if len(pword) < 8:
errors.append('Please choose a password longer than 8 characters')
if pword_confirm == "":
errors.append("Please confirm password")
if pword != pword_confirm:
errors.append("Passwords do not match")
return errors
# def TimeConverter(self, right_now, message_time):
# self.days_since = (right_now - message_time).days
# self.hours_since = self.days_since/24
# self.minutes_since = self.days_since/(24*60)
# if self.days_since >= 1:
# time_since = str(self.days_since) + " days ago"
# if self.hours_since >= 1:
# time_since = str(self.hours_since) + " hours ago"
# else:
# time_since = str(self.minutes_since) + " minutes ago"
# return time_since
class User(models.Model):
fname = models.CharField(max_length=255)
lname = models.CharField(max_length=255)
email = models.CharField(max_length=255)
uname = models.CharField(max_length=255)
pword = models.CharField(max_length=255)
user_profile = models.CharField(max_length=255)
created_at = models.DateTimeField(default=datetime.now())
updated_at = models.DateTimeField(default=datetime.now())
objects = UserManager()
def __repr__(self):
return "<{} {}>".format(self.fname, self.lname)
class Message(models.Model):
user_to_id = models.ForeignKey(User, related_name="messages_received")
user_from_id = models.ForeignKey(User, related_name="messages_sent")
content = models.TextField(max_length=2000)
created_at = models.DateTimeField(default=datetime.now())
class Comment(models.Model):
content = models.TextField(max_length=1000)
user = models.ForeignKey(User, related_name="comments")
message = models.ForeignKey(Message, related_name="comments")
created_at = models.DateTimeField(default=datetime.now())<file_sep>$(document).ready(function(){
$('h1').click(function(){
$('.details').html("");
});
$('.container').on('click','img',function(){
$('.details').html("");
var which = $(this).attr('data-id');
$.get('https://anapioficeandfire.com/api/houses/'+which, function(response){
// console.log(response);
var html_str = `
<h2>${response.name}</h2>
<h3>"${response.words}"</h3>
<p>${response.titles}</p>
`;
$('.details').append(html_str)
}, 'json');
});
})
// https://anapioficeandfire.com/api/houses?page=1&pageSize=50
// https://anapioficeandfire.com/api/houses?name=House%20Stark%20of%20Winterfell or
// https://anapioficeandfire.com/api/houses?name=House%20Baratheon%20of%20Storm%27s%20End or 17
// https://anapioficeandfire.com/api/houses?name=House%20Lannister%20of%20Casterly%20Rock or 229
// https://anapioficeandfire.com/api/houses?name=House%20House%20Targaryen%20of%20King%27s%20Landing or 378
<file_sep>// REQUIRE MONGOOSE
const mongoose = require('mongoose');
const color = require('colors');
// MONGOOSE CONNECTION
//mongoose connection takes the url of the db you want to work with including the port.
//useNewUrlParser is a new feature they are implementing so start incorporating
//you can pass along other options like username, password
// mongoose.connect('mongodb://localhost:27017/animals', {
// useNewUrlParser: true,
// user: 'bob',
// pass: '<PASSWORD>'
// });
mongoose.connect('mongodb://localhost:27017/animals', { useNewUrlParser: true });
//connection is an object that has an event emitter and listener
mongoose.connection.on('connected', () => console.log('Mongoose connected'));
// OBJECTS
// let's build our object
const o = {
a: 'this is a',
b: 'this is b'
};
// traditional way to call attribute a of object o:
// const a = o.a;
// destructuring way of calling attribute b of object o:
// const {b} = o;
// with destructuring we can call both attributes at the same time:
// const {a,b} = o;
// console.log(a, b);
// but if a is already declared somewhere? there is a solution, we rename o.a to somenthing else:
const a = 'original a';
const { a: notA, b } = o;
console.log(a, notA, b);
// SCHEMA
// schema is how we are going to define shape to our data
// we provide shape or structure to the db documents through schemas
// from the mongoose object, we extract Schema, we use an object destructuring pattern like so....
// either ... const Schema = mongoose.schema;
// or its equivalent... mongoose {Schema } = mongoose;
// Schema is a constructor, and this is how it is used...
const {Schema} = mongoose;
//each attribute of the Schema is a path, we can specify certain behavior like required, trim...
const animalSchema = new Schema({
name: {
type: String,
required: [true, `Provide a name for your animal`],
trim: true
},
age: {
type: Number,
min: [0, `Age minimum is 0`],
required: [true, `Provide the age of your animal`],
},
legs: {
type: Number,
min: [0, `Leg minimum is 0`],
required: [true, `How many legs does your animal have?`],
},
eatsPeople: {
type: Boolean,
default: false
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: false
}
});
// with the shape of the information, we now tell mongoose and mongo about it, so we register it with them with mongoose's 'model' method which is a getter and a setter:
//to name it use capital letter and singular, this will become a collection and it will rename it to lower case and plural; it also needs the schema, and it builds a blueprint for our data
const Animal = mongoose.model('Animal', animalSchema);
//to retrieve this information (getter) if working in another file
// const Animal = mongoose.model('Animal');
//to create new animal instances (setter)
const animal1 = new Animal({
name: 'Lion',
age: 6,
legs: 4,
eatsPeople: true
});
console.log(color.white(animal1));
//we save to database with the .save() method
// animal1.save();
// the instance we create extends a document, which has a number of methods attached to it.
// we can pass callbacks through the .save() db command and see
// we pass error and saved callbacks; ***remember that error is passed first on callbacks***
// animal1.save((error,saved)=>{
// console.log(error, saved);
// });
//we might want to do something with the error:
// animal1.save((error,saved)=>{
// if (error) {
// //handle the error
// }
// console.log(animal1);
// });
// but better if we use promises to avoid pyramid of doom:
// if we console log the animal.save() operation, we notice there is a promise pending, so we can use promises here for error handling
//console.log(animal.save())
animal1.save()
.then(function(saved) {
//do stuff
console.log(color.yellow(saved));
})
//assumes validation type errors:
.catch(function(error) {
const errors = Object.keys(error.errors)
.map(key => error.errors[key].message);
console.log(color.red(errors))
// if we wanted to render the errors in a page:
// response.render('some_page', {errors});
});
// .catch(function(error) {
// //Object.keys(error.errors) gives us an array of all keys containing an error:
// const keys = Object.keys(error.errors);
// const errors = [];
// for (let i = 0; i < keys.length; i++) {
// console.log(i, keys[i]);
// const message = error.errors[keys[i]].message
// console.log(message);
// errors.push(message);
// }
// console.log(errors)
// });
// .catch(function(error) {
// const errors = [];
// Object.keys(error.errors).forEach(key => {
// console.log(key);
// const message = error.errors[key].message;
// errors.push(message);
// })
// console.log (errors);
// });
// .catch(function(error) {
// const errors = Object.keys(error.errors).map(key => {
// console.log(color.red(key));
// const message = error.errors[key].message;
// return message;
// })
// console.log(color.red(errors));
// });
<file_sep>#given an object, we can create methods:
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.logged = False
def login(self):
self.logged = True
print self.name + " is logged in"
return self
def show(self):
print "this is " + self.name
return self
def logout(self):
self.logged = False
print "is " + self.name + " logged in?" + " " + str(self.logged)
return self
user1 = User("<NAME>", "<EMAIL>")
#we can run methods like this:
# user1.login()
# user1.show()
# user1.logout()
#or we can run them like this when we return self after each method:
user1.login().show().logout()
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-11 20:08
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20180811_1448'),
]
operations = [
migrations.AlterField(
model_name='user',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 11, 15, 8, 44, 589000)),
),
migrations.AlterField(
model_name='user',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 11, 15, 8, 44, 589000)),
),
]
<file_sep>function ETF(ticker, rsi,pctR) {
this.ticker = ticker;
this.rsi = rsi;
this.pctR = pctR;
};
ETF.prototype.rate = function() {
this.rating = this.rsi + this.pctR;
// console.log(this.rating);
return this;
};
function rate_etfs() {
for (i = 0; i < etfs.length; i++) {
etfs[i].rate();
}
};
function investability(ticker) {
var investability_rating = ticker.rating;
if (investability_rating >= 60) {
console.log(ticker.ticker+' is investable');
} else {
console.log(ticker.ticker+' is not investable');
}
return investability_rating;
};
function recommendations(etfs, callback) {
for (let i = 0; i < etfs.length; i++) {
// console.log(etfs[i], etfs[i].rating)
callback(etfs[i]);
}
};
//this process built the initial database
var EWG = new ETF('EWG', 50, -69);
var XLF = new ETF('XLF', 66, -28);
var XLB = new ETF('XLB', 59, -36);
var XLY = new ETF('XLY', 77, -1);
var XLI = new ETF('XLI', 68, -13);
var SPY = new ETF('SPY', 75, -1);
var etfs = [EWG, XLF, XLB, XLY, XLI, SPY];
//run this process to update the array of stocks in the database
let XME = new ETF('XME', 52.42, -49.66);
etfs.push(XME);
//run this process to update technicals of the stocks
// XLF.rsi=90;
//run this process to rate all ETFS
rate_etfs();
//run this process to issue recommendations
recommendations(etfs, investability);
//get all investable tickers
function investable() {
const investables = []
for (var i = 0; i < etfs.length; i++) {
if (etfs[i].rating > 60) {
investables.push(etfs[i]);
}
}
return investables
}
// console.log(investable());
return (XLF,investability);<file_sep>class Car(object):
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
if self.price > 10000:
self.tax = 0.15
else:
self.tax = 0.12
def display_all(self):
print "Car price: {}, speed:{}, fuel: {}, mileage: {}, tax: {}".format(self.price, self.speed, self.fuel, self.mileage, self.tax)
return self
car1 = Car(2000, "35mph", fuel = "Full", mileage = "15mpg")
car2 = Car(2000, "5mph", fuel = "Not Full", mileage = "105mpg")
car3 = Car(2000, "15mph", fuel = "Full", mileage = "25mpg")
car4 = Car(2000, "45mph", fuel = "Empty", mileage = "25mpg")
car5 = Car(20000, "35mph", fuel = "Empty", mileage = "15mpg")
car1.display_all()
car2.display_all()
car3.display_all()
car4.display_all()
car5.display_all()
<file_sep>const express = require('express');
const app = express();
app.use('/users', (req, res, next) => {
console.log('in the users route');
res.send('<p>You got to the users route</p>');
});
app.use('/', (req, res, next) => {
console.log('in the root route');
res.send('<p>You got to the root route</p>');
});
app.listen(3000);
<file_sep>// in this example, we refactor the prototypical inheritance methods into a reusable function. The use of this function is called intermediate function inheritance.
function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
function Shape(color) {
this.color = color;
}
Shape.prototype.duplicate = function() {
console.log("duplicate");
};
function Circle(radius, color) {
Shape.call(this, color); // super constructor
this.radius = radius;
}
extend(Circle, Shape);
Circle.prototype.draw = function() {
console.log("draw");
};
function Square(size, color) {
Shape.call(this, color);
this.size = size;
}
extend(Square, Shape);
const sq = new Square(10, "blue");
console.log(sq);<file_sep>#Inheritance and composition
#The question of "inheritance versus composition" comes down to an attempt to solve the problem of reusable code. You don't want the duplicated code all over your codebase since it is neither clean nor efficient. Inheritance solves this problem by creating a mechanism for you to have implied features in base classes. Composition solves this by giving you modules and the ability to call functions in other classes.
class Apples(object):
def color(self):
print "red"
def taste(self):
print "sweet"
def shape(self):
print "roundish"
class Oranges(object):
def __init__(self):
self.apples = Apples()
def color(self):
print "orange"
def taste(self):
print "sweet-sour"
def shape(self):
self.apples.shape()
# notice that Oranges is not a child of Apples, but calls Apples object in order to use one of its attributes
florida = Oranges()
florida.color()
florida.taste()
florida.shape()
<file_sep>"use strict";
// what are they and why use them?
// immediately invoked function expression
// they are used not to pollute the global scope with variables from the different files that are loaded
// IIFE makes it possible to wrap the functionality in anonymous functions like so:
function thing() {
const thing = {name: "Halo"}
console.log("the thing is ", thing);
}
thing();
(function() {
const thing = {name: "Thirteen"}
console.log("the thing is ", thing)
})();
// notice we don't need to name it, therefore, less pollution.
// the idea is we don't want to get any loose functions from any source to pollute the global scope
// named functions pollute:
console.log(thing)
<file_sep>def change(cents):
coins = {
'dollar': 1,
'quarter': 0.25,
'dime': 0.1,
'nickel': 0.05,
'penny': 0.01
}
#dollars = 0
#quarters = 0
#dimes = 0
#nickels = 0
#pennies = 0
if cents > coins['dollar']:
dollars = (int(cents/coins['dollar']))
remainder = cents - dollars
print "{} dollars".format(dollars)
print "and {} cents remaining".format(remainder)
if remainder > 0:
quarters = (int(remainder/coins['quarter']))
remainder = round(remainder - quarters*coins['quarter'],2)
print "{} quarters".format(quarters)
print "and {} cents remaining".format(remainder)
if remainder > 0:
dimes = (int(remainder/coins['dime']))
remainder = round(remainder - dimes*coins['dime'],2)
print "{} dimes".format(dimes)
print "and {} cents remaining".format(remainder)
if remainder > 0:
nickels = (int(remainder/coins['nickel']))
remainder = round(remainder - nickels*coins['nickel'],2)
print "{} nickels".format(nickels)
print "and {} cents remaining".format(remainder)
if remainder > 0:
pennies = (int(remainder/coins['penny']))
remainder = round(remainder - pennies*coins['penny'],2)
print "{} pennies".format(pennies)
print "and {} cents remaining".format(remainder)
change(3.8)
<file_sep>const express = require('express');
const app = express();
// we route requests to different middleware with the use of paths
// path is the first parameter taken by app.use()
// the second parameter is the middleware
// for more info about app.use, check the expressjs.com api
// file is read top to bottom and looks for path matches.
// so we reserve the '/' root route for the bottom...
// note we don't use next(); so that we don't send two responses by sending request to the next middleware
// but if we do use next();, we'll be able to channel requests through middleware that always runs:
app.use('/', (req, res, next) => {
console.log('This always runs, has the root route, but let\'s request to continue because of next');
next();
});
app.use('/new', (req, res, next) => {
console.log('In the new middleware!');
res.send('<h1>The Add New Page</h1>');
});
app.use('/', (req, res, next) => {
console.log('In the root middleware!');
res.send('<h1>Hello from Express!</h1>');
});
app.listen(3000);<file_sep>function HtmlElement() {
this.click = function() {
console.log("click");
};
}
HtmlElement.prototype.focus = function() {
console.log("focus");
};
const e = new HtmlElement();
e.click();
e.focus();
function HtmlSelectElement(items = []) {
this.items = items;
this.addItem = function(i) {
this.items.push(i);
};
this.removeItem = function(i) {
items.splice(this.items.indexOf(i), 1);
};
this.render = function() {
return `
<select>${this.items
.map(item => `<option>${item}</option>`)
.join("")}</select>`;
};
}
HtmlSelectElement.prototype = new HtmlElement();
HtmlSelectElement.prototype.constructor = HtmlSelectElement;
function HtmlImageElement(src) {
this.src = src;
this.render = function() {
return `<img src="${this.src}" />`;
};
}
HtmlImageElement.prototype = new HtmlElement();
HtmlImageElement.prototype.constructor = HtmlImageElement;
const img = new HtmlImageElement();
console.log(img);
img.src = "http://";
img.render();
const elements = [
new HtmlSelectElement([1, 2, 3]),
new HtmlImageElement("http://")
];
<file_sep># you can override parent behavior by defining it at the child level and there will not be a conflict:
class Parent(object):
def hobbies(self):
print "Watching TV"
class Child(Parent):
def hobbies(self):
print "Coding"
bob = Parent()
ren = Child()
bob.hobbies()
ren.hobbies()
# polymorphism occurs when other siblings also differ but in a different way
class Sibling(Parent):
def hobbies(self):
print "instagram"
pip = Sibling()
pip.hobbies()<file_sep>sentence = ["This is a tricky exercise"]
for word in sentence:
for letter in word[-10:]:
print(letter)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
import bcrypt
from django.contrib import messages
from datetime import datetime, timedelta, tzinfo
import pytz
from time import strftime, gmtime
from .models import *
# Create your views here.
def index(request):
return render(request, "user_dashboard/index.html")
def login(request):
# if request.method != 'POST':
# return redirect('main')
return render(request, "user_dashboard/login.html")
def login_process(request):
if request.method != 'POST':
return redirect('login')
uname = request.POST['uname']
pword = request.POST['pword']
result = User.objects.LoginValidator(uname, pword)
if result[0]:
request.session['logged_user'] = result[1]
request.session['user'] = User.objects.get(id=request.session['logged_user']).fname
request.session['user_profile'] = User.objects.get(id=request.session['logged_user']).user_profile
print request.session['user'], "IS LOGGED IN AS: ", request.session['user_profile']
return redirect('/users/dashboard')
else:
for message in result[1]:
messages.error(request, message)
return redirect('/login')
return redirect("/")
def register(request):
# if request.method != 'POST':
# return redirect('main')
return render(request, "user_dashboard/register.html")
def register_process(request):
if request.method != 'POST':
return redirect('registration')
fname = request.POST['fname']
lname = request.POST['lname']
email = request.POST['email']
uname = request.POST['uname']
pword = request.POST['pword']
if request.POST['admin'] == "Yes":
user_profile = "admin"
else:
user_profile = "user"
errors = User.objects.validator(fname, lname, email, uname, pword)
if len(errors) == 0:
User.objects.create(
fname = fname,
lname = lname,
email = email,
uname = uname,
pword = bcrypt.hashpw(pword.encode(), bcrypt.gensalt()),
user_profile = user_profile
)
messages.success(request, "User has been created")
return redirect('/register')
else:
for message in errors:
messages.error(request, message)
return redirect('/register')
return redirect("/register")
def edit(request, id):
if 'logged_user' not in request.session:
return redirect('main')
if request.method != 'POST':
return redirect('dashboard')
user = User.objects.get(id=id)
print "WILL UPDATE {}, {}, {}, {}".format(user.fname, user.lname, user.email, user.uname)
context = {
'id':user.id,
'fname':user.fname,
'lname':user.lname,
'email':user.email,
'uname':user.uname
}
return render(request, "user_dashboard/edit.html", context)
def editing(request, id):
if request.method != 'POST':
return redirect('dashboard')
user = User.objects.get(id=id)
if len(request.POST['fname']) == 0:
user.fname = user.fname
else:
user.fname=request.POST['fname']
if len(request.POST['lname']) == 0:
user.lname = user.lname
else:
user.lname=request.POST['lname']
if len(request.POST['email']) == 0:
user.email = user.email
else:
user.email=request.POST['email']
if len(request.POST['uname']) == 0:
user.uname = user.uname
else:
user.uname=request.POST['uname']
if request.POST['admin'] == "Yes":
user.user_profile = "admin"
else:
user.user_profile = "user"
errors = User.objects.UserUpdateValidator(id, fname=user.fname, lname=user.lname, email=user.email, uname=user.uname)
if len(errors) == 0:
user.updated_at = datetime.now()
user.save()
messages.success(request, "User contact successfully updated")
else:
for message in errors:
messages.error(request, message)
return redirect('/users/'+id+'/edit')
def updating_pw(request, id):
if request.method != 'POST':
return redirect('dashboard')
pword = request.POST['pword']
pword_confirm = request.POST['pword_confirm']
errors = User.objects.PasswordValidator(id, pword, pword_confirm)
if len(errors) == 0:
user = User.objects.get(id=id)
user.pword = bcrypt.hashpw(pword.encode(), bcrypt.gensalt())
user.save()
messages.success(request, "Password successfully changed")
return redirect('/users/'+id+'/edit')
else:
for message in errors:
messages.error(request, message)
return redirect('/users/'+id+'/edit')
return redirect('/users/'+id+'/edit')
def update(request, id):
if 'logged_user' not in request.session:
return redirect('main')
if request.method != 'POST':
return redirect('dashboard')
user = User.objects.get(id=id)
request.session['fname'] = user.fname
request.session['lname'] = user.lname
request.session['email'] = user.email
request.session['user_profile'] = user.user_profile
context = {
'fname':user.fname,
'lname':user.lname,
'email':user.email
}
return render(request, "user_dashboard/update.html", context)
def add(request):
if 'logged_user' not in request.session:
return redirect('main')
if request.method != 'POST':
return redirect('dashboard')
return render(request, "user_dashboard/new.html")
def add_process(request):
if request.method != 'POST':
return redirect('dashboard')
fname = request.POST['fname']
lname = request.POST['lname']
email = request.POST['email']
uname = request.POST['uname']
pword = request.POST['pword']
if request.POST['admin'] == "Yes":
user_profile = "admin"
else:
user_profile = "user"
errors = User.objects.validator(fname, lname, email, uname, pword)
if len(errors) == 0:
User.objects.create(
fname = fname,
lname = lname,
email = email,
uname = uname,
pword = bcrypt.hashpw(pword.encode(), bcrypt.gensalt()),
user_profile = user_profile
)
messages.success(request, "User has been created")
return redirect('add')
else:
for message in errors:
messages.error(request, message)
return redirect('add')
return redirect("dashboard")
def delete(request, id):
if 'logged_user' not in request.session:
return redirect('main')
if request.method != 'POST':
return redirect('dashboard')
delete_user = User.objects.get(id=id)
delete_user.delete()
return redirect('/users/dashboard')
def process(request):
if request.method != 'POST':
return redirect('dashboard')
User.objects.create(
first_name=request.POST['first_name'],
last_name=request.POST['last_name'],
email=request.POST['email'],
password=request.POST['password'],
)
return redirect('/user_dashboard')
def show(request, id):
if 'logged_user' not in request.session:
return redirect('main')
u = User.objects.get(id=id)
m = u.messages_received.all()
# #this is an exercise to see if timedelta works:
# right_now = datetime.now()
# message_time = u.created_at.replace(tzinfo=None)
# days_since = (right_now - message_time).days
# print right_now
# print message_time
# print days_since
# time_since = User.objects.TimeConverter(right_now, message_time)
# print "TIME SINCE: ",time_since
message_list = []
for i in range(0,len(m)):
c = m[i].comments.all()
message_dict = {}
message_dict['id'] = m[i].id
message_dict['content'] = m[i].content
message_dict['author'] = str("{} {}".format(m[i].user_from_id.fname, m[i].user_from_id.lname))
message_dict['date'] = str(m[i].created_at.strftime('%x %X'))
message_dict['comments'] = []
for j in range(0,len(c)):
comment_dict = {}
comment_dict['id'] = c[j].id
comment_dict['content'] = c[j].content
comment_dict['author'] = str("{} {}".format(c[j].user.fname, c[j].user.lname))
comment_dict['date'] = str(c[j].created_at.strftime('%x %X'))
message_dict['comments'].append(comment_dict)
message_list.append(message_dict)
context = {
'user':u,
'messages':reversed(message_list)
}
return render(request,"user_dashboard/user.html", context)
def dashboard(request):
if 'logged_user' not in request.session:
return redirect('main')
users = User.objects.all()
context = {
'users':users
}
return render(request, "user_dashboard/dashboard.html", context)
def logout(request):
for key in request.session.keys():
del request.session[key]
return redirect('main')
def message(request, id):
if request.method != 'POST':
return redirect('dashboard')
if request.POST['message'] == "":
return redirect('show', id)
message = request.POST['message']
message_to = User.objects.get(id=id)
message_from = User.objects.get(id=request.session['logged_user'])
Message.objects.create(user_to_id=message_to, user_from_id=message_from, content=message, created_at=datetime.now())
return redirect('show', id)
def comment(request, u_id, m_id):
if request.method != 'POST':
return redirect('dashboard')
if request.POST['comment'] == "":
return redirect('show', u_id)
comment = request.POST['comment']
comment_to = Message.objects.get(id=m_id)
comment_from = User.objects.get(id=request.session['logged_user'])
Comment.objects.create(content=comment, user=comment_from, message=comment_to, created_at=datetime.now())
return redirect('show', u_id)
<file_sep>function sumAndReturn(arr){
var count = 0;
if(arr.length == 1){
console.log("not possible");
}
else {
for(var i = 0; i < arr.length; i++){
if(arr[i] > arr[1]){
console.log(arr[i]);
count++;
}
}
console.log(count);
}
}
sumAndReturn([7,5,8,2,7,3,9]);
<file_sep>function leapYear(y){
if( y % 4 == 0 ){
if( y % 100 == 0 && y % 400 !== 0 ){
return("not leap year");
}
return("leap year");
}
else{
return("not leap year");
}
}
console.log(leapYear(2000)); <file_sep>function mixUp(lowNum, highNum, mult){
for( var i = highNum; i >= lowNum; i--){
if(i % mult == 0){
console.log(i);
}
}
}
mixUp(5,67,12);<file_sep>from datetime import datetime
now = datetime.now()
filename = datetime.strftime(now, "%Y-%m-%d-%H-%M-%S-%f") + ".txt"
print(filename)
with open('files/file1.txt', 'r') as file1:
f1 = file1.read()
with open('files/file2.txt', 'r') as file2:
f2 = file2.read()
with open('files/file3.txt', 'r') as file3:
f3 = file3.read()
with open('files/%s' % filename, 'w') as filename:
filename.write(f1 + "\n" + f2 + "\n" + f3)
<file_sep>import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-assignment2',
templateUrl: './assignment2.component.html',
styles: [`
.fivePlus {
background-color: lightgray;
}
`]
})
export class Assignment2Component implements OnInit {
togglerPress = true;
counter = 0;
counts: number[] = [];
timestamps: object[] = [];
constructor() { }
ngOnInit() {
}
toggleView(): void {
this.togglerPress = !this.togglerPress;
}
countMore(): void {
this.counter++;
this.counts.push(this.counter);
this.timestamps.push(new Date());
}
resetCounter(): void {
this.counter = 0;
this.counts = [];
this.timestamps = [];
}
}
<file_sep>const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello Again!'));
//requests for static files are served with the use of express.static built-in middleware function in Express.
//the function signature es 'express.static(root,[options])'
app.use(express.static('static'));
//to create virtual path prefixes:
app.use('/static', express.static('static'));
//if the directory where static files are is relative to the directory from where the node server is launched, safer to use the absolute path:
app.use('static', express.static(__dirname, 'static'));
app.listen(port, () => console.log(`Example app listening on port ${port}`));
<file_sep>//PAGE 16
//setting and swapping
var myNumber = 43;
var myName = "Jose";
var tempOral = myName;
var myName = myNumber;
var myNumber = tempOral;
console.log(myNumber, myName);
var tempOral = myNumber;
var myNumber = myName;
var myName = tempOral;
console.log(myNumber, myName);
//print -52 to 1066
for (var i = -52; i <=1066; i++){
console.log(i);
}
//Don't Worry, Be Happy
function beCheerful() {
for (var i = 1; i <= 98; i++){
console.log("good morning!");
}
}
beCheerful();
//Multiples of Three -- but Not All
for (var skippy = -300; skippy <= 0; skippy++){
if (skippy % 3 === 0){
if (skippy === -6 || skippy === -3){
continue;
}
console.log(skippy);
}
}
//Printing Integers with While
var num = 2000;
while (num <= 5280){
console.log(num);
num = num + 1;
}
//You Say It's Your Birthday
function birthYayNay (num1, num2){
if ((num1 === 10 || num1 === 8) && (num2 === 10 || num2 === 8)){
console.log("How did you know?");
}
else{
console.log("Just another day.");
}
}
//Leap Year
function LeapYear (numYear){
if ((numYear % 4 === 0 && numYear % 100 === 0) || numYear % 400 === 0){
console.log("Leap year!");
}
else{
console.log("Not a leap year.");
}
}
//Print and Count
var pBucket = []
var pAndC = 512;
while (pAndC <= 4096){
if (pAndC % 5 === 0){
console.log(pAndC);
pBucket.push(pAndC);
}
pAndC = pAndC + 1;
}
console.log(pBucket.length);
//Multiples of Six
var multiSix = 6;
while (multiSix <= 60){
if (multiSix % 6 === 0){
console.log(multiSix);
}
multiSix = multiSix + 1;
}
//Counting the Dojo Way
for (i = 1; i <= 100; i++){
if (i % 10 === 0 && i % 5 === 0){
console.log("Coding Dojo");
}
else if (i % 5 === 0){
console.log("Coding");
}
else{
console.log(i);
}
}
//What Do You Know?
function printParameter(toPrint){
console.log(toPrint);
}
//Whoa, That Sucker's Huge...
var oddBucket = [];
var sumBucket = 0
for (i = -300000; i <= 300000; i++){
if (i % 2 === 0){
continue;
}
sumBucket = sumBucket + i;
oddBucket.push(i);
}
console.log(sumBucket/oddBucket.length);
//Countdown by Fours
var numStart = 2016;
while (numStart > 0){
if (numStart % 4 === 0){
console.log(numStart);
}
numStart = numStart - 1;
}
//Flexible Countdown
function flexibleCountdown(lowNum, highNum, mult){
while (highNum > lowNum){
if (highNum % mult === 0){
console.log(highNum);
}
highNum = highNum - 1;
}
}
//The Final Countdown
function finalCountdown(param1,param2,param3,param4){
for (chips = param2; chips <= param3; chips++){
if (chips % param1 === 0){
if(chips === param4){
continue;
}
console.log(chips);
}
}
}
//PAGE 20
//Countdown
function countDown(inIput){
var arr = [];
for (i = inIput; i > 0; i--){
arr.push(i);
}
console.log(arr.length);
}
//Print and Return
function printAndReturn(num1, num2){
var arr = [num1, num2];
console.log(arr[0]);
return(arr[1]);
}
//First Plus Length
function weirdArray(item1, item2, item3, item4){
var arr = [item1, item2, item3, item4];
var weirdSum = arr[0] + arr.length;
console.log(weirdSum);
}
//Values Greater than Second
arr = [1,3,5,7,9,13];
arrBucket = [];
for (i = 0; i < arr.length; i++){
if (arr[i] > arr[1]){
arrBucket.push(arr[i]);
console.log(arr[i]);
}
}
console.log(arrBucket.length);
//Values Greater than Second, Generalized
function greaterThanSecond(arr){
var arrBucket = [];
for (i = 0; i < arr.length; i++){
if (arr[i] > arr[1]){
arrBucket.push(arr[i]);
console.log(arr[i]);
}
}
console.log(arrBucket.length);
}
//This Length, That Value
function jinxIt(num1, num2){
var arrJinx = [];
if (num1 === num2){
console.log("Jinx!");
}
else{
for (i = 0; i <= num1; i++){
arrJinx.push(num2);
}
}
return(arrJinx);
}
//Fit the First Value
function fitThat(arr){
if(arr[0] > arr.length){
console.log("Too big!");
}
else if(arr[0] < arr.length){
console.log("Too small!");
}
else{
console.log("Just perfect!");
}
}
//Fahrenheit to Celsius
function fahrenheitToCelsius(fDegrees){
var celsiusTemp = (fDegrees - 32) * 5/9;
console.log(celsiusTemp);
}
//Celsius to Fahrenheit
function celsiusToFahrenheit(cDegrees){
var fahrenheitTemp = cDegrees * 9/5 + 32;
console.log(fahrenheitTemp);
}
//PAGE 22
//Biggie Size
function biggieSize(arr){
for (i = 0; i < arr.length; i++){
if (arr[i] > 0){
arr[i] = "big";
}
}
console.log(arr);
}
//Pring Low, Return High
function printLReturnH(arr){
var maxi = arr[0];
var mini = arr[0];
for (i = 1; i < arr.length; i++){
if (arr[1] > maxi){
maxi = arr[1];
}
else if (arr[1] < mini){
mini = arr[1];
}
}
console.log(mini);
return(maxi);
}
//Double Vision
function double(arr){
var arrDouble = [];
for (i = 0; i < arr.length; i++){
arrDouble.push(arr[i]*2);
}
console.log(arrDouble);
}
//Count Positives
function countPositives(arr){
var arrBucket = [];
for (i = 0; i < arr.length; i++){
if (arr[i] > 0){
arrBucket.push(arr[i]);
}
}
arr.pop();
arr.push(arrBucket.length);
console.log(arr);
}
//Evens and Odds
function evenOdds(arr){
var evenTracker = 0;
var oddTracker = 0;
for (i = 0; i < arr.length; i++){
if (arr[i] % 2 === 0){
oddTracker = 0;
evenTracker += 1;
}
else{
evenTracker = 0;
oddTracker += 1;
}
if (oddTracker > 0 && oddTracker % 3 === 0){
console.log("That's odd!");
}
else if (evenTracker > 0 && evenTracker % 3 === 0){
console.log("Even more so!");
}
}
}
//Increment the Seconds
function incrementSeconds(arrOriginal){
var arrIncreased = [];
for (i = 0; i < arrOriginal.length; i++){
if (arrOriginal[i] % 2 === 0){
arrIncreased.push(arrOriginal[i]);
}
else{
arrIncreased.push(arrOriginal[i]+1);
console.log(arrOriginal[i]+1);
}
}
console.log("original: " + arrOriginal);
console.log("increased: " + arrIncreased);
}
//Previous Lengths
function previousLengths(stringArr){
var numArr = [];
for (i = 0; i < stringArr.length; i++){
numArr.push(stringArr[i].length);
}
console.log(numArr);
}
//Seven Up
function sevenUp(originalArr){
var modifiedArr = [originalArr[0]];
for (i = 1; i < originalArr.length; i++){
modifiedArr.push(originalArr[i] + 7);
}
console.log(modifiedArr);
}
//Reverse Array - the short version
function reverseArray(originalArr){
originalArr.reverse();
console.log(originalArr);
}
//Reverse Array - the long version
function revArr(arr) {
var reversed = [];
for(var i = arr.length - 1; i >= 0; i--) {
reversed.push(arr[i]);
}
console.log(reversed);
}
revArr([1,2,3,4,5,6]);
//Outlook: Negative
function outlookNegative(arr){
for (i = 0; i < arr.length; i++){
if (arr[i] > 0){
arr[i] = -arr[i];
}
}
console.log(arr);
}
//Always Hungry
function alwaysHungry(arr){
var foodBucket = [];
for (i =0; i < arr.length; i++){
if (arr[i] === "food"){
console.log("yummy");
foodBucket.push(1);
}
}
if (foodBucket.length === 0){
console.log("I'm hungry");
}
}
//Swap Toward the Center
function complexSwap(arr){
var iterations = Math.round(arr.length/4);
for (i = 0; i < iterations; i++){
var temp = arr[0 + i*2];
arr[0 + i*2] = arr[arr.length - i*2 - 1];
arr[arr.length - i*2 - 1] = temp;
}
console.log(arr);
}
//Scale the Array
function scaledArr(arr, num){
for (i = 0; i < arr.length; i++){
arr[i] = arr[i] * num;
}
console.log(arr);
}<file_sep>const Product = require('../models/product');
module.exports = {
getProducts(req, res, next) {
Product.findAll()
.then(products => {
res.render('shop/product-list', {
prods: products,
pageTitle: 'All Products',
path: '/products'
});
})
.catch(err => console.log(err));
},
getProduct(req, res, next) {
const prodId = req.params.productId;
Product.findByPk(prodId)
.then((product) => {
res.render('shop/product-detail', {
product: product,
pageTitle: product.title,
path: '/products'
});
})
.catch(err => console.log(err));
},
getIndex(req, res, next) {
Product.findAll()
.then(products => {
res.render('shop/index', {
prods: products,
pageTitle: 'Shop',
path: '/'
});
})
.catch(err => console.log(err));
},
getCart(req, res, next) {
req.user
.getCart()
.then(cart => {
return cart
.getProducts()
.then(products => {
res.render('shop/cart', {
path: '/cart',
pageTitle: 'Your Cart',
products: products
});
})
.catch(err => console.log(err));
})
.catch(err => console.log(err))
},
postCart(req, res, next) {
const prodId = req.body.productId;
let fetchedCart;
let newQuantity = 1;
req.user
.getCart()
.then(cart => {
fetchedCart = cart;
return cart.getProducts({where: {id: prodId}});
})
.then(products => {
let product;
if(products.length > 0) {
product = products[0];
}
if (product) {
const oldQuantity = product.cartItem.quantity;
newQuantity = oldQuantity + 1;
return product;
}
return Product.findByPk(prodId)
})
.then(product => {
return fetchedCart.addProduct(product, {through: {quantity: newQuantity}});
})
.then(() => {
res.redirect('/cart');
})
.catch(err => console.log(err));
},
postCartDeleteProduct(req, res, next) {
const prodId = req.body.productId;
req.user.getCart()
.then(cart => {
return cart.getProducts({where: {id: prodId}});
})
.then(products => {
const product = products[0];
return product.cartItem.destroy();
})
.then(result => {
res.redirect('/cart');
})
.catch(err => console.log(err));
},
postOrder(req, res, next) {
let fetchedCart;
req.user.getCart()
.then(cart => {
fetchedCart = cart;
return cart.getProducts();
})
.then(products => {
return req.user.createOrder()
.then(order => {
return order.addProducts(products.map(product => {
product.orderItem = {quantity: product.cartItem.quantity};
return product;
}));
})
.catch(err => console.log(err));
})
.then(result => {
return fetchedCart.setProducts(null);
})
.then(result => {
res.redirect('/orders');
})
.catch(err => console.log(err));
},
getOrders(req, res, next) {
req.user.getOrders({include: ['products']})
.then(orders => {
res.render('shop/orders', {
path: '/orders',
pageTitle: 'Your Orders',
orders: orders
});
})
.catch(err => console.log(err));
},
}
<file_sep>user_input = float(input("Enter a number: "))
if user_input > 100:
print("Greater than 100")
elif user_input == 100:
print("Is 100")
else:
print("Smaller than 100")<file_sep>arr = ['mike','baby','samuel','parachute']
function insertionSort(arr) {
for (var i = 0; i < arr.length; i++) {
var value = arr[i]
for (var j = i -1; j > -1 && arr[j] > value; j--) {
arr[j + 1] = arr[j]
}
arr[j + 1] = value
}
console.log(arr)
}
insertionSort(arr);<file_sep>const _radius = new WeakMap();
class Circle {
constructor(radius) {
_radius.set(this, radius);
}
get radius() {
return _radius.get(this);
}
set radius(v) {
if (v <= 0) throw new Error("invalid property");
_radius.set(this, v);
}
}
const c = new Circle(1);
console.log(c.radius);
c.radius = 10;
console.log(c.radius);
c.radius = 2;
console.log(c.radius);
<file_sep>// initialize an object
function Dog () {};
// that was a function used as constructor. as any function, it is initialized WITH a prototype object.
console.log(Dog.prototype); // Dog {}
console.log(Dog.prototype.prototype); // undefined, prototypes' common ancestor is Null
var fido = new Dog();
console.log(fido.prototype);
// constructor is 'new' and creates another Dog object called fido, which is an instance of Dog
Dog.prototype.bark = function () { console.log('wooof!') };
console.log(Dog.prototype);
console.log(fido.prototype);
fido.bark();
// bark method is available to its instances via their prototype; it is not of the instance, it is of its prototype, but are available through an invisible link, this called 'differential' inheritance or prototype chain. JS looks for bark() in fido, does not find it, so goes up a level to its prototype, where it finds it
var dido = Object.create(Dog);
console.log(dido)
// Object.create creates a new, empty object that has Dog in its prototype chain
function Car () {};
var ford = new Car();
var chevy = Object.create(Car);
console.log(`var ford = new Car() gives: `,ford)
console.log("var ford = Object.create(Car) prototype is: ",ford.prototype)
console.log("ford type of is: ",typeof ford)
console.log(`var chevy = new Car() gives: `,chevy)
console.log("Object.create(Car) prototype is: ",chevy.prototype)
console.log("chevy type of is: ",typeof chevy)
Car.prototype.drive = function() {console.log('vrooom')};
ford.drive();
// chevy.drive(); throws an error
//this is an object, but not a constructor
var Plane = { fly: function() {console.log('flying high speeed!');}};
Plane.fly();
//this is prototypal initialization
var jumbo = Object.create(Plane.prototype);
jumbo.fly();
console.log(`jumbo is `,jumbo )
console.log(`jumbo's prototype is `,jumbo.prototype);
console.log(`jumbo is of type `,typeof jumbo);
Plane.prototype.land = function() {console.log('landing!!')};
jumbo.land();
// this is a constructor
function Rectangle (width, height) {
this.width = width;
this.height = height;
};
Rectangle.prototype.area = function() {
return this.width * this.height
};
// this is an object
var rect = new Rectangle(3,4);
console.log(rect.area());
// this throws an error saying that Object prototype can only be an object or null, not a function!!
// var mini = Object.create(Rectangle(2,2));
<file_sep>string = 'ABCDEFG123456'
this = string[1]
print(this)
# slice
# variable[start:end:step]
slice1 = string[2:6:2]
slice2 = string[2:6:1]
print(slice1)
print(slice2)
slice3 = string[:4]
slice4 = string[5:]
slice5 = string[5::2]
print(slice3)
print(slice4)
print(slice5)
# reverse with slice
slice6 = string[::-1]
slice7 = string[:6:-1]
print(slice6)
print(slice7)
<file_sep>from django import forms
from .models import Post
class new_post_form(forms.Form):
title = forms.CharField(max_length=45)
content = forms.CharField(widget=forms.Textarea)
<file_sep>"use strict";
// use sliding window to keep track of a subset of data within a larger one
// in this exercise, find the max sum of n consecutive numbers:
function maxSubarraySum(arr, num) {
if (num > arr.length) {
return null;
}
let sum1 = 0;
for (let i = 0; i < num; i++) {
sum1 = sum1 + arr[i];
}
let sumRoll = sum1;
for (let j = num; j < arr.length; j++) {
sumRoll = sumRoll + arr[j] - arr[j - num];
sum1 = Math.max(sum1, sumRoll);
}
let result = Math.max(sum1, sumRoll);
return result;
}
const arr1 = [2,6,9,2,1,8,5,6,3];
const num1 = 3;
let res1 = maxSubarraySum(arr1, num1);
console.log(res1);
<file_sep>from flask import Flask, render_template #adding render_template allows us to render the referenced html within templates folder
app = Flask(__name__) #create variable Flask(and wait for a name)
@app.route('/') #this functions as the root route because only '/'
def root_route(): #this is the function triggered at the root
return render_template('index.html')
@app.route('/success') #@ decorator attaches the upcoming function to the '/success' path
def success(): #we define the function
return render_template('success.html') #this is what the function will do, will render the html in the templates folder
app.run(debug=True) #run app in debug mode
# recap:
# create a generic route:
# @app.route('/some_route')
# def some_function():
# //some code
# and voila! whenever someone calls for localhost:5000/some_route in the browser, the function will be called into action
<file_sep>const book_controller = require('../../controllers').book_controller;
const router = require('express').Router();
router.get('/', book_controller.index);
router.get('/new', book_controller.new);
router.post('/', book_controller.create);
router.get('/:id', book_controller.show);
router.get('/:id/edit', book_controller.edit);
router.post('/:id/update', book_controller.update);
router.get('/:id/delete', book_controller.destroy);
module.exports = router;<file_sep>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^create_note$', views.create_note, name="create_note"),
url(r'^delete_note/(?P<id>\d+)$', views.delete_note, name="delete_note"),
url(r'^edit_note/(?P<id>\d+)$', views.edit_note, name="edit_note"),
]
<file_sep>$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault()
$.ajax({
url: $(this).attr('action'), /* where this will go */
method: $(this).attr('method'), /* which http verb */
data: $(this).serialize(), /* any data to send along; serialized is easier for server to parse */
success: function(serverResponse){ /* callback function: code to run when server responds */
console.log("got the server response, should be rendering via ajax...")
$('.posts').html(serverResponse) /* replace html inside div class posts with the response */
}
})
});
});
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse
from .forms import new_post_form
from .models import Post
# Create your views here.
#this function renders index html with the post form designed in forms.py
def index(request):
# fetch all posts and render them with form
context = {
'posts':Post.objects.all(),
'post_form':new_post_form()
}
return render(request, "basic_setup/index.html", context)
#the form submission is taken over by javascript
#js will route the submission to ursl.py:post/create which routes to the post_create function
#post_create function sends data to models for creation in the database
def posts(request):
if request.method == 'POST':
# create post (could run validation prior to doing this)
Post.objects.create(title=request.POST['title'], content=request.POST['content'])
#create context to render partial html
context = {
'posts':Post.objects.all()
}
return render(request, "basic_setup/posts.html", context)
#in parallel, we have created an html called posts.html to format the context created above with only the notes<file_sep>class User(object):
name = "Helen"
anna = User()
print anna.name
anna.name = "Mikel"
print anna.name
bob = User()
print bob.name
#inherits name from parent
#self refers to the individual instance of the object
#notice no need to pass self through the User() object upon creation because it is implicit<file_sep>import math
# more in depth number libraries are numpy and scipy
#rounding
num = 2 / 3
print(num)
print(math.floor(num))
print(math.ceil(num))
#special numbers
print(math.pi)
print(math.e)
#trigonometry
print(math.cos(0))
print(math.asin(0))
print(math.acos(0))
print(math.sin(math.pi/2))
print(math.sin(math.pi))
# to make sin of pi exactly zero:
print(math.floor(math.sin(math.pi)))
#pythagorean theorem
print(math.hypot(3,4))
#powers .. this returns float
print(math.pow(2,3))
#or .. this returns int
print(2**3)
#exponential
print(math.exp(2))
#natural log
print(math.log(math.e))
print(math.log(2/3))
#base 10 log
print(math.log10(1000))
#base 2 log
print(math.log2(3))
<file_sep>function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
function Shape(color) {
this.color = color;
}
Shape.prototype.duplicate = function() {
console.log("duplicate shape");
};
function Circle(radius, color) {
Shape.call(this, color); // super constructor
this.radius = radius;
}
extend(Circle, Shape);
Circle.prototype.draw = function() {
console.log("draw");
};
// here we override a shape method so it behaves as we need in a circle
Circle.prototype.duplicate = function() {
console.log("duplicate circle");
}
const s1 = new Shape("green");
const c1 = new Circle(1, "red");
s1.duplicate();
c1.duplicate();
<file_sep># make a class
class Pound:
value = 1.00
color = "gold"
num_edges = 1
diameter = 22.50 # mm
thickness = 3.15 # mm
heads = True
# make an object
coin1 = Pound()
print(type(coin1))
print(coin1.value)
print(coin1.color)
# update an object's state
coin1.color = 'greenish'
print(coin1.color)
# create a new instance, and see that objects behave independently from each other
coin2 = Pound()
print(coin2.color)
<file_sep>import {
Component,
Input,
OnInit,
OnChanges,
SimpleChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy,
} from '@angular/core';
@Component({
selector: 'app-server-element',
templateUrl: './server-element.component.html',
styleUrls: ['./server-element.component.css']
})
export class ServerElementComponent implements OnInit,
OnChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy {
@Input() element: {type: string, name: string, content: string};
@Input() name: string;
constructor() {
console.log('in the constructor');
}
// onChanges takes an argument
// changes observes the bound element which in here is an "@Input() element"
// it logs current and previous values of tracked elements
ngOnChanges(changes: SimpleChanges) {
console.log('from onChanges we see...', changes);
}
// does not give access to element contents that are being craeted because they do not exist on init.
ngOnInit() {
console.log('from ngOnInit');
}
// doCheck tracks every change. if there's a click, an input, a promise is returned
ngDoCheck() {
console.log('ngDoCheck');
}
ngAfterContentInit() {
console.log('ngAfterContentInit');
}
ngAfterContentChecked() {
console.log('ngAfterContentChecked');
}
// content init and view init are different. a view can be projected even though it does not exist in the component; a content does exist
// @ContentChile gives access to this information, see an example in the project called cmp-databinding-projecting_content_into_components
// from this point, you can start checking DOM cntent with the methods because at this point, the values are rendered
ngAfterViewInit() {
console.log('ngAfterViewInit');
}
ngAfterViewChecked() {
console.log('ngAfterContentChecked');
}
ngOnDestroy() {
console.log('ngOnDestroy');
}
}
<file_sep># folium is the library used for maps, it creates maps with js, css, html in the browser via Python
# pip install folium
import folium
# get help with
# dir(folium) to get list of all available objects; Map is the class that creates the map; Marker is used to add markers and popups
# help(folium.Map) tells you the parameters that the Map class takes, including which tiles (layers like terrain, streets) you want in it
# create a map object
map = folium.Map((14.6261887,-90.5626019), width="50%", height="50%", zoom_start=2, tiles="Mapbox Bright")
# add child objects to the map object with Marker:
# step 1, create a feature group where all the map features will be appended
fg = folium.FeatureGroup(name="map_features")
# step 2, create a feature and add it as child of the feature group
fg.add_child(folium.Marker(location=(44.97399,-93.2299172), popup="Born here!", icon=folium.Icon(color="green")))
fg.add_child(folium.Marker(location=(14.6357891,-90.5149832), popup="Grew up here!", icon=folium.Icon(color="blue")))
fg.add_child(folium.Marker(location=(35.6189578,-97.4742407), popup="Now live here!", icon=folium.Icon(color="red")))
# step 3, add the feature group to the Map object
map.add_child(fg)
# save the map object in a file, this will create it in the folder where this .py file resides
map.save("Map1.html")<file_sep>function orderSupplies(item) {
let warehouse;
const deliveryTime = Math.random() * 3000;
return new Promise((resolve,reject) => {
setTimeout(() => {
warehouse = {
paint: {
product: 'Neon green paint',
directions: () => {return 'mix it'}
},
brush: {
product: 'Horsehair brush',
directions: () => {return 'start painting!'}
},
tarp: {
product: 'Plastic tarp',
directions: () => {return 'cover the floor'}
}
};
console.log('item ready: ',item)
if (item in warehouse) {
resolve(warehouse[item]);
} else {
reject(new Error(`${item} is out of stock`));
};
}, deliveryTime);
});
};
function receivedItem(item) {
console.log(`Received the ${item.product}, time to ${item.directions()}`)
};
const tarp = orderSupplies('tarp');
const paint = orderSupplies('paint');
const brush = orderSupplies('brush');
const roller = orderSupplies('roller').catch((error) => {console.log(error.message)});
// tarp.then((item) => {
// receivedItem(item);
// return paint;
// })
// .then((item) => {
// receivedItem(item);
// return brush;
// })
// .then((item) => {
// receivedItem(item);
// return roller;
// })
// .then((item) => {
// receivedItem(item);
// });
Promise.all([tarp,paint,brush,roller]).then((items) => {
items.forEach(receivedItem);
});
<file_sep>"use strict";
const performance = require("perf_hooks").performance;
// given two positive integers, find out if they have the same frequency of digits
const n1 = 2812;
const n2 = 1821;
function sameFrequency(n1, n2) {
let a1 = n1.toString().split("");
let a2 = n2.toString().split("");
if (a1.length !== a2.length) {
return false;
}
let obj1 = {};
for (let n of a1) {
obj1[n] = (obj1[n] || 0) + 1;
}
for (let m of a2) {
if (obj1[m]) {
obj1[m]--;
} else {
return false;
}
}
return true;
}
const t1 = performance.now();
const res = sameFrequency(n1, n2);
const t2 = performance.now();
console.log(res);
console.log(`Time elapsed: ${(t2 - t1) / 1000} seconds`);
// another solution -- bit slower
function sameFreq(n1, n2) {
let a1 = n1.toString();
let a2 = n2.toString();
if (a1.length !== a2.length) return false;
let obj1 = {};
let obj2 = {};
for (let i = 0; i < a1.length; i++) {
obj1[a1[i]] = (obj1[a1[i]] || 0) + 1;
}
for (let j = 0; j < a2.length; j++) {
obj2[a2[j]] = (obj2[a2[j]] || 0) + 1;
}
for (let key in obj1) {
if (obj1[key] !== obj2[key]) return false;
}
return true;
}
const t3 = performance.now();
const result = sameFreq(n1, n2);
const t4 = performance.now();
console.log(result);
console.log(`Time elapsed: ${(t4 - t3) / 1000} seconds`);
<file_sep>const performance = require('perf_hooks').performance;
function addUpTo(n) {
total = 0;
for (let i = 0; i <= n; i++) {
total += i;
}
return total;
}
let t1 = performance.now();
tot = addUpTo(100);
let t2 = performance.now();
console.log(tot);
console.log(`Time elapsed: ${(t2 - t1)/1000} seconds`);<file_sep>function map(array, callback) {
const newArray = [];
for (let index = 0; index < array.length; index++) {
const element = callback(array[index], index, array);
newArray.push(element)
}
return newArray;
}
function filter(array, callback) {
const filteredArray = [];
for (let index = 0; index < array.length; index++) {
if (callback(array[index], index, array)) {
const element = array[index];
filteredArray.push(element);
};
};
return filteredArray;
};
function reject(array, callback) {
const newArray = [];
for (let index = 0; index < array.length; index++) {
if (!(callback(array[index], index, array))) {
const element = array[index];
newArray.push(element);
};
};
return newArray
};
function find(array, callback) {
for ( let index = 0; index < array.length; index++ ) {
if (callback(array[index], index, array)) {
const element = array[index]
return (element);
};
};
};
function reduce(array, callback, memo) {
const results = [].concat(array);
if (memo === undefined) {
memo = results.pop();
};
for (let index = 0; index < array.length; index++) {
memo = callback(memo, array[index], index);
};
return memo;
};
array = [7,8,4,1,2,6]
const tryMap = map(array, function(element) {
const square = element * element;
return square
})
console.log(tryMap)
const tryReject = reject(array, function(element) {
const rejected = element % 2 === 0;
return rejected;
})
console.log(tryReject);
const tryFilter = filter(array, function(element) {
const remaining = element % 2 === 0;
return remaining;
})
console.log(tryFilter);
const tryFind = filter(array, function(element) {
const found = element > 5;
return found;
})
console.log(tryFind);
const tryReduce = reduce(array, function(num1, num2){
const accum = num1 + num2;
return accum
})
console.log(tryReduce)<file_sep>const http = require('http');
const routes = require('./routes');
// this creates the event listener that spins the server:
const server = http.createServer(routes.handler);
// server starts listening for requests:
server.listen(3000);
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from .models import User, Career
# Create your views here.
users = []
def index(request):
#SELECT * FROM User;
print User.objects.all(), "is all our users"
context = {
'users' : User.objects.all()
}
return render(request, "login_reg/index.html", context)
def show(request, id):
context = {
'user' : None
}
for user in users:
if str(user['id']) == id:
context['user'] = user
return render(request, "login_reg/user.html", context)
def new(request):
if request.method == 'POST':
print request.POST
new_user = User.objects.create(
first_name = request.POST['fname'],
last_name = request.POST['lname'],
date_of_birth = request.POST['dob']
)
print new_user
print new_user.first_name
return redirect('/login_reg')
def grad(request):
if request.method == 'POST':
print request.POST
new_grad = Career.objects.create(
title = request.POST['title'],
year_graduation = request.POST['gyear']
)
print new_grad
print new_grad.title
return redirect('/login_reg')
#code below not used because models is used:
# if users in request.session:
# user_list = request.session['users']
# new_user = {
# 'first_name' : request.POST['fname'],
# 'last_name' : request.POST['lname'],
# 'email' : request.POST['email']
# }
# user_list.append(new_user)
# request.session['users'] = user_list
# else:
# request.session['users'] = [{
# 'first_name' : request.POST['fname'],
# 'last_name' : request.POST['lname'],
# 'email' : request.POST['email']
# }]
# return redirect('hello:index')
def clear(request):
for key in request.session.keys():
del request.session[key]
# request.session.clear()
return redirect('login_reg:index')<file_sep>const express = require('express');
const body_parser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8000;
const app = express();
require('./server/config/database');
app
.use(body_parser.urlencoded({extended: true}))
.use(body_parser.json())
// angular replaces static
// to find out where angular will build components, go to
// angular.json and look for "outputPath":
// change whatever name it has now to 'dist/public'
// .use(express.static(path.resolve('dist/public')))
.use(express.static(path.join(__dirname, 'dist/public')))
// angular built package.json
// go there to add the entry point to our application if not yet there
// add or look for:
// "main": "server.js",
// with that done, you can launch it with nodemon
// package.json also contains the command line dict under "scripts"
// helpful if you don't remember, example, ng build
// ng build will create the "dist" file with the output of the project, "public"
// run ng build --watch
// to build "public" and watch for changes so it updates automatically
// ngbuild content is not permanent so don't do permanent mods here.
// do modifications on the "src"
app.use(require('./server/config/routes'));
app
.listen(port, () => console.log(`Express server listening on port ${port}`));
<file_sep>from random import choice
questions = ["Why is the sky blue? ", "Why are trees tall? ", "Where are the dinosaurs? "]
question = choice(questions)
answer = input(question).strip().lower()
end = "just because"
while answer != end:
answer = input("But why? ").strip().lower()
print("Oh... okay")
<file_sep>class Product(object):
def __init__(self, price, item_name, weight, brand):
self.price = price
self.item_name = item_name
self.brand = brand
self.weight = weight
self.status = "for sale"
def sell(self):
self.status = "sold"
return self
def addTax(self):
self.price = self.price * 1.085
return self
def item_return(self, return_state):
if return_state == "defective":
self.status = "defective"
self.price = 0
if return_state == "like new":
self.status = "for sale"
if return_state == "opened":
self.status = "used"
self.price = self.price * 0.8
else:
print "please try again! specify status as either 'defective', 'like new' or 'opened'"
return self
def display_info(self):
print "Product name: {}, brand: {}, price: {}, weight: {}, status: {}".format(self.item_name, self.brand, self.price, self.weight, self.status)
return self
product1 = Product(10, "pants", "1pound", "china_gold")
product1.display_info().addTax().display_info().sell().display_info().item_return("closed").display_info()
<file_sep>import random
score = random.randint(60,100)
grade_grid = {}
for i in range (60,69):
grade_grid[i] = "D"
for i in range (70,79):
grade_grid[i] = "C"
for i in range (80,89):
grade_grid[i] = "B"
for i in range (90,100):
grade_grid[i] = "A"
def grade_gen(grade):
return grade_grid[grade]
print "Your score: {}".format(score)+"; your grade is {}".format(grade_gen(score)) <file_sep>function addToIndex(arr){
for(var i = 0; i < arr.length; i++){
if(i % 2 !== 0){
arr[i] = arr[i] + 1;
}
}
console.log(arr);
}
addToIndex([1,1,1,1,1,1,1,15,5,5,5,5]);<file_sep>import random
health = 50
difficulty = 1
boost = int(random.randint(25,50) / difficulty)
health = health + boost
print(health)
<file_sep>
# open file in read mode
file_object = open("fruits.txt", "r")
print(file_object)
text_var = file_object.read()
file_object.close()
print(text_var)
# splitlines() removes the split characters \n and creates list
text_var = text_var.splitlines()
print(text_var)
<file_sep>import { Component, OnInit, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
@Output() createdServer = new EventEmitter<{name: string, content: string}>();
@Output() createdBlueprint = new EventEmitter<{name: string, content: string}>();
constructor() { }
ngOnInit() {
}
onAddServer(name: HTMLInputElement, content: HTMLInputElement) {
console.log(name.value, content.value);
this.createdServer.emit({name: name.value, content: content.value});
}
onAddBlueprint(name: HTMLInputElement, content: HTMLInputElement) {
console.log(name.value, content.value);
this.createdBlueprint.emit({name: name.value, content: content.value});
}
}
<file_sep>// typically, putting the member functions on the prototype are the way to go
// however, these are all public and are mutable from the outside by doing obj.property = "some value"
// if you want private properties, need to add them to the body and make them reference the parameters passed through when the object was created -- with the aid of closure (remember?)
function Person(first_name, last_name) {
this.first_name = first_name;
this.last_name = last_name;
this.full_name = first_name + " " + last_name;
}
// notice? not using "this" to build the full_name
Person.prototype.full_name_prototype = function() {
return this.first_name + " " + this.last_name;
};
const bob = new Person("Bob", "Smith");
console.log(bob.full_name)
bob.first_name = "Sam"
console.log(bob.first_name, "we just changed Bob's name!");
console.log(bob.full_name, "no change on the full name method that benefits from closures!");
console.log(bob.full_name_prototype(), "changed!! because the prototypical method does not have access to the constructor parameters");
// see how the full name function at prototype level is subject to change, but the on in the body that references the original parameters preserves state thanks to closure!!!
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.models import User
# ^^ this is how we import the User model ^^
from django.contrib.auth import authenticate, login
# ^^ this is how we import the authentication methods
# One of the neat things is that user is usable as an element on the templates with request prefixing it.
# Create your views here.
def index(request):
users = User.objects.all()
return render(request, "usertest/index.html", {'users':users})
def login_request(request):
testuser=authenticate(username=request.POST['username'], password=request.POST['password'])
login(request,testuser)
print request.user.first_name
return redirect('/index')
def register(request):
User.objects.create_user(first_name=request.POST['first_name'], last_name=request.POST['last_name'], username=request.POST['username'], email=request.POST['email'], password=request.POST['<PASSWORD>'])
return redirect('/index')
<file_sep>correct_pw = "<PASSWORD>"
first_name = input("Please enter name: ")
last_name = input("Please enter last name: ")
password = input("Enter password: ")
while password != correct_pw:
password = input("Please try again: ")
message = "Hello %s %s, you are logged in!" % (first_name, last_name)
print(message)
<file_sep>interface Dude {
name: string;
age: number;
}
//class implements an interface
class Student implements Dude {
constructor(public name: string, public age: number) {
}
}
const student = new Student('Bob', 5);
console.log(student);
//class inheritance with a default value
class Senior extends Student {
constructor(name: string, age = 18) {
super(name, age);
}
}
const tammy = new Senior('Tammy');
console.log(tammy);
//class inheritance with a method and a defined return type: initially undefined (void) until parameters are passed through it
class Junior extends Student {
constructor(name: string, age = 15) {
super(name, age);
}
sayHello(name: string): void {
console.log(`Hello ${name}, from ${this.name}`);
}
}
const george = new Junior('Geo');
george.sayHello(tammy.name);
<file_sep>from flask import Flask, render_template, session, redirect, request
import random
app = Flask(__name__)
app.secret_key = "randnum"
@app.route('/', methods=['GET','POST'])
def generate():
session['num'] = random.randint(1,101)
number = session['num']
print "number is {}".format(number)
return redirect('/play')
@app.route('/play', methods=['GET','POST'])
def gameStart():
return render_template("game.html")
@app.route('/compare', methods=['POST'])
def compareNums():
guess = request.form['guess']
print "guess is {}".format(guess)
if session['num'] == int(guess):
return render_template("yay.html")
elif session['num'] > int(guess):
print "number is {} type is{}".format(session['num'],type(session['num']))
print "guess is {} type is{}".format(guess, type(guess))
return render_template("game.html", msg = "Too low")
elif session['num'] < int(guess):
print "number is {} type is{}".format(session['num'],type(session['num']))
print "guess is {} type is{}".format(guess, type(guess))
return render_template("game.html", msg = "Too high")
else:
print "number is {} type is{}".format(session['num'],type(session['num']))
print "guess is {} type is{}".format(guess, type(guess))
return render_template("game.html", msg = "Remember you have to guess a number from 1 to 100")
@app.route('/restart', methods=['POST'])
def gameStartOver():
session.clear()
return redirect('/')
app.run(debug=True)<file_sep>//simulated really slow DB call.
//**********EXECUTION JUMPS TO HERE***************
function getStuffFromDatabase(callback){
var data;
var myTimer = setTimeout(function(){
if (typeof(callback) == 'function'){
data = [{name:'Todd'},{name:'Michael'},{name:'Portia'}];
callback(data);
}
}, 5000);
return data;
}
// ************EXECUTION HERE**************
function requestDataFromDatabase(){
var data = getStuffFromDatabase(function (data){ // fetch the data with a function call that will provide it
console.log(data, "ASynchronous"); // data is the return from the called function
for (var i = 0; i < data.length; i ++){
console.log(data[i].name);
}
});
console.log(data, "Synchronous"); // but this data is the variable initialized in line 16, and is unavailable because of the delay
}
//**************EXECUTION ENDS HERE*****************
function catchFly(){
console.log('I just caught a fly!');
}
requestDataFromDatabase();
// keep running my program!
console.log('Hello');
catchFly();
//etc.
<file_sep>// stacks
// available methods:
// .pop()
// .push()
// .peek()
// .length()
// example
let letters = []; // this is our stack
const word = "racecar"
let rword = ""
// put letters of word in stack
for (let i = 0; i < word.length; i++) {
letters.push(word[i]);
}
// extract letters from stack in reverse order
for (let i = 0; i < letters.length; i++) {
rword += letters.pop();
}
if (word === rword) {
console.log(word + " is a palindrome")
} else {
console.log(word + " is not a palindrome")
}
// example 2
const Stack = function() {
this.count = 0;
this.storage = {};
// adds a value onto the end of the stack
this.push = function(value) {
this.storage[this.count] = value;
this.count++;
}
// removes and returns the value at the end of the stack
this.pop = function() {
if(this.count === 0) {
return undefined;
}
this.count--;
var result = this.storage[this.count];
delete this.storage[this.count];
return result
}
this.size = function() {
return this.count;
}
// return the value at the end of the stack
this.peek = function() {
return this.storage[this.count - 1];
}
}
const myStack = new Stack();
myStack.push(1);
myStack.push(2);
console.log(myStack.peek());
console.log(myStack.pop());
console.log(myStack.peek());
myStack.push("coding");
console.log(myStack.size());
console.log(myStack.peek());
console.log(myStack.pop());
console.log(myStack.peek());
<file_sep>{% extends './layout.html' %}
{% block title %}Book Page{% endblock %}
{% block body %}
<div class="container">
<div class="row">
<div class="col">
<h5>"Hello, {{ request.session.user }}"</h5>
</div>
<div class="col d-flex justify-content-end">
<a href="{% url 'add' %}">Write a review</a>
<a href="/logout">Logout</a>
</div>
</div>
<div class="row">
<div class="col">
<h2>Recent Book Reviews:</h2>
<!-- make a list of three latest book reviews sorted in reverse chornological order -->
<!-- For each display: -->
<!-- Title -->
<!-- Star rating as stars -->
<!-- Reviewer's name as a link to the reviewer's page -->
<!-- The content of the review itself -->
<!-- Created at date only -->
<ul class="list-group">
{% for review in latest %}
<li class="list-group-item review">
<a href="/books/{{ review.book.id }}"><p class="font-weight-bold">{{ review.book.title }}</p></a>
<p class="font-italic">{{ review.content }}</p>
<div class="d-flex align-items-center">
<a href="/users/{{ review.user.id }}"><p>{{ review.user.first_name }} {{ review.user.last_name }}</p></a>
<p> - {{ review.created_at|date }}</p>
</div>
</li>
{% endfor %}
</ul>
</div><!-- end of recent book reviews section -->
<div class="col">
<h2>Other Books Reviews:</h2>
<!-- make a scrolling textarea with links to other reviews -->
<!-- this is a list of book titles, each displaying as a link to the book page -->
<div class ="other_reviews border rounded h-50">
{% for review in other %}
<a href="/books/{{ review.book.id }}"><p class="font-weight-bold">{{ review.book.title }}</p></a>
{% endfor %}
</div>
</div><!-- end of list of other book reviews -->
</div>
</div>
{% endblock %}
<file_sep>//Longest word: return the longest word from a string
function LongestWord(e){
var count = 0;
var max = 0;
var ref = "";
for (var i = 0; i < e.length; i++){
console.log(e.charCodeAt(i));
if (e.charCodeAt(i) >= 65 && e.charCodeAt(i) <= 122){
count++;
if (count > max){
max = count;
ref = i;
}
}
else{
count = 0;
}
document.getElementById('result1').innerHTML = max;
document.getElementById('result2').innerHTML = ref;
}
}
LongestWord("ain't chimera a real word?");
//Return the first factorial of a given number
function firstFactorial(e){
var arr = [];
for (var i = 1; i <= e; i++){
arr.push(i);
}
document.getElementById('result1').innerHTML = arr;
function multiplication(){
var arrIn = arr;
var multip = 1;
for (j = 0; j < arrIn.length; j++){
multip = multip * arr[j];
}
document.getElementById('result2').innerHTML = multip;
}
multiplication();
}
//firstFactorial(8);
<file_sep>const user_controller = require('../controllers/users');
//doing restful routing, with root route redirecting to '/users', which is the main page in a restful structure
module.exports = function(app) {
app.get('/', (request,response) => response.redirect('/users'));
app.get('/users', user_controller.index);
app.get('/users/new', user_controller.new);
app.get('/users/:id', user_controller.show);
app.post('/users', user_controller.create);
app.get('/users/:id/edit', user_controller.edit);
app.post('/users/:id', user_controller.update);
app.post('/users/:id/delete', user_controller.destroy);
//task is to send the login model into its own models/login.js file, export it there and require it here
app.post('/login', (request,response) => {
User.findOne({email: request.body.email})
.then(userInfo => {
if (!userInfo) {
throw new Error();
}
return User.validatePassword(request.body.password, userInfo.password)
.then(() => {
//add session id
})
})
.catch(error => {
//re-render the form so user does not need to re-enter all the information. If doing re-direct, they would have to type everything again
response.render('/', {error: 'Email and password combination does not exist'})
});
});
//logout:
//do the routing as with previous examples above
app.post('/logout', (request,response) => {
});
};<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def index(request):
message = "Look at all the food!"
if 'foods' not in request.session:
message = "Add some food!"
context = {
'message' : message
}
return render(request, "food_list/index.html", context)
def process(request):
# print request.POST
new_food = {
'type' : request.POST['type'],
'name' : request.POST['name']
}
try:
request.session['foods']
except KeyError:
request.session['foods'] = []
food_list = request.session['foods'] #because one cannot append to a list if it's a key in session, the trick is to bypass with a variable
food_list.append(new_food) #append the new entry to the variable
request.session['foods'] = food_list #updated list is then assigned back to the session key
return redirect('/food_list')
def clear(request):
for key in request.session.keys():
del request.session[key]
return redirect('/food_list')
<file_sep>import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appUnlessStructural]'
})
export class UnlessStructuralDirective {
// set converts the property into a method that observe for changes whenever the property changes.
// it changes whenever a parameter of this condition changes, so it needs to receive a value. in this case, condition.
@Input() set appUnlessStructural(condition: boolean) {
if (!condition) {
this.vcRef.createEmbeddedView(this.templateRef);
} else {
this.vcRef.clear();
}
}
// needs us to inject the tempate (what to display --what is refered to as ng-template when explicitly written in the html)
// and the view (where to render --Angular marks this place)
constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) { }
}
<file_sep>def bubble(arr):
for i in range(0,len(arr)):
for j in range(0,len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print arr
bubble([6,5,4,3,2,1])
<file_sep>// spread opearator
const children = {
first: 'Helen',
second: 'Mikel'
};
console.log(children);
const family = {
...children,
spouse: 'Johi',
};
console.log(family);
// updating parameter values
const meal = {
id: 1,
descr: 'breakfast',
};
const updatedMeal = {
...meal,
descr: 'brunch',
cal: 600,
};
console.log('meal ' + Object.entries(meal), 'updated ' + Object.entries(updatedMeal));
// destructuring
const { id, descr, cal } = updatedMeal;
console.log(id, descr, cal);
const { spouse, ...kids } = family;
console.log(spouse);
console.log(kids);
console.log(spouse, kids);
// exercise
const food = {
description: 'dinner'
};
const foodInfo = {
...food,
calories: 200
};
console.log(foodInfo);
const foodUpdate = {
...foodInfo,
calories: foodInfo.calories + 100
}
console.log(foodUpdate);
const { description, calories } = foodUpdate;
console.log(description);<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { BasicHighlightDirective } from './directives/basic-highlight.directive';
import { BetterHighlightDirective } from './directives/better-highlight.directive';
import { HostListenerHighlightDirective } from './directives/host-listener-highlight.directive';
import { HostBindingHighlightDirective } from './directives/host-binding-highlight.directive';
import { CustomHighlightDirective } from './directives/custom-highlight.directive';
import { CustomHighlightWithInitDirective } from './directives/custom-highlight-with-init.directive';
import { CustomHighlightWithInitAlternativeDirective } from './directives/custom-highlight-with-init-alternative.directive';
import { FadoutDirective } from './directives/fadout.directive';
import { UnlessStructuralDirective } from './unless-structural.directive';
@NgModule({
declarations: [
AppComponent,
BasicHighlightDirective,
BetterHighlightDirective,
HostListenerHighlightDirective,
HostBindingHighlightDirective,
CustomHighlightDirective,
CustomHighlightWithInitDirective,
CustomHighlightWithInitAlternativeDirective,
FadoutDirective,
UnlessStructuralDirective
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>const {Circle, Square} = require("./module");
const c = new Circle(3);
const s = new Square(10);
c.draw();
s.draw()<file_sep>// destructuring creates local variables out of object properties
// in objects, elements are pulled out by name
const person = {
name: 'Bob',
age: 87,
hobbies: ['fishing', 'barbecue', 'huntn'],
greet() {
console.log('I am ', this.name);
}
}
const printName = ({name}) => console.log(name);
printName(person);
const {name, age} = person;
console.log(name, age);
// array destructuring:
// in arrays, elements are pulled out by position
const [hobby1, hobby2, hobby3] = person.hobbies;
console.log(hobby2);
const [hobby, ...rest] = person.hobbies;
console.log(hobby);
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
#Our new manager! this is useful for validations
#No methods in our new manager should ever catch the whole request object with a parameter!!! (just parts, like request.POST)
#this means, don't simply use request, better to narrow it down with request.POST
class BlogManager(models.Manager):
def basic_validator(self, postData):
errors = {}
if len(postData['name']) < 5:
errors["name"] = "Blog name should be more than 5 characters"
if len(postData['desc']) < 10:
errors["desc"] = "Blog desc should be more than 10 characters"
return errors
class Blog(models.Model):
name = models.CharField(max_length=255)
desc = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
# *************************
# Connect an instance of BlogManager to our Blog model overwriting
# the old hidden objects key with a new one with extra properties!!!
objects = BlogManager()
# *************************<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages
from time import gmtime, strftime
from django.utils.crypto import get_random_string
from .models import Blog
def index(request):
return render(request, 'blogs/index.html', { "blogs": Blog.objects.all() })
def new(request):
return render(request, 'blogs/new.html')
def show(request, id):
return render(request, 'blogs/show.html', { "blog": Blog.objects.get(id = id) })
def update(request, id):
if len(errors):
for tag, error in errors.iteritems():
messages.error(request, error, extra_tags = tag)
return redirect('blogs/edit/'+id)
else:
blog = Blog.objects.get(id = id)
blog.name = request.POST['name']
blog.desc = request.POST['desc']
blog.save()
return redirect('/blogs')
# return redirect('../show/'+id)
def create(request):
if request.method == "POST":
print "*"*50
print request.POST
print request.POST['name']
print request.POST['desc']
request.session['name'] = "test"
print "*"*50
return redirect("/blogs")
else:
return redirect("/blogs")
def blog(request, blog):
return HttpResponse("placeholder to display blog number " + blog)
def destroy(request, blog):
return redirect('/blogs')<file_sep>// binary search tree
// a data structure that holds data and when you visualize it, it looks like a tree, with branches and branches and subbranches
// all data points are called nodes
// main node is the root
// node relationships can be parent, child, sibling
// leaf nodes are at the end of branches and have no children
// any children of a node are parents of their own sub-tree
// a binary tree is a type of tree that has only two branches per node
// binary trees are ordered. each subtree is less than or equal to the parent node, and each right subtree is greater than or equal to the parent node
// on average, search operations are able to skip about half of the tree, so each lookup, insertion or deletion takes time proportional to the log of the number items stored in the tree.
// this is much better than the linear time it takes to find items by key in an unsorted array
// still, it is slower than operations done in a hash table
// we'll create classes to construct a binary search tree
// node class represents each node in the tree
class Node {
constructor(data, left = null, right = null) {
this.data = data;
this.left = left;
this.right = right;
}
}
// BST === binary search tree, and has 3 data properties
class BST {
constructor() {
this.root = null;
}
add(data) {
// if there was no data, root would be null, so we populate with first data point
const node = this.root;
if (node === null) {
this.root = new Node(data);
return;
} else {
// we place the data using a recursive function to build the tree
const searchTree = function(node) {
if (data < node.data) {
if (node.left === null) {
node.left = new Node(data);
return;
} else if (node.left !== null) {
return searchTree(node.left);
}
} else if (data > node.data) {
if (node.right === null) {
node.right = new Node(data);
return;
} else if (node.right !== null) {
return searchTree(node.right);
}
} else {
return null;
}
};
// we hereby call the recursive function written above
return searchTree(node);
}
}
findMin() {
let current = this.root;
while (current.left !== null) {
current = current.left;
}
return current.data;
}
findMax() {
let current = this.root;
while (current.right !== null) {
current = current.right;
}
return current.data;
}
find(data) {
let current = this.root;
while (current.data !== data) {
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
if (current === null) {
return null;
}
}
return current;
}
isPresent(data) {
let current = this.root;
while(current) {
if (data === current.data) {
return true;
}
if (data < current.data) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
// remove is also a recursive function; we call the function at the end, you'll see
remove(data) {
const removeNode = function(node, data) {
if (node == null) {
return null;
}
if (data == node.data) {
// node has no children
if (node.left == null && node.right == null) {
return null;
}
// node has no left child
if (node.left == null) {
return node.right;
}
// node has no right child
if (node.right == null) {
return node.left;
}
// node has two children
let tempNode = node.right;
while (tempNode.left != null) {
tempNode = tempNode.left;
}
node.data = tempNode.data;
node.right = removeNode(node.right, tempNode.data);
return node;
} else if (data < node.data) {
node.left = removeNode(node.left, data);
return node;
} else {
node.right = removeNode(node.right, data);
return node;
}
}
this.root = removeNode(this.root, data);
}
}
const bst = new BST();
bst.add(4)
bst.add(2)
bst.add(6)
bst.add(1)
bst.add(3)
bst.add(5)
bst.add(7)
bst.remove(4)
console.log(bst.findMin());
console.log(bst.findMax());
bst.remove(7)
console.log(bst.findMax());
console.log(bst.isPresent(4));
<file_sep>from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def got_to_index():
return render_template('index.html')
@app.route('/ninjas')
def call_ninjas():
return render_template('ninjas.html')
@app.route('/dojos')
def dojo_enroll():
return render_template('dojos.html')
@app.route('/new', methods=['POST'])
def new_ninja():
name=request.form['name']
email=request.form['email']
return render_template("success.html")
app.run(debug=True)
<file_sep>class Animal(object):
def __init__(self, name):
self.name = name
self.health = 100
def walk(self):
self.health -= 1
return self
def run(self):
self.health -= 5
return self
def displayHealth(self):
print self.health
return self
#animal1 = Animal("Boon")
#animal1.walk().walk().walk().run().run().displayHealth()
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-08-17 16:13
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviews', '0002_auto_20180816_1922'),
]
operations = [
migrations.AlterField(
model_name='author',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 264000)),
),
migrations.AlterField(
model_name='author',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 264000)),
),
migrations.AlterField(
model_name='book',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 265000)),
),
migrations.AlterField(
model_name='book',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 265000)),
),
migrations.AlterField(
model_name='review',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 265000)),
),
migrations.AlterField(
model_name='review',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 265000)),
),
migrations.AlterField(
model_name='user',
name='created_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 248000)),
),
migrations.AlterField(
model_name='user',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2018, 8, 17, 11, 13, 26, 248000)),
),
]
<file_sep>from flask import Flask, render_template, redirect, request, session, flash
#re module let's us do expression operations
import re
#this object we are creating will check if email address has email syntax
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = "safeKeeping"
@app.route('/')
def index():
return render_template("index.html")
#flash messages exist for one redirect cycle. Similar to session, they can be accessed through embedded python tags {{}} & {%%}
@app.route("/name", methods=["POST"])
def name():
if len(request.form["name"]) < 1:
flash("Name cannot be empty!")
else:
flash("Success! your name is {}".format(request.form['name']))
return redirect("/")
#.match method returns None of there is no match
@app.route("/email", methods=["POST"])
def email():
if len(request.form["email"]) < 5:
flash("Email cannot be empty!")
elif not EMAIL_REGEX.match(request.form['email']):
flash("Invalid email address!")
else:
flash("Success! Your email is {}".format(request.form['email']))
return redirect("/")
app.run(debug=True)
#other validation methods --search python docs for details--:
#str.alpha() - returns boolean after checking if string is all alphabetic
#time.strptime(string,[format]) - within the time module (--import time--) changes a string to a time using the given format <file_sep>function Shape(color) {
this.color = color;
}
Shape.prototype.duplicate = function() {
console.log("duplicate");
};
function Circle(radius, color) {
Shape.call(this, color); // super constructor
this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.draw = function() {
console.log("draw");
};
// because Shape has a property (color) and we need to point "this" of such property to Circle instances, we use the super constructor
const c1 = new Circle(1, "red");
console.log(c1) // circle now has color<file_sep>// classical vs prototypical inheritance
// classical creates instances of a template, used in older languages --> build a house from an architectural diagram
// prototypical inheritance copies another object --> building a house from another house
// JS uses prototypical inheritance.
// if it is said there is JS classical inheritance, it is because on code it looks like it, but it really is prototypical
// so, in JS there is:
// 1. pseudo-classical pattern (code looks classical)
// 2. prototypal pattern
<file_sep>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// register the bodyParser middleware through which requests pass. Before calling next, this parses the request's body sent through forms
// with this middleware we're able to get key:value pairs with req.body
app.use(bodyParser.urlencoded({extended: false}));
// we route requests to different middleware with the use of paths
// path is the first parameter taken by app.use()
// the second parameter is the middleware
// for more info about app.use, check the expressjs.com api
// file is read top to bottom and looks for path matches.
// so we reserve the '/' root route for the bottom...
// note we don't use next(); so that we don't send two responses by sending request to the next middleware
// but if we do use next();, we'll be able to channel requests through middleware that always runs:
app.get('/new', (req, res, next) => {
console.log('In the new middleware!');
res.send('<form action="/create" method="POST"><input type="text" name="username"><button type="submit">Submit</button></form>');
});
// by substituting app.get for app.post, this route will only listen for post requests
// do this when you want to filter request types because app.use accepts all kinds of request methods
// see how above the app.get has been used
// available filters are .get, .post, .delete, .put, .patch
app.post('/create', (req, res, next) => {
console.log('in the create middleware');
const data = req.body;
console.log(req.body);
res.redirect('/');
});
// use is a general route that will not do full matching. If we change this to app.get, it will do exact matching of the url, and this improves router behavior
app.use('/', (req, res, next) => {
console.log('In the root middleware!');
res.send('<h1>Hello from Express!</h1>');
});
app.listen(3000);<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
import bcrypt
from django.contrib import messages
from .models import *
# Registration:
# make dict with request.POST data and save it to database
# validate that:
# name is longer than 2
# last name is longer than 1
# email conforms with regex
# username is no less than 8 characters
# password is no less than 8 characters
# flash list of error messages, if any
# email and username do not exist in database
# flash message if they do
# hash password with bcrypt
# Login
# look up username in database
# if user does not exist, flash message
# if user exists,
# get the password and compare with the one on database
# if not the same, flash message to reenter information
# if the same, redirect to welcome page
def index(request):
return render(request, 'login_reg/index.html')
def register(request):
if request.method != 'POST':
return redirect('/')
else:
context = {
'first_name':request.POST['first_name'],
'last_name':request.POST['last_name'],
'email':request.POST['email'],
'username':request.POST['username'],
'password':request.POST['<PASSWORD>'],
'confirm_password':request.POST['confirm_password']
}
result = User.objects.RegistrationValidator(context)
for message in result[1]:
if result[0] == True:
messages.success(request, message)
else:
messages.error(request, message)
return redirect('/')
def login(request):
if request.method != 'POST':
return redirect('/')
username = request.POST['username']
password = request.POST['password']
result = User.objects.LoginValidator(username, password)
if result[0]:
request.session['logged_user'] = result[1]
request.session['user'] = User.objects.get(id=request.session['logged_user']).first_name
return redirect('/dashboard')
else:
for message in result[1]:
messages.error(request, message)
return redirect('/')
return redirect("/")
def logout(request):
for key in request.session.keys():
del request.session[key]
return redirect('/')
def dashboard(request):
context = {
'logged_user':request.session['logged_user']
}
return render(request,"login_reg/dashboard.html",context)
# hash1 = bcrypt.hashpw('test'.encode(), bcrypt.gensalt())
# bcrypt.checkpw('test'.encode(), hash1.encode())<file_sep>class MathDojo(object):
def __init__(self):
self.output = 0
def show_list(self):
print self.__dict__
print len(self.list)
def add(self, *numbers):
self.list = list(numbers)
for i in range(len(self.list)):
self.output += self.list[i]
return self
def subtract(self, *numbers):
self.list = list(numbers)
for i in range(len(self.list)):
self.output -= self.list[i]
return self
def result(self):
print self.output
return self
md = MathDojo()
md.add(2).add(2,5).subtract(3,2).result()
<file_sep>// hide the details and complexity and show only the essencials
function Circle(radius) {
this.radius = radius;
// a private property
let location = {
x: 2,
y: 3
};
this.draw = function() {
console.log("draw");
};
// a private method
let compute = function() {
return location.x * location.y;
};
// a getter
this.computation = function() {
return compute();
};
// a better getter and setter, takes 3 parameters:
// (context, name of setter/getter, function object)
Object.defineProperty(this, "rad", {
get: function() {
return radius;
},
set: function(r) {
if (typeof r !== 'number') {
throw new Error("please enter a number");
}
radius = r;
}
});
}
const circle1 = new Circle(1);
const compu = circle1.computation();
console.log(compu);
const see = circle1.rad;
console.log(see);
circle1.rad = 3;
console.log(circle1.rad);<file_sep>const express = require('express');
const body_parser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 8000;
const app = express();
app.use(body_parser.urlencoded({extended:true}));
app.use(body_parser.json());
app.use(express.static(path.join(__dirname, 'static')));
app.set('views', path.resolve('views'));
app.set('view engine', 'ejs');
require('./server/config/database');
app.use(require('./server/config/routes'));
app.listen(port, () => console.log(`express listening on port ${port}`));
<file_sep>table = [1,2,3,4,5,6,7,8,9,10,11,12]
x = 2
def multiply(x):
return x * i
for i, num in enumerate(table,1):
print map(multiply, table)
<file_sep>// ES6 makes available a wrapper called classes that provides some synthatic sugar to work with constructor functions
// when creating objects using the 'class' keyword, we define a method called 'constructor'. All ES6 classes have a constructor, and the constructor always runs whenever we create a new class
class Dot {
constructor(x,y) {
this.x = x;
this.y = y;
console.log("a dot has been created");
};
};
const dot1 = new Dot(6,9);
// notable things:
// 1. the console.log fires without need to call the dot instance. it fires upon creation
// 2. classes are NOT hoisted, they will remain the the same place they were initialized and won't move during interpretation
// the ES5 way:
function Dotty(x,y) {
this.x = x;
this.y = y;
};
Dotty.prototype.showLocation = function(){
console.log("This dot is at coordinates (x: "+this.x+", y: "+this.y+")");
};
var dot2 = new Dotty(7,8);
dot2.showLocation();
// the ES6 way:
class Dotto {
constructor(x,y) {
this.x = x;
this.y = y;
};
showLoco() {
console.log(`This dot is at coordinates (x: ${this.x}, y: ${this.y})`)
};
static getHelp() {
console.log(`This is a Dot class to create dots. A Dot takes x and y coordinates, type "new dot" to create one!`);
};
};
var dot3 = new Dotto(9,10);
dot3.showLoco();
// NOTICE THE STRING INTERPOLATION DONE INSIDE BACKTICKS
// NO FUNCTION WORD BEFORE THE METHOD'S NAME
// THE METHOD IS NO LONGER APPENDED BY WAY OF PROTOTYPE. INSTEAD IT IS WRITTEN INSIDE THE CONSTRUCTOR BUT BEHAVES THE SAME WAY
console.log(dot1);
console.log(dot2);
console.log(dot3);
// notice that the methods continue to be a class level thing and are not logged as methods of the instance!
Dotto.getHelp();
// dot3.getHelp();
// because getHelp has been tagged as a static method, it is not accessible from the instances, only from the Class directly<file_sep>const R = require('ramda');
const color = require('colors');
const sentence = 'PechaKucha is a presentation style in which 20 slides are shown for 20 seconds each (6 minutes and 40 seconds in total).';
const digits = R.split('', sentence);
const numbersInString = R.pipe(
R.split(''),
R.map(parseInt),
R.filter(Number.isInteger),
R.length,
);
console.log(numbersInString(sentence));
// using R.pipe to combine methods from left to right
// using split to split the sentence into characters and make an array
// using map to apply a function to each character. In this case, parseInt to convert to number all those characters that are numbers
// using filter to leave only numbers in the array
// using length to count the number of characters in the array
<file_sep># lambdas are lightweight functions that do very specific operations; they are defined without a name and require no return statement.
# syntax
# lambda arguments: expression
# examples:
double = lambda x: x * 2
square = lambda x: x ** 2
print double(5)
print square(5)
# using lambda: when we require a nameless function for a short period of time, example, inside another function
# example:
# filter all the even numbers from a list:
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0), my_list))
print new_list
# lambdas are purely statements, they can be among other elements in a list:
function_list = [lambda x: x ** 0.5, lambda x: x ** 2, lambda x: x ** 3]
print function_list[0](5)
print function_list[1](5)
print function_list[2](5)
# here we pass 5 through the different elements of the list of functions
<file_sep>"use strict";
// divide and conquer is a pattern that is used to diminish time complexity by dividing an array into pieces
// the array has to be sorted
// return the index of found item
let array = [1, 2, 3, 4, 5, 6];
let find = 2;
function binarySearch(arr, ele) {
let min = 0;
let max = arr.length - 1;
while (min <= max) {
let mid = Math.floor((max + min) / 2);
if (arr[mid] < ele) {
min = mid + 1;
} else if (arr[mid] > ele) {
max = mid - 1;
} else {
return mid;
}
}
return -1;
}
let result = binarySearch(array, find);
console.log(result);
<file_sep>from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import MySQLConnector
import md5
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
app = Flask(__name__)
app.secret_key = "regisvalid1234"
mysql = MySQLConnector(app,'message_wall_assignment')
@app.route('/')
def index():
if "user_id" in session:
return redirect('/welcome')
else:
return render_template("index.html")
#REGISTRATION
@app.route('/register', methods=['POST'])
def register():
#receive data
#validate data
valid = True
#if not valid
#flash error message and redirect to index
if len(request.form['fname']) < 1:
valid = False
flash("Please enter a full first name")
if len(request.form['lname']) < 1:
valid = False
flash("Please enter a full last name")
if len(request.form['email']) < 5:
valid = False
flash("Please enter a full email")
if not EMAIL_REGEX.match(request.form['email']):
valid = False
flash("Invalid email address!")
if len(request.form['pword']) < 8:
valid = False
flash("Please make password at least 8 characters long")
if valid != True:
return redirect ('/')
#if valid
#create query
query = "INSERT INTO `users` (`first_name`, `last_name`, `email`, `password`, `created_at`, `updated_at`) VALUES (:fname, :lname, :email, :pword, now(), now());"
#build dictionary with form data
data = {
'fname':request.form['fname'],
'lname':request.form['lname'],
'email':request.form['email'],
'pword':md5.new(request.form['pword']).hexdigest()
}
#store it to db
mysql.query_db(query,data)
#flash success message
flash("Successfully registered!")
return redirect('/')
#LOGIN
@app.route('/login', methods=['POST'])
def login():
#receive data
#validate data
valid = True
#if not valid
#flash error message and redirect to index
if len(request.form['email']) < 5:
valid = False
flash("Please enter a full email")
if not EMAIL_REGEX.match(request.form['email']):
valid = False
flash("Invalid email address!")
if len(request.form['pword']) < 8:
valid = False
flash("Please make password at least 8 characters long")
if valid != True:
return redirect ('/')
#valid
else:
#create query
query = "SELECT * FROM users WHERE email = :email"
#build dictionary
data = {
'email':request.form['email']
}
#get user information from database
users = mysql.query_db(query,data)
#validate credentials
#if user exists, db will return a dictionary with the information
if len(users) > 0:
user = users[0]
password = md5.new(request.form['pword']).hex<PASSWORD>()
#validate password by comparing with input with that in the db
if password == users[0]['password']:
session['user_id'] = user['id']
#flash("Succesful login, user id:{}".format(session['user_id']))
return redirect('/welcome')
else:
flash("Please check credentials")
#if user does not exist
else:
flash("Email does not exist")
return redirect('/')
@app.route('/welcome')
def welcome():
query = "SELECT * FROM users WHERE id = :logged_id"
data = {
'logged_id':session['user_id']
}
session['logged_user'] = mysql.query_db(query,data)[0]['first_name']
message_query = "SELECT m.id AS message_id, m.message AS message, CONCAT_WS(' ',u.first_name, u.last_name) AS posted_by, u.id AS posted_by_id, DATE_FORMAT(m.updated_at, '%M %d %Y') AS message_date FROM messages m JOIN users u ON m.user_id = u.id ORDER BY m.updated_at;"
comment_query = "SELECT c.comment AS comment, CONCAT_WS(' ', cm.first_name, cm.last_name) as commentator, c.message_id AS commented_message, DATE_FORMAT(c.updated_at, '%M %d %Y') AS comment_date FROM comments c Left JOIN users cm ON c.user_id = cm.id ORDER BY c.message_id;"
messages = mysql.query_db(message_query)
comments = mysql.query_db(comment_query)
return render_template("wall.html", logged_user=session['logged_user'], all_messages=messages, all_comments=comments)
@app.route('/messages', methods=['POST'])
def post_message():
if "user_id" not in session:
return redirect('/')
query = "INSERT INTO `messages` (`message`, `user_id`, `created_at`, `updated_at`) VALUES (:message, :user, now(), now());"
data = {
'message':request.form['message'],
'user':session['user_id']
}
mysql.query_db(query,data)
return redirect('/welcome')
@app.route('/comment/<message_id>', methods=['POST'])
def post_comment(message_id):
if "user_id" not in session:
return redirect('/')
query = "INSERT INTO `comments` (`comment`, `user_id`, `message_id`, `created_at`, `updated_at`) VALUES (:comment, :user, :message, now(), now());"
data = {
'comment':request.form['comment'],
'user':session['user_id'],
'message':message_id
}
mysql.query_db(query,data)
return redirect('/welcome')
@app.route('/delete/<message_id>', methods=['POST'])
def delete_user(message_id):
query = "DELETE FROM messages WHERE id = :specified_id"
data = {
'specified_id':message_id
}
mysql.query_db(query,data)
return redirect('/welcome')
#LOGOUT
@app.route('/logout', methods=['POST'])
def logout():
session.clear()
return redirect('/')
app.run(debug=True)<file_sep>function weightedRandom(){
var weights = [0.1, 0.15, 0.2, 0.25, 0.3];
var list = ['volcano', 'tsunami', 'earthquake', 'blizzard', 'meteor'];
var max = 0;
var count = 0;
for(var i = 0; i < weights.length; i++){
if(weights[i] > max){
max = weights[i];
count++;
}
}
console.log(list[count-1]);
}
weightedRandom();<file_sep>import { Directive, Renderer2, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListenerHighlight]'
})
export class HostListenerHighlightDirective {
constructor(private elRef: ElementRef, private renderer: Renderer2) {
}
// as a parameter we pass the event we are listening for, one of the events supported by the DOM; *can also be custom events
// we bind HostListener to a method we want to execute
// mouseenter is the methods we want to execute
// that takes the event which we have referenced in the HostListener paramater. This event can be captured by a custom event as $event
@HostListener('mouseenter') mouseenter(eventData: Event) {
this.renderer.setStyle(this.elRef.nativeElement, 'background-color', '#CDCED0');
}
@HostListener('mouseleave') mouseleave(eventData: Event) {
this.renderer.setStyle(this.elRef.nativeElement, 'background-color', 'transparent');
}
}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
import bcrypt
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your models here.
class UserManager(models.Manager):
def RegistrationValidator(self, context):
errors = []
#validate if there are blank fields
if context['first_name'] == "":
errors.append("Please enter a first name")
if context['last_name'] == "":
errors.append("Please enter a last name")
if context['email'] == "":
errors.append("Please enter an email")
if context['username'] == "":
errors.append("Please enter a username")
if context['password'] == "":
errors.append("Please enter a password")
if len(errors) != 0:
return (False, errors)
else:
#more validations start
#validate if passwords match
if context['password'] != context['confirm_password']:
errors.append("Passwords don't match")
if len(errors) != 0:
return (False, errors)
else:
#validate email format:
if not EMAIL_REGEX.match(context['email']):
errors.append("Please use a valid email address")
#validate lengths of username and password
if len(context['username']) < 8:
errors.append("Please enter a username, at least 8 characters expected")
if len(context['password']) < 8:
errors.append("Please enter a password, at least 8 characters expected")
#validate if email already exists
email_exists = self.filter(email=context['email'])
if len(email_exists) != 0:
errors.append("Email already exists")
#validate if username alreagy exists
username_exists = self.filter(username=context['username'])
if len(username_exists) != 0:
errors.append("Username already exists")
#more validations end
if len(errors) != 0:
return (False, errors)
else:
#send data to database
self.create(
first_name = context['first_name'],
last_name = context['last_name'],
email = context['email'],
username = context['username'],
password = <PASSWORD>.hashpw(context['password'].encode(), bcrypt.gensalt())
)
errors.append("User has been created")
return (True, errors)
def LoginValidator(self, username, password):
errors = []
if username == "":
errors.append("Please enter a username")
if password == "":
errors.append("Please enter a password")
if len(errors) != 0:
return (False, errors)
else:
logging_user = self.filter(username=username)
if len(logging_user) == 0:
errors.append("Username does not exist")
else:
user = logging_user[0]
user_password = <PASSWORD>
if bcrypt.checkpw(password.encode(), user_password.encode()):
return (True, user.id)
else:
errors.append("Password does not match")
return (False, errors)
class User(models.Model):
first_name = models.CharField(max_length=45)
last_name = models.CharField(max_length=45)
email = models.EmailField(max_length=45)
username = models.CharField(max_length=45)
password = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = UserManager()
def __repr__(self):
return "<{} {}>".format(self.first_name, self.last_name)
<file_sep># open a file
# open is a built in python method that creates a python file object
myfile = open('sample.txt')
print(type(myfile))
#if you want to see methods available for a python file object:
dir(myfile)
# read the file
# read is a method that converts the file conent to string, so we are storing a string in variable content
content = myfile.read()
print("file content:\n", content)
# release computre resources
myfile.close()
# convert content to list
# the content would originally be text divided by \n characters
mylist = content.splitlines()
print(mylist)<file_sep>// this is a brief introduction of what can be done that is called curried
// uncurried
function ninjaBelt(ninja,beltColor) {
console.log(`Ninja ${ninja} has earned ${beltColor}!`)
};
ninjaBelt('Devon','black');
function beltNinja(ninja) {
return function belt(beltColor) {
console.log(`Ninja ${ninja} has earned ${beltColor}!`)
}
}
beltNinja("Eileen")('yellow')<file_sep>// when we want an object to inherit not directly from Object, but from another object in order to inherit its members.
function Shape() {}
Shape.prototype.duplicate = function() {
console.log("duplicate");
};
function Circle(radius) {
this.radius = radius;
}
// as it stands, having created the Circle constructor function makes it inherit from Object, as if we'd created it doing the following:
// Circle.prototype = Object.create(Circle.prototype);
// but we want Circle prototype to inherit from Shape, not from Object, so...
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.draw = function() {
console.log("draw");
};
const s = new Shape();
const c = new Circle(1);
s.duplicate();
c.draw();
c.duplicate();
// there is a problem with this implementation, and it is that we reset the Circle prototype and we can no longer dynamically create circles. with new Circle();
// as a best practice, whenever the prototype of an object is reset, also reset the constructor:
Circle.prototype.constructor = Circle;
<file_sep>function Circle(radius) {
this.radius = radius;
let location = { x: 1, y: 1 }; // private property
this.draw = function() {
console.log(
`drawing radius of ${this.radius} centered at (${location.x}, ${
location.y
}).`
); // no need to call private properties with "this"
};
}
// add a property:
const circle1 = new Circle(1);
circle1.color = "red";
// or using bracket notation
circle1["unique name"] = "Bob";
console.log(circle1);
// delete a property:
delete circle1["unique name"];
console.log(circle1);
// enumerate properties and methods
for (let key in circle1) {
console.log(key);
}
// filter the properties and methods
for (let key in circle1) {
if (typeof circle1[key] === "function") {
console.log("the methods are:", key);
}
}
// return property and method names, values, or entries as arrays:
let pm = Object.keys(circle1);
console.log(pm);
let pv = Object.values(circle1);
console.log(pv);
let pe = Object.entries(circle1);
console.log(pe);
// check if an object has a certain property
if ('radius' in circle1) {
console.log("circle has a radius");
}
// object destructuring:
for (let [key, value] of Object.entries(circle1)) {
// console.log(key, value);
console.log({key, value});
}
<file_sep>from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def default():
return render_template("default.html")
@app.route('/ninja', methods=['POST', 'GET'])
def ninjas():
return render_template("ninja.html", image="tmnt.png")
@app.route("/boilerplate", methods=['POST'])
def boiler():
color = request.form['color'].lower()
print color
return redirect("/ninja/"+color)
@app.route('/ninja/<color>')
def turtle(color):
if color == "blue":
return render_template("/blue.html")
elif color == "orange":
return render_template("/orange.html")
elif color == "red":
return render_template("/red.html")
elif color == "purple":
return render_template("/purple.html")
else:
return render_template("/notapril.html")
app.run(debug=True)<file_sep>import datetime
class Call(object):
def __init__(self, id, name, number, time, reason):
self.id = id
self.name = name
self.number = number
self.time = time
self.reason = reason
def display(self):
print self.__dict__
call1 = Call(1, "Bob", "786-590-2234", datetime.datetime(2018,8,1,1,22), "broken leg")
call2 = Call(2, "Debbie", "520-624-8857", datetime.datetime(2018,8,1,1,25), "stolen car")
call3 = Call(3, "Chuck", "504-333-5026", datetime.datetime(2018,8,1,1,27), "lost cat")
call_list = []
call_list.append(call1)
call_list.append(call2)
call_list.append(call3)
class CallCenter(object):
def __init__(self, call_list):
self.calls = call_list
#print type(self.calls)
self.queue = len(self.calls)
#print self.queue
def info(self):
print "Queue is {} calls long".format(self.queue)
print "Call list details:"
#print self.calls
for i, call in enumerate(self.calls):
print "Call ID: {} Name: {} Number: {} Reason: {}".format(call.id, call.name, call.number, call.reason)
return self
def sort(self):
for i in range(0,self.queue):
for j in range(0,self.queue - 1 - i):
if self.calls[j].time > self.calls[j+1].time:
self.calls[j], self.calls[j+1] = self.calls[j+1], self.calls[j]
return self
def add(self, new_call):
self.calls.append(new_call)
self.queue = len(self.calls)
return self
def delete(self):
self.calls.pop(0)
self.queue = len(self.calls)
return self
def delete_by_phone_number(self, phone_number):
pass
cc1 = CallCenter(call_list)
call4 = Call(4, "Pedro", "305-888-3300", datetime.datetime(2018,8,1,1,31), "insomnia")
call5 = Call(5, "Kiki", "713-220-3789", datetime.datetime(2018,8,1,1,28), "internet challenge")
cc1.info().add(call4).info().delete().add(call5).sort().info().delete().info()<file_sep>users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name': 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
# for people in students:
# print i['first_name']
for types in users:
for people in users[types]:
print people['first_name']
<file_sep>function yummy(arr){
var counter = 0;
for(var i = 0; i < arr.length; i++){
if(arr[i] == "food"){
console.log("yummy");
counter++;
}
}
if(counter==0){
console.log("I'm hungry");
}
}
yummy(['orange', 'apple', 'door', 'caterpillar']);
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Match Found</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class=flashes>
{% for category, message in messages %}
<p class="{{ category }}">{{ message }}</p>
{% endfor %}
</div>
{% endif %}
{% endwith %}
<p>Matches so far are:</p>
<ul>
{% for email in email_matches %}
<li>email: {{ email.email }} - created: {{ email.created_at }} - updated: {{ email.updated_at }}</li>
{% endfor %}
</ul>
</div>
</body>
</html><file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class NoteManager(models.Manager):
def CreateNote(self, context):
messages = []
if context['title'] == "":
messages.append("Title cannot be blank, please insert title")
if context['content'] == "":
messages.append("Note content cannot be blank, please insert content")
if len(messages) == 0:
Note.objects.create(title=context['title'], content=context['content'])
new_note = Note.objects.last().id
return(True, new_note)
else:
return(False, messages)
class Note(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = NoteManager()
<file_sep>for i in range (1,6):
print "hello" + str(i)
print "printed hello + concatenated index as string"
my_list = [12,14,16,18,20]
for i in my_list:
print i
print "printed values, not the index because it is for looping an array"
#note looping arrays does not access the index, it's a superficial loop through the values only, so cannot change values through a loop.
#to access the index, use range:
print my_list
for value in range(0,len(my_list)): #this will iterate from zero up to not including last one
print value #this prints the index
print my_list[value] #this prints the value at each index
my_list[value] = 5 #this will change of values to 5
print my_list
#increment by 2 or other multiple
for i in range (1,9,2):
print i
my_dictionary = {
"name":"Uncle",
"last":"Sam"
}
for value in my_dictionary:
print value #for loops through the keys!
print my_dictionary[value] #prints the values at each key
punk = {
"tempo":"fast",
"guitar":"crunch",
"bass":"overdrive"
}
metal = {
"tempo":"steady",
"guitar":"distortion",
"bass":"compressed"
}
funk = {
"tempo":"groovy",
"guitar":"shiny",
"bass":"nasal"
}
genres = [punk, metal, funk]
for value in genres:
print value
for key in value:
print key +": "+ value[key]
print "That's "+str(genres[-1]['tempo'])
#RECAP: FOR LOOP THROUGH A RANGE = LOOPS THROUGH THE INDEXES
# FOR LOOP THROUGH AN ARRAY = LOOPS THROUGH THE VALUES
# FOR LOOP THROUGH AN OBJECT = LOOPS THROUGH THE KEYS
<file_sep>from flask import Flask, render_template, request, redirect, jsonify # jsonify lets us send JSON back!
# Import MySQLConnector class from mysqlconnection.py
from mysqlconnection import MySQLConnector
app = Flask(__name__)
'''
Set variable 'mysql' to be an instance of the MySQLConnector class,
taking our entire application as the first argument and the database
name as the second argument.
'''
mysql = MySQLConnector(app, 'myownapi')
# HTML-oriented index method
@app.route('/quotes')
def index():
return render_template('index.html')
# JSON-oriented index method
@app.route('/quotes/index_json')
def index_json():
query = "SELECT * FROM quotes"
print "doing the query"
quotes = mysql.query_db(query)
many = len(quotes)
print "got this many ",many
print jsonify(quotes).__dict__
return jsonify(quotes=quotes)
# Because creating html from json using javascript (as done above) is prone to errors, we can return an html response as well by creating a partial html that will be added to index.html
@app.route('/quotes/index_html')
def index_partial():
query = "SELECT * FROM quotes"
quotes = mysql.query_db(query)
return render_template('partials/quotes.html', quotes=quotes)
app.run(debug=True)
<file_sep>const stringArray = ['1','2','3','4','5'];
const mixedArray = ['1','apple','2','3','sugar','4','5','horse'];
class Each {
constructor (array, callback) {
this.array = array;
};
print() {
for (let index = 0; index < this.array.length; index++) {
console.log(this.array[index])
};
return this;
};
};
const array1 = new Each(stringArray);
console.log(array1)
array1.print().print()<file_sep>list1 = ["a", "b", "c"]
list2 = [1,2,3]
for i, j in zip(list1, list2):
print("%s is %s" %(i, j))
# remember what zip does:
new_dict = dict(zip(list1, list2))
print(new_dict)
<file_sep>#a module is a library of methods
class Underscore(object):
def map(self, arr, callback):
self.output = list(map(callback, arr))
return self.output
def reduce(self, arr, callback):
from functools import reduce
self.output = reduce(callback, arr)
return self.output
def find(self, content, find_what):
content = content
self.output = content.find(find_what)
return self.output
def filter(self, arr, callback):
self.output = list(filter(callback, arr))
return self.output
_ = Underscore()
solve = _.reduce([1,2,3,4], lambda x ,y: x + y)
print solve
<file_sep>// multiple techniques for handling async code
// callbacks
const fetchData = callback => {
setTimeout(() => {
callback('Done!')
}, 1500);
}
setTimeout(() => {
console.log('timer is done!');
fetchData(text => {
console.log(text);
});
}, 2000);
<file_sep>#General structure of objects and inheritance:
# class Parent(object): # inherits from the object class
# parent methods and attributes here
# class Child(Parent): #inherits from Parent class so we define Parent as the first parameter
# parent methods and attributes are implicitly inherited
# child methods and attributes
#create a parent class --- known as blueprint class
#has attributes under def __init__()
#has methods under def methodName()
class Vehicle(object):
def __init__(self, wheels, capacity, make, model):
self.wheels = wheels
self.capacity = capacity
self.make = make
self.model = model
self.mileage = 0
def drive(self, miles):
self.mileage += miles
return self
def reverse(self, miles):
self.mileage -= miles
return self
#implicit inheritance: create subclasses that have all attributes and methods of the blueprint class plus their own
#add method without adding attributes or methods to the blueprint
class Bike(Vehicle):
def vehicle_type(self):
return "Bike"
#add method that assigns a value to a blueprint attribute
class Car(Vehicle):
def set_wheels(self):
self.wheels = 4
return self
#this method takes an argument and updates a blueprint attribute
class Airplane(Vehicle):
def fly(self, miles):
self.mileage += miles
return self
v = Vehicle(4,8,"dodge","minivan")
print v.make
b = Bike(2,1,"Schwinn","Paramount")
print b.vehicle_type()
c = Car(8,5,"Toyota","Matrix")
c.set_wheels()
print c.wheels
#despite having indicated 8 wheels, because set_wheels method is called, it updates the self.wheels attribute
a = Airplane(22,853,"Airbus","A380")
a.fly(580)
print a.mileage
#method added miles passed through as argument to the blueprint value 0
<file_sep># return
def rev(text):
return text[::-1]
print(rev("abrahadabra"))
# scope
# in python, functions create local scopes vs loops and if statements that don't
a = 100
def f1():
a = 200
print(a)
def f2():
print(a)
f1()
f2()
# if you want to modify a global variable through a function, use the word global
b = 100
def f3():
global b
b = 300
print(b)
def f4():
b = 500
print(b)
f3()
f4()
print(b)
# lists and dictionaries can be modified globally from within functions!
c = [1,2,3]
def f5():
c[0] = 5
print(c)
f5()
print(c)
<file_sep>//create an object
var Jose = {};
Jose = {
Name: '<NAME>',
Age: 43,
Title: 'Owner',
Company: ['Riskulture', 'The Drub', 'Binnies'],
Location: {
State: "Oklahoma",
City: "Oklahoma City",
Zip: 73113
}
}
<file_sep>import { Directive, HostBinding, Input, HostListener, OnInit } from '@angular/core';
@Directive({
selector: '[appCustomHighlightWithInit]'
})
export class CustomHighlightWithInitDirective implements OnInit {
@Input() initialColor: string;
@Input() highlightColor: string;
@HostBinding('style.backgroundColor') backgroundAlter = this.initialColor;
ngOnInit(): void {
this.backgroundAlter = this.initialColor;
// or
// delete ngOnInit so that starts out with the initialColor = 'cyan'
// if you want to have a pre-mousenter color different to the mouseleave color
}
@HostListener('mouseenter') mouseenter(eventData: Event) {
this.backgroundAlter = this.highlightColor;
}
@HostListener('mouseleave') mouseleave(eventData: Event) {
this.backgroundAlter = this.initialColor;
}
}
<file_sep>//Count elements within an array of arrays that meet a specified condition
var arrays = [
[1,2,3,4,5],
[4,5],
[1,3,5,6],
]
var cond = 3;
function countArrays(){
var counter = 0;
for(var i = 0; i < arrays.length; i++){
for(var u = 0; u < arrays[i].length; u++){
if(arrays[i][u] >= cond){
counter++;
}
}
}
console.log(counter);
}
//Create variables for each element of an array
function createArrays(arr){
for (var i = 0; i < arr.length; i++){
var nameof = "arr"+i+"";
//var "arr"+i+"" = [];
//"arr"+i+"".push(arr[i]);
document.getElementById('outputpage').innerHTML = nameof;
}
}
createArrays([7,4,5,9,1]);
//Reverse an array
function reverseArr(arr){
arr.reverse();
document.getElementById('outputpage').innerHTML = arr
}
reverseArr([5,6,7,8]);
//Studies of console.log vs return
//1
function a(){
console.log('hello');
}
console.log('dojo');
//2
function a(){
console.log('n is', n);
x = n + 15;
}
x = a(3);
console.log('x is', x);
//3
function a(n){
console.log('n is', n);
return n + 15;
}
x = a(3);
console.log('x is', x);
//4
function op(a,b){
c = a+b;
console.log('c is', c);
return c;
}
x = op(2,3) + op(3,5);
console.log('x is', x);
//5
function op(a,b){
c = a+b;
console.log('c is', c);
return c;
}
x = op(2,3) + op(3,op(1,2)) + op(op(2,1),op(2,3));
console.log('x is',x);
//6
x = 15;
function a(){
x = 10;
}
console.log(x);
a();
console.log(x);
//Algorithms II
//1
function multiply(x,y){
console.log(x);
console.log(y);
}
b = multiply(2,3);
console.log(b)
//2
function multiply(x,y){
return x * y;
}
b = multiply(2,3);
console.log(b);
console.log(multiply(5,2));
//3
var x = [1,2,3,4,5,10];
for(var i=0; i<5; i++)
{
i = i + 3;
console.log(i);
}
//4
x=15;
console.log(x);
function awesome(){
x=10;
console.log(x);
}
console.log(x);
awesome();
console.log(x);
//5
for(var i=0; i<15; i+=2){
console.log(i);
}
//6
for(var i=0; i<3; i++){
for(var j=0; j<2; j++){
console.log(i*j);
}
}
//7
function looping(x,y){
for(var i=0; i<x; i++){
for(var j=0; j<x; j++){
console.log(i*j);
}
}
}
z = looping(3,3);
console.log(z);
//8
function looping(x,y){
for(var i=0; i<x; i++){
for(var j=0; j<y; j++){
console.log(i*j);
}
}
return x*y;
}
z = looping(3,5);
console.log(z);
//9
function printUpTo(x){
if(x < 0){
console.log('negative number');
return 'false';
}
else{
for(var i = 1; i <= x; i++){
console.log(i);
}
}
}
printUpTo(10); // should print all the integers from 1 to 10
y = printUpTo(-10); // should return false
console.log(y); // should print false
//10
function printSum(x){
sum = 0;
arr = [];
for(var i = 0; i < 255; i++){
arr.push(i);
sum = sum + arr[i]
console.log(arr);
}
return sum
}
y = printSum(255) // should print all the integers from 0 to 255 and with each integer print the sum so far.
console.log(y) // should print 32385
//11
function printSumArray(x){
sum = 0;
for(var i=0; i<x.length; i++) {
sum = sum + x[i];
}
return sum;
}
console.log( printSumArray([1,2,3]) ); // should log 6
<file_sep>//simplest class and inheritance
class Pet {
move(distance: number = 0) {
console.log(`Pet moved ${distance}`)
}
}
class Dog extends Pet {
bark() {
console.log('Woof! Woof!');
}
}
const doggy = new Dog();
doggy.bark();
doggy.move(10);
doggy.bark();
//class with constructor; super call executes the base class constructor and methods within the subclass
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}`);
}
}
class Snake extends Animal {
constructor(name) {
super(name);
}
move(distance = 5) {
console.log("Slithering...")
super.move(distance);
}
}
class Horse extends Animal {
constructor(name) {
super(name);
}
move(distance = 45) {
console.log("Galloping!")
super.move(distance);
}
}
let sneeky = new Snake("Sneeky");
let johnny = new Horse("Johnny");
sneeky.move();
//we can override default values
johnny.move(34);
//private properties cannot be accessed from outside the class. a side effect is that classes with different private properties become incompatible:
class Plant {
private name: string;
constructor(theName: string) {
this.name = theName;
}
move(distance: number = 0) {
console.log(`${this.name} grows ${distance} per year`);
}
}
let tree = new Plant("Tree");
sneeky = johnny;
// sneeky = tree; results in error because name is private
//classes and interfaces
//interface shapes a group of data
//classes utilize an interface by implementing it
interface Person {
name: string;
age: number;
}
//before the constructor we declare the variables we'll assign in the constructor
// class User implements Person {
// name: string;
// age: number;
// constructor(name: string, age: number) {
// this.name = name;
// this.age = age;
// }
// }
//shortcut for the above is using public, and public automatically does the assignment for us
class User implements Person {
constructor(public name: string, public age: number) {
}
}
const user = new User('Tommy', 12);
//in Angular, we use private more than we use public
//private helps control the visibility of information
<file_sep>//with default property
function objectInit(theObject) {
var a = theObject.a, _a = theObject.b, b = _a === void 0 ? 1001 : _a;
}
var baby = objectInit({ a: "cute" });
console.log(baby);
<file_sep>//run immediately, are self-called. JQuery is built on these
(function() {
console.log("I am a bird!");
} () );
//another syntax
(function() {
console.log("I am an igloo!");
}) ();
// they can take arguments:
(function(arg1,arg2) {
console.log(`the first argument is ${arg1} and the second ${arg2}.`)
}) ('Tommy','the Cat');
// they are used to nest methods so they don't contaminate other variables
(function() {
var a = 5;
var b = 10;
function sum() {
console.log(a + b);
}
function subtract() {
console.log(a - b);
}
sum();
subtract();
} () );
<file_sep>//boolean
let isDone: boolean = false;
//number
let decimal: number = 10;
let series: number = 0xf00d;
//string
let color: string = 'blue';
color = 'red';
//string
let fullName: string = "<NAME>";
let age: number = 45;
let greenting: string = `Hello, my name is ${fullName}
`
let sentence: string = `I'll be ${age + 1} soon`
//array
let array: number[] = [1,2,3];
let list: string[] = ['a', 'b', 'c'];
//tuples
//declare a tuple type
let x: [string,number];
//initialize it
x = ['hello',1];
//then use methods according to type:
console.log(x[0].substring(1));
console.log(x[1].toString());
//union types
let newArr: (string | number);
newArr[1] = 'happy';
newArr[0] = 1;
newArr[2] = 'family';
//enum
enum Color {Red, Green, Blue}
let c: Color = Color.Red
enum Hue {Orange = 1, Purple, Pink}
let h: string = Hue[1];
enum Options {Black = 3, White = 6, Gray = 9}
let o: string = Options[3];
//object = non-primitive object
declare function create(o: object | null): void;
create({prop: 0});
create(null);
// create('fiction'); //error
create({name: "Toby", height: 24});
//type assertions
//one way, with angle-brackets
let someValue: any = `All is lost`;
let strLength: number = (<string>someValue).length;
//another way with 'as' syntax
let thisValue: any = `Not all!`;
let strSize: number = (thisValue as string).length;
//making custom mix of types
type boolStrNum = boolean | string | number;
const thisArray: boolStrNum[] = ['cat', 'dog', 2,7,true]
const firstVal = thisArray[0];
//a function that tells us if something is a string
function isString(value: any): value is string {
return typeof value === 'string';
}
if (isString(firstVal)) {
console.log(firstVal.toUpperCase);
}
<file_sep>const admin_controller = require('./admin');
const shop_controller = require('./shop');
module.exports = {
admin_controller,
shop_controller,
}<file_sep>//with default property
function objectInit(theObject: {
a:string,
b?: number}) {
let {a , b = 1001 } = theObject;
}
const baby = objectInit({a:"cute"});
console.log(baby);
type C = {d: string, e?: number};
function f({d,e}: C):void {
//...
}
<file_sep>#DICTIONARIES BUILT-IN FUNCTIONS
#cmp(dict1, dict2) compares dictionaries in the following order:
# length, key names, values
#len() returns length of dictionary
#str() produces a string representation of the dictionary
#type() returns the type of passed variable; if dictionary, returns _dict_
#DICTIONARIES METHODS
#.clear() removes all elements from a dictionary
#.copy() returns a shallow copy of the dictionary
#.fromkeys(sequence,[value]) create dictionary with sequence as keys and [value] as values
#.get(key, default=None) for key _key_, return its value or default if not in dictionary
#.has_key(key) return true if key in dictionary, false if not
#.items() return a list of dictionary pairs as tuples (key,value)
#.keys() return a list of dictionary keys
#.setdefault(key,default=None) creates key with default value if key not already in dictionary
#.update(dict2) adds dict2 key:value pairs to an existing dictionary
#.values() returns a list of dictionary values
<file_sep># packing and unpacking kwargs is based on the concept of dictionaries
# kwargs are packed and unpacked with **
# unpacking kwargs:
def about(name, age, likes):
sentence = "Meet {}! They are {} years old and like {}.".format(name, age, likes)
return sentence
dict1 = {'name': 'Jose', 'age': 44, 'likes': 'coding'}
dict2 = {'likes': 'surfing', 'name': 'Jambi', 'age': 32}
print(about(**dict1))
print(about(**dict2))
# packing kwargs
# make a dictionary with a function
def foo(**kwargs):
for key, value in kwargs.items():
print("{}:{}".format(key, value))
foo(huda = 'female', zayid = 'male', john = 'male', jambi = 'female')
<file_sep>//object destructuring
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
var _a;
//create variables t.a and t.b without declaration
var t = {
a: "Hank",
b: 12,
c: "Tank"
};
var a = t.a, b = t.b;
console.log(a);
console.log(b);
//assignment without declaration, needs surrounding ()
(_a = { a: "baz", b: 101 }, a = _a.a, b = _a.b);
console.log(a, b);
//that does not affect t
console.log(t);
//create variable for remaining items
var rex = {
h: "stomach",
g: 4,
j: "paws"
};
var h = rex.h, remaining = __rest(rex, ["h"]);
console.log(h);
console.log(remaining);
//renaming properties
var firstName = t.a;
var tanks = t.b;
var lastName = t.c;
console.log(t);
<file_sep># map is used to pass a function through each of the elements of a list
# syntax:
# map(function_to_apply, list_of_inputs)
# example, if you wanted to double all values of a list:
my_list = [1,2,3,4,5]
new_list = list(map(lambda x: x * 2, my_list))
print new_list
# exmaple 2
terms = 10
term_list = list(map(lambda x: x ** 2, range(terms)))
print term_list
for i in range(len(term_list)):
print str(i) + ' squared is equal to', str(term_list[i])<file_sep>def prime_or_psquare(a,b):
for i in range (a,b+1):
if i**(1.0/2)%1==0:
print i,"Bar"
elif i%2 == 0 or i%3 == 0:
print i,"Foo Bar"
else:
print i,"Foo"
prime_or_psquare(100,1000)
<file_sep># quick note: methods like .append() and .insert() change the list behind the scenes and have a return of None.
# Therefore, if used in assignments like listA = listA.append(0)
# that will delete the list
# this happens because lists are mutable types
# append
list1 = [1,3,5,7]
list1.append(2)
print(list1)
# +
list1 = list1 + [4, 6]
print(list1)
# list(), only works with strings because int are not iterable
list1 = list1 + list("ABC")
print(list1)
list1 = list1 + list(str(123))
print(list1)
# embedded list
list1 = list1 + [[1,2,3]]
print(list1)
# do not use .append() in assignments because it deletes the list. Uncomment the below and see that it returns None
# list1 = list1.append([4,5,6])
# insert at any point in the list
# syntax is insert(index, value)
list1.insert(0, "ODDS")
print(list1)
list1.insert(list1.index(2), "EVENS")
print(list1)
<file_sep>import { BrowserModule } from '@angular/platform-browser';
// we can have angular handle forms by importing the forms module from "@angular/forms": "^6.1.0", which is found in the package.json file
import { FormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { HttpService} from './http.service';
import * as fromBooks from './books';
import { SearchPipe } from './pipes/search.pipe';
import { AppRoutingModule } from './app-routing.module';
import { NavComponent } from './nav/nav.component';
import { BookResolve } from './resolvers';
@NgModule({
declarations: [
AppComponent,
...fromBooks.components,
SearchPipe,
NavComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
AppRoutingModule
],
providers: [HttpService, BookResolve],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep># list comprehensions combine for loops, if statements, and variables to create lists
# syntax:
# [[element] [for [element] in [list]] [optional condition]]
# create a list of all even numbers from 0 t0 100
# element = each number; list = range(1,101); condition = if statement
even_numbers = [x for x in range(1,101) if x % 2 == 0]
print(even_numbers)
# create lists out of a list of words
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split()
answer = [[w.upper(), w.lower(), len(w)] for w in words]
print(answer)
# create lists out of a list of words with a condition
answer = [[w.upper(), w.lower(), len(w)] for w in words if len(w) == 5]
print(answer)
<file_sep>import random
class Coin:
def __init__(self, rare=False, clean=True, heads=True, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
self.is_rare = rare
self.is_clean = clean
self.heads = heads
if self.is_rare:
self.value = self.original_value * 1.25
else:
self.value = self.original_value
if self.is_clean:
self.color = self.clean_color
else:
self.color = self.rusty_color
def __del__(self):
print("Coin spent")
def rust(self):
self.color = self.rusty_color
def clean(self):
self.color = self.clean_color
def flip(self):
heads_options = [True, False]
self.heads = random.choice(heads_options)
class Pound(Coin):
def __init__(self):
data = {
"original_value": 1.00,
"clean_color": "gold",
"rusy_color": "greenish",
"num_edges": 1,
"diameter": 22.50,
"thickness": 3.15,
"mass": 9.50
}
super().__init__(**data)
<file_sep>const reversedNumbers = [12.87, 12.64, 12.72, 12.75, 12.91, 12.84, 12.87, 12.84, 12.34, 12.48, 12.47, 12.68, 12.46, 12.8, 12.69, 12.65, 12.61, 12.94, 12.73, 12.84, 123.01, 12.96, 13.15, 13.44, 13.19];
const numbers = reversedNumbers.reverse()
function sum(x, y) {
return x + y;
}
function deviation(mean) {
return function(ret) {
return Math.pow(ret - mean, 2);
}
}
function returns(array) {
let returns = [];
for (let i = 0; i < array.length - 1; i++) {
returns.push(Math.log(array[i+1]/array[i]));
}
return returns;
}
const logReturns = returns(reversedNumbers);
const meanReturn = logReturns.reduce(sum) / logReturns.length;
const deviations = logReturns.map(deviation(meanReturn));
const variance = deviations.reduce(sum) / deviations.length;
const standardDeviation = Math.sqrt(variance);
const workDays = 365 - 10 - 52*2;
const volatility = standardDeviation * Math.sqrt(deviations.length / workDays)
console.log(volatility);
|
c751562ea538476464a13a281f321cbfebf89b76
|
[
"SQL",
"HTML",
"JavaScript",
"Python",
"TypeScript"
] | 415
|
Python
|
brizjose/JBCodingDojo
|
fc161de86995d285bb5b2c39e28e9adbe04faebc
|
7e598419c0e090be4a92f7c3e80323daa9b4bb26
|
refs/heads/master
|
<repo_name>aspic/Rekord<file_sep>/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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.noodlesandwich</groupId>
<artifactId>rekord</artifactId>
<version>0.3-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Rekord</name>
<description>Records in Java. Useful as a replacement for Java beans/value objects/type-safe maps that requires less code.</description>
<url>https://github.com/SamirTalwar/Rekord</url>
<licenses>
<license>
<name>The MIT License (MIT)</name>
<url>http://samirtalwar.mit-license.org/</url>
<distribution>repo</distribution>
</license>
</licenses>
<parent>
<groupId>org.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
<scm>
<connection>scm:git:git<EMAIL>:SamirTalwar/Rekord.git</connection>
<developerConnection>scm:git:git<EMAIL>:SamirTalwar/Rekord.git</developerConnection>
<url><EMAIL>:SamirTalwar/Rekord.git</url>
<tag>HEAD</tag>
</scm>
<distributionManagement>
<repository>
<id>sonatype-nexus-staging</id>
<name>Nexus Staging Repository</name>
<url>http://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
</repository>
</distributionManagement>
<developers>
<developer>
<id>SamirTalwar</id>
<name><NAME></name>
<email><EMAIL></email>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>org.pcollections</groupId>
<artifactId>pcollections</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>17.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlmatchers</groupId>
<artifactId>xml-matchers</artifactId>
<version>1.0-RC1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.2.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<effort>Max</effort>
<threshold>Low</threshold>
<xmlOutput>true</xmlOutput>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>2.12.1</version>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>build/checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>release</id>
<activation>
<property>
<name>release</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<tagNameFormat>v@{project.version}</tagNameFormat>
<mavenExecutorId>forked-path</mavenExecutorId>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
<file_sep>/README.md
# Rekords in Java [](https://travis-ci.org/SamirTalwar/Rekord)
A rekord is an immutable data structure of key-value pairs. Kind of like an immutable map of objects, but completely
type-safe, as the keys themselves contain the type information of the value.
It can be used as an alternative to classes with getters (immutable beans, if you will) so you don't have to implement a
new concrete class for every value concept—instead, a single type has you covered. You also get builders for free,
`equals` and `hashCode` are implemented for you, validation and serialization are covered, and other concepts, such as
default values, can be implemented once and used for all rekords. Finally, all Rekords, being immutable, are thread-safe
to construct and to use.
And there's no magic.
An example:
```java
Rekord<Sandvich> sandvich = Sandvich.rekord
.with(Sandvich.filling, Lettuce)
.with(Sandvich.style, Burger);
assertThat(sandvich.get(Sandvich.bread), is(Brown));
assertThat(sandvich.get(Sandvich.filling), is(Lettuce));
assertThat(sandvich.get(Sandvich.style), is(Burger));
```
How's that work? And why is the bread brown? We didn't specify that.
The magic is really in the key. It's defined as follows:
```java
public interface Sandvich {
Key<Sandvich, Bread> bread = Key.named("bread").that(defaultsTo(Brown));
Key<Sandvich, Filling> filling = Key.named("filling");
Key<Sandvich, Style> style = Key.named("style");
Rekord<Sandvich> rekord = Rekord.of(Sandvich.class).accepting(filling, bread, style);
}
```
So all you need is one interface and a few constants. The return type of the `Rekord::get` method is the type embodied
in the key, so for the sandvich filling, the return type is `Filling`.
### What else?
There's more. Every Rekord is also a **builder**. Rekords themselves are immutable, so the `with` method returns a new
Rekord each time. Use them, pass them around, make new rekords out of them; because they don't mutate, they're perfectly
safe.
There are [**matchers**][Hamcrest] for the builders. You can assert that a rekord conforms to a specific specification,
just check they have specific keys, or anywhere in between. Take a look at [`RekordMatchers`][RekordMatchers.java] for
more information.
This plays into **validation**. Rather than just building a rekord and using it, you can also create a
[`ValidatingRekord`][ValidatingRekordTest.java] which allows you to build a rekord up, then ensure it passes a
specification. Just like the matchers, Hamcrest is used for validation.
Finally, rekords can be **serialized**. Whether you want it to be JSON, XML or just a Java map, we've got you covered.
It's pretty simple. For example:
```java
Rekord<Person> spongebob = Person.rekord
.with(Person.firstName, "Spongebob")
.with(Person.lastName, "Squarepants");
Document document = spongebob.serialize(new DomXmlSerializer());
assertThat(the(document), isSimilarTo(the(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<person>" +
" <first-name>Spongebob</first-name>" +
" <last-name>Squarepants</last-name>" +
"</person>")));
```
You can see the list of serializers in the [`serialization`][serialization] package. If you don't spot the one you're
looking for, just implement your own. The API is fairly simple.
There are a couple of extra pieces of functionality in the [`extra`][extra] package. At the moment, there are
transformers that use [Guava][], and a serializer that uses [Jackson][]. They're hidden away because you'll get
compilation failures if you try and use them without the correct JAR dependencies. If you're interested, grab the
libraries and get going.
There's almost certainly a bunch of stuff we haven't covered. More examples can be found [in the tests][Tests].
[Tests]: https://github.com/SamirTalwar/Rekord/tree/master/src/test/java/com/noodlesandwich/rekord
[RekordMatchers.java]: https://github.com/SamirTalwar/Rekord/blob/master/src/main/java/com/noodlesandwich/rekord/validation/RekordMatchers.java
[ValidatingRekordTest.java]: https://github.com/SamirTalwar/Rekord/blob/master/src/test/java/com/noodlesandwich/rekord/validation/ValidatingRekordTest.java
[serialization]: https://github.com/SamirTalwar/Rekord/tree/master/src/main/java/com/noodlesandwich/rekord/serialization
[extra]: https://github.com/SamirTalwar/Rekord/tree/master/src/main/java/com/noodlesandwich/rekord/extra
[Guava]: https://code.google.com/p/guava-libraries/
[Hamcrest]: https://github.com/hamcrest/JavaHamcrest
[Jackson]: http://jackson.codehaus.org/
## Installation
You can use Rekord v0.2 by dropping the following into your Maven `pom.xml`. It's in Maven Central.
```xml
<dependency>
<groupId>com.noodlesandwich</groupId>
<artifactId>rekord</artifactId>
<version>0.2</version>
</dependency>
```
If you're not using Maven, alter as appropriate for your dependency management system. If you just want a JAR, you can
[download it directly from Maven][rekord-0.2.jar].
[rekord-0.2.jar]: http://search.maven.org/remotecontent?filepath=com/noodlesandwich/rekord/0.2/rekord-0.2.jar
## Why "Rekord"?
I was in Germany, at [SoCraTes 2013][SoCraTes Conference], when I named it. So I thought I'd make the name a little more
German. ;-)
[SoCraTes Conference]: http://www.socrates-conference.de/
## Credits
Thanks go to:
* [<NAME>][@natpryce], for coming up with the idea of "key" objects in [Make It Easy][].
* [<NAME>][@domfox], for extending the idea by delegating to a simple map in [karg][].
* <NAME>, for working with me on the initial implementation of this library.
[@natpryce]: https://twitter.com/natpryce
[@domfox]: https://twitter.com/domfox
[Make It Easy]: https://code.google.com/p/make-it-easy/
[karg]: https://github.com/youdevise/karg
<file_sep>/src/main/java/com/noodlesandwich/rekord/properties/Properties.java
package com.noodlesandwich.rekord.properties;
public interface Properties<T> extends Iterable<Property<? super T, ?>> {
}
<file_sep>/src/main/java/com/noodlesandwich/rekord/implementation/LimitedPropertyMap.java
package com.noodlesandwich.rekord.implementation;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.noodlesandwich.rekord.keys.Key;
import com.noodlesandwich.rekord.keys.Keys;
import com.noodlesandwich.rekord.properties.Properties;
import com.noodlesandwich.rekord.properties.Property;
import com.noodlesandwich.rekord.properties.PropertyMap;
import org.pcollections.HashTreePMap;
import org.pcollections.PMap;
public final class LimitedPropertyMap<T> implements Properties<T>, PropertyMap<T> {
private static final String UnacceptableKeyTemplate = "The key \"%s\" is not a valid key for this Rekord.";
private final Keys<T> acceptedKeys;
private final PMap<Key<? super T, ?>, Property<? super T, ?>> properties;
public LimitedPropertyMap(Keys<T> acceptedKeys) {
this(acceptedKeys, HashTreePMap.<Key<? super T, ?>, Property<? super T, ?>>empty());
}
private LimitedPropertyMap(Keys<T> acceptedKeys, PMap<Key<? super T, ?>, Property<? super T, ?>> properties) {
this.acceptedKeys = acceptedKeys;
this.properties = properties;
}
@SuppressWarnings("unchecked")
@Override
public <V> V get(Key<? super T, V> key) {
if (!has(key)) {
return null;
}
return (V) properties.get(key).value();
}
@Override
public boolean has(Key<? super T, ?> key) {
return properties.containsKey(key);
}
public Keys<T> keys() {
Set<Keys<? super T>> keys = new HashSet<>();
for (Property<? super T, ?> property : properties.values()) {
keys.add(property.key());
}
return KeySet.from(keys);
}
public Keys<T> acceptedKeys() {
return acceptedKeys;
}
public LimitedPropertyMap<T> with(Property<? super T, ?> property) {
Key<? super T, ?> key = property.key();
Object value = property.value();
if (value == null) {
throw new NullPointerException("A property cannot have a null value.");
}
if (!acceptedKeys.contains(key)) {
throw new IllegalArgumentException(String.format(UnacceptableKeyTemplate, key.name()));
}
return new LimitedPropertyMap<>(acceptedKeys, properties.plus(key, property));
}
public LimitedPropertyMap<T> without(Key<? super T, ?> key) {
return new LimitedPropertyMap<>(
acceptedKeys,
properties.minus(key)
);
}
@Override
public Iterator<Property<? super T, ?>> iterator() {
return properties.values().iterator();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof LimitedPropertyMap)) {
return false;
}
@SuppressWarnings("unchecked")
LimitedPropertyMap<T> that = (LimitedPropertyMap<T>) other;
return properties.equals(that.properties);
}
@Override
public int hashCode() {
return properties.hashCode();
}
@Override
public String toString() {
return properties.toString();
}
}
<file_sep>/src/main/java/com/noodlesandwich/rekord/keys/OriginalKey.java
package com.noodlesandwich.rekord.keys;
import com.noodlesandwich.rekord.implementation.AbstractKey;
import com.noodlesandwich.rekord.properties.Property;
import com.noodlesandwich.rekord.properties.PropertyMap;
public abstract class OriginalKey<T, V> extends AbstractKey<T, V> {
public OriginalKey(String name) {
super(name);
}
@Override
public final Property<T, V> of(V value) {
return new Property<>(this, value);
}
@Override
public final V get(PropertyMap<? extends T> properties) {
return properties.get(this);
}
@Override
public final boolean test(PropertyMap<? extends T> properties) {
return properties.has(this);
}
}
<file_sep>/src/main/java/com/noodlesandwich/rekord/validation/Check.java
package com.noodlesandwich.rekord.validation;
import com.noodlesandwich.rekord.FixedRekord;
public interface Check<T> {
boolean check(FixedRekord<T> rekord);
}
|
d9499e42c3319b791155269504bc91caabe70bac
|
[
"Markdown",
"Java",
"Maven POM"
] | 6
|
Maven POM
|
aspic/Rekord
|
ffdf655f1d06a635145e7227d4e50451ef42f4fd
|
36706d3476ee762d9717584531e3840d07cd20fd
|
refs/heads/master
|
<repo_name>andrei9505/ALF<file_sep>/TD1/String.js
Varianta 1:
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Hello Hello Hello World";
var part1 = /(Hello )+/g;
var res = str.match(part1);
document.write(res);
</script>
</body>
</html>
Varianta 2 :
<!DOCTYPE html>
<html>
<body>
<script>
var str = "Hello Hello Hello Vorld!";
var part1 = /^Hello Hello Hello/g;
var res = str.match(part1);
document.write(res);
</script>
</body>
</html>
|
fef64952344f8fbd7585e9449237269ff8f57567
|
[
"JavaScript"
] | 1
|
JavaScript
|
andrei9505/ALF
|
27f1202bc5eccc29fd6fae75ff42354fb95a6481
|
be2ee030dc55ed6a43b175bb14a98d3717b9786a
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp15
{
class Program
{
static void Main(string[] args)
{
Team Barcelona = new Team()
{
Name = "Barcelona",
City = "Barcelona",
Country = "Spain"
};
Team RealMadrid = new Team()
{
Name = "<NAME>",
City = "Madrid",
Country = "Spain"
};
Player messi = new Player()
{
Name = "Leonel",
Surname = "Messi",
Birthdate = Convert.ToDateTime("01-01-1987"),
Number = 10,
Position = "forward",
Team = Barcelona
};
Player benzema = new Player()
{
Name = "Karim",
Surname = "Benzema",
Birthdate = Convert.ToDateTime("01-01-1986"),
Number = 9,
Position = "forward",
Team = RealMadrid
};
messi.Info();
Console.WriteLine("------------");
benzema.Info();
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp15
{
class Player
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime Birthdate { get; set; }
public int Number { get; set; }
public string Position { get; set; }
public Team Team { get; set; }
public void Info()
{
Console.WriteLine
(
$"Name: {Name}\n" +
$"Surname: {Surname}\n"+
$"Birthdate: {Birthdate.ToString()}\n"+
$"Number: {Number}\n"+
$"Position: {Position}\n"+
$"Team: {Team.Name}."
);
}
}
}
|
d06080b409d2fc57845ce8be96f97b80bcbc9f2e
|
[
"C#"
] | 2
|
C#
|
AkbarGM/PlayerTeam
|
656a7820c27a06524805067c720c3cfb3a82150c
|
54cb46e4458e89cc21fe3e9e906506409a0ed69d
|
refs/heads/main
|
<repo_name>joanacmsilva/Drown_teste<file_sep>/Assets/scripts/Gravidade.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gravidade : MonoBehaviour
{
public bool gravitySwitch;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
gravitySwitch = !gravitySwitch;
if (gravitySwitch)
{
Physics.gravity = new Vector3(0, 1, 0);
}
else if (!gravitySwitch)
{
Physics.gravity = new Vector3(0, -1, 0);
}
}
}
}<file_sep>/Assets/scripts/Jogo.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Jogo : MonoBehaviour
{
[SerializeField]
Transform[] coordenadas = new Transform[2];
[SerializeField]
GameObject colectavel;
[SerializeField]
Text textoPontos;
public bool instanciar = true;
private int[] preenchidos = new int[2];
private int contaPreenchidos = 0;
private int pontos = 0;
// Start is called before the first frame update
void Start()
{
ResetPreenchidos();
}
// Update is called once per frame
void Update()
{
if (instanciar) InstanciaColectavel();
}
private void InstanciaColectavel()
{
instanciar = false;
Instantiate(colectavel, coordenadas[Sorteio()].position, Quaternion.identity);
}
private int Sorteio()
{
int sorteado = 0;
bool livre = false;
while (livre == false)
{
sorteado = Random.Range(0, 2);
if (preenchidos[sorteado] == 0)
{
preenchidos[sorteado] = 1;
livre = true;
}
}
contaPreenchidos++;
if (contaPreenchidos >= 2) ResetPreenchidos();
return sorteado;
}
private void ResetPreenchidos()
{
contaPreenchidos = 0;
for (int i = 0; i < preenchidos.Length; i++)
{
preenchidos[i] = 0;
}
}
public void Pontuacao()
{
pontos++;
textoPontos.text = pontos.ToString();
}
}
<file_sep>/README.md
# Drown2
|
30fb7760b19c1747ea0fb7dc3e356baa30f29c61
|
[
"Markdown",
"C#"
] | 3
|
C#
|
joanacmsilva/Drown_teste
|
e6d2fc9925ecfd44fe8f9d694c97ed7ddae69b3b
|
73ab463d90eeea499ac8fd3ca221a1c1d8a1662a
|
refs/heads/main
|
<repo_name>berkcvlk/todo-app<file_sep>/src/components/TodoItem/TodoItem.js
import React from "react";
import "./TodoItem.css";
import TodoHeader from "../TodoHeader/TodoHeader";
class TodoItem extends React.Component {
state = {
isLineThrough: false,
};
lineThroughHandler = () => {
this.setState({
isLineThrough: !this.state.isLineThrough,
});
};
render() {
return (
<div onClick={this.lineThroughHandler} className="d-flex justify-content-between align-items-center">
<TodoHeader
className={this.state.isLineThrough ? "line-through" : ""}
content={this.props.content}
/>
<button
onClick={() => {
this.props.deleteTodoItem(this.props.id);
}}
className="btn btn-danger"
>
Sil
</button>
</div>
);
}
}
export default TodoItem;
|
a702c6520feb7f9ddfa8a5bf05a54fab9163a35a
|
[
"JavaScript"
] | 1
|
JavaScript
|
berkcvlk/todo-app
|
713095a5d18459f31293411194be804909839081
|
3bfc1392fd90b4f1599584d9b8e4c1850e3611ca
|
refs/heads/master
|
<file_sep>// 1: how could you rewrite the following to make it shorter?
if (foo) {
bar.doSomething(el);
} else {
bar.doSomethingElse(el);
}
foo === true ? bar.doSomethingElse(el) : bar.doSomethingElse(el);
==========================================================================
// 2: what is the faulty logic in the following code?
var foo = 'hello';
(function() {
var foo = foo || 'world';
console.log(foo);
})();
//has to do with scopes. logs world but global scope should make it say hello
=======================================================================================
// 3: given the following code, how would you override the value of the bar
// property for the variable foo without affecting the value of the bar
// property for the variable bim? how would you affect the value of the bar
// property for both foo and bim? how would you add a method to foo and bim to
// console.log the value of each object's bar property? how would you tell if
// the object's bar property had been overridden for the particular object?
var Thinger = function() {
return this;
};
Thinger.prototype = {
bar : 'baz'
};
var foo = new Thinger(),
bim = new Thinger();
===============================================================================================
// 4: given the following code, and assuming that each defined object has a
// 'destroy' method, how would you destroy all of the objects contained in the
// myObjects object?
var myObjects = {
thinger : new myApp.Thinger(),
gizmo : new myApp.Gizmo(),
widget : new myApp.Widget()
};
===============================================================================================
// 5: given the following array, create an array that contains the contents of
// each array item repeated three times, with a space between each item. so,
// for example, if an array item is 'foo' then the new array should contain an
// array item 'foo foo foo'. (you can assume the library of your choice is
// available)
var myArray = [ 'foo', 'bar', 'baz' ];
var myArray = [ 'foo', 'bar', 'baz' ];
var len = myArray.length;
var newArray = [];
for (var i = 0; i < len; i++){
var word = myArray[i];
newArray.push(word+ " " + word +" "+ word);
}
newArray;
======================================================================================================
// 6: how could you improve the following code?
$(document).ready(function() {
$('.foo #bar').css('color', 'red');
$('.foo #bar').css('border', '1px solid blue');
$('.foo #bar').text('new text!');
$('.foo #bar').click(function() {
$(this).attr('title', 'new title');
$(this).width('100px');
});
$('.foo #bar').click();
});
+++
$(document).ready(function() {
var x = $('.foo #bar');
x.css('color', 'red', 'border', '1px solid blue').text('new text!');
x.click(function() {
$(this).attr('title', 'new title');
$(this).width('100px');
});
x.click();
});
=========================================================================================================
// 7: what issues do you see with the following code? how would you fix it?
(function() {
var foo;
dojo.xhrGet({
url : 'foo.php',
load : function(resp) {
foo = resp.foo;
}
});
if (foo) {
// run this important code
}
})();
===============================================================================================================
// 8: how could you rewrite the following code to make it shorter?
(function($){
$('li.foo a').attr('title', 'i am foo');
$('li.bar a').attr('title', 'i am bar');
$('li.baz a').attr('title', 'i am baz');
$('li.bop a').attr('title', 'i am bop');
})(jQuery);
+++++++++++++++++++
(function($){
var classId = $(this).attr('class');
//$(this+classID+"a");
$('li.'+classID+'a').attr('title', 'i am ' + classId);
})(jQuery);
===========================================================================================================
// 9: how would you improve the following code?
for (i = 0; i <= 100; i++) {
$('#thinger').append('<p><span class="thinger">i am thinger ' + i + '</span></p>');
$('#gizmo').append('<p><span class="gizmo">i am gizmo ' + i + '</span></p>');
}
++++++++
for (i = 0; i <= 100; i++) {
var className = $(this).attr('class')
className.append("<p><span class="+className+">i am "+className "" + i + "</span></p>");
}
===============================================================================================
// 10: a user enters their desired tip into a text box; the baseTotal, tax,
// and fee values are provided by the application. what are some potential
// issues with the following function for calculating the total?
function calculateTotal(baseTotal, tip, tax, fee) {
return baseTotal + tip + tax + fee;
}
++++++++++
function calculateTotal(baseTotal, tip, tax, fee) {
if(tip === undefined || isNaN(tip)){
tip = 0;
}
return baseTotal + tip + tax + fee;
}
calculateTotal(3,undefined, 3,4);
====================================================================================================
// 11: write code such that the following alerts "Hello World"
say('Hello')('World');
String.prototype.say = function () {
alert(this);
}
var say = function(str1){
return function (str2){
alert(str1 +" "+ str2);
};
};
say ("hello")("world");
|
f459207acd1472947b2993db37ada09356abfa91
|
[
"JavaScript"
] | 1
|
JavaScript
|
bymak87/jsprac
|
251e016d6f00705e6ed25ae433da705825522910
|
8c1e6be2883ffebccd1979c6edb8577b1f72a5fc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.