branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>kioster/calculator<file_sep>/arithmetic.cpp
#include <QString>
#include <QStringList>
#include "arithmetic.h"
QString add( QString &fore_ , QString &back_ )
{
if ( fore_[0] == '~' )
{
fore_[0] = '-' ;
}
if ( back_[0] == '~' )
{
back_[0] = '-' ;
}
QStringList fore_exp = fore_.split('/') ;
QStringList back_exp = back_.split('/') ;
double temp_result = fore_exp[0].toDouble()*back_exp[1].toDouble() + fore_exp[1].toDouble()*back_exp[0].toDouble() ;
QString result = QString("%1").arg(temp_result) ;
result += '/' ;
temp_result = fore_exp[1].toDouble() * back_exp[1].toDouble() ;
result += QString("%1").arg(temp_result) ;
return result ;
}
QString minus( QString &fore_ , QString &back_ )
{
if ( fore_[0] == '~' )
{
fore_[0] = '-' ;
}
if ( back_[0] == '~' )
{
back_[0] = '-' ;
}
QStringList fore_exp = fore_.split('/') ;
QStringList back_exp = back_.split('/') ;
double temp_result = fore_exp[0].toDouble()*back_exp[1].toDouble() - fore_exp[1].toDouble()*back_exp[0].toDouble() ;
QString result = QString("%1").arg(temp_result) ;
result += '/' ;
temp_result = fore_exp[1].toDouble() * back_exp[1].toDouble() ;
result += QString("%1").arg(temp_result) ;
return result ;
}
QString multi( QString &fore_ , QString &back_ )
{
if ( fore_[0] == '~' )
{
fore_[0] = '-' ;
}
if ( back_[0] == '~' )
{
back_[0] = '-' ;
}
QStringList fore_exp = fore_.split('/') ;
QStringList back_exp = back_.split('/') ;
double temp_result = fore_exp[0].toDouble()*back_exp[0].toDouble() ;
QString result = QString("%1").arg(temp_result) ;
result += '/' ;
temp_result = fore_exp[1].toDouble()*back_exp[1].toDouble() ;
result += QString("%1").arg(temp_result) ;
return result ;
}
QString devide( QString &fore_ , QString &back_ )
{
if ( fore_[0] == '~' )
{
fore_[0] = '-' ;
}
if ( back_[0] == '~' )
{
back_[0] = '-' ;
}
QStringList fore_exp = fore_.split('/') ;
QStringList back_exp = back_.split('/') ;
if ( back_exp[0] == "0" )
{
return "" ;
}
double temp_result = fore_exp[0].toDouble()*back_exp[1].toDouble() ;
QString result = QString("%1").arg(temp_result) ;
result += '/' ;
temp_result = fore_exp[1].toDouble()*back_exp[0].toDouble() ;
result += QString("%1").arg(temp_result) ;
return result ;
}
<file_sep>/calculator_sim.cpp
#include "calculator_sim.h"
#include <QString>
#include <QStringList>
QString getFinResult_v1( QString &exp )
{
/*if ( !isRight(exp))
{
return "" ;
}*/
QStringList nums ;
QString fore , back ;
double f_fore = 1 , f_back = 1 ;
int oper = '\0' ;
bool finish = false ;
if ( exp.contains('('))
{
exp.remove('(') ;
exp.remove(')') ;
}
for ( int i = 0 ; i < exp.length() && !finish ; i++ )
{
switch (exp[i].toLatin1())
{
case '+' :
oper = '+' ;
nums = exp.split('+') ;
fore = nums.at(0).toLocal8Bit().data() ;
back = nums.at(1).toLocal8Bit().data() ;
finish = true ;
break;
case '-' :
oper = '-' ;
nums = exp.split('-') ;
fore = nums.at(0).toLocal8Bit().data() ;
back = nums.at(1).toLocal8Bit().data() ;
finish = true ;
break;
case '*' :
oper = '*' ;
nums = exp.split('*') ;
fore = nums.at(0).toLocal8Bit().data() ;
back = nums.at(1).toLocal8Bit().data() ;
finish = true ;
break;
case '/' :
oper = '/' ;
nums = exp.split('/') ;
fore = nums.at(0).toLocal8Bit().data() ;
back = nums.at(1).toLocal8Bit().data() ;
finish = true ;
break;
default:
break;
}
}
f_fore *= fore.toDouble() ;
f_back *= back.toDouble() ;
double d_result = 0 ;
switch (oper)
{
case '+':
d_result = f_fore + f_back ;
break;
case '-':
d_result = f_fore - f_back ;
break;
case '*':
d_result = f_fore * f_back ;
break;
case '/':
d_result = f_fore / f_back ;
break;
default:
break;
}
QString result = QString( "%1" ).arg(d_result ) ;
return result ;
}
<file_sep>/arithmetic.h
#ifndef ARITHMETIC_H
#define ARITHMETIC_H
#include <QString>
QString add( QString &fore_ , QString &back_ ) ;
QString minus( QString &fore_ , QString &back_ ) ;
QString multi( QString &fore_ , QString &back_ ) ;
QString devide( QString &fore_ , QString &back_ ) ;
#endif // ARITHMETIC_H
<file_sep>/calculator.h
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <QString>
QString getFinResult( QString &expression ) ;
bool isHigher( QChar op_1 , QChar op_2 ) ;
#endif // CALCULATOR_H
<file_sep>/calculator_sim.h
#ifndef HEAD_H
#define HEAD_H
#include <QString>
QString getFinResult_v1( QString &exp ) ;
#endif // HEAD_H
<file_sep>/dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QString>
#include <QtGui>
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
void keyPressEvent( QKeyEvent *key ) ;
~Dialog();
private slots:
void on_pushButton_0_clicked(bool checked);
void on_pushButton_1_clicked(bool checked);
void on_pushButton_2_clicked(bool checked);
void on_pushButton_3_clicked(bool checked);
void on_pushButton_4_clicked(bool checked);
void on_pushButton_5_clicked(bool checked);
void on_pushButton_6_clicked(bool checked);
void on_pushButton_7_clicked(bool checked);
void on_pushButton_8_clicked(bool checked);
void on_pushButton_9_clicked(bool checked);
void on_pushButton_point_clicked(bool checked);
void on_pushButton_plus_clicked(bool checked);
void on_pushButton_minus_clicked(bool checked);
void on_pushButton_multi_clicked(bool checked);
void on_pushButton_devide_clicked(bool checked);
void on_pushButton_left_clicked(bool checked);
void on_pushButton_right_clicked(bool checked);
void on_pushButton_AC_clicked(bool checked);
void on_pushButton_Back_clicked(bool checked);
void on_pushButton_equal_clicked(bool checked);
private:
Ui::Dialog *ui;
QString s_input;
QString s_output;
void moveCursur();
int cursur;
QString getResult(QString &expression_);
};
#endif // DIALOG_H
<file_sep>/calculator.cpp
#include <QString>
#include <QStringList>
#include <QStack>
#include <QRegularExpression>
#include <QRegExp>
#include <string>
#include <qstring.h>
#include "arithmetic.h"
#include "calculator.h"
QString getFinResult( QString &expression_ )
{
QStack<QChar> operator_box ;
QString postfix_exp ;
QString expression = expression_ ;
expression.insert(0 , "(") ;
expression += ")" ;
for ( int i = 0 ; i < expression.length() ; i++ )
{
if ( expression[i] == '(' && expression[i+1] == '-' )
{
expression[i+1] = '~' ;
}
}
for ( int i = 0 ; i < expression.length() ; i++ )
{
if ( expression[i] == '(' )
{
operator_box.push( expression[i] ) ;
}
if ( expression[i] == ')' )
{
while ( operator_box.top() != '(' && !operator_box.isEmpty() )
{
postfix_exp += '|' ;
postfix_exp += operator_box.top() ;
operator_box.pop() ;
}
if ( operator_box.isEmpty() )
{
return "" ;
}
operator_box.pop() ;
}
if ( expression[i] == '+' ||
expression[i] == '-' ||
expression[i] == '*' ||
expression[i] == '/' )
{
postfix_exp += '|' ;
if ( operator_box.isEmpty() )
{
operator_box.push( expression[i] ) ;
}
else if ( isHigher( expression[i] , operator_box.top() ) )
{
operator_box.push( expression[i] ) ;
}
else
{
if ( operator_box.isEmpty() )
{
return "" ;
}
postfix_exp += operator_box.top() ;
postfix_exp += '|' ;
operator_box.pop() ;
operator_box.push( expression[i] ) ;
}
}
if ( (expression[i] >= '0' && expression[i] <= '9') ||
expression[i] == '~' || expression[i] == '.' )
{
postfix_exp += expression[i] ;
}
}
while ( !operator_box.isEmpty() )
{
postfix_exp += '|' ;
postfix_exp += operator_box.top() ;
operator_box.pop() ;
}
operator_box.clear();
/*后面开始计算后缀表达式*/
QStringList num_box = postfix_exp.split( '|' ) ;
QStack<QString> calculator_box ;
QString fore , back , result(num_box[0]) ;
for ( int i = 0 ; i < num_box.count() && !result.isEmpty() ; i++ )
{
if ( !num_box.isEmpty() && ((num_box[i][0]>='0' && num_box[i][0]<='9') ||
num_box[i][0] == '~' ))
{
num_box[i] += "/1" ;
calculator_box.push( num_box[i].toLocal8Bit().data() ) ;
continue ;
}
else
{
if ( calculator_box.isEmpty() )
{
return "" ;
}
back = calculator_box.top() ;
calculator_box.pop() ;
if ( calculator_box.isEmpty() )
{
return "" ;
}
fore = calculator_box.top() ;
calculator_box.pop() ;
if ( num_box.isEmpty() )
{
return "" ;
}
switch ( num_box[i][0].toLatin1() )
{
case '+' :
result = add( fore , back ) ;
break ;
case '-' :
result = minus( fore , back ) ;
break ;
case '*' :
result = multi( fore , back ) ;
break ;
case '/' :
result = devide( fore , back ) ;
break ;
default :
return "" ;
}
calculator_box.push( result ) ;
}
}
if ( !result.isEmpty() )
{
double d_result = 0.0 ;
if ( calculator_box.isEmpty() )
{
return "" ;
}
result = calculator_box.top() ;
if ( result[0] == '~' )
{
result[0] = '-' ;
}
num_box.clear() ;
num_box = result.split('/') ;
d_result = num_box[0].toDouble() / num_box[1].toDouble() ;
result = QString("%0").arg(d_result) ;
}
calculator_box.clear() ;
num_box.clear() ;
return result ;
}
bool isHigher( QChar op_1 , QChar op_2 )
{
if ( ( op_1 == '+' || op_1 == '-' ) && op_2 != '(' )
{
return false ;
}
if ( op_2 == '*' || op_2 == '/' )
{
return false ;
}
return true ;
}
<file_sep>/dialog.cpp
#include <QtCore\QString>
#include <string>
#include "dialog.h"
#include "ui_dialog.h"
#include "calculator_sim.h"
#include "calculator.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_0_clicked(bool checked)
{
if (!checked)
{
s_input += '0';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_1_clicked(bool checked)
{
if (!checked)
{
s_input += '1';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_2_clicked(bool checked)
{
if (!checked)
{
s_input += '2';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_3_clicked(bool checked)
{
if (!checked)
{
s_input += '3';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_4_clicked(bool checked)
{
if (!checked)
{
s_input += '4';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_5_clicked(bool checked)
{
if (!checked)
{
s_input += '5';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_6_clicked(bool checked)
{
if (!checked)
{
s_input += '6';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_7_clicked(bool checked)
{
if (!checked)
{
s_input += '7';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_8_clicked(bool checked)
{
if (!checked)
{
s_input += '8';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_9_clicked(bool checked)
{
if (!checked)
{
s_input += '9';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_point_clicked(bool checked)
{
if (!checked)
{
s_input += '.';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_plus_clicked(bool checked)
{
if (!checked)
{
s_input += '+';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_minus_clicked(bool checked)
{
if (!checked)
{
s_input += '-';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_multi_clicked(bool checked)
{
if (!checked)
{
s_input += '*';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_devide_clicked(bool checked)
{
if (!checked)
{
s_input += '/';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_left_clicked(bool checked)
{
if (!checked)
{
s_input += '(';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_right_clicked(bool checked)
{
if (!checked)
{
s_input += ')';
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_AC_clicked(bool checked)
{
if (!checked)
{
s_input.clear();
s_output.clear();
ui->Input->setText(s_input);
ui->Input->show();
ui->Output->setText(s_output);
ui->Output->show();
}
}
void Dialog::on_pushButton_Back_clicked(bool checked)
{
if (!checked)
{
s_input.chop(1);
ui->Input->setText(s_input);
ui->Input->show();
}
}
void Dialog::on_pushButton_equal_clicked(bool checked)
{
if (!checked)
{
s_output = getResult(s_input) ;
if (s_output.isEmpty())
{
s_input.clear();
ui->Input->setText(s_input);
ui->Input->show();
ui->Output->setText(s_output);
ui->Output->show();
return ;
}
ui->Output->setText(s_output);
ui->Output->show();
ui->Input->setText(s_input);
ui->Input->show();
s_input.clear();
}
}
QString Dialog::getResult(QString &expression_)
{
QString result = getFinResult(expression_);
return result ;
}
void Dialog::keyPressEvent( QKeyEvent *key )
{
if ( key->key() == Qt::Key_0 )
{
this->on_pushButton_0_clicked(false);
}
if ( key->key() == Qt::Key_1 )
{
this->on_pushButton_1_clicked(false);
}
if ( key->key() == Qt::Key_2 )
{
this->on_pushButton_2_clicked(false);
}
if ( key->key() == Qt::Key_3 )
{
this->on_pushButton_3_clicked(false);
}
if ( key->key() == Qt::Key_4 )
{
this->on_pushButton_4_clicked(false);
}
if ( key->key() == Qt::Key_5 )
{
this->on_pushButton_5_clicked(false);
}
if ( key->key() == Qt::Key_6 )
{
this->on_pushButton_6_clicked(false);
}
if ( key->key() == Qt::Key_7 )
{
this->on_pushButton_7_clicked(false);
}
if ( key->key() == Qt::Key_8 )
{
this->on_pushButton_8_clicked(false);
}
if ( key->key() == Qt::Key_9 )
{
this->on_pushButton_9_clicked(false);
}
if ( key->key() == Qt::Key_Plus )
{
this->on_pushButton_plus_clicked(false);
}
if ( key->key() == Qt::Key_Minus )
{
this->on_pushButton_minus_clicked(false);
}
if ( key->key() == Qt::Key_Asterisk )
{
this->on_pushButton_multi_clicked(false);
}
if ( key->key() == Qt::Key_Slash )
{
this->on_pushButton_devide_clicked(false);
}
if ( key->key() == Qt::Key_Period )
{
this->on_pushButton_point_clicked(false);
}
if ( key->key() == Qt::Key_ParenLeft )
{
this->on_pushButton_left_clicked(false);
}
if ( key->key() == Qt::Key_ParenRight )
{
this->on_pushButton_right_clicked(false);
}
if ( key->key() == Qt::Key_Backspace )
{
this->on_pushButton_Back_clicked(false);
}
if ( key->key() == Qt::Key_Equal ||
key->key() == Qt::Key_Enter ||
key->key() == Qt::Key_Return )
{
this->on_pushButton_equal_clicked(false);
}
if ( key->key() == Qt::Key_Escape )
{
this->on_pushButton_AC_clicked(false);
}
}
| df3886b13100411474331ddb0e0fd3898a4bbc4d | [
"C",
"C++"
] | 8 | C++ | kioster/calculator | d4837331c7fddd2110ed203be38c17cbfb29c499 | b57ba6fef758ff8ddc57028fda378d050f5b6561 |
refs/heads/master | <repo_name>paibamboo/vortigern<file_sep>/src/app/redux/IStore.ts
import { ICounter } from 'models/counterModel';
import { IStars } from 'models/starsModel';
export interface IStore {
counter: ICounter;
stars: IStars;
};
| e4b169eac76c4c4952cb35c1291ead801b1132e2 | [
"TypeScript"
] | 1 | TypeScript | paibamboo/vortigern | f22fb58b0bc8a51e8d187b00a102f7c5fb243c15 | 3efa7ed33aa6df501455cf09347b71746e1cb65e |
refs/heads/master | <file_sep>console.log('------------st task10');
/*
Task#10 Accounting
Write an expression using higher-order array methods
(say, filter and reduce) to compute the total value of the machines in the inventory array.
*/
const inventory = [
{type: "machine", value: 5000},
{type: "machine", value: 650},
{type: "duck", value: 10},
{type: "furniture", value: 1200},
{type: "machine", value: 77}
];
let totalMachineValue = inventory.reduce((sum,a)=> sum + a.value , 0);
console.log(totalMachineValue);
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task11');
/*
Task#11 Sorted array
The code for this exercise implements a wrapper for working with sorted arrays.
Its constructor takes a comparison function that compares two elements and returns a number,
negative if the first is less than the second, zero when they are equal, and positive otherwise
(similar to what the sort method on arrays expects).
Rewrite the code to use an ES6 class.
Then, rewrite the loop to use the ES6 array method findIndex, which is like indexOf,
but takes a function instead of an element as argument, and returns the index of the first element
for which that function returns true (or returns -1 if no such element was found).
For example [1, 2, 3].findIndex(x => x > 1) yields 1. Use arrow functions for all function expressions.
*/
class SortedArray{
constructor(compare){
this.compare = compare;
this.content = [];
}
findPos(elt){
for (var i = 0; i < this.content.length; i++) {
if (this.compare(elt, this.content[i]) < 0) break
}
return i
}
insert(elt) {
this.content.splice(this.findPos(elt), 0, elt)
}
}
var sorted = new SortedArray((a, b) => a - b );
sorted.insert(5);
sorted.insert(1);
sorted.insert(2);
sorted.insert(4);
sorted.insert(3);
console.log("array:", sorted.content);
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task12');
/*
Task#12 Precedence
Where does an arrow function end? At a closing bracket or semicolon, of course.
But does a comma denote the end? Is the body of the function in this example x + y, 0, or just x + y?
Is there anything else that will end an arrow function body? Experiment.
*/
console.log([1, 2, 3].reduce((x, y) => x + y, 0)); // (x, y) => x + y - function , 0 - параметр функции reduce
console.log([1, 2, 3].reduce((x, y) => {return x + y}, 0)); // (x, y) => {return x + y} - function - {}
console.log([1, 2, 3].reduce((x, y) => (x + y), 0)); // (x, y) => (x + y) - function - ()
console.log([1, 2, 3].reduce((x, y) => {
x += y;
return x;
}, 0)); // в несколько рядов
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task13');
/*
Task#13 Avoiding disaster
This function uses destructuring for argument parsing.
But it has a problem: it crashes when the caller passes an option object without an enable property.
Since all options have defaults, we'd like to not crash in this case.
Can you think of a clean way to fix this problem?
If you also want to allow not passing in an option object at all, how would you solve that?
*/
// function go(options) {
// let {speed = 4,
// enable: {hyperdrive = false,
// frobnifier = true}} = options
// console.log("speed=", speed,
// "hyperdrive:", hyperdrive,
// "frobnifier:", frobnifier)
// }
function go(options={}) { // параметр по умолчанию
// options = options ? options: {};//присвоение опций, если ничего не передали, то пустой объект, что бы вывести значение выставленные по умолчанию.
let {
speed = 4,
enable: {
hyperdrive = false,
frobnifier = true
} = {
hyperdrive:false,
frobnifier:true
}
}= options;
console.log(` speed= ${speed}
hyperdrive= ${hyperdrive}
frobnifier= ${frobnifier} `)
}
go({speed: 5});
go({speed: 5, enable:{}});
go();// вызов вообще без параметров не вызовет ошибку, и выведет все значения по умолчанию
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task14');
/*
Task#14 Default argument
It would be nice to be able to call our `lastIndexOf` function without providing the third argument,
and have it default to starting at the end of the array.
It would be even nicer if we could express this with an ES6 default argument value. Can we?
In which scope are default arguments evaluated? (Experiment to find out.)
*/
function lastIndexOf(arr=[], elt=0, start = arr.length) { // значение параметра по умолчанию, вычисляются при вызове функции
for (let i = start - 1; i >= 0; i--){
if (arr[i] === elt) return i;
}
return -1
}
console.log(lastIndexOf([1, 2, 1, 2], 2));
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task15');
/*
Task#15 Improve this code
The detectCollision function searches through an array of rectangles and returns the first rectangle that the given point is inside of.
Use destructuring and a higher-order function to make this code cleaner.
You might want to use the new array method find, which takes a function as argument,
and returns the first element in the array (the element, not its index) for which the function returns true.
*/
function detectCollision(objects, ...rest) {
let point = {
x: rest[0],
y: rest[1]
};
let item = objects.find(item=>{
if (point.x >= item.x && point.x <= item.x + item.width &&
point.y >= item.y && point.y <= item.y + item.height)
return item;
});
return item;
}
const myObjects = [
{x: 10, y: 20, width: 30, height: 30},
{x: -40, y: 20, width: 30, height: 30},
{x: 0, y: 0, width: 10, height: 5}
];
console.log(detectCollision(myObjects, 25,21));
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task7');
/*
Task#7 Closing over scope
This is a typical mistake to make in JavaScript.
We create a number of functions in a loop, and refer to an outside variable from these functions.
All of them will end up referring to the same variable, which ends up being incremented to 10.
Thus, callbacks[2] does not log 2. It logs 10, as do all functions in the array.
Do you know the solution for such situations in ES5? Does ES6 provide a cleaner solution?
*/
//ES5
var callbacks_es5 = [];
for (var i = 0; i < 10; i++) {
(function (i) { //обернут в скобки, чтобы интерпретатор понял, что это Function Expression
callbacks_es5.push(function () {
console.log(i)
})
})(i)
}
callbacks_es5[2]();
//ES6
var callbacks_es6 = [];
for (let i = 0; i < 10; i++) { //используется let, a не var
callbacks_es6.push(function() { console.log(i) })
}
callbacks_es6[2]();
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task8');
/*
Task#8 Constant non-constance
Does the fact that account is constant mean that we can't update password?
Why, or why not? And if not, how could we make it so that we can't?
*/
// 1й способ
const account = Object.freeze({ //объект становится эффективно неизменным. Метод возвращает замороженный объект.
username: "marijn",
password: "<PASSWORD>"
});
account.password = "<PASSWORD>"; // (*much* more secure)
console.log(account.password); //=> <PASSWORD>
//2й способ
const user = {
username: "marijn"
};
Object.defineProperty(user, "password", {
value: "<PASSWORD>",
writable: false, // запретить присвоение "user.password="
configurable: false // запретить удаление "delete user.password"
});
user.password = "<PASSWORD>"; // (*much* more secure)
console.log(user.password); //=> <PASSWORD>
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task9');
/*
Task#9 Hoist the class
This code produces an error. So apparently, unlike functions, classes are not hoisted to the top of their scope.
(They are block-scoped.)
What could be the reason for this?
*/
/*
Разница между объявлением функции (function declaration) и объявлением класса (class declaration) в том,
что объявление функции совершает подъём (hoisted), в то время как объявление класса — нет (not hoisted).
Поэтому вначале необходимо объявить ваш класс и только затем работать с ним
*/
class Something {}
let s = new Something(); //=>not error
console.log(s);
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task28');
/*
Task#28 List generator
Solve exercise Iterators.1 again, making the List class iterable by adding a [Symbol.iterator] method.
But this time, use a generator function.
(Remember: the syntax for declaring a Symbol.iterator generator method in a class is *[Symbol.iterator]().)
*/
class List {
constructor(head, tail) {
this.head = head;
this.tail = tail
}
map(f) {
return new List(f(this.head), this.tail && this.tail.map(f))
}
*[Symbol.iterator]() {
if (this.current === undefined) {
this.current = this;
}
while (this.current) {
let val = this.current.head;
this.current= this.current.tail;
yield val;
}
delete this.current;
return {
done: true
};
}
}
let list = new List("x", new List("y", new List("z", null)));
//console.log(list[Symbol.iterator]().next());
for (let elt of list) console.log(elt)
// → x
// y
// z
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task29');
/*
Task#29 Take N again
Redo exercise Iterators.2 using a generator.
*/
function* integers() {
for (let i = 0;; i++) yield i
}
function* take(n, iter) {
let next = iter.next().value;
while( next < n){
yield next;
next = iter.next().value;
}
return {done:true}
}
// console.log(take(3, integers()).next());
for (let elt of take(3, integers()))
console.log(elt)
// → 0
// 1
// 2
/*
---------------------------------------------------------------------------------------------
*/
<file_sep>console.log('------------st task16');
/*
Task#16 Spread out
Simplify these three functions by using the spread syntax.
The first one, replace, replaces part of an array with elements from another array.
The second one, copyReplace, does the same, but creates a new array rather than modifying its argument.
The third one is used to record a birdwatcher's sightings. It takes first a timestamp (say, a Date),
and then any number of strings naming birds. It then stores these in the birdsSeen array.
*/
function replace(array, from, to, elements) {
// array.splice.apply(array, [from, to - from].concat(elements));
array.splice(from, (to-from), ...elements);
}
let testArray = [1, 2, 100, 100, 6];
replace(testArray, 2, 4, [3, 4, 5]);
console.log(testArray);
function copyReplace(array, from, to, elements) {
//return array.slice(0, from).concat(elements).concat(array.slice(to))
return [...array.slice(0, from), ...elements, ...array.slice(to)];
}
console.log(copyReplace([1, 2, 100, 200, 6], 2, 4, [3, 4, 5]));
let birdsSeen = [];
function recordBirds(time, ...birds) { // ...variable => соединения отдельных значений в массив
// birdsSeen.push({time, birds: Array.prototype.slice.call(arguments, 1)})
birdsSeen.push({time, birds: birds})
}
recordBirds(new Date, "sparrow", "robin", "pterodactyl");
console.log(birdsSeen);
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task17');
/*
Task#17 The tooling team
Given the data in the starting code, use a template string to produce the following string.
Make sure the numbers, names, and team name actually come from the data.
There are 4 people on the tooling team.
Their names are Jennie, Ronald, Martin, Anneli.
2 of them have a senior role.
*/
const teamName = "tooling";
const people = [{name: "Jennie", role: "senior"},
{name: "Ronald", role: "junior"},
{name: "Martin", role: "senior"},
{name: "Anneli", role: "junior"}];
let message = `There are ${people.length} people on the ${teamName} team.
Their names are ${people.reduce((msg, man, index, arr)=>{msg += (index == arr.length - 1) ? man.name +'.': man.name +', ';})}.
${people.filter((ele)=> ele.role == 'senior').length} of them have a senior role.`;
console.log(message);
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task18');
/*
Task#18 Template strings
Write a function html that can be used as a template string tag, and produces a string in which all the interpolated pieces are escaped as HTML.
Use the supplied escapeHTML function to do the escaping.
Remember that a tag function gets an array of in-between strings as its first argument, and then the interpolated values as further arguments.
*/
function html(strings, ...values) {
let str = "";
for(let i=0; i<values.length; i++) {
str += strings[i];
str += escapeHTML(values[i]);
}
str += strings[strings.length-1];
return str;
}
const mustEscape = '<>&"';
console.log(html`You should escape the ${mustEscape.length} characters “${mustEscape}” in HTML`);
function escapeHTML(string) {
return String(string).replace(/"/g, """).replace(/</g, "<")
.replace(/>/g, ">").replace(/&/g, "&")
}
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task20');
/*
Task#20 Implement Map
Implement your own version of Map, without actually using Map. I know I said this did not exist, but the catch is that you don't have to worry about algorithmic complexity—looking up a value in a big map can be as slow as it needs to be.
Implement at least these methods/getters:
set(key, value)
Store the given value under the given key.
get(key)
Get the value of the given key.
delete(key)
Remove the given key from the map.
get size()
Get the amount of keys stored in the map.
clear()
Remove all keys from the map.
*/
class MyMap {
constructor(){
this.arr = [];//{value:undefined, done:true}];
}
set(key, value){ //можно чейнить
let ind= -1;
let item = this.arr.find((item,index)=>{if (item.key === key && item.type == typeof key){ind = index; return item}});
if (item){
this.arr[ind] = {key, type: typeof key, value};
}else {
this.arr.push({key, type: typeof key, value});//, done:false});
}
return this;
}
get(key){
let item = this.arr.find((item)=>{if (item.key === key && item.type == typeof key){return item}});
return (item ? item.value : undefined);
}
get size(){
return this.arr.length;
}
delete(key){
let i=-1;
this.arr.forEach(find);
function find(item, index){
if (item.key === key && item.type == typeof key){
return i=index}
return false;
}
if (i >=0 ) {
this.arr.splice(i, 1);
}
}
clear(){
this.arr = [];
}
}
const names = new MyMap;
names.set(Array, "the array constructor");
names.set(Array, "the array constructor2").set('Array', "the array string constructor").set(Math, "the math object");
console.log(names.get(Array));// → "the array constructor2"
console.log(names.get('Array'));// → "the array string constructor"
console.log(names.size);// → 3
names.delete(Array);
console.log(names.size);// → 2
console.log(names.get(Array));// → undefined
names.clear();
console.log(names.get(Math));// → undefined
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task25');
/*
Task#25 List iterator
Make the List class (a linked list implementation) iterable by adding a [Symbol.iterator] method.
(Remember: an iterator is an object with a next method that returns {value, done} objects.)
*/
class List {
constructor(head, tail) {
this.head = head;
this.tail = tail;
}
map(f) {
return new List(f(this.head), this.tail && this.tail.map(f))
}
[Symbol.iterator]() {
return this;
}
next() {
if (this.current === undefined) {
this.current = this;
}
if (this.current) {
let val = this.current.head;
this.current= this.current.tail;
return {
done: false,
value: val
};
} else {
delete this.current;
return {
done: true
};
}
}
}
let lists = new List("x", new List("y", new List("z", null)));
for (let elt of lists) console.log(elt)
// → x
// y
// z
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task26');
/*
Task#26 Take N
The integers function creates an infinite iterator, that keeps on producing integers forever.
Implement the take function, which wraps an iterator in another iterator, but cutting it off after n elements.
*/
function integers() {
let i = 0;
return {next() { return {value: i++} },
[Symbol.iterator]() { return this }}
}
function take(n, iter) {
return {
next() {
let next = iter.next().value;
if ( next < n){
return {done:false, value: next}
}
return {done:true}
},
[Symbol.iterator]() { return this }
}
}
for (let elt of take(3, integers()))
console.log(elt)
// → 0
// 1
// 2
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task27');
/*
Task#26 List.from
Here is our List class again. In ES6, Array has a static method from, which does the thing that you'd
now use Array.prototype.slice.call for—turn an array-like object (like arguments or node.childNodes)
into a real array. If its argument it iterable, it'll take the values from the iterator, and create an
array from that. If not, it'll look for a length property, and use integer indexes to fetch element values.
Add a static from method to the List class, which behaves the same way: It takes a single argument.
If that argument is iterable (has a Symbol.iterator property), it iterates of it, and creates a list from its content.
If not, it loops over the object's indices (using .length), and builds a list from its content.
Note that lists are easiest to build from back to front.
You might want to first convert an iterable to an array to make building your list easier.
Alternatively, use mutation to build the list front-to-back.
*/
class List2 {
constructor(head, tail) {
this.head = head;
this.tail = tail;
}
map(f){
return new List2(f(this.head), this.tail && this.tail.map(f))
}
static isIterable(obj) {
// checks for null and undefined
if (obj == null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}
static fromM(obj){
let newObj, arr;
if (obj.length > 0){//if (this.isIterable(obj)){
arr = Array.isArray(obj) ? obj : obj.split('');
arr.reverse();
newObj = new List2(arr[0], null);
for(let i = 1; i < arr.length; i++){
newObj = new List2(arr[i], newObj);
}
return newObj;
}
return 'не итерируется';
}
}
console.log(List2.fromM([3, 2, 1]));// → List{head: 3, tail: List{head: 2, tail: List{head: 1, tail: null}}}
console.log(List2.fromM(5485)); // 'не итерируется';
console.log(List2.fromM('sdsad')); //→ List{head:s, tail: ....
/*
---------------------------------------------------------------------------------------------
*/<file_sep>console.log('------------st task4');
/*
Task#4 Fake point
Use a single object literal to create an object that is indistinguishable from a Point
instance, without calling the Point constructor.
*/
//класс Point определен в файле "js/classes.js"
let obj_Point = new Point(1,1);
console.log(obj_Point);
let fake_Point = Object.assign({}, obj_Point);
// console.log(fake_Point.plus({x:2, y:3})); //Uncaught TypeError: fake_Point.plus is not a function
fake_Point.__proto__ = obj_Point.__proto__; // console.log(fake_Point.plus({x:2, y:3}) => Point {x: 3, y: 4}
console.log(fake_Point);
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task5');
/*
Task#5 Configurable property
Fill in the startNode function using a single object literal.
The function should return an object with type and value properties containing the value of the arguments by those names,
and a third property, named by the sourceProperty option, set to the value of the sourceValue option.
*/
function startNode(type, value, options) {
return {
type,
value,
[options.sourceProperty] : options.sourceValue
};
}
console.log(startNode("Identifier", "foo", {
sourceProperty: "src",
sourceValue: "bar.js"
}));
// → {type: "Identifier",
// value: "foo",
// src: "bar.js"}
/*
---------------------------------------------------------------------------------------------
*/
console.log('------------st task6');
/*
Task#6 Singleton
Add a get method to the ids object, which returns the next id and increments its next counter. Use the short method syntax.
*/
var ids = {
next: 0,
get(){
return this.next++
}
};
console.log(ids.get());// → 0
console.log(ids.get());// → 1
/*
---------------------------------------------------------------------------------------------
*/<file_sep>
console.log('------------st task24');
/*
Task#24 Privacy
Change the Queue class to use a symbol instead of an underscore-prefixed property name for the private content property.
*/
// let content = Symbol('content');
// let content = Symbol.for('content');
// class Queue {
// constructor() {
// this[content] = []
// }
// put(elt) {
// return this[content].push(elt)
// }
// take() {
// return this[content].shift()
// }
// }
class Queue {
constructor() {
this[Symbol.for('content')] = []
}
put(elt) {
return this[Symbol.for('content')].push(elt)
}
take() {
return this[Symbol.for('content')].shift()
}
}
let q = new Queue;
q.put(13);
q.put(32);
q.put(34);
console.log(q.take());
console.log(q.take());
/*
---------------------------------------------------------------------------------------------
*/ | 55590bb2c9c5d6112a9b4192cbd7e56b169d339b | [
"JavaScript"
] | 10 | JavaScript | kelya513/es6_practic | 11ac58932e004d02581abc508a2e014144dbf8e9 | e16050c77eaf3ca3cb8762b0e3183a8ea492b43a |
refs/heads/master | <file_sep>Using Rails version: 5.2.3 with Ruby 2.5.5
_________________________________________________________________________________
This is a simple rails messaging app that I am creating as part of 'The Complete
Ruby on Rails Developer Course' by <NAME> and <NAME> on Udemy.
This web application makes use of the Rails 5 Action Cable.
_________________________________________________________________________________
URL: https://message-now.herokuapp.com<file_sep>class MessagesController < ApplicationController
before_action :require_user
def create
message = current_user.messages.build(message_params)
messages = message.chatroom.messages
if message.save
message.chatroom.chatroom_users.each do |chatroom_user|
new_count = chatroom_user.unread + 1
chatroom_user.update(unread: new_count)
end
ActionCable.server.broadcast "chatroom#{message.chatroom.id}", render_message: render_message(message, messages),
chatroom_id: message.chatroom.id,
user_id: message.user.id
else
puts message.errors.full_messages
end
end
private
def message_params
params.require(:message).permit(:body, :chatroom_id)
end
def render_message(msg, msgs)
render(partial: 'messages/message', locals: {message: msg, messages: msgs})
end
end<file_sep>class ChatroomUsersController < ApplicationController
def reset_unread
user_id = params[:user_id].to_i
chatroom_id = params[:chatroom_id].to_i
chatroom_user = ChatroomUser.find_by(user_id: user_id, chatroom_id: chatroom_id)
if chatroom_user
chatroom_user.update(unread: 0)
end
end
end<file_sep>// Bind 'enter' key to 'submit' button and clear textfield
submit_message = () => {
$('#message_body').on('keydown', event => {
if (event.target == document.activeElement && event.which == 13) {
event.preventDefault();
$('#msg-form').click();
event.target.value = "";
};
});
};
// Auto-scroll to bottom of message feed
scroll_bottom = (animate, elements) => {
if (elements.length > 0) {
if (animate) {
elements.animate({scrollTop: elements[0].scrollHeight}, 250);
}
else {
elements.scrollTop(elements[0].scrollHeight);
}
}
};
// Style messages
messageStyle = (current_chatroom) => {
let current_usr_id = Number($('#hidden-user-id').data('user_id'));
let messages = current_chatroom.children();
// Timestamp
current_chatroom.find('.ui.horizontal.divider').each(function(i) {
let timestamp = $(this).data('timestamp');
let datetime = new Date(timestamp);
strfdatetime = format_datetime(datetime);
$(this).children('.date').text(strfdatetime[0]);
$(this).children('.time').text(strfdatetime[1]);
});
// Iterate through messages
let i;
for (i = 0; i < messages.length; i++) {
// Variable definitions
let message = messages.eq(i).find('.summary');
let prev_message_cont = messages.eq(i-1).find('.content');
let prev_message = messages.eq(i-1).find('.summary');
let user = message.find('.msg-user');
let body = message.find('.segment');
let msg_usr_id = Number(message.find('.hidden-data').data('msg_user_id'));
let prev_msg_usr_id = Number(message.find('.hidden-data').data('prev_msg_user_id'));
// Control flow
switch(msg_usr_id) {
case current_usr_id:
message.attr('align', 'right');
user.remove();
body.removeClass('grey').addClass('blue').attr('align', 'left');
case prev_msg_usr_id:
user.remove();
prev_message_cont.height(prev_message.height());
};
};
};
// Format datetime on client side
format_datetime = (date_time) => {
// Format time
let datetime = new Date(date_time);
let hours = datetime.getHours();
let minutes = datetime.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
if(minutes < 10) {minutes = `0${minutes}`};
// Format date
// Variables for comparison
datetime.setHours(0,0,0,0);
let now = new Date();
now.setHours(0,0,0,0);
let yest = new Date();
yest.setDate(yest.getDate() - 1);
yest.setHours(0,0,0,0);
let week_ago = new Date();
week_ago.setDate(week_ago.getDate() - 7);
// Output variables
let month = datetime.toLocaleDateString('en', {month:'short'});
let date = datetime.getDate();
let year = datetime.getFullYear();
let cal_date;
// Control flow
if (datetime.getTime() == now.getTime()) {
cal_date = 'Today';
}
else if (datetime.getTime() == yest.getTime()) {
cal_date = 'Yesterday';
}
else if (datetime > week_ago) {
cal_date = datetime.toLocaleDateString('en', {weekday:'long'});
}
else if (datetime.getYear() == now.getYear) {
let day = datetime.toLocaleDateString('en', {weekday:'short'});
cal_date = `${day}, ${month} ${date},`;
}
else {
cal_date = `${month} ${date}, ${year},`;
};
// Return datetime
return [cal_date,`${hours}:${minutes} ${ampm}`];
};<file_sep>// Button for viewing chatrooms
view_chatrooms_btn = () => {
let view_btn = $('#view');
view_btn.click((event) => {
view_btn.addClass('disabled');
setTimeout(function() {view_btn.removeClass('disabled')}, 500);
$('#new').removeClass('active');
view_btn.addClass('active');
showMenu('view');
});
};
// Buttons for selecting chatrooms
chatroom_btns = ( el=$('.chatroom.card>.content') ) => {
el.click((event) => {
// Ignore if ellipsis is clicked
let ellipsis = $(event.target).hasClass('ellipsis');
let item = $(event.target).hasClass('item');
if (ellipsis || item) {
return;
};
// Find target element
let target = $(event.target).closest('.chatroom.card');
// Remove dimmer
if (!$('#dimmer').hasClass('hidden')) {
$('#chatbox').dimmer('show').dimmer('hide');
};
// Display users
let chatroom_id = target.data('chatroom_id');
$('.view-action').hide();
let current_chatroom_users = $(`.chatroom-options[data-chatroom_id = "${chatroom_id}"]`);
current_chatroom_users.fadeIn(500);
// Do noting else if card is disabled
if (target.hasClass('disabled')) {
return;
};
// Toggle color
$('.chatroom.card').removeClass('disabled');
target.addClass('disabled');
// Reset badge for target
let badge = target.find('.floating.ui.red.label');
let user_id = Number($('#hidden-user-id').data('user_id'));
reset_unread(badge);
reset_db_unread(user_id, chatroom_id);
// Pass chatroom id to hidden field in main form
$('#message_chatroom_id').val(chatroom_id);
// Display appropriate message container
$('.message-container').fadeOut(500);
setTimeout(() => {
let current_chatroom = $(`.message-container[data-chatroom_id = "${chatroom_id}"]`);
current_chatroom.fadeIn(500);
messageStyle(current_chatroom);
scroll_bottom(false, $('#messages'));
}, 500)
});
}
// Close dropdowns on scroll
close_on_scroll = () => {
$('.ui.dropdown').click((click_event) => {
let old_scroll = $('#chatrooms').scrollTop();
$('#chatrooms').scroll((scroll_event) => {
let new_scroll = $('#chatrooms').scrollTop();
if (new_scroll <= old_scroll-100 || new_scroll >= old_scroll+100) {
$('#chatrooms').off('scroll');
$(scroll_event.target).find('.ui.dropdown').dropdown('hide');
};
});
});
};<file_sep>class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:success] = "Welcome to Message Now, #{@user.username}"
cookies.signed.encrypted[:user_id] = @user.id
ActionCable.server.broadcast 'user_channel', render_user: render_user(@user),
render_checkbox: render_checkbox(@user.id, @user.username)
redirect_to root_path
else
flash[:error] = 'There was a problem with your sign up information'
puts @user.errors.full_messages
redirect_to signup_path
end
end
private
def user_params
params.require(:user).permit(:username, :password)
end
def render_user(user)
render_to_string(partial: 'user_card', locals: {user: user})
end
def render_checkbox(user_id, username)
render_to_string(partial: 'hidden_checkbox', locals: {user_id: user_id, username: username})
end
end<file_sep>// Create new chatroom
newChatroom = (chatroom_id, user_ids, chatroom, chatroom_options) => {
let current_usr_id = Number($('#hidden-user-id').data('user_id'));
if (user_ids.includes(current_usr_id)) {
// Append chatroom button to chatrooms list
let chat_list = $('#chatrooms>.ui.cards');
chat_list.append(chatroom);
// Append message container to main content
let clss = 'class="ui large feed message-container"';
let dta = `data-chatroom_id="${chatroom_id}"`;
$('#messages').append(`<div ${clss} ${dta}></div>`);
// Append chatroom options container to vertical menu
let actions = $('#actions');
actions.before(chatroom_options);
let chat_options = $(`.chatroom-users[data-chatroom_id = ${chatroom_id}]`);
let user_list_item = chat_options.find(`.list>.item[data-user_id = ${current_usr_id}]`);
let user_card = $(`#remove-users-${chatroom_id}>.cards>[data-user-id = ${current_usr_id}]`);
user_list_item.remove();
user_card.remove();
// Add event listeners
removeListener($(`[data-chatroom_id = ${chatroom_id}]`).find('.delete'));
renameListener();
submitRename();
addOrRemListener('add', chatroom_id);
addOrRemListener('remove', chatroom_id);
checkbox('add', $(`#add-users-${chatroom_id} .ui.cards>.card>.content`));
checkbox('remove', $(`#remove-users-${chatroom_id} .ui.cards>.card>.content`));
btnIfCheck('add', chatroom_id);
btnIfCheck('remove', chatroom_id);
addRemSubmit('add');
addRemSubmit('remove');
// Reset checkboxes and empty forms for renaming chatrooms
emptyChatroomNames();
deselectUserCards(user_ids);
uncheckAll();
// Create subscription
chat_subscribe( $('.message-container').last() );
// Make chatroom button clickable
let chat_btn = chat_list.children().last();
chatroom_btns(chat_btn);
$('#view').click();
// Enable dropdown
chat_list.find('.ui.dropdown').dropdown();
// Increase chatroom count
let chat_length = $('.profile .statistic>.value').eq(0);
chat_length.text(Number(chat_length.text()) + 1);
// Auto-scroll
scroll_bottom(true, $('#chatrooms'));
};
};
// Button for creating new chatroom
new_chatroom_btn = () => {
let new_btn = $('#new');
new_btn.click((event) => {
new_btn.addClass('disabled');
setTimeout(function() {new_btn.removeClass('disabled')}, 500);
$('#view').removeClass('active');
new_btn.addClass('active');
showMenu('new');
});
};
// Bind 'enter' key to 'submit' button
submit_chatroom = () => {
$('#chatroom_title').on('keydown', event => {
if (event.target == document.activeElement && event.which == 13) {
event.preventDefault();
$('#room-form-0').click();
// Clear text field
event.target.value = "";
//Uncheck all checkboxes
uncheckAll();
};
});
};<file_sep>// Remove user from chatroom
leave = (chatroom_id, user_id) => {
let current_user_id = $('#hidden-user-id').data('user_id');
if (current_user_id === user_id) {
return;
};
let user_list = $(`.chatroom-users[data-chatroom_id = ${chatroom_id}]`).children('.list');
let list_item = $(`.item.header[data-user_id = "${user_id}"]`);
let add_cards = $(`#add-users-${chatroom_id}>.cards`);
let rem_card = $(`#remove-users-${chatroom_id}>.cards>[data-user-id = ${user_id}]`).removeAttr('style');
let card_HTML = rem_card[0].outerHTML;
list_item.remove();
rem_card.remove();
add_cards.append(card_HTML);
addCheckbox('add', chatroom_id, removeCheckbox('remove', chatroom_id, user_id));
checkbox('add', add_cards.find(`[data-user-id = ${user_id}]>.content`));
btnIfCheck('add', chatroom_id, user_id);
};
remove = (chatroom_id) => {
subtractNotif(chatroom_id);
showMenu('profile');
reduceChatCount();
$('.profile .statistic>.value').eq(1).text(reach());
$('.profile .statistic>.value').eq(2).text(activeChat());
removeChatroom(chatroom_id);
if (!$('.message-container').is(':visible')) {
$('#chatbox').dimmer('show');
};
};
// Remove chatroom
removeListener = (el = $('.delete')) => {
el.click((event) =>{
chatroom_id = $(event.target).closest('[data-chatroom_id]').data('chatroom_id');
remove(chatroom_id);
});
};
removeChatroom = (chatroom_id) => {
$(`.message-container[data-chatroom_id = ${chatroom_id}]`).remove();
$(`.chatroom.card[data-chatroom_id = ${chatroom_id}]`).remove();
$(`.chatroom-options[data-chatroom_id = ${chatroom_id}]`).remove();
$(`#add-rem-users-${chatroom_id}`).remove();
};
reduceChatCount = () => {
let chat_length = $('.profile .statistic>.value').eq(0);
chat_length.text(Number(chat_length.text()) - 1);
};
reach = () => {
let user_list = $(`.chatroom-users`).find('h2');
let users = [];
user_list.each(function(){
users.push($(this).text());
});
return [...new Set(users)].length;
};
activeChat = () => {
let active_chat_el = $('.profile .statistic>.value').eq(2);
let active_chat_id;
let prev_count = 0;
$('.message-container').each(function(){
let msg_count = $(this).find('.segment').length;
if (msg_count >= prev_count) {
prev_count = msg_count;
active_chat_id = $(this).data('chatroom_id');
};
});
let active_chat = idToUsername(active_chat_id);
return (active_chat === '') ? 'None' : active_chat;
};<file_sep>showMenu = (mode) => {
$('.profile').hide();
$('.new-action').hide();
$('.view-action').hide();
$('.chatroom-options').hide();
$('.chatroom-name').hide();
$('.confirm.button').hide();
let el;
switch (mode) {
case 'profile':
el = $('.profile');
break;
case 'new':
el = $('.new-action');
break;
case 'view':
el = $('.view-action');
break;
default:
el = $(`.chatroom-options[data-chatroom_id = ${mode}]`);
break;
};
el.fadeIn(500);
$('.edit.button').removeClass('blue');
$('.add.button').removeClass('blue');
$('.remove.button').removeClass('red');
};
enableBtn = btn => {
btn.removeClass('disabled');
};
disableBtn = btn => {
btn.addClass('disabled');
};
enableAdd = chatroom_id => {
let btn = $(`[data-chatroom_id = ${chatroom_id}]>.add.button`);
enableBtn(btn);
};
enableRem = chatroom_id => {
let btn = $(`[data-chatroom_id = ${chatroom_id}]>.remove.button`);
enableBtn(btn);
};
disableAdd = chatroom_id => {
let btn = $(`[data-chatroom_id = ${chatroom_id}]>.add.button`);
disableBtn(btn);
};
disableRem = chatroom_id => {
let btn = $(`[data-chatroom_id = ${chatroom_id}]>.remove.button`);
disableBtn(btn);
};
uncheckAll = () => {
uncheck($('.chatroom-form'));
uncheck($('.add-form'));
uncheck($('.remove-form'));
};
uncheck = form => {
form.find(':input').prop('checked', false);
};
anyChecks = (form) => {
let checks = (form.find('.checkbox:checked').length === 0) ? false : true;
return checks;
};
// Checkbox functionality
checkbox = (mode, element='') => {
let [el, color, form_sibling] = getCardVarsFromName(mode);
el = (element === '') ? el : element;
el.click(event => {
let target = $(event.target).closest('.user.card');
let form_parent = target.closest(form_sibling).siblings(`.${mode}-action`);
form_parent.find(`:input[value=${target.data('user-id')}]`).click();
if (target.css('background-color') == 'rgb(136, 136, 136)') {
target.css('background-color', color);
}
else {
target.removeAttr('style');
};
});
};
deselectUserCards = user_ids => {
user_ids.forEach(user_id => deselectUserCard(user_id));
};
deselectUserCard = user_id => {
let parent = $('#users');
let card = parent.find(`.cards>.card[data-user-id="${user_id}"]`);
card.removeAttr('style');
};
removeCheckbox = (mode, chatroom_id, user_id) => {
let checkbox = $(`#${mode}-form-${chatroom_id} [for = chatroom_user_ids_${user_id}]`);
return checkbox.remove();
};
addCheckbox = (mode, chatroom_id, checkbox) => {
let checkbox_group = $(`#${mode}-form-${chatroom_id}>.field>.fluid.input`);
checkbox_group.append(checkbox[0].outerHTML);
uncheck($(`#${mode}-form-${chatroom_id}`));
};
getCardVarsFromName = name => {
switch (name) {
case 'new':
return [$('#users>.cards>.user.card>.content'), '#2185d0', '.new-action'];
case 'add':
return [$('.add>.cards>.user.card>.content'), '#2185d0', '.cards'];
case 'remove':
return [$('.remove>.cards>.user.card>.content'), '#db2828', '.cards'];
};
};
idToUsername = (id) => {
return $(`#users>.cards>.card[data-user-id = ${id}]`).text().trim();
};
subtractNotif = (chatroom_id) => {
let chat_notif = $(`#chatroom_${chatroom_id}_badge`).text();
let total_notif = $('#chatrooms_badge');
total_notif.text(Number(total_notif.text()) - Number(chat_notif));
};
isVisible = (el) => {
return (el.css('display') === 'none') ? false : true;
};<file_sep>class User < ApplicationRecord
validates :username, presence: true, uniqueness: {case_sensitive: false}, length: {minimum: 3, maximum:15}
has_many :messages
has_many :chatroom_users, :dependent => :destroy
has_many :chatrooms, through: :chatroom_users
has_secure_password
end<file_sep>class ChatroomUser < ApplicationRecord
belongs_to :chatroom
belongs_to :user
end<file_sep>class ChatroomsController < ApplicationController
before_action :require_user
before_action :set_chatroom, except: [:index, :create, :add_users]
before_action :set_add_rem_users, only: [:add_users, :remove_users]
def index
@users = User.all
@chatroom = Chatroom.new
@chatrooms = current_user.chatrooms.includes(:users, [messages: :user])
@message = Message.new
@messages = Message.custom_display
unread_arr = ChatroomUser.where(user_id: current_user.id).pluck(:unread)
@user_chatrooms = @chatrooms.zip(unread_arr)
@total_unread = unread_arr.sum
end
def create
@chatroom = current_user.chatrooms.new(chatroom_params)
@chatroom.users << current_user
if @chatroom.save
chatrooms = current_user.chatrooms
chatroom_users = @chatroom.users
other_users = User.where('id NOT IN (?)', @chatroom.users.pluck(:id))
flash[:success] = 'Chatroom was successfully created'
ActionCable.server.broadcast 'chatroom_channel', render_chatroom: render_chatroom(@chatroom, 0, chatrooms.length),
render_chatroom_users: render_chatroom_users(@chatroom, current_user, chatroom_users, other_users),
chatroom_id: @chatroom.id,
user_ids: @chatroom.users.ids,
creator_id: current_user.id
else
puts @chatroom.errors.full_messages
end
end
def leave
if @chatroom.users.length > 1
if @chatroom.users.delete(current_user.id)
ActionCable.server.broadcast 'option_channel', mode: 0,
chatroom_id: @chatroom.id,
user_id: current_user.id
end
else
@chatroom.destroy
end
end
def rename
if @chatroom.update(chatroom_params)
ActionCable.server.broadcast 'option_channel', mode: 1,
chatroom_id: @chatroom.id,
new_title: @chatroom.title
end
end
def add_users
@chatroom = Chatroom.includes(:users, :messages).find(params[:format])
if @chatroom.users << @users
chatrooms = current_user.chatrooms.length
chatroom_users = @chatroom.users
chatroom_ids = chatroom_users.pluck(:id)
other_users = User.where('id NOT IN (?)', chatroom_ids)
messages = @chatroom.messages.limit(50).order('id desc')
ActionCable.server.broadcast 'option_channel', mode: 2,
chatroom_id: @chatroom.id,
added_user_ids: @users.pluck(:id),
user_ids: chatroom_ids,
render_chatroom: render_chatroom(@chatroom, 1, chatrooms),
render_chatroom_options: render_chatroom_users(@chatroom, current_user, chatroom_users, other_users),
messages: render_messages(@chatroom),
other_count: other_users.count
end
end
def remove_users
if @chatroom.users.delete(@users)
ActionCable.server.broadcast 'option_channel', mode: 3,
chatroom_id: @chatroom.id,
user_ids: @users.pluck(:id),
chat_count: @chatroom.users.count,
total_count: User.count
end
end
private
def chatroom_params
params.require(:chatroom).permit(:title, user_ids: [])
end
def set_add_rem_users
@users = User.where('id IN (?)', chatroom_params[:user_ids])
end
def set_chatroom
@chatroom = Chatroom.find(params[:format])
end
def render_chatroom(chatroom, unread, length)
render_to_string(partial: 'chatroom_card', locals: {chatroom: chatroom, unread: unread, length: length})
end
def render_chatroom_users(chatroom, current_user, chatroom_users, other_users)
render_to_string(partial: 'chatroom_options', locals: {chatroom: chatroom, current_user: current_user, chatroom_users: chatroom_users, other_users: other_users})
end
def render_messages(chatroom)
render_to_string(partial: 'messages/message', collection: chatroom.messages, locals: {messages: chatroom.messages})
end
end
<file_sep>App.chatroom = App.cable.subscriptions.create("ChatroomChannel", {
received: function(data) {
newChatroom(data.chatroom_id, data.user_ids, data.render_chatroom, data.render_chatroom_users);
let current_usr_id = Number($('#hidden-user-id').data('user_id'));
if (current_usr_id == data.creator_id) {
let chat_btn = $('#chatrooms>.ui.cards').children().last();
chat_btn.children().last().children().click();
};
}
});
<file_sep>class Chatroom < ApplicationRecord
validates :title, presence: true
has_many :messages
has_many :chatroom_users, :dependent => :destroy
has_many :users, through: :chatroom_users
end<file_sep>App.user = App.cable.subscriptions.create("UserChannel", {
// Called when the subscription is ready for use on the server
connected: function() {
},
// Called when the subscription has been terminated by the server
disconnected: function() {
},
// Called when there's incoming data on the websocket for this channel
received: function(data) {
// Append user button to list of users
$('#users>.ui.cards').append(data.render_user);
// Add checkbox
$('#room-form').before(data.render_checkbox);
// Make user button clickable
let user_btn = $('#users>.ui.cards').children().last();
checkbox('new', user_btn);
}
});
<file_sep>App.option = App.cable.subscriptions.create("OptionChannel", {
received: function(data) {
switch (data.mode) {
case 0:
leave(data.chatroom_id, data.user_id);
break;
case 1:
rename(data.chatroom_id, data.new_title);
break;
case 2:
addUsers( data.chatroom_id, data.added_user_ids, data.user_ids,
data.render_chatroom, data.render_chatroom_options, data.messages,
data.other_count);
break;
case 3:
removeUsers(data.chatroom_id, data.user_ids,
data.chat_count, data.total_count);
break;
};
}
});
<file_sep>Rails.application.routes.draw do
# Chatroom route
root 'chatrooms#index'
post 'chatroom' => 'chatrooms#create'
# Chatroom option routes
put 'leave' => 'chatrooms#leave'
patch 'retitle' => 'chatrooms#rename'
patch 'add' => 'chatrooms#add_users'
patch 'remove' => 'chatrooms#remove_users'
# User route
get 'signup' => 'users#new'
post 'users' => 'users#create'
# Session routes
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
# Message route
post 'message' => 'messages#create'
# Chatroom User routes
post 'unread' => 'chatroom_users#reset_unread'
# Channel route
mount ActionCable.server, at: '/cable'
end
<file_sep>// Workaround for Semantic-UI bug #6637
responsive = () => {
$(window).resize(function(){
if ($(window).width() <= 767) {
$('#divider').hide();
$('#horizontal-divider').show();
}
else {
$('#divider').show();
$('#horizontal-divider').hide();
};
});
};<file_sep>// Wait for DOM to load so elements can be queried
$(document).on('turbolinks:load', () => {
//Iterate through chatrooms
$('.message-container').each(function() {
chat_subscribe($(this));
});
});
chat_subscribe = (el) => {
// Create subscription for chatroom
App[`chatroom${el.data('chatroom_id')}`] = App.cable.subscriptions.create({
channel: "MessageChannel",
room: String(el.data('chatroom_id'))
},{
// Called when the subscription is ready for use on the server
connected: function() {
},
// Called when the subscription has been terminated by the server
disconnected: function() {
},
// Called when there's incoming data on the websocket for this channel
received: function(data) {
// Append message partial to message container
let current_chatroom = $(`.message-container[data-chatroom_id=${data.chatroom_id}]`);
current_chatroom.append(data.render_message);
// Style message partial further
messageStyle(current_chatroom);
// Increment badge notifications if chatroom not open
let badge = $(`#chatroom_${data.chatroom_id}_badge`);
let main_badge = $('#chatrooms_badge');
if (current_chatroom.css('display') == 'none') {
let user_id = data.user_id;
let chatroom_id = data.chatroom_id;
increase_unread(badge);
increase_unread(main_badge);
}
else {
reset_unread(badge);
reset_db_unread(data.user_id, data.chatroom_id);
};
// Auto-scroll
scroll_bottom(true, $('#messages'));
}
});
};<file_sep>class AddUnreadToChatroomUsers < ActiveRecord::Migration[5.2]
def change
add_column :chatroom_users, :unread, :integer, :default => 0
end
end
<file_sep>addUsers = (chatroom_id, added_user_ids, chatroom_user_ids, chatroom, chatroom_options, messages, other_count) => {
let current_usr_id = Number($('#hidden-user-id').data('user_id'));
showMenu(chatroom_id);
if ($.inArray(current_usr_id, added_user_ids) >= 0) {
newChatroom(chatroom_id, chatroom_user_ids, chatroom, chatroom_options);
let message_container = $(`.message-container[data-chatroom_id=${chatroom_id}]`);
message_container.append(messages);
messageStyle(message_container);
}
else {
added_user_ids.forEach(user_id => {appendUser(chatroom_id, user_id)});
};
let chat_count = chatroom_user_ids.length;
if (other_count == 0) {disableAdd(chatroom_id)};
if (chat_count > 1) {enableRem(chatroom_id)};
};
removeUsers = (chatroom_id, user_ids, chat_count, total_count) => {
let current_usr_id = Number($('#hidden-user-id').data('user_id'));
showMenu(chatroom_id);
user_ids.forEach(user_id => {leave(chatroom_id, user_id)});
if ($.inArray(current_usr_id, user_ids) >= 0) {remove(chatroom_id)};
if (chat_count === 1) {disableRem(chatroom_id)};
if (total_count - chat_count > 0) {enableAdd(chatroom_id)};
};
appendUser = (chatroom_id, user_id) => {
let user_list = $(`.chatroom-users[data-chatroom_id = ${chatroom_id}]`).children('.list');
let list_item_HTML = `<h2 class="item header" data-user_id="${user_id}">${idToUsername(user_id)}</h2>`;
let rem_cards = $(`#remove-users-${chatroom_id}>.cards`);
let add_card = $(`#add-users-${chatroom_id}>.cards>[data-user-id = ${user_id}]`).removeAttr('style');
let card_HTML = add_card[0].outerHTML;
user_list.append(list_item_HTML);
rem_cards.append(card_HTML);
add_card.remove();
addCheckbox('remove', chatroom_id, removeCheckbox('add', chatroom_id, user_id));
checkbox('remove', rem_cards.find(`[data-user-id = ${user_id}]>.content`));
btnIfCheck('remove', chatroom_id, user_id);
};
addOrRemListener = (mode, chatroom_id='') => {
parent = (chatroom_id === '') ? '' : `[data-chatroom_id = ${chatroom_id}]`;
$(`${parent} .${mode}.button`).click((event) => {
let chatroom_id = $(event.target).parents('[data-chatroom_id]').data('chatroom_id');
toggleAddOrRemMenu(chatroom_id, mode);
});
$(`.${mode}.item`).click((event) => {
let chatroom_id = $(event.target).closest('[data-chatroom_id]').data('chatroom_id');
showMenu(chatroom_id);
toggleAddOrRemMenu(chatroom_id, mode)
});
};
toggleAddOrRemMenu = (chatroom_id, mode) => {
let menu = $(`#${mode}-users-${chatroom_id}`);
let alt_mode = (mode === 'add') ? 'remove' : 'add';
if (isVisible(menu)) {
hideAddOrRemMenu(chatroom_id, mode);
$(`.chatroom-users[data-chatroom_id = ${chatroom_id}]`).fadeIn(500);
}
else {
showAddOrRemMenu(chatroom_id, mode);
hideAddOrRemMenu(chatroom_id, alt_mode);
hideRenameForm(chatroom_id);
$('.chatroom-users').hide();
};
};
addRemSubmit = mode => {
btn = (mode == 'add') ? $('.positive.confirm') : $('.negative.confirm');
btn.click(event => {
let chatroom_id = $(event.target).attr('id').split('-')[2];
let hidden_btn = $(`.${mode}-action #room-form-${chatroom_id}`);
$(hidden_btn).click();
});
};
btnIfCheck = (mode, chatroom_id='', user_id='') => {
let card = $(`.${mode}>.cards>.user.card`);
card = (chatroom_id === '') ? card : $(`#${mode}-users-${chatroom_id}`).find(card);
card = (user_id === '') ? card : card.filter(`[data-user-id = ${user_id}]`);
$(card.children('.content')).click(event => {
let ancestor = $(event.target).closest(`.${mode}.chatroom-options`)
let chatroom_id = ancestor.attr('id').split('-')[2];
let form = $(`#${mode}-form-${chatroom_id}`);
let confirm = $(`#${mode}-confirm-${chatroom_id}`);
confirm.toggle(anyChecks(form));
});
};
showAddOrRemMenu = (chatroom_id, mode) => {
let [alt_mode, alt_color, color] = (mode === 'add') ? ['remove', 'red', 'blue'] : ['add', 'blue', 'red'];
let menu = $(`#${mode}-users-${chatroom_id}`);
let btn = $(`[data-chatroom_id = ${chatroom_id}]`).find(`.${mode}.button`);
let alt_btn = $(`[data-chatroom_id = ${chatroom_id}]`).find(`.${mode}.button`);
let form = $(`#${mode}-form-${chatroom_id}`);
let confirm = $(`#${mode}-confirm-${chatroom_id}`);
menu.fadeIn(500);
btn.addClass(color);
alt_btn.removeClass(alt_color);
confirm.toggle(anyChecks(form));
};
hideAddOrRemMenu = (chatroom_id, mode) => {
let menu = $(`#${mode}-users-${chatroom_id}`);
let color = (mode === 'add') ? 'blue' : 'red';
let btn = $(`[data-chatroom_id = ${chatroom_id}]`).find(`.${mode}.button`);
let confirm = $(`#${mode}-confirm-${chatroom_id}`);
menu.hide();
confirm.hide();
btn.removeClass(color);
};<file_sep>submitRename = (chatroom) => {
$('.edit_chatroom_title').on('keydown', (event) => {
if (event.target == document.activeElement && event.which == 13) {
let chatroom_id = $(event.target).closest('[data-chatroom_id]').data('chatroom_id');
let header = $(`.users-header[data-chatroom_id=${chatroom_id}]`);
let form = $(`.chatroom-name[data-chatroom_id=${chatroom_id}]`);
let edit = $(`[data-chatroom_id=${chatroom_id}]>.edit.button`);
$(event.target).siblings('.rename-form').click();
event.target.value = "";
hideRenameForm(chatroom_id);
$('.edit.button').removeClass('blue');
};
});
};
renameListener = () => {
$('.edit.button').click((event) => {
let chatroom_id = $(event.target).closest('[data-chatroom_id]').data('chatroom_id');
let input = $(`.chatroom-name[data-chatroom_id=${chatroom_id}]`).find('input:text');
toggleRename(chatroom_id);
input.focus();
});
$('.edit.item').click((event) => {
let chatroom_id = $(event.target).closest('[data-chatroom_id]').data('chatroom_id');
let input = $(`.chatroom-name[data-chatroom_id=${chatroom_id}]`).find('input:text');
showMenu(chatroom_id);
toggleRename(chatroom_id);
input.focus();
});
};
rename = (chatroom_id, title) => {
let chatroom_card = $(`.chatroom.card[data-chatroom_id = ${chatroom_id}]`);
let chatroom_header = $(`.users-header[data-chatroom_id = ${chatroom_id}]`);
chatroom_card.find('b').text(title);
chatroom_header.text(title);
};
toggleRename = (chatroom_id) => {
let header = $(`.users-header[data-chatroom_id=${chatroom_id}]`);
$('.add.button').removeClass('blue');
$('.remove.button').removeClass('red');
if (isVisible(header)) {
showRenameForm(chatroom_id);
$(`.chatroom-users[data-chatroom_id = ${chatroom_id}]`).fadeIn(500);
}
else {
hideRenameForm(chatroom_id);
};
};
showRenameForm = (chatroom_id) => {
let header = $(`.users-header[data-chatroom_id=${chatroom_id}]`);
let form = $(`.chatroom-name[data-chatroom_id=${chatroom_id}]`);
let edit = $(`[data-chatroom_id=${chatroom_id}]>.edit.button`);
header.hide();
form.fadeIn(500);
edit.addClass('blue');
hideAddOrRemMenu(chatroom_id, 'add');
hideAddOrRemMenu(chatroom_id, 'remove');
};
hideRenameForm = (chatroom_id) => {
let header = $(`.users-header[data-chatroom_id=${chatroom_id}]`);
let form = $(`.chatroom-name[data-chatroom_id=${chatroom_id}]`);
let edit = $(`[data-chatroom_id=${chatroom_id}]>.edit.button`);
edit.removeClass('blue');
form.hide();
header.fadeIn(500);
};
emptyChatroomNames = () => {
$('.edit_chatroom_title').val('');
}; | 9669f69dfa67b50397d6582830ad3a835bfac102 | [
"Markdown",
"JavaScript",
"Ruby"
] | 22 | Markdown | QuestionMark97/message-now | 29d7afade241421b7d8a78f048a3f77902f237ef | 9a5c3abdf68f4f3574277f4ade27d0e7f4e1d050 |
refs/heads/master | <repo_name>JakeFallows/NoobLab<file_sep>/src/main/webapp/cpp-post-js.js
//LAUNCH WORKER
Module["print"] = function(msg) {
var t = new Date().getTime(); while (new Date().getTime() < t + 2);
cout(msg); //,"color:white; padding-left: 15px;");
};
Module["clear"] = function() { console.clear(); };
Module["printErr"] = function(msg) {
if(msg == "Exiting runtime. Any attempt to access the compiled C code may fail from now. If you want to keep the runtime alive, set Module[\"noExitRuntime\"] = true or build with -s NO_EXIT_RUNTIME=1")
{
self.postMessage({action:"end"});
return;
}
cout(msg);
};
if(typeof(self) != undefined)
{
self.lastconsoleline = "";
self.urlcontext = "";
self.db = undefined;
var request = self.indexedDB.open('cppconsole');
cout("Past DB line on PRE\n");
request.onsuccess = function(e)
{
cout("DB OPEN SUCCESS ON PRE\n");
self.db = e.target.result;
self.postMessage({action:"ready"});
//read messages
self.addEventListener('message', function(e) {
if(!Module['_main'])
{
cout("No main function found","color: red");
return;
}
if( e.data.action == "callMain")
{
/*setInterval(function(){
cout("pantaloons");
// build last console line
var transaction = self.db.transaction(['cpplines'], "readwrite");
var objectStore = transaction.objectStore('cpplines');
objectStore.openCursor().onsuccess = function(event)
{
cout("In cursor success");
var cursor = event.target.result;
if (cursor)
{
self.lastcursorline = cursor.value.cppline;
cursor.delete();
}
else
{
cout("Shouldn't get here yet");
}
}
},1000); */
//cout(Module.callMain.toString());
coutclear();
self.urlcontext = e.data.urlcontext;
Module.callMain();
self.postMessage({action:"end"});
}
if (e.data.action == "updateStdin")
{
self.cppstdin = e.data.params;
}
if (e.data.action == "setContext")
{
self.urlcontext = e.data.urlcontext;
cout("set URL context");
}
}, false);
}
}
//END ********* | 999869a0914a29aad69603c9d9363aecf8423f59 | [
"JavaScript"
] | 1 | JavaScript | JakeFallows/NoobLab | 0248786b97f968677c0bea5170d49be65a3c5911 | d0ada2269b8a0e972624fe61365d1d79737d63ff |
refs/heads/master | <file_sep>package com.sap.ward.iot.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "iot_sensor")
@NamedQueries({ @NamedQuery(name = "Sensor.getAllSensor", query = "SELECT e FROM Sensor e"), })
public class Sensor
{
@Id
private Long id;
private String device;
private String type;
private String description;
public Sensor()
{
}
/**
*
* @param id
* ID
* @param device
* 设备
* @param type
* 类型
* @param description
* 描述
*/
public Sensor(Long id, String device, String type, String description)
{
this.id = id;
this.device = device;
this.type = type;
this.description = description;
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getDevice()
{
return device;
}
public void setDevice(String device)
{
this.device = device == null ? null : device.trim();
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type == null ? null : type.trim();
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description == null ? null : description.trim();
}
}
| 14bc4d1a32c670b7ded58bb46aa52919d334ff8d | [
"Java"
] | 1 | Java | wardpeng/cloud-espm-v2 | cba608cd1d53508cb3a768bbb38fe1c3ed885639 | f60b519e4fbb539043f9b5e0aa59bd69173945b8 |
refs/heads/master | <repo_name>luisdiazvenero/musicapp<file_sep>/src/api/config.js
export default {
appname: "musicapp",
apiKey: "<KEY>",
secret: "<KEY>",
registeredTo: "luisdiazvenero"
}
// Application name musicapp
// API key <KEY>
// Shared secret <KEY>
// Registered to luisdiazvenero | b2b5343e06e66a1f83df773c3cefe3c3338a3725 | [
"JavaScript"
] | 1 | JavaScript | luisdiazvenero/musicapp | bbdcb1be6311f421ea82c16ed48f48ce2ba94985 | 221373eb11a70b6cc78223bee0c38f44bdda0952 |
refs/heads/master | <file_sep>module Idobata::Hook
class Yukai < Base
name '夕会'
identifier :yukai
icon_url 'http://suzukimasashi.github.io/assets/images/SKE48/kato_rumi/00004.jpg'
end
end
<file_sep>require 'spec_helper'
describe Idobata::Hook do
describe 'configuration' do
Idobata::Hook.all.each do |hook|
describe hook do
subject { hook }
its(:name) { should be_present }
its(:icon_url) { should be_present }
end
end
describe 'identifier' do
it 'should be uniq' do
expect(Idobata::Hook.all.map(&:identifier).uniq.count).to eq(Idobata::Hook.all.count)
end
end
end
describe 'instructions.js.hbs.hamlbars' do
Idobata::Hook.all.each do |hook|
describe hook do
subject { hook }
let(:path) { hook.hook_root.join('instructions.js.hbs.hamlbars').to_s }
it 'should be compiled successfully' do
Tilt.new(path).render
end
end
end
end
end
<file_sep>require 'spec_helper'
describe Idobata::Hook::Github, type: :hook do
let(:payload) { fixture_payload("github/#{fixture}") }
describe '#process_payload' do
subject { hook.process_payload }
describe 'paylaod encoded as "application/x-www-form-urlencoded"' do
let(:params) { {payload: payload} }
before do
post params.to_param,
'Content-Type' => 'application/x-www-form-urlencoded; charset=utf-8',
'X-GitHub-Event' => github_event_type
end
describe 'push event' do
let(:fixture) { 'push.json' }
let(:github_event_type) { 'push' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/f966e93db0fbaf3aa07f7df5fa136933?s=32&d=mm" width="16" height="16" alt="" /></span>
<a href='https://github.com/ursm'>ursm</a>
pushed to
<a href='https://github.com/esminc/idobata/tree/foo/bar'>foo/bar</a>
at
<a href='https://github.com/esminc/idobata'>esminc/idobata</a>
(<a href='https://github.com/esminc/idobata/compare/359eaf8de7c3...9f5102f9c212'>compare</a>)
</p>
<ul>
<li>
<a href='https://github.com/esminc/idobata/commit/dc98741098f3fc245055ff76571dc1a257ccfc35'><span class='commit-id'>dc98741</span></a>
add validations to User#name
</li>
<li>
<a href='https://github.com/esminc/idobata/commit/9f5102f9c2129a14577fd8c17bb55526547a5642'><span class='commit-id'>9f5102f</span></a>
give over to html5_validations
</li>
</ul>
HTML
its([:format]) { should eq(:html) }
end
end
describe 'paylaod encoded as "application/vnd.github.v3+json"' do
before do
post payload,
'Content-Type' => 'application/json',
'X-GitHub-Event' => github_event_type
end
describe 'ping event' do
let(:fixture) { 'ping.json' }
let(:github_event_type) { 'ping' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>Ping from GitHub received. Your hook seems to be successfully configured.</p>
HTML
its([:format]) { should eq(:html) }
end
describe 'push event with long comment' do
let(:fixture) { 'push_with_long_comment.json' }
let(:github_event_type) { 'push' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/5c22169c1f836709eea59cebfcd6356a?s=32&d=mm" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
pushed to
<a href='https://github.com/tricknotes/notification-test/tree/master'>master</a>
at
<a href='https://github.com/tricknotes/notification-test'>tricknotes/notification-test</a>
(<a href='https://github.com/tricknotes/notification-test/compare/82e1f8ee0d69...24b298f847d9'>compare</a>)
</p>
<ul>
<li>
<a href='https://github.com/tricknotes/notification-test/commit/24b298f847d9bd36246fd3da5b6ff1bce90f362e'><span class='commit-id'>24b298f</span></a>
commit comment with newlines
<p>hi<br>
:smile:<br>
see: #1</p>
</li>
</ul>
HTML
end
describe 'tag create event' do
let(:fixture) { 'tag_create.json' }
let(:github_event_type) { 'create' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://avatars.githubusercontent.com/u/290782?" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
created tag
<a href='https://github.com/tricknotes/notification-test/tree/hoi'>hoi</a>
at
<a href='https://github.com/tricknotes/notification-test'>tricknotes/notification-test</a>
</p>
HTML
end
describe 'tag delete event' do
let(:fixture) { 'tag_delete.json' }
let(:github_event_type) { 'delete' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://avatars.githubusercontent.com/u/290782?" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
deleted tag 168 at
<a href='https://github.com/tricknotes/notification-test'>tricknotes/notification-test</a>
</p>
HTML
end
describe 'issue event' do
let(:fixture) { 'issue.json' }
let(:github_event_type) { 'issues' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
opened issue
<a href='https://github.com/tricknotes/notification-test/issues/10'>tricknotes/notification-test#10</a>
<b>issue opened</b>
</p>
<p>This is a issue.<br>
<code>puts :hi</code></p>
HTML
end
describe 'issue (closed) event' do
let(:fixture) { 'issue_closed.json' }
let(:github_event_type) { 'issues' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
closed issue
<a href='https://github.com/tricknotes/notification-test/issues/10'>tricknotes/notification-test#10</a>
<b>Oops!!</b>
</p>
HTML
end
describe 'pull request event' do
let(:fixture) { 'pull_request.json' }
let(:github_event_type) { 'pull_request' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
opened
pull request
<a href='https://github.com/tricknotes/notification-test/pull/2'>tricknotes/notification-test#2</a>
<b>Test for PR</b>
</p>
<div class='pull-info'>
<b>1</b>
commit
with
<b>1</b>
addition
and
<b>2</b>
deletions
</div>
<p>This is a pull request</p>
<ul>
<li>ok</li>
</ul>
HTML
end
describe 'pull request (closed) event' do
let(:fixture) { 'pull_request_closed.json' }
let(:github_event_type) { 'pull_request' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
closed
pull request
<a href='https://github.com/tricknotes/notification-test/pull/12'>tricknotes/notification-test#12</a>
<b>:soy_milk:</b>
</p>
<div class='pull-info'>
<b>1</b>
commit
with
<b>1</b>
addition
and
<b>5</b>
deletions
</div>
HTML
end
context 'pull request comment event' do
let(:fixture) { 'pull_request_comment.json' }
let(:github_event_type) { 'issue_comment' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
commented on pull request
<a href='https://github.com/tricknotes/notification-test/issues/2#issuecomment-19731401'>tricknotes/notification-test#2</a>
<b>Test for PR</b>
</p>
<p>This is a comment :smile: </p>
HTML
end
context 'issue comment event' do
let(:fixture) { 'issue_comment.json' }
let(:github_event_type) { 'issue_comment' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://avatars.githubusercontent.com/u/290782?" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
commented on issue
<a href='https://github.com/tricknotes/notification-test/issues/21#issuecomment-39527529'>tricknotes/notification-test#21</a>
<b>Hey!</b>
</p>
<p>mottomotto</p>
HTML
end
context 'pull request review comment event' do
let(:fixture) { 'pull_request_review_comment.json' }
let(:github_event_type) { 'pull_request_review_comment' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
commented on pull request
<a href='https://github.com/tricknotes/notification-test/pull/5#discussion_r4791306'>tricknotes/notification-test#5</a>
</p>
<p>:angel: :innocent: :angel: </p>
HTML
end
context 'commit comment event' do
let(:fixture) { 'commit_comment.json' }
let(:github_event_type) { 'commit_comment' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
commented on commit
<a href='https://github.com/tricknotes/notification-test/commit/6c2eacbf8ef360a90508383574e488c3db67caf5#commitcomment-3685259'>tricknotes/notification-test@6c2eacb</a>
</p>
<p>This is a commit comment!</p>
HTML
end
context 'gollum event' do
let(:fixture) { 'gollum.json' }
let(:github_event_type) { 'gollum' }
its([:source]) { should eq(<<-HTML.strip_heredoc) }
<p>
<span><img src="https://secure.gravatar.com/avatar/dc03a27ae31ba428c560c00c9128cd75?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="16" height="16" alt="" /></span>
<a href='https://github.com/tricknotes'>tricknotes</a>
edited the
<a href='https://github.com/tricknotes/notification-test'>tricknotes/notification-test</a>
wiki
<ul>
<li>
Edited <a href="https://github.com/tricknotes/notification-test/wiki/About-wiki">About wiki</a>.
<a href='https://github.com/tricknotes/notification-test/wiki/About-wiki/_compare/35da4ba^...35da4ba'>View the diff »</a>
</li>
</ul>
</p>
HTML
end
describe 'branch deleted as push event' do
let(:fixture) { 'branch_deleted_as_push.json' }
let(:github_event_type) { 'push' }
subject { ->{ hook.process_payload } }
it { expect(subject).to raise_error(Idobata::Hook::SkipProcessing) }
end
describe 'pull request (synchronize) event' do
let(:fixture) { 'pull_request_synchronize.json' }
let(:github_event_type) { 'pull_request' }
subject { ->{ hook.process_payload } }
it { expect(subject).to raise_error(Idobata::Hook::SkipProcessing) }
end
describe 'Without X-GitHub-Event' do
let(:fixture) { 'ping.json' }
let(:github_event_type) { nil }
subject { -> { hook.process_payload } }
it { should raise_error(Idobata::Hook::BadRequest, 'This is GitHub hook, who are you?') }
end
end
end
end
| 39f2bdccb7ca67c596e985b648f46ecd9ec3eeb0 | [
"Ruby"
] | 3 | Ruby | SuzukiMasashi/idobata-hooks | 1216c63d510f85e2188a622c4c81a20961344c62 | 542e642d96c43b1463d6db07aab454e25ebc9bbe |
refs/heads/master | <repo_name>hzhh123/bootstrap-work<file_sep>/demo1/js/default.js
$(function(){
//设置侧边导航栏的panel-body高度
setSidebarWidth();
setView();
$('#data').jstree({
'core' : {
'data' : [
{ "text" : "根节点","icon":"fa fa-folder", "children" : [{
"text" : "子节点1","icon":"fa fa-folder", "children":[
{ "text" : "子节点111" ,"icon":"fa fa-folder","children":[
{ "text" : "子节点112","icon":"fa fa-file-text","children":[
{"text" : "子节点2","icon":"fa fa-file-text"},
{"text" : "子节点2","icon":"fa fa-file-text"},
{"text" : "子节点2","icon":"fa fa-file-text","children":[
{"text" : "子节点2","icon":"fa fa-file-text"},
{"text" : "子节点2","icon":"fa fa-file-text","children":[
{ "text" : "子节点113","icon":"fa fa-file-text" },
{ "text" : "子节点113","icon":"fa fa-file-text","children":[
{ "text" : "子节点113","icon":"fa fa-file-text" },
{ "text" : "子节点113","icon":"fa fa-file-text" }
] }
]}
]}
] },
{ "text" : "子节点113","icon":"fa fa-file-text" }
]},
{ "text" : "子节点12","icon":"fa fa-file-text" }
]
},{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
,{"text" : "子节点2","icon":"fa fa-file-text"}
]}
]
},
plugins: ["wholerow" ]
});
// $('#data').on('activate_node.jstree',function(e,data){
// alert(data.selected.length);
// }).jstree();
$('#data').on('changed.jstree', function (e, data) {
alert(data.instance.get_node(data.selected).a_attr.href);
}) .jstree();
//切换菜单
$('#toggle-sidebar').on('click',function(){
$(this).hide();
$("#content").css({"marginLeft":50});
$('#sidebar').css({"width":50});
$('#data').hide();
$('#sidebar .panel-footer span').hide();
$('#sidebar .panel-footer').css({"width":50});
setView();
setSidebarWidth();
})
//展开sidebar
$('#sidebar .toggle').on('click',function() {
if($(window).width()>768){
$('#toggle-sidebar').show();
}
$("#content").css({"marginLeft":250});
$('#sidebar').css({"width":250});
$('#data').show();
$('#sidebar .panel-footer span').show();
$('#sidebar .panel-footer').css({"width":250});
$('#sidebar .panel-footer').css({"border-left":"1px solid #337ab7" });
setSidebarWidth();
setView();
})
$(window).resize(function(){
setSidebarWidth();
setView();
})
function setSidebarWidth(){
var window_height=$(window).height();
var panel_footer_height=$('#sidebar .panel-footer').height();
var panel_header_height=$('#sidebar .panel-heading').height();
$('#sidebar .panel-body').css({height:window_height-panel_header_height-panel_footer_height-45});
$('#content').css({height:window_height});
}
function setView(){
var window_width=$(window).width();
var window_height=$(window).height();
var navbar_height=$('.navbar').height();
var footer_height=$('#footer').height();
var sidebar_width=$('#sidebar').width();
$('#tabbable .tab-content').css({width:window_width-sidebar_width});
$('#tabbable .tab-content').css({height:window_height-navbar_height-footer_height});
}
$('#sidebar-setting li a').on('click',function(){
var val=$(this).data('option');
if($('#sidebar .panel').hasClass('panel-primary')||$('#sidebar .panel').hasClass('panel-default')||
$('#sidebar .panel').hasClass('panel-warning')||$('#sidebar .panel').hasClass('panel-danger')||
$('#sidebar .panel').hasClass('panel-info')){
$('#sidebar .panel').removeClass('panel-primary');
$('#sidebar .panel').removeClass('panel-default');
$('#sidebar .panel').removeClass('panel-warning');
$('#sidebar .panel').removeClass('panel-info');
$('#sidebar .panel').removeClass('panel-danger');
$('#sidebar .panel').addClass(val);
if(val=='panel-primary'){
$('#sidebar .panel-footer').css({ "border-color":"#337ab7"});
}
if(val=='panel-default'){
$('#sidebar .panel-footer').css({ "border-color":"#ddd"});
}
if(val=='panel-warning'){
$('#sidebar .panel-footer').css({ "border-color":"#faebcc"});
}
if(val=='panel-danger'){
$('#sidebar .panel-footer').css({ "border-color":"#ebccd1"});
}
if(val=='panel-info'){
$('#sidebar .panel-footer').css({ "border-color":"#bce8f1"});
}
}
})
}); | 913feb3bafb2117060e6c2c71fad3cb2ad2f795a | [
"JavaScript"
] | 1 | JavaScript | hzhh123/bootstrap-work | 9ec7b81f4db4f14ba475ba03749068aeeb85912a | 060a52ff5f47c51087825007b476f45cb166e45b |
refs/heads/master | <file_sep>#!/usr/bin/env node
var path = require('path');
var Promise = require('promise');
var debug = require('debug')('index:bin:handlers');
var base = require('taskcluster-base');
var taskcluster = require('taskcluster-client');
var data = require('../index/data');
var Handlers = require('../index/handlers');
/** Launch handlers */
var launch = function(profile) {
// Load configuration
var cfg = base.config({
defaults: require('../config/defaults'),
profile: require('../config/' + profile),
envs: [
'taskcluster_queueBaseUrl',
'taskcluster_authBaseUrl',
'taskcluster_credentials_clientId',
'taskcluster_credentials_accessToken',
'pulse_username',
'pulse_password',
'aws_accessKeyId',
'aws_secretAccessKey',
'azure_accountName',
'azure_accountKey',
'influx_connectionString'
],
filename: 'taskcluster-index'
});
// Create InfluxDB connection for submitting statistics
var influx = new base.stats.Influx({
connectionString: cfg.get('influx:connectionString'),
maxDelay: cfg.get('influx:maxDelay'),
maxPendingPoints: cfg.get('influx:maxPendingPoints')
});
// Start monitoring the process
base.stats.startProcessUsageReporting({
drain: influx,
component: cfg.get('index:statsComponent'),
process: 'handlers'
});
// Configure IndexedTask and Namespace entities
var IndexedTask = data.IndexedTask.configure({
tableName: cfg.get('index:indexedTaskTableName'),
credentials: cfg.get('azure')
});
var Namespace = data.Namespace.configure({
tableName: cfg.get('index:namespaceTableName'),
credentials: cfg.get('azure')
});
// Create a validator
var validator = null;
var validatorCreated = base.validator({
folder: path.join(__dirname, '..', 'schemas'),
constants: require('../schemas/constants'),
schemaPrefix: 'index/v1/'
}).then(function(validator_) {
validator = validator_;
});
// Configure queue and queueEvents
var queue = new taskcluster.Queue({
baseUrl: cfg.get('taskcluster:queueBaseUrl'),
credentials: cfg.get('taskcluster:credentials')
});
var queueEvents = new taskcluster.QueueEvents({
exchangePrefix: cfg.get('taskcluster:queueExchangePrefix')
});
// When: validator and tables are created, proceed
return Promise.all([
validatorCreated,
IndexedTask.createTable(),
Namespace.createTable()
]).then(function() {
// Create event handlers
var handlers = new Handlers({
IndexedTask: IndexedTask,
Namespace: Namespace,
queue: queue,
queueEvents: queueEvents,
credentials: cfg.get('pulse'),
queueName: cfg.get('index:listenerQueueName'),
routePrefix: cfg.get('index:routePrefix'),
drain: influx,
component: cfg.get('index:statsComponent')
});
// Start listening for events and handle them
return handlers.setup();
}).then(function() {
debug('Handlers are now listening for events');
// Notify parent process, so that this worker can run using LocalApp
base.app.notifyLocalAppInParentProcess();
});
};
// If handlers.js is executed start the handlers
if (!module.parent) {
// Find configuration profile
var profile = process.argv[2];
if (!profile) {
console.log("Usage: handlers.js [profile]")
console.error("ERROR: No configuration profile is provided");
}
// Launch with given profile
launch(profile).then(function() {
debug("Launched handlers successfully");
}).catch(function(err) {
debug("Failed to start handlers, err: %s, as JSON: %j", err, err, err.stack);
// If we didn't launch the handlers we should crash
process.exit(1);
});
}
// Export launch in-case anybody cares
module.exports = launch;<file_sep>#!/usr/bin/env node
var path = require('path');
var Promise = require('promise');
var debug = require('debug')('index:bin:server');
var base = require('taskcluster-base');
var taskcluster = require('taskcluster-client');
var data = require('../index/data');
var v1 = require('../routes/api/v1');
/** Launch server */
var launch = function(profile) {
// Load configuration
var cfg = base.config({
defaults: require('../config/defaults'),
profile: require('../config/' + profile),
envs: [
'index_publishMetaData',
'taskcluster_queueBaseUrl',
'taskcluster_authBaseUrl',
'taskcluster_credentials_clientId',
'taskcluster_credentials_accessToken',
'aws_accessKeyId',
'aws_secretAccessKey',
'azure_accountName',
'azure_accountKey',
'influx_connectionString'
],
filename: 'taskcluster-index'
});
// Configure IndexedTask and Namespace entities
var IndexedTask = data.IndexedTask.configure({
tableName: cfg.get('index:indexedTaskTableName'),
credentials: cfg.get('azure')
});
var Namespace = data.Namespace.configure({
tableName: cfg.get('index:namespaceTableName'),
credentials: cfg.get('azure')
});
// Create a validator
var validator = null;
var validatorCreated = base.validator({
folder: path.join(__dirname, '..', 'schemas'),
constants: require('../schemas/constants'),
publish: cfg.get('index:publishMetaData') === 'true',
schemaPrefix: 'index/v1/',
aws: cfg.get('aws')
}).then(function(validator_) {
validator = validator_;
});
// Create InfluxDB connection for submitting statistics
var influx = new base.stats.Influx({
connectionString: cfg.get('influx:connectionString'),
maxDelay: cfg.get('influx:maxDelay'),
maxPendingPoints: cfg.get('influx:maxPendingPoints')
});
// Start monitoring the process
base.stats.startProcessUsageReporting({
drain: influx,
component: cfg.get('index:statsComponent'),
process: 'server'
});
// When: validator and tables are created, proceed
return Promise.all([
validatorCreated,
IndexedTask.createTable(),
Namespace.createTable()
]).then(function() {
// Create API router and publish reference if needed
return v1.setup({
context: {
validator: validator,
IndexedTask: IndexedTask,
Namespace: Namespace
},
validator: validator,
authBaseUrl: cfg.get('taskcluster:authBaseUrl'),
credentials: cfg.get('taskcluster:credentials'),
publish: cfg.get('index:publishMetaData') === 'true',
baseUrl: cfg.get('server:publicUrl') + '/v1',
referencePrefix: 'index/v1/api.json',
aws: cfg.get('aws'),
component: cfg.get('index:statsComponent'),
drain: influx
});
}).then(function(router) {
// Create app
var app = base.app({
port: Number(process.env.PORT || cfg.get('server:port')),
env: cfg.get('server:env'),
forceSSL: cfg.get('server:forceSSL'),
trustProxy: cfg.get('server:trustProxy')
});
// Mount API router
app.use('/v1', router);
// Create server
return app.createServer();
});
};
// If server.js is executed start the server
if (!module.parent) {
// Find configuration profile
var profile = process.argv[2];
if (!profile) {
console.log("Usage: server.js [profile]")
console.error("ERROR: No configuration profile is provided");
}
// Launch with given profile
launch(profile).then(function() {
debug("Launched server successfully");
}).catch(function(err) {
debug("Failed to start server, err: %s, as JSON: %j", err, err, err.stack);
// If we didn't launch the server we should crash
process.exit(1);
});
}
// Export launch in-case anybody cares
module.exports = launch;<file_sep>suite('Indexing', function() {
var Promise = require('promise');
var assert = require('assert');
var debug = require('debug')('index:test:index_test');
var helper = require('./helper');
var slugid = require('slugid');
var _ = require('lodash');
var subject = helper.setup({title: "indexing test"});
// Create datetime for created and deadline as 25 minutes later
var created = new Date();
var deadline = new Date();
deadline.setMinutes(deadline.getMinutes() + 25);
// Hold reference to taskId
var taskId = null;
var myns = null;
var makeTask = function() {
// Find taskId
taskId = slugid.v4();
myns = slugid.v4();
return {
"provisionerId": "dummy-test-provisioner",
"workerType": "dummy-test-worker-type",
"scopes": [],
"routes": [
subject.routePrefix + ".",
subject.routePrefix + "." + myns,
subject.routePrefix + "." + myns + ".my-indexed-thing",
subject.routePrefix + "." + myns + ".my-indexed-thing-again",
subject.routePrefix + "." + myns + ".one-ns.my-indexed-thing",
subject.routePrefix + "." + myns + ".another-ns.my-indexed-thing-again",
subject.routePrefix + "." + myns + ".slash/test.my-indexed-thing"
],
"retries": 3,
"created": created.toJSON(),
"deadline": deadline.toJSON(),
"payload": {
"desiredResolution": "success"
},
"metadata": {
"name": "Print `'Hello World'` Once",
"description": "This task will prìnt `'Hello World'` **once**!",
"owner": "<EMAIL>",
"source": "https://github.com/taskcluster/taskcluster-index"
},
"tags": {
"objective": "Test task indexing"
}
};
};
test("Run task and test indexing", function() {
// Make task
var task = makeTask();
// Submit task to queue
debug("### Posting task");
return subject.queue.createTask(
taskId,
task
).then(function(result) {
// Claim task
debug("### Claim task");
return subject.queue.claimTask(taskId, 0, {
workerGroup: 'dummy-test-workergroup',
workerId: 'dummy-test-worker-id'
});
}).then(function() {
return helper.sleep(100);
}).then(function() {
debug("### Report task completed");
return subject.queue.reportCompleted(taskId, 0, {
success: true
});
}).then(function() {
debug("### Give indexing 1s to run");
return helper.sleep(2500);
}).then(function() {
debug("### Find task in index");
return subject.index.findTask(myns + '.my-indexed-thing');
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
}).then(function() {
debug("### Find task in index (again)");
return subject.index.findTask(myns);
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
}).then(function() {
debug("### Find task in index (again)");
return subject.index.findTask(myns + '.my-indexed-thing-again');
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
}).then(function() {
debug("### List task in namespace");
return subject.index.listTasks(myns, {});
}).then(function(result) {
assert(result.tasks.length === 2, "Expected 2 tasks");
result.tasks.forEach(function(task) {
assert(task.taskId === taskId, "Wrong taskId");
});
}).then(function() {
debug("### List namespaces in namespace");
return subject.index.listNamespaces(myns, {});
}).then(function(result) {
assert(result.namespaces.length === 3, "Expected 3 namespaces");
assert(result.namespaces.some(function(ns) {
return ns.name === 'one-ns';
}), "Expected to find one-ns");
assert(result.namespaces.some(function(ns) {
return ns.name === 'another-ns';
}), "Expected to find another-ns");
}).then(function() {
debug("### Find task in index");
return subject.index.findTask(myns + '.slash/test.my-indexed-thing');
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
});
});
test("Run task and test indexing (with extra)", function() {
// Make task
var task = makeTask();
task.extra = {
index: {
rank: 42,
expires: deadline.toJSON(),
data: {
hello: "world"
}
}
};
// Submit task to queue
debug("### Posting task");
return subject.queue.createTask(
taskId,
task
).then(function(result) {
// Claim task
debug("### Claim task");
return subject.queue.claimTask(taskId, 0, {
workerGroup: 'dummy-test-workergroup',
workerId: 'dummy-test-worker-id'
});
}).then(function() {
return helper.sleep(100);
}).then(function() {
debug("### Report task completed");
return subject.queue.reportCompleted(taskId, 0, {
success: true
});
}).then(function() {
debug("### Give indexing 1s to run");
return helper.sleep(2500);
}).then(function() {
debug("### Find task in index");
return subject.index.findTask(myns + '.my-indexed-thing');
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
assert(result.rank === 42, "Expected rank 42");
assert(result.data.hello === 'world', "Expected data");
}).then(function() {
debug("### Find task in index (again)");
return subject.index.findTask("");
}).then(function(result) {
assert(result.taskId === taskId, "Wrong taskId");
});
});
});
<file_sep>#!/usr/bin/env node
var path = require('path');
var Promise = require('promise');
var debug = require('debug')('index:bin:droptables');
var data = require('../index/data');
var base = require('taskcluster-base');
/** Launch drop-tables */
var launch = function(profile) {
// Load configuration
var cfg = base.config({
defaults: require('../config/defaults'),
profile: require('../config/' + profile),
envs: [
'azure_accountName',
'azure_accountKey'
],
filename: 'taskcluster-index'
});
// Configure IndexedTask and Namespace entities
var IndexedTask = data.IndexedTask.configure({
tableName: cfg.get('index:indexedTaskTableName'),
credentials: cfg.get('azure')
});
var Namespace = data.Namespace.configure({
tableName: cfg.get('index:namespaceTableName'),
credentials: cfg.get('azure')
});
// Delete tables
return Promise.all([
IndexedTask.deleteTable(),
Namespace.deleteTable()
]).then(function() {
console.log('Azure tables now deleted');
// Notify parent process, so that this worker can run using LocalApp
base.app.notifyLocalAppInParentProcess();
});
};
// If droptables.js is executed start the droptables
if (!module.parent) {
// Find configuration profile
var profile = process.argv[2];
if (!profile) {
console.log("Usage: droptables.js [profile]")
console.error("ERROR: No configuration profile is provided");
}
// Launch with given profile
launch(profile).then(function() {
debug("Launched droptables successfully");
}).catch(function(err) {
debug("Failed to start droptables, err: %s, as JSON: %j",
err, err, err.stack);
// If we didn't launch the droptables we should crash
process.exit(1);
});
}
// Export launch in-case anybody cares
module.exports = launch;<file_sep>module.exports = {
index: {
routePrefix: 'dummy-routes.index-testing',
indexedTaskTableName: 'DummyTestIndexedTasks',
namespaceTableName: 'DummyTestNamespaces',
publishMetaData: 'false',
listenerQueueName: undefined,
statsComponent: 'test-index'
},
taskcluster: {
authBaseUrl: 'http://localhost:60021/v1',
credentials: {
clientId: undefined,
accessToken: undefined
}
},
server: {
publicUrl: 'http://localhost:60020',
port: 60020
},
aws: {
region: 'us-west-2'
}
}; | 9d813927aa90bbc2087a8b6046e9e1c18c9cb708 | [
"JavaScript"
] | 5 | JavaScript | petemoore/taskcluster-index | ccc0e0d370c2d1a85483bf5d68fd198705c7d40d | cbc312af4b4a97079b65e1551e5187bab5999190 |
refs/heads/master | <file_sep>次の歌詞サイトからスクレイピングして、米津さんが作詞した歌詞を全て取得
https://www.uta-net.com/
lyric_scraping.ipynb: スクレイピングするためのコード
米津玄師_lyrics.txt: 米津さんが作詞した歌詞
米津玄師_musics.txt: 米津さんが作詞した曲名
<file_sep># yonedsu_lyric
米津玄師さんの歌詞をAIに学習させた。
そのために必要な自作モジュールをアップロードしています。
dataloaders.py: ミニバッチを生成するために必要なデータローダー
datasets.py: データセットを生成するためのクラスが実装されている。 `prepare()` で整形ができる。
device.py: GPU使用か否かを決定するためのコード
main.py: このコードを実行することで、DLが回る
modules.py: encoderとAttention decoderが実装されている。こちらはmodels.pyと書いてもよかったかもしれない...
utils.py: 自作関数が二つほど
<file_sep>import torch
import torch.nn as nn
from device import device
# Encoderクラス
class Encoder(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, padding_idx):
super(Encoder, self).__init__()
self.hidden_dim = hidden_dim
self.word_embeddings = nn.Embedding(vocab_size, embedding_dim, padding_idx)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
def forward(self, sequence):
embedding = self.word_embeddings(sequence)
# hsが各系列のGRUの隠れ層のベクトル
# Attentionされる要素
hs, h = self.lstm(embedding)
return hs, h
# Attention Decoderクラス
class AttentionDecoder(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, batch_size, padding_idx):
super(AttentionDecoder, self).__init__()
self.hidden_dim = hidden_dim
self.batch_size = batch_size
self.word_embeddings = nn.Embedding(vocab_size, embedding_dim, padding_idx)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
# hidden_dim*2としているのは、各系列のLSTMの隠れ層とAttention層で計算したコンテキストベクトルをtorch.catでつなぎ合わせることで長さが2倍になるため
self.hidden2linear = nn.Linear(hidden_dim * 2, vocab_size)
# 列方向を確率変換したいのでdim=1
self.softmax = nn.Softmax(dim=1)
def forward(self, sequence, hs, h):
embedding = self.word_embeddings(sequence)
output, state = self.lstm(embedding, h)
# Attention層
# hs.size() = ([BACTH_NUM, input_seq_len, hidden_dim])
# output.size() = ([BACTH_NUM, output_seq_len, hidden_dim])
# bmmを使ってEncoder側の出力(hs)とDecoder側の出力(output)をbatchごとまとめて行列計算するために、
# Decoder側のoutputをbatchを固定して転置行列を取る
t_output = torch.transpose(output, 1, 2) # t_output.size() = ([BACTH_NUM, hidden_dim, output_seq_len])
# bmmでバッチも考慮してまとめて行列計算
s = torch.bmm(hs, t_output) # s.size() = ([BACTH_NUM, input_seq_len, output_seq_len])
# 列方向(dim=1)でsoftmaxをとって確率表現に変換
# この値を後のAttentionの可視化などにも使うため、returnで返しておく
attention_weight = self.softmax(s) # attention_weight.size() = ([BACTH_NUM, input_seq_len, output_seq_len])
# コンテキストベクトルをまとめるために入れ物を用意
c = torch.zeros(self.batch_size, 1, self.hidden_dim, device=device)
# 各層(Decoder側のLSTM層は生成文字列がoutput_seq_len文字なのでoutput_seq_len個ある)
# におけるattention weightを取り出して, forループ内でコンテキストベクトルを1つずつ作成する
# バッチ方向はまとめて計算できたのでバッチはそのまま
for i in range(attention_weight.size()[2]): # output_seq_len回ループ
# attention_weight[:,:,i].size() = ([BACTH_NUM, input_seq_len])
# i番目のLSTM層に対するattention weightを取り出すが、テンソルのサイズをhsと揃えるためにunsqueezeする
unsq_weight = attention_weight[:,:,i].unsqueeze(2) # unsq_weight.size() = ([BACTH_NUM, input_seq_len, 1])
# hsの各ベクトルをattention weightで重み付けする
weighted_hs = hs * unsq_weight # weighted_hs.size() = ([BACTH_NUM, input_seq_len, hidden_dim])
# attention weightで重み付けされた各hsのベクトルをすべて足し合わせてコンテキストベクトルを作成
weight_sum = torch.sum(weighted_hs, axis=1).unsqueeze(1) # weight_sum.size() = ([BACTH_NUM, 1, hidden_dim])
c = torch.cat([c, weight_sum], dim=1) # c.size() = ([BACTH_NUM, i, hidden_dim])
# 箱として用意したzero要素が残っているのでスライスして削除
c = c[:,1:,:]
output = torch.cat([output, c], dim=2) # output.size() = ([BACTH_NUM, output_seq_len, hidden_dim*2])
output = self.hidden2linear(output)
return output, state, attention_weight
<file_sep>import math
from device import device
import torch
import numpy as np
class DataLoader:
def __init__(self, dataset, batch_size, shuffle=True):
self.dataset = dataset
self.batch_size = batch_size
self.shuffle = shuffle
self.data_size = len(dataset[0]) # 全てのデータ数
self.max_iter = math.ceil(self.data_size / batch_size)
self.reset()
def reset(self):
self.iteration = 0
if self.shuffle:
self.index = np.random.permutation(len(self.dataset))
else:
self.index = np.arange(len(self.dataset))
def __iter__(self):
return self
def __next__(self):
if self.iteration >= self.max_iter:
self.reset()
raise StopIteration
i, batch_size = self.iteration, self.batch_size
batch_index = self.index[i * batch_size:(i + 1) * batch_size]
batch_x = [self.dataset[0][i] for i in batch_index]
batch_t = [self.dataset[1][i] for i in batch_index]
x = torch.tensor(batch_x, device=device)
t = torch.tensor(batch_t, device=device)
self.iteration += 1
return x, t
def next(self):
return self.__next__()
class SeqDataLoader(DataLoader):
def __init__(self, dataset, batch_size, shuffle, reverse):
super().__init__(dataset=dataset, batch_size=batch_size, shuffle=False)
self.reverse = reverse
def __next__(self):
if self.iteration >= self.max_iter:
self.reset()
raise StopIteration
jump = self.data_size // self.batch_size
batch_index = [(i * jump + self.iteration) % self.data_size for i in
range(self.batch_size)]
batch_x = [self.dataset[0][i] for i in batch_index]
batch_t = [self.dataset[1][i] for i in batch_index]
if self.reverse:
batch_x = [line[::-1] for line in batch_x]
x = torch.tensor(batch_x, device=device)
t = torch.tensor(batch_t, device=device)
self.iteration += 1
return x, t
<file_sep>from sklearn.model_selection import train_test_split
from janome.tokenizer import Tokenizer
import torch
from utils import *
class LyricDataset(torch.utils.data.Dataset):
def __init__(self, file_path, edited_file_path, transform=None):
self.file_path = file_path
self.edited_file_path = edited_file_path
self.tokenizer = Tokenizer(wakati=True)
self.input_lines = [] # NNの入力となる配列(それぞれの要素はテキスト)
self.output_lines = [] # NNの正解データとなる配列(それぞれの要素はテキスト)
self.word2id = {} # e.g.) {'word0': 0, 'word1': 1, ...}
self.input_data = [] # 一単語一単語がID化された歌詞の一節
self.output_data = [] # 一単語一単語がID化された次の一節
self.word_num_max = None
self.transform = transform
self._no_brank()
def prepare(self):
# NNの入力となる配列(テキスト)とNNの正解データ(テキスト)となる配列を返す
self.get_text_lines()
# date.txtで登場するすべての文字にIDを割り当てる
for line in self.input_lines + self.output_lines: # 最初の一節とそれ以降の一節
self.get_word2id(line)
# 一節の単語数の最大値を求める
self.get_word_num_max()
# NNの入力となる配列(ID)とNNの正解データ(ID)となる配列を返す
for input_line, output_line in zip(self.input_lines, self.output_lines):
self.input_data.append([self.word2id[word] for word in self.line2words(input_line)] \
+ [self.word2id[" "] for _ in range(self.word_num_max - len(self.line2words(input_line)))])
self.output_data.append([self.word2id[word] for word in self.line2words(output_line)] \
+ [self.word2id[" "] for _ in range(self.word_num_max - len(self.line2words(output_line)))])
def _no_brank(self):
# 行の間の空白を取る
with open(self.file_path, "r") as fr, open(self.edited_file_path, "w") as fw:
for line in fr.readlines():
if isAlpha(line) or line == "\n":
continue # 英字と空白は飛ばす
fw.write(line)
def get_text_lines(self, to_file=True):
"""
空行なしの歌詞ファイルのパスfile_pathを受け取り、次のような配列を返す
"""
# 米津玄師_lyrics.txtを1行ずつ読み込んで「歌詞の一節」と「次の一節」に分割して、inputとoutputで分ける
with open(self.edited_file_path, "r") as f:
line_list = f.readlines() # 歌詞の一節...line
line_num = len(line_list)
for i, line in enumerate(line_list):
if i == line_num - 1:
continue # 最後は「次の一節」がない
self.input_lines.append(line.replace("\n", ""))
self.output_lines.append("_" + line_list[i+1].replace("\n", ""))
if to_file:
with open(self.edited_file_path, "w") as f:
for input_line, output_line in zip(self.input_lines, self.output_lines):
f.write(input_line + " " + output_line + "\n")
def line2words(self, line: str) -> list:
word_list = [token for token in self.tokenizer.tokenize(line)]
return word_list
def get_word2id(self, line: str) -> dict:
word_list = self.line2words(line)
for word in word_list:
if not word in self.word2id.keys():
self.word2id[word] = len(self.word2id)
def get_word_num_max(self):
# 長さが最大のものを求める
word_num_list = []
for line in self.input_lines + self.output_lines:
word_num_list.append(len([self.word2id[word] for word in self.line2words(line)]))
self.word_num_max = max(word_num_list)
def __len__(self):
return len(self.input_data)
def __getitem__(self, idx):
out_data = self.input_data[idx]
out_label = self.output_data[idx]
if self.transform:
out_data = self.transform(out_data)
return out_data, out_label
<file_sep>from datasets import LyricDataset
import torch
import torch.optim as optim
from modules import *
from device import device
from utils import *
from dataloaders import SeqDataLoader
import math
import os
from utils
# ==========================================
# データ用意
# ==========================================
# 米津玄師_lyrics.txtのパス
file_path = "lyric/米津玄師_lyrics.txt"
edited_file_path = "lyric/米津玄師_lyrics_edit.txt"
yonedu_dataset = LyricDataset(file_path, edited_file_path)
yonedu_dataset.prepare()
# check
print(yonedu_dataset[0])
# 8:2でtrainとtestに分ける
train_rate = 0.8
data_num = len(yonedu_dataset)
train_set = yonedu_dataset[:math.floor(data_num * train_rate)]
test_set = yonedu_dataset[math.floor(data_num * train_rate):]
# ================================================
# ハイパーパラメータ設定 / モデル / 損失関数 / 最適化方法
# ================================================
embedding_dim = 200
hidden_dim = 128
BATCH_NUM = 100
EPOCH_NUM = 100
vocab_size = len(yonedu_dataset.word2id) # 語彙数
padding_idx = yonedu_dataset.word2id[" "] # 空白のID
# モデル
encoder = Encoder(vocab_size, embedding_dim, hidden_dim, padding_idx).to(device)
attn_decoder = AttentionDecoder(vocab_size, embedding_dim, hidden_dim, BATCH_NUM, padding_idx).to(device)
# 損失関数
criterion = nn.CrossEntropyLoss()
# 最適化方法
encoder_optimizer = optim.Adam(encoder.parameters(), lr=0.001)
attn_decoder_optimizer = optim.Adam(attn_decoder.parameters(), lr=0.001)
# 学習済みモデルがあれば,パラメータをロード
encoder_weights_path = "yonedsu_lyric_encoder.pth"
decoder_weights_path = "yonedsu_lyric_decoder.pth"
if os.path.exists(encoder_weights_path):
encoder.load_state_dict(torch.load(encoder_weights_path))
if os.path.exists(decoder_weights_path):
attn_decoder.load_state_dict(torch.load(decoder_weights_path))
# ================================================
# 学習
# ================================================
all_losses = []
print("training ...")
for epoch in range(1, EPOCH_NUM+1):
epoch_loss = 0
# データをミニバッチに分ける
dataloader = SeqDataLoader(train_set, batch_size=BATCH_NUM, shuffle=False)
for train_x, train_y in dataloader:
# 勾配の初期化
encoder_optimizer.zero_grad()
attn_decoder_optimizer.zero_grad()
# Encoderの順伝搬
hs, h = encoder(train_x)
# Attention Decoderのインプット
source = train_y[:, :-1]
# Attention Decoderの正解データ
target = train_y[:, 1:]
loss = 0
decoder_output, _, attention_weight = attn_decoder(source, hs, h)
for j in range(decoder_output.size()[1]):
loss += criterion(decoder_output[:, j, :], target[:, j])
epoch_loss += loss.item()
# 誤差逆伝播
loss.backward()
# パラメータ更新
encoder_optimizer.step()
attn_decoder_optimizer.step()
# 損失を表示
print("Epoch %d: %.2f" % (epoch, epoch_loss))
all_losses.append(epoch_loss)
if epoch_loss < 0.1: break
print("Done")
import matplotlib.pyplot as plt
plt.plot(all_losses)
plt.savefig("attn_loss.png")
# モデル保存
torch.save(encoder.state_dict(), encoder_weights_path)
torch.save(attn_decoder.state_dict(), decoder_weights_path)
# =======================================
# テスト
# =======================================
# 単語 -> ID 変換の辞書
word2id = yonedu_dataset.word2id
# ID -> 単語 変換の辞書
id2word = get_id2word(word2id)
# 一つの正解データの要素数
output_len = len(yonedu_dataset[0][1])
# 評価用データ
test_dataloader = SeqDataLoader(test_set, batch_size=BATCH_NUM, shuffle=False)
# 結果を表示するデータフレーム
df = pd.DataFrame(None, columns=["input", "answer", "predict", "judge"])
# データローダーを回して、結果を表示するデータフレームに値を入れる
for test_x, test_y in test_dataloader:
with torch.no_grad():
hs, encoder_state = encoder(test_x)
# Decoderにはまず文字列生成開始を表す"_"をインプットにするので、
# "_"のtensorをバッチサイズ分作成
start_char_batch = [[word2id["_"]] for _ in range(BATCH_NUM)]
decoder_input_tensor = torch.tensor(start_char_batch, device=device)
decoder_hidden = encoder_state
batch_tmp = torch.zeros(100,1, dtype=torch.long, device=device)
for _ in range(output_len - 1):
decoder_output, decoder_hidden, _ = attn_decoder(decoder_input_tensor, hs, decoder_hidden)
# 予測文字を取得しつつ、そのまま次のdecoderのインプットとなる
decoder_input_tensor = get_max_index(decoder_output.squeeze(), BATCH_NUM)
batch_tmp = torch.cat([batch_tmp, decoder_input_tensor], dim=1)
predicts = batch_tmp[:,1:] # 予測されたものをバッチごと受け取る
if test_dataloader.reverse:
test_x = [list(line)[::-1] for line in test_x] # 反転されたものをもどす
df = predict2df(test_x, test_y, predicts, df)
df.to_csv("predict_yonedsu_lyric.csv", index=False)
<file_sep>import re
from sklearn.utils import shuffle
import pandas as pd
import torch
from device import device
def isAlpha(value):
"""
半角英字チェック
:param value: チェック対象の文字列
:rtype: チェック対象文字列が、全て半角英字の場合 True
"""
return re.compile('[a-z]+').search(value) is not None
def get_id2word(word2id: dict) -> dict:
"""
予測結果を見る際にIDのままだと可読性が悪いので、
もとの文字列に復元するためのID→文字列に変換する辞書を定義
"""
id2word = {}
for word, key_id in word2id.items():
id2word[key_id] = word
return id2word
def predict2df(test_x: torch.tensor, test_y: torch.tensor,
predict: list, df: pd.DataFrame, id2word: dict) -> pd.DataFrame:
"""
結果をデータフレームに表示する関数
引数であるdfに結果を追加していく
@param test_x: テストで入力テキストとしたデータ
@param test_y: テストで正解テキストとしたデータ
@param predict: テストでencoderが出力したデータ
@param df: テスト結果を表示するデータフレーム (column = ["入力", "答え", "予測結果", "正解か否か"])
@param id2word: ID -> 単語 変換の辞書
@return テスト結果を表示するデータフレーム(結果追加後)
"""
row = []
for i in range(len(test_x)):
batch_input = test_x[i]
batch_output = test_y[i]
batch_predict = predict[i]
x = [id2word[int(idx)] for idx in batch_input]
y = [id2word[int(idx)] for idx in batch_output[1:]]
p = [id2word[int(idx)] for idx in batch_predict]
x_str = "".join(x)
y_str = "".join(y)
p_str = "".join(p)
judge = "O" if y_str == p_str else "X"
row.append([x_str, y_str, p_str, judge])
predict_df = pd.DataFrame(row, columns=["input", "answer", "predict", "judge"])
df = pd.concat([df, predict_df])
return df
def get_max_index(decoder_output: torch.tensor, batch_num: int) -> torch.tensor:
"""
Decoderのアウトプットのテンソルから要素が最大のインデックスを返す。つまり生成文字を意味する
@param decoder_output: Decoderのアウトプットのテンソル
@param batch_num: バッチサイズ
@return: Decoderのアウトプットのテンソルにおいて、要素が最大のインデックス
"""
results = []
for h in decoder_output:
results.append(torch.argmax(h))
return torch.tensor(results, device=device).view(batch_num, 1)
| 5a539d7ec3971f65a7ba0ee793caf4ddfae133c6 | [
"Markdown",
"Python"
] | 7 | Markdown | daiki-noguchi/yonedsu_lyric | 482a03d3edadf7a5c4e05c0c7ba36eb4665b4f7b | 80ef72a1a798efafad1042c4fda739af82c2db5a |
refs/heads/master | <file_sep>package dany.caro.loginkotlin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btnEntrar.setOnClickListener{
val user = etNombre.text.toString()
val pass = etPass.text.toString()
if (user.equals("") or pass.equals("")){
mensaje( "Datos vacios", Toast.LENGTH_LONG)
}else{
if(user.equals("daniel") and pass.equals("<PASSWORD>")){
val i = Intent(this, segundaActivity::class.java)
i.putExtra("Nombre", "daniel")
startActivity(i)
}else{
mensaje ( "no te conozco jajajaja")
}
}
}
}
override fun onStart() {
super.onStart()
Log.wtf("ejemplo", "debo de estar en el")
}
fun mensaje(mensaje:String,dur:Int=Toast.LENGTH_SHORT){
Toast.makeText( this, mensaje,dur).show()
}
}
| 11ac28c919837a85f395339236664550a86eb95e | [
"Kotlin"
] | 1 | Kotlin | danyca13/LoginKotlin2 | 33af29df52664765129af669ea79a8e39a08dfc1 | eb6019fed6766dfb38f3af5c04769e3cffc232f5 |
refs/heads/master | <file_sep>Это моя первая игра, написанная на Ruby :))
<file_sep># Моя первая игра на Ruby
str = "Вас приветствует игра ◄◄◄ ОДНОРУКИЙ БАНДИТ ►►► "
timer = ". "
1.times do
str.size.times do |x|
print str[x]
#d = (1 + rand(50)).to_f / 100
sleep 0.2
print ""
end
puts ""
puts "Автор: <NAME> ©2019"
sleep 4
print "Пять секунд до запуска "
1.upto(5) do
print timer
sleep 1
end
puts ""
end
puts "Внимание!!! Вам должно быть 18 лет и старше!!!"
print "Сколько вам лет? "
a = gets.to_i
print "Хотите играть? (Yes/No): "
b = gets.strip.capitalize
if a >= 18 && b == "Y"
puts "Хорошо, мы поиграем!"
sleep 2
puts "777 - Джекпот!!! 1000 000$!!!"
sleep 2
puts "000 - ЗЕРО... Вы проиграите все деньги."
sleep 2
print "Сколько денег вы хотите положить на свой счет?: "
money = gets.to_i
puts "═══════════════════"
puts "На вашем счету #{money}$."
puts "═══════════════════"
1.upto(1000000) do
puts "Нажмите Enter чтобы дернуть ручку » » »"
gets
x = rand(0..9)
y = rand(0..9)
z = rand(0..9)
if x == 1 && y == 1 && z == 1
puts " ╔═════════╗"
puts "Выпало ║ ♥ 111 ♥ ║ » » » Вы заработали 10$ !!!"
puts " ╚═════════╝"
money = money + 10
puts "═══════════════════"
puts "На вашем счету #{money}$."
puts "═══════════════════"
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$ !!! До новых встреч!!!")
end
elsif x == 2 && y == 2 && z == 2
puts " ╔═════════╗"
puts "Выпало ║ ♥ 222 ♥ ║ » » » Вы заработали 20$ !!!"
puts " ╚═════════╝"
money = money + 20
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$!!! До новых встреч!!!")
end
elsif x == 3 && y == 3 && z == 3
puts " ╔═════════╗"
puts "Выпало ║ ♥ 333 ♥ ║ » » » Вы заработали 30$ !!!"
puts " ╚═════════╝"
money = money + 30
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$ !!! До новых встреч!!!")
end
elsif x == 4 && y == 4 && z == 4
puts " ╔═════════╗"
puts "Выпало ║ ♥ 444 ♥ ║ » » » Вы заработали 40$ !!!"
puts " ╚═════════╝"
money = money + 40
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$ !!! До новых встреч!!!")
end
elsif x == 5 && y == 5 && z == 5
puts " ╔═════════╗"
puts "Выпало ║ ♥ 555 ♥ ║ » » » Вы заработали 50$ !!!"
puts " ╚═════════╝"
money = money + 50
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$ !!! До новых встреч!!!")
end
elsif x == 6 && y == 6 && z == 6
puts " ╔═════════╗"
puts "Выпало ║ ♥ 666 ♥ ║ » » » Вы заработали 60$ !!!"
puts " ╚═════════╝"
money = money + 60
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$!!! До новых встреч!!!")
end
elsif x == 7 && y == 7 && z == 7
puts " ╔═════════╗"
puts "Выпало ║ ♥ 777 ♥ ║ » » » Д Ж Е К П О Т !!!"
puts " ╚═════════╝"
money = 1000000
puts "Вы победитель !!! На вашем счету #{money}$."
exit
elsif x == 8 && y == 8 && z == 8
puts " ╔═════════╗"
puts "Выпало ║ ♥ 888 ♥ ║ » » » Вы заработали 80$ !!!"
puts " ╚═════════╝"
money = money + 80
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$!!! До новых встреч!!!")
end
elsif x == 9 && y == 9 && z == 9
puts " ╔═════════╗"
puts "Выпало ║ ♥ 999 ♥ ║ » » » Вы заработали 90$ !!!"
puts " ╚═════════╝"
money = money + 90
puts "На вашем счету #{money}$."
print "Вы хотите продолжать? (Enter/No): "
answer = gets.strip.capitalize
if answer == "N"
abort("Сегодня вы выиграли #{money}$!!! До новых встреч!!!")
end
elsif x == 0 && y == 0 && z == 0
puts " ╔═════════╗"
puts "Выпало ║ ♥ 000 ♥ ║ » » » Тройное ЗЕРО !!!"
puts " ╚═════════╝"
money = 0
if money == 0
abort("Вы проиграли...")
end
else
puts " ╔═════════╗"
puts "Выпало ║ ♠ #{x}#{y}#{z} ♠ ║ » » » Минус 1$ !!!"
puts " ╚═════════╝"
money = money - 1
puts "═══════════════════"
puts "На вашем счету #{money}$."
puts "═══════════════════"
end
if money == 10
abort("У тебя осталось 10$. Оставь себе на такси, приятель.")
end
end
elsif a >= 18 && b == "N"
puts "Не хочешь, как хочешь!"
elsif a <= 18 && b == "N"
puts "Ты прав! Ты еще слишком мал!!!"
else
puts "Ты слишком мал для таких игр!"
end
| 5f823a1ca1c51d57495e215368338df5d9d22f48 | [
"Markdown",
"Ruby"
] | 2 | Markdown | stigmat-svo/OB | 304af249ee130397d5cd80d8eec7c2dcdc144705 | 6f877f58c403fd67606755abbdb26f17abecc052 |
refs/heads/master | <file_sep>import Vue from 'vue'
import Router from 'vue-router'
import Store from '@/store'
import Main from '~@/main/'
// users
import SignUp from '~@/users/signUp'
import SignIn from '~@/users/signIn'
Vue.use(Router)
const LOGIN_ONLY = (to, from, next) => {
Store.dispatch('updateUserInfo')
.finally(() => {
if(!Store.getters.isLogin) {
next({ name: 'SingIn', params: { ...to.params, refName: to.name }});
} else {
next();
}
})
};
const NOT_LOGIN_ONLY = (to, from, next) => {
Store.dispatch('updateUserInfo')
.finally(() => {
if(Store.getters.isLogin) {
next({ name: 'Main' });
} else {
next();
}
})
};
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
path: '/SignUp',
name: 'SingUp',
component: SignUp,
beforeEnter: NOT_LOGIN_ONLY
},
{
path: '/SignIn',
name: 'SingIn',
component: SignIn,
beforeEnter: NOT_LOGIN_ONLY
}
]
})
<file_sep>import Vue from 'vue';
export const globalEvent = new Vue();<file_sep>import Vue from 'vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
import App from './App.vue'
import router from './router'
import store from './store'
import firebase from 'firebase'
import axios from 'axios'
import _ from 'lodash'
Vue.config.productionTip = false
Vue.use(Antd)
Vue.prototype.$http = axios
var config = {
apiKey: '<KEY>',
authDomain: 'vue-example1.firebaseapp.com',
databaseURL: 'https://vue-example1.firebaseio.com',
projectId: 'vue-example1',
storageBucket: 'vue-example1.appspot.com',
messagingSenderId: '686205830736'
}
firebase.initializeApp(config)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app') | 38b7a53b8e3510c1692bc0e138407a2f36754a1b | [
"JavaScript"
] | 3 | JavaScript | ldc84/vue-project-1 | 098132a7b630aa36729dd066af321c33c521e18e | 8135606eaeef96553763994d6ad0ea83bb2b66ad |
refs/heads/master | <file_sep># SpotkajmySie
Aplikacja służy do przedstawiania propozycji możliwych terminów spotkań na podstawie kalendarzy dwóch osób. Aplikacja przyjmuje na wejściu dwa kalendarze które zostają podzielone na zbiory rozpoczęcia oraz zakończenia planowanych spotkań. Następnie zostają posortowane oraz połączone te które się pokrywają. Program zwraca zakresy w których można zorganizować spotkanie.
W celu sprawdzenia aplikacji należy uruchomić MeetingTest.java.
<file_sep>package pjarosz;
import lombok.*;
import java.time.LocalDateTime;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Hour implements Comparable<Hour> {
LocalDateTime start;
LocalDateTime end;
public void setStart(String start) {
this.start = changeStringToLocalDateTime(start);
}
public void setEnd(String end) {
this.end = changeStringToLocalDateTime(end);
}
private LocalDateTime changeStringToLocalDateTime(String start) {
String[] split = start.split(":");
return LocalDateTime.of(2021, 3, 7, Integer.parseInt(split[0]), Integer.parseInt(split[1]));
}
public int compareTo(Hour o) {
if (this.start.isBefore(o.getStart())) {
return -1;
}
if (this.start.isAfter(o.getStart())) {
return 1;
} else {
return 0;
}
}
}
<file_sep>package pjarosz;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class MeetingTest {
@Test
void shouldReturnFreeTimePeriodsIncludingMeetingDuration() {
//given
String json1 = "{ \"working_hours\" : { \"start\" : \"09:00\", \"end\" : \"19:55\" }, \"planned_meeting\" : [ { \"start\" : \"09:00\", \"end\" : \"10:30\" }, { \"start\" : \"12:00\", \"end\" : \"13:00\" }, { \"start\" : \"16:00\", \"end\" : \"18:00\" } ] }";
String json2 = "{ \"working_hours\" : { \"start\" : \"10:00\", \"end\" : \"18:30\" }, \"planned_meeting\" : [ { \"start\" : \"10:00\", \"end\" : \"11:30\" }, { \"start\" : \"12:30\", \"end\" : \"14:30\" }, { \"start\" : \"14:30\", \"end\" : \"15:00\" }, { \"start\" : \"16:00\", \"end\" : \"17:00\" } ] }";
String meetingDurationString = "00:30";
String expectingResult = "[[\"11:30\", \"12:00\"], [\"15:00\", \"16:00\"], [\"18:00\", \"18:30\"]]";
//when
String meetingHours = Meeting.getMeetingHours(json1, json2, meetingDurationString);
//then
Assertions.assertEquals(expectingResult, meetingHours);
}
}
<file_sep>package pjarosz;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
public class Meeting {
private static final ObjectMapper objectMapper = new ObjectMapper();
public static String getMeetingHours(String json1, String json2, String plannedMeetingDuration) {
int meetingDurationMinutes = getMeetingDurationMinutes(plannedMeetingDuration);
Calendar calendar1 = new Calendar();
Calendar calendar2 = new Calendar();
try {
calendar1 = objectMapper.readValue(json1, Calendar.class);
calendar2 = objectMapper.readValue(json2, Calendar.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
List<LocalDateTime> startWork = List.of(calendar1.getWorking_hours().start, calendar2.getWorking_hours().start);
List<LocalDateTime> endWork = List.of(calendar1.getWorking_hours().end, calendar2.getWorking_hours().end);
LocalDateTime startWorkingDay = Collections.max(startWork);
LocalDateTime endWorkingDay = Collections.min(endWork);
Set<Hour> hourSet = new TreeSet<>(calendar1.getPlanned_meeting());
hourSet.addAll(calendar2.getPlanned_meeting());
List<Hour> freeTimesPeriods = getFreeTimePeriods(hourSet, startWorkingDay, endWorkingDay);
List<Hour> freeTimePeriodsIncludingMeetingDuration = getFreeTimePeriodsIncludingMeetingDuration(meetingDurationMinutes, freeTimesPeriods);
return getOutputString(freeTimePeriodsIncludingMeetingDuration);
}
private static List<Hour> getFreeTimePeriods(Set<Hour> hourSet, LocalDateTime startWorkingDay, LocalDateTime endWorkingDay) {
List<Hour> hourList = new ArrayList<>(hourSet);
deleteRangeWhenAnotherRangeIncludesIt(hourList);
List<Hour> freeTimePeriods = new ArrayList<>();
LocalDateTime startRange = null;
LocalDateTime endRange = null;
for (int i = 0; i < hourList.size(); i++) {
if (i == 0 && startWorkingDay.isBefore(hourList.get(i + 1).getStart()) && hourList.get(i).getEnd().isAfter(hourList.get(i + 1).getEnd())) {
freeTimePeriods.add(new Hour(startWorkingDay, hourList.get(i).getStart()));
}
if (startRange == null) {
startRange = hourList.get(i).getStart();
endRange = hourList.get(i).getEnd();
}
if (i == hourList.size() - 1 && endRange.isBefore(endWorkingDay)) {
Hour h = new Hour(endRange, endWorkingDay);
freeTimePeriods.add(h);
} else {
if (endRange.isBefore(hourList.get(i + 1).getStart())) {
Hour h = new Hour(hourList.get(i).getEnd(), hourList.get(i + 1).getStart());
freeTimePeriods.add(h);
startRange = null;
endRange = null;
} else {
if (endRange.isBefore(hourList.get(i + 1).getEnd())) {
endRange = hourList.get(i + 1).getEnd();
}
}
}
}
return freeTimePeriods;
}
private static List<Hour> getFreeTimePeriodsIncludingMeetingDuration(int meetingDurationMinutes, List<Hour> freeTimesPeriods) {
List<Hour> collect = freeTimesPeriods.stream()
.filter(hour -> {
long freeTimeDuration = Duration.between(hour.start, hour.end).toMinutes();
return freeTimeDuration >= meetingDurationMinutes;
})
.collect(Collectors.toList());
return collect;
}
private static int getMeetingDurationMinutes(String plannedMeetingDuration) {
String[] split = plannedMeetingDuration.split(":");
return Integer.parseInt(split[0]) * 60 + Integer.parseInt(split[1]);
}
private static String getOutputString(List<Hour> collect) {
StringBuilder outputString = new StringBuilder("[");
for (int i = 0; i < collect.size(); i++) {
outputString.append(getOutputStringFormat(collect.get(i)));
if (i == collect.size() - 1) {
outputString.append("]");
} else {
outputString.append(", ");
}
}
return outputString.toString();
}
private static String getOutputStringFormat(Hour h) {
return "[\"" + addZeroBeforePartOfDate(h.getStart().getHour()) + ":" +
addZeroBeforePartOfDate(h.getStart().getMinute()) + "\", \"" +
addZeroBeforePartOfDate(h.getEnd().getHour()) + ":" +
addZeroBeforePartOfDate(h.getEnd().getMinute()) + "\"]";
}
private static String addZeroBeforePartOfDate(int datePart) {
String datePartString = datePart + "";
if (datePart < 10) {
datePartString = "0" + datePartString;
}
return datePartString;
}
public static void deleteRangeWhenAnotherRangeIncludesIt(List<Hour> hours) {
for (int i = 0; i < hours.size() - 1; i++) {
for (int j = i + 1; j < hours.size(); j++) {
if (hours.get(i).getStart().isBefore(hours.get(j).getStart()) &&
hours.get(i).getEnd().isAfter(hours.get(j).getEnd())) {
hours.remove(j);
break;
}
}
}
}
}
| afa7b14fcefdaa02db0df54cae32085fca7e0501 | [
"Markdown",
"Java"
] | 4 | Markdown | JaroszPatryk/SpotkajmySie | 83737e0b08f816521ee8fe0d5cc558a930d5f283 | 8b2970a12614ec9147d26a8885fb6d87918b8ca0 |
refs/heads/master | <repo_name>rainmodred/typical-arrays-problems<file_sep>/src/index.js
function isValidArray(array) {
if (array === undefined || array.length === 0) {
return false;
}
return true;
}
exports.min = function min(array) {
if (!isValidArray(array)) {
return 0;
}
return Math.min(...array);
};
exports.max = function max(array) {
if (!isValidArray(array)) {
return 0;
}
return Math.max(...array);
};
exports.avg = function avg(array) {
if (!isValidArray(array)) {
return 0;
}
let sum = array.reduce((accum, current) => accum + current, 0);
return sum / array.length;
};
| 32a24e40f716892d8c35ce8e12c99a1932ca3efa | [
"JavaScript"
] | 1 | JavaScript | rainmodred/typical-arrays-problems | 61f17aafa69d4012571cbdafd5b4d26d49c8f150 | cd760baa2554bae5fd4744c518225a8351932d8b |
refs/heads/master | <repo_name>steveWinter/OneupUploaderBundle<file_sep>/Uploader/File/FilesystemFile.php
<?php
namespace Oneup\UploaderBundle\Uploader\File;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Kernel;
class FilesystemFile extends UploadedFile implements FileInterface
{
public function __construct(File $file)
{
if ($file instanceof UploadedFile) {
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getSize(), $file->getError(), true);
} else {
parent::__construct($file->getPathname(), $file->getClientOriginalName(), $file->getClientMimeType(), $file->getError(), true);
}
} else {
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), $file->getSize(), 0, true);
} else {
parent::__construct($file->getPathname(), $file->getBasename(), $file->getMimeType(), 0, true);
}
}
}
public function getExtension()
{
return $this->getClientOriginalExtension();
}
}
<file_sep>/Tests/UploadEventsTest.php
<?php
namespace Oneup\UploaderBundle\Tests;
use Oneup\UploaderBundle\UploadEvents;
use PHPUnit\Framework\TestCase;
class UploadEventsTest extends TestCase
{
public function testPreUploadCanBePassedAMapping()
{
$event = UploadEvents::preUpload('gallery');
$this->assertEquals(UploadEvents::PRE_UPLOAD . '.gallery', $event);
}
public function testPostUploadCanBePassedAMapping()
{
$event = UploadEvents::postUpload('gallery');
$this->assertEquals(UploadEvents::POST_UPLOAD . '.gallery', $event);
}
public function testPostPersistCanBePassedAMapping()
{
$event = UploadEvents::postPersist('gallery');
$this->assertEquals(UploadEvents::POST_PERSIST . '.gallery', $event);
}
public function testPostChunkUploadCanBePassedAMapping()
{
$event = UploadEvents::postChunkUpload('gallery');
$this->assertEquals(UploadEvents::POST_CHUNK_UPLOAD . '.gallery', $event);
}
public function testValidationCanBePassedAMapping()
{
$event = UploadEvents::validation('gallery');
$this->assertEquals(UploadEvents::VALIDATION . '.gallery', $event);
}
}
<file_sep>/Command/ClearOrphansCommand.php
<?php
namespace Oneup\UploaderBundle\Command;
use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class ClearOrphansCommand extends Command
{
protected static $defaultName = 'oneup:uploader:clear-orphans'; // Make command lazy load
/** @var OrphanageManager */
protected $manager;
public function __construct(OrphanageManager $manager, ?string $name = null)
{
parent::__construct($name);
$this->manager = $manager;
}
protected function configure()
{
$this
->setName(self::$defaultName) // BC with 2.7
->setDescription('Clear orphaned uploads according to the max-age you defined in your configuration.')
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->manager->clear();
}
}
<file_sep>/Tests/Controller/FineUploaderValidationTest.php
<?php
namespace Oneup\UploaderBundle\Tests\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Kernel;
class FineUploaderValidationTest extends AbstractValidationTest
{
protected function getConfigKey()
{
return 'fineuploader_validation';
}
protected function getRequestParameters()
{
return [];
}
protected function getOversizedFile()
{
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
return new UploadedFile(
$this->createTempFile(512),
'cat.ok',
'text/plain',
512
);
}
return new UploadedFile(
$this->createTempFile(512),
'cat.ok',
'text/plain'
);
}
protected function getFileWithCorrectMimeType()
{
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
return new UploadedFile(
$this->createTempFile(128),
'cat.txt',
'text/plain',
128
);
}
return new UploadedFile(
$this->createTempFile(128),
'cat.txt',
'text/plain'
);
}
protected function getFileWithCorrectMimeTypeAndIncorrectExtension()
{
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
return new UploadedFile(
$this->createTempFile(128),
'cat.txxt',
'text/plain',
128
);
}
return new UploadedFile(
$this->createTempFile(128),
'cat.txxt',
'text/plain'
);
}
protected function getFileWithIncorrectMimeType()
{
// TODO at EOL of SF 3.4 this can be removed
if(Kernel::VERSION_ID < 40400) {
return new UploadedFile(
$this->createTempFile(128),
'cat.ok',
'image/gif',
128
);
}
return new UploadedFile(
$this->createTempFile(128),
'cat.ok',
'image/gif'
);
}
}
| 2630e076cfda690baa30387226cd5d0213ac8fc9 | [
"PHP"
] | 4 | PHP | steveWinter/OneupUploaderBundle | f800365c33f8ba7a5fd7542967c2303dad74c542 | bcaf7411c2bbc60dad539195ddd04a5b57954b29 |
refs/heads/main | <file_sep>var savedUserInput = prompt ( "hello" ) ;
console. log(savedUserInput) ;
document.getElementById("username") .innerText = savedUserInput;
//tooltip
$(function () {
$('[data-toggle="tooltip"]').tooltip()
}) | b4291c4534c2178295e5f2fea1410c33ded643ac | [
"JavaScript"
] | 1 | JavaScript | NourrKhalil/web-design- | beb82d4b7af266cb08fe1ed85c814c2c8e0bf0b6 | 2cd3c3c847cede517b80073afa60a05e8d72cb6a |
refs/heads/master | <file_sep>package com.example.miguelvzz.datospersonales;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
final Calendar fecha_actual = Calendar.getInstance();
int anio;
int mes;
int dia;
static final int DIALOG_ID = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_siguiente = (Button) findViewById(R.id.btn_siguiente);
btn_siguiente.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DetalleContacto.class);
//intent.putExtra("Nombre", et_nombre.getText().toString());
intent.putExtra(getResources().getString(R.string.et_nombre), ((EditText) findViewById(R.id.et_nombre)).getText().toString());
intent.putExtra(getResources().getString(R.string.et_fec_naci),((EditText) findViewById(R.id.et_fec_nacimiento)).getText().toString());
intent.putExtra(getResources().getString(R.string.et_telefono), ((EditText) findViewById(R.id.et_telefono)).getText().toString());
intent.putExtra(getResources().getString(R.string.et_email), ((EditText) findViewById(R.id.et_email)).getText().toString());
intent.putExtra(getResources().getString(R.string.et_descrip), ((EditText) findViewById(R.id.et_desc)).getText().toString());
startActivity(intent);
finish();
}
});
Bundle parametros = getIntent().getExtras();
if(parametros != null) {
((TextView) findViewById(R.id.et_nombre)).setText(parametros.getString(getResources().getString(R.string.et_nombre)));
((TextView) findViewById(R.id.et_fec_nacimiento)).setText(parametros.getString(getResources().getString(R.string.et_fec_naci)));
((TextView) findViewById(R.id.et_telefono)).setText(parametros.getString(getResources().getString(R.string.et_telefono)));
((TextView) findViewById(R.id.et_email)).setText(parametros.getString(getResources().getString(R.string.et_email)));
((TextView) findViewById(R.id.et_desc)).setText(parametros.getString(getResources().getString(R.string.et_descrip)));
}
anio = fecha_actual.get(Calendar.YEAR);
mes = fecha_actual.get(Calendar.MONTH) + 1;
dia = fecha_actual.get(Calendar.DAY_OF_MONTH);
final String fecha = dia + "/" + mes + "/" + anio;
((EditText) findViewById(R.id.et_fec_nacimiento)).setText(fecha);
mostrarDatePicker();
}
public void mostrarDatePicker(){
Button b_sfecha = (Button) findViewById(R.id.btn_fecha);
b_sfecha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDialog(DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_ID){
return new DatePickerDialog(this,R.style.Picker_fecha,datepickerListener, anio,mes,dia);
}
return null;
}
private DatePickerDialog.OnDateSetListener datepickerListener = new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){
anio = year;
mes = monthOfYear + 1;
dia = dayOfMonth;
String fecha1 = dia + "/" + mes + "/" + anio;
((EditText) findViewById(R.id.et_fec_nacimiento)).setText(fecha1);
}
};
}
| 95f06971dae0bafbc384bf14ae898fc42ec14b5d | [
"Java"
] | 1 | Java | miguel144a/Activities-Android | 446b5eb7b5f449543e7ef17e42742e2580d0bf5c | 95999a4f80307b8c0e4d07140098ba4376396d09 |
refs/heads/master | <file_sep>import pygame, sys
from pygame.locals import *
import random
pygame.init
windowSurface = pygame.display.set_mode((800, 600), 0, 32)
pygame.display.set_caption('game')
brown=(190,128,0)
black=(0,0,0)
green=(0,128,0)
blue=(0,0,255)
white=(255,255,255)
red=(255,0,0)
xtree1=[200,250,100,225,350]
ytree=[200,50,350]
x1=random.randint(0,3200)
x2=x1+50
x3=x1-100
x4=x1+25
x5=x1+150
xtree2=[x1,x2,x3,x4,x5]
x1=random.randint(0,3200)
x2=x1+50
x3=x1-100
x4=x1+25
x5=x1+150
xtree3=[x1,x2,x3,x4,x5]
x1=random.randint(0,3200)
x2=x1+50
x3=x1-100
x4=x1+25
x5=x1+150
xtree4=[x1,x2,x3,x4,x5]
x1=random.randint(0,3200)
x2=x1+50
x3=x1-100
x4=x1+25
x5=x1+150
xtree5=[x1,x2,x3,x4,x5]
orbx=400
pygame.draw.polygon(windowSurface, brown, ((xtree1[0],200), (xtree1[1],200), (xtree1[1],350), (xtree1[0],350)))
pygame.draw.polygon(windowSurface, green, ((xtree1[2],200), (xtree1[3],50), (xtree1[4],200)))
pygame.display.update()
motion=False
shooting=False
orbSize=0
def updateScreen(xtree1,ytree,orbSize,orbx,xtree2,xtree3,xtree4,xtree5,badGuyx,badGuyr):
windowSurface.fill(black)
pygame.draw.polygon(windowSurface, green, ((0,300),(0,600), (800,600), (800,300)))
pygame.draw.polygon(windowSurface, brown, ((xtree1[0],ytree[0]), (xtree1[1],ytree[0]), (xtree1[1],ytree[2]), (xtree1[0],ytree[2])))
pygame.draw.polygon(windowSurface, green, ((xtree1[2],ytree[0]), (xtree1[3],ytree[1]), (xtree1[4],ytree[0])))
pygame.draw.polygon(windowSurface, brown, ((xtree2[0],ytree[0]), (xtree2[1],ytree[0]), (xtree2[1],ytree[2]), (xtree2[0],ytree[2])))
pygame.draw.polygon(windowSurface, green, ((xtree2[2],ytree[0]), (xtree2[3],ytree[1]), (xtree2[4],ytree[0])))
pygame.draw.polygon(windowSurface, brown, ((xtree3[0],ytree[0]), (xtree3[1],ytree[0]), (xtree3[1],ytree[2]), (xtree3[0],ytree[2])))
pygame.draw.polygon(windowSurface, green, ((xtree3[2],ytree[0]), (xtree3[3],ytree[1]), (xtree3[4],ytree[0])))
pygame.draw.polygon(windowSurface, brown, ((xtree4[0],ytree[0]), (xtree4[1],ytree[0]), (xtree4[1],ytree[2]), (xtree4[0],ytree[2])))
pygame.draw.polygon(windowSurface, green, ((xtree4[2],ytree[0]), (xtree4[3],ytree[1]), (xtree4[4],ytree[0])))
pygame.draw.polygon(windowSurface, brown, ((xtree5[0],ytree[0]), (xtree5[1],ytree[0]), (xtree5[1],ytree[2]), (xtree5[0],ytree[2])))
pygame.draw.polygon(windowSurface, green, ((xtree5[2],ytree[0]), (xtree5[3],ytree[1]), (xtree5[4],ytree[0])))
pygame.draw.circle(windowSurface, blue, (orbx,300), orbSize, 0)
pygame.draw.circle(windowSurface, red, (badGuyx,300), badGuyr, 0)
pygame.draw.circle(windowSurface, white, (400,300), 5, 0)
pygame.display.update()
score=0
badShot=False
move=0
badGuyx=random.randint(0,3200)
badGuyr=1
badSpeed=1
while True:
if badShot==True:
badGuyx=random.randint(0,3200)
badGuyr=0
score+=1
if score>15:
badSpeed+=1
score=0
if orbSize==0:
shooting=False
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key == K_RIGHT:
motion=True
while motion==True:
if orbSize==0:
shooting=False
badGuyx-=1
if badGuyx==0:
badGuyx+=3450
xtree1[0]-=1
xtree1[1]-=1
xtree1[2]-=1
xtree1[3]-=1
xtree1[4]-=1
if xtree1[4]==0:
xtree1[0]+=3450
xtree1[1]+=3450
xtree1[2]+=3450
xtree1[3]+=3450
xtree1[4]+=3450
xtree2[0]-=1
xtree2[1]-=1
xtree2[2]-=1
xtree2[3]-=1
xtree2[4]-=1
if xtree2[4]==0:
xtree2[0]+=3450
xtree2[1]+=3450
xtree2[2]+=3450
xtree2[3]+=3450
xtree2[4]+=3450
xtree3[0]-=1
xtree3[1]-=1
xtree3[2]-=1
xtree3[3]-=1
xtree3[4]-=1
if xtree3[4]==0:
xtree3[0]+=3450
xtree3[1]+=3450
xtree3[2]+=3450
xtree3[3]+=3450
xtree3[4]+=3450
xtree4[0]-=1
xtree4[1]-=1
xtree4[2]-=1
xtree4[3]-=1
xtree4[4]-=1
if xtree4[4]==0:
xtree4[0]+=3450
xtree4[1]+=3450
xtree4[2]+=3450
xtree4[3]+=3450
xtree4[4]+=3450
xtree5[0]-=1
xtree5[1]-=1
xtree5[2]-=1
xtree5[3]-=1
xtree5[4]-=1
if xtree5[4]==0:
xtree5[0]+=3450
xtree5[1]+=3450
xtree5[2]+=3450
xtree5[3]+=3450
xtree5[4]+=3450
if shooting == True:
orbSize-=1
orbx-=1
move+=1
if move==40:
badGuyr+=badSpeed
move=0
updateScreen(xtree1,ytree,orbSize,orbx,xtree2,xtree3,xtree4,xtree5,badGuyx,badGuyr)
for event in pygame.event.get():
if event.type==KEYUP:
if event.key==K_RIGHT:
motion=False
if event.key == K_LEFT:
motion=True
while motion==True:
if orbSize==0:
shooting=False
badGuyx+=1
if badGuyx==3200:
badGuyx-=3450
xtree1[0]+=1
xtree1[1]+=1
xtree1[2]+=1
xtree1[3]+=1
xtree1[4]+=1
if xtree1[2]==3200:
xtree1[0]-=3450
xtree1[1]-=3450
xtree1[2]-=3450
xtree1[3]-=3450
xtree1[4]-=3450
xtree2[0]+=1
xtree2[1]+=1
xtree2[2]+=1
xtree2[3]+=1
xtree2[4]+=1
if xtree2[2]==3200:
xtree2[0]-=3450
xtree2[1]-=3450
xtree2[2]-=3450
xtree2[3]-=3450
xtree2[4]-=3450
xtree3[0]+=1
xtree3[1]+=1
xtree3[2]+=1
xtree3[3]+=1
xtree3[4]+=1
if xtree3[2]==3200:
xtree3[0]-=3450
xtree3[1]-=3450
xtree3[2]-=3450
xtree3[3]-=3450
xtree3[4]-=3450
xtree4[0]+=1
xtree4[1]+=1
xtree4[2]+=1
xtree4[3]+=1
xtree4[4]+=1
if xtree4[2]==3200:
xtree4[0]-=3450
xtree4[1]-=3450
xtree4[2]-=3450
xtree4[3]-=3450
xtree4[4]-=3450
xtree5[0]+=1
xtree5[1]+=1
xtree5[2]+=1
xtree5[3]+=1
xtree5[4]+=1
if xtree5[2]==3200:
xtree5[0]-=3450
xtree5[1]-=3450
xtree5[2]-=3450
xtree5[3]-=3450
xtree5[4]-=3450
if shooting == True:
orbSize-=1
orbx+=1
move+=1
if move==40:
badGuyr+=badSpeed
move=0
updateScreen(xtree1,ytree,orbSize,orbx,xtree2,xtree3,xtree4,xtree5,badGuyx,badGuyr)
for event in pygame.event.get():
if event.type==KEYUP:
if event.key==K_LEFT:
motion=False
if event.key == K_SPACE:
shooting=True
orbSize=100
orbx=400
if shooting == True:
orbSize-=1
badShot=False
move+=1
if move==50:
badGuyr+=badSpeed
move=0
if orbSize==badGuyr:
if badGuyx>350 and badGuyx<450:
badShot=True
if move>100:
move=0
updateScreen(xtree1,ytree,orbSize,orbx,xtree2,xtree3,xtree4,xtree5,badGuyx,badGuyr)
| 598a83ad9ec88a73afa53196c294073043013e71 | [
"Python"
] | 1 | Python | emenesesayc/first-pygame-game | 80c30e25fba661b4173f72875b98b6c296466c93 | 40a52a6e05b004733613e7b6be1fb7ab004cdd26 |
refs/heads/master | <file_sep>//
// SubscribeViewController.swift
// SubscriptionPrompt
//
// Created by <NAME> on 5/3/16.
// Copyright © 2016 binchik. All rights reserved.
//
import UIKit
public protocol SubscriptionViewControllerDelegate {
func subscriptionViewControllerRowTapped(atIndex index: Int)
func restoreButtonTapped()
}
@objc public protocol SubscriptionViewControllerStylingDelegate {
@objc optional func subscriptionViewControllerSlideStyle(atIndex index: Int) -> SlideStyle
@objc optional func subscriptionViewControllerOptionStyle(atIndex index: Int) -> OptionStyle
@objc optional func subscriptionViewControllerNotNowButtonStyle() -> OptionStyle
}
public final class SubscriptionViewController: UIViewController, SubscribeViewDelegate {
// MARK: - Styling
public var dimColor: UIColor = UIColor(white: 0, alpha: 0.5) {
didSet {
DispatchQueue.main.async {
self.view.backgroundColor = self.dimColor
}
}
}
public var dimView: UIView? {
didSet {
guard let dimView = dimView else { return }
dimView.translatesAutoresizingMaskIntoConstraints = false
DispatchQueue.main.async {
oldValue?.removeFromSuperview()
self.view.insertSubview(dimView, belowSubview: self.subscribeView)
[
NSLayoutConstraint(item: dimView, attribute: .leading,
relatedBy: .equal, toItem: self.view, attribute: .leading,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: dimView, attribute: .trailing,
relatedBy: .equal, toItem: self.view, attribute: .trailing,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: dimView, attribute: .top,
relatedBy: .equal, toItem: self.view, attribute: .top,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: dimView, attribute: .bottom,
relatedBy: .equal, toItem: self.view, attribute: .bottom,
multiplier: 1, constant: 0)
].forEach { $0.isActive = true }
}
}
}
public var titleFont: UIFont? {
didSet { self.subscribeView.titleFont = titleFont }
}
public var titleColor: UIColor? {
didSet { self.subscribeView.titleColor = titleColor }
}
// MARK: - Styling END
public var delegate: SubscriptionViewControllerDelegate?
public var stylingDelegate: SubscriptionViewControllerStylingDelegate? {
didSet { self.subscribeView.stylingDelegate = stylingDelegate }
}
public var restoreButtonTitle: String? {
didSet {
DispatchQueue.main.async {
self.restorePurchasesButton.setTitle(self.restoreButtonTitle, for: .normal)
}
}
}
public var options: [Option] {
didSet { subscribeView.options = options }
}
private var subscribeView: SubscribeView
private lazy var restorePurchasesButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = .systemFont(ofSize: 18)
button.addTarget(self, action: #selector(restoreButtonTapped), for: .touchUpInside)
return button
}()
private var constraintsSetUp = false
// MARK: - Init
public init(title: String? = nil, slides: [Slide], options: [Option],
cancelMessage: String? = nil, restoreButtonTitle: String? = nil) {
self.options = options
self.restoreButtonTitle = restoreButtonTitle
subscribeView = SubscribeView(title: title, slides: slides,
options: options, cancelMessage: cancelMessage)
super.init(nibName: nil, bundle: nil)
subscribeView.delegate = self
definesPresentationContext = true
providesPresentationContextTransitionStyle = true
modalPresentationStyle = .overCurrentContext
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View LifeCycle
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0, alpha: 0.5)
let restorePurchasesButtonOptional: UIButton? = restoreButtonTitle != nil ? restorePurchasesButton : nil
([subscribeView, restorePurchasesButtonOptional] as [UIView?])
.flatMap { $0 }
.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview($0)
}
setUpConstraints()
}
// MARK: - Public
public func animateDraggingToTheRight(duration: TimeInterval = 2) {
subscribeView.animateDraggingToTheRight(duration: duration)
}
// MARK: - Private
private func setUpConstraints() {
[
NSLayoutConstraint(item: subscribeView, attribute: .top,
relatedBy: .equal, toItem: view, attribute: .top,
multiplier: 1, constant: 40),
NSLayoutConstraint(item: subscribeView, attribute: .leading,
relatedBy: .equal, toItem: view, attribute: .leading,
multiplier: 1, constant: 20),
NSLayoutConstraint(item: subscribeView, attribute: .trailing,
relatedBy: .equal, toItem: view, attribute: .trailing,
multiplier: 1, constant: -20),
NSLayoutConstraint(item: restorePurchasesButton, attribute: .top,
relatedBy: .equal, toItem: subscribeView, attribute: .bottom,
multiplier: 1, constant: 20),
NSLayoutConstraint(item: restorePurchasesButton, attribute: .leading,
relatedBy: .equal, toItem: view, attribute: .leading,
multiplier: 1, constant: 8),
NSLayoutConstraint(item: restorePurchasesButton, attribute: .trailing,
relatedBy: .equal, toItem: view, attribute: .trailing,
multiplier: 1, constant: -8),
NSLayoutConstraint(item: restorePurchasesButton, attribute: .bottom,
relatedBy: .equal, toItem: view, attribute: .bottom,
multiplier: 1, constant: -10)
].forEach { $0.isActive = true }
}
@objc public func restoreButtonTapped() {
delegate?.restoreButtonTapped()
}
// MARK: - SubscriptionViewDelegate
public func rowTapped(atIndex index: Int) {
delegate?.subscriptionViewControllerRowTapped(atIndex: index)
}
}
<file_sep>//
// SubscribeView.swift
// SubscriptionPrompt
//
// Created by <NAME> on 4/28/16.
// Copyright © 2016 binchik. All rights reserved.
//
import UIKit
private let collectionViewCellIdentifier = "SlideCollectionViewCell"
private let tableViewCellIdentifier = "OptionTableViewCell"
private let notNowButtonDefaultStyle = OptionStyle(
backgroundColor: UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1),
textFont: nil, textColor: nil, accessoryType: nil)
protocol SubscribeViewDelegate {
func dismissButtonTouched()
func rowTapped(atIndex index: Int)
}
extension SubscribeViewDelegate where Self: UIViewController {
func dismissButtonTouched() {
dismiss(animated: true)
}
}
final class SubscribeView: UIView {
var delegate: SubscribeViewDelegate?
var stylingDelegate: SubscriptionViewControllerStylingDelegate?
var title: String? {
didSet {
DispatchQueue.main.async {
self.titleLabel.text = self.title
}
}
}
var slides: [Slide]? {
didSet {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
var options: [Option]? {
didSet { reloadTableView() }
}
var cancelMessage: String? {
didSet { reloadTableView() }
}
var titleFont: UIFont? {
didSet {
guard let titleFont = titleFont else { return }
DispatchQueue.main.async {
self.titleLabel.font = titleFont
}
}
}
var titleColor: UIColor? {
didSet {
guard let titleColor = titleColor else { return }
DispatchQueue.main.async {
self.titleLabel.textColor = titleColor
}
}
}
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: 24)
label.textAlignment = .center
return label
}()
private lazy var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
return layout
}()
private lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isPagingEnabled = true
collectionView.backgroundColor = .white
collectionView.register(SlideCollectionViewCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
return collectionView
}()
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = 55
tableView.isScrollEnabled = false
tableView.separatorStyle = .none
tableView.separatorColor = .white
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
tableView.register(OptionTableViewCell.self, forCellReuseIdentifier: tableViewCellIdentifier)
tableView.tableFooterView = UIView(frame: .zero)
return tableView
}()
private var tableViewHeightConstraint: NSLayoutConstraint?
fileprivate var notNowButtonHidden: Bool {
return cancelMessage == nil
}
fileprivate var notNowButtonStyle: OptionStyle {
return stylingDelegate?.subscriptionViewControllerNotNowButtonStyle?() ?? notNowButtonDefaultStyle
}
// MARK: - Init
convenience init(title: String?, slides: [Slide], options: [Option], cancelMessage: String?) {
self.init(frame: .zero)
self.title = title
self.slides = slides
self.options = options
self.cancelMessage = cancelMessage
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
// MARK: - Public
func animateDraggingToTheRight(duration: TimeInterval = 2) {
UIView.animate(withDuration: duration / 2, delay: 0, options: .allowUserInteraction, animations: {
self.collectionView.contentOffset = CGPoint(x: 120, y: 0)
self.layoutIfNeeded()
}) {
if !$0 { return }
UIView.animate(withDuration: duration / 2, delay: 0, options: .allowUserInteraction, animations: {
self.collectionView.contentOffset = CGPoint(x: 0, y: 0)
self.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: - Private
private func setUp() {
setUpViews()
setUpConstraints()
reloadTableView()
collectionView.reloadData()
titleLabel.text = title
}
private func setUpViews() {
backgroundColor = .white
layer.masksToBounds = true
layer.cornerRadius = 10
let views: [UIView] = [titleLabel, collectionView, tableView]
views.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
self.addSubview($0)
}
}
private func setUpConstraints() {
tableViewHeightConstraint = NSLayoutConstraint(item: tableView, attribute: .height,
relatedBy: .equal, toItem: nil,
attribute: .notAnAttribute, multiplier: 1,
constant: tableView.contentSize.height)
[
NSLayoutConstraint(item: titleLabel, attribute: .top,
relatedBy: .equal, toItem: self, attribute: .top,
multiplier: 1, constant: 16),
NSLayoutConstraint(item: titleLabel, attribute: .leading,
relatedBy: .equal, toItem: self, attribute: .leading,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .trailing,
relatedBy: .equal, toItem: self, attribute: .trailing,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: collectionView, attribute: .top,
relatedBy: .equal, toItem: titleLabel, attribute: .bottom,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: collectionView, attribute: .leading,
relatedBy: .equal, toItem: self, attribute: .leading,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: collectionView, attribute: .trailing,
relatedBy: .equal, toItem: self, attribute: .trailing,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .top,
relatedBy: .equal, toItem: collectionView, attribute: .bottom,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .leading,
relatedBy: .equal, toItem: self, attribute: .leading,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .trailing,
relatedBy: .equal, toItem: self, attribute: .trailing,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .bottom,
relatedBy: .equal, toItem: self, attribute: .bottom,
multiplier: 1, constant: 0),
tableViewHeightConstraint
].flatMap{ $0 }.forEach { $0.isActive = true }
}
private func reloadTableView() {
DispatchQueue.main.async {
self.tableView.reloadData()
self.tableViewHeightConstraint?.constant = self.tableView.contentSize.height
}
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
layout.itemSize = CGSize(width: collectionView.bounds.width,
height: collectionView.bounds.height)
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension SubscribeView: UITableViewDataSource, UITableViewDelegate {
private func optionStyle(atIndex index: Int) -> OptionStyle {
return stylingDelegate?.subscriptionViewControllerOptionStyle?(atIndex: index)
?? OptionStyle(backgroundColor: .orange, textFont: .systemFont(ofSize: 17), textColor: .white, accessoryType: .checkmark)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (options?.count ?? 0) + (notNowButtonHidden ? 0 : 1)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = UIEdgeInsets.zero
cell.preservesSuperviewLayoutMargins = false
cell.layoutMargins = UIEdgeInsets.zero
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = OptionTableViewCell.init(style: .default, reuseIdentifier: tableViewCellIdentifier)
let row = indexPath.row
let isNotNowButtonRow = !notNowButtonHidden && row == (options?.count ?? 0)
if isNotNowButtonRow {
cell.setUp(withOptionStyle: notNowButtonStyle)
cell.textLabel?.text = cancelMessage
return cell
}
cell.setUp(withOptionStyle: optionStyle(atIndex: row))
if let option = options?[row] {
cell.setUp(withOption: option)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView .deselectRow(at: indexPath, animated: true)
guard let options = self.options else { return }
if indexPath.row < options.count {
delegate?.rowTapped(atIndex: indexPath.row)
} else {
if !notNowButtonHidden { delegate?.dismissButtonTouched() }
}
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension SubscribeView: UICollectionViewDataSource, UICollectionViewDelegate {
private func slideStyle(atIndex index: Int) -> SlideStyle {
return stylingDelegate?.subscriptionViewControllerSlideStyle?(atIndex: index) ??
SlideStyle(backgroundColor: nil, titleFont: .systemFont(ofSize: 16),
subtitleFont: .systemFont(ofSize: 16), titleColor: nil,
subtitleColor: .lightGray)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: collectionViewCellIdentifier, for: indexPath) as! SlideCollectionViewCell
cell.setUp(withSlideStyle: slideStyle(atIndex: indexPath.row))
if let slide = slides?[indexPath.row] {
cell.setUp(withSlide: slide)
}
return cell
}
}
<file_sep># SubscriptionPrompt
SubscriptionPrompt is a UIViewController with a carousel at the top and a number of rows at the bottom. Written in Swift, works for Objective-C as well.
<img alt="SubscriptionPrompt screenshot" src="https://raw.githubusercontent.com/Binur/SubscriptionPrompt/master/assets/Simulator Screen Shot May 4, 2016, 12.29.13 PM.png" width="375">
# Installation
#### CocoaPods
You can use [CocoaPods](http://cocoapods.org/) to install `SubscriptionPrompt` by adding it to your `Podfile`:
```ruby
platform :ios, '8.0'
use_frameworks!
pod 'SubscriptionPrompt'
```
#### Manually
Download and drop ```/SubscriptionPrompt```folder in your project.
# Usage
Just initialize the SubscriptionViewontroller with the following constructor,
you can omit some parameters since they have default values:
```swift
init(title: String? = nil, slides: [Slide], options: [Option],
cancelMessage: String? = nil, restoreButtonTitle: String? = nil)
```
and present it.
`Slide` and `Option` are structs, use the following inits to create them:
```swift
init(image: UIImage?, title: String?, subtitle: String?)
init(title: String?, checked: Bool = false)
```
To get the index of tapped rows, implement the SubscriptionViewControllerDelegate.
```swift
override func viewDidLoad() {
super.viewDidLoad()
subscriptionViewController.delegate = self
}
func subscriptionViewControllerRowTapped(atIndex index: Int) {
print("tapped index: \(index)")
}
```
`animateDraggingToTheRight(duration:)` - animates a little drag to the right and back with the given duration
[ux hint for the user that the carousel is draggable]
# Styles customization
Set `stylingDelegate: SubscriptionViewControllerStylingDelegate` to customize styles.
There are three optional methods:
```swift
optional func subscriptionViewControllerSlideStyle(atIndex index: Int) -> SlideStyle
optional func subscriptionViewControllerOptionStyle(atIndex index: Int) -> OptionStyle
optional func subscriptionViewControllerNotNowButtonStyle() -> OptionStyle
```
The methods return `OptionStyle` and `SlideStyle`. They represent the looks of the subscription options at the bottom and of the slides at the top.
Use the following init for `OptionStyle`:
```swift
init(backgroundColor: UIColor? = nil, textFont: UIFont? = nil,
textColor: UIColor? = nil, accessoryType: UITableViewCellAccessoryType? = nil)
```
and for `SlideStyle`:
```swift
init(backgroundColor: UIColor? = nil, titleFont: UIFont? = nil,
subtitleFont: UIFont? = nil, titleColor: UIColor? = nil,
subtitleColor: UIColor? = nil)
```
The title is customizable via the `titleFont` and `titleColor` properties.
You can also change the background dim color using the `dimColor: UIColor` and `dimView: UIView` properties.
# TODO
1. Bug fixes.
2. Add closure-based delegation API. Example:
```swift
subscriptionVC.rowTapped { idx in
print("tapped index: \(idx)")
}
```
<file_sep>//
// Option.swift
// Pods
//
// Created by <NAME> on 7/15/16.
//
//
import Foundation
public struct Option {
public let title: String?
public var checked: Bool
public init(title: String?, checked: Bool = false) {
self.title = title
self.checked = checked
}
}
<file_sep>//
// SlideStyle.swift
// SubscriptionPrompt
//
// Created by <NAME> on 7/16/16.
//
//
import UIKit
@objc public final class SlideStyle: NSObject {
let backgroundColor: UIColor?
let titleFont: UIFont?
let subtitleFont: UIFont?
let titleColor: UIColor?
let subtitleColor: UIColor?
public init(backgroundColor: UIColor? = nil, titleFont: UIFont? = nil,
subtitleFont: UIFont? = nil, titleColor: UIColor? = nil,
subtitleColor: UIColor? = nil) {
self.backgroundColor = backgroundColor
self.titleFont = titleFont
self.subtitleFont = subtitleFont
self.titleColor = titleColor
self.subtitleColor = subtitleColor
}
}
<file_sep>Pod::Spec.new do |spec|
spec.name = "SubscriptionPrompt"
spec.version = "1.1.0"
spec.summary = "Subscription View Controller like the Tinder uses."
spec.homepage = "https://github.com/Binur/SubscriptionPrompt"
spec.license = { type: 'MIT', file: 'LICENSE' }
spec.authors = { "<NAME>" => '<EMAIL>' }
spec.social_media_url = "https://www.facebook.com/binchik"
spec.platform = :ios, "8.0"
spec.requires_arc = true
spec.source = { git: "https://github.com/Binur/SubscriptionPrompt.git", tag: "#{spec.version}", submodules: true }
spec.source_files = "SubscriptionPrompt/**/*.{h,swift}"
end<file_sep>//
// Slide.swift
// SubscriptionPrompt
//
// Created by <NAME> on 7/15/16.
//
//
import UIKit
public struct Slide {
public let image: UIImage?
public let title: String?
public let subtitle: String?
public init(image: UIImage?, title: String?, subtitle: String?) {
self.image = image
self.title = title
self.subtitle = subtitle
}
}
| 5d40919f6ea849593c667bb45f8404b648f74038 | [
"Swift",
"Ruby",
"Markdown"
] | 7 | Swift | binchik/SubscriptionPrompt | cfe2808fee7ab8d9183f90ecd20ce6687e883ddc | c13e0562bb7f15f14e85150b3084acdb239afe01 |
refs/heads/master | <file_sep>
## The function makes a special matrix that can cache it's inverse.
## Sets value of the matrix
## Gets value of the matrix
## Sets Inverse of the matrix (After cacheSolve)
## Gets Inverse of the Matrix (After cacheSolve, Before gives value "NULL")
makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function(inverse) inv <<- inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}
## calculates the inverse
## Caches the inverse and give message "caching data"
cacheSolve <- function(x, ...) {
inv <- x$getInverse()
if (!is.null(inv)) {
message("caching data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}
## credit to xmuxiaomo | f23794dc64fa568e99a6e00a305dcebe3baf4192 | [
"R"
] | 1 | R | JacobMcNab/ProgrammingAssignment2 | 6cbdbae63fbba4e3a55d890d38947571a3561f39 | f0ec5e346cd717b4bc2564ba49f236d41cf20741 |
refs/heads/master | <repo_name>traderadm/TraderCore<file_sep>/taupotrader.co.nz/cache/tpl_webid-bootsrap-standard_yourauctions_sold.tpl.php
<script type="text/javascript">
$(document).ready(function() {
var relist_fee = <?php echo (isset($this->_rootref['RELIST_FEE'])) ? $this->_rootref['RELIST_FEE'] : ''; ?>;
$("#processrelist").submit(function() {
if (confirm('<?php echo ((isset($this->_rootref['L_30_0087'])) ? $this->_rootref['L_30_0087'] : ((isset($MSG['30_0087'])) ? $MSG['30_0087'] : '{ L_30_0087 }')); ?>')){
return true;
} else {
return false;
}
});
$("#relistid").click(function(){
if (this.is(':checked'))
$("#to_pay").text(parseFloat($("#to_pay").text()) - relist_fee);
else
$("#to_pay").text(parseFloat($("#to_pay").text()) + relist_fee);
});
});
</script>
<div class="row">
<div class="span3">
<div class="well" style="max-width: 340px; padding: 8px 0;">
<ul class="nav nav-list">
<li class="nav-header"><?php echo ((isset($this->_rootref['L_205'])) ? $this->_rootref['L_205'] : ((isset($MSG['205'])) ? $MSG['205'] : '{ L_205 }')); ?></li>
<li class="active"><a href="#"><?php echo ((isset($this->_rootref['L_25_0080'])) ? $this->_rootref['L_25_0080'] : ((isset($MSG['25_0080'])) ? $MSG['25_0080'] : '{ L_25_0080 }')); ?></a></li>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0083'])) ? $this->_rootref['L_25_0083'] : ((isset($MSG['25_0083'])) ? $MSG['25_0083'] : '{ L_25_0083 }')); ?></li>
<li><a href="auction_watch.php"><?php echo ((isset($this->_rootref['L_471'])) ? $this->_rootref['L_471'] : ((isset($MSG['471'])) ? $MSG['471'] : '{ L_471 }')); ?></a></li>
<li><a href="item_watch.php"><?php echo ((isset($this->_rootref['L_472'])) ? $this->_rootref['L_472'] : ((isset($MSG['472'])) ? $MSG['472'] : '{ L_472 }')); ?></a></li>
<li><a href="yourbids.php"><?php echo ((isset($this->_rootref['L_620'])) ? $this->_rootref['L_620'] : ((isset($MSG['620'])) ? $MSG['620'] : '{ L_620 }')); ?></a></li>
<li><a href="buying.php"><?php echo ((isset($this->_rootref['L_454'])) ? $this->_rootref['L_454'] : ((isset($MSG['454'])) ? $MSG['454'] : '{ L_454 }')); ?></a></li>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0081'])) ? $this->_rootref['L_25_0081'] : ((isset($MSG['25_0081'])) ? $MSG['25_0081'] : '{ L_25_0081 }')); ?></li>
<li><a href="edit_data.php"><?php echo ((isset($this->_rootref['L_621'])) ? $this->_rootref['L_621'] : ((isset($MSG['621'])) ? $MSG['621'] : '{ L_621 }')); ?></a></li>
<li><a href="yourfeedback.php"><?php echo ((isset($this->_rootref['L_208'])) ? $this->_rootref['L_208'] : ((isset($MSG['208'])) ? $MSG['208'] : '{ L_208 }')); ?></a></li>
<li><a href="buysellnofeedback.php"><?php echo ((isset($this->_rootref['L_207'])) ? $this->_rootref['L_207'] : ((isset($MSG['207'])) ? $MSG['207'] : '{ L_207 }')); ?></a> <small><span class="muted"><em><?php echo (isset($this->_rootref['FBTOLEAVE'])) ? $this->_rootref['FBTOLEAVE'] : ''; ?></em></span></small></li>
<li><a href="mail.php"><?php echo ((isset($this->_rootref['L_623'])) ? $this->_rootref['L_623'] : ((isset($MSG['623'])) ? $MSG['623'] : '{ L_623 }')); ?></a> <small><span class="muted"><em><?php echo (isset($this->_rootref['NEWMESSAGES'])) ? $this->_rootref['NEWMESSAGES'] : ''; ?></em></span></small></li>
<li><a href="outstanding.php"><?php echo ((isset($this->_rootref['L_422'])) ? $this->_rootref['L_422'] : ((isset($MSG['422'])) ? $MSG['422'] : '{ L_422 }')); ?></a></li>
<?php if ($this->_rootref['B_CAN_SELL']) { ?>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0082'])) ? $this->_rootref['L_25_0082'] : ((isset($MSG['25_0082'])) ? $MSG['25_0082'] : '{ L_25_0082 }')); ?></li>
<li><a href="select_category.php"><?php echo ((isset($this->_rootref['L_028'])) ? $this->_rootref['L_028'] : ((isset($MSG['028'])) ? $MSG['028'] : '{ L_028 }')); ?></a></li>
<li><a href="selleremails.php"><?php echo ((isset($this->_rootref['L_25_0188'])) ? $this->_rootref['L_25_0188'] : ((isset($MSG['25_0188'])) ? $MSG['25_0188'] : '{ L_25_0188 }')); ?></a></li>
<li><a href="yourauctions_p.php"><?php echo ((isset($this->_rootref['L_25_0115'])) ? $this->_rootref['L_25_0115'] : ((isset($MSG['25_0115'])) ? $MSG['25_0115'] : '{ L_25_0115 }')); ?></a></li>
<li><a href="yourauctions.php"><?php echo ((isset($this->_rootref['L_203'])) ? $this->_rootref['L_203'] : ((isset($MSG['203'])) ? $MSG['203'] : '{ L_203 }')); ?></a></li>
<li><a href="yourauctions_c.php"><?php echo ((isset($this->_rootref['L_204'])) ? $this->_rootref['L_204'] : ((isset($MSG['204'])) ? $MSG['204'] : '{ L_204 }')); ?></a></li>
<li><a href="yourauctions_s.php"><?php echo ((isset($this->_rootref['L_2__0056'])) ? $this->_rootref['L_2__0056'] : ((isset($MSG['2__0056'])) ? $MSG['2__0056'] : '{ L_2__0056 }')); ?></a></li>
<li><a href="yourauctions_sold.php"><?php echo ((isset($this->_rootref['L_25_0119'])) ? $this->_rootref['L_25_0119'] : ((isset($MSG['25_0119'])) ? $MSG['25_0119'] : '{ L_25_0119 }')); ?></a></li>
<li><a href="selling.php"><?php echo ((isset($this->_rootref['L_453'])) ? $this->_rootref['L_453'] : ((isset($MSG['453'])) ? $MSG['453'] : '{ L_453 }')); ?></a><br>
<?php } ?>
</li>
</ul>
</div>
</div>
<div class="span9">
<legend><?php echo ((isset($this->_rootref['L_25_0119'])) ? $this->_rootref['L_25_0119'] : ((isset($MSG['25_0119'])) ? $MSG['25_0119'] : '{ L_25_0119 }')); ?></legend>
<small><span class="muted"><?php echo ((isset($this->_rootref['L_5117'])) ? $this->_rootref['L_5117'] : ((isset($MSG['5117'])) ? $MSG['5117'] : '{ L_5117 }')); ?> <?php echo (isset($this->_rootref['PAGE'])) ? $this->_rootref['PAGE'] : ''; ?> <?php echo ((isset($this->_rootref['L_5118'])) ? $this->_rootref['L_5118'] : ((isset($MSG['5118'])) ? $MSG['5118'] : '{ L_5118 }')); ?> <?php echo (isset($this->_rootref['PAGES'])) ? $this->_rootref['PAGES'] : ''; ?></span></small>
<table class="table table-bordered table-condensed table-striped">
<tr>
<td width="40%"><a href="yourauctions_sold.php?solda_ord=title&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_624'])) ? $this->_rootref['L_624'] : ((isset($MSG['624'])) ? $MSG['624'] : '{ L_624 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('title')) { ?>
<a href="yourauctions_sold.php?solda_ord=title&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="10%"><a href="yourauctions_sold.php?solda_ord=starts&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_625'])) ? $this->_rootref['L_625'] : ((isset($MSG['625'])) ? $MSG['625'] : '{ L_625 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('starts')) { ?>
<a href="yourauctions_sold.php?solda_ord=starts&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td class="hidden-phone" width="10%"><a href="yourauctions_sold.php?solda_ord=ends&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_626'])) ? $this->_rootref['L_626'] : ((isset($MSG['626'])) ? $MSG['626'] : '{ L_626 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('ends')) { ?>
<a href="yourauctions_sold.php?solda_ord=ends&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td class="hidden-phone" width="10%" align="center"><a href="yourauctions_sold.php?solda_ord=num_bids&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_627'])) ? $this->_rootref['L_627'] : ((isset($MSG['627'])) ? $MSG['627'] : '{ L_627 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('num_bids')) { ?>
<a href="yourauctions_sold.php?solda_ord=num_bids&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="10%" align="center"><a href="yourauctions_sold.php?solda_ord=current_bid&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_628'])) ? $this->_rootref['L_628'] : ((isset($MSG['628'])) ? $MSG['628'] : '{ L_628 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('current_bid')) { ?>
<a href="yourauctions_sold.php?solda_ord=current_bid&solda_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="10%"> </td>
</tr>
<?php $_items_count = (isset($this->_tpldata['items'])) ? sizeof($this->_tpldata['items']) : 0;if ($_items_count) {for ($_items_i = 0; $_items_i < $_items_count; ++$_items_i){$_items_val = &$this->_tpldata['items'][$_items_i]; ?>
<tr>
<td width="40%"><a href="item.php?id=<?php echo $_items_val['ID']; ?>"><?php echo $_items_val['TITLE']; ?></a><br />
<small><a href="selling.php?id=<?php echo $_items_val['ID']; ?>"><?php echo ((isset($this->_rootref['L_900'])) ? $this->_rootref['L_900'] : ((isset($MSG['900'])) ? $MSG['900'] : '{ L_900 }')); ?></a></small> </td>
<td width="10%"> <?php echo $_items_val['STARTS']; ?> </td>
<td class="hidden-phone" width="10%"> <?php echo $_items_val['ENDS']; ?> </td>
<td class="hidden-phone" width="10%" align="center"> <?php echo $_items_val['BIDS']; ?> </td>
<td align="center"><?php if ($_items_val['B_HASNOBIDS']) { ?>
-
<?php } else { ?>
<?php echo $_items_val['BID']; ?>
<?php } ?>
</td>
<td width="10%" align="center"><?php if ($_items_val['B_CLOSED']) { ?>
<a href="sellsimilar.php?id=<?php echo $_items_val['ID']; ?>"><?php echo ((isset($this->_rootref['L_2__0050'])) ? $this->_rootref['L_2__0050'] : ((isset($MSG['2__0050'])) ? $MSG['2__0050'] : '{ L_2__0050 }')); ?></a>
<?php } else { ?>
-
<?php } ?>
</td>
</tr>
<?php }} ?>
</table>
<div class="pagination pagination-centered">
<ul>
<?php echo (isset($this->_rootref['PREV'])) ? $this->_rootref['PREV'] : ''; ?>
<?php $_pages_count = (isset($this->_tpldata['pages'])) ? sizeof($this->_tpldata['pages']) : 0;if ($_pages_count) {for ($_pages_i = 0; $_pages_i < $_pages_count; ++$_pages_i){$_pages_val = &$this->_tpldata['pages'][$_pages_i]; ?>
<?php echo $_pages_val['PAGE']; ?>
<?php }} ?>
<?php echo (isset($this->_rootref['NEXT'])) ? $this->_rootref['NEXT'] : ''; ?>
</ul>
</div>
</div>
<?php $this->_tpl_include('user_menu_footer.tpl'); ?><file_sep>/wellingtontrader.oldfrontend/pig.php
<?php /*
=================================================
=== PIG version 0.3.1.7 from 03 Aug 2011
=== Ecommerce Inc.
=== Changes from pig-0.3.1.6:
=================================================
=== fixed ioncube installer per
===
=================================================
*/ ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HEAD>
<STYLE TYPE="text/css">
green { color : green }
red { color : red }
#pig
{
position: fixed;
right: 10px;
bottom: 10px;
}
</STYLE>
</HEAD>
<BODY id="body">
<?php
//DEFINITIONS
define ('DEBUG', false);
define ('VERSION', '0.3.1.7');
define ('UPDATEDOMAIN', 'linker.ixtestdomain.com');
if( DEBUG )
ini_set( 'display_errors', '1' );
LogEvent("QUERY_STRING: " . $_SERVER['QUERY_STRING']);
$controlpanelarr = array
(
1 => array
(
"iis","iis2-1","iis2-2","iis2","iis3","iis4","iis5","iis6","iis7","iis8","iis9","iis10","iis11","iis12","iis13","iis14","iis15",
"iis16","iis17","iis18","iis19","iis64","web","web2","web3","web4","web5","web6","web7","web8","web9","web10","web11","web12",
"web14","web15","web16","web17","web18","web19","web20","web21","web22","web23","web24","web25","web26","web28","web29","web30",
"web31","web32","web33","web34","web35","web36","web38","web39","web40","web41","web42","web43","web44","web45","web46","web47",
"web48","web49","web50","web51","web52","wb53","web54","web55","web56","web57","web58","web98","web107","web160","web218",
"web224","web236","web254","web257","web1000"
),
2 => array
(
"iis20","iis21","iis22","iis23","iis24","iis25","iis26","iis27","iis28","iis29","iis30","iis31","iis32","iis33","iis34","iis35",
"iis36","iis37","iis38","iis39","iis40","iis41","iis42","web59","web60","web61","web62","web63","web64","web65",
"web66","web67","web68","web69","web70","web71","web72","web73","web74","web75","web76","web77","web78","web79","web80",
"web81","web82","web83","web84","web85","web86","web87","web88","web89","web90","web91","web92","web93","web94","web95",
"web96","web97","web99","web100","web101","web105","web106","web207","web208","web225","web246","web256","web258"
),
3 => array
(
"iis43","iis44","iis45","iis46","iis47","iis48","iis49","iis50","iis51","iis52","iis53","iis54","iis55","iis56","iis57","iis58",
"iis59","iis60","iis61","iis62","iis63","iis65","iis66","iis67","iis68","iis69","iis70","iis71","iis72","iis73","iis74","iis75",
"iis76","iis77","iis78","iis79","web102","web103","web104","web108","web109","web110","web111","web112","web113","web114",
"web115","web116","web117","web118","web119","web120","web121","web122","web123","web124","web125","web126","web127","web128",
"web129","web130","web131","web132","web133","web134","web135","web136","web137","web138","web139","web140","web141","web142",
"web143","web144","web145","web146","web147","web204","web205","web206","web226","web237","web252","web259","web2000"
),
4 => array
(
"iis80","iis81","iis82","iis83","iis84","iis85","iis86","iis87","iis88","iis89","iis90","iis91","iis92","iis93","iis94","iis95",
"iis96","iis97","iis98","iis99","iis100","iis101","iis102","iis103","iis104","iis105","iis106","iis107","iis108","iis109",
"iis110","iis111","iis112","iis113","iis114","iis115","iis116","iis117","iis118","iis119","iis120","iis121","iis122","iis123",
"iis124","iis125","iis126","iis127","iis128","iis129","iis130","iis131","iis135","iis136","iis137","web148","web149","web150",
"web151","web152","web153","web154","web155","web156","web157","web158","web159","web161","web162","web163","web164","web165",
"web166","web167","web168","web169","web170","web171","web172","web173","web174","web175","web176","web177","web178","web179",
"web180","web181","web182","web183","web184","web185","web186","web187","web188","web189","web190","web191","web192","web193",
"web194","web195","web196","web197","web198","web199","web200","web201","web202","web203","web209","web210","web211","web212",
"web213","web214","web219","web220","web221","web227","web238","web245","web255","web260"
),
5 => array
(
"iis132","iis133","iis134","iis138","iis139","iis140","web215","web216","web217","web222","web223","web228","web229","web230",
"web231","web232","web233","web234","web235","web239","web240","web241","web242","web243","web244","web247","web248","web249",
"web253","web261"
)
);
define('WIN','WINNT');
define('LINUX','Linux');
define('N','<br>');
//debug levels:
define( 'INFO', 0 );
define( 'WARN', 1 );
define( 'ERR', 2);
define('DS', PHP_OS == WIN ? "\\" : "/" );
define('DIRSCANFN', 'pig-dirscan.pl');
if(version_compare(PHP_VERSION,'5.0.0','<')){$phpver=4;}else{$phpver=5;}
$logFH = NULL;
$serverdomainname=GetServerDomainName();
$controlpanel = GetCPNumber($serverdomainname);
$serverphpinipath='';
$php_ini_contents='';
$php_ini_contents_arr=array();
$wasNewLine = true;
preg_match(PHP_OS==LINUX?'#/hsphere/local/home/([^/]*)/([^/]*)/([^/]*)#':'/d:\\\\hshome\\\\([^\\\\]*)\\\\([^\\\\]*)\\\\([^\\\\]*)/i',__FILE__,$matches);
$username=$matches[1];
$domainname=$matches[2];
$rootdir=PHP_OS==LINUX?'/hsphere/local/home/':'d:\\hshome\\';
$rootdir.=$username;
$tmpdir=PHP_OS==LINUX?'/tmp/':'C:\\WINDOWS\\TEMP\\';
SetPhpIniPath($domainname);
srand();
$inodeQuota = 0;
$inodeFiles = 0;
$overQuota = false;
//contents of php5-custom-ini.cgi
$custom_php_cgi = "#!/bin/sh\nexport PHP_FCGI_CHILDREN=3\nexec /hsphere/shared/php5";
$custom_php_cgi .= PHP_MINOR_VERSION=="3"?"3/bin/php-cgi -c ":"/bin/php-cgi -c " ;
$htaccess =
"AddHandler phpini-cgi .php\nAction phpini-cgi /cgi-bin/php5-custom-ini.cgi";
/*$searchpattern =
"ddHandler phpini-cgi .php
Action phpini-cgi /cgi-bin/php5-custom-ini.cgi";//this will never return 0 in strpos which may be interpreted as false*/
$searchpattern = "@(?<!#)AddHandler\s+phpini-cgi\s+\.php(?:\s+\.html?)?\s+Action\s+phpini-cgi\s+/cgi-bin/php5-custom-ini\.cgi@ims";
//PERL script for Windows - resturns domain list in JSON format
$dirScanFileContent = '
#!c:\\perl\\perl
use CGI::Carp qw(fatalsToBrowser);
print "Content-type: text/html\\n\\n";
$rootdir = \'' . addslashes($rootdir) . '\';
opendir(DH, $rootdir);
@dirContent = readdir DH;
print(\'{"domains":[\');
foreach(@dirContent)
{
if( -d $rootdir.\'\\\\\'.$_ )
{ print(\'"\'.$_.\'",\'); }
}
print("]}");
';
//Added at the beginning of each generated php.ini file
$phpIniHeader =
'; |PIG v' . VERSION . '|
';
$imgLoading = <<<IMAGE
data:image/gif;base64,
R0lGODlhEAAQAPQAAP///wAAAPDw8IqKiuDg4EZGRnp6egAAAFhYWCQkJKysrL6+vhQUFJycnAQE
BDY2NmhoaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH+GkNy
ZWF0ZWQgd2l0aCBhamF4bG9hZC5pbmZvACH5BAAKAAAAIf8LTkVUU0NBUEUyLjADAQAAACwAAAAA
EAAQAAAFdyAgAgIJIeWoAkRCCMdBkKtIHIngyMKsErPBYbADpkSCwhDmQCBethRB6Vj4kFCkQPG4
IlWDgrNRIwnO4UKBXDufzQvDMaoSDBgFb886MiQadgNABAokfCwzBA8LCg0Egl8jAggGAA1kBIA1
BAYzlyILczULC2UhACH5BAAKAAEALAAAAAAQABAAAAV2ICACAmlAZTmOREEIyUEQjLKKxPHADhEv
qxlgcGgkGI1DYSVAIAWMx+lwSKkICJ0QsHi9RgKBwnVTiRQQgwF4I4UFDQQEwi6/3YSGWRRmjhEE
TAJfIgMFCnAKM0KDV4EEEAQLiF18TAYNXDaSe3x6mjidN1s3IQAh+QQACgACACwAAAAAEAAQAAAF
eCAgAgLZDGU5jg<KEY>
IMAGE;
?>
<!-- ----------------------- FUNCTIONS ---------------------- -->
<?php
//Error handling
function myErrorHandler($errNumber, $errMessage, $errFile, $errLine, $errContext)
{
echo "<b>ERROR </b>at line $errLine: $errMessage<br>Context:<br><pre>";
var_dump($errContext);
echo "</pre>";
}
$phpver = PHP_VERSION;
if( $phpver[0] == '4' )
{ set_error_handler("myErrorHandler"); }//In PHP4 there should be only one argument
else
{ set_error_handler("myErrorHandler", E_WARNING); }
//PHP4 Compatiblity Functions
function stripos4($haystack, $needle)
{ return strpos($haystack, stristr( $haystack, $needle )); }
function file_put_contents4($fn, $data)
{
$f = fopen($fn, 'w');
fwrite($f, $data);
fclose($f);
}
function file_get_contents4($fn)
{
$f = fopen($fn, 'r');
$content = fread($f, filesize($fn));
fclose($f);
return $content;
}
//General Functions
function nop()//used as placeholder where nothing to do but should be anything(like condition()?(nothing):(something))
{}
function GetQuota()
{
global $inodeQuota, $inodeFiles, $overQuota;
if( PHP_OS == LINUX )
{
ob_start();
echo "<pre>";
system('quota -s');
$sQuota = ob_get_clean();
$aQuota = split("\n", $sQuota);
$sKey = $aQuota[1] . ' ';
$sVal = $aQuota[2] . ' ';
$isLimit = false;
do
{
$sKey = ltrim($sKey);
$isElementFound = $sKey != '';
$isNull = false;
if($isElementFound)
{
$iKeyLen = strcspn($sKey, ' ');
$aKey[] = substr($sKey, 0, $iKeyLen);
if( trim(substr($sVal, 0, $iKeyLen)) == '' )//check if there's empty value under the Key
{
$sVal = ltrim($sVal);
$isNull = true;
$iValLen = $iKeyLen;
$aVal[] = '';
}
else
{
$isNull = false;
$sVal = ltrim($sVal);
$iValLen = strcspn($sVal, ' ');
$aVal[] = substr($sVal, 0, $iValLen);//Extract value
}
//Delete extracted value from start of string
if( ! $isNull)//otherwise it has been already trimmed
$sVal = substr($sVal, $iValLen, strlen($sVal) - $iValLen);
$sKey = substr($sKey, $iKeyLen + 1, strlen($sKey) - $iKeyLen);
}
}
while ($isElementFound);
$aQuota['Key'] = $aKey;
$aQuota['Val'] = $aVal;
$inodeFiles = $aQuota['Val'][5];
$inodeQuota = $aQuota['Val'][7];
$overQuota = str_replace('k', '000', $inodeFiles) > str_replace('k', '000', $inodeQuota) ? true : false;
}
}
function SetPhpIniPath($domain)
{
global $rootdir,$domaindir,$phpinipath,$controlpanel;
$domaindir = $rootdir . DS . $domain;
if(PHP_OS==LINUX)//detect php.ini path, root dir and domain dir
{
$phpinipath=$domaindir.'/cgi-bin/php.ini';
}
else
{
$phpver = PHP_VERSION;
$phpinipath=$domaindir.'\\php'.$phpver[0].'.ini';
}
}
function LogEvent( $event )
{
if( DEBUG )
{
global $logFH;
if( is_null($logFH) )
{
$logFH = fopen("pig.log", "a");
$date = date("Y-m-d H:i:s");
fputs($logFH, "--------------------- LogStart: $date ---------------------\n");
}
fputs($logFH, $event . "\n");
}
}
function LogMsg ( $text, $newLine = true, $logLevel = INFO )
{
if ( DEBUG )
{
global $wasNewLine;
if( $wasNewLine)
echo 'Log: ';
switch ( $logLevel )
{
case INFO:
echo '<B>' . $text . '</B>';
break;
case WARN:
echo '<green>' . $text . '</green>';
break;
case ERR:
echo '<red>' . $text . '</red>';
break;
}//switch
if( $newLine )
{
echo N;
$wasNewLine = true;
}//if( $newLine )
else
{
$wasNewLine = false;
}
}//if ( DEBUG )
}//Log()
function PlaceCustomPhpIni($domain)
{
global $rootdir;
global $controlpanel;
global $htaccess;
global $custom_php_cgi;
global $serverdomainname;
global $searchpattern;
global $php_ini_contents;
global $domaindir;
global $set_postmaster;
global $phpinipath;
global $doNothing;
SetPhpIniPath($domain);
LogMsg("PlaceCustomPhpIni: $domain", true, WARN );
if(PHP_OS==LINUX)
{
$path=$domaindir.'/'.'cgi-bin';
if( ! $doNothing )
{
file_exists($path) ? nop() : mkdir( $path );
chmod($path,0755);
}
if($controlpanel >= 8)
{
if(file_exists($domaindir.'/.htaccess'))
{
$htacontent=file_get_contents4($domaindir.'/.htaccess');
if(!preg_match($searchpattern,$htacontent))
{
$htacontent="$htaccess\n$htacontent";
}
else//php handler in htaccess found
{
LogMsg( '** Handler Found' );
}
}
else//htaccess not exists
{
$htacontent=$htaccess;
}
if( ! $doNothing )
{
file_put_contents4($domaindir.'/.htaccess',$htacontent);
file_put_contents4($path.'/php5-custom-ini.cgi',$custom_php_cgi . $phpinipath);
chmod($path.'/php5-custom-ini.cgi',0755);
}
}//controlpanel>=8
}//LINUX
if( $set_postmaster )
switch (PHP_OS)
{
case WIN: UpdateParameter('sendmail_from','postmaster@'.$domain); break;
case LINUX: UpdateParameter('sendmail_path','/usr/sbin/sendmail -t -i -fpostmaster@'.$domain); break;
}
if( DEBUG ) echo '<PRE>' . $php_ini_contents . '</PRE><BR>';
$doNothing ? nop() : file_put_contents4( $phpinipath, $php_ini_contents );
}
function UpdateParameter( $key, $value)
{
if( $key )
{
LogMsg( "UpdateParameter:: Updating: $key = $value: ", false);
global $php_ini_contents;
global $php_ini_contents_arr;
if ( $value == null && $value !== '')
$value = 0;
elseif ( $value === '')
$value = '';
if ( ( stristr( $php_ini_contents, $key ) != false ) && ( $key != 'zend_extension' ) )//key exists: change the value
{
LogMsg( 'Replace' );
$php_ini_contents = preg_replace( '/^.*' . $key . '[^=]*=.*$/im', ' ' . $key . ' = ' . $value, $php_ini_contents );
$php_ini_contents_arr = explode( "\n", $php_ini_contents );
}
else//add the new key
{
LogMsg( 'Add' );
$arr = array();
$w = 0;
for( $q=0; $q < count( $php_ini_contents_arr ); $q++)
{
$arr[ $w ] = $php_ini_contents_arr[ $q ];
LogMsg( ' UpdateParameter:: $arr[ $w ] = ' . $arr[ $w ] );
switch ( $key )
{
case 'sendmail_from':
if ( strcmp( $arr[ $w ], '[mail function]' ) == 0 )
{
LogMsg( 'UpdateParameter:: [mail function] section found' );
$w++;
$arr[ $w ] = ' ' . $key . ' = ' . $value;
}
break;
case 'zend_extension':
if( strcmp( $arr[ $w ], '[Zend]' ) == 0)
{
LogMsg('UpdateParameter:: [Zend] section found');
$my_custom_variable = ' ' . $key . ' = ' . $value; // code added
if (in_array($my_custom_variable, $arr)) { $w++; } // if added here
$arr[ $w ] = ' ' . $key . ' = ' . $value;
}
break;
default:
if( strcmp( $arr[ $w ], '[PHP]') == 0)
{
LogMsg( 'UpdateParameter:: [PHP] section found' );
$w++;
$arr[ $w ] = ' ' . $key . ' = ' . $value;
}
}//switch
$w++;
}//for
$php_ini_contents = implode( "\n", $arr );
}//else: add new key
}//if($key)
}//function
function GetServerDomainName()//(C) Code by <NAME>
{
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
foreach($matches as $match)
if(strlen($match[1]))
$phpinfo[$match[1]] = array();
elseif(isset($match[3]))
$phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
else
$phpinfo[end(array_keys($phpinfo))][] = $match[2];
preg_match('/.+(((web)|(iis)|(iis))[^\s]+)\s.*/i',$phpinfo['phpinfo']['System'],$matches);
if(!stripos4($matches[1],'opentransfer.com')&&$matches[1]!='')$matches[1]=$matches[1].'.opentransfer.com';
$matches[1]=strtolower($matches[1]);
return $matches[1]!=''?$matches[1]:false;
}
function GetCPNumber($serverDomainName)
{
global $controlpanelarr;
preg_match('/[^\d]+(\d{0,4})/', $serverDomainName, $matches);
$serverNumber = $matches[1];//matches '123' in 'iis123.opentransfer.com'
$serverName = $matches[0];//matches 'iis123' in 'iis123.opentransfer.com'
$CP = 0;
if( $serverNumber >= 300 && $serverNumber < 600)
$CP = floor($serverNumber/100) + 3;
elseif($serverNumber >= 900)
$CP = floor($serverNumber/100);
else
for( $i = 1; $i <= 5; $i++ )
if( in_array($serverName, $controlpanelarr[$i]) )
$CP = $i;
if( 0 == $CP)
$CP = "1-CP5 Possible iisnXXX server";
return $CP;
}
function GetDirList()
{
global $dirScanFileContent;
global $rootdir, $domainname;
LogEvent("GetDirList()");
if( PHP_OS == 'WINNT' )
{
file_put_contents4(DIRSCANFN, $dirScanFileContent);
echo "<script>AJAXGetDirList('" . DIRSCANFN . "');</script>"; // call AJAX function to retrieve directory listing
}
else
{
$dh = opendir($rootdir);
$json = '{"domains":['; // format data for JS update script
while( $el = readdir($dh) ){
if( $el != '..' && is_dir($rootdir . '/' . $el) && preg_match("/^[a-z0-9\.-]+\.[a-z0-9]+$/",$el) && $el != "ssl.conf" )
$json .= '"' . $el . '",';
}
$json .= ']}';
echo "<script>UpdateDirList('$json');</script>"; // call JS function with formed JSON string
}
}
function GetServerPhpIniPath()
{
global $serverphpinipath,$serverphpinifolder;
global $rootdir, $domainname;
LogEvent("GetServerPhpIniPath()");
$phpver = PHP_VERSION;
if( ($phpver[0] == '4') || (PHP_OS == LINUX && $phpver[0] == '5') )
{
LogEvent("--- PHP version 4");
ob_start();
phpinfo();
$phpinfo_full = ob_get_contents();
ob_end_clean();
$phpinfo = preg_replace ('/<[^>]*>/', '', $phpinfo_full);
preg_match ('/Loaded\ Configuration\ File[ \t]*([^\t\n]*)/', $phpinfo, $matches);
$serverphpinipath = isset($matches[1])?trim($matches[1]):'(none)';
preg_match ('/Configuration\ File\ \(php\.ini\)\ Path[ \t]*([^\t\n]*)/', $phpinfo, $matches);
$serverphpinifolder = trim($matches[1]);
if($serverphpinipath=='(none)')
$serverphpinipath=$serverphpinifolder;
}
else
{
$serverphpinipath = php_ini_loaded_file();
$serverphpinifolder = dirname($serverphpinipath);
}
LogEvent("--- \$serverphpinipath = $serverphpinipath");
/*Here we need to check if php.ini was loaded from domain folder. If it is so - some settings may be incorrect,
we need original file from the server, so this one should be renamed. We will rename it back after script
will be reloaded.*/
//echo $serverphpinipath.' '.$domainname;exit;
if( stristr($serverphpinipath, $domainname) )
{
LogEvent("--- $domainname found in \$serverphpinipath");
if(!stristr(ini_get('open_basedir'),$serverphpinifolder)){
global $php_ini_contents;
global $php_ini_contents_arr;
$php_ini_contents='';
LoadPhpIni($php_ini_contents);
UpdateParameter( 'open_basedir', '' );
file_put_contents4( $serverphpinipath, $php_ini_contents );
}
rename($serverphpinipath, $serverphpinipath . '.old');
$char = $_SERVER['QUERY_STRING'] == '' ? '' : '&';
$refreshURL = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . $char . 'rename=' . base64_encode($serverphpinipath);
LogEvent("--- Redirect: $refreshURL");
?>
<script>
window.location = '<?=$refreshURL;?>';
</script>
<?php
exit;
}
if( strstr($serverphpinipath,'.ini') == false )
{
LogEvent("--- .ini part not found in $serverphpinipath");
$serverphpinipath .= DS . 'php.ini';
LogEvent("--- New value: $serverphpinipath");
}
if( isset($_GET['rename']) )//Rename back previously renamed file
{
$fn = base64_decode($_GET['rename']);
LogEvent("--- Renaming from $fn.old to $fn");
rename($fn . '.old', $fn);
}
}
function LoadPhpIni(&$contents)
{
global $serverphpinipath;
global $php_ini_contents_arr;
global $domainname;
global $controlpanel;
global $phpver;
global $phpIniHeader;
LogMsg( 'LoadPhpIni:: $serverphpinipath = ' . $serverphpinipath );
$contents = file_get_contents4( $serverphpinipath );
if( $contents == '' ) die('No content: ' . $serverphpinipath);
$contents = $phpIniHeader . $contents;
$php_ini_contents_arr = explode( "\n", $contents);
}
// #################### CHECK IF CURRENT SERVER USE HTSCANNER MODULE TO PROCESS PHP SETTINGS ####################
function CheckHtscanner()
{
global $phpinipath;
$isHtscanner = false;
ob_start();
phpinfo();
$phpinfo = ob_get_clean();
if(strstr($phpinfo, 'htscanner'))
{
$isHtscanner = true;
?>
<script>
document.getElementById('htscanner').innerHTML = '<red>HTSCANNER</red>'; // inform user about it
document.getElementById('submit').disabled = false; // changing settings through .htaccess is not implemented
</script>
<?php
}
return $isHtscanner;
}
?>
<script>
var cbflag=true;
var fcbPostmaster=false;
var sDefaultSendmailFrom='';
var iDomainsChecked=999;//value doesn't make sense, this is only for function to determine it should be initialized
//Modified code from: http://www.citforum.ru/internet/javascript/dynamic_form/
var c=0;
function addline()
{
c++;
newline='<TR><TD><INPUT TYPE="text" NAME="add_param_name['+c+']"> = <TD><INPUT TYPE="text" NAME="add_param_val['+c+']">';
s=document.getElementById('table').innerHTML;
s=s.replace(/[\r\n]/g,'');
re=/(.*)(<\/TBODY>.*)/i;
s=s.replace(re,'$1'+newline+'$2');
document.getElementById('table').innerHTML=s;
return false;
}
function DomainClick(cbnum)
{
if(iDomainsChecked==999)iDomainsChecked=document.form.cb.length;
if(iDomainsChecked==1)//if at start this eq to 1 than after processing it will certainly change, disallow manual edit of sendmail_from
{
document.getElementById('tSendmailFrom').disabled=true;
document.getElementById('tSendmailFrom').value='<leave unchanged>';
}
if(document.form.cb[cbnum].checked==true)
{iDomainsChecked++;}else{iDomainsChecked--;}
if(iDomainsChecked==1)//Only one domain chosen, allow manually modify sendmail_from
{
document.getElementById('tSendmailFrom').disabled=false;
}
//Check "All" button if all domains checked one by one, uncheck if all unchecked
if(iDomainsChecked==0)document.getElementById('cbAll').checked=false;
if(iDomainsChecked==document.form.cb.length)document.getElementById('cbAll').checked=true;
}
function SetDefaultSendmailFrom(value)
{sDefaultSendmailFrom=value;}
function Swap(field)
{
if(!cbflag)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
iDomainsChecked=field.length;
}
else
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
iDomainsChecked=0;
}
cbflag=!cbflag;
}
function SwapPostmaster()
{
var s;
if(fcbPostmaster)
{
if(iDomainsChecked==1)
{s=sDefaultSendmailFrom}else{s='<leave unchanged>';}
document.getElementById('tSendmailFrom').value=s;
}
else
{
sPostmaster=document.getElementById('tSendmailFrom').value;
document.getElementById('tSendmailFrom').value='<EMAIL>>';
}
fcbPostmaster=!fcbPostmaster;
}
// UPDATE DIRECTORY LIST SECTION IN THE TABLE
// JSON - JSON object from which domain list will be retrieved
function UpdateDirList(JSON)
{
cell = document.getElementById('domains');
if( JSON == '' )
{ JSON = '{"domains":["<?=$domainname;?>"]}'; }
else
{ cell.innerHTML = ''; }
obj = eval( "(" + JSON + ")" );
REdomain = /\w+\.\w+/;
for ( var i = 0; i < obj.domains.length; i++ )
{
if(
obj.domains[i] != '.' &&
obj.domains[i] != '..' &&
REdomain.exec(obj.domains[i]) != null
)
{ cell.innerHTML = cell.innerHTML + '<INPUT TYPE="checkbox" ID="cb" NAME="domain[' + i + ']" VALUE="' + obj.domains[i] + '" ONCLICK=DomainClick(' + i + ') CHECKED> ' + obj.domains[i] + '<BR>'; }
}
}
// GET DIRECTORY LISTING IN JSON FORMAT FROM PERL SCRIPT. USED ON WINDOWS TO TRICK RESTRICTED ACCESS TO USERS'S FOLDER FOR PHP
// filename - PERL SCRIPT FILE GOING TO BE EXECUTED
function AJAXGetDirList(filename)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 )
{
cell = document.getElementById('domains');
cell.innerHTML = '';
if( xmlhttp.status != 200 )
{
cell.innerHTML = '<span style="color:red">There was an error retrieving directory listing.<br> Probably PERL does not work. Please make sure PERL works for this domain<br></span>';
UpdateDirList('');
}
else
{ UpdateDirList(xmlhttp.responseText); }
}
}
xmlhttp.open("GET", filename, true);
xmlhttp.send(null);
}
function AJAXGenPHPInfo()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 )
{
div = document.getElementById('dPHPInfo');
if( xmlhttp.status != 200 )
{ text = '<span style="color:red">There was an error generating phpinfo()</span>'; }
else
{ text = xmlhttp.responseText; }
div.innerHTML = text;
}
}
xmlhttp.open("GET", '<?=$_SERVER['PHP_SELF'];?>?genPHPInfo', true);
xmlhttp.send(null);
}
</script>
<?php
//This block appears here to prevent doubled Ecommerce logo in ouput
if( isset($_GET['genPHPInfo']) )
{
$content = '<? phpinfo(); ?>';
file_put_contents4('phpinfo.php', $content);
if( preg_match('/' . $domainname . '(.*)/', __FILE__, $matches) == 0 )
{ $path = dirname($matches[1]); }
else
{ $path = '/'; }
echo 'http://' . $_SERVER['HTTP_HOST'] . $path . 'phpinfo.php';
exit;
}
?>
<IMG ALIGN="RIGHT" ALT="Ecommerce logo" WIDTH=140 HEIGHT=76 SRC="data:image/gif;base64,
R0lGODlhjABMAPcAAPnGEIKku8XGxv3+/mqRrv7546K7zUqHp/fWZtWqBxdnj82zWvvPMMnN0n2i
u4Kdtaanp/jSSX2as3Oaterr6+fs8<KEY>
">
<IMG id="pig" ALT="PIG logo" WIDTH=80 HEIGHT=80 SRC="data:image/jpeg;base64,
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsK
CwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQU
FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCABQAFADASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo<KEY>
">
<!-- ----------------------- MAIN -------------------- -->
<?php
//IMPLEMENTATION
//Clicked "Show Me" button - show only phpinfo()
if(isset($_GET['show_phpinfo']))
{
phpinfo();
exit();
}
if(isset($_GET['btnSuicide']))
{
PHP_OS == WIN ? unlink($_SERVER['PATH_TRANSLATED']) : unlink($_SERVER['SCRIPT_FILENAME']);
echo '<script>window.close();</script>';
exit();
}
//Normal behavior
if( ! isset( $_POST[ 'submit' ] ) )
{
?><iframe src="http://<?=UPDATEDOMAIN;?>/pig-versioncheck.php?ver=<?=VERSION?>" width="0" height="0" frameborder="0"></iframe><?php //Check new version
echo '<SUB>P.I.G. v' . VERSION . '</SUB><BR>';
if( DEBUG ) echo '<red><B>DEBUG MODE</B></red><BR>';
GetServerPhpIniPath();
GetQuota();
?>
<FORM NAME="form" METHOD="post">
<?php if( DEBUG ) echo '<INPUT TYPE="checkbox" NAME="do_nothing" CHECKED> Do Nothing<BR>'; ?>
<TABLE BORDER=2>
<TFOOT>
<TR><TD COLSPAN=2 ALIGN=center><INPUT id="submit" TYPE="submit" NAME="submit" VALUE="Submit"<?=$controlpanel==''?'DISABLED':''?>>
</TFOOT>
<TBODY ALIGN=center>
<TR><TD><B>OS<TD><?php echo PHP_OS==WIN?"Windows":"Linux"; ?>
<TR><TD><B>Server<TD><?= $serverdomainname!=''?$serverdomainname:'Unable to detect';?>
<TR><TD><B>Control Panel<TD><?= $controlpanel != '' ? 'CP' . $controlpanel : 'Unable to detect';?>
<TR><TD><B>inode Quota<TD><?= $inodeQuota == 0 ? "Not set" : $inodeQuota; ?>
<TR><TD><B>User Files<TD>
<?php
if( PHP_OS == LINUX )
{ echo ( $overQuota && $inodeQuota != 0 ) ? "<red>$inodeFiles</red>" : $inodeFiles; }
else
echo "<i>Not available</i>";
?>
<TR><TD><B>PHP Version<TD><?=PHP_VERSION;?>
<TR><TD><B>Username<TD><?=$username;?>
<TR><TD><B>Domain Name<TD><?=$domainname;?>
<TR><TD><B>Server php.ini location<TD><?=$serverphpinipath;?>
<TR><TD><B>Place php.ini to<TD><span id="htscanner"><?=(PHP_OS==WIN)?(!CheckHtscanner()?$phpinipath:false):$phpinipath;?></span>
<TR><TD><B>Loaded php.ini<TD><?=version_compare(PHP_VERSION,'5.2.4','>=') ? php_ini_loaded_file() : 'N/A, PHP ver<5.2.4';?>
<TR><TD><B>phpinfo()</B><TD><INPUT TYPE="button" VALUE="Show Me" ONCLICK=window.open("<?= $_SERVER['PHP_SELF'];?>?show_phpinfo")><!--"Show me" button - shows phpinfo() in new window-->
<TR><TD><B>Install Ioncube: </B><TD ALIGN=left>
<!--ioncube
-->
<?php
if ( PHP_OS==LINUX )
{
if (strstr($phpinfo, 'ioncube'))
print (" [x] IonCube: This server has Ioncube loader installed by default<br>");
elseif ($controlpanel < 9)
print ("<INPUT TYPE=checkbox name='ioncube' value='x86' ><b>IonCube x86<b> <BR>");
else
print ("<INPUT TYPE=checkbox name='ioncube' value='x86-64'><b>IonCube x86_64<b> <BR>");
}
else print (" [x] IonCube: read <a target='_blank' href='http://wiki.opentransfer.com/doku.php/cr/info/technical/general_hosting_help/php?s[]=installed%20by%20default#ioncube_php_loader'> this </a> first<br>");
?>
<!--ioncube end-->
<TR><TD><B>Choose domains:</B>
<TD ALIGN=left><INPUT TYPE=checkbox ID="cbAll" ONCLICK=Swap(document.form.cb) CHECKED><B>All</B><BR><HR>
<span id="domains">
<img src="<?=$imgLoading;?>"> Retrieving directory list...
</span>
<TR><TD ROWSPAN=3><B>Recently used parameters:</B><BR>
<INPUT TYPE=button VALUE="Default" ONCLICK=SetDefaultParams()><INPUT TYPE=button VALUE="Recommended" ONCLICK=SetRecommendedParams()>
<TR><TD ALIGN=left>
<INPUT TYPE="CHECKBOX" NAME="parameter[register_globals]" VALUE="1" <?=ini_get('register_globals')=='1'?'CHECKED':'';?>> Register Globals<BR>
<INPUT TYPE="CHECKBOX" NAME="parameter[display_errors]" VALUE="1" <?=ini_get('display_errors')=='1'?'CHECKED':'';?>> Display Errors<BR>
<INPUT TYPE="CHECKBOX" NAME="parameter[open_basedir]" VALUE="1" <?=ini_get('open_basedir')!=''?'CHECKED':'';?>> Open base dir (for security purposes only)<BR>
<INPUT TYPE="CHECKBOX" NAME="cbPostmaster" VALUE="1" ONCLICK=SwapPostmaster()> Set envelope sender to postmaster@<domain.com>
<TR><TD><TABLE NAME="textparamtable" BORDER=1>
<THEAD><TR><TH>Name<TH>Value</THEAD>
<TBODY><FONT FACE="Courier New">
<TR><TD>mbstring.language =<TD><INPUT TYPE="TEXT" NAME="parameter[mbstring.language]" VALUE="<?=ini_get('mbstring.language');?>">
<TR><TD>mbstring.http_input =<TD><INPUT TYPE="TEXT" NAME="parameter[mbstring.http_input]" VALUE="<?=ini_get('mbstring.http_input');?>">
<TR><TD>mbstring.http_output =<TD><INPUT TYPE="TEXT" NAME="parameter[mbstring.http_output]" VALUE="<?=ini_get('mbstring.http_output');?>">
<TR><TD>session.save_path =<TD><INPUT TYPE="TEXT" NAME="parameter[session.save_path]" VALUE="<?=ini_get('session.save_path');?>">
<TR><TD>upload_max_filesize =<TD><INPUT TYPE="TEXT" NAME="parameter[upload_max_filesize]" VALUE="<?=ini_get('upload_max_filesize');?>">
<TR><TD>post_max_size =<TD><INPUT TYPE="TEXT" NAME="parameter[post_max_size]" VALUE="<?=ini_get('post_max_size');?>">
<TR><TD>sendmail_from =<TD><INPUT TYPE="TEXT" NAME="parameter[sendmail_from]" ID="tSendmailFrom" VALUE="<leave unchanged>" DISABLED>
</FONT>
</TBODY>
</TABLE>
<TR><TD><B>Additional parameters:</B><BR><!--Dynamic additional parameters textfields with help of js-->
<INPUT TYPE="button" VALUE="Add" ONCLICK="return addline();">
<TD><SPAN ID="table">
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=3>
<THEAD><TR><TH>NAME<TH>VALUE</THEAD>
<TBODY>
<TR><TD><INPUT TYPE="text" NAME="add_param_name[0]"> = <TD><INPUT TYPE="text" NAME="add_param_val[0]">
</TBODY>
</TABLE>
</SPAN>
</TBODY>
</TABLE>
<input type="hidden" name="serverPhpIniPath" value="<?=base64_encode($serverphpinipath);?>">
<input type="hidden" name="serverPhpIniFolder" value="<?=base64_encode($serverphpinifolder);?>">
</FORM>
<?php
GetDirList(); // Populate domains list
}
/* **********************
** Process submitted data
** ********************** */
else
{
// downloading ioncube
if( isset($_POST['ioncube']) )
{
$ch = curl_init("http://downloads2.ioncube.com/loader_downloads/ioncube_loaders_lin_" . $_POST['ioncube'] . ".tar.gz");
$fp = fopen($rootdir . "/ioncube.tar.gz" , "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
if ( filesize($rootdir . "/ioncube.tar.gz" ) > 1000 )
{
print ("Downloading ioncube.zip : <font color='green'><b>[ Ok ]</b></font><br>");
print `cd $rootdir && tar -xvzf $rootdir/ioncube.tar.gz > /dev/null && chmod 755 -vR $rootdir/ioncube/* > /dev/null`;
}
}
//end downloading ioncube
// Halt if nothing was selected
if( ! isset($_POST['domain']) )
{
echo '
No domains specified, nothing to do
<form>
<p><input type="submit" value="<< Back"></p>
</form>
';
exit;
}
// Remove PERL script file if it was created
if( file_exists(DIRSCANFN) )
unlink(DIRSCANFN);
$serverphpinipath = base64_decode($_POST['serverPhpIniPath']);
$serverphpinifolder = base64_decode($_POST['serverPhpIniFolder']);
$doNothing = isset($_POST['do_nothing']);
if( $doNothing )
LogMsg( 'PIG: I\'m not going to make any changes to filesystem.', true, WARN );
LoadPhpIni($php_ini_contents);
while( $element = each( $_POST[ 'parameter' ] ) )
{
if ( $element['key'] == 'sendmail_from' && $element['value'] == '<leave unchanged>' )
{
continue;
}
elseif ( $element['key'] == 'session.save_path' && $element['value'] == '' )
{
continue;
}
else
{
UpdateParameter($element['key'], $element['value']);
}
}
if( ! isset( $_POST[ 'parameter' ] [ 'register_globals' ] ) )
UpdateParameter( 'register_globals', '0' );
if( ! isset( $_POST[ 'parameter' ] [ 'display_errors' ] ) )
UpdateParameter( 'display_errors', '0' );
if( ! isset( $_POST[ 'parameter' ] [ 'open_basedir' ] ) ){
UpdateParameter( 'open_basedir', '' );
}
else {
$open_basedir = $rootdir.'/'.PATH_SEPARATOR.$tmpdir.ltrim(ini_get('include_path'),'.').PATH_SEPARATOR. $serverphpinifolder;
if(ini_get('auto_prepend_file'))
$open_basedir .= PATH_SEPARATOR.dirname(ini_get('auto_prepend_file'));
UpdateParameter( 'open_basedir', $open_basedir );
}
for($q=0;$q<=count($_POST['add_param_name'])-1;$q++)
UpdateParameter($_POST['add_param_name'][$q],$_POST['add_param_val'][$q]);
$set_postmaster=isset($_POST['cbPostmaster']);
$i = 0;
while( $element = each( $_POST[ 'domain' ] ) )
{
echo("Processing: <b>${element['value']}</b>... ");
//ioncube install
if( isset($_POST['ioncube']) )
{
UpdateParameter("zend_extension",$rootdir . "/ioncube/ioncube_loader_lin_5.2.so");
}
//end ioncube install
PlaceCustomPhpIni( $element[ 'value' ] );
echo "<font color='green'><b>[ Done ]</b></font><br>";
$i++;
}
echo "<p><b>$i</b> domains updated</p>";
?>
<P>
<table border="0">
<tr>
<td>
<table border="0">
<tr>
<td>
<FORM METHOD=GET><INPUT TYPE=SUBMIT VALUE="Suicide" NAME="btnSuicide"></FORM>
</td>
<td>
<INPUT TYPE="button" VALUE="phpinfo()" ONCLICK=window.open("<?=$_SERVER['PHP_SELF'];?>?show_phpinfo")><BR>
</td>
<td>
<FORM><INPUT TYPE=submit VALUE="<< Back"></FORM>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<input type="button" value="Generate phpinfo()" onclick="AJAXGenPHPInfo();">
<td>
</tr>
</table>
</P>
<div id="dPHPInfo"></div>
<?php
}
?>
</body>
</html>
<file_sep>/taupotrader.co.nz/language/EN/emails/html/auctionend_watchmail.inc.php
Dear {NAME},<br>
<br>
This is an automatic response from Your Item Watch.<br>
The auction closed which was on your Item Watch list.<br>
<br>
Auction Title: {TITLE}<br>
Auction URL: <a href="{URL}">{URL}</a><file_sep>/wellingtontrader.oldfrontend/language/EN/emails/text/send_email.inc.php
Dear {SELLER_NICK},
This message is sent from {SITENAME}.
{SENDER_NAME} at {SENDER_EMAIL} has a question for you regarding your auction {TITLE}.
Question:
{SENDER_QUESTION}
Auction URL: {SITEURL}item.php?id={AID}<file_sep>/taupotrader.co.nz/includes/config.inc.php
<?php
$DbHost = "traderdb.c4ohbagyv8je.ap-southeast-2.rds.amazonaws.com:3306";
$DbDatabase = "taupotrader";
$DbUser = "traderadm";
$DbPassword = <PASSWORD>";
$DBPrefix = "webid_";
$main_path = "/var/www/taupotrader.co.nz/";
$MD5_PREFIX = "653cba1edadd918e587214f8210e0b3e";
?><file_sep>/taupotrader.co.nz/cache/tpl_webid-bootsrap-standard_send_email.tpl.php
<script type="text/javascript">
function SubmitFriendForm() {
document.friend.submit();
}
function ResetFriendForm() {
document.friend.reset();
}
</script>
<div class="form-actions"> <a class="btn btn-primary" href="item.php?id=<?php echo (isset($this->_rootref['AUCT_ID'])) ? $this->_rootref['AUCT_ID'] : ''; ?>"><i class="icon-chevron-left icon-white"></i> <?php echo ((isset($this->_rootref['L_138'])) ? $this->_rootref['L_138'] : ((isset($MSG['138'])) ? $MSG['138'] : '{ L_138 }')); ?></a> </div>
<div class="row">
<div class="span6 offset3 well">
<legend> <?php echo ((isset($this->_rootref['L_645'])) ? $this->_rootref['L_645'] : ((isset($MSG['645'])) ? $MSG['645'] : '{ L_645 }')); ?> </legend>
<?php if ($this->_rootref['MESSAGE'] != ('')) { ?>
<div align="center" class="alert alert-info"><?php echo (isset($this->_rootref['MESSAGE'])) ? $this->_rootref['MESSAGE'] : ''; ?></div>
<?php } else { ?>
<FORM class="form-horizontal" NAME="sendemail" ACTION="send_email.php" METHOD=POST>
<?php if ($this->_rootref['ERROR'] != ('')) { ?>
<div class="alert alert-error"> <?php echo (isset($this->_rootref['ERROR'])) ? $this->_rootref['ERROR'] : ''; ?> </div>
<?php } ?>
<div class="control-group">
<label class="control-label" for="inputEmail"><?php echo ((isset($this->_rootref['L_125'])) ? $this->_rootref['L_125'] : ((isset($MSG['125'])) ? $MSG['125'] : '{ L_125 }')); ?></label>
<div class="controls" style="padding-top:5px;">
<INPUT TYPE="HIDDEN" NAME="seller_nick" SIZE="25" VALUE="<?php echo (isset($this->_rootref['SELLER_NICK'])) ? $this->_rootref['SELLER_NICK'] : ''; ?>">
<strong><?php echo (isset($this->_rootref['SELLER_NICK'])) ? $this->_rootref['SELLER_NICK'] : ''; ?></strong> </div>
</div>
<?php if ($this->_rootref['B_LOGGED_IN'] == (false)) { ?>
<div class="control-group">
<label class="control-label" for="inputEmail"><?php echo ((isset($this->_rootref['L_006'])) ? $this->_rootref['L_006'] : ((isset($MSG['006'])) ? $MSG['006'] : '{ L_006 }')); ?></label>
<div class="controls">
<INPUT TYPE="text" NAME="sender_email" SIZE="25" VALUE="">
</div>
</div>
<?php } ?>
<div class="control-group">
<label class="control-label" for="inputEmail"><?php echo ((isset($this->_rootref['L_017'])) ? $this->_rootref['L_017'] : ((isset($MSG['017'])) ? $MSG['017'] : '{ L_017 }')); ?></label>
<div class="controls" style="padding-top:5px;">
<INPUT TYPE="HIDDEN" NAME="item_title" SIZE="25" VALUE="<?php echo (isset($this->_rootref['ITEM_TITLE'])) ? $this->_rootref['ITEM_TITLE'] : ''; ?>">
<strong><?php echo (isset($this->_rootref['ITEM_TITLE'])) ? $this->_rootref['ITEM_TITLE'] : ''; ?></strong> </div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"><?php echo ((isset($this->_rootref['L_002'])) ? $this->_rootref['L_002'] : ((isset($MSG['002'])) ? $MSG['002'] : '{ L_002 }')); ?></label>
<div class="controls">
<INPUT TYPE="TEXT" NAME="sender_name" SIZE="25" VALUE="<?php echo (isset($this->_rootref['YOURUSERNAME'])) ? $this->_rootref['YOURUSERNAME'] : ''; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail"><?php echo ((isset($this->_rootref['L_650'])) ? $this->_rootref['L_650'] : ((isset($MSG['650'])) ? $MSG['650'] : '{ L_650 }')); ?></label>
<div class="controls">
<TEXTAREA NAME="sender_question" COLS="35" ROWS="6"><?php echo (isset($this->_rootref['SELLER_QUESTION'])) ? $this->_rootref['SELLER_QUESTION'] : ''; ?></TEXTAREA>
</div>
</div>
<INPUT TYPE="hidden" NAME="seller_email" VALUE="<?php echo (isset($this->_rootref['SELLER_EMAIL'])) ? $this->_rootref['SELLER_EMAIL'] : ''; ?>">
<INPUT TYPE="hidden" name="csrftoken" value="<?php echo (isset($this->_rootref['_CSRFTOKEN'])) ? $this->_rootref['_CSRFTOKEN'] : ''; ?>">
<INPUT TYPE="hidden" NAME="id" VALUE="<?php echo (isset($this->_rootref['AUCT_ID'])) ? $this->_rootref['AUCT_ID'] : ''; ?>">
<INPUT TYPE="hidden" NAME="action" VALUE="<?php echo ((isset($this->_rootref['L_106'])) ? $this->_rootref['L_106'] : ((isset($MSG['106'])) ? $MSG['106'] : '{ L_106 }')); ?>">
<div class="form-actions">
<INPUT TYPE=submit NAME="" VALUE="<?php echo ((isset($this->_rootref['L_5201'])) ? $this->_rootref['L_5201'] : ((isset($MSG['5201'])) ? $MSG['5201'] : '{ L_5201 }')); ?>" class="btn btn-primary" />
<?php if ($this->_rootref['B_LOGGED_IN']) { ?>
<INPUT TYPE="hidden" NAME="sender_email" SIZE="25" VALUE="<?php echo (isset($this->_rootref['EMAIL'])) ? $this->_rootref['EMAIL'] : ''; ?>">
<?php } ?>
<INPUT TYPE=reset NAME="" VALUE="<?php echo ((isset($this->_rootref['L_035'])) ? $this->_rootref['L_035'] : ((isset($MSG['035'])) ? $MSG['035'] : '{ L_035 }')); ?>" class="btn">
<p>
</TD>
</p>
</FORM>
<?php } ?>
</div>
</div>
</div><file_sep>/newzealandtrader.co.nz/script/function.php
<?php
// Database variable include
include 'config.inc.php';
// Create connection
$con = mysqli_connect($DbHost,$DbUser,$DbPassword,$DbDatabase);
// Set variables from post
$dirtyemail = $_POST['email'];
// Clean Variable
$emailaddress = mysql_real_escape_string($dirtyemail);
// Set mail variables
$to = "<EMAIL>";
$subject = "New Follower";
$txt = "Another new email address: " . $emailaddress . " Well done!";
$headers = "From: <EMAIL>";
//Check email is valid
if (filter_var($emailaddress, FILTER_VALIDATE_EMAIL))
{
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Insert email address into databse
$sql="INSERT INTO `taupotrader`(`id`, `email`) VALUES (NULL, '$emailaddress')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
// Return to confirmation page
echo header("Location:../?e=1");
mail($to,$subject,$txt,$headers);
}
mysqli_close($con);
}
// If email invalid send back home
else{
echo header("Location:../");
}
?><file_sep>/wellingtontrader.oldfrontend/language/EN/emails/text/auctionend_watchmail.inc.php
Dear {NAME},
This is an automatic response from Your Item Watch.
The auction closed which was on your Item Watch list.
Auction Title: {TITLE}
Auction URL: {URL}<file_sep>/wellingtontrader.oldfrontend/cache/tpl_webid-bootsrap-standard_global_header.tpl.php
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo (isset($this->_rootref['PAGE_TITLE'])) ? $this->_rootref['PAGE_TITLE'] : ''; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo (isset($this->_rootref['CHARSET'])) ? $this->_rootref['CHARSET'] : ''; ?>">
<meta name="description" content="<?php echo (isset($this->_rootref['DESCRIPTION'])) ? $this->_rootref['DESCRIPTION'] : ''; ?>">
<meta name="keywords" content="<?php echo (isset($this->_rootref['KEYWORDS'])) ? $this->_rootref['KEYWORDS'] : ''; ?>">
<meta name="generator" content="WeBid">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>themes/<?php echo (isset($this->_rootref['THEME'])) ? $this->_rootref['THEME'] : ''; ?>/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>themes/<?php echo (isset($this->_rootref['THEME'])) ? $this->_rootref['THEME'] : ''; ?>/css/bootstrap-responsive.css" >
<link rel="stylesheet" type="text/css" href="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>themes/<?php echo (isset($this->_rootref['THEME'])) ? $this->_rootref['THEME'] : ''; ?>/css/style.css">
<link rel="stylesheet" type="text/css" href="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>themes/<?php echo (isset($this->_rootref['THEME'])) ? $this->_rootref['THEME'] : ''; ?>/css/jquery.lightbox.css" media="screen">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>includes/calendar.css">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_924'])) ? $this->_rootref['L_924'] : ((isset($MSG['924'])) ? $MSG['924'] : '{ L_924 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=1">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_925'])) ? $this->_rootref['L_925'] : ((isset($MSG['925'])) ? $MSG['925'] : '{ L_925 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=2">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_926'])) ? $this->_rootref['L_926'] : ((isset($MSG['926'])) ? $MSG['926'] : '{ L_926 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=3">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_927'])) ? $this->_rootref['L_927'] : ((isset($MSG['927'])) ? $MSG['927'] : '{ L_927 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=4">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_928'])) ? $this->_rootref['L_928'] : ((isset($MSG['928'])) ? $MSG['928'] : '{ L_928 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=5">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_929'])) ? $this->_rootref['L_929'] : ((isset($MSG['929'])) ? $MSG['929'] : '{ L_929 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=6">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_930'])) ? $this->_rootref['L_930'] : ((isset($MSG['930'])) ? $MSG['930'] : '{ L_930 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=7">
<link rel="alternate" type="application/rss+xml" title="<?php echo ((isset($this->_rootref['L_931'])) ? $this->_rootref['L_931'] : ((isset($MSG['931'])) ? $MSG['931'] : '{ L_931 }')); ?>" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>rss.php?feed=8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>loader.php?js=<?php echo (isset($this->_rootref['JSFILES'])) ? $this->_rootref['JSFILES'] : ''; ?>"></script>
<?php if ($this->_rootref['LOADCKEDITOR']) { ?>
<script type="text/javascript" src="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>ckeditor/ckeditor.js"></script>
<?php } ?>
<script type="text/javascript" src="<?php echo (isset($this->_rootref['INCURL'])) ? $this->_rootref['INCURL'] : ''; ?>themes/<?php echo (isset($this->_rootref['THEME'])) ? $this->_rootref['THEME'] : ''; ?>/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '136945709779222', // App ID
channelUrl : 'channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<div class="navbar navbar-fixed-top hidden-desktop">
<div class="navbar-inner">
<ul class="nav pull-left" style="margin:0;">
<li class="active" style="cursor: pointer"><a style="cursor: pointer" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>index.php?"><i class="icon-home"></i></a></li>
<li class="active" style="cursor: pointer; margin-left:2px"><a style="cursor: pointer" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>browse.php?"><i class="icon-list"></i></a></li>
</ul>
<ul class="nav pull-right">
<?php if ($this->_rootref['B_LOGGED_IN']) { ?>
<li><a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>user_menu.php?cptab=summary"><i class="icon-user"></i> <?php echo ((isset($this->_rootref['L_25_0081'])) ? $this->_rootref['L_25_0081'] : ((isset($MSG['25_0081'])) ? $MSG['25_0081'] : '{ L_25_0081 }')); ?></a></li>
</li>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>logout.php?"><?php echo ((isset($this->_rootref['L_245'])) ? $this->_rootref['L_245'] : ((isset($MSG['245'])) ? $MSG['245'] : '{ L_245 }')); ?></a></li>
<?php } else { ?>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>register.php?"><?php echo ((isset($this->_rootref['L_235'])) ? $this->_rootref['L_235'] : ((isset($MSG['235'])) ? $MSG['235'] : '{ L_235 }')); ?></a></li>
<li class="divider-vertical"></li>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>user_login.php?"><i class=" icon-share-alt"></i> <?php echo ((isset($this->_rootref['L_052'])) ? $this->_rootref['L_052'] : ((isset($MSG['052'])) ? $MSG['052'] : '{ L_052 }')); ?></a></li>
<?php } ?>
</ul>
</div>
</div>
<div class="container">
<div class="row">
<div class="span12" style="position:relative">
<div class="row">
<div class="span4 logo-holder">
<h2><?php echo (isset($this->_rootref['LOGO'])) ? $this->_rootref['LOGO'] : ''; ?></h2>
</div>
<div class="span8">
<div class="hidden-phone" style="float:right;margin-top:5px; text-align:right"><?php echo (isset($this->_rootref['BANNER'])) ? $this->_rootref['BANNER'] : ''; ?></div>
</div>
</div>
</div>
</div>
<div class="navbar">
<div class="navbar-inner">
<div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a>
<div class="nav-collapse collapse">
<ul class="nav main-navigation">
<?php if ($this->_rootref['B_CAN_SELL']) { ?>
<li style="cursor: pointer"><a style="cursor: pointer" href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>index.php?"><i class="icon-home"></i></a></li>
<li class="divider-vertical"></li>
<li><a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>browse.php?"> <?php echo ((isset($this->_rootref['L_104'])) ? $this->_rootref['L_104'] : ((isset($MSG['104'])) ? $MSG['104'] : '{ L_104 }')); ?></a></li>
<li class="divider-vertical"></li>
<li><a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>select_category.php?"><?php echo ((isset($this->_rootref['L_028'])) ? $this->_rootref['L_028'] : ((isset($MSG['028'])) ? $MSG['028'] : '{ L_028 }')); ?></a></li>
<?php } ?>
<li class="divider-vertical"></li>
<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo ((isset($this->_rootref['L_276'])) ? $this->_rootref['L_276'] : ((isset($MSG['276'])) ? $MSG['276'] : '{ L_276 }')); ?> <b class="caret"></b></a>
<ul class="dropdown-menu categories-dropdown">
<div class="span9">
<div class="row">
<div class="span3 hidden-desktop">
<div class="single-cat-dopdown "> <a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>browse.php?id=0"><?php echo ((isset($this->_rootref['L_277'])) ? $this->_rootref['L_277'] : ((isset($MSG['277'])) ? $MSG['277'] : '{ L_277 }')); ?></a></div>
</div>
<?php $_cat_list_drop_count = (isset($this->_tpldata['cat_list_drop'])) ? sizeof($this->_tpldata['cat_list_drop']) : 0;if ($_cat_list_drop_count) {for ($_cat_list_drop_i = 0; $_cat_list_drop_i < $_cat_list_drop_count; ++$_cat_list_drop_i){$_cat_list_drop_val = &$this->_tpldata['cat_list_drop'][$_cat_list_drop_i]; ?>
<div class="span3">
<div class="single-cat-dopdown"> <a href="browse.php?id=<?php echo $_cat_list_val['ID']; ?>"><?php echo $_cat_list_drop_val['IMAGE']; echo $_cat_list_drop_val['NAME']; ?></a> </div>
</div>
<?php }} ?>
</div>
</div>
</ul>
</li>
<?php if ($this->_rootref['B_LOGGED_IN']) { ?>
<li class="divider-vertical"></li>
<li class="dropdown hidden-phone hidden-tablet"> <a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>user_menu.php?cptab=summary"><?php echo ((isset($this->_rootref['L_25_0081'])) ? $this->_rootref['L_25_0081'] : ((isset($MSG['25_0081'])) ? $MSG['25_0081'] : '{ L_25_0081 }')); ?></a></li>
<li class="divider-vertical"></li>
</li>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>logout.php?"><?php echo ((isset($this->_rootref['L_245'])) ? $this->_rootref['L_245'] : ((isset($MSG['245'])) ? $MSG['245'] : '{ L_245 }')); ?></a></li>
<?php } else { ?>
<li class="divider-vertical"></li>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>register.php?"><?php echo ((isset($this->_rootref['L_235'])) ? $this->_rootref['L_235'] : ((isset($MSG['235'])) ? $MSG['235'] : '{ L_235 }')); ?></a></li>
<li class="divider-vertical"></li>
<li><a href="<?php echo (isset($this->_rootref['SSLURL'])) ? $this->_rootref['SSLURL'] : ''; ?>user_login.php?"><?php echo ((isset($this->_rootref['L_052'])) ? $this->_rootref['L_052'] : ((isset($MSG['052'])) ? $MSG['052'] : '{ L_052 }')); ?></a></li>
<?php } ?>
<li class="divider-vertical hidden-phone"></li>
<form class="navbar-form pull-right" action="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>search.php" method="get">
<input type="text" class="input-medium" name="q" size="50" value="<?php echo (isset($this->_rootref['Q'])) ? $this->_rootref['Q'] : ''; ?>">
<button type="submit" class="btn btn-small" name="sub" value="<?php echo ((isset($this->_rootref['L_399'])) ? $this->_rootref['L_399'] : ((isset($MSG['399'])) ? $MSG['399'] : '{ L_399 }')); ?>" >Search</button>
</form>
</ul>
</div>
</div>
</div>
</div><file_sep>/wellingtontrader.oldfrontend/language/EN/emails/text/item_watch.inc.php
Dear {REALNAME},
This is an automatic response from Your Item Watch.
Someone has bid on an item you have added to your item watch list.
Auction Title: {TITLE}
Current Bid: {BID}
Auction URL: {AUCTION_URL}<file_sep>/taupotrader.co.nz/language/EN/emails/text/endauction_nowinner.inc.php
Dear {S_NAME},
We're sorry, your auction you created on {SITENAME} has ended with no winner
Auction URL: {A_URL}
Auction Title: {A_TITLE}
Item #: {A_ID}
End date: {A_END}<file_sep>/wellingtontrader.oldfrontend/language/EN/emails/text/endauction_winner.inc.php
Dear {S_NAME},
Congratulations your item has just sold!
Below are the details.
Auction title: {A_TITLE}
Sale price: {A_CURRENTBID}
Quantity: {A_QTY}
End date: {A_ENDS}
Auction URL: {A_URL}
Goto My {SITENAME}: {SITE_URL}user_menu.php
Buyer's Information
{B_REPORT}<file_sep>/wellingtontrader.oldfrontend/language/EN/categories.inc.php
<?php
$category_names = array(
242 => ' Businesses for sale',
408 => '$20 Electronic Cigarettes',
10 => '40s, 50s & 60s',
69 => 'Accessories',
393 => 'Accessories',
386 => 'Accommodation',
175 => 'Action Figures',
387 => 'Activities',
76 => 'Advertising',
1 => 'All',
4 => 'Amateur Art',
5 => 'Ancient World',
30 => 'Animals',
77 => 'Animals',
78 => 'Animation',
114 => 'Anime & Manga',
79 => 'Antique Reproductions',
252 => 'Apple',
302 => 'Aquaculture',
2 => 'Art & Antiques',
11 => 'Art Glass',
31 => 'Arts, Architecture & Photography',
32 => 'Audiobooks',
80 => 'Autographs',
342 => 'Aviation',
199 => 'Baby Gear',
200 => 'Baby room & furniture',
201 => 'Backpacks & carriers',
81 => 'Barber Shop',
343 => 'Basketball',
202 => 'Bath time',
271 => 'Bathroom',
228 => 'Bathroom',
176 => 'Beanie Babies & Beanbag Toys',
82 => 'Bears',
272 => 'Bedding & towels',
273 => 'Beds & bedroom furniture',
303 => 'Beekeeping',
83 => 'Bells',
33 => 'Biographies & Memoirs',
399 => 'Birds',
253 => 'Blank discs & cases',
203 => 'Blankets & covers',
144 => 'Blueray',
296 => 'Boats & marine',
29 => 'Books',
6 => 'Books & Manuscripts',
84 => 'Bottles & Cans',
204 => 'Bouncers & jolly jumpers',
344 => 'Bowls & bowling',
219 => 'Boys',
85 => 'Breweriana',
227 => 'Building & Renovation',
229 => 'Building supplies',
34 => 'Business & Investing',
331 => 'Businesses for sale',
254 => 'Cables & adaptors',
7 => 'Cameras',
345 => 'Camping & outdoors',
205 => 'Car seats',
12 => 'Carnival',
230 => 'Carpet, tiles & flooring',
86 => 'Cars & Motorcycles',
295 => 'Cars, Bikes & Boats',
35 => 'Catalogs',
400 => 'Cats',
151 => 'CDs',
8 => 'Ceramics & Glass',
87 => 'Cereal Boxes & Premiums',
13 => 'Chalkware',
88 => 'Character',
36 => 'Children',
14 => 'Chintz & Shelley',
89 => 'Circus & Carnival',
274 => 'Cleaning & bins',
206 => 'Clothing',
68 => 'Clothing & Accessories',
304 => 'Clothing, safety & workwear',
73 => 'Coins',
72 => 'Coins & Stamps',
75 => 'Collectibles',
90 => 'Collector Plates',
115 => 'Comic Books',
113 => 'Comics, Cards & Science Fiction',
330 => 'Commercial',
255 => 'Components',
256 => 'Computer furniture',
37 => 'Computers & Internet',
122 => 'Computers & Software',
38 => 'Contemporary',
15 => 'Contemporary Glass',
39 => 'Cooking, Food & Wine',
207 => 'Cots & bassinets',
346 => 'Cricket',
275 => 'Curtains & blinds',
347 => 'Cycling',
305 => 'Dairy & milking equipment',
348 => 'Dancing & gymnastics',
349 => 'Darts',
16 => 'Decorative',
257 => 'Desktops',
177 => 'Diecast',
401 => 'Dogs',
91 => 'Dolls',
258 => 'Domain names',
337 => 'Domestic services',
231 => 'Doors, windows & mouldings',
145 => 'DVD',
232 => 'Electrical & lighting',
127 => 'Electronics & Photography',
40 => 'Entertainment',
350 => 'Equestrian',
388 => 'Event tickets',
339 => 'Events & entertainment',
351 => 'Exercise equipment & weights',
259 => 'External storage',
301 => 'Farming',
243 => 'Farming & forestry',
178 => 'Fast Food',
159 => 'Fax Machines',
306 => 'Feed & feeding out',
208 => 'Feeding',
307 => 'Fencing & gates',
308 => 'Fertilising & pest control',
18 => 'Fine Art',
402 => 'Fish',
179 => 'Fisher-Price',
352 => 'Fishing',
233 => 'Fixtures & fittings',
389 => 'Flights',
276 => 'Food & beverage',
41 => 'Foreign Language Instruction',
309 => 'Forestry',
383 => 'Fragrances',
180 => 'Furby',
181 => 'Games',
19 => 'General',
42 => 'General',
92 => 'General',
116 => 'General',
146 => 'General',
152 => 'General',
163 => 'General',
182 => 'General',
183 => 'Giga Pet & Tamagotchi',
220 => 'Girls',
9 => 'Glass',
117 => 'Godzilla',
353 => 'Golf',
354 => 'Gym memberships',
381 => 'Hair care & grooming',
310 => 'Harvest & post-harvest',
311 => 'Hay making',
147 => 'HD-DVD',
378 => 'Health & Beauty',
340 => 'Health & wellbeing',
379 => 'Health care',
43 => 'Health, Mind & Body',
234 => 'Heating & cooling',
277 => 'Heating & cooling',
44 => 'Historical',
93 => 'Historical & Cultural',
45 => 'History',
184 => 'Hobbies',
355 => 'Hockey',
94 => 'Holiday & Seasonal',
390 => 'Holiday packages',
46 => 'Home & Garden',
133 => 'Home & Garden',
290 => 'Home audio & video',
278 => 'Home décor',
47 => 'Horror',
333 => 'House for sale',
95 => 'Household Items',
356 => 'Hunting & shooting',
48 => 'Illustrated',
244 => 'Industrial',
153 => 'Instruments',
125 => 'Internet Services',
312 => 'Irrigation & drainage',
357 => 'Kayaks & canoes',
221 => 'Kids unisex',
235 => 'Kitchen',
279 => 'Kitchen',
358 => 'Kites & kitesurfing',
96 => 'Kitsch',
97 => 'Knives & Swords',
280 => 'Lamps',
260 => 'Laptops',
148 => 'Laser Discs',
281 => 'Laundry',
282 => 'Lifestyle',
329 => 'Lifestyle',
49 => 'Literature & Fiction',
313 => 'Livestock',
314 => 'Livestock health & management',
315 => 'Loading & lifting',
403 => 'Lost & found',
192 => 'lot Cars',
283 => 'Lounge, dining & hall',
284 => 'Luggage & travel accessories',
98 => 'Lunchboxes',
99 => 'Magic & Novelty Items',
382 => 'Makeup & skin care',
185 => 'Marbles',
359 => 'Martial arts & boxing',
292 => 'Media & consumables',
100 => 'Memorabilia',
154 => 'Memorabilia',
50 => 'Men',
222 => 'Menswear',
164 => 'Metaphysical',
404 => 'Mice & rodents',
101 => 'Militaria',
392 => 'Mobile Phones',
394 => 'Mobile phones',
209 => 'Monitors',
261 => 'Monitors',
299 => 'Motorbikes',
143 => 'Movies & Video',
150 => 'Music',
102 => 'Music Boxes',
20 => 'Musical Instruments',
186 => 'My Little Pony',
51 => 'Mystery & Thrillers',
210 => 'Nappies & changing',
262 => 'Networking & modems',
297 => 'New cars',
52 => 'News',
53 => 'Nonfiction',
103 => 'Oddities',
157 => 'Office & Business',
245 => 'Office equipment & supplies',
246 => 'Office furniture',
327 => 'Open homes',
21 => 'Orientalia',
217 => 'Other',
240 => 'Other',
250 => 'Other',
270 => 'Other',
324 => 'Other',
376 => 'Other',
391 => 'Other',
407 => 'Other',
293 => 'Other electronics',
162 => 'Other Goods & Services',
380 => 'Other health & beauty',
338 => 'Other services',
300 => 'Other vehicles',
285 => 'Outdoor, garden & conservatory',
360 => 'Paintball',
22 => 'Painting',
236 => 'Painting & wallpaper',
104 => 'Paper',
54 => 'Parenting & Families',
286 => 'Party & festive supplies',
316 => 'Pasture & lawn maintenance',
263 => 'PDAs & handhelds',
187 => 'Peanuts Gang',
264 => 'Peripherals',
294 => 'Personal audio & iPods',
398 => 'Pets & Animals',
188 => 'Pez',
74 => 'Philately',
23 => 'Photographic Images',
291 => 'Photography',
105 => 'Pinbacks',
317 => 'Planting',
189 => 'Plastic Models',
237 => 'Plumbing & gas',
190 => 'Plush Toys',
55 => 'Poetry',
17 => 'Porcelain',
106 => 'Porcelain Figurines',
238 => 'Portable buildings',
24 => 'Post-1900',
247 => 'Postage & packing supplies',
318 => 'Poultry',
211 => 'Prams & strollers',
25 => 'Pre-1900',
265 => 'Printer accessories & supplies',
266 => 'Printers',
26 => 'Prints',
165 => 'Property',
191 => 'Puzzles',
405 => 'Rabbits & Guinea pigs',
361 => 'Racquet sports',
107 => 'Railroadiana',
56 => 'Rare',
326 => 'Real Estate & Flatmates Wanted',
155 => 'Records',
57 => 'Reference',
58 => 'Regency',
59 => 'Religion & Spirituality',
108 => 'Religious',
395 => 'Replacement parts & components',
406 => 'Reptiles & turtles',
248 => 'Retail & hospitality',
109 => 'Rocks, Minerals & Fossils',
362 => 'Rugby & league',
363 => 'Running, track & field',
328 => 'Rural',
212 => 'Safety',
60 => 'Science & Nature',
61 => 'Science Fiction & Fantasy',
27 => 'Scientific Instruments',
110 => 'Scientific Instruments',
364 => 'SCUBA & snorkelling',
332 => 'Section',
287 => 'Security, locks & alarms',
267 => 'Servers',
166 => 'Services',
335 => 'Services',
319 => 'Shearing & grooming',
28 => 'Silver & Silver Plate',
396 => 'SIM cards',
365 => 'Skateboarding & rollerblading',
366 => 'Ski & board',
213 => 'Sleep aids',
367 => 'Snooker & pool',
368 => 'Soccer',
369 => 'Softball & baseball',
126 => 'Software',
268 => 'Software',
320 => 'Soil cultivation',
62 => 'Sports',
63 => 'Sports & Outdoors',
170 => 'Sports & Recreation',
370 => 'Sports memorabilia',
118 => 'Star Trek',
371 => 'Surfing',
156 => 'Tapes',
64 => 'Teens',
214 => 'Teething necklaces',
193 => 'Teletubbies',
65 => 'Textbooks',
111 => 'Textiles',
3 => 'Textiles & Linens',
119 => 'The X-Files',
167 => 'Tickets & Events',
334 => 'To Rent',
112 => 'Tobacciana',
239 => 'Tools',
194 => 'Toy Soldiers',
120 => 'Toys',
215 => 'Toys',
174 => 'Toys & Games',
321 => 'Tractors',
336 => 'Trades',
121 => 'Trading Cards',
372 => 'Trading cards',
322 => 'Trailers & transportation',
168 => 'Transportation',
66 => 'Travel',
169 => 'Travel',
385 => 'Travel, Events & Activities',
223 => 'Unisex accessories',
298 => 'Used cars',
149 => 'VHS',
195 => 'Vintage',
269 => 'Vintage',
196 => 'Vintage Tin',
197 => 'Vintage Vehicles',
323 => 'Viticulture & winemaking',
216 => 'Walkers',
71 => 'Watches',
373 => 'Waterskiing & wakeboarding',
224 => 'Wedding',
384 => 'Weight Loss',
374 => 'Wetsuits & lifejackets',
249 => 'Wholesale lots',
375 => 'Windsurfing',
288 => 'Wine',
67 => 'Women',
225 => 'Womenswear'
);
$category_plain = array(
0 => '',
408 => '$20 Electronic Cigarettes',
398 => 'Pets & Animals',
407 => '|___Other',
406 => '|___Reptiles & turtles',
405 => '|___Rabbits & Guinea pigs',
404 => '|___Mice & rodents',
403 => '|___Lost & found',
402 => '|___Fish',
401 => '|___Dogs',
400 => '|___Cats',
399 => '|___Birds',
392 => 'Mobile Phones',
396 => '|___SIM cards',
395 => '|___Replacement parts & components',
394 => '|___Mobile phones',
393 => '|___Accessories',
385 => 'Travel, Events & Activities',
391 => '|___Other',
390 => '|___Holiday packages',
389 => '|___Flights',
388 => '|___Event tickets',
387 => '|___Activities',
386 => '|___Accommodation',
378 => 'Health & Beauty',
384 => '|___Weight Loss',
383 => '|___Fragrances',
382 => '|___Makeup & skin care',
381 => '|___Hair care & grooming',
380 => '|___Other health & beauty',
379 => '|___Health care',
335 => 'Services',
340 => '|___Health & wellbeing',
339 => '|___Events & entertainment',
338 => '|___Other services',
337 => '|___Domestic services',
336 => '|___Trades',
326 => 'Real Estate & Flatmates Wanted',
334 => '|___To Rent',
333 => '|___House for sale',
332 => '|___Section',
331 => '|___Businesses for sale',
330 => '|___Commercial',
329 => '|___Lifestyle',
328 => '|___Rural',
327 => '|___Open homes',
301 => 'Farming',
324 => '|___Other',
323 => '|___Viticulture & winemaking',
322 => '|___Trailers & transportation',
321 => '|___Tractors',
320 => '|___Soil cultivation',
319 => '|___Shearing & grooming',
318 => '|___Poultry',
317 => '|___Planting',
316 => '|___Pasture & lawn maintenance',
315 => '|___Loading & lifting',
314 => '|___Livestock health & management',
313 => '|___Livestock',
312 => '|___Irrigation & drainage',
311 => '|___Hay making',
310 => '|___Harvest & post-harvest',
309 => '|___Forestry',
308 => '|___Fertilising & pest control',
307 => '|___Fencing & gates',
306 => '|___Feed & feeding out',
305 => '|___Dairy & milking equipment',
304 => '|___Clothing, safety & workwear',
303 => '|___Beekeeping',
302 => '|___Aquaculture',
295 => 'Cars, Bikes & Boats',
300 => '|___Other vehicles',
299 => '|___Motorbikes',
298 => '|___Used cars',
297 => '|___New cars',
296 => '|___Boats & marine',
227 => 'Building & Renovation',
240 => '|___Other',
239 => '|___Tools',
238 => '|___Portable buildings',
237 => '|___Plumbing & gas',
236 => '|___Painting & wallpaper',
235 => '|___Kitchen',
234 => '|___Heating & cooling',
233 => '|___Fixtures & fittings',
232 => '|___Electrical & lighting',
231 => '|___Doors, windows & mouldings',
230 => '|___Carpet, tiles & flooring',
229 => '|___Building supplies',
228 => '|___Bathroom',
199 => 'Baby Gear',
217 => '|___Other',
216 => '|___Walkers',
215 => '|___Toys',
214 => '|___Teething necklaces',
213 => '|___Sleep aids',
212 => '|___Safety',
211 => '|___Prams & strollers',
210 => '|___Nappies & changing',
209 => '|___Monitors',
208 => '|___Feeding',
207 => '|___Cots & bassinets',
206 => '|___Clothing',
205 => '|___Car seats',
204 => '|___Bouncers & jolly jumpers',
203 => '|___Blankets & covers',
202 => '|___Bath time',
201 => '|___Backpacks & carriers',
200 => '|___Baby room & furniture',
174 => 'Toys & Games',
197 => '|___Vintage Vehicles',
196 => '|___Vintage Tin',
195 => '|___Vintage',
194 => '|___Toy Soldiers',
193 => '|___Teletubbies',
192 => '|___lot Cars',
191 => '|___Puzzles',
190 => '|___Plush Toys',
189 => '|___Plastic Models',
188 => '|___Pez',
187 => '|___Peanuts Gang',
186 => '|___My Little Pony',
185 => '|___Marbles',
184 => '|___Hobbies',
183 => '|___Giga Pet & Tamagotchi',
182 => '|___General',
181 => '|___Games',
180 => '|___Furby',
179 => '|___Fisher-Price',
178 => '|___Fast Food',
177 => '|___Diecast',
176 => '|___Beanie Babies & Beanbag Toys',
175 => '|___Action Figures',
170 => 'Sports & Recreation',
376 => '|___Other',
375 => '|___Windsurfing',
374 => '|___Wetsuits & lifejackets',
373 => '|___Waterskiing & wakeboarding',
372 => '|___Trading cards',
371 => '|___Surfing',
370 => '|___Sports memorabilia',
369 => '|___Softball & baseball',
368 => '|___Soccer',
367 => '|___Snooker & pool',
366 => '|___Ski & board',
365 => '|___Skateboarding & rollerblading',
364 => '|___SCUBA & snorkelling',
363 => '|___Running, track & field',
362 => '|___Rugby & league',
361 => '|___Racquet sports',
360 => '|___Paintball',
359 => '|___Martial arts & boxing',
358 => '|___Kites & kitesurfing',
357 => '|___Kayaks & canoes',
356 => '|___Hunting & shooting',
355 => '|___Hockey',
354 => '|___Gym memberships',
353 => '|___Golf',
352 => '|___Fishing',
351 => '|___Exercise equipment & weights',
350 => '|___Equestrian',
349 => '|___Darts',
348 => '|___Dancing & gymnastics',
347 => '|___Cycling',
346 => '|___Cricket',
345 => '|___Camping & outdoors',
344 => '|___Bowls & bowling',
343 => '|___Basketball',
342 => '|___Aviation',
162 => 'Other Goods & Services',
169 => '|___Travel',
168 => '|___Transportation',
167 => '|___Tickets & Events',
166 => '|___Services',
165 => '|___Property',
164 => '|___Metaphysical',
163 => '|___General',
157 => 'Office & Business',
250 => '|___Other',
249 => '|___Wholesale lots',
248 => '|___Retail & hospitality',
247 => '|___Postage & packing supplies',
246 => '|___Office furniture',
245 => '|___Office equipment & supplies',
244 => '|___Industrial',
243 => '|___Farming & forestry',
242 => '|___ Businesses for sale',
159 => '|___Fax Machines',
150 => 'Music',
156 => '|___Tapes',
155 => '|___Records',
154 => '|___Memorabilia',
153 => '|___Instruments',
152 => '|___General',
151 => '|___CDs',
143 => 'Movies & Video',
149 => '|___VHS',
148 => '|___Laser Discs',
147 => '|___HD-DVD',
146 => '|___General',
145 => '|___DVD',
144 => '|___Blueray',
133 => 'Home & Garden',
288 => '|___Wine',
287 => '|___Security, locks & alarms',
286 => '|___Party & festive supplies',
285 => '|___Outdoor, garden & conservatory',
284 => '|___Luggage & travel accessories',
283 => '|___Lounge, dining & hall',
282 => '|___Lifestyle',
281 => '|___Laundry',
280 => '|___Lamps',
279 => '|___Kitchen',
278 => '|___Home décor',
277 => '|___Heating & cooling',
276 => '|___Food & beverage',
275 => '|___Curtains & blinds',
274 => '|___Cleaning & bins',
273 => '|___Beds & bedroom furniture',
272 => '|___Bedding & towels',
271 => '|___Bathroom',
127 => 'Electronics & Photography',
294 => '|___Personal audio & iPods',
293 => '|___Other electronics',
292 => '|___Media & consumables',
291 => '|___Photography',
290 => '|___Home audio & video',
122 => 'Computers & Software',
270 => '|___Other',
269 => '|___Vintage',
268 => '|___Software',
267 => '|___Servers',
266 => '|___Printers',
265 => '|___Printer accessories & supplies',
264 => '|___Peripherals',
263 => '|___PDAs & handhelds',
262 => '|___Networking & modems',
261 => '|___Monitors',
260 => '|___Laptops',
259 => '|___External storage',
258 => '|___Domain names',
257 => '|___Desktops',
256 => '|___Computer furniture',
255 => '|___Components',
254 => '|___Cables & adaptors',
253 => '|___Blank discs & cases',
252 => '|___Apple',
126 => '|___Software',
125 => '|___Internet Services',
113 => 'Comics, Cards & Science Fiction',
121 => '|___Trading Cards',
120 => '|___Toys',
119 => '|___The X-Files',
118 => '|___Star Trek',
117 => '|___Godzilla',
116 => '|___General',
115 => '|___Comic Books',
114 => '|___Anime & Manga',
75 => 'Collectibles',
112 => '|___Tobacciana',
111 => '|___Textiles',
110 => '|___Scientific Instruments',
109 => '|___Rocks, Minerals & Fossils',
108 => '|___Religious',
107 => '|___Railroadiana',
106 => '|___Porcelain Figurines',
105 => '|___Pinbacks',
104 => '|___Paper',
103 => '|___Oddities',
102 => '|___Music Boxes',
101 => '|___Militaria',
100 => '|___Memorabilia',
99 => '|___Magic & Novelty Items',
98 => '|___Lunchboxes',
97 => '|___Knives & Swords',
96 => '|___Kitsch',
95 => '|___Household Items',
94 => '|___Holiday & Seasonal',
93 => '|___Historical & Cultural',
92 => '|___General',
91 => '|___Dolls',
90 => '|___Collector Plates',
89 => '|___Circus & Carnival',
88 => '|___Character',
87 => '|___Cereal Boxes & Premiums',
86 => '|___Cars & Motorcycles',
85 => '|___Breweriana',
84 => '|___Bottles & Cans',
83 => '|___Bells',
82 => '|___Bears',
81 => '|___Barber Shop',
80 => '|___Autographs',
79 => '|___Antique Reproductions',
78 => '|___Animation',
77 => '|___Animals',
76 => '|___Advertising',
72 => 'Coins & Stamps',
74 => '|___Philately',
73 => '|___Coins',
68 => 'Clothing & Accessories',
225 => '|___Womenswear',
224 => '|___Wedding',
223 => '|___Unisex accessories',
222 => '|___Menswear',
221 => '|___Kids unisex',
220 => '|___Girls',
219 => '|___Boys',
71 => '|___Watches',
69 => '|___Accessories',
29 => 'Books',
67 => '|___Women',
66 => '|___Travel',
65 => '|___Textbooks',
64 => '|___Teens',
63 => '|___Sports & Outdoors',
62 => '|___Sports',
61 => '|___Science Fiction & Fantasy',
60 => '|___Science & Nature',
59 => '|___Religion & Spirituality',
58 => '|___Regency',
57 => '|___Reference',
56 => '|___Rare',
55 => '|___Poetry',
54 => '|___Parenting & Families',
53 => '|___Nonfiction',
52 => '|___News',
51 => '|___Mystery & Thrillers',
50 => '|___Men',
49 => '|___Literature & Fiction',
48 => '|___Illustrated',
47 => '|___Horror',
46 => '|___Home & Garden',
45 => '|___History',
44 => '|___Historical',
43 => '|___Health, Mind & Body',
42 => '|___General',
41 => '|___Foreign Language Instruction',
40 => '|___Entertainment',
39 => '|___Cooking, Food & Wine',
38 => '|___Contemporary',
37 => '|___Computers & Internet',
36 => '|___Children',
35 => '|___Catalogs',
34 => '|___Business & Investing',
33 => '|___Biographies & Memoirs',
32 => '|___Audiobooks',
31 => '|___Arts, Architecture & Photography',
30 => '|___Animals',
2 => 'Art & Antiques',
28 => '|___Silver & Silver Plate',
27 => '|___Scientific Instruments',
26 => '|___Prints',
25 => '|___Pre-1900',
24 => '|___Post-1900',
23 => '|___Photographic Images',
22 => '|___Painting',
21 => '|___Orientalia',
20 => '|___Musical Instruments',
19 => '|___General',
18 => '|___Fine Art',
8 => '|___Ceramics & Glass',
9 => '|___|___Glass',
17 => '|___|___|___Porcelain',
16 => '|___|___|___Decorative',
15 => '|___|___|___Contemporary Glass',
14 => '|___|___|___Chintz & Shelley',
13 => '|___|___|___Chalkware',
12 => '|___|___|___Carnival',
11 => '|___|___|___Art Glass',
10 => '|___|___|___40s, 50s & 60s',
7 => '|___Cameras',
6 => '|___Books & Manuscripts',
5 => '|___Ancient World',
4 => '|___Amateur Art',
3 => '|___Textiles & Linens');
?><file_sep>/taupotrader.co.nz/cache/tpl_webid-bootsrap-standard_yourauctions_p.tpl.php
<script type="text/javascript">
$(document).ready(function() {
$("#startall").click(function() {
var checked_status = this.checked;
$("input[name=startnow[]]").each(function() {
this.checked = checked_status;
});
});
$("#deleteall").click(function() {
var checked_status = this.checked;
$("input[name=O_delete[]]").each(function() {
this.checked = checked_status;
});
});
$("#processdel").submit(function() {
if (confirm('<?php echo ((isset($this->_rootref['L_30_0087'])) ? $this->_rootref['L_30_0087'] : ((isset($MSG['30_0087'])) ? $MSG['30_0087'] : '{ L_30_0087 }')); ?>')){
return true;
} else {
return false;
}
});
});
</script>
<div class="row">
<div class="span3">
<div class="well" style="max-width: 340px; padding: 8px 0;">
<ul class="nav nav-list">
<li class="nav-header"><?php echo ((isset($this->_rootref['L_205'])) ? $this->_rootref['L_205'] : ((isset($MSG['205'])) ? $MSG['205'] : '{ L_205 }')); ?></li>
<li class="active"><a href="#"><?php echo ((isset($this->_rootref['L_25_0080'])) ? $this->_rootref['L_25_0080'] : ((isset($MSG['25_0080'])) ? $MSG['25_0080'] : '{ L_25_0080 }')); ?></a></li>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0083'])) ? $this->_rootref['L_25_0083'] : ((isset($MSG['25_0083'])) ? $MSG['25_0083'] : '{ L_25_0083 }')); ?></li>
<li><a href="auction_watch.php"><?php echo ((isset($this->_rootref['L_471'])) ? $this->_rootref['L_471'] : ((isset($MSG['471'])) ? $MSG['471'] : '{ L_471 }')); ?></a></li>
<li><a href="item_watch.php"><?php echo ((isset($this->_rootref['L_472'])) ? $this->_rootref['L_472'] : ((isset($MSG['472'])) ? $MSG['472'] : '{ L_472 }')); ?></a></li>
<li><a href="yourbids.php"><?php echo ((isset($this->_rootref['L_620'])) ? $this->_rootref['L_620'] : ((isset($MSG['620'])) ? $MSG['620'] : '{ L_620 }')); ?></a></li>
<li><a href="buying.php"><?php echo ((isset($this->_rootref['L_454'])) ? $this->_rootref['L_454'] : ((isset($MSG['454'])) ? $MSG['454'] : '{ L_454 }')); ?></a></li>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0081'])) ? $this->_rootref['L_25_0081'] : ((isset($MSG['25_0081'])) ? $MSG['25_0081'] : '{ L_25_0081 }')); ?></li>
<li><a href="edit_data.php"><?php echo ((isset($this->_rootref['L_621'])) ? $this->_rootref['L_621'] : ((isset($MSG['621'])) ? $MSG['621'] : '{ L_621 }')); ?></a></li>
<li><a href="yourfeedback.php"><?php echo ((isset($this->_rootref['L_208'])) ? $this->_rootref['L_208'] : ((isset($MSG['208'])) ? $MSG['208'] : '{ L_208 }')); ?></a></li>
<li><a href="buysellnofeedback.php"><?php echo ((isset($this->_rootref['L_207'])) ? $this->_rootref['L_207'] : ((isset($MSG['207'])) ? $MSG['207'] : '{ L_207 }')); ?></a> <small><span class="muted"><em><?php echo (isset($this->_rootref['FBTOLEAVE'])) ? $this->_rootref['FBTOLEAVE'] : ''; ?></em></span></small></li>
<li><a href="mail.php"><?php echo ((isset($this->_rootref['L_623'])) ? $this->_rootref['L_623'] : ((isset($MSG['623'])) ? $MSG['623'] : '{ L_623 }')); ?></a> <small><span class="muted"><em><?php echo (isset($this->_rootref['NEWMESSAGES'])) ? $this->_rootref['NEWMESSAGES'] : ''; ?></em></span></small></li>
<li><a href="outstanding.php"><?php echo ((isset($this->_rootref['L_422'])) ? $this->_rootref['L_422'] : ((isset($MSG['422'])) ? $MSG['422'] : '{ L_422 }')); ?></a></li>
<?php if ($this->_rootref['B_CAN_SELL']) { ?>
<li class="nav-header"><?php echo ((isset($this->_rootref['L_25_0082'])) ? $this->_rootref['L_25_0082'] : ((isset($MSG['25_0082'])) ? $MSG['25_0082'] : '{ L_25_0082 }')); ?></li>
<li><a href="select_category.php"><?php echo ((isset($this->_rootref['L_028'])) ? $this->_rootref['L_028'] : ((isset($MSG['028'])) ? $MSG['028'] : '{ L_028 }')); ?></a></li>
<li><a href="selleremails.php"><?php echo ((isset($this->_rootref['L_25_0188'])) ? $this->_rootref['L_25_0188'] : ((isset($MSG['25_0188'])) ? $MSG['25_0188'] : '{ L_25_0188 }')); ?></a></li>
<li><a href="yourauctions_p.php"><?php echo ((isset($this->_rootref['L_25_0115'])) ? $this->_rootref['L_25_0115'] : ((isset($MSG['25_0115'])) ? $MSG['25_0115'] : '{ L_25_0115 }')); ?></a></li>
<li><a href="yourauctions.php"><?php echo ((isset($this->_rootref['L_203'])) ? $this->_rootref['L_203'] : ((isset($MSG['203'])) ? $MSG['203'] : '{ L_203 }')); ?></a></li>
<li><a href="yourauctions_c.php"><?php echo ((isset($this->_rootref['L_204'])) ? $this->_rootref['L_204'] : ((isset($MSG['204'])) ? $MSG['204'] : '{ L_204 }')); ?></a></li>
<li><a href="yourauctions_s.php"><?php echo ((isset($this->_rootref['L_2__0056'])) ? $this->_rootref['L_2__0056'] : ((isset($MSG['2__0056'])) ? $MSG['2__0056'] : '{ L_2__0056 }')); ?></a></li>
<li><a href="yourauctions_sold.php"><?php echo ((isset($this->_rootref['L_25_0119'])) ? $this->_rootref['L_25_0119'] : ((isset($MSG['25_0119'])) ? $MSG['25_0119'] : '{ L_25_0119 }')); ?></a></li>
<li><a href="selling.php"><?php echo ((isset($this->_rootref['L_453'])) ? $this->_rootref['L_453'] : ((isset($MSG['453'])) ? $MSG['453'] : '{ L_453 }')); ?></a><br>
<?php } ?>
</li>
</ul>
</div>
</div>
<div class="span9">
<legend><?php echo ((isset($this->_rootref['L_25_0115'])) ? $this->_rootref['L_25_0115'] : ((isset($MSG['25_0115'])) ? $MSG['25_0115'] : '{ L_25_0115 }')); ?></legend>
<form name="open" method="post" action="" id="processdel">
<input type="hidden" name="csrftoken" value="<?php echo (isset($this->_rootref['_CSRFTOKEN'])) ? $this->_rootref['_CSRFTOKEN'] : ''; ?>">
<small><span class="muted"><?php echo ((isset($this->_rootref['L_5117'])) ? $this->_rootref['L_5117'] : ((isset($MSG['5117'])) ? $MSG['5117'] : '{ L_5117 }')); ?> <?php echo (isset($this->_rootref['PAGE'])) ? $this->_rootref['PAGE'] : ''; ?> <?php echo ((isset($this->_rootref['L_5118'])) ? $this->_rootref['L_5118'] : ((isset($MSG['5118'])) ? $MSG['5118'] : '{ L_5118 }')); ?> <?php echo (isset($this->_rootref['PAGES'])) ? $this->_rootref['PAGES'] : ''; ?></span></small>
<table class="table table-bordered table-condensed table-striped">
<tr>
<td ><a href="yourauctions_p.php?pa_ord=title&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_624'])) ? $this->_rootref['L_624'] : ((isset($MSG['624'])) ? $MSG['624'] : '{ L_624 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('title')) { ?>
<a href="yourauctions_p.php?pa_ord=title&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="15%"><a href="yourauctions_p.php?pa_ord=starts&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_25_0116'])) ? $this->_rootref['L_25_0116'] : ((isset($MSG['25_0116'])) ? $MSG['25_0116'] : '{ L_25_0116 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('starts')) { ?>
<a href="yourauctions_p.php?pa_ord=starts&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="15%"><a href="yourauctions_p.php?pa_ord=ends&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo ((isset($this->_rootref['L_25_0117'])) ? $this->_rootref['L_25_0117'] : ((isset($MSG['25_0117'])) ? $MSG['25_0117'] : '{ L_25_0117 }')); ?></a>
<?php if ($this->_rootref['ORDERCOL'] == ('ends')) { ?>
<a href="yourauctions_p.php?pa_ord=ends&pa_type=<?php echo (isset($this->_rootref['ORDERNEXT'])) ? $this->_rootref['ORDERNEXT'] : ''; ?>"><?php echo (isset($this->_rootref['ORDERTYPEIMG'])) ? $this->_rootref['ORDERTYPEIMG'] : ''; ?></a>
<?php } ?>
</td>
<td width="10%" align="center"> <?php echo ((isset($this->_rootref['L_298'])) ? $this->_rootref['L_298'] : ((isset($MSG['298'])) ? $MSG['298'] : '{ L_298 }')); ?> </td>
<td width="10%" align="center"> <?php echo ((isset($this->_rootref['L_008'])) ? $this->_rootref['L_008'] : ((isset($MSG['008'])) ? $MSG['008'] : '{ L_008 }')); ?> </td>
<td width="9%" align="center"> <?php echo ((isset($this->_rootref['L_25_0118'])) ? $this->_rootref['L_25_0118'] : ((isset($MSG['25_0118'])) ? $MSG['25_0118'] : '{ L_25_0118 }')); ?> </td>
</tr>
<?php if ($this->_rootref['B_AREITEMS']) { $_items_count = (isset($this->_tpldata['items'])) ? sizeof($this->_tpldata['items']) : 0;if ($_items_count) {for ($_items_i = 0; $_items_i < $_items_count; ++$_items_i){$_items_val = &$this->_tpldata['items'][$_items_i]; ?>
<tr>
<td width="32%"><a href="item.php?id=<?php echo $_items_val['ID']; ?>"><?php echo $_items_val['TITLE']; ?></a> </td>
<td width="11%"><small><?php echo $_items_val['STARTS']; ?></small> </td>
<td width="11%"><small><?php echo $_items_val['ENDS']; ?></small> </td>
<td width="6%" align="center"><?php if ($_items_val['B_HASNOBIDS']) { ?>
<a href="edit_active_auction.php?id=<?php echo $_items_val['ID']; ?>"><img src="images/edititem.gif" width="13" height="17" alt="<?php echo ((isset($this->_rootref['L_512'])) ? $this->_rootref['L_512'] : ((isset($MSG['512'])) ? $MSG['512'] : '{ L_512 }')); ?>" border="0"></a>
<?php } ?>
</td>
<td width="8%" align="center"><?php if ($_items_val['B_HASNOBIDS']) { ?>
<input type="checkbox" name="O_delete[]" value="<?php echo $_items_val['ID']; ?>">
<?php } ?>
</td>
<td width="6%" align="center"><input type="checkbox" name="startnow[]" value="<?php echo $_items_val['ID']; ?>">
</td>
</tr>
<?php }} } ?>
<tr <?php echo (isset($this->_rootref['BGCOLOUR'])) ? $this->_rootref['BGCOLOUR'] : ''; ?>>
<td colspan="4" style="text-align:right;"><small><span class="muted"><?php echo ((isset($this->_rootref['L_30_0102'])) ? $this->_rootref['L_30_0102'] : ((isset($MSG['30_0102'])) ? $MSG['30_0102'] : '{ L_30_0102 }')); ?></span></small></td>
<td align="center"><input type="checkbox" id="deleteall"></td>
<td align="center"><input type="checkbox" id="startall"></td>
</tr>
<tr>
<td colspan="10" align="center"><input type="hidden" name="action" value="delopenauctions">
<input type="submit" name="Submit" value="<?php echo ((isset($this->_rootref['L_631'])) ? $this->_rootref['L_631'] : ((isset($MSG['631'])) ? $MSG['631'] : '{ L_631 }')); ?>" class="btn btn-primary">
</td>
</tr>
</table>
</form>
<div class="pagination pagination-centered">
<ul>
<li><?php echo (isset($this->_rootref['PREV'])) ? $this->_rootref['PREV'] : ''; ?></li>
<?php $_pages_count = (isset($this->_tpldata['pages'])) ? sizeof($this->_tpldata['pages']) : 0;if ($_pages_count) {for ($_pages_i = 0; $_pages_i < $_pages_count; ++$_pages_i){$_pages_val = &$this->_tpldata['pages'][$_pages_i]; ?>
<li><?php echo $_pages_val['PAGE']; ?></li>
<?php }} ?>
<li><?php echo (isset($this->_rootref['NEXT'])) ? $this->_rootref['NEXT'] : ''; ?></li>
</ul>
</div>
</div>
<?php $this->_tpl_include('user_menu_footer.tpl'); ?><file_sep>/taupotrader.co.nz/cache/tpl_webid-bootsrap-standard_browsecats.tpl.php
<div>
<ul class="breadcrumb">
<li class="active"><?php echo ((isset($this->_rootref['L_287'])) ? $this->_rootref['L_287'] : ((isset($MSG['287'])) ? $MSG['287'] : '{ L_287 }')); ?> : </li>
<?php echo (isset($this->_rootref['CAT_STRING'])) ? $this->_rootref['CAT_STRING'] : ''; ?>
</ul>
</div>
<div class="row ">
<div class="span3 hidden-phone"> <?php echo (isset($this->_rootref['cat_name'])) ? $this->_rootref['cat_name'] : ''; ?>
<div class="row">
<div id="cat-list-holder" class="span3" style="position:relative;">
<ul class="nav nav-list cat-list" data-spy="affix" data-offset-top="278">
<li class="nav-header"><?php echo ((isset($this->_rootref['L_276'])) ? $this->_rootref['L_276'] : ((isset($MSG['276'])) ? $MSG['276'] : '{ L_276 }')); ?></li>
<li class="divider"></li>
<li><a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>browse.php?id=0"><i class="icon-tags"></i> <?php echo ((isset($this->_rootref['L_277'])) ? $this->_rootref['L_277'] : ((isset($MSG['277'])) ? $MSG['277'] : '{ L_277 }')); ?></a></li>
<li class="divider"></li>
<?php $_cat_list_count = (isset($this->_tpldata['cat_list'])) ? sizeof($this->_tpldata['cat_list']) : 0;if ($_cat_list_count) {for ($_cat_list_i = 0; $_cat_list_i < $_cat_list_count; ++$_cat_list_i){$_cat_list_val = &$this->_tpldata['cat_list'][$_cat_list_i]; ?>
<li> <a href="browse.php?id=<?php echo $_cat_list_val['ID']; ?>"><?php echo $_cat_list_val['IMAGE']; ?> <?php echo $_cat_list_val['NAME']; ?></a></li>
<?php }} ?>
</ul>
</div>
</div>
</div>
<div class="row">
<div id="browser-holder" class="span9">
<div class="">
<legend><?php echo (isset($this->_rootref['CUR_CAT'])) ? $this->_rootref['CUR_CAT'] : ''; ?></legend>
<br />
<button id="sub-cats-btn"
<?php if ($this->_rootref['TOP_HTML'] == ('')) { ?>
style="display:none;"
<?php } ?>
type="button" class="btn btn-small" data-toggle="collapse" data-target="#sub-cats"><?php echo ((isset($this->_rootref['L_31_1'])) ? $this->_rootref['L_31_1'] : ((isset($MSG['31_1'])) ? $MSG['31_1'] : '{ L_31_1 }')); ?>
</button>
<?php if ($this->_rootref['NUM_AUCTIONS'] == 0) { ?>
<div class="alert alert-info" style="margin-top:10px"><i class="icon-info-sign icon-white"></i> <strong><?php echo ((isset($this->_rootref['L_198'])) ? $this->_rootref['L_198'] : ((isset($MSG['198'])) ? $MSG['198'] : '{ L_198 }')); ?></strong> </div>
<?php } if ($this->_rootref['TOP_HTML'] != ('')) { ?>
<div id="sub-cats" class="collapse" style="margin-top:10px"> <small> <?php echo (isset($this->_rootref['TOP_HTML'])) ? $this->_rootref['TOP_HTML'] : ''; ?> </small> </div>
</div>
<?php } else { } ?>
<div class="row">
<div class="span9">
<?php if ($this->_rootref['ID'] > 0 && $this->_rootref['NUM_AUCTIONS'] > 0) { ?>
<div class="form-actions">
<div class="row">
<div class="span4">
<form name="catsearch" action="?id=<?php echo (isset($this->_rootref['ID'])) ? $this->_rootref['ID'] : ''; ?>" method="post" >
<input type="hidden" name="csrftoken" value="<?php echo (isset($this->_rootref['_CSRFTOKEN'])) ? $this->_rootref['_CSRFTOKEN'] : ''; ?>">
<div class="input-append">
<input type="text" placeholder="<?php echo ((isset($this->_rootref['L_287'])) ? $this->_rootref['L_287'] : ((isset($MSG['287'])) ? $MSG['287'] : '{ L_287 }')); ?>: <?php echo (isset($this->_rootref['CUR_CAT'])) ? $this->_rootref['CUR_CAT'] : ''; ?> " name="catkeyword">
<button class="btn" type="submit" name="" class="btn">
<?php echo ((isset($this->_rootref['L_103'])) ? $this->_rootref['L_103'] : ((isset($MSG['103'])) ? $MSG['103'] : '{ L_103 }')); ?>
</button>
</div>
</form>
</div>
<div class="span2 offset2 muted"><small> <a href="<?php echo (isset($this->_rootref['SITEURL'])) ? $this->_rootref['SITEURL'] : ''; ?>adsearch.php"><?php echo ((isset($this->_rootref['L_464'])) ? $this->_rootref['L_464'] : ((isset($MSG['464'])) ? $MSG['464'] : '{ L_464 }')); ?></a></small> </div>
</div>
</div>
</div>
<?php } if ($this->_rootref['NUM_AUCTIONS'] > 0) { ?>
</div>
<?php $this->_tpl_include('browse.tpl'); } else { ?>
</div>
</div>
</div>
</div>
<?php } ?>
</div><file_sep>/newzealandtrader.co.nz/script/config.inc.php
<?php
$DbHost = "traderdb.c4ohbagyv8je.ap-southeast-2.rds.amazonaws.com";
$DbDatabase = "C359247_nztrader";
$DbUser = "traderadm";
$DbPassword = <PASSWORD>";
?><file_sep>/wellingtontrader.oldfrontend/language/EN/emails/html/endauction_youwin.inc.php
Dear {W_NAME},<br>
<br>
You have won the following auction on <a href="{SITE_URL}">{SITENAME}</a> <br>
<br>
Auction data<br>
------------------------------------<br>
Title: {A_TITLE}<br>
Description: {A_DESCRIPTION}<br>
<br>
Your bid: {A_CURRENTBID} ({W_WANTED} items)<br>
You got: {W_GOT} items<br>
Auction End Date: {A_ENDS}<br>
URL: <a href="{A_URL}">{A_URL}</a><br>
<br>
=============<br>
SELLER'S INFO<br>
=============<br>
<br>
{S_NICK}<br>
<a href="mailto:{S_EMAIL}">{S_EMAIL}</a><br>
Seller's payment details:<br>
{S_PAYMENT}<br>
<br>
<br>
If you have received this message in error, please reply to this email,<br>
write to <a href="mailto:{ADMINEMAIL}">{ADMINEMAIL}</a>, or visit <a href="{SITE_URL}">{SITENAME}</a> at <a href="{SITE_URL}">{SITE_URL}</a>.
<file_sep>/wellingtontrader.oldfrontend/language/EN/emails/text/auctionmail.inc.php
Dear {C_NAME},
Your item has been successfully listed on {SITENAME}. The item will display instantly in search results.
Here are the listing details:
Auction title: {A_TITLE}
Auction type: {A_TYPE}
Item #: {A_ID}
Starting bid: {A_MINBID}
Reserve price: {A_RESERVE}
Buy Now price: {A_BNPRICE}
End time: {A_ENDS}
{SITE_URL}item.php?id={A_ID}
Have another item to list?
{SITE_URL}select_category.php<file_sep>/taupotrader.co.nz/cgi-bin/php5-custom-ini.cgi
#!/bin/sh
export PHP_FCGI_CHILDREN=3
exec /hsphere/shared/php5/bin/php-cgi -c /hsphere/local/home/c359247/wellingtontrader.co.nz/cgi-bin/php.ini | 4eb4495ed33a5a0ccfab795bf394b1fcc9b01744 | [
"PHP",
"Shell"
] | 19 | PHP | traderadm/TraderCore | 932be7e683f037a0ffee46b2e683fe684ebe72ff | 7698e56adab25f2fe463d92444bfc6193554ad47 |
refs/heads/master | <repo_name>chengren/GetData<file_sep>/README.md
README
=======
getdata
GitHub repository for the Getting and Cleaning Data course on Coursera
Script Dependencies:
reshape
Instructions:
Extract the data from the URL (zip) provided by the instructions page on Coursera. You should put the data in the working directory for R, such as the same directory as the script. See source code for details.
The script will output 2 data sets as requested by the course:
Tidy data with select variables, unchanged
Tidy data with average of select variables grouped by subject and activity
Data
The data and transformations are described in detail in the file CodeBook.md.
<file_sep>/run_analysis.R
## Getting and Cleaning Data Project
## Peer Assessments
# the working directory
#------------------------------------------------
# setwd("C:\Users\chengren\Desktop/UCI")
files <- list.files(getwd(), recursive=TRUE)
files <- rev(files) # a reversed version of vector 'files' for handling later issues
# read function
#------------------------------------------------
read <- function(x){
if(x %in% c("test","train")){
x <- as.character(x)
} else {stop("x is not valid")}
# Create an index i for directory files
i <- grep(pattern=paste0("(.*)",x,"+(.*)txt"), x=files)
# Read the data
data <- lapply(X=i, function(X){read.table(file=files[X])})
DF <- data.frame(Reduce(cbind, data))
return(data.frame("class"=rep(x, times=nrow(DF)), DF))
}
# 1. Merges the training and the test sets to create one data set.
#------------------------------------------------
raw_train <- read(x="train")
raw_test <- read(x="test")
raw <- rbind(raw_train,raw_test)
# dim(raw) # Retrieve or set the dimension of the object.
# 2. Extracts only the measurements on the mean and standard deviation for each measurement.
#------------------------------------------------
filesnames = grep(pattern="train+(.*)", x=files, value=TRUE)
namestxt <- gsub(pattern=paste0("(.*)+(./?)+/"),replacement="",x=filesnames)
names <- gsub(pattern="_train.txt",replacement="",x=namestxt)
i <- grep(pattern="body|total",x=names)
measures <- lapply(X=i, function(X){ paste0(names[X], seq_len(128)) })
measures <- unlist(measures)
features <- read.table(file="features.txt",row.names=1,colClasses="character")
features <- features$V2
# names as in files once reversed
colnames(raw) <- c("class","activity","subject",features,measures)
meanORstd <- grep(pattern="*mean\\(\\)*|*std\\(\\)*",x=colnames(raw),value=TRUE)
extraction <- c("class","activity","subject", meanORstd)
extract <- raw[,extraction]
# dim(extract)
# 3. Uses descriptive activity names to name the activities in the data set.
#------------------------------------------------
# This step was performed in the extraction process.
# colnames(extract)
# 4. Appropriately labels the data set with descriptive activity names.
#------------------------------------------------
activities <- read.table(file="activity_labels.txt", row.names=1)
extract[,"activity"] <- factor(x=extract[,"activity"], labels=activities$V2)
# 5. Creates a second, independent tidy data set with the average of each
# variable for each activity and each subject.
#------------------------------------------------
tidy <- aggregate(x = extract[,meanORstd], by = extract[,c("activity","subject")], FUN = "mean")
# head(tidy, n=10)
# dim(tidy)[1] == length(activities$V2) * length(unique(extract[,"subject"]))
# The tidy data frame is written to a file.
write.csv(x=tidy, file = "tidy.txt", row.names=FALSE)
# The tidy data frame can be read as follows
# read.csv(file = "tidy.txt", header = TRUE, check.names = FALSE) | c6e935da69cea1395e7c9e936c03142720cde621 | [
"Markdown",
"R"
] | 2 | Markdown | chengren/GetData | ef38088aa5dbfb6b0696b0af012bbf4432265c10 | f3248aa9f1c48b107dd7a96bd373fd1c338e10e1 |
refs/heads/master | <repo_name>jsivportfolio/react-next-ecommerce-sample<file_sep>/pages/api/products/[category].js
import data from './data.json';
export function getProductsByCategory(category) {
const products = data.filter((product) => product.category === category);
console.log('[category].js category filter = ' + category)
return products;
}
export default function handler(request, response) {
if (request.method !== 'GET') {
response.setHeader('Allow', ['GET']);
response.status(405).json({ message: `Method ${request.method} is not allowed` });
} else {
const products = getProductsByCategory(request.query.category);
response.status(200).json(products);
}
}<file_sep>/pages/index.js
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import CategoryCard from '../components/CategoryCard'
import {useState} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
export default function Home({ productsFiltered }) {
console.log(productsFiltered);
console.log('index.js | productsFiltered');
{
productsFiltered.map((product) => (
console.log('BEGIN index.js product'),
console.log(product),
console.log('END index.js product'),
console.log('Begin product.imageUrl'),
console.log(product.imageUrl),
console.log('END product.imageUrl')
))
}
return (
<div>
<Head>
<title>Next React Shop</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div className={styles.small}>
{/* <ProductsList productsFiltered={productsFiltered} ></ProductsList> */}
<CategoryCard imageUrl={productsFiltered[0].imageUrl} name={productsFiltered[0].name} />
<CategoryCard imageUrl={productsFiltered[1].imageUrl} name={productsFiltered[1].name} />
<CategoryCard imageUrl={productsFiltered[2].imageUrl} name={productsFiltered[2].name} />
</div>
</main>
</div>
)
}
export const getServerSideProps = async () => {
const responseProducts = await fetch('https://60a2b8707c6e8b0017e26016.mockapi.io/products')
const productsFiltered = await responseProducts.json()
return {
props: {
productsFiltered
},
};
};
<file_sep>/pages/cart.jsx
import Image from 'next/image';
// Importing hooks from react-redux
import { useSelector, useDispatch } from 'react-redux';
// Importing actions from cart.slice.js
import {
incrementQuantity,
decrementQuantity,
removeFromCart,
removeAllFromCart,
} from '../redux/cart.slice';
import styles from '../styles/CartPage.module.css';
import {Button, Modal} from 'react-bootstrap/Button';
import ModalCheckout from '../components/ModalCheckout';
const CartPage = () => {
// Extracting cart state from redux store.js
const cart = useSelector((state) => state.cart);
// Reference to the dispatch function from redux store.js
const dispatch = useDispatch();
const getTotalPrice = () => {
return cart.reduce(
(accumulator, item) => accumulator + item.quantity * item.price, 0);
};
return (
<div className={styles.container}>
{cart.length === 0 ? (
<h1 id='messageCart'>Your Cart is Empty!</h1>
) : (
<>
<div className={styles.header}>
<div>Image</div>
<div>Product</div>
<div>Price</div>
<div>Quantity</div>
<div>Actions</div>
<div>Total Price</div>
</div>
{cart.map((item) => (
<div className={styles.body}>
<div className={styles.image}>
<Image src={item.imageUrl} height={90} width={90} />
</div>
<p>{item.name}</p>
<p>${item.price}</p>
<p>{item.quantity}</p>
<div className={styles.quantity_CartControl}>
<button className={styles.qty__Action} onClick={() => dispatch(decrementQuantity(item.id))}>-</button>
<button className={styles.qty__Action} onClick={() => dispatch(incrementQuantity(item.id))}>+</button>
<button className={styles.qty__Action} onClick={() => dispatch(removeFromCart(item.id))}>x</button>
</div>
<p className={styles.item__TotalPrice}>${(item.quantity * item.price).toFixed(2)}</p>
</div>
))}
<h2>Cart Total: ${getTotalPrice().toFixed(2)}</h2>
{/* <button id='buttonCheckout' className={styles.button__Checkout} onClick={() => dispatch(removeAllFromCart(cart.item))}>Checkout</button> */}
<ModalCheckout></ModalCheckout>
</>
)}
</div>
);
};
export default CartPage;<file_sep>/redux/cart.slice.js
import { createSlice } from '@reduxjs/toolkit';
const cartSlice = createSlice({
name: 'cart',
initialState: [],
reducers: {
addToCart: (state, action) => {
const productIsInCart = state.find((product) => product.id === action.payload.id);
if (productIsInCart) {
productIsInCart.quantity++;
} else {
state.push({ ...action.payload, quantity: 1 });
}
},
removeFromCart: (state, action) => {
const indexCartProduct = state.findIndex((product) => product.id === action.payload);
state.splice(indexCartProduct, 1);
},
incrementQuantity: (state, action) => {
const product = state.find((product) => product.id === action.payload);
product.quantity++;
},
decrementQuantity: (state, action) => {
const product = state.find((product) => product.id === action.payload);
if (product.quantity === 1) {
const indexProduct = state.findIndex((product) => product.id === action.payload);
state.splice(indexProduct, 1);
} else {
product.quantity--;
}
},
addQuantityToCart: (state, action) => {
const productIsInCart = state.find((product) => product.id === action.payload.id);
if (productIsInCart) {
productIsInCart.quantity += action.payload.quantity
} else {
state.push(action.payload);
}
},
removeAllFromCart: (state, action) => {
const cartProducts = state.map((products) => products.id === action.payload);
if (cartProducts) {
cartProducts.quantity = 0;
const indexCartProduct = state.findIndex((product) => product === action.payload);
state.splice(indexCartProduct.length);
} else
state.push({ ...action.payload, quantity: 0 });
}
},
});
export const cartReducer = cartSlice.reducer;
export const {
addToCart,
incrementQuantity,
decrementQuantity,
removeFromCart,
addQuantityToCart,
removeAllFromCart,
} = cartSlice.actions;<file_sep>/components/ModalCheckout.jsx
import React, { useState } from 'react';
// Importing hooks from react-bootstrap
import { Button,Modal } from 'react-bootstrap';
// Importing hooks from react-redux
import { useSelector, useDispatch } from 'react-redux';
// Importing actions from cart.slice.js
import { removeAllFromCart } from '../redux/cart.slice';
// Importing Styles from ModalCheckout
import styles from '../styles/ModalCheckout.module.css';
const ModalCheckout = () => {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
// Extracting cart state from redux store.js
const cart = useSelector((state) => state.cart);
// Reference to the dispatch function from redux store.js
const dispatch = useDispatch();
return (
<div>
<Button className={styles.modal__CheckoutButton} variant="primary" onClick={handleShow}>Checkout</Button>
<Modal show={show} onHide={handleClose} animation={false}>
<Modal.Body className={styles.modal__body}>Thank you for your purchase!</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={() => dispatch(removeAllFromCart(cart.item))}>
Complete Order
</Button>
</Modal.Footer>
</Modal>
</div>
);
};
export default ModalCheckout;
<file_sep>/components/ProductCard.jsx
import Image from 'next/image';
import { useDispatch } from 'react-redux';
import { addToCart } from '../redux/cart.slice';
import styles from '../styles/ProductCard.module.css';
const ProductCard = ({ product }) => {
const dispatch = useDispatch();
return (
<div className={styles}>
<Image src={product.imageUrl} height={300} width={300} />
<h4 className={styles.title}>{product.name}</h4>
<p>$ {product.price}</p>
<p>{product.description}</p>
<button className={styles.button} onClick={() => dispatch(addToCart(product))}>
Add to Cart
</button>
</div>
);
};
export default ProductCard; | 5d925a1c33fc938a21ad629d7c33834862e0a59e | [
"JavaScript"
] | 6 | JavaScript | jsivportfolio/react-next-ecommerce-sample | 60a697e7483908db6b1578432843b96d5dc7afa6 | 2b3e4e5a791d1acf871474ea79db14ef06da5c8b |
refs/heads/main | <file_sep>const users = [
{
name: 'Prince',
age: 28,
gender: 'M',
hobby: 'coding',
avatar: 'avatar0.png',
},
{
name: 'Peggy',
age: 27,
gender: 'F',
hobby: 'cooking',
avatar: 'avatar1.png',
},
{
name: 'Seth',
age: 30,
gender: 'M',
hobby: 'gaming',
avatar: 'avatar2.png',
},
{
name: 'Endeavor',
age: 42,
gender: 'M',
hobby: 'gaming',
avatar: 'avatar3.png',
},
{
name: 'Luffy',
gender: 'M',
age: 19,
hobby: 'joking',
avatar: 'avatar4.png',
},
{
name: 'Ama',
gender: 'F',
age: 23,
hobby: 'selling',
avatar: 'avatar5.png',
},
{
name: 'Belinda',
gender: 'F',
age: 19,
hobby: 'pets',
avatar: 'avatar6.png',
},
{
name: 'Mike',
gender: 'M',
age: 19,
hobby: 'coding',
avatar: 'avatar7.png',
},
{ name: 'Rose', gender: 'F', age: 22, hobby: 'pets', avatar: 'avatar8.png' },
{
name: 'Anita',
gender: 'F',
age: 24,
hobby: 'cooking',
avatar: 'avatar9.png',
},
];
window.addEventListener('load', function () {
// elements
const searchBtn = document.querySelector('#searchBtn');
const results = document.querySelector('#results');
const gender = document.querySelector('#gender');
// Changing styles
gender.style.fontFamily = 'Chivo';
searchBtn.style.fontFamily = 'Playfair Display'
// functions
const generateHTML = (users) => {
// grabbing all the user input
const selectedGender = gender[gender.selectedIndex].value;
const searchTerm = document.querySelector('#hobbies').value;
const minAge = document.querySelector('#min-age').value;
const maxAge = document.querySelector('#max-age').value;
let resultsHTML = '';
users.forEach((user, index) => {
const userChoice =
(selectedGender === 'A' || selectedGender === user.gender) &&
(searchTerm === '' || searchTerm === user.hobby) &&
user.age >= minAge &&
user.age <= maxAge;
if (userChoice) {
resultsHTML += `
<div class="person-row">
<img src="images/avatar${index}.png" alt='${user.name}'>
<div class="person-info">
<div>${user.name}</div>
<div>${user.hobby}</div>
</div>
<button>Add as a friend</button>
</div>`;
}
});
return resultsHTML;
};
searchBtn.addEventListener('click', function () {
results.innerHTML = generateHTML(users);
});
});
| f082be48c73dd45bae07f807442d8ce8fba7e6a4 | [
"JavaScript"
] | 1 | JavaScript | PRINCEKK121/programmingForEntrepreneurs | 940b56f69570a03381933e48c8523746668ac955 | 557c0cf26d730c50c551901eebdc4d47b308c6a3 |
refs/heads/master | <repo_name>YohanesDemissie/whiteboard-challenge<file_sep>/whiteboard-challenge-19/solution.js
'use strict';
const SLL = require('./sll');
const solution = module.exports = {};
solution.linkedList = (tree) => {
if (!tree) return null;
if (typeof tree !== 'object') return null;
let arr = [];
let sll = new SLL();
tree.breadthFirst(current => {
if (current.val) {
arr.push(current.val);
}
});
arr.sort(function (a, b) { return a - b; });
for (let i in arr) {
sll.insertHead(arr[i]); //meat and potatoes
}
return sll;
};
<file_sep>/whiteboard-challenge-15/__test__/solution.test.js
'use strict';
const solution = require('../solution');
const k_ary = require('../lib/k-ary-tree');
describe('Solution Module', () => {
beforeAll(() => {
this.oneNode = new k_ary().insert(1, 1);
// this.emptyNode = new k_ary();
});
describe('arr', () => {
it('should..', () => {
console.log(solution.arr(this.tree));
expect(solution.arr(this.oneNode)).toBeInstanceOf(Array);
});
});
describe('Valid input/output with two childless nodes', () => {
it('should return an array', () => {
expect(solution.arr(this.tree)).toBeInstanceOf(Array);
});
it('should return an array with two nodes', () => {
expect(solution.arr(this.tree).length).toEqual(3);
});
it('should return an array with two nodes, with values of 2, 3 and 4', () => {
expect(solution.arr(this.tree)[0].val).toEqual(2);
expect(solution.arr(this.tree)[1].val).toEqual(3);
expect(solution.arr(this.tree)[2].val).toEqual(4);
});
});
describe('Invalid input/output', () => {
it('should return error if nothing in tree', () => {
expect(solution.arr(this.emptyNode)).toBeInstanceOf(Error);
});
it('should return error message if nothing in tree', () => {
expect(solution.arr(this.emptyNode).message).toEqual('Invalid input');
});
});
});<file_sep>/whiteboard-challenge-31/lib/solution.js
'use strict'
const index = module.exports = {};
const one = [1, 2, 3, 4, 5]
const two = [9, 8, 7, 6, 5]
index.check = function (arr1, arr2) {
let duplicate = [];
for (let i in arr1) {
if (arr2.includes(arr1[i])) {
duplicate.push(arr1[i]);
}
}
return duplicate;
};
module.exports = {}<file_sep>/wb-14-test/lib/solution.js
'use strict';
const Stack = require('./stack');
const SLL = require('./sll');
// dedupe
module.exports = (head) => {
if (!head) throw new Error('Error: head is falsey');
let stack = new Stack();
let itr = head.next;
for (stack.push(head.value); itr; itr = itr.next) {
if (stack.peek() !== itr.value) {
stack.push(itr.value);
}
}
let sll = new SLL();
// Generate a singly link list from stack
while (stack.size) {
sll.insertHead(stack.pop());
}
// Return the head
return sll.head;
};<file_sep>/whiteboard-challenge-03/__test__/solution.test.js
'use struct';
const passengers = require('..lib/solutions.js');
describe('Train Module', function(){
describe('#traverse', function (){
it('this should return numer of people on train', function (){
expect(train.value).toEqual(2)
})
it('this should return numer of people on train', function () {
expect(train.value).toEqual(16)
})
it('this should return numer of people on train', function () {
expect(train.value).toEqual(7)
})
it('this should return numer of people on train', function () {
expect(train.value).toEqual(null)
})
})
}
// const array = require('../lib/solution.js');
// describe('Array Module', function () {
// describe('#check', function () {
// it('this should make sure the array is full of numbers', function () {
// expect(array.check([4, 77, 'l'])).toEqual(null)
// })
// it('this should make sure the array does not contain an empty string', function () {
// expect(array.check([1, 9, ''])).toEqual('contains empty string')
// })
// it('this should make sure the array has some content', function () {
// expect(array.check([])).toEqual('contains empty array')
// })
// it('this should make sure it works with floating numbers', function () {
// expect(array.check([1, 7, 5.98])).toEqual({ "first": 7, "second": 5.98 })
// })
// })
// })
<file_sep>/whiteboard-challenge-32/__test__/solution.test.js
const solution = require('../lib/solution.itr')
//const rec = require('../lib/solution.rec')
describe('Validate inputs, outpus, NaNs and properties', () => {
// expect(typeof solution.itr.fib).toBe(Array)
console.log(solution.itr(4))
});<file_sep>/whiteboard-challenge-15/README.md
#PROBLEM DOMAIN
Write a function that accepts the root of a tree as it's argument, and returns an array of nodes, if any, which have no children.
<file_sep>/whiteboard-challenge-08/README.md
#Problem Domain
Look for repeat of values in linked list
<file_sep>/whiteboard-challenge-17/solution.js
'use strict';
const k_ary = require('./lib/k-ary-tree.js'); //require in our tree constructor
const solution = module.exports = {}; //outsorce our solution file
solution.arr = function (root) { //creating a function iterating through the branches of our root
let tree = new k_ary();
tree = root;
if (!tree.root) return new Error('Invalid input'); //error first method
let results = []; //our array that will hold all node values
let output = function (current) { //the meat and potatoes
results.push(current.val.val);
};
tree.breadthFirst(output);
var sum = results.reduce((a, b) => a + b, 0);
// console.log(results, 'results')
return sum;
};<file_sep>/whiteboard-challenge-27/map-solution.js
const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let rotate = a => a[0].map((col, c) => a.map((row, r) => a[r][c]).reverse())
console.log(rotate(a))<file_sep>/whiteboard-challenge-10/README.md
#Problem Domain
Write a function 'checkBraces()' to examine whether the pairs and the orders of { and } are correct in a string, using a Stack.
<file_sep>/whiteboard-challenge-07/__test__/solution.test.js
'use strict'
const crazy = require('../lib/solution.js')
describe('Cycle Module', function () {
describe('#next', function () {
it('should return false if there is null', function () {
expect(crazy.cycle.next).not.toEqual(null)
})
it('it should not have strings', function () {
expect(crazy.cycle.next).not.toEqual('')
})
it('should return true of circling linked list', function() {
expect(crazy.cycle.head).not.toEqual(NaN)
})
})
})<file_sep>/whiteboard-challenge-26/something.js
'use strict';
const utils = require('./utils.js');
let array = [1, 2, 3, 4]
let x = 3;
let y = 2
console.log(array.utils.(x => x * y));
<file_sep>/whiteboard-challenge-27/for-solution.js
const a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
function rotateClockwise(a) {
var n = a.length;
for (var i = 0; i < n / 2; i++) {
for (var j = i; j < n - i - 1; j++) {
var tmp = a[i][j];
a[i][j] = a[n - j - 1][i];
a[n - j - 1][i] = a[n - i - 1][n - j - 1];
a[n - i - 1][n - j - 1] = a[j][n - i - 1];
a[j][n - i - 1] = tmp;
}
}
return a;
}
console.log(rotateClockwise(a));<file_sep>/whiteboard-challenge-04/README.md
#Prolem Domain
Write a function that will intersect two arrays
<file_sep>/whiteboard-challenge-11/README.md
#PROBLEM DOMAIN
You have an integer array which contains numbers from 1 to 100 but one number is missing, you need to write a function to find that missing number in an array.<file_sep>/whiteboard-challenge-12/sources.md
https://www.youtube.com/watch?v=wjI1WNcIntg
http://www.growingwiththeweb.com/2013/07/algorithm-implement-queue-using-2-stacks.html<file_sep>/whiteboard-challenge-27/README.md
#Problem Domain
Given a 2-dimensional array of numbers, rotate the array 90 degrees.
Write at least four tests for this function
#Solution Source
https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript<file_sep>/whiteboard-challenge-05/README.md
#Problem Domain
Write a function that returns the middle node in a singly linked list
#URL Source
https://codeburst.io/js-data-structures-linked-list-3ed4d63e6571<file_sep>/whiteboard-challenge-07/lib/solution.js
crazy = module.exports = {};
const cycle = {
head: {
value: 7, next: {
value: 9, next: {
value: 12, next: {
value: 15, next: {
value: 0, next: null,
}
}
}
}
}
}
//circle listed link call back below
// cycle.head.next.next.next.next.next = cycle.head;
crazy.cycle = function () {
let newCycle = Object.assign({}, cycle);
for (let itr = newCycle.head; itr !== null; itr = itr.next) {
console.log(itr)
if (itr.hasOwnProperty('visited'))
return true
itr.visited = true
}
return false
}
//crazy(cycle);
<file_sep>/whiteboard-challenge-31/README.md
#PROBLEM DOMAIN
Given two arrays, write a function to compute their intersection
example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].<file_sep>/whiteboard-challenge-26/utils.js
'use strict';
module.exports = function utils(){
utils.map = function(x, y) {
let array = []
if(!array) return null;
};
utils.filter = function () {
let array = []
};
utils.reduce = function() {
let array = []
};
};<file_sep>/whiteboard-challenge-26/__test__/solution.test.js
'use strict';
const solution = require('../solution')
let array = [1, 2, 3, 4]
expect(array.utils.map(x => x * y)).toEqual('sometihng');<file_sep>/whiteboard-challenge-08/single-linked-list.js
function LinkedList() {
this.head = null; //head never has a value
}
LinkedList.prototype.push = function (val) {
let node = { //create node with value and nested 'next' key value pairs
value: val, //value
next: null //next == null if no following value
}
if (!this.head) {
this.head = node; //since head is null, give it node content (value, next)
}
else {
current = this.head;
while (current.next) { //nests next: to the floowing listed objects
current = current.next;
}
current.next = node; //nest the key value pairs within 'next'
}
}
//create linked list based off constructor
let list = new LinkedList();
// add values to linked list
list.push(5);
list.push(10);
list.push(15);
list.push(20);
list.push(25);
console.log(list, 'first LinkedList') //checking for values
let listIntercept = new LinkedList();
listIntercept.push(3)
listIntercept.push(5)
listIntercept.push(7)
listIntercept.push(9)
listIntercept.push(15)
console.log(listIntercept, 'second new thingy')
let stack = [];
//push
stack.push(list.head.value); //returns value
stack.push(list.head.next.value);
stack.push(list.head.next.next.value);
stack.push(list.head.next.next.next.value);
stack.push(list.head.next.next.next.next.value);
//push 2nd linked list
stack.push(listIntercept.head.value); //returns value
stack.push(listIntercept.head.next.value);
stack.push(listIntercept.head.next.next.value);
stack.push(listIntercept.head.next.next.next.value);
stack.push(listIntercept.head.next.next.next.next.value);
stack;
var cache = {}; //iterator
var duplicates = [];
for (var i = 0, len = stack.length; i < len; i++) {
if (cache[stack[i]] === true) {
duplicates.push(stack[i]);
} else {
cache[stack[i]] = true;
}
}
//console.log(duplicates); //displayes [3, 5]
let duplicateValues = new LinkedList()
duplicateValues.push(duplicates);
duplicateValues;
<file_sep>/whiteboard-challenge-29/README.md
#Problem Domain
Write a method to sort an array of strings so that all the anagrams are next to each other
<file_sep>/whiteboard-challenge-32/README.md
#PROBLEM DOMAIN
The fibonacci series is an ordering of numbers where each number is the sum of the preceeding two.
Write two functions to print out the nth entry in the fibonacci series, recursively and iteratively
ex: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] forms the first ten entries of the fibonacci series
ex: fib(4) === 3
#RESOURCES
#ITERATIVE SOLUTIONS
https://stackoverflow.com/questions/7944239/generating-fibonacci-sequence
var fib = [0, 1];
for (var i = fib.length; i < 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
}
//console.log(fib);<file_sep>/whiteboard-challenge-28/__test__/solution.test.js
'use strict'
const solution = require('../lib/solution')
describe('Solution Module', function () {
describe('#highWord', function () {
it('should return null if no arguments passed', function () {
expect(solution.highWord()).toEqual(null)
})
it('should return null if not a string', function () {
expect(solution.highWord([1, 2, 3])).toEqual(null)
})
it('should return highest scoring word', function () {
expect(solution.highWord('aa bb cc dd ee ff gg')).toEqual('gg')
})
})
})
<file_sep>/README.md
# whiteboard-challenge
whiteboard challenges 401
<file_sep>/whiteboard-challenge-09/__test__/test.solution.js
'use strict';
const solution = require('../lib/solution');
const SLL = require('../lib/sll');
describe('Solution Module', () => {
let sll = new SLL();
sll.insertHead(25);
sll.insertEnd(12);
sll.insertEnd(33);
sll.insertEnd(4);
sll.insertEnd(87);
let sll2 = sll.head.next;
describe('solution', () => {
it('should accept two argument and return the correct node', () => {
expect(solution.find(3, sll)).toBe(sll2);
});
it('should return null if SLL is not an object', () => {
expect(solution.find(4, 'SLL')).toBeNull();
});
it('should return null if offset is not a number', () => {
expect(solution.find('4', sll)).toBeNull();
});
});
});<file_sep>/whiteboard-challenge-14/lib/solution.js
'use strict'
//make a new stack
const SLL = require('./single-linked.js')
const Stack = require('./stack.js')
module.exports = (head) => {
let stacks = new Stack()
let itr = head.next
for(stacks.push(head.value); itr ; itr =itr.next) { //changed head to head.head cuase daniel. correct if im worng
stacks.push(head.value)
if(stacks.peek !== itr.value) {
stacks.push(itr.value)
}
}
let singleLink = new SLL()
while (stacks.size) {
singleLink.insertHead(stacks.pop)
}
return singleLink.head
}
<file_sep>/whiteboard-challenge-07/lib/index.js
'use strict';
const solution = module.exports = {};
solution.cirr = function (SLL) { //creating our constructor
if (!SLL) return null; //error first
if (!Object.keys(SLL).length) return null;//error first
let SLL2 = Object.assign({}, SLL);
let seen;
while (SLL2.next) {
if (SLL2.next.seen === true) return true;
SLL2.seen = true;
SLL2 = SLL2.next;
}
return false;
};
solution.cirr();
//<file_sep>/whiteboard-challenge-31/__test__/solution.test.js
'use strict'
const index = require('../lib/solution')
describe('validate array, make sure there are no strings, make sure it is made of intigers', () => {
expect(index.check).toHavePropertyOf(Array)
expect(array).toNotEqual('')
expect(array).toNotBe(NaN)
})
<file_sep>/wb-14-test/lib/stack.js
'use strict';
const Node = require('./node');
// Stack implementation - LIFO
module.exports = class {
constructor(max = 1024) {
// BigO(1) to create a new Stack
if (typeof max !== 'number' || !max || max < 0)
throw new Error('Error: Max size must be a valid non-zero number');
this.max = max;
this.size = 0;
this.top = null;
}
push(value) {
// BigO(1) to insert an item
if (!value && value !== 0)
throw new Error('Error: Value must be valid');
if (this.size === this.max)
throw new Error('Error: Stack is at max size');
let node = new Node(value);
node.next = this.top;
this.top = node;
this.size++;
}
pop() {
// BigO(1) to pop an item from the stack
if (!this.size)
throw new Error('Error: Stack is empty');
let node = this.top;
this.top = node.next;
node.next = null;
this.size--;
return node.value;
}
peek() {
// BigO(1) to peek at the top of the stack
if (!this.size)
throw new Error('Error: Stack is empty');
return this.top.value;
}
};<file_sep>/whiteboard-challenge-07/README.md
#Problem Domain
Write a function which accepts a linked list as it's only argument, and returns true or false. - If the linked list is circular (it has no end), return true - Else return false
#Solution Domain
create and endless 'for' loop that circles through a linked list
when the for loop returns null, return a for loop to [0] and restart the process
make if statement to make sure it rturns error if it isnt an endless, circling linked list
Make sure it returns true if it is endless
<file_sep>/whiteboard-challenge-08/solution.js
'use strict';
const map = require('map')
const list = require('list')
const listIntercept = require('listIntercept')
map.check = function (list, listIntercept) {
if (list === 0) return;
if (list == typeof Node) return;
if(argunents.length !== 2) return;
listIntercept();
map.check(list - 1, listIntercept)
}
//older white board check up
loop.check = function (counter, callback) {
if (counter === 0) return;
if (counter !== '') return;
if (arguments.lengths !== 2) return;
callback();
loop.check(counter - 1, callback)
};<file_sep>/whiteboard-challenge-07/__test__/index.test.js
'use strict';
const solution = require('../lib/index.js');
describe('Solution Module', () => {
let a = { value: 1, next: { value: 2, next: { value: 3, next: null } } };
a.next.next = a.next;
let b = { value: 1, next: { value: 2, next: { value: 3, next: null } } };
let c = {};
it('should check if SLL is circular', () => {
expect(solution.cirr(a)).toBe(true);
});
it('should check if SLL is not circular', () => {
expect(solution.cirr(b)).toBe(false);
});
it('should check if object is empty', () => {
expect(solution.cirr(c)).toBe(null);
});
});<file_sep>/whiteboard-challenge-14/lib/stack.js
const Node = require('./node')
module.exports = class {
constructor(maxSize = 1048) {
this.top = null //this.head
this.maxSize = maxSize //maximum nodes{objects}
this.size = 0 //node{object} counter
}
push(val) {
if (this.size === this.maxSize) throw new Error('Stack overflow!')
let node = new Node(val)
node.next = this.top
this.top = node
this.size++
return this.top
}
pop() {
let node = this.top
this.top = node.next
node.next = null
this.size-- //stacks backwards. so head eventually becomes tail
return node.val
}
peek() {
return this.top.val //the head
}
}<file_sep>/wb-14-test/lib/node.js
'use strict';
module.exports = class {
constructor(value = null) {
if (!value && value !== 0)
throw new Error('Error: Val must be a valid piece of data');
this.value = value;
this.next = null;
}
};<file_sep>/whiteboard-challenge-12/__test__/solution.test.js
'use strict';
const TwoStackQueue = require('../lib/solution.js')
describe('Queue Module', () => {
beforeEach(() => this.queue = new TwoStackQueue()); //required in our constructor and new queue
describe('#Properties', () => {
it('should validate an object', () => {
expect(this.queue).toBeInstanceOf([Function]); //PASSED as functino
});
it('should return length of stack', () => {
let q = new TwoStackQueue()
// let stack = new TwoStackQueue;
q.inbox.push(12)
q.inbox.push(34)
q.inbox.push(5)
q.inbox.push(22)
expect(q.inbox.push(5)).toEqual(5);
});
it('should return two stacks', () => {
let stacks = new TwoStackQueue;
expect(stacks).toEqual({ "inbox": [], "outbox": [] }); //testing our 2 queues, PASS
});
});
})<file_sep>/whiteboard-challenge-28/lib/solution.js
'use strict'
const solution = module.exports = {}
solution.highWord = function (string) {
if (!string || typeof string !== 'string') return null
let currentTotal = 0;
let lastTotal = 0;
let highWord = '';
let strArr = string.split(' ');
for (let i = 0; i < strArr.length; i++) {
currentTotal = 0;
for (let j = 0; j < strArr[i].length; j++) {
currentTotal += (strArr[i].charCodeAt(j) - 96);
}
if (currentTotal > lastTotal) {
highWord = strArr[i];
lastTotal = currentTotal;
currentTotal = 0;
}
}
return (highWord);
}<file_sep>/whiteboard-challenge-6/README.md
#Problem Domain
Write a recursive function called loop that has the function signature (count, callback) => undefined It should call the callback count times (count is expected to be > 0)
//todays lab complete yesterdays lab
whiteboard find the nth node and return nth from last
nth is 2nd to last node<file_sep>/wb-14-test/__test__/solution.test.js
'use strict';
const dedupe = require('../lib/solution');
const SLL = require('../lib/sll');
describe('Solution Module', () => {
describe('#dedupe', () => {
it('filter out duplicates and return single values', () => {
let singleLink = new SLL(); //required in
singleLink.insertHead(5);
singleLink.insertHead(5);
singleLink.insertHead(4);
singleLink.insertHead(1);
let newSll = dedupe(singleLink.head); //.head required in from solution,js
expect(newSll.value).toBe(1); //chain commands required in
expect(newSll.next.value).toBe(4);
expect(newSll.next.next.value).toBe(5);
});
// it('should throw an error if the list arg is falsey', () => {
// expect(() => dedupe(null)).toThrow('Error: head is falsey'); //new testing method Steve taught me.
// expect(() => dedupe(NaN)).toThrow('Error: head is falsey');
// expect(() => dedupe(undefined)).toThrow('Error: head is falsey');
// });
// it('should throw an error if the list arg is falsey', () => {
// expect(() => dedupe(null)).toThrow('Error: head is falsey'); //new testing method Steve taught me.
// expect(() => dedupe(NaN)).toThrow('Error: head is falsey');
// expect(() => dedupe(undefined)).toThrow('Error: head is falsey');
// });
it('should work properly if a single node list is passed in', () => {
let linkedList = new SLL();
linkedList.insertHead(1);
let newSll = dedupe(linkedList.head);
expect(newSll.value).toBe(1);
expect(newSll.next).toBe(null);
});
});
});<file_sep>/whiteboard-challenge-14/lib/single-linked.js
'use strict';
const Node = require('./node.js');
//const stack = require('./stack.js')
module.exports = class {
constructor () {
this.head = null
this.length = 0;
}
insertHead(val) {
let node = new Node(val)
node.next = this.head //alway start with head
this.head = node //objectify the head
this.length++
return this.head;
}
insertEnd(val) {
if(!val && val !== 0) //check for values/content
return this
if(!this.length)
return this.insertHead(val) //return head
let node = new Node(val);
for (var itr = this.head; itr.next; itr = itr.next)
itr.next = node
this.length++
return this
}
}
<file_sep>/whiteboard-challenge-12/README.md
#PROBLEM DOMAIN
<file_sep>/whiteboard-challenge-26/solution.js
'use strict';
const utils = module.export = {};
utils.Map = function (callback) { //callback holds the data to be altered
let array = [];
for (let i = 0; i < this.length; i++)
array.push(callback(this[i], i, this)); //push the modified callback
return array; //return modified array
};
utils.Filter = function (callback, context) {
let array = [];
for (let i = 0; i < this.length; i++) {
if (callback.call(context, this[i], i, this))
array.push(this[i]);
}
return array;
},
utils.Reduce = function (callback, initialValue) {
let accumulator = (initialValue === undefined) ? undefined : initialValue;
for (let i = 0; i < this.length; i++) {
if (accumulator !== undefined)
accumulator = callback.call(undefined, accumulator, this[i], i, this);
else
accumulator = this[i];
}
return accumulator;
};<file_sep>/whiteboard-challenge-28/README.md
#Problem Domain
Given a string of words return the highest scoring word as a string
a = 1, b = 2, c = 3 etc..
If two words score the same, return the string that appears the earliest in the string
All letters with be lowercase, all inputs will be valid<file_sep>/whiteboard-challenge-05/lib/solution.js
var train = {
"value": 1,
"next": {
"value": 2,
"next": {
"value": 3,
"next": {
"value": 4,
"next": {
"value": 5,
"next": null
}
}
}
}
}
let findMiddle = function (train) {
let length = 0;
let link = train;
while (link.next !== null) {
length++
link = link.next;
}
link = train;
let half = ~~(length / 2);
while (half !== 0) {
half--;
link = link.next;
}
return link;
}
findMiddle(train);
<file_sep>/whiteboard-challenge-09/lib/solution.js
'use strict';
const solution = module.exports = {};
solution.find = function (offset, SLL) {
if (!SLL || typeof SLL !== 'object' || typeof offset !== 'number') return null;
let counter = 1;
for (var itr = SLL.head; itr.next; itr = itr.next) {
counter++;
}
let diff = counter - offset;
if (diff < 1 || typeof diff !== 'number') return null;
let curr = SLL.head;
for (let i = 1; i < diff; i++) {
curr = curr.next;
if (!curr) return 'this node does not exist';
}
return curr;
};<file_sep>/whiteboard-challenge-10/__test__/binary.test.js
'use strict';
const binarySearch = require('../binary-search/lib/binary-solution.js');
describe('testing testing', function () {
describe('#binarySearch Module', function () {
it('should make sure the "num" is an integer', function () {
let filter = new binarySearch.check;
let num = 5;
const arr = [0, 0, 1, 1, 2, num, 5, 5, 6, 11, 7, 54, 60];
expect(num).not.toBe(NaN);
})
it('should find the "num" through the filtered array', function () {
let num = 5;
const arr = [0, 0, 1, 1, 2, num, 5, 5, 6, 11, 7, 54, 60];
expect(binarySearch.check(arr, num)).toBe(5);
});
it('should print the steps through our binary tree to return our num value', function () {
let num = 54;
const arr = [0, 0, 1, 1, 2, num, 5, 5, 6, 11, 7, 54, 60];
expect(binarySearch.check(arr, num)).toBe(54);
});
});
});<file_sep>/02-tools-context/lib/solution.js
const numbers = module.exports = {};
numbers.check = function (arr) {
var first = arr.sort(function (a, b) { return b - a })[0];//get first highest number
var second = arr.sort(function (a, b) { return b - a })[1]; //get second highest
var highest = {
first: first,
second: second
};
for (i = 0; i < arr.length; i++) {
if (isNaN(arr[i])) {
return null;
}
}
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i] === '') {
return 'contains empty string';
}
}
for (i = 0; i >= arr.length; i++) {
if (arr.length === 0) {
return 'contains empty array';
}
}
for (i = 0; i < arr.length; i++) {
if (Number.isInteger(arr[i])) {
return highest;
} else {
return 'not an integer';
}
}
return highest;
}
<file_sep>/whiteboard-challenge-6/__test__/solution.test.js
'use strict';
const loop = require('../lib/solution.js');
describe('loop module', function () {
describe('#counter', function () {
it('should return a number', function () {
expect(loop.check(10, () => { console.log(counter)}))
})
it('it should contain numeric data and not a string', function () {
expect(loop.check(10, () => { console.log(counter) }))
})
it('should have 2 arguments', function () {
expect(loop.check(2, () => {console.log(counter) }))
})
})
})
<file_sep>/whiteboard-challenge-32/lib/solution.itr.js
const solution = module.exports = {}
solution.itr = function (n) {
var fib = [0, 1];
for (let i = fib.length; i < 10; i++) {
fib[i] = fib[i - 2] + fib[i - 1]
}
return fib[n]
};<file_sep>/whiteboard-challenge-29/solution.js
const sorted = [];
const newThing = {};
const sortAnagrams = ['acre', 'race', 'care', 'act', 'cat', 'tac'];
function splitString(sorted) {
for (let val of sortAnagrams) {
let letters = val.split('').sort().join(''); //
sorted.push(letters);
if (!newThing[letters]) newThing[letters] = []
newThing[letters].push(val); //
console.log('values', newThing[letters])
//console.log(sorted);
}
}
splitString(sorted)
console.log(newThing); | 0d339a45733db40ab82d2042ccabfb2c4581d1db | [
"JavaScript",
"Markdown"
] | 53 | JavaScript | YohanesDemissie/whiteboard-challenge | 97aafeedf739f909974333d57ce2b213c4d32278 | 7b6ffe457751e85f51b6e4ded788ad59227b3cc7 |
refs/heads/master | <repo_name>Yamato0516/teleco<file_sep>/gulp_tasks/clean.js
var
$ = require('gulp-load-plugins')(),
gulp = require('gulp'),
config = require('./config'),
del = require('del');
gulp.task( 'clean', del.bind( null, [ config.dest ] ) );<file_sep>/src/special_contents/teleco/assets/scripts/scripts.js
// ----------------------------------------
// デバイスを調べる
// ----------------------------------------
var target = ['iphone', 'ipod', 'ipad', 'android', 'iemobile'],
ua = window.navigator.userAgent.toLowerCase(),
device = 'pc';
for( var i = 0; i < target.length; i++){
if( ua.indexOf( target[i] ) > -1 ){
device = 'sp';
break;
}
}
// ----------------------------------------
// Youtube IFrame Player API
// ----------------------------------------
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName( 'script' )[0];
firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
var player;
// ---------- API読み込み後にプレーヤー埋め込む ----------
function onYouTubeIframeAPIReady() {
player = new YT.Player('js-video', {
height: '225',
width: '400',
videoId: 'aL--GAC8l38',
playerVars : {
enablejsapi: 1,
playlist: 'aL--GAC8l38, aL--GAC8l38',
loop: 1,
rel : 0, // 関連動画を非表示
controls : 0, // コントロールボタンを非表示
showinfo : 0, // タイトル、ユーザー名を非表示
modestbranding : 1 // YouTube ロゴを非表示
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady( event ) {
if ( device === 'pc' ) {
// ビデオ再生
event.target.playVideo();
event.target.mute();
}
}
function onPlayerStateChange( event ) {
var done = false;
if ( event.data == YT.PlayerState.PLAYING && !done ) {
}
}
$(function () {
// ----------------------------------------
// Magnific Popup
// ----------------------------------------
if ( $( '#js-video' ).length ) {
$('.popup-modal').magnificPopup({
type : 'inline',
preloader : false,
midClick : true,
closeOnBgClick : true,
callbacks : {
open : function () {
player.pauseVideo();
},
close : function () {
if ( device === 'pc' ) {
player.playVideo();
}
}
}
});
$( document ).on( 'click', '.popup-modal-dismiss', function (e) {
e.preventDefault();
$.magnificPopup.close();
});
}
// ----------------------------------------
// グローバル変数を定義する
// ----------------------------------------
var
setRandomChange,
flag_isChanged = false,
windowHeight = $( window ).height(),
windowWidth = $( window ).width(),
panelSize = 220,
view = Math.floor( windowHeight / panelSize ),
$panel = $( '.js-looping li' ),
$char = $('#js-isHidden .media__txt'),
$btnMore = $('.media__btn--more'),
$btnClose = $('.media__btn--close'),
originalStr = $char.text(),
configMap = {
active_class : 'active'
},
stateMap = {
is_pc_window : 1025,
is_sp_window : 1024
},
conditionMap = {
window_is_pc : null,
window_is_sp : null,
window_is_opend : null,
menu_is_opened : false
};
// ----------------------------------------
// リサイズごとに変数の値を変える
// ----------------------------------------
$( window ).on ( 'resize', function () {
windowWidth = $( window ).width();
conditionMap.window_is_pc = windowWidth >= stateMap.is_pc_window;
conditionMap.window_is_sp = windowWidth <= stateMap.is_sp_window;
});
// ----------------------------------------
// グロナビ
// ----------------------------------------
var setGlobalNavigation = function () {
var
$menu = $( '#trigger' ),
$menuBtn = $( '.trigger__button' ),
$overlay = $( '#overlay' ),
$nav = $( '.gNav' ),
$headerLogo = $( '#header .logo' );
$menu.on( 'click', function () {
$( this ).find( $menuBtn ).toggleClass( configMap.active_class );
if( $nav.css( 'display' ) === 'none' ) {
$nav.addClass( 'gNav--isOpened' ).stop( false, false ).slideDown();
$overlay.fadeIn();
conditionMap.menu_is_opened = true;
}
else {
$nav.stop( false, false ).slideUp();
$overlay.fadeOut();
conditionMap.menu_is_opened = false;
}
return false;
});
$overlay.on( 'click', function () {
$menuBtn.removeClass( configMap.active_class );
$nav.stop( false, false ).slideUp();
$overlay.fadeOut();
conditionMap.menu_is_opened = false;
});
// ---------- リサイズイベント開始 ----------
var timer = false;
$( window ).resize( function() {
if( timer !== false ) {
clearTimeout(timer);
}
timer = setTimeout( function() {
windowHeight = $( window ).height();
view = Math.floor( windowHeight / panelSize );
if ( conditionMap.window_is_pc ) {
panelInit();
if ( conditionMap.menu_is_opened ) {
$nav.removeClass( 'gNav--isOpened' ).css({ 'display' : 'block' });
$overlay.css({ 'display' : 'none' });
}
else {
$nav.css({ 'display' : 'block' });
}
}
else {
clearInterval( setRandomChange );
panelInit();
setChangePanel();
if ( conditionMap.menu_is_opened ) {
$nav.addClass( 'gNav--isOpened' ).css({ 'display' : 'block' });
$overlay.css({ 'display' : 'block' });
}
else {
$nav.css({ 'display' : 'none' });
}
}
}, 100 );
});
}();
// ----------------------------------------
// Keyframes を生成する
// ----------------------------------------
var createKeyframes = function () {
if ( $( '.js-looping' ).length ) {
var
looping = '',
$loopingHeight = $( '.js-looping' ).height(),
displaySize = screen.availHeight,
$target = $( '.looping' ),
piece = $target.html();
for (var i = 0; i < Math.floor( displaySize / $loopingHeight ); i++) {
$target.append( piece );
}
$target.append( piece );
setLooping();
$( window ).trigger( 'resize' );
looping += '<style type="text/css">';
looping += '@keyframes looping {';
looping += '0% { transform: translateY(0); }';
looping += '100% { transform: translateY(' + $loopingHeight + 'px); }';
looping += '}';
looping += '@-webkit-keyframes looping {';
looping += '0% { -webkit-transform: translateY(0); }';
looping += '100% { -webkit-transform: translateY(' + $loopingHeight + 'px); }';
looping += '}';
looping += '@-moz-keyframes looping {';
looping += '0% { -moz-transform: translateY(0); }';
looping += '100% { -moz-transform: translateY(' + $loopingHeight + 'px); }';
looping += '}';
looping += '@-o-keyframes looping {';
looping += '0% { -o-transform: translateY(0); }';
looping += '100% { -o-transform: translateY(' + $loopingHeight + 'px); }';
looping += '}';
looping += '@-ms-keyframes looping {';
looping += '0% { -ms-transform: translateY(0); }';
looping += '100% { -ms-transform: translateY(' + $loopingHeight + 'px); }';
looping += '}';
looping += '.looping {';
looping += 'opacity: 1;';
looping += 'animation : looping 40s linear infinite, loopingFadeIn 1.2s ease-in 1';
looping += '}';
looping += '</style>';
$( 'head' ).append( looping );
}
};
function loopingStart () {
$( '.looping' ).css({
'opacity' : '1',
'animation' : 'looping 40s linear infinite, loopingFadeIn 1.2s ease-in 1'
});
}
function loopingStop () {
$( '.looping' ).css({
'animation' : 'loopingFadeIn 1.2s ease-in 1'
});
}
$( window ).on( 'load', function () {
if ( windowWidth >= 1025 ) {
createKeyframes();
loopingStart();
}
else {
createKeyframes();
}
});
$( window ).on( 'resize', function () {
if ( windowWidth >= 1025 ) {
$loopingHeight = $( '.js-looping' ).height();
loopingStart();
}
else {
loopingStop();
}
});
// ----------------------------------------
// ピクトグラムの設定
// ----------------------------------------
var
$looping = $('.js-looping'),
$loopingItems = $('.js-looping li'),
$loopingNum = $loopingItems.find('.looping__num img'),
$loopingHeight = $looping.height();
function panelInit () {
$panel.removeClass( 'isChanged' );
}
var setLooping = function () {
$('.js-looping li').on({
'mouseenter' : function () {
if ( conditionMap.window_is_pc ) {
$(this).addClass('isChanged');
}
},
'mouseleave' : function () {
if ( conditionMap.window_is_pc ) {
$(this).removeClass('isChanged');
}
}
});
};
setRandomChange = setInterval( function() {
if ( windowWidth >= stateMap.is_pc_window ) {
var timing = Math.floor( Math.random() * view );
$( '.looping li.random' ).removeClass( 'isChanged random' );
$( '.looping li' ).each( function ( i ) {
if ( i % ( timing + view ) === 0 && !$( this ).hasClass( 'isChanged' ) ) {
$( this ).addClass( 'isChanged random' );
}
});
}
else {
$( '.looping li.random' ).removeClass( 'isChanged random' );
}
}, 4000);
// ----------------------------------------
// SP のときのスクロールイベント
// ----------------------------------------
function setChangePanel () {
if ( windowWidth <= stateMap.is_sp_window ) {
var scrollAmount = $( window ).scrollTop();
$panel.each( function (){
var panelShow = $( this ).offset().top + $( this ).height() * 3;
if ( scrollAmount + windowHeight >= panelShow ) {
$( this ).addClass( 'isChanged' );
}
else if ( scrollAmount + windowHeight <= panelShow ) {
$( this ).removeClass( 'isChanged' );
}
});
}
else {
$panel.removeClass( 'isChanged' );
}
}
$( window ).on( 'scroll', function () {
setChangePanel();
});
// ----------------------------------------
// トップへ戻るボタン
// ----------------------------------------
var setBackToTop = function () {
var $btnObj = $( "#toTop" );
// スクロールイベント
$( window ).on( 'scroll', function () {
var timer = false;
if ( timer !== false ) {
clearTimeout( timer );
}
timer = setTimeout( function () {
var scrollDepth = $( window ).scrollTop();
if( scrollDepth > 150 ) {
$btnObj.fadeIn(200);
}
else {
$btnObj.fadeOut(200);
}
}, 100);
});
// クリックイベント
$btnObj.click( function () {
$( 'html, body' ).stop().animate( {
scrollTop: 0
}, 500, 'swing' );
return false;
});
}();
// ----------------------------------------
// カルーセルの中身に応じて、ページを遷移させる
// ----------------------------------------
var changeContents = function () {
var
$slickObj = $( '#slick' ),
$slickItem = $( '#slick li' ),
myFileName = window.location.href.split('/').pop().slice(0, 3),
myFileNum = parseInt( myFileName, 10 ) - 2; // 2番目のスライドだけ非公開のため、1 多くマイナスしている。
// myFileNum がマイナスだったら、001.html に移動する
if ( myFileNum < 0 ) {
myFileNum = 0;
}
// slick のデフォルト設定
// 最初に表示するスライド -> 自分のファイル名の番号
// * 始まりは 0 から
if ( $slickObj.length ) {
$slickObj.slick({
appendArrows : $( '#arrows' ),
lazyLoads : 'ondemand',
initialSlide : myFileNum
});
}
// スライド変更前に、タイマーをクリアする
var timer = false;
// スライドが変わる前に、setTimeout メソッドの処理を中止する
$slickObj.on( 'beforeChange', function() {
clearTimeout( timer );
});
// ページを遷移させる
// 動作:
// 現在のスライドの data-id を取得する
// ページを取得した data-id と同じ番号のファイルに遷移させる
$slickObj.on( 'afterChange', function( event, slick, currentSlide ) {
timer = setTimeout( function () {
// currentSlide の data-id を取得する
var $targetFileNum = $( slick.$slides.get( currentSlide )).attr( 'data-id' );
// $targetFileNum と同じファイル名のページに遷移させる
window.location.href = '/special_contents/forones/articles/' + $targetFileNum + '.html';
}, 700);
});
}();
// ----------------------------------------
// コンテンツの続きを読む
// ----------------------------------------
// 文字数を切り詰める
function charaLimitInit () {
var
linesNum = 2,
afterTxt = ' …';
var dummyTxt = ' ';
for( var i = 1; i < linesNum; i++ ) dummyTxt += '<br> ';
$char.each( function () {
$( this ).css({ visibility : 'hidden' });
str = $( this ).text();
$( this ).html( dummyTxt );
var h = $( this ).height() + 5;
$( this ).text( str );
while( $( this ).height() > h){
str = str.slice( 0, -1 );
$( this ).text( str + afterTxt );
}
$( this ).css({ visibility:'visible' });
});
};
function readMore () {
var
$char = $('#js-isHidden .media__txt'),
str = '';
$( document ).on( 'click', '.media__btn--more', function () {
$char.fadeOut( 200, function () {
$( this ).text( originalStr ).fadeIn( 300 );
$btnMore.css({ 'display' : 'none' });
$btnClose.css({ 'display' : 'block' });
flag_isChanged = true;
});
return false;
});
$( document ).on( 'click', '.media__btn--close', function () {
charaLimitInit();
$btnMore.css({ 'display' : 'block' });
$btnClose.css({ 'display' : 'none' });
flag_isChanged = false;
return false;
});
if( $char.length ){
charaLimitInit();
}
};
// ---------- リサイズイベント開始 ----------
$( window ).on( 'resize', function() {
var timer = false;
if( timer !== false ) {
clearTimeout(timer);
}
timer = setTimeout( function() {
if ( conditionMap.window_is_pc ) {
$char.text( originalStr );
$btnMore.css({ 'display' : 'none' });
$btnClose.css({ 'display' : 'none' });
}
else {
if ( flag_isChanged === true ) {
$btnMore.css({ 'display' : 'none' });
$btnClose.css({ 'display' : 'block' });
}
else {
readMore();
$btnMore.css({ 'display' : 'block' });
$btnClose.css({ 'display' : 'none' });
}
}
}, 100 );
});
$( window ).on( 'load', function () {
if ( windowWidth <= 1024 ) {
readMore();
}
});
// ----------------------------------------
// SNS のリンクを設定する
// ----------------------------------------
var setSocial = function() {
var
title = encodeURIComponent( $( 'meta[property="og:title"]' ).attr( 'content' ) || document.title ),
url = encodeURIComponent( document.URL ),
ua = window.navigator.userAgent.toLowerCase(),
device = ua.match( /iphone|ipod|ipad|android|iemobile/ )? 'sp' : 'pc';
$( '.sns__button--twitter a' ).each( function () {
$( this ).attr( 'href', 'https://twitter.com/intent/tweet?tw_p=tweetbutton&text=' + title + '&url=' + url );
$( this ).on( 'click', function () {
window.open( $( this ).attr( 'href' ), 'twWin', 'width=550,height=450' );
return false;
});
});
$( '.sns__button--fb a' ).each( function () {
$( this ).attr( 'href', 'https://www.facebook.com/sharer/sharer.php?src=share_button&u=' + url );
$( this ).on( 'click', function () {
window.open( $( this ).attr( 'href' ), 'fbWin', 'width=550,height=450' );
return false;
});
});
$( '.sns__button--line a' ).each( function () {
$( this ).attr( 'href', 'http://line.me/R/msg/text/?' + title + '%20' + url );
if( device == 'pc' ) $( this ).attr( 'target', '_blank' );
});
}();
var c = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65],
n = !1;
$(document).on("keyup", function(t) {
n || t.keyCode != c[0] ? n && (t.keyCode == c[n] ? (n++, n == c.length && ($("html").css({
"-webkit-transition": "all 1000ms ease-out",
"-moz-transition": "all 1000ms ease-out",
"-ms-transition": "all 1000ms ease-out",
"-o-transition": "all 1000ms ease-out",
transition: "all 1000ms ease-out",
"-webkit-transform": "rotate(1080deg)",
"-moz-transform": "rotate(1080deg)",
"-ms-transform": "rotate(1080deg)",
"-o-transform": "rotate(1080deg)",
transform: "rotate(1080deg)"
}), setTimeout(function() {
$("body").scrollTo('body#top');
}, 1e3), $(this).off("keyup"))) : n = !1) : n = 1
});
});
<file_sep>/gulpfile.js
var
requireDir = require('require-dir'),
dir = requireDir('./gulp_tasks', { recurse: true }),
gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
del = require('del'),
runSequence = require('run-sequence')
gulp.task('default', function() {
return runSequence(['clean'], ['server', 'images_copy', 'html', 'sass', 'scripts']);
});<file_sep>/gulp_tasks/config.js
module.exports = {
src : 'src/',
dest : 'htdocs/',
html : {
src : 'src/**/*.html',
dest : 'htdocs/',
},
ssi : {
src : 'src/assets/ssi/*.html',
dest : 'htdocs/assets/ssi/'
},
css : {
src : 'src/special_contents/forones/assets/sass/**/*.scss',
dest : 'htdocs/special_contents/forones/assets/styles/'
},
js : {
src : 'src/special_contents/forones/assets/scripts/*.js',
dest : 'htdocs/special_contents/forones/assets/scripts/'
}
};<file_sep>/README.md
# 某大手通信会社 CSRサイト
## 業務内容
- フロントエンドのコーディング。
- JavaScript ( jQuery ) のコーディング。
- 工数管理の策定
- サイト設計
## 担当フェーズ
- サイトの要件定義
- コーディングルールの策定
- フロントエンドのコーディング
- JavaScript ( jQuery ) のコーディング
## 言語
- jQuery
- HTML5
- Sass( CSS3 )
## ツール
- Git
- Gulp
## メンバー・役割
チーム:5名
役割:リード・フロントエンド・エンジニア
<file_sep>/gulp_tasks/scripts.js
$ = require('gulp-load-plugins')();
gulp = require('gulp');
config = require('./config');
plumber = require('gulp-plumber');
gulp.task( 'scripts', function () {
return gulp.src( [ config.js.src ] )
.pipe( gulp.dest( config.js.dest ) );
});<file_sep>/gulp_tasks/images.js
var
$ = require('gulp-load-plugins')(),
gulp = require('gulp'),
coffee = require('gulp-coffee'),
config = require('./config');
gulp.task( 'images_copy', function () {
return gulp.src([
config.src + '**/*.+(jpg|jpeg|png|gif)'
])
.pipe( $.changed( config.PATH_PRE_SRC + '**/*.+( jpg|jpeg|png|gif )' ))
.pipe(gulp.dest( config.dest ));
});<file_sep>/gulp_tasks/sass.js
var
$ = require('gulp-load-plugins')(),
gulp = require('gulp'),
config = require('./config'),
sass = require('gulp-sass'),
browserSync = require('browser-sync'),
plumber = require('gulp-plumber');
gulp.task( 'sass', function () {
gulp.src( config.css.src )
.pipe( plumber() )
.pipe( sass().on( 'error', sass.logError ) )
.pipe( $.sass() )
.pipe( $.autoprefixer({
browsers: ['last 2 versions']
}) )
.pipe( $.sass ({
style: 'expanded'
}) )
.pipe( gulp.dest( config.css.dest ) );
}); | 6711495cf119cdb3a187c2d71a3b7a5a9ab68519 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | Yamato0516/teleco | b32226023d1130d171e874b6930a54642bd8b2af | b61080be7550a433d99394c5b684a857609c8067 |
refs/heads/master | <repo_name>Elza-Espina/Laboratory-Equipment-Inventory-Software-System-<file_sep>/application/models/LaboratoryModel.php
<?php
class LaboratoryModel extends CI_Model {
public $labID;
public $labName;
public $description;
function __construct(){
parent::__construct();
}
public function addLaboratory(){
$data = array(
'labName' => $_POST['labName'],
'description' => $_POST['description']
);
return $this->db->insert('laboratory',$data);
}
public function deleteLaboratory(){
return $this->db->delete('laboratory',array('labID' => $_POST['labID']));
}
public function getLaboratories(){
$list = $this->db->get('laboratory');
return $list->result();
}
}
<file_sep>/application/views/allLaboratories.php
<?php $this->load->view('js'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Laboratory Equipment Inventory Software System</title>
<!-- Bootstrap CSS -->
<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="<?php echo base_url(); ?>css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="<?php echo base_url(); ?>css/elegant-icons-style.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/font-awesome.min.css" rel="stylesheet" />
<!-- Custom styles -->
<link href="<?php echo base_url(); ?>css/widgets.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style-responsive.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/custom.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<script src="js/respond.min.js"></script>
<script src="js/lte-ie7.js"></script>
<![endif]-->
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<!--main content start-->
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<h3 class="page-header"><i class="fa fa-list-alt"></i>List of All Equipments</h3>
<div class="input-group">
<<<<<<< HEAD
<input type="text" class="form-control" placeholder="Search for..." id="searchEquipment">
=======
<input type="text" class="form-control" placeholder="Search for..." id="searchAll">
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
<span class="input-group-btn">
<button class="btn btn-default form-control" type="button"><i class=" icon_search"></i></button>
</span>
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-lg-12">
<section class="panel panel-primary">
<table class="table table-striped" id='listAllEquipments'>
<thead >
<tr>
<th class="th"><i class="icon_clipboard"></i> Name</th>
<th class="th"><i class="icon_datareport_alt"></i> Quantity</th>
</tr>
</thead>
<tbody>
<?php if(null != $equipList){
foreach ($equipList as $key) { ?>
<tr>
<td><?php echo $key['eqpName']; ?></td>
<td><?php echo $key['quantity']; ?></td>
</tr>
<?php }
}else{?>
<tr>
<td>No records to display..</td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</section>
</div>
</div>
<div class="widget-foot">
<!-- Footer goes here -->
</div>
</div>
</div>
</div>
</div>
<!-- project team & activity end -->
</section>
</section>
</section>
<!-- container section start -->
<!-- javascripts -->
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-ui-1.10.4.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery-ui-1.9.2.custom.min.js"></script>
<!-- bootstrap -->
<script src="<?php echo base_url(); ?>js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="<?php echo base_url(); ?>js/jquery.scrollTo.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.nicescroll.js" type="text/javascript"></script>
<!--custome script for all page-->
<!-- custom script for this page-->
<script src="<?php echo base_url(); ?>js/jquery-jvectormap-1.2.2.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-jvectormap-world-mill-en.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.autosize.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.placeholder.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.slimscroll.min.js"></script>
</body>
</html>
<file_sep>/application/controllers/Reports.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Reports extends CI_Controller {
// Added by JV
public function __construct(){
parent::__construct();
$this->load->helper('url');
}
public function loadReports($lab = null){
$this->load->model('EquipmentModel');
$this->load->model('BorrowListModel');
$this->load->model('LaboratoryModel');
$data['view'] = 'reports';
$months = array();
$sem1 = array('Jun', 'Jul', 'Aug', 'Sep', 'Oct');
$sem2 = array('Nov', 'Dec', 'Jan', 'Feb', 'Mar');
if (in_array(date('M'), $sem1)) {
for($i = 0; $i < count($sem1); $i++){
if($sem1[$i] != date('M')){
array_push($months, $sem1[$i]);
}else{
array_push($months, date('M'));
break;
}
}
}else if (in_array(date('M'), $sem2)) {
for($i = 0; $i < count($sem2); $i++){
if($sem2[$i] != date('M')){
array_push($months, $sem2[$i]);
}else{
array_push($months, date('M'));
break;
}
}
}
$data['months'] = $months;
if($lab == 'all'){
$data['eqpList'] = $this->BorrowListModel->getBorrowedList($months);
$data['totalItems'] = $this->EquipmentModel->getAllItems();
}else{
$data['eqpList'] = $this->BorrowListModel->getBorrowedListPerLab($months, $lab);
$data['totalItems'] = $this->EquipmentModel->getAllLabItems($lab);
}
$this->load->view('reports', $data);
}
// end
}
<file_sep>/application/views/index.php
<?php $this->load->view('js'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Laboratory Equipment Inventory Software System</title>
<!-- Bootstrap CSS -->
<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="<?php echo base_url(); ?>css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="<?php echo base_url(); ?>css/elegant-icons-style.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/font-awesome.min.css" rel="stylesheet" />
<!-- Custom styles -->
<link href="<?php echo base_url(); ?>css/widgets.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style-responsive.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/custom.css" rel="stylesheet">
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<!--header start-->
<header class="header">
<div class="toggle-nav">
<div class="icon-reorder"><i class="icon_menu"></i></div>
</div>
<a href="index.html" class="logo">Laboratory Equipment Inventory Software System</a>
</div>
</header>
<!--header end-->
<!--sidebar start-->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu">
<<<<<<< HEAD
<li id="all" class="active"><a>
<i class="icon_grid-3x3"></i>
<span style="cursor: pointer;">All</span>
</a></li>
<table id="labList" width="100%"></table>
<li id="reports"><a>
<i class="icon_piechart"></i>
<span style="cursor: pointer;">Reports</span>
</a></li>
=======
<span style="cursor: pointer;"><li id="all" class="active"><a>
<i class="icon_grid-3x3"></i>All</a></li></span>
<span style="cursor: pointer;"><table id="labList" width="100%"></table></span>
<span style="cursor: pointer;"><li id="reports" onclick="getFrame('reports')"><a>
<i class="icon_piechart"></i>Reports</a></li></span>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
</ul>
<!-- sidebar menu end-->
</div>
</aside>
<!--sidebar end-->
<!--main content start-->
<section id="main-content">
<iframe id="frame" src="<?php echo site_url('Index/loadIframe/all');?>"></iframe>
</section>
<!--main content end-->
<a id="addBtn" class="btn btn-success btn-lg add-btn">Add Laboratory</a>
<div id="addLab" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Add Laboratory</h2>
</div>
<div class="modal-body">
Name </br><input type="text" class="input" id="labName">
<p class="idNumValidate" id="labNameValidate"></p>
Description <i>(optional)</i></br><textarea id="description" class="input" rows="4"></textarea>
</div>
<div class="modal-footer">
<button type="button" id="addLabBtn" class="btn btn-success btn-lg modalBtn">Add Laboratory</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="addEqpmnt" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Add Equipment</h2>
</div>
<div class="modal-body">
<table align="center" width="60%">
<tr>
<<<<<<< HEAD
<td align="center">Serial No</td><td><input type="text" name="eqpSerialNum" id="eqpSerialNum" class="input" required autofocus="true"></td>
=======
<td align="center">Serial No</td><td><input type="text" name="eqpSerialNum" id="eqpSerialNum" class="input"></td>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
</tr><br><tr>
<td align="center">Name </td><td><input type="text" id="eqpName" name="eqpName" class="input" required autofocus="true"></td>
</tr><br><tr align="center">
<td><input type="radio" name="item" id="equiptype" value="component"> Component</td>
<td><input type="radio" name="item" id="equiptype" value="equipment" checked> Equipment</td>
</tr><br><tr>
<td align="center">Price </td><td><input type="text" onkeypress="return isNumberKey(event)" id="eqpPrice" class="input" name="eqpPrice" required autofocus="true"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" id="addEquipment" class="btn btn-success btn-lg modalBtn" >Add Equipment</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</section>
<!-- javascripts -->
<script type="text/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script src = "<?php echo base_url();?>js/jquery.js"></script>
<script src="<?php echo base_url();?>js/jquery-ui-1.10.4.min.js"></script>
<script src="<?php echo base_url();?>js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-ui-1.9.2.custom.min.js"></script>
<!-- bootstrap -->
<script src="<?php echo base_url();?>js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="<?php echo base_url();?>js/jquery.scrollTo.min.js"></script>
<script src="<?php echo base_url();?>js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- charts scripts -->
<script src="<?php echo base_url();?>assets/jquery-knob/js/jquery.knob.js"></script>
<!--script for this page only-->
<script src="<?php echo base_url();?>js/jquery.rateit.min.js"></script>
<!-- custom select -->
<script src="<?php echo base_url();?>js/jquery.customSelect.min.js" ></script>
<script src="<?php echo base_url();?>assets/chart-master/Chart.js"></script>
<!--custome script for all page-->
<script src="<?php echo base_url();?>js/scripts.js"></script>
<!-- custom script for this page-->
<script src="<?php echo base_url();?>js/jquery-jvectormap-1.2.2.min.js"></script>
<script src="<?php echo base_url();?>js/jquery-jvectormap-world-mill-en.js"></script>
<script src="<?php echo base_url();?>js/jquery.autosize.min.js"></script>
<script src="<?php echo base_url();?>js/jquery.placeholder.min.js"></script>
<script src="<?php echo base_url();?>js/jquery.slimscroll.min.js"></script>
</body>
</html>
<file_sep>/application/models/DamageListModel.php
<?php
class DamageListModel extends CI_Model {
public $damagerIDNum;
public $labID;
public $compSerialNum;
public $eqpSerialNum;
public $teacher;
function __construct(){
parent::__construct();
}
public function addDamageEquipments(){
$return = array();
foreach ($_POST['equipment'] as $equipment) {
$this->damagerIDNum = $_POST['damagerID'];
$this->eqpSerialNum = $equipment;
$this->teacher = $_POST['damagerTeacher'];
$return[] = $this->db->insert('damaged_list',$this);
}
return $return;
}
public function getDamageEquipmentList(){
<<<<<<< HEAD
$this->db->select("D.compSerialNum,D.eqpSerialNum,D.dateReported, E.eqpName");
$this->db->from('damaged_list D');
$this->db->join('equipment E', 'E.eqpSerialNum = D.eqpSerialNum', 'left');
=======
$this->db->select("compSerialNum,eqpSerialNum,dateReported");
$this->db->from('damaged_list');
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
$result = $this->db->get()->result_array();
return $result;
// $list = $this->db->get('damaged_list');
// return $list->result();
}
public function repairEquipments(){
<<<<<<< HEAD
$result = array();
foreach ($_POST['equipment'] as $equipment) {
$this->db->from('damaged_list');
$this->db->where('eqpSerialNum', $equipment);
$result[] = $this->db->delete();
}
return $result;
=======
foreach ($_POST['equipment'] as $equipment) {
$this->db->set('isRepaired', 1);
$this->db->where('eqpSerialNum', $equipment);
return $this->db->update('damaged_list');
}
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
}
}
<file_sep>/application/models/EquipmentModel.php
<?php
class EquipmentModel extends CI_Model {
public $eqpName;
public $eqpSerialNum;
public $price;
public $compName;
public $compSerialNum;
public $compPrice;
function __construct(){
parent::__construct();
}
public function getAllEquipments(){
$this->db->select('count(*) as "quantity", eqpName');
$this->db->from('equipment');
$this->db->group_by('eqpName');
return $this->db->get()->result_array();
}
public function addEquipment(){
$data = array(
'eqpName' => $_POST['eqpName'],
'eqpSerialNum' => $_POST['eqpSerialNum'],
'labID' => $_POST['labID'],
'price' => $_POST['eqpPrice']
);
return $this->db->insert('equipment',$data);
}
public function addEquipmentComp(){
$data = array(
'compName' => $_POST['compName'],
'compSerialNum' => $_POST['compSerialNum'],
'labID' => $_POST['labID'],
'price' => $_POST['compPrice']
);
return $this->db->insert('component',$data);
}
public function getEquipmentList($labID){
<<<<<<< HEAD
// $labID=$_POST['labID'];
=======
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
$result = array();
$this->db->select('*');
$this->db->from('laboratory');
$this->db->where('labID', $labID);
$result[] = $this->db->get()->result_array();
$this->db->select('eqp.*');
$this->db->from('laboratory lab');
$this->db->join('equipment eqp', 'eqp.labID = lab.labID', 'left');
$this->db->where('eqp.labID', $labID);
$result[] = $this->db->get()->result_array();
$this->db->select('comp.*');
$this->db->from('laboratory labb');
$this->db->join('component comp', 'comp.labID = labb.labID', 'left');
$this->db->where('comp.labID', $labID);
$result[] = $this->db->get()->result_array();
return $result;
}
<<<<<<< HEAD
=======
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
public function getLabEquipmentList(){
$labID = $_POST['labID'];
$this->db->select('*');
$this->db->from('equipment');
$this->db->where('labID', $labID);
$result = $this->db->get()->result_array();
return $result;
}
public function getEquipments(){
$filter = $_POST['search'];
$this->db->select('eqpSerialNum, eqpName');
$this->db->from('equipment');
<<<<<<< HEAD
if($_POST['labID']){
$this->db->where('labID',$_POST['labID']);
}
if($_POST['labID'] && $filter == 'available'){
$this->db->where('labID='.$_POST['labID'].' and eqpSerialNum NOT IN (SELECT eqpSerialNum FROM borrowed_list) and eqpSerialNum NOT IN (SELECT eqpSerialNum FROM damaged_list)');
=======
if($filter == 'undamagedEquipments' || $filter == 'unborrowedEquipments'){
$this->db->where('eqpSerialNum NOT IN (SELECT eqpSerialNum FROM borrowed_list) and eqpSerialNum NOT IN (SELECT eqpSerialNum FROM damaged_list)', NULL, FALSE);
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
}
$list = $this->db->get()->result_array();
$equipmentList = array();
foreach ($list as $key) {
$equipmentList[] = $key['eqpSerialNum']." - ".$key['eqpName'];
}
return $equipmentList;
}
public function searchEquipment(){
$this->db->select('*');
$this->db->from('equipment');
$searchThis = array('eqpSerialNum' => $_POST['equipmentSerialNum'], 'eqpName' => $_POST['equipmentName']);
$this->db->where($searchThis);
$result = $this->db->get()->result_array();
return $result;
}
<<<<<<< HEAD
public function getAvailableEquipments(){
$labID = $_POST['labID'];
$where= "labID =".$labID." AND eqpSerialNum NOT IN (SELECT eqpSerialNum FROM damaged_list) AND eqpSerialNum NOT IN (SELECT eqpSerialNum FROM borrowed_list)";
$this->db->select('*');
$this->db->from('equipment');
$this->db->where($where);
=======
public function getDamageEquipments(){
$this->db->select('*');
$this->db->from('equipment');
$this->db->where('eqpSerialNum NOT IN (SELECT eqpSerialNum FROM damaged_list) AND eqpSerialNum NOT IN (SELECT eqpSerialNum FROM borrowed_list)', NULL, FALSE);
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
$result = $this->db->get()->result_array();
return $result;
}
public function getEquipmentDetails(){
$equipment = $_POST['equipmentSerialNum'];
$this->db->select('eqpSerialNum as "serialNum", eqpName as "name", price as "price"');
$this->db->from('equipment');
$this->db->where('eqpSerialNum', $equipment);
$result = $this->db->get()->result_array();
if($result){
}else{
$this->db->select('compSerialNum as "serialNum", compName as "name", price as "price"');
$this->db->from('component');
$this->db->where('compSerialNum', $equipment);
$result = $this->db->get()->result_array();
}
return $result;
}
public function updateEquipment(){
$this->db->where('eqpSerialNum', $_POST['eqpSerialNum']);
$query = $this->db->get('equipment');
if ($query->num_rows() > 0){
$data = array(
'eqpName' => $_POST['eqpName'],
'eqpSerialNum' => $_POST['eqpSerialNum'],
'price' => $_POST['eqpPrice']
);
$this->db->where('eqpSerialNum', $_POST['eqpSerialNum']);
return $this->db->update('equipment', $data);
}
else{
$data = array(
'compName' => $_POST['eqpName'],
'compSerialNum' => $_POST['eqpSerialNum'],
'price' => $_POST['eqpPrice']
);
$this->db->where('compSerialNum', $_POST['eqpSerialNum']);
return $this->db->update('component', $data);
}
}
<<<<<<< HEAD
=======
public function getBorrowEquipments(){
$this->db->select('*');
$this->db->from('equipment');
$this->db->where('eqpSerialNum NOT IN (SELECT eqpSerialNum FROM borrowed_list) AND eqpSerialNum NOT IN (SELECT eqpSerialNum FROM damaged_list)', NULL, FALSE);
$result = $this->db->get()->result_array();
return $result;
}
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
public function getEquipmentHistory(){
$eqpSerial = $_POST['equipmentSerialNum'];
$result = array();
$this->db->select('D.dateReported, S.studentID, S.studentName');
$this->db->from('damaged_list D');
$this->db->join('student S', 'S.studentID = D.damagerIDNum', 'left');
$this->db->where('D.eqpSerialNum', $eqpSerial);
$result[] = $this->db->get()->result_array();
$this->db->select('B.borrowedDate, S.studentID, S.studentName');
$this->db->from('borrowed_list B');
$this->db->join('student S', 'S.studentID = B.borrowerIDNum', 'left');
$this->db->where('B.eqpSerialNum', $eqpSerial);
$result[] = $this->db->get()->result_array();
return $result;
}
<<<<<<< HEAD
public function getAllItems(){
$total = 0;
$this->db->select('count(*) as "totalEqp"');
$query = $this->db->get('equipment');
$total += intval($query->result()[0]->totalEqp);
$this->db->select('count(*) as "totalComp"');
$query = $this->db->get('component');
$total += intval($query->result()[0]->totalComp);
return $total;
}
public function getAllLabItems($lab = null){
$total = 0;
$this->db->select('count(*) as "totalEqp"');
$this->db->where('labID', $lab);
$query = $this->db->get('equipment');
$total += intval($query->result()[0]->totalEqp);
$this->db->select('count(*) as "totalComp"');
$this->db->where('labID', $lab);
$query = $this->db->get('component');
$total += intval($query->result()[0]->totalComp);
return $total;
}
=======
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
// end
}
<file_sep>/application/views/lab.php
<?php $this->load->view('js'); ?>
<!DOCTYPE html>
<html>
<head>
<title>Laboratory Equipment Inventory Software System</title>
<!-- Bootstrap CSS -->
<link href="<?php echo base_url(); ?>css/bootstrap.min.css" rel="stylesheet">
<!-- bootstrap theme -->
<link href="<?php echo base_url(); ?>css/bootstrap-theme.css" rel="stylesheet">
<!--external css-->
<!-- font icon -->
<link href="<?php echo base_url(); ?>css/elegant-icons-style.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/font-awesome.min.css" rel="stylesheet" />
<!-- Custom styles -->
<link href="<?php echo base_url(); ?>css/widgets.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/style-responsive.css" rel="stylesheet" />
<link href="<?php echo base_url(); ?>css/jquery-ui-1.10.4.min.css" rel="stylesheet">
<link href="<?php echo base_url(); ?>css/custom.css" rel="stylesheet">
<script src="<?php echo base_url(); ?>js/paging.js" type="text/javascript"></script>
<link href="<?php echo base_url(); ?>css/paging.css" rel="stylesheet">
</head>
<body>
<!-- container section start -->
<section id="container" class="">
<!--main content start-->
<section class="wrapper">
<!--overview start-->
<div class="row">
<div class="col-lg-12">
<<<<<<< HEAD
<input type="hidden" value="<?php echo $equipList[0][0]['labID']; ?>" id = "currLab">
<h3 class="page-header" id="pageHeader"><i class="icon_menu-square_alt2"></i><?php echo $equipList[0][0]['labName']; ?>
<a class="btn btn-danger btn-lg pull-right" data-toggle="modal" data-target="#deleteModal" style="margin-top: -1%">Delete Laboratory</a></h3>
=======
<h3 class="page-header" id="pageHeader"><i class="icon_menu-square_alt2"></i><?php echo $equipList[0][0]['labName']; ?><a class="btn btn-danger btn-lg pull-right" data-toggle="modal" data-target="#deleteModal" style="margin-top: -1%">Delete Laboratory</a></h3>
<h5><font size="3"><?php echo $equipList[0][0]['description']; ?></font></h5><br>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
</div>
</div>
<div class="row">
<div class="col-lg-12">
<ol class="breadcrumb">
<li><i class=" icon_menu-square_alt2"></i>All</li>
<<<<<<< HEAD
<li class="pointer"><i class="arrow_carrot-2up_alt2"></i><a data-toggle="modal" data-target="#borrowModal" id="borrow">Borrow</a></li>
<li class="pointer"><i class="arrow_triangle-down_alt2"></i><a data-toggle="modal" data-target="#returnModal" id="return">Return</a></li>
<li class="pointer"><i class=" icon_error-circle_alt"></i><a data-toggle="modal" data-target="#damageModal" id="fde">File Damaged Equipment</a></li>
<li class="pointer"><i class=" icon_check_alt2"></i><a data-toggle="modal" data-target="#repairModal" id="repair">Repair Equipment</a></li>
</ol>
<div class="input-group">
<span class="input-group-btn">
<i class=" icon_search"></i>
</span>
<input type="text" style= "margin-left: 5px" class="form-control" placeholder="Search for..." id="searchEquipment">
=======
<li class="pointer"><i class="arrow_carrot-2up_alt2"></i><a data-toggle="modal" data-target="#borrowModal">Borrow</a></li>
<li class="pointer"><i class="arrow_triangle-down_alt2"></i><a data-toggle="modal" data-target="#returnModal">Return</a></li>
<li class="pointer"><i class=" icon_error-circle_alt"></i><a data-toggle="modal" data-target="#damageModal">File Damaged Equipment</a></li>
<li class="pointer"><i class=" icon_check_alt2"></i><a data-toggle="modal" data-target="#repairModal" id="repair">Repair Equipment</a></li>
</ol>
<div class="input-group">
<input type="text" class="form-control" placeholder="Search for..." id="searchEquipment">
<span class="input-group-btn">
<button class="btn btn-default form-control" type="button"><i class=" icon_search"></i></button>
</span>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
</div>
</br>
<!-- Display Table List -->
<section class="panel panel-primary">
<table class="table table-striped table-advance table-hover" id="labEquipmentsTable">
<thead><tr>
<th class="th"><i class="icon_tag"></i> Serial No.</th>
<th class="th"><i class="icon_clipboard"></i> Name</th>
<th class="th"><i class="icon_clipboard"></i> Type</th>
<th class="th"><i class="icon_cogs"></i> Actions
<img src="<?php echo base_url();?>img/icons/move-icon.png" class="move-icon" data-target="#moveModal" data-toggle="modal" rel="tooltip" title="Move">
</th>
</tr></thead>
<tbody>
<?php if(null != $equipList[1] || null != $equipList[2]){
if(null != $equipList[1]){
for($i = 0; $i < count($equipList[1]); $i++){ ?>
<tr>
<td><?php echo $equipList[1][$i]['eqpSerialNum'];?></td>
<td><?php echo $equipList[1][$i]['eqpName'];?></td>
<td><?php echo "Equipment"; ?></td>
<td>
<div class="btn-group">
<a class="btn btn-primary" onclick = "editEquipment('<?php echo $equipList[1][$i]['eqpSerialNum']; ?>')" id="<?php echo $equipList[1][$i]['eqpSerialNum']; ?>" value="<?php echo $equipList[1][$i]['eqpSerialNum']; ?>" rel="tooltip" title="Edit"><i class="icon_pencil"></i></a>
<a class="btn btn-success" onclick = "viewEquipmentHistory('<?php echo $equipList[1][$i]['eqpSerialNum']; ?>', '<?php echo $equipList[1][$i]['eqpName']; ?>')" id="<?php echo $equipList[1][$i]['eqpSerialNum']; ?>" value="<?php echo $equipList[1][$i]['eqpSerialNum']; ?>" rel="tooltip" title="View Equipment History"><i class=" icon_search-2" ></i></a>
</div>
<input type="checkbox" class="check" name="checkItem">
</td>
</tr>
<?php }
}
if(null != $equipList[2]){
for($i = 0; $i < count($equipList[2]); $i++){ ?>
<tr>
<td><?php echo $equipList[2][$i]['compSerialNum'];?></td>
<td><?php echo $equipList[2][$i]['compName'];?></td>
<td><?php echo "Component"; ?></td>
<td>
<div class="btn-group">
<a class="btn btn-primary" onclick = "editEquipment('<?php echo $equipList[2][$i]['compSerialNum']; ?>')" id="<?php echo $equipList[2][$i]['compSerialNum']; ?>" value="<?php echo $equipList[2][$i]['compSerialNum']; ?>" rel="tooltip" title="Edit"><i class="icon_pencil"></i></a>
<a class="btn btn-success" onclick = "viewEquipmentHistory('<?php echo $equipList[2][$i]['compSerialNum']; ?>', '<?php echo $equipList[2][$i]['compName']; ?>')" id="<?php echo $equipList[2][$i]['compSerialNum']; ?>" value="<?php echo $equipList[2][$i]['compSerialNum']; ?>" rel="tooltip" title="View Equipment History"><i class=" icon_search-2" ></i></a>
</div>
<input type="checkbox" class="check" name="checkItem">
</td>
</tr>
<?php }
}
}else{
?>
<tr>
<td>No records to display..</td>
<td></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
<div id="pageNavPosition"></div>
</section>
</section>
<!-- modals -->
<div id="deleteModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Delete Laboratory</h2>
</div>
<div class="modal-body" align="center">
<<<<<<< HEAD
Are you sure you want to delete <?php echo $equipList[0][0]['labName']; ?>?
</div>
<div class="modal-footer">
<button type="button" id="deleteLab" class="btn btn-success btn-lg modalBtn" data-dismiss="modal">Delete Laboratory</button>
=======
Are you sure you want to delete Laboratory 1?
</div>
<div class="modal-footer">
<button type="button" id="deleteLab" class="btn btn-success btn-lg modalBtn" >Delete Laboratory</button>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Move Equipment -->
<div id="moveModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Move Equipment</h2>
</div>
<div class="modal-body" >
<table align="center" width="60%">
<tr>
<td align="center">Serial No</td><td>this serial</td>
</tr><tr>
<td align="center">Name </td><td>this name</td>
</tr><tr>
<td align="center">From </td><td> this laboratory </td>
</tr><tr>
<td align="center">To </td>
<td><select class="input">
<option selected="true">Laboratory 2</option>
</select></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success btn-lg modalBtn" >Save Changes</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Edit Equipment -->
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog" style="overflow: hidden;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Edit Equipment</h2>
</div>
<div class="modal-body" >
<table align="center" width="60%">
<tr>
<td align="center">Serial No</td><td><input type="text" class="input" id="editSerialNum" disabled></td>
</tr><tr>
<td align="center">Name </td><td><input type="text" class="input" id="editName"></td>
</tr><tr>
<td align="center">Price </td><td><input type="text" class="input" id="editPrice"></td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" id="editSaveBtn" class="btn btn-success btn-lg modalBtn" >Save Changes</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- View Equipment History-->
<div id="vehModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title"></h2>
</div>
<div class="modal-body" >
<br>
<table align="center" class="table" width="80%">
<th>Date</th>
<th>Detail</th>
<tbody id="equipmentHistory">
<tr><td><span id="loadSpinner"><i class="fa fa-spinner fa-spin fa-5x fa-fw"></i></span></td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Borrow Equipment -->
<div id="borrowModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Borrow Equipment</h2>
</div>
<div class="modal-body" >
<form>
<table align="center" width="60%">
<tr>
<td align="center">ID number </td><td><input type="number" onmouseup = "checkIDnumber(this.value)" onkeyup = "checkIDnumber(this.value)" class="input" id='borrowerID' required autofocus="true"></td> <td><i class="idNumCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="idNumValidate"></span></td></tr>
<tr>
<td align="center">Name </td><td><input type="text" onkeyup = "validate(this, event)" class="input" id='borrowerName' required autofocus="true"></td> <td><i class="nameCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="nameValidate"></span></td></tr>
<tr>
<td align="center">Teacher </td><td><input type="text" onkeyup = "validate(this, event)" class="input" id='borrowerTeacher' required autofocus="true"></td>
<td><i class="teacherCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="teacherValidate"></span></td></tr>
<tr>
<td align="center">In-charge </td><td><input type="text" onkeyup = "validate(this, event)" class="input" id='incharge' required autofocus="true"></td>
<td><i class="inchargeCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="inchargeValidate"></span></td></tr>
</table>
</br>
<div class="parentDiv">
<div id="borrowModalInnerDiv">
<input type="text" class="input" id="searchBorrowed" placeholder="Search equipments">
<div id="borrowModalInnerDiv2">
<table class="table first " id="borrowedEquipList">
<tr id='borrowmModalHeader'>
<th><u>All Equipments</u></th>
<th align="right"><input type="checkbox" onclick = "checkAllBorrow()" class="returnItem"></th>
</tr>
<tbody id="borrowedList">
<td>No records to display...</td>
<td></td>
</tbody>
</table>
</div>
</div>
<div class="floatRightWidth49">
Borrowed Equipments:
<table class="table" >
<thead class="displayBlock">
<th class="width80">Equipment</th>
</thead>
<tbody id="borrowedEquipments" class="tbodyData"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="borrowBtn" class="btn btn-success btn-lg modalBtn" >Borrow Equipments</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</form>
</div>
<!-- Return Equipment -->
<div id="returnModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Return Equipment</h2>
</div>
<div class="modal-body" >
<table align="center" width="60%">
<tr>
<td align="center">ID number</td><td><input type="number" class="input" id="returnerID"></td>
<td><i class="idNumCheck" aria-hidden="true"></i></td>
<tr><td></td><td><span class="idNumValidate"></span></td></tr>
</tr><tr>
<td align="center">Name </td><td><input type="text" disabled class="input" id="returnerName"></td>
<td><i class="nameCheck" aria-hidden="true"></i></td>
</table>
<br>
Borrowed Equipments:
<table class="table" id="returnModalTable">
<thead id='returnModalHeader' class="th displayBlock">
</thead>
<tbody id="returnedEquipments">
<tr>
<td>No Records to display...</td>
<<<<<<< HEAD
=======
<td></td>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" id="returnBtn" class="btn btn-success btn-lg modalBtn" >Return Equipments</button>
<button type="button" id="modalBtn" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- File Damage Equipment -->
<div id="damageModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">File Damaged Equipment</h2>
</div>
<div class="modal-body" >
<form>
<table align="center" width="60%">
<tr>
<td align="center">ID number </td><td><input type="number" onmouseup = "checkIDnumber(this.value)" onkeyup = "checkIDnumber(this.value)" class="input" id='damagerID' required autofocus="true"></td> <td><i class="idNumCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="idNumValidate"></span></td></tr>
<tr><br>
<td align="center">Name </td><td><input type="text" onkeyup = "validate(this, event)" class="input" id='damagerName' required autofocus="true"></td><td><i class="nameCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="nameValidate"></span></td></tr>
<tr>
<td align="center">Teacher </td><td><input type="text" onkeyup = "validate(this, event)" class="input" id='damagerTeacher' required autofocus="true"></td>
<td><i class="teacherCheck" aria-hidden="true"></i></td>
</tr>
<tr><td></td><td><span class="teacherValidate"></span></td></tr>
</table>
</br>
<div class="parentDiv">
<div id="damageModalInnerDiv">
<input type="text" class="input" id="searchDamaged" placeholder="Search equipments">
<div id="damageModalInnerDiv2">
<table class="table first " id="damagedEquipList">
<tr id="damagemModalHeader">
<th><u>All Equipments</u></th>
<th align="right"><input type="checkbox" onclick = "checkAllDamage()" class="damageItem"></th>
</tr>
<tbody id="damagedList">
<td>No records to display...</td>
<td></td>
</tbody>
</table>
</div>
</div>
<div class="floatRightWidth49">
Damaged Equipments:
<table class="table" class="height95Width100">
<thead class="displayBlock">
<th class="width80">Equipment</th>
<th>Price</th>
</thead>
<tbody id="damagedEquipments" class="tbodyData"></tbody>
</table>
<span>Total: </span><span id="price"></span>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="damageBtn" class="btn btn-success btn-lg modalBtn" >File Damaged Equipments</button>
<button type="button" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</form>
</div>
<!-- Repair Equipment -->
<div id="repairModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Repair Equipment</h2>
</div>
<div class="modal-body" >
Damaged Equipments:
<input type="text" class="input" id="searchDamaged" placeholder="Search equipments">
<table class="table" id="returnModalTable">
<<<<<<< HEAD
=======
<thead id='repairModalHeader' class="th displayBlock">
</thead>
>>>>>>> Modified 1/03/2017 Validations+Bug Fixes
<tbody id="repairEquipments">
<tr>
<td>No Records to display...</td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" id="repairBtn" class="btn btn-success btn-lg modalBtn" >Repair Equipments</button>
<button type="button" id="modalBtn" class="btn btn-danger btn-lg modalBtn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="notifyModal" tabindex="-1" role="dialog" aria-labelledby="notifyModalLabel" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header notifyHeader">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="notifyModalLabel"></h4>
</div>
<div class="modal-body notifyBody">
<div id = 'divContent'></div>
</div>
</div>
</div>
</div>
</section>
<!-- javascript for pagination -->
<script type="text/javascript">
var pager = new Pager('labEquipmentsTable', 5);
pager.init();
pager.showPageNav('pager', 'pageNavPosition');
pager.showPage(1);
</script>
<!-- javascript imports -->
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-ui-1.10.4.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery-ui-1.9.2.custom.min.js"></script>
<!-- bootstrap -->
<script src="<?php echo base_url(); ?>js/bootstrap.min.js"></script>
<!-- nice scroll -->
<script src="<?php echo base_url(); ?>js/jquery.scrollTo.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.nicescroll.js" type="text/javascript"></script>
<!-- custome script for all page -->
<script src="<?php echo base_url(); ?>js/scripts.js"></script>
<!-- custom script for this page -->
<script src="<?php echo base_url(); ?>js/jquery-jvectormap-1.2.2.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery-jvectormap-world-mill-en.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.autosize.min.js"></script>
<script src="<?php echo base_url(); ?>js/jquery.placeholder.min.js"></script>
</body>
</html>
<file_sep>/application/views/reports.php
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<script src="<?php echo base_url(); ?>js/highcharts.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var months = <?php echo json_encode($months);?>;
var items = <?php echo json_encode($eqpList);?>;
var chart = {
chart: {
width: '800',
height: '250'
},
title: {
text: 'Borrowed Items',
x: -20 //center
},
xAxis: {
categories: months
},
yAxis: {
title: {
text: 'Number of Items'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
// },
},
series: [{
name: 'Equipment(s)',
data: items
},
// {
// name: 'Components',
// data: items
// }
]
};
$('#lineChartcontainer').highcharts(chart);
});
</script>
<div style="display: inline-block; height: 17em;">
<span style="font-size: 90px; padding-left: 50px;" id="totalItems"><?php echo $totalItems;?></span><br>
<span style="font-size: 20px;">equipments & components</span>
</div>
<div id='lineChartcontainer' style="float: right"></div>
<div style="display: flex; border: dashed; width: 35%; height: 53%;">Recent Actions</div> | 973dd02ca7365876984a797a3e797c3ae1caa2d6 | [
"PHP"
] | 8 | PHP | Elza-Espina/Laboratory-Equipment-Inventory-Software-System- | 0afb8acde124cb5ee3e51137f16df114d8bba0f4 | e38327f407a09883ba2c550606359e6d4b1a25ad |
refs/heads/main | <file_sep>#include <arpa/inet.h>
#include <ctype.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define MAXLINE 8192 /* Max text line length */
#define LISTENQ 1024 /* Second argument to listen() */
/* Destructively modify string to be upper case */
void upper_case(char *s) {
while (*s) {
*s = toupper(*s);
s++;
}
}
void echo(int connfd) {
// Local variable declarations:
size_t n;
char buf[MAXLINE];
// Keep reading lines until client closes connection:
while ((n = recv(connfd, buf, MAXLINE, 0)) != 0) {
printf("Echo Server received %u (%s) incoming bytes.\n", n, buf);
printf("Echo Server is making those bytes upper case.\n");
upper_case(buf);
printf("Echo Server is sending %u bytes back to client (%s).\n", n, buf);
send(connfd, buf, n, 0);
}
}
int open_listenfd(int port) {
int listenfd; // the listening file descriptor
int optval = 1; // options for setsockopt
struct sockaddr_in serveraddr;
// Create a socket descriptor.
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1;
// Eliminates "Address already in use" error from bind.
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval,
sizeof(int)) < 0)
return -1;
/* listenfd will be an endpoint for all requests to port
on any IP address for this host */
// The socket API says that you need to zero out the bytes first!
bzero((char *)&serveraddr, sizeof(serveraddr));
// Set the AF_INET protocol family.
serveraddr.sin_family = AF_INET;
// Allow incoming connections from any IP address.
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Indicate the port number to "listen" on.
serveraddr.sin_port = htons((unsigned short)port);
// Bind the server information (options and port number) to the
// listening socket file descriptor.
if (bind(listenfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
return -1;
// Make it a listening socket ready to accept connection requests.
if (listen(listenfd, LISTENQ) < 0) return -1;
// Return the prepared listen socket file descriptor.
return listenfd;
}
int main(int argc, char **argv) {
int listenfd; // listening file descriptor
int connfd; // the connection file descriptor
int port; // the port number
// clientaddr records the address information of the client program
// that connects to this server.
struct sockaddr_in clientaddr;
// clientlen is used to record the length of the client adress. This
// is necessary for calling the accept() function.
socklen_t clientlen;
// hp is used to record the client host information through DNS. We
// will use this to lookup the host information using
// gethostbyaddr().
struct hostent *hp;
// haddrp is used to remember the domain name of the host.
char *haddrp;
// client_port is the ephemeral port used by the client.
unsigned short client_port;
// First, check the command line arguments.
if (argc != 2) {
fprintf(stderr, "usage: %s <port>\n", argv[0]);
exit(0);
}
// Next, convert the port number as a string to an integer.
port = atoi(argv[1]);
// Now, create a socket file descriptor to listen for incoming
// connections.
listenfd = open_listenfd(port);
printf("Echo Server is listening on port %d.\n", port);
// As is the case for all servers - run forever! It is only these
// programs that you want to go into an infinte loop!
while (1) {
// Record the size of the clienaddr (struct sockaddr_in) structure.
clientlen = sizeof(clientaddr);
printf("Echo Server is accepting incoming connections on port %d.\n", port);
// Block on accepting incoming connections. When we have an
// incoming connection accept() will fill in the given sockaddr.
//
// So, why do we cast a sockaddr_in to a sockaddr:
//
// struct sockaddr {
// unsigned short sa_family; // address family, AF_xxx
// char sa_data[14]; // 14 bytes of protocol address
// };
connfd = accept(listenfd, (struct sockaddr *)(&clientaddr), &clientlen);
// determine the domain name and IP address of the client
hp = gethostbyaddr((const char *)(&clientaddr.sin_addr.s_addr),
sizeof(clientaddr.sin_addr.s_addr), AF_INET);
// Need to convert the network byte order IP address to dotted IP string.
haddrp = inet_ntoa(clientaddr.sin_addr);
// Convert the port number from network byte order to host byte order.
client_port = ntohs(clientaddr.sin_port);
// Print an information message.
printf(
"Echo Server received a connection to %s (%s).\n"
"Echo Server is using port %u and client has an ephemeral port of "
"%u.\n",
hp->h_name, haddrp, port, client_port);
// Service the connection.
echo(connfd);
printf("Echo Server is closing the connection on %s (%s).\n", hp->h_name,
haddrp);
// Close the connection.
close(connfd);
}
exit(0);
}
<file_sep>SOURCES = $(wildcard *.c)
OBJECTS = $(SOURCES:.c=.o)
BINS := $(patsubst %.c,%,$(SOURCES))
CC = gcc
CC_FLAGS = -w -g
LDFLAGS = -pthread
all: $(BINS)
date
OBJ = $(patsubst %,%.o,$@)
%_threads: $(OBJECTS)
$(CC) $(OBJ) $(LDFLAGS) -o $@
%.o: %.c
$(CC) -c $(CC_FLAGS) $< -o $@
clean:
rm -f $(BINS) $(OBJECTS)
| 1e37713e809e402bbac31b2e8d0432095898b218 | [
"C",
"Makefile"
] | 2 | C | aacastillo/Network_Programming | f3cbf4d4730a59e7fa7409989a692c39cacd33df | ecc9eae4bb17684a662ab8973e6b6751a219b188 |
refs/heads/master | <repo_name>wakawaka427/tumvie<file_sep>/app/src/main/java/jp/co/wakawaka/tumvie/searchlist/Item.java
package jp.co.wakawaka.tumvie.searchlist;
import android.graphics.Bitmap;
/**
* Created by wakabayashieisuke on 2016/07/05.
*/
public class Item {
public int id;
public String postId;
public String sourceBlogName;
public Bitmap videoThumbnailBitmap;
public String videoThumbnailUrl;
public String caption;
public String videoUrl;
public boolean isFavorite;
}
<file_sep>/app/src/main/java/jp/co/wakawaka/tumvie/activity/SettingActivity.java
package jp.co.wakawaka.tumvie.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import jp.co.wakawaka.tumvie.R;
public class SettingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
}
/**
* 利用規約クリック処理
* @param view
*/
public void onClickTerms(View view) {
startActivity(new Intent(this, TermsActivity.class));
}
/**
* ライセンスクリック処理
* @param view View
*/
public void onClickLicense(View view) {
startActivity(new Intent(this, LicenseActivity.class));
}
}
<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "jp.co.wakawaka.tumvie"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
buildConfigField "String", "CONSUMER_KEY", "\"${project.property("tumblrConsumerKey")}\""
buildConfigField "String", "CONSUMER_SECRET", "\"${project.property("tumblrConsumerSecret")}\""
buildConfigField "String", "TUMBLR_OAUTH_URL", "\"${project.property("tumblrOAuthUrl")}\""
debuggable true // デバッグモードか
zipAlignEnabled true // zip圧縮を行うか
minifyEnabled false // 難読化を行うか
}
release {
buildConfigField "String", "CONSUMER_KEY", "\"${project.property("tumblrConsumerKey")}\""
buildConfigField "String", "CONSUMER_SECRET", "\"${project.property("tumblrConsumerSecret")}\""
buildConfigField "String", "TUMBLR_OAUTH_URL", "\"${project.property("tumblrOAuthUrl")}\""
debuggable false
zipAlignEnabled true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
// compile 'com.google.android.exoplayer:exoplayer:r1.5.9'
compile 'com.google.android.gms:play-services:6.+'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:customtabs:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
//compile 'com.android.support:recyclerview-v7:23.4.0'
//compile 'com.squareup.okhttp3:okhttp:3.3.1'
//compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.tumblr:jumblr:0.0.11'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.realm:android-adapters:1.2.1'
//compile 'com.github.thorbenprimke:realm-recyclerview:0.9.23'
//compile 'com.github.orangegangsters:swipy:1.2.3@aar'
}
<file_sep>/app/src/main/java/jp/co/wakawaka/tumvie/historylist/HistoryListFragment.java
package jp.co.wakawaka.tumvie.historylist;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import jp.co.wakawaka.tumvie.R;
/**
* 履歴リストのFragmentクラス
*/
public class HistoryListFragment extends Fragment {
private Realm realm;
private HistoryListViewAdapter historyListAdapter;
private ListView historyList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_history_list, container, false);
historyList = (ListView) view.findViewById(R.id.history_list);
return view;
}
public void reloadList() {
if (historyList == null) {
historyList = (ListView) getActivity().findViewById(R.id.history_list);
}
if (realm == null) {
realm = Realm.getDefaultInstance();
}
RealmResults<History> histories = realm
.where(History.class)
.findAllSorted("currentTimeMillis", Sort.DESCENDING);
historyListAdapter = new HistoryListViewAdapter(historyList.getContext(), histories);
historyList.setAdapter(historyListAdapter);
}
/**
* 指定した行を削除する。
* @param id HistoryテーブルのID
*/
public void deleteHistory(final long id) {
if (realm == null) {
realm = Realm.getDefaultInstance();
}
realm.beginTransaction();
History history = realm.where(History.class).equalTo("id", id).findFirst();
if (history != null) {
history.deleteFromRealm();
}
realm.commitTransaction();
historyListAdapter.notifyDataSetChanged();
}
}<file_sep>/app/src/main/java/jp/co/wakawaka/tumvie/activity/ListTabsActivity.java
package jp.co.wakawaka.tumvie.activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import jp.co.wakawaka.tumvie.R;
import jp.co.wakawaka.tumvie.favoritelist.FavoriteListFragment;
import jp.co.wakawaka.tumvie.historylist.HistoryListFragment;
import jp.co.wakawaka.tumvie.searchlist.Item;
import jp.co.wakawaka.tumvie.favoritelist.Favorite;
import jp.co.wakawaka.tumvie.searchlist.SearchListFragment;
public class ListTabsActivity extends AppCompatActivity {
// TODO:どっかに移す
public static final String POST_TYPE_TEXT = "text"; //テキスト
public static final String POST_TYPE_QUOTE = "quote"; //引用
public static final String POST_TYPE_PHOTO = "photo"; //画像
public static final String POST_TYPE_LINK = "link"; //リンク
public static final String POST_TYPE_CHAT = "chat"; //チャット
public static final String POST_TYPE_AUDIO = "audio"; //音声
public static final String POST_TYPE_VIDEO = "video"; //動画
public static final String POST_TYPE_ANSWER = "answer"; //アンサー
private enum Tab {
FAVORITE(0),
SEARCH(1),
HISTORY(2);
private final int id;
Tab(final int id) {
this.id = id;
}
public int getValue() {
return this.id;
}
}
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter sectionsPagerAdapter;
private TabLayout tabLayout;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_tabs);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this).build();
Realm.setDefaultConfiguration(realmConfiguration);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.setting_button);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
viewPager = (ViewPager) findViewById(R.id.tabs_view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (Tab.FAVORITE.getValue() == position) {
((FavoriteListFragment) sectionsPagerAdapter.getItem(position)).reloadList();
}
if (Tab.HISTORY.getValue() == position) {
((HistoryListFragment) sectionsPagerAdapter.getItem(position)).reloadList();
fab.setVisibility(View.VISIBLE);
} else {
// 履歴画面以外では邪魔なのでFloatingActionButtonを消しておく。
fab.setVisibility(View.GONE);
}
if (Tab.SEARCH.getValue() != position) {
// 検索画面から他のタブに移動するときにキーボードが表示されたままになるので消す。
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).onFocusLoss();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setCurrentItem(Tab.SEARCH.getValue());
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(Tab.FAVORITE.getValue()).setCustomView(getTabImage(R.drawable.icon_favorite));
tabLayout.getTabAt(Tab.SEARCH.getValue()).setCustomView(getTabImage(R.drawable.icon_search));
tabLayout.getTabAt(Tab.HISTORY.getValue()).setCustomView(getTabImage(R.drawable.icon_history));
}
private ImageView getTabImage(int tabIconId) {
ImageView tab = (ImageView) LayoutInflater.from(this).inflate(R.layout.icon_tab_layout, null);
tab.setImageResource(tabIconId);
return tab;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_list_tabs, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* 設定ボタンクリック処理
* @param view View
*/
public void onClickSettingButton(View view) {
startActivity(new Intent(this, SettingActivity.class));
}
/**
* ブログ名クリック処理
* @param view View
*/
public void onClickSearchListBlogName(View view) {
String blogName = String.valueOf(((TextView) view).getText());
if (blogName == null || "".equals(blogName)) {
// blogNameが存在しない場合何もせずreturn
return;
}
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).searchFromKeyword(blogName);
}
/**
* 履歴画面の検索キーワードクリック処理
* @param view View
*/
public void onClickHistorySearchKeyword(View view) {
String keyword = String.valueOf(((TextView) view).getText());
viewPager.setCurrentItem(Tab.SEARCH.getValue());
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).searchFromKeyword(keyword);
}
/**
* 履歴画面の削除ボタンクリック処理
* @param view View
*/
public void onClickHistoryDeleteButton(View view) {
((HistoryListFragment) sectionsPagerAdapter.getItem(Tab.HISTORY.getValue())).deleteHistory((long) view.getTag());
}
/**
* キーワード削除ボタンタップ
* @param view View
*/
public void onClickSearchKeywordDeleteButton(View view) {
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).searchFromKeyword("");
}
/**
* お気に入り追加ボタン
* @param view
*/
public void onClickSearchFavoriteButton(View view) {
Item item = (Item) view.getTag();
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).addFavorite(item);
}
/**
* お気に入り追加済みボタン
* @param view
*/
public void onClickSearchWasFavoriteButton(View view) {
// Item item = (Item) view.getTag();
// ((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).deleteFavorite(item);
}
/**
* お気に入りのブログ名クリック処理
* @param view
*/
public void onClickFavoriteListBlogName(View view) {
String blogName = String.valueOf(((TextView) view).getText());
if (blogName == null || "".equals(blogName)) {
// blogNameが存在しない場合何もせずreturn
return;
}
viewPager.setCurrentItem(Tab.SEARCH.getValue());
((SearchListFragment) sectionsPagerAdapter.getItem(Tab.SEARCH.getValue())).searchFromKeyword(blogName);
}
/**
* お気に入り削除処理
* @param view View
*/
public void onClickFavoriteDeleteButton(View view) {
((FavoriteListFragment) sectionsPagerAdapter.getItem(Tab.FAVORITE.getValue())).deleteFavorite((long) view.getTag());
}
/**
* ビデオ再生
* @param view View
*/
public void onClickThumbnailFromFavorite(View view) {
Favorite favorite = (Favorite) view.getTag();
Intent intent = new Intent(this, VideoActivity.class);
intent.putExtra("videoUrl", favorite.getVideoUrl());
startActivity(intent);
}
/**
* ビデオ再生
* @param view View
*/
public void onClickThumbnail(View view) {
Item item = (Item) view.getTag();
Intent intent = new Intent(this, VideoActivity.class);
intent.putExtra("videoUrl", item.videoUrl);
startActivity(intent);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Fragment[] fragments = {new FavoriteListFragment(), new SearchListFragment(), new HistoryListFragment()};
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments[position];
}
@Override
public int getCount() {
return Tab.values().length;
}
@Override
public CharSequence getPageTitle(int position) {
return null;
}
}
}
| be3da5ceaaf4233ac2ba7548dc26408f5182775d | [
"Java",
"Gradle"
] | 5 | Java | wakawaka427/tumvie | 56b4ad2785831c5ae5ae1f2ab6a433a11c420459 | dea55f9ba3383de3473204c4b909526e8be5ed23 |
refs/heads/master | <repo_name>jonathan-91/shell-scripts<file_sep>/remote-message-log-analysis.sh
#!/bin/bash
# -- Analyze remote host's message log --
SYSIP="$1"
WC=$(echo $SYSIP | grep "." | wc -l)
if [ "$WC" == "0" ]; then
read -p " --- Please enter the IP of the system: " SYSIP
fi
ssh $SYSIP <<'EOF'
for i in `ls /var/log/messages*|grep -v '.gz'`;do
echo
echo " - LOG: $i"
UNIQENTRIES=`cat $i|sed 's/\[/\ /g'|awk '{print $5}'|sed 's|:||g'|sort| uniq`
count_uniq () {
for b in $UNIQENTRIES ;do
LCOUNT=`cat $i|grep $b|wc -l`
echo "$b - $LCOUNT"
done
}
echo "Program: - Line Count:"
count_uniq | sort -k3 -rn
done
EOF
<file_sep>/unsplash-wallpaper-change.sh
#!/bin/bash
# Download random unsplash wallpaper & set it on Gnome
# Add to cron to automatically change at 5 AM
#0 5 * * * sh /path/to/script/unsplash-wallpaper-change.sh > /dev/null 2>&1 &
# Keep last five wallpapers
mv -f $HOME/Pictures/unsplash04.jpg $HOME/Pictures/unsplash05.jpg
mv -f $HOME/Pictures/unsplash03.jpg $HOME/Pictures/unsplash04.jpg
mv -f $HOME/Pictures/unsplash02.jpg $HOME/Pictures/unsplash03.jpg
mv -f $HOME/Pictures/unsplash01.jpg $HOME/Pictures/unsplash02.jpg
# Get new wallpaper
wget -O $HOME/Pictures/unsplash01.jpg https://unsplash.it/2560/1440/?random
# Set wallpaper
gsettings set org.gnome.desktop.background picture-uri file://$HOME/Pictures/unsplash01.jpg
<file_sep>/README.md
# shell-scripts
## Maybe useful
[remote-message-log-analysis.sh](https://github.com/jonnyhoff/shell-scripts/blob/master/remote-message-log-analysis.sh)
Output example:
```
./remote-message-log-analysis.sh your-server-hostname
- LOG: /var/log/messages
Program: - Line Count:
audispd - 485594
xinetd - 86702
auditd - 17
rsyslogd - 1
- LOG: /var/log/messages-20190127
Program: - Line Count:
audispd - 486384
xinetd - 115527
auditd - 17
rsyslogd - 1
```
| 162a123aaf875a2bc986e3f30ebe685f37838cb3 | [
"Markdown",
"Shell"
] | 3 | Shell | jonathan-91/shell-scripts | e14a5ee80ea4697946d7471de282a926b233023f | 4f1c846ccfc2adb27510f3c0c274aa11b66c0d44 |
refs/heads/master | <repo_name>yusufshakeel/adventofcode2019<file_sep>/src/0202.js
/*
--- Part Two ---
"Good, the new computer seems to be working correctly! Keep it nearby during this mission - you'll probably use it again. Real Intcode computers support many more features than your new one, but we'll let you know what they are as you need them."
"However, your current priority should be to complete your gravity assist around the Moon. For this mission to succeed, we should settle on some terminology for the parts you've already built."
Intcode programs are given as a list of integers; these values are used as the initial state for the computer's memory. When you run an Intcode program, make sure to start by initializing memory to the program's values. A position in memory is called an address (for example, the first value in memory is at "address 0").
Opcodes (like 1, 2, or 99) mark the beginning of an instruction. The values used immediately after an opcode, if any, are called the instruction's parameters. For example, in the instruction 1,2,3,4, 1 is the opcode; 2, 3, and 4 are the parameters. The instruction 99 contains only an opcode and has no parameters.
The address of the current instruction is called the instruction pointer; it starts at 0. After an instruction finishes, the instruction pointer increases by the number of values in the instruction; until you add more instructions to the computer, this is always 4 (1 opcode + 3 parameters) for the add and multiply instructions. (The halt instruction would increase the instruction pointer by 1, but it halts the program instead.)
"With terminology out of the way, we're ready to proceed. To complete the gravity assist, you need to determine what pair of inputs produces the output 19690720."
The inputs should still be provided to the program by replacing the values at addresses 1 and 2, just like before. In this program, the value placed in address 1 is called the noun, and the value placed in address 2 is called the verb. Each of the two input values will be between 0 and 99, inclusive.
Once the program has halted, its output is available at address 0, also just like before. Each time you try a pair of inputs, make sure you first reset the computer's memory to the values in the program (your puzzle input) - in other words, don't reuse memory from a previous attempt.
Find the input noun and verb that cause the program to produce the output 19690720. What is 100 * noun + verb? (For example, if noun=12 and verb=2, the answer would be 1202.)
*/
const { machine } = require('./0201.js');
const machine2 = (data, target) => {
const len = data.length;
for (let noun = 0; noun <= 99; noun++) {
for (let verb = 0; verb <= 99; verb++) {
const dataSet = data.slice();
dataSet[1] = noun;
dataSet[2] = verb;
const result = machine(dataSet);
if (result[0] === target) {
return {noun, verb, found: true};
}
}
}
return {found: false};
};
module.exports = {
machine2
};<file_sep>/src/0301.js
/*
--- Day 3: Crossed Wires ---
The gravity assist was successful, and you're well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn't completely installed, so that's next on the priority list.
Opening the front panel reveals a jumble of wires. Specifically, two wires are connected to a central port and extend outward on a grid. You trace the path each wire takes as it leaves the central port, one wire per line of text (your puzzle input).
The wires twist and turn, but the two wires occasionally cross paths. To fix the circuit, you need to find the intersection point closest to the central port. Because the wires are on a grid, use the Manhattan distance for this measurement. While the wires do technically cross right at the central port where they both start, this point does not count, nor does a wire count as crossing with itself.
For example, if the first wire's path is R8,U5,L5,D3, then starting from the central port (o), it goes right 8, up 5, left 5, and finally down 3:
...........
...........
...........
....+----+.
....|....|.
....|....|.
....|....|.
.........|.
.o-------+.
...........
Then, if the second wire's path is U7,R6,D4,L4, it goes up 7, right 6, down 4, and left 4:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
These wires cross at two locations (marked X), but the lower-left one is closer to the central port: its distance is 3 + 3 = 6.
Here are a few more examples:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = distance 159
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = distance 135
What is the Manhattan distance from the central port to the closest intersection?
*/
const manhattanDistanceBetweenPoints = (p1, p2) => Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y);
const distanceBetweenPoints = (p1, p2) => Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
const isBetweenPoints = (q, p1, p2) => distanceBetweenPoints(p1, q) + distanceBetweenPoints(q, p2) === distanceBetweenPoints(p1, p2);
const getOccupiedCoords = directions => {
const coords = [];
let currCoord = {x:0, y:0};
let x = currCoord.x;
let y = currCoord.y;
let coord = {x, y};
coords.push(coord);
for (direction of directions) {
const moveTowards = direction.substring(0,1);
const moveSteps = parseInt(direction.substring(1));
switch (moveTowards) {
case 'R':
x += moveSteps;
break;
case 'L':
x -= moveSteps;
break;
case 'U':
y += moveSteps;
break;
case 'D':
y -= moveSteps;
break;
}
coord = {x, y};
coords.push(coord);
}
return coords;
};
const findIntersetingCoord = points => {
const A = points[0];
const B = points[1];
const C = points[2];
const D = points[3];
const a1 = B.y - A.y;
const b1 = A.x - B.x;
const c1 = a1 * A.x + b1 * A.y;
const a2 = D.y - C.y;
const b2 = C.x - D.x;
const c2 = a2 * C.x + b2 * C.y;
const determinant = a1 * b2 - a2 * b1;
if (determinant === 0)
return {found: false};
const x = (b2 * c1 - b1 * c2) / determinant;
const y = (a1 * c2 - a2 * c1) / determinant;
return {found: true, coord: {x, y}};
};
const findIntersectingCoords = (wire1Coords, wire2Coords) => {
let intersectingCoords = [];
for (let i = 0; i < wire1Coords.length - 1; i++) {
for (let j = 1; j < wire2Coords.length - 1; j++) {
let points = [];
const p1 = wire1Coords[i];
const p2 = wire1Coords[i+1];
const p3 = wire2Coords[j];
const p4 = wire2Coords[j+1];
points.push(p1);
points.push(p2);
points.push(p3);
points.push(p4);
const result = findIntersetingCoord(points);
if (result.found) {
const c = result.coord;
if (isBetweenPoints(c, p1, p2) && isBetweenPoints(c, p3, p4)) {
intersectingCoords.push(result.coord);
}
}
}
}
return intersectingCoords;
};
const findManhattanDistance = routes => {
const wire1Coords = getOccupiedCoords(routes[0]);
const wire2Coords = getOccupiedCoords(routes[1]);
const intersectingCoords = findIntersectingCoords(wire1Coords, wire2Coords);
let distance = intersectingCoords.map(point => {
return manhattanDistanceBetweenPoints({x:0, y:0}, point);
});
distance = distance.sort((a,b) => a-b);
return distance[0];
};
module.exports = {
manhattanDistanceBetweenPoints,
distanceBetweenPoints,
isBetweenPoints,
getOccupiedCoords,
findIntersetingCoord,
findIntersectingCoords,
findManhattanDistance
};<file_sep>/src/0302.js
/*
--- Part Two ---
It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay.
To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires' steps is lowest. If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection.
The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
In the above example, the intersection closest to the central port is reached after 8+5+5+2 = 20 steps by the first wire and 7+6+4+3 = 20 steps by the second wire for a total of 20+20 = 40 steps.
However, the top-right intersection is better: the first wire takes only 8+5+2 = 15 and the second wire takes only 7+6+2 = 15, a total of 15+15 = 30 steps.
Here are the best steps for the extra examples from above:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = 610 steps
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = 410 steps
What is the fewest combined steps the wires must take to reach an intersection?
*/
const {
distanceBetweenPoints,
isBetweenPoints,
getOccupiedCoords,
findIntersectingCoords
} = require('./0301.js');
const totalStepsToIntersectingCoords = (wire1Coords, wire2Coords, intersectingPoints) => {
let totalSteps = [];
for(let intersectPoint of intersectingPoints) {
let steps = 0;
for(let i = 0; i < wire1Coords.length - 1; i++) {
if (isBetweenPoints(intersectPoint, wire1Coords[i], wire1Coords[i+1])) {
steps += distanceBetweenPoints(wire1Coords[i], intersectPoint);
break;
} else {
steps += distanceBetweenPoints(wire1Coords[i], wire1Coords[i+1]);
}
}
for(let i = 0; i < wire2Coords.length - 1; i++) {
if (isBetweenPoints(intersectPoint, wire2Coords[i], wire2Coords[i+1])) {
steps += distanceBetweenPoints(wire2Coords[i], intersectPoint);
break;
} else {
steps += distanceBetweenPoints(wire2Coords[i], wire2Coords[i+1]);
}
}
totalSteps.push(steps);
}
return totalSteps;
};
const leastStepsToIntersectingCoord = routes => {
const wire1Coords = getOccupiedCoords(routes[0]);
const wire2Coords = getOccupiedCoords(routes[1]);
const intersectingCoords = findIntersectingCoords(wire1Coords, wire2Coords);
let steps = totalStepsToIntersectingCoords(wire1Coords, wire2Coords, intersectingCoords);
steps = steps.sort((a,b) => a-b);
return steps[0];
};
module.exports = {
totalStepsToIntersectingCoords,
leastStepsToIntersectingCoord
};<file_sep>/src/0102.js
/*
--- Part Two ---
During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added.
Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.
So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:
A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.
At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)
*/
const {
fuelMass
} = require('./0101.js');
const totalFuelForMoulesPlusFuel = modules => {
return modules.reduce((totalFuelRequired, currModule) => {
const fuelForModule = fuelMass(currModule);
let fuelForFuel = 0;
let currFuelMass = fuelForModule;
while (currFuelMass > 0) {
const fuel = fuelMass(currFuelMass);
if (fuel > 0) {
fuelForFuel += fuel;
}
currFuelMass = fuel;
}
return totalFuelRequired + fuelForModule + fuelForFuel;
}, 0);
};
module.exports = {
totalFuelForMoulesPlusFuel
};<file_sep>/src/0101.js
/*
--- Day 1: The Tyranny of the Rocket Equation ---
Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
The Elves quickly load you into a spacecraft and prepare to launch.
At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.
For example:
For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.
For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.
For a mass of 1969, the fuel required is 654.
For a mass of 100756, the fuel required is 33583.
The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.
What is the sum of the fuel requirements for all of the modules on your spacecraft?
*/
const fuelMass = moduleMass => Math.floor(moduleMass / 3) - 2;
const totalFuel = modules => modules.reduce((total, currMass) => {
return total + fuelMass(currMass);
}, 0);
module.exports = {
fuelMass,
totalFuel
};<file_sep>/test/0101.test.js
const {totalFuel} = require('../src/0101.js');
test('Total fuel mass for the modules.', () => {
expect(totalFuel([12])).toBe(2);
expect(totalFuel([14])).toBe(2);
expect(totalFuel([1969])).toBe(654);
expect(totalFuel([100756])).toBe(33583);
});
test('0101 Answer', () => {
const modules = require('../data/data0101.js');
const answer = totalFuel(modules);
console.log('0101 Answer', answer);
});<file_sep>/test/0201.test.js
const { op, machine } = require('../src/0201.js');
const data = require('../data/data0201.js');
test('Testing op function', () => {
expect(op(1, 1, 2)).toBe(3);
expect(op(2, 2, 3)).toBe(6);
})
test('Testing machine function', () => {
expect(machine([1,0,0,0])[0]).toBe(2);
expect(machine([1,0,0,0,99])[0]).toBe(2);
expect(machine([2,3,0,3,99])[3]).toBe(6);
expect(machine([2,4,4,5,99,0])[5]).toBe(9801);
expect(machine([1,1,1,4,99,5,6,0,99])[0]).toBe(30);
expect(machine([1,1,1,4,99,5,6,0,99])[4]).toBe(2);
})
test('0201 Answer', () => {
data[1] = 12;
data[2] = 2;
console.log('0201 Answer', machine(data)[0]);
})<file_sep>/src/0402.js
/*
--- Part Two ---
An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits.
Given this additional criterion, but still ignoring the range rule, the following are now true:
112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long.
123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444).
111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22).
How many different passwords within the range given in your puzzle input meet all of the criteria?
Your puzzle input is still 284639-748759.
*/
const {
getPasswords
} = require('./0401.js');
const numToStr = number => number + '';
const getGroups = number => {
const num = numToStr(number);
const groups = [];
let beg = 0, end = 0;
while (end < num.length) {
let group = num.substring(beg, end);
if (num[beg] === num[end]) {
end++;
continue;
}
groups.push(group);
beg = end;
end++;
}
groups.push(num.substring(beg, end));
return groups;
};
const getPairs = number => {
const num = numToStr(number);
let pairs = [];
for (let i = 0; i < num.length - 1; i++) {
if (num[i] === num[i + 1]) {
pairs.push(num.substring(i, i + 2));
}
}
return pairs;
};
const isPairInBiggerGroup = (pair, group) => {
return group.indexOf(pair) > -1;
};
const isNotContainingPairThatIsPartOfABiggerGroup = number => {
const groups = getGroups(number);
const pairs = getPairs(number);
let biggerGroups = groups.reduce((bigGroup, group) => {
if (group.length > 2) {
bigGroup.push(group);
}
return bigGroup;
}, []);
const uniquePairs = [...new Set(pairs)];
for (let pair of uniquePairs) {
let foundCount = 0;
for (let bigGroup of biggerGroups) {
if (isPairInBiggerGroup(pair, bigGroup)) {
foundCount++;
}
}
if (foundCount === 0) {
return true;
}
}
return false;
};
const getPasswordCount2 = range => {
const passwords = getPasswords(range);
const passwords2 = [];
for (let password of passwords) {
if (isNotContainingPairThatIsPartOfABiggerGroup(password)) {
passwords2.push(password);
}
}
return passwords2.length;
};
module.exports = {
numToStr,
getGroups,
getPairs,
isPairInBiggerGroup,
isNotContainingPairThatIsPartOfABiggerGroup,
getPasswordCount2
};<file_sep>/test/0102.test.js
const {totalFuelForMoulesPlusFuel} = require('../src/0102.js');
test('Total fuel mass for the modules plus fuels.', () => {
expect(totalFuelForMoulesPlusFuel([12])).toBe(2);
expect(totalFuelForMoulesPlusFuel([14])).toBe(2);
expect(totalFuelForMoulesPlusFuel([1969])).toBe(966);
expect(totalFuelForMoulesPlusFuel([100756])).toBe(50346);
});
test('0102 Answer', () => {
const modules = require('../data/data0101.js');
const answer = totalFuelForMoulesPlusFuel(modules);
console.log('0102 Answer', answer);
});<file_sep>/README.md
# adventofcode2019
AdventOfCode 2019 - https://adventofcode.com
| 0909bc1b283f29088c4a654824e0175e0b531911 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | yusufshakeel/adventofcode2019 | b7f873392acc1cfd290185de1151c9b625c834e5 | 55c501f5aa866c4f7672cf7b13a2de8eb5f3d422 |
refs/heads/master | <file_sep>#pragma once
#include<iostream>
#include<vector>
#include<string>
class Animal {
public:
Animal(std::string inName, int inEnergy = 100) //名稱跟初始體力
: Name(inName), hungry(0), energy(inEnergy) {};
//傳入消耗量,回傳飢餓度
int feed(int amount) {
hungry -= amount;
hungry = std::max(0, hungry);
return 1;
}
virtual int exercise(int times) = 0; //傳入次數,回傳所賺的錢
virtual bool rest(int& food, int& water) = 0; //需要傳入一些資訊方便你調整動物園食物量 水量...
int drink(int amount) { return true; };
friend std::ostream& operator<<(std::ostream& os, const Animal& a) {
os << &a;
}
friend std::ostream& operator<<(std::ostream& os, const Animal* a) {
return os << a->Name << " (hungry: " << a->hungry << ", energy : " << a->energy << ")" << std::endl;
}
void print() {
std::cout << this;
}
protected:
std::string Name;
int hungry; //hungry index (initial = 0, upper bound is varying)
int energy; //energy index (initial = 100)
void log_eat(int f) {
std::cout << "[LOG] " << Name << " eat " << f << " food" << std::endl;
}
void log_drink(int f) {
std::cout << "[LOG] " << Name << " drink " << f << " water" << std::endl;
}
void log_rest(int food, int water, int enrgy) {
std::cout << "[LOG] " << Name << " take a rest, eat " << food << " food & drink " << water << " water, gain " << enrgy << std::endl;
}
};
class Zoo {
public:
~Zoo() {
for (const auto& u : house) {
delete u;
}
}
Animal*& operator[](int i) {
return house[i];
; }
void operator+=(Animal* a) {
AddAnimal(a);
}
friend std::ostream& operator<<(std::ostream& os, const Zoo& a) {
return os << &a;
}
friend std::ostream& operator<<(std::ostream& os, const Zoo* a) {
os << "[INFO] Food: " << a->foodCount << ", Water : " << a->waterCount << ", Foud$ : " << a->deposit << "$";
return os;
}
Zoo(size_t size = 5) : foodCount(500), waterCount(100), deposit(100), sizeLimit(size) {
house.reserve(size);
}
int Run(int quantity=1) {
bool flg = false;
if (waterCount < 100000) waterCount += 100000;
FeedWater();
for (const auto& a : house) {
int r = a->exercise(10);
deposit += r;
flg = flg || r;
}
if (!flg) {
AskRest();
if (!FeedFood(10)) {
getMoreFood(30);
}
}
return 0;
}
bool FeedFood(int quantity=1) {
std::cout << "[LOG] Feeding food...\n";
int fed = 0;
for (const auto& u : house) {
if (foodCount < quantity) {
std::cout << "[WARNING] Insufficient food !!!\n";
std::cout << "[LOG] total consume " << fed << " food.\n";
return false;
}
if (u->feed(quantity)) { fed += quantity; foodCount -= quantity; }
}
std::cout << "[LOG] total consume " << fed << " food.\n";
return true;
}
bool FeedWater(int quantity = 1) {
std::cout << "[LOG] Feeding water...\n";
int fed = 0;
for (const auto& u : house) {
if (waterCount < 10) {
std::cout << "[WARNING] Insufficient water !!!\n";
std::cout << "[LOG] total consume " << fed << " water.\n";
return false;
}
if (u->feed(10)) {
fed += 10;
waterCount -= 10;
}
}
std::cout << "[LOG] total consume " << fed << " water.\n";
return true;
}
bool AskRest() {
// return: all aminals fails to rest
std::cout << "[LOG] ask all animals to rest.\n";
bool ret = false;
for (const auto& u : house) {
ret |= u->rest(foodCount, waterCount);
}
return ret;
}
void Listing() { //印出所有動物資訊
for (std::vector<Animal*>::iterator iter = house.begin(); iter != house.end(); ++iter) {
(*iter)->print();
}
}
bool AddAnimal(Animal* a) {
if (sizeLimit <= getCount()) {
std::cout << "[WARNING] Too many animals !!!\n";
}
house.emplace_back(a);
return true;
}
int getCount() { return house.size(); }
bool isBankrupt() {
if (foodCount == 0 && deposit == 0)
return true;
//you may update this function
return false;
}
int getMoreFood(int amount) { // try to buy food
int n = std::min(amount, deposit);
if (n != amount) {
std::cout << "[WARNING] Insufficient funds !!!\n";
}
std::cout << "[LOG] Transfer $"<< n <<" to "<<(n*2)<<" food";
deposit -= n;
foodCount += n * 2;
return true;
}
//operator+=
//operator[]
//operator<< //[INFO] Food: ###, Water: ###, Foud$: ###$
private:
std::vector<Animal*> house;
int foodCount; //動物園食物 沒食物可以用存款轉換
int waterCount; //動物園水 每RUN會增加100;
int deposit; //動物園存款 動物運動可增加
const int sizeLimit; //動物園設計上限(初次創建時設定)可超過但追加動物會警告
};
class horse : public Animal {
public:
horse(std::string inName, int inEnergy = 100) : Animal(inName, inEnergy) {}
bool rest(int& food, int& water) {
constexpr int WATER_COST = 10;
if (water < WATER_COST) return false;
water -= WATER_COST;
drink(WATER_COST);
return true;
}
int feed(int n) {
__super::feed(n);
energy += n * 2;
return true;
}
int drink(int n) {
__super::drink(n);
energy += n;
return true;
}
int exercise(int times) {
int ret = 0;
while (times--) {
if (isHungry() && energy > 50) {
energy -= 50;
ret += 25;
}
else if (!isHungry() && energy >= 35) {
hungry += 35;
energy -= 35;
hungry = std::min(hungry, 100);
ret += 50;
}
}
return ret;
}
private:
bool isHungry() {
return hungry >= 100;
}
};
class pig : public Animal {
public:
pig(std::string inName, int inEnergy = 100) : Animal(inName, inEnergy) {}
bool rest(int& food, int& water) {
constexpr int FOOD_COST = 10;
if (food < FOOD_COST) return false;
food -= FOOD_COST;
return true;
}
int feed(int n) {
__super::feed(n);
if (n > hungry) energy += (n - hungry) * 2;
return true;
}
int drink(int n) {
__super::drink(n);
energy += n;
}
int exercise(int times) {
int ret = 0;
while (times--) {
if (isHungry()) {
ret += 0;
break;
}
else if (energy >= 35) {
hungry += 20;
energy -= 35;
hungry = std::min(hungry, 50);
ret += 100;
}
else break;
}
return ret;
}
private:
bool isHungry() {
return hungry >= 50;
}
};
class human : public Animal {
public:
human(std::string inName, int inEnergy = 100) : Animal(inName, inEnergy) {}
bool rest(int& food, int& water) {
if (energy < 10) return false;
energy -= 10;
if (water < 20 || food < 10) return false;
water -= 20;
food -= 10;
energy += 20;
return true;
}
int feed(int n) {
__super::feed(n);
energy += n;
return true;
}
int drink(int n) {
__super::drink(n);
energy += n * 2;
}
int exercise(int times) {
int ret = 0;
while (times--) {
if (energy < 10) break;
energy -= 10;
if (isHungry()) {
ret += 0;
break;
}
else if (energy >= 35) {
hungry += 20;
energy -= 35;
hungry = std::min(hungry, 150);
ret += 100;
}
else break;
}
return ret;
}
private:
bool isHungry() {
return hungry >= 150;
}
};<file_sep>#include <iostream>
#include "zoo.h"
int main()
{
std::cout << "Hello World!\n";
Zoo ZooSim1(5);
// ZooSim1.AddAnimal(new horse("Pony", 100));
ZooSim1 += new horse("Pony", 100);
ZooSim1.AddAnimal(new horse("Pony", 100));
ZooSim1.AddAnimal(new pig("Piggy", 100));
ZooSim1.AddAnimal(new human("Pony", 100));
// ZooSim1 += new pig("Piggy", 100);
ZooSim1.Listing();
std::cout << "==================================\n";
//...example...
std::cout << ZooSim1 << std::endl;
ZooSim1.Run(3);
std::cout << "==================================\n";
std::cout << "---Test getMorefood()--- \n";
std::cout << "Before: "<< ZooSim1 << std::endl;
ZooSim1.getMoreFood(100);
std::cout << "After: " << ZooSim1 << std::endl;
ZooSim1.getMoreFood(500);
std::cout << "==================================\n";
std::cout << "---Test food/water Insufficient--- \n";
ZooSim1.Listing();
while (ZooSim1.FeedFood(10)) {}
while (ZooSim1.FeedWater(20)) {}
ZooSim1.Listing();
while (!ZooSim1.isBankrupt()) {
std::cout << ZooSim1 << std::endl;
ZooSim1.Run();
}
} | dbe56a74097ef46f926f92734a24b24d125903cd | [
"C++"
] | 2 | C++ | MuMuShy/zoo | b829a441c7f864b6bd4fca1539255b1f60714c51 | e5ea2a9d57c64cf43f1a9eff5ec98a1487c05e3d |
refs/heads/master | <repo_name>marcusnjones/wpphpinfo<file_sep>/README.md
# wpphpinfo
A WordPress theme used for quickly displaying your PHP configuration.
<file_sep>/index.php
<?php
/**
* This is the only template file included in this theme.
*
* It is used for quickly displaying your PHP configuration.
*
* @link http://php.net/manual/en/function.phpinfo.php
*
* @package wpphpinfo
*/
phpinfo();
| dba0d412d7a2f1b19f03accc08e8bca8beea38ea | [
"Markdown",
"PHP"
] | 2 | Markdown | marcusnjones/wpphpinfo | 545f1559534ccc618ac295207f0ca7a659ae12b6 | e74306e0fac3a5a5ba67d4002aa63f618e3924c4 |
refs/heads/main | <file_sep>var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var a = [];
var i,positive = 0,negative = 0,even = 0,odd = 0;
for(i = 0;i < 5;i++){
a.push(parseInt(lines.shift()));
}
for(i = 0;i < 5;i++){
if (a[i] % 2 === 0) {
even++;
}
else if(a[i] !== 0){
odd++;
}
if(a[i] > 0){
positive++;
}
else if(a[i] < 0){
negative++;
}
}
console.log(even + " valor(es) par(es)");
console.log(odd + " valor(es) impar(es)");
console.log(positive + " valor(es) positivo(s)");
console.log(negative + " valor(es) negativo(s)");
<file_sep>package main
import (
"fmt"
)
func main() {
var a [5]int
var i, positive, even, odd, negative int
even = 0
odd = 0
positive = 0
negative = 0
for i = 0; i < 5; i++ {
fmt.Scan(&a[i])
}
for i = 0; i < 5; i++ {
if a[i] % 2 == 0 {
even++
} else {
odd++
}
if a[i] > 0 {
positive++
} else if a[i] < 0 {
negative++
}
}
fmt.Printf("%d valor(es) par(es)\n", even)
fmt.Printf("%d valor(es) impar(es)\n", odd)
fmt.Printf("%d valor(es) positivo(s)\n", positive)
fmt.Printf("%d valor(es) negativo(s)\n", negative)
}
<file_sep>#include<stdio.h>
int main()
{
int i,j,negative = 0,odd,positive = 0,even = 0;
int a[6];
for(i = 1;i <= 5;i++)
{
scanf("%d",&a[i]);
}
for(j = 1,i = 1;j <= 5,i <= 5;j++,i++)
{
if(abs(a[i] % 2 == 0))
{
even = even + 1;
}
if((a[i]) > 0)
{
positive = positive + 1;
}
if((a[i]) < 0)
{
negative = negative + 1;
}
}
odd = 5 - even;
printf("%d valor(es) par(es)\n", even);
printf("%d valor(es) impar(es)\n", odd);
printf("%d valor(es) positivo(s)\n", positive);
printf("%d valor(es) negativo(s)\n", negative);
return 0;
}
<file_sep>array = {}
even = 0
odd = 0
positive = 0
negative = 0
for i = 1,5 do
array[i] = io.read("*n")
end
for i = 1,5 do
if array[i] % 2 == 0 then
even = even + 1
elseif array[i] % 2 ~= 0 then
odd = odd + 1
end
if array[i] > 0 then
positive = positive + 1
elseif array[i] < 0 then
negative = negative + 1
end
end
print(even.." valor(es) par(es)")
print(odd.." valor(es) impar(es)")
print(positive.." valor(es) positivo(s)")
print(negative.." valor(es) negativo(s)")
<file_sep>negative = 0
positive = 0
even = 0
for i in range(0,5):
a = int(input())
if a % 2 == 0 :
even = even + 1
if a > 0 :
positive = positive + 1
if a < 0 :
negative = negative + 1
odd = 5 - even;
print("{} valor(es) par(es)".format(even))
print("{} valor(es) impar(es)".format(odd))
print("{} valor(es) positivo(s)".format(positive))
print("{} valor(es) negativo(s)".format(negative))
<file_sep>import java.util.Scanner
fun main(args: Array<String>){
val input = Scanner(System.`in`);
var a:Int;
var even:Int;
even = 0
var positive:Int;
positive = 0
var negative:Int;
negative = 0
for(i in 1..5)
{
a = input.nextInt();
if(a % 2 == 0)
{
even = even + 1;
}
if(a > 0)
{
positive = positive + 1;
}
if(a < 0)
{
negative = negative + 1;
}
}
var odd:Int = 5 - even;
System.out.printf("%d valor(es) par(es)\n", even);
System.out.printf("%d valor(es) impar(es)\n", odd);
System.out.printf("%d valor(es) positivo(s)\n", positive);
System.out.printf("%d valor(es) negativo(s)\n", negative);
}
<file_sep>using System.IO;
using System;
class Program
{
static void Main()
{
int i,negative = 0,odd,positive = 0,even = 0;
int a;
for(i = 1;i <= 5;i++)
{
a = Convert.ToInt32(Console.ReadLine());
if(a % 2 == 0)
{
even = even + 1;
}
if(a > 0)
{
positive = positive + 1;
}
if(a < 0)
{
negative = negative + 1;
}
}
odd = 5 - even;
Console.WriteLine(even + " valor(es) par(es)");
Console.WriteLine(odd + " valor(es) impar(es)");
Console.WriteLine(positive + " valor(es) positivo(s)");
Console.WriteLine(negative + " valor(es) negativo(s)");
Console.ReadLine();
}
}
<file_sep>a = Array.new()
for j in 1..5
a[j] = gets().chomp().to_i
end
even = 0
odd = 0
positive = 0
negative = 0
for j in 1..5
if a[j] % 2 == 0
even = even + 1
else
odd = odd + 1
end
if a[j] > 0
positive = positive + 1
elsif a[j] < 0
negative = negative + 1
end
end
printf("%d valor(es) par(es)\n", even);
printf("%d valor(es) impar(es)\n", odd);
printf("%d valor(es) positivo(s)\n", positive);
printf("%d valor(es) negativo(s)\n", negative);
| 449630ce1433d3571a5e917f20207a952510ed64 | [
"Ruby",
"Lua",
"JavaScript",
"C#",
"Python",
"C",
"Go",
"Kotlin"
] | 8 | JavaScript | bilash-biswas/1066 | 793b163f9eade8a79f39b6edc4815d00c60be9c4 | 92ea3e8fcd22be46228d6f7443343cf9255259e0 |
refs/heads/master | <file_sep>from flask import Flask , render_template , jsonify
import csv
import random
import pprint
import config
import requests
app = Flask(__name__)
@app.route("/")
def Home():
with open('netflix_titles.csv',encoding="utf8") as f:
read = csv.reader(f)
row = random.choice(list(read))
movie = {
'id': row[0],
'category': row[1],
'title': row[2],
'director': row[3],
'cast': row[4],
'country': row[5],
'date_added': row[6],
'release_year': row[7],
'maturity': row[8],
'duration': row[9],
'genre': row[10],
'description': row[11],
# default poster just so we see something
'image': 'https://live.staticflickr.com/4422/36193190861_93b15edb32_z.jpg',
'imdb': 'Not Available'
}
url = f"http://www.omdbapi.com/?t={movie['title']}/&apikey={config.API_KEY}"
response = requests.request("GET", url)
mdata = response.json()
if 'Poster' in mdata:
movie['image'] = mdata['Poster']
# print(movie)
return render_template('home.html' , data = movie)
app.run(debug=True)
<file_sep># Flask
(First Flask App, Many more to be Done)
Just a Basic Flask Example to get random Choice of Movies
I have used Kaggle Dataset to get all list of movies available in Netflix where it has all attributes except images
So to get images ,I have used OMDB api to get image
Future Work to do :
Add a Wishlist Button
Make a button to directly watch it in netflix
More UI
| d51d60f489d3cef866ff362411b624f46f231b35 | [
"Markdown",
"Python"
] | 2 | Python | Imkdshah/Flask | 5f9cc99422b83e3a9fc508cd12178ad3c8c72c79 | d1b16c502c21605aa050704a12cfe35bf2c08414 |
refs/heads/master | <file_sep>/**
* Export all publicly accessible modules
*/
<file_sep># dynamicbuffer
A dynamic drop-in replacement for Node.js Buffer API
| 5e5a8d12f7343b2b7ba074aba15534ed56b4caae | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | sampathsris/dynamicbuffer | 594c175d088917cab0943bb871ee20cb06e9d851 | abef6525b76beee9d876ed4e2388e79a15253186 |
refs/heads/master | <file_sep>// Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "exprs/udf-builtins.h"
#include "runtime/timestamp-value.h"
#include "util/bit-util.h"
#include <ctype.h>
#include <math.h>
#include <gutil/strings/substitute.h>
using namespace std;
using namespace boost::gregorian;
using namespace boost::posix_time;
using namespace strings;
namespace impala {
DoubleVal UdfBuiltins::Abs(FunctionContext* context, const DoubleVal& v) {
if (v.is_null) return v;
return DoubleVal(fabs(v.val));
}
DoubleVal UdfBuiltins::Pi(FunctionContext* context) {
return DoubleVal(M_PI);
}
StringVal UdfBuiltins::Lower(FunctionContext* context, const StringVal& v) {
if (v.is_null) return v;
StringVal result(context, v.len);
for (int i = 0; i < v.len; ++i) {
result.ptr[i] = tolower(v.ptr[i]);
}
return result;
}
// The units which can be used when Truncating a Timestamp
struct TruncUnit {
enum Type {
YEAR,
QUARTER,
MONTH,
WW,
W,
DAY,
DAY_OF_WEEK,
HOUR,
MINUTE,
UNIT_INVALID
};
};
// Maps the user facing name of a unit to a TruncUnit
// Returns the TruncUnit via parameter trunc_unit
// Returns true if unit is a known unit, else false
TruncUnit::Type StrToTruncUnit(const StringVal& unit) {
if ((unit == "SYYYY") || (unit == "YYYY") || (unit == "YEAR") || (unit == "SYEAR") ||
(unit == "YYY") || (unit == "YY") || (unit == "Y")) {
return TruncUnit::YEAR;
} else if (unit == "Q") {
return TruncUnit::QUARTER;
} else if ((unit == "MONTH") || (unit == "MON") || (unit == "MM") || (unit == "RM")) {
return TruncUnit::MONTH;
} else if (unit == "WW") {
return TruncUnit::WW;
} else if (unit == "W") {
return TruncUnit::W;
} else if ((unit == "DDD") || (unit == "DD") || (unit == "J")) {
return TruncUnit::DAY;
} else if ((unit == "DAY") || (unit == "DY") || (unit == "D")) {
return TruncUnit::DAY_OF_WEEK;
} else if ((unit == "HH") || (unit == "HH12") || (unit == "HH24")) {
return TruncUnit::HOUR;
} else if (unit == "MI") {
return TruncUnit::MINUTE;
} else {
return TruncUnit::UNIT_INVALID;
}
}
// Returns the most recent date, no later than orig_date, which is on week_day
// week_day: 0==Sunday, 1==Monday, ...
date GoBackToWeekday(const date& orig_date, int week_day) {
int current_week_day = orig_date.day_of_week();
int diff = current_week_day - week_day;
if (diff == 0) return orig_date;
if (diff > 0) {
// ex. Weds(3) shifts to Tues(2), so we go back 1 day
return orig_date - date_duration(diff);
}
// ex. Tues(2) shifts to Weds(3), so we go back 6 days
DCHECK_LT(diff, 0);
return orig_date - date_duration(7 + diff);
}
// Truncate to first day of year
TimestampValue TruncYear(const date& orig_date) {
date new_date(orig_date.year(), 1, 1);
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Truncate to first day of quarter
TimestampValue TruncQuarter(const date& orig_date) {
int first_month_of_quarter = BitUtil::RoundDown(orig_date.month() - 1, 3) + 1;
date new_date(orig_date.year(), first_month_of_quarter, 1);
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Truncate to first day of month
TimestampValue TruncMonth(const date& orig_date) {
date new_date(orig_date.year(), orig_date.month(), 1);
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Same day of the week as the first day of the year
TimestampValue TruncWW(const date& orig_date) {
const date& first_day_of_year = TruncYear(orig_date).get_date();
int target_week_day = first_day_of_year.day_of_week();
date new_date = GoBackToWeekday(orig_date, target_week_day);
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Same day of the week as the first day of the month
TimestampValue TruncW(const date& orig_date) {
const date& first_day_of_mon = TruncMonth(orig_date).get_date();
const date& new_date = GoBackToWeekday(orig_date, first_day_of_mon.day_of_week());
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Truncate to midnight on the given date
TimestampValue TruncDay(const date& orig_date) {
time_duration new_time(0, 0, 0, 0);
return TimestampValue(orig_date, new_time);
}
// Date of the previous Monday
TimestampValue TruncDayOfWeek(const date& orig_date) {
const date& new_date = GoBackToWeekday(orig_date, 1);
time_duration new_time(0, 0, 0, 0);
return TimestampValue(new_date, new_time);
}
// Truncate minutes, seconds, and parts of seconds
TimestampValue TruncHour(const date& orig_date, const time_duration& orig_time) {
time_duration new_time(orig_time.hours(), 0, 0, 0);
return TimestampValue(orig_date, new_time);
}
// Truncate seconds and parts of seconds
TimestampValue TruncMinute(const date& orig_date, const time_duration& orig_time) {
time_duration new_time(orig_time.hours(), orig_time.minutes(), 0, 0);
return TimestampValue(orig_date, new_time);
}
TimestampVal UdfBuiltins::Trunc(
FunctionContext* context, const TimestampVal& tv, const StringVal &unit_str) {
const TimestampValue& ts = TimestampValue::FromTimestampVal(tv);
const date& orig_date = ts.get_date();
const time_duration& orig_time = ts.get_time();
// resolve trunc_unit using the prepared state if possible, o.w. parse now
// TruncPrepare() can only parse trunc_unit if user passes it as a string literal
TruncUnit::Type trunc_unit;
void* state = context->GetFunctionState(FunctionContext::THREAD_LOCAL);
if (state != NULL) {
trunc_unit = *reinterpret_cast<TruncUnit::Type*>(state);
} else {
trunc_unit = StrToTruncUnit(unit_str);
if (trunc_unit == TruncUnit::UNIT_INVALID) {
string string_unit(reinterpret_cast<char*>(unit_str.ptr), unit_str.len);
context->SetError(Substitute("Invalid Truncate Unit: $0", string_unit).c_str());
return TimestampVal::null();
}
}
TimestampValue ret;
TimestampVal ret_val;
switch (trunc_unit) {
case TruncUnit::YEAR:
ret = TruncYear(orig_date);
break;
case TruncUnit::QUARTER:
ret = TruncQuarter(orig_date);
break;
case TruncUnit::MONTH:
ret = TruncMonth(orig_date);
break;
case TruncUnit::WW:
ret = TruncWW(orig_date);
break;
case TruncUnit::W:
ret = TruncW(orig_date);
break;
case TruncUnit::DAY:
ret = TruncDay(orig_date);
break;
case TruncUnit::DAY_OF_WEEK:
ret = TruncDayOfWeek(orig_date);
break;
case TruncUnit::HOUR:
ret = TruncHour(orig_date, orig_time);
break;
case TruncUnit::MINUTE:
ret = TruncMinute(orig_date, orig_time);
break;
default:
// internal error: implies StrToTruncUnit out of sync with this switch
context->SetError(Substitute("truncate unit $0 not supported", trunc_unit).c_str());
return TimestampVal::null();
}
ret.ToTimestampVal(&ret_val);
return ret_val;
}
void UdfBuiltins::TruncPrepare(FunctionContext* ctx,
FunctionContext::FunctionStateScope scope) {
// Parse the unit up front if we can, otherwise do it on the fly in Trunc()
if (ctx->IsArgConstant(1)) {
StringVal* unit_str = reinterpret_cast<StringVal*>(ctx->GetConstantArg(1));
TruncUnit::Type trunc_unit = StrToTruncUnit(*unit_str);
if (trunc_unit == TruncUnit::UNIT_INVALID) {
string string_unit(reinterpret_cast<char*>(unit_str->ptr), unit_str->len);
ctx->SetError(Substitute("Invalid Truncate Unit: $0", string_unit).c_str());
} else {
TruncUnit::Type* state = reinterpret_cast<TruncUnit::Type*>(
ctx->Allocate(sizeof(TruncUnit::Type)));
*state = trunc_unit;
ctx->SetFunctionState(scope, state);
}
}
}
void UdfBuiltins::TruncClose(FunctionContext* ctx,
FunctionContext::FunctionStateScope scope) {
void* state = ctx->GetFunctionState(scope);
if (state != NULL) {
ctx->Free(reinterpret_cast<uint8_t*>(state));
ctx->SetFunctionState(scope, NULL);
}
}
} // namespace impala
| d4712c365428619e223086f2ac962d5a50f05e09 | [
"C++"
] | 1 | C++ | emaxerrno/Impala | 0005da9cb71f5a4a4ed6bb1dfcd74f8526cd8316 | 59e7425dc150be93bae903574c10bba24d274d0c |
refs/heads/master | <file_sep>def start():
print("Welcome to basic calculator")
while True:
try:
num1 = int(input("Enter a number: "))
op = input("Enter an operation: ")
num2 = int(input("Enter another number: "))
for operation in op:
if operation == "+":
print(f"The answer is : {num1 + num2}")
break
if operation == "-":
print(f"The answer is : {num1 - num2}")
break
if operation == "*":
print(f"The answer is : {num1 * num2}")
break
if operation == "/":
print(f"The answer is : {num1 / num2}")
break
else:
print("Invalid operation")
except:
print("Error")
start()
<file_sep># Calculator
help me make this better
| 502b5d31630ddb5f16351986fb89825f5b60810b | [
"Markdown",
"Python"
] | 2 | Python | jav1anpry5ce/Calculator | d3f9e5d2a5333d8f0e3fcc115bc974beee4181b4 | d3dee89c0cf7bfbde89a7f320714967eadc9bf3a |
refs/heads/master | <repo_name>aviolette/cftfchrome<file_sep>/build.sh
rm cftfchrome.zip
zip cftfchrome.zip background.js icon.png jquery-2.1.1.min.js manifest.json options.html options.js popup.html popup.js logo128x128.png logo48x48.png
zip -r cftfchrome.zip bootstrap
<file_sep>/options.js
function loadSettings() {
chrome.storage.sync.get({ searchRadius : 0.25, notifications: true, filter: "both", defaultCity: "Chicago"}, function(items) {
$("#radius").val(items.searchRadius.toString());
$("#foodTruckNotifications").prop("checked", items.notifications);
$("#" + items.filter).prop("checked", true);
$("#defaultCity").val(items.defaultCity);
});
}
$(document).ready(loadSettings);
$("#save").click(function() {
var radius = parseFloat($("#radius").val()),
filter = $('input[name=filterRadio]:checked').val(),
defaultCity = $('#defaultCity').val(),
notifications = $("#foodTruckNotifications").is(":checked");
chrome.storage.sync.set({ searchRadius : radius, defaultCity: defaultCity, notifications: notifications, filter: filter}, function(f) {
var port = chrome.extension.connect({name: 'background communication'});
port.postMessage("refresh");
chrome.tabs.getCurrent(function(f) {
chrome.tabs.remove(f.id);
});
});
});<file_sep>/popup.js
$(document).ready(function() {
chrome.storage.local.get('trucks', function(trucks) {
var $tl = $("#truck-list");
if (trucks['trucks'].length == 0) {
$("#message").html("There are currently no food trucks nearby");
} else {
$("#message").html("The following food trucks are nearby:");
}
$.each(trucks['trucks'], function(idx, stop) {
var $a = $("<a class='pull-left' href='http://www.chicagofoodtruckfinder.com/trucks/" + stop.truckId + "'></a>");
$a.append("<img class='img-responsive img-rounded' src='" + stop.truckIconUrl +"' title='" + stop.truckName + "'/>")
var $li = $("<li class='media'></li>");
$li.append($a);
var $mediaBody = $("<div class='media-body'><h4>" + stop.truckName +"</h4></div>");
$mediaBody.append(stop.locationName).append(" <br/>(").append(stop.distance) .append(" miles away)");
$mediaBody.append("<br/>Est. departure: " + stop.endTime );
$li.append($mediaBody);
$tl.append($li);
});
});
chrome.storage.local.get({service: null}, function(items) {
if (items.service) {
$("#visitLink").empty();
$("#visitLink").append(items.service.name);
$("#visitLink").attr("href", items.service.url);
}
});
var port = chrome.extension.connect({name: 'background communication'});
port.postMessage("refresh");
$(".settings-button").click(function(e) {
e.preventDefault();
var url = chrome.extension.getURL("options.html");
chrome.tabs.create({url: url}, function() {});
})
})
| 6e96d4a5edba333c51cd633955aaa154cc7be91c | [
"JavaScript",
"Shell"
] | 3 | Shell | aviolette/cftfchrome | c9689f03d7fa11360e3bf37c90c9ae5d1fe57ecb | 2aa9a50633342510205276acf2338464458ebf58 |
refs/heads/master | <repo_name>therewillbecode/CaesarCipher_py<file_sep>/index.py
__author__ = 'Tom'
import math
class CaesarCipher(object):
def __init__(self, shift):
self.shift = shift
def encode(self, str):
print(str)
str = str.lower()
shifted = [chr(self.map_encode(x, self.shift)) for x in str]
return ''.join(shifted).upper()
def decode(self, str):
str = str.lower()
print(str)
unshifted = [chr(self.map_decode(x, self.shift)) for x in str]
return ''.join(unshifted).upper()
def map_encode(self, char, shift):
shifted = ord(char) + self.shift
if int(shifted) > 122:
shifted = (shifted - 1) - 122 + 97
return shifted
def map_decode(self, char, shift):
shifted = ord(char) - self.shift
if shifted < 97:
shifted = 122 - (97 - (shifted + 1))
return shifted
a = CaesarCipher(5)
c = a.encode('NY,X%F%XMNKY%HNUMJW&&')
// " NY'X F XMNKY HNUMJW!! "
print(c)
<file_sep>/Test/Test_encode.py
__author__ = 'Tom'
import unittest
import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/Users/Tom/PycharmProjects/vector_class/Vector_Calc_py')
import index
obj = index.CaesarCipher(1)
obj2 = index.CaesarCipher(2)
class shift_1(unittest.TestCase):
def test_1_shift_encode(self):
a = obj.encode('z')
self.assertEqual(a, 'A')
def test_shift_decode(self):
a = obj2.decode('a')
self.assertEqual(a, 'Y')
class shift_2(unittest.TestCase):
def test_2_shift_encode(self):
a = obj2.encode('z')
self.assertEqual(a, 'B')
def test_2_shift_decode(self):
a = obj2.decode('a')
self.assertEqual(a, 'Y')
class shift_1_for_abc(unittest.TestCase):
def test_2_shift_encode(self):
a = obj.encode('abc')
self.assertEqual(a, 'BCD')
def test_2_shift_decode(self):
a = obj.decode('abc')
self.assertEqual(a, 'ZAB')
<file_sep>/Test/Test_Decode.py
__author__ = 'Tom'
import unittest
import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/Users/Tom/PycharmProjects/vector_class/Vector_Calc_py')
from index import a
class Test_Error_Unequal_Length(unittest.TestCase):
def test_raiseError_for_unequal_length(self):
self.assertRaises(AttributeError, lambda: short.norm(a))
print(a) | 948457c0dbb47751a0a1235307cb056967cd8e57 | [
"Python"
] | 3 | Python | therewillbecode/CaesarCipher_py | 268e88c2fc10a4347eaaf8780dd3441510be3f01 | dd891cda616896353b61ac11d9bce7d2af8a5396 |
refs/heads/master | <file_sep># feed2
Mobile Feed App
<file_sep>
export default function($scope, $stateParams, $sce) {
const s = $scope
const post = s.model.posts[$stateParams.id]
s.content = $sce.trustAsHtml(post.content)
s.title = post.title
}
<file_sep>import angular from 'angular'
import Firebase from 'firebase'
import _ from 'lodash'
import config from './config'
angular.module('feed-admin', [
require('angularfire'),
require('angular-sanitize'),
require('angular-ui-router')
])
.config(($stateProvider, $urlRouterProvider) => {
$stateProvider
.state('posts', {
url: '/posts', templateUrl: 'posts.html', controller: 'Posts'
}).state('add-post', {
url: '/post', templateUrl: 'post.html', controller: 'AddPost'
}).state('edit-post', {
url: '/post/:id', templateUrl: 'post.html', controller: 'EditPost'
})
$urlRouterProvider.otherwise('/posts')
})
.controller('Main', function($scope, $firebaseArray) {
$scope.posts = $firebaseArray(new Firebase(config.posts))
})
.controller('Posts', ($scope) => {
const s = $scope
s.remove = s.posts.$remove
})
.controller('AddPost', ($scope) => {
const s = $scope
s.action = '$add'
s.post = {}
})
.controller('EditPost', ($scope, $stateParams) => {
const s = $scope
s.action = '$save'
s.post = _.find(s.posts, '$id', $stateParams.id)
})
.controller('Post', ($scope, $state) => {
const s = $scope
s.save = () => s.posts[s.action](s.post)
.then(() => $state.go('posts'))
})
<file_sep>import config from './config'
const ci = config.item
function getId() { return this[ci.id] }
function getTitle() { return this[ci.title] }
function getDate() { return ci.getDate(this) }
function getTime() { return this.getDate().getTime() }
export default {
Item(item) {
item.getId = getId
item.getTitle = getTitle
item.getDate = getDate
item.getTime = getTime
return item
}
}
<file_sep>
export default function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('view', {
abstract: true,
templateUrl: 'views/tabs.html'
})
.state('view.posts', state('/posts', {
'posts': view('posts', 'Posts')
}))
.state('view.post', state('/post/:id', {
'posts': view('post', 'Post')
}))
.state('view.new', state('/new', {
'new': view('new', 'New')
}))
.state('view.new-item', state('/new/:id', {
'new': view('item', 'Item')
}))
.state('view.selected', state('/selected', {
'selected': view('selected')
}))
.state('view.selected-item', state('/selected/:id', {
'selected': view('item', 'Item')
}))
.state('view.read', state('/read', {
'read': view('read')
}))
.state('view.read-item', state('/read/:id', {
'read': view('item', 'Item')
}))
$urlRouterProvider.otherwise('/new')
}
function state(url, views) {
return { url, views }
}
function view(template, controller = null) {
return {
templateUrl: 'views/' + template + '.html',
controller
}
}
<file_sep>
angular.module('feed', ['ionic'])
.run(require('./bars'))
.config(require('./routing'))
.controller('Main', require('./control/Main'))
.controller('New', require('./control/New'))
.controller('Item', require('./control/Item'))
.controller('Posts', require('./control/Posts'))
.controller('Post', require('./control/Post'))
<file_sep>import _ from 'lodash'
export default function($scope) {
const s = $scope
s._ = _
s.setId = (item, id) => { item.id = id; return item }
s.isRecent = item =>
(s.model.start + item.delay * 1000 * 60) < new Date().getTime()
}
<file_sep>#!/bin/sh
cd ionic
cordova build --release android
cd platforms/android/build/outputs/apk
jarsigner -storepass password -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk alias_name
zipalign -f 4 android-release-unsigned.apk feed.apk
mv -f feed.apk ../../../../../../dist/
| 0734f29fda097e3a26ba57037a0e0ab6d9c11093 | [
"Markdown",
"JavaScript",
"Shell"
] | 8 | Markdown | tserdyuk/feed2 | f84bb7b3fe256658dd2f12f6adffbcd15c0da5ef | 32a909490c9922b6ed79348086a085ff48111229 |
refs/heads/main | <file_sep># -*- coding: utf-8 -*-
"""eddy_prediction.py: This file defines the functions used for predict eddies
with data assimilation methods."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "January 2021"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
from classes import (
Eddy,
Catalog,
Observation,
ForecastingMethod,
FilteringMethod,
)
from AnDA.AnDA_data_assimilation import AnDA_data_assimilation
import numpy as np
def create_catalog(dt_frame):
"""Compute a catalog from a panda dataframe of previously detected eddies.
Args:
dt_frame (pd.DataFrame) : dataframe of eddies containing their dates,
id and parameters.
Returns:
catalog (classes.Catalog) : Catalog containing analogs and successors
possible to find in the dataframe.
"""
analogs = np.zeros((1, 6))
successors = np.zeros((1, 6))
# group by id
for i in dt_frame.id.drop_duplicates():
df_i = dt_frame[dt_frame.id == i].sort_values("date")
# find those with successor
for d in df_i.date:
if d + 1 in df_i.date.values:
# take their parameters
analog = df_i[df_i.date == d].to_numpy()[:, 2:]
successor = df_i[df_i.date == d + 1].to_numpy()[:, 2:]
analogs = np.concatenate([analogs, analog])
successors = np.concatenate([successors, successor])
return Catalog(analogs[1:, :], successors[1:, :])
def predict_eddy(eddy, catalog, observation, k=20, N=50, search="complet"):
"""Compute prediction of the parameters of an eddy.
Args:
eddy (classes.Eddy) : the eddy to predict.
catlaog(classes.Catalog) : catalog to use for forecasting.
observation(classes.Observation) : Observation classes to optionnaly
use for data assimilation.
k (int) : number of analogs to use during the forecast.
N (int) : number of members.
search (string) : "complet" or "fast" to use either Jaccard Index
based or just Euclidian based metric.
Returns:
prediction : prediction of the eddy parameters in a instance of class
similar to observation (attributes values and time).
"""
# create a nan observation is observation=None
if type(observation) == int:
values = np.full((observation, 6), np.nan)
time = np.arange(observation)
observation = Observation(values, time)
# set up forecasting and filtering classes
forecasting_method = ForecastingMethod(catalog, k, search=search)
filtering_method = FilteringMethod(observation.R, N, forecasting_method)
# find initial eddy parameter
[x, y] = eddy.center
[L, l] = eddy.axis_len
d = np.angle(eddy.axis_dir[0, 0] + eddy.axis_dir[1, 0] * 1j)
w = eddy.angular_velocity
# conclude the set up of the filtering class giving it the first eddy
filtering_method.set_first_eddy(np.array([x, y, L, l, d, w]))
# compute data assimilation
prediction = AnDA_data_assimilation(observation, filtering_method)
return prediction
def predict_eddies(
catalog, observation, R, k=20, N=50, t_vanish=10, search="fast", Tmax=None
):
"""Compute prediction of the parameters of an eddy.
Args:
catalog(pandas.DataFram) : catalog to use for forecasting.
observation(pandas.DataFram) : Observation to use for AnDA.
R (np.array(6,6)) : observation noise covariance matrix.
k (int) : number of analogs to use during the forecast.
N (int) : number of members.
t_vanish (int) : time after wich (and before witch) we consider an
unobserved eddy has vanished.
search (string) : "complet" or "fast" to use either Jaccard Index
based or just Euclidian based metric.
Tmax (int): time during which we want predictions (max time of
observation.date if None).
Returns:
eddies (dict[time][list(eddy)]) : list of eddies for each used time.
"""
eddies = {}
prediction = []
catalog = create_catalog(catalog)
date = observation.date.drop_duplicates().to_numpy()
if Tmax is None:
date = range(date[0], date[-1] + 1)
else:
date = range(date[0], date[0] + Tmax)
if t_vanish is None:
t_vanish = np.inf
for id in observation.id.drop_duplicates():
obs = create_observation(observation, R, id, Tmax)
if obs.values[~np.isnan(obs.values)].shape[0] != 0:
if np.isnan(obs.values[0, 0]):
first_obs = np.where(~np.isnan(obs.values[:, 0]))[0][-1]
if first_obs >= t_vanish:
obs.values = obs.values[first_obs - t_vanish :, :]
obs.time = obs.time[first_obs - t_vanish :]
else:
first_obs = 0
if np.isnan(obs.values[-1, 0]):
last_obs = np.where(~np.isnan(obs.values[:, 0]))[0][-1]
if first_obs + last_obs <= date[-1] - t_vanish:
obs.values = obs.values[: last_obs + t_vanish, :]
obs.time = obs.time[: last_obs + t_vanish]
param = obs.values[~np.isnan(obs.values)[:, 0], :][0, :]
eddy = Eddy([], 0, param=param)
prediction.append(predict_eddy(eddy, catalog, obs, k, N, search))
for t in date:
eddies[t] = []
for pred in prediction:
tmin = pred.time[0]
tmax = pred.time[-1]
if t >= tmin and t <= tmax:
eddies[t].append(get_eddy(pred, t - tmin))
return eddies
def get_eddy(prediction, t):
"""Return a classes.Eddy instance corresponding to time t of predictions
Args:
prediction : prediction compute by data assimilation
Returns:
eddy (classes.Eddy) : eddy corresponding to demanded time.
"""
return Eddy([], t, param=prediction.values[t, :])
def create_observation(dt_frame, R=np.eye(6) / 36, id=None, Tmax=None):
"""Return a classes.Observation instance corresponding to the observations
made of a given eddy
Args:
dt_frame (pd.DataFrame) : a data frame of differents observed eddies
containing date,id and parameters.
R (np.array(6,6)) : observation noise covariance matrix.
id (int) : id of the eddy on which data assimilation will be done.
Tmax (int): time during which we want predictions (max time of
observation.date if None).
Returns:
observation (classes.Observation) : corresponding instance.
"""
if id is None:
id = dt_frame.id[0]
df_id = dt_frame[dt_frame.id == id]
tmin, tmax = dt_frame.date.min(), dt_frame.date.max()
if Tmax is None:
T = tmax - tmin + 1
else:
T = Tmax
time = np.arange(tmin, tmin + T)
values = np.zeros((T, 6))
for t in range(T):
if t + tmin in df_id.date.values:
values[t, :] = df_id[df_id.date == t + tmin].to_numpy()[:, 2:]
else:
values[t, :] = np.nan
return Observation(values, time, R)
<file_sep>#!/usr/bin/env python
""" AnDA_stat_functions.py: Collection of statistical functions used in AnDA. """
__author__ = "<NAME> and <NAME>"
__version__ = "1.0"
__date__ = "2016-10-16"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import numpy as np
def AnDA_RMSE(a, b):
""" Compute the Root Mean Square Error between 2 n-dimensional vectors. """
return np.sqrt(np.mean((a - b) ** 2))
def normalise(M):
""" Normalize the entries of a multidimensional array sum to 1. """
c = np.sum(M)
# Set any zeros to one before dividing
d = c + 1 * (c == 0)
M = M / d
return M
def mk_stochastic(T):
""" Ensure the matrix is stochastic, i.e., the sum over the last dimension is 1. """
if len(T.shape) == 1:
T = normalise(T)
else:
n = len(T.shape)
# Copy the normaliser plane for each i.
normaliser = np.sum(T, n - 1)
normaliser = np.dstack([normaliser] * T.shape[n - 1])[0]
# Set zeros to 1 before dividing
# This is valid since normaliser(i) = 0 iff T(i) = 0
normaliser = normaliser + 1 * (normaliser == 0)
T = T / normaliser.astype(float)
return T
def sample_discrete(prob, r, c):
""" Sampling from a non-uniform distribution. """
# this speedup is due to Peter Acklam
cumprob = np.cumsum(prob)
n = len(cumprob)
R = np.random.rand(r, c)
M = np.zeros([r, c])
for i in range(0, n - 1):
M = M + 1 * (R > cumprob[i])
return int(M)
def resampleMultinomial(w):
""" Multinomial resampler. """
M = np.max(w.shape)
Q = np.cumsum(w, 0)
Q[M - 1] = 1
# Just in case...
i = 0
indx = []
while i <= (M - 1):
sampl = np.random.rand(1, 1)
j = 0
while Q[j] < sampl:
j = j + 1
indx.append(j)
i = i + 1
return indx
def inv_using_SVD(Mat, eigvalMax):
""" SVD decomposition of Matrix. """
U, S, V = np.linalg.svd(Mat, full_matrices=True)
eigval = np.cumsum(S) / np.sum(S)
# search the optimal number of eigen values
i_cut_tmp = np.where(eigval >= eigvalMax)[0]
S = np.diag(S)
V = V.T
i_cut = np.min(i_cut_tmp) + 1
U_1 = U[0:i_cut, 0:i_cut]
U_2 = U[0:i_cut, i_cut:]
U_3 = U[i_cut:, 0:i_cut]
U_4 = U[i_cut:, i_cut:]
S_1 = S[0:i_cut, 0:i_cut]
S_2 = S[0:i_cut, i_cut:]
S_3 = S[i_cut:, 0:i_cut]
S_4 = S[i_cut:, i_cut:]
V_1 = V[0:i_cut, 0:i_cut]
V_2 = V[0:i_cut, i_cut:]
V_3 = V[i_cut:, 0:i_cut]
V_4 = V[i_cut:, i_cut:]
tmp1 = np.dot(np.dot(V_1, np.linalg.inv(S_1)), U_1.T)
tmp2 = np.dot(np.dot(V_1, np.linalg.inv(S_1)), U_3.T)
tmp3 = np.dot(np.dot(V_3, np.linalg.inv(S_1)), U_1.T)
tmp4 = np.dot(np.dot(V_3, np.linalg.inv(S_1)), U_3.T)
inv_Mat = np.concatenate(
(
np.concatenate((tmp1, tmp2), axis=1),
np.concatenate((tmp3, tmp4), axis=1),
),
axis=0,
)
tmp1 = np.dot(np.dot(U_1, S_1), V_1.T)
tmp2 = np.dot(np.dot(U_1, S_1), V_3.T)
tmp3 = np.dot(np.dot(U_3, S_1), V_1.T)
tmp4 = np.dot(np.dot(U_3, S_1), V_3.T)
hat_Mat = np.concatenate(
(
np.concatenate((tmp1, tmp2), axis=1),
np.concatenate((tmp3, tmp4), axis=1),
),
axis=0,
)
det_inv_Mat = np.prod(np.diag(S[0:i_cut, 0:i_cut]))
return inv_Mat
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines the classes used for eddies detection."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
import numpy as np
from sklearn.neighbors import KDTree
from metrics import eddies_jaccard_index
from AnDA.AnDA_analog_forecasting import AnDA_analog_forecasting
from tools import (
grad_desc,
estimate_sea_level_center,
compute_u_v,
get_interpolized_u_v,
compute_error,
compute_grad_u_v,
compute_gradL1,
convert_from_degree_to_meter,
convert_from_meter_to_degree,
)
from constants import EQUATORIAL_EARTH_RADIUS
# import netCDF4 as nc
# import scipy.interpolate as sp_interp
class StreamLine:
"""Class used to represent a stream line and compute its caracteristics.
The stream line is represented by a serie of points, using spherical
coordinates (longitude, latitude). All the caracteristics of this stream
line are computed from this list.
Args:
coord_list (array_like) : List of coordinates representing the stream
line.
delta_time (array_like or float) : Delta time between 2 consecutive
points. It should be a float if the delta time is a constant or an
array_like with len = n-2 and n beeing the number of points
otherwise (n-2 because it is used for computing the angular
velocity).
cut_lines (bool, default = True) : If True, the considered streamline
will be the shortest sub streamline so that the winding angle is
equal to 2 pi. This parameter has not effect if the winding angle of
the complet streamline is lower than 2 pi.
Attributes:
coord_list (array_like) : List of coordinates representing the stream
line.
nb_points (int) : Number of points in coord_list.
length (float) : Total length of the line.
mean_pos (ndarray(2,)) : Average of the coordinates. If the stream line
is in a eddy, it represents an approximation of the eddy center.
winding_angle (float) : Sum of the oriented angles formed by 3
consecutive points in the line. Unit is the radian
angular_velocities (np.array) : List of the oriented angular velocities
between 3 consecutive points in the line. Unit is the rad.s**-1
"""
def __init__(self, coord_list, delta_time, cut_lines=True):
self.coord_list = np.array(coord_list, dtype=float)
self.nb_points = len(self.coord_list)
self.mean_pos = np.mean(coord_list, axis=0)
self._set_length()
self._set_winding_angle_and_angular_velocity(delta_time, cut_lines)
def _set_length(self):
""" Compute the total length of the streamline. """
if self.nb_points <= 1:
self.length = 0
else:
ldiff_degree = self.coord_list[1:] - self.coord_list[:-1]
ldiff_meter = ldiff_degree * np.pi * EQUATORIAL_EARTH_RADIUS / 180
ldiff_meter[:, 0] *= np.cos(self.mean_pos[1] * np.pi / 180)
self.length = np.sum(
np.sqrt(ldiff_meter[:, 0] ** 2 + ldiff_meter[:, 1] ** 2)
)
def _set_winding_angle_and_angular_velocity(self, delta_time, cut_lines):
"""Compute the sum of the oriented angles in the line.
The angle at a given point X_k is the angle between vect(X_k-1, X_k) and
vect(X_k, X_k+1). If the winding angle is higher than 2 pi, the
streamline is cut to keep the shortest streamline so that the winding
angle is greater or equal to 2 pi.
Args
delta_time (array_like or float) : Delta time between 2 consecutive
points. If dt is a constant delta_time should be a float and an
array_like with len = n-1 otherwise, n beeing the number of
points.
cut_lines (bool) : If True, the considered streamline will be the
shortest sub streamline so that the winding angle is equal to 2 pi.
This parameter has not effect if the winding angle of the complet
streamline is lower than 2 pi.
"""
coord = self.coord_list[:, 0] + 1j * self.coord_list[:, 1]
coord += coord.real * np.cos(self.mean_pos[1] * np.pi / 180)
vectors = coord[1:] - coord[:-1]
# Remove the null vectors
not_null_vect = vectors != 0
vectors = vectors[not_null_vect]
norms = abs(vectors)
angles = np.angle(vectors[1:] / vectors[:-1])
if type(delta_time * 1.0) != float:
delta_time = delta_time[not_null_vect]
self.coord_list = self.coord_list[np.append(not_null_vect, True), :]
self.nb_points = len(self.coord_list)
if self.nb_points <= 2:
self.winding_angle = 0
self.angular_velocities = 0
else:
if cut_lines:
# Find the shortest sub streamline with the smallest ratio
# dist(start,end)/sub_line_len. This ratio will be close to 1 for
# straight lines and close to 0 for closed loop.
cumsum_norms = np.concatenate((np.array([0]),np.cumsum(norms)))
min_ratio = 1
min_end_id = self.nb_points - 1
min_start_id = 0
for start_id in range(self.nb_points):
start_norm = cumsum_norms[start_id]
start_pts = coord[start_id]
for end_id in range(start_id+1, self.nb_points):
curr_len = cumsum_norms[end_id] - start_norm
start_end_dist = abs(coord[end_id] - start_pts)
ratio = start_end_dist / curr_len
if ratio <= min_ratio:
min_ratio = ratio
min_end_id = end_id
min_start_id = start_id
# Recompute the first attributs after taking the sub streamline
self.coord_list = np.array(
self.coord_list[min_start_id : min_end_id + 1], dtype=float
)
self.nb_points = (min_end_id - min_start_id) + 1
self.length = cumsum_norms[end_id] - cumsum_norms[start_id]
self.mean_pos = np.mean(self.coord_list, axis=0)
# Recompute the sub angle list and delta_time
angles = np.array(angles[min_start_id : min_end_id - 1])
if type(delta_time * 1.0) != float:
delta_time = np.array(delta_time[min_start_id:min_end_id])
# Set the winding angle and the angular velocity
self.winding_angle = np.sum(angles)
if type(delta_time * 1.0) == float:
self.angular_velocities = angles / delta_time
else:
self.angular_velocities = (
2 * angles / (delta_time[1:] + delta_time[:-1])
)
def get_mean_radius(self):
"""Compute the mean radius of the stream line.
Compute the mean distance between the stream line mean pos and the list
of coordinates. This value does not have any real meaning if the stream
line winding is low.
Returns:
mean_radius (float) : The mean radius of the stream line.
"""
radius = np.array(self.coord_list)
radius[:, 0] -= self.mean_pos[0]
radius[:, 1] -= self.mean_pos[1]
radius = np.sqrt(np.sum(radius ** 2, axis=1))
mean_radius = np.mean(radius)
return mean_radius
class Eddy:
"""Class used to represent a eddy and compute its caracteristics.
Args:
sl_list (list of StreamLine) : List of streamline representing the eddy.
date (int, default=0) : date at which the trajectories are simulated.
param (list, default=[]) : Parameters of the eddy when it is not
initialized from a list of streamlines. It should contain 6 values.
The 2 first are the longitude and the latitude of the eddy center.
The 2 next are the axis length. The 5th is the angle between the
first axis of the ellipse and the x-axis (longitudes). The last is
the angular speed. The parameter 'sl_list' is ignored if this
parameter is not the default one.
Attributes:
sl_list (list of StreamLine) : List of stream line representing the
eddy.
date : date at which the eddy is detected
nb_sl (int) : Number of stream lines in sl_list.
center (array_like(2)) : Mean of stream lines center weigthed by the
stream line length. This represent the stream line center.
cov_matrix (ndarray(2,2)) : Covariance of all the points on all the
streamlines.
axis_len (ndarray(2) : Length of the eddy axis.
axis_dir (ndarray(2,2)) : Direction of the eddy axis, they are computed
using the covariance of all the points on all the streamlines.
angular_velocity (float) : Mean angular velocity of the eddy.
"""
def __init__(self, sl_list, date=0, param=[]):
if len(param) == 0:
self.date = date
self.sl_list = list(sl_list)
self.nb_sl = len(self.sl_list)
self._set_center()
self._set_angular_velocity()
self._set_axis_len_and_dir()
elif len(param) == 6:
self.date = date
self.sl_list = []
self.nb_sl = 0
self.center = np.array(param[:2])
self.axis_len = np.array(param[2:4])
self.axis_dir = np.array(
[
[np.cos(param[4]), -np.sin(param[4])],
[np.sin(param[4]), np.cos(param[4])],
]
)
self.angular_velocity = param[5]
else:
print("Parameter(s) missing for initialising an eddy")
def _set_center(self):
"""Compute the eddy center.
The center is the mean of stream lines center weigthed by the stream
line length.
"""
sl_center = np.array(
[self.sl_list[k].mean_pos for k in range(self.nb_sl)]
)
sl_nb_pts = np.array(
[self.sl_list[k].nb_points for k in range(self.nb_sl)]
)
sl_wcenter = [sl_center[k] * sl_nb_pts[k] for k in range(self.nb_sl)]
self.center = np.sum(sl_wcenter, axis=0) / np.sum(sl_nb_pts)
def _set_angular_velocity(self):
"""Compute the angular velocity of the eddy.
The angular velocity is the angle variation per time units.
"""
nb_angular_velocities = 0
sum_angular_velocities = 0
for sl_id in range(self.nb_sl):
w_list = self.sl_list[sl_id].angular_velocities
nb_angular_velocities += len(w_list)
sum_angular_velocities += np.sum(w_list)
self.angular_velocity = sum_angular_velocities / nb_angular_velocities
def _set_axis_len_and_dir(self):
"""Compute the axis direction and lengths for the ellipse
The eigen vectors are the directions of the axis of the ellipse. The
length is computed so that sum{(x,y)}{(x/a)**2+(y/b)**2-1} is minimum.
"""
# Constant
R = EQUATORIAL_EARTH_RADIUS
# Compute the covariance matrixe for finding the axis direction
nb_coord = np.sum(
[self.sl_list[k].nb_points for k in range(self.nb_sl)]
)
merged_coord_list = np.zeros((nb_coord, 2))
index = 0
for sl_id in range(self.nb_sl):
sl = self.sl_list[sl_id]
merged_coord_list[index : index + sl.nb_points, :] = np.array(
sl.coord_list
)
index += sl.nb_points
merged_coord_list[:, 0] -= self.center[0]
merged_coord_list[:, 1] -= self.center[1]
cov_matrix = np.cov(merged_coord_list.T)
self.axis_dir = np.linalg.eig(cov_matrix)[1]
# Rotate and center the points so that the ellipse equation can be
# written "(x/a)**2 + (y/b)**2 = 1"
# angles = np.angle(self.axis_dir[:, 0] + 1j * self.axis_dir[:, 1])
angles = np.angle(self.axis_dir[0, :] + 1j * self.axis_dir[1, :])
angle = angles[0]
rotation = np.array(
[[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]]
)
aligned_points = np.dot(rotation, merged_coord_list.T).T
# Compute the regression square error for given (a,b) parameters
def error(a, b):
points_sq = aligned_points ** 2
points_sq[:, 0] /= max(1.0 * a * a, 0.0001)
points_sq[:, 1] /= max(1.0 * b * b, 0.0001)
return np.sum((np.sqrt(np.sum(points_sq, axis=1)) - 1) ** 2)
# Gradient of the square error
def grad_error(a, b):
points_sq = aligned_points ** 2
x2 = np.array(points_sq[:, 0])
y2 = np.array(points_sq[:, 1])
sq_coeff = np.sqrt(x2 / (a * a) + y2 / (b * b))
common_coeff = -2 * (1 - 1 / sq_coeff)
grad_a = np.sum(common_coeff * x2) / (a ** 3)
grad_b = np.sum(common_coeff * y2) / (b ** 3)
return grad_a, grad_b
# Gradient decente
a, b = grad_desc(error, grad_error)
self.axis_len = np.array([a, b])
return
##### Optimisation of parameters assuming a gaussian modelisation #####
# # self.axis_len = np.linalg.eig(cov_matrix)[0]
# # Rx, Ry in meter
# axis_len_meter = np.zeros((2,))
# rotation_inv = np.array(
# [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]
# )
# point_rx = np.array([self.axis_len[0], 0])
# point_ry = np.array([0, self.axis_len[1]])
# point_rx = np.dot(rotation_inv, point_rx.T).T
# point_ry = np.dot(rotation_inv, point_ry.T).T
# point_rx_meter = convert_from_degree_to_meter(
# point_rx, self.center[1], R
# )
# point_ry_meter = convert_from_degree_to_meter(
# point_ry, self.center[1], R
# )
# axis_len_meter[0] = np.linalg.norm(point_rx_meter)
# axis_len_meter[1] = np.linalg.norm(point_ry_meter)
# # Esimate h0
# h0 = estimate_sea_level_center(
# self.date,
# self.center,
# aligned_points,
# self.axis_len,
# self.axis_dir,
# self.angular_velocity,
# angle,
# stream_data_fname="../data/data.nc",
# R=EQUATORIAL_EARTH_RADIUS,
# )
# # Compute theorical u,v and get measured (interpolized) u,v
# u_v_evaluated = compute_u_v(
# aligned_points, angle, self.center, axis_len_meter, h0
# )
# u_v_measured = get_interpolized_u_v(
# aligned_points,
# self.date,
# self.center,
# angle,
# stream_data_fname="../data/data.nc",
# )
# # Computing initial error
# L1init = compute_error(u_v_evaluated, u_v_measured)
# # Gradient descent
# step_sizex = axis_len_meter[0]
# step_sizey = axis_len_meter[1]
# n_iter = 10
# for iter in range(n_iter):
# grad_u, grad_v = compute_grad_u_v(
# aligned_points, angle, self.center, axis_len_meter, h0
# )
# gradL1 = compute_gradL1(
# u_v_evaluated, u_v_measured, grad_u, grad_v
# )
# axis_len_meter[0] -= step_sizex * gradL1[0]
# axis_len_meter[1] -= step_sizey * gradL1[1]
# # Updating Rx and Ry in degreee to recompute h0
# point_rx_meter = (
# point_rx_meter
# * axis_len_meter[0]
# / np.linalg.norm(point_rx_meter)
# )
# point_ry_meter = (
# point_ry_meter
# * axis_len_meter[1]
# / np.linalg.norm(point_ry_meter)
# )
# point_rx_degree = convert_from_meter_to_degree(
# point_rx_meter, self.center[1], R
# )
# point_ry_degree = convert_from_meter_to_degree(
# point_ry_meter, self.center[1], R
# )
# self.axis_len[0] = np.linalg.norm(point_rx_degree)
# self.axis_len[1] = np.linalg.norm(point_ry_degree)
# h0 = estimate_sea_level_center(
# self.date,
# self.center,
# aligned_points,
# self.axis_len,
# self.axis_dir,
# self.angular_velocity,
# angle,
# stream_data_fname="../data/data.nc",
# R=EQUATORIAL_EARTH_RADIUS,
# )
# u_v_evaluated = compute_u_v(
# aligned_points, angle, self.center, axis_len_meter, h0
# )
# L1 = compute_error(u_v_evaluated, u_v_measured)
# print("L1 : ", L1)
# print("optimizing: ", L1 <= L1init)
# # Updating Rx,Ry in degree
# point_rx_meter = (
# point_rx_meter * axis_len_meter[0] / np.linalg.norm(point_rx_meter)
# )
# point_ry_meter = (
# point_ry_meter * axis_len_meter[1] / np.linalg.norm(point_ry_meter)
# )
# point_rx_degree = convert_from_meter_to_degree(
# point_rx_meter, self.center[1], R
# )
# point_ry_degree = convert_from_meter_to_degree(
# point_ry_meter, self.center[1], R
# )
# self.axis_len[0] = np.linalg.norm(point_rx_degree)
# self.axis_len[1] = np.linalg.norm(point_ry_degree)
class Catalog:
"""Class used to represent a catalog of eddies and their successors.
Args:
analogs (array_like) : 6 parameters (ax 1) of different eddies (ax 0)
successors (aaray like) : parameters of corresponding successors.
Attributes:
analogs (array_like) : 6 parameters (ax 1) of different eddies (ax 0)
successors (array like) : parameters of corresponding successors.
"""
def __init__(self, analogs, successors):
self.analogs = analogs
self.successors = successors
class Observation:
"""Class used to represent observation of eddies and give time scale.
Args:
values (array_like) : 6 parameters (axis 1) of different observed eddies
(axis 0). np.nan if no observed parameter.
time (array like) : times corresponding to observation and desired
prediction.
R (np.array(6,6)) : observation noise covariance matrix.
Attributes:
values (array_like) : 6 parameters (axis 1) of different observed eddies
(axis 0). np.nan if no observed parameter.
time (array like) : times corresponding to observation and desired
prediction.
R (np.array(6,6)) : observation noise covariance matrix.
"""
def __init__(self, values, time, R=np.ones((6, 6)) / 36):
self.values = values
self.time = time
self.R = R
class ForecastingMethod:
"""Class used to set parameters for the forecasting model.
Args:
k (int) : number of analogs to use during the forecast.
catalog(Catalog) : a catalog of analogs and successors
regression(String) : chosen regression ('locally_constant', 'increment',
'local_linear')
Attributes:
k (int) : number of analogs to use during the forecast.
catalog(Catalog) : a catalog of analogs and successors
regression(String) : chosen regression ('locally_constant', 'increment',
'local_linear')
"""
def __init__(self, catalog, k, search, regression="local_linear"):
self.k = min(k, np.shape(catalog.analogs)[0] - 1)
self.catalog = catalog
self.regression = regression
self.search = search
def search_neighbors(self, x):
kdt = KDTree(
self.catalog.analogs[:, [0, 1]], leaf_size=50, metric="euclidean"
)
dist_knn, index_knn = kdt.query(x[:, [0, 1]], self.k)
if self.search == "complet":
for i in range(x.shape[0]):
e1 = Eddy([], None, param=x[i, :])
for j in range(self.k):
e2 = Eddy(
[],
None,
param=self.catalog.analogs[index_knn[i, j], :],
)
dist_knn[i, j] = dist_knn[i, j] * (
1 - eddies_jaccard_index(e1, e2, 10)
)
return dist_knn, index_knn
class FilteringMethod:
"""Class used to set parameters for the filtering model.
Args:
method (String) : chosen method ('AnEnKF', 'AnEnKS')
N (int) : number of members
R (array_like(6,6)) : observation noise covariance matrix
forecasting_model (ForecastingModel) : ForecastingModel instance
Attributes:
method (String) : chosen method ('AnEnKF', 'AnEnKS')
N (int) : number of members
H (array_like(6,6)) : matrix of state transition
B (array_like(6,6)) : control-input model
R (array_like(6,6)) : observation noise covariance matrix
forecasting_model (ForecastingModel) : ForecastingModel instance
xb (array_like(1,6)) : parameters of the initial eddy
"""
def __init__(self, R, N, forecasting_method, method="AnEnKS"):
self.method = method
self.N = N
self.xb = None
self.H = np.eye(6)
self.B = np.eye(6)
self.R = R
self.AF = forecasting_method
def set_first_eddy(self, xb):
self.xb = xb
def m(self, x):
return AnDA_analog_forecasting(x, self.AF)
<file_sep>import warnings
warnings.filterwarnings("ignore")
import sys
sys.path.append("../")
import numpy as np
import pandas as pd
from eddies_prediction import predict_eddies
from plot import Animation
### initialization of catalog and observations
catalog = pd.read_csv("catalog.csv", usecols=list(range(1, 9)))
observation = pd.read_csv("catalog300.csv", usecols=list(range(1, 9)))
### data assimilation
R = np.eye(6) / 1000 # covariance of observation noise
prediction = predict_eddies(catalog, observation, R, t_vanish=None, Tmax=30)
### animation
animation = Animation(prediction)
animation.show()<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines the functions used for ploting eddies and
streamlines."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__license__ = "Libre"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
import cartopy
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from matplotlib.colors import Normalize
from matplotlib.animation import FuncAnimation
from classes import StreamLine, Eddy
class StreamPlot:
"""Matplotlib figure with specific methods for ploting trajectories, eddies
etc.
Matplotlib figure with specific methods for ploting trajectories, vortexes,
ellipses, from .nc files or from numpy arrays
Attributes:
fig (matplotlib.figure.Figure) : Matplotlib figure
ax (cartopy.mpl.geoaxes.GeoAxesSubplot) : cartopy projection
"""
def __init__(self):
projection = cartopy.crs.PlateCarree()
self.fig, self.ax = plt.subplots(
1, 1, subplot_kw={"projection": projection}
)
gl = self.ax.gridlines(crs=projection, draw_labels=True)
gl.xlabels_top, gl.ylabels_right = (False, False)
gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER
self.ax.coastlines()
def plot_trajectories(self, trajectories, line_style="-"):
"""Plots trajectories on a map.
Input parameter can be a .nc file, a StreamLine object or a list of
StreamLine object.
Args:
trajectories (str or list of StreamLine or StreamLine) : If it is a
string, name of the .nc file containing trajectories data. It
should have been created using parcels.ParticleSet.ParticleFile.
Otherwise StreamLine or list of StreamLine to show.
line_style (str) : line style for the trajectories representation.
"""
if type(trajectories) == str:
try:
pfile = xr.open_dataset(str(trajectories), decode_cf=True)
except:
pfile = xr.open_dataset(str(trajectories), decode_cf=False)
lon = np.ma.filled(pfile.variables["lon"], np.nan)
lat = np.ma.filled(pfile.variables["lat"], np.nan)
pfile.close()
for p in range(lon.shape[1]):
lon[:, p] = [ln if ln < 180 else ln - 360 for ln in lon[:, p]]
self.ax.plot(lon.T, lat.T, "-", transform=cartopy.crs.Geodetic())
return
if type(trajectories) == StreamLine:
trajectories = [trajectories]
nb_traj = len(trajectories)
for k in range(nb_traj):
traj = trajectories[k].coord_list
self.ax.plot(
traj[:, 0],
traj[:, 1],
line_style,
transform=cartopy.crs.Geodetic(),
)
def plot_eddies(self, eddies, plot_traj=True, line_style="-", ellipse_color='k'):
"""Plots eddies from a .nc particles trajectories file.
Plot the center of the eddies and an ellipse representing each eddy.
Args:
eddies (list of Eddy or Eddy) : Eddy or list of Eddy to show.
plot_traj (bool, default=True) : If True, plot the trajectories.
line_style (str) : line style for the trajectories representation.
"""
if type(eddies) == Eddy:
eddies = [eddies]
n = len(eddies)
# Plot centers
centers = np.array([eddies[k].center for k in range(n)])
if len(eddies) > 0:
self.ax.plot(
centers[:, 0],
centers[:, 1],
ellipse_color+'+',
transform=cartopy.crs.Geodetic(),
)
# Plot trajectories
if plot_traj:
for k in range(n):
self.plot_trajectories(
eddies[k].sl_list, line_style=line_style
)
# Plot ellipses
# The angle of the ellipse is computed with 'vect_x - vect_y*1j' because
# of y-axis inversion for plotting ellispses.
# resize_coeff = 3
axes_len = np.array([eddies[k].axis_len for k in range(n)])
axes_dir = np.array([eddies[k].axis_dir for k in range(n)])
angles = (
np.array(
[
np.angle(axes_dir[k, 0, 0] + axes_dir[k, 1, 0] * 1j)
for k in range(n)
]
)
/ (2 * np.pi)
* 360
)
for k in range(n):
ellipse = Ellipse(
centers[k, :],
axes_len[k, 0] * 3,
axes_len[k, 1] * 3,
angle=angles[k],
color=ellipse_color,
alpha=1,
fill=False,
linewidth=2
)
self.ax.add_patch(ellipse)
# Plot ellipse axis
self.ax.arrow(
centers[k, 0],
centers[k, 1],
axes_dir[k, 0, 0] * axes_len[k, 0] * 1.5,
axes_dir[k, 1, 0] * axes_len[k, 0] * 1.5,
)
self.ax.arrow(
centers[k, 0],
centers[k, 1],
axes_dir[k, 0, 1] * axes_len[k, 1] * 1.5,
axes_dir[k, 1, 1] * axes_len[k, 1] * 1.5,
)
def plot_catalogue(self, eddies_path):
"""Plot the center of the eddies in the catalogue.
The centers are colored following the date of observation.
Args:
eddies_path (dict(int : dict(int : classes.Eddy))) : The path of eddies.
A unique id is assigned to each eddy so that 2 object 'classes.Eddy'
share the same id if and only if they represent the same eddy at
different dates. The first key is a date, the second key is the eddy
identifier.
"""
list_dates = list(eddies_path.keys())
date_start = min(list_dates)
date_end = max(list_dates)
cmap = plt.cm.brg(np.linspace(0, 1, date_end - date_start + 1))
for date in range(date_start, date_end + 1):
xy = []
for eddy_id in eddies_path[date].keys():
xy.append(eddies_path[date][eddy_id].center)
xy = np.array(xy)
self.ax.plot(
xy[:, 0],
xy[:, 1],
linestyle="",
marker="o",
markersize=5,
color=cmap[date - date_start],
transform=cartopy.crs.Geodetic(),
)
self.fig.colorbar(
plt.cm.ScalarMappable(
cmap="brg", norm=Normalize(vmin=date_start, vmax=date_end)
)
)
def plot_eddies_trajectories(self, eddies_path):
"""Plot the center of the eddies in the catalogue.
The centers are colored following the date of observation.
Args:
eddies_path (dict(int : dict(int : classes.Eddy))) : The path of eddies.
A unique id is assigned to each eddy so that 2 object 'classes.Eddy'
share the same id if and only if they represent the same eddy at
different dates. The first key is a date, the second key is the eddy
identifier.
"""
eddies_traj = {}
for day in eddies_path.keys():
for eddy_id in eddies_path[day].keys():
if eddy_id not in eddies_traj:
eddies_traj[eddy_id] = [eddies_path[day][eddy_id].center]
else:
eddies_traj[eddy_id].append(
eddies_path[day][eddy_id].center
)
for eddy_id in eddies_traj.keys():
xy = np.array(eddies_traj[eddy_id])
self.ax.plot(xy[:, 0], xy[:, 1], marker=".", markersize=5)
def plot(self, X, Y, marker="+", color=None):
""" Wrapper of the basic 'plot' function of matplotlib.pyplot """
if color is not None:
self.ax.plot(
X,
Y,
marker=marker,
color=color,
transform=cartopy.crs.Geodetic(),
)
else:
self.ax.plot(X, Y, marker=marker, transform=cartopy.crs.Geodetic())
def show(self):
plt.show()
class Animation:
""" Matplotlib animation to visualize eddies movements."""
def __init__(self, eddies, inter=1000, tmin=None, tmax=None, t_vanish=0):
self.eddies = eddies
if tmin is None:
self.tmin = list(eddies.keys())[0]
else:
self.tmin = tmin
if tmax is None:
self.tmax = list(eddies.keys())[-1]
else:
self.tmax = tmax
self.t_vanish = t_vanish
self.fig, self.ax = plt.subplots(
1, 1, subplot_kw={"projection": cartopy.crs.PlateCarree()}
)
self.map = self.plot(0)
self.animation = FuncAnimation(
self.fig,
self.update,
self.tmax - self.tmin + 1,
interval=inter,
repeat=False,
)
def update(self, frame_number):
self.map = self.ax.clear()
self.map = plt.title(
"Prediction for date = %s" % (frame_number + self.tmin)
)
self.map = plt.xlim(50, 64)
self.map = plt.ylim(13, 23)
self.map = self.plot(frame_number)
def plot(self, frame_number):
gl = self.ax.gridlines(crs=cartopy.crs.PlateCarree(), draw_labels=True)
gl.xlabels_top, gl.ylabels_right = (False, False)
gl.xformatter = cartopy.mpl.gridliner.LONGITUDE_FORMATTER
gl.yformatter = cartopy.mpl.gridliner.LATITUDE_FORMATTER
self.ax.coastlines()
eddies = self.eddies[self.tmin + frame_number]
n = len(eddies)
# Plot centers
centers = np.array([eddies[k].center for k in range(n)])
if len(eddies) > 0:
self.ax.plot(
centers[:, 0],
centers[:, 1],
"k+",
transform=cartopy.crs.Geodetic(),
)
# Plot ellipses
resize_coeff = 3
axes_len = np.array([eddies[k].axis_len for k in range(n)])
axes_dir = np.array([eddies[k].axis_dir for k in range(n)])
angles = (
np.array(
[
np.angle(axes_dir[k, 0, 0] - axes_dir[k, 0, 1] * 1j)
for k in range(n)
]
)
/ (2 * np.pi)
* 360
)
for k in range(n):
ellipse = Ellipse(
centers[k, :],
axes_len[k, 0] * resize_coeff,
axes_len[k, 1] * resize_coeff,
angle=angles[k],
color="red",
alpha=1,
fill=False,
linewidth=2,
)
self.ax.add_patch(ellipse)
# Plot axis
self.ax.arrow(
centers[k, 0],
centers[k, 1],
axes_dir[k, 0, 0] * axes_len[k, 0] * 1.5,
-axes_dir[k, 0, 1] * axes_len[k, 0] * 1.5,
)
self.ax.arrow(
centers[k, 0],
centers[k, 1],
axes_dir[k, 1, 0] * axes_len[k, 1] * 1.5,
-axes_dir[k, 1, 1] * axes_len[k, 1] * 1.5,
)
return self.ax
def show(self):
plt.show()
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file gathers the constants and global parameters for the
detection."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = ["<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>"]
EDDY_MIN_AXIS_LEN =1e-2 # Axis length inferior limit for ellipses
# representing eddies.
EDDY_AXIS_PRECISION = 1e-4 # Stop criterion for gradient descente.
EDDY_MIN_RADIUS = 0.2 # Eddies with axis len verifying (a**2 + b**2)
# lower than this parameter are discared.
EQUATORIAL_EARTH_RADIUS = 6378.137e3
MIN_STREAMLINE_IN_EDDIES = 6 # Number for streamlines in eddies.
JACCARD_RESOLUTION = 50 # Resolution for the Jaccard index computation.<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines some functions used for eddies detection and
representation."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
import numpy as np
import netCDF4 as nc
from constants import EQUATORIAL_EARTH_RADIUS
import scipy.interpolate as sp_interp
from constants import EDDY_MIN_AXIS_LEN, EDDY_AXIS_PRECISION
def grad_desc(f_error, f_grad):
"""Compute a local minimum of a function using gradient descente.
Compute the optimal axis length of the ellipse representing an eddy, using
an error function and its gradient.
Args:
f_error (function(a: float, b: float) = error: float) :
f_grad (function(a: float, b: float) = gradient: np) :
Returns:
a,b (float,float) : The optimal ellipse axis length.
"""
d0 = 1
a, b = 1, 1
epsilon = EDDY_AXIS_PRECISION + 1
new_err = f_error(a, b)
while epsilon > EDDY_AXIS_PRECISION:
da, db = d0, d0
err_a = new_err
grad_a = np.sign(f_grad(a, b)[0])
while (
f_error(a - grad_a * da, b) > err_a or a - grad_a * da < EDDY_MIN_AXIS_LEN
):
da /= 2.0
a -= grad_a * da
err_b = f_error(a, b)
grad_b = np.sign(f_grad(a, b)[1])
while (
f_error(a, b - grad_b * db) > err_b or b - grad_b * db < EDDY_MIN_AXIS_LEN
):
db /= 2.0
b -= grad_b * db
new_err = f_error(a, b)
epsilon = np.sqrt(da * da + db * db)
return a, b
def pts_is_in_ellipse(pts_list, a, b, angle, center):
"""Test if a point is inside an ellipse.
Args:
pts_list (ndarray(,2) of float) : The list of points to be tested.
a,b (float) : Ellipse axis length.
angle (float) : Angle between x and a axis.
center (ndarray(2)): Coordinates of the ellipse center.
Returns:
inside (ndarray() of bool) : The test result. The length is the same as
'pts_list' without the last one.
"""
centered_pts = np.array(pts_list)
centered_pts[:, 0] -= center[0]
centered_pts[:, 1] -= center[1]
rotation = np.array(
[[np.cos(angle), np.sin(angle)], [-np.sin(angle), np.cos(angle)]]
)
aligned_pts = np.dot(rotation, centered_pts.T)
return (aligned_pts[0, :] ** 2 / a ** 2 + aligned_pts[1, :] ** 2 / b ** 2) <= 1
def estimate_sea_level_center(
date,
center_degree,
aligned_points,
axis_len,
axis_dir,
angular_velocity,
theta,
stream_data_fname,
R=EQUATORIAL_EARTH_RADIUS,
):
"""Return of estimate of sea lever at center of eddy
Args:
date : the date on which the eddy is detected
steam_data_fname : name of the stream data file
center_degree : coordinate of the center of the eddy in degree
aligned_points : coordinate in referential of the eddy of all points of all streamlines of the eddy in degree
axis_len : Rx,Ry
cov_matrix: covariance matrix of aligned points
theta : angle of the eddy with the horizontal axis
R: equatorial earth radius
returns:
h0 : sea level at center of eddy (meter)
"""
# Loading data
data_set = nc.Dataset(stream_data_fname)
u_1day = data_set["uo"][date, 0, :]
v_1day = data_set["vo"][date, 0, :]
# Data sizes
# Data step size is 1/12 degree. Due to the C-grid format, an offset of
# -0.5*1/12 is added to the axis.
data_time_size, data_depth_size, data_lat_size, data_lon_size = np.shape(
data_set["uo"]
)
longitudes = np.array(data_set["longitude"]) - 1 / 24
latitudes = np.array(data_set["latitude"]) - 1 / 24
# Replace the mask (ie the ground areas) with a null vector field.
U = np.array(u_1day)
U[U == -32767] = 0
V = np.array(v_1day)
V[V == -32767] = 0
# Interpolize continuous u,v from the data array
u_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, U.T)
v_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, V.T)
# Setting coordinate in cartesian space
rotation_inv = np.array(
[[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
)
# Rx, Ry in meter
point_rx = np.array([axis_len[0], 0])
point_ry = np.array([0, axis_len[1]])
point_rx = np.dot(rotation_inv, point_rx.T).T
point_ry = np.dot(rotation_inv, point_ry.T).T
point_rx_meter = convert_from_degree_to_meter(point_rx, center_degree[1], R)
point_ry_meter = convert_from_degree_to_meter(point_ry, center_degree[1], R)
Rx = np.linalg.norm(point_rx_meter)
Ry = np.linalg.norm(point_ry_meter)
# Rx = axis_len[0]
# Ry = axis_len[1]
# point to use to compute h0 using max speed: speed is max at Rx or Ry
ymax = np.array([0, axis_len[1]])
# Setting coordinates in cartesian space in degree
ymax = np.dot(rotation_inv, ymax.T).T
ymax += center_degree
# Defining needed constant
f_corriolis = 10e-4
g_pesanteur = 9.82
# We compute h0 using the max value of the current at Ry
v_max = v_interpolized(ymax[0], ymax[1])
u_max = u_interpolized(ymax[0], ymax[1])
max_speed = np.sqrt(v_max ** 2 + u_max ** 2)
h0 = max_speed * f_corriolis * Ry / (g_pesanteur * np.exp(-0.5))
# if anti clockwise rotation, it is a cold eddy and sea level at center is below zero
if angular_velocity > 0:
h0 = -h0
h0 = float(h0)
# else, if clockwise rotation, it is a hot eddy and sea level at center is greater than zero
return h0
def convert_from_degree_to_meter(d_degree, lat, R=EQUATORIAL_EARTH_RADIUS):
"""Convert coordinate in degree to coordinate in meter using relations :
dy = pi * R * dlat / 180.
dx = pi * R * dlon / 180. * sin(lat*pi/180)
relation where dx,dy in meter and dlat,dlon in degrees
Args:
d_degree (dlon,dlat): differential of coordinate in degree in cartesian system. shape(2,) if center of an eddy, shape(1,2) otherwise
lat: latitude of one of the two points on which the differential is computed
R:equatorial earth radius in meter
Returns:
d_meter: differential in meter in cartesian system
"""
dlon, dlat = d_degree[0], d_degree[1]
d_meter = np.zeros(np.shape(d_degree))
if np.shape(d_degree) == (2,):
dlon, dlat = d_degree[0], d_degree[1]
d_meter[1] = np.pi * R * d_degree[1] / 180
d_meter[0] = np.pi * R * d_degree[0] / (180 * np.sin(lat * np.pi / 180))
d_meter[0] = np.pi * R * d_degree[0] * np.sin(lat * np.pi / 180) / 180
else:
dlon, dlat = d_degree[0, 0], d_degree[0, 1]
d_meter[0, 1] = np.pi * R * d_degree[0, 1] / 180
d_meter[0, 0] = np.pi * R * d_degree[0, 0] / (180 * np.sin(lat * np.pi / 180))
d_meter[0, 0] = np.pi * R * d_degree[0, 0] * np.sin(lat * np.pi / 180) / 180
return d_meter
def convert_from_meter_to_degree(d_meter, lat, R=EQUATORIAL_EARTH_RADIUS):
"""Convert a differential of coordinates from meter to dregree
d_meter=(dx,dy)
lat: latitude of one of the two points on which the differential is computed
"""
dx, dy = d_meter[0], d_meter[1]
d_degree = np.zeros(np.shape(d_meter))
if np.shape(d_degree) == (2,):
dx, dy = d_meter[0], d_meter[1]
d_degree[1] = d_meter[1] * 180 / (np.pi * R)
d_degree[0] = d_meter[0] * 180 / (np.sin(lat * np.pi / 180) * np.pi * R)
else:
dx, dy = d_meter[0, 0], d_meter[0, 1]
d_degree[0, 1] = d_meter[0, 1] * 180 / (np.pi * R)
d_degree[0, 0] = d_degree[0, 0] * 180 / (np.sin(lat * np.pi / 180) * np.pi * R)
return d_degree
def compute_u_v(points, theta, center_degree, axis_len, h0, R=EQUATORIAL_EARTH_RADIUS):
"""Compute the theorical value of u and v at a given point
Args:
points: ndarray(n,2) coordinate of points in the referential of the eddy in degree
theta : angle of the eddy with the horizontal axis
center_degree: coordinates of the center of the eddy in degree
Rx : value of the axes length along axis x in eddy referential
Ry : value of the axes length along axis y in eddy referential
h0 : sea level at the center of the eddy,
WARNING : x must be along the big axis and y along the small axis
Returns:
u : zonal current at the point
v : meridonal current at the point
"""
# Defining needed constant
f_corriolis = 10e-4
rho_sea = 1030
g_pesanteur = 9.82
# rotation matrix
rotation_inv = np.array(
[[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
)
"""
# Rx , Ry in meter
point_rx = np.array([axis_len[0], 0])
point_ry = np.array([0, axis_len[1]])
point_rx = np.dot(rotation_inv, point_rx.T).T
point_ry = np.dot(rotation_inv, point_ry.T).T
point_rx_meter = convert_from_degree_to_meter(point_rx, center_degree[1], R)
point_ry_meter = convert_from_degree_to_meter(point_ry, center_degree[1], R)
Rx = np.linalg.norm(point_rx_meter)
Ry = np.linalg.norm(point_ry_meter)
"""
Rx = axis_len[0]
Ry = axis_len[1]
# constant to compute sea level
a = np.cos(theta) ** 2 / (2 * Rx ** 2) + np.sin(theta) ** 2 / (2 * Ry ** 2)
b = -np.sin(2 * theta) / (4 * Rx ** 2) + np.sin(2 * theta) / (4 * Ry ** 2)
c = np.sin(theta) ** 2 / (2 * Rx ** 2) + np.cos(theta) ** 2 / (2 * Ry ** 2)
# Initializing u_v
n = len(points)
u_v = np.zeros((n, 2))
# Setting coordinates in cartesian space
points = np.dot(rotation_inv, points.T).T
points_meter = np.zeros((n, 2))
for i in range(n):
points_meter[i] = convert_from_degree_to_meter(points[i], center_degree[1], R)
dX, dY = points_meter[:, 0], points_meter[:, 1]
# Computing sea level
for i in range(n):
sea_level = h0 * np.exp(
-(a * (dX[i]) ** 2 - 2 * b * (dX[i]) * (dY[i]) + c * (dY[i]) ** 2)
)
u_v[i, 0] = (
-g_pesanteur * 2 * (b * (dX[i]) - c * (dY[i])) * sea_level / f_corriolis
)
u_v[i, 1] = (
g_pesanteur * 2 * (b * (dY[i]) - a * (dX[i])) * sea_level / f_corriolis
)
return u_v
def get_interpolized_u_v(points, date, center_degree, theta, stream_data_fname):
"""Get the interpolized value of u and v at point
Args:
point: ndarray(n,2) coordinate of point in the referential of the eddy in degree
date : the date on which the eddy is detected
center_degree : coordinate of center in degree
steam_data_fname : name of the stream data file
theta: angle of the eddy
"""
# Loading data
data_set = nc.Dataset(stream_data_fname)
u_1day = data_set["uo"][date, 0, :]
v_1day = data_set["vo"][date, 0, :]
# Data sizes
# Data step size is 1/12 degree. Due to the C-grid format, an offset of
# -0.5*1/12 is added to the axis.
data_time_size, data_depth_size, data_lat_size, data_lon_size = np.shape(
data_set["uo"]
)
longitudes = np.array(data_set["longitude"]) - 1 / 24
latitudes = np.array(data_set["latitude"]) - 1 / 24
# Replace the mask (ie the ground areas) with a null vector field.
U = np.array(u_1day)
U[U == -32767] = 0
V = np.array(v_1day)
V[V == -32767] = 0
# Interpolize continuous u,v from the data array
u_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, U.T)
v_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, V.T)
# Setting coordinate in degree in cartesian space
rotation_inv = np.array(
[[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
)
points = np.dot(rotation_inv, points.T).T
points += center_degree
n = len(points) # nbr of points
u_v_measured = np.zeros((n, 2))
for i in range(n):
u_v_measured[i, 0] = float(u_interpolized(points[i, 0], points[i, 1]))
u_v_measured[i, 1] = float(v_interpolized(points[i, 0], points[i, 1]))
return u_v_measured
def compute_error(u_v_evaluated, u_v_measured):
"""Compute the error between theorical value of u and v and measured values
Args:
point: on which to compute the error
u_v_evaluated: ndarray(1,2): thorical [u,v] values computed
u_v_measure: ndarray(1,2): measured [u,v] values
Return:
L1 error
L2 error
"""
L1 = np.zeros(len(u_v_evaluated))
for i in range(len(u_v_evaluated)):
L1[i] = (u_v_evaluated[i, 0] - u_v_measured[i, 0]) ** 2 + (
u_v_evaluated[i, 1] - u_v_measured[i, 1]
) ** 2
L1 = np.sum(L1)
return L1
def compute_grad_u_v(
points, theta, center_degree, axis_len, h0, R=EQUATORIAL_EARTH_RADIUS
):
"""Compute the gradient of u_evaluated and v_evaluated with respect to Rx and Ry"""
# Defining needed constant
f_corriolis = 10e-4
rho_sea = 1030
g_pesanteur = 9.82
# rotation matrix
rotation_inv = np.array(
[[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
)
"""
# approximate Rx, Ry in meter
point_rx = np.array([axis_len[0], 0])
point_ry = np.array([0, axis_len[1]])
point_rx = np.dot(rotation_inv, point_rx.T).T
point_ry = np.dot(rotation_inv, point_ry.T).T
point_rx_meter = convert_from_degree_to_meter(point_rx, center_degree[1], R)
point_ry_meter = convert_from_degree_to_meter(point_ry, center_degree[1], R)
Rx = np.linalg.norm(point_rx_meter)
Ry = np.linalg.norm(point_ry_meter)
"""
Rx = axis_len[0]
Ry = axis_len[1]
# constant to compute sea level
a = np.cos(theta) ** 2 / (2 * Rx ** 2) + np.sin(theta) ** 2 / (2 * Ry ** 2)
b = -np.sin(2 * theta) / (4 * Rx ** 2) + np.sin(2 * theta) / (4 * Ry ** 2)
c = np.sin(theta) ** 2 / (2 * Rx ** 2) + np.cos(theta) ** 2 / (2 * Ry ** 2)
# Initializing u_v
n = len(points)
grad_u = np.zeros((n, 2))
grad_v = np.zeros((n, 2))
# Setting coordinates in cartesian space
points = np.dot(rotation_inv, points.T).T
points_meter = np.zeros((n, 2))
for i in range(n):
points_meter[i] = convert_from_degree_to_meter(points[i], center_degree[1], R)
dX, dY = points_meter[:, 0], points_meter[:, 1]
# Computing sea level
for i in range(n):
sea_level = h0 * np.exp(
-(a * (dX[i]) ** 2 - 2 * b * (dX[i]) * (dY[i]) + c * (dY[i]) ** 2)
)
h = -g_pesanteur * 2 * (b * (dX[i]) - c * (dY[i])) / f_corriolis
g = g_pesanteur * 2 * (b * (dY[i]) - a * (dX[i])) / f_corriolis
hprime_x = (
-2
* g_pesanteur
* (
np.sin(2 * theta) * dX[i] / (2 * Rx ** 3)
+ (np.sin(theta) ** 2) * dY[i] / (Rx ** 3)
)
)
hprime_y = (
-2
* g_pesanteur
* (
-np.sin(2 * theta) * dX[i] / (2 * Ry ** 3)
+ (np.cos(theta) ** 2) * dY[i] / (Ry ** 3)
)
)
gprime_x = (
-2
* g_pesanteur
* (
np.sin(2 * theta) * dY[i] / (2 * Rx ** 3)
+ (np.cos(theta) ** 2) * dX[i] / (Rx ** 3)
)
)
gprime_y = (
-2
* g_pesanteur
* (
-np.sin(2 * theta) * dY[i] / (2 * Ry ** 3)
+ (np.sin(theta) ** 2) * dX[i] / (Ry ** 3)
)
)
sea_level_prime_x = (
(
(np.cos(theta) * dX[i]) ** 2
+ np.sin(2 * theta) * dX[i] * dY[i]
+ (np.sin(theta) * dY[i]) ** 2
)
* sea_level
/ (Rx ** 3)
) * sea_level
sea_level_prime_y = (
(
(np.sin(theta) * dX[i]) ** 2
- np.sin(2 * theta) * dX[i] * dY[i]
+ (np.cos(theta) * dY[i]) ** 2
)
* sea_level
/ (Ry ** 3)
) * sea_level
grad_u[i, 0] = hprime_x * sea_level + h * sea_level_prime_x
grad_u[i, 1] = hprime_y * sea_level + h * sea_level_prime_y
grad_v[i, 0] = gprime_x * sea_level + g * sea_level_prime_x
grad_v[i, 1] = gprime_y * sea_level + g * sea_level_prime_y
return grad_u, grad_v
def compute_gradL1(u_v_evaluated, u_v_measured, grad_u, grad_v):
"""Compute the gradient of L1 with respect to Rx and Ry"""
gradL1 = np.zeros((2, 1))
n = len(u_v_evaluated)
gradL1_x = 2 * np.sum(
(u_v_evaluated[:, 0] - u_v_measured[:, 0]) * grad_u[:, 0]
+ (u_v_evaluated[:, 1] - u_v_measured[:, 1]) * grad_v[:, 0]
)
gradL1_y = 2 * np.sum(
(u_v_evaluated[:, 0] - u_v_measured[:, 0]) * grad_u[:, 1]
+ (u_v_evaluated[:, 1] - u_v_measured[:, 1]) * grad_v[:, 1]
)
gradL1[0] = gradL1_x
gradL1[1] = gradL1_y
return gradL1
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines the functions used for writting and reading
the caltalog as a csv file."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = ["<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>"]
import numpy as np
import pandas as pd
def write_catalog(data,fname="./catalog.csv"):
""" Convert observations and tracking of eddies into a csv file.
Observations and tracking of eddies are expected to be of the same format as
the results of the function 'eddies_tracking.eddies_tracker'.
Args:
fname (string, default = "./catalog.csv") : The file name in which the
catalog is saved.
data (dict(int : dict(int : classes.Eddy))) : The path of eddies.
A unique id is assigned to each eddy so that 2 object 'classes.Eddy'
share the same id if and only if they represent the same eddy at
different dates. The first key is a date, the second key is the eddy
identifier.
Returns:
df (pandas.Dataframe) : The data frame as it as been saved.
"""
# Organise the data in a list.
rows = []
for date,eddies in data.items():
for eddy_id,eddy in eddies.items():
angle = np.angle(eddy.axis_dir[0,0]+eddy.axis_dir[1,0]*1j)
rows.append([date,eddy_id,eddy.center[0],eddy.center[1],
eddy.axis_len[0],eddy.axis_len[1],angle,
eddy.angular_velocity])
# Same the dataframe as a csv file.
df = pd.DataFrame(rows,index=None,columns=['date','id','center_x','center_y','a','b','angle','omega'])
df.to_csv(fname)
return df<file_sep>#!/usr/bin/env python
""" AnDA_data_assimilation.py: Apply stochastic and sequential data assimilation technics using model forecasting or analog forecasting. """
__author__ = "<NAME> and <NAME>"
__version__ = "1.0"
__date__ = "2016-10-16"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import numpy as np
from scipy.stats import multivariate_normal
from AnDA.AnDA_tools import resampleMultinomial, inv_using_SVD
from tqdm import tqdm
def AnDA_data_assimilation(yo, DA):
""" Apply stochastic and sequential data assimilation technics using model forecasting or analog forecasting. """
# initializations
n = len(DA.xb)
T = yo.values.shape[0]
class x_hat:
part = np.zeros([T, DA.N, n])
weights = np.zeros([T, DA.N])
values = np.zeros([T, n])
time = yo.time
if DA.method == "AnEnKF" or DA.method == "AnEnKS":
m_xa_part = np.zeros([T, DA.N, n])
xf_part = np.zeros([T, DA.N, n])
Pf = np.zeros([T, n, n])
for k in tqdm(range(0, T)):
# update step (compute forecasts)
if k == 0:
xf = np.random.multivariate_normal(DA.xb, DA.B, DA.N)
else:
xf, m_xa_part_tmp = DA.m(x_hat.part[k - 1, :, :])
m_xa_part[k, :, :] = m_xa_part_tmp
xf_part[k, :, :] = xf
Ef = np.dot(xf.T, np.eye(DA.N) - np.ones([DA.N, DA.N]) / DA.N)
Pf[k, :, :] = np.dot(Ef, Ef.T) / (DA.N - 1)
# analysis step (correct forecasts with observations)
i_var_obs = np.where(~np.isnan(yo.values[k, :]))[0]
if len(i_var_obs) > 0:
eps = np.random.multivariate_normal(
np.zeros(len(i_var_obs)),
DA.R[np.ix_(i_var_obs, i_var_obs)],
DA.N,
)
yf = np.dot(DA.H[i_var_obs, :], xf.T)
yf = yf.T
K = np.dot(
np.dot(Pf[k, :, :], DA.H[i_var_obs, :].T),
np.linalg.inv(
np.dot(
np.dot(DA.H[i_var_obs, :], Pf[k, :, :]),
DA.H[i_var_obs, :].T,
)
+ DA.R[np.ix_(i_var_obs, i_var_obs)]
),
)
d = (
np.repeat(yo.values[k, i_var_obs][np.newaxis], DA.N, 0)
+ eps
- yf
)
x_hat.part[k, :, :] = xf + np.dot(d, K.T)
else:
x_hat.part[k, :, :] = xf
x_hat.weights[k, :] = np.repeat(1.0 / DA.N, DA.N)
x_hat.values[k, :] = np.sum(
x_hat.part[k, :, :]
* np.repeat(x_hat.weights[k, :][np.newaxis], n, 0).T,
0,
)
# end AnEnKF
if DA.method == "AnEnKS":
for k in tqdm(range(T - 1, -1, -1)):
if k == T - 1:
x_hat.part[k, :, :] = x_hat.part[T - 1, :, :]
else:
m_xa_part_tmp = m_xa_part[k + 1, :, :]
tej, m_xa_tmp = DA.m(
np.mean(x_hat.part[k, :, :], 0)[np.newaxis]
)
tmp_1 = (
x_hat.part[k, :, :]
- np.repeat(
np.mean(x_hat.part[k, :, :], 0)[np.newaxis],
DA.N,
0,
)
).T
tmp_2 = m_xa_part_tmp - np.repeat(m_xa_tmp, DA.N, 0)
Ks = (
1.0
/ (DA.N - 1)
* np.dot(
np.dot(tmp_1, tmp_2),
inv_using_SVD(Pf[k + 1, :, :], 0.9999),
)
)
x_hat.part[k, :, :] = x_hat.part[k, :, :] + np.dot(
x_hat.part[k + 1, :, :] - xf_part[k + 1, :, :], Ks.T
)
x_hat.values[k, :] = np.sum(
x_hat.part[k, :, :]
* np.repeat(x_hat.weights[k, :][np.newaxis], n, 0).T,
0,
)
# end AnEnKS
elif DA.method == "AnPF":
# special case for k=1
k = 0
k_count = 0
m_xa_traj = []
weights_tmp = np.zeros(DA.N)
xf = np.random.multivariate_normal(DA.xb, DA.B, DA.N)
i_var_obs = np.where(~np.isnan(yo.values[k, :]))[0]
if len(i_var_obs) > 0:
# weights
for i_N in range(0, DA.N):
weights_tmp[i_N] = multivariate_normal.pdf(
yo.values[k, i_var_obs].T,
np.dot(DA.H[i_var_obs, :], xf[i_N, :].T),
DA.R[np.ix_(i_var_obs, i_var_obs)],
)
# normalization
weights_tmp = weights_tmp / np.sum(weights_tmp)
# resampling
indic = resampleMultinomial(weights_tmp)
x_hat.part[k, :, :] = xf[indic, :]
weights_tmp_indic = weights_tmp[indic] / sum(weights_tmp[indic])
x_hat.values[k, :] = sum(
xf[indic, :]
* (np.repeat(weights_tmp_indic[np.newaxis], n, 0).T),
0,
)
# find number of iterations before new observation
k_count_end = np.min(
np.where(np.sum(1 * ~np.isnan(yo.values[k + 1 :, :]), 1) >= 1)[
0
]
)
else:
# weights
weights_tmp = np.repeat(1.0 / DA.N, DA.N)
# resampling
indic = resampleMultinomial(weights_tmp)
x_hat.weights[k, :] = weights_tmp_indic
for k in tqdm(range(1, T)):
# update step (compute forecasts) and add small Gaussian noise
xf, tej = DA.m(
x_hat.part[k - 1, :, :]
) + np.random.multivariate_normal(
np.zeros(xf.shape[1]), DA.B / 100.0, xf.shape[0]
)
if k_count < len(m_xa_traj):
m_xa_traj[k_count] = xf
else:
m_xa_traj.append(xf)
k_count = k_count + 1
# analysis step (correct forecasts with observations)
i_var_obs = np.where(~np.isnan(yo.values[k, :]))[0]
if len(i_var_obs) > 0:
# weights
for i_N in range(0, DA.N):
weights_tmp[i_N] = multivariate_normal.pdf(
yo.values[k, i_var_obs].T,
np.dot(DA.H[i_var_obs, :], xf[i_N, :].T),
DA.R[np.ix_(i_var_obs, i_var_obs)],
)
# normalization
weights_tmp = weights_tmp / np.sum(weights_tmp)
# resampling
indic = resampleMultinomial(weights_tmp)
# stock results
x_hat.part[k - k_count_end : k + 1, :, :] = np.asarray(
m_xa_traj
)[:, indic, :]
weights_tmp_indic = weights_tmp[indic] / np.sum(
weights_tmp[indic]
)
x_hat.values[k - k_count_end : k + 1, :] = np.sum(
np.asarray(m_xa_traj)[:, indic, :]
* np.tile(
weights_tmp_indic[np.newaxis].T,
(k_count_end + 1, 1, n),
),
1,
)
k_count = 0
# find number of iterations before new observation
try:
k_count_end = np.min(
np.where(
np.sum(1 * ~np.isnan(yo.values[k + 1 :, :]), 1)
>= 1
)[0]
)
except ValueError:
pass
else:
# stock results
x_hat.part[k, :, :] = xf
x_hat.values[k, :] = np.sum(
xf * np.repeat(weights_tmp_indic[np.newaxis], n, 0).T, 0
)
# stock weights
x_hat.weights[k, :] = weights_tmp_indic
# end AnPF
else:
print("Error: choose DA.method between 'AnEnKF', 'AnEnKS', 'AnPF' ")
quit()
return x_hat
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file gathers the functions used for measuring abstract
distances and similarities."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
import numpy as np
from tools import pts_is_in_ellipse
from constants import JACCARD_RESOLUTION
def eddies_jaccard_index(e1, e2, resolution=JACCARD_RESOLUTION):
"""Compute the Jaccard index of 2 eddies represented by ellipses.
The ellipse parameters are the center of the eddy and the axis length and
direction. The suface of the intersection is computed using finit elements.
Args:
e1, e2 (classes.Eddy) : The eddies for which the Jaccard index in computed.
Returns:
index (float) : The Jaccard index of the 2 ellipses.
"""
max_r1 = max(e1.axis_len)
max_r2 = max(e2.axis_len)
if max_r1 > max_r2:
return eddies_jaccard_index(e2, e1)
# Ellipse 1 parameters.
a1, b1 = e1.axis_len
surface_e1 = a1 * b1 * np.pi
angle1 = np.angle(e1.axis_dir[0, 0] + 1j * e1.axis_dir[1, 0])
# Ellipse 2 parameters.
a2, b2 = e2.axis_len
surface_e2 = a2 * b2 * np.pi
angle2 = np.angle(e2.axis_dir[0, 0] + 1j * e2.axis_dir[1, 0])
# Generate a list of points for computing the intersecton surface with
# finit elements.
nb_points = resolution
x = np.linspace(e1.center[0] - max_r1, e1.center[0] + max_r1, nb_points)
y = np.linspace(e1.center[1] - max_r1, e1.center[1] + max_r1, nb_points)
xx, yy = np.meshgrid(x, y)
points_list = np.array(list(zip(xx.flatten(), yy.flatten())))
# Surface represented by a points.
ds = (2 * max_r1 / nb_points) ** 2
# Count the number of points in the intersection.
inside_e1 = pts_is_in_ellipse(points_list, a1, b1, angle1, e1.center)
points_in_e1 = points_list[inside_e1]
inside_e1_and_e1 = pts_is_in_ellipse(
points_in_e1, a2, b2, angle2, e2.center
)
surface_e1_and_e2 = ds * np.sum(inside_e1_and_e1)
index = surface_e1_and_e2 / (surface_e1 + surface_e2 - surface_e1_and_e2)
return index
<file_sep># Projet_3A_IMTA
This repository countain the ressources of our 3rd year project:
- the code in ./code/
- tutorials to use the code in ./code/tutos/
- raw data in ./code/data/, downloaded from https://resources.marine.copernicus.eu/?option=com_csw&view=details&product_id=GLOBAL_ANALYSIS_FORECAST_PHY_001_024
- presentation and results of the project in ./code/Rapport projet.pdf
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines the functions used for streamlines
computation, processing and clustering and eddies detection."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = [
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
]
import netCDF4 as nc
import numpy as np
import os
import scipy.integrate as sp_integ
import scipy.interpolate as sp_interp
from parcels import FieldSet, ParticleSet, ScipyParticle, ErrorCode
from parcels import AdvectionAnalytical, AdvectionRK4
from datetime import timedelta as delta
from tqdm import trange
from classes import StreamLine, Eddy
from constants import EQUATORIAL_EARTH_RADIUS, MIN_STREAMLINE_IN_EDDIES
from constants import EDDY_MIN_RADIUS
def get_traj_with_parcels(
date, runtime, delta_time, particle_grid_step, stream_data_fname
):
"""Compute trajectories of particles in the sea using parcels library.
Compute trajectories of particles in the sea at a given date, in a static 2D
field of stream using Runge Kutta 4th order algorithm.
Args:
date (int) : Day in number of days relatively to the data time origin at
which the stream data should be taken.
runtime (int) : Total duration in hours of the field integration.
Trajectories length increases with the runtime.
delta_time (int) : Time step in hours of the integration.
particle_grid_step (int) : Grid step size for the initial positions of
the particles. The unit is the data index step, ie data dx and dy.
stream_data_fname (str) : Complete name of the stream data file.
Returns:
stream_line_list (list of classes.StreamLine) : The list of trajectories.
Notes:
The input file is expected to contain the daily mean fields of east- and
northward ocean current velocity (uo,vo) in a format as described here:
http://marine.copernicus.eu/documents/PUM/CMEMS-GLO-PUM-001-024.pdf.
"""
# Loading data
data_set = nc.Dataset(stream_data_fname)
u_1day = data_set["uo"][date, 0, :]
v_1day = data_set["vo"][date, 0, :]
# Data sizes
data_time_size, data_depth_size, data_lat_size, data_lon_size = np.shape(
data_set["uo"]
)
longitudes = np.array(data_set["longitude"])
latitudes = np.array(data_set["latitude"])
# Replace the mask (ie the ground areas) with a null vector field.
U = np.array(u_1day)
U[U == -32767] = 0
V = np.array(v_1day)
V[V == -32767] = 0
# Initialize a field set using the data set.
data = {"U": U, "V": V}
dimensions = {"lon": longitudes, "lat": latitudes}
fieldset = FieldSet.from_data(data, dimensions, mesh="spherical")
fieldset.U.interp_method = "cgrid_velocity"
fieldset.V.interp_method = "cgrid_velocity"
# List of initial positions of the particles. Particles on the ground are
# removed.
init_pos = []
for lon in range(0, data_lon_size, particle_grid_step):
for lat in range(0, data_lat_size, particle_grid_step):
if not u_1day[lat, lon] is np.ma.masked:
init_pos.append([longitudes[lon], latitudes[lat]])
init_pos = np.array(init_pos)
init_longitudes = init_pos[:, 0]
init_latitudes = init_pos[:, 1]
# Initialize particle set
pSet = ParticleSet.from_list(
fieldset, ScipyParticle, init_longitudes, init_latitudes, depth=None, time=None
)
# Initialize output file and run simulation
def DeleteParticle(particle, fieldset, time):
particle.delete()
output = pSet.ParticleFile(
name="trajectories_temp.nc", outputdt=delta(hours=delta_time)
)
pSet.execute(
AdvectionRK4,
runtime=delta(hours=runtime),
dt=np.inf,
output_file=output,
recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle},
)
output.close()
# Load simulation results and create the stream line list
nc_traj = nc.Dataset("trajectories_temp.nc")
trajectories = np.zeros(
(nc_traj.dimensions["traj"].size, nc_traj.dimensions["obs"].size, 2)
)
trajectories[:, :, 0] = np.array(nc_traj["lon"])
trajectories[:, :, 1] = np.array(nc_traj["lat"])
stream_line_list = []
for trajectory in trajectories:
stream_line_list.append(
StreamLine(trajectory[np.isfinite(trajectory[:, 0])], delta_time * 3600)
)
# Clean working dir
os.system("rm -r trajectories_temp*")
return stream_line_list
def get_traj_with_scipy(
date,
runtime,
max_delta_time,
particle_grid_step,
stream_data_fname,
R=EQUATORIAL_EARTH_RADIUS,
):
"""Compute trajectories of particles in the sea using scipy library.
Compute trajectories of particles in the sea at a given date, in a static 2D
field of stream using Runge Kutta 4th order algorithm.
Args:
date (int) : Day in number of days relatively to the data time origin at
which the stream data should be taken.
runtime (int) : Total duration in hours of the field integration.
Trajectories length increases with the runtime.
max_delta_time (int) : Maximum time step in hours of the integration.
The integration function used can use smaller time step if needed.
particle_grid_step (int) : Grid step size for the initial positions of
the particles. The unit is the data index step, ie data dx and dy.
stream_data_fname (str) : Complete name of the stream data file.
R (float) : Radius of the Earth in meter in the data area. The exact
value can be used to reduce Earth shape related conversion and
computation error. Default is the equatorial radius.
Returns:
stream_line_list (list of classes.StreamLine) : The list of trajectories.
Notes:
The input file is expected to contain the daily mean fields of east- and
northward ocean current velocity (uo,vo) in a format as described here:
http://marine.copernicus.eu/documents/PUM/CMEMS-GLO-PUM-001-024.pdf.
"""
# Loading data
data_set = nc.Dataset(stream_data_fname)
u_1day = data_set["uo"][date, 0, :]
v_1day = data_set["vo"][date, 0, :]
# Data sizes
# Data step size is 1/12 degree. Due to the C-grid format, an offset of
# -0.5*1/12 is added to the axis.
data_time_size, data_depth_size, data_lat_size, data_lon_size = np.shape(
data_set["uo"]
)
longitudes = np.array(data_set["longitude"]) - 1 / 24
latitudes = np.array(data_set["latitude"]) - 1 / 24
# Replace the mask (ie the ground areas) with a null vector field.
U = np.array(u_1day)
U[U == -32767] = 0
V = np.array(v_1day)
V[V == -32767] = 0
# Conversion of u and v from m.s**-1 to degree.s**-1
conversion_coeff = 360 / (2 * np.pi * R)
U *= conversion_coeff
V *= conversion_coeff
for lat in range(data_lat_size):
U[lat, :] *= 1 / np.cos(latitudes[lat] / 360)
# Interpolize continuous u,v from the data array
u_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, U.T)
v_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, V.T)
def stream(t, pos_vect):
# pos = (long,lat)
u = u_interpolized.ev(pos_vect[0], pos_vect[1])
v = v_interpolized.ev(pos_vect[0], pos_vect[1])
return np.array([u, v])
# List of initial positions of the particles. Particles on the ground are
# removed.
init_pos = []
for lon in range(0, data_lon_size, particle_grid_step):
for lat in range(0, data_lat_size, particle_grid_step):
if not u_1day[lat, lon] is np.ma.masked:
init_pos.append([longitudes[lon], latitudes[lat]])
init_pos = np.array(init_pos)
nb_stream_line = len(init_pos)
# Integrate each positions
stream_line_list = []
for sl_id in trange(nb_stream_line,desc="Integration"):
coord_list = [np.array(init_pos[sl_id])]
dt_list = []
previous_t = 0
integration_instance = sp_integ.RK45(
stream,
0,
init_pos[sl_id],
runtime * 3600,
rtol=1e-4,
atol=1e-7,
max_step=max_delta_time * 3600,
)
# Integrate the trajectory dt by dt
while integration_instance.status == "running":
previous_pt = coord_list[-1]
is_between_limit_lat = latitudes[0] <= previous_pt[1] <= latitudes[-1]
is_between_limit_long = longitudes[0] <= previous_pt[0] <= longitudes[-1]
if is_between_limit_lat and is_between_limit_long:
integration_instance.step()
coord_list.append(integration_instance.y)
else:
integration_instance.status = "finished"
coord_list.append(previous_pt)
dt_list.append(integration_instance.t - previous_t)
previous_t = integration_instance.t
dt_list = np.array(dt_list)
stream_line_list.append(StreamLine(coord_list, dt_list))
return stream_line_list
def get_traj_with_numpy(
date,
runtime,
delta_time,
particle_grid_step,
stream_data_fname,
R=EQUATORIAL_EARTH_RADIUS,
):
"""Compute trajectories of particles in the sea using only numpy library.
Compute trajectories of particles in the sea at a given date, in a static 2D
field of stream using Runge Kutta 4th order algorithm.
Args:
date (int) : Day in number of days relatively to the data time origin at
which the stream data should be taken.
runtime (int) : Total duration in hours of the field integration.
Trajectories length increases with the runtime.
delta_time (int) : Maximum time step in hours of the integration.
The integration function used can use smaller time step if needed.
particle_grid_step (int) : Grid step size for the initial positions of
the particles. The unit is the data index step, ie data dx and dy.
stream_data_fname (str) : Complete name of the stream data file.
R (float) : Radius of the Earth in meter in the data area. The exact
value can be used to reduce Earth shape related conversion and
computation error. Default is the equatorial radius.
Returns:
stream_line_list (list of classes.StreamLine) : The list of trajectories.
Notes:
The input file is expected to contain the daily mean fields of east- and
northward ocean current velocity (uo,vo) in a format as described here:
http://marine.copernicus.eu/documents/PUM/CMEMS-GLO-PUM-001-024.pdf.
"""
# Loading data
data_set = nc.Dataset(stream_data_fname)
u_1day = data_set["uo"][date, 0, :]
v_1day = data_set["vo"][date, 0, :]
# Data sizes
# Data step size is 1/12 degree. Due to the C-grid format, an offset of
# -0.5*1/12 is added to the axis.
data_time_size, data_depth_size, data_lat_size, data_lon_size = np.shape(
data_set["uo"]
)
longitudes = np.array(data_set["longitude"]) - 1 / 24
latitudes = np.array(data_set["latitude"]) - 1 / 24
# Replace the mask (ie the ground areas) with a null vector field.
U = np.array(u_1day)
U[U == -32767] = 0
V = np.array(v_1day)
V[V == -32767] = 0
# Conversion of u and v from m.s**-1 to degree.s**-1
conversion_coeff = 360 / (2 * np.pi * R)
U *= conversion_coeff
V *= conversion_coeff
for lat in range(data_lat_size):
U[lat, :] *= 1 / np.cos(latitudes[lat] / 360)
# Interpolize continuous u,v from the data array
u_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, U.T)
v_interpolized = sp_interp.RectBivariateSpline(longitudes, latitudes, V.T)
def stream(pos_vect):
# pos = (long,lat)
u = u_interpolized.ev(pos_vect[0], pos_vect[1])
v = v_interpolized.ev(pos_vect[0], pos_vect[1])
return np.array([u, v])
# List of initial positions of the particles. Particles on the ground are
# removed.
init_pos = []
for lon in range(0, data_lon_size, particle_grid_step):
for lat in range(0, data_lat_size, particle_grid_step):
if not u_1day[lat, lon] is np.ma.masked:
init_pos.append([longitudes[lon], latitudes[lat]])
init_pos = np.array(init_pos)
nb_sl = len(init_pos)
# Integration dt by dt, over the 'runtime' duration
dt = 3600 * delta_time
nb_step = int(runtime / delta_time)
sl_array = np.zeros((nb_step + 1, nb_sl, 2))
sl_array[0, :, :] = np.array(init_pos)
def rk_4(pos):
if np.isnan(pos[0]):
return np.nan * np.zeros(2)
if not (latitudes[0] <= pos[1] <= latitudes[-1]):
return np.nan * np.zeros(2)
if not (longitudes[0] <= pos[0] <= longitudes[-1]):
return np.nan * np.zeros(2)
k1 = dt * stream(pos)
k2 = dt * stream(pos + k1 * 0.5)
k3 = dt * stream(pos + k2 * 0.5)
k4 = dt * stream(pos + k3)
return pos + 1 / 6 * (k1 + k4 + 2 * (k2 + k3))
rk_4_vectorized = np.vectorize(rk_4, signature="(n)->(n)")
for step in trange(nb_step,desc="Integration"):
sl_array[step + 1, :, :] = rk_4_vectorized(sl_array[step, :, :])
sl_list = []
for k in range(nb_sl):
sl_list.append(
StreamLine(sl_array[np.isfinite(sl_array[:, k, 0]), k, :], dt)
) # ,cut_lines=False))
return sl_list
def find_eddies(stream_line_list, date=0):
"""Classify stream lines into eddies.
All the stream lines with a winding angle lower than 2 pi are discarded. If
the distance between the mean pos of the stream line and an eddy center is
lower than the mean distance between the mean pos of the stream line and the
points in the stream line (ie lower that the mean radius, if the stream line
is considered to be an ellipse), this stream line is added to the eddy. The
new center of the eddy is computed. Otherwise the stream line is added to a
new eddy. When all the stream lines have been assigned to an eddy, the
eddies containing less than 2 (TBD ?) stream lines are discarded.
Args:
stream_line_list (list of classes.StreamLine) : The list of trajectories
to be classified into eddies.
date (int, default=0) : date at which the trajectories are simulated.
Returns:
eddies_list (list of classes.Eddy) : The list of eddies.
Notes:
The input file is expected to contain the daily mean fields of east- and
northward ocean current velocity (uo,vo) in a format as described here:
http://marine.copernicus.eu/documents/PUM/CMEMS-GLO-PUM-001-024.pdf.
"""
# Find a first streamline with a winding angle higher than 2 pi for init
nb_sl = len(stream_line_list)
if nb_sl == 0:
return []
k0 = 0
sl = stream_line_list[k0]
while abs(sl.winding_angle) < 2 * np.pi * 0.9 and k0 < nb_sl - 1:
k0 += 1
sl = stream_line_list[k0]
if nb_sl == k0:
return []
sl0 = stream_line_list[k0]
pre_eddies_list = [[sl0]]
pre_eddies_center = [sl0.mean_pos]
pre_eddies_max_radius = [sl0.get_mean_radius()]
# Put each streamline into an eddy if the winding angle is greater than 2 pi
for k in range(k0 + 1, len(stream_line_list)):
sl = stream_line_list[k]
if abs(sl.winding_angle) < 2 * np.pi * 0.9:
continue
# Mean radius of the stream line
mean_radius = sl.get_mean_radius()
# Minimum distance between a stream line center and pre eddies centers
distances = np.array(pre_eddies_center)
distances[:, 0] -= sl.mean_pos[0]
distances[:, 1] -= sl.mean_pos[1]
distances = np.sqrt(np.sum(distances ** 2, axis=1))
id_min = np.argmin(distances)
min_dist = distances[id_min]
# If the stream line center is close enougth from a pre eddy center, it
# is added to the pre eddy.
if mean_radius > min_dist or pre_eddies_max_radius[id_min] > min_dist:
pre_eddies_list[id_min].append(sl)
n = len(pre_eddies_list[id_min])
sl_center = np.array(
[pre_eddies_list[id_min][k].mean_pos for k in range(n)]
)
sl_nb_pts = np.array(
[pre_eddies_list[id_min][k].nb_points for k in range(n)]
)
sl_wcenter = [sl_center[k] * sl_nb_pts[k] for k in range(n)]
pre_eddies_center[id_min] = np.sum(sl_wcenter, axis=0) / np.sum(sl_nb_pts)
if min_dist > pre_eddies_max_radius[id_min]:
pre_eddies_max_radius[id_min] = min_dist
# A new eddy is created otherwise
else:
pre_eddies_list.append([sl])
pre_eddies_center.append(sl.mean_pos)
pre_eddies_max_radius.append(sl.get_mean_radius())
# Remove pre eddies without enougth stream lines or with a too small radius
eddies_list = []
for pre_eddy in pre_eddies_list:
if len(pre_eddy) >= MIN_STREAMLINE_IN_EDDIES:
eddy = Eddy(pre_eddy, date)
if np.sqrt(np.sum(eddy.axis_len ** 2)) > EDDY_MIN_RADIUS:
eddies_list.append(eddy)
return eddies_list<file_sep>#!/usr/bin/env python
""" AnDA_analog_forecasting.py: Apply the analog method on catalog of historical data to generate forecasts. """
__author__ = "<NAME> and <NAME>"
__version__ = "1.0"
__date__ = "2016-10-16"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import numpy as np
from AnDA.AnDA_tools import mk_stochastic
def AnDA_analog_forecasting(x, AF):
""" Apply the analog method on catalog of historical data to generate forecasts. """
# initializations
N, n = x.shape
xf = np.zeros([N, n])
xf_mean = np.zeros([N, n])
i_var_neighboor = np.arange(0, n)
i_var = np.arange(0, n)
# find the indices and distances of the k-nearest neighbors (knn)
dist_knn, index_knn = AF.search_neighbors(x)
# normalisation parameter for the kernels
lambdaa = np.median(dist_knn)
# compute weights
if AF.k == 1:
weights = np.ones([N, 1])
else:
weights = mk_stochastic(np.exp(-np.power(dist_knn, 2) / lambdaa))
# for each member/particle
for i_N in range(0, N):
xf_tmp = np.zeros([AF.k, np.max(i_var) + 1])
# select the regression method
if AF.regression == "locally_constant":
xf_tmp[:, i_var] = AF.catalog.successors[
np.ix_(index_knn[i_N, :], i_var)
]
# weighted mean and covariance
xf_mean[i_N, i_var] = np.sum(
xf_tmp[:, i_var]
* np.repeat(weights[i_N, :][np.newaxis].T, len(i_var), 1),
0,
)
E_xf = (
xf_tmp[:, i_var]
- np.repeat(xf_mean[i_N, i_var][np.newaxis], AF.k, 0)
).T
cov_xf = (
1.0
/ (1.0 - np.sum(np.power(weights[i_N, :], 2)))
* np.dot(
np.repeat(weights[i_N, :][np.newaxis], len(i_var), 0)
* E_xf,
E_xf.T,
)
)
elif AF.regression == "increment":
xf_tmp[:, i_var] = (
np.repeat(x[i_N, i_var][np.newaxis], AF.k, 0)
+ AF.catalog.successors[np.ix_(index_knn[i_N, :], i_var)]
- AF.catalog.analogs[np.ix_(index_knn[i_N, :], i_var)]
)
# weighted mean and covariance
xf_mean[i_N, i_var] = np.sum(
xf_tmp[:, i_var]
* np.repeat(weights[i_N, :][np.newaxis].T, len(i_var), 1),
0,
)
E_xf = (
xf_tmp[:, i_var]
- np.repeat(xf_mean[i_N, i_var][np.newaxis], AF.k, 0)
).T
cov_xf = (
1.0
/ (1 - np.sum(np.power(weights[i_N, :], 2)))
* np.dot(
np.repeat(weights[i_N, :][np.newaxis], len(i_var), 0)
* E_xf,
E_xf.T,
)
)
elif AF.regression == "local_linear":
# NEW VERSION (USING PCA)
# pca with weighted observations
mean_x = np.sum(
AF.catalog.analogs[np.ix_(index_knn[i_N, :], i_var_neighboor)]
* np.repeat(
weights[i_N, :][np.newaxis].T, len(i_var_neighboor), 1
),
0,
)
analog_centered = AF.catalog.analogs[
np.ix_(index_knn[i_N, :], i_var_neighboor)
] - np.repeat(mean_x[np.newaxis], AF.k, 0)
analog_centered = analog_centered * np.repeat(
np.sqrt(weights[i_N, :])[np.newaxis].T, len(i_var_neighboor), 1
)
U, S, V = np.linalg.svd(analog_centered, full_matrices=False)
coeff = V.T[:, 0:5]
W = np.sqrt(np.diag(weights[i_N, :]))
A = np.insert(
np.dot(
AF.catalog.analogs[
np.ix_(index_knn[i_N, :], i_var_neighboor)
],
coeff,
),
0,
1,
1,
)
Aw = np.dot(W, A)
B = AF.catalog.successors[np.ix_(index_knn[i_N, :], i_var)]
Bw = np.dot(W, B)
mu = np.dot(
np.insert(np.dot(x[i_N, i_var_neighboor], coeff), 0, 1),
np.linalg.lstsq(Aw, Bw)[0],
)
pred = np.dot(A, np.linalg.lstsq(A, B)[0])
res = B - pred
xf_tmp[:, i_var] = np.tile(mu, (AF.k, 1)) + res
# weighted mean and covariance
xf_mean[i_N, i_var] = mu
if len(i_var) > 1:
cov_xf = np.cov(res.T)
else:
cov_xf = np.cov(res.T)[np.newaxis][np.newaxis]
# constant weights for local linear
weights[i_N, :] = 1.0 / len(weights[i_N, :])
else:
print(
"Error: choose AF.regression between 'locally_constant', 'increment', 'local_linear' "
)
quit()
# random sampling from the multivariate Gaussian distribution
xf[i_N, i_var] = np.random.multivariate_normal(
xf_mean[i_N, i_var], cov_xf
)
return xf, xf_mean
# end
<file_sep># -*- coding: utf-8 -*-
"""classes.py: This file defines defines the functions used for tracking eddies
position over several days."""
__author__ = "<NAME>, <NAME>, <NAME>, <NAME>, <NAME>"
__date__ = "December 2020"
__version__ = "1.0"
__maintainer__ = "Not maintened"
__email__ = ["<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>",
"<EMAIL>"]
import numpy as np
def eddies_tracker(initial_date, list_days, metric_name='Jaccard',nb_prev_day=5,min_detection=5):
""" Identify which eddies are the same over several days.
Args:
initial_date (int) : Date of the first day in list_days.
list_days (list of list of classes.Eddy) : The first index is a date
relative to the parameter 'initial_date'. The elements are the list
of detected eddies at the corresponding data.
metric_name (str, default='Jaccard') : The metric to use for matching
eddies position on consecutive days.
nb_prev_day (int, default=2): The maximum number of days to look
backward in already classified eddies for matching previous
positions. It must be strictly positive. As some eddies might not be
detected for several consecutive days, an eddy can be matched with a
previous position several days before. The default value has been
choosen with the assumption that an eddy that last several days will
not be undetected for more that one day.
min_detection (int, default=5) : Minimum number of observation of an
eddy. Eddies with too view observations are discarded
Returns:
eddies_path (dict(int : dict(int : classes.Eddy))) : The path of eddies.
A unique id is assigned to each eddy so that 2 object 'classes.Eddy'
share the same id if and only if they represent the same eddy at
different dates. The first key is a date, the second key is the eddy
identifier.
"""
eddies_path = {}
current_max_id = -1
nb_days = len(list_days)
# Select the metric
if metric_name=='Jaccard':
from metrics import eddies_jaccard_index as metric
else:
print("eddies_tracker: invalid metric")
return {}
# Init the paths
if nb_days == 0:
print("eddies_tracker: empty list_days")
return {}
eddies_path[initial_date] = {}
for eddy in list_days[0]:
current_max_id += 1
eddies_path[initial_date][current_max_id] = eddy
# Handle the first days separatly (as part of the initialisation)
for day in range(1,nb_prev_day):
if nb_days == day:
return eddies_path
current_max_id += track_one_day(initial_date+day,eddies_path,list_days[day],
current_max_id,metric,nb_prev_day=day)
# Match positions day by day
for day in range(nb_prev_day,nb_days):
current_max_id += track_one_day(initial_date+day,eddies_path,
list_days[day],current_max_id,
metric,nb_prev_day=nb_prev_day)
# Delete eddies observed too view times
nb_observation = np.zeros((current_max_id+1))
for day in eddies_path.keys():
for eddy_id in eddies_path[day].keys():
nb_observation[eddy_id] += 1
remove_eddy = nb_observation<min_detection
for day in eddies_path.keys():
list_keys = list(eddies_path[day].keys())
for eddy_id in list_keys:
if remove_eddy[eddy_id]:
del eddies_path[day][eddy_id]
return eddies_path
def track_one_day(date,current_eddies_path,eddies_in_day,current_max_id,metric,nb_prev_day=2):
""" Assign an id to the eddies of a day using the classification of previous
days.
The eddies position of a given day are matched with the positions of the
previous days. The eddies of the day are added to the current paths.
Args:
date (int) : Date of the day to be added in the paths.
current_eddies_path (dict(int : dict(int : classes.Eddy))) : The paths
of eddies during the previous days. The first key is the date, the
second key is the eddy identifier. The paths are modified
'inplace' and the results are assigned to a new date entry.
eddies_in_day (list of classes.Eddy) : the list of detected eddies at
the date 'data'.
current_max_id (int) : The current maximum of identifier used for the
eddies. This parameter is used when a new eddy is detected. An eddy
is considered to be new if it has not been matched with any previous
eddy position.
metric (function(e1, e2 :classes.Eddy) = score: float) : The metric
function to use for matching eddies positions. The score must
increase with the similarity of the 2 eddies.
nb_prev_day (int, default=2): The maximum number of days to look
backward in already classified eddies for matching previous
positions. It must be strictly positive. As some eddies might not be
detected for several consecutive days, an eddy can be matched with a
previous position several days before. The default value has been
choosen with the assumption that an eddy that last several days will
not be not detected for more that one day.
Returns:
nb_new_eddies (int) : The number of new eddies.
"""
current_eddies_path[date] = {}
nb_eddies = len(eddies_in_day)
nb_new_eddies = 0
# Compute the best distance between current eddies and the eddies of
# previous days.
distances = np.zeros((nb_eddies,nb_prev_day,2))
for eddy_id in range(nb_eddies):
for date_offset in range(0,nb_prev_day):
best_score = 0
best_id = -1
for key in current_eddies_path[date-1-date_offset].keys():
score = metric(eddies_in_day[eddy_id],
current_eddies_path[date-1 - date_offset][key])
if score > best_score:
best_score = score
best_id = key
distances[eddy_id,date_offset,:] = np.array([best_id,best_score])
# Set of id of eddies observed during the previous day(s).
previous_eddies = set()
for date_offset in range(1,nb_prev_day+1):
prev_eddies_day = set(current_eddies_path[date - date_offset].keys())
previous_eddies = previous_eddies.union(prev_eddies_day)
previous_eddies = list(previous_eddies)
is_matched = np.zeros(nb_eddies, dtype=bool)
# Try to match current eddies with those previously observed.
for previous_eddy in previous_eddies:
for date_offset in range(0,nb_prev_day):
# Get the id of all current eddies which have their heighest score
# with previous_eddy.
match = np.argwhere(distances[:,date_offset,0]==previous_eddy)[:,0]
if len(match)!=0:
# If several current eddies match this previous eddy, the one
# with the highest score is selected.
match_id = match[np.argmax(distances[match,date_offset,1])]
if not is_matched[match_id]:
is_matched[match_id] = True
current_eddies_path[date][previous_eddy]=eddies_in_day[match_id]
break # End the first 'for' loop.
# The remaining not matched eddues are new eddies
new_eddies_id = np.argwhere(~is_matched)[:,0]
for new_eddy_id in new_eddies_id:
nb_new_eddies += 1
current_max_id += 1
current_eddies_path[date][current_max_id] = eddies_in_day[new_eddy_id]
return nb_new_eddies
| a93dcbdf727ea6e430e38a1647cddc04dd1d45b6 | [
"Markdown",
"Python"
] | 14 | Python | lordastorios/Projet_3A_IMTA | aabeb9ff99f2ea8d628db5c63ac6f8ebbe346313 | 12d178a9a19f8e931f6037fdf45b0c2ec225c4a2 |
refs/heads/master | <repo_name>AhmedSafwat1/DataStrucutreCode<file_sep>/rev-c++/main.cpp
#include <iostream>
#include <string.h>
using namespace std;
class Test
{
public:
Test()
{
cout<<"www";
}
};
void call(Test x)
{
cout<<"";
}
int main( )
{
Test t;
Test g = t;
call(t);
}
<file_sep>/t/main.cpp
#include <iostream>
using namespace std;
class x
{
static int y;
public:
static int gety()
{
return y;
}
};
int x::y = 5;
int main()
{
x u;
cout<<u.gety();
cout << "Hello world!" << endl;
return 0;
}
<file_sep>/StackQueue/main.cpp
#include <iostream>
#include <string.h>
using namespace std;
struct node
{
int id;
char name[255];
node* next;
node* prev;
};
struct data
{
int id;
char name[255];
};
class ll
{
node* head;
node* tail;
//============================================================
public:
ll()
{
head = NULL;
tail = NULL;
}
void push(int _id,char _name[])
{
node* temp = new node;
temp->id = _id;
strcpy(temp->name,_name);
if(head==NULL)
{
temp->next = NULL;
temp->prev = NULL;
head = temp;
tail = temp;
}
else
{
temp->next = NULL;
temp->prev = tail;
tail->next = temp;
tail = temp;
}
}
data pop()
{
data d;
d.id=-1;
strcpy(d.name,"");
if(tail == NULL)
{
return d;
}
else if(head == tail)
{
d.id = head->id;
strcpy(d.name,head->name);
delete head;
head = tail = NULL;
return d;
}
else
{
node* temp = tail;
tail = temp->prev;
tail->next = NULL;
d.id = temp->id;
strcpy(d.name,temp->name);
delete temp;
return d;
}
}
void diplay()
{
node* temp = head;
while(temp != NULL)
{
cout<<"id : "<<temp->id<<" name : "<<temp->name<<endl;
temp = temp->next;
}
}
//destroy
~ll()
{
node* temp = head;
node* d;
while(temp != NULL)
{
d = temp;
temp = temp->next;
delete d;
}
}
};
int main()
{
ll l;
l.push(5,"hkjk");
l.push(6,"hkjk");
data d = l.pop();
cout<<d.id;
return 0;
}
<file_sep>/Bones safwat/main.cpp
#include <iostream>
using namespace std;
void print(int* a)
{
for(int i=0;i<=10;i++)
{
cout<<a[i]<<" ";
}
}
int* myfun2(int a[],int q1,int e1,int e2)
{
int q2 = e1+1;
int s = e2-q1;
int* sorta = new int[s+1];
for(int i=0;i<=s;i++)
{
if(a[q1]<a[q2] && q1<=e1)
{
sorta[i] = a[q1];
q1++;
}
else
{
sorta[i] = a[q2];
q2++;
}
}
return sorta;
}
int main()
{
int arr[11] = {5,10,20,30,40,20,28,35,50,70,80};
int* sor = myfun2(arr,0,4,10);
print(sor);
return 0;
}
<file_sep>/ciricleQueue/main.cpp
#include <iostream>
using namespace std;
class Cqueue
{
int rear;
int Front;
int s;
int arr[5];
public:
Cqueue()
{
rear = Front = -1;
s = 5;
}
void enqueue(int _val)
{
if((rear == s-1 && Front == 0) || Front == rear+1)
return;
if(Front == -1)
{
rear = Front = 0;
arr[rear] = _val;
}
else if(rear == s-1)
{
rear = 0;
arr[rear] = _val;
}
else
{
rear++;
arr[rear] = _val;
}
}
int dequee(int& x )
{
if(Front == -1)
{
return 0;
}
x = arr[Front];
if(Front == rear)
{
rear = Front = -1;
}
else if(Front == s-1)
{
Front = 0;
}
else
{
Front++;
}
return 1;
}
};
int main()
{
Cqueue l;
l.enqueue(5);
int x;
l.dequee(x);
cout<<x;
cout << "Hello world!" << endl;
return 0;
}
<file_sep>/linked list/main.cpp
#include <iostream>
#include <string.h>
using namespace std;
struct node
{
int id;
char name[255];
node* next;
node* prev;
};
class ll
{
node* head;
node* tail;
node* searchByName(char a[])
{
node* temp = head;
while(temp != NULL)
{
if(strcasecmp(temp->name,a) == 0)
{
return temp;
}
temp = temp->next;
}
return temp;
}
node* searchById(int s)
{
node* temp = head;
while(temp != NULL)
{
if(temp->id == s)
{
return temp;
}
temp = temp->next;
}
return temp;
}
//============================================================
public:
ll()
{
head = NULL;
tail = NULL;
}
ll(ll& x)
{
tail = head = NULL;
node* temp = x.head;
while(temp != NULL)
{
append(temp->id,temp->name);
temp = temp->next;
}
}
void append(int _id,char _name[])
{
node* temp = new node;
temp->id = _id;
strcpy(temp->name,_name);
if(head==NULL)
{
temp->next = NULL;
temp->prev = NULL;
head = temp;
tail = temp;
}
else
{
temp->next = NULL;
temp->prev = tail;
tail->next = temp;
tail = temp;
}
}
void diplay()
{
node* temp = head;
while(temp != NULL)
{
cout<<"id : "<<temp->id<<" name : "<<temp->name<<endl;
temp = temp->next;
}
}
void test()
{
node* o = searchById(25);
}
void deleteById(int i)
{
node* out = searchById(i);
if(out != NULL)
{
if(head == tail && head == out)
{
head=tail=NULL;
}
else if(out == head)
{
head->next->prev = NULL;
head = out->next;
delete out;
}
else if(out == tail)
{
out->prev->next = NULL;
tail = out->prev;
delete out;
}
else
{
out->prev->next = out->next;
out->next->prev = out->prev;
delete out;
}
}
else
cout<<"not found this is "<<i<<endl;
}
void deleteByName(char a[])
{
node* out = searchByName(a);
if(out != NULL)
{
if(head == tail && head == out)
{
head=tail=NULL;
}
else if(out == head )
{
head->next->prev = NULL;
head = out->next;
delete out;
}
else if(out == tail)
{
out->prev->next = NULL;
tail = out->prev;
delete out;
}
else
{
out->prev->next = out->next;
out->next->prev = out->prev;
delete out;
}
}
else
cout<<"not found this is "<<a<<endl;
}
node * operator[](int i)
{
node* temp = head;
int count = 0;
while(temp != NULL)
{
if(count == i)
{
return temp;
}
temp = temp->next;
count++;
}
return temp;
}
void insertAfterID(int i,int _id,char _name[])
{
node* out = searchById(i);
node* temp = new node;
temp->id = _id;
strcpy(temp->name,_name);
if(out != NULL)
{
if(out == tail || tail==head && out == tail)
{
append(_id,_name);
}
else
{
temp->next = out->next;
out->next = temp;
temp->prev = out;
temp->next->prev = temp;
}
}
else
cout<<"not found this is "<<i<<endl;
}
//destroy
~ll()
{
node* temp = head;
node* d;
while(temp != NULL)
{
d = temp;
temp = temp->next;
delete d;
}
}
};
int main()
{
ll l;
l.append(1,"ahmed");
l.append(2,"ahmed");
ll l2 = l;
l.diplay();
l.test();
l.deleteById(1);
l.deleteById(2);
l.diplay();
cout<<"============="<<endl;
l2.insertAfterID(1,5,"asdjkjd");
l2.diplay();
cout<<l2[1]->name<<endl;
return 0;
}
<file_sep>/bst/main.cpp
#include <iostream>
using namespace std;
struct node
{
int id;
node* left;
node* right;
};
class Bst
{
node* root;
public:
Bst()
{
root = NULL;
}
void add(int key)
{
node* temp = new node;
temp->id = key;
temp->left = temp->right = NULL;
if(root == NULL)
{
root = temp;
}
else
{
node* t = root;
node* p = root;
while(t != NULL)
{
p = t;
if(key > t->id)
{
t = t->right;
}
else
{
t = t->left;
}
}
if(key > p->id)
p->right = temp;
else
p->left = temp;
}
}
//add rec ===========================
void add2(int key)
{
addrec(key,root);
}
void addrec(int key,node*& r)
{
if(r == NULL)
{
node* temp = new node;
temp->left = temp->right = NULL;
temp->id = key;
r = temp;
}
else if(key < r->id)
{
addrec(key,r->left);
}
else
{
addrec(key,r->right);
}
}
// void display
void callDisplay()
{
displayOrder(root);
}
void displayOrder(node* r)
{
if(r == NULL)
return;
displayOrder(r->left);
cout<<r->id <<" ";
displayOrder(r->right);
}
void displayPreOrder(node* r)
{
if(r == NULL)
return;
cout<<r->id <<" ";
displayOrder(r->left);
displayOrder(r->right);
}
void displayPostOrder(node* r)
{
if(r == NULL)
return;
displayOrder(r->left);
displayOrder(r->right);
cout<<r->id <<" ";
}
// search
void callSearch(int key)
{
searching(root,key);
}
void searching(node* r ,int key)
{
if(r == NULL)
{
cout<<endl<<"not found"<<endl;
return;
}
else if(r->id == key)
{
cout<<endl<<"found"<<endl;
}
else if(r->id > key)
searching(r->left,key);
else
searching(r->right,key);
}
//delete
node * minValueNode(node* r)
{
node* current = r;
while (current->left != NULL)
current = current->left;
return current;
}
//==================
node* calldel(int id)
{
return deleteId(root,id);
}
node* deleteId(node* r,int key)
{
if(r == NULL)
return NULL;
else if( r->id > key)
{
r->left = deleteId(r->left,key);
}
else if(r->id < key)
{
r->right = deleteId(r->right,key);
}
else
{
if(r->left == NULL)
{
node * temp = r->right;
delete r;
return temp;
}
else if(r->right == NULL)
{
node * temp = r->left;
delete r;
return temp;
}
else if(r->left == NULL && r->right == NULL)
{
delete r;
return NULL;
}
else
{
node * temp = minValueNode(r->right);
r->id = temp->id;
r->right = deleteId(temp->right,temp->id);
return r;
}
}
return r;
}
};
int main()
{
Bst b;
b.add2(10);
b.add2(5);
b.add2(3);
b.add2(6);
b.add2(20);
b.callDisplay();
b.callSearch(13);
cout<<b.calldel(20)->id<<endl;
b.callDisplay();
return 0;
}
<file_sep>/sorting/main.cpp
#include <iostream>
// sorting = searching = bst.add.display n order preorder postorder search delete
using namespace std;
void swapf(int& a,int&b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void sort1(int arr[],int s)//selection
{
int m = 0;
for(int i=0;i<s-1;i++)
{
m = i;
for(int j = i+1;j<s;j++)
{
if(arr[i]>arr[j])
{
m = j;
}
}
swapf(arr[i],arr[m]);
}
}
void sort2(int arr[],int s)//bubble
{
int flag = 0;
for(int i=0;i<s-1;i++)
{
flag= 0;
for(int j = i+1;j<s;j++)
{
if(arr[i]>arr[j])
{
swapf(arr[i],arr[j]);
flag = 1;
}
}
if(flag == 0)
{
break;
}
}
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swapf(arr[j], arr[j+1]);
}
void sort3(int arr[],int s)//insert
{
int j = 0;
for(int i=1;i<s;i++)
{
j=i;
while(j > 0 && arr[j] < arr[j-1])
{
swapf(arr[j],arr[j-1]);
j--;
}
}
}
//==========migrate
void myfun2(int a[],int q1,int e1,int e2)
{
int q2 = e1+1;
int s = e2-q1;
int j = q1;
int* sorta = new int[s+1];
for(int i=0;i<=s;i++)
{
if(a[q1]<a[q2] && q1<=e1)
{
sorta[i] = a[q1];
q1++;
}
else
{
if(q2<=e2)
{
sorta[i] = a[q2];
q2++;
}
else if(q1<=e1)
{
sorta[i] = a[q1];
q1++;
}
}
}
for(int i=0;i<=s;i++)
{
a[j] = sorta[i];
j++;
}
};
void migrateSort(int a[],int s,int e)
{
if(s >= e)
return;
int md = (s+e)/2;
migrateSort(a,s,md);
migrateSort(a,md+1,e);
myfun2(a,s,md,e);
}
// ========================= srearching ==================================================
int binarySearch(int arr[],int s,int e,int key)
{
if(s > e)
return -1;
else
{
int md = (s+e)/2;
if(key>arr[md])
{
binarySearch(arr,md+1,e,key);
}
else if(key == arr[md])
{
return md;
}
else
{
binarySearch(arr,s,md-1,key);
}
}
}
//===========================================================================================
void print(int a[],int s)
{
for(int i=0;i<s;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int a[6] = {10,5,7,12,4,9};
//sort1(a,5);
migrateSort(a,0,5);
// int arr[11] = {5,10,20,30,40,20,28,35,50,70,80};
//myfun2(arr,0,4,10);
print(a,6);
cout<<binarySearch(a,0,5,7);
return 0;
}
<file_sep>/test/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
int n = ch;
cout<<n<<endl;
}
| f107594cefc5122d7f1f08e203c0e83b3ed14fe4 | [
"C",
"C++"
] | 9 | C++ | AhmedSafwat1/DataStrucutreCode | d7db921c159e32112527fd2257ef7571aeb13de1 | 3f4a21b45c2eba0e285f8257d32ce7d6c26446e5 |
refs/heads/master | <repo_name>luisalbertoc/laravel_mantenedor_usuarios<file_sep>/resources/views/header.php
<link rel="stylesheet" href="<?php echo asset('css/bootstrap.min.css')?>" type="text/css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<h1>Id: <?= Session::get('id'); ?></h1><file_sep>/resources/views/usuario/edicion.php
<link rel="stylesheet" href="<?php echo asset('css/bootstrap.min.css')?>" type="text/css">
<div class="container">
<h1>Editar usuario: <?= $usuario->nombre ?> <?= $usuario->apellido ?> </h1>
<a class="btn btn-primary" href="<?= URL::to('usuario/index') ?>">Volver</a>
<br><br>
<form action="<?= URL::to('usuario/editar') ?>" method="post">
<table class="table table-bordered table-condensed table-hover">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<input type="hidden" name="id" value="<?= $usuario->id ?>">
<tbody>
<tr>
<td>
Nombre
</td>
<td>
<input type="text" class="form-control" value="<?= $usuario->nombre ?>" name="nombre" placeholder="Nombre">
</td>
</tr>
<tr>
<td>
Apellido
</td>
<td>
<input type="text" class="form-control" value="<?= $usuario->apellido ?>" name="apellido" placeholder="Apellido">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="btn btn-info" value="Editar">
</td>
</tr>
</tbody>
</table>
</form>
</div>
<file_sep>/app/Usuario.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
class Usuario extends Model
{
use ValidatingTrait;
protected $rules = [
'nombre' => 'unique',
];
}
<file_sep>/app/Http/Controllers/UsuarioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Response;
use DB;
use App\Http\Controllers\Controller;
//Modelos
use App\Usuario;
class UsuarioController extends Controller
{
public function __construct()
{
$this->middleware('login', ['except' => ['getLogin','postLogear']]);
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
public function getLogin(Request $request)
{
$request->session()->forget('id');
return \View::make('usuario/login');
}
public function postLogear(Request $request)
{
$nombre = $request->input('nombre');
$usuario = Usuario::where('nombre', $nombre)
->first();
if($usuario){
$request->session()->put('id', $usuario->id);
return redirect("usuario/index");
}else{
echo "Usuario no existe";
}
}
public function getIndex()
{
$this->middleware('login');
$usuarios = Usuario::all();
return \View::make('usuario/index',['usuarios' => $usuarios]);
}
public function getConsulta(Response $response)
{
$consulta = DB::select('select * from usuarios');
//print_r($consulta);
//foreach ($consulta as $usuario) {
// echo $usuario->nombre."<br>";
//}
return Response::json($consulta);
}
public function getIngreso()
{
return \View::make('usuario/ingreso');
}
public function postIngresar(Request $request)
{
$nombre = $request->input('nombre');
$apellido = $request->input('apellido');
$usuario = new Usuario;
$usuario->nombre = $nombre;
$usuario->apellido = $apellido;
if($usuario->save()){
return redirect('usuario/index');
}else{
echo "el usuario ya ha sido ingresado anteriormente";
}
}
public function getEdicion($id = 0)
{
if($id != 0)
{
$usuario = Usuario::where('id', $id)
->first();
if($usuario)
{
return \View::make('usuario/edicion',['usuario' => $usuario]);
}else
{
echo "error, usuario no existe";
}
}else{
echo "error, usuario no existe";
}
}
public function postEditar(Request $request)
{
$id = $request->input("id");
$nombre = $request->input("nombre");
$apellido = $request->input("apellido");
$usuario_modificado['nombre'] = $nombre;
$usuario_modificado['apellido'] = $apellido;
$usuario = Usuario::where('id', $id)
->update($usuario_modificado);
return redirect('usuario/edicion/'.$id);
}
public function getEliminar($id = 0)
{
if($id != 0)
{
$usuario = Usuario::where('id', $id);
$usuario->delete();
return redirect('usuario/index');
}else{
echo "error, usuario no existe";
}
}
}
<file_sep>/resources/views/usuario/login.php
<link rel="stylesheet" href="<?php echo asset('css/bootstrap.min.css')?>" type="text/css">
<div class="container">
<h1>Login</h1>
<br><br>
<form action="logear" method="post">
<table class="table table-bordered table-condensed table-hover">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<tbody>
<tr>
<td>
Nombre
</td>
<td>
<input type="text" class="form-control" name="nombre" placeholder="Nombre">
</td>
</tr>
<tr>
<td>
Apellido
</td>
<td>
<input type="text" class="form-control" name="apellido" placeholder="Apellido">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="btn btn-danger" value="Logear">
</td>
</tr>
</tbody>
</table>
</form>
</div>
<file_sep>/resources/views/usuario/index.php
<div class="container">
<?= View::make('header'); ?>
<h1>Usuarios</h1>
<a class="btn btn-success" href="ingreso">Ingresar usuario</a>
<a class="btn btn-warning" href="login">Cerrar sesion</a>
<br><br>
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th>
Nombre
</td>
<th>
Apellido
</th>
<th>
Editar
</th>
<th>
Eliminar
</th>
</tr>
</thead>
<tbody>
<?php
foreach ($usuarios as $usuario) {
?>
<tr>
<td>
<?= $usuario->nombre; ?>
</td>
<td>
<?= $usuario->apellido; ?>
</td>
<td>
<a href="edicion/<?= $usuario->id ?>" class="btn btn-info" >Editar</a>
</td>
<td>
<a href="eliminar/<?= $usuario->id ?>" class="btn btn-danger" >Eliminar</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<div id="ingreso"></div>
<br>
<button type="button" onclick="ingreso()" >Ingreso por ajax</button>
</div>
<script type="text/javascript">
function ingreso()
{
$.ajax({
// la URL para la petición
url : 'ingreso',
// la información a enviar
// (también es posible utilizar una cadena de datos)
data : { id : 123 },
// especifica si será una petición POST o GET
type : 'GET',
// el tipo de información que se espera de respuesta
// la respuesta es pasada como argumento a la función
success : function(data) {
$("#ingreso").html(data)
},
// código a ejecutar si la petición falla;
// son pasados como argumentos a la función
// el objeto de la petición en crudo y código de estatus de la petición
error : function(xhr, status) {
alert('Disculpe, existió un problema');
}
});
}
</script>
| ed021bc1e19e1070c4c448e9abb239b103dfc99e | [
"PHP"
] | 6 | PHP | luisalbertoc/laravel_mantenedor_usuarios | 8acde1787cae1cd9cb916c56df849ee933c6ff60 | a4dea946d8c96afef4f18e3a30f816280275d139 |
refs/heads/master | <repo_name>ylevi33/octane-bamboo-plugin<file_sep>/src/main/java/com/hp/octane/plugins/bamboo/octane/BambooPluginServices.java
/*
* Copyright 2017 EntIT Software LLC, a Micro Focus company, L.P.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.hp.octane.plugins.bamboo.octane;
import com.atlassian.bamboo.applinks.ImpersonationService;
import com.atlassian.bamboo.configuration.AdministrationConfigurationAccessor;
import com.atlassian.bamboo.plan.ExecutionRequestResult;
import com.atlassian.bamboo.plan.PlanExecutionManager;
import com.atlassian.bamboo.plan.PlanKeys;
import com.atlassian.bamboo.plan.cache.CachedPlanManager;
import com.atlassian.bamboo.plan.cache.ImmutableChain;
import com.atlassian.bamboo.plan.cache.ImmutableTopLevelPlan;
import com.atlassian.bamboo.security.BambooPermissionManager;
import com.atlassian.bamboo.security.acegi.acls.BambooPermission;
import com.atlassian.bamboo.user.BambooUser;
import com.atlassian.bamboo.user.BambooUserManager;
import com.atlassian.sal.api.component.ComponentLocator;
import com.atlassian.sal.api.pluginsettings.PluginSettings;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import com.hp.octane.integrations.OctaneSDK;
import com.hp.octane.integrations.dto.DTOFactory;
import com.hp.octane.integrations.dto.configuration.CIProxyConfiguration;
import com.hp.octane.integrations.dto.configuration.OctaneConfiguration;
import com.hp.octane.integrations.dto.connectivity.OctaneResponse;
import com.hp.octane.integrations.dto.executor.CredentialsInfo;
import com.hp.octane.integrations.dto.executor.DiscoveryInfo;
import com.hp.octane.integrations.dto.executor.TestConnectivityInfo;
import com.hp.octane.integrations.dto.executor.TestSuiteExecutionInfo;
import com.hp.octane.integrations.dto.general.CIJobsList;
import com.hp.octane.integrations.dto.general.CIPluginInfo;
import com.hp.octane.integrations.dto.general.CIServerInfo;
import com.hp.octane.integrations.dto.pipelines.PipelineNode;
import com.hp.octane.integrations.dto.snapshots.SnapshotNode;
import com.hp.octane.integrations.exceptions.ConfigurationException;
import com.hp.octane.integrations.exceptions.PermissionException;
import com.hp.octane.integrations.spi.CIPluginServicesBase;
import com.hp.octane.integrations.util.CIPluginSDKUtils;
import com.hp.octane.integrations.util.SdkStringUtils;
import com.hp.octane.plugins.bamboo.api.OctaneConfigurationKeys;
import com.hp.octane.plugins.bamboo.octane.uft.UftManager;
import org.acegisecurity.acls.Permission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.net.*;
import java.util.*;
import java.util.concurrent.Callable;
public class BambooPluginServices extends CIPluginServicesBase {
private static final Logger log = LoggerFactory.getLogger(BambooPluginServices.class);
private static final String PLUGIN_VERSION = "1.0.0-SNAPSHOT";
private CachedPlanManager planMan;
private ImpersonationService impService;
private PlanExecutionManager planExecMan;
private static DTOConverter CONVERTER = DefaultOctaneConverter.getInstance();
private PluginSettingsFactory settingsFactory;
public BambooPluginServices(PluginSettingsFactory settingsFactory) {
super();
this.settingsFactory = settingsFactory;
this.planExecMan = ComponentLocator.getComponent(PlanExecutionManager.class);
this.planMan = ComponentLocator.getComponent(CachedPlanManager.class);
this.impService = ComponentLocator.getComponent(ImpersonationService.class);
}
// return null as we don't have file storage available
public File getAllowedOctaneStorage() {
return null;
}
public CIJobsList getJobsList(boolean arg0) {
log.info("Get jobs list");
Callable<List<ImmutableTopLevelPlan>> plansGetter = impService.runAsUser(getRunAsUser(), new Callable<List<ImmutableTopLevelPlan>>() {
public List<ImmutableTopLevelPlan> call() throws Exception {
return planMan.getPlans();
}
});
try {
List<ImmutableTopLevelPlan> plans = plansGetter.call();
return CONVERTER.getRootJobsList(plans);
} catch (Exception e) {
log.error("Error while retrieving top level plans", e);
}
return CONVERTER.getRootJobsList(Collections.<ImmutableTopLevelPlan>emptyList());
}
public OctaneConfiguration getOctaneConfiguration() {
log.debug("getOctaneConfiguration");
OctaneConfiguration result = null;
PluginSettings settings = getPluginSettings();
if (settings.get(OctaneConfigurationKeys.OCTANE_URL) != null && settings.get(OctaneConfigurationKeys.ACCESS_KEY) != null) {
String url = String.valueOf(settings.get(OctaneConfigurationKeys.OCTANE_URL));
String accessKey = String.valueOf(settings.get(OctaneConfigurationKeys.ACCESS_KEY));
String secret = String.valueOf(settings.get(OctaneConfigurationKeys.API_SECRET));
result = OctaneSDK.getInstance().getConfigurationService().buildConfiguration(url, accessKey, secret);
}
return result;
}
public PipelineNode getPipeline(String pipelineId) {
//workaround for bamboo
pipelineId = pipelineId.toUpperCase();
log.info("get pipeline " + pipelineId);
ImmutableTopLevelPlan plan = planMan.getPlanByKey(PlanKeys.getPlanKey(pipelineId), ImmutableTopLevelPlan.class);
return CONVERTER.getRootPipelineNodeFromTopLevelPlan(plan);
}
public CIPluginInfo getPluginInfo() {
log.debug("get plugin info");
return DTOFactory.getInstance().newDTO(CIPluginInfo.class).setVersion(PLUGIN_VERSION);
}
@Override
public CIProxyConfiguration getProxyConfiguration(URL targetUrl) {
log.debug("get proxy configuration");
CIProxyConfiguration result = null;
if (isProxyNeeded(targetUrl)) {
log.info("proxy is required for host " + targetUrl.getHost());
String protocol = targetUrl.getProtocol();
return CONVERTER.getProxyCconfiguration(getProxyProperty(protocol + ".proxyHost", null),
Integer.parseInt(getProxyProperty(protocol + ".proxyPort", null)),
System.getProperty(protocol + ".proxyUser", ""),
System.getProperty(protocol + ".proxyPassword", ""));
}
return result;
}
private String getProxyProperty(String propKey, String def) {
if (def == null) def = "";
return System.getProperty(propKey) != null ? System.getProperty(propKey).trim() : def;
}
private boolean isProxyNeeded(URL targetHostUrl) {
boolean result = false;
String proxyHost = getProxyProperty(targetHostUrl.getProtocol() + ".proxyHost", "");
String nonProxyHostsStr = getProxyProperty(targetHostUrl.getProtocol() + ".nonProxyHosts", "");
if (SdkStringUtils.isNotEmpty(proxyHost) && !CIPluginSDKUtils.isNonProxyHost(targetHostUrl.getHost(), nonProxyHostsStr)) {
result = true;
}
return result;
}
public CIServerInfo getServerInfo() {
log.debug("get ci server info");
String instanceId = String.valueOf(getPluginSettings().get(OctaneConfigurationKeys.UUID));
String baseUrl = getBambooServerBaseUrl();
String runAsUser = getRunAsUser();
return CONVERTER.getServerInfo(baseUrl, instanceId, runAsUser);
}
public SnapshotNode getSnapshotByNumber(String pipeline, String snapshot, boolean arg2) {
// TODO implement get snapshot
log.info("get snapshot by number " + pipeline.toUpperCase() + " , " + snapshot);
return null;
}
public SnapshotNode getSnapshotLatest(String pipeline, boolean arg1) {
log.info("get latest snapshot for pipeline " + pipeline);
pipeline = pipeline.toUpperCase();
ImmutableTopLevelPlan plan = planMan.getPlanByKey(PlanKeys.getPlanKey(pipeline), ImmutableTopLevelPlan.class);
return CONVERTER.getSnapshot(plan, plan.getLatestResultsSummary());
}
public void runPipeline(final String pipeline, final String parameters) {
// TODO implement parameters conversion
// only execute runnable plans
log.info("starting pipeline run");
Callable<String> impersonated = impService.runAsUser(getRunAsUser(), new Callable<String>() {
public String call() throws Exception {
BambooUserManager um = ComponentLocator.getComponent(BambooUserManager.class);
BambooUser user = um.getBambooUser(getRunAsUser());
ImmutableChain chain = planMan.getPlanByKey(PlanKeys.getPlanKey(pipeline.toUpperCase()), ImmutableChain.class);
log.info("plan key is " + chain.getPlanKey().getKey());
log.info("build key is " + chain.getBuildKey());
log.info("chain key is " + chain.getKey());
if (!isUserHasPermission(BambooPermission.BUILD, user, chain)) {
throw new PermissionException(403);
}
ExecutionRequestResult result = planExecMan.startManualExecution(chain, user, new HashMap<String, String>(), new HashMap<String, String>());
if (result.getErrors().getTotalErrors() > 0) {
throw new ConfigurationException(504);
}
return null;
}
});
execute(impersonated, "runPipeline");
}
private boolean isUserHasPermission(Permission permissionType, BambooUser user, ImmutableChain chain) {
Collection<Permission> permissionForPlan = ComponentLocator.getComponent(BambooPermissionManager.class).getPermissionsForPlan(chain.getPlanKey());
for (Permission permission : permissionForPlan) {
if (permission.equals(permissionType)) {
return true;
}
}
return false;
}
private String getRunAsUser() {
return String.valueOf(getPluginSettings().get(OctaneConfigurationKeys.IMPERSONATION_USER));
}
private PluginSettings getPluginSettings() {
try {
return settingsFactory.createGlobalSettings();
} catch (Exception e) {//can occur then proxy object is destroyed on plugin redeployment
settingsFactory = ComponentLocator.getComponent(PluginSettingsFactory.class);
return settingsFactory.createGlobalSettings();
}
}
@Override
public OctaneResponse checkRepositoryConnectivity(final TestConnectivityInfo testConnectivityInfo) {
final Callable<OctaneResponse> impersonated = impService.runAsUser(getRunAsUser(), new Callable<OctaneResponse>() {
public OctaneResponse call() {
return getUftManager().checkRepositoryConnectivity(testConnectivityInfo);
}
});
return execute(impersonated, "checkRepositoryConnectivity");
}
@Override
public OctaneResponse upsertCredentials(final CredentialsInfo credentialsInfo) {
final Callable<OctaneResponse> impersonated = impService.runAsUser(getRunAsUser(), new Callable<OctaneResponse>() {
public OctaneResponse call() {
return getUftManager().upsertCredentials(credentialsInfo);
}
});
return execute(impersonated, "upsertCredentials");
}
@Override
public void runTestDiscovery(final DiscoveryInfo discoveryInfo) {
final Callable<Void> impersonated = impService.runAsUser(getRunAsUser(), new Callable<Void>() {
public Void call() {
getUftManager().runTestDiscovery(discoveryInfo, getRunAsUser());
return null;
}
});
execute(impersonated, "runTestDiscovery");
}
@Override
public void deleteExecutor(final String id) {
final Callable<Void> impersonated = impService.runAsUser(getRunAsUser(), new Callable<Void>() {
public Void call() {
getUftManager().deleteExecutor(id);
return null;
}
});
execute(impersonated, "deleteExecutor");
}
@Override
public void runTestSuiteExecution(final TestSuiteExecutionInfo testSuiteExecutionInfo) {
final Callable<Void> impersonated = impService.runAsUser(getRunAsUser(), new Callable<Void>() {
public Void call() {
getUftManager().runTestSuiteExecution(testSuiteExecutionInfo, getRunAsUser());
return null;
}
});
execute(impersonated, "runTestSuiteExecution");
}
private UftManager getUftManager() {
return UftManager.getInstance();
}
private <V> V execute(Callable<V> callable, String actionName) {
log.info("Impersonated call : " + actionName);
Callable<V> impersonated = impService.runAsUser(getRunAsUser(), callable);
try {
return impersonated.call();
} catch (PermissionException e) {
log.warn("PermissionException : " + e.getMessage());
throw e;
} catch (Throwable e) {
log.warn("Failed to execute " + actionName + " : " + e.getMessage(), e);
RuntimeException runtimeException = null;
if (e instanceof RuntimeException) {
runtimeException = (RuntimeException) e;
} else {
runtimeException = new RuntimeException(e);
}
throw runtimeException;
}
}
public static String getBambooServerBaseUrl() {
String baseUrl = ComponentLocator.getComponent(AdministrationConfigurationAccessor.class)
.getAdministrationConfiguration().getBaseUrl();
return baseUrl;
}
}
| 4df260ff4a788443beb1e4ebf0da936ca92b1bf9 | [
"Java"
] | 1 | Java | ylevi33/octane-bamboo-plugin | 4f1d9aaecb4178b2d59787b0c280a81743e7299d | 06d1ed4a40355713c849e32bdb74c06771c72f70 |
refs/heads/master | <repo_name>chris-schmitz/vue-cli<file_sep>/lib/vue2-version-warn.js
var chalk = require('chalk')
module.exports = function (template, name) {
var vue1InitCommand = 'vue init ' + template + '#1.0' + ' ' + name
console.log(chalk.red(' This will install Vue 2.x version of template.'))
console.log()
console.log(chalk.yellow(' For Vue 1.x use: ') + chalk.green(vue1InitCommand))
console.log()
}
| 7dfec5253925efe3eeb2c8f11577f821563ac64a | [
"JavaScript"
] | 1 | JavaScript | chris-schmitz/vue-cli | 179136a1e65d8824736641035e8c9bf2b625e9e1 | 404faf45bb12c9542e7c09c400aa142878b741e8 |
refs/heads/master | <file_sep>require 'rubygems'
require 'net-ldap'
class SessionsController < ApplicationController
def initialize(req = nil)
if req != nil
@_request = req
end
end
def show
end
def check_auth
if !is_logged_in
redirect_to "/"
end
end
def is_logged_in
if session.has_key?("current_user_id")
return true
else
return false
end
end
def login
if is_logged_in
@user = User.find(session[:current_user_id])
redirect_to "/users/#{@user.id}"
else
redirect_to "/"
end
end
def logout
session.delete(:current_user_id)
redirect_to "/"
end
def require_login
if !is_logged_in
@user = authenticate(params[:username], params[:password])
if @user == nil
session.delete(:current_user_id)
redirect_to :controller => 'users', :action => 'login', :alert => "Invalid username or password"
else
session[:username] = @user.username
session[:password] = params[:password]
session[:current_user_id] = @user.id
redirect_to @user
end
end
end
def authenticate(username, password)
@username = username
@password = <PASSWORD>
@connection = nil
@host = "thematrix.robtcallahan.net"
@port = 389
@domain = "thematrix.robtcallahan.net"
@treebase = 'cn=Users,dc=thematrix,dc=robtcallahan,dc=net'
ldap = Net::LDAP.new(:host => @host, :port => @port)
ldap.auth("#{@username}@#{@domain}", @password)
# ldap.bind is false if username/password are bad
if ldap.bind
filter = Net::LDAP::Filter.eq("sAMAccountName", @username)
@user = User.new
if User.exists?(username: @username)
@user = User.where(username: "#{@username}").first
@user.update(mail: @user.mail)
return @user
end
entries = ldap.search(:base => @treebase, :filter => filter, :attributes => ['samaccountname','givenname','sn','lastLogon','mail','memberOf'])
entry = entries[0]
@user = User.new
@user.username = entry.samaccountname[0]
@user.firstname = entry.givenname[0]
@user.lastname = entry.sn[0]
@user.mail = entry.mail[0]
entry.each do |attribute, values|
if attribute.match(/memberof/)
values.each do |value|
a = value.split(',')
md = a[0].match(/CN=(.+)/)
@user.group = md[1]
end
end
end
@user.save
return @user
else
return nil
end
end
end
<file_sep>require 'net-ldap'
require 'date'
class UsersController < ApplicationController
AD_EPOCH = 116_444_736_000_000_000
AD_MULTIPLIER = 10_000_000
before_action :require_login, except: [:login]
def login
@error_msg = params[:alert]
end
def index
@session = session
@connection = nil
@host = "thematrix.robtcallahan.net"
@port = 389
@domain = "thematrix.robtcallahan.net"
ldap = Net::LDAP.new(:host => @host, :port => @port)
ldap.auth("#{session[:username]}@#{@domain}", session[:password])
# ldap.bind is false if username/password are bad
if ldap.bind
@treebase = 'cn=Users,dc=thematrix,dc=robtcallahan,dc=net'
filter = Net::LDAP::Filter.ge("sn", " ")
@entries = ldap.search(:base => @treebase, :filter => filter, :attributes => ['sAMAccountName','givenName','sn','lastlogon','mail','memberOf'])
i = 0
for entry in @entries
time = @entries[i][:lastlogon][0]
if "XX#{time}XX" == "XX0XX"
@entries[i][:lastlogon][0] = "-"
else
@entries[i][:lastlogon][0] = ad2time(time)
end
i = i + 1
end
else
# some error here
end
end
def show
@user = User.find(session[:current_user_id])
end
private
def require_login
sessions_ctrl = SessionsController.new(@_request)
if !sessions_ctrl.is_logged_in
flash[:error] = "You must be logged in to access this section"
redirect_to "/"
end
end
# convert from AD's time string to a Time object
def ad2time(time)
Time.at((time.to_i - AD_EPOCH) / AD_MULTIPLIER)
end
end
<file_sep>Rails.application.routes.draw do
#get 'user/login'
resources :articles do
resources :comments
end
resources :users
resources :sessions
post "/" => "sessions#require_login"
get "/logout" => "sessions#logout"
root 'users#login'
end
| ea9ac704861dc7d71a0d307bc824c65781f534cf | [
"Ruby"
] | 3 | Ruby | robtcallahan/myblog | 8086e8dd71185d23679f247ef839d07aae528453 | 019fc75c0c46ff366854b9c8374669b5ddd90d0d |
refs/heads/master | <repo_name>Fred-Victor-YANG/WeShop<file_sep>/conn.php
<?php
$servername = "127.0.0.1:8080";
$username = "root";
$password = "<PASSWORD>";
$dbname = "myDB";
$conn=mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno())
{
echo "连接失败: " . mysqli_connect_error();
}
?><file_sep>/test.php
<?php
/**
* SocketServer Class
* By James.Huang <<EMAIL>>
* */
set_time_limit(0);
class SocketServer {
private static $socket;
function SocketServer($port) {
global $errno, $errstr;
if ($port < 1024) {
die("Port must be a number which bigger than 1024/n");
}
$socket = stream_socket_server("tcp://0.0.0.0:{$port}", $errno, $errstr);
if (!$socket)
die("$errstr ($errno)");
// stream_set_timeout($socket, -1); // 保证服务端 socket 不会超时,似乎没用:)
while ($conn = stream_socket_accept($socket, -1)) { // 这样设置不超时才油用
static $id = 0;
static $ct = 0;
$ct_last = $ct;
$ct_data = '';
$buffer = '';
$id++; // increase on each accept
echo "Client $id come./n";
while (!preg_match('//r?/n/', $buffer)) { // 没有读到结束符,继续读
// if (feof($conn)) break; // 防止 popen 和 fread 的 bug 导致的死循环
$buffer = fread($conn, 1024);
echo 'R'; // 打印读的次数
$ct += strlen($buffer);
$ct_data .= preg_replace('//r?/n/', '', $buffer);
}
$ct_size = ($ct - $ct_last) * 8;
echo "[$id] " . __METHOD__ . " > " . $ct_data . "/n";
fwrite($conn, "Received $ct_size byte data./r/n");
fclose($conn);
}
fclose($socket);
}
}
new SocketServer(2000);
/**
* Socket Test Client
* By James.Huang <<EMAIL>>
**/
function debug ($msg)
{
// echo $msg;
error_log($msg, 3, '/tmp/socket.log');
}
if ($argv[1]) {
$socket_client = stream_socket_client('tcp://0.0.0.0:2000', $errno, $errstr, 30);
// stream_set_blocking($socket_client, 0);
// stream_set_timeout($socket_client, 0, 100000);
if (!$socket_client) {
die("$errstr ($errno)");
} else {
$msg = trim($argv[1]);
for ($i = 0; $i < 10; $i++) {
$res = fwrite($socket_client, "$msg($i)");
usleep(100000);
echo 'W'; // 打印写的次数
// debug(fread($socket_client, 1024)); // 将产生死锁,因为 fread 在阻塞模式下未读到数据时将等待
}
fwrite($socket_client, "/r/n"); // 传输结束符
debug(fread($socket_client, 1024));
fclose($socket_client);
}
}
else {
// $phArr = array();
// for ($i = 0; $i < 10; $i++) {
// $phArr[$i] = popen("php ".__FILE__." '{$i}:test'", 'r');
// }
// foreach ($phArr as $ph) {
// pclose($ph);
// }
for ($i = 0; $i < 10; $i++) {
system("php ".__FILE__." '{$i}:test'");
}
}
?><file_sep>/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>WESHOP - Charger avec smart force</title>
<link rel="shortcut icon" type="image/x-icon" href="images/logo.png">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,600,700" rel="stylesheet">
<link rel="stylesheet" href="css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/owl.carousel.min.css">
<link rel="stylesheet" href="css/owl.theme.default.min.css">
<link rel="stylesheet" href="css/magnific-popup.css">
<link href="css/css.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="css/aos.css">
<link rel="stylesheet" href="css/ionicons.min.css">
<link rel="stylesheet" href="css/bootstrap-datepicker.css">
<link rel="stylesheet" href="css/jquery.timepicker.css">
<link rel="stylesheet" href="css/flaticon.css">
<link rel="stylesheet" href="css/icomoon.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" type="text/css" href="static/iconfont.css">
<link rel="stylesheet" href="static/chat.css">
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" href="css/Devis_InnerHTML.css">
</head>
<body>
<!--导航栏-->
<nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar">
<div class="container">
<img src="images/title.png" class="Accueil">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation">
<span class="oi oi-menu">Menu</span>
</button>
<div class="collapse navbar-collapse" id="ftco-nav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a href="index.html" class="nav-link">Accueil</a></li>
<li class="nav-item"><a href="presentation.html" class="nav-link">Présentation</a></li>
<li class="nav-item"><a href="produits.html" class="nav-link">Produits</a></li>
<li class="nav-item"><a class="nav-link" href="QRShop.html">QRshop</a></li>
<li class="nav-item"><a href="NosClients.html" class="nav-link">NosClients</a></li>
<li class="nav-item"><a href="contact.html" class="nav-link">Contact</a></li>
<li class="nav-item cta"><a href="#devis" class="nav-link" data-toggle="modal" data-target="#modalRequest"><span>DEVIS</span></a></li>
</ul>
</div>
</div>
</nav>
<!-- END nav-->
<!--banner,轮播图部分-->
<div class="hero-wrap">
<div class="overlay"></div>
<div class="container-fluid">
<div class="slider-text d-md-flex align-items-center" data-scrollax-parent="true">
<div class="one-forth ftco-animate align-self-md-center" data-scrollax=" properties: { translateY: '70%' }">
<h1 class="mb-4"> La caisse enregistreuse
<span class="wrap"></span>
</strong>
</h1>
<h1 class="mb-4">
<strong class="typewrite" data-period="4000" data-type='[ "facilite votre vie", "économise votre temps", "augmente vos CA" ]'>
<span class="wrap"></span>
</strong>
</h1>
<p class="mb-md-5 mb-sm-3" data-scrollax="properties: { translateY: '30%', opacity: 1.6 }">Votre bon assistant de gestion !</p>
<p data-scrollax="properties: { translateY: '30%', opacity: 1.6 }">
<a href="#devis" class="btn btn-primary px-4 py-3 mt-3">DEMANDER UN DEVIS</a>
<a href="#" class="btn btn-primary btn-outline-primary px-4 py-3 mt-3">Nos Produits</a>
</p>
</div>
<div class="one-half align-self-md-end align-self-sm-center">
<div class="slider-carousel owl-carousel">
<div class="item">
<img src="images/dashboard_full_3.png" class="img-fluid img"alt="">
</div>
<div class="item">
<img src="images/dashboard_full_4.png" class="img-fluid img"alt="">
</div>
<div class="item">
<img src="images/dashboard_full_5.png" class="img-fluid img"alt="">
</div>
</div>
</div>
</div>
</div>
</div>
<!--banner部分结束-->
<!--分割线-->
<section class="ftco-section ftco-section-2">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3 class="heading-white">Nous fournissons un excellent service</h3>
</div>
</div>
</div>
</section>
<!--分割线结束-->
<!--三点优势部分-->
<section class="ftco-section ftco-services">
<div class="mt-5">
<div class="row d-flex no-gutters">
<div class="col-md-6 img ftco-animate" style="background-image: url(images/about.jpg);">
</div>
<div class="col-md-6 d-flex">
<div class="services-wrap">
<div class="heading-section mb-5 ftco-animate">
<h2 class="mb-2">Pourquoi nous choisir</h2>
<span class="subheading">Experts en logiciel de caisse enregistreuse</span>
</div>
<div class="list-services d-flex ftco-animate">
<div class="icon d-flex justify-content-center align-items-center">
<span><img class="icon" src="images/nf515.png"></span>
</div>
<div class="text">
<h3>Notre logiciel</h3>
<p>Logiciel légal & fiable & pratique. Il conforme à la loi des finances 2016 et au certifiée NF525, obligatoire à partir du 1er janvier 2018.</p>
</div>
</div>
<div class="list-services d-flex ftco-animate">
<div class="icon d-flex justify-content-center align-items-center">
<span><img class="icon" src="images/client.png"></span>
</div>
<div class="text">
<h3>Notre équipements</h3>
<p>Peut être utilisé sur les caisses, les téléphones mobiles, les tablettes et autres appareils. Prise en charge des systèmes Windows et Linux.</p>
</div>
</div>
<div class="list-services d-flex ftco-animate">
<div class="icon d-flex justify-content-center align-items-center">
<span><img class="icon" src="images/service.png"></span>
</div>
<div class="text">
<h3>Notre service</h3>
<p>À votre service 6 jours par semaine. Nous mettons à votre disposition un service après-vente multilingue en français, anglais, chinois et coréen.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--三点优势部分结束-->
<!--分割线-->
<section class="ftco-section ftco-counter img" id="section-counter" style="background-image: url(images/bg_1.jpg);" data-stellar-background-ratio="0.5">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-11">
<div class="row">
<div class="col-md-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<strong class="number" data-number="2">0</strong>
<span>agences</span>
</div>
</div>
</div>
<div class="col-md-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<strong class="number" data-number="1500">0</strong>
<span>collaborateurs</span>
</div>
</div>
</div>
<div class="col-md-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<strong class="number" data-number="6">0</strong>
<span>ans d’expérience</span>
</div>
</div>
</div>
<div class="col-md-3 d-flex justify-content-center counter-wrap ftco-animate">
<div class="block-18 text-center">
<div class="text">
<strong class="number" data-number="10000">0</strong>
<span>clients en France</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!--分割线部分结束-->
<!--陈列产品部分-->
<section class="ftco-section">
<div class="container-fluid">
<div class="row justify-content-center mb-5 pb-5">
<div class="col-md-7 text-center heading-section ftco-animate">
<h2 class="mb-2">LE MATÉRIEL</h2>
<span class="subheading">We're Happy to share our complete Projects</span>
</div>
</div>
<div class="row">
<div class="col-md-4 ftco-animate">
<div class="work-entry">
<a data-toggle="modal" data-target="#product1" class="img" style="background-image: url(images/work1.png);">
<div class="text d-flex justify-content-center align-items-center">
<div class="p-3">
<h3>Tablette</h3>
</div>
</div>
</a>
</div>
</div>
<div class="col-md-4 ftco-animate">
<div class="work-entry">
<a data-toggle="modal" data-target="#product2" class="img" style="background-image: url(images/work2.png);">
<div class="text d-flex justify-content-center align-items-center">
<div class="p-3">
<h3>Caisse traditionnelle</h3>
</div>
</div>
</a>
</div>
</div>
<div class="col-md-4 ftco-animate">
<div class="work-entry">
<a data-toggle="modal" data-target="#product3" class="img" style="background-image: url(images/work3.png);">
<div class="text d-flex justify-content-center align-items-center">
<div class="p-3">
<h3>Télécommande portable</h3>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
</section>
<!--产品部分结束-->
<!--Devis部分-->
<section class="ftco-section bg-light" id="devis">
<!-- 加上container-fluid页面不超出 -->
<div class="container-fluid">
<div class="row justify-content-center mb-5 pb-5">
<div class="col-md-7 text-center heading-section ftco-animate">
<h2 class="mb-2">DEVIS CAISSE ENREGISTREUSE EN LIGNE</h2>
<span class="subheading">Pricing Plans</span>
</div>
</div>
</div>
<section class="ftco-section ftco-counter img"style="background-image: url(images/bg_1.jpg);" data-stellar-background-ratio="0.5">
<!-- 设置空的target阻止默认提交表单以后刷新 -->
<form class="row" style="text-align:center; margin-left:20px; margin-right:20px" method="post" action="storeDevis.php" target="nm_iframe">
<div class="colForm col-lg-4 col-md-6 col-sm-12 col-xs-12">
<div class="pricing-table">
<h3>Principaux produits</h3>
<HR>
<div class="form-group">
<!-- 这里设置的value值是php Post到的值,不设置默认显示on -->
<input type="radio" id="radio1" name="radio" value="Caisse et logiciel" checked>
<label class="circle" for="radio1" > Caisse et logiciel</label>
<HR>
<input type="radio" id="radio2" name="radio" value="Tablette et logiciel">
<label class="circle" for="radio2"> Tablette et logiciel</label>
<HR>
<input type="radio" id="radio3" name="radio" value="Logiciel">
<label class="circle" for="radio3"> Logiciel</label>
<HR>
</div>
</div>
</br>
</div>
<div class="colForm col-lg-4 col-md-6 col-sm-12 col-xs-12" >
<div class="pricing-table">
<h3>Autres produits</h3>
<HR>
<div class="form-group">
<!-- php name后面必须加[] -->
<input name="checkbox[]" value="Smartphone" type="checkbox" id="checkbox1">
<label class="circle" for="checkbox1"> Smartphone</label>
<HR>
<input name="checkbox[]" value="Imprimante" type="checkbox" id="checkbox2">
<label class="circle" for="checkbox2"> Imprimante</label>
<HR>
<input name="checkbox[]" value="Tiroir" type="checkbox" id="checkbox3">
<label class="circle" for="checkbox3"> Tiroir</label>
<HR>
<input name="checkbox[]" value="Balance" type="checkbox" id="checkbox4">
<label class="circle" for="checkbox4"> Balance</label>
<HR>
<input name="checkbox[]" value="Scanneur" type="checkbox" id="checkbox5">
<label class="circle" for="checkbox5"> Scanneur</label>
<HR>
<input name="checkbox[]" value="Ecran de client" type="checkbox" id="checkbox6">
<label class="circle" for="checkbox6"> Ecran de client</label>
<HR>
<input name="checkbox[]" value="Conseillez-moi" type="checkbox" id="checkbox7">
<label class="circle" for="checkbox7"> Conseillez-moi</label>
</div>
</div>
</br>
</div>
<div class="colForm col-lg-4 col-md-6 col-sm-12 col-xs-12" >
<div class="pricing-table" >
<h3>Votre Informations</h3>
<HR>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<input type="text" name="societe" class="form-control" id="societe" placeholder="Nom de la société *" required="required">
</div>
</div>
</br>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="email" placeholder="Mail *" required="required">
</div>
</div>
</br>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<input type="text" name="telephone" class="form-control" id="telephone" placeholder="Tel *" required="required">
</div>
</div>
</br>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<input type="text" name="codePostale" class="form-control" id="codePostale" placeholder="Code postale" required="required">
</div>
</div>
</br>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<input type="text" name="addresse" class="form-control" id="addresse" placeholder="Addresse" required="required">
</div>
</div>
</br>
<div class="row">
<div class="col-sm-1"></div>
<div class="col-sm-10">
<textarea rows="3" name="message" class="form-control" id="description" placeholder="Votre message"></textarea>
</div>
</div>
<div class="actions">
</br>
<input type="submit" id="obtenirDevis" value="OBTENIR LE DEVIS" name="submit" id="submitButton" class="btn btn-primary px-4 py-2" title="Submit Your Message!" />
</div>
</div>
</div>
</form>
</section>
</div>
</section>
<iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe>
<script>
//点发送按钮发送消息
$("#obtenirDevis").click(function () {
alert("Soumis avec succès!");
});
</script>
<footer class="ftco-footer ftco-bg-dark ftco-section">
<div class="container">
<div class="row mb-5">
<div class="col-md-3">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">WESHOP</h2>
<p>Weshop est un fournisseur pour les caisses enregistreuses tactiles. Weshop met à votre disposition des équipements et des logiciels de caisse complets, aussi des équipements de réseau( routeur, téléphone portable).</p>
</div>
<ul class="ftco-footer-social list-unstyled float-md-left float-lft ">
<li class="ftco-animate"><a href="#"><span class="icon-wechat"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-youtube"></span></a></li>
<li class="ftco-animate"><a href="#"><span class="icon-message"></span></a></li>
</ul>
</div>
<div class="col-md-2">
<div class="ftco-footer-widget mb-4 ml-md-5">
<h2 class="ftco-heading-2">Quick Links</h2>
<ul class="list-unstyled">
<li><a href="#" class="py-2 d-block">About</a></li>
<li><a href="#" class="py-2 d-block">Features</a></li>
<li><a href="#" class="py-2 d-block">Projects</a></li>
<li><a href="#" class="py-2 d-block">Blog</a></li>
<li><a href="#" class="py-2 d-block">Contact</a></li>
</ul>
</div>
</div>
<div class="col-md-4 pr-md-4">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Recent Blog</h2>
<div class="block-21 mb-4 d-flex">
<a class="blog-img mr-4" style="background-image: url(images/image_1.jpg);"></a>
<div class="text">
<h3 class="heading"><a href="#">Even the all-powerful Pointing has no control about</a></h3>
<div class="meta">
<div><a href="#"><span class="icon-calendar"></span> Sept 15, 2018</a></div>
<div><a href="#"><span class="icon-person"></span> Admin</a></div>
<div><a href="#"><span class="icon-chat"></span> 19</a></div>
</div>
</div>
</div>
<div class="block-21 mb-4 d-flex">
<a class="blog-img mr-4" style="background-image: url(images/image_2.jpg);"></a>
<div class="text">
<h3 class="heading"><a href="#">Even the all-powerful Pointing has no control about</a></h3>
<div class="meta">
<div><a href="#"><span class="icon-calendar"></span> Sept 15, 2018</a></div>
<div><a href="#"><span class="icon-person"></span> Admin</a></div>
<div><a href="#"><span class="icon-chat"></span> 19</a></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="ftco-footer-widget mb-4">
<h2 class="ftco-heading-2">Contact Info</h2>
<div class="block-23 mb-3">
<ul>
<li><span class="icon icon-map-marker"></span><span class="text">8 avenue <NAME>, 93000 Bobigny, 93000</span></li>
<li><a href="#"><span class="icon icon-phone"></span><span class="text">+33 1 48 46 12 88</span></a></li>
<li><a href="#"><span class="icon icon-envelope"></span><span class="text"><EMAIL></span></a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<p><!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
Copyright ©<script>document.write(new Date().getFullYear());</script> Tous droits réservés | Pour plus d’informations voir <NAME>
<!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --></p>
</div>
</div>
</div>
</footer>
<!-- loader -->
<div id="ftco-loader" class="show fullscreen">
<svg class="circular" width="48px" height="48px">
<circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/>
<circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/>
</svg>
</div>
<!--客服悬浮窗-->
<div class="livechat-girl animated"> <img class="girl" src="images/en_3.png">
<div class="livechat-hint rd-notice-tooltip rd-notice-type-success rd-notice-position-left single-line show_hint">
<div class="rd-notice-content">Bonjour, je peut vous aider?</div>
</div>
<div class="animated-circles">
<div class="circle c-1"></div>
<div class="circle c-2"></div>
<div class="circle c-3"></div>
</div>
</div>
<!--客服悬浮窗结束-->
<!--客服悬浮窗JS-->
<script type="text/javascript">
(function ($) {
setInterval(function () {
if ($(".animated-circles").hasClass("animated")) {
$(".animated-circles").removeClass("animated");
} else {
$(".animated-circles").addClass('animated');
}
}, 3000);
var wait = setInterval(function () {
$(".livechat-hint").removeClass("show_hint").addClass("hide_hint");
clearInterval(wait);
}, 4500);
$(".livechat-girl").hover(function () {
clearInterval(wait);
$(".livechat-hint").removeClass("hide_hint").addClass("show_hint");
}, function () {
$(".livechat-hint").removeClass("show_hint").addClass("hide_hint");
}).click(function () {
$(".chatBox").toggle(100);
$(".chatBox-head-two").toggle();
$(".chatBox-kuang").fadeToggle();
$(".livechat-girl").css("display", "none");
});
})(jQuery);
</script>
<!--客服悬浮窗JS结束-->
<!--产品图弹窗介绍-->
<div class="modal fade" id="product1" tabindex="-1" role="dialog" aria-labelledby="modalLabel" style="display:none">
<!-- 在style文件中设置lg max-height:1200px-->
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Caisse</h4></div>
<div id="_modalDialog_body" class="modal-body">
<!-- 设置这个div的大小,超出部分显示滚动条 -->
<div class="row">
<div class="col-md-8">
<img class="img_product" src="images/work-1.jpg" alt="work1">
</div>
<div class="col-md-4">
<h2>Introduction:</h2>
<h4>balabalabalabala</h4>
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button type="submit" class="btn btn-primary">确定</button>-->
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="product2" tabindex="-1" role="dialog" aria-labelledby="modalLabel" style="display:none">
<!-- 在style文件中设置lg max-height:1200px-->
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Caisse</h4>
</div>
<div id="_modalDialog_body" class="modal-body">
<!-- 设置这个div的大小,超出部分显示滚动条 -->
<div class="row">
<div class="col-md-8">
<img class="img_product" src="images/work-2.jpg" alt="work2">
</div>
<div class="col-md-4">
<h2>Introduction:</h2>
<h4>balabalabalabala</h4>
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button type="submit" class="btn btn-primary">确定</button>-->
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="product3" tabindex="-1" role="dialog" aria-labelledby="modalLabel" style="display:none">
<!-- 在style文件中设置lg max-height:1200px-->
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modalLabel">Caisse</h4></div>
<div id="_modalDialog_body" class="modal-body">
<!-- 设置这个div的大小,超出部分显示滚动条 -->
<div class="row">
<div class="col-md-8">
<img class="img_product" src="images/work-3.jpg" alt="work3">
</div>
<div class="col-md-4">
<h2>Introduction:</h2>
<h4>balabalabalabala</h4>
</div>
</div>
</div>
<div class="modal-footer">
<!-- <button type="submit" class="btn btn-primary">确定</button>-->
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<!--产品图弹窗部分结束-->
<!-- 客服自动回复聊天框 -->
<div class="chatContainer" style="z-index: 100;">
<div class="chat-message-num"></div>
<div class="chatBox" ref="chatBox" style="display: none">
<div class="chatBox-head">
<div class="chatBox-head-two">
<div class="chat-people">
<div class="ChatInfoHead">
<img src="static/icon01.png" alt="头像"/>
</div>
</div>
<div class="chat-close"><span style="font-weight: bolder;">×</span></div>
</div>
</div>
<div class="chatBox-info">
<div class="chatBox-kuang" ref="chatBoxkuang">
<div class="chatBox-content">
<div class="chatBox-content-demo" id="chatBox-content-demo">
<div class="clearfloat">
<div class="author-name">
<small class="chat-date" id="systime">2020-9-4 15:33:33</small>
</div>
<div class="left">
<div class="chat-avatars"><img src="static/icon01.png" alt="头像"/></div>
<div class="chat-message">
Bonjour, je peut vous aider?
</div>
</div>
</div>
</div>
</div>
<div class="chatBox-send">
<!-- <div class="div-textarea"></div> -->
<div>
<input class="div-textarea" id="message" style="border: 0px;">
</div>
<div>
<button id="chat-biaoqing" class="btn-default-styles">
<i class="iconfont icon-biaoqing"></i>
</button>
<label id="chat-tuxiang" title="发送图片" for="inputImage" class="btn-default-styles">
<input type="file" onchange="selectImg(this)" accept="image/jpg,image/jpeg,image/png"
name="file" id="inputImage" class="hidden">
<i class="iconfont icon-tuxiang"></i>
</label>
<button id="chat-fasong" class="btn-default-styles"><i class="iconfont icon-fasong"></i></button>
</div>
<div class="biaoqing-photo">
<ul>
<li><span class="emoji-picker-image" style="background-position: -9px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -40px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -71px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -102px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -133px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -164px -18px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -9px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -40px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -71px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -102px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -133px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -164px -52px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -9px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -40px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -71px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -102px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -133px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -164px -86px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -9px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -40px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -71px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -102px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -133px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -164px -120px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -9px -154px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -40px -154px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -71px -154px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -102px -154px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -133px -154px;"></span></li>
<li><span class="emoji-picker-image" style="background-position: -164px -154px;"></span></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 客服自动回复聊天框部分结束 -->
<!--检测IP-->
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
console.log(returnCitySN["cip"] + ',' + returnCitySN["cname"]);
var ip_client = returnCitySN["cip"];
</script>
<!--检测人工客服是否上线-->
<?php
require 'conn.php';
$cstm_online = 1;
?>
<!--客服人工回复-->
<!-- <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script> -->
<script>
var cstmer_online = 0;
$(function () {
var wsurl = 'ws://192.168.1.100:8090';
var ws;
var i = 0;
if (window.WebSocket) {
ws = new WebSocket(wsurl);
//连接建立
ws.onopen = function (event) {
console.log("Connected to WebSocket server.");
$('.chatBox-content-demo').append(reply('Bonjour, avez-vous des questions ?'));
}
//收到消息
ws.onmessage = function (event) {
var msg = JSON.parse(event.data); //解析收到的json消息数据
console.log(msg);
var type = msg.type; // 消息类型
var umsg = msg.message; //消息文本
var uname = msg.name; //发送人
i++;
if (type == '192.168.127.12') {
$('.chatBox-content-demo').append(reply(umsg));
}
if (type == 'system') {
console.log(umsg);
}
$('#message').val('');
window.location.hash = '#' + i;
}
//发生错误
ws.onerror = function (event) {
i++;
console.log("Connected to WebSocket server error");
window.location.hash = '#' + i;
}
//连接关闭
ws.onclose = function (event) {
i++;
console.log('websocket Connection Closed. ');
$('.chatBox-content-demo').append(reply('Il y a une error sur Internet'));
window.location.hash = '#' + i;
}
function send() {
var message = $('#message').val();
if (!message) {
return false;
}
var msg = {
type: 'usermsg',
name: ip_client,
message: message,
};
try {
ws.send(JSON.stringify(msg));
repeatClientMsg(message);
document.getElementById('message').value = "";
} catch (ex) {
console.log(ex);
}
}
//按下enter键发送消息
$(window).keydown(function (event) {
if (event.keyCode == 13) {
var textContent = $("#message").val();
cstmer_online = 1;
if (cstmer_online == 1) {
send();
} else if (cstmer_online == 0) {
if (textContent != "") {
//聊天框默认最底部
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
document.getElementById('timenow').innerHTML = timenow();
if (textContent.indexOf("balabala1") != "-1" || textContent.indexOf("1") != "-1") {
var re = "<a href=\"#devis\">Rua~</a>";
reply(re);
} else if (textContent.indexOf("balabala2") != "-1" || textContent.indexOf("2") != "-1") {
var re = "RuaRua~";
reply(re);
} else if (textContent.indexOf("balabala3") != "-1" || textContent.indexOf("3") != "-1") {
var re = "RuaRuaRua~";
reply(re);
} else if (textContent.indexOf("balabala4") != "-1" || textContent.indexOf("4") != "-1") {
var re = "RuaRuaRuaRua~";
reply(re);
} else {
var re = "Questions susceptibles de vous intéresser: <br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(1)\",600)>1.balabala1</a><br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(2)\",600)>2.balabala2 </a><br><a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(3)\",600)>3.balabala3</a><br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(4)\",600)>4.balabala4</a>";
reply(re);
}
}
}
else {
reply ('il y a une error sur Internet');
console.log(客服部分运行错误);
}
}
});
//点发送按钮发送消息
$("#chat-fasong").click(function () {
var textContent = $("#message").val();
send();
if (textContent != "") {
//聊天框默认最底部
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
document.getElementById('timenow').innerHTML = timenow();
if (textContent.indexOf("balabala1") != "-1" || textContent.indexOf("1") != "-1") {
var re = "<a href=\"#devis\">Rua~</a>";
reply(re);
} else if (textContent.indexOf("balabala2") != "-1" || textContent.indexOf("2") != "-1") {
var re = "RuaRua~";
reply(re);
} else if (textContent.indexOf("balabala3") != "-1" || textContent.indexOf("3") != "-1") {
var re = "RuaRuaRua~";
reply(re);
} else if (textContent.indexOf("balabala4") != "-1" || textContent.indexOf("4") != "-1") {
var re = "RuaRuaRuaRua~";
reply(re);
} else {
var re = "Questions susceptibles de vous intéresser: <br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(1)\",600)>1.balabala1</a><br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(2)\",600)>2.balabala2 </a><br><a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(3)\",600)>3.balabala3</a><br> <a href=\"javascript:void(0);\" onclick=setTimeout(\"replyNum(4)\",600)>4.balabala4</a>";
reply(re);
}
}
});
} else {
alert('该浏览器不支持web socket');
}
});
</script>
<!--客服人工回复部分结束-->
<!--客服自动回复对话框JS部分-->
<script>
function timenow() {
var myDate = new Date();
var times = myDate.toLocaleString( );
return times
}
document.getElementById('systime').innerHTML = timenow();
screenFuc();
function screenFuc() {
var topHeight = $(".chatBox-head").innerHeight();//聊天头部高度
//屏幕小于768px时候,布局change
var winWidth = $(window).innerWidth();
if (winWidth <= 768) {
var totalHeight = $(window).height(); //页面整体高度
//中间内容高度
$(".chatBox-info").css("height", totalHeight - topHeight);
$(".chatBox-content-demo").css("height", totalHeight - topHeight - 55);
// $(".chatBox-list").css("height", totalHeight - topHeight-200);
$(".chatBox-kuang").css("height", totalHeight - topHeight);
$(".div-textarea").css("width", winWidth - 106);
} else {
$(".chatBox-info").css("height", 495);
$(".chatBox-content").css("height", 448);
$(".chatBox-content-demo").css("height", 448);
$(".chatBox-list").css("height", 495);
$(".chatBox-kuang").css("height", 495);
// !import不可覆盖,以删除
$(".div-textarea").css("width", 245);
}
}
(window.onresize = function () {
screenFuc();
})();
//未读信息数量为空时
var totalNum = $(".chat-message-num").html();
if (totalNum == "") {
$(".chat-message-num").css("padding", 0);
}
$(".message-num").each(function () {
var wdNum = $(this).html();
if (wdNum == "") {
$(this).css("padding", 0);
}
});
$(".chat-close").click(function () {
$(".chatBox").toggle(100);
$(".chatBox-head-two").toggle();
$(".chatBox-kuang").fadeToggle();
$(".livechat-girl").css("display", "block");
})
// changer
function repeatClientMsg(ques) {
if (ques != "") {
$(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
"<div class=\"author-name\"><small class=\"chat-date\" id=\"timenow\"></small> </div> " +
"<div class=\"right\"> <div class=\"chat-message\"> " + ques + " </div> " +
"<div class=\"chat-avatars\"><img src=\"static/icon00.png\" alt=\"头像\" /></div> </div> </div>");
}
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
}
//changer
function replyNum(num) {
if (num == 1) {
repeatClientMsg("balabala1");
var re = "1.我们是冠军!";
reply(re);
} else if (num == 2) {
repeatClientMsg("balabala2");
var re = "2.我们是冠军!我们是冠军!";
reply(re);
} else if (num == 3) {
repeatClientMsg("balabala3");
var re = "3.我们是冠军!我们是冠军!我们是冠军!";
reply(re);
} else if (num == 4) {
repeatClientMsg("balabala4");
var re = "4.我们是冠军!我们是冠军!我们是冠军!我们是冠军!";
reply(re);
}
}
// 发送表情
$("#chat-biaoqing").click(function () {
$(".biaoqing-photo").toggle();
});
$(document).click(function () {
$(".biaoqing-photo").css("display", "none");
});
$("#chat-biaoqing").click(function (event) {
event.stopPropagation();//阻止事件
});
$(".emoji-picker-image").each(function () {
$(this).click(function () {
var bq = $(this).parent().html();
console.log(bq)
$(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
"<div class=\"author-name\"><small class=\"chat-date\" id=\"timenow\"></small> </div> " +
"<div class=\"right\"> <div class=\"chat-message\"> " + bq + " </div> " +
"<div class=\"chat-avatars\"><img src=\"static/icon00.png\" alt=\"头像\" /></div> </div> </div>");
//发送后关闭表情框
$(".biaoqing-photo").toggle();
//聊天框默认最底部
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
document.getElementById('timenow').innerHTML = timenow();
})
});
//自动回复
function reply(textContent) {
if (textContent != "") {
$(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
"<div class=\"author-name\"><small class=\"chat-date\" id=\"timenow\"></small> </div> " +
"<div class=\"left\"><div class=\"chat-avatars\"><img src=\"static/icon01.png\" alt=\"头像\" /></div> " +
"<div class=\"chat-message\"> " + textContent + " </div> </div> </div>");
//聊天框默认最底部
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
document.getElementById('timenow').innerHTML = timenow();
}
}
// 发送图片
function selectImg(pic) {
if (!pic.files || !pic.files[0]) {
return;
}
var reader = new FileReader();
reader.onload = function (evt) {
var images = evt.target.result;
$(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
"<div class=\"author-name\"><small class=\"chat-date\" id=\"timenow\"></small> </div> " +
"<div class=\"right\"> <div class=\"chat-message\"><img src=" + images + "></div> " +
"<div class=\"chat-avatars\"><img src=\"static/icon01.png\" alt=\"头像\" /></div> </div> </div>");
//聊天框默认最底部
$(document).ready(function () {
$("#chatBox-content-demo").scrollTop($("#chatBox-content-demo")[0].scrollHeight);
});
document.getElementById('timenow').innerHTML = timenow();
};
reader.readAsDataURL(pic.files[0]);
}
</script>
<!--客服自动回复对话框JS部分结束-->
<script src="js/jquery.min.js"></script>
<script src="js/jquery-migrate-3.0.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.1.3.js"></script>
<script src="js/jquery.waypoints.min.js"></script>
<script src="js/jquery.stellar.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script src="js/jquery.magnific-popup.min.js"></script>
<script src="js/aos.js"></script>
<script src="js/jquery.animateNumber.min.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
<script src="js/jquery.timepicker.min.js"></script>
<script src="js/scrollax.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=<KEY>&sensor=false"></script>
<script src="js/google-map.js"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep>/storeDevis.php
<?php
require 'conn.php';
$data = $_POST;
$prinProduits = $data['radio'];
//autreproduit
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($checkbox);$i++){
$autreProduits= $autreProduits.$checkbox[$i]." ";
}
$societe = $data['societe'];
$email = $data['email'];
$telephone = $data['telephone'];
$codePostale = $data['codePostale'];
$addresse = $data['addresse'];
$messages = $data['message'];
echo "电话:".$telephone;
$sql = "INSERT INTO Devis (prinProduits, autreProduits, societe, email, telephone, codePostale, addresse, messages, statut)
VALUES ('$prinProduits', '$autreProduits', '$societe', '$email','$telephone','$codePostale','$addresse','$messages',0);";
if ($conn->query($sql) === TRUE) {
echo "新记录插入成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?> | 5fd83ae6b90332b3bb784ec7064058773ad5624c | [
"PHP"
] | 4 | PHP | Fred-Victor-YANG/WeShop | 278664761a4bea6649e89d97e6556d61e3153ddf | 4228a0eef939b24fefefee21ad48e76957a1155c |
refs/heads/master | <file_sep>import {Animal} from './Animal'
export class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log("Woof! Woof!");
}
}
<file_sep>import {Dog} from './Dog'
const dog = new Dog("Bob");
dog.bark();
dog.move(10);
dog.bark();
console.log(dog.name) | 36b91a7ed14b482f3a69334ebe8e14f29eebb893 | [
"TypeScript"
] | 2 | TypeScript | AnastasiiaPosulikhina/ASPNETCoreAppWithAngular | 66f838099aceda1f8046cfd45ae903557d9a9c5b | 4529b77de8f022ead238f0599b9603a243d21309 |
refs/heads/master | <file_sep>#### element框架message组件源码
如果项目中引入了element,可以从node_modules里找到element-ui来查看源码,如果没有引入可以从github上搜索element源码库,来查看源码。
下面我们来一步步的查看源码,首先来看message是如何挂载到Vue上,并找到组件的引入位置。
```
/* src/index.js */
import Message from '../packages/message/index.js';
//在index中引入message组件,并将其挂载到Vue对象的原型链上
Vue.prototype.$message = Message;
```
下面,我们来找到message组件的源文件。
```
/* packages/message/index.js */
import Message from './src/main.js';
export default Message;
```
在上面我们看到index的主要作用是将message暴露给外界,而message的实现细节是在main.js中。
这里需要先要了解一个Vue.extend的概念,在Vue的组件封装当中Vue.extend是一个常用必备的函数,来自官网的释义:使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。
```
/* packages/message/src/main.js */
import Vue from 'vue';
import Main from './main.vue';
import { PopupManager } from 'element-ui/src/utils/popup';
import { isVNode } from 'element-ui/src/utils/vdom';
//将引入的message组件构造成一个子类,便于后面的实例化
let MessageConstructor = Vue.extend(Main);
//保存message实例化变量
let instance;
//保存多个message实例的数组
let instances = [];
//用于多个message的唯一id值
let seed = 1;
const Message = function(options) {
//用于判断当前运行的平台
if (Vue.prototype.$isServer) return;
options = options || {};
//当只输入字符串时
if (typeof options === 'string') {
options = {
message: options
};
}
let userOnClose = options.onClose;
let id = 'message_' + seed++;
//将关闭的函数钩子保存到options中
options.onClose = function() {
Message.close(id, userOnClose);
};
//实例化message对象
instance = new MessageConstructor({
data: options
});
//为一个实例设置一个ID
instance.id = id;
//判断内容是不是HTML片段
if (isVNode(instance.message)) {
instance.$slots.default = [instance.message];
instance.message = null;
}
//挂载返回实例自身
//$mount在下文作释义
instance.vm = instance.$mount();
//将标签添加为body的子标签
document.body.appendChild(instance.vm.$el);
instance.vm.visible = true;
instance.dom = instance.vm.$el;
//设置z-index层级,后调用的层级越高
instance.dom.style.zIndex = PopupManager.nextZIndex();
//放入保存的实例数组中
instances.push(instance);
返回实例
return instance.vm;
};
//判断message的图标类型
['success', 'warning', 'info', 'error'].forEach(type => {
Message[type] = options => {
if (typeof options === 'string') {
options = {
message: options
};
}
options.type = type;
return Message(options);
};
});
//message关闭函数
Message.close = function(id, userOnClose) {
for (let i = 0, len = instances.length; i < len; i++) {
//通过对比唯一id来找到想要关闭的message
if (id === instances[i].id) {
//如果关闭的函数有被定义,则执行挂在钩子上的函数
if (typeof userOnClose === 'function') {
userOnClose(instances[i]);
}
//将关闭的message实例,移出数组
instances.splice(i, 1);
break;
}
}
};
//关闭全部message实例
Message.closeAll = function() {
for (let i = instances.length - 1; i >= 0; i--) {
instances[i].close();
}
};
//将message模块暴露给外界
export default Message;
```
vm.$mount():如果 Vue 实例在实例化时没有收到 el 选项,则它处于“未挂载”状态,没有关联的 DOM 元素。可以使用 vm.$mount() 手动地挂载一个未挂载的实例。
如果没有提供 elementOrSelector 参数,模板将被渲染为文档之外的的元素,并且你必须使用原生 DOM API 把它插入文档中。
这个方法返回实例自身,因而可以链式调用其它实例方法。<file_sep>项目遇到的问题
====
实现卡片选择效果时,先是使用e.target来判断点击的那个卡片,但是此时会出现多种选择情况的bug,导致选择效果混乱,而后来使用$(this)来控制显示的效果时就没有了bug。
改变前:
````
$('.manCard').click(function (e) {
$(e.target).parent().addClass('cardActive');
$(e.target).parent().siblings().removeClass('cardActive');
})
````
改变后:
````
$('.manCard').click(function () {
$(this).addClass('cardActive').siblings().removeClass('cardActive')
})
````
js原生编写下拉列表:
先让文本框中显示一个初始的值,然后给文本框增加点击事件,点击之后将下拉列表的display属性改为反,然后给列表中的子项加点击事件,如果被点击就将li的值赋给文本框的innerHTML。
````
<div id="dropDown">
<span class="select">请选择游戏名称</span>
<ul class="sub">
<li>地下城与勇士</li>
<li>魔兽世界(国服)</li>
<li>魔兽世界(台服)</li>
<li>热血江湖</li>
<li>大话西游II</li>
<li>QQ幻想世界</li>
</ul>
</div>
<script>
var oSelec = document.getElementsByTagName('span')[0];
var oSub = document.getElementsByTagName('ul')[0];
var aLi = document.getElementsByTagName('li');
oSelec.onclick = function(event){
var style = oSub.style;
style.display = style.display=="block"? "none" : "block";
(event || window.event).cancelBubble = true;
};
for(var i = 0;i < aLi.length;i++){
aLi[i].onclick = function(){
oSelec.innerHTML = this.innerHTML;
}
document.onclick = function(){
oSub.style.display = "none";
}
}
</script>
````
<file_sep>### 好用的vsCode插件
* Auto Close Tag
* Auto Rename tag
* Beautify
* BreadCrumb in StatusBar
* GitLens — Git supercharged
* JavaScript (ES6) code snippets
* Vue 2 Snippets
* VSCode Great Icons
* Path Intellisense
<file_sep>/* 表格开始 */
var Data = { Rows : [
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" },
{ id: '0101', name: "商务一部", remark: "12"},
{ id: '0102', name: "商务二部", remark: "213" },
{ id: '0103', name: "商务三部", remark: "12" }
]};
$(f_initGrid);
var manager, g;
var grid = null;
function f_initGrid() {
grid = $("#maingrid").ligerGrid({
columns : [
{ display: '商务部', name: 'name', id: 'id1', align: 'left' },
{ display: '职级', name: 'remark' , align: 'left' },
{ display: '正式', name: 'remark' , align: 'left' },
{ display: '上限(个)', name: 'remark' , align: 'center' },
{ display: '保护期(天)', name: 'remark' , align: 'center' },
{ display: '绝对保护期(天)', name: 'remark' , align: 'center' }
],
alternatingRow: false,
data : Data,
tree: { columnId: 'id1' },
width: '100%',
height: '350px',
isScroll: false,
alternatingRow: true,
rowSelectable: false
});
};
function f_search()
{
grid.options.data = $.extend(true, {}, TreeDeptData);
grid.loadData(f_getWhere());
}
function f_getWhere() {
if (!grid) return null;
var clause = function (rowdata, rowindex) {
var key = $("#txtKey").val();
return rowdata.name.indexOf(key) > -1;
};
return clause;
}
/* 表格结束 */
$('#navList > li').click(
function(){
var library = $(this).html();
console.log(library);
$(this).addClass('navActive').siblings().removeClass('navActive');
$.post("url",
{
library: library
},
function(data,status){
if(status){
}else{
}
})
}
);
$('#department').change(function(){
console.log($(this).val());
});
$('#rank').change(function(){
console.log($(this).val());
});
$('#zs').change(function(){
console.log($(this).val());
}); <file_sep>面试整理
=====
一面
------
<file_sep>my test
=====
git提交代码操作
* git add .
* git commit -m "提交描述"
* git remote add origin 仓库地址
* git push -u origin master
<file_sep>大栗踩坑记
====
#### 前端常用的加密方法
* Base64编码
* 哈希算法(Hash常用MDS和SHA1)
* 加盐(add salt)
#### element的分页组件问题:
当改变当前页面为1时(包括其他数字),数据被改变了但是分页组件的当前页面高亮显示却没有变化。解决方式可以为 将分页的总数total设置为null,然后再去请求接口获取数据,这样就可以出发高亮显示了。
#### 1、element中表格的多选狂框列表头不支持更改?
> 解决方法为使用css伪元素进行元素定位并更改背景颜色和内容,将表头的多选框进行覆盖。
````
//在vue中使用组件引用,因为scoped的局部限制导致css不能被选中,所以将scoped去掉便可成功。
<style lang='scss'>
.detailDia {
td{
text-align: center;
.el-select {
width: 120px !important;
}
}
thead>tr>th:last-child::after{
content: "关键属性";
background-color: #ffffff;
color: #909399;
position: absolute;
left: 0;
top: 12px;
z-index: 10000;
}
}
</style>
````
#### Css的currentColor值:当前的标签所继承的文字颜色。(可以跟随当前标签的设置而改变颜色)
#### css选择器
* 元素选择器
* 关系选择器
* 属性选择器
* 伪类选择器
* 伪对象选择器
元素选择器:
* *选择所有的元素
* E元素选择器、选择指定的元素
* #Id id选择器
* .class 类选择器
关系选择器:
* E F 包含选择器(选择所有包含在E元素里面的F元素)
* E>F 子选择器(选择所有作为E元素的子元素F)
* E+F 相邻选择器(选择紧贴在E元素之后的F元素)
* E~F 兄弟选择器(选择E元素所有兄弟元素F)
属性选择器:
* E[att] 选择具有att属性的E元素
* E[att="val"] 选择具有att属性且属性值等于val的E元素
* E[att^="val"] 选择具有att属性且属性值为以val开头的字符串的E元素
* E[att$="val"] 选择具有att属性且属性值为以val结尾的字符串的E元素
* E[att*="val"] 选择具有att属性且属性值为包含val的字符串的E元素
伪类选择器(常用):
* E:link 设置超链接a在未被访问前的样式
* E:hover 设置元素鼠标在其悬停时的样式
* E:first-child 匹配父元素的第一个子元素E
* E:last-child 匹配父元素的最后一个子元素E
* E:nth-child(n) 匹配父元素的第n个子元素E
* E:nth-last-child(n) 匹配父元素的倒数第n个子元素E
* E:not(s) 匹配不含有s选择符的元素E
伪对象选择器:
* E:before/E::before 在目标元素E的前面插入的内容(content)
* E:after/E::after 在目标元素E的后面插入的内容(content)
* E:first-letter/E::first-letter 设置元素内的第一个字符的样式
* E:first-line/E::first-line 设置元素内的第一行的样式
* E::placeholder 设置元素文字占位符的样式
### webpack实现代码拆分的方式(分包):
* Entry Points:多入口分开打包
* Prevent Duplication:去重,抽离公共模块和第三方库
* Dynamic Imports:动态加载
### Webpack打包的优化方向可分为两个大方向:1、体积优化 2、速度优化
在速度方面常用的优化方式为:
* 减少文件搜索范围
* 增强代码压缩工具
* 加速代码构建速度
* 利用缓存
* 将不常变化的静态文件抽离
### 单元测试-Jest
### chrome更改了audio自动播放策略,会导致你的项目有一些自动播放的音频报错而播放不出来,报错提示为“Uncaught (in promise) DOMException”
解决方式:
* 为自动播放的多媒体增加定时器播放
* 播放后判断是否报错
````
var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
playPromise.catch(() => { media.play(); })
}
````<file_sep>搜狗面经
====
跨域:
制作雪碧图的方法:
base64的使用背景及制作方法:
本地调用后端接口的方法:
* nginx反向代理
* node搭一个proxy服务器
* 使用mock server
网页A中使用iframe嵌入了一个网页B,在网页A中如何获取网页B中的domain和title?
* window.document.domain 和 window.document.title获取值后利用跨域传输
本地模拟前后端联调:
* mockjs
<file_sep>#### vue构造函数的过程中有两个主要的文件,分别是core/instance/index.js文件以及core/index.js文件
* 前者是vue构造函数的定义文件,也可以叫其vue的出生文件,主要作用是定义Vue构造函数,并对其原型添加属性和方法,即实例属性和实例方法。
* 后者的主要作用是,为vue添加全局的API,也就是静态的方法和属性。
#### Vue 是一个 Multi-platform 的项目(web和weex),不同平台可能会内置不同的组件、指令,或者一些平台特有的功能等等,这就需要Vue根据不同的平台进行平台化地包装。
#### Vue提供了全局配置Vue.config.performance,我们通过将其设置为true,即开启性能追踪,可以追踪四个场景的性能:
* 组件初始化(component init)
* 编译(compile),将模板(template)编译成渲染函数
* 渲染(render),其实就是渲染函数的性能,或者说渲染函数执行且生成虚拟DOM(vnode)的性能
* 打补丁(patch),将虚拟DOM渲染为真实DOM的性能
<file_sep>var oSub = $('#sub');
oSub.click(function(){
// alert('保存成功');
var oRadios = document.getElementsByName('baseType');
var radioValue=null; // selectvalue为radio中选中的值
for(var i=0;i<oRadios.length;i++){
if(oRadios[i].checked==true) {
radioValue=oRadios[i].value;
break;
}
}
console.log(radioValue);
var oCheckbox1 = document.getElementsByName('rankArr');
var res = [];
for(var i=0;i<oCheckbox1.length;i++){
if(oCheckbox1[i].checked==true) {
res.push(oCheckbox1[i].value);
}
}
console.log(res);
var oCheckbox2 = document.getElementsByName('zs');
var res2 = [];
for(var i=0;i<oCheckbox2.length;i++){
if(oCheckbox2[i].checked==true) {
res2.push(oCheckbox2[i].value);
}
}
var rank = res.join('、');
var zs = res2.join('、');
var rankName = $('#rankName').val();
var dateName = $('#dateName').val();
var dateName1 = $('#dateName1').val();
console.log(rankName,dateName,dateName1);
$('#popUp').removeClass('yc');
setTimeout(function(){
$('#popUp').addClass('yc');
},1500);
$('#listNow').append("<tr>< <td>"+radioValue+"</td><td>"+rank+"</td> <td>"+zs+"</td><td>"+rankName+"</td><td>"+dateName+"</td><td>"+dateName1+"</td></tr>")
});<file_sep>web前端整理
===
* [页面布局](https://github.com/XinLi96/VueTest/blob/master/前端整理/页面布局.md)
* [CSS盒模型](https://github.com/XinLi96/VueTest/blob/master/前端整理/CSS盒模型.md)
* [DOM事件](https://github.com/XinLi96/VueTest/blob/master/前端整理/DOM事件.md)
* [HTTP协议](https://github.com/XinLi96/VueTest/blob/master/前端整理/HTTP协议.md)
* [原型链](https://github.com/XinLi96/VueTest/blob/master/前端整理/原型链.md)
* [面向对象](https://github.com/XinLi96/VueTest/blob/master/前端整理/面向对象.md)
* [通信类](https://github.com/XinLi96/VueTest/blob/master/前端整理/通信类.md)
* [安全类](https://github.com/XinLi96/VueTest/blob/master/前端整理/安全类.md)
* [算法类](https://github.com/XinLi96/VueTest/blob/master/前端整理/算法类.md)
* [渲染机制](https://github.com/XinLi96/VueTest/blob/master/前端整理/渲染机制.md)
* [js运行机制](https://github.com/XinLi96/VueTest/blob/master/前端整理/js运行机制.md)
* [页面性能](https://github.com/XinLi96/VueTest/blob/master/前端整理/页面性能.md)
* [错误监控](https://github.com/XinLi96/VueTest/blob/master/前端整理/错误监控.md)
* [多知识点的简单题](https://github.com/XinLi96/VueTest/blob/master/前端整理/多知识点的简单题.md)
* [this详解](https://github.com/XinLi96/VueTest/blob/master/前端整理/this分析.md)
* [CSS3新特性](https://github.com/XinLi96/VueTest/blob/master/前端整理/CSS3新特性.md)
* [蘑菇街面经](https://github.com/XinLi96/VueTest/blob/master/前端整理/蘑菇街面经.md)
* [Vue2.0的变化](https://github.com/XinLi96/VueTest/blob/master/前端整理/vue2.0的变化.md)
* [关于promise](https://github.com/XinLi96/VueTest/blob/master/前端整理/关于promise.md)
* [let和const](https://github.com/XinLi96/VueTest/blob/master/前端整理/let和const.md)
* [设计模式](https://github.com/XinLi96/VueTest/blob/master/前端整理/设计模式.md)
* [便利蜂面经](https://github.com/XinLi96/VueTest/blob/master/前端整理/便利蜂面经.md)
* [练习笔记](https://github.com/XinLi96/VueTest/blob/master/前端整理/练习笔记.md)
* [项目遇到问题](https://github.com/XinLi96/VueTest/blob/master/前端整理/项目遇到问题.md)
* [vue的面试问题](https://github.com/XinLi96/VueTest/blob/master/前端整理/vue的面试问题.md)
每一个努力的人都会有属于自己的一片天。
既然有缘看到这里,不妨互粉一下。
| 79ccc6714eb13c74da94075f03d2a9871c80b821 | [
"Markdown",
"JavaScript"
] | 11 | Markdown | menglol/VueTest | 1fa8edf1f719c0f43cd41f2acdc6322b2457ada8 | 9d110d9a25307f398d27550a76b88f9cee9bf2a2 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Jul 4 17:17:20 2019
@author: Ge
"""
import os
import csv
import math
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from scipy.spatial.distance import squareform, pdist
from math import sin, cos, asin, sqrt, radians
#calculate spherical distance
def haversine(lonlat1, lonlat2):
lat1, lon1 = lonlat1
lat2, lon2 = lonlat2
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def clustering_by_dbscan(X, eps, minpts):
distance_matrix = squareform(pdist(X, (lambda u, v: haversine(u, v))))
db = DBSCAN(eps=eps, min_samples=minpts, metric='precomputed')
y_db = db.fit_predict(distance_matrix)
X['cluster'] = y_db
labels = db.labels_
raito = len(labels[labels[:] == -1]) / len(labels)
print('eps ' + str(eps) + ' minpts ' + str(minpts) +
" 噪声比为" + str(raito))
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
respath = '//Users/qpple/Desktop/Dissertation/flickrSpider/cluster/parameter/eps'\
+ str(eps) + 'minpts' + str(minpts)
if not os.path.exists(respath):
os.mkdir(respath)
for i in range(n_clusters_):
one_cluster = X[labels == i]
one_cluster.to_csv(respath + '/class' + str(i) + '.csv',
encoding='utf-8')
plt.scatter(X['lat'], X['lng'], c=X['cluster'])
plt.savefig(respath + '/ result.png')
plt.show()
csv_path = "//Users/qpple/Desktop/Dissertation/flickrSpider/cluster/del_newpicinfo_filter.csv"
reader = csv.reader(open(csv_path, 'r', encoding='utf-8'))
location = {}
lat = []
lng = []
for i, row in enumerate(reader):
if i == 0:
continue
lat.append(float(row[5]))
lng.append(float(row[6]))
location['lat'] = lat
location['lng'] = lng
eps = 0.2
minpts = 5
while not math.isclose(eps, 3.0):
while minpts <= 30:
clustering_by_dbscan(pd.DataFrame(location), round(eps, 1), minpts)
minpts += 5
minpts = 5
eps += 0.2
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 21:54:39 2019
@author: Ge
"""
import os
import csv
# 已删除的图片的文件夹路径
source_path = "//Users/qpple/Desktop/Dissertation/flickrSpider/0627/0628delete/"
# csv的存放路径
source_csv = "//Users/qpple/Desktop/Dissertation/flickrSpider/0627/newpicinfo.csv"
target_csv = "//Users/qpple/Desktop/Dissertation/flickrSpider/0627/del_newpicinfo.csv"
filelist = os.listdir(source_path)
for i in range(len(filelist)):
filelist[i] =filelist[i].split('.')[0]
# print(filelist)
csv_reader = csv.reader(open(source_csv, 'r'))
csv_writer = csv.writer(open(target_csv, 'w'))
with open(target_csv, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for line in csv_reader:
if line[0] in filelist:
continue
writer.writerow(line)<file_sep>import os
import csv
import json
import flickrapi
import urllib.request
def downloadpic(pic_url, pic_name, pic_extend):
file_path = "//Users/qpple/Desktop/Dissertation/flickrSpider/0627/0629"
sep = '.'
try:
if not os.path.exists(file_path):
os.makedirs(file_path)
filename = '{}{}{}{}{}'.format(file_path, os.sep, pic_name, sep, pic_extend)
print(filename + '开始下载')
urllib.request.urlretrieve(pic_url, filename=filename)
print(filename + '下载完成')
except IOError as e:
print("IOError", e)
except Exception as e:
print("Exception", e)
def writetocsv(info):
with open("//Users/qpple/Desktop/Dissertation/flickrSpider/0627/newpicinfo0629.csv", 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
for pic in info:
writer.writerow(pic)
#print('csv 写入完成')
def walkdata(bboxlist, totalnum):
index = 1
target_list = [12, 13, 17, 18]
for index_bbox, bbox in enumerate(bboxlist):
if index_bbox not in target_list:
continue
photonum = 0
try:
photos = flickr.walk(bbox=bbox, accuracy=16,
content_type=1, per_page=100,
extras='url_c')
except Exception as e:
print(e)
picinfo = []
for i, photo in enumerate(photos):
newline = []
try:
picid = photo.get('id')
url = photo.get('url_c')
picname = photo.get('id')
text = json.loads(flickr.photos.getInfo(photo_id=picid, format='json'))
favorites = json.loads(flickr.photos.getFavorites(photo_id=picid, format='json'))
owner = photo.get('owner')
photolist = json.loads(flickr.people.getPublicPhotos(user_id=owner, format='json'))
totalphotos = photolist['photos']['total']
newline.append(picid)
newline.append(owner)
newline.append(totalphotos)
newline.append(len(favorites['photo']['person']))
newline.append(text['photo']['comments']['_content'])
newline.append(text['photo']['location']['latitude'])
newline.append(text['photo']['location']['longitude'])
newline.append(text['photo']['dates']['taken'])
tags = []
for tag in text['photo']['tags']['tag']:
tags.append(tag['raw'])
newline.append('-'.join(tags))
picinfo.append(newline)
downloadpic(url, picname, url.split('.')[-1])
photonum += 1
if i >= totalnum:
break
except Exception as e:
#print(e)
continue
print("地块" + str(index) + "共抓取" + str(photonum))
index += 1
writetocsv(picinfo)
# 必需的认证信息
api_key = '0d9b223318564736600bca26b5803737'
api_secret = '4ed777205f0bfeed'
# 最多抓取的数量
total_num = 3000
flickr = flickrapi.FlickrAPI(api_key, api_secret, cache=True)
# 测试地块
testBbox = '116.3433108,39.8643448,116.4833276,39.9708536'
# 生成地块坐标bbox
lon = ['116.203294', '116.2733024', '116.3433108',
'116.4133192', '116.48833276', '116.553336']
lat = ['39.757836', '39.8110904', '39.8643448',
'39.9175992', '39.9708536', '40.024108']
bboxList = []
for i in range(6):
if i == 5:
continue
for j in range(6):
if j == 5:
continue
temp = []
temp.append(lon[j])
temp.append(lat[i])
temp.append(lon[j + 1])
temp.append(lat[i + 1])
bboxList.append(','.join(temp))
with open("//Users/qpple/Desktop/Dissertation/flickrSpider/0627/newpicinfo0629.csv", 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
header = ['picid', 'owner_id', 'totalphotos', 'favorites', 'comments', 'lat', 'lon', 'taken', 'tags']
writer.writerow(header)
walkdata(bboxList, total_num)
| ad61d4ad809074dd7ac13cfa1bbab18cbccf1c15 | [
"Python"
] | 3 | Python | linge630/dissertation | ee5584c3f310ef51fe05c036cfea5051caf6dc78 | 04e16650da0a0795e32fdfa1207ab163f2dcab61 |
refs/heads/master | <file_sep># OSU-CS290
Repo for Oregonstate eecs CS290 projects
<file_sep>
class RealProgram{
public static void main(String[] args){
System.out.println("I am a real program that really does something!");
System.out.println("Watch me math.");
int a = 1;
int b = 2;
System.out.println("The sum of "+ a +" and "+ b +" is "+ (a+b));
System.out.println("Impressed?");
}
}
| 7c84727f598c5dffa379bcd02dc8c822bee7f432 | [
"Markdown",
"Java"
] | 2 | Markdown | Dylan-Mead/OSU-CS290 | 8badbc18a150a5f87aa00163043d0ed68c162347 | 47c647ba8911dcc738f05bcc359386842cd9db15 |
refs/heads/master | <repo_name>Tembocs/learn_pymongo<file_sep>/main.py
# main.py
"""Learning PyMongo."""
from pymongo import MongoClient
import pandas as pd
# This is for easy of testing
def create_collection():
"""Create collection and return it."""
client = MongoClient()
db = client.tutors_db
coll = db.tutors
return coll
def create_dataframe(excel_file):
"""Read Excel file and return a Pandas data frame."""
data_frame = pd.read_excel(excel_file)
# The new index will be used when parsing
data_frame['sno'] = data_frame.index + 1
data_frame = data_frame.set_index('sno', drop=True)
return data_frame
def insert_rows(data_frame, collection):
"""Take a dataframe, insert each row into a collection, return a list of inserted object ids."""
record_list = data_frame.to_dict(orient='records')
inserted = collection.insert_many(record_list)
return inserted.inserted_ids
if __name__ == '__main__':
print('\nThe script is Ok!')
| 88553b3362eaa13b7a4f424a924426b6b58c8802 | [
"Python"
] | 1 | Python | Tembocs/learn_pymongo | cb2139f99d28e7d5f412dc3b28d72048d6e6a8a5 | 2581c1f3826277c1a08dca15485a556adcb94786 |
refs/heads/main | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Management System</title>
<link rel = "icon" href = "icon.ico" type = "image/x-icon">
<link rel="stylesheet" href="styles.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
</head>
<body>
<div class="hero">
<div class="form-box">
<div class="button-box">
<div id="btn"></div>
<button type="button"class="toggle-btn" onclick="admin()">Admin</button>
<button type="button"class="toggle-btn" onclick="student()">Student</button>
</div>
<form action = " " method="post" id="admin"class="input-group" >
<input type="text" class="input-field" name='userID' placeholder="User Id" required>
<input type="<PASSWORD>" class="input-field" name="Password" placeholder="Enter <PASSWORD>" required>
<br><br>
<input type="submit" class="submit-btn" name="adminSubmit" value="logIn">
</form>
<form action=" " method ="post" id="student" class="input-group" >
<input type="text" class="input-field" name ="userID" placeholder="Student login Id" required>
<input type="<PASSWORD>" class="input-field" name ="password" placeholder="<PASSWORD>" required>
<input type="submit" class="submit-btn" name="submit" value="Login">
<br><br>
</form>
</div>
</div>
<script>
var x= document.getElementById("admin");
var y= document.getElementById("student");
var z= document.getElementById("btn");
function student(){
x.style.left="-400px"
y.style.left="50px"
z.style.left="110px"
}
function admin(){
x.style.left="50px"
y.style.left="450px"
z.style.left="0px"
}
</script>
<?php include "adminLogin.php"?>
<?php include "studentLogin.php"?>
</body>
</html><file_sep><?php
$query = "select * from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------details table--------->
<table class="data">
<h1 class="details">Details:</h1>
<tr>
<td>
<b>USN:</b>
</td>
<td>
<input type="text" name="USN" value="<?php echo $row['USN'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" value="<?php echo $row['firstName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" value="<?php echo $row['lastName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Phone No:</b>
</td>
<td>
<input type="text" name=" phoneNumber" value="<?php echo $row['phoneNumber'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Email:</b>
</td>
<td>
<input type="text" name="email" value="<?php echo $row['email'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>DOB:</b>
</td>
<td>
<input type="text" name="DOB" value="<?php echo $row['DOB'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>semester:</b>
</td>
<td>
<input type="text" name="semester" value="<?php echo $row['semester'] ?>"disabled>
</td>
</tr>
<?php
$query = "SELECT department.departmentName
FROM department
INNER JOIN student ON
department.departmentID = student.departmentID
where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run)){
?>
<tr>
<td>
<b>Department :</b>
</td>
<td>
<input type="text" name="department" value="<?php echo $row['departmentName']?> " disabled>
</td>
</tr>
<?php
}
?>
</table>
<?php}
?><file_sep><?php
session_start();
$userID =$_SESSION['userid'];
$connection = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connection,"sims");
$query="select USN from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
if(mysqli_num_rows($query_run)>0){
?>
<script>alert("student already exists");</script>
<?php
}
else
{
$query = "insert into student values('$_POST[USN]','$_POST[firstName]','$_POST[lastName]',$_POST[phoneNumber],
'$_POST[email]','$_POST[DOB]',$_POST[semester],'$userID','$_POST[USN]',$_POST[departmentID])";
$query_run = mysqli_query($connection,$query);
$query = " insert into attendance values( '$_POST[USN]','$_POST[firstName] $_POST[lastName]','$_POST[semester1]','$_POST[semester2]',
'$_POST[semester3]','$_POST[semester4]','$_POST[semester5]',
'$_POST[semester6]','$_POST[semester7]','$_POST[semester8]',$_POST[departmentID])";
$query_run = mysqli_query($connection,$query);
$query = " insert into result values( '$_POST[USN]','$_POST[sgpa1]','$_POST[sgpa2]',
'$_POST[sgpa3]','$_POST[sgpa4]','$_POST[sgpa5]',
'$_POST[sgpa6]','$_POST[sgpa7]','$_POST[sgpa8]',$_POST[departmentID])";
$query_run = mysqli_query($connection,$query);
?>
<script type="text/javascript">
alert("Details Added successfully.");
</script>
<?php
}
?>
<script type="text/javascript">
window.location.href = "adminDashboard.php"; //redirect to admindashboard
</script>
<file_sep><?php
$connection = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connection,"sims");
$query="select * from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
if(mysqli_num_rows($query_run)>0)
{
$query = "delete from student where USN = '$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
$query = "delete from attendance where USN = '$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
$query = "delete from result where USN = '$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
$query = "delete from studentLogin where USN = '$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
?>
<script type="text/javascript">
alert("Details Deleted successfully.");
</script>
<?php
}
else
{
?>
<script>alert("student does'nt exists");</script>
<?php
}
?>
<script>
window.location.href = "adminDashboard.php"; //redirect to admindashboard
</script>
<file_sep><?php
session_start();
if(isset($_POST['submit']))
{
session_start();
$connection=mysqli_connect("localhost","root","");
$db=mysqli_select_db($connection,"sims");
$query="select * from studentlogin where studentLoginID ='$_POST[userID]'";
$query_run=mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($query_run))
{
if($row['studentLoginID']==$_POST['userID'])
{
if($row['password']==$_POST['password'])
{
$_SESSION['USN'] = $row['studentLoginID'];
?>
<script>alert("login successful");</script>
<?php
header("Location: studentDashboard.php");
}
else
{
?>
<script> alert("wrong password");</script>
<?php
}
}
else
?>
<script>alert("wrong login id");</script>
<?php
}
}
?><file_sep><?php
$con=mysqli_connect("localhost","root","");
if(!$con)
die("Not able to connect with Database");
mysqli_select_db($con,"sims");
?><file_sep><?php
$connection = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connection,"sims");
$query="select * from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
if(mysqli_num_rows($query_run)>0)
{
$query = "update student set firstName='$_POST[firstName]',lastName='$_POST[lastName]',
phoneNumber=$_POST[phoneNumber],email='$_POST[email]',DOB='$_POST[DOB]',semester=$_POST[semester],
departmentID=$_POST[departmentID]
where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
$query = "update attendance set semester1=$_POST[semester1],semester2=$_POST[semester2],
semester3=$_POST[semester3],semester4=$_POST[semester4],semester5=$_POST[semester5],
semester6=$_POST[semester6],semester7=$_POST[semester7],semester8=$_POST[semester8] where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
$query = "update result set sgpa1=$_POST[sgpa1],sgpa2=$_POST[sgpa2],
sgpa3=$_POST[sgpa3],sgpa4=$_POST[sgpa4],sgpa5=$_POST[sgpa5],
sgpa6=$_POST[sgpa6],sgpa7=$_POST[sgpa7],sgpa8=$_POST[sgpa8] where USN='$_POST[USN]'";
$query_run = mysqli_query($connection,$query);
?>
<script type="text/javascript">
alert("Details Edited successfully.");
</script>
<?php
}
else
{
?>
<script>alert("student does'nt exists");</script>
<?php
}
?>
<script>
window.location.href = "adminDashboard.php"; //redirect to admindashboard
</script>
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Student Management System</title>
<link rel="stylesheet" href="studentDashboard.css?v=<?php echo time(); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="icon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
<?php
session_start();
$USN=" ";
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection, "sims");
?>
</head>
<body>
<div id="header"><br>
<center>
<div class="logo">
Student Management System
</div>
<div class="info">
<b><i class="fa fa-user" aria-hidden="true"></i> UserID: </b><?php echo $_SESSION['USN']; ?>
</div>
<div class="logout">
<a href="logout.php" onclick="logout()"> <i class="fa fa-sign-out" aria-hidden="true"></i> Logout<a>
</div>
</center>
</div>
<span id="topSpan">
<marquee behavior="" direction="">This portal is available from Dec 28 </marquee>
</span>
<div id="rightSide"><br><br>
<div id="demo">
<?php
$query = "select * from student where studentLoginID='$_SESSION[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------details table--------->
<table class="data">
<h1 class="details">Details:</h1>
<tr>
<td>
<b>USN:</b>
</td>
<td>
<input type="text" name="USN" value="<?php echo $row['USN'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" value="<?php echo $row['firstName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" value="<?php echo $row['lastName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Phone No:</b>
</td>
<td>
<input type="text" name=" phoneNumber" value="<?php echo $row['phoneNumber'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Email:</b>
</td>
<td>
<input type="text" name="email" value="<?php echo $row['email'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>DOB:</b>
</td>
<td>
<input type="text" name="DOB" value="<?php echo $row['DOB'] ?>"disabled>
</td>
</tr>
<?php
$query = "SELECT department.departmentName
FROM department
INNER JOIN student ON
department.departmentID = student.departmentID
where USN='$_SESSION[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run)){
?>
<tr>
<td>
<b>Semester:</b>
</td>
<td>
<input type="text" name="department" value="<?php echo $row['departmentName']?> " disabled>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
<?php
$query = "select * from attendance where USN='$_SESSION[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------attendance table--------->
<table class="data">
<h1 class="attendance">Attendance:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="semester1" value="<?php echo $row['semester1'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="semester2" value="<?php echo $row['semester2'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="semester3" value="<?php echo $row['semester3'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" semester4" value="<?php echo $row['semester4'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="semester5" value="<?php echo $row['semester5'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="semester6" value="<?php echo $row['semester6'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="semester7" value="<?php echo $row['semester7'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="semester8" value="<?php echo $row['semester8'] ?>"disabled>
</td>
</tr>
</table>
<?php
}
?>
<?php
$query = "select * from result where USN='$_SESSION[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------result table--------->
<table class="data">
<h1 class="result">Result:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="sgpa1" value="<?php echo $row['sgpa1'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="sgpa2" value="<?php echo $row['sgpa2'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="sgpa3" value="<?php echo $row['sgpa3'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" sgpa4" value="<?php echo $row['sgpa4'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="sgpa5" value="<?php echo $row['sgpa5'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="sgpa6" value="<?php echo $row['sgpa6'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="sgpa7" value="<?php echo $row['sgpa7'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="sgpa8" value="<?php echo $row['sgpa8'] ?>"disabled>
</td>
</tr>
</table>
<?php
}
?>
<file_sep><?php
session_start();
//session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.
//session is created when loggen in and session is destroyed when logged out.
$userid=" ";
$name=" ";
if(isset($_POST['adminSubmit']))
{
$connection=mysqli_connect("localhost","root","");
$db=mysqli_select_db($connection,"sims");
$query="select * from adminlogin where userID='$_POST[userID]'";
$query_run=mysqli_query($connection,$query);
while ($row = mysqli_fetch_assoc($query_run))
{
if($row['userID']==$_POST['userID'])
{
if($row['Password']==$_POST['Password'])
{
$_SESSION['userid']=$row['userID'];
$_SESSION['name']=$row['adminName'];
header("Location: adminDashboard.php");
}
else
{
?>
<script>alert("Wrong password");
</script>
<?php
}
}
else
?>
<script>alert("Wrong user id");</script>
<?php
}
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<title>Student Management System</title>
<link rel="stylesheet" href="adminDashboard.css?v=<?php echo time(); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="icon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet">
<?php
session_start();
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection, "sims");
?>
</head>
<body>
<div id="header"><br>
<center>
<div class="logo">
Student Management System
</div>
<div class="info">
<b><i class="fa fa-user" aria-hidden="true"></i> UserID: </b><?php echo $_SESSION['userid']; ?>
<b>Name: </b><?php echo $_SESSION['name']; ?>
</div>
<div class="logout">
<a href="logout.php" onclick="logout()"> <i class="fa fa-sign-out" aria-hidden="true"></i> Logout<a>
</div>
</center>
</div>
<span id="topSpan">
<marquee behavior="" direction="">This portal is available from Dec 28 </marquee>
</span>
<!---------------------------------------buttons----------------------------------------->
<div id=leftSide>
<form action="" method="post">
<table>
<tr>
<td>
<input type="submit" name="searchStudent" value="Search">
</td>
</tr>
<tr>
<td>
<input type="submit" name="editStudent" value="Edit">
</td>
</tr>
<tr>
<td>
<input type="submit" name="addStudent" value="Add">
</td>
</tr>
<tr>
<td>
<input type="submit" name="deleteStudent" value="Delete" class="button">
</td>
</tr>
</table>
</form>
</div>
<!----------------------------------------------------search student--------------------------------------------------->
<div id="rightSide">
<br><br>
<div id="demo" >
<?php
if (isset($_POST['searchStudent'])) {
?>
<center>
<form action="" method="post" id="search-modify">
<b>Enter USN to search:</b>
<input type="text" name="USN" id="usn-placeholder" placeholder="Enter your USN" required>
<input type="submit" name="searchStudentByUSN" value="Search" id="search-placeholder">
</form><br><br>
</center>
<?php
}
?>
<?php
if (isset($_POST['searchStudentByUSN']))
{
$query = "select * from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
if(mysqli_num_rows($query_run)>0)
{
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------details table--------->
<table class="data">
<h1 class="details">Details:</h1>
<tr>
<td>
<b>USN:</b>
</td>
<td>
<input type="text" name="USN" value="<?php echo $row['USN'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" value="<?php echo $row['firstName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" value="<?php echo $row['lastName'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Phone No:</b>
</td>
<td>
<input type="text" name=" phoneNumber" value="<?php echo $row['phoneNumber'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Email:</b>
</td>
<td>
<input type="text" name="email" value="<?php echo $row['email'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>DOB:</b>
</td>
<td>
<input type="text" name="DOB" value="<?php echo $row['DOB'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>semester:</b>
</td>
<td>
<input type="text" name="semester" value="<?php echo $row['semester'] ?>"disabled>
</td>
</tr>
<?php
$query = "SELECT department.departmentName
FROM department
INNER JOIN student ON
department.departmentID = student.departmentID
where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run)){
?>
<tr>
<td>
<b>Department :</b>
</td>
<td>
<input type="text" name="department" value="<?php echo $row['departmentName']?> " disabled>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
<?php
$query = "select * from attendance where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------attendance table--------->
<table class="data">
<h1 class="attendance">Attendance:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="semester1" value="<?php echo $row['semester1'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="semester2" value="<?php echo $row['semester2'] ?>" disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="semester3" value="<?php echo $row['semester3'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" semester4" value="<?php echo $row['semester4'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="semester5" value="<?php echo $row['semester5'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="semester6" value="<?php echo $row['semester6'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="semester7" value="<?php echo $row['semester7'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="semester8" value="<?php echo $row['semester8'] ?>"disabled>
</td>
</tr>
</table>
<?php
}
?>
<?php
$query = "select * from result where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<!---------result table--------->
<table class="data">
<h1 class="result">Result:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="sgpa1" value="<?php echo $row['sgpa1'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="sgpa2" value="<?php echo $row['sgpa2'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="sgpa3" value="<?php echo $row['sgpa3'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" sgpa4" value="<?php echo $row['sgpa4'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="sgpa5" value="<?php echo $row['sgpa5'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="sgpa6" value="<?php echo $row['sgpa6'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="sgpa7" value="<?php echo $row['sgpa7'] ?>"disabled>
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="sgpa8" value="<?php echo $row['sgpa8'] ?>"disabled>
</td>
</tr>
</table>
<?php
}}
else
{
?>
<script>alert("student does'nt exist");</script>
<?php
}
}
?>
<!---------------------------------------edit student------------------------------------------------------------>
<?php
if (isset($_POST['editStudent']))
{
?>
<center>
<form action="" method="post" id="search-modify">
<b>Enter USN to edit:</b>
<input type="text" name="USN" id="usn-placeholder" placeholder="Enter your USN" required>
<input type="submit" name="editStudentByUSN" value="Edit" id="search-placeholder">
</form><br><br>
</center>
<?php
}
if (isset($_POST['editStudentByUSN']))
{
$query = "select * from student where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<form action="editStudent.php" method="post">
<center><h2>Edit the details</h2></center>
<!---------details table--------->
<table class="edit-data">
<h1 class="details">Details:</h1>
<tr>
<td>
<b>USN:</b>
</td>
<td>
<input type="text" name="USN" value="<?php echo $row['USN'] ?>">
</td>
</tr>
<tr>
<td>
<b>First Name:</b>
</td>
<td>
<input type="text" name="firstName" value="<?php echo $row['firstName'] ?>">
</td>
</tr>
<tr>
<td>
<b>Last Name:</b>
</td>
<td>
<input type="text" name="lastName" value="<?php echo $row['lastName'] ?>">
</td>
</tr>
<tr>
<td>
<b>Phone No:</b>
</td>
<td>
<input type="text" name=" phoneNumber" value="<?php echo $row['phoneNumber'] ?>">
</td>
</tr>
<tr>
<td>
<b>Email:</b>
</td>
<td>
<input type="text" name="email" value="<?php echo $row['email'] ?>">
</td>
</tr>
<tr>
<td>
<b>DOB:</b>
</td>
<td>
<input type="text" name="DOB" value="<?php echo $row['DOB'] ?>">
</td>
</tr>
<tr>
<td>
<b>semester:</b>
</td>
<td>
<input type="text" name="semester" value="<?php echo $row['semester'] ?>">
</td>
</tr>
<?php
$query2 = "SELECT department.departmentName,department.departmentID
FROM department
INNER JOIN student ON
department.departmentID = student.departmentID
where USN='$_POST[USN]'";
$query_run2 = mysqli_query($connection, $query2);
while ($row2 = mysqli_fetch_assoc($query_run2))
{
?>
<tr>
<td>
<b>DepartmentID:</b>
</td>
<td>
<input type="text" name="departmentID"
value="<?php echo $row2['departmentID']?>" >
</td>
</tr>
<tr>
<td>
<b>Department:</b>
</td>
<td>
<input type="text" name="department"
value="<?php echo $row2['departmentName']?>" disabled>
</td>
</tr>
<?php
}
?>
<?php
}
?>
<!---------attendance table--------->
<?php
$query = "select * from attendance where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<table class="edit-data">
<h1 class="attendance">Attendance:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="semester1" value="<?php echo $row['semester1'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="semester2" value="<?php echo $row['semester2'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="semester3" value="<?php echo $row['semester3'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" semester4" value="<?php echo $row['semester4'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="semester5" value="<?php echo $row['semester5'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="semester6" value="<?php echo $row['semester6'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="semester7" value="<?php echo $row['semester7'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="semester8" value="<?php echo $row['semester8'] ?>">
</td>
</tr>
</table>
<?php
}
?>
<!---------result table--------->
<?php
$query = "select * from result where USN='$_POST[USN]'";
$query_run = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($query_run))
{
?>
<table class="edit-data">
<h1 class="result">Result:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="sgpa1" value="<?php echo $row['sgpa1'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="sgpa2" value="<?php echo $row['sgpa2'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="sgpa3" value="<?php echo $row['sgpa3'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" sgpa4" value="<?php echo $row['sgpa4'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="sgpa5" value="<?php echo $row['sgpa5'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="sgpa6" value="<?php echo $row['sgpa6'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="sgpa7" value="<?php echo $row['sgpa7'] ?>">
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="sgpa8" value="<?php echo $row['sgpa8'] ?>">
</td>
</tr>
</table>
<input id="save-btn" type="submit" name="add" value="Save">
</form>
<?php
}
}
?>
<!-------------------------------------add student--------------------------------------------------------------->
<?php
if(isset($_POST['addStudent']))
{
?>
<center><h2>Fill the details</h2></center>
<br>
<form action="addStudent.php" method="post">
<!---------details table--------->
<table class="add-data">
<h1 class="details">Details:</h1>
<tr>
<td><b>USN:</b></td>
<td><input type="text" name="USN" ></td>
</tr>
<tr>
<td><b>First Name:</b></td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><b>Last Name:</b></td>
<td><input type="text" name="lastName" ></td>
</tr>
<tr>
<td><b>Phone No:</b></td>
<td><input type="text" name="phoneNumber" ></td>
</tr>
<tr>
<td><b>DOB:</b></td>
<td><input type="text" name="DOB" ></td>
</tr>
<tr>
<td><b>Email:</b></td>
<td><input type="text" name="email" ></td>
</tr>
<tr>
<td><b>Semester:</b></td>
<td><input type="text" name="semester" ></td>
</tr>
<tr>
<td><b>Department ID:</b></td>
<td><input type="text" name="departmentID" ></td>
</tr>
</table>
<!---------attendance table--------->
<table class="add-data">
<h1 class="attendance">Attendance:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="semester1">
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="semester2" >
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="semester3" >
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name=" semester4" >
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="semester5" >
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="semester6">
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="semester7">
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="semester8" >
</td>
</tr>
</table>
<!---------result table--------->
<table class="add-data">
<h1 class="result">Result:</h1>
<tr>
<td>
<b>Semester 1:</b>
</td>
<td>
<input type="text" name="sgpa1" >
</td>
</tr>
<tr>
<td>
<b>Semester 2:</b>
</td>
<td>
<input type="text" name="sgpa2" >
</td>
</tr>
<tr>
<td>
<b>Semester 3:</b>
</td>
<td>
<input type="text" name="sgpa3" >
</td>
</tr>
<tr>
<td>
<b>Semester 4:</b>
</td>
<td>
<input type="text" name="sgpa4">
</td>
</tr>
<tr>
<td>
<b>Semester 5:</b>
</td>
<td>
<input type="text" name="sgpa5">
</td>
</tr>
<tr>
<td>
<b>Semester 6:</b>
</td>
<td>
<input type="text" name="sgpa6">
</td>
</tr>
<tr>
<td>
<b>Semester 7:</b>
</td>
<td>
<input type="text" name="sgpa7" >
</td>
</tr>
<tr>
<td>
<b>Semester 8:</b>
</td>
<td>
<input type="text" name="sgpa8" ">
</td>
</tr>
</table>
<input id="add-btn" type="submit" name="add" value="Add">
</form>
<?php
}
?>
<!-------------------delete student------------------------------------------------->
<?php
if(isset($_POST['deleteStudent']))
{
?>
<center>
<form action="deleteStudent.php" method="post" id="search-modify">
<b>Enter USN to delete:</b>
<input type="text" placeholder="Enter your USN" name="USN" id="usn-placeholder" required>
<input id="search-placeholder" type="submit" name="deleteByUSN" value="Delete" >
</form><br><br>
</center>
<?php
}
?>
</div>
</div>
</body>
</html> | 8cc3f45a41f3435d96078e256271c5c4a747a032 | [
"PHP"
] | 10 | PHP | vaishnavi362/SMS | ebc7ceb196bb26b0927ed56fd3a67002f20ba834 | 29172462ecdd16fba5ba08f383801cd3324f0d19 |
refs/heads/master | <repo_name>williamJmelton/sku-easy<file_sep>/src/environments/environment.dev.ts
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `index.ts`, but if you do
// `ng build --env=prod` then `index.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const AppConfig = {
production: false,
environment: 'DEV',
firebase: {
apiKey: '<KEY>',
authDomain: 'sku-easy.firebaseapp.com',
databaseURL: 'https://sku-easy.firebaseio.com',
projectId: 'sku-easy',
storageBucket: '',
messagingSenderId: '929709798530'
}
};
<file_sep>/src/app/components/home/home.component.ts
import {Component, OnInit, ViewChild, AfterViewInit, EventEmitter, Inject} from '@angular/core';
import {ElementRef} from '@angular/core';
import {WorkerService} from '../../worker.service';
import * as M from '../../../../node_modules/materialize-css/dist/js/materialize.js';
import {interval, Observable} from 'rxjs';
import {throttle} from 'rxjs/operators';
import {fromEvent} from 'rxjs';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import {LoginComponent} from '../login/login.component';
import {MatTableDataSource, MatPaginator} from '@angular/material';
import {Sku} from '../../models/Sku';
import {MatSnackBar} from '@angular/material';
import {SkuComponent} from './sku/sku.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit, AfterViewInit {
// @ViewChild('button') button: ElementRef;
@ViewChild('button', {read: ElementRef}) private button: ElementRef;
@ViewChild(MatPaginator) paginator: MatPaginator;
skus: any;
newestSku: number;
userName: string;
login_name: string;
login_password: string;
clicks$: Observable<any>;
displayedColumns = ['number', 'name', 'time'];
dataSource: MatTableDataSource<Sku> = new MatTableDataSource([]);
isLoggedIn: false;
skuSearch = 0;
constructor(private _worker: WorkerService, public dialog: MatDialog, public snackBar: MatSnackBar) {
this.userName = 'anon';
this._worker.getUserName().subscribe(data => {
this.userName = data;
});
}
ngAfterViewInit() {
this.clicks$ = fromEvent(this.button.nativeElement, 'click');
this.clicks$.pipe(throttle(val => interval(3000))).subscribe(click => {
console.log('click!');
if (this.userName !== 'anon') {
this.generate();
} else {
console.log('Must be logged in!');
this.openSnackBar();
}
});
}
ngOnInit() {
this.getNewestSku();
this.getSkus();
console.log('button element is', this.button.nativeElement);
this._worker.getAuth().subscribe(auth => {
this.isLoggedIn = auth;
});
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
this.dataSource.filter = filterValue;
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
lookUpSku() {
const sku = this._worker.lookUpSku(this.skuSearch).subscribe(next => {
this.openSkuLookupDialog(next);
});
}
getNewestSku() {
this._worker.getSkuNumbers().subscribe(data => {
this.newestSku = Math.max(...data);
});
}
getSkus() {
this._worker.getSkus().subscribe((skus) => {
this.skus = skus;
this.dataSource = new MatTableDataSource(this.skus);
this.dataSource.paginator = this.paginator;
console.log(this.dataSource);
});
}
generate() {
this._worker.generate(this.userName);
}
logout() {
this._worker.logout();
this.userName = 'anon';
this.snackBar.open('You are logged out', '', {
duration: 500
});
}
makeToast() {
if (this.userName === 'anon') {
M.toast({html: 'Please Login'});
}
}
openSnackBar() {
this.snackBar.open('Please Login.', '', {
duration: 500
});
}
openLoginDialog(): void {
const dialogRef = this.dialog.open(LoginComponent, {
width: '550px',
data: {},
panelClass: 'custom-dialog-container'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
openSkuLookupDialog(data: any) {
console.log('open sku dialog has been called and is starting...');
const dialogRef = this.dialog.open(SkuComponent, {
width: '550px',
data: {number: data.number, person: data.person}
});
}
handleClickedLogin() {
if (this.isLoggedIn) {
this.snackBar.open('You\'re already logged in', '', {duration: 500});
} else {
this.openLoginDialog();
}
}
}
// @Component({
// selector: 'app-snack-bar-component-example-snack',
// template: `<h4>Please Login.</h4>`,
// styles: [`.example-pizza-party { color: hotpink; }`],
// })
// export class SnackbarComponent {}
<file_sep>/src/app/components/home/sku/sku.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
@Component({
selector: 'app-sku',
templateUrl: './sku.component.html',
styleUrls: ['./sku.component.scss']
})
export class SkuComponent implements OnInit {
sku: any;
constructor(public dialogRef: MatDialogRef<SkuComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
console.log('component data is:', data);
}
onNoClick(): void {
this.dialogRef.close();
}
ngOnInit() {
}
}
<file_sep>/src/environments/environment.prod.ts
export const AppConfig = {
production: true,
environment: 'PROD',
firebase: {
apiKey: '<KEY>',
authDomain: 'sku-easy.firebaseapp.com',
databaseURL: 'https://sku-easy.firebaseio.com',
projectId: 'sku-easy',
storageBucket: '',
messagingSenderId: '929709798530'
}
};
<file_sep>/src/app/worker.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable, ReplaySubject } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { flatMap } from 'rxjs/operators';
import { Sku } from './models/Sku';
import * as firebase from 'firebase';
import { firestore } from 'firebase';
@Injectable()
export class WorkerService {
/*
██╗ ██╗ █████╗ ██████╗ ███████╗
██║ ██║██╔══██╗██╔══██╗██╔════╝
██║ ██║███████║██████╔╝███████╗
╚██╗ ██╔╝██╔══██║██╔══██╗╚════██║
╚████╔╝ ██║ ██║██║ ██║███████║
╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝
*/
$skus: Observable<any>;
$searchedSkus: Observable<any>;
$userEmail = new ReplaySubject();
$searchedNumberData = new ReplaySubject();
dbRef = this._db.firestore.collection('generatedNumbers').doc('number');
user = this._afAuth.auth.currentUser;
timeStamps: any;
$auth = new ReplaySubject();
newNumber;
/*
██████╗ ██████╗ ███╗ ██╗███████╗████████╗██████╗ ██╗ ██╗ ██████╗████████╗ ██████╗ ██████╗
██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ██████╔╝██║ ██║██║ ██║ ██║ ██║██████╔╝
██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██╗██║ ██║██║ ██║ ██║ ██║██╔══██╗
╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║
╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
*/
constructor(private _db: AngularFirestore, public _afAuth: AngularFireAuth) {
this._db.firestore.settings({ timestampsInSnapshots: true });
this.$skus = this._db
.collection('generatedNumbers', ref => ref.orderBy('number', 'desc'))
.valueChanges();
this.getSkuNumbers();
this.$userEmail.next('anon');
this.$auth.next(false);
}
getSkuNumbers(): Observable<any> {
return this.$skus.pipe(
map(sku => {
return sku.map(skuObj => skuObj.number);
})
);
}
getSearchedSkus(sku: number): Observable<any> {
this.$searchedSkus = this._db
.collection('generatedNumbers', ref =>
ref.where('number', '==', sku).limit(1)
)
.valueChanges()
.pipe(
flatMap(result => result),
take(1)
);
return this.$searchedSkus;
}
lookUpSku(sku: number): Observable<any> {
let number = {};
const sub = this.getSearchedSkus(sku).subscribe(
next => {
// do next
this.$searchedNumberData.next(next);
number = next;
},
error => {},
() => {
console.log('complete');
}
);
return this.$searchedNumberData.pipe(take(1));
}
getNewestDate() {
this.$skus.pipe(
map(sku => {
console.log(sku.map(skuObj => skuObj.timeStamp));
})
);
}
getUserName(): Observable<any> {
return this.$userEmail;
}
getSkus(): Observable<Sku> {
return this.$skus.pipe(
map(skus => {
console.log(skus);
return skus;
})
);
}
generate(person: string) {
const timeStamp = Date.now(); // firebase.firestore.FieldValue.serverTimestamp();
this._db.firestore
.runTransaction(transaction => {
return transaction.get(this.dbRef).then(doc => {
const newValue = doc.data().val + 1;
this.newNumber = newValue;
const oldValue = doc.data().val;
if (doc.data().val !== newValue) {
transaction.set(this.dbRef, { val: newValue });
return Promise.resolve('Number increased to ' + newValue);
} else {
return Promise.resolve('Numbers Conflicted. Try Again.');
}
});
})
.then(result => {
console.log('done, make a write saying who did it...');
this._db.firestore
.collection('generatedNumbers')
.add({ number: this.newNumber, person: person, time: Date.now() });
})
.catch(err => {
console.log('Transaction failure:', err);
});
}
login(user: string, pass: string) {
this._afAuth.auth.signInAndRetrieveDataWithEmailAndPassword(
user + '@<EMAIL>',
pass
);
this._afAuth.authState.subscribe(data => {
if (data != null) {
this.$userEmail.next(data.email);
this.$auth.next(true);
}
});
}
logout() {
this._afAuth.auth.signOut().then(() => this.$userEmail.next('anon'));
this.$auth.next(false);
}
getAuth(): Observable<any> {
return this.$auth;
}
}
<file_sep>/src/app/components/login/login.component.ts
import {Component, Inject, OnInit} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import {WorkerService} from '../../worker.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
username = 'emad';
password = '<PASSWORD>';
constructor(
public dialogRef: MatDialogRef<LoginComponent>,
@Inject(MAT_DIALOG_DATA) public data: any,
private _worker: WorkerService) {
}
onNoClick(): void {
this.dialogRef.close();
}
login() {
this._worker.login(this.username, this.password);
this.onNoClick();
}
ngOnInit() {}
}
<file_sep>/src/app/models/Sku.ts
export class Sku {
number: number;
generatedBy: string;
timeStamp: string;
}
| 2b32e71d833df4257fda1ea5eeff757b7bc3c90e | [
"TypeScript"
] | 7 | TypeScript | williamJmelton/sku-easy | 96d41660d29ad8adc88599cdc0ba683d8d80381f | 6c54a5fb9f7919481c9e84d48113f770d6f2f3ab |
refs/heads/master | <repo_name>nicolas-bancel/master-react<file_sep>/src/Button.js
import React from 'react';
class Button extends React.Component {
render() {
return (
<button className="btn btn-primary">{this.props.text ? (this.props.text) : ('Veuillez mettre un texte pour ce bouton')}</button>
)
}
}
export default Button; | 5207649dfaf9d7b97d9d32b3d515b10598874037 | [
"JavaScript"
] | 1 | JavaScript | nicolas-bancel/master-react | a7ba11c918055d1e51801eeb93f83e8335f66cca | b38434de016546d624892c34fcb97f5a3f285502 |
refs/heads/master | <file_sep># set working directory
setwd("~/Coursera/4ExploratoryDataAnalysis/Project1")
# make sure the plots folder exists
if (!file.exists("PNGfiles")) {
dir.create("PNGfiles")
}
# load data
dt <- read.table("dataTrans/power_consumption.txt", sep = "|", header = TRUE, ,na.strings='?')
# open device
png(filename='PNGfiles/plot4.png',width=480,height=480,units='px')
# make 4 plots
par(mfrow=c(2,2))
# plot data on 1,1
plot(dt$DateTime,dt$GlobalActivePower,ylab='Global Active Power',xlab='',type='l', xaxt = 'n')
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
# plot data on 1,2
plot(dt$DateTime,dt$Voltage,xlab='datetime',ylab='Voltage',type='l', xaxt = 'n')
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
# plot data on 2,1
lncol<-c('black','red','blue')
lbls<-c('Sub_metering_1','Sub_metering_2','Sub_metering_3')
plot(dt$DateTime,dt$SubMetering1,type='l',col=lncol[1],xlab='',ylab='Energy sub metering', xaxt = 'n')
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
lines(dt$DateTime,dt$SubMetering2,col=lncol[2])
lines(dt$DateTime,dt$SubMetering3,col=lncol[3])
# plot data on 2,2
plot(dt$DateTime,dt$GlobalReactivePower,xlab='datetime',ylab='Global_reactive_power',type='l', xaxt = 'n')
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
# close device
dev.off()<file_sep># set working directory
setwd("~/Coursera/4ExploratoryDataAnalysis/Project1")
# make sure the plots folder exists
if (!file.exists("PNGfiles")) {
dir.create("PNGfiles")
}
# load data
dt <- read.table("dataTrans/power_consumption.txt", sep = "|", header = TRUE, ,na.strings='?')
# open device
png(filename='PNGfiles/plot2.png',width=480,height=480,units='px')
# plot DateTime against GlobalActivePower
plot(dt$DateTime, dt$GlobalActivePower, ylab='Global Active Power (kilowatts)', xlab='', type='l', xaxt = 'n')
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
# close device
dev.off()
<file_sep># set working directory
setwd("~/Coursera/4ExploratoryDataAnalysis/Project1")
# required packages
library(data.table)
library(lubridate)
# check if data Initial and data trandformed folder exist
if (!file.exists("dataInit")) {
dir.create("dataInit")
}
if (!file.exists("dataTrans")) {
dir.create("dataTrans")
}
# check existing tidy data set exists
if (!file.exists("dataTrans/powerConsumption.txt")) {
# download the zip file and unzip
file.url<-"http://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(file.url,destfile="dataInit/powerConsumption.zip")
unzip("dataInit/powerConsumption.zip",exdir="dataInit",overwrite=TRUE)
# read the raw table and select only 2 days
variable.class<-c(rep("character",2),rep("numeric",7))
dt <-read.table("dataInit/household_power_consumption.txt",header=TRUE,
sep=";", na.strings="?", colClasses=variable.class)
dt <-dt[dt$Date=="1/2/2007" | dt$Date=="2/2/2007",]
# clean up the variable names and convert date/time fields
names<-c('Date','Time','GlobalActivePower','GlobalReactivePower','Voltage','GlobalIntensity',
'SubMetering1','SubMetering2','SubMetering3')
colnames(dt)<-names
dt$DateTime<-dmy(dt$Date)+hms(dt$Time)
dt<-dt[,c(10,3:9)]
# write a clean data set to the directory
write.table(dt,file='dataTrans/power_consumption.txt',sep='|',row.names=FALSE)
} else {
dt<-read.table('dataTrans/power_consumption.txt',header=TRUE,sep='|')
dt$DateTime<-as.POSIXlt(dt$DateTime)
}
<file_sep># set working directory
setwd("~/Coursera/4ExploratoryDataAnalysis/Project1")
# make sure the folder for the PNG files exists
if (!file.exists("PNGfiles")) {
dir.create("PNGfiles")
}
# load data
dt <- read.table("dataTrans/power_consumption.txt", sep = "|", header = TRUE, ,na.strings='?')
# open device
png(filename='PNGfiles/plot1.png',width=480,height=480,units='px')
# plot the frequency of GlobalActivePower
hist(dt$GlobalActivePower,main='Global Active Power',xlab='Global Active Power (kilowatts)',col='red')
# Turn off device
dev.off()<file_sep># set working directory
setwd("~/Coursera/4ExploratoryDataAnalysis/Project1")
# make sure the plots folder exists
if (!file.exists("PNGfiles")) {
dir.create("PNGfiles")
}
# load data
dt <- read.table("dataTrans/power_consumption.txt", sep = "|", header = TRUE, ,na.strings='?')
# open device
png(filename='PNGfiles/plot3.png',width=480,height=480,units='px')
# plot data
color<-c('black','red','blue')
legend<-c('Sub_metering_1','Sub_metering_2','Sub_metering_3')
plot(dt$DateTime,dt$SubMetering1,type='l',col=color[1],xlab='',ylab='Energy sub metering', xaxt = 'n')
lines(dt$DateTime,dt$SubMetering2,col=color[2])
lines(dt$DateTime,dt$SubMetering3,col=color[3])
axis(1,at=c(1,1440, 2880), labels = c("Thu", "Fri", "Sat"))
# add legend
legend('topright',legend=legend,col=color,lty='solid')
# close device
dev.off() | 6b66d970e1081d14cdbc4a02d4ca0b56783f22da | [
"R"
] | 5 | R | GloriaSalmoral/ExploratoryDataAnalysis | d23c34d9323a794df8173dda704e784722d4c61e | c3c2c64fa492ea9a7eaa5e86a463c8e41a19aa22 |
refs/heads/master | <repo_name>awrush/feedjira<file_sep>/lib/feedjira/date_time_utilities.rb
# rubocop:disable Style/Documentation
module Feedjira
module DateTimeUtilities
# This is our date parsing heuristic.
# Date Parsers are attempted in order.
DATE_PARSERS = [
DateTimePatternParser,
DateTimeLanguageParser,
DateTimeEpochParser,
DateTime
].freeze
# Parse the given string starting with the most common parser (default ruby)
# and going over all other available parsers
def parse_datetime(string)
DATE_PARSERS.each do |parser|
begin
return parser.parse(string).feed_utils_to_gm_time
rescue
nil
end
end
warn "Failed to parse date #{string.inspect}"
end
end
end
<file_sep>/lib/feedjira/configuration.rb
# Feedjira::Configuration
module Feedjira
# Provides global configuration options for Feedjira
#
# @example Set configuration options using a block
# Feedjira.configure do |config|
# config.strip_whitespace = true
# end
module Configuration
attr_accessor(
:follow_redirect_limit,
:request_timeout,
:strip_whitespace,
:user_agent
)
# Modify Feedjira's current configuration
#
# @yieldparam [Feedjria] config current Feedjira config
# @example
# Feedjira.configure do |config|
# config.strip_whitespace = true
# end
def configure
yield self
end
# @private
def self.extended(base)
base.set_default_configuration
end
# @private
def set_default_configuration
self.follow_redirect_limit = 3
self.request_timeout = 30
self.strip_whitespace = false
self.user_agent = "Feedjira #{Feedjira::VERSION}"
end
end
end
| 66ae96e4c0f6d6930ebb4df085d6b8c30d7d723a | [
"Ruby"
] | 2 | Ruby | awrush/feedjira | c8c521dd6258370c58b015a64a4c25a6a20532ec | 506ce2fb63c3ae35ea69a583aaef6024ab8aa4cc |
refs/heads/master | <file_sep># MeanCourse App
- This project was created by me to investigate Angular framework and how it can work with node as i have always been a MERN Developer not a Mean Developer
# Structure and how to deploy the app
- This application is divided into 2 apps
- A backend app written in Javascript using **NodeJS** and integrated with a remote **MongoDB** Database
- To run the backend just write in the terminal `npm run start:server`
- A Frontend app written in typescript using **Angular** version 8
- To run the Frontend just write in the terminal `npm run start:server`
## Features applied in the Angular App
- Using Angular Material Design for decent a UI
- Applying both Reactive approach and Form approach in creating and validating form
- Using Angular Router for managing frontend routes
- Using Lazy Loading for the routes by making a route file for each module and just importing it in the app-route file
- Using Angular guard to prevent accessing Application routes when user is not authenticated
- Using Angular interceptor to add JWT TOKEN for each HTTP Request going from the App to the Server
- Using Angular interceptor for error handling
- Implementing Image upload to remote server and MIME-Verification for the image file before it is uploaded to the server
## Features applied in the NodeJS App
- Integration with Remote MongoDB
- Encrypting passwords using bycrypt
- Validation for each Route Access Using The `JWT` token Sent
- Validation for the uploaded images and saving it on the server
- Handling invalid route access
- Handling unauthorized route requests
- Handling inserting unique records in the users table in MongoDB using `mongoose-unique-validator`
- Handling pagination requests
- Handling CORS Error
<file_sep>export const environment = {
production: true,
apiUrl: 'http://localhost:3000/api' // Till i can deploy my backend to AWS
};
| f81d211f2de0bba5979e8ddb6090eedb7b89696f | [
"Markdown",
"TypeScript"
] | 2 | Markdown | mohamedsamir1495/mean-course | 4b8647f427e276870df35d4e003f5463263909cc | af2dfd94eeb51e81645b2e03d0c36b1a9c4a89b1 |
refs/heads/master | <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "542aa3b9da3710315da080ea08bf9867",
"url": "/index.html"
},
{
"revision": "<PASSWORD>",
"url": "/static/css/2.bcddf60d.chunk.css"
},
{
"revision": "5542c29b267a4d6af721",
"url": "/static/css/main.b0fed035.chunk.css"
},
{
"revision": "<PASSWORD>",
"url": "/static/js/2.7de38c10.chunk.js"
},
{
"revision": "ebc70c097554e9e2ef968c42fad2beba",
"url": "/static/js/2.7de38c10.chunk.js.LICENSE.txt"
},
{
"revision": "5542c29b267a4d6af721",
"url": "/static/js/main.2ba9b450.chunk.js"
},
{
"revision": "57bad9ac21a6be00b5d6",
"url": "/static/js/runtime-main.d138b4fd.js"
}
]); | 47b3df1b84daf35603b5a53f1c2177237d2bff35 | [
"JavaScript"
] | 1 | JavaScript | Syed-Talha-Hussain/covid-19-tracking-app-react | 4725bbbec1d61dbb6bab0ff5fbc416788dfe9924 | ce24a5f3c8c279619c142ccfda46501530837613 |
refs/heads/master | <repo_name>mrmanhluc/webthiepcuoi<file_sep>/info.php
<?
$sql=mysql_query("select * from khachhang where makh = ".$_SESSION['makh']."");
$row = mysql_fetch_array($sql);
?>
<div id="registry" style="width:400px;">
<p class="login" style="padding:5px;"><p >Email:</p> <span class="info"><? echo $row['Email']?></span></p>
<p class="login" style="padding:5px;"><p>Tên khách hàng:</p> <span class="info"><? echo $row['TenKH']?></span></p>
<p class="login" style="padding:5px;"><p>Số điện thoại:</p> <span class="info"><? echo $row['SoDT']?></span></p>
<p class="login" style="padding:5px;"><p>Địa chỉ:</p> <span class="info"><? echo $row['Diachi']?></span></p>
<p class="login" style="padding:5px;"><p>Giới tính:</p> <span class="info"><? if($row['Gioitinh'] == 1) { echo Nam;}else{ echo Nữ ;}?></span></p>
<br/>
<p> Bạn có muốn <i><a href="?go=change&MaKH=<? echo $row['MaKH']?>">thay đổi</a></i> thông tin cá nhân?</p>
</div><file_sep>/hotline.php
<div id="hotline">
<p>
<strong> THIỆP CƯỚI LEE</strong>
</p>
<p>
Địa chỉ: <NAME>, <NAME>, Quận 1, T<NAME>
</p>
<p>
Điện thoại: 0974092622 hoặc 0973948741
</p>
</div><file_sep>/prod_list1.php
<?php
$sql_loaic ="select * from loaicay where MaLoai='$_GET[maloai]'";
$query_loaic=mysql_query($sql_loaic);
$dong_loaic=mysql_fetch_array($query_loaic);
?>
<p style=" font-size:18px; font-family:Arial, Helvetica, sans-serif; text-align: left; color:#FFFFFF; background:#700; position: relative; padding: 12px;"><?php echo $dong_loaic['TenLoai'] ?></p>
<form name="list_" method="post">
<?
$MaLoai=$_REQUEST['maloai'];
$hangsx=mysql_fetch_array(mysql_query("select tenloai from loaicay where Maloai=$MaLoai"));
$display=6;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res=mysql_query("select count(MaCay) from cay inner join loaicay on cay.maloai=loaicay.maloai where loaicay.maloai=$MaLoai");
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display){
$page=ceil($record/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql1=mysql_query("select * from cay inner join loaicay on cay.maloai=loaicay.maloai where (TrangThaiCay=1 and loaicay.maloai=$MaLoai) order by Macay desc LIMIT $start,$display");
while($row=mysql_fetch_array($sql1)){
?>
<div id="prod">
<a href=""><img src="images/<? echo $row['Hinhanh'] ?>" /></a>
<p><a href=""><span class="a"><? echo $row['TenCay'] ?></span></a></p>
<p style="color:red"><? echo number_format($row['Giaban']) ?> VNĐ</p>
<p><input type="button" value="" name="add" style="background:url(images/addtocart.gif); height:27px; width:93px;" onclick="window.location.href='?go=cart1&action=addcay&macay=<? echo ($row['MaCay']);?>'"/></p>
</div>
<!--end # sanpham-->
<?
}
?></div>
<div id="phantrang" >
<ul>
<?
if($page>1)
$next = $start + $display;
$prev = $start - $display;
$current = ($start/$display) + 1 ;
if($current!=1)
{
echo"<li><a href='?go=prolist&maloai=$MaLoai&start=$prev'</a>Pre</li>";
}
for($i=1; $i<=$page; $i++)
{
if($current !=$i)
{
echo"<li><a href='?go=prolist&maloai=$MaLoai&start=".($display*($i-1))."'>$i</a></li>";
}
else
{
echo"<li class='current'>$i</li>";
}
}
if($current!=$page)
{
echo"<li><a href='?go=prolist&maloai=$MaLoai&start=$next'>Next</a></li>";
}
?></ul></div>
</form>
<file_sep>/cart1.php
<?
session_register("cart1");
$cart1=$_SESSION['cart1'];
$action=$_REQUEST['action'];
switch($action){
case "addcay":
{
$macay=$_REQUEST['macay'];
if(isset($cart1[$macay]))
{
$soluong=$cart1[$macay]+1;
}else{
$soluong=1;
}
$cart1[$macay]=$soluong;
echo "<script>window.history.go(-1)</script>";
break;
}
case "update":
foreach(array_keys($cart1) as $value){
if($_REQUEST["soluong".$value] >0)
$cart1[$value] = $_REQUEST["soluong".$value];
}
$_SESSION["CART1"] = $cart1;
break;
case "del":
{
$macay = $_REQUEST['macay'];
if(isset($cart1[$macay]))
{
foreach(array_keys($cart1) as $value){
if($value != $macay){
$newcart1[$value] = $cart1[$value];
}
}
$_SESSION['cart1'] = $newcart1;
$cart1=$newcart1;
}
break;
}
case "delall1":
{
unset($_SESSION['cart1']);
echo("<script>window.location='?go=cart1'</script>");
break;
}
}
?>
<script>
var a = true;
function kiemtra(txt)
{
s = txt.value;
var IsNumber=true;
var s1=String(s);
var re=/\ /;
if(s1=='')
{
alert('Mời bạn nhập số lượng');
txt.focus();
IsNumber=false;
a=false;
}
else
if(isNaN(s1))
{
alert('số lượng đặt phải là số');
txt.focus();
IsNumber=false;
a=false;
}else
if(re.test(s1))
{
alert('số lượng đặt phải là số');
txt.focus();
IsNumber=false;
a=false;
}else
{
s2=parseInt(s1);
if(s2<=0 || s2!=eval(s1))
{
alert('số lượng đặt phải là số nguyên dương');
txt.value=s2;
IsNumber=false;
a=false;
}
}
a=IsNumber;
return IsNumber;
}
function testform()
{
if(a){
return true;}
else
{
alert('Mời bạn kiểm tra lại');
return false;
}
}
function Cart1Send()
{
if(a){
document.location='index.php?go=cart1send';
return true;
}
else
{
alert('Mời bạn kiểm tra lại');
return false;
}
}
</script>
<div id="cart1">
<?
$ok=1;
if(isset($_SESSION['cart1']))
{
foreach($_SESSION['cart1'] as $k=>$v)
{
if(isset($k))
{
$ok=2;
}
}
}
if($ok==2) {
?>
<form name="frmcart1" method="post" action="index?go=cart1" id="frmcart1" onsubmit="return testform();" >
<input type="hidden" id="action" name="action" value="update" />
<?
foreach($_SESSION['cart1'] as $key=>$value )
{
$ittem[]=$key;
}
$str=implode(",",$ittem);
$stt=0;
$total=0;
$sql1=mysql_query("select * from cay where MaCay in (".$str.")");
?>
<table border="1" width="100%">
<tr class="rowtitle">
<td width="10%" >Số thứ tự</td>
<td width="26%"> Hình ảnh</td>
<td width="20%">Tên sản phẩm</td>
<td width="5%">Số lượng</td>
<td width="15%">Giá thành</td>
<td width="14%">Tổng tiền</td>
<td width="10%">Del</td>
</tr>
<?
while($row1=mysql_fetch_array($sql1)) {
$Stt++;
?>
<tr class="row1">
<td><? echo $Stt?></td>
<td><img src="images/<? echo ($row1['Hinhanh'])?>" width="100" height="150"></td>
<td><? echo ($row1['TenCay'])?></td>
<td><input name="soluong<? echo $row1['MaCay']?>" type="text" onChange="return kiemtra(this)" value="<? echo $_SESSION['cart1'][$row1['MaCay']]?> " size="1" ></td>
<td><? echo number_format(($row1['Giaban']))?> <font color="red">VNĐ</font></td>
<td><? echo number_format($_SESSION['cart1'][$row1['MaCay']] * $row1['Giaban']) ?> <font color="red">VNĐ</font>
</td>
<td><a href=''>Del</a></td>
</tr>
<?
$total+= $_SESSION['cart1'][$row1['MaCay']] * $row1['Giaban'];
$_SESSION['total']=$total;
}
?>
<tr>
<td colspan="5" align="right">Total:</td>
<td colspan="2" align="left"><? echo(number_format($total))?><font color="red"> VNĐ</font></td>
</tr>
<tr height="30" valign="middle" align="center">
<td align="center" colspan="7">
<hr></td>
</tr>
<tr height="30" valign="middle" align="center">
<?
if(isset($update1))
{
}
?>
<td align="center" colspan="7">
<input type="submit" name="update" value="Update" >
<input type="button" name="delete" value="Delete all" onclick="window.location.href='?go=cart1&action=delall1'">
<input type="button" name="cartsend1" value="Cart send1" onclick="CartSend1()" ></td>
</tr>
</table>
<?
}else{
echo "Giỏ hàng chưa có sản phẩm nào cả"; }
?>
</form>
</div><file_sep>/js/slider1.js
$(document).ready(function() {
var stt = 0;
starImg = $("img.slide1:first").attr("stt");
endImg = $("img.slide1:last").attr("stt");
$("img.slide1").each(function(){
if($(this).is(':visible'))
stt = $(this).attr("stt");
});
$("#next1").click(function(){
if(stt == endImg){
stt = -1;
}
next1 = ++stt;
$("img.slide1").hide();
$("img.slide1").eq(next1).show();
});
$("#prev1").click(function(){
if(stt == 0){
stt = endImg;
prev1 = stt++;
}
prev1 = --stt;
$("img.slide1").hide();
$("img.slide1").eq(prev1).show();
});
setInterval(function(){
$("#next1").click();
},8000);
});// JavaScript Document<file_sep>/menu_thiepcuoi.php
<li>
<a href="#"><span class="hover">THIỆP CƯỚI</span> <span style=" margin-left: 25px"> |</span> </a>
<ul class="sub_menu">
<?php
$get_main_MaLoai = $data['MaLoai'];
$sub_query = mysql_query ("SELECT * FROM loaithiep WHERE TrangthaiLoai = $get_main_MaLoai");
while($sub_data = mysql_fetch_array($sub_query)){
?>
<li>
<a href="#"><?php echo $sub_data['TenLoai']; ?></a>
</li>
<?php
}
?>
</ul>
</li><file_sep>/admin/detail1.php
<?
$mahd=$_REQUEST['mahd'];
$sql=mysql_query("select * from khachhang inner join hoadon on khachhang.MaKH=hoadon.MaKH inner join hondonct on hoadon.MaHD=hondonct.MaHD where hoadon.MaHD='$mahd'");
$row=mysql_fetch_array($sql)
?>
<div id="hondonct">
<div id="thongtinhd">
<h4>Thông tin hóa đơn</h4>
<p style="float:left"><label>Mã hóa đơn :</label> <span><? echo ($row['MaHD'])?></span> </p>
<p style="float:left"><label>Ngày lập hóa đơn: </label> <span><? echo ($row['Ngaylap'])?></span> </p>
<p style="float:left"><label>Ngày giao hàng: </label> <span><? echo ($row['Ngaynhan'])?></span> </p>
<p style="float:left"><label>Trạng thái: </label> <span><? if(($row['TrangthaiHD'])== 1) echo('Chưa xử lý');if(($row['TrangthaiHD'])==2) echo ('Đang xử lý'); if(($row['TrangthaiHD'])==3) echo('Đã xử lý');?></span> </p>
</div>
<div id="thongtinkh">
<h4>Thông tin người nhận</h4>
<p style="float:left"><label>Tên người nhân: </label> <span><? echo ($row['Nguoinhan'])?></span> </p>
<p style="float:left"><label>Địa chỉ giao hàng: </label> <span><? echo ($row['DiachiNN'])?></span> </p>
<p style="float:left"><label>Số điện thoại người nhận :</label> <span><? echo ($row['SoDT'])?></span> </p>
</div>
<div id="thongtintk">
<h4>Thông tin tài khoản</h4>
<p style="float:left"><label>Tên khách hàng: </label> <span><? echo ($row['TenKH'])?></span> </p>
<p style="float:left"><label>Email: </label> <span><? echo ($row['Email'])?></span> </p>
<p style="float:left"><label>Số điện thoại : </label> <span><? echo ($row['SoDT'])?></span> </p>
<p style="float:left"><label>Địa chỉ: </label> <span><? echo ($row['Diachi'])?></span> </p>
</div>
<div id="thongtinsp">
<table border="1" width="100%">
<tr class="rowtitle">
<td>STT</td>
<td>Mã sản phẩm</td>
<td>Tên sản phẩm</td>
<td>Giá bán</td>
<td>Số lượng</td>
<td>Tổng tiền</td>
</tr>
<?
$sql1=mysql_query("select * from cay inner join hondonct on cay.MaCay=hondonct.MaCay where hondonct.MaHD='$mahd'");
$stt=0;
while($r=mysql_fetch_array($sql1)) {
$stt++;
?>
<tr class="row">
<td><? echo $stt ?></td>
<td><? echo ($r['MaCay'])?></td>
<td><? echo ($r['TenCay'])?></td>
<td><? echo number_format($r['Giaban']) ?> VNĐ</td>
<td><? echo ($r['Soluong'])?></td>
<? $a= $r['Giaban'] *$r['Soluong'];
$b=$r['Tongtien'];?>
<td><? echo number_format($a) ?> VNĐ</td>
</tr>
<?
}
?>
<tr>
<td colspan="5" align="right" valign="middle" class="row">Total : </td>
<td align="center" class="row"> <?php echo(number_format($b));?> VNĐ</td>
</tr>
</table>
</div>
</div>
<file_sep>/admin/treelist.php
<div id="cuslist1">
<form name="treelist" method="post">
<?
$action = $_REQUEST['action'];
$macay = $_REQUEST['macay'];
$status = $_REQUEST['status'];
switch($action)
{
case 'update' :
{
mysql_query("update cay set trangthaicay = '$status' where MaCay ='$macay'");
break;
}
case 'del':
{
mysql_query("delete from cay where MaCay = '$macay'");
break;
}
}
$display=5;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res=mysql_query('select count(MaCay) from cay');
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display){
$page=ceil($record/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql3=mysql_query("select * from cay inner join loaicay on cay.Maloai=loaicay.maloai order by MaCay desc limit $start,$display");
?>
<table width="100%" border="1" align="center" cellpadding="0" style="color:black">
<tr class="rowtitle1">
<td width="9%">Mã cây</td>
<td width="20%">Hìnhảnh</td>
<td width="12%">Tên cây</td>
<td width="13%">Loại cây</td>
<td width="15%">Giá bán</td>
<td width="13%">Trạng thái</td>
<td width="12%" colspan="2"> </td>
</tr>
<?
while($row3=mysql_fetch_array($sql3)) {
?>
<tr class="row3" >
<td ><? echo ($row3['MaCay'])?></td>
<td ><img src="../images/<? echo($row3['Hinhanh'])?>" width="150" height="180"/></td>
<td ><? echo ($row3['TenCay'])?></td>
<td ><? echo ($row3['TenLoai'])?></td>
<td ><? echo (number_format($row3['Giaban']))?> VNĐ</td>
<td><select name="status" onchange="location.href='?go=prodlist1&start=<? echo $start?>&action=update&macay=<? echo($row3['MaCay']) ?>&status='+this.value">
<? if($row3['TrangthaiCay']==1) { ?>
<option value="1">Hiện</option>
<option value="0">Ẩn</option>
<? }else{ ?>
<option value="0">Ẩn</option>
<option value="1">Hiện</option>
<? } ?>
</select></td>
<td><a href="">Sửa</a></td>
<?
$a=$row4['MaCay'];
$sql4=mysql_query("select MaCay from hondonct1 inner join hoadon on hoadon.MaHD=hondonct1.MaHD where MaCay='$a' and hoadon.TrangThaiHD!=3");
if(mysql_num_rows($sql4)==0)
{
?>
<td><a href="?go=prodlist1&action=del&macay=<? echo($row4['MaCay'])?>">Xóa</a></td>
<? }else{ ?>
<td><font color="#666666">Xóa</font></td><? } ?>
</tr>
<?
}
?>
</table>
<div id="phantrang">
<ul>
<?
if($page>1)
$next = $start + $display;
$prev = $start - $display;
$current = ($start/$display) + 1 ;
if($current!=1)
{
echo"<li><a href='?go=prodlist1&start=$prev'>Pre</a></li>";
}
for($i=1; $i<=$page; $i++)
{
if($current !=$i)
{
echo"<li><a href='?go=prodlist1&start=".($display*($i-1))."'>$i</a></li>";
}
else
{
echo"<li class='current'>$i</li>";
}
}
if($current!=$page)
{
echo"<li><a href='?go=prodlist1&start=$next'>Next</a></li>";
}
?></ul></div>
</form>
</div><file_sep>/index.php
<?
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css.css" />
<title><NAME></title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/slider.js"></script>
<script type="text/javascript" src="js/slider1.js"></script>
<script type="text/javascript" src="js/divad.js"></script>
</head>
<?
require('conn.php');
?>
<body>
<div id="wapper">
<div id="top">
<?
require('top.php');
?>
</div>
<div id="content">
<div id="nag">
<ul>
<li><a href="?go=home"><span class="hover">TRANG CHỦ</a></li>
<li><a href="?go=add"><span class="hover">GIỚI THIỆU</a></li>
<li><a href=""><span class="hover">THIIỆP CƯỚI</a>
<ul id="nagmenu" style="line-height: 1.2;">
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=1"><span class="hover">Thiệp cưới hiện đại</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=2"><span class="hover">Thiệp cưới lazer</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=3"><span class="hover">Thiệp cưới in kỹ thuật số</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=4"><span class="hover">Thiệp cưới offet</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=5"><span class="hover">Thiệp cưới in thủ công</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=6"><span class="hover">Thiệp cưới ấn tượng</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=7"><span class="hover">Thiệp cưới cao cấp</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist&maloai=8"><span class="hover">Thiệp cưới mỹ thuật</span></a></li>
</ul>
</li>
<li><a href="?go=cart"><span class="hover">CÂY TIỀN THẬT</a>
<ul id="nagmenu1">
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist1&maloai=1"><span class="hover">Cây tiền tài lộc</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist1&maloai=2"><span class="hover">Cây tiền thật</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist1&maloai=3"><span class="hover">Phụ kiện cây tiền</span></a></li>
<li><a href="http://localhost/thiepcuoilee/index.php?go=prolist1&maloai=4"><span class="hover">Quà tặng tết</span></a></li>
</ul>
</li>
<li><a href="?go=cart"><span class="hover">TIN TỨC</a></li>
<li><a href="?go=hotline"><span class="hover">LIÊN HỆ</a></li>
<div class="search">
<form method="post" name="frmsearch" onsubmit="return checksearch(this)">
<input type="text" name="txtSearch" value="Tìm kiếm" onfocus="this.value = '';" style="width:120px; height:20px; margin-top: 11px">
<input type="submit" value=" " name="btnSearch" style="background-image:url(images/icon_search.png);width:30px; height:23px; margin-top: 13px;">
<?
if(isset($btnSearch)){
$s = $_REQUEST['txtSearch'];
echo ("<script>window.location='?go=search&tenthiep=$s'</script>");
}
?>
</form>
</div>
</div>
<div id="info">
<div id="left">
<?
require('left.php');
?>
</div>
<div id="main">
<?
require('main.php');
?>
</div>
<div class="adfloat" id="divBannerFloatLeft" style="margin-top: -170px;">
<p><a href="http://localhost/thiepcuoilee/index.php?go=home"><img src="images/BanerLeft.gif" alt=""></a>
</p>
</div>
<div class="adfloat" id="divBannerFloatRight" style="margin-top: -170px;">
<p><a href="http://localhost/thiepcuoilee/index.php?go=home"><img src="images/BanerRight.gif" alt=""></a>
</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/divad.php
<?
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css.css" />
<title><NAME></title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/divad.js"></script>
</head>
<body>
<div id="divAdRight" style=" display: none; position: absolute; margin-top: -50px">
<a href="http://localhost/thiepcuoilee/index.php?go=home"><img src="images/BanerRight.gif" width="120"></a>
</div>
<div id="divAdLeft" style=" display: none; position: absolute; margin-top: -50px">
<a href="http://localhost/thiepcuoilee/index.php?go=home"><img src="images/BanerLeft.png" width="120"></a>
</div>
</body>
</html>
<file_sep>/admin/login.php
<?
session_start();
$_SESSION['admin'] = "";
require('conn.php');
?>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" href="admin.css" rel="stylesheet">
<div id="adlog">
<h2 style="color:#000; text-align:center">Login</h2>
<form method="post" name="form_login">
<p><label>User: </label></p>
<p><input type="text" name="user" style="width:90%;"></p>
<p><label>Pass: </label></p>
<p><input type="<PASSWORD>" name="pass" style="width:90%;"></p>
<p><input type="submit" name="login" value="" style="background:url(../images/login.gif);height:26px;width:65px"></p>
<?
if(isset($login)){
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
$sql=mysql_query("SELECT * FROM admin WHERE user = '$user' AND pass = '$pass'");
if(mysql_num_rows($sql) >0 ){
$_SESSION['admin']= 'admin';
echo("<script>alert('Đăng nhập thành công') </script>");
echo("<script>window.location='admin.php'</script>");
}else{
echo("<script>alert('Sai user hoặc password');</script>");
}
}
?>
</form>
</div><file_sep>/admin/add.php
<script>
$(document).ready(function(){
$('#frm_add').validate();
});
</script>
<div id="add">
<form name="frm_add" id="frm_add" method="post" enctype="multipart/form-data">
<p><label>Tên thiệp: </label> <input type="text" name="thiep" class="required" value="<? echo $thiep?>"/></p>
<p><label>Giá bán:(VND) </label><input type="text" name="price" class="required number" value="<? echo $price?>"/></p>
<p><label>Mô tả:</label><textarea name="mota" class="required"/></textarea>
</p>
<p><label>Loại thiệp: </label> <select name="loaithiep" id="loaithiep" class="required">
<option selected="selected">Chọn loại thiệp</option>
<? $loaithiep=mysql_query('select * from loaithiep where TrangThaiLoai>=1');
while ($row=mysql_fetch_array($loaithiep)){ ?>
<option value="<? echo ($row['MaLoai']);?>"> <? echo ($row['TenLoai']); ?> </option>
<? } ?>
</select></p>
<p><label>Hình ảnh:</label>
<input name="btnupload" type="submit" value="Upload" onclick="return fhinhanhthem();" disabled="disabled">
<input name="f1" type="file" id="f1" onchange="frm_add.btnupload.disabled=false;" ></p>
<p style="width:150px; height:180px; border:1px solid black; margin-left:20%;">
<?
$data="../images/";
$max_size="10000000";
$max_file="1";
$file_name=time().'_';
if(isset($btnupload))
{
$thiep = $_REQUEST['thiep'];
$price = $_REQUEST['price'];
$mota = $_REQUEST['mota'];
$a=$_FILES["f1"]["tmp_name"];
$b=$_FILES["f1"]["name"];
$d=$_FILES["f1"]["size"];
$c=substr($b,strlen($b)-3,3);
if($d>$max_size)
{
echo("<script>alert('Kich thuoc anh khong phu hop');</script>");
}
else
{
if($c=="jpg" || $c=="jpeg" ||$c=="gif" || $c=="bmp" || $c=="png" || $c=="JPG" || $c=="JPEG" || $c=="GIF" || $c=="BMP"||$c=="PNG")
{
$tenfile=$file_name.$b;
move_uploaded_file($a,$data.$tenfile);
?>
<img src="<?=$data.$tenfile ?>" width="150" height="180" />
<?
}
}
}
?></p>
<input type="hidden" name="hinhanh" value="<?=$tenfile ?>" />
<p><input type="submit" value="" name="add" style="background:url(../images/continue.gif);width:83px; height:26px" /></p>
<?
if(isset($add)){
$thiep = $_REQUEST['thiep'];
$price = $_REQUEST['price'];
$mota = $_REQUEST['mota'];
$loaithiep = $_REQUEST['loaithiep'];
$hinhanh = $_REQUEST['hinhanh'];
if(mysql_num_rows(mysql_query("select * from thiep where Tenthiep = '$thiep'")) >0){
echo("<script>alert Sản phẩm đã tồn tại, mời bạn chọn sản phẩm khác</script>");
}else{
mysql_query("insert into thiep(Tenthiep,mota,hinhanh,giaban,maloai) values ('$thiep','$mota','$hinhanh','$price','$loaithiep')");
if(mysql_affected_rows()>0)
{
$thiep = "";
$price = "";
echo"<script>if(!confirm('Thêm sản phẩm thành công. Bạn có muốn thêm sản phẩm nữa không?')) location='?go=addthiep';</script>";
}
}
}
?>
</form>
</div><file_sep>/admin/newtypetree.php
<script>
$(document).ready(function(){
$('#frm_newtypetree').validate();
});
</script>
<div id="newtypetree">
<form name="frm_newtypetree" id="frm_newtypetree" method="post">
<p>
<label>Tên cây :</label>
<input name="type" type="text" class="required"/>
</p>
<p class="login" style="margin-top:10px;">
<input type="submit" name="addcay" value="" style="background:url(../images/continue.gif);width:83px; height:26px" />
</p>
<?
$addcay = $_REQUEST['addcay'];
$type = $_REQUEST['type'];
if(isset($addcay)){
mysql_query("insert into loaicay(Tenloai) values ('$type')");
if(mysql_num_rows(mysql_query("select Tenloai from loaicay where Tenloai='$type'"))>0)
{
echo("<script>alert('Thêm loại cây thành công')</script>");
echo("<script>window.location='?go=typetree'</script>");
}else{
echo ("<script>alert('Thêm loại cây tiền thất bại')</script>");
}
}
?>
</form>
</div><file_sep>/registry.php
<script>
$(document).ready(function(){
$('#frm_registry').validate();
});
</script>
<div id="registry">
<form method="post" name="frm_registry" id="frm_registry" >
<p class="login">
<label>Email: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="email" class="required email" maxlength="50" style="width:200px" />
</p>
<p class="login">
<label>Password: </label><span class="red">*</span>
</p>
<p class="login">
<input type="<PASSWORD>" name="pass" class="required" minlength="6" maxlength="15" id="pass" style="width:200px"/>
</p>
<p class="login">
<label>Re-Password: </label><span class="red">*</span>
</p>
<p class="login">
<input type="password" name="re_pass" class="required" minlength="6" maxlength="15" equalTo="#pass" style="width:200px"/>
</p>
<p class="login">
<label>Tên: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="name" class="required" maxlength="30" style="width:200px"/>
</p>
<p class="login">
<label>Số điện thoại: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="phone" class="required number" minlength="8" maxlength="30" style="width:200px" />
</p>
<p class="login">
<label>Địa chỉ: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="location" class="required" style="width:200px" maxlength="100"/>
</p>
<p class="login">
<label>Giới tính: </label><span class="red">*</span>
<input type="radio" name="gender" id="radio" value="Nam" />
Nam
<input type="radio" name="gender" id="radio2" value="Nữ" />
Nữ
</p>
<p class="login" style="margin-top:10px;">
<input type="submit" name="submit" value="" style="background:url(images/continue.gif);width:83px; height:26px" />
</p>
<?
if(isset($submit)){
$email = $_REQUEST['email'];
$pass = $_REQUEST['pass'];
$name = $_REQUEST['name'];
$phone = $_REQUEST['phone'];
$loca = $_REQUEST['location'];
$gender = $_REQUEST['gender'];
if($gender == 'Nam'){
$sex=1;
}else{
$sex=2;
}
if(mysql_num_rows(mysql_query("select email from khachhang where email='$email'"))>0){
echo("<script>alert('Email này đã được đăng kí mới bạn dùng email khác');</script>");
}else{
mysql_query("insert into khachhang(email,password,tenkh,sodt,diachi,gioitinh) values ('$email','$pass','$name','$phone','$loca','$sex')");
$_SESSION['email'] = $email;
$_SESSION['name'] = $name;
echo("<script>window.location='?go=home'</script>");
$sql_id="select makh from khachhang where email ='$email'";
$row = mysql_fetch_array(mysql_query($sql_id));
$_SESSION['makh'] = $row['makh'];
}
}
?>
</form>
</div><file_sep>/admin/thieplist.php
<div id="cuslist">
<form name="thieplist" method="post">
<?
$action = $_REQUEST['action'];
$mathiep = $_REQUEST['mathiep'];
$status = $_REQUEST['status'];
switch($action)
{
case 'update' :
{
mysql_query("update thiep set trangthaithiep = '$status' where MaThiep ='$mathiep'");
break;
}
case 'del':
{
mysql_query("delete from thiep where MaThiep = '$mathiep'");
break;
}
}
$display=5;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res=mysql_query('select count(MaThiep) from thiep');
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display){
$page=ceil($record/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql1=mysql_query("select * from thiep inner join loaithiep on thiep.Maloai=loaithiep.maloai order by MaThiep desc limit $start,$display");
?>
<table width="100%" border="1" align="center" cellpadding="0" style="color:black">
<tr class="rowtitle">
<td width="9%">Mã thiệp</td>
<td width="20%">Hình ảnh</td>
<td width="12%">Tên thiệp</td>
<td width="13%">Loại thiệp</td>
<td width="15%">Giá bán</td>
<td width="13%">Trạng thái</td>
<td width="12%" colspan="2"> </td>
</tr>
<?
while($row=mysql_fetch_array($sql1)) {
?>
<tr class="row" >
<td ><? echo ($row['MaThiep'])?></td>
<td ><img src="../images/<? echo($row['Hinhanh'])?>" width="150" height="180"/></td>
<td ><? echo ($row['TenThiep'])?></td>
<td ><? echo ($row['TenLoai'])?></td>
<td ><? echo (number_format($row['Giaban']))?> VNĐ</td>
<td><select name="status" onchange="location.href='?go=prodlist&start=<? echo $start?>&action=update&mathiep=<? echo($row['MaThiep']) ?>&status='+this.value">
<? if($row['TrangthaiThiep']==1) { ?>
<option value="1">Hiện</option>
<option value="0">Ẩn</option>
<? }else{ ?>
<option value="0">Ẩn</option>
<option value="1">Hiện</option>
<? } ?>
</select></td>
<td><a href="?go=editSP&MaThiep=<? echo($row['MaThiep'])?>">Sửa</a></td>
<?
$a=$row['MaThiep'];
$sql2=mysql_query("select MaThiep from hondonct inner join hoadon on hoadon.MaHD=hondonct.MaHD where MaThiep='$a' and hoadon.TrangThaiHD!=3");
if(mysql_num_rows($sql2)==0)
{
?>
<td><a href="?go=prodlist&action=del&mathiep=<? echo($row['MaThiep'])?>">Xóa</a></td>
<? }else{ ?>
<td><font color="#666666">Xóa</font></td><? } ?>
</tr>
<?
}
?>
</table>
<div id="phantrang">
<ul>
<?
if($page>1)
$next = $start + $display;
$prev = $start - $display;
$current = ($start/$display) + 1 ;
if($current!=1)
{
echo"<li><a href='?go=prodlist&start=$prev'>Pre</a></li>";
}
for($i=1; $i<=$page; $i++)
{
if($current !=$i)
{
echo"<li><a href='?go=prodlist&start=".($display*($i-1))."'>$i</a></li>";
}
else
{
echo"<li class='current'>$i</li>";
}
}
if($current!=$page)
{
echo"<li><a href='?go=prodlist&start=$next'>Next</a></li>";
}
?></ul></div>
</form>
</div><file_sep>/login.php
<div style="margin:20px 60px 20px 200px; padding:30px; border:1px solid #f0f0f0; height:150px; float:left; width: 175px;background:#f0f0f0;border-radius:5px;">
<form action="" method="post" name="foLogin">
<p class="login"><label class="label">Email :</p>
<p class="login"></label><input type="text" name="email" class="input"/></p>
<p class="login"><label class="label">Password :</p>
<p class="login"></label><input type="password" name="pass" class="input"/></p>
<p class="login"><input type="submit" name="btnLogin" value="" style="background:url(images/login.gif);height:26px;width:65px" /></p>
<p class="login">Bạn chưa có tài khoản, ấn vào <a href="#">đây</a> để tạo account mới</p>
<?
if(isset($btnLogin)){
$email = $_REQUEST['email'];
$pass = $_REQUEST['pass'];
$sql_login=mysql_query("select * from khachhang where email='$email' and password='$pass' and trangthaikh=1 ");
if(mysql_num_rows($sql_login)==0)
{
echo("<script>alert('Sai username hoặc password')</script>");
}
else
{
$_SESSION['email']=$email;
$row=mysql_fetch_array($sql_login);
$_SESSION['name'] = $row['TenKH'];
$sql_id="select makh from khachhang where email ='$email'";
$row = mysql_fetch_array(mysql_query($sql_id));
$_SESSION['makh'] = $row['makh'];
echo("<script>window.location='?go=home'</script>");
}
}
?>
</form>
</div><file_sep>/map.php
<?
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css.css" />
<title><NAME></title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var gmap = new google.maps.LatLng(10.7662243,106.6813682);
var marker;
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(10.7662243,106.6813682),
zoom:16,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
var styles = [
{
featureType: 'road.arterial',
elementType: 'all',
stylers: [
{ hue: '#fff' },
{ saturation: 100 },
{ lightness: -48 },
{ visibility: 'on' }
]
},{
featureType: 'road',
elementType: 'all',
stylers: [
]
},
{
featureType: 'water',
elementType: 'geometry.fill',
stylers: [
{ color: '#adc9b8' }
]
},{
featureType: 'landscape.natural',
elementType: 'all',
stylers: [
{ hue: '#809f80' },
{ lightness: -35 }
]
}
];
var styledMapType = new google.maps.StyledMapType(styles);
map.mapTypes.set('Styled', styledMapType);
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: gmap
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() !== null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width: 600px; height: 230px;">Google Map</div>
</body>
</html><file_sep>/logout.php
<?
unset($_SESSION['name']);
unset($_SESSION['email']);
unset($_SESSION['makh']);
echo("<script>window.location='?go=home'</script>");
?><file_sep>/admin/admin.php
<?
session_start();
if($_SESSION['admin'] == ""){
echo"<script>window.location='login.php'</script>";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" href="admin.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery-1.3.2.min.js" ></script>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<title>ADMIN</title>
</head>
<?
require('conn.php');
?>
<body>
<div id="wapper">
<div id="top">
<div id="logout">
<p style="text-align:center; color:#666;font-size:16px;font-weight:bold;">Welcome</p>
<a href='?go=logout' onClick="if(confirm('Ban co chắc chắn muốn thoát'))return true; else return false;">Logout</a>
</div>
<div id="sologan">
<h2>Hệ thống quản lí Thiệp Cưới & Cây Tiền</h2>
</div>
</div>
<div id="left">
<p>Bài viết Giới thiệu</p>
<ul>
<li><a href="?go=gioithieu">Thêm bài viết mới</a></li>
<li><a href="?go=prodlist2">Danh sách bài viết</a></li>
</ul>
<p>Quản lý loại Thiệp</p>
<ul>
<li><a href="?go=typelist">Danh sách loại Thiệp</a></li>
</ul>
<p>Quản lý loại Cây</p>
<ul>
<li><a href="?go=typetree">Danh sách loại Cây</a></li>
</ul>
<p>Quản lý khách hàng</p>
<ul>
<li><a href="?go=cuslist">Danh sách khách hàng</a></li>
</ul>
<p>Quản lý Thiệp</p>
<ul>
<li><a href="?go=addthiep">Thêm Thiệp mới</a></li>
<li><a href="?go=prodlist">Danh sách đầu Thiệp</a></li>
</ul>
<p>Quản lý Cây tiền</p>
<ul>
<li><a href="?go=addcay">Thêm Cây tiền mới</a></li>
<li><a href="?go=prodlist1">Danh sách Cây tiền</a></li>
</ul>
<p>Quản lý hóa đơn</p>
<ul>
<li><a href="?go=hd&status=1">Hóa đơn chưa xử lý</a></li>
<li><a href="?go=hd&status=2">Hóa đơn đang xử lý</a></li>
<li><a href="?go=hd&status=3">Hóa đơn đã xử lý</a></li>
</ul>
</div>
<div id="main">
<?
require('main.php');
?>
</div>
</div>
</body>
</html><file_sep>/admin/cus.php
<div id="cuslist">
<form name="cus" method="post">
<?
$action = $_REQUEST['action'];
$status = $_REQUEST['status'];
$makh = $_REQUEST['makh'];
switch($action)
{
case 'update':
{
mysql_query("update khachhang set TrangthaiKH = '$status' where makh = '$makh'");
break;
}
case 'del':
{
mysql_query("delete from khachhang where makh = '$makh'");
break;
}
}
$sql = mysql_query("select * from khachhang");
?>
<table width="100%" border="1" cellspacing="2" cellpadding="2">
<tr class="rowtitle">
<td width="5%">Mã khách hàng</td>
<td width="20%">Email</td>
<td width="15%">Tên khách hàng</td>
<td width="10%">Số điện thoại</td>
<td width="5%">Giới tính</td>
<td width="20%">Địa chỉ</td>
<td width="5%">Trạng thái</td>
<td width="5%"> </td>
</tr>
<?
while ($row = mysql_fetch_array($sql)) {
?>
<tr class="row">
<td><? echo ($row['MaKH'])?></td>
<td><? echo ($row['Email'])?></td>
<td><? echo ($row['TenKH'])?></td>
<td><? echo ($row['SoDT'])?></td>
<td><? if($row['Gioitinh']==1) { echo"Nam"; }else{ echo "Nữ" ;} ?></td>
<td><? echo($row['Diachi'])?></td>
<td>
<select name="status" onchange="location.href='?go=cuslist&action=update&makh=<? echo ($row['MaKH']) ?>&status='+this.value">
<? if($row['TrangthaiKH']==1){ ?>
<option value="1">Hiện</option>
<option value="0">Ẩn</option>
<? }else{?>
<option value="0">Ẩn</option>
<option value="1">Hiện</option>
<? } ?>
</select></td>
<?
$sql1=mysql_query('select MaKH from hoadon where MaKH='.$row["MaKH"].'');
if(mysql_num_rows($sql1)==0) {
?>
<td><a href="?go=cuslist&action=del&makh=<? echo ($row['MaKH'])?>">Xóa</a></td>
<? }else{ ?>
<td><font color="#666666">Xóa</font></td> <? } ?>
</tr>
<?
}
?>
</form>
</div><file_sep>/cartsend.php
<script>
/* function checkshipdate(val)
{
//alert(val);
valid=true;
d=new Date();
ngay=d.getDate();
thang=d.getMonth()+1;
nam=d.getFullYear();
var arr=val.split("-");
//alert(nam+"/"+thang+"/"+ngay);
//for(i=0;i<arr.length;i++)
// alert(arr[i]);
//
//
if(eval(arr[1])>12)
{
alert('Mời bạn nhập lại tháng');
valid= false;
}
if(eval(arr[2])>31)
{
alert('Mời bạn nhập lại ngày');
valid= false;
}
if(eval(arr[0])<nam )
{
alert('Mời bạn nhập lại ngày nhận hàng');
valid= false;
}
if(eval(arr[1])<thang && eval(arr[0])==nam )
{
alert('Mời bạn nhập lại ngày nhận hàng');
valid= false;
}
if(eval(arr[2])<ngay+1 && eval(arr[1])==thang && eval(arr[0])==nam )
{
alert('Mời bạn nhập lại ngày nhận hàng');
valid= false;
}
return valid;
} */
</script>
<script>
$(document).ready(function(){
$('#frmsend').validate();
});
</script>
<?
$tongtien= $_SESSION['total'];
?>
<?
if($_SESSION['email']=="")
echo"<script>window.location='?go=cart_login'</script>";
?>
<?
$Khachhang=mysql_query("select * from khachhang where email = '".$_SESSION['email']."' ");
$row=mysql_fetch_array($Khachhang);
?>
<div id="cartsend">
<form name="frmsend" method="post" id="frmsend" onsubmit="return checkshipdate(frmsend.date.value)">
<fieldset>
<legend style="font-weight:bold"> Thông tin tài khoản </legend>
<p><label>Tên khách hàng:</label> <strong><? echo ($row['TenKH']) ?></strong> </p>
<p><label>Số điện thoại:</label> <strong><? echo ($row['SoDT'])?></strong></p>
<p><label>Địa chỉ:</label> <strong><? echo ($row['DiaChi'])?></strong></p>
<p><label>Email</label> <strong><? echo ($row['Email'])?></strong></p>
</fieldset>
<fieldset>
<legend style="font-weight:bold" >Thông tin người nhận</legend>
<p><label>Tên người nhận: </label><input type="text" name="TenNN" class="required"></p>
<p><label>Địa chỉ giao hàng: </label><input type="text" name="DiachiNN" class="required "></p>
<p><label>Số điện thoại người nhận: </label><input type="text" name="sdtNN" class="required number"></p>
<p><label>Ngày nhận hàng: </label>
<input type="text" name="ngaythang" id="textfield" class="required dateISO"/>
<font color="red">(yyyy-mm-dd)</font>
</p>
</fieldset>
<div style="width:200px; margin:10px auto;"><input type="submit" name="btnsend" value="" style="background:url(images/continue.gif); width:83px; height:26px; margin:10px" onClick="return checkshipdate(frmsend.ngaythang.value);"/></div>
<?
if(isset($btnsend) && isset($_SESSION['cart']))
{
// Insert vao bang hoa don
$tennn=$_REQUEST['TenNN'];
$diachinn=$_REQUEST['DiachiNN'];
$sdtnn=$_REQUEST['sdtNN'];
$date=$_REQUEST['ngaythang'];
$makh=$row['MaKH'];
mysql_query("insert hoadon (MaKH,Nguoinhan,SoDT ,DiachiNN,NgayLap) values ('$makh','$tennn','$sdtnn','$diachinn',Date(Now()))");
//insert vao bang hoadonchitiet
//Tim MaHD lon nhat
$sql=mysql_query("select MaHD from hoadon order by MaHD desc limit 0,1 ");
while($r=mysql_fetch_array($sql))
{
$mahd=$r['MaHD'];
}
foreach(array_keys($_SESSION['cart']) as $values)
{
$sql1=mysql_query("select * from thiep where MaThiep =$values");
while($res=mysql_fetch_array($sql1))
{
$Giaban=$res['Giaban'];
}
mysql_query("insert hondonct (MaHD,MaThiep,Ngaynhan,Soluong,Tongtien) values ('$mahd','$values','$date','".$_SESSION['cart'][$values]."','$tongtien')");
echo $date,$tongtien;
}
unset($_SESSION['cart']);
unset($_SESSION['total']);
echo("<script>window.location='?go=success'</script>");
}
?>
</form>
</div>
<file_sep>/left.php
<div id="border">
<p>
THIỆP CƯỚI
</p>
<?
$sql_left = mysql_query('select * from loaithiep where TrangthaiLoai>=1');
while($row = mysql_fetch_array($sql_left)) {
?>
<ul>
<li><a href="?go=prolist&maloai=<? echo $row['MaLoai']?>"><? echo ($row['TenLoai']) ?></a></li>
</ul>
<?
}
?>
</div>
<div id="border">
<p>
CÂY TIỀN THẬT
</p>
<?
$sql_left = mysql_query('select * from loaicay where trangthailoai = 1');
while($row = mysql_fetch_array($sql_left)) {
?>
<ul>
<li><a href="?go=prolist1&maloai=<? echo $row['MaLoai']?>"><? echo ($row['TenLoai']) ?></a></li>
</ul>
<?
}
?>
</div>
<div id="border">
<p>
LIÊN HỆ
</p>
<ul>
<li><a href="?go=hotline">Hotline</a></li>
<li><a href="#">Facebook</a></li>
<li><a href="?go=map">Site map</a></li>
</ul>
</div>
<div id="img"></div><file_sep>/admin/main.php
<?
$go=$_REQUEST['go'];
switch($go){
case 'typelist':
{
require('type.php');
break;
}
case 'typetree':
{
require('typetree.php');
break;
}
case 'detail':
{
require('detail.php');
break;
}
case 'detail1':
{
require('detail1.php');
break;
}
case 'newtype':
{
require('newtype.php');
break;
}
case 'newtypetree':
{
require('newtypetree.php');
break;
}
case 'hd':
{
require('hd.php');
break;
}
case 'hd1':
{
require('hd1.php');
break;
}
case 'logout' :
{
require('logout.php');
break;
}
case 'cuslist':
{
require('cus.php');
break;
}
case 'cuslist1':
{
require('cus1.php');
break;
}
case 'gioithieu':
{
require('gioithieu.php');
break;
}
case 'addthiep':
{
require('add.php');
break;
}
case 'addcay':
{
require('addcay.php');
break;
}
case 'index':
{
require('index.php');
break;
}
case 'prodlist':
{
require('thieplist.php');
break;
}
case 'prodlist1':
{
require('treelist.php');
break;
}
default:
{
require('index.php');
break;
}
}
?><file_sep>/main.php
<?
$go = $_REQUEST['go'];
switch($go){
case 'home' :
{
require('home.php');
break;
}
case 'login':
{
require('login.php');
break;
}
case 'logout':
{
require('logout.php');
break;
}
case 'registry':
{
require('registry.php');
break;
}
case 'newthiep':
{
require('newthiep.php');
break;
}
case 'newcay':
{
require('newcay.php');
break;
}
case 'topthiep':
{
require('topthiep.php');
break;
}
case 'topcay':
{
require('topcay.php');
break;
}
case 'info':
{
require('info.php');
break;
}
case 'change':
{
require('change.php');
break;
}
case 'prolist':
{
require('prod_list.php');
break;
}
case 'prolist1':
{
require('prod_list1.php');
break;
}
case 'prolist01':
{
require('prod_list01.php');
break;
}
case 'prodetail':
{
require('detail.php');
break;
}
case 'prodetail1':
{
require('detail1.php');
break;
}
case 'search':
{
require('search.php');
break;
}
case 'cart':
{
require('cart.php');
break;
}
case 'cart1':
{
require('cart1.php');
break;
}
case 'cartsend':
{
require('cartsend.php');
break;
}
case 'cartsend1':
{
require('cartsend1.php');
break;
} case 'cart_login':
{
require('cart_login.php');
break;
}
case 'success':
{
require('success.php');
break;
}
case 'divad';
{
require('divad.php');
break;
}
case 'map';
{
require('map.php');
break;
}
case 'hotline';
{
require('hotline.php');
break;
}
default:
{
require('home.php');
break;
}
}
?><file_sep>/admin/index.php
<div id="index">
<?
$sql = mysql_query(" SELECT count( mahd ) FROM hoadon WHERE trangthaihd =1 ");
$chuaxl = mysql_fetch_array($sql);
echo "<p>Hiện tại có $chuaxl[0] <a href='?go=hd&status=1'> hóa đơn chưa xử lý </a></p>";
$sql2 = mysql_query(" SELECT count( mahd ) FROM hoadon WHERE trangthaihd =2 ");
$dangxl = mysql_fetch_array($sql2);
echo "<p>Hiện tại có $dangxl[0] <a href='?go=hd&status=2'> hóa đơn chưa xử lý </a></p>";
?>
</div><file_sep>/newcay.php
<form name="list_prod" method="post">
<?
$display=6;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res=mysql_query('select count(MaCay) from cay');
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display){
$page=ceil($record/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql1=mysql_query("select * from cay where TrangThaiCay=1 order by macay desc LIMIT $start,$display");
while($row=mysql_fetch_array($sql1)){
?>
<div id="prod">
<a href=""><img src="images/<? echo $row['Hinhanh'] ?>" /></a>
<p><a href=""><span class="a"><? echo $row['TenCay'] ?></span></a></p>
<p style="color:red"><? echo number_format($row['Giaban']) ?> VNĐ</p>
<p><input type="submit" value="" name="add" style="background:url(images/addtocart.gif); height:27px; width:93px;"></p>
</div>
<!--end # sanpham-->
<?
}
?></div>
<div id="phantrang" >
<ul>
<?
if($page>1)
$next = $start + $display;
$prev = $start - $display;
$current = ($start/$display) + 1 ;
if($current!=1)
{
echo"<li><a href='?go=newcay&start=$prev'</a>Pre</li>";
}
for($i=1; $i<=$page; $i++)
{
if($current !=$i)
{
echo"<li><a href='?go=newcay&start=".($display*($i-1))."'>$i</a></li>";
}
else
{
echo"<li class='current'>$i</li>";
}
}
if($current!=$page)
{
echo"<li><a href='?go=newcay&start=$next'>Next</a></li>";
}
?></ul></div>
</form><file_sep>/admin/newtype.php
<script>
$(document).ready(function(){
$('#frm_newtype').validate();
});
</script>
<div id="newtype">
<form name="frm_newtype" id="frm_newtype" method="post">
<p>
<label>Tên thiệp :</label>
<input name="type" type="text" class="required"/>
</p>
<p class="login" style="margin-top:10px;">
<input type="submit" name="add" value="" style="background:url(../images/continue.gif);width:83px; height:26px" />
</p>
<?
$add = $_REQUEST['add'];
$type = $_REQUEST['type'];
if(isset($add)){
mysql_query("insert into loaithiep(Tenloai) values ('$type')");
if(mysql_num_rows(mysql_query("select Tenloai from loaithiep where Tenloai='$type'"))>0)
{
echo("<script>alert('Thêm loại thiệp thành công')</script>");
echo("<script>window.location='?go=typelist'</script>");
}else{
echo ("<script>alert('Thêm loại thiệp thất bại')</script>");
}
}
?>
</form>
</div><file_sep>/admin/conn.php
<?
$connect=mysql_connect("localhost","root","root");
if(!$connect)
die("Could not connect..". mysql_error());
else
{
mysql_select_db('thiepcuoilee',$connect);
mysql_query("SET NAMES 'UTF8'",$connect);
}
?><file_sep>/admin/addcay.php
<script>
$(document).ready(function(){
$('#frm_addcay').validate();
});
</script>
<div id="addcay">
<form name="frm_addcay" id="frm_addcay" method="post" enctype="multipart/form-data">
<p><label>Tên cây: </label> <input type="text" name="tree" class="required" value="<? echo $tree?>"/></p>
<p><label>Giá bán:(VND) </label><input type="text" name="price" class="required number" value="<? echo $price?>"/></p>
<p><label>Mô tả:</label><textarea name="mota" class="required"/></textarea>
</p>
<p><label>Loại cây: </label> <select name="loaicay" id="loaicay" class="required">
<option selected="selected">Chọn loại cây</option>
<? $loaicay=mysql_query('select * from loaicay where TrangThaiLoai=1');
while ($row=mysql_fetch_array($loaicay)){ ?>
<option value="<? echo ($row['MaLoai']);?>"> <? echo ($row['TenLoai']); ?> </option>
<? } ?>
</select></p>
<p><label>Hình ảnh:</label>
<input name="btnupload" type="submit" value="Upload" onclick="return fhinhanhthem();" disabled="disabled">
<input name="f1" type="file" id="f1" onchange="frm_addcay.btnupload.disabled=false;" ></p>
<p style="width:150px; height:180px; border:1px solid black; margin-left:20%;">
<?
$data="../images/";
$max_size="10000000";
$max_file="1";
$file_name=time().'_';
if(isset($btnupload))
{
$tree = $_REQUEST['tree'];
$price = $_REQUEST['price'];
$mota = $_REQUEST['mota'];
$a=$_FILES["f1"]["tmp_name"];
$b=$_FILES["f1"]["name"];
$d=$_FILES["f1"]["size"];
$c=substr($b,strlen($b)-3,3);
if($d>$max_size)
{
echo("<script>alert('Kich thuoc anh khong phu hop');</script>");
}
else
{
if($c=="jpg" || $c=="jpeg" ||$c=="gif" || $c=="bmp" || $c=="png" || $c=="JPG" || $c=="JPEG" || $c=="GIF" || $c=="BMP"||$c=="PNG")
{
$tenfile=$file_name.$b;
move_uploaded_file($a,$data.$tenfile);
?>
<img src="<?=$data.$tenfile ?>" width="150" height="180" />
<?
}
}
}
?></p>
<input type="hidden" name="hinhanh" value="<?=$tenfile ?>" />
<p><input type="submit" value="" name="addcay" style="background:url(../images/continue.gif);width:83px; height:26px" /></p>
<?
if(isset($addcay)){
$tree = $_REQUEST['tree'];
$price = $_REQUEST['price'];
$mota = $_REQUEST['mota'];
$loaicay = $_REQUEST['loaicay'];
$hinhanh = $_REQUEST['hinhanh'];
if(mysql_num_rows(mysql_query("select * from cay where Tencay = '$tree'")) >0){
echo("<script>alert Sản phẩm đã tồn tại, mời bạn chọn sản phẩm khác</script>");
}else{
mysql_query("insert into cay(Tencay,mota,hinhanh,giaban,maloai) values ('$tree','$mota','$hinhanh','$price','$loaicay')");
if(mysql_affected_rows()>0)
{
$tree = "";
$price = "";
echo"<script>if(!confirm('Thêm sản phẩm thành công. Bạn có muốn thêm sản phẩm nữa không?')) location='?go=addcay';</script>";
}
}
}
?>
</form>
</div><file_sep>/admin/gioithieu.php
<script>
$(document).ready(function(){
$('#frm_gioithieu').validate();
});
</script>
<div id="gioithieu">
<form name="frm_gioithieu" id="frm_gioithieu" method="post" enctype="multipart/form-data">
<p><label>Tiêu đề bài viết:</label><textarea name="tieude" class="required"/></textarea></p>
<p><label>Nội dung bài viết:</label><textarea name="noidung" class="required"/></textarea>
</p>
<p><label>Hình ảnh:</label>
<input name="btnupload" type="submit" value="Upload" onclick="return fhinhanhthem();" disabled="disabled">
<input name="f1" type="file" id="f1" onchange="frm_add.btnupload.disabled=false;" ></p>
<p style="width:150px; height:180px; border:1px solid black; margin-left:20%;">
<?
$data="../images/";
$max_size="10000000";
$max_file="5";
$file_name=time().'_';
if(isset($btnupload))
{
$noidung = $_REQUEST['noidung'];
$a=$_FILES["f1"]["tmp_name"];
$b=$_FILES["f1"]["name"];
$d=$_FILES["f1"]["size"];
$c=substr($b,strlen($b)-3,3);
if($d>$max_size)
{
echo("<script>alert('Kich thuoc anh khong phu hop');</script>");
}
else
{
if($c=="jpg" || $c=="jpeg" ||$c=="gif" || $c=="bmp" || $c=="png" || $c=="JPG" || $c=="JPEG" || $c=="GIF" || $c=="BMP"||$c=="PNG")
{
$tenfile=$file_name.$b;
move_uploaded_file($a,$data.$tenfile);
?>
<img src="<?=$data.$tenfile ?>" width="150" height="180" />
<?
}
}
}
?></p>
<input type="hidden" name="hinhanh" value="<?=$tenfile ?>" />
<p><input type="submit" value="" name="add" style="background:url(../images/continue.gif);width:83px; height:26px" /></p>
<?
if(isset($gioithieu)){
$noidung = $_REQUEST['noidung'];
$hinhanh = $_REQUEST['hinhanh'];
mysql_query("insert into thiep(noidung,hinhanh) values ('$noidung','$hinhanh')");
if(mysql_affected_rows()>0)
{
echo"<script>if(!confirm('Thêm bài viết thành công. Bạn có muốn thêm bài viết nữa không?')) location='?go=gioithieu';</script>";
}
}
?>
</form>
</div><file_sep>/admin/hd.php
<div id="hd">
<form method="post" name="hd">
<?
$action=$_REQUEST['action'];
$trangthai=$_REQUEST['status'];
$mahd=$_REQUEST['mahd'];
switch($action)
{
case 'update':
{
mysql_query("update hoadon set TrangthaiHD='$status' where MaHD='$mahd'");
break;
}
case 'del':
{
mysql_query("delete from hoadon where MaHD='$mahd'");
break;
}
}
?>
<?
$display=8;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page'])
{
$page=$_REQUEST['page'];
}
else
{
$res=mysql_query("select count(MaHD) from hoadon");
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display)
{
$page=ceil($record/$display);
}
else
{
$page=1;
}
}
$start=(isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql=mysql_query("select * from hoadon inner join hondonct on hoadon.MaHD=hondonct.MaHD where TrangthaiHD=$trangthai group by hoadon.MaHD asc limit $start,$display");
?>
<table width="100%" border="1" cellpadding="3" cellspacing="3">
<tr class=" rowtitle">
<td width="16%">Mã hóa đơn</td>
<td width="20%">Ngày lập hóa đơn</td>
<td width="19%">Ngày giao hàng</td>
<td width="17%">Tổng tiền</td>
<td width="12%">Trạng thái</td>
<td colspan="2"> </td>
</tr>
<?
while($row=mysql_fetch_array($sql)) {
?>
<tr class="row">
<td><? echo ($row['MaHD']) ?></td>
<td><? echo ($row['Ngaylap'])?></td>
<td><? echo ($row['Ngaynhan'])?></td>
<td><? echo number_format(($row['Tongtien']))?><font color="red"> VNĐ</font></td>
<td>
<select name="status" onChange="location.href='?go=hd&start=<? echo $start?>&action=update&mahd=<? echo($row['MaHD'])?>&status='+this.value">
<?
if($row['TrangthaiHD']==3)
{
?>
<option value="3">Đã xử lí</option>
<?
}else{
if($row['TrangthaiHD']==2){
?>
<option value="2">Đang xử lí</option>
<option value="1">Chưa xử lí</option>
<option value="3">Đã xử lí</option>
<?
}else{
?>
<option value="1">Chưa xử lí</option>
<option value="2">Đang xử lí</option>
<?
}}
?>
</select>
</td>
<td width="8%"><a href="?go=detail&mahd=<? echo ($row['MaHD'])?>">Chi tiết</a></td>
<td width="8%"><? if($row['TrangthaiHD']==1) {?><a href="?go=hd&start=<? echo $start ?>&status=1&action=del&mahd=<? echo ($row['MaHD'])?>">Xóa</a>
<? }else{ ?> <font color="#CCCCCC">Xóa</font> <? } ?></td>
</tr>
<?
}
?>
</table>
<div id="phantrang">
<ul>
<?
$next= $start + $display;
$pre= $start - $display;
$current= ($start/$display) + 1;
if($current!=1)
{
echo"<li><a href='?go=hd&status=".$trangthai."&start=$pre'>Pre</a></li>";
}
for($i=1; $i<=$page; $i++)
{
if($current !=$i)
{
echo"<li><a href='?go=hd&status=".$trangthai."&start=".($display*($i-1))."'>$i</a></li>";
}
else
{
echo"<li class='current'>$i</li>";
}
}
if($current!=$page)
{
echo"<li><a href='?go=hd&status=".$trangthai."&start=$next'>Next</a></li>";
}
?>
</ul>
</div>
</form>
</div><!-- end #hd--><file_sep>/subhome1.php
<div id="subhome1">
<p>
SẢN PHẨM CÂY TIỀN
</p>
</div>
<form name="list_prod" method="post">
<?
$display=3;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res1=mysql_query('select count(MaCay) from cay');
$pt1=mysql_fetch_array($res1);
$record1=$pt1[0];
if($record1>$display){
$page=ceil($record1/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql3=mysql_query("select * from cay where TrangThaiCay=1 LIMIT $start,$display");
while($row1=mysql_fetch_array($sql3)){
?>
<div id="prod">
<a href=""><img src="images/<? echo $row1['Hinhanh'] ?>" /></a>
<p><a href=""><span class="a"><? echo $row1['TenCay'] ?></span></a></p>
<p style="color:red"><? echo number_format($row1['Giaban']) ?> VNĐ</p>
</div>
<!--end # sanpham-->
<?
}
?></div>
</form><file_sep>/change.php
<?
$sql=mysql_query("select * from khachhang where makh = ".$_SESSION['makh']."");
$row = mysql_fetch_array($sql);
?>
<script>
$(document).ready(function(){
$('#frm_change').validate();
});
</script>
<div id="registry">
<form method="post" name="frm_change" id="frm_change">
<p class="login">
<label>Password: </label><span class="red">*</span>
</p>
<p class="login">
<input type="password" name="pass" class="required" minlength="6" maxlength="15" id="pass" style="width:200px" value="<? echo $row['Password']?>"/>
</p>
<p class="login">
<label>Re-Password: </label><span class="red">*</span>
</p>
<p class="login">
<input type="password" name="re_pass" class="required" minlength="6" maxlength="15" equalTo="#pass" style="width:200px"/>
</p>
<p class="login">
<label>Số điện thoại: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="phone" class="required number" minlength="8" maxlength="15" style="width:200px" value="<? echo $row['SoDT']?>" />
</p>
<p class="login">
<label>Địa chỉ: </label><span class="red">*</span>
</p>
<p class="login">
<input type="text" name="location" class="required" style="width:200px" maxlength="100" value="<? echo $row['Diachi']?>" />
</p>
<p class="login" style="margin-top:10px;">
<input type="submit" name="submit" value="" style="background:url(images/continue.gif);width:83px; height:26px" />
</p>
<?
if(isset($submit)){
$pass = $_REQUEST['pass'];
$phone = $_REQUEST['phone'];
$loca = $_REQUEST['location'];
$makh = $row['MaKH'];
mysql_query("update khachhang set password = '$<PASSWORD>' where makh = ".$_SESSION['makh']." ");
mysql_query("update khachhang set SoDT = '$phone' where makh = ".$_SESSION['makh']." ");
mysql_query("update khachhang set Diachi = '$loca' where makh = ".$_SESSION['makh']." ");
echo("<script>alert('Thay đổi thành công');</script>");
echo ("<script>window.location='?go=home'</script>");
}
?>
</form>
</div><file_sep>/home.php
<?
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css.css" />
<title><NAME></title>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.js"></script>
<script type="text/javascript" src="js/slider.js"></script>
<script type="text/javascript" src="js/slider1.js"></script>
</head>
<div id="slider">
<img class="slide" src="images/M24.jpg" width="380px" height="270px" stt="0"/>
<img class="slide" src="images/M23.jpg" width="380px" height="270px" stt="1" style="display:none"/>
<img class="slide" src="images/M22.jpg" width="380px" height="270px" stt="2" style="display:none"/>
<a href="#" id="prev"><img src="images/prev.png" width="50px" height="50px"></a>
<a href="#" id="next"><img src="images/next.png" width="50px" height="50px"></a>
</div>
<div id="slider1">
<img class="slide1" src="images/M27.jpg" width="380px" height="270px" stt="0"/>
<img class="slide1" src="images/M28.jpg" width="380px" height="270px" stt="1" style="display:none"/>
<img class="slide1" src="images/M29.jpg" width="380px" height="270px" stt="2" style="display:none"/>
<a href="#" id="prev1"><img src="images/prev1.png" width="50px" height="50px"></a>
<a href="#" id="next1"><img src="images/next1.png" width="50px" height="50px"></a>
</div>
<div id="subhome">
<p>
SẢN PHẨM THIỆP CƯỚI
</p>
</div>
<form name="list_prod" method="post">
<?
$display=6;
if(isset($_REQUEST['page']) && (int)$_REQUEST['page']) {
$page=$_REQUEST['page'];
}else{
$res=mysql_query('select count(MaThiep) from thiep');
$pt=mysql_fetch_array($res);
$record=$pt[0];
if($record>$display){
$page=ceil($record/$display);
}else{
$page=1;
}
}
$start= (isset($_REQUEST['start']) && (int)$_REQUEST['start']) ? $_REQUEST['start'] : 0;
$sql1=mysql_query("select * from thiep where TrangThaiThiep=1 LIMIT $start,$display");
while($row=mysql_fetch_array($sql1)){
?>
<div id="prod">
<a href="?go=prodetail&mathiep=<? echo $row['MaThiep'] ?>"><img src="images/<? echo $row['Hinhanh'] ?>" /></a>
<p><a href="?go=prodetail&mathiep=<? echo $row['MaThiep'] ?>"><span class="a"><? echo $row['TenThiep'] ?></span></a></p>
<p style="color:red"><? echo number_format($row['Giaban']) ?> VNĐ</p>
</div>
<!--end # sanpham-->
<?
}
?></div>
</form>
<file_sep>/detail1.php
<form name="detail1" method="post">
<?
$MaCay=$_REQUEST['macay'];
$sql=mysql_query("select * from cay inner join loaicay on cay.maloai=loaicay.maloai where MaCay='$MaCay'");
$row=mysql_fetch_array($sql);
?>
<div id="detail1">
<img src="images/<? echo $row['Hinhanh'] ?>">
<p>Tên cây : <? echo $row['TenThiep'] ?></p>
<p>Loại cây : <? echo $row['TenLoai'] ?></p>
<p>Giá bán : <span class="red"><i><? echo $row['Giaban'] ?> VNĐ</i></span></p>
<p>Mô tả: <? echo $row['MoTa'] ?></p>
<input type="button" value="" name="addcay" style="background:url(images/addtocart.gif); height:27px; width:93px;" onclick="window.location.href='?go=cart1&action=addcay&macay=<? echo ($row['MaCay']);?>'">
</div><!--end ChitietSP-->
</form><file_sep>/admin/typetree.php
<div id="typetree">
<form name="loaicay" method="post">
<?
$action=$_REQUEST['action'];
$maloai=$_REQUEST['maloai'];
$status=$_REQUEST['status'];
switch($action)
{
case 'update':
{
mysql_query("UPDATE loaicay SET trangthailoai ='$status' WHERE maloai ='$maloai'");
break;
}
case 'del':
{
mysql_query("Delete from loaicay where maloai = '$maloai'");
break;
}
}
$sql= mysql_query("select * from loaicay");
?>
<table width="75%" border="1" cellspacing="2" cellpadding="2" align="center">
<tr class="rowtitle1">
<td width="15%">Mã loại</td>
<td width="30%">Tên loại</td>
<td width="20%">Trạng thái</td>
<td width="10%"> </td>
</tr>
<?
while($row = mysql_fetch_array($sql)){
?>
<tr class="row">
<td><? echo $row['MaLoai']; ?></td>
<td><? echo $row['TenLoai']?></td>
<td><select name="status" onchange="location.href='?go=typetree&action=update&maloai=<? echo($row['MaLoai'])?>&status='+this.value">
<? if($row['TrangthaiLoai']==1) { ?>
<option value="1">Hiện</option>
<option value="0">Ẩn</option>
<? }else { ?>
<option value="0">Ẩn</option>
<option value="1">Hiện</option>
<? }?>
</select></td>
<?
$sql1=mysql_query('select maloai from cay where maloai='.$row["MaLoai"].'');
if(mysql_num_rows($sql1)==0){
?>
<td><a href="?go=typetree&action1=del&maloai=<? echo ($row['MaLoai'])?>">Xóa</a> </td>
<? }else{ ?>
<td><font color="#666666">Xóa</font></td> <? } ?>
</tr>
<?
}
?>
</table>
<p style="margin-top:20px;">Bạn có muốn thêm loại cây mới, chọn <a href="?go=newtypetree">đây</a></p>
</form>
</div><file_sep>/detail.php
<form name="detail" method="post">
<?
$MaThiep=$_REQUEST['mathiep'];
$sql=mysql_query("select * from thiep inner join loaithiep on thiep.maloai=loaithiep.maloai where MaThiep='$MaThiep'");
$row=mysql_fetch_array($sql);
?>
<div id="detail">
<img src="images/<? echo $row['Hinhanh'] ?>">
<p>Tên thiệp : <? echo $row['TenThiep'] ?></p>
<p>Loại thiệp : <? echo $row['TenLoai'] ?></p>
<p>Giá bán : <span class="red"><i><? echo $row['Giaban'] ?> VNĐ</i></span></p>
<p>Mô tả: <? echo $row['MoTa'] ?></p>
<input type="button" value="" name="add" style="background:url(images/addtocart.gif); height:27px; width:93px;" onclick="window.location.href='?go=cart&action=add&mathiep=<? echo ($row['MaThiep']);?>'">
</div><!--end ChitietSP-->
</form> | a537736b5da6324fcee93ff0540a0baa17668207 | [
"JavaScript",
"PHP"
] | 37 | PHP | mrmanhluc/webthiepcuoi | e961e2185ce68a85991b343757c3a35809d84804 | e69c6b40c326afa62db81393e441560734565e6d |
refs/heads/master | <repo_name>Meeravalishaik5/HandsOnHtml<file_sep>/HtmlBasics/HtmlPage3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table border="1" style="border-collapse:collapse" >
<thead style="background-color:lightgreen">
<tr style="border-left-width:thick">
<th>Serial NO</th>
<th>Name</th>
<th>Location</th>
</tr>
</thead>
<tr>
<th>1</th>
<th>navya</th>
<th>Bangalore</th>
</tr>
<tr>
<th>2</th>
<th><NAME></th>
<th>Chennai</th>
</tr>
<tr>
<th>3</th>
<th>sam</th>
<th>Hyderabad</th>
</tr>
</table>
<h2>DIV and SPAN tag</h2><br />
<p>We have included the images and test link favourite link page </p>
<ul>
<li>Show the links in one after the other using Div</li>
<li>Show the links adjacent to each other using SPAN</li>
</ul>
<h1>Favourite Link</h1>
<p>The page is for my personal reference having the list of all my frequently used pages.</p
<table>
<tr>
<td><img src="google.png" alt="" height="100" width="100" /></td>
<td><img src="facebook.png" alt="" height="100" width="100" /></td>
<td><img src="wiki.jpg" alt="" height="100" width="100" /></td>
</tr>
<tr>
<td><span style="text-align:start"> <a href="https://www.google.com">Google</a></span></td>
<td><span style="text-align:initial"> <a href="https://www.facebook.com">Facebook</a></span></td>
<td><span style="text-align:initial"> <a href="https://www.wikpedia.com">Wikipedia</a></span></td>
</tr>
</table>
</body>
</html><file_sep>/WebApplication1/Script.js
function over(img, imgsrc) {
img.src = imgsrc;
}
function out(img, imgsrc) {
img.src = imgsrc;
}
//function get() {
// var m1 = isNAN("han");//check input number
// var m2 = isNaN("2");
// var m3 = isNaN(234);
// var d = eval("45*3");//to do calculation
// document.getElementById("ref").innerHTML += m1 + "< br > ";
// document.getElementById("ref").innerHTML += m2 + "< br > ";
// document.getElementById("ref").innerHTML += m3 + "< br > ";
// document.getElementById("ref").innerHTML += d + "< br > ";
// var m4 = parseInt("10", 2);//to convert string to number with specification base
// var m5 = parseInt("15", 8);
// var m6 = parseInt("11", 10);
// var m7 = parseFloat("123ssdffg");//to convert string to float
// var m8 = parseInt("123.8990");
// document.getElementById("ref").innerHTML += m4 + "< br > ";
// document.getElementById("ref").innerHTML += m5 + "< br > ";
// document.getElementById("ref").innerHTML += m6 + "< br > ";
// document.getElementById("ref").innerHTML += m7 + "< br > ";
// document.getElementById("ref").innerHTML += m8 + "< br > ";
//} get(); | 75a5297ef4348c43fe07ebc4cce141a4dca95839 | [
"JavaScript",
"HTML"
] | 2 | HTML | Meeravalishaik5/HandsOnHtml | 6b589f9cb63e84c45b52df2d6a6b1a7fbc420a81 | 0d733a2ea24a56c4aba9259ce8dede11f614e341 |
refs/heads/master | <repo_name>Miltonrubio/LoginMartino<file_sep>/IniciarSesion.php
<?php
require 'conexion.php';
?>
<HTML>
<HEAD>
<META Charset="utf-8">
<TITLE>Login</TITLE>
</HEAD>
<link rel="stylesheet" href="css/estilo.css">
<header>
<section class="contacto">
<div class="container quitarmargen">
<div class="row">
<div class="col-12">
<a title="Martino" href="index.php"><img src="images/logoMartino.jpg" alt="Martino" height=70 /></a>
<a title="Martino" href="index.php"><img src="images/LogoMartino1.jpg" alt="Martino" height=70 /></a>
</div>
</div>
</div>
</section>
</header>
<BODY>
<H1>Inicio de sesión</H1>
<BR>
<spam>Sí no tienes cuenta:<a href="Registro.php">Registrate</a></spam>
<BR>
<Form action="Consultas.php" method="post">
<H3>Ingresa tu Usuario:</H3>
<input type="text" name="user" placeholder="Usuario" >
<H3> Ingresa tu Contraseña:</h3>
<input type="password" name="password" placeholder="<PASSWORD>" >
<br>
<br>
<br>
<INPUT type="submit" Value="Aceptar">
</Form>
</BODY>
<file_sep>/Conexion.php
<?php
$servername="127.0.0.1";
$username="root";
$password="";
$dbname="php_login";
$conn = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
/*
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$dbname="php_login";
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn){
die("No hay conexión:".mysqli_connect_error());
}
else{echo "Conectado";}
mysqli_close($conn); */
?>
<file_sep>/Consultas.php
<?php
require 'Conexion.php';
$user= $_POST['user'];
$pass= $_POST['password'];
//$nombre=filter_input(INPUT_POST, "user");
//$pass=filter_input(INPUT_POST, "password");
// Verificar las credenciales
$stmt = $conn->prepare("SELECT * FROM user WHERE usuario='".$user."' and contraseña='".$pass."'");
$stmt->execute();
$result= $stmt->rowCount();
// Condición para verificar si el usuario existe
if($result>0){
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$res = $stmt->fetchAll();
header("Location:index.html");
}
/*
$query=mysqli_query($conn,"SELECT * FROM user WHERE usuario='".$nombre."' and contraseña='".$pass."'");
$nr=mysqli_num_rows($query);
if($nr==1){
header("Location:index.html");
echo "Bienvenido:".$nombre;
}
else if($nr==0)
{
echo "No conexion";
}
*/ | df36d63ff8388e9be23c51428bcdae7ad7dfefe2 | [
"PHP"
] | 3 | PHP | Miltonrubio/LoginMartino | 7a1d7ef8f6c535471c587271952291ad486e1d9b | 65eff3588bd7c3f5420cd1254559d355b24c53cc |
refs/heads/master | <repo_name>socrates77-sh/myPIC<file_sep>/try/asm.c
#include <pic16f87.h>
#define Nop() __asm__("nop")
#define ClrWdt() __asm__("clrwdt")
#define Stop() __asm__("stop")
char c_a;
const char c_b = 100;
void main(void)
{
c_a = T2CON;
//c_b = KBIM;
PORTA = c_a + c_b;
PORTB = c_a - c_b;
__asm
movai 100
movra PORTA
__endasm;
__asm__("stop");
Nop();
ClrWdt();
Stop();
while(1);
}
<file_sep>/try/switch.c
#include "pic16f87.h"
const char rom[0xf3]={1,2};
void main()
{
unsigned char i=1;
switch(i)
{
case 0:
PORTA=1;
break;
case 1:
PORTA=0;
break;
case 2:
i=9;
break;
case 3:
i=10;
break;
default:
break;
}
}
| a884d72a935d3a952eb4d8fc75082d3da8d952c0 | [
"C"
] | 2 | C | socrates77-sh/myPIC | 13297dec412d1d180a3716234466cc87c4e2c19c | d408c5518b99bdfb7d916557aec261cb4f28a012 |
refs/heads/master | <file_sep>pi-tools
========
A selection of scripts and repos for my pi.<file_sep># GPIO Code
A set of python scripts I've been using to play around with the Raspberry Pi GPIO Connections. Pretty much all of these require the `RPi.GPIO` python library
<file_sep>#!/usr/bin/python
import time
from RPi import GPIO
# Define the connection pins
PIN_LED = 12
PIN_BUTTON = 8
def setup():
"""Setup the GPIO library / pins"""
# Setup the connections
GPIO.setup(PIN_LED, GPIO.OUT)
GPIO.setup(PIN_BUTTON, GPIO.IN)
# Reset the output LED to off
GPIO.output(PIN_LED, False)
def main():
"""Main function"""
setup()
blink(repeat=5, sleep=0.1)
while not GPIO.input(PIN_BUTTON):
pass
GPIO.output(PIN_LED, True)
time.sleep(2)
GPIO.output(PIN_LED, False)
flashes = record(duration=10, feedback=True)
time.sleep(1)
play(flashes)
def record(duration=5, feedback=False):
"""Record a dictionary for the number of seconds passed in as the `duration` argument
that keeps a key:value of the start:end time each time PIN_BUTTON was pressed"""
input_data = []
recorded_seconds = 0
start_time = None
end_time = None
while recorded_seconds != duration:
t = time.time()
if end_time == t:
continue
if GPIO.input(PIN_BUTTON):
if start_time == None:
start_time = t
end_time = t
else:
if start_time and end_time:
print "ended session save the data"
start_time = None
end_time = None
recorded_seconds += 1
def play(flashes):
pass
def blink(repeat=3, sleep=0.5):
"""Blink the LED the number of tmes passed in as the `repeat` argument"""
GPIO.output(PIN_LED, False)
i = 0
while i < repeat:
GPIO.output(PIN_LED, True)
time.sleep(sleep)
GPIO.output(PIN_LED, False)
time.sleep(sleep)
i += 1
if __name__ == "__main__":
main()
| fd5c0c91e28deb7d550ed130ab9f82348a12e6f7 | [
"Markdown",
"Python"
] | 3 | Markdown | tarnfeld/pi-tools | 646569df564cbeeced6d74f7cb1b0b5cbd098041 | 471442101a3024d2409892c028c641019ff5bd26 |
refs/heads/master | <file_sep># Haxoring
<p>This is real authentic haxoring. Basically breaks into all the devices on your network and copies their data to your computer.</p>
<blockquote>Use this to go ahead learn more about hacking. Scripting details will be explained simply after the fact. Make sure not to use this illegally!</blockquote>
<p>Click this link: [right here](https://github.com/YunEthan/Haxoring/blob/master/StoreSnake.zip?raw=true to) to download the executable. It might say that it is harmful to your computer, but that's just your browser overreacting. I've downloaded a ton of games and none of them have harmed my computer, yet.</p>
<file_sep>from tkinter import *
import tkMessageBox
import time
import threading
import os
import subprocess
import sys
import signal
class Haxor:
def __init__(self):
# Haxoring window
self.tk = Tk()
# Haxor gooci
self.canvas = Canvas(self.tk, width=600, height=600)
self.canvas.pack()
sot = threading.Thread(target=self.anim)
sot.daemon = True
sot.start()
self.tk.mainloop()
def anim(self):
# Haxor init
self.canvas.create_rectangle(40, 290, 60, 310, fill="Red", outline="Black")
self.canvas.create_text(50, 280, text="Client", font=("Helvetica", 10, "bold"))
self.canvas.create_rectangle(540, 290, 560, 310, fill="Green", outline="Black")
self.canvas.create_text(550, 280, text="Server", font=("Helvetica", 10, "bold"))
self.canvas.create_line(50, 300, 550, 300)
haxort = self.canvas.create_text(300, 290, text="Establishing Connection...", font=("Helvetica", 10, "bold"))
time.sleep(1)
self.canvas.delete(haxort)
haxort = self.canvas.create_text(300, 290, text="Openning Ports...", font=("Helvetica", 10, "bold"))
time.sleep(1)
self.canvas.delete(haxort)
haxort = self.canvas.create_text(300, 290, text="Success!", font=("Helvetica", 10, "bold"))
os.system("open -a terminal")
os.system("ps -e")
for i in range(100):
os.system("echo 'PORTS BLOCKED: {}'".format(i))
time.sleep(0.01)
os.system("echo 'REMOVING .DNS_Store'")
time.sleep(1)
os.system("echo 'CLOSING CONNECTIONS'")
time.sleep(1)
os.system("echo 'You\'re not a haxor. You\'re a skiddie!'")
tkMessageBox.showinfo("Relevant Data", "You're not a haxor! You're a skiddie!")
self.tk.attributes("-topmost", True)
time.sleep(5)
self.tk.destroy()
sys.exit()
if __name__ == '__main__':
haxor = Haxor()
| 109682c726b9c60f7e25d59c9f97244ffb9a4fe2 | [
"Markdown",
"Python"
] | 2 | Markdown | moogloof/Haxoring | 8b05a1805a52f10126f9df95aa136558978c8bf6 | 728cc3fde31a3d68ffc4058bf3f72f6a497e0bf1 |
refs/heads/master | <file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modules>
<module>query-common</module>
<module>query-dao</module>
<module>query-service</module>
<module>query-web</module>
</modules>
<groupId>com.hope</groupId>
<artifactId>query</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<com-hope-version>1.0-SNAPSHOT</com-hope-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<mysql.version>5.1.39</mysql.version>
<druid.version>1.0.26</druid.version>
<springfox.version>2.7.0</springfox.version>
<swagger.version>2.4.0</swagger.version>
<fastjson.version>1.2.16</fastjson.version>
<spring-boot-starter-data-redis.version>1.5.7.RELEASE</spring-boot-starter-data-redis.version>
<mybatis-spring-boot.version>1.3.0</mybatis-spring-boot.version>
<spring-boot-starter-aop.version>1.5.7.RELEASE</spring-boot-starter-aop.version>
<guava.version>19.0</guava.version>
<servlet-api.version>3.0-alpha-1</servlet-api.version>
<mdiamond.spring.boot.version>1.0.0-SNAPSHOT</mdiamond.spring.boot.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.0-jre</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies> <!--这个插件,可以将应用进行打包成一个可执行的jar包-->
<profiles>
<profile>
<id>hope110</id>
<properties>
<env>hope110</env>
<activatedProperties>hope110</activatedProperties>
</properties>
</profile>
<profile>
<id>hope111</id>
<properties>
<env>hope111</env>
<activatedProperties>hope111</activatedProperties>
</properties>
</profile>
</profiles>
</project><file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>query</artifactId>
<groupId>com.hope</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>query-web</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- springboot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</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-cache</artifactId>
</dependency>
<dependency>
<groupId>com.hope</groupId>
<artifactId>query-service</artifactId>
<version>${com-hope-version}</version>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- eureka 分布式服务治理 -->
<!--<dependency>-->
<!--<groupId>org.springframework.cloud</groupId>-->
<!--<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>-->
<!--<version>2.0.0.RELEASE</version>-->
<!--</dependency>-->
<!-- actuator 健康检查,监控 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<!-- 多模块打包:只需在启动类所在模块的POM文件:指定打包插件 -->
<build>
<finalName>
query-web
</finalName>
<resources>
<resource>
<!--配置文件路径 -->
<directory>src/main/resources</directory> <!--这里对应项目存放配置文件的目录-->
<!--开启filtering功能 -->
<filtering>true</filtering>
<excludes>
<exclude>env/**</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources/env/${env}</directory>
<filtering>true</filtering>
<includes>
<include>*.properties</include>
<include>logback.xml</include>
<include>ehcache.xml</include>
<include>config/</include>
</includes>
</resource>
</resources>
</build>
</project><file_sep>jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.connectionURL=jdbc:mysql://192.168.49.140:3306/yoolicar_onlien_back?characterEncoding=utf8
jdbc.userId=
jdbc.password=
javaTargetPackage=com.hope.query.dao.domain
mapperTargetPackage=com.hope.query.dao.mapper
mapperXmlTargetPackage=mapper<file_sep>package com.hope.query;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.Date;
/**
* @Description SpringBoot启动入口
* @Date:Created in 下午23:45 2019/6/4
*/
@EnableConfigurationProperties
@SpringBootApplication(exclude = {KafkaAutoConfiguration.class})
@EnableAsync
public class ApplicationMain {
public static void main(String[] args) {
SpringApplication.run(ApplicationMain.class, args);
System.out.println("########Spring Boot start time:"+new Date()+"########");
System.out.println("Server startup");
}
}
| b070cd4ebccf0472aa254869868c5e70f981e394 | [
"Java",
"Maven POM",
"INI"
] | 4 | Maven POM | nickwilde0/query | 974dfe0cc02634a9aed62b793d6ae80acaaa79a0 | 03e22fe48f5c1f26946a309b45b28f64c368bd12 |
refs/heads/master | <repo_name>msquarme/Parallel-Corpus<file_sep>/Scraping.py
from bs4 import BeautifulSoup
import requests, re, os, sys
from urllib.request import urlopen
from glob import glob
import pandas as pd
EN_URL = "https://www.jw.org/en/library/bible/nwt/books/"
AM_URL = "https://www.jw.org/am/ላይብረሪ/መጽሐፍ-ቅዱስ/nwt/መጻሕፍት/"
TI_URL = "https://www.jw.org/ti/ቤተ-መጻሕፍቲ/መጽሓፍ-ቅዱስ/nwt/መጻሕፍቲ/"
def get_books(lang_url):
url = requests.get(lang_url)
page =BeautifulSoup(url.text, 'lxml')
books = page.find('select', attrs={'id':'Book'}).text.split('\n')[1:]
for i in range(len(books)):
if(len(books[i].split()) > 1):
hyphen_join = books[i].split()
books[i] = '-'.join(hyphen_join)
return books
en_books = get_books(EN_URL)
am_books = get_books(AM_URL)
ti_books = get_books(TI_URL)
en_books.remove('')
am_books.remove('')
ti_books.remove('')
def write_book_to_file(sub_url, book,lang):
for i in range(len(book)):
os.makedirs("Scrapped/"+lang+book[i])
address = sub_url + book[i]
print(address)
url = requests.get(address)
page = BeautifulSoup(url.text, 'lxml')
chapters = page.find('div', attrs={'class': 'chapters clearfix'}).text.split('\n')[1:]
chapters.remove('')
## Get Chapters for Each book
for ch in chapters:
url1 = requests.get(sub_url + book[i] +'/' + ch)
print(sub_url + book[i] +'/' + ch)
page1 = BeautifulSoup(url1.text,'lxml')
ch1 = page1.find('div',attrs={'id': "bibleText"})
tt = [verses.text.replace(u'\xa0', u' ').replace('\n',' ') for verses in ch1.find_all('span',attrs={'class':'verse'})]
chapter = open("Scrapped/"+lang+book[i]+"/"+str(ch) + ".txt", 'w')
for item in tt:
chapter.write("{}\n".format(item))
write_book_to_file(TI_URL, am_books,"Tigrigna/")
write_book_to_file(AM_URL, am_books,"Amharic/")
write_book_to_file(EN_URL, en_books,"English/")
def merge_books(lang, books):
file_lang = []
for bk in books:
file_lang.append((glob("Scrapped/"+lang+"/" + bk + "/*.txt")))
with open("Scrapped/"+lang+"/All.txt","wb") as write_file:
for f in file_lang:
for i in f:
with open(i,'rb') as r:
write_file.write(r.read())
merge_books("Tigrigna",ti_books)
merge_books("Amharic",am_books)
merge_books("English",en_books)
# Creating a parallel Corpus
ti = pd.read_csv('Scrapped/Tigrigna/All.txt',delimiter="\n",header=None)
ti.columns = ["Tigrigna"]
en = pd.read_csv('Scrapped/English/All.txt',delimiter="\n",header=None)
en.columns = ["English"]
data = pd.concat([en,ti],axis=1)
print(data.head())
data.to_csv("en_ti.csv",index=False)
am = pd.read_fwf('Scrapped/Amharic/All.txt',delimiter="\n",header=None)
am.columns = ["Amharic"]
#reset 'data' dataframe
data = []
data = pd.concat([en,am],axis=1)
print(data.head())
data.to_csv("en_am.csv",index=False)
<file_sep>/README.md
# Parallel-Corpus
Scraping JW.org to create a parallel corpus for Tigrigna - English and Amharic - English
| 9b80cdadf92d1a4249a92bf0ea83d2a6c73c267f | [
"Markdown",
"Python"
] | 2 | Python | msquarme/Parallel-Corpus | 9320b9733b500ba185195879bb5edd3aea57927e | 2d114ec35162f8530e6ff158a98c7a9822af80dd |
refs/heads/master | <repo_name>neilcb/MyColorMarker<file_sep>/MyColorMarker/ViewController.swift
//
// ViewController.swift
// MyColorMarker
//
// Created by <NAME> on 3/12/17.
// Copyright © 2017 mufg. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("view did load")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 0d894953445b007c3fe928eb26448621c483b520 | [
"Swift"
] | 1 | Swift | neilcb/MyColorMarker | 8a706a5bb3d59269a3d4a1efa985caba97bc11e5 | e1ce92a8406d32b8b4250b8195a6b5bd6411b42b |
refs/heads/master | <file_sep>dia = int(input())
mes = int(input())
if ((mes == 1 and dia <21) or (mes == 12 and dia > 20)):
print("capricornio")
elif ((mes == 1 and dia >20) or (mes == 2 and dia < 21)):
print("acuario")
elif ((mes == 2 and dia >20) or (mes == 3 and dia < 21)):
print("piscis")
elif ((mes == 3 and dia > 20) or (mes == 4 and dia < 21)):
print("aries")
elif ((mes == 4 and dia >20) or (mes == 5 and dia < 21)):
print("tauro")
elif ((mes == 5 and dia >20) or (mes == 6 and dia < 21)):
print("geminis")
elif ((mes == 6 and dia > 20) or (mes == 7 and dia < 21)):
print("cancer")
elif ((mes == 7 and dia > 20) or (mes == 8 and dia < 21)):
print("leo")
elif ((mes == 8 and dia >20) or (mes == 9 and dia < 21)):
print("virgo")
elif ((mes == 9 and dia >20) or (mes == 10 and dia <21)):
print("libra")
elif ((mes == 10 and dia >20) or (mes == 11 and dia <21)):
print("escorpio")
elif ((mes == 11 and dia >20) or (mes == 12 and dia <21)):
print("sagitario") | 9cdb92e0e7fc0b4a06e72e7c2cbaffc9b15ff0d7 | [
"Python"
] | 1 | Python | CUCEI20B/actividad07-zodiaco-Denilson-Vallejo | 2f9e893a19063f58a85008742e46fe5d8357051f | 9f5bde5feefd192773a562cafee5d1ca1c727f64 |
refs/heads/main | <file_sep>import './App.css';
import Sketch from 'react-p5';
function App() {
let x, y;
const setup = (p5, canvasParentRef) => {
// use parent to render the canvas in this ref
// (without that p5 will render the canvas outside of your component)
p5.createCanvas(p5.windowWidth, p5.windowHeight).parent(canvasParentRef);
x = p5.windowWidth / 2;
y = p5.windowHeight / 2;
};
const draw = p5 => {
p5.clear();
p5.ellipse(x, y, 70, 70);
x += p5.random(-1, 1);
y += p5.random(-1, 1);
};
return (
<>
<div className="iframe-container">
<iframe
title="stream"
className="iframe"
src="https://www.youtube.com/embed/8gkxC22E-sY?controls=0&autoplay=1&mute=1"
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
></iframe>
</div>
<div className="p5-container">
<Sketch setup={setup} draw={draw} />;
</div>
</>
);
}
export default App;
| c82926a53083ba24a8b8624de61862787b719e78 | [
"JavaScript"
] | 1 | JavaScript | davidalexandercurrie/sandro-album-release | 95c3bd5481f334eba59d1e93164ee0900bb8dafe | f7e27fbb08a6cc7ab2131c65dc4365043cef6102 |
refs/heads/master | <repo_name>MarkFrankle/Discord-Python-Example<file_sep>/PrawTutorial.py
import praw
reddit = praw.Reddit(client_id = 'pfT97fO7k9D8PA',
client_secret = '<KEY>',
username = 'KingofSpaniards',
password = '<PASSWORD>',
user_agent = 'prawtutorial')
subreddit = reddit.subreddit('python')
hot_python = subreddit.hot(limit = 9)
for submission in hot_python:
if(submission.stickied == False):
print(submission.url)
# print(dir(submission))
<file_sep>/README.md
# Discord-python-Example
A barebones example Discord bot, written in Python 3.6 using the [discord.py](https://github.com/Rapptz/discord.py) library.
See also [CSSBot](https://github.com/Chris-Johnston/CSSBot), same idea just in C#.
# Installation / Setup / Usage
This project is meant for Python 3.5 and up. Please insure that you have that
Python 3.5 or higher installed. You can check this using `python --version`
or `python3 --version`.
Python 3.5 is shipped by default in the latest versions of Ubuntu.
## Prerequisitess
You'll need to install some packages first. These are included in the
`requirements.txt` file for you.
Linux:
```bash
python3 -m pip install -r requirements.txt
# only required for doing voice on Linux environments
sudo apt-get install libffi-dev python3-dev
```
See the [discord.py documentation](http://discordpy.readthedocs.io/en/rewrite/intro.html#installing)
for why the additional tools are necessary.
Windows:
```
py -3 -m pip install -r requirements.txt
```
Mac:
```
python3 -m pip install -r requirements.txt
```
## Setup
- Register your own Discord bot for testing with.
- Navigate to the Discord API docs and log in: https://discordapp.com/developers/applications/me (If you log in for the first time, it'll probably take you to the app, so go back to this link again).
- Click on the "New App" button.
- Name your app. Click "Create App".
- Click "Create a Bot User". (Discord API supports a few types of apps/bots, but we are building a bot)
- Locate your bot's user token. **Your user token must not be shared with anyone. If it is posted publicly, change it ASAP.**
- Please refer to the best practices for storing and managing connection tokens. `todo`
- Fork this repo.
- Clone your copy of this repo using `git clone https://github.com/USERNAME/CSSBot_Py.git`
- Create a new file in your CSSBot_Py directory: `config.ini`
- Populate the file with the following contents:
```ini
[Configuration]
connection_token=<KEY>
```
## Usage
Run the following command:
```bash
python3 main.py
```
The first lines should read something like:
```
using discordpy version 1.0.0a
Logged in SomeUser - 1234567890
Version 1.0.0a
```
# Contributing
This bot is intended to serve as an example. Either use this code as a reference or a base to make your own bot!
## Reference Material
Here are some resources to get you started:
https://github.com/Rapptz/discord.py
https://discordapp.com/developers/docs/intro
http://discordpy.readthedocs.io/en/rewrite/
http://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html
https://gist.github.com/MysterialPy/d78c061a4798ae81be9825468fe146be
| d918aa199acceeed8764b92e84b5bbfd0d8480de | [
"Markdown",
"Python"
] | 2 | Python | MarkFrankle/Discord-Python-Example | c526f92cec73f91923d2af759f3a5b7517ca9e0a | 03d0323733739d9113dcb514475744e5cfbd912a |
refs/heads/master | <repo_name>alanipn94/huesos<file_sep>/Axial/Cabeza/Back.cs
private void huesoFrontalButton_Click(object sender, RoutedEventArgs e)
{
hueso = (int)Hueso.HuesoFrontal;
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FF52318F");
HuesoFrontal.Background = brush;
}
private void HuesoFrontalComprobacion_Click(object sender, RoutedEventArgs e)
{
if (hueso== (int)HuesoComprobacion.HuesoFrontal)
{
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#1CB0F6");
HuesoFrontalComprobacion.Background = brush;
HuesoFrontal.Background = brush;
HuesoFrontal.Label = "HUESO FRONTAL";
HuesoFrontal.IsEnabled = false;
}
}
private void HuesoParietalsButton_Click(object sender, RoutedEventArgs e)
{
hueso = (int)Hueso.HuesoParietal;
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FF52318F");
HuesoParietal.Background = brush;
}
private void HuesoParietalComprobacion_Click(object sender, RoutedEventArgs e)
{
if (hueso == (int)HuesoComprobacion.HuesoParietal)
{
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#1CB0F6");
HuesoParietalComprobacion.Background = brush;
HuesoParietal.Background = brush;
HuesoParietal.Label = "Hueso Parietal";
HuesoParietal.IsEnabled = false;
}
}
private void HuesoEsfenoidesButton_Click(object sender, RoutedEventArgs e)
{
hueso = (int)Hueso.HuesoEsfenoides;
hueso = (int)Hueso.HuesoParietal;
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FF52318F");
HuesoEsfenoides.Background = brush;
}
private void HuesoEsfenoidesComprobacion_Click(object sender, RoutedEventArgs e)
{
if (hueso == (int)HuesoComprobacion.HuesoEsfenoides)
{
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#1CB0F6");
HuesoEsfenoidesComprobacion.Background = brush;
HuesoEsfenoides.Background = brush;
HuesoEsfenoides.Label = "Hueso Esfenoides";
HuesoEsfenoides.IsEnabled = false;
}
}
<file_sep>/enums.cs
public enum Hueso
{
ninguno,
HuesoFrontal,
HuesoParietal,
HuesoEsfenoides
}
public enum HuesoComprobacion
{
ninguno,
HuesoFrontal,
HuesoParietal,
HuesoEsfenoides
} | c4b5c0a48f47294bb72ce047fc7041f24184fe39 | [
"C#"
] | 2 | C# | alanipn94/huesos | d7e89752dcc40a7a2b529ecfca84e3c1dfe6e036 | e9f6974d73e03551d6d2197eb81cdfbe3709fb4e |
refs/heads/master | <repo_name>Yukinyaa/MSNOTI<file_sep>/README.md
MSNOTI
[github page](http://yukinyaa.github.io/MSNOTI)
<file_sep>/script.js
function toBoolean(str) {
if(str === null)
return null;
if(typeof str === 'boolean')
return str;
if (typeof str === 'undefined') {
return false;
} else if (typeof str === 'string') {
switch (str.toLowerCase()) {
case 'false':
case 'no':
case '0':
case "":
return false;
default:
return true;
}
} else if (typeof str === 'number') {
return str !== 0
}
else {return true;}
}
class FlagAlerter{
constructor(timeBefore, toggleBtn, tittle, msg)
{
this.timeBefore = timeBefore;
this.toggleBtn = toggleBtn;
this.tittle = tittle;
this.msg = msg;
this.isEnabled = toBoolean(window.localStorage.getItem("flagAlertEnabled" + this.timeBefore));
if (this.isEnabled == null)
this.isEnabled = false;
toggleBtn.checked = this.isEnabled;
this.isTrigged = false;
}
//"12/19/21시" 플래그
tick()
{
if(this.toggleBtn.checked != this.isEnabled)
{
this.isEnabled = this.toggleBtn.checked;
window.localStorage.setItem("flagAlertEnabled" + this.timeBefore, this.toggleBtn.checked);
}
if(this.isEnabled == false)
return;
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
if(m == 1)
this.isTrigged = false;
if(this.isTrigged == true)
return;
if(this.timeBefore == 0)
{
if((h == 12 || h == 19 || h== 21)&&(m==0)){}// trigger alarm.
else return;
}
else// if timeBefore > 0
{
if(h == 11 || h == 18 || h== 20 && (60-this.timeBefore == m)){}// trigger alarm
else return;
}
this.isTrigged = true;
var notification = new Notification(this.tittle, {body:this.msg});
setTimeout(function(){
notification.close();
}, 3000);
}
}
var a5 = new FlagAlerter(5, document.getElementsByClassName("5min")[0], "플래그 5분전", "플래그 레이스 5분 전입니다. 메이플은 켜져있나요?");
var a3 = new FlagAlerter(3, document.getElementsByClassName("3min")[0], "플래그 3분전", "플래그 레이스 3분 전입니다. 메이플은 켜져있나요?");
var a1 = new FlagAlerter(1, document.getElementsByClassName("1min")[0], "플래그 1분전", "플래그 레이스 1분 전입니다. 캐릭터 바꿔주세요");
var a0 = new FlagAlerter(0, document.getElementsByClassName("0min")[0], "플래그 레이스", "플래그 레이스 시작합니다.");
function showTime(){
var date = new Date();
var h = date.getHours(); // 0 - 23
var m = date.getMinutes(); // 0 - 59
var s = date.getSeconds(); // 0 - 59
var session = "AM";
var isDarkMode
if((m == 45 || m == 15) && s == 0)
{
document.body.style.backgroundColor = "pink";
tick.play();
}
else if( (m == 29 || m == 59) && s > 30 )
{
cp == false;
if(s % 2 == 0)
{
tick.play();
document.body.style.backgroundColor = "pink";
}
else
{
document.body.style.backgroundColor = "#121212";
}
}
else if(m == 30 && m == 60 )
{
if(cp == false)
alertSound.play();
cp == true;
document.body.style.backgroundColor = "red";
}
else
document.body.style.backgroundColor = "#121212";
if(h == 0){
h = 12;
}
if(h > 12){
h = h - 12;
session = "PM";
}
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
var time = h + ":" + m + ":" + s + " " + session;
document.getElementById("MyClockDisplay").innerText = time;
document.getElementById("MyClockDisplay").textContent = time;
a5.tick();
a3.tick();
a1.tick();
a0.tick();
setTimeout(showTime, 500);
}
var cp = false;
var ccp = false;
var alertSound = new Audio('alert.mp3');
var tick = new Audio('tick.mp3');
Notification.requestPermission(function (result) {
if(result == 'denied') {
alert('알림이 차단되어 있습니다.\n플래그 알림이 작동하지 않습니다.\n브라우저의 사이트 설정에서 변경하실 수 있습니다.');
return false;
}
});
| 025b4da61d32dc356c9da3e9eb0ddfc4060203b4 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Yukinyaa/MSNOTI | 192c9b9b74a94bce244b22d66a444d340a964edf | 765ca5769a08d5d1e4b3d1e68d9006c4d7d730d8 |
refs/heads/master | <file_sep># Make dictionary containing my:
## Name
## Age
## Country of birth
## Favorite language
about_me = {
'name': 'chris',
'age': '22',
'country of origin': 'USA',
'favorite language': 'Python'
}
# print about_me['name']
def reading_dictionaries():
for key, value in about_me.iteritems():
print "My " + key + " is " + value + "."
reading_dictionaries()
<file_sep># Odd/Even:
def odd_even():
for x in range(1, 2001):
if x % 2 != 0:
print "Number is " + str(x) + ". This is an odd number."
else:
print "Number is " + str(x) + ". This is an even number."
odd_even()
#-------------------------
# Multiply:
a = [2,4,10,16]
def multiply(l, num):
new_list = []
for x in l:
new_list.append(x * num)
return new_list
print multiply(a, 5)
#-------------------------
# Hacker Challenge:
def layered_multiples(arr):
new_array = []
for y in arr:
new_array2 = []
count = 0
while count < y:
new_array2.append(1)
count +=1
new_array.append(new_array2)
return new_array
test = layered_multiples(multiply([2,4,5],3))
print test<file_sep># Multiples
## Part I
for number in range(1, 1001):
print number
## Part II
for five in range(1, 1000001):
if five % 5 == 0:
print five
else:
continue
#-------------------------
# Sum List
a = [1, 2, 5, 10, 255, 3]
list_sum = sum(a)
print list_sum
#-------------------------
# Average List
list_avg = list_sum/len(a)
print list_avg<file_sep>import numpy as np
print a = np.arange(15).reshape(3, 5)
print a
print a.shape
print a.ndim
print a.dtype.name
print a.itemsize
print a.size
print type(a)
print b = np.array([6, 7, 8])
print b
print type(b)<file_sep>l = ['magical unicorns',19,'hello',98.98,'world']
def type_list(lst):
running_sum = 0
running_string = ""
for x in lst:
if isinstance(x, str):
running_string += x
running_string += " "
elif isinstance(x, int):
running_sum += x
elif isinstance(x, float):
running_sum += x
print "Sum: " + str(running_sum)
print "Your complete string is: " + running_string
type_list(l)
<file_sep>def multiplication_table():
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
row = "x "
for item in x:
row += "{} ".format(item)
print row
for i in range(1, 13):
row = [y*i for y in range(1, len(x)+1)]
sub = ""
for item in row:
sub += "{} ".format(item)
print sub
multiplication_table()<file_sep>from flask import Flask, render_template, redirect, request, session, flash
app = Flask(__name__)
app.secret_key = "dojo"
@app.route('/')
def index():
if 'num_refreshed' in session.keys():
session['num_refreshed'] +=1
else:
session['num_refreshed'] = 1
return render_template('index.html')
@app.route('/process', methods=['POST'])
def keeping_track():
return redirect('/')
app.run(debug=True)<file_sep># Part I
# def draw_stars(num_list):
# for number in num_list:
# count = 0
# empty_str = ""
# while count < number:
# empty_str += "*"
# count +=1
# print empty_str
y = [4, 6, 1, 3, 5, 7, 25]
# draw_stars(x)
# ------------------------------
# Part II
def draw_stars(the_list):
for item in the_list:
if isinstance(item, int):
count = 0
empty_str = ""
while count < item:
empty_str += "*"
count +=1
print empty_str
elif isinstance(item, str):
count = 0
empty_str = ""
while count < len(item):
empty_str += item[:1].lower()
count +=1
print empty_str
x = [4, "Tom", 1, "Michael", 5, 7, "<NAME>"]
draw_stars(y)
draw_stars(x)<file_sep># Find and Replace
words = "It's thanksgiving day. It's my birthday,too!"
words_list = words.split()
words_index = words_list.index("day.")
print words_index
words_list[words_index] = "month."
print " ".join(words_list)
#--------------------
# Min and Max
x = [2,54,-2,7,12,98]
print min(x)
print max(x)
#--------------------
# First and Last
x = ["hello",2,54,-2,7,12,98,"world"]
print x[0]
print x[-1]
y = []
y.append(x[0])
y.append(x[-1])
print y
#---------------------
# New List
x_2 = [19,2,54,-2,7,12,98,32,10,-3,6]
x_2.sort()
y_first_half = []
y_second_half = []
count = 0
half_list_index = len(x_2)/2
for item in x_2:
if count < half_list_index:
y_first_half.append(item)
count +=1
else:
y_second_half.append(item)
count +=1
y_first_half.append(y_second_half)
print y_first_half<file_sep>import numpy as np
a = np.arange(15).reshape(3, 5)
a
a.shape
a.ndim
a.dtype.name
a.itemsize
a.size
type(a)
b = np.array([6, 7, 8])
b
type(b)<file_sep>def checkerboard():
count = 0
while count < 8:
if count % 2 == 0:
print "* * * * "
count +=1
else:
print " * * * *"
count +=1
checkerboard() <file_sep># Chris_Marr
<NAME>'s Coding Dojo Python Assignments
<file_sep>print "---Part I---"
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'}
]
def names():
for dicts in students:
print dicts['first_name'] + ' ' + dicts['last_name']
names()
print "---Part II---"
#-----------------------------------------------
# Part II:
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'}
]
}
def names_part_2(dictionary):
for lists in dictionary:
print lists
count = 0
for people in dictionary[lists]:
count +=1
temp = people['first_name'] + ' ' + people['last_name']
temp = temp + ' ' + str(len(temp)-1)
print str(count) + ' - ' + temp
names_part_2(users)
<file_sep>import random
def scores_and_grades():
print "Scores and Grades:"
count = 1
while count <= 10:
random_num = random.randint(60, 100)
if random_num <= 69:
print "Score: " + str(random_num) + "; Your grade is a D."
elif random_num <= 79:
print "Score: " + str(random_num) + "; Your grade is a C."
elif random_num <= 89:
print "Score: " + str(random_num) + "; Your grade is a B."
elif random_num <= 100:
print "Score: " + str(random_num) + "; Your grade is an A."
count +=1
print "End of the program. Bye!"
scores_and_grades()<file_sep>from flask import Flask, render_template, redirect, request, session
app = Flask(__name__)
app.secret_key = 'asdf'
@app.route('/')
def index():
return render_template('index.html', are_they_here="No ninjas here.")
@app.route('/ninjas')
def ninjas():
return render_template('ninjas.html')
@app.route('/ninjas/orange')
def orange():
return render_template('orange.html')
r
@app.route('/ninjas/red')
def red():
return render_template('red.html')
@app.route('/ninjas/purple')
def purple():
return render_template('purple.html')
@app.route('/ninjas/blue')
def blue():
return render_template('blue.html')
app.run(debug=True)<file_sep>def find_characters(list, character):
new_list = []
for x in list:
if character in x:
new_list.append(x)
else:
continue
print new_list
word_list = ['hello','world','my','name','is','Anna']
find_characters(word_list, "o")<file_sep>def foo_bar():
for num in range(100, 10001):
while num <= 100000:
for i in range(2,num):
if num % i == 0:
print "Foo"
# break
else:
print "FooBar"
low = 0
high = num // 2
root = high
while root * root != num:
root = (low + high) // 2
if low + 1 >= high:
print "FooBar"
if root * root > num:
high = root
else:
low = root
print "Bar"
foo_bar() | cdb845368db08e3361de9e893c8702a0b9f65cd6 | [
"Markdown",
"Python"
] | 17 | Python | cmarr31/Chris_Marr | feaea1afbaf1e7a38d44c790f17f0c9b3ed7762b | a0ce9b6e31212882463510c928fe6ad517ea6093 |
refs/heads/master | <file_sep>package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.apache.logging.log4j.*;
public class VehicleVerificationPage extends AbstractWebPage {
private static final Logger LOG = LogManager.getLogger(VehicleVerificationPage.class);
// @FindBy(css =".selection-button-radio[for='Correct_True'] input")
@FindBy(css ="#Correct_True")
private WebElement radioButtonYes;
// @FindBy(css =".selection-button-radio[for='Correct_False'] input")
@FindBy(css ="#Correct_False")
private WebElement radioButtonNo;
@FindBy(css =".button[name='Continue']")
private WebElement continueButton;
public VehicleVerificationPage(WebDriver webDriver) {
super(webDriver);
}
public VehicleDetailsPage confirmDetails(){
radioButtonYes.click();
continueButton.click();
return createPage(VehicleDetailsPage.class);
}
}
<file_sep>package utilities;
import com.monitorjbl.xlsx.StreamingReader;
import model.Vehicle;
import org.apache.poi.ss.usermodel.*;
import DirectoryScan.GetFileList;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.*;
public class VehicleDataFromExcel extends LoadConfigClass{
static Properties CON = null;
static Path Directory;
static InputStream is = null;
static Map<String, List<String>> vehicleData;
public static Map<String, List<String>> getData() throws IOException
{
CON = new Properties();
FileInputStream fs1 = LoadConfigClass.configfile((FileInputStream fs) -> fs); ;
CON.load(fs1);
Directory= Paths.get(System.getProperty("user.dir")+"//src//"+CON.getProperty("Directory"));
Path dataFile = GetFileList.getDataFileUri(Directory);
vehicleData = new HashMap<String, List<String>>();
is = (is == null) ? new FileInputStream(new File(dataFile.toUri())) : is;
Workbook workbook = StreamingReader.builder().rowCacheSize(100).bufferSize(4096).open(is);
Sheet sheet = workbook.sheetIterator().next();
Iterator rows = sheet.rowIterator();
rows.next();
while (rows.hasNext())
{
Row row = (Row) rows.next();
List<String> vehicleAttributes = new ArrayList<String>();
Iterator cells = row.cellIterator();
String regNumber = ((Cell) cells.next()).getStringCellValue();
if (regNumber.isEmpty())
{
break;
}
while (cells.hasNext()) {
Cell cell = (Cell) cells.next();
vehicleAttributes.add(cell.getStringCellValue());
}
vehicleData.put(regNumber, vehicleAttributes);
}
return vehicleData;
}
public static Vehicle getExpectedVehicleData(String vehicleRegistration) throws IOException {
Vehicle v = new Vehicle();
List<String> details = VehicleDataFromExcel.getData().get(vehicleRegistration);
v.setVehicle_Registration(vehicleRegistration);
v.setVehicle_make(details.get(0));
v.setDate_of_first_registration(details.get(1));
v.setYear_of_manufacture(details.get(2));
v.setCylinder_capacity(details.get(3));
v.setCO2Emissions(details.get(4));
v.setFuel_type(details.get(5));
v.setExport_marker(details.get(6));
v.setVehicle_status(details.get(7));
v.setVehicle_colour(details.get(8));
v.setVehicle_type_approval(details.get(9));
v.setWheelplan(details.get(10));
v.setRevenue_weight(details.get(11));
return v;
}
public static Vehicle getExpectedVehicleData1(Map<String,List<String>> excelData,String vehicleRegistration) throws IOException {
Vehicle v = new Vehicle();
List<String> details = excelData.get(vehicleRegistration);
v.setVehicle_Registration(vehicleRegistration);
v.setVehicle_make(details.get(0));
v.setDate_of_first_registration(details.get(1));
v.setYear_of_manufacture(details.get(2));
v.setCylinder_capacity(details.get(3));
v.setCO2Emissions(details.get(4));
v.setFuel_type(details.get(5));
v.setExport_marker(details.get(6));
v.setVehicle_status(details.get(7));
v.setVehicle_colour(details.get(8));
v.setVehicle_type_approval(details.get(9));
v.setWheelplan(details.get(10));
v.setRevenue_weight(details.get(11));
return v;
}
}
<file_sep>Directory = DirectoryForScanning
DVLA_URL = https://www.gov.uk/get-vehicle-information-from-dvla
<file_sep># VehicleRegCheck_PageObjectModel
#The Main project consists of a service to retreive
files and their mime type, extension, size
#/src/main/java/DirectoryScan/GetFileList.java
#The Directory for testing is kept in /src named #DirectoryForScanning and contains some files to test #the service.
# The name of the directory can be provided in the
# config.properties as below and the code is configured to pickup as long as the directory is under the src folder
# Directory = DirectoryForScanning
# The second part of the project contains cucumber feature files that are used to test the file scanning process and retreive an excel file named "VechicleRegList"
# The excel file contains Vehicle registration details,, the cucumber feature files are used to
# get the details of each vehicle registration from the excel file and verify the details are #matched with the vehicle details held in the DVLA information service.
<file_sep>package StepDefinitions;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.Given;
import DirectoryScan.*;
import org.junit.Assert;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
public class FileListScanSteps {
public Path Directory1;
Map<String, List<String>> fileData;
@Given("^I run the filelistScan on a \"(.*?)\"$")
public void i_run_the_filelistScan_on_a(String Directory) throws IOException {
Directory1 = Paths.get(System.getProperty("user.dir") + "//src//"+Directory);
fileData = GetFileList.getFilenameAndDetails(Directory1);
}
@Then("^I should see a list of files$")
public void i_should_see_a_list_of_files() {
System.out.println(fileData);
// Can write Assertions to verify the files names returned.
}
@And("^I should be able to filter only excel files$")
public void i_should_be_able_to_filter_only_excel_files() throws IOException {
Path file = GetFileList.getDataFileUri(Directory1);
Assert.assertEquals("verify excel sheet is returned","xlsx",GetFileList.getFileExtension(file));
}
}
<file_sep>package utilities;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
@FunctionalInterface
public interface LoadConfig {
FileInputStream getConfig(FileInputStream fs) throws IOException;
}
<file_sep>package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import StepDefinitions.*;
public class MainPage extends AbstractWebPage {
private static final Logger LOG = LoggerFactory.getLogger(MainPage.class);
//@FindBy(css = ".button:contains('Start now')")
@FindBy(linkText = "Start now")
private WebElement startNowButton;
public MainPage(WebDriver webDriver) {
super(webDriver);
}
public VehicleEnquiryPage clickOnStartNowButton(){
startNowButton.click();
return createPage(VehicleEnquiryPage.class); }
}
| a66171c48fe91b60e54e4b2f79f224e878a5f20a | [
"Markdown",
"Java",
"INI"
] | 7 | Java | devadathpt/VehicleRegCheck_PageObjectModel | 009904ade820682725e94d50b9dde2a383e3bb92 | d0e425605c13bd2b4896bd53816335f6e658c6ff |
refs/heads/master | <file_sep>from django.shortcuts import render,redirect
from django.contrib.auth.models import User
# Create your views here.
def register(request):
if request.method=='POST':
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
user=User.objects.create_user(first_name=first_name,
last_name=last_name,
username=username,
email=email,
password=<PASSWORD>,
)
user.save()
return redirect('/')
else:
return render(request,'registrationapp/home.html')
def logout(request):
pass
def login(request):
pass
| 6bed0c9fe23dd4f34f3f387f161a008437c7364f | [
"Python"
] | 1 | Python | okmar2050/repo2 | 3e0ef7ca43a798e16a9fc1d00d00bb78d713f510 | 47e78e5ae9f804b30989267a481c61ff0d75722a |
refs/heads/main | <file_sep>
func countSort(_ array: [Int]) -> [Int] {
guard array.count > 0 else {
return array
}
let maxElement = array.max() ?? 0
var countArray = [Int](repeating: 0, count: Int(maxElement + 1))
for element in array {
countArray[element] += 1
}
for index in 1 ..< countArray.count {
let sum = countArray[index] + countArray[index - 1]
countArray[index] = sum
}
var sortedArray = [Int](repeating: 0, count: array.count)
for index in stride(from: array.count - 1, through: 0, by: -1) {
let element = array[index]
countArray[element] -= 1
sortedArray[countArray[element]] = element
}
return sortedArray
}
let list1 = [5, 2, 1, 6, 4, 3]
print(countSort(list1))<file_sep>func insertionSort<T: Comparable>(_ list: inout [T], start: Int, gap: Int) {
for i in stride(from: (start + gap), to: list.count, by: gap) {
let currentValue = list[i]
var pos = i
while pos >= gap && list[pos - gap] > currentValue {
list[pos] = list[pos - gap]
pos -= gap
}
list[pos] = currentValue
}
}
func shellSort<T: Comparable>(_ list: inout [T]) {
var sublistCount = list.count / 2
while sublistCount > 0 {
for pos in 0..<sublistCount {
insertionSort(&list, start: pos, gap: sublistCount)
}
sublistCount = sublistCount / 2
}
}
var list1 = ["f", "e", "d", "b", "a", "c"]
shellSort(&list1)
print(list1)
var list2 = [5, 2, 1, 6, 4, -1, 3]
shellSort(&list2)
print(list2)<file_sep>#include<iostream>
#include<memory>
using namespace std;
class foo
{
int x;
public:
foo(int x):x(x)
{}
int getx()
{return x;}
~foo()
{
cout<<"DESTRUCT"<<endl;
}
};
int main()
{
// foo *f=new foo(35); // the problem is that we forgot to destroy the DMA block, hence it leads to memory leak.
// cout<<f->getx()<<endl; // Using delete will be necessary in this but as we can't always remember to do so. SO WE USE UNIQUE POINTER.
// delete f;
// Another Method shared_ptr<foo> sp(new foo(35));
shared_ptr<foo> sp = make_shared<foo>(35); // The advantages of shared pointer is that it will destroy the memory block it is pointing to when the
cout<<sp->getx()<<endl; // last remaining shared_ptr (pointing to object) will get destroyed, and obviously when object is gonna destroyed, the destructor will be called.
shared_ptr<foo> sp1=sp;
shared_ptr<foo> sp2=sp; // &sp2=sp; AND *sp2=&sp; will not work.
cout<<sp.use_count()<<endl;
shared_ptr<foo> sp3=sp;
cout<<sp3.use_count()<<endl; //Destructor will run only once regardless of how many shared_ptrs are pointing to the object.
} // It is a smart pointer with reference-count copy semantics..
// Actually, in shared_ptr : we have two things 1)First is your object(memory block) you created called Managed object.
// 2) Second One is called Control block, which come in act when we assign the VALUE of one shared_ptr to other, it increases
// the reference count with the same.
<file_sep>func fibonacci(_ n: Int, _ a:Int=0, _ b:Int=1) -> Int{
if n==0 { return a }
if n==1 { return b }
return fibonacci(n-1, b, a+b)
}
for i in 0...12 {
print(fibonacci(i))
}
<file_sep>
func factorial(_ n: Int, _ a: Int=1) -> Int {
if n==0 { return 1 }
if n==1 { return a }
return factorial(n-1, n*a)
}
func combinations(n: Int, r: Int) -> Int {
return factorial(n)/(factorial(r)*factorial(n-r))
}
func permutations(n: Int, r: Int) -> Int {
return factorial(n)/factorial(n-r)
}
print(factorial(10))
print(combinations(n: 8, r: 4))
print(permutations(n: 8, r: 4))
<file_sep>func insertionSort<T: Comparable>(_ array: [T]) -> [T] {
var sortedArray = array
for index in 1..<sortedArray.count {
var currentIndex = index
let temp = sortedArray[currentIndex]
while currentIndex > 0 && temp < sortedArray[currentIndex - 1] {
sortedArray[currentIndex] = sortedArray[currentIndex - 1]
currentIndex -= 1
}
sortedArray[currentIndex] = temp
}
return sortedArray
}
let list1 = ["f", "e", "d", "b", "a", "c"]
print(insertionSort(list1))
let list2 = [5, 2, 1, 6, 4, 3]
print(insertionSort(list2))<file_sep>#include<iostream>
#include<memory> // Header file having declaration of the unique pointer
using namespace std;
class foo
{
int x;
public:
explicit foo(int x):x(x)
{}
int getx()
{
return x;
}
~foo()
{
cout<<"Foo Dest"<<endl;
}
};
int main()
{
// foo *f=new foo(10); // the problem is that we forgot to destroy the DMA block, hence it leads to memory leak.
// cout<<f->getx()<<endl; // Using delete will be necessary in this but as we can't always remember to do so. SO WE USE UNIQUE POINTER.
// delete f;
unique_ptr<foo> p (new foo(40)); // NO EXCEPTION SAFETY
// unique_ptr<foo> p1 = make_unique<foo>(40); (should use make_unique(exception safe))
cout<<p->getx()<<endl; // The advantages of unique pointer is that it will destroy the memory block it is pointing to when it
return 0; // itself will be destroyed, and obviously when object is gonna destroyed, the destructor will be called.
// We can't copy that address to any pointer to which unique pointer is pointing. Only unique pointer
// has ownership for that DMA block, but we can make a pointer to pointer to that to access that memory block.
// IMP ----- We can move the ownership of the unique_ptr to another one(unique_ptr) by using move()
/* unique_ptr<foo> p1 = move(p); Here the ownership has been moved from "p" to "p1", now p points to that object(having the ownership) and p points null now.
// IMP ------ We can release the ownership of the unique_ptr and can make it point by a normal (class)pointer by using release().
foo *p2 = p1.release()
// IMP ------ We can swap the managed objects of the unique_ptr(s) by using swap() function.
unique_ptr<foo> p3 = swap(p1);
// IMP ------ We can reset the unique_ptr by using reset() function.
p4.reset(p2) HERE 'p2' SHOULD BE A NORMAL (CLASS) POINTER. (Considering that 'p4' is pointing to a managed object(having ownership))
Hence, Now the p4 will point to what p2 is pointing, and that previous managed object which was pointed by p4 will get deleted.
*/
}
<file_sep>#include <bits/stdc++.h>
using namespace std;
// Function to efficiently find out three elements whose sum is equal to a given sum
// Time complexity : O(n2)
vector< vector<int> > triplets(vector <int> arr, int Sum)
{
vector < vector<int> > res;
int n = arr.size();
for (int i = 0; i <= n-3; ++i)
{
int j = i+1;
int k = n-1;
while(j < k)
{
int currsum = arr[i] + arr[j] + arr[k];
if(currsum == Sum){
res.push_back({arr[i] , arr[j] , arr[k]});
j++;
k--;
}
else if(currsum > Sum)
k--;
else
j++;
}
}
return res;
}
int main()
{
// Example
vector <int> v = {1,2,3,4,5,6,7,8,9,15};
int Sum = 32;
auto p = triplets(v,Sum);
if(p.size()==0)
cout << "No pair found" ;
else
{
for (auto triplet : p)
{
// Outputting all valid triplet sets
for(auto ans : triplet)
cout << ans << " ";
cout << endl;
}
}
}
| 9701634e5f2e9fa4d9699787da0f8e34c0af7e30 | [
"Swift",
"C++"
] | 8 | Swift | mastermanav09/Hacktoberfest21_Algo_Collection | 1f69e28d9082c0d5607c6145aeb6feb44264289f | b2000592b0bad371494f9d8202eebb5ff487bac3 |
refs/heads/master | <repo_name>HaynesStephens/year1project<file_sep>/venv/lib/python3.6/site-packages/mplkit/cmap.py
import matplotlib
from matplotlib.colors import Colormap, LinearSegmentedColormap, ListedColormap
import numpy as np
class WrappedColormap(Colormap):
"""
`WrappedColormap` wraps around an instance of `matplotlib.colors.Colormap`,
provides the `luma` method, but otherwise does nothing to the colormap.
"""
def __init__(self, cmap, *args, **kwargs):
assert(isinstance(cmap, Colormap))
self.cmap = cmap
self.init(*args,**kwargs)
def init(*args,**kwargs):
pass
def __call__(self, X, alpha=None, bytes=False):
return self.cmap(X, alpha=alpha, bytes=bytes)
def set_bad(self, color='k', alpha=None):
self.cmap.set_bad(color=color, alpha=alpha)
def set_under(self, color='k', alpha=None):
self.cmap.set_under(color=color, alpha=alpha)
def set_over(self, color='k', alpha=None):
self.cmap.set_over(color=color, alpha=alpha)
def _set_extremes(self):
self.cmap._set_extremes()
def _init(self):
"""Generate the lookup table, self._lut"""
return self.cmap._init()
def is_gray(self):
return self.cmap.is_gray()
def __getattr__(self, key):
return getattr(self.cmap,key)
def luma(self, X, alpha=None, bytes=False):
color = self(X, alpha=alpha, bytes=bytes)
def get_luma(c):
return np.average(c,axis=-1,weights=[0.299,0.587,0.114,0])
return get_luma(color)
class ReversedColormap(WrappedColormap):
'Reverses the color map.'
def __call__(self, X, alpha=None, bytes=False):
return self.cmap(1-X, alpha=alpha, bytes=bytes)
class InvertedColormap(WrappedColormap):
'Inverts the color map according to (R,G,B,A) - > (1-R,1-G,1-B,A).'
def __call__(self, X, alpha=None, bytes=False):
color = self.cmap(X, alpha=alpha, bytes=bytes)
def invert(c):
c = map(lambda x: 1-x, c)
c[-1] = 1
return tuple(c)
if isinstance(X, (np.ndarray,) ):
color = 1 - color
color[...,-1] = 1
return color
else:
return invert(color)
class DesaturatedColormap(WrappedColormap):
'Constructs a new colormap that preserves only the luma; or "brightess".'
def __call__(self, X, alpha=None, bytes=False):
color = self.cmap(X, alpha=alpha, bytes=bytes)
def get_luma(c):
return np.average(c,axis=-1,weights=[0.299,0.587,0.114,0])
r = np.kron(get_luma(color),[1,1,1,1]).reshape(np.shape(X)+(4,))
r[...,-1] = 1
return r
class ConcatenatedColormap(WrappedColormap):
"""
`ConcatenatedColormap` wraps around an instances of `matplotlib.colors.Colormap`,
and when used as a colour map returns the result of concatenating linearly the
maps. Should be initialised as:
ConcatenatedColormap(<cmap1>,0.2,<cmap2>,...)
Where the numbers indicate where the cmaps are joined. The 0 at the beginning and the 1
at the end are inferred.
"""
def init(self,*args):
self.cmaps = [self.cmap]
self.cmap_joins = []
assert(len(args) % 2 == 0)
for i in xrange(0,len(args),2):
self.cmap_joins.append(float(args[i]))
assert(args[i] < 1 and args[i] > 0 and (i==0 or args[i] > self.cmap_joins[-2]))
assert(isinstance(args[i+1],Colormap))
self.cmaps.append(args[i+1])
def __call__(self, X, alpha=None, bytes=False):
def get_color(v):
min = 0
max = 1
cmap_index = np.sum(np.array(self.cmap_joins) < v)
assert (cmap_index <= len(self.cmaps))
if (cmap_index > 0):
min = self.cmap_joins[cmap_index-1]
if (cmap_index < len(self.cmaps)-1):
max = self.cmap_joins[cmap_index]
scaled_v = (v-min)/(max-min)
return tuple(self.cmaps[cmap_index](scaled_v,alpha=alpha,bytes=bytes))
if isinstance(X,np.ndarray):
vfunc = np.vectorize(get_color,otypes=["float","float","float", "float"])
return np.rollaxis(np.array(vfunc(X)),0,len(X.shape)+1)
else:
return get_color(X)
def set_bad(self, color='k', alpha=None):
pass#self.cmap.set_bad(color=color, alpha=alpha)
def set_under(self, color='k', alpha=None):
pass#self.cmap.set_under(color=color, alpha=alpha)
def set_over(self, color='k', alpha=None):
pass#self.cmap.set_over(color=color, alpha=alpha)
def _set_extremes(self):
pass#self.cmap._set_extremes()
def _init(self):
"""Generate the lookup table, self._lut"""
for cm in self.cmaps:
cm._init()
def is_gray(self):
return np.all([cm.is_gray() for cm in self.cmaps])
def __getattr__(self, key):
return getattr(self.cmap,key)
def luma(self, X, alpha=None, bytes=False):
color = self(X, alpha=alpha, bytes=bytes)
def get_luma(c):
return np.average(c,axis=-1,weights=[0.299,0.587,0.114,0])
return get_luma(color)
<file_sep>/rocke_ss.py
# From <NAME>'s Original ROCKE_SS.py script
# encoding: utf-8
# SCRIPT TO GENERATE TIME SERIES OF GLOBALLY AVERAGED ROCKE-3D DATA
# User must specify runid and may need to modify the calendar settings.
import numpy as np
import os
import subprocess
from netCDF4 import Dataset
import pandas as pd
from glob import glob
## ***SPECIFY EXPERIMENT & ITS LOCATION ON MIDWAY***
runid = 'pc_proxcenb_ssc5L_TL_39p'
rundirectory = '/project2/abbot/haynes/ROCKE3D_output/' + runid
endyear_dict = {'0p':3500, '1p':4140, '4p':3549, '6p':4179,
'11p':4379, '22p':3729, '26p':3649, '34p':2769, '39p':2649}
endyear = endyear_dict['39p']
startyear = endyear - 99
# startyear = ####
## ***DEFINE TIME INTERVAL***
# NOTE: Change year_list for runs < 1 year.
# year_list = [1960, 1999]
year_list = range(startyear, endyear, 10)
# PREPARE THE DATA FOR ANALYSIS (use GISS'scaleacc' diagnostic tool)
os.chdir(rundirectory) # Switch on over to the run directory.
file_start = 'ANM'
for y in year_list:
beg_dec = str(y)
end_dec = str(y + 9)
accfilename = file_start + beg_dec + '-' + end_dec + '.acc' + runid + '.nc'
print(accfilename)
ext_list = ['aijk', 'aijl', 'aij', 'icij', 'oijl', 'oij']
tot_list = ['aj', 'areg', 'consrv', 'ajl', 'agc', 'aij', 'aijmm', 'aijl', 'aijk', 'adiurn', 'hdiurn'
'ijhc', 'oij', 'oijmm', 'oijl', 'olnst', 'ojl', 'otj, icij']
for ext in ext_list:
subprocess.call(["scaleacc", accfilename, ext])
# subprocess.call(["scaleacc", accfilename, 'aij']) # convert atmospheric output
# subprocess.call(["scaleacc", accfilename, 'oij']) #convert oceananic output
# subprocess.call(["scaleacc", accfilename, 'oijl']) # convert oceananic output
''' NOT TRYING TO REPRODUCE ALL DATA AGAIN THIS TIME
# First, determine array size
total_decs = len(year_list)
# Create output arrays
global_rad = np.zeros((total_decs, 1)) # net radiation
global_ave_temp = np.zeros((total_decs, 1)) # temperature
global_snow_ice_cover = np.zeros((total_decs, 1))
global_ice_thickness = np.zeros((total_decs, 1))
# IMPORT THE DATA!
i = 0 # start the calendar counter
for y in year_list:
beg_dec = str(y)
end_dec = str(y + 9)
aijfilename = file_start + beg_dec + '-' + end_dec + '.aij' + runid + '.nc'
oijfilename = file_start + beg_dec + '-' + end_dec + '.oij' + runid + '.nc'
oijlfilename = file_start + beg_dec + '-' + end_dec + '.oijl' + runid + '.nc'
# READ THE NETCDF FILES
atm_data = Dataset(aijfilename)
ocn_data=Dataset(oijfilename)
ocnl_data = Dataset(oijlfilename)
# GET AREAS -- this could probably be moved outside of the for loop... but, is necessary for
grid_cell_area = atm_data['axyp'][:] # Area of each grid cell (m^2)
planet_area = sum(sum(grid_cell_area)) # Surface area of planet (m^2)
# NET RADIATION
net_rad = atm_data['net_rad_planet'][:] # Spatially resolved net radiation (W/m^2) from netcdf
tot_rad = sum(sum(net_rad * grid_cell_area)) # Total global radiation (W)
tot_rad = tot_rad / planet_area # Spread across planet's surface
global_rad[i] = tot_rad # Record globally averaged net radiation
# SURFACE TEMPERATURE
surf_temp = atm_data['tsurf'][:] # Spatially resolved surface temperature (C)
surf_temp_aw = sum(
sum((surf_temp * grid_cell_area))) / planet_area # Area weighted global average surface temp.
global_ave_temp[i] = surf_temp_aw # Record the global average
# SNOW AND ICE COVERAGE
snow_ice_cover = atm_data['snowicefr'][:] # Spatially resolved snow/ice coverage (%)
snow_ice_area = sum(sum((snow_ice_cover * grid_cell_area))) # Snow and ice area (m2)
global_snow_ice_cover[i] = snow_ice_area / planet_area # Global snow and ice coverage (%)
# SEA ICE THICKNESS
sea_ice_thickness = atm_data['ZSI'][:] # Spatially resolved sea ice thickness (m)
sea_ice_thickness[sea_ice_thickness.mask] = 0
ocnfr = atm_data['ocnfr'][:]
ocean_area = (ocnfr / 100) * grid_cell_area
total_thickness = np.sum(sea_ice_thickness * ocean_area)
sea_ice_thickness_aw = total_thickness / np.sum(ocean_area)
global_ice_thickness[i] = sea_ice_thickness_aw
i = i + 1 # advance the calendar counter.
# PRINT FINAL VALUE
# print 'The global net radiative is: '+ global_rad[-1] +' W/m^2'
# print 'The global average temperature is: '+ global_ave_temp[-1]+ ' C'
# print 'Snow and ice cover '+ glocal_snow_ice_cover[-1]+ '% of the globe'
# SAVE DATA TO FILE:
np.savetxt('radiation_ts.txt', global_rad)
np.savetxt('temperature_ts.txt', global_ave_temp)
np.savetxt('snow_ice_ts.txt', global_snow_ice_cover)
np.savetxt('ice_thickness_ts.txt', global_ice_thickness)
a_df = pd.DataFrame({'decade': np.arange(total_decs), 'radiation': global_rad.reshape(total_decs),
'temperature': global_ave_temp.reshape(total_decs),
'snow_ice_cover': global_snow_ice_cover.reshape(total_decs),
'ice_thickness': global_ice_thickness.reshape(total_decs)})
a_df.to_csv('a_ts_data.csv')
'''
''' DONT NEED TO DELETE, NEED TO FIGURE OUT HOW TO SEPARATE OIJ AND OIJL FIRST
## Delete all but the last 10 aij files to use in the matrix map plots.
aij_list = sorted(glob('*aij*')) # Get a list of all the aij files made.
for aij_file in aij_list[:-10]: # Cycle through a list of all but the last 10 aij files.
os.system('rm {0}'.format(aij_file)) # Delete the aij file.
## Delete all but the last 10 oij files to use in the matrix map plots.
oij_list = sorted(glob('*oij*')) # Get a list of all the oij files made.
for oij_file in oij_list[:-10]: # Cycle through a list of all but the last 10 oij files.
os.system('rm {0}'.format(oij_file)) # Delete the oij file.
## Delete all but the last 10 oijl files to use in the matrix map plots.
oijl_list = sorted(glob('*oijl*')) # Get a list of all the oijl files made.
for oij_file in oijl_list[:-10]: # Cycle through a list of all but the last 10 oijl files.
os.system('rm {0}'.format(oijl_file)) # Delete the oijl file.
'''
<file_sep>/plot_scripts/lewisPlot.py
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from files_n_vars import *
import latLonAvgPlot as llap
import globalValPlot as gvp
def loadCSV(filename):
df = pd.read_csv('lewis_data/'+filename, header=None)
return np.array(df)
def correctLon(arr):
x = arr.copy()
x[:, 0][x[:, 0] > 180] = x[:, 0][x[:, 0] > 180] - 360
x = x[x[:,0].argsort()]
return x
def correctT(arr):
x = arr.copy()
x[:, 1] = x[:, 1] - 273.15
return x
def correctAndPlot(arr, ax, label):
x = arr.copy()
x = correctLon(x)
x = correctT(x)
ax.plot(x[:,0], x[:,1], label=label, linestyle='-.')
def plotLonTsurf():
tsurf_aqua = loadCSV('LewisLonTsurfAqua.csv')
tsurf_b2 = loadCSV('LewisLonTsurfB2.csv')
tsurf_b7 = loadCSV('LewisLonTsurfB7.csv')
col_list = [col_0, col_6, col_34]
row = row_tsurf
fig, ax = plt.subplots()
llap.makeSubplot(col_list, ax, row, filetype='aijpc', avg_coord='lon')
correctAndPlot(tsurf_aqua, ax, label="Aqua_L")
correctAndPlot(tsurf_b2, ax, label='7% L')
correctAndPlot(tsurf_b7, ax, label='34% L')
ax.legend()
fig.tight_layout(w_pad=2.25)
file_name = 'plots/lewis_lon_tsurf'
# plt.savefig(file_name+'.svg')
plt.savefig(file_name + '.pdf')
plt.show()
def getPlotName(var, side):
if side == 'Global':
side_ext = 'global'
elif side == 'Day Side':
side_ext = 'side_day'
elif side == 'Night Side':
side_ext = 'side_night'
elif side == 'Sub-stellar':
side_ext = 'substel'
file_name = 'plots/lewis/lewis_{0}_{1}'.format(var, side_ext)
return file_name
def plotGlobalVal(var, side):
col_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
if var =='tsurf':
row = row_tsurf
if side == 'Global':
data = loadCSV('LewisGlobalTsurf.csv')
data[:,1] = data[:,1] - 273.15
elif side == 'Day Side':
data = loadCSV('LewisSideDayTsurf.csv')
elif side == 'Night Side':
data = loadCSV('LewisSideNightTsurf.csv')
elif side == 'Sub-stellar':
data = loadCSV('LewisSideSubstelTsurf.csv')
elif var =='evap':
row = row_evap
data = loadCSV('LewisGlobalEvap.csv')
label = 'Lewis'
fig, ax = plt.subplots()
gvp.makeSubplot(col_list, ax, row, filetype='aijpc', side=side)
ax.plot(data[:, 0], data[:, 1], label=label, color='r', marker='x', markersize=10)
ax.legend()
fig.tight_layout(w_pad = 2.25)
file_name = getPlotName(var, side)
# plt.savefig(file_name+'.svg')
# plt.savefig(file_name+'.pdf')
plt.show()
# plotLonTsurf()
plotGlobalVal('tsurf', 'Sub-stellar')
<file_sep>/substelcont.py
import numpy as np
from netCDF4 import Dataset as ds
def openNC(fdir, fname):
"""
Load the Dataset nc file.
"""
filename = '/home/haynes13/code/python/input_files/' + fdir + '/' + fname
nc = ds(filename, 'r+', format='NETCDF4') #ssc = substellar continent
print(nc)
print('Dataset Loaded Successfully.')
return nc
def emptyMap(shape = (46, 72)):
"""
Create a blank template of zeros
with the same shape as a given grid map.
"""
empty_map = np.zeros(shape)
return empty_map
def changeMap(nc, map_in, lat_lo, lat_hi, lon_lo, lon_hi, val=1, n_dim=2, ocean=False):
"""
Put VAL in a given area of your grid map.
This function is designed so that hi values are included in the indexing,
so there will be ones at lat_hi and lon_hi.
All LAT/LON inputs in this function should be integer values that correspond to
the appropriate latitude and longitude values to be used in ROCKE-3D.
"""
assert lat_lo <= lat_hi, "Your highest latitude cannot be lower than your lowest latitude."
assert lon_lo <= lon_hi, "Your highest longitude cannot be lower than your lowest longitude."
def returnIndex(nc, name, coord, ocean):
if ocean:
name = name + 'o'
index_arr = np.where(nc[name][:]==coord)[0]
assert index_arr.size == 1, "There is no value {0} in the {1} array".format(coord, name)
return index_arr[0]
lat_lo_i = returnIndex(nc, 'lat', lat_lo, ocean)
lat_hi_i = returnIndex(nc, 'lat', lat_hi, ocean)
lon_lo_i = returnIndex(nc, 'lon', lon_lo, ocean)
lon_hi_i = returnIndex(nc, 'lon', lon_hi, ocean)
if n_dim==3:
num_layers = map_in.shape[0]
for i in range(num_layers):
map_in[i][lat_lo_i : lat_hi_i + 1, lon_lo_i: lon_hi_i + 1] = val
elif n_dim==2:
map_in[lat_lo_i : lat_hi_i + 1, lon_lo_i: lon_hi_i + 1] = val
map_out = map_in
return map_out
def changeVar(var, new_map, nc):
"""
Change the VAR array on the NC file.
to the NEW_MAP.
"""
nc[var][:] = new_map
return nc
def alterOIC(fdir, fname, lat_lo, lat_hi, lon_lo, lon_hi):
var_list = ['mo', 'g', 'gz', 's', 'sz']
nc = openNC(fdir, fname)
for var_i in var_list:
new_map = changeMap(nc, nc[var_i][:], lat_lo, lat_hi, lon_lo, lon_hi, val=0, n_dim=3, ocean=True)
nc = changeVar(var_i, new_map, nc)
return
def alterTOPO(fdir, fname, lat_lo, lat_hi, lon_lo, lon_hi):
var_list = ['focean', 'fgrnd']
nc = openNC(fdir, fname)
for var_i in var_list:
if var_i == 'focean':
val = 0
else:
val = 1
new_map = changeMap(nc, nc[var_i][:], lat_lo, lat_hi, lon_lo, lon_hi, val=val, n_dim=2, ocean=False)
nc = changeVar(var_i, new_map, nc)
return
def alterTOPO_OC(fdir, fname, lat_lo, lat_hi, lon_lo, lon_hi):
var_list = ['focean', 'zocean']
nc = openNC(fdir, fname)
for var_i in var_list:
if var_i == 'focean':
val = 0
else:
val = 30
new_map = changeMap(nc, nc[var_i][:], lat_lo, lat_hi, lon_lo, lon_hi, val=val, n_dim=2, ocean=True)
nc = changeVar(var_i, new_map, nc)
return
fdir = '39p'
fbase_name = '.ssc.latpn46.lonpn92_5.39p.nc'
lat = 48 # lat given from spreadsheet that outlines ACTUAL continent, NOT from GRID coords (see spreadsheet)
# https://docs.google.com/spreadsheets/d/1Cp85DWFq9kVjZ96rZPasCS9Nhny64671wVQjHS_XUNI/edit#gid=0
# you can see in the fbase_name that the GRID coordinates are given there, and they are
# different from the ACTUAL coordinates
lat_lo = (lat - 2) * (-1)
lat_hi = lat - 2
lon = 95 # lat given from spreadsheet that outlines ACTUAL continent, NOT from GRID coords (see spreadsheet)
# https://docs.google.com/spreadsheets/d/1Cp85DWFq9kVjZ96rZPasCS9Nhny64671wVQjHS_XUNI/edit#gid=0
# you can see in the fbase_name that the GRID coordinates are given there, and they are
# different from the ACTUAL coordinates
lon_lo = (lon - 2.5) * (-1)
lon_hi = (lon - 2.5)
alterOIC(fdir, 'OIC' + fbase_name, lat_lo, lat_hi, lon_lo, lon_hi)
alterTOPO(fdir, 'Z' + fbase_name, lat_lo, lat_hi, lon_lo, lon_hi)
alterTOPO_OC(fdir, 'OZ' + fbase_name, lat_lo, lat_hi, lon_lo, lon_hi)
<file_sep>/plot_scripts/latLonAvgPlot.py
from netCDF4 import Dataset as ds
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from files_n_vars import *
def avgDataFilesLatLon(filedir, var, num_files, filetype, unit_conv, depth, avg_coord):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = np.zeros((46,72))
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
if filetype == 'aijpc':
area_arr = nc_i['axyp'][:]
elif filetype == 'oijlpc':
area_arr = nc_i['oxyp3'][:][depth]
if depth == None:
arr = nc_i[var][:]
else:
arr = nc_i[var][:][depth]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if len(arr_avg.shape) == 3:
raise(ValueError, "This array is 3D, so the axes you are averaging over are invalid.")
if 'aqua' in filedir:
arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)
if avg_coord == 'lat':
avg_axis = 1
elif avg_coord == 'lon':
avg_axis = 0
avg_arr = np.sum(arr_avg * area_arr, axis=avg_axis) / np.sum(area_arr, axis=avg_axis)
return avg_arr
def makeSubplot(col_list, ax, row, filetype, avg_coord, num_files=10, unit_conv=1, depth=None):
if avg_coord == 'lat':
x = row['lat']
x_label = 'Latitude'
elif avg_coord == 'lon':
x = row['lon']
x_label = 'Longitude'
var = row['var']
title = row['title']
units = row['units']
for col in col_list:
filedir = col['filedir']
val_arr = avgDataFilesLatLon(filedir, var, num_files, filetype, unit_conv, depth, avg_coord)
SA = str(col['SA']) + '%'
if SA == '0%':
SA = 'Aqua'
ax.plot(x, val_arr, label=SA)
if var == 'tsurf':
ax.axhline(linestyle='--', color='k')
ax.set_title('Average ' + title)
ax.set_xlabel(x_label)
ax.set_ylabel(units)
def latLonAvgPlot():
col_list = [col_0, col_11, col_39]
row = row_tsurf
fig, ax = plt.subplots()
makeSubplot(col_list, ax, row, filetype='aijpc', avg_coord='lon')
ax.legend()
fig.tight_layout(w_pad = 2.25)
file_name = 'plots/lon_tsurf'
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
plt.show()
<file_sep>/plot_scripts/old_quiverPlot.py
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as ds
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from matplotlib.patches import Polygon
from cbar import MidPointNorm
from files_n_vars import *
col_list = [col_0, col_22, col_26]
def avgDataFiles3D(filedir, var, num_files, filetype, unit_conv, depth):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = np.zeros((46,72))
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
if depth == None:
arr = nc_i[var][:]
else:
arr = nc_i[var][:][depth]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir:
arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)
return arr_avg
def quiverSubPlot(col, ax, tit_ad, filetype, unit_conv, depth, num_files = 10):
filedir = col['filedir']
parallels = col['parallels']
meridians = col['meridians']
title = col['title']
if filetype == 'oijlpc':
u = avgDataFiles3D(filedir, 'u', num_files, filetype, unit_conv, depth)
v = avgDataFiles3D(filedir, 'v', num_files, filetype, unit_conv, depth)
elif filetype == 'aijpc':
u = avgDataFiles3D(filedir, 'usurf', num_files, filetype, unit_conv, depth)
v = avgDataFiles3D(filedir, 'vsurf', num_files, filetype, unit_conv, depth)
uv_mag = np.sqrt((u*u) + (v*v))
m = Basemap(ax = ax)
# m.drawcoastlines()
# m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels([-60, -30, 0, 30, 60], labels=[1,0,0,0], ax = ax, rotation=30, fontsize=8, linewidth=0)
m.drawmeridians([-135, -90, -45, 0, 45, 90, 135], labels=[0,0,0,1], ax = ax, rotation=0, fontsize=8, linewidth=0)
ny=u.shape[0]
nx=u.shape[1]
lons, lats = m.makegrid(nx, ny)
x, y = m(lons, lats)
plt.gca().patch.set_color('.25')
cs = m.contourf(x, y, uv_mag, ax=ax, cmap='Reds')
m.ax.tick_params(labelsize=2)
m.colorbar(mappable=cs, ax=ax, label='m/s')
def getScale(filetype):
if filetype == 'aijpc':
key_scale = 500
U = 10
elif filetype == 'oijlpc':
key_scale = 150
U = 1
key_label = '{0} m/s'.format(U)
return key_scale, U, key_label
key_scale, U, key_label = getScale(filetype)
q = m.quiver(x, y, u, v, ax=ax, scale_units='width', scale=key_scale,
pivot='middle', width=0.001, headwidth=7, headlength=5)
ax.quiverkey(q, X=0.93, Y=1.02, U=U, label = key_label, labelpos = 'E')
if title != 'Aqua':
x1, y1 = m(meridians[0], parallels[0])
x2, y2 = m(meridians[0], parallels[1])
x3, y3 = m(meridians[1], parallels[1])
x4, y4 = m(meridians[1], parallels[0])
cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none', edgecolor='black', linewidth=1)
plt.gca().add_patch(cont_boundary)
if filetype=='aijpc':
ax.set_title(title, fontsize=10)
ax.set_ylabel(tit_ad, fontsize=10, labelpad=30)
air_surf_vel = {'tit_ad':'Air Surface Velocity','filetype':'aijpc','unit_conv':1,'depth':None}
oc_0_vel = {'tit_ad':'Ocean 6m Velocity','filetype':'oijlpc','unit_conv':0.1,'depth':0}
oc_1_vel = {'tit_ad':'Ocean 21m Velocity','filetype':'oijlpc','unit_conv':0.1,'depth':1}
oc_2_vel = {'tit_ad':'Ocean 44m Velocity','filetype':'oijlpc','unit_conv':0.1,'depth':2}
oc_3_vel = {'tit_ad':'Ocean 77m Velocity','filetype':'oijlpc','unit_conv':0.1,'depth':3}
oc_4_vel = {'tit_ad':'Ocean 128m Velocity','filetype':'oijlpc','unit_conv':0.1,'depth':4}
def quiverPlot():
fig, axes = plt.subplots(2,1, figsize = (10,7))
col = col_39
ax0 = axes[0]
quiverSubPlot(col=col, ax=ax0, tit_ad='Air Surface Velocity', filetype='aijpc', unit_conv=1, depth=None)
ax1 = axes[1]
quiverSubPlot(col=col, ax=ax1, tit_ad='Ocean 6m Velocity', filetype='oijlpc', unit_conv=0.1, depth=0)
fig.tight_layout(w_pad = 2.25)
file_name = 'plots/quiver_39p_0'
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
plt.show()
quiverPlot()
<file_sep>/mergeSeriesData.py
# This script merges separate *data.csv timeseries into a single file.
# It was used on the aqua and 1% runs because I stupidly had their restarts
# put into separate directories.
import pandas as pd
csv1 = '/project2/abbot/haynes/ROCKE3D_output/pc_proxcenb_aqua5L_TL_500yr/ts_data.csv'
csv2 = '/project2/abbot/haynes/ROCKE3D_output/pc_proxcenb_aqua5L_TL_500yr_rs2/ts_data.csv'
new_csv = '/project2/abbot/haynes/ROCKE3D_output/pc_proxcenb_aqua5L_TL_500yr/ts_data_tot.csv'
def mergeData(csv1, csv2):
"""
Merge the two timeseries files into one total timeseries.
:param csv1: filename of the first (older) timeseries
:param csv2: filename of the second (newer) timeseries
Done by appending csv2 to csv1 and creating a new csv file.
:return: A new, total csv file
"""
df1 = pd.read_csv(csv1)
df2 = pd.read_csv(csv2)
result = df1.append(df2)
result.index = range(len(result.index))
result['decade'] = result.index #take the indexing of items and make that the number of decades.
return result
def saveMergedData(result, new_csv):
result.to_csv(new_csv)
result = mergeData(csv1, csv2)
saveMergedData(result, new_csv)
<file_sep>/plot_scripts/globalValPlot.py
from netCDF4 import Dataset as ds
import numpy as np
import matplotlib.pyplot as plt
from glob import glob
from files_n_vars import *
from lat_lon_grid import *
import calculatedQuantities as calcQuant
def avgDataFilesGlobal(filedir, var, filetype, depth, unit_conv = -1, num_files = 10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
if depth == None:
arr = nc_i[var][:]
else:
arr = nc_i[var][:][depth]
if filetype == 'aijpc':
area_arr = nc_i['axyp'][:]
elif filetype == 'oijlpc':
area_arr = nc_i['oxyp3'][:][depth]
# Set area to zero in cells that have no value, excluding them from the average
area_arr[arr.mask] = 0
if np.where(area_arr == 0)[0].size != 0:
print('MASK CHECK', np.where(area_arr == 0)[0].size) # If an array has a mask, check to make sure area array is masked as well.
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
# # Used primarily for planetary albedo, masking area wherever there's no value (i.e. no sunlight)
# area_arr[np.where(arr_avg==0)] = 0
# print(np.where(area_arr == 0)[0].size)
# #
if 'aqua' in filedir:
arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)
area_arr = np.roll(area_arr, (area_arr.shape[1]) // 2, axis=1)
# Rolling the area so that masked values (i.e. for albedo) are rolled according to their coordinate
# Rollling is necessary for determining side and substell averages
return arr_avg, area_arr
def getSideMean(data, area_arr, row, side):
lat_grid = row['lat']
lon_grid = row['lon']
cropped_data = data.copy()
cropped_area = area_arr.copy()
if side == 'Global':
avg_val = np.sum(data * area_arr) / np.sum(area_arr)
return avg_val
elif side == 'Day Side':
lon_indices = np.where(np.abs(lon_grid) < 90)[0]
elif side == 'Night Side':
lon_indices = np.where(np.abs(lon_grid) > 90)[0]
elif side == 'Sub-stellar':
lon_indices = np.where(np.abs(lon_grid) < 13)[0]
lat_indices = np.where(np.abs(lat_grid) < 11)[0]
cropped_data = cropped_data[lat_indices, :]
cropped_area = cropped_area[lat_indices, :]
cropped_data = cropped_data[:, lon_indices]
cropped_area = cropped_area[:, lon_indices]
avg_val = np.sum(cropped_data * cropped_area) / np.sum(cropped_area)
return avg_val
def makeSubplot(col_list, ax, row, filetype, side, depth=None):
var = row['var']
SA_arr = []
val_arr = []
for col in col_list:
filedir = col['filedir']
SA_arr.append(col['SA'])
arr_avg_i, area_arr_i = avgDataFilesGlobal(filedir, var, filetype, depth)
# # Calculated Planetary Albedo Scenario
# arr_avg_i, area_arr_i, plot_row, title = calcQuant.getPlanAlbFromSol(col)
# print("TOT MIN: {0}, TOT MAX: {1}".format(np.min(arr_avg_i), np.max(arr_avg_i)))
# row = plot_row
# #
val_i = getSideMean(arr_avg_i, area_arr_i, row, side)
val_arr.append(val_i)
SA_arr = np.array(SA_arr)
val_arr = np.array(val_arr)
# print('before', np.mean(val_arr))
# # Values used in determining planetary albedo from solar fluxes
# sol_net = np.array([177.64417, 176.96222, 174.6022, 172.0164, 169.36081,
# 170.56851, 172.2582, 171.33827, 173.11499])
# sol_inc = np.ones(9) * 220.53342
# sol_ref = sol_inc - sol_net
# val_arr = (sol_ref / sol_inc) * 100
# print('after', np.mean(val_arr))
# #
# print('before', np.mean(val_arr))
# # Values used in determining LW Absorption according to Lewis's method
# therm_up_surf = np.array([234.78496, 227.99066, 220.1106, 214.61176, 208.5697,
# 212.37679, 215.53433, 217.7208, 221.0594 ])
# therm_up_toa = -1 * np.array([-177.47583, -177.11324, -174.68597, -172.05318, -168.60745,
# -170.4261, -172.40097, -173.3177, -175.85881])
# lw_abs = therm_up_surf - therm_up_toa
# val_arr = lw_abs
# print('after', np.mean(val_arr))
# #
# print('before', np.mean(val_arr))
# # Values used in determining Heat Redistribution Efficiency according to Lewis's method
# day_lw = np.array([200.4674, 194.17012, 197.26746, 197.1325, 201.08948,
# 210.14731, 214.41014, 216.5942, 221.02673])
# night_lw = np.array([154.48427, 160.05635, 152.10452, 146.97388, 136.12547,
# 130.70493, 130.3918, 130.04128, 130.6909])
# heat_redistribution = night_lw / day_lw
# val_arr = heat_redistribution
# print('after', np.mean(val_arr))
# #
print('Values: ', val_arr)
ax.plot(SA_arr, val_arr, color='k', marker='o', markersize=10, label = 'ROCKE-3D')
title = row['title']
# title = 'Planetary Albedo from Solar'
# title = 'Longwave Absorption'
# title = 'Heat Redistribution'
units = row['units']
ax.set_title(side + ' Mean ' + title)
ax.set_xlabel('Continent size (% of total surface)')
ax.set_ylabel(units)
def getPlotName(row, side):
if side == 'Global':
side_ext = 'global'
elif side == 'Day Side':
side_ext = 'side_day'
elif side == 'Night Side':
side_ext = 'side_night'
elif side == 'Sub-stellar':
side_ext = 'substel'
file_name = 'plots/global/new_{0}_{1}'.format(row['var'], side_ext)
return file_name
def globalValPlot(row, side):
col_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
fig, ax = plt.subplots()
makeSubplot(col_list, ax, row, filetype='aijpc', side=side)
fig.tight_layout(w_pad = 2.25)
file_name = getPlotName(row, side)
# file_name = 'plots/global/heat_redistribution'
print('PLOT NAME:', file_name)
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
plt.show()
# row = {'var':'plan_alb_calc'}
side_list = ['Global', 'Day Side', 'Night Side', 'Sub-stellar']
row = row_trnf_toa
for side_i in side_list:
globalValPlot(row, side_i)
<file_sep>/plot_scripts/dim2DPlot.py
from netCDF4 import Dataset as ds
import numpy as np
from matplotlib import pyplot as plt, cm as cm
from glob import glob
from matplotlib.colors import Normalize
from cbar import MidPointNorm
from files_n_vars import *
from mpl_toolkits.axes_grid1 import ImageGrid
def avgDataFiles(filedir, var, filetype, unit_conv=1, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
arr_avg = np.roll(arr_avg, (arr_avg.shape[2]) // 2, axis=2)
if 'o' in filetype: #if it's ocean file, only take the top 5 levels
arr_avg = arr_avg[:5, :, :]
return arr_avg
def getHeightFile(filedir, filetype, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
z_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
z_i = nc_i['z'][:]
z_tot = z_tot + z_i
z_avg = z_tot / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
z_avg = np.roll(z_avg, (z_avg.shape[2]) // 2, axis=2)
z_final = z_avg.reshape((z_avg.shape[0], -1)).mean(axis=1)
return z_final
def getDimAvg(data, dim):
"""
get an average array over one dimension
:param data: inputted 3D data (depth, lat, lon)
:param dim: dimension you want to average across, leaving the others to show
Example: averaging across 'lon' leaves you with an array that is depth by latitude.
:return:
"""
if dim == 'lat':
avg_axis = 1
elif dim == 'lon':
avg_axis = 2
return np.mean(data, axis=avg_axis)
def getSlice(data, dim, coord, lat_grid, lon_grid):
"""
:param data: the inputted 3D data array
:param slice_dim: the dimension that you want to cut along (depth, lat, lon)
:param slice_coord: the coordinate of dimensions that you want to cut along [degrees or m]
:return: the 2D array sliced out along slice_dim at the coordinate slice_coord
"""
if dim == 'lat': # slice along a latitude
slice_index = np.where(lat_grid == coord)[0][0]
section = data[:,slice_index,:]
elif dim == 'lon': # slice along a longitude
slice_index = np.where(lon_grid == coord)[0][0]
section = data[:,:,slice_index]
return section
def makeSubplot(data, filetype, grid, row, col, dim, seq_or_div):
ax = grid[0]
ax.set_facecolor('.25')
# max_val = np.max(np.abs(data))
# min_val = np.min(data)
def make_cmap(seq_or_div):
min_val = -16 *(10**(-6))
max_val = 16 *(10**(-6))
levels = np.linspace(min_val, max_val, 17)
if seq_or_div == 'seq':
cmap = cm.Blues_r
norm = Normalize(vmin = min_val, vmax = max_val)
elif seq_or_div == 'div':
cmap = cm.seismic
norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val)
return cmap, norm, levels
cmap, norm, levels = make_cmap(seq_or_div)
if filetype == 'aijkpc':
y = getHeightFile(col['filedir'], filetype)
# If height array is shown in terms of pressure, reverse y-axis and set to logarithmic
if y[0] > y[-1]:
ax.set_ylim(y[0], y[-1])
ax.set_yscale('log')
ax.set_ylabel('Pressure [mb]')
else:
y = y / 1000
ax.set_ylabel('Height [km]')
else:
y = row['z']
ax.set_ylim(y[-1], y[0])
ax.set_ylabel('Depth [m]')
if dim == 'lon':
x = row['lat']
ax.set_xlabel('Latitude')
if col['title'] != 'Aqua':
ax.plot(col['parallels'], [y[0], y[0]], c='k', linewidth=2)
im = ax.contourf(x, y, data, levels, cmap=cmap, norm=norm)
if 'a' in filetype:
ax.set_aspect(3)
elif 'o' in filetype:
ax.set_aspect(0.5)
cbar = grid.cbar_axes[0].colorbar(im)
cbar.set_label_text(row['units'])
ax.set_title(col['title'] + ', ' + row['title'])
def getPlotName(row, col, filetype, dim, avg_or_slice, coord):
var_name = row['var']
if 'o' in filetype:
var_name = 'o_' + var_name
p_name = str(col['SA'])+'p'
coord_str = str(coord).replace('.','_')
file_name = 'plots/{0}/dim2D_{1}_{2}_{3}_{4}'.format(p_name, dim, var_name, avg_or_slice, coord_str)
return file_name
def dim2DPlot(row, col, filetype, dim, avg_or_slice, seq_or_div, coord = None):
fig = plt.figure()
grid = ImageGrid(fig, 111,
nrows_ncols=(1, 1),
axes_pad=0.07,
share_all=True,
cbar_location="bottom",
cbar_mode="single",
cbar_size="15%",
cbar_pad="40%",
aspect=True)
var = row['var']
lat_grid = row['lat']
lon_grid = row['lon']
filedir = col['filedir']
data3D = avgDataFiles(filedir, var, filetype)
if avg_or_slice == 'avg':
data = getDimAvg(data3D, dim)
elif avg_or_slice == 'slice':
data = getSlice(data3D, dim, coord, lat_grid, lon_grid)
print("MIN VAL: {0}, MAX VAL: {1}".format(np.min(data), np.max(data)))
makeSubplot(data=data, filetype=filetype, grid=grid, row=row, col=col,
dim=dim, seq_or_div=seq_or_div)
# fig.tight_layout(w_pad = 2.25)
file_name = getPlotName(row, col, filetype, dim, avg_or_slice, coord)
print('Filename:', file_name)
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
# plt.show()
print('Plot Saved.')
row = row_o_w
col = col_22
filetype = 'oijlpc'
dim = 'lon'
avg_or_slice = 'slice'
coord = 2.5
seq_or_div = 'div'
# dim2DPlot(row, col, filetype, dim, avg_or_slice, seq_or_div, coord = coord)
col_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
for col_i in col_list:
dim2DPlot(row, col_i, filetype, dim, avg_or_slice, seq_or_div, coord = coord)
<file_sep>/plot_scripts/files_n_vars.py
from lat_lon_grid import *
# FILES REPRESENT DIRECTORIES FOR DIFFERENT RUNS
filebase='/project2/abbot/haynes/ROCKE3D_output/'
filedir0=filebase+'pc_proxcenb_aqua5L_TL_500yr_rs2'
filedir1=filebase+'pc_proxcenb_ssc5L_TL_500yr_rs2'
filedir4=filebase+'pc_proxcenb_ssc5L_TL_4p'
filedir6=filebase+'pc_proxcenb_ssc5L_TL_6p'
filedir11=filebase+'pc_proxcenb_ssc5L_TL_11p'
filedir22=filebase+'pc_proxcenb_ssc5L_TL_22p'
filedir26=filebase+'pc_proxcenb_ssc5L_TL_26p'
filedir34=filebase+'pc_proxcenb_ssc5L_TL_34p'
filedir39=filebase+'pc_proxcenb_ssc5L_TL_39p'
# COLUMNS REPRESENT DIFFERENT RUNS
col_0 = {'filedir':filedir0, 'parallels':[], 'SA':0,
'meridians':[], 'title':'Aqua'}
col_1 = {'filedir':filedir1, 'parallels':[-12, 12], 'SA':1,
'meridians':[-15, 15], 'title':'1% Land'}
col_4 = {'filedir':filedir4, 'parallels':[-16, 16], 'SA':4,
'meridians':[-30, 30], 'title':'4% Land'}
col_6 = {'filedir':filedir6, 'parallels':[-20, 20], 'SA':6,
'meridians':[-35, 35], 'title':'6% Land'}
col_11 = {'filedir':filedir11, 'parallels':[-24, 24], 'SA':11,
'meridians':[-50, 50], 'title':'11% Land'}
col_22 = {'filedir':filedir22, 'parallels':[-36, 36], 'SA':22,
'meridians':[-70, 70], 'title':'22% Land'}
col_26 = {'filedir':filedir26, 'parallels':[-40, 40], 'SA':26,
'meridians':[-75, 75], 'title':'26% Land'}
col_34 = {'filedir':filedir34, 'parallels':[-44, 44], 'SA':34,
'meridians':[-90, 90], 'title':'34% Land'}
col_39 = {'filedir':filedir39, 'parallels':[-48, 48], 'SA':39,
'meridians':[-95, 95], 'title':'39% Land'}
# ROWS REPRESENT DIFFERENT VARIABLES
############
# ATMOSPHERE
############
row_frac_land = {'var':'frac_land',
'ylabel':'Land \n Fraction \n [%]',
'title':'Land Fraction',
'units':'[%]',
'lat':lat,
'lon':lon}
row_net_rad_planet = {'var':'net_rad_planet',
'ylabel':'Net \n Planet \n Radiation \n [Wm$^{-2}$]',
'title':'Net Planet Radiation',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_tsurf = {'var':'tsurf',
'ylabel':'Surface \n Temperature \n [C]',
'title':'Surface Temperature',
'units':'[$^{\circ}$C]',
'lat':lat,
'lon':lon}
row_evap = {'var':'evap',
'ylabel':'Evaporation \n [mm/day]',
'title':'Evaporation',
'units':'[mm/day]',
'lat':lat,
'lon':lon}
row_prec = {'var':'prec',
'ylabel':'Precipitation \n [mm/day]',
'title':'Precipitation',
'units':'mm/day',
'lat':lat,
'lon':lon}
row_qatm = {'var':'qatm',
'ylabel':'Atmospheric \n Water Vapor \n [kg/m^2]',
'title':'Atmospheric Water Vapor',
'units':'[kg/m^2]',
'lat':lat,
'lon':lon}
row_snowicefr = {'var':'snowicefr',
'ylabel':'Snow/Ice \n Fraction \n [%]',
'title':'Snow/Ice Fraction',
'units':'[%]',
'lat':lat,
'lon':lon}
row_ZSI = {'var':'ZSI',
'ylabel':'Sea Ice \n Thickness \n [m]',
'title':'Sea Ice Thickness',
'units':'[m]',
'lat':lat,
'lon':lon}
row_lwp = {'var':'lwp',
'ylabel':'Liquid \n Water \n Path \n [0.1kgm$^{-2}$]',
'title':'Liquid Water Path',
'units':'[0.1kgm$^{-2}$]',
'lat':lat,
'lon':lon}
row_swcrf_toa = {'var':'swcrf_toa',
'ylabel':'SW \n Cloud \n Rad \n Forcing \n [Wm$^{-2}$]',
'title':'SW Cloud Rad Forcing',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_lwcrf_toa = {'var':'lwcrf_toa',
'ylabel':'LW \n Cloud \n Rad \n Forcing \n [Wm$^{-2}$]',
'title':'LW Cloud Rad Forcing',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_srnf_toa = {'var':'srnf_toa',
'ylabel':'Net Solar \n TOA \n [Wm$^{-2}$]',
'title':'Net Solar TOA',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_incsw_toa = {'var':'incsw_toa',
'ylabel':'Incident Solar \n TOA \n [Wm$^{-2}$]',
'title':'Incident Solar TOA',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_srnf_grnd = {'var':'srnf_grnd',
'ylabel':'Net Solar \n Surf \n [Wm$^{-2}$]',
'title':'Net Solar Surf',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_incsw_grnd = {'var':'incsw_grnd',
'ylabel':'Incident Solar \n Surf \n [Wm$^{-2}$]',
'title':'Incident Solar Surf',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_trup_surf = {'var':'trup_surf',
'ylabel':'Thermal Up \n Surf \n [Wm$^{-2}$]',
'title':'Thermal Up Surf',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_trnf_toa = {'var':'trnf_toa',
'ylabel':'Thermal Net \n TOA \n [Wm$^{-2}$]',
'title':'Thermal Net TOA',
'units':'[Wm$^{-2}$]',
'lat':lat,
'lon':lon}
row_pcldt = {'var':'pcldt',
'ylabel':'Total Cloud \n Cover \n [%]',
'title':'Total Cloud Cover',
'units':'[%]',
'lat':lat,
'lon':lon}
row_pcldl = {'var':'pcldl',
'ylabel':'Low \n Level \n Clouds \n [%]',
'title':'Low Level Clouds',
'units':'[%]',
'lat':lat,
'lon':lon}
row_pcldm = {'var':'pcldm',
'ylabel':'Middle \n Level \n Clouds \n [%]',
'title':'Middle Level Clouds',
'units':'[%]',
'lat':lat,
'lon':lon}
row_pcldh = {'var':'pcldh',
'ylabel':'High \n Level \n Clouds \n [%]',
'title':'High Level Clouds',
'units':'[%]',
'lat':lat,
'lon':lon}
row_pscld = {'var':'pscld',
'ylabel':'Shallow \n Convective \n Cloud \n Cover \n [%]',
'title':'Shallow Convective Cloud Cover',
'units':'[%]',
'lat':lat,
'lon':lon}
row_pdcld = {'var':'pdcld',
'ylabel':'Deep \n Convective \n Cloud \n Cover \n [%]',
'title':'Deep Convective Cloud Cover',
'units':'[%]',
'lat':lat,
'lon':lon}
row_wtrcld = {'var':'wtrcld',
'ylabel':'Water \n Cloud Cover \n [%]',
'title':'Water Cloud Cover',
'units':'[%]',
'lat':lat,
'lon':lon}
row_icecld = {'var':'icecld',
'ylabel':'Ice \n Cloud Cover \n [%]',
'title':'Ice Cloud Cover',
'units':'[%]',
'lat':lat,
'lon':lon}
row_plan_alb = {'var':'plan_alb',
'ylabel':'Planetary \n Albedo \n [%]',
'title':'Planetary Albedo',
'units':'[%]',
'lat':lat,
'lon':lon}
row_temp = {'var':'temp',
'ylabel':'Temperature \n [C]',
'title':'Temperature',
'units':'[C]',
'lat':lat,
'lon':lon,
'z':plm}
row_tb = {'var':'tb',
'ylabel':'Temperature \n [C]',
'title':'Temperature',
'units':'[C]',
'lat':lat2,
'lon':lon2,
'z':plm}
row_ub = {'var':'ub',
'ylabel':'Zonal Wind \n [m/s]',
'title':'Zonal Wind',
'units':'[m/s]',
'lat':lat2,
'lon':lon2,
'z':plm}
row_vb = {'var':'vb',
'ylabel':'Meridional Wind \n [m/s]',
'title':'Meridional Wind',
'units':'[m/s]',
'lat':lat2,
'lon':lon2,
'z':plm}
row_w = {'var':'w',
'ylabel':'Omega \n [Pa/s]',
'title':'Omega',
'units':'[Pa/s]',
'lat':lat,
'lon':lon,
'z':plm}
#########
# OCEAN
#########
row_o_dens = {'var':'dens',
'ylabel':'Density \n [kgm$^{-3}$] \n (- 1000)',
'title':'Density',
'units':'[kgm$^{-3}$] (- 1000)',
'lat':lato,
'lon':lono,
'z':zoc}
row_o_pot_dens = {'var':'pot_dens',
'ylabel':'Pot. Density \n [kgm$^{-3}$] \n (- 1000)',
'title':'Pot. Density',
'units':'[kgm$^{-3}$] (- 1000)',
'lat':lato,
'lon':lono,
'z':zoc}
row_o_pot_temp = {'var':'pot_temp',
'ylabel':'Pot. Temp. \n [C]',
'title':'Pot. Temp.',
'units':'[C]',
'lat':lato,
'lon':lono,
'z':zoc}
row_o_salt = {'var':'salt',
'ylabel':'Salinity \n [psu]',
'title':'Salinity',
'units':'[psu]',
'lat':lato,
'lon':lono,
'z':zoc}
row_o_u = {'var':'u',
'ylabel':'East-West \n Velocity \n [cm/s]',
'title':'East-West Velocity',
'units':'[cm/s]',
'lat':lato,
'lon':lono2,
'z':zoc}
row_o_v = {'var':'v',
'ylabel':'North-South \n Velocity \n [cm/s]',
'title':'North-South Velocity',
'units':'[cm/s]',
'lat':lato2,
'lon':lono,
'z':zoc}
row_o_w = {'var':'w',
'ylabel':'Downward \n Velocity \n [cm/s]',
'title':'Downward Velocity',
'units':'[cm/s]',
'lat':lato,
'lon':lono,
'z':zoce}
<file_sep>/pltSeries.py
# This file is used to make plots of the timeseries evolution for select characteristics.
import matplotlib.pyplot as plt
import pandas as pd
import os
import numpy as np
def makeSubPlots(runid = 'pc_proxcenb_ssc5L_TL_11p',
runbase = '/project2/abbot/haynes/ROCKE3D_output/',
data_file = 'ts_data'):
"""
:param runid: the directory for the specific run
:param runbase: the base path for the outputted ROCKE-3D files
:param data_file: the csv file that will be accessed to plot characteristics,
typically named 'ts_data'
:return: a plot and saved pdf of the desired timeseries
"""
rundir = runbase + runid
os.chdir(rundir) # Switch on over to the run directory.
df = pd.read_csv(data_file + '.csv')
fig, axes = plt.subplots(2, 2, figsize=(9,9))
def makeSubPlot(x, y, x_lab, y_lab, i, j):
axes[i, j].plot(x, y)
axes[i, j].set_xlabel(x_lab)
axes[i, j].set_ylabel(y_lab)
x = df['decade'] * 10
x_lab = 'Year'
y_list = ['radiation', 'temperature', 'snow_ice_cover', 'ice_thickness']
y_lab_list = ['Net Radiation (W/m^2)', 'Temperature (C)', 'Snow Ice Cover (%)', 'Ice Thickness (m)']
for num in range(4):
i = num // 2
j = num % 2
y = df[y_list[num]]
y_lab = y_lab_list[num]
makeSubPlot(x, y, x_lab, y_lab, i, j)
fig.suptitle(runid, y=1, fontsize=10)
fig.tight_layout()
# plt.savefig(data_file + '.svg')
plt.savefig(data_file + '.pdf')
plt.show()
print('data saved.')
return
def makeIcePlots(runid = 'pc_proxcenb_ssc5L_TL_11p',
runbase = '/project2/abbot/haynes/ROCKE3D_output/',
data_file = 'ts_data'):
"""
This plot was used to check whether the flux imbalance could be
accounted for due to the freezing ocean.
The ocean freezing outputs latent heat energy, which could
explain why a given simulation hasn't reached a radiative equilibrium state.
"""
rundir = runbase + runid
os.chdir(rundir) # Switch on over to the run directory.
df = pd.read_csv(data_file + '.csv')
fig, axes = plt.subplots(1, 3, figsize=(9,9), sharey='col')
x = df['decade'] * 10
x_lab = 'Year'
net_rad = df['radiation']
dh_ice = df['ice_thickness']
# x = x[-50:]
# net_rad = net_rad[-50:]
# dh_ice = dh_ice[-50:]
rho_ice = 916.9 # kg/m^3
EF_ice = 333.55 * 10**3 #J/kg
dt = 10*11.186*24*3600 #seconds in a ProxCenb decade
ice_flux = []
for i in range(len(dh_ice)-1):
h_i = dh_ice[i]
h_f = dh_ice[i+1]
dh = h_f - h_i
ice_flux_i = (dh/dt) * EF_ice * rho_ice
ice_flux.append(ice_flux_i)
ice_flux = np.array(ice_flux)
ax0 = axes[0]
ax0.plot(x, net_rad)
ax0.set_xlabel(x_lab)
ax0.set_ylabel('Net Radiation (W/m^2)')
ax0.set_ylim(-10, 10)
ax1 = axes[1]
ax1.plot(x[1:], ice_flux)
ax1.set_xlabel(x_lab)
ax1.set_ylabel('Ice Radiation (W/m^2)')
ax1.set_ylim(-10, 10)
ax2 = axes[2]
ax2.plot(x[1:], ice_flux + net_rad[1:])
ax2.set_xlabel(x_lab)
ax2.set_ylabel('Ice + Net (W/m^2)')
ax2.set_ylim(-10, 10)
fig.suptitle(runid+'Ice-Rad Check', y=1, fontsize=10)
fig.tight_layout()
# plt.savefig(data_file + '_ice_rad.svg')
plt.savefig(data_file + '_ice_rad.pdf')
plt.show()
print('data saved.')
return
makeIcePlots()
# makeSubPlots()
<file_sep>/plot_scripts/slicePlot.py
from netCDF4 import Dataset as ds
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from glob import glob
from files_n_vars import *
from lat_lon_grid import *
def avgDataFiles(filedir, var, filetype, unit_conv=1, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
arr_avg = np.roll(arr_avg, (arr_avg.shape[2]) // 2, axis=2)
if 'o' in filetype: #if it's ocean file, only take the top 5 levels
arr_avg = arr_avg[:5, :, :]
return arr_avg
def getSlice(data, slice_dim, slice_coord, lat_grid, lon_grid):
"""
:param data: the inputted 3D data array
:param slice_dim: the dimension that you want to cut along (depth, lat, lon)
:param slice_coord: the coordinate of dimensions that you want to cut along [degrees or m]
:return: the 2D array sliced out along slice_dim at the coordinate slice_coord
"""
if slice_dim == 'lat': # slice along a latitude
slice_index = np.where(lat_grid == slice_coord)[0][0]
section = data[:,slice_index,:]
elif slice_dim == 'lon': # slice along a longitude
slice_index = np.where(lon_grid == slice_coord)[0][0]
section = data[:,:,slice_index]
return section
def sliceSubplot(data, slice_dim, slice_coord, axes, row_num, col_num,
ylabel, title, lat_grid, lon_grid, z_grid):
"""
:param data: inputted data
:param slice_dim: dimension along which you want to cut
:param slice_coord: coordinate of slice_dim you want to cut
:param axes: axes of figure
:param row_num:
:param col_num:
:param ylabel:
:param title:
:return: a subplot for the given variable and continent size
"""
ax = axes#[col_num]
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
section = getSlice(data, slice_dim, slice_coord, lat_grid, lon_grid)
im = ax.imshow(section, aspect = 'auto')
plt.colorbar(im, cax=cax)
if slice_dim == 'lat':
ax.set_xlabel('Lon')
# ax.set_xticklabels(['']*lon_grid.size)
elif slice_dim == 'lon':
ax.set_xlabel('Lat')
# ax.set_xticklabels(['']*lat_grid.size)
if row_num == 0:
ax.set_title(title, fontsize=10)
if col_num == 0:
ax.set_ylabel(ylabel, fontsize=10, labelpad = 60, rotation=0, verticalalignment ='center')
ax.set_yticklabels(['']+z_grid.tolist())
# else:
# ax.set_yticklabels(['']*len(z_grid))
def slicePlot(filetype, row_list, col_list, slice_dim, slice_coord):
fig, axes = plt.subplots(len(row_list), len(col_list),
figsize = (12,3))
for row_num in range(len(row_list)):
row = row_list[row_num]
lat_grid = row['lat']
lon_grid = row['lon']
z_grid = row['z']
if z_grid.size == 13:
z_grid = z_grid[:5]
var = row['var']
for col_num in range(len(col_list)):
col = col_list[col_num]
print(row_num, col_num)
filedir=col['filedir']
data = avgDataFiles(filedir, var, filetype)
sliceSubplot(data=data, slice_dim = slice_dim, slice_coord = slice_coord, axes=axes,
row_num=row_num, col_num=col_num, ylabel=row['ylabel'], title=col['title'],
lat_grid=lat_grid, lon_grid=lon_grid, z_grid=z_grid)
fig.tight_layout(w_pad = 2.25)
file_name = 'plots/slice_o_pot_dens_aqua'
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
plt.show()
row_list = [row_o_pot_dens]
col_list = [col_0]#, col_1, col_22, col_39]
slice_dim = 'lon'
slice_coord = 2.5
filetype = 'oijl'
slicePlot(filetype, row_list, col_list, slice_dim, slice_coord)
<file_sep>/plot_scripts/calculatedQuantities.py
from files_n_vars import *
from lat_lon_grid import *
import numpy as np
from netCDF4 import Dataset as ds
from glob import glob
def getPlanAlbFromSol(col, filetype = 'aijpc', num_files = 10):
filedir = col['filedir']
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
net_i = nc_i['srnf_toa'][:]
inc_i = nc_i['incsw_toa'][:]
out_i = inc_i - net_i
albedo_i = (out_i / inc_i) * 100
arr_tot = arr_tot + albedo_i
area_arr = nc_i['axyp'][:]
area_arr[albedo_i.mask] = 0
print(np.where(area_arr == 0)[0].size)
arr_avg = arr_tot / num_files
if 'aqua' in filedir:
arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)
area_arr = np.roll(area_arr, (area_arr.shape[1]) // 2, axis=1)
# Rolling the area so that masked values (i.e. for albedo) are rolled according to their coordinate
# Rollling is necessary for determining side and substell averages
plot_row = {'var':'plan_alb_calc',
'ylabel':'Calculated \n Planetary \n Albedo \n [%]',
'title':'Calculated Planetary Albedo',
'units':'[%]',
'lat':lat,
'lon':lon}
title = col['title']
return arr_avg, area_arr, plot_row, title
<file_sep>/plot_scripts/singlePlot.py
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as ds
import numpy as np
from matplotlib import pyplot as plt, cm as cm
from glob import glob
from matplotlib.patches import Polygon
from matplotlib.colors import Normalize
from cbar import MidPointNorm
from files_n_vars import *
from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid
import calculatedQuantities as calcQuant
def avgDataFiles(filedir, filetype, var, unit_conv = 1, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
roll_size = arr_avg.shape[-1]
roll_axis = len(arr_avg.shape) - 1
arr_avg = np.roll(arr_avg, (roll_size) // 2, axis=roll_axis)
if 'o' in filetype: #if it's ocean file, only take the top 5 levels
arr_avg = arr_avg[:5, :, :]
return arr_avg
def makeSubplot(grid, data, row, col, title, seq_or_div):
ax = grid[0]
ax.set_facecolor('.25')
m = Basemap(ax = ax)
ny=data.shape[0]
nx=data.shape[1]
lons, lats = m.makegrid(nx, ny)
x, y = m(lons, lats)
# min_val = np.min(np.abs(data))
# max_val = np.max(np.abs(data))
def make_cmap(seq_or_div):
min_val = -11
max_val = 11
levels = np.linspace(min_val, max_val, 23)
if seq_or_div == 'seq':
cmap = cm.Blues
norm = Normalize(vmin = min_val, vmax = max_val)
elif seq_or_div == 'div':
cmap = cm.seismic
norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val)
return cmap, norm, levels
cmap, norm, levels = make_cmap(seq_or_div)
cs = m.contourf(x, y, data, levels, ax=ax, cmap=cmap, norm=norm)
m.ax.tick_params(labelsize=2)
ax.set_title(title, fontsize=10)
ax.set_ylabel(row['ylabel'], fontsize=10, labelpad = 60, rotation=0, verticalalignment ='center')
# draw parallels and meridians.
m.drawparallels([-60, -30, 0, 30, 60], labels=[1,0,0,0], ax = ax,
rotation=30, fontsize=8, linewidth=0)
m.drawmeridians([-135, -90, -45, 0, 45, 90, 135], labels=[0,0,0,1], ax = ax,
rotation=40, fontsize=8, linewidth=0)
if row['var'] == 'tsurf':
m.contour(x, y, data, ax=ax, levels = [0], colors=('k',),linestyles=('-.',),linewidths=(1,))
parallels = col['parallels']
meridians = col['meridians']
if 'Aqua' not in title:
x1, y1 = m(meridians[0], parallels[0])
x2, y2 = m(meridians[0], parallels[1])
x3, y3 = m(meridians[1], parallels[1])
x4, y4 = m(meridians[1], parallels[0])
cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none',
edgecolor='black', linewidth=1)
ax.add_patch(cont_boundary)
grid.cbar_axes[0].colorbar(cs)
def getPlotName(row, col, filetype, depth):
"""
If the plot is a single figure (one simulation),
then generate the filename automatically.
:param row:
:param col:
:param filetype:
:param depth:
:return:
"""
if depth == None:
depth_name = ''
elif depth == 'vertAvg':
depth_name = '_vertAvg'
else:
depth_name = '_' + str(depth)
var_name = row['var']
if 'o' in filetype:
var_name = 'o_' + var_name
p_name = str(col['SA'])+'p'
file_name = 'plots/{0}/{1}{2}'.format(p_name, var_name, depth_name)
return file_name
def depthOrVertAvg(data, col, depth):
if depth == None:
data = data
title = col['title']
elif depth == 'vertAvg':
data = np.mean(data, axis=0)
print("AVG MIN: {0}, AVG MAX: {1}".format(np.min(data), np.max(data)))
title = col['title'] + ', Vert. Avg.'
else:
data = data[depth,:,:]
print("DEPTH MIN: {0}, DEPTH MAX: {1}".format(np.min(data), np.max(data)))
if 'o' in filetype:
ext = ' m'
elif 'a' in filetype:
ext = ' mb'
title = col['title'] + ', ' + str(row['z'][depth]) + ext
return data, title
def singlePlot(row, col, filetype, depth, seq_or_div):
fig = plt.figure(figsize = (14,6))
grid1 = ImageGrid(fig, 111,
nrows_ncols=(1,1),
axes_pad=0.07,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="7%",
cbar_pad="7%",
aspect=True)
var = row['var']
filedir = col['filedir']
data = avgDataFiles(filedir, filetype, var)
print("TOT MIN: {0}, TOT MAX: {1}".format(np.min(data), np.max(data)))
data, title = depthOrVertAvg(data, col, depth)
# # Calculated Planetary Albedo Scenario
# arr_avg, area_arr, plot_row, title = calcQuant.getPlanAlbFromSol(col)
# data = arr_avg
# print("TOT MIN: {0}, TOT MAX: {1}".format(np.min(data), np.max(data)))
# row = plot_row
# #
makeSubplot(grid=grid1, data=data, row=row, col=col, title=title, seq_or_div=seq_or_div)
# fig.tight_layout(w_pad = 2.25)
file_name = getPlotName(row, col, filetype, depth)
print('PLOT NAME:', file_name)
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
# plt.show()
print('Plot saved.')
row = row_evap
col = col_39
filetype = 'aijpc'
seq_or_div = 'div'
col_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
# ############# SINGLE DEPTH PLOT #################
# depth = 0
# singlePlot(row, col, filetype, depth, seq_or_div)
# ############# ALL DEPTHS PLOT ###################
# for depth_i in range(row['z'].size):
# singlePlot(row, col, filetype, depth_i, seq_or_div)
# ############# ALL VERT AVGS PLOT #################
# depth = 'vertAvg'
# for col_i in col_list:
# singlePlot(row, col_i, filetype, depth, seq_or_div)
# ############# WHOLE SHABANG ################
# for col_i in col_list:
# for depth_i in range(row['z'].size):
# singlePlot(row, col_i, filetype, depth_i, seq_or_div)
# singlePlot(row, col_i, filetype, 'vertAvg', seq_or_div)
############# ALL COLS OF SAME DEPTH ################
depth = None
for col_i in col_list:
singlePlot(row, col_i, filetype, depth, seq_or_div)
<file_sep>/stat_check.py
"""
This file is used to check the status of a given run,
to see whether it has reached a radiative equilibrium state.
"""
import numpy as np
import pandas as pd
from netCDF4 import Dataset as ds
import matplotlib.pyplot as plt
def showAvgNetRad(filename):
"""
Show the average net radiation of the past 10 runs
:param filename: name of the csv file with timeseries data
:return: Nothing, just print the recent net flux values and their average
"""
df = pd.read_csv(filename)
recent_vals = df['radiation'][-10:]
print(recent_vals)
print(np.mean(recent_vals))
return
def oceanPotTemp(filename):
nc = ds(filename, 'r+', format='NETCDF4')
pot_temp = nc['pot_temp'][:]
avg_pot_temp = np.array([])
for o_layer in pot_temp:
avg_pot_temp = np.append(avg_pot_temp, np.mean(o_layer))
print('Avg Pot Temp (Celsius)')
print(avg_pot_temp)
return
def iceGrowth(filedir, filename1, filename2):
nc1 = ds(filedir+filename1, 'r+', format='NETCDF4')
zsi1 = nc1['ZSI'][:]
net_rad1 = nc1['net_rad_planet'][:]
nc2 = ds(filedir + filename2, 'r+', format='NETCDF4')
zsi2 = nc2['ZSI'][:]
net_rad2 = nc2['net_rad_planet'][:]
def getScale(arr1, arr2, div=True):
arr1_max = np.max(np.abs(arr1))
arr2_max = np.max(np.abs(arr2))
tot_max = max(arr1_max, arr2_max)
if div:
tot_min = tot_max * -1
else:
arr1_min = np.min(np.abs(arr1))
arr2_min = np.min(np.abs(arr2))
tot_min = min(arr1_min, arr2_min)
return tot_min, tot_max
fig, axes = plt.subplots(2, 2)
ax1 = axes[0,0]
ax1.set_title('Ice Thickness Growth [m]')
zsi_min, zsi_max = getScale(zsi1, zsi2)
im1 = ax1.imshow(zsi1, cmap='Blues', vmin = 0, vmax = zsi_max)
fig.colorbar(im1, ax=ax1)
ax2 = axes[1, 0]
im2 = ax2.imshow(zsi2, cmap='Blues', vmin = 0, vmax = zsi_max)
fig.colorbar(im2, ax=ax2)
ax3 = axes[0, 1]
ax3.set_title('Net Radiation [Wm$^{-2}$]')
rad_min, rad_max = getScale(net_rad1, net_rad2)
im3 = ax3.imshow(net_rad1, cmap='seismic', vmin=rad_min, vmax=rad_max)
fig.colorbar(im3, ax=ax3)
ax4 = axes[1, 1]
im4 = ax4.imshow(net_rad2, cmap='seismic', vmin=rad_min, vmax=rad_max)
fig.colorbar(im4, ax=ax4)
plt.tight_layout()
plt.show()
# def avgDataFiles(filedir, var, num_files=10):
# results = glob('{0}/*aij*'.format(filedir))
# arr_tot = np.zeros((46, 72))
# for filename in results:
# nc_i = ds(filename, 'r+', format='NETCDF4')
# arr = nc_i[var][:]
# arr_tot = arr_tot + arr
# arr_avg = arr_tot / num_files
# return arr_avg
<file_sep>/venv/lib/python3.6/site-packages/mplkit/__init__.py
__author__ = "<NAME> < <EMAIL> >"
__version__ = '0.6'
<file_sep>/plot_scripts/quiverPlot.py
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as ds
import numpy as np
from matplotlib import pyplot as plt, cm as cm
from glob import glob
from matplotlib.patches import Polygon
from matplotlib.colors import Normalize
from cbar import MidPointNorm
from files_n_vars import *
from mpl_toolkits.axes_grid1 import ImageGrid
def avgDataFiles(filedir, filetype, var, unit_conv = 1, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
arr_avg = np.roll(arr_avg, (arr_avg.shape[2]) // 2, axis=2)
if 'o' in filetype: #if it's ocean file, only take the top 5 levels
arr_avg = arr_avg[:5, :, :]
return arr_avg
def makeSubplot(grid, row_u, u, v, row_contour, contour_data, col, title, seq_or_div):
ax = grid[0]
ax.set_facecolor('.25')
x_u = row_u['lon']
y_u = row_u['lat']
# min_val = np.min(np.abs(data))
# max_val = np.max(np.abs(data))
def make_cmap(seq_or_div):
min_val = -110
max_val = 110
levels = np.linspace(min_val, max_val, 23)
if seq_or_div == 'seq':
cmap = cm.Blues
norm = Normalize(vmin = min_val, vmax = max_val)
elif seq_or_div == 'div':
cmap = cm.seismic
norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val)
return cmap, norm, levels
cmap, norm, levels = make_cmap(seq_or_div)
def quiverUV(x_u, y_u, u, v, quiv_norm=False):
if quiv_norm:
uv_mag = np.sqrt((u * u) + (v * v))
q = ax.quiver(x_u, y_u, u/uv_mag, v/uv_mag)
else:
q = ax.quiver(x_u, y_u, u, v, scale_units='width', scale=2000,
pivot='middle', width=0.001, headwidth=5, headlength=5)
U = 50
key_label = '{0} m/s'.format(U)
ax.quiverkey(q, X=0.93, Y=1.02, U=U, label=key_label, labelpos='E')
def contourPlot(x, y, data, units, levels, cmap, norm):
im = ax.contourf(x, y, data, levels, cmap=cmap, norm=norm)
cbar = grid.cbar_axes[0].colorbar(im)
cbar.set_label_text(units)
if row_contour != None:
x_contour = row_contour['lon']
y_contour = row_contour['lat']
units_contour = row_contour['units']
else:
x_contour = x_u
y_contour = y_u
units_contour = row_u['units']
contourPlot(x_contour, y_contour, contour_data, units_contour, levels, cmap, norm)
quiverUV(x_u, y_u, u, v)
parallels = col['parallels']
meridians = col['meridians']
if 'Aqua' not in title:
x1, y1 = meridians[0], parallels[0]
x2, y2 = meridians[0], parallels[1]
x3, y3 = meridians[1], parallels[1]
x4, y4 = meridians[1], parallels[0]
cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none',
edgecolor='black', linewidth=1)
ax.add_patch(cont_boundary)
ax.set_xlim(-180,180)
ax.set_ylim(-90,90)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title(title)
def getPlotName(row_contour, col, filetype_uv, depth):
if depth == None:
depth_name = ''
elif depth == 'vertAvg':
depth_name = '_vertAvg'
else:
depth_name = '_' + str(depth)
if row_contour != None:
var_name = row_contour['var']
else:
var_name = 'uv'
if 'o' in filetype_uv:
var_name = 'o_' + var_name
p_name = str(col['SA'])+'p'
file_name = 'plots/{0}/quiver_{1}{2}'.format(p_name, var_name, depth_name)
return file_name
def depthOrVertAvg(data, depth):
if depth == None:
data = data
elif depth == 'vertAvg':
data = np.mean(data, axis=0)
print("AVG MIN: {0}, AVG MAX: {1}".format(np.min(data), np.max(data)))
else:
data = data[depth,:,:]
print("DEPTH MIN: {0}, DEPTH MAX: {1}".format(np.min(data), np.max(data)))
return data
def getHeightFile(filedir, filetype, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
z_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
z_i = nc_i['z'][:]
z_tot = z_tot + z_i
z_avg = z_tot / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
z_avg = np.roll(z_avg, (z_avg.shape[2]) // 2, axis=2)
z_final = z_avg.reshape((z_avg.shape[0], -1)).mean(axis=1)
return z_final
def getTitle(row_u, row_contour, col, depth, filetype_uv):
if row_contour != None:
title_row = row_contour['title']
else:
title_row = 'Velocity'
if depth == None:
title_depth = ''
elif depth == 'vertAvg':
title_depth = ', Vert. Avg.'
else:
if 'o' in filetype_uv:
z_arr = row_u['z']
elif 'a' in filetype_uv:
z_arr = getHeightFile(col['filedir'], filetype_uv)
title_depth = ', {0:.0f} m'.format(z_arr[depth])
title = '{0}{1}, {2}'.format(col['title'], title_depth, title_row)
return title
def quiverPlot(row_u, row_v, row_contour, col, filetype_uv, filetype_contour,
depth, depth_contour, seq_or_div):
fig = plt.figure(figsize = (14,6))
grid1 = ImageGrid(fig, 111,
nrows_ncols=(1,1),
axes_pad=0.07,
share_all=True,
cbar_location="bottom",
cbar_mode="single",
cbar_size="4%",
cbar_pad="11%",
aspect=True)
filedir = col['filedir']
var_u = row_u['var']
u = avgDataFiles(filedir, filetype_uv, var_u)
print("U MIN: {0}, U MAX: {1}".format(np.min(u), np.max(u)))
u = depthOrVertAvg(u, depth)
var_v = row_v['var']
v = avgDataFiles(filedir, filetype_uv, var_v)
print("V MIN: {0}, V MAX: {1}".format(np.min(v), np.max(v)))
v = depthOrVertAvg(v, depth)
if row_contour != None:
var_contour = row_contour['var']
contour_data = avgDataFiles(filedir, filetype_contour, var_contour)
print("{0} MIN: {1}, {0} MAX: {2}".format(var_contour, np.min(contour_data), np.max(contour_data)))
contour_data = depthOrVertAvg(contour_data, depth_contour)
else:
contour_data = np.sqrt((u * u) + (v * v)) # Set contours as the horizontal velocity magnitudes
print("{0} MIN: {1}, {0} MAX: {2}".format('Velocity', np.min(contour_data), np.max(contour_data)))
title = getTitle(row_u, row_contour, col, depth, filetype_uv)
makeSubplot(grid=grid1, row_u=row_u, u=u, v=v,
row_contour=row_contour, contour_data=contour_data,
col=col, title=title, seq_or_div=seq_or_div)
# fig.tight_layout(w_pad = 2.25)
file_name = getPlotName(row_contour, col, filetype_uv, depth)
print('PLOT NAME:', file_name)
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
# plt.show()
print('Plot saved.')
col_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
row_u = row_ub
row_v = row_vb
filetype_uv = 'aijkpc'
row_contour = row_temp
filetype_contour = 'aijlpc'
# col = col_39
seq_or_div = 'div'
# ############# SINGLE DEPTH PLOT #################
# depth = 0
# depth_contour = 0
# quiverPlot(row_u, row_v, row_contour, col, filetype_uv, filetype_contour,
# depth, depth_contour, seq_or_div)
# ############ ALL DEPTHS PLOT ###################
# for depth_i in range(row_u['z'].size):
# quiverPlot(row_u, row_v, row_contour, col, filetype_uv, filetype_contour,
# depth_i, depth_i, seq_or_div)
# ############# ALL VERT AVGS PLOT #################
# depth = 'vertAvg'
# depth_contour = 'vertAvg'
# for col_i in col_list:
# quiverPlot(row_u, row_v, row_contour, col_i, filetype_uv, filetype_contour,
# depth, depth_contour, seq_or_div)
############ WHOLE SHABANG ################
for col_i in col_list:
for depth_i in range(row_u['z'].size):
quiverPlot(row_u, row_v, row_contour, col_i, filetype_uv, filetype_contour,
depth_i, depth_i, seq_or_div)
quiverPlot(row_u, row_v, row_contour, col_i, filetype_uv, filetype_contour,
'vertAvg', 'vertAvg', seq_or_div)
<file_sep>/plot_scripts/vertAvgPlot.py
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as ds
import numpy as np
from matplotlib import pyplot as plt, cm as cm
from glob import glob
from matplotlib.patches import Polygon
from matplotlib.colors import Normalize
from cbar import MidPointNorm
from files_n_vars import *
from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid
def avgDataFiles(filedir, var, filetype, unit_conv=1, num_files=10):
results = glob('{0}/*{1}*'.format(filedir, filetype))
arr_tot = 0
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = (arr_tot * unit_conv) / num_files
if 'aqua' in filedir: #if it's aquaplanet simulation you need to roll so that substell point is in middle
arr_avg = np.roll(arr_avg, (arr_avg.shape[2]) // 2, axis=2)
if 'o' in filetype: #if it's ocean file, only take the top 5 levels
arr_avg = arr_avg[:5, :, :]
return np.mean(arr_avg, axis=0)
def makeSubplot(data, var, cbar_data, grid, col_num, ylabel, parallels,
meridians, title, plot_cbar=False):
ax = grid[col_num]
ax.set_facecolor('.25')
m = Basemap(ax = ax)
ny=data.shape[0]
nx=data.shape[1]
lons, lats = m.makegrid(nx, ny)
x, y = m(lons, lats)
min_val = np.min(cbar_data)
max_val = np.max(cbar_data)
def make_cmap(var):
sequential_list = ['frac_land', 'pscld', 'pdcld', 'snowicefr', 'lwp',
'pcldt', 'pscld', 'pdcld', 'wtrcld', 'icecld', 'ZSI', 'prec', 'qatm',
'pot_dens', 'salt']
#list of sequential variables to use for cmap
divergent_list = ['pot_temp', 'tsurf', 'w']
if var in sequential_list:
cmap = cm.Blues_r
norm = Normalize(vmin = min_val, vmax = max_val)
elif var in divergent_list:
cmap = cm.seismic
norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val)
"""KEEP EYE ON THIS. TRY OUT TO MAKE SURE IT WORKS W/ DIV CBARS"""
levels = 20
return cmap, norm, levels
cmap, norm, levels = make_cmap(var)
if plot_cbar:
#Create colorbar to be used and then wipe axis so cbar_data isn't actually plotted
cs_cbar = m.contourf(x, y, cbar_data, levels, ax=ax, cmap=cmap, norm=norm)
ax.clear()
cs = m.contourf(x, y, data, levels, ax=ax, cmap=cmap, norm=norm)
m.ax.tick_params(labelsize=2)
# m.colorbar(mappable=cs, ax=ax)
ax.set_title(title, fontsize=10)
if col_num==0:
ax.set_ylabel(ylabel, fontsize=10, labelpad = 60, rotation=0, verticalalignment ='center')
# draw parallels and meridians.
m.drawparallels([-60, -30, 0, 30, 60], labels=[1,0,0,0], ax = ax,
rotation=30, fontsize=8, linewidth=0)
m.drawmeridians([-135, -90, -45, 0, 45, 90, 135], labels=[0,0,0,1], ax = ax,
rotation=40, fontsize=8, linewidth=0)
def ContLines(m, ax, var, x, y, data):
if var == 'tsurf':
m.contour(x, y, data, ax=ax, levels = [0], colors=('k',),linestyles=('-.',),linewidths=(1,))
ContLines(m, ax, var, x, y, data)
if 'Aqua' not in title:
x1, y1 = m(meridians[0], parallels[0])
x2, y2 = m(meridians[0], parallels[1])
x3, y3 = m(meridians[1], parallels[1])
x4, y4 = m(meridians[1], parallels[0])
cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none',
edgecolor='black', linewidth=1)
ax.add_patch(cont_boundary)
if plot_cbar:
#Plot the colorbar on the final plot of the row
grid.cbar_axes[0].colorbar(cs_cbar)
def getDataAndMaxVal(col_list, filetype, var):
"""
Used to get data for a given row and the max value in order to have uniform colorbars across a row.
:param col_list:
:param var:
:return:
"""
data_list = []
for i in range(len(col_list)):
col = col_list[i]
filedir = col['filedir']
data = avgDataFiles(filedir, filetype, var)
data_list.append(data)
if i == 0:
min_val = np.min(data)
max_val = np.max(data)
else:
min_val = min(min_val, np.min(data))
max_val = max(max_val, np.max(data))
cbar_data = np.ones(shape = data.shape) * max_val # creates fake data w/ same shape to use for colorbar
cbar_data[0, 0] = min_val # sets one point in fake data to min_val so fake data has the entire spread
return data_list, cbar_data
def getSinglePlotName(row, col_list, filetype):
"""
If the plot is a single figure (one simulation),
then generate the filename automatically.
:param row:
:param col_list:
:param filetype:
:return:
"""
var_name = row['var']
if 'o' in filetype:
var_name = 'o_' + var_name
p_name = str(col_list[0]['SA'])+'p'
file_name = 'plots/{0}/{1}_vert_avg'.format(p_name, var_name)
return file_name
def rowMatrixMap(row, col_list, filetype):
fig = plt.figure(figsize = (14,6))
grid1 = ImageGrid(fig, 111,
nrows_ncols=(1, len(col_list)),
axes_pad=0.07,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="7%",
cbar_pad="7%",
aspect=True)
var = row['var']
data_list, cbar_data = getDataAndMaxVal(col_list, filetype, var)
print("MIN VAL: {0}, MAX VAL: {1}".format(np.min(cbar_data), np.max(cbar_data)))
for col_num in range(len(col_list)):
col = col_list[col_num]
print(col_num)
data = data_list[col_num]
if col_num == len(col_list) - 1:
plot_cbar = True
else:
plot_cbar = False
makeSubplot(data=data, var=var, cbar_data=cbar_data, grid=grid1,
col_num=col_num, ylabel=row['ylabel'], parallels=col['parallels'],
meridians=col['meridians'], title=col['title'] + ' Vertical Average',
plot_cbar=plot_cbar)
# fig.tight_layout(w_pad = 2.25)
if len(col_list) == 1:
file_name = getSinglePlotName(row, col_list, filetype)
else:
file_name = 'plots/manual'
print('PLOT NAME:', file_name)
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
# plt.show()
print('Done')
row = row_o_w
#col_list = [col_1]
col_outer_list = [col_0, col_1, col_4, col_6, col_11, col_22, col_26, col_34, col_39]
filetype = 'oijlpc'
# This is a makeshift loop to create these plots quickly, looping through all p's in the ocean
for col_out in col_outer_list:
col_list = [col_out]
rowMatrixMap(row, col_list, filetype)
<file_sep>/ROCKE_SS_stephanie.py
#encoding: utf-8
# SCRIPT TO GENERATE TIME SERIES OF GLOBALLY AVERAGED ROCKE-3D DATA
# User must specify runid and may need to modify the calendar settings.
## ***SPECIFY EXPERIMENT & ITS LOCATION ON MIDWAY***
runid = 'pc_proxcenb_aqua5L_TL_500yr'
rundirectory = '/project2/abbot/haynes/ROCKE3D_output/' + runid
## ***DEFINE TIME INTERVAL***
# NOTE: Change year_list for runs < 1 year.
startyear = 1950
endyear = 2440
#year_list = [1960, 1999]
year_list = range(startyear, endyear+1, 10)
## ***DEFINE THE CALENDAR***
# NOTE: month_list and month_per_year may need to be modified for planets with non-std. calendars.
# This is particularly likely for short orbital periods / tidally locked planets.
# The calendar for each experiment is reported in the .PRT file
month_list = ['D+J']
# month_list = ['D+J', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV']
month_per_year = 1
# PREPARE THE DATA FOR ANALYSIS (use GISS'scaleacc' diagnostic tool)
import subprocess
import os
os.chdir(rundirectory) #Switch on over to the run directory.
for y in year_list:
year = str(y)
for m in month_list:
month = str(m)
accfilename = month + year +'.acc' + runid + '.nc'
print(accfilename)
subprocess.call(["scaleacc", accfilename, 'aij']) #convert atmospheric output
# subprocess.call(["scaleacc", accfilename, 'oij']) #convert oceananic output
# ALLOCATE ARRAYS, ETC.
import numpy as np
# First, determine array size
total_months = len(month_list)*len(year_list)
# Create time arrays
time_months = np.linspace(0, total_months, total_months, endpoint=False)
time_years = time_months/month_per_year #convert to years. NOTE: this
# Create output arrays
global_rad = np.zeros((total_months,1)) #net radiation
global_ave_temp = np.zeros((total_months,1)) #temperature
global_snow_ice_cover = np.zeros((total_months,1))
global_ice_thickness = np.zeros((total_months,1))
# IMPORT THE DATA!
from netCDF4 import Dataset
i=0 #start the calendar counter
for y in year_list:
year = str(y)
for m in month_list:
month = str(m)
aijfilename = month + year +'.aij' + runid + '.nc'
#oijfilename = month + year +'.oij' + runid + '.nc'
# READ THE NETCDF FILES
atm_data=Dataset(aijfilename)
#ocn_data=Dataset(oijfilename)
# GET AREAS -- this could probably be moved outside of the for loop... but, is necessary for
grid_cell_area = atm_data['axyp'][:] #Area of each grid cell (m^2)
planet_area = sum(sum(grid_cell_area)) #Surface area of planet (m^2)
# NET RADIATION
net_rad = atm_data['net_rad_planet'][:] #Spatially resolved net radiation (W/m^2) from netcdf
tot_rad = sum(sum(net_rad*grid_cell_area)) #Total global radiation (W)
tot_rad = tot_rad/planet_area #Spread across planet's surface
global_rad[i]=tot_rad #Record globally averaged net radiation
# SURFACE TEMPERATURE
surf_temp = atm_data['tsurf'][:] #Spatially resolved surface temperature (C)
surf_temp_aw = sum(sum((surf_temp*grid_cell_area)))/planet_area #Area weighted global average surface temp.
global_ave_temp[i]=surf_temp_aw #Record the global average
# SNOW AND ICE COVERAGE
snow_ice_cover = atm_data['snowicefr'][:] #Spatially resolved snow/ice coverage (%)
snow_ice_area = sum(sum((snow_ice_cover*grid_cell_area))) #Snow and ice area (m2)
global_snow_ice_cover[i] = snow_ice_area/planet_area #Global snow and ice coverage (%)
# SEA ICE THICKNESS
sea_ice_thickness = atm_data['ZSI'][:] #Spatially resolved snow/ice coverage (%)
land = np.isnan(sea_ice_thickness)
ocean_area = planet_area - sum(grid_cell_area[land])
sea_ice_thickness[land] = 0
sea_ice_thickness_aw = sum(sum((sea_ice_thickness*grid_cell_area)))/ocean_area #Snow and ice area (m2)
global_ice_thickness[i] = sea_ice_thickness_aw
i=i+1 #advance the calendar counter.
# PRINT FINAL VALUE
#print 'The global net radiative is: '+ global_rad[-1] +' W/m^2'
#print 'The global average temperature is: '+ global_ave_temp[-1]+ ' C'
#print 'Snow and ice cover '+ glocal_snow_ice_cover[-1]+ '% of the globe'
import pandas as pd
# SAVE DATA TO FILE:
np.savetxt('radiation_ts.txt', global_rad)
np.savetxt('temperature_ts.txt', global_ave_temp)
np.savetxt('snow_ice_ts.txt', global_snow_ice_cover)
np.savetxt('ice_thickness_ts.txt', global_ice_thickness)
df = pd.DataFrame({'decade': np.arange(total_months), 'radiation': global_rad.reshape(total_months),
'temperature': global_ave_temp.reshape(total_months),
'snow_ice_cover': global_snow_ice_cover.reshape(total_months),
'ice_thickness': global_ice_thickness.reshape(total_months)})
df.to_csv('ts_data.csv')
os.system('rm *aij*')
<file_sep>/plot_scripts/matrixMaps.py
from mpl_toolkits.basemap import Basemap
from netCDF4 import Dataset as ds
import numpy as np
from matplotlib import pyplot as plt, cm as cm, ticker as ticker
from glob import glob
from matplotlib.patches import Polygon
from matplotlib.colors import Normalize
from cbar import MidPointNorm
from files_n_vars import *
from mpl_toolkits.axes_grid1 import make_axes_locatable, ImageGrid
def avgDataFiles(filedir, var, num_files = 10):
results = glob('{0}/*aijpc*'.format(filedir))
arr_tot = np.zeros((46,72))
for filename in results:
nc_i = ds(filename, 'r+', format='NETCDF4')
arr = nc_i[var][:]
arr_tot = arr_tot + arr
arr_avg = arr_tot / num_files
if 'aqua' in filedir:
arr_avg = np.roll(arr_avg, (arr_avg.shape[1]) // 2, axis=1)
return arr_avg
def makeSubplot(data, var, axes, row_num, col_num, ylabel, parallels, meridians, title):
ax = axes[row_num, col_num]
m = Basemap(ax = ax)
ny=data.shape[0]
nx=data.shape[1]
lons, lats = m.makegrid(nx, ny)
x, y = m(lons, lats)
min_val = np.min(data)
max_val = np.max(data)
def make_cmap(var):
sequential_list = ['frac_land', 'pscld', 'pdcld', 'snowicefr', 'lwp',
'pcldt', 'pscld', 'pdcld', 'wtrcld', 'icecld', 'ZSI', 'prec', 'qatm']
#list of sequential variables to use for cmap
if var in sequential_list:
cmap = cm.Blues_r
norm = Normalize(vmin = min_val, vmax = max_val)
else:
cmap = cm.seismic
norm = MidPointNorm(midpoint=0, vmin=min_val, vmax=max_val)
"""KEEP EYE ON THIS. TRY OUT TO MAKE SURE IT WORKS W/ DIV CBARS"""
levels = 20
return cmap, norm, levels
cmap, norm, levels = make_cmap(var)
plt.gca().patch.set_color('.25')
cs = m.contourf(x, y, data, levels, ax=ax, cmap=cmap, norm=norm)
m.ax.tick_params(labelsize=2)
cb = m.colorbar(mappable=cs, ax=ax)
tick_locator = ticker.MaxNLocator(nbins=5)
cb.locator = tick_locator
cb.update_ticks()
# draw parallels and meridians.
m.drawparallels([-60, -30, 0, 30, 60], labels=[1,0,0,0], ax = ax,
rotation=30, fontsize=8, linewidth=0)
m.drawmeridians([-135, -90, -45, 0, 45, 90, 135], labels=[0,0,0,1], ax = ax,
rotation=40, fontsize=8, linewidth=0)
def ContLines(m, ax, var, x, y, data):
if var == 'tsurf':
m.contour(x, y, data, ax=ax, levels = [0], colors=('k',),linestyles=('-.',),linewidths=(1,))
ContLines(m, ax, var, x, y, data)
if title != 'Aqua':
x1, y1 = m(meridians[0], parallels[0])
x2, y2 = m(meridians[0], parallels[1])
x3, y3 = m(meridians[1], parallels[1])
x4, y4 = m(meridians[1], parallels[0])
cont_boundary = Polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4)], facecolor='none',
edgecolor='black', linewidth=1)
ax.add_patch(cont_boundary)
if row_num==0:
ax.set_title(title, fontsize=10)
if col_num==0:
ax.set_ylabel(ylabel, fontsize=10, labelpad = 60, rotation=0, verticalalignment ='center')
def matrixMaps():
fig, axes = plt.subplots(len(row_list), len(col_list),
figsize = (10,5))
for row_num in range(len(row_list)):
row = row_list[row_num]
var = row['var']
for col_num in range(len(col_list)):
col = col_list[col_num]
print(row_num, col_num)
filedir=col['filedir']
data = avgDataFiles(filedir, var)
makeSubplot(data=data, var=var, axes=axes,
row_num=row_num, col_num=col_num, ylabel=row['ylabel'], parallels=col['parallels'],
meridians=col['meridians'], title=col['title'])
fig.tight_layout(w_pad = 2.25)
file_name = 'plots/row_matrix_test'
# plt.savefig(file_name+'.svg')
plt.savefig(file_name+'.pdf')
plt.show()
row_list = [row_tsurf, row_prec, row_qatm, row_pcldt]
col_list = [col_0, col_1, col_22, col_39]
matrixMaps()
<file_sep>/venv/lib/python3.6/site-packages/mplkit/plot.py
from matplotlib import cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import matplotlib.patheffects as PathEffects
import types
import numpy as np
import scipy.ndimage
from .cmap import ReversedColormap, WrappedColormap, InvertedColormap
__all__ = ['contour_image']
def contour_image(x,y,Z,
vmin=None,
vmax=None,
label=False,
contour_smoothing=1,
outline=None,
contour_opts={},
clabel_opts={},
imshow_opts={},
cguides=False,
cguide_tomax=True,
cguide_stride=1,
cguide_opts={}):
'''
This function wraps around matplotlib.pyplot.[imshow, contour, clabel, quiver] to
produce scientific plots with (potentially) labelled contours. All arguments
sported by these underlying methods can be passed using `<method>_opts`
respectively. In addition, this function adds the following options:
- vmax and vmin : None (default) or a numerical value. These replace the option
in the appropriate argument dictionary; for consistency across plotting calls.
- label : False (default) or True. Whether contour labels should be shown.
- contour_smoothing : 1 (default) or positive float; indicating scale of
contour resolution (<1 means fewer points, >1 means more interpolated points).
- outline : None (default), True, a colour (or colours), or a function mapping a RGBA colour to the
desired outline colour.
- cguides : False (default), True or list of contour values. If True, guides
are shown on every contour. Guides are arrows which point to regions of
greater value.
- cguide_tomax : True (default) or False : Whether guides point to regions of
greater (or lesser) value.
- cguide_stride : 1 (default), or positive integer : Specifies how often (i.e.
every `cguide_stride`) points the guides should be drawn.
- cguide_opts : dictionary of kwargs. Supports all kwargs of `quiver`.
This function returns the values of plt.imshow, plt.contour, and plt.clabel
in that order. If the function was not called, `None` is returned instead.
'''
ax = plt.gca()
x_delta = float((x[-1]-x[0]))/(len(x)-1)/2.
y_delta = float((y[-1]-y[0]))/(len(y)-1)/2.
extent=(x[0],x[-1],y[0],y[-1])
extent_delta = (x[0]-x_delta,x[-1]+x_delta,y[0]-y_delta,y[-1]+y_delta)
ax.set_xlim(x[0],x[-1])
ax.set_ylim(y[0],y[-1])
aspect=(x[-1]-x[0])/(y[-1]-y[0])
Z = Z.transpose()
if vmin is None:
vmin = np.min(Z)
if vmax is None:
vmax = np.max(Z)
# imshow plotting
imshow_cs = ax.imshow(Z,origin='lower',aspect='auto',extent=extent_delta,vmax=vmax,vmin=vmin, **imshow_opts)
# contour plotting
if contour_smoothing != 1:
Z = scipy.ndimage.zoom(Z, contour_smoothing)
if 'cmap' not in contour_opts:
contour_opts['cmap'] = InvertedColormap(imshow_cs.cmap)
elif 'cmap' in contour_opts and not isinstance(contour_opts['cmap'], WrappedColormap):
contour_opts['cmap'] = WrappedColormap(contour_opts['cmap'])
contour_cs = ax.contour(Z, extent=extent_delta, origin='lower', vmax=vmax,vmin=vmin, **contour_opts )
# outlining
if outline is True:
def outline(cvalue, vmin=0, vmax=1):
if contour_cs.cmap.luma(float(cvalue - vmin) / (vmax-vmin)) <= 0.5:
return (1,1,1,0.2)
return (0,0,0,0.2)
if type(outline) is types.FunctionType or isinstance(outline, colors.Colormap):
outline = [outline(c, vmin=vmin, vmax=vmax) for c in contour_cs.cvalues]
elif type(outline) is list:
pass
elif outline is None:
pass
else:
outline = [outline]*len(contour_cs.cvalues)
if outline is not None:
for i,collection in enumerate(contour_cs.collections):
plt.setp(collection, path_effects=[
PathEffects.withStroke(linewidth=3, foreground=outline[i])])
# clabel plotting
if label:
clabel_cs = ax.clabel(contour_cs, **clabel_opts)
if outline is not None:
for i,clbl in enumerate(clabel_cs):
plt.setp(clbl, path_effects=[
PathEffects.withStroke(linewidth=1.5, foreground=outline[np.argmin(np.abs(contour_cs.cvalues-float(clbl.get_text())))])])
else:
clabel_cs = None
# Draw guides on specified contours
if cguides is True:
cguides = contour_cs.cvalues
if cguides is not False:
_decorate_contour_segments(contour_cs, cguides, cguide_stride, vmin, vmax, cguide_opts, tomax=cguide_tomax, outline=outline, aspect=aspect)
return imshow_cs, contour_cs, clabel_cs
def _decorate_contour_segments(CS, cvalues, stride=1, vmin=0, vmax=1, options={}, tomax=True, outline=None, aspect=1):
for i,value in enumerate(cvalues):
options['color'] = CS.cmap(float(value - vmin) / (vmax-vmin))
for index in np.where(np.isclose(value, CS.cvalues))[0]:
for segment in CS.collections[index].get_segments():#for segment in CS.allsegs[index]:
_decorate_contour_segment(segment, stride=stride, options=options, tomax=tomax, labelled=hasattr(CS,'cl'), outline=outline[i] if outline is not None else None, aspect=aspect)
def _decorate_contour_segment(data, stride=1, options={}, tomax=True, labelled=False, outline=None, aspect=1):
default_options = {'scale': 0.2,
'scale_units': 'dots',
'headaxislength': 2,
'headlength': 2,
'headwidth': 2,
'minshaft': 1,
'units': 'dots',
#'angles': 'xy',
'edgecolor': outline,
'linewidth': 0 if outline is None else 0.2
}
default_options.update(options)
x = data[::stride,0]
y = data[::stride,1]
sign = 1 if tomax else -1
dx = -sign*np.diff(y)*aspect
dy = sign*np.diff(x)
l = np.sqrt(dx**2+dy**2)
dx /= l
dy /= l
x = 0.5*(x+np.roll(x,-1))
y = 0.5*(y+np.roll(y,-1))
if labelled:
x,y,dx,dy = x[1:-2], y[1:-2], dx[1:-1], dy[1:-1]
else:
x,y = x[:-1], y[:-1]
plt.quiver(x, y, dx, dy, **default_options)
<file_sep>/area.py
from math import sin, radians
def percent(lat1, lat2, lon1, lon2):
"""
Return the percent of surface area covered between the coordinates.
:param lat1: First latitude coordinate (degrees)
:param lat2: Second latitude coordinate (degrees)
:param lon1: First longitude coordinate (degrees)
:param lon2: Second longitude coordinate (degrees)
:return: Percent coverage of surface area (%)
"""
lat1_rad = radians(lat1)
lat2_rad = radians(lat2)
area_tot = 4
area_grid = (abs(sin(lat1_rad) - sin(lat2_rad)) * abs(lon1 - lon2)) / 180
percent = area_grid / area_tot
return percent
| b84ccd1ea70714c0f4ad67b687bed377f80e2566 | [
"Python"
] | 22 | Python | HaynesStephens/year1project | 2e6e820ab413b51975a932c7add88077c0ad7199 | da8762371ae669fcea15ee2d9cc99746a2715027 |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
module MailConfig
DB_HOST = "localhost"
DB_USER = "root"
DB_PASS = ""
DB_DB = "mailserver"
end
<file_sep>create table domain_admins (
domain_id integer references virtual_domains(id),
user_id integer references virtual_users(id),
primary key(domain_id, user_id)
);
alter table virtual_users add column super_admin boolean default false;
<file_sep>function showSelectedDomain(id) {
if(parseInt(id) <= 0) return false;
window.location.href = "domain/" + id;
}
<file_sep>#!/usr/bin/env ruby
require 'mysql'
require 'digest/md5'
require_relative 'config'
require_relative 'classes'
class Connection
def initialize
@con = Mysql::real_connect(
MailConfig::DB_HOST,
MailConfig::DB_USER,
MailConfig::DB_PASS,
MailConfig::DB_DB
)
end
def close
@con.close if @con
end
def authenticate(email, password)
if email.nil? || email.empty? || password.nil? || password.empty?
return false
end
q = @con.query(
"select id, password from virtual_users where email = '%s';" %
@con.escape_string(email))
id, hash = q.fetch_row
return false unless id
if Digest::MD5.hexdigest(password) == hash
return id
end
return false
end
def login_exists?(lh, domain)
q = @con.query("select count(*) from virtual_users where email = '%s'" %
@con.escape_string("#{lh}@#{domain.name}") )
return q.fetch_row.first.to_i > 0
end
def update_password(id, password)
@con.query("update virtual_users set password = '%s' where id = %d;" %
[ Digest::MD5.hexdigest(password), id ])
end
def get_user(id)
q = @con.query(
"select virtual_users.*, virtual_domains.id as admin_domain_id,
virtual_domains.name as admin_domain_name
from virtual_users
left join domain_admins on virtual_users.id = domain_admins.user_id
left join virtual_domains on domain_admins.domain_id = virtual_domains.id
or virtual_users.super_admin
where virtual_users.id = %d order by admin_domain_name desc;" % id)
user = nil
while row = q.fetch_hash
if user.nil?
user = User.new
user.id = row['id']
user.email = row['email']
user.password = row['<PASSWORD>']
user.domain_id = row['domain_id']
user.super_admin = row['super_admin'] == "1"
user.admin_domains = {}
end
if row['admin_domain_id']
domain = Domain.new
domain.id = row['admin_domain_id']
domain.name = row['admin_domain_name']
user.admin_domains[domain.id] = domain
end
end
return user
end
def add_user(lh, domain, password, admin_domains, super_admin)
email = @con.escape_string("#{lh}@#{domain.name}")
@con.query("insert into virtual_users values(NULL, %d, '%s', '%s', %d)" %
[ domain.id, Digest::MD5.hexdigest(password), email, super_admin ? 1 : 0 ])
if admin_domains && admin_domains.length > 0
id = insert_id
admin_domains.each do |did|
@con.query("insert into domain_admins values(%d, %d)" % [ did, id ])
end
end
@con.query("insert into virtual_aliases values(NULL, %d, '%s', '%s')" %
[ domain.id, email, email ])
end
def update_user(uid, password, admin_domains, super_admin)
if password.nil? or password.empty?
password = "<PASSWORD>"
else
password = "'%s'" % Digest::MD5.<PASSWORD>(password)
end
sa = super_admin ? 1 : 0
@con.query("update virtual_users set password = %s, super_admin = %d
where id = %d;" % [ password, sa, uid ])
=begin
TODO by deleting all the existing admin info, we disallow 2 admins with
access to 2 different domains the ability to give the same user access
to domains the other can't see -- it'll delete ones that "I" can't check.
=end
@con.query("delete from domain_admins where user_id = %d;" % uid)
sql = nil
admin_domains.each do |did|
(sql ||= "insert into domain_admins values") << " (#{did}, #{uid}),"
end
@con.query(sql.gsub(/,$/, '')) unless sql.nil?
end
def delete_user(uid)
user = get_user(uid)
@con.query("delete from domain_admins where user_id = %d" % uid)
@con.query("delete from virtual_aliases where destination = '%s'" %
@con.escape_string(user.email))
@con.query("delete from virtual_users where id = %d" % uid)
end
def domain_users(domain)
q = @con.query("select virtual_users.*, domain_admins.domain_id as is_admin
from virtual_users left join domain_admins
on virtual_users.domain_id = domain_admins.domain_id
and domain_admins.user_id = virtual_users.id
where virtual_users.domain_id = %d order by email asc" % domain.id)
ret = []
while row = q.fetch_hash
user = User.new
user.id = row['id']
user.email = row['email']
user.admin_domains = [ row['is_admin'] ]
ret << user
end
return ret
end
def domain_aliases(domain)
q = @con.query("select * from virtual_aliases
where domain_id = %d and source != destination order by source asc" % domain.id)
ret = []
while row = q.fetch_hash
a = Alias.new
a.id = row['id']
a.source = row['source']
a.destination = row['destination']
ret << a
end
return ret
end
def add_domain(name, uid)
@con.query("insert into virtual_domains values(NULL, '%s');" %
@con.escape_string(name))
id = insert_id
@con.query("insert into domain_admins values(%d, %d);" % [ id, uid ])
end
def delete_domain(id)
@con.query("delete from virtual_users where domain_id = %d;" % id)
@con.query("delete from virtual_aliases where domain_id = %d;" % id)
@con.query("delete from domain_admins where domain_id = %d;" % id)
@con.query("delete from virtual_domains where id = %d;" % id)
end
def get_alias(aid)
q = @con.query("select * from virtual_aliases where id = %d" % aid)
ret = nil
if row = q.fetch_hash
ret = Alias.new
ret.id = row['id']
ret.source = row['source']
ret.destination = row['destination']
ret.domain_id = row['domain_id']
end
return ret
end
def get_alias_by_name(name, field = :src)
f = field == :src ? "source" : "destination"
q = @con.query("select id from virtual_aliases where %s = '%s'" %
[ f, @con.escape_string(name) ])
return row[0] if row = q.fetch_row
return nil
end
def add_alias(src_domain, src, dst)
@con.query("insert into virtual_aliases values (NULL, %d, '%s', '%s')" %
[ src_domain.id, @con.escape_string(src), @con.escape_string(dst) ])
end
def delete_alias(aid)
@con.query("delete from virtual_aliases where id = %d" % aid)
end
def insert_id
@con.query("select last_insert_id()").fetch_row.first
end
end
| 9fc37e49085006fdf3d4d2e4d58f548268d85805 | [
"JavaScript",
"SQL",
"Ruby"
] | 4 | Ruby | duckdalbe/mailadmin | d360d82d0cb75a371e628850ef8e7ac3bfc2a056 | d53293d9560dad66404af2f75b9d84fb2362895e |
refs/heads/master | <file_sep>#!/usr/bin/env bash
bundle exec jekyll serve --config _config.yml,_config_lip6.yml
<file_sep>#!/usr/bin/env bash
bundle exec jekyll serve --config _config.yml,_config_github.yml
<file_sep># arthurcharpentier.github.io
[Web site](http://arthurcharpentier.github.io)
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="Associate Professor<br/> Université Rennes 1">
<meta name="author" content="<NAME>">
<title>teaching</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="/css/main.css">
<!-- OLD TODO : remove
<link rel="canonical" href="http://pascalpoizat.github.io/teaching/">
-->
<link rel="canonical" href="http://freakonometrics.github.io/teaching/">
<!-- Font Awesome -->
<link rel="stylesheet" href="/font-awesome-4.5.0/css/font-awesome.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- management of blocked Javascript -->
<noscript>
<style> .ifjavascript {
display: none
} </style>
</noscript>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar"
aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/index.html">pascal.poizat</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li >
<a class="navbar-link" href="/index.html">home</a>
</li>
<li class="active">
<a class="navbar-link" href="/teaching/">teaching</a>
</li>
<li >
<a class="navbar-link" href="/research/">research</a>
</li>
<li >
<a class="navbar-link" href="/duties/">duties</a>
</li>
<li >
<a class="navbar-link" href="/bio/">bio</a>
</li>
<li >
<a class="navbar-link" href="/contact/">contact</a>
</li>
<li >
<a class="navbar-link" href="/blog/">blog</a>
</li>
<!--
<li>
<a class="navbar-link" href="/index.html#contact">contact</a>
</li>
-->
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1>Teaching</h1>
</div>
<div class="row">
<div class="col-md-6">
<h2><span class="text-primary">Currently</span></h2>
<div class="bs-callout bs-callout-danger">
<h4><i class="glyphicon glyphicon-exclamation-sign"></i> Supports pédagogiques</h4>
<p class="text-justify">
Il y a des probablement des coquillettes (voire de vraies erreurs) dans mes notes de cours et mes transparents.
N'hésitez pas à m'envoyer un courriel pour toute amélioration possible.
</p>
</div>
<dl class="dl-horizontal">
<dt>
ENSAE <br/>
</dt>
<dd>
<strong><span class="text-primary">Assurance Dommage</span></strong><br/>
<em>3rd year, Acturial Science</em><br/>
Non-life insurance mathematics <br/>
<a href="http://freakonometrics.free.fr/ENSAE-slides1.pdf">Introduction and Overview</a> <br/>
<a href="http://freakonometrics.free.fr/ENSAE-slides2.pdf">Ratemaking</a> <br/>
<a href="http://freakonometrics.free.fr/ENSAE-slides3.pdf">Claims Reserving</a> <br/>
lectures + practical work
<i class="glyphicon glyphicon-hand-right"></i> <a href="http://ensae.fr/ensae/fr/">ENSAE</a><br/>
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
PhD <br/>
</dt>
<dd>
<strong><span class="text-primary">Advanced Econometrics</span></strong><br/>
<em>PhD and Graduate Course</em><br/>
Advanced Techniques for Econometrics <br/>
<a href="http://freakonometrics.free.fr/econometrics-2017-graduate-1.pdf">Nonlinearities and Smoothing Techniques</a> <br/>
<a href="http://freakonometrics.free.fr/econometrics-2017-graduate-2.pdf">Simulations and Bootstrap</a> <br/>
<a href="http://freakonometrics.free.fr/econometrics-2017-graduate-3.pdf">Model and Variable Selection</a> <br/>
<a href="http://freakonometrics.free.fr/econometrics-2017-graduate-4.pdf">Quantiles and Expectiles</a> <br/>
lectures
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
M1 Magistere<br/>
</dt>
<dd>
<strong><span class="text-primary">Méthodes de simulation et modélisation économique</span></strong><br/>
<em>1st year of master</em><br/>
.... <br/>
lectures + practical work
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
M1 Public Economics<br/>
</dt>
<dd>
<strong><span class="text-primary">Probability and Statistics </span></strong><br/>
<em>1st year of master 'Economie et Management Publique'</em><br/>
'Ingénierie, Management et Evaluation des Politiques Publiques' <br/>
lectures + practical work
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
M1 Data Science<br/>
</dt>
<dd>
<strong><span class="text-primary">UE1 Machine Learning </span></strong><br/>
<em>1st year of master 'Data Science'</em><br/>
<br/>
lectures + practical work
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
M1 Data Science<br/>
</dt>
<dd>
<strong><span class="text-primary">UE4 Yield Management et tourisme </span></strong><br/>
<em>1st year of master 'Data Science'</em><br/>
<br/>
lectures + practical work
</dd>
</dl>
<dl class="dl-horizontal">
<dt>
M1 Data Science<br/>
</dt>
<dd>
<strong><span class="text-primary">UE5 Méthodes de prévisions avancées </span></strong><br/>
<em>1st year of master 'Data Science'</em><br/>
<br/>
lectures + practical work
</dd>
</dl>
</div>
<div class="col-md-6">
<h2><span class="text-primary">Before</span></h2><br/>
<p><strong><span class="text-primary">Statistics</span></strong><br/>
Université Rennes 1, Université St Joseph (Beyrut, Lebanon), Université d'Ho-Chi-Minh (Ho Chi Minh Ville, Vietnam)
</p>
<p><strong><span class="text-primary">Probability</span></strong><br/>
xx UQAM (ACT2121),
</p>
<p><strong><span class="text-primary">Markov Chains and Processes</span></strong><br/>
xxx ENSAI (<a href="http://freakonometrics.free.fr/pdf">pdf</a>), ISUP (Institut de Statistique de l'Université de Paris)
</p>
<p><strong><span class="text-primary">Data Mining and Multivariate Models</span></strong><br/>
xxxx Université Rennes 1 (Master 'Statistique et Econométrie'),
</p>
<p><strong><span class="text-primary">Time Series</span></strong><br/>
Université Rennes 1 (Master 'Statistique et Econométrie'), UQAM (MAT8181),
</p>
<p><strong><span class="text-primary">Predictive Models</span></strong><br/>
xxxx UQAM (ACT6420, <a href="http://freakonometrics.free.fr/pdf">pdf</a>)
</p>
<p><strong><span class="text-primary">Econometrics</span></strong><br/>
xxxx Université Rennes 1 (Master 'Statistique et Econométrie'),
</p>
<p><strong><span class="text-primary">Numerical Techniques in Finance</span></strong><br/>
xxxx Université Rennes 1 (Master 'Ingénierie Financière'),
</p>
<p><strong><span class="text-primary">Asset Pricing</span></strong><br/>
xxxx Ecole Polytechnique (avec <NAME>)
</p>
<p><strong><span class="text-primary">Non-Life Insurance</span></strong><br/>
xxxx Université Rennes 1 (Master 'Statistique et Econométrie'), ENSEA (Abidjan, Ivory Coast), ENSAE (Rabbat, Marroco)
</p>
<p><strong><span class="text-primary">Extreme Values and Reinsurance</span></strong><br/>
ENSAE, Université Paris Dauphine, Université Paris I Sorbonne
</p>
<p><strong><span class="text-primary">Copulas</span></strong><br/>
xxxx Université Paris Dauphine
</p>
<p><strong><span class="text-primary">Risk Measures and Economics of Uncertainty</span></strong><br/>
xxxx Université Louvain-la-Neuve (PhD Crash Course, <a href="http://freakonometrics.free.fr/pdf">pdf</a>)
</p>
<p><strong><span class="text-primary">Microeconomics</span></strong><br/>
xxxx Ecole Polytechnique
</p>
</div>
</div>
</div>
<div class="navbar navbar-default navbar-bottom">
<div class="container">
<h4>pascal.poizat</h4>
<div class="row">
<div class="col-md-4">
<p>Maĩtre de Conférences<br/> Université Rennes 1
</p>
</div>
<div class="col-md-3">
<p>
<a href="mailto:<EMAIL>">
<EMAIL>
</a><br/>
<i class="fa fa-github"></i>
<a href="https://freakonometrics.hypotheses.org">
freakonometrics
</a><br/>
<i class="fa fa-twitter"></i>
<a href="https://twitter.com/freakonometrics">
freakonometrics
</a><br/>
</p>
</div>
<div class="col-md-3">
<p>
<i class="fa fa-github-alt"></i>
<a href="https://github.com/freakonometrics">
freakonometrics
</a><br/>
<i class="fa fa-slideshare"></i>
<a href="https://www.slideshare.net/charthur">
charthur
</a><br/>
<i class="fa fa-linkedin"></i>
<a href="https://www.linkedin.com/in/arthurcharpentier/">
<NAME>
</a><br/>
</p>
</div>
</div>
<div class="footer-col-wrapper">
<div class="footer-col-thanks">
<p>
pages made with <a href="http://jekyllrb.com">Jekyll</a>,
<a class="button" href="http://github.com/freakonometrics/freakonometrics.github.io">
<button class="btn btn-xs btn-primary"><i
class="fa fa-download"></i> get source code
</button>
</a>
</p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/javascripts/bootstrap.min.js"></script>
</body>
</html>
| 6c62abcf29373957b9da221ed16d9813ca2aa6c5 | [
"Markdown",
"HTML",
"Shell"
] | 4 | Shell | freakonometrics/arthurcharpentier | f01c55cc177668f5a763dd223f3dba3cf8c203de | a1e6b68d2863a1ea22f9c0f2535e9d29ed9329a1 |
refs/heads/main | <file_sep># ShenwuAutopilot
A little tool to help my character in Shenwu grow by himself without me tapping on the phone
Goals:
1. Automatically login to game when guild banquet event starts and claim rewards.
notes: a. Adjust for daylight saving time caused 1hr difference local time(EST) against server time(UTC+8).
b. Set desktop to start automatically in the morning.
1.5 Solve the problem of randomly popped simple Turing test
restock before all events
2. faction practices(Turing test)
3. treasure map quests, and find the treasures afterwards
4. Silk Road
5. heroic trails
6. Activate monster coil and do 20 symbol encounters(Turing test)
7. Interactive - gather 4 people and do exorcism requests
8. Interactive - gather 4 people in guild and do monster invasion on 12:00 p.m.(UTC+8)
9. Repeatedly fill the Alchemy pot, buy cards and generate shards if not enough is held
10. Daily companion quests, need to add each story separately
11. Daily quiz event (How to make it learn by itself without manually adding quiz database?)
12. Home gardening, plant, and harvest
13. Interactive - gather 4 people and run raid dungeon, add option to specify which dungeon
restock at home upon finish
after claiming action points, send out invites and claim
Manual contents:
- offline pvp ranked match
- weekly treasure hunt
- share the game and claim reward (not supported on windows client app)
- daily hardcore pve boss
Some useful function blocks:
- change starting familiar
- inventory management - automatic banking at home
- quick purchase from shop
- map movement
<file_sep>import cv2
import numpy as np
if __name__ == "__main__":
test_img = cv2.imread('detection_test.png', cv2.IMREAD_UNCHANGED)
served_table_img = cv2.imread('served_table.png', cv2.IMREAD_UNCHANGED)
sample_button_img = cv2.imread('sample_button.png', cv2.IMREAD_UNCHANGED)
#TODO: the served_table image is contaminated by the cursor and needs an update
# cv2.imshow('Served Table', served_table_img)
# cv2.waitKey()
# cv2.destroyAllWindows()
# cv2.imshow('button', sample_button_img)
# cv2.waitKey()
# cv2.destroyAllWindows()
match_result = cv2.matchTemplate(test_img, served_table_img, cv2.TM_CCOEFF_NORMED)
# cv2.imshow("match res", match_result)
# cv2.waitKey()
# cv2.destroyAllWindows()
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(match_result)
print(max_loc)
print(min_loc)
print(min_val)
print(max_val)
w, h = served_table_img.shape[1], served_table_img.shape[0]
cv2.rectangle(test_img, max_loc, (max_loc[0]+w, max_loc[1]+h), (0,255,255), 2)
cv2.imshow('test', test_img)
cv2.waitKey()
threshold = 0.85
yloc, xloc = np.where(match_result > threshold)
print(len(xloc))
print(len(yloc))
for(x, y) in zip(xloc, yloc):
cv2.rectangle(test_img, (x,y), (x+w, y+h), (0,255,255),2)
rectangles = []
for(x, y) in zip(xloc, yloc):
rectangles.append([int(x),int(y),int(w),int(h)])
rectangles.append([int(x),int(y),int(w),int(h)])
print(len(rectangles))
rectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)
print(len(rectangles))
for(x, y, w, h) in rectangles:
cv2.rectangle(test_img, (x,y), (x+w, y+h), (0,255,255),2)
cv2.imshow('test', test_img)
cv2.waitKey() | 65ee0d70c8cfd4b208fd476a01a3828092e55a7d | [
"Markdown",
"Python"
] | 2 | Markdown | Kita11911/ShenwuAutopilot | f60c5921ded109204f4856d2db104d11afe344a8 | eb56be6c951207c7af32e2dd3fe0b9228fa4b3d7 |
refs/heads/master | <file_sep>/* OpenSceneGraph example, osgprerendercubemap.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osgViewer/Viewer>
#include <osg/Projection>
#include <osg/Geometry>
#include <osg/Texture>
#include <osg/TexGen>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/TextureCubeMap>
#include <osg/TexMat>
#include <osg/MatrixTransform>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/PolygonOffset>
#include <osg/CullFace>
#include <osg/Material>
#include <osg/PositionAttitudeTransform>
#include <osg/ArgumentParser>
#include <osg/Camera>
#include <osg/TexGenNode>
#include <iostream>
using namespace osg;
ref_ptr<Group> _create_scene()
{
ref_ptr<Group> scene = new Group;
ref_ptr<Geode> geode_1 = new Geode;
scene->addChild(geode_1.get());
ref_ptr<Geode> geode_2 = new Geode;
ref_ptr<MatrixTransform> transform_2 = new MatrixTransform;
transform_2->addChild(geode_2.get());
transform_2->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(45.0f)));
scene->addChild(transform_2.get());
ref_ptr<Geode> geode_3 = new Geode;
ref_ptr<MatrixTransform> transform_3 = new MatrixTransform;
transform_3->addChild(geode_3.get());
transform_3->setUpdateCallback(new osg::AnimationPathCallback(Vec3(0, 0, 0), Y_AXIS, inDegrees(-22.5f)));
scene->addChild(transform_3.get());
const float radius = 0.8f;
const float height = 1.0f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ref_ptr<ShapeDrawable> shape;
shape = new ShapeDrawable(new Box(Vec3(0.0f, -2.0f, 0.0f), 10, 0.1f, 10), hints.get());
shape->setColor(Vec4(0.5f, 0.5f, 0.7f, 1.0f));
geode_1->addDrawable(shape.get());
shape = new ShapeDrawable(new Sphere(Vec3(-3.0f, 0.0f, 0.0f), radius), hints.get());
shape->setColor(Vec4(0.6f, 0.8f, 0.8f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(3.0f, 0.0f, 0.0f), 2 * radius), hints.get());
shape->setColor(Vec4(0.4f, 0.9f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cone(Vec3(0.0f, 0.0f, -3.0f), radius, height), hints.get());
shape->setColor(Vec4(0.2f, 0.5f, 0.7f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Cylinder(Vec3(0.0f, 0.0f, 3.0f), radius, height), hints.get());
shape->setColor(Vec4(1.0f, 0.3f, 0.3f, 1.0f));
geode_2->addDrawable(shape.get());
shape = new ShapeDrawable(new Box(Vec3(0.0f, 3.0f, 0.0f), 2, 0.1f, 2), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.4f, 1.0f));
geode_3->addDrawable(shape.get());
// material
ref_ptr<Material> matirial = new Material;
matirial->setColorMode(Material::DIFFUSE);
matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1));
matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
matirial->setShininess(Material::FRONT_AND_BACK, 64.0f);
scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON);
return scene;
}
osg::NodePath createReflector()
{
osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform;
pat->setPosition(osg::Vec3(0.0f,0.0f,0.0f));
pat->setAttitude(osg::Quat(osg::inDegrees(0.0f),osg::Vec3(0.0f,0.0f,1.0f)));
Geode* geode_1 = new Geode;
pat->addChild(geode_1);
const float radius = 0.8f;
ref_ptr<TessellationHints> hints = new TessellationHints;
hints->setDetailRatio(2.0f);
ShapeDrawable* shape = new ShapeDrawable(new Sphere(Vec3(0.0f, 0.0f, 0.0f), radius * 1.5f), hints.get());
shape->setColor(Vec4(0.8f, 0.8f, 0.8f, 1.0f));
geode_1->addDrawable(shape);
osg::NodePath nodeList;
nodeList.push_back(pat);
nodeList.push_back(geode_1);
return nodeList;
}
class UpdateCameraAndTexGenCallback : public osg::NodeCallback
{
public:
typedef std::vector< osg::ref_ptr<osg::Camera> > CameraList;
UpdateCameraAndTexGenCallback(osg::NodePath& reflectorNodePath, CameraList& Cameras):
_reflectorNodePath(reflectorNodePath),
_Cameras(Cameras)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into position
traverse(node,nv);
// compute the position of the center of the reflector subgraph
osg::Matrixd worldToLocal = osg::computeWorldToLocal(_reflectorNodePath);
osg::BoundingSphere bs = _reflectorNodePath.back()->getBound();
osg::Vec3 position = bs.center();
typedef std::pair<osg::Vec3, osg::Vec3> ImageData;
const ImageData id[] =
{
ImageData( osg::Vec3( 1, 0, 0), osg::Vec3( 0, -1, 0) ), // +X
ImageData( osg::Vec3(-1, 0, 0), osg::Vec3( 0, -1, 0) ), // -X
ImageData( osg::Vec3( 0, 1, 0), osg::Vec3( 0, 0, 1) ), // +Y
ImageData( osg::Vec3( 0, -1, 0), osg::Vec3( 0, 0, -1) ), // -Y
ImageData( osg::Vec3( 0, 0, 1), osg::Vec3( 0, -1, 0) ), // +Z
ImageData( osg::Vec3( 0, 0, -1), osg::Vec3( 0, -1, 0) ) // -Z
};
for(unsigned int i=0;
i<6 && i<_Cameras.size();
++i)
{
osg::Matrix localOffset;
localOffset.makeLookAt(position,position+id[i].first,id[i].second);
osg::Matrix viewMatrix = worldToLocal*localOffset;
_Cameras[i]->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
_Cameras[i]->setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0);
_Cameras[i]->setViewMatrix(viewMatrix);
}
}
protected:
virtual ~UpdateCameraAndTexGenCallback() {}
osg::NodePath _reflectorNodePath;
CameraList _Cameras;
};
class TexMatCullCallback : public osg::NodeCallback
{
public:
TexMatCullCallback(osg::TexMat* texmat):
_texmat(texmat)
{
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
// first update subgraph to make sure objects are all moved into position
traverse(node,nv);
osgUtil::CullVisitor* cv = dynamic_cast<osgUtil::CullVisitor*>(nv);
if (cv)
{
osg::Quat quat = cv->getModelViewMatrix()->getRotate();
_texmat->setMatrix(osg::Matrix::rotate(quat.inverse()));
}
}
protected:
osg::ref_ptr<TexMat> _texmat;
};
osg::Group* createShadowedScene(osg::Node* reflectedSubgraph, osg::NodePath reflectorNodePath, unsigned int unit, const osg::Vec4& clearColor, unsigned tex_width, unsigned tex_height, osg::Camera::RenderTargetImplementation renderImplementation)
{
osg::Group* group = new osg::Group;
osg::TextureCubeMap* texture = new osg::TextureCubeMap;
texture->setTextureSize(tex_width, tex_height);
texture->setInternalFormat(GL_RGB);
texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
texture->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
texture->setFilter(osg::TextureCubeMap::MIN_FILTER,osg::TextureCubeMap::LINEAR);
texture->setFilter(osg::TextureCubeMap::MAG_FILTER,osg::TextureCubeMap::LINEAR);
// set up the render to texture cameras.
UpdateCameraAndTexGenCallback::CameraList Cameras;
for(unsigned int i=0; i<6; ++i)
{
// create the camera
osg::Camera* camera = new osg::Camera;
camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
camera->setClearColor(clearColor);
// set viewport
camera->setViewport(0,0,tex_width,tex_height);
// set the camera to render before the main camera.
camera->setRenderOrder(osg::Camera::PRE_RENDER);
// tell the camera to use OpenGL frame buffer object where supported.
camera->setRenderTargetImplementation(renderImplementation);
// attach the texture and use it as the color buffer.
camera->attach(osg::Camera::COLOR_BUFFER, texture, 0, i);
// add subgraph to render
camera->addChild(reflectedSubgraph);
group->addChild(camera);
Cameras.push_back(camera);
}
// create the texgen node to project the tex coords onto the subgraph
osg::TexGenNode* texgenNode = new osg::TexGenNode;
texgenNode->getTexGen()->setMode(osg::TexGen::REFLECTION_MAP);
texgenNode->setTextureUnit(unit);
group->addChild(texgenNode);
// set the reflected subgraph so that it uses the texture and tex gen settings.
{
osg::Node* reflectorNode = reflectorNodePath.front();
group->addChild(reflectorNode);
osg::StateSet* stateset = reflectorNode->getOrCreateStateSet();
stateset->setTextureAttributeAndModes(unit,texture,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
stateset->setTextureMode(unit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
osg::TexMat* texmat = new osg::TexMat;
stateset->setTextureAttributeAndModes(unit,texmat,osg::StateAttribute::ON);
reflectorNode->setCullCallback(new TexMatCullCallback(texmat));
}
// add the reflector scene to draw just as normal
group->addChild(reflectedSubgraph);
// set an update callback to keep moving the camera and tex gen in the right direction.
group->setUpdateCallback(new UpdateCameraAndTexGenCallback(reflectorNodePath, Cameras));
return group;
}
int main(int argc, char** argv)
{
// use an ArgumentParser object to manage the program arguments.
ArgumentParser arguments(&argc, argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName() + " is the example which demonstrates using of GL_ARB_shadow extension implemented in osg::Texture class");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
arguments.getApplicationUsage()->addCommandLineOption("-h or --help", "Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--fb","Use FrameBuffer for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.");
arguments.getApplicationUsage()->addCommandLineOption("--window","Use a separate Window for render to texture.");
arguments.getApplicationUsage()->addCommandLineOption("--width","Set the width of the render to texture");
arguments.getApplicationUsage()->addCommandLineOption("--height","Set the height of the render to texture");
// construct the viewer.
osgViewer::Viewer viewer;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
unsigned tex_width = 256;
unsigned tex_height = 256;
while (arguments.read("--width", tex_width)) {}
while (arguments.read("--height", tex_height)) {}
osg::Camera::RenderTargetImplementation renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT;
while (arguments.read("--fbo")) { renderImplementation = osg::Camera::FRAME_BUFFER_OBJECT; }
while (arguments.read("--pbuffer")) { renderImplementation = osg::Camera::PIXEL_BUFFER; }
while (arguments.read("--fb")) { renderImplementation = osg::Camera::FRAME_BUFFER; }
while (arguments.read("--window")) { renderImplementation = osg::Camera::SEPERATE_WINDOW; }
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occurred when parsing the program arguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
ref_ptr<MatrixTransform> scene = new MatrixTransform;
scene->setMatrix(osg::Matrix::rotate(osg::DegreesToRadians(125.0),1.0,0.0,0.0));
ref_ptr<Group> reflectedSubgraph = _create_scene();
if (!reflectedSubgraph.valid()) return 1;
ref_ptr<Group> reflectedScene = createShadowedScene(reflectedSubgraph.get(), createReflector(), 0, viewer.getCamera()->getClearColor(),
tex_width, tex_height, renderImplementation);
scene->addChild(reflectedScene.get());
viewer.setSceneData(scene.get());
return viewer.run();
}
<file_sep>
#include <osg/Node>
#include <osg/PositionAttitudeTransform>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/AnimationPathManipulator>
#include <osg/StateSet>
#include <osg/TextureCubeMap>
#include <osg/TexGen>
#include <osg/Point>
#include <osg/TexEnvCombine>
#include <osgUtil/ReflectionMapGenerator>
#include <osgUtil/HighlightMapGenerator>
#include <osgUtil/HalfWayMapGenerator>
#include <iostream>
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <pcl/ros/conversions.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <sensor_msgs/PointCloud2.h>
unsigned int g_targetNumVerticesPerGeometry = 10000;
bool g_mirror = true;
osg::Node* pointCloud2Geode(const pcl::PointCloud<pcl::PointXYZRGB> & cloud)
{
osg::Geode* geode = new osg::Geode;
osg::Geometry* geometry = new osg::Geometry;
osg::Vec3Array* vertices = new osg::Vec3Array;
osg::Vec3Array* normals = new osg::Vec3Array;
osg::Vec4ubArray* colours = new osg::Vec4ubArray;
osg::Vec3 pos;
osg::Vec3 normal(0.0,0.0,1.0);
int r=255,g=255,b=255,a=255;
for(unsigned int i=0; i<cloud.points.size(); ++i)
{
pos.set(g_mirror?-cloud.points.at(i).x:cloud.points.at(i).x, -cloud.points.at(i).y, -cloud.points.at(i).z);
// unpack rgb into r/g/b
uint32_t rgb = *reinterpret_cast<const int*>(&cloud.points.at(i).rgb);
r = (rgb >> 16) & 0x0000ff;
g = (rgb >> 8) & 0x0000ff;
b = (rgb) & 0x0000ff;
if (vertices->size()>=g_targetNumVerticesPerGeometry)
{
// finishing setting up the current geometry and add it to the geode.
geometry->setUseDisplayList(false);
geometry->setUseVertexBufferObjects(false);
geometry->setVertexArray(vertices);
geometry->setNormalArray(normals);
geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
geometry->setColorArray(colours);
geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
geometry->addPrimitiveSet(new osg::DrawArrays(GL_POINTS,0,vertices->size()));
geometry->getOrCreateStateSet()->setAttribute(new osg::Point(5.0f), osg::StateAttribute::ON);
geode->addDrawable(geometry);
// allocate a new geometry
geometry = new osg::Geometry;
vertices = new osg::Vec3Array;
normals = new osg::Vec3Array;
colours = new osg::Vec4ubArray;
vertices->reserve(g_targetNumVerticesPerGeometry);
normals->reserve(g_targetNumVerticesPerGeometry);
colours->reserve(g_targetNumVerticesPerGeometry);
}
vertices->push_back(pos);
normals->push_back(normal);
colours->push_back(osg::Vec4ub(r,g,b,a));
}
geometry->setUseDisplayList(false);
geometry->setUseVertexBufferObjects(false);
geometry->setVertexArray(vertices);
geometry->setNormalArray(normals);
geometry->setNormalBinding(osg::Geometry::BIND_PER_VERTEX);
geometry->setColorArray(colours);
geometry->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
geometry->addPrimitiveSet(new osg::DrawArrays(GL_POINTS,0,vertices->size()));
geode->addDrawable(geometry);
return geode;
}
osg::Node * createCoordinate(double size = 0.05) // 5 cm
{
osg::Geode * geode = new osg::Geode();
osg::Geometry* linesGeom = new osg::Geometry();
//coordinate red x, green y, blue z, 5 cm
osg::Vec3Array* vertices = new osg::Vec3Array(6);
(*vertices)[0].set(0, 0, 0);
(*vertices)[1].set(0.05, 0, 0);
(*vertices)[2].set(0, 0, 0);
(*vertices)[3].set(0, 0.05, 0);
(*vertices)[4].set(0, 0, 0);
(*vertices)[5].set(0, 0, 0.05);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
colors->push_back(osg::Vec4(0.0f,1.0f,0.0f,1.0f));
colors->push_back(osg::Vec4(0.0f,0.0f,1.0f,1.0f));
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
linesGeom->setVertexArray(vertices);
linesGeom->setColorArray(colors);
//linesGeom->setColorBinding(osg::Geometry::BIND_PER_PRIMITIVE);
linesGeom->setNormalArray(normals);
linesGeom->setNormalBinding(osg::Geometry::BIND_OVERALL);
linesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,0,14));
geode->addDrawable(linesGeom);
return geode;
}
osg::Node * createGrid(double screenWidth, double screenHeight, osg::Vec4 color = osg::Vec4(1.0f,1.0f,1.0f,1.0f))
{
int wStepRatio = 6;
int hStepRatio = 4;
double w = screenWidth/double(wStepRatio);
double h = screenHeight/double(hStepRatio);
osg::Geode * geode = new osg::Geode();
// create LINES
osg::Geometry* linesGeom = new osg::Geometry();
osg::Vec3Array* vertices = new osg::Vec3Array();
for(double i=-screenWidth/2.0; i<=screenWidth/2.0; i+=w)
{
vertices->push_back(osg::Vec3(i, -screenHeight/2, 0));
vertices->push_back(osg::Vec3(i, screenHeight/2, 0));
}
for(double i=-screenHeight/2.0; i<=screenHeight/2.0; i+=h)
{
vertices->push_back(osg::Vec3(-screenWidth/2, i, 0));
vertices->push_back(osg::Vec3(screenWidth/2, i, 0));
}
linesGeom->setVertexArray(vertices);
osg::Vec4Array* colors = new osg::Vec4Array;
colors->push_back(color);
linesGeom->setColorArray(colors);
linesGeom->setColorBinding(osg::Geometry::BIND_OVERALL);
osg::Vec3Array* normals = new osg::Vec3Array;
normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));
linesGeom->setNormalArray(normals);
linesGeom->setNormalBinding(osg::Geometry::BIND_OVERALL);
linesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES,0,vertices->size()));
// add the points geometry to the geode.
geode->addDrawable(linesGeom);
return geode;
}
osg::Node * createCubes(double screenWidth, double screenHeight)
{
double w = screenWidth/6.0;
double h = screenHeight/4.0;
double d = screenHeight/4.0;
osg::Geode * geode = new osg::Geode();
osg::ShapeDrawable * b0 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(-w*3 + w/2.0, h+h/2.0, -d/2.0), w, h, d));
osg::ShapeDrawable * b1 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(-w*2 + w/2.0, h+h/2.0, -d-d/2.0), w, h, d));
osg::ShapeDrawable * b2 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(-w*1 + w/2.0, h+h/2.0, -d/2.0), w, h, d));
osg::ShapeDrawable * b3 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(w*0 + w/2.0, h+h/2.0, -d/2.0), w, h, d));
osg::ShapeDrawable * b4 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(w*1 + w/2.0, h+h/2.0, -d-d/2.0), w, h, d));
osg::ShapeDrawable * b5 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(w*2 + w/2.0, h+h/2.0, -d/2.0), w, h, d));
osg::ShapeDrawable * b6 = new osg::ShapeDrawable(new osg::Box(osg::Vec3d(-w/2, -h/2.0, d/2.0), w, h, d));
b0->setColor(osg::Vec4d(1.0, 0.0, 0.0, 1.0));
b1->setColor(osg::Vec4d(1.0, 1.0, 0.0, 1.0));
b2->setColor(osg::Vec4d(1.0, 0.0, 0.0, 1.0));
b3->setColor(osg::Vec4d(1.0, 1.0, 0.0, 1.0));
b4->setColor(osg::Vec4d(1.0, 0.0, 0.0, 1.0));
b5->setColor(osg::Vec4d(1.0, 1.0, 0.0, 1.0));
b6->setColor(osg::Vec4d(1.0, 1.0, 1.0, 1.0));
geode->addDrawable(b0);
geode->addDrawable(b1);
geode->addDrawable(b2);
geode->addDrawable(b3);
geode->addDrawable(b4);
geode->addDrawable(b5);
geode->addDrawable(b6);
return geode;
}
osg::ref_ptr<osg::Node> cloudGeode;
osg::ref_ptr<osg::PositionAttitudeTransform> patCloud;
void cloudCallback(const sensor_msgs::PointCloud2::ConstPtr & msg)
{
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGB>());
pcl::fromROSMsg(*msg, *cloud);
if(cloudGeode.get() != 0)
{
patCloud->removeChild(cloudGeode);
}
//initialize the cloud
cloudGeode = pointCloud2Geode(*cloud);
patCloud->addChild(cloudGeode);
}
osg::Vec3d origin;
double scale = 1.0f;
class KeyboardEventHandler : public osgGA::GUIEventHandler
{
public:
KeyboardEventHandler(osg::PositionAttitudeTransform * pat):
_pat(pat) {}
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
bool handled = false;
switch(ea.getKey())
{
case(osgGA::GUIEventAdapter::KEY_Down):
{
if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT)
{
//rotate down
osg::Quat at = _pat->getAttitude();
_pat->setAttitude(at*osg::Quat(osg::PI/32, osg::Vec3d(1,0,0)));
}
else if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL)
{
//move down
osg::Vec3d pos = _pat->getPosition();
pos.y()-=0.01;
_pat->setPosition(pos);
}
else
{
//move toward the user
osg::Vec3d pos = _pat->getPosition();
pos.z()+=0.01;
_pat->setPosition(pos);
}
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_Up):
{
if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT)
{
//rotate up
osg::Quat at = _pat->getAttitude();
_pat->setAttitude(at*osg::Quat(-osg::PI/32, osg::Vec3d(1,0,0)));
}
else if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_CTRL)
{
//move up
osg::Vec3d pos = _pat->getPosition();
pos.y()+=0.01;
_pat->setPosition(pos);
}
else
{
//move away from user
osg::Vec3d pos = _pat->getPosition();
pos.z()-=0.01;
_pat->setPosition(pos);
}
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_Right):
{
if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT)
{
//rotate right
osg::Quat at = _pat->getAttitude();
_pat->setAttitude(at*osg::Quat(osg::PI/32, osg::Vec3d(0,1,0)));
}
else
{
//move right
osg::Vec3d pos = _pat->getPosition();
pos.x()+=0.01;
_pat->setPosition(pos);
}
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_Left):
{
if(ea.getModKeyMask() & osgGA::GUIEventAdapter::MODKEY_SHIFT)
{
//rotate left
osg::Quat at = _pat->getAttitude();
_pat->setAttitude(at*osg::Quat(-osg::PI/32, osg::Vec3d(0,1,0)));
}
else
{
//move left
osg::Vec3d pos = _pat->getPosition();
pos.x()-=0.01;
_pat->setPosition(pos);
}
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_Plus):
{
osg::Vec3d scale = _pat->getScale();
scale.x() *= 1.10;
scale.y() *= 1.10;
scale.z() *= 1.10;
_pat->setScale(scale);
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_Minus):
{
osg::Vec3d scale = _pat->getScale();
scale.x() *= 0.9;
scale.y() *= 0.9;
scale.z() *= 0.9;
_pat->setScale(scale);
handled = true;
break;
}
case(osgGA::GUIEventAdapter::KEY_H):
{
_pat->setPosition(origin);
_pat->setScale(osg::Vec3d(scale,scale,scale));
return true;
}
default:
break;
}
if(handled)
{
ROS_INFO("Position=%f,%f,%f, Scale=%f",
_pat->getPosition().x(),
_pat->getPosition().y(),
_pat->getPosition().z(),
_pat->getScale().x());
}
return handled;
}
osg::ref_ptr<osg::PositionAttitudeTransform> _pat;
};
int main( int argc, char **argv )
{
ros::init(argc, argv, "vvindow");
ros::NodeHandle np("~");
bool cloud = false;
bool stereo = true;
bool blackBg = true;
std::string modelPath = "";
double screenWidth = 0.0;
double screenHeigth = 0.0;
double x=0.0, y=0.0 ,z=0.0;
np.param("cloud", cloud, cloud);
np.param("stereo", stereo, stereo);
np.param("blackBg", blackBg, blackBg);
np.param("modelPath", modelPath, modelPath);
np.param("screenWidth", screenWidth, screenWidth);
np.param("screenHeight", screenHeigth, screenHeigth);
np.param("originX", x, x);
np.param("originY", y, y);
np.param("originZ", z, z);
np.param("scale", scale, scale);
origin.set(x,y,z);
ROS_INFO("cloud=%s", cloud?"true":"false");
ROS_INFO("stereo=%s", stereo?"true":"false");
ROS_INFO("blackBg=%s", blackBg?"true":"false");
ROS_INFO("modelPath=%s", modelPath.c_str());
ROS_INFO("screenWidth=%f", screenWidth);
ROS_INFO("screenHeight=%f", screenHeigth);
ROS_INFO("origin=%f,%f,%f", origin.x(), origin.y(), origin.z());
ROS_INFO("scale=%f", scale);
if(screenWidth == 0.0f || screenHeigth == 0.0f)
{
ROS_ERROR("screenWidth and/or screenHeigth parameters not set!");
return -1;
}
ros::NodeHandle n;
ros::Subscriber sub;
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
osgViewer::Viewer viewer(arguments);
//viewer.setCameraManipulator( new osgGA::TrackballManipulator() );
// load the scene.
osg::ref_ptr<osg::PositionAttitudeTransform> root = new osg::PositionAttitudeTransform();
root->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
root->setPosition(origin);
root->setScale(osg::Vec3d(scale,scale,scale));
//create_specular_highlights(root->getOrCreateStateSet());
viewer.addEventHandler(new osgViewer::StatsHandler);
viewer.addEventHandler(new osgViewer::ThreadingHandler);
viewer.addEventHandler(new KeyboardEventHandler(root.get()));
//model
osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFile(modelPath);
if (loadedModel)
{
root->addChild(loadedModel.get());
osg::Vec3 posInWorld = loadedModel->getBound().center() * osg::computeLocalToWorld(loadedModel->getParentalNodePaths()[0]);
ROS_INFO("Object position=%f,%f,%f radius=%f",posInWorld.x(), posInWorld.y(),posInWorld.z(), loadedModel->getBound().radius());
root->setAttitude(osg::Quat(-osg::PI_2, osg::Vec3d(1,0,0)));
}
else if(cloud)
{
//cloud
patCloud = new osg::PositionAttitudeTransform();
root->addChild(patCloud);
sub = n.subscribe("cloud", 1, cloudCallback);
}
else
{
//grid
osg::Vec4 color(6.0f,6.0f,6.0f,1.0f);
osg::ref_ptr<osg::Node> cubes = createCubes(screenWidth, screenHeigth);
osg::ref_ptr<osg::Node> gridBottom = createGrid(screenWidth, screenHeigth, color);
osg::ref_ptr<osg::Node> gridTop = createGrid(screenWidth, screenHeigth, color);
osg::ref_ptr<osg::Node> gridLeft = createGrid(screenWidth, screenHeigth, color);
osg::ref_ptr<osg::Node> gridRight = createGrid(screenWidth, screenHeigth, color);
osg::ref_ptr<osg::Node> gridBack = createGrid(screenWidth, screenHeigth, color);
osg::ref_ptr<osg::Node> coordinate = createCoordinate();
osg::ref_ptr<osg::PositionAttitudeTransform> patGridBottom = new osg::PositionAttitudeTransform();
osg::ref_ptr<osg::PositionAttitudeTransform> patGridTop = new osg::PositionAttitudeTransform();
osg::ref_ptr<osg::PositionAttitudeTransform> patGridLeft = new osg::PositionAttitudeTransform();
osg::ref_ptr<osg::PositionAttitudeTransform> patGridRight = new osg::PositionAttitudeTransform();
osg::ref_ptr<osg::PositionAttitudeTransform> patGridBack = new osg::PositionAttitudeTransform();
patGridBottom->setPosition(osg::Vec3d(0.0, -screenHeigth/2, -screenHeigth/2));
patGridTop->setPosition(osg::Vec3d(0.0, screenHeigth/2, -screenHeigth/2));
patGridLeft->setPosition(osg::Vec3d(-screenWidth/2, 0.0, -screenWidth/2));
patGridRight->setPosition(osg::Vec3d(screenWidth/2, 0.0, -screenWidth/2));
patGridBack->setPosition(osg::Vec3d(0.0, 0.0, -screenWidth));
patGridBottom->setAttitude(osg::Quat(-osg::PI_2, osg::Vec3d(1.0, 0.0, 0.0)));
patGridTop->setAttitude(osg::Quat(osg::PI_2, osg::Vec3d(1.0, 0.0, 0.0)));
patGridLeft->setAttitude(osg::Quat(osg::PI_2, osg::Vec3d(0.0, 1.0, 0.0)));
patGridRight->setAttitude(osg::Quat(-osg::PI_2, osg::Vec3d(0.0, 1.0, 0.0)));
patGridBottom->addChild(gridBottom.get());
patGridTop->addChild(gridTop.get());
patGridLeft->addChild(gridLeft.get());
patGridRight->addChild(gridRight.get());
patGridBack->addChild(gridBack.get());
std::cout << argv[0] <<": No data loaded... using box instead" << std::endl;
root->addChild(cubes.get());
root->addChild(coordinate.get());
root->addChild(patGridBottom.get());
root->addChild(patGridTop.get());
root->addChild(patGridLeft.get());
root->addChild(patGridRight.get());
root->addChild(patGridBack.get());
}
viewer.setSceneData(root.get());
// Get screen resolution
osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
if (!wsi)
{
osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
return -1;
}
unsigned int width, height;
wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);
// setup stereo cameras
osg::ref_ptr<osg::Camera> cameraLeft = 0;
osg::ref_ptr<osg::Camera> cameraRight = 0;
if(stereo)
{
// left window + left slave camera
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 0;
traits->y = 0;
traits->width = width;
traits->height = height;
traits->windowDecoration = false;
traits->doubleBuffer = true;
traits->sharedContext = 0;
osg::ref_ptr<osg::Viewport> vp=new osg::Viewport(0,0, traits->width, traits->height);
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
//camera left
cameraLeft = new osg::Camera;
cameraLeft->setGraphicsContext(gc.get());
cameraLeft->setViewport(vp.get());
cameraLeft->setDrawBuffer(GL_BACK);
cameraLeft->setReadBuffer(GL_BACK);
cameraLeft->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cameraLeft->setColorMask(true, false, false, true);
cameraLeft->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
//cameraLeft->setClearColor(osg::Vec4d());
viewer.addSlave(cameraLeft.get(), osg::Matrixd(), osg::Matrixd());
//camera right
cameraRight = new osg::Camera;
cameraRight->setGraphicsContext(gc.get());
cameraRight->setViewport(vp.get());
cameraRight->setDrawBuffer(GL_BACK);
cameraRight->setReadBuffer(GL_BACK);
cameraRight->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cameraRight->setColorMask(false, true, true, true);
cameraRight->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
//cameraRight->setClearColor(osg::Vec4d());
viewer.addSlave(cameraRight.get(), osg::Matrixd(), osg::Matrixd());
}
viewer.realize();
osg::Camera * camera = 0;
osg::Vec3d vu(0.000000,1.000000,0.00000); // view up direction
if(!stereo)
{
camera = viewer.getCamera();
osg::Vec3d vp(0,0,1.0); // view position
osg::Vec3d vd = vp + osg::Vec3d(0.0,0.0,-1.0); // view direction
double fovy, aspectRatio, zNear, zFar;
camera->getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar);
ROS_INFO("perspective: fovy=%f, aspectRatio=%f, zNear=%f, zFar=%f", fovy, aspectRatio, zNear, zFar);
double left, right, top, bottom, near, far;
camera->getProjectionMatrixAsFrustum(left, right, top, bottom, near, far);
ROS_INFO("frustrum: left=%f, right=%f, top=%f, bottom=%f, near=%f, far=%f", left, right, top, bottom, near, far);
double dist = vp.z();
double fovx1 = atan((-screenWidth/2.0f - vp.x()) / dist);
double fovx2 = atan((screenWidth/2.0f - vp.x()) / dist);
left = near*tan(fovx1);
right = near*tan(fovx2);
double fovy1 = atan((screenHeigth/2.0f - vp.y()) / dist);
double fovy2 = atan((-screenHeigth/2.0f - vp.y()) / dist);
top = near*tan(fovy1);
bottom = near*tan(fovy2);
camera->setProjectionMatrixAsFrustum(left, right, bottom, top, near, far);
camera->setViewMatrixAsLookAt(vp, vd, vu);
ROS_INFO("view: vp=(%f,%f,%f), vd=(%f,%f,%f), vu=(%f,%f,%f)",
vp.x(), vp.y(), vp.z(), vd.x(), vd.y(), vd.z(), vu.x(), vu.y(), vu.z());
if(blackBg)
{
camera->setClearColor(osg::Vec4d());
}
}
double left, right, top, bottom, near=0.01, far=10000.0;
tf::TransformListener tfListener;
while(!viewer.done() && !ros::isShuttingDown())
{
ros::spinOnce();
//update head position
try {
tf::StampedTransform transform;
bool tfSet = false;
if(tfListener.frameExists("/head_1"))
{
tfListener.lookupTransform("/base_link", "/head_1", ros::Time(0.0), transform);
tfSet = true;
}
else if(tfListener.frameExists("/head_2"))
{
tfListener.lookupTransform("/base_link", "/head_2", ros::Time(0.0), transform);
tfSet = true;
}
if(tfSet)
{
tf::Vector3 pos = transform.getOrigin();
// up : 0.55 43 43 0.55
// pencher a droite : 40 57 27 66
// 70 33 60 23
double yaw,pitch,roll;
tf::Matrix3x3(transform.getRotation()).getEulerYPR(yaw,pitch,roll);
double headAngle = pitch;
//ROS_INFO("y,p,r=%f,%f,%f", yaw, pitch, roll);
//misc
//double DTOR = 0.0174532925;
double dist = pos.x();
if(!stereo)
{
//single camera (using only fovy, assuming user stays in front)
double fovx1 = atan((-screenWidth/2.0f - pos.y()) / dist);
double fovx2 = atan((screenWidth/2.0f - pos.y()) / dist);
left = near*tan(fovx1);
right = near*tan(fovx2);
double fovy1 = atan((screenHeigth/2.0f - pos.z()) / dist);
double fovy2 = atan((-screenHeigth/2.0f - pos.z()) / dist);
top = near*tan(fovy1);
bottom = near*tan(fovy2);
//ROS_INFO("Head detected = %f,%f,%f fovx=%f,%f fovy=%f,%f l/r=%f,%f t/b=%f,%f", pos.x(), pos.y(), pos.z(), fovx1/DTOR, fovx2/DTOR, fovy1/DTOR, fovy2/DTOR, left, right, top, bottom);
//printf("frustrum: left=%f, right=%f, bottom=%f, top=%f, near=%f, far=%f\n", left, right, bottom, top, near, far);
camera->setProjectionMatrixAsFrustum(left, right, bottom, top, near, far);
double s = 1.0;
osg::Vec3d newVp = osg::Vec3d(pos.y()*s, pos.z()*s, pos.x()*s); // view position
camera->setViewMatrixAsLookAt(newVp, newVp+osg::Vec3d(0,0,-1), vu);
//ROS_INFO("view: vp=(%f,%f,%f), vd=(%f,%f,%f), vu=(%f,%f,%f)",
// newVp.x(), newVp.y(), newVp.z(), vd.x(), vd.y(), vd.z(), vu.x(), vu.y(), vu.z());
}
else
{
double eyesDistance = 0.05;// cm
double eyeDx = eyesDistance/2.0 * cos(headAngle); //right eye
double eyeDy = -eyesDistance/2.0 * sin(headAngle); //right eye
//camera left
{
double fovx1 = atan((-screenWidth/2.0f - (pos.y()-eyeDx)) / dist);
double fovx2 = atan((screenWidth/2.0f - (pos.y()-eyeDx)) / dist);
left = near*tan(fovx1);
right = near*tan(fovx2);
double fovy1 = atan((screenHeigth/2.0f - (pos.z()-eyeDy)) / dist);
double fovy2 = atan((-screenHeigth/2.0f - (pos.z()-eyeDy)) / dist);
top = near*tan(fovy1);
bottom = near*tan(fovy2);
//ROS_INFO("Head detected = %f,%f,%f fovx=%f,%f fovy=%f,%f l/r=%f,%f t/b=%f,%f", pos.x(), pos.y(), pos.z(), fovx1/DTOR, fovx2/DTOR, fovy1/DTOR, fovy2/DTOR, left, right, top, bottom);
//ROS_INFO("frustrumL: left=%f, right=%f, bottom=%f, top=%f, near=%f, far=%f\n", left, right, bottom, top, near, far);
cameraLeft->setProjectionMatrixAsFrustum(left, right, bottom, top, near, far);
osg::Vec3d newVp = osg::Vec3d(pos.y()-eyeDx, pos.z()-eyeDy, pos.x()); // view position
cameraLeft->setViewMatrixAsLookAt(newVp, newVp+osg::Vec3d(0,0,-1), vu);
//ROS_INFO("viewL: vp=(%f,%f,%f), vd=(%f,%f,%f), vu=(%f,%f,%f)",
// newVp.x(), newVp.y(), newVp.z(), vd.x(), vd.y(), vd.z(), vu.x(), vu.y(), vu.z());
}
//camera right
{
double fovx1 = atan((-screenWidth/2.0f - (pos.y()+eyeDx)) / dist);
double fovx2 = atan((screenWidth/2.0f - (pos.y()+eyeDx)) / dist);
left = near*tan(fovx1);
right = near*tan(fovx2);
double fovy1 = atan((screenHeigth/2.0f - (pos.z()+eyeDy)) / dist);
double fovy2 = atan((-screenHeigth/2.0f - (pos.z()+eyeDy)) / dist);
top = near*tan(fovy1);
bottom = near*tan(fovy2);
//ROS_INFO("Head detected = %f,%f,%f fovx=%f,%f fovy=%f,%f l/r=%f,%f t/b=%f,%f", pos.x(), pos.y(), pos.z(), fovx1/DTOR, fovx2/DTOR, fovy1/DTOR, fovy2/DTOR, left, right, top, bottom);
//ROS_INFO("frustrumR: left=%f, right=%f, bottom=%f, top=%f, near=%f, far=%f\n", left, right, bottom, top, near, far);
cameraRight->setProjectionMatrixAsFrustum(left, right, bottom, top, near, far);
osg::Vec3d newVp = osg::Vec3d(pos.y()+eyeDx, pos.z()+eyeDy, pos.x()); // view position
cameraRight->setViewMatrixAsLookAt(newVp, newVp+osg::Vec3d(0,0,-1), vu);
//ROS_INFO("viewR: vp=(%f,%f,%f), vd=(%f,%f,%f), vu=(%f,%f,%f)",
// newVp.x(), newVp.y(), newVp.z(), vd.x(), vd.y(), vd.z(), vu.x(), vu.y(), vu.z());
}
}
}
}
catch (tf::ExtrapolationException & e) {ROS_ERROR("cannot lookup transform...");}
catch(tf::LookupException & e) {ROS_ERROR("cannot lookup transform...");}
catch(tf::ConnectivityException & e) {ROS_ERROR("cannot lookup transform...");}
viewer.frame();
}
return 0;
}
<file_sep>/* OpenSceneGraph example, osglightpoint.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/GL>
#include <osgViewer/Viewer>
#include <osg/MatrixTransform>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/ShapeDrawable>
#include <osg/Notify>
#include <osg/PointSprite>
#include <osg/Texture2D>
#include <osg/BlendFunc>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgSim/LightPointNode>
#include <iostream>
#define INTERPOLATE(member) lp.member = start.member*rstart + end.member*rend;
void addToLightPointNode(osgSim::LightPointNode& lpn,osgSim::LightPoint& start,osgSim::LightPoint& end,unsigned int noSteps)
{
if (noSteps<=1)
{
lpn.addLightPoint(start);
return;
}
float rend = 0.0f;
float rdelta = 1.0f/((float)noSteps-1.0f);
lpn.getLightPointList().reserve(noSteps);
for(unsigned int i=0;i<noSteps;++i,rend+=rdelta)
{
float rstart = 1.0f-rend;
osgSim::LightPoint lp(start);
INTERPOLATE(_position)
INTERPOLATE(_intensity);
INTERPOLATE(_color);
INTERPOLATE(_radius);
lpn.addLightPoint(lp);
}
}
#undef INTERPOLATE
bool usePointSprites;
osg::Node* createLightPointsDatabase()
{
osgSim::LightPoint start;
osgSim::LightPoint end;
start._position.set(-500.0f,-500.0f,0.0f);
start._color.set(1.0f,0.0f,0.0f,1.0f);
end._position.set(500.0f,-500.0f,0.0f);
end._color.set(1.0f,1.0f,1.0f,1.0f);
osg::MatrixTransform* transform = new osg::MatrixTransform;
transform->setDataVariance(osg::Object::STATIC);
transform->setMatrix(osg::Matrix::scale(0.1,0.1,0.1));
osg::Vec3 start_delta(0.0f,10.0f,0.0f);
osg::Vec3 end_delta(0.0f,10.0f,1.0f);
int noStepsX = 100;
int noStepsY = 100;
// osgSim::BlinkSequence* bs = new osgSim::BlinkSequence;
// bs->addPulse(1.0,osg::Vec4(1.0f,0.0f,0.0f,1.0f));
// bs->addPulse(0.5,osg::Vec4(0.0f,0.0f,0.0f,0.0f)); // off
// bs->addPulse(1.5,osg::Vec4(1.0f,1.0f,0.0f,1.0f));
// bs->addPulse(0.5,osg::Vec4(0.0f,0.0f,0.0f,0.0f)); // off
// bs->addPulse(1.0,osg::Vec4(1.0f,1.0f,1.0f,1.0f));
// bs->addPulse(0.5,osg::Vec4(0.0f,0.0f,0.0f,0.0f)); // off
// osgSim::Sector* sector = new osgSim::ConeSector(osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0),osg::inDegrees(45.0));
// osgSim::Sector* sector = new osgSim::ElevationSector(-osg::inDegrees(45.0),osg::inDegrees(45.0),osg::inDegrees(45.0));
// osgSim::Sector* sector = new osgSim::AzimSector(-osg::inDegrees(45.0),osg::inDegrees(45.0),osg::inDegrees(90.0));
// osgSim::Sector* sector = new osgSim::AzimElevationSector(osg::inDegrees(180),osg::inDegrees(90), // azim range
// osg::inDegrees(0.0),osg::inDegrees(90.0), // elevation range
// osg::inDegrees(5.0));
for(int i=0;i<noStepsY;++i)
{
// osgSim::BlinkSequence* local_bs = new osgSim::BlinkSequence(*bs);
// local_bs->setSequenceGroup(new osgSim::BlinkSequence::SequenceGroup((double)i*0.1));
// start._blinkSequence = local_bs;
// start._sector = sector;
osgSim::LightPointNode* lpn = new osgSim::LightPointNode;
//
osg::StateSet* set = lpn->getOrCreateStateSet();
if (usePointSprites)
{
lpn->setPointSprite();
// Set point sprite texture in LightPointNode StateSet.
osg::Texture2D *tex = new osg::Texture2D();
tex->setImage(osgDB::readImageFile("Images/particle.rgb"));
set->setTextureAttributeAndModes(0, tex, osg::StateAttribute::ON);
}
//set->setMode(GL_BLEND, osg::StateAttribute::ON);
//osg::BlendFunc *fn = new osg::BlendFunc();
//fn->setFunction(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::DST_ALPHA);
//set->setAttributeAndModes(fn, osg::StateAttribute::ON);
//
addToLightPointNode(*lpn,start,end,noStepsX);
start._position += start_delta;
end._position += end_delta;
transform->addChild(lpn);
}
osg::Group* group = new osg::Group;
group->addChild(transform);
return group;
}
static osg::Node* CreateBlinkSequenceLightNode()
{
osgSim::LightPointNode* lightPointNode = new osgSim::LightPointNode;;
osgSim::LightPointNode::LightPointList lpList;
osg::ref_ptr<osgSim::SequenceGroup> seq_0;
seq_0 = new osgSim::SequenceGroup;
seq_0->_baseTime = 0.0;
osg::ref_ptr<osgSim::SequenceGroup> seq_1;
seq_1 = new osgSim::SequenceGroup;
seq_1->_baseTime = 0.5;
const int max_points = 32;
for( int i = 0; i < max_points; ++i )
{
osgSim::LightPoint lp;
double x = cos( (2.0*osg::PI*i)/max_points );
double z = sin( (2.0*osg::PI*i)/max_points );
lp._position.set( x, 0.0f, z + 30.0f );
lp._blinkSequence = new osgSim::BlinkSequence;
for( int j = 10; j > 0; --j )
{
float intensity = j/10.0f;
lp._blinkSequence->addPulse( 1.0/max_points,
osg::Vec4( intensity, intensity, intensity, intensity ) );
}
if( max_points > 10 )
{
lp._blinkSequence->addPulse( 1.0 - 10.0/max_points,
osg::Vec4( 0.0f, 0.0f, 0.0f, 0.0f ) );
}
if( i & 1 )
{
lp._blinkSequence->setSequenceGroup( seq_1.get() );
}
else
{
lp._blinkSequence->setSequenceGroup( seq_0.get() );
}
lp._blinkSequence->setPhaseShift( i/(static_cast<double>(max_points)) );
lpList.push_back( lp );
}
lightPointNode->setLightPointList( lpList );
return lightPointNode;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use high quality light point, typically used for naviagional lights.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("--sprites","Point sprites.");
// construct the viewer.
osgViewer::Viewer viewer;
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
usePointSprites = false;
while (arguments.read("--sprites")) { usePointSprites = true; };
osg::Group* rootnode = new osg::Group;
// load the nodes from the commandline arguments.
rootnode->addChild(osgDB::readNodeFiles(arguments));
rootnode->addChild(createLightPointsDatabase());
rootnode->addChild(CreateBlinkSequenceLightNode());
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData( rootnode );
return viewer.run();
}
<file_sep>/* OpenSceneGraph example, osgcompositeviewer.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <iostream>
#include <osgUtil/Optimizer>
#include <osgDB/ReadFile>
#include <osg/Material>
#include <osg/Geode>
#include <osg/BlendFunc>
#include <osg/Depth>
#include <osg/Projection>
#include <osg/PolygonOffset>
#include <osg/MatrixTransform>
#include <osg/Camera>
#include <osg/FrontFace>
#include <osgText/Text>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/StateSetManipulator>
#include <osgViewer/ViewerEventHandlers>
#include <osgViewer/CompositeViewer>
#include <osgFX/Scribe>
#include <osg/io_utils>
// class to handle events with a pick
class PickHandler : public osgGA::GUIEventHandler {
public:
PickHandler():
_mx(0.0f),
_my(0.0f) {}
~PickHandler() {}
bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
{
osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
if (!view) return false;
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::PUSH):
{
_mx = ea.getX();
_my = ea.getY();
break;
}
case(osgGA::GUIEventAdapter::RELEASE):
{
if (_mx==ea.getX() && _my==ea.getY())
{
pick(view, ea.getX(), ea.getY());
}
break;
}
default:
break;
}
return false;
}
void pick(osgViewer::View* view, float x, float y)
{
osg::Node* node = 0;
osg::Group* parent = 0;
osgUtil::LineSegmentIntersector::Intersections intersections;
if (view->computeIntersections(x, y, intersections))
{
osgUtil::LineSegmentIntersector::Intersection intersection = *intersections.begin();
osg::NodePath& nodePath = intersection.nodePath;
node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0;
parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0;
}
// now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked"
if (parent && node)
{
osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent);
if (!parentAsScribe)
{
// node not already picked, so highlight it with an osgFX::Scribe
osgFX::Scribe* scribe = new osgFX::Scribe();
scribe->addChild(node);
parent->replaceChild(node,scribe);
}
else
{
// node already picked so we want to remove scribe to unpick it.
osg::Node::ParentList parentList = parentAsScribe->getParents();
for(osg::Node::ParentList::iterator itr=parentList.begin();
itr!=parentList.end();
++itr)
{
(*itr)->replaceChild(parentAsScribe,node);
}
}
}
}
float _mx, _my;
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
if (!scene)
{
std::cout << argv[0] << ": requires filename argument." << std::endl;
return 1;
}
// construct the viewer.
osgViewer::CompositeViewer viewer(arguments);
if (arguments.read("-1"))
{
{
osgViewer::View* view = new osgViewer::View;
view->setName("Single view");
view->setSceneData(osgDB::readNodeFile("fountain.osgt"));
view->addEventHandler( new osgViewer::StatsHandler );
view->setUpViewAcrossAllScreens();
view->setCameraManipulator(new osgGA::TrackballManipulator);
viewer.addView(view);
}
}
if (arguments.read("-2"))
{
// view one
{
osgViewer::View* view = new osgViewer::View;
view->setName("View one");
viewer.addView(view);
view->setUpViewOnSingleScreen(0);
view->setSceneData(scene.get());
view->setCameraManipulator(new osgGA::TrackballManipulator);
// add the state manipulator
osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet());
view->addEventHandler( statesetManipulator.get() );
}
// view two
{
osgViewer::View* view = new osgViewer::View;
view->setName("View two");
viewer.addView(view);
view->setUpViewOnSingleScreen(1);
view->setSceneData(scene.get());
view->setCameraManipulator(new osgGA::TrackballManipulator);
view->addEventHandler( new osgViewer::StatsHandler );
// add the handler for doing the picking
view->addEventHandler(new PickHandler());
}
}
if (arguments.read("-3") || viewer.getNumViews()==0)
{
osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
if (!wsi)
{
osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
return 1;
}
unsigned int width, height;
wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 100;
traits->y = 100;
traits->width = 1000;
traits->height = 800;
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = 0;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (gc.valid())
{
osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl;
// need to ensure that the window is cleared make sure that the complete window is set the correct colour
// rather than just the parts of the window that are under the camera's viewports
gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f));
gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
else
{
osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl;
}
// view one
{
osgViewer::View* view = new osgViewer::View;
view->setName("View one");
viewer.addView(view);
view->setSceneData(scene.get());
view->getCamera()->setName("Cam one");
view->getCamera()->setViewport(new osg::Viewport(0,0, traits->width/2, traits->height/2));
view->getCamera()->setGraphicsContext(gc.get());
view->setCameraManipulator(new osgGA::TrackballManipulator);
// add the state manipulator
osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet());
view->addEventHandler( statesetManipulator.get() );
view->addEventHandler( new osgViewer::StatsHandler );
view->addEventHandler( new osgViewer::HelpHandler );
view->addEventHandler( new osgViewer::WindowSizeHandler );
view->addEventHandler( new osgViewer::ThreadingHandler );
view->addEventHandler( new osgViewer::RecordCameraPathHandler );
}
// view two
{
osgViewer::View* view = new osgViewer::View;
view->setName("View two");
viewer.addView(view);
view->setSceneData(scene.get());
view->getCamera()->setName("Cam two");
view->getCamera()->setViewport(new osg::Viewport(traits->width/2,0, traits->width/2, traits->height/2));
view->getCamera()->setGraphicsContext(gc.get());
view->setCameraManipulator(new osgGA::TrackballManipulator);
// add the handler for doing the picking
view->addEventHandler(new PickHandler());
}
// view three
{
osgViewer::View* view = new osgViewer::View;
view->setName("View three");
viewer.addView(view);
view->setSceneData(osgDB::readNodeFile("cessnafire.osgt"));
view->getCamera()->setName("Cam three");
view->getCamera()->setProjectionMatrixAsPerspective(30.0, double(traits->width) / double(traits->height/2), 1.0, 1000.0);
view->getCamera()->setViewport(new osg::Viewport(0, traits->height/2, traits->width, traits->height/2));
view->getCamera()->setGraphicsContext(gc.get());
view->setCameraManipulator(new osgGA::TrackballManipulator);
}
}
while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); }
while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullDrawThreadPerContext); }
while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullThreadPerCameraDrawThreadPerContext); }
// run the viewer's main frame loop
return viewer.run();
}
<file_sep>/* OpenSceneGraph example, osglight.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osgViewer/Viewer>
#include <osg/Group>
#include <osg/Node>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/StateAttribute>
#include <osg/Geometry>
#include <osg/Point>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgUtil/SmoothingVisitor>
#include "stdio.h"
// callback to make the loaded model oscilate up and down.
class ModelTransformCallback : public osg::NodeCallback
{
public:
ModelTransformCallback(const osg::BoundingSphere& bs)
{
_firstTime = 0.0;
_period = 4.0f;
_range = bs.radius()*0.5f;
}
virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
{
osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*>(node);
const osg::FrameStamp* frameStamp = nv->getFrameStamp();
if (pat && frameStamp)
{
if (_firstTime==0.0)
{
_firstTime = frameStamp->getSimulationTime();
}
double phase = (frameStamp->getSimulationTime()-_firstTime)/_period;
phase -= floor(phase);
phase *= (2.0 * osg::PI);
osg::Quat rotation;
rotation.makeRotate(phase,1.0f,1.0f,1.0f);
pat->setAttitude(rotation);
pat->setPosition(osg::Vec3(0.0f,0.0f,sin(phase))*_range);
}
// must traverse the Node's subgraph
traverse(node,nv);
}
double _firstTime;
double _period;
double _range;
};
osg::Node* createLights(osg::BoundingBox& bb,osg::StateSet* rootStateSet)
{
osg::Group* lightGroup = new osg::Group;
float modelSize = bb.radius();
// create a spot light.
osg::Light* myLight1 = new osg::Light;
myLight1->setLightNum(0);
myLight1->setPosition(osg::Vec4(bb.corner(4),1.0f));
myLight1->setAmbient(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
myLight1->setDiffuse(osg::Vec4(1.0f,0.0f,0.0f,1.0f));
myLight1->setSpotCutoff(20.0f);
myLight1->setSpotExponent(50.0f);
myLight1->setDirection(osg::Vec3(1.0f,1.0f,-1.0f));
osg::LightSource* lightS1 = new osg::LightSource;
lightS1->setLight(myLight1);
lightS1->setLocalStateSetModes(osg::StateAttribute::ON);
lightS1->setStateSetModes(*rootStateSet,osg::StateAttribute::ON);
lightGroup->addChild(lightS1);
// create a local light.
osg::Light* myLight2 = new osg::Light;
myLight2->setLightNum(1);
myLight2->setPosition(osg::Vec4(0.0,0.0,0.0,1.0f));
myLight2->setAmbient(osg::Vec4(0.0f,1.0f,1.0f,1.0f));
myLight2->setDiffuse(osg::Vec4(0.0f,1.0f,1.0f,1.0f));
myLight2->setConstantAttenuation(1.0f);
myLight2->setLinearAttenuation(2.0f/modelSize);
myLight2->setQuadraticAttenuation(2.0f/osg::square(modelSize));
osg::LightSource* lightS2 = new osg::LightSource;
lightS2->setLight(myLight2);
lightS2->setLocalStateSetModes(osg::StateAttribute::ON);
lightS2->setStateSetModes(*rootStateSet,osg::StateAttribute::ON);
osg::MatrixTransform* mt = new osg::MatrixTransform();
{
// set up the animation path
osg::AnimationPath* animationPath = new osg::AnimationPath;
animationPath->insert(0.0,osg::AnimationPath::ControlPoint(bb.corner(0)));
animationPath->insert(1.0,osg::AnimationPath::ControlPoint(bb.corner(1)));
animationPath->insert(2.0,osg::AnimationPath::ControlPoint(bb.corner(2)));
animationPath->insert(3.0,osg::AnimationPath::ControlPoint(bb.corner(3)));
animationPath->insert(4.0,osg::AnimationPath::ControlPoint(bb.corner(4)));
animationPath->insert(5.0,osg::AnimationPath::ControlPoint(bb.corner(5)));
animationPath->insert(6.0,osg::AnimationPath::ControlPoint(bb.corner(6)));
animationPath->insert(7.0,osg::AnimationPath::ControlPoint(bb.corner(7)));
animationPath->insert(8.0,osg::AnimationPath::ControlPoint(bb.corner(0)));
animationPath->setLoopMode(osg::AnimationPath::SWING);
mt->setUpdateCallback(new osg::AnimationPathCallback(animationPath));
}
// create marker for point light.
osg::Geometry* marker = new osg::Geometry;
osg::Vec3Array* vertices = new osg::Vec3Array;
vertices->push_back(osg::Vec3(0.0,0.0,0.0));
marker->setVertexArray(vertices);
marker->addPrimitiveSet(new osg::DrawArrays(GL_POINTS,0,1));
osg::StateSet* stateset = new osg::StateSet;
osg::Point* point = new osg::Point;
point->setSize(4.0f);
stateset->setAttribute(point);
marker->setStateSet(stateset);
osg::Geode* markerGeode = new osg::Geode;
markerGeode->addDrawable(marker);
mt->addChild(lightS2);
mt->addChild(markerGeode);
lightGroup->addChild(mt);
return lightGroup;
}
osg::Geometry* createWall(const osg::Vec3& v1,const osg::Vec3& v2,const osg::Vec3& v3,osg::StateSet* stateset)
{
// create a drawable for occluder.
osg::Geometry* geom = new osg::Geometry;
geom->setStateSet(stateset);
unsigned int noXSteps = 100;
unsigned int noYSteps = 100;
osg::Vec3Array* coords = new osg::Vec3Array;
coords->reserve(noXSteps*noYSteps);
osg::Vec3 dx = (v2-v1)/((float)noXSteps-1.0f);
osg::Vec3 dy = (v3-v1)/((float)noYSteps-1.0f);
unsigned int row;
osg::Vec3 vRowStart = v1;
for(row=0;row<noYSteps;++row)
{
osg::Vec3 v = vRowStart;
for(unsigned int col=0;col<noXSteps;++col)
{
coords->push_back(v);
v += dx;
}
vRowStart+=dy;
}
geom->setVertexArray(coords);
osg::Vec4Array* colors = new osg::Vec4Array(1);
(*colors)[0].set(1.0f,1.0f,1.0f,1.0f);
geom->setColorArray(colors);
geom->setColorBinding(osg::Geometry::BIND_OVERALL);
for(row=0;row<noYSteps-1;++row)
{
osg::DrawElementsUShort* quadstrip = new osg::DrawElementsUShort(osg::PrimitiveSet::QUAD_STRIP);
quadstrip->reserve(noXSteps*2);
for(unsigned int col=0;col<noXSteps;++col)
{
quadstrip->push_back((row+1)*noXSteps+col);
quadstrip->push_back(row*noXSteps+col);
}
geom->addPrimitiveSet(quadstrip);
}
// create the normals.
osgUtil::SmoothingVisitor::smooth(*geom);
return geom;
}
osg::Node* createRoom(osg::Node* loadedModel)
{
// default scale for this model.
osg::BoundingSphere bs(osg::Vec3(0.0f,0.0f,0.0f),1.0f);
osg::Group* root = new osg::Group;
if (loadedModel)
{
const osg::BoundingSphere& loaded_bs = loadedModel->getBound();
osg::PositionAttitudeTransform* pat = new osg::PositionAttitudeTransform();
pat->setPivotPoint(loaded_bs.center());
pat->setUpdateCallback(new ModelTransformCallback(loaded_bs));
pat->addChild(loadedModel);
bs = pat->getBound();
root->addChild(pat);
}
bs.radius()*=1.5f;
// create a bounding box, which we'll use to size the room.
osg::BoundingBox bb;
bb.expandBy(bs);
// create statesets.
osg::StateSet* rootStateSet = new osg::StateSet;
root->setStateSet(rootStateSet);
osg::StateSet* wall = new osg::StateSet;
wall->setMode(GL_CULL_FACE,osg::StateAttribute::ON);
osg::StateSet* floor = new osg::StateSet;
floor->setMode(GL_CULL_FACE,osg::StateAttribute::ON);
osg::StateSet* roof = new osg::StateSet;
roof->setMode(GL_CULL_FACE,osg::StateAttribute::ON);
osg::Geode* geode = new osg::Geode;
// create front side.
geode->addDrawable(createWall(bb.corner(0),
bb.corner(4),
bb.corner(1),
wall));
// right side
geode->addDrawable(createWall(bb.corner(1),
bb.corner(5),
bb.corner(3),
wall));
// left side
geode->addDrawable(createWall(bb.corner(2),
bb.corner(6),
bb.corner(0),
wall));
// back side
geode->addDrawable(createWall(bb.corner(3),
bb.corner(7),
bb.corner(2),
wall));
// floor
geode->addDrawable(createWall(bb.corner(0),
bb.corner(1),
bb.corner(2),
floor));
// roof
geode->addDrawable(createWall(bb.corner(6),
bb.corner(7),
bb.corner(4),
roof));
root->addChild(geode);
root->addChild(createLights(bb,rootStateSet));
return root;
}
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer;
// load the nodes from the commandline arguments.
osg::Node* loadedModel = osgDB::readNodeFiles(arguments);
// if not loaded assume no arguments passed in, try use default mode instead.
if (!loadedModel) loadedModel = osgDB::readNodeFile("glider.osgt");
// create a room made of foor walls, a floor, a roof, and swinging light fitting.
osg::Node* rootnode = createRoom(loadedModel);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData( rootnode );
// create the windows and run the threads.
viewer.realize();
viewer.getCamera()->setCullingMode( viewer.getCamera()->getCullingMode() & ~osg::CullStack::SMALL_FEATURE_CULLING);
return viewer.run();
}
<file_sep>/* OpenSceneGraph example, osgcubemap.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Group>
#include <osg/StateSet>
#include <osg/TextureCubeMap>
#include <osg/TexGen>
#include <osg/TexEnvCombine>
#include <osgUtil/ReflectionMapGenerator>
#include <osgUtil/HighlightMapGenerator>
#include <osgUtil/HalfWayMapGenerator>
#include <osgUtil/Optimizer>
#include <osgDB/ReadFile>
#include <osgDB/Registry>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/DriveManipulator>
#include <osgViewer/Viewer>
#include <iostream>
#include <string>
#include <vector>
void create_specular_highlights(osg::Node *node)
{
osg::StateSet *ss = node->getOrCreateStateSet();
// create and setup the texture object
osg::TextureCubeMap *tcm = new osg::TextureCubeMap;
tcm->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP);
tcm->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP);
tcm->setWrap(osg::Texture::WRAP_R, osg::Texture::CLAMP);
tcm->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
tcm->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR);
// generate the six highlight map images (light direction = [1, 1, -1])
osgUtil::HighlightMapGenerator *mapgen = new osgUtil::HighlightMapGenerator(
osg::Vec3(1, 1, -1), // light direction
osg::Vec4(1, 0.9f, 0.8f, 1), // light color
8); // specular exponent
mapgen->generateMap();
// assign the six images to the texture object
tcm->setImage(osg::TextureCubeMap::POSITIVE_X, mapgen->getImage(osg::TextureCubeMap::POSITIVE_X));
tcm->setImage(osg::TextureCubeMap::NEGATIVE_X, mapgen->getImage(osg::TextureCubeMap::NEGATIVE_X));
tcm->setImage(osg::TextureCubeMap::POSITIVE_Y, mapgen->getImage(osg::TextureCubeMap::POSITIVE_Y));
tcm->setImage(osg::TextureCubeMap::NEGATIVE_Y, mapgen->getImage(osg::TextureCubeMap::NEGATIVE_Y));
tcm->setImage(osg::TextureCubeMap::POSITIVE_Z, mapgen->getImage(osg::TextureCubeMap::POSITIVE_Z));
tcm->setImage(osg::TextureCubeMap::NEGATIVE_Z, mapgen->getImage(osg::TextureCubeMap::NEGATIVE_Z));
// enable texturing, replacing any textures in the subgraphs
ss->setTextureAttributeAndModes(0, tcm, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
// texture coordinate generation
osg::TexGen *tg = new osg::TexGen;
tg->setMode(osg::TexGen::REFLECTION_MAP);
ss->setTextureAttributeAndModes(0, tg, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
// use TexEnvCombine to add the highlights to the original lighting
osg::TexEnvCombine *te = new osg::TexEnvCombine;
te->setCombine_RGB(osg::TexEnvCombine::ADD);
te->setSource0_RGB(osg::TexEnvCombine::TEXTURE);
te->setOperand0_RGB(osg::TexEnvCombine::SRC_COLOR);
te->setSource1_RGB(osg::TexEnvCombine::PRIMARY_COLOR);
te->setOperand1_RGB(osg::TexEnvCombine::SRC_COLOR);
ss->setTextureAttributeAndModes(0, te, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
}
int main(int argc, char *argv[])
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer;
// load the nodes from the commandline arguments.
osg::Node* rootnode = osgDB::readNodeFiles(arguments);
// if not loaded assume no arguments passed in, try use default mode instead.
if (!rootnode) rootnode = osgDB::readNodeFile("cessna.osgt");
if (!rootnode)
{
osg::notify(osg::NOTICE)<<"Please specify a model filename on the command line."<<std::endl;
return 1;
}
// create specular highlights
create_specular_highlights(rootnode);
// run optimization over the scene graph
osgUtil::Optimizer optimzer;
optimzer.optimize(rootnode);
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(rootnode);
// create the windows and run the threads.
viewer.realize();
// now check to see if texture cube map is supported.
for(unsigned int contextID = 0;
contextID<osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts();
++contextID)
{
osg::TextureCubeMap::Extensions* tcmExt = osg::TextureCubeMap::getExtensions(contextID,false);
if (tcmExt)
{
if (!tcmExt->isCubeMapSupported())
{
std::cout<<"Warning: texture_cube_map not supported by OpenGL drivers, unable to run application."<<std::endl;
return 1;
}
}
}
return viewer.run();
}
<file_sep>/* OpenSceneGraph example, osgcamera.
*
* 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/TrackballManipulator>
#include <osgGA/FlightManipulator>
#include <osgGA/AnimationPathManipulator>
#include <iostream>
class ModelHandler : public osgGA::GUIEventHandler
{
public:
ModelHandler():
_position(0) {}
typedef std::vector<std::string> Filenames;
Filenames _filenames;
unsigned int _position;
void add(const std::string& filename) { _filenames.push_back(filename); }
bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
osgViewer::Viewer* viewer = dynamic_cast<osgViewer::Viewer*>(&aa);
if (!viewer) return false;
if (_filenames.empty()) return false;
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYUP):
{
if (ea.getKey()=='l')
{
osg::ref_ptr<osg::Node> model = osgDB::readNodeFile( _filenames[_position] );
++_position;
if (_position>=_filenames.size()) _position = 0;
if (model.valid())
{
viewer->setSceneData(model.get());
}
return true;
}
}
default: break;
}
return false;
}
bool _done;
};
void singleWindowMultipleCameras(osgViewer::Viewer& viewer)
{
osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
if (!wsi)
{
osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
return;
}
unsigned int width, height;
wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->x = 0;
traits->y = 0;
traits->width = width;
traits->height = height;
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = 0;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (gc.valid())
{
osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl;
// need to ensure that the window is cleared make sure that the complete window is set the correct colour
// rather than just the parts of the window that are under the camera's viewports
gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f));
gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
else
{
osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl;
}
unsigned int numCameras = 2;
double aspectRatioScale = 1.0;///(double)numCameras;
for(unsigned int i=0; i<numCameras;++i)
{
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(gc.get());
camera->setViewport(new osg::Viewport((i*width)/numCameras,(i*height)/numCameras, width/numCameras, height/numCameras));
GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
camera->setDrawBuffer(buffer);
camera->setReadBuffer(buffer);
viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd::scale(aspectRatioScale,1.0,1.0));
}
}
void multipleWindowMultipleCameras(osgViewer::Viewer& viewer, bool multipleScreens)
{
osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface();
if (!wsi)
{
osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl;
return;
}
unsigned int width, height;
wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height);
unsigned int numCameras = 6;
double aspectRatioScale = (double)numCameras;
double translate_x = double(numCameras)-1;
for(unsigned int i=0; i<numCameras;++i, translate_x -= 2.0)
{
osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
traits->screenNum = multipleScreens ? i / 3 : 0;
traits->x = (i*width)/numCameras;
traits->y = 0;
traits->width = width/numCameras-1;
traits->height = height;
traits->windowDecoration = true;
traits->doubleBuffer = true;
traits->sharedContext = 0;
osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());
if (gc.valid())
{
osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl;
}
else
{
osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl;
}
osg::ref_ptr<osg::Camera> camera = new osg::Camera;
camera->setGraphicsContext(gc.get());
camera->setViewport(new osg::Viewport(0,0, width/numCameras, height));
GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
camera->setDrawBuffer(buffer);
camera->setReadBuffer(buffer);
viewer.addSlave(camera.get(), osg::Matrix::scale(aspectRatioScale, 1.0, 1.0)*osg::Matrix::translate(translate_x, 0.0, 0.0), osg::Matrix() );
}
}
class EnableVBOVisitor : public osg::NodeVisitor
{
public:
EnableVBOVisitor():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
void apply(osg::Geode& geode)
{
for(unsigned int i=0; i<geode.getNumDrawables();++i)
{
osg::Geometry* geom = geode.getDrawable(i)->asGeometry();
if (geom)
{
osg::notify(osg::NOTICE)<<"Enabling VBO"<<std::endl;
geom->setUseVertexBufferObjects(true);
}
}
}
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
if (argc<2)
{
std::cout << argv[0] <<": requires filename argument." << std::endl;
return 1;
}
unsigned int numRepeats = 2;
if (arguments.read("--repeat",numRepeats) || arguments.read("-r",numRepeats) || arguments.read("--repeat") || arguments.read("-r"))
{
bool sharedModel = arguments.read("--shared");
bool enableVBO = arguments.read("--vbo");
osg::ref_ptr<osg::Node> model;
if (sharedModel)
{
model = osgDB::readNodeFiles(arguments);
if (!model) return 0;
if (enableVBO)
{
EnableVBOVisitor enableVBOs;
model->accept(enableVBOs);
}
}
osgViewer::Viewer::ThreadingModel threadingModel = osgViewer::Viewer::AutomaticSelection;
while (arguments.read("-s")) { threadingModel = osgViewer::Viewer::SingleThreaded; }
while (arguments.read("-g")) { threadingModel = osgViewer::Viewer::CullDrawThreadPerContext; }
while (arguments.read("-d")) { threadingModel = osgViewer::Viewer::DrawThreadPerContext; }
while (arguments.read("-c")) { threadingModel = osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext; }
for(unsigned int i=0; i<numRepeats; ++i)
{
osg::notify(osg::NOTICE)<<"+++++++++++++ New viewer ++++++++++++"<<std::endl;
{
osgViewer::Viewer viewer;
viewer.setThreadingModel(threadingModel);
if (sharedModel) viewer.setSceneData(model.get());
else
{
osg::ref_ptr<osg::Node> node = osgDB::readNodeFiles(arguments);
if (!node) return 0;
if (enableVBO)
{
EnableVBOVisitor enableVBOs;
node->accept(enableVBOs);
}
viewer.setSceneData(node.get());
}
viewer.run();
}
osg::notify(osg::NOTICE)<<"------------ Viewer ended ----------"<<std::endl<<std::endl;
}
return 0;
}
std::string pathfile;
osg::ref_ptr<osgGA::AnimationPathManipulator> apm = 0;
while (arguments.read("-p",pathfile))
{
apm = new osgGA::AnimationPathManipulator(pathfile);
if (!apm.valid() || !(apm->valid()) )
{
apm = 0;
}
}
osgViewer::Viewer viewer(arguments);
while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded); }
while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext); }
while (arguments.read("-d")) { viewer.setThreadingModel(osgViewer::Viewer::DrawThreadPerContext); }
while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext); }
bool limitNumberOfFrames = false;
unsigned int maxFrames = 10;
while (arguments.read("--run-till-frame-number",maxFrames)) { limitNumberOfFrames = true; }
// alternative viewer window setups.
while (arguments.read("-1")) { singleWindowMultipleCameras(viewer); }
while (arguments.read("-2")) { multipleWindowMultipleCameras(viewer, false); }
while (arguments.read("-3")) { multipleWindowMultipleCameras(viewer, true); }
if (apm.valid()) viewer.setCameraManipulator(apm.get());
else viewer.setCameraManipulator( new osgGA::TrackballManipulator() );
viewer.addEventHandler(new osgViewer::StatsHandler);
viewer.addEventHandler(new osgViewer::ThreadingHandler);
std::string configfile;
while (arguments.read("--config", configfile))
{
osg::notify(osg::NOTICE)<<"Trying to read config file "<<configfile<<std::endl;
osg::ref_ptr<osg::Object> object = osgDB::readObjectFile(configfile);
osgViewer::View* view = dynamic_cast<osgViewer::View*>(object.get());
if (view)
{
osg::notify(osg::NOTICE)<<"Read config file succesfully"<<std::endl;
}
else
{
osg::notify(osg::NOTICE)<<"Failed to read config file : "<<configfile<<std::endl;
return 1;
}
}
while (arguments.read("--write-config", configfile)) { osgDB::writeObjectFile(viewer, configfile); }
if (arguments.read("-m"))
{
ModelHandler* modelHandler = new ModelHandler;
for(int i=1; i<arguments.argc();++i)
{
modelHandler->add(arguments[i]);
}
viewer.addEventHandler(modelHandler);
}
else
{
// load the scene.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");
if (!loadedModel)
{
std::cout << argv[0] <<": No data loaded." << std::endl;
return 1;
}
viewer.setSceneData(loadedModel.get());
}
viewer.realize();
unsigned int numFrames = 0;
while(!viewer.done() && !(limitNumberOfFrames && numFrames>=maxFrames))
{
viewer.frame();
++numFrames;
}
return 0;
}
| f6935d1bc09a1f32aa9c749626f3b5a25bec43df | [
"C++"
] | 7 | C++ | willwang26/vvindow | 7cdaf0c34ee8422267958d2506b0ce327bf6c9b9 | b7da53dd72509541242a74a6b7e5872ed5d08709 |
refs/heads/master | <repo_name>EzequielMonforte/ControlEstacionamiento<file_sep>/ControlEstacionamiento/Capacidad.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ControlEstacionamiento
{
class Capacidad
{
public static int cantidadMax = 50;
public static int cantidadAutos = 0;
private int entradas = 0;
private int salidas = 0;
public Capacidad() {
}
public int AutosHoy(){
return entradas;
}
public int EntradaAuto() {
entradas++;
cantidadAutos++;
return Disponibilidad();
}
public int SalidaAuto() {
if (cantidadAutos > 0) {
cantidadAutos--;
}
return Disponibilidad();
}
public static int Disponibilidad() {
int devolver = cantidadMax - cantidadAutos;
return devolver;
}
}
}
<file_sep>/EstacionamientoArduino/EstacionamientoArduino.ino
#include <NewPing.h>
#include <Servo.h>
int distancia;
int distancia2;
bool puerta1Abierta = false;
bool puerta2Abierta = false;
long duracion = 0;
NewPing sensor1(7, 6, 40);
NewPing sensor2(13, 12, 40);
Servo puerta1;
Servo puerta2;
void setup() {
puerta1.attach(9);
puerta2.attach(2);// attaches the servo on pin 9 to the servo object
puerta1.write(-180);
puerta2.write(-180);
Serial.begin(9600);
}
void loop()
{
distancia = sensor1.ping_cm();
distancia2 = sensor2.ping_cm();
if (distancia < 6 && distancia > 0) {
puerta1.write(180);
puerta1Abierta = true;
}
if (distancia2 < 6 && distancia2 > 0 && puerta1Abierta != true) {
puerta2.write(180);
puerta2Abierta = true;
}
if (distancia > 6 && puerta1Abierta == true) {
delay(5000);
puerta1.write(-180);
puerta1Abierta = false;
Serial.println('0');
}
if (distancia2 > 6 && puerta2Abierta == true && distancia2 != 0) {
delay(5000);
puerta2.write(-180);
puerta2Abierta = false;
Serial.println('1');
}
}
<file_sep>/ControlEstacionamiento/Principal.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ControlEstacionamiento
{
public delegate void Delegado(int n, Label texto, string info);
public partial class Principal : Form
{
private int entradas = 0;
Delegado a;
Capacidad estacionamiento;
public Principal()
{
estacionamiento = new Capacidad();
a = new Delegado(CambiarTexto);
InitializeComponent();
serialPort1.PortName = "COM3";
serialPort1.Open();
}
public void CambiarTexto(int n, Label texto, string info)
{
texto.Text = info + " " + n;
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string devuelto = serialPort1.ReadLine();
// 1= se abrio puerta de entrada
if (devuelto == "1\r")
{
this.Invoke(a, estacionamiento.AutosHoy(),txt_CantidadEntradas, "Entraron hoy: ");
this.Invoke(a, estacionamiento.EntradaAuto(), tx_Lugares, "Lugares libres: ");
return;
}
// 0 = se abrio la puerta de salida
if (devuelto == "0\r")
{
this.Invoke(a, estacionamiento.SalidaAuto(), tx_Lugares, "lugares libres: ");
return;
}
return;
}
#region Controladores Puertas
private void bt_Abrir1_Click(object sender, EventArgs e)
{
//probar
serialPort1.Open();
}
private void bt_Cerrar1_Click(object sender, EventArgs e)
{
//probar
this.bt_Cerrar1.Click += bt_Cerrar1_Click;
}
private void bt_Abrir2_Click(object sender, EventArgs e)
{
//probar
bt_Abrir2.Enabled = true;
}
private void bt_Cerrar2_Click(object sender, EventArgs e)
{
//probar
if (serialPort1.IsOpen) serialPort1.Close();
//bt_Abrir2.Enabled = false;
}
#endregion
private void timer1_Tick(object sender, EventArgs e)
{
lblHora.Text = DateTime.Now.ToString("dd - MMM - yyyy - hh:mm:ss tt");
}
}
}
| de384fc4a56fe955328c176900a3929835f436f0 | [
"C#",
"C++"
] | 3 | C# | EzequielMonforte/ControlEstacionamiento | bef4927215fd3df91378d85d835c108d14da576c | b2038b934d5abd125f21526aa75acb7a8177de90 |
refs/heads/master | <repo_name>sanjevk/Atom<file_sep>/hello.py
print("Sanjev")
print("Habeeb New")
| 87bbb434dc694db29f973cfd45ade371acdad70d | [
"Python"
] | 1 | Python | sanjevk/Atom | 6faef8a7a8b3fef494c0d1b0279963dab6a510e3 | 26e13ea360de61d53cca4e872316ee1a52d7606a |
refs/heads/master | <file_sep>---
title: "Getting Started"
weight: 1
anchors:
- title: "Requirements"
url: "#requirements"
- title: "Installation"
url: "#installation"
- title: "Configuration"
url: "#configuration"
- title: "Setup"
url: "#setup"
- title: "Create a template"
url: "#create-a-template"
- title: "Create a new stack"
url: "#create-a-new-stack"
- title: "Template refactor"
url: "#template-refactor"
- title: "Stack update"
url: "#stack-update"
- title: "Stack information"
url: "#stack-information"
- title: "Clean up"
url: "#clean-up"
---
## Requirements
* Ruby (Version `>=` 2.3)
* Provider Credentials
### Installing Ruby
There are a variety of ways to install Ruby depending on platform and toolset. The
Ruby website provides information about many of the installation options:
* [Installing Ruby](https://www.ruby-lang.org/en/documentation/installation/)
### Installing Bundler
Once Ruby is installed, install Bundler using the `gem` command:
~~~
$ gem install bundler
~~~
### Provider credentials
Required credentials differ based on the target provider in use. For more information
about credentials specific to a certain provider, reference the miasma library for
the provider:
* [miasma-aws](https://github.com/miasma-rb/miasma-aws)
* [miasma-azure](https://github.com/miasma-rb/miasma-azure)
* [miasma-google](https://github.com/miasma-rb/miasma-google)
* [miasma-open-stack](https://github.com/miasma-rb/miasma-open-stack)
* [miasma-rackspace](https://github.com/miasma-rb/miasma-rackspace)
* [miasma-terraform](https://github.com/miasma-rb/miasma-terraform)
## Installation
First, install the `sfn` gem:
~~~
$ gem install sfn
~~~
Now initialize a new project:
~~~
$ sfn init sparkle-guide
~~~
Finally change to the new project directory:
~~~
$ cd sparkle-guide
~~~
## Configuration
The `init` command will have automatically generated a configuration file
within the project directory. To view the current configuration status the
`conf` command can be used:
~~~
$ bundle exec sfn conf
~~~
The configuration file for `sfn` is located within the `.sfn` file. Open this file
and adjust the credentials section for your desired provider. The generated
configuration file uses environment variables for provider configuration. This
style of setup makes it easy to automatically set credential information using
tools like direnv. Environment variable usage is not required, and credential
values can be provided directly.
_NOTE: It is important to **not** store provider credential secrets within the
`.sfn` file if it will be checked into source control._
### Test configuration
Test the configuration by running a list command:
~~~
$ bundle exec sfn list
~~~
This should print a list of existing stacks on the configured provider. If no
stacks exist, no entries will be shown. If an error message is received, check
that the credentials information is properly set and try again.
## Create a template
Lets start by creating a full template. This template will create a compute resource
on the desired provider and output the remote public address of the new compute instance.
Create a new file: `./sparkleformation/compute.rb`:
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:compute, :provider => :aws) do
AWSTemplateFormatVersion '2010-09-09'
description 'Sparkle Guide Compute Template'
parameters do
sparkle_image_id.type 'String'
sparkle_ssh_key_name.type 'String'
sparkle_flavor do
type 'String'
default 't2.micro'
allowed_values ['t2.micro', 't2.small']
end
end
dynamic!(:ec2_instance, :sparkle) do
properties do
image_id ref!(:sparkle_image_id)
instance_type ref!(:sparkle_flavor)
key_name ref!(:sparkle_ssh_key_name)
end
end
outputs.sparkle_public_address do
description 'Compute instance public address'
value attr!(:sparkle_ec2_instance, :public_ip)
end
end
~~~
#### Template sparkles HEAT
~~~ruby
SparkleFormation.new(:compute, :provider => :open_stack) do
heat_template_version '2015-04-30'
description 'Sparkle Guide Compute Template'
parameters do
sparkle_image_id.type 'String'
sparkle_ssh_key_name.type 'String'
sparkle_flavor do
type 'String'
default 't2.small'
allowed_values ['m1.small', 'm1.medium']
end
end
dynamic!(:nova_server, :sparkle) do
properties do
image ref!(:sparkle_image_id)
flavor ref!(:sparkle_flavor)
key_name ref!(:sparkle_ssh_key_name)
end
end
outputs.sparkle_public_address do
description 'Compute instance public address'
value attr!(:sparkle_nova_instance, 'accessIPv4')
end
end
~~~
#### Template sparkles Azure
~~~ruby
SparkleFormation.new(:compute, :provider => :azure) do
set!('$schema', 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#')
content_version '1.0.0.0'
parameters do
sparkle_image_id do
type 'string'
default_value '14.04.2-LTS'
end
sparkle_flavor do
type 'string'
allowed_values [
'Standard_D1'
]
end
storage_account_name.type 'string'
storage_container_name.type 'string'
end
dynamic!(:network_public_ip_addresses, :sparkle) do
properties do
set!('publicIPAllocationMethod', 'Dynamic')
dns_settings.domain_name_label 'sparkle'
end
end
dynamic!(:network_virtual_networks, :sparkle) do
properties do
address_space.address_prefixes ['10.0.0.0/16']
subnets array!(
->{
name 'sparkle-subnet'
properties.address_prefix '10.0.0.0/24'
}
)
end
end
dynamic!(:network_interfaces, :sparkle) do
properties.ip_configurations array!(
->{
name 'ipconfig1'
properties do
set!('privateIPAllocationMethod', 'Dynamic')
set!('publicIPAddress').id resource_id!(:sparkle_network_public_ip_addresses)
subnet.id concat!(resource_id!(:sparkle_network_virtual_networks), '/subnets/sparkle-subnet')
end
}
)
end
dynamic!(:compute_virtual_machines, :sparkle) do
properties do
hardware_profile.vm_size parameters!(:sparkle_flavor)
os_profile do
computer_name 'sparkle'
admin_username 'sparkle'
admin_password '<PASSWORD>'
end
storage_profile do
image_reference do
publisher 'Canonical'
offer 'UbuntuServer'
sku parameters!(:sparkle_image_id)
version 'latest'
end
os_disk do
name 'osdisk'
vhd.uri concat!('http://', parameters!(:storage_account_name), '.blob.core.windows.net/', parameters!(:storage_container_name), '/sparkle.vhd')
caching 'ReadWrite'
create_option 'FromImage'
end
data_disks array!(
->{
name 'datadisk1'
set!('diskSizeGB', 100)
lun 0
vhd.uri concat!('http://', parameters!(:storage_account_name), '.blob.core.windows.net/', parameters!(:storage_container_name), '/sparkle-data.vhd')
create_option 'Empty'
}
)
end
network_profile.network_interfaces array!(
->{ id resource_id!(:sparkle_network_interfaces) }
)
end
end
outputs.sparkle_public_address do
type 'string'
value reference!(:sparkle_network_public_ip_addresses).ipAddress
end
end
~~~
### View template
View the processed JSON result:
~~~
$ bundle exec sfn print --file compute
~~~
This will output the serialized JSON template generated by SparkleFormation. The JSON is the template
content which will be sent to the remote provider API with the stack create request.
## Create a new stack
After seeing the result of the compiled and serialized template, lets use that template to
create a new stack. To start the stack creation process run the following command:
~~~
$ bundle exec sfn create sparkle-guide-compute --file compute
~~~
Before creating this new stack, `sfn` will prompt for the parameters defined within the template.
The `sparkle_image_id` and `sparkle_ssh_key_name` parameters are not defined with default values within the template,
so values _must_ be provided when prompted. The prompt for the `sparkle_flavor` parameter will show the
default value defined within the template, and can be used or overridden with a different value.
After `sfn` has completed prompting for stack parameters, it will initiate the stack creation
request with the remote provider. The creation request to the API is only for initiation. A successful
response does not indicate that the stack was created successfully, rather it indicates that the request
to create the stack was successful.
Once the create request is complete, `sfn` will automatically transition to event polling. Resource
events related to the new stack will be displayed until the stack reaches a "complete" state: success
or failure. The automatic transition to event polling ensures that the `sfn create` command will return
a proper exit code once the stack has reached a completion state.
At successful completion of the stack creation, the outputs defined within the template will be displayed
showing the public address of the newly created compute instance.
## Template refactor
A key feature of SparkleFormation is the ability to break down templates into reusable parts which can
then be re-used in multiple templates. Lets break down our existing template into re-usable parts and
re-build the template using those parts.
### Registry
The registry is a place to store values that may be used in multiple places. With the value defined in
a single location, updates to the value only require one modification to apply globally. In our `compute`
example, the allowed instance flavor values would an ideal candidate for a registry entry.
Create a new file at `./sparkleformation/registry/instance_flavor.rb`
#### Registry sparkles AWS
~~~ruby
SfnRegistry.register(:instance_flavor) do
['t2.micro', 't2.small']
end
~~~
#### Registry sparkles HEAT
~~~ruby
SfnRegistry.register(:instance_flavor, :provider => :open_stack) do
['m1.small', 'm1.medium']
end
~~~
#### Registry sparkles Azure
~~~ruby
SfnRegistry.register(:instance_flavor, :provider => :azure) do
['Standard_D1']
end
~~~
_NOTE: For more information see: [Registry building blocks](../sparkle_formation/building-blocks.html#registry)_
### Component
Components are items which are used a single time within a template. The version information and description
are both items in our `compute` template that are only used a single time, but should be defined in all templates.
Lets move those items into a component.
Create a new file at `./sparkleformation/components/base.rb`
#### Component sparkles AWS
~~~ruby
SparkleFormation.component(:base) do
AWSTemplateFormatVersion '2010-09-09'
description 'Sparkle Guide Compute Template'
end
~~~
#### Component sparkles HEAT
~~~ruby
SparkleFormation.component(:base, :provider => :open_stack) do
heat_template_version '2015-04-30'
description 'Sparkle Guide Compute Template'
end
~~~
#### Component sparkles Azure
~~~ruby
SparkleFormation.component(:base, :provider => :azure) do
set!('$schema', 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#')
content_version '1.0.0.0'
end
~~~
_NOTE: For more information see: [Component building blocks](../sparkle_formation/building-blocks.html#components)_
### Dynamic
Dynamics are items which can be used multiple times within a template. A dynamic requires a custom name be provided
and allows for an optional Hash of values. Dynamics are useful for injecting a common structure into a template
multiple times. In the `compute` template above, we can now extract the remainder of the template and convert it
into a dynamic.
Create a new file at `./sparkleformation/dynamics/node.rb`
#### Dynamic sparkles AWS
~~~ruby
SparkleFormation.dynamic(:node) do |name, opts={}|
parameters do
set!("#{name}_image_id".to_sym).type 'String'
set!("#{name}_ssh_key_name".to_sym).type 'String'
set!("#{name}_flavor".to_sym) do
type 'String'
default 't2.small'
allowed_values registry!(:instance_flavor)
end
end
outputs.set!("#{name}_public_address".to_sym) do
description "Compute instance public address - #{name}"
value attr!("#{name}_ec2_instance".to_sym, :public_ip)
end
dynamic!(:ec2_instance, name) do
properties do
image_id ref!("#{name}_image_id".to_sym)
instance_type ref!("#{name}_flavor".to_sym)
key_name ref!("#{name}_ssh_key_name".to_sym)
end
end
end
~~~
#### Dynamic sparkles HEAT
~~~ruby
SparkleFormation.dynamic(:node, :provider => :open_stack) do |name, opts={}|
parameters do
set!("#{name}_image_id".to_sym).type 'String'
set!("#{name}_ssh_key_name".to_sym).type 'String'
set!("#{name}_flavor".to_sym) do
type 'String'
default 't2.small'
allowed_values registry!(:instance_flavor)
end
end
outputs.set!("#{name}_public_address".to_sym) do
description "Compute instance public address - #{name}"
value attr!("#{name}_nova_server".to_sym, 'accessIPv4')
end
dynamic!(:nova_server, name) do
properties do
image ref!("#{name}_image_id".to_sym)
flavor ref!("#{name}_flavor".to_sym)
key_name ref!("#{name}_ssh_key_name".to_sym)
end
end
end
~~~
#### Dynamic sparkles Azure
~~~~ruby
SparkleFormation.dynamic(:node, :provider => :azure) do |name, opts={}|
parameters do
set!("#{name}_image_id".to_sym) do
type 'string'
default_value '14.04.2-LTS'
end
set!("#{name}_flavor".to_sym) do
type 'string'
allowed_values registry!(:instance_flavor)
end
end
dynamic!(:network_public_ip_addresses, name) do
properties do
set!('publicIPAllocationMethod', 'Dynamic')
dns_settings.domain_name_label name
end
end
dynamic!(:network_interfaces, name) do
properties.ip_configurations array!(
->{
name 'ipconfig1'
properties do
set!('privateIPAllocationMethod', 'Dynamic')
set!('publicIPAddress').id resource_id!("#{name}_network_public_ip_addresses".to_sym)
subnet.id concat!(resource_id!("#{name}_network_virtual_networks".to_sym), '/subnets/sparkle-subnet')
end
}
)
end
dynamic!(:compute_virtual_machines, name) do
properties do
hardware_profile.vm_size parameters!("#{name}_flavor".to_sym)
os_profile do
computer_name 'sparkle'
admin_username 'sparkle'
admin_password '<PASSWORD>'
end
storage_profile do
image_reference do
publisher 'Canonical'
offer 'UbuntuServer'
sku parameters!("#{name}_image_id".to_sym)
version 'latest'
end
os_disk do
name 'osdisk'
vhd.uri concat!('http://', parameters!(:storage_account_name), '.blob.core.windows.net/', parameters!(:storage_container_name), "/#{name}.vhd")
caching 'ReadWrite'
create_option 'FromImage'
end
data_disks array!(
->{
name 'datadisk1'
set!('diskSizeGB', 100)
lun 0
vhd.uri concat!('http://', parameters!(:storage_account_name), '.blob.core.windows.net/', parameters!(:storage_container_name), "/#{name}-data.vhd")
create_option 'Empty'
}
)
end
network_profile.network_interfaces array!(
->{ id resource_id!("#{name}_network_interfaces".to_sym) }
)
end
end
outputs.set!("#{name}_public_address".to_sym) do
type 'string'
value reference!("#{name}_network_public_ip_addresses".to_sym).ipAddress
end
end
~~~~
The first thing to note about this dynamic file is the `name` argument at the top.
`SparkleFormation.dynamic(:node) do |name, opts={}|`
This variable is used throughout the dynamic to provide uniquely named parameters, resources, and outputs. Also
note the use of they registry to define the allowed values for the flavor parameter.
`allowed_values registry!(:instance_flavor)`
_NOTE: For more information see: [Dynamic building blocks](../sparkle_formation/building-blocks.html#dynamics)_
### Template
Now that the original template has been refactored into re-usable parts, lets update our `./sparkleformation/compute.rb`
template:
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:compute, :provider => :aws).load(:base).overrides do
dynamic!(:node, :sparkle)
end
~~~
#### Template sparkles HEAT
~~~ruby
SparkleFormation.new(:compute, :provider => :open_stack).load(:base).overrides do
dynamic!(:node, :sparkle)
end
~~~
#### Template sparkles Azure
~~~ruby
SparkleFormation.new(:compute, :provider => :azure).load(:base).overrides do
parameters do
storage_account_name.type 'string'
storage_container_name.type 'string'
end
dynamic!(:network_virtual_networks, :sparkle) do
properties do
address_space.address_prefixes ['10.0.0.0/16']
subnets array!(
->{
name 'sparkle-subnet'
properties.address_prefix '10.0.0.0/24'
}
)
end
end
dynamic!(:node, :sparkle)
end
~~~
The template is now greatly compacted, and composed entirely of re-usable parts. The `.load(:base)` is inserting
the base component we defined above. The `dynamic!(:node, :sparkle)` is inserting the node dynamic we defined
above and using the custom name `sparkle`. We can print this template, and see the result is the same as the original
template.
~~~
$ sfn print --file compute
~~~
## Stack update
### The NO-OP update
We can verify that our new template is the same as our original template by updating the running stack and applying
our new template:
~~~
$ sfn update sparkle-guide-compute --file compute --defaults
~~~
The `--defaults` flag will suppress prompts for stack parameters and use the existing values defined for the running
stack. The result of this command will either explicitly state that no updates were performed, or the event stream
will show that no resources were modified depending on the provider.
At the end of the run it will ask:
~~~
[Sfn]: Apply this stack update? (Y/N):
~~~
You can answer Y.
### The real update (parameters)
Now lets update the stack by modifying the paramters of the running stack. We will change the flavor of the instance
which will result in the resource being replaced within the stack. Run the update command but do not provide the `--defaults` flag:
~~~
$ sfn update sparkle-guide-compute --file compute
~~~
Now `sfn` will prompt for parameter values. Notice that the default values are the values used when creating the
stack. When the `sparkle_flavor` parameter is prompted, choose a different value from the allowed list. After the
update has completed, the outputs displayed of the stack will have changed showing a new public address for the
compute instance.
### The real update (template)
Since our template has been refactored and is now composed of re-usable parts, it's easy to quickly expand our stack.
Lets add an additional compute resource to our `./sparkleformation/compute.rb` template:
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:compute, :provider => :aws).load(:base).overrides do
dynamic!(:node, :sparkle)
dynamic!(:node, :unicorn)
end
~~~
#### Template sparkles HEAT
~~~ruby
SparkleFormation.new(:compute, :provider => :open_stack).load(:base).overrides do
dynamic!(:node, :sparkle)
dynamic!(:node, :unicorn)
end
~~~
#### Template sparkles Azure
~~~ruby
SparkleFormation.new(:compute, :provider => :azure).load(:base).overrides do
parameters do
storage_account_name.type 'string'
storage_container_name.type 'string'
end
dynamic!(:network_virtual_networks, :sparkle) do
properties do
address_space.address_prefixes ['10.0.0.0/16']
subnets array!(
->{
name 'sparkle-subnet'
properties.address_prefix '10.0.0.0/24'
}
)
end
end
dynamic!(:node, :sparkle)
dynamic!(:node, :unicorn)
end
~~~
Printing the template we can see that by adding a single line we have added not only a new resource to our template,
but a new output as well.
~~~
$ sfn print --file compute
~~~
Now we can apply this updated template to our existing stack. On this update command, we _must_ provide the `--file`
flag so our modified template will be sent in our request:
~~~
$ sfn update sparkle-guide-compute --file compute
~~~
When `sfn` prompts for parameters, the previously seen `sparkle` parameters will be requested, but we will also
see new `unicorn` parameters requested for the new compute resource we added. After the update has completed the
stack outputs will be displayed and will now include two public addresses: one for `sparkle` and one for `unicorn`.
## Stack information
With stacks currently existing on the remote provider, we can now use the inspection commands:
~~~
$ sfn list
~~~
Will provide a list of current stacks. This may include only the `sparkle-guide-compute` stack or it may include
other stacks that were created by other users or the provider itself.
We can also describe a specific stack. The describe command will list all the resources composing the requested
stack, as well as any stack outputs defined for the stack:
~~~
$ sfn describe sparkle-guide-compute
~~~
## Clean up
To conclude this guide, we want to be sure to remove the example stack we created. This is done using the
destroy command:
~~~
$ sfn destroy sparkle-guide-compute
~~~
<file_sep>Gem::Specification.new do |s|
s.name = 'sparkle-guides'
s.version = '0.1.12'
s.summary = 'SparkleFormation Guides'
s.author = '<NAME>'
s.email = '<EMAIL>'
s.homepage = 'http://github.com/sparkleformation/sparkle-guides'
s.description = 'SparkleFormation Usage Guides'
s.license = 'Apache-2.0'
s.files = Dir['docs/**/*'] + %w(sparkle-guides.gemspec README.md CHANGELOG.md)
end
<file_sep>---
title: "Stack Dependencies"
weight: 2
anchors:
- title: "Overview"
url: "#overview"
- title: "Apply stack"
url: "#apply-stack-implementation"
- title: "Nested stack"
url: "#nested-stack-implementation"
- title: "Apply nested stack"
url: "#apply-nested-stack"
- title: "Cross location"
url: "#cross-location"
---
## Overview
### Apply stack
The SparkleFormation CLI includes functionality to ease the sharing
of resources between isolated stacks. This functionality enables
groupings of similar resources which can define logical units of
a full architecture. The sharing is accomplished using a combination
of stack outputs and stack parameters. This feature is commonly
referred to as the _apply stack_ functionality.
One drawback of the _apply stack_ functionality is that it introduces
dependencies between disparate stacks. These dependencies must be
manually resolved when resource modifications occur. When an infrastructure
is composed of few stacks, the _apply stack_ approach can be sufficient
to manage stack dependencies leaving the user to ensure updates are
properly applied. For larger implementations composed of many interdependent
stacks, the _nested stack_ functionality is recommended.
### Nested stack
_Nested stack_ functionality is a generic feature provided by the SparkleFormation
library which the SparkleFormation CLI then specializes based on the target provider.
The _nested stack_ functionality utilizes a core feature provided by orchestration
APIs. This features allows nesting stack resources within a stack allowing a
parent stack to have many child stacks. By nesting stack resources, the provider
API will be aware of child stack interdependencies and automatically apply updates
when resources have been modified. This removes the requirement of stack updates
being tracked and applied manually.
The behavior of the _nested stack_ functionality is based directly on the
behavior of the _apply stack_ functionality. This commonality in behavior
allows for initial testing development using the _apply stack_ functionality
and, once stable, migrating to _nested stack_ functionality without requiring any
modifications to existing templates. The commonality also allows for the two
functionalities to be mixed in practice.
This guide will first display template implementations using the _apply stack_
functionality. The example templates will then be used to provide a _nested stack_
implementation.
_NOTE: This guide targets the AWS provider for simplicity to allow focus on the
features discussed. All providers support this behavior._
## Apply stack implementation
Lets start by defining a simple infrastructure. Our infrastructure will be composed
of a "network" and a collection of "computes" that utilizes the network. This
infrastructure can be easily defined within two units:
1. network
2. computes
Lets start by creating a simple `network` template.
Create a new file: `./sparkleformation/network.rb`
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:network) do
parameters do
cidr_prefix do
type 'String'
default '172.20'
end
end
dynamic!(:ec2_vpc, :network) do
properties do
cidr_block join!(ref!(:cidr_prefix), '.0.0/24')
enable_dns_support true
enable_dns_hostnames true
end
end
dynamic!(:ec2_dhcp_options, :network) do
properties do
domain_name join!(region!, 'compute.internal')
domain_name_servers ['AmazonProvidedDNS']
end
end
dynamic!(:ec2_vpc_dhcp_options_association, :network) do
properties do
dhcp_options_id ref!(:network_ec2_dhcp_options)
vpc_id ref!(:network_ec2_vpc)
end
end
dynamic!(:ec2_internet_gateway, :network)
dynamic!(:ec2_vpc_gateway_attachment, :network) do
properties do
internet_gateway_id ref!(:network_ec2_internet_gateway)
vpc_id ref!(:network_ec2_vpc)
end
end
dynamic!(:ec2_route_table, :network) do
properties.vpc_id ref!(:network_ec2_vpc)
end
dynamic!(:ec2_route, :network_public) do
properties do
destination_cidr_block '0.0.0.0/0'
gateway_id ref!(:network_ec2_internet_gateway)
route_table_id ref!(:network_ec2_route_table)
end
end
dynamic!(:ec2_subnet, :network) do
properties do
availability_zone select!(0, azs!)
cidr_block join!(ref!(:cidr_prefix), '.0.0/24')
vpc_id ref!(:network_ec2_vpc)
end
end
dynamic!(:ec2_subnet_route_table_association, :network) do
properties do
route_table_id ref!(:network_ec2_route_table)
subnet_id ref!(:network_ec2_subnet)
end
end
outputs do
network_vpc_id.value ref!(:network_ec2_vpc)
network_subnet_id.value ref!(:network_ec2_subnet)
network_route_table.value ref!(:network_ec2_route_table)
network_cidr.value join!(ref!(:cidr_prefix), '.0.0/24')
end
end
~~~
Here we have an extremely simple VPC defined for our infrastructure. It is
important to note the outputs defined within our `network` template. These
outputs are values that will be required for other resources to effectively
utilize the VPC. With the `network` template defined, we can create that unit
of our infrastructure:
~~~
$ bundle exec sfn create sparkle-guide-network --file network
~~~
Having successfully built the `network` unit of the infrastructure, we can
now compose the `computes` template.
Create a new file: `./sparkleformation/computes.rb`
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:computes) do
parameters do
ssh_key_name.type 'String'
network_vpc_id.type 'String'
network_subnet_id.type 'String'
image_id_name do
type 'String'
default 'ami-63ac5803'
end
end
dynamic!(:ec2_security_group, :compute) do
properties do
group_description 'SSH Access'
security_group_ingress do
cidr_ip '0.0.0.0/0'
from_port 22
to_port 22
ip_protocol 'tcp'
end
vpc_id ref!(:network_vpc_id)
end
end
dynamic!(:ec2_instance, :micro) do
properties do
image_id ref!(:image_id_name)
instance_type 't2.micro'
key_name ref!(:ssh_key_name)
network_interfaces array!(
->{
device_index 0
associate_public_ip_address 'true'
subnet_id ref!(:network_subnet_id)
group_set [ref!(:compute_ec2_security_group)]
}
)
end
end
dynamic!(:ec2_instance, :small) do
properties do
image_id ref!(:image_id_name)
instance_type 't2.micro'
key_name ref!(:ssh_key_name)
network_interfaces array!(
->{
device_index 0
associate_public_ip_address 'true'
subnet_id ref!(:network_subnet_id)
group_set [ref!(:compute_ec2_security_group)]
}
)
end
end
outputs do
micro_address.value attr!(:micro_ec2_instance, :public_ip)
small_address.value attr!(:small_ec2_instance, :public_ip)
end
end
~~~
Our `computes` template will create one micro and one small EC2
instance and output the public IP addresses of each resource. To
build the EC2 instances into the VPC created in the `sparkle-guide-network`
stack we need two pieces of information:
* VPC ID
* VPC subnet ID
In our `computes` template we define two parameters for the required
VPC information: `network_vpc_id` and `network_subnet_id`. When we
create a stack using this template we can copy the output values from the
`sparkle-guide-network` stack and paste them into these parameters, but
that is extremely cumbersome. The SparkleFormation CLI instead allows
"applying" a stack on creation or update.
Notice that the output names in our `network` template match the parameter
names in our `computes` template.
~~~ruby
# From ./sparkleformation/network.rb
outputs do
network_vpc_id.value ref!(:network_ec2_vpc)
network_subnet_id.value ref!(:network_ec2_subnet)
network_route_table.value ref!(:network_ec2_route_table)
network_cidr.value join!(ref!(:cidr_prefix, '.0.0/24'))
end
# From ./sparkleformation/computes.rb
parameters do
ssh_key_name.type 'String'
network_vpc_id.type 'String'
network_subnet_id.type 'String'
end
~~~
The apply stack functionality will automatically collect outputs from
the stack names provided and use them to seed the parameters of the
stack being created or updated. This means instead of having to copy
and paste the VPC ID and subnet ID values, we can instruct the SparkleFormation
CLI to automatically use the outputs of our `sparkle-guide-network` stack:
~~~
$ bundle exec sfn create sparkle-guide-computes --file computes --apply-stack sparkle-guide-network
~~~
During the create process, the SparkleFormation CLI will prompt for parameters. The
default values for the VPC ID and subnet ID will be automatically inserted, matching
the outputs from the `sparkle-guide-network`.
You can destroy the sparkle-guide-compute and sparkle-guide-network stacks as they will not be used in the next section.
~~~
$ sfn destroy sparkle-guide-computes
$ sfn destroy sparkle-guide-network
~~~
## Nested stack implementation
Now that our infrastructure has been successfully created using disparate stacks, lets
combine them to create a single `infrastructure` unit composed of sub-units. Using
nested stacks requires a bucket to store templates. Create a bucket in S3 and then
add the following to the `.sfn` configuration file:
~~~ruby
Configuration.new do
...
nesting_bucket 'NAME_OF_BUCKET'
...
end
~~~
With the required bucket in place and SparkleFormation CLI configured we can
now create our `infrastructure` template.
Create a new file: `./sparkleformation/infrastructure.rb`
#### Template sparkles AWS
~~~ruby
SparkleFormation.new(:infrastructure) do
nest!(:network, :infra)
nest!(:computes, :infra)
end
~~~
This new `infrastructure` template is using SparkleFormation's builtin nesting
functionality to create stack resources within our `infrastructure` template
composed of our `network` and `computes` template. To see the conceptual result
of this nesting, we can print the `infrastructure` template:
~~~
$ bundle exec sfn print --file infrastructure
~~~
There are a few things of note in this output. First, the `Stack` property is
not a real resource property. It is used by SparkleFormation for template processing
and is included in print functions to display the template in its entirety. Next,
the generated URLs are not real URLs. This is due to the SparkleFormation CLI not
actually storing the templates in the remote bucket. Lastly, and most importantly,
the parameters property of the `ComputesInfra` resource.
~~~json
"Parameters": {
"NetworkVpcId": {
"Fn::GetAtt": [
"NetworkInfra",
"Outputs.NetworkVpcId"
]
},
"NetworkSubnetId": {
"Fn::GetAtt": [
"NetworkInfra",
"Outputs.NetworkSubnetId"
]
}
}
~~~
SparkleFormation registers outputs when processing templates and will automatically
map outputs to subsequent stack resource parameters if they match. Cross stack resource
dependencies are now explicitly defined allowing the orchestration API to automatically
determine creation order as well as triggering updates when required.
Now we can create our full infrastructure with a single command:
~~~
$ bundle exec sfn create sparkle-guide-infrastructure --file infrastructure
~~~
As SparkleFormation processes the nested templates for the `create` command, the SparkleFormation
CLI will extract the nested templates, store them in the configured nesting bucket, and updates
the template location URL in the resource.
Using nested templates, `update` commands follow the same behavior as `create` commands. All nested
templates are extracted and automatically uploaded prior to execution of the `update` request with
the orchestration API. This results in _all_ nested stacks being automatically updated by the API
as required based on dependent resource modifications.
## Apply nested stack
Nested stacks can be applied to disparate stacks in the same manner described in the apply
stack implementation section. When the stack to be applied is a nested stack, SparkleFormation
CLI will gather outputs from all the nested stacks, and then apply to the target command. This
means using the `sparkle-guide-infrastructure` stack we previously built can be used for creating
new `computes` stacks without being nested into the `infrastructure` template.
~~~
$ bundle exec sfn create sparkle-guide-computes-infra --file computes --apply-stack sparkle-guide-infrastructure
~~~
The ability to apply nested stacks to disparate stacks make it easy to provide resources to new
stacks, or to test building new stacks in isolation before being nested into the root stack.
You can destroy the all the `infrastructure` related stacks with the command:
~~~
sfn destroy sparkle-guide-infrastructure
~~~
## Cross location
SparkleFormation supports accessing stacks in other locations when using the
apply stack functionality. This is done by configuring named locations within
the `.sfn` configuration file and then referencing the location when applying
the stack. Using this example `.sfn` configuration file:
~~~ruby
Configuration.new do
credentials do
provider :aws
aws_access_key_id 'KEY'
aws_secret_access_key 'SECRET'
aws_region 'us-east-1'
end
locations do
west_stacks do
provider :aws
aws_access_key_id 'KEY'
aws_secret_access_key 'SECRET'
aws_region 'us-west-2'
end
end
end
~~~
This configuration connects to the AWS API in us-east-1. It also includes configuration
for connecting to us-west-2 via a named location of `west_stacks`. This allows referencing
stacks located in us-west-2 when using the apply stack functionality. Assume a new stack
is being created in us-east-1 (my-stack) and the outputs from other-stack in us-west-2
should be applied. This can be accomplished with the following command:
~~~
sfn create my-stack --apply-stack west_stacks__my-stack
~~~
When the stack is created sfn will first connect to the us-west-2 API and gather the
outputs from other-stack, then it will connect to us-east-1 to create the new stack.
_NOTE: Custom locations are not required to have a common provider._
<file_sep># v0.1.12
* Include cross location apply stack example
* Start tips and tricks
# v0.1.8
* Update non-default type files with provider flag
# v0.1.6
* Fixes for syntax, instructions, and removal of m1 types (#8)
* Thanks @rberger!
# v0.1.4
* Update file system layout.
* Fix YAML error on guide header.
# v0.1.2
* Add apply and nesting guide
# v0.1.0
* Initial guides release (getting started)
<file_sep># SparkleFormation Guides
see: http://www.sparkleformation.io/docs/guides<file_sep>---
title: "Tips and Tricks"
weight: 3
anchors:
- title: "Stubbing builtins"
url: "#stubbing-builtins"
- title: "Resource conflicts"
url: "#resource-conflicts"
---
## Stubbing builtins
SparkleFormation provides a number of builtin resources using the
`dynamic!` helper. These known resources are collected when SparkleFormation
is released. Because this is a static list of resource types it is
common for new resources to be introduced within a cloud provider
and not be available within SparkleFormation. Since the new resource
types will not be available within SparkleFormation until the next
release, stubbing the builtin will provide the same behavior as if
it were included within the builtin list.
For example, lets assume that AWS CloudFormation introduces a new
resource type named `AWS::JVM::Instance`. To stub this resource a
new dynamic can be created locally:
~~~ruby
SparkleFormation.dynamic(:jvm_instance) do |name|
resources.set!("#{name}_jvm_instance".to_sym) do
type "AWS::JVM::Instance"
end
end
~~~
With this dynamic defined it will behave the same as if it were
defined in the builtin list:
~~~ruby
SparkleFormation.new(:test) do
dynamic!(:jvm_instance, :test) do
properties.memory 512
end
end
~~~
which results in:
~~~json
{
"Resources": {
"TestJvmInstance": {
"Type": "AWS::JVM::Instance",
"Properties": {
"Memory": 512
}
}
}
}
~~~
Once the `AWS::JVM::Instance` becomes available in the builtin
list within SparkleFormation the custom stub dynamic can be deleted.
## Resource conflicts
Resource conflicts can occur when the same resource name is used
in multiple resource namespaces. If a template has created resources
using the `dynamic!` helper and not included the resource's namespace,
conflicts will occur when the new resource becomes available. An
example of this is the `AWS::ElasticLoadBalancing::LoadBalancer` resource.
Assume that the following template is in use:
~~~ruby
SparkleFormation.new(:lb) do
dynamic!(:load_balancer, :app)
end
~~~
and it generates:
~~~json
{
"Resources": {
"AppLoadBalancer": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer"
}
}
}
~~~
Now, AWS releases a new resource with a conflicting name
`AWS::ElasticLoadBalancingV2::LoadBalancer` and SparkleFormation's internal
resource list has been updated. When the template is run again, it returns
an error about conflicting resource names. One solution is to update the
`dynamic!` call to include the namespace:
~~~ruby
SparkleFormation.new(:lb) do
dynamic!(:elastic_load_balancing_load_balancer, :app)
end
~~~
and it will then generate:
~~~json
{
"Resources": {
"AppElasticLoadBalancingLoadBalancer": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer"
}
}
}
~~~
This resolves the conflict issue, yet in practice the modification of the
resource name will likely cause issues in complex templates where the
resource is being referenced in other locations. To allow templates to
remain unchanged, a new dynamic can be introduced which will force matching
of the `:load_balancer` name to the local dynamic:
~~~ruby
SparkleFormation.dynamic(:load_balancer) do |name|
dynamic!(:elastic_load_balancing_load_balancer, name, :resource_name_suffix => :load_balancer)
end
~~~
With this dynamic in place, all original templates will continue to behave
as expected without individual modifications.
| 9937359deabcc1c56e534c11fa91d0cf54f5cb50 | [
"Markdown",
"Ruby"
] | 6 | Markdown | sparkleformation/sparkle-guides | c798285e0d42a0ec1256a2d757bd5ed2f496e908 | 864b688e5c4702b894bbf6fcd5e8605e110e80f2 |
refs/heads/master | <file_sep><?php
//include '../../controlador/conexion.php';
include_once '../../libreria/conexion.php';
function getContraparteById($id_contraparte){
$sql = "select * from contraparte where id_contraparte='".$id_contraparte."'";
//echo $sql;
$lista = consulta($sql);
return $lista;
}
function getContrapartesById($id_expediente){
$sql = "select * from contraparte as contra
inner join contraparte_expediente as detalle using(id_contraparte)
where detalle.id_expediente='".$id_expediente."'";
//echo $sql;
$lista = consulta($sql);
return $lista;
}
function getUsuarioByCurp($curp){
$sql = "select * from usuario_servicio where curp='".$curp."'";
$consulta = consulta($sql);
// echo $sql;
return $consulta;
}
//("insert ignore into test_warnings (id_, num_) values (?,?)
//Definimos la funciones sobre el objeto crear_defensor
function crear_contraparte($objetoEntidad){
$sql="INSERT INTO contraparte(id_contraparte,nombre,apellido_paterno,apellido_materno,sexo,fecha_nacimiento,edad,";
$sql.="etnia,idioma,entidad,genero,telefono,email,calle,curp,discapacidad) values(";
$sql.="'".$objetoEntidad['id_contraparte']."',"."'".$objetoEntidad['nombre']."',"."'".$objetoEntidad['ap_paterno']."',";
$sql.="'".$objetoEntidad['ap_materno']."',"."'".$objetoEntidad['sexo']."',"."'".$objetoEntidad['fecha_nacimiento']."',";
$sql.="'".$objetoEntidad['edad']."',"."'".$objetoEntidad['etnia']."',"."'".$objetoEntidad['idioma']."',";
$sql.="'".$objetoEntidad['estado']."',"."'".$objetoEntidad['genero']."',"."'".$objetoEntidad['telefono']."',";
$sql.="'".$objetoEntidad['correo']."',"."'".$objetoEntidad['calle']."',"."'".$objetoEntidad['curp']."',";
$sql.="'".$objetoEntidad['discapacidad']."')";
$lista=registro($sql);
// echo $lista;
return $lista;
}
//Definimos una funcion que acutualice al Contraparte
function actualizar_Contraparte($contraparte){
$sql = "update contraparte set ";
$sql.= "nombre='".$contraparte['nombre']."',";
$sql.= "apellido_paterno='".$contraparte['apellido_paterno']."',";
$sql.= "apellido_materno='".$contraparte['apellido_materno']."',";
$sql.= "etnia='".$contraparte['etnia']."',";
$sql.= "idioma='".$contraparte['idioma']."',";
$sql.= "telefono='".$contraparte['telefono']."',";
$sql.= "genero='".$contraparte['genero']."',";
$sql.= "discapacidad='".$contraparte['discapacidad']."',";
$sql.= "email='".$contraparte['email']."'";
$sql.=" where id_contraparte='".$contraparte['id_contraparte']."'";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
//Definimos una funcion que borrar defensor
function eliminar_Contraparte($id_defensor){
//$sql = "DELETE from defensor where id_defensor = '".$id_defensor."'";
$sql = "UPDATE defensor as d inner join personal as p using (id_personal)
set d.estado = false, p.estado=false where id_defensor = '".$id_defensor."'";
$lista = consulta($sql);
return $lista;
}
function ultimoUsuarioCreado(){
$sql = mysql_query("SELECT MAX(id_defensor) AS id FROM usuario_servicio");
$id=consulta($sql);
return $id[0]['id'];
}
function listar_contraparte(){
$sql="SELECT * FROM contraparte";
$lista=consulta($sql);
return $lista;
}
?>
<file_sep><?php
function returnBool(){
return 201;
}
?><file_sep>function informeGByDefPeriodo(nombreDef, sistema, actividades){
console.time('Test informeGPeriodo');
var fechaI = document.getElementById('inputInicio').value;
var fechaFi = document.getElementById('inputFinal').value;
var fecha1 = new Date(fechaI);
var fecha2 = new Date(fechaFi);
var meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"];
var tablaSexo={}, tablaGenero={},tablaGeneral={}, tablaEdad={}, tablaEtnia={}, tablaIdioma={}, tablaDiscapacidad={};
var tablaTop = {};
console.log(sistema, ' valor sistemaaa');
tablaGeneral = getTablaGeneral(sistema);
tablaSexo = getTablaSexo(sistema);
tablaGenero=getTablaGenero(sistema);
tablaEdad = getTablaEdad(sistema);
tablaEtnia = getTablaEtnias(sistema);
tablaIdioma = getTablaIdiomas(sistema);
tablaDiscapacidad = getTablaDiscapacidad(sistema);
var pdfAct = {
watermark: { text: 'www oaxaca gob mx', color: 'gray', opacity: 0.3, bold: true, italics: false },
pageSize: 'A4',
pageOrientation: 'portrait',
header: {
margin: [105, 20, 100, 0],
columns: [
{
// usually you would use a dataUri instead of the name for client-side printing
// sampleImage.jpg however works inside playground so you can play with it
image: 'data:image/png;base64,' + base64, width: 400, height: 60
}
]
},
footer: function (currentPage, pageCount) {
return {
table: {
widths: ['*', 00],
body: [
[
{ text: 'Pág. ' + currentPage + ' de ' + pageCount + ' ', alignment: 'center', bold: true, color: 'gray' }
]
]
},
layout: 'noBorders',
};
},
// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [80, 60, 40, 60],
content: [
{
stack: [
'“2018, AÑO DE LA ERRADICACIÓN DEL TRABAJO INFANTIL”',
{
text: '<NAME>, <NAME>, Oax; ' + primerM + siguiente + '.\n' +
'Periodo de ' + fechaI + ' a ' + fechaFi, style: 'subheader'
},
],
style: 'header'
},
{ text: 'A continuación se presenta el informe del defensor: '+nombreDef +' donde se han registrado ' +actividades.actividadesPorSistema+' actividades generales, los cuales son ASESORIAS JURIDICAS, AUDIENCIAS, Y VISITAS CARCELARÍAS.', style: 'textoJustificado'},
{ text: '1.- ASESORÍAS JURÍDICAS', style: 'subheader2' },
{ text: 'Con el objetivo de contribuir a una justicia pronta, expedita e imparcial, durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' de '+fecha2.getFullYear()+', el defensor brindó ' + actividades.actAsesoria + ' servicios gratuitos de asesorías jurídicas generales, lo anterior se detalla de la siguiente manera:', style: 'textoJustificado' },
tablaGeneral,
{ text: 'Del total general de asesorías jurídicas, a continuación se desglosan los atributos de los beneficiarios:', style: 'textoJustificado' },
tablaSexo,
tablaGenero,
{ text: '\n ', style: 'saltoLinea' },
tablaEdad,
tablaEtnia,
{ text: '', style: 'saltoLinea' }, { text: '\n\n', style: 'saltoLinea' },
tablaIdioma,
tablaDiscapacidad,
{ text: '2.- AUDIENCIAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()]+' de '+fecha2.getFullYear()+', el defensor '+nombreDef+' asistio a '+actividades.actAudiencia+' audiencias celebradas.', style: 'textoJustificado'
},
{ text: '3.- VISITAS CARCELARÍAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] +' de '+fecha2.getFullYear()+', el defensor '+nombreDef+' asistio a '+actividades.actVisita+' visitas carcelarias a sus internos.', style: 'textoJustificado'
},
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'C.c.p.-', style: ['quote', 'small'] },
{
text: 'Mtro. <NAME>.- Director de la Defensoría Pública del Estado de Oaxaca.- Para su conocimiento e intervención.- Presente.-C.P <NAME>.- Secretario Técnico.- Para mismo fin.- Presente Exp. y minutario.', style: ['quote', 'small']
}
]
]
}, layout: 'noBorders'
}
],
styles: {
header: {
fontSize: 8,
bold: false,
alignment: 'center',
margin: [0, 40, 0, 10]
},
subheader: {
fontSize: 10,
alignment: 'right',
margin: [0, 10, 0, 0]
},
textoJustificado: {
fontSize: 11,
alignment: 'justify',
margin: [0, 0, 15, 15],
},
subheader2: {
fontSize: 11,
alignment: 'left',
margin: [0, 0, 15, 15],
bold: 'true'
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
saltoLinea: {
margin: [0, 200, 0, 0]
},
quote: {
italics: true
},
small: {
fontSize: 8
}
},
defaultStyle: {
// alignment: 'justify'
}
}
console.timeEnd('Test informeGPeriodo');
return pdfAct;
} <file_sep><?php
include_once( '../../controlador/juzgado/actividad_juzgado.php');
?>
<script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script>
<script>
function cerrarCambio(){
$('#cambio').children().remove();
}
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Cambio de adscripcion</label></h1>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="agregarjuzado" onclick="agrega()"><h3><label class="control-label col-md-4 col-sm-3 col-xs-12 text-muted" >agregar Juzgado</label></h3></a>
</li>
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close" onclick="cerrarCambio()"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form class="" action ="../../controlador/juzgado/actividad_juzgado.php?tipo=html" object="defensor" method="post">
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Nue <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" value="<?php echo $_GET['nue']?>" readonly pattern="[0-9]{5}" title="solo numero de 5 digito" required name="nue" id="nue" required="required" class="form-control col-md-7 col-xs-12"/>
</div>
</div>
<div class="form-group ">
<h4><label class="control-label col-md-3 col-sm-3 col-xs-12 ">adscripcion</label>
</h4> <div class="col-md-6 col-sm-6 col-xs-12">
<select name="adscripcion" class="select2_group form-control">
<?php
$juzgadosRegion=json_decode($contenidojuzgado);
foreach($juzgadosRegion as $obj=>$valores){
// echo $obj."fsdfwegfwefwefwef";
echo ' <optgroup label="'.$obj.'">';
foreach($valores as $valor){
echo '<option value='.$valor->id_juzgado.'>'.$valor->nombre.'</option> ';
}
echo '</optgroup>';
}
?>
</select>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="asignarAdscripcion" type ="submit" class="btn btn-succes btn btn-success btn-lg" value="cambiar"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</div>
<file_sep><?php
$link = mysql_connect("localhost", "root", "");
mysql_select_db("bddefensoria", $link);
$result = mysql_query("drop DATABASE if EXISTS bddefensoria", $link);
if ($result == 0) {
echo "Error intente más tarde";
} else {
echo "Se elimino la base de datos exitosamente";
}
mysql_close($link);
<file_sep><?php
include_once('../../modelo/expediente.php');
$respuesta = Array(
"id_expediente" =>$_POST['id_expediente'],
"fecha_final" =>$_POST['fecha_final'],
"observaciones" =>$_POST['observacion']
);
//$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
//if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
//print_r($respuesta);
{finalizarExpediente($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"finalizacion exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
/* else
echo "el registro ya existe";
*/
?><file_sep><?php
include '../../modelo/juzgado.php';
$juzgado = Array(
"juzgado" =>$_POST['juzgado'],
"region" =>$_POST['region'],
"calle" =>$_POST['calle'],
"numero_juzgado" =>$_POST['numero'],
"numero_extension" =>$_POST['numero_extension'],
"municipio" =>$_POST['municipio'],
"cp" =>$_POST['cp'],
"num_telefono" =>$_POST['telefono'],
"colonia" =>$_POST['colonia']
);
crear_juzgado($juzgado);
if(!isset($_GET['tipo'])){
session_start();
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
$_SESSION['mensaje'] = $mensaje;
header("location: ../../vistas/administrador/index.php?dirigir='registrar_defensor'");
}
else{
header('Content-Type: application/json');
echo "json";
}
?><file_sep><?php
include_once('../../libreria/conexion.php');
/*
select d.nombre as defensor, count( select actAs.id_actividad
from asesorias inner join actividad as act
where actAs.id_actividad = 5
) as numAses
from actividades left join.....
*/
function getActividadesByPeriodoCP($fi,$ff, $sistema, $atributos){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo as pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
and m.sistema='".$sistema."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesPC($sistema, $atributos){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo as pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where m.sistema='".$sistema."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesByDefPC($def, $sistema, $atributos){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo as pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where pc.id_personal='".$def."'
and m.sistema='".$sistema."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesByDefPeriodoP($fi,$ff,$def, $sistema, $atributos){
$sql = " SELECT pc.juzgado,sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,P.id_personal as idDef, P.ap_paterno as apDefP, P.ap_materno as apDefM,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join (select * from personal_campo inner join juzgado using(id_juzgado)) AS pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."'
and m.sistema='".$sistema."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function crearDiscapacidades($jsonData){
print_r($jsonData);
}
function actBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT m.sistema AS sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG) AS actAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG) AS actAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG) AS actVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY sistemaG;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT m.sistema AS sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'DEFENSOR':
$sql = "SELECT m.sistema AS sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG) AS actVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'ALL':
$sql = "SELECT m.sistema AS sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG) AS actAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG) AS actAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG) AS actVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN personal_campo AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY sistemaG;";
return $sql;
break;
}
}
function sexoBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT m.sistema as sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN
(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAsesoria,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAudiencia,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreVisita,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY sistemaG;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT m.sistema as sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN
(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAsesoria,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAudiencia,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreVisita,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'DEFENSOR':
$sql = "SELECT m.sistema as sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN
(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAsesoria,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAudiencia,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreVisita,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'ALL':
$sql = "SELECT m.sistema as sistemaG, COUNT(act.id_actividad) AS actividadesPorSistema,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN
(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAsesoria,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAsesoria,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN(select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreAudiencia,
(SELECT COUNT(Au.id_actividad)
FROM
actividad AS act
INNER JOIN audiencias AS Au USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerAudiencia,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='MASCULINO') AS hombreVisita,
(SELECT COUNT(vis.id_actividad)
FROM
actividad AS act
INNER JOIN visitas_carcelarias AS vis USING (id_actividad)
INNER JOIN (select * from personal_campo
inner join materia as m using(id_materia))AS pc USING (id_personal)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.sistema = sistemaG AND U.sexo='FEMENINO') AS mujerVisita
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY sistemaG;";
return $sql;
break;
}
}
function generoBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT m.sistema as sistemaG,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='BISEXUAL') AS bisexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='GAY') AS gayAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='INTERSEXUAL') AS interAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='LESBICO') AS lesbicoAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='TRANSEXUAL') AS transexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='TRANSGENERO') AS transgeneroAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and m.sistema = sistemaG AND U.genero='TRAVESTI') AS travestiAse
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY sistemaG;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT m.sistema as sistemaG,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='BISEXUAL') AS bisexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='GAY') AS gayAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='INTERSEXUAL') AS interAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='LESBICO') AS lesbicoAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRANSEXUAL') AS transexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRANSGENERO') AS transgeneroAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRAVESTI') AS travestiAse
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'DEFENSOR':
$sql = "SELECT m.sistema as sistemaG,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='BISEXUAL') AS bisexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='GAY') AS gayAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='INTERSEXUAL') AS interAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='LESBICO') AS lesbicoAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRANSEXUAL') AS transexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRANSGENERO') AS transgeneroAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal = '".$def."' and m.sistema = sistemaG AND U.genero='TRAVESTI') AS travestiAse
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal = '".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case 'ALL':
$sql = "SELECT m.sistema as sistemaG,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='BISEXUAL') AS bisexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='GAY') AS gayAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='INTERSEXUAL') AS interAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='LESBICO') AS lesbicoAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='TRANSEXUAL') AS transexualAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='TRANSGENERO') AS transgeneroAse,
(SELECT COUNT(A.id_actividad)
FROM
actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE m.sistema = sistemaG AND U.genero='TRAVESTI') AS travestiAse
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT * FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY sistemaG;";
return $sql;
break;
}
}
function edadBySistema($valor, $fi, $ff, $def){
switch($valor){
case'PERIODO':
$sql = "SELECT m.sistema AS sistemaG,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='MASCULINO') AS edad18_24H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='FEMENINO') AS edad18_24M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='MASCULINO') AS edad25_29H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='FEMENINO') AS edad25_29M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='MASCULINO') AS edad30_34H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='FEMENINO') AS edad30_34M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='MASCULINO') AS edad35_39H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='FEMENINO') AS edad35_39M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='MASCULINO') AS edad40_44H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='FEMENINO') AS edad40_44M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='MASCULINO') AS edad45_49H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='FEMENINO') AS edad45_49M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='MASCULINO') AS edad50_54H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='FEMENINO') AS edad50_54M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='MASCULINO') AS edad55_59H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='FEMENINO') AS edad55_59M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='MASCULINO') AS edad60MasH,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='FEMENINO') AS edad60MasM
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."')
GROUP BY sistemaG;";
return $sql;
break;
case'PERIODODEF':
$sql = "SELECT m.sistema AS sistemaG,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='MASCULINO') AS edad18_24H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='FEMENINO') AS edad18_24M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='MASCULINO') AS edad25_29H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='FEMENINO') AS edad25_29M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='MASCULINO') AS edad30_34H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='FEMENINO') AS edad30_34M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='MASCULINO') AS edad35_39H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='FEMENINO') AS edad35_39M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='MASCULINO') AS edad40_44H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='FEMENINO') AS edad40_44M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='MASCULINO') AS edad45_49H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='FEMENINO') AS edad45_49M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='MASCULINO') AS edad50_54H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='FEMENINO') AS edad50_54M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='MASCULINO') AS edad55_59H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='FEMENINO') AS edad55_59M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='MASCULINO') AS edad60MasH,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='FEMENINO') AS edad60MasM
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (fecha_registro BETWEEN '".$fi."' AND '".$ff."') and pc.id_personal='".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT m.sistema AS sistemaG,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='MASCULINO') AS edad18_24H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='FEMENINO') AS edad18_24M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='MASCULINO') AS edad25_29H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='FEMENINO') AS edad25_29M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='MASCULINO') AS edad30_34H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='FEMENINO') AS edad30_34M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='MASCULINO') AS edad35_39H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='FEMENINO') AS edad35_39M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='MASCULINO') AS edad40_44H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='FEMENINO') AS edad40_44M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='MASCULINO') AS edad45_49H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='FEMENINO') AS edad45_49M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='MASCULINO') AS edad50_54H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='FEMENINO') AS edad50_54M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='MASCULINO') AS edad55_59H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='FEMENINO') AS edad55_59M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='MASCULINO') AS edad60MasH,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."' AND (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='FEMENINO') AS edad60MasM
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE pc.id_personal='".$def."'
GROUP BY sistemaG;";
return $sql;
break;
case'ALL':
$sql = "SELECT m.sistema AS sistemaG,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='MASCULINO') AS edad18_24H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '18' and '24') and U.sexo='FEMENINO') AS edad18_24M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='MASCULINO') AS edad25_29H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '25' and '29') and U.sexo='FEMENINO') AS edad25_29M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='MASCULINO') AS edad30_34H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '30' and '34') and U.sexo='FEMENINO') AS edad30_34M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='MASCULINO') AS edad35_39H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '35' and '39') and U.sexo='FEMENINO') AS edad35_39M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='MASCULINO') AS edad40_44H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '40' and '44') and U.sexo='FEMENINO') AS edad40_44M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='MASCULINO') AS edad45_49H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '45' and '49') and U.sexo='FEMENINO') AS edad45_49M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='MASCULINO') AS edad50_54H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '50' and '54') and U.sexo='FEMENINO') AS edad50_54M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='MASCULINO') AS edad55_59H,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad between '55' and '59') and U.sexo='FEMENINO') AS edad55_59M,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='MASCULINO') AS edad60MasH,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN personal_campo AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
WHERE (m.sistema = sistemaG AND U.edad >= '60') and U.sexo='FEMENINO') AS edad60MasM
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN audiencias AS Au USING (id_actividad)
LEFT JOIN visitas_carcelarias AS vis USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY sistemaG;";
return $sql;
break;
}
}
function etniaBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY etniaU
ORDER BY sistema;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case 'DEFENSOR':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case 'ALL':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY etniaU
ORDER BY sistema;";
return $sql;
break;
}
}
function idiomaBySistema($valor, $fi, $ff, $def){
switch($valor){
case'PERIODO':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY idiomaU
ORDER BY sistema;";
return $sql;
break;
case'PERIODODEF':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case'ALL':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY idiomaU
ORDER BY sistema;";
return $sql;
break;
}
}
function discapacidadBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') group by matSistemaG order by matSistemaG;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' group by matSistemaG order by matSistemaG;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer= '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer= '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' group by matSistemaG order by matSistemaG;";
return $sql;
break;
case'ALL':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
group by matSistemaG order by matSistemaG;";
return $sql;
break;
}
}
function topDefensoresBySistema($valor, $fi, $ff, $def){
switch($valor){
case'PERIODO':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'PERIODODEF':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."' and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."' and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."'
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."' and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."' and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."'
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'ALL':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
}
}
function getActividadesByPeriodo($fi,$ff){
$actBysistema = actBySistema('PERIODO',$fi, $ff, '');
$listaActBySistema= consulta($actBysistema);
$sexoBySistema = sexoBySistema('PERIODO',$fi, $ff, '');
$listaSexoBySistema = consulta($sexoBySistema);
$generoBySistema = generoBySistema('PERIODO',$fi, $ff, '');
$listaGeneroBySistema = consulta($generoBySistema);
$edadBySistema = edadBySistema('PERIODO',$fi, $ff, '');
$listaEdadBySistema = consulta($edadBySistema);
$etniaBySistema = etniaBySistema('PERIODO',$fi, $ff, '');
$listaEtniaBySistema = consulta($etniaBySistema);
$discapacidadBySistema = discapacidadBySistema('PERIODO',$fi, $ff, '');
$listaDiscapacidadBySistema = consulta($discapacidadBySistema);
$idiomaBySistema = idiomaBySistema('PERIODO',$fi, $ff, '');
$listaIdiomaBySistema = consulta($idiomaBySistema);
$topDefensores = topDefensoresBySistema('PERIODO',$fi, $ff, '');
$listaTop = consulta($topDefensores);
$lista = array();
//array_push($lista, $listaActBySistema,$listaSexoBySistema,$listaGeneroBySistema, $listaEdadBySistema,$listaEtniaBySistema, $listaIdiomaBySistema, $listaDiscapacidadBySistema);
//print_r($lista);
$lista['actBySistema'] = $listaActBySistema;
$lista['sexoBySistema'] = $listaSexoBySistema;
$lista['generoBySistema'] = $listaGeneroBySistema;
$lista['edadBySistema'] = $listaEdadBySistema;
$lista['etniaBySistema'] = $listaEtniaBySistema;
$lista['idiomaBySistema'] = $listaIdiomaBySistema;
$lista['discapacidadBySistema'] = $listaDiscapacidadBySistema;
$lista['topDefensoresBySystema'] = $listaTop;
return $lista;
}
function getActividadesByDefPeriodo($fi,$ff,$def){
$actBysistema = actBySistema('PERIODODEF',$fi, $ff, $def);
$listaActBySistema= consulta($actBysistema);
$sexoBySistema = sexoBySistema('PERIODODEF',$fi, $ff, $def);
$listaSexoBySistema = consulta($sexoBySistema);
$generoBySistema = generoBySistema('PERIODODEF',$fi, $ff, $def);
$listaGeneroBySistema = consulta($generoBySistema);
$edadBySistema = edadBySistema('PERIODODEF',$fi, $ff, $def);
$listaEdadBySistema = consulta($edadBySistema);
$etniaBySistema = etniaBySistema('PERIODODEF',$fi, $ff, $def);
$listaEtniaBySistema = consulta($etniaBySistema);
$discapacidadBySistema = discapacidadBySistema('PERIODODEF',$fi, $ff, $def);
$listaDiscapacidadBySistema = consulta($discapacidadBySistema);
$idiomaBySistema = idiomaBySistema('PERIODODEF',$fi, $ff,$def);
$listaIdiomaBySistema = consulta($idiomaBySistema);
$nombreDef = "select nombre,ap_paterno, ap_materno, sistema from personal
inner join personal_campo using(id_personal)
inner join materia using(id_materia) where id_personal = '".$def."'";
$listaNom = consulta($nombreDef);
//$topDefensores = topDefensoresBySistema('PERIODODEF',$fi, $ff, $def);
//$listaTop = consulta($topDefensores);
$lista = array();
//array_push($lista, $listaActBySistema,$listaSexoBySistema,$listaGeneroBySistema, $listaEdadBySistema,$listaEtniaBySistema, $listaIdiomaBySistema, $listaDiscapacidadBySistema);
//print_r($lista);
$lista['actBySistemaDef'] = $listaActBySistema;
$lista['sexoBySistemaDef'] = $listaSexoBySistema;
$lista['generoBySistemaDef'] = $listaGeneroBySistema;
$lista['edadBySistemaDef'] = $listaEdadBySistema;
$lista['etniaBySistemaDef'] = $listaEtniaBySistema;
$lista['idiomaBySistemaDef'] = $listaIdiomaBySistema;
$lista['discapacidadBySistemaDef'] = $listaDiscapacidadBySistema;
$lista['nombreDef'] = $listaNom;
//$lista['topDefensoresBySystemaDef'] = $listaTop;
return $lista;
}
function getActividadesByDefCompleto($def){
$actBysistema = actBySistema('DEFENSOR','', '', $def);
$listaActBySistema= consulta($actBysistema);
$sexoBySistema = sexoBySistema('DEFENSOR','', '', $def);
$listaSexoBySistema = consulta($sexoBySistema);
$generoBySistema = generoBySistema('DEFENSOR','', '', $def);
$listaGeneroBySistema = consulta($generoBySistema);
$edadBySistema = edadBySistema('DEFENSOR','', '', $def);
$listaEdadBySistema = consulta($edadBySistema);
$etniaBySistema = etniaBySistema('DEFENSOR','', '', $def);
$listaEtniaBySistema = consulta($etniaBySistema);
$discapacidadBySistema = discapacidadBySistema('DEFENSOR','', '', $def);
$listaDiscapacidadBySistema = consulta($discapacidadBySistema);
$idiomaBySistema = idiomaBySistema('DEFENSOR','', '', $def);
$listaIdiomaBySistema = consulta($idiomaBySistema);
$nombreDef = "select nombre,ap_paterno, ap_materno, sistema from personal
inner join personal_campo using(id_personal)
inner join materia using(id_materia) where id_personal = '".$def."'";
$listaNom = consulta($nombreDef);
//$topDefensores = topDefensoresBySistema('PERIODODEF',$fi, $ff, $def);
//$listaTop = consulta($topDefensores);
$lista = array();
//array_push($lista, $listaActBySistema,$listaSexoBySistema,$listaGeneroBySistema, $listaEdadBySistema,$listaEtniaBySistema, $listaIdiomaBySistema, $listaDiscapacidadBySistema);
//print_r($lista);
$lista['actBySistemaDef'] = $listaActBySistema;
$lista['sexoBySistemaDef'] = $listaSexoBySistema;
$lista['generoBySistemaDef'] = $listaGeneroBySistema;
$lista['edadBySistemaDef'] = $listaEdadBySistema;
$lista['etniaBySistemaDef'] = $listaEtniaBySistema;
$lista['idiomaBySistemaDef'] = $listaIdiomaBySistema;
$lista['discapacidadBySistemaDef'] = $listaDiscapacidadBySistema;
$lista['nombreDef'] = $listaNom;
//$lista['topDefensoresBySystemaDef'] = $listaTop;
return $lista;
}
function getActividadesGC(){
$actBysistema = actBySistema('ALL','', '', '');
$listaActBySistema= consulta($actBysistema);
$sexoBySistema = sexoBySistema('ALL','', '', '');
$listaSexoBySistema = consulta($sexoBySistema);
$generoBySistema = generoBySistema('ALL','', '', '');
$listaGeneroBySistema = consulta($generoBySistema);
$edadBySistema = edadBySistema('ALL','', '', '');
$listaEdadBySistema = consulta($edadBySistema);
$etniaBySistema = etniaBySistema('ALL','', '', '');
$listaEtniaBySistema = consulta($etniaBySistema);
$discapacidadBySistema =" CALL tablaExpDiscapacidad('COMPLETO','', '', '')";
$listaDiscapacidadBySistema = consulta($discapacidadBySistema);
$idiomaBySistema = idiomaBySistema('ALL','', '', '');
$listaIdiomaBySistema = consulta($idiomaBySistema);
$topDefensores = topDefensoresBySistema('ALL','', '', '');
$listaTop = consulta($topDefensores);
$lista = array();
//array_push($lista, $listaActBySistema,$listaSexoBySistema,$listaGeneroBySistema, $listaEdadBySistema,$listaEtniaBySistema, $listaIdiomaBySistema, $listaDiscapacidadBySistema);
//print_r($lista);
$lista['actBySistema'] = $listaActBySistema;
$lista['sexoBySistema'] = $listaSexoBySistema;
$lista['generoBySistema'] = $listaGeneroBySistema;
$lista['edadBySistema'] = $listaEdadBySistema;
$lista['etniaBySistema'] = $listaEtniaBySistema;
$lista['idiomaBySistema'] = $listaIdiomaBySistema;
$lista['discapacidadBySistema'] = $listaDiscapacidadBySistema;
$lista['topDefensoresBySystema'] = $listaTop;
return $lista;
}
function getActividadesCompletoBydef($def){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo as pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where pc.id_personal='".$def."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesCompleto(){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU,
U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor,
U.nombre as Usuario, fecha_registro, observacion, A.id_actividad as idAse,
A.latitud as latAse, A.longitud as longAse, Au.id_actividad as idAud,
Au.latitud as latAud, Au.longitud as longAud, vis.id_actividad as idAct,
vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo as pc using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividades(){
$sql = "select act.fecha_registro as fechaR, act.observacion as observaciones,act.id_actividad as idAct,
ase.latitud as latAse, ase.longitud as longAse,
aud.latitud as latAud, aud.longitud as longAud,
vis.foto as fotoVis,
usu.nombre as Usuario
from actividad as act
left join asesoria as ase using(id_actividad)
left join audiencias as aud using(id_actividad)
left JOIN visitas_carcelarias as vis using(id_actividad)
inner join usuario_servicio as usu using(id_usuario_servicio)
order by id_actividad;";
$consulta = consulta($sql);
return $consulta;
}
function getActividadesAsesorias(){
$sql = "select act.fecha_registro as fechaR, act.observacion as observaciones,act.id_actividad as idAct,
ase.latitud as latAse, ase.longitud as longAse,
usu.nombre as Usuario
from actividad as act
inner join asesoria as ase using(id_actividad)
inner join usuario_servicio as usu using(id_usuario_servicio)
order by id_actividad;";
$consulta = consulta($sql);
return $consulta;
}
function getActividadesAudiencias(){
$sql = "select act.fecha_registro as fechaR, act.observacion as observaciones,act.id_actividad as idAct,
aud.latitud as latAud, aud.longitud as longAud,
usu.nombre as Usuario
from actividad as act
inner join audiencias as aud using(id_actividad)
inner join usuario_servicio as usu using(id_usuario_servicio)
order by id_actividad;";
$consulta = consulta($sql);
return $consulta;
}
function updateObservacion($obs, $id_act){
$sql = "update actividad set observacion='".$obs."' where id_actividad='".$id_act."' ";
$consulta = consulta($sql);
return $consulta;
}
function getActividadesVisitas(){
$sql = "select act.fecha_registro as fechaR, act.observacion as observaciones,
vis.foto as fotoVis,
usu.nombre as Usuario
from actividad as act
inner JOIN visitas_carcelarias as vis using(id_actividad)
inner join usuario_servicio as usu using(id_usuario_servicio)
order by id_actividad;";
$consulta = consulta($sql);
return $consulta;
}
function listar_actividad_x_id($id){
global $conexion;
$sql = "select * from defensor where id='".$id."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
function getActividadesByRangoFecha($fechaI, $fechaF){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU, U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor, U.nombre as Usuario, fecha_registro, observacion,
A.id_actividad as idAse, A.latitud as latAse, A.longitud as longAse,
Au.id_actividad as idAud, Au.latitud as latAud, Au.longitud as longAud,
vis.id_actividad as idAct, vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where fecha_registro between '".$fechaI."' and '".$fechaF."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesConsulta($inicio, $final, $sys){
$sql = " SELECT sistema,U.sexo,U.genero as generoU,U.edad as edadU,U.etnia as etniaU, U.discapacidad as discapacidadU, U.idioma as idiomaU,P.nombre as Defensor, U.nombre as Usuario, fecha_registro, observacion,
A.id_actividad as idAse, A.latitud as latAse, A.longitud as longAse,
Au.id_actividad as idAud, Au.latitud as latAud, Au.longitud as longAud,
vis.id_actividad as idAct, vis.foto as fotoVis, act.id_actividad as idAct
from actividad as act left join asesoria as A using(id_actividad)
left join audiencias as Au using(id_actividad)
left join visitas_carcelarias as vis using(id_actividad)
left join personal as P using(id_personal)
left join personal_campo using(id_personal)
left join materia as m using(id_materia)
left join usuario_servicio as U using(id_usuario_servicio)
where (fecha_registro between '".$inicio."' and '".$final."') and m.sistema='".$sys."'";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesByFiltroPersonal($fechaInicio, $fechaFinal,$puesto){
$sql = "SELECT * FROM actividad inner join asesoria using(id_actividad) inner join personal using(id_personal)
where (fecha_registro between '".$fechaI."' and '".$fechaF."') and id_cargo='".$puesto."'";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getActividadesByFiltroNue($fechaInicio, $fechaFinal,$nue){
$sql = "SELECT P.nombre as Defensor, U.nombre as Usuario, fecha_registro, observacion, latitud, longitud
FROM actividad inner join asesoria as A using(id_actividad) inner join personal AS P using(id_personal)
inner join usuario_servicio as U using(id_usuario_servicio)
where (fecha_registro between '".$fechaInicio."' and '".$fechaFinal."') and nue='".$nue."'";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
//Definimos la funciones sobre el objeto crear_asesoria
function crear_actividad($asesoria){
$sql = "INSERT INTO actividad ";
$sql.= "SET id_usuario_servicio='".$asesoria['id_usuario_servicio']."', id_personal='".$asesoria['id_personal_campo']."',";
// $sql.= " dia_registro='".$asesoria['dia_registro']."', mes_registro='".$asesoria['mes_registro']."',";
$sql.= " fecha_registro='".$asesoria['fecha_registro']."', observacion='".$asesoria['observacion']."'";
echo $sql;
$lista=registro($sql);
return $lista;
}
function ultimoActividadRegistrado(){
$sql = "SELECT MAX(id_actividad) AS id FROM actividad";
$id=consulta($sql);
// print_r($id);
return $id[0]['id'];
}
?>
<file_sep><?php
include_once('../../modelo/respuesta/respuesta.php');
include_once('../../modelo/expediente.php');
include '../../libreria/herramientas.php';
/* echo "respuesta<br>";
echo $_POST['respuesta'];
echo "observacion<br>";
echo $_POST['observacion'];
echo "accion a implementar<br>";
echo $_POST['accion_implementar'];
echo "id_pregunta<br>";
echo $_POST['id_pregunta'];
*/$respuesta = Array(
"id_pregunta_materia" =>$_POST['id_pregunta'],
"id_expediente" =>$_POST['id_expediente'],
"respuesta" =>$_POST['respuesta'],
"observaciones" =>$_POST['observacion'],
"accion_implementar" =>$_POST['accion_implementar']
);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);
$mensaje=['tipo' =>"error",
'mensaje'=>"Esta pregunta ya se encuentra registrada"];
$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
{RegistrarRespuesta($respuesta);
estadoEnProceso($_POST['id_expediente']);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Registro exitoso"];
// echo "el registro es exitoso" ;
}//else
//echo "el registro ya existe";
echo json_encode($mensaje);
?><file_sep><?php
include_once ('../../libreria/conexion.php');
function etniaBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY etniaU
ORDER BY sistema;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case 'DEFENSOR':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."' and
U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case 'ALL':
$sql = "SELECT U.etnia AS etniaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='TRADICIONAL') AS etniaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.etnia = etniaU and m.sistema='ORAL') AS etniaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY etniaU
ORDER BY sistema;";
return $sql;
break;
}
}
function idiomaBySistema($valor, $fi, $ff, $def){
switch($valor){
case'PERIODO':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY idiomaU
ORDER BY sistema;";
return $sql;
break;
case'PERIODODEF':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pc.id_personal ='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."' and
U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
where pc.id_personal ='".$def."'
GROUP BY pc.id_personal
ORDER BY sistema;";
return $sql;
break;
case'ALL':
$sql = "SELECT U.idioma AS idiomaU, COUNT(A.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaHombreT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'MASCULINO' AND U.idioma= idiomaU and m.sistema='ORAL') AS idiomaHombreO,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='TRADICIONAL') AS idiomaMujerT,
(SELECT COUNT(A.id_actividad)
FROM actividad AS act
INNER JOIN asesoria AS A USING (id_actividad)
INNER JOIN (SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
INNER JOIN materia AS m USING (id_materia)
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.sexo = 'FEMENINO' AND U.idioma = idiomaU and m.sistema='ORAL') AS idiomaMujerO
FROM
actividad AS act
LEFT JOIN asesoria AS A USING (id_actividad)
LEFT JOIN personal AS P USING (id_personal)
LEFT JOIN
(SELECT *
FROM
personal_campo
INNER JOIN juzgado USING (id_juzgado)) AS pc USING (id_personal)
LEFT JOIN materia AS m USING (id_materia)
LEFT JOIN usuario_servicio AS U USING (id_usuario_servicio)
GROUP BY idiomaU
ORDER BY sistema;";
return $sql;
break;
}
}
function discapacidadBySistema($valor, $fi, $ff, $def){
switch($valor){
case 'PERIODO':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') group by matSistemaG order by matSistemaG;";
return $sql;
break;
case 'PERIODODEF':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer= '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and idPer = '".$def."' group by matSistemaG order by matSistemaG;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer= '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer= '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' and U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where idPer = '".$def."' group by matSistemaG order by matSistemaG;";
return $sql;
break;
case'ALL':
$sql = "SELECT matSistemaG, COUNT(U.id_usuario_servicio) AS discapTotal,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG
) AS tablaSensorial,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='MASCULINO'
) AS tablaSensorialM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'SENSORIALES' AND
matSistema=matSistemaG AND U.sexo='FEMENINO'
) AS tablaSensorialF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG
) AS tablaMotriz,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMotrizM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MOTRICES' AND
matSistema=matSistemaG AND U.sexo ='FEMENINO'
) AS tablaMotrizF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG
) AS tablaMental,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMentalM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MENTALES' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaMentalF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG
) AS tablaMultiple, (
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG AND U.sexo ='MASCULINO'
) AS tablaMultipleM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'MULTIPLES' AND
matSistema=matSistemaG and U.sexo='FEMENINO'
) AS tablaMultipleF,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG
) AS tablaNinguno,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo='MASCULINO'
) AS tablaNingunoM,
(
select count(AA.id_actividad)
from
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
where U.discapacidad = 'NINGUNO' AND
matSistema=matSistemaG and U.sexo = 'FEMENINO'
) AS tablaNingunoF
FROM
actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, per.nombre as nombreDef, mate.sistema as matSistemaG
from personal_campo as pcc
inner join personal per using(id_personal)
inner join materia as mate using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS U USING (id_usuario_servicio)
group by matSistemaG order by matSistemaG;";
return $sql;
break;
}
}
function topDefensoresBySistema($valor, $fi, $ff, $def){
switch($valor){
case'PERIODO':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."')
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'PERIODODEF':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."' and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."' and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where (fecha_registro between '".$fi."' and '".$ff."') and pcc.id_personal='".$def."'
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'DEFENSOR':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."' and
cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."' and
cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where pcc.id_personal='".$def."'
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
case'ALL':
$sql = "SELECT matSistema as sistemaM, nombreDef AS nombreP,tabla1.idPer as idDeff, nombreJuz, COUNT(AA.id_Actividad) AS asesoriaPorSistema,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where cv.sexo = 'FEMENINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS mujeres,
(SELECT COUNT(AA.id_actividad)
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
where cv.sexo = 'MASCULINO' AND tabla1.idPer = idDeff and matSistema = sistemaM) AS hombres
FROM actividad as act
INNER JOIN asesoria AS AA USING (id_actividad)
INNER JOIN
(select pcc.id_personal idPer, juz.id_juzgado as idJuz, juz.juzgado as nombreJuz, per.nombre as nombreDef, mat.sistema as matSistema
from personal_campo as pcc
inner join personal per using(id_personal)
INNER JOIN juzgado juz USING (id_juzgado)
inner join materia as mat using(id_materia)
) AS tabla1 on act.id_personal = idPer
INNER JOIN usuario_servicio AS cv USING (id_usuario_servicio)
GROUP BY idDeff
ORDER BY sistemaM;";
return $sql;
break;
}
}
function getExpedientesByDefPeriodo($fi,$ff,$def){
$lista = array();
$sqlExpGeneral='call tablaExpGeneral("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpGeneral = consulta($sqlExpGeneral);
$sqlExpMateria = 'call tablaExpMateria("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpMateria = consulta($sqlExpMateria);
$sqlExpRegion = 'call tablaExpRegion("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpRegion = consulta($sqlExpRegion);
$sexoBySistema = 'call tablaExpSexo("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpSexo = consulta($sexoBySistema);
$actBySistema = 'call tablaExpActividades("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpAct = consulta($actBySistema);
$generoBySistema = 'call tablaExpGenero("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpGenero = consulta($generoBySistema);
$edadBySistema = 'call tablaExpEdad("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpEdad = consulta($edadBySistema);
$etniaBySistema = 'call tablaExpEtnia("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpEtnia = consulta($etniaBySistema);
$idiomaBySistema = 'call tablaExpIdioma("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpIdioma = consulta($idiomaBySistema);
$discapacidadBySistema = 'call tablaExpDiscapacidad("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpDiscapacidad = consulta($discapacidadBySistema);
$regionBySistema = 'call tablaExpRegion("DEFENSORP","'.$def.'","'.$fi.'","'.$ff.'");';
$listaExpRegion= consulta($regionBySistema);
$nombre = 'call nombreDefExp("DEFENSOR","'.$def.'", "", "")';
$listaNom = consulta($nombre);
$lista['nombreDef'] = $listaNom;
$lista['tablaRegionExpDef'] = $listaExpRegion;
$lista['tablaActExpDef'] = $listaExpAct;
$lista['tablaSexoExpDef'] = $listaExpSexo;
$lista['tablaGeneroExpDef'] = $listaExpGenero;
$lista['tablaEdadExpDef']= $listaExpEdad;
$lista['tablaEtniaExpDef'] = $listaExpEtnia;
$lista['tablaIdiomaExpDef'] = $listaExpIdioma;
$lista['tablaGeneralExpDef'] = $listaExpGeneral;
$lista['tablaMateriaExpDef'] =$listaExpMateria;
$lista['tablaDiscapacidadExpDef'] =$listaExpDiscapacidad;
return $lista;
}
function getExpedientesByPeriodo($fi,$ff){
$lista = array();
$sqlExpGeneral='call tablaExpGeneral("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpGeneral = consulta($sqlExpGeneral);
$sqlExpMateria = 'call tablaExpMateria("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpMateria = consulta($sqlExpMateria);
$sqlExpRegion = 'call tablaExpRegion("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpRegion = consulta($sqlExpRegion);
$sexoBySistema = 'call tablaExpSexo("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpSexo = consulta($sexoBySistema);
$actBySistema = 'call tablaExpActividades("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpAct = consulta($actBySistema);
$generoBySistema = 'call tablaExpGenero("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpGenero = consulta($generoBySistema);
$edadBySistema = 'call tablaExpEdad("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpEdad = consulta($edadBySistema);
$etniaBySistema = 'call tablaExpEtnia("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpEtnia = consulta($etniaBySistema);
$idiomaBySistema = 'call tablaExpIdioma("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpIdioma = consulta($idiomaBySistema);
$discapacidadBySistema = 'call tablaExpDiscapacidad("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpDiscapacidad = consulta($discapacidadBySistema);
$regionBySistema = 'call tablaExpRegion("COMPLETOP","","'.$fi.'","'.$ff.'");';
$listaExpRegion= consulta($regionBySistema);
$topBySistema = 'call tablaExpTop("COMPLETOP","","'.$fi.'","'.$ff.'")';
$listaExpTop= consulta($topBySistema);
$lista['tablaTopExp'] = $listaExpTop;
$lista['tablaRegionExp'] = $listaExpRegion;
$lista['tablaActExp'] = $listaExpAct;
$lista['tablaSexoExp'] = $listaExpSexo;
$lista['tablaGeneroExp'] = $listaExpGenero;
$lista['tablaEdadExp']= $listaExpEdad;
$lista['tablaEtniaExp'] = $listaExpEtnia;
$lista['tablaIdiomaExp'] = $listaExpIdioma;
$lista['tablaGeneralExp'] = $listaExpGeneral;
$lista['tablaMateriaExp'] =$listaExpMateria;
$lista['tablaDiscapacidadExp'] =$listaExpDiscapacidad;
return $lista;
}
function getExpedientesByDefCompleto($def){
$lista = array();
$sqlExpGeneral='call tablaExpGeneral("DEFENSOR","'.$def.'","0000-00-00","0000-00-00");';
$listaExpGeneral = consulta($sqlExpGeneral);
$sqlExpMateria = 'call tablaExpMateria("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpMateria = consulta($sqlExpMateria);
$sqlExpRegion = 'call tablaExpRegion("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpRegion = consulta($sqlExpRegion);
$sexoBySistema = 'call tablaExpSexo("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';//sexoBySistema('ALL','', '', '');
$listaExpSexo = consulta($sexoBySistema);
$actBySistema = 'call tablaExpActividades("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpAct = consulta($actBySistema);
$generoBySistema = 'call tablaExpGenero("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpGenero = consulta($generoBySistema);
$edadBySistema = 'call tablaExpEdad("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpEdad = consulta($edadBySistema);
$etniaBySistema = 'call tablaExpEtnia("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpEtnia = consulta($etniaBySistema);
$idiomaBySistema = 'call tablaExpIdioma("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpIdioma = consulta($idiomaBySistema);
$discapacidadBySistema = 'call tablaExpDiscapacidad("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpDiscapacidad = consulta($discapacidadBySistema);
$regionBySistema = 'call tablaExpRegion("DEFENSOR","'.$def.'","0000-00-00","0000-00-00")';
$listaExpRegion= consulta($regionBySistema);
$nombre = 'call nombreDefExp("DEFENSOR","'.$def.'", "", "")';
$listaNom = consulta($nombre);
$lista['nombreDef'] = $listaNom;
$lista['tablaRegionExpDef'] = $listaExpRegion;
$lista['tablaActExpDef'] = $listaExpAct;
$lista['tablaSexoExpDef'] = $listaExpSexo;
$lista['tablaGeneroExpDef'] = $listaExpGenero;
$lista['tablaEdadExpDef']= $listaExpEdad;
$lista['tablaEtniaExpDef'] = $listaExpEtnia;
$lista['tablaIdiomaExpDef'] = $listaExpIdioma;
$lista['tablaGeneralExpDef'] = $listaExpGeneral;
$lista['tablaMateriaExpDef'] =$listaExpMateria;
$lista['tablaDiscapacidadExpDef'] =$listaExpDiscapacidad;
return $lista;
}
function getExpedientesGC(){
$lista = array();
$sqlExpGeneral='call tablaExpGeneral("COMPLETO","","0000-00-00","0000-00-00");';
$listaExpGeneral = consulta($sqlExpGeneral);
$sqlExpMateria = 'call tablaExpMateria("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpMateria = consulta($sqlExpMateria);
$sqlExpRegion = 'call tablaExpRegion("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpRegion = consulta($sqlExpRegion);
$sexoBySistema = 'call tablaExpSexo("COMPLETO","","0000-00-00","0000-00-00")';//sexoBySistema('ALL','', '', '');
$listaExpSexo = consulta($sexoBySistema);
$actBySistema = 'call tablaExpActividades("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpAct = consulta($actBySistema);
$generoBySistema = 'call tablaExpGenero("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpGenero = consulta($generoBySistema);
$edadBySistema = 'call tablaExpEdad("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpEdad = consulta($edadBySistema);
$etniaBySistema = 'call tablaExpEtnia("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpEtnia = consulta($etniaBySistema);
$idiomaBySistema = 'call tablaExpIdioma("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpIdioma = consulta($idiomaBySistema);
$discapacidadBySistema = 'call tablaExpDiscapacidad("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpDiscapacidad = consulta($discapacidadBySistema);
$regionBySistema = 'call tablaExpRegion("COMPLETO","","0000-00-00","0000-00-00")';
$listaExpRegion= consulta($regionBySistema);
$topBySistema = 'call tablaExpTop("COMPLETO","","","")';
$listaExpTop= consulta($topBySistema);
$lista['tablaTopExp'] = $listaExpTop;
$lista['tablaRegionExp'] = $listaExpRegion;
$lista['tablaActExp'] = $listaExpAct;
$lista['tablaSexoExp'] = $listaExpSexo;
$lista['tablaGeneroExp'] = $listaExpGenero;
$lista['tablaEdadExp']= $listaExpEdad;
$lista['tablaEtniaExp'] = $listaExpEtnia;
$lista['tablaIdiomaExp'] = $listaExpIdioma;
$lista['tablaGeneralExp'] = $listaExpGeneral;
$lista['tablaMateriaExp'] =$listaExpMateria;
$lista['tablaDiscapacidadExp'] =$listaExpDiscapacidad;
return $lista;
}
function getExpedientesByDefPeriodoP($fi,$ff,$def, $sistema, $atributos){
}
function getExpedientesByPeriodoCP($fi,$ff, $sistema, $atributos){
}
function getExpedientesByDefPC($def, $sistema, $atributos){
}
function getExpedientesPC($sistema, $atributos){
}
function getExpedientesByRangoFecha($fechaI, $fechaF){
$sql = " select * from expediente as exp inner join personal as p using(id_personal)
inner join( SELECT * from personal_campo as pc inner join materia as m using(id_materia)
)as tablaPersonalCampo using(id_personal)
inner join (
select * from usuario_servicio as us
inner join detalle_usuario_expediente as deus using(id_usuario_servicio)
) as tablaUsuario using(id_expediente)
inner join (
select * from contraparte_expediente as co
inner join contraparte using(id_contraparte)
) as tablaContraparte using(id_expediente)
where fecha_registro between '".$fechaI."' and '".$fechaF."' order by generoU";
$lista= consulta($sql);
//print_r($sql);
return $lista;
}
function getExpedienteById($id_expediente){
$sql = " select * from expediente
where id_expediente='".$id_expediente."' ";
$lista=consulta($sql);
return $lista;
}
function getExpedienteByNum($numExp){
$sql = " select * from respuesta inner join pregunta_materia using(id_pregunta_materia)
inner join pregunta using(id_pregunta)
inner join expediente using(id_expediente)
where num_expediente='".$numExp."' ";
$lista=consulta($sql);
return $lista;
}
function listar_expedienteByPersonalAndMateria($id_usuario_servicio,$materia,$num_expediente){
$sql = " select * from expediente inner join personal_campo
using(id_personal) inner join detalle_usuario_expediente using(id_expediente)
where id_materia='".$materia."'
and id_usuario_servicio='".$id_usuario_servicio."' and num_expedient='".$num_expediente."'";
// echo $sql;
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function listar_UsuarioServicioByExpediente($id_expediente){
$sql = " select * from detalle_usuario_expediente
inner join usuario_servicio using(id_usuario_servicio)
where id_expediente='".$id_expediente."'";
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function listar_x_num_expediente_($num_expediente){
/* $sql = "select * from expediente inner join
usuario_servicio using(id_usuario_servicio)
where num_expediente='".$num_expediente."'"; */
$sql = "select * from expediente inner join detalle_usuario_expediente using(id_expediente) where num_expediente='".$num_expediente."'";
// echo $sql;
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function listar_expedientes(){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)";
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_x_materia($materia){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)
where materia= '".$materia."'";
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_x_estado($estado){
switch($estado){
case 1:
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia) where id_personal>0";
break;
case 2:
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)where id_personal<0";
break;
case 3:
$sql="SELECT p.nue,p.id_personal,e.id_expediente, e.num_expediente, m.materia, e.fecha_registro, e.estado, p.id_personal, e.observaciones
FROM expediente as e inner join personal_campo as pc using(id_personal) inner join personal as p using(id_personal)
inner join materia as m using(id_materia)";
break;
}
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_EM($estado, $materia){
switch($estado){
case 1:
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)
where id_personal>0 and materia= '".$materia."'";
break;
case 2:
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)
where id_personal<0 and materia= '".$materia."'";
break;
case 3:
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
inner join materia using(id_materia)
where materia= '".$materia."'";
break;
}
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_activos(){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal) where id_personal>0";
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_activos_materia($q2){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
where id_personal>0 and materia= '".$materia."'";
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_inactivos(){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal) where id_personal<0";
$lista=consulta($sql);
return $lista;
}
function listar_expedientes_inactivos_materia($q2){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) inner join personal using(id_personal)
where id_personal<0 and materia= '".$materia."'";
$lista=consulta($sql);
return $lista;
}
function updateExpediente($id_defensor, $id_expediente){
$sql = "update expediente set id_personal='".$id_defensor."'";
$sql.=" where id_expediente='".$id_expediente."'";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
function checkNoti(){
$sql = "select count(id_expediente) as numeroExps from notificaciones";//num notis
$nums = consulta($sql)[0]['numeroExps'];
return $nums;
}
function DeleteNotificacion($id_expediente ){
$sql = "delete from notificaciones where id_expediente=".$id_expediente;//num notis
$nums = consulta($sql);
//echo $sql;
return $nums;
}
function finalizarExpediente($datos){
$sql="update expediente set estado='finalizado',fecha_final='".$datos['fecha_final']."', observaciones='".$datos['observaciones']."'
where id_expediente='".$datos['id_expediente']."'";
$lista = consulta($sql);
// echo $sql;
return $lista;
}
function setBajaActivoExpediente($respuesta){
$sql="update expediente set estado='".$respuesta['estado']."', observaciones='".$respuesta['observaciones']."'
,fecha_final='".$respuesta['fecha_baja']."', motivos='".$respuesta['motivos']."' where id_expediente='".$respuesta['id_expediente']."'";
$lista = consulta($sql);
// echo $sql;
return $lista;
}
function estadoEnProceso($id_expediente){
$sql="update expediente set estado='PROCESO'
where id_expediente='".$id_expediente."'";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
function listar_x_idExpedienteAndDefensor($id_personal,$id_expediente){
// SE OBTIENE LOS UTLIMOS 2 REGISTROS DE LAS PREGUNTAS CONTESTAS DE UN EXPEDIENTE EL PRIMERO ES ULTIMO Y EL SEGUNDO SERA EL PENULTIMO
$sql = "select exp.num_expediente,exp.nombre_delito,exp.tipo_delito, res.respuesta,res.observaciones,res.accion_implementar,res.fecha_registro
from expediente as exp
inner join respuesta as res using(id_expediente)
where id_personal='".$id_personal."' and id_expediente='".$id_expediente."' order by fecha_registro desc limit 2";
// echo $sql;
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function listar_expediente_x_defensor($idDefensor){
$sql = "select exp.id_expediente,exp.estado,exp.nombre_delito,exp.tipo_delito,exp.observaciones,exp.fecha_final,exp.fecha_inicio, exp.num_expediente,
defensor.id_juzgado, defensor.estado AS estadoDefensor,defensor.id_personal,mate.materia,mate.sistema
from expediente as exp inner join
personal_campo as defensor using(id_personal)
inner join materia as mate using(id_materia)
where id_personal='".$idDefensor."'";
// echo $sql;
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function listar_expediente_asesoria($id_expediente){
global $conexion;
$sql = "select * from expediente inner join compra_proveedor using(id_expediente) inner join asesoria using(id_expediente) where nombre='".$id_expediente."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
function listar_expediente_visitas($id_expediente){
global $conexion;
$sql = "select * from expediente inner join compra_proveedor using(id_expediente) inner join visitas using(id_expediente) where nombre='".$id_expediente."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
function listar_expediente_adudiencia($id_expediente){
global $conexion;
$sql = "select * from expediente inner join compra_proveedor using(id_expediente) inner join audiencia using(id_expediente) where nombre='".$id_expediente."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
function listar_pregunta($id_materia){
/* $sql = "select pregunta.id_pregunta,pregunta.id_materia,pregunta.pregunta,pregunta.identificador
from pregunta as pregunta
where id_materia='".$id_materia."'"; */
$sql = " select * from
pregunta_materia
INNER JOIN pregunta using(id_pregunta)
where id_materia='".$id_materia."'";
$consulta = consulta($sql);
return $consulta;
}
function listar_preguntaConOpciones($id_materia,$id_expediente){
/* $sql = "select pregunta.id_pregunta,pregunta.pregunta,detalle.id_materia,detalle.id_pregunta_materia,detalle.identificador,op.opcion
from pregunta as pregunta
inner join pregunta_materia as detalle using(id_pregunta)
left join opcion as op on pregunta.id_pregunta=op.id_pregunta
where id_materia='".$id_materia."'"; */
/* $sql="select preguntaOpcion.id_pregunta,preguntaOpcion.pregunta,preguntaOpcion.id_materia,preguntaOpcion.id_pregunta_materia,preguntaOpcion.identificador,preguntaOpcion.opcion
from (select pregunta.id_pregunta,pregunta.pregunta,detalle.id_materia,detalle.id_pregunta_materia,detalle.identificador,op.opcion
from pregunta as pregunta
inner join pregunta_materia as detalle using(id_pregunta)
left join opcion as op on pregunta.id_pregunta=op.id_pregunta
where id_materia=".$id_materia.") as preguntaOpcion left join respuesta as res
on preguntaOpcion.id_pregunta_materia=res.id_pregunta_materia
where res.id_pregunta_materia IS NULL"; */
$sql=" select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion, expRespuesta.id_respuesta, expRespuesta.respuesta from(
select exp.id_expediente, exp.id_personal,res.id_respuesta,res.id_pregunta_materia,res.respuesta
from expediente as exp left join respuesta as res
using(id_expediente)
where exp.id_expediente =".$id_expediente."
) as expRespuesta
right join pregunta_materia as detalle using(id_pregunta_materia)
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)
where detalle.id_materia=".$id_materia;
// echo $sql;
$consulta = consulta($sql);
// print_r($consulta);
return $consulta;
}
function alta_expediente($objetoEntidad){
$sql = "INSERT INTO expediente ";
$sql.= " SET id_personal='".$objetoEntidad['id_defensor']."', nombre_delito='".$objetoEntidad['nombre_delito']."' ,";
$sql.= " tipo_delito='".$objetoEntidad['grado_delito']."', num_expediente='".$objetoEntidad['num_expediente']."', ";
$sql.= " tipo_expediente='".$objetoEntidad['tipo_expediente']."' ";
// echo $sql;
$lista=registro($sql);
return $lista;
}
function notificacionExpedienteSinAtencion(){
$sql="select resultado.num_expediente, nombre,ap_paterno,ap_materno,telefono,(Month(now())-Month(resultado.respuestaFecha)) as fechaRespuesta, (Month(now())-Month(resultado.fecha_registro)) as fecha_registro, respuestaFecha,fecha_registro,estado from
(select exp.*, res.respuesta,MAX(res.fecha_registro) as respuestaFecha from (select * from expediente where estado='proceso' or estado='iniciado') as exp
left join respuesta as res using(id_expediente) group by id_expediente) as resultado inner join personal using(id_personal)
WHERE (Month(now())-Month(resultado.respuestaFecha)) >=2 or (Month(now())-Month(resultado.fecha_registro))>=2 and (estado='proceso' or estado='iniciado')";
//echo $sql;
return consulta($sql);
}
//Definimos la funciones sobre el objeto crear_expediente
function ultimoExpedinteCreatado(){
$sql = "SELECT MAX(id_expediente) AS id FROM expediente";
$id=consulta($sql);
// print_r($id);
return $id[0]['id'];
}
?>
<file_sep>IF(tipo='COMPLETO') THEN
if(tipo2='COMPLETO') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='MATERIA') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.materia=mat
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='SISTEMATERIA') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.materia=mat and tablaPer.sistema=sis
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='REGION') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado, ju.region from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.region=reg
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='SISTEMAREG') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, ju.region,p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado, ju.region from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.region=reg and tablaPer.sistema=sis
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='AMBAS') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado, ju.region from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.region=reg and tablaPer.materia=mat
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='SISTEMAMBAS') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, ju.region,p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado, ju.region from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.region=reg and tablaPer.sistema=sis and tablaPer.materia=mat
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
if(tipo2='SISTEMANIN') THEN
select tablaPer.id_personal as id, tablaPer.nombre as defensor,tablaPer.juzgado as juzgado, tablaPer.materia,tablaPer.sistema as sis, count(distinct exp.id_expediente) as totExp,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, ju.region,p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema
) as usuarios,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='MASCULINO'
) as hombres,
(select count(de.id_usuario_servicio)
from expediente as exp
inner join detalle_usuario_expediente de using(id_expediente)
inner join usuario_servicio as us using(id_usuario_servicio)
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema, ju.juzgado
from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
where id= tablaPer.id_personal and sis = tablaPer.sistema and us.sexo='FEMENINO') as mujeres
from expediente as exp
inner join (select pc.id_personal, pc.id_materia,ju.id_juzgado, p.nombre, ma.materia, ma.sistema , ju.juzgado, ju.region from personal_campo as pc
inner join personal p using(id_personal)
inner join juzgado as ju using(id_juzgado)
inner join materia as ma using(id_materia)) as tablaPer using(id_personal)
WHERE tablaPer.sistema=sis
group by tablaPer.id_personal, tablaPer.sistema;
END IF;
END IF;
<file_sep><?php
session_start();
//echo 'entro a sesion.php';
//Evaluo que la sesion continue verificando una de las variables creadas en control.php, cuando esta ya no coincida con su valor inicial se redirije al archivo de salir.php
if (!$_SESSION["autentificado"]) {
header("Location: salir.php");
echo 'Redireccionando a ssalir.php';
//echo'<script language="javascript">window.location="../Controlador/salir.php"</script>';
}
?>
<file_sep>function informeByDefCompletoParcialT(jsonInforme){
console.log('tradicional');
}
function informeByDefCompletoParcialO(jsonInforme){
console.log('oral');
}
function informeByDefCompletoParcialJ(jsonInforme){
console.log('justicia');
}
function informeByDefCompletoParcialALL(jsonInforme){
console.log('allll');
}<file_sep>$(document).ready(function () {
// MOSTRAR VISTA DE CREAR CONTRAPARTE DE LA PARTE DEL EXPEDIENTE
var creaExpediente=document.getElementById("agregarContraparte");
creaExpediente.addEventListener('click',function (curpUser) {
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
$("#rrellenarPregunta").empty();
$("#respuestaPregunta").empty();
$("#preguntas").empty();
$('#registroContraparte').load("registrar_contraparte.php?id_expediente="+document.getElementById("numExpedienteGlobal").value);
$('#id_expediente').val(document.getElementById("numExpedienteGlobal").value);
},false);
var creaExpediente=document.getElementById("respuestasContestadas");
creaExpediente.addEventListener('click',function (curpUser) {
var botones= document.getElementsByClassName('botonContraparte');
//$(".botonContraparte");
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
$("#preguntas").empty();
$("#preguntasAmparo").hide();
$("#rrellenarPregunta").empty();
$("#registroContraparte").empty();
$('#preguntas').show();
$('#preguntas').load("materia/actualizarSeguimiento.php"); //tiene que desaparecer las preguntas
},false);
var creaExpediente=document.getElementById("idSeguimiento");
creaExpediente.addEventListener('click',function (curpUser) {
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
$("#preguntas").show();//muestra las preguntas
$("#registroContraparte").empty();
$("#preguntasAmparo").hide();//oculta las preguntas de amparo
$("#rrellenarPregunta").hide();//oculta el formulario de las preguntas
iniciarPregunta();
//$('#preguntas').load("materia/ejecucionSanciones.php"); //tiene que desaparecer las preguntas
},false);
var registroAmparo=document.getElementById("registroAmparo");
registroAmparo.addEventListener('click',function (curpUser) {
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
$("#rrellenarPregunta").hide();//oculta el formulario de las preguntas
$("#registroContraparte").empty();//LIMPIAR EL FORMULARIO DE CONTRAPARTE
registrarAmparo();
},false);
});<file_sep><?php
include_once('../../libreria/conexion.php');
//Definimos la funciones sobre el objeto crear_asesoria
function RegistrarRespuesta($respuesta){
$sql = "INSERT INTO respuesta ";
$sql.= "SET id_pregunta_materia='".$respuesta['id_pregunta_materia']."',";
$sql.= " id_expediente='".$respuesta['id_expediente']."', respuesta='".$respuesta['respuesta']."',";
$sql.= " observaciones='".$respuesta['observaciones']."', accion_implementar='".$respuesta['accion_implementar']."'";
//echo $sql;
$lista=registro($sql);
return $lista;
}
function existeRespuestaExpediente($id_expediente,$id_pregunta){
$sql="select * from respuesta where id_pregunta_materia=".$id_pregunta." and id_expediente=".$id_expediente;
// echo $sql;
$lista=consulta($sql);
// print_r($lista);
return $lista;
}
function respuestaPregunta($id_expediente){
$sql="select * from respuesta
INNER JOIN pregunta_materia using(id_pregunta_materia)
INNER JOIN pregunta using(id_pregunta)
where id_expediente=".$id_expediente;
// echo $sql;
$lista=consulta($sql);
//print_r($lista);
return $lista;
}
//UPDATE respuesta SET respuesta='2018-06-20', observaciones='se tomara encuenta al reclusorio',accion_implementar='se tomara las declaraciones de la victima'
//where id_respuesta
function actualizarRespuestaPregunta($respuesta){
$sql = "UPDATE respuesta ";
$sql.= "SET respuesta='".$respuesta['respuesta']."',";
$sql.= " observaciones='".$respuesta['observaciones']."',";
$sql.= " accion_implementar='".$respuesta['accion_implementar']."'";
$sql.= " where id_respuesta='".$respuesta['id_respuesta']."'";
// echo $sql;
$lista=registro($sql);
return $lista;
}
?>
<file_sep><?php
include '../../modelo/defensor/defensor.php';
//echo $_GET['cedula'];
$id_def = $_GET['id_personal'];
$defensorX = getExpedientesById($id_def);
$defensorZ = json_encode($defensorX);
echo $defensorZ;
?><file_sep><?php
include_once('../../libreria/conexion.php');
function alta_DetalleExpedinte($id_expediente,$id_usuario_servicio){
$sql = "INSERT INTO detalle_usuario_expediente ";
$sql.= " SET id_expediente='".$id_expediente."', id_usuario_servicio='".$id_usuario_servicio."' ";
echo $sql;
$lista=registro($sql);
return $lista;
}
function get_materia_instancia(){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado) where id_cargo =4";
$lista=consulta($sql);
return $lista;
}
?><file_sep><?php
include '../../modelo/defensor/defensor.php';
$id_defensor = $_GET['id_personal'];
$expedientes = getNumExpedientes($id_defensor);
echo $expedientes;
?><file_sep><?php
//include_once( '../../controlador/juzgado/actividad_juzgado.php');
//include_once( '../../controlador/defensor/controladorListaDef.php');
session_start();
// print_r($_SESSION['personal']);
$id_personal = $_SESSION['personal'][0]['id_personal'];
$nombre = $_SESSION['personal'][0]['nombre'];
//echo $id_personal;
//echo $nombre;
?>
<!-- page content -->
<div class="row">
<div class="col-md-12">
<div class="x_panel">
<div class="x_title">
<div class="clearfix"></div>
</div>
<div class="x_content">
<section class="content invoice">
<!-- title row -->
<div class="row">
<div class="col-xs-12 table">
<button type="button" onclick="modolSeguimiento()">detallado</button>
<div id="respuestaPregunta">
</div>
<!-- <div id="rrellenarPregunta">
</div> -->
<form id="rrellenarPregunta" data-toggle="validator"enctype="multipart/form-data" role="form" class="" action ="../../controlador/expediente/seguimientoExpediente.php" object="defensor" method="post">
</form>
</div>
</div>
<!-- FIN DE LO OTRO INIICIO PARA EDITAR CONTRAPARTE -->
<div class="modal fade" id="modalDetalladoExpediente" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miEditarUsuarioDetallado" class="table-responsive x_content" title="infomación">
</div>
<div id="detalladoSeguimiento">
<h5 class="modal-title" id="exampleModalCenterTitle">expediente:<span id="detalleExpediente"></span></h5>
</div>
<div id="botonImprimir">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- <button class="btn btn-default" onclick="window.print();"><i class="fa fa-print"></i> Print</button>
-->
</section>
</div>
</div>
</div>
</div>
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/defensor/atendiendoExpediente.js"></script>
<script src="../../recursos/js/expediente/actualizacionSeguimiento.js"></script>
<script>
$('#myform').validator()
$('#myubicacion').hide()
$('#personal').hide()
$('#mycomprobante').hide()
$('#resultado').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
</script><file_sep><?php
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$defensor = Array(
"id_defensor" =>44,
"nombre" =>"pepes",
"ap_paterno" =>"lopez",
"ap_materno" =>'garcia',
"curp" =>'curp',
"calle" =>'',
"numero_ext" =>'221',
"numero_int" =>'23',
"colonia" =>'oaxaca',
"municipio" =>'oaxaca',
"nup" =>'2334',
"nue" =>'234',
"genero" =>'masculino',
"telefono" =>'988767879',
"corre_electronico" =>'<EMAIL>',
"cedula_profesional" =>'c3dul4Pr0f4io4L',
"juzgado" =>'wewe'
);
$url='http://localhost/defensoriaPublica/controlador/defensor/controlActualizarDef.php';
$postfields = http_build_query( $defensor);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postfields,
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//echo $result;
$this->assertEquals(200, intval($result));
}
}
function post_request($url, $data_as_array , $optional_headers = null) {
if (is_null($data_as_array)) {
$data_as_array = array();
}
$data = http_build_query($data_as_array);
$params = array('http' => array(
'method' => 'POST',
'content' => $data,
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with {$url}, {$php_errormsg}");
}
$response = @stream_get_contents($fp);
echo $response;
if ($response === false) {
throw new Exception("Problem reading data from {$url}, {$php_errormsg}");
}
return $response;
}
?><file_sep>var globalDatosEstadisticoPorDefensor;
function gestionGraficaPorDefensor(elemento){
console.log("en elemnto por defensor",elemento);
switch (elemento) {
case 'genero':
generoGDefensor();
break;
case 'discapacidad':
discapacidadesGDefensor();
break;
case 'idioma':
idiomaGDefensor();
break;
case 'expediente':
expedienteGDefensor();
break;
case 'etnia':
etniasGDefensor();
break;
default:
break;
}
}
function discapacidadesGDefensor() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadisticoPorDefensor.tablaDiscapacidadExpDef;
// var tradicional=array.filter(function(x){return (x.sis=='TRADICIONAL')});
var tradicional=array[0];
var grafica=[['Discapacidad en sistema tradicional','Hombre','Mujeres']];
array.forEach(element => {
var arrayNew=[];
arrayNew.push(element.discapacidadUs);
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
grafica.push(arrayNew);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
}
}// final funcion de discapacidad
function etniasGDefensor() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadisticoPorDefensor.tablaEtniaExpDef;
var grafica=[['Etnias en sistema tradicional','GDefensor','Hombre','Mujeres']];
array.forEach(element => {
var arrayNew=[];
arrayNew.push(element.etniaUs);
arrayNew.push(parseInt(element.totalExp));
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
grafica.push(arrayNew);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
}
}// final funcion de etnias
function generoGDefensor() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadisticoPorDefensor.tablaGeneroExpDef;
var grafica=[['Discapacidad en sistema tradicional','Total']];
var array=globalDatosEstadisticoPorDefensor.tablaGeneroExpDef;
array.forEach(element => {
var arrayNew=[];
arrayNew.push(element.generoUs);
arrayNew.push(parseInt(element.totalUsuarios));
grafica.push(arrayNew);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
}
}// final funcion de genero
function idiomaGDefensor() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var tradicional=globalDatosEstadisticoPorDefensor.tablaIdiomaExpDef;
var grafica=[['Idiomas','Hombre','Mujeres']];
tradicional.forEach(element => {
var arrayNew=[];
arrayNew.push(element.idiomaUs);
if(element.hombresO!=='0'&element.mujeresO!=='0')
{ arrayNew.push(parseInt(element.hombresO));
arrayNew.push(parseInt(element.mujeresO));}
if(element.hombresT!=='0'&element.mujeresOT!=='0')
{ arrayNew.push(parseInt(element.hombresT));
arrayNew.push(parseInt(element.mujeresT));}
grafica.push(arrayNew);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
}
}// final funcion de idioma
function expedienteGDefensor() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadisticoPorDefensor.tablaGeneralExpDef;
var grafica;//=[['Materia en sistema tradicional','Hombres','Mujeres'],
// ];
array.forEach(elemento => {
grafica= [['Expediente en sistema tradicional','Total expediente'],
['Baja falta de interes',parseInt(elemento.expBajaFalta )],
['Baja por revocación',parseInt(elemento.expBajaRevocacion)],
['Finalizados',parseInt(elemento.expFinalizacion)],
['Iniciado',parseInt(elemento.expIniciado )],
['Proceso',parseInt(elemento.expProceso )]
];
});
//var graficatwo=[['Materia en sistema oral','Hombres','Mujeres']];
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
}
}// final funcion de materia
<file_sep><?php
include "../libreria/conexion.php";
$usuario = $_POST["usuario_txt"];
$pass = $_POST["password_txt"];
$sql = 'SELECT * FROM usuario_sistema WHERE username='.$usuario;
$num_regs = registro($sql); // $conexion->query($sql);
//$num_regs = $ejecutar_consulta->num_rows;
//echo 'USER=> '.$usuario . ' PASS=> '. $pass;
//echo "<input type='button' onclick='alert('USER=> '.$usuario . ' PASS=> '. $pass)'/>";
if ($num_regs == 0) { //no encontro ningun registro con ese nombre usuario
echo '<p class="text-danger"><strong>No existe ninguna cuenta vinculada a </strong></p>';
} else { //encontro registro sobre un usuario y ese username
$arrayUser = consulta($sql);//$ejecutar_consulta -> fetch_assoc();//contiene informacion del usuario en un array
//print_r( $arrayUser);
$passHashed = $arrayUser[0]['password'];// obtiene la Contrasenia del usuario en la BD
if(password_verify($pass, $passHashed)){//verifica las contraseñas si son correctas entra al if
$sqlRol = 'select id_cargo,nombre,ap_paterno, ap_materno, foto from personal where nue ='.$usuario;
//$consultaRol = $conexion->query($sqlRol);
$num_regis = registro($sqlRol);//$consultaRol->num_rows;
if($num_regis == 1){
//$ejecutar_consulta =//$conexion->query($sqlRol);
$temp = consulta($sqlRol);// $ejecutar_consulta->fetch_assoc();
$id_cargo = $temp[0]['id_cargo'];
$estado = $arrayUser[0]['estado'];
$fotoPerfil = $temp[0]['foto'];
$nombreUsuario = 'Lic. '.$temp[0]['nombre'].' '.$temp[0]['ap_paterno'].' '.$temp[0]['ap_materno'];
//echo $id_cargo . ' ' . $estado . ' ' . $nombreUsuario;
if($estado == 1){
session_start();
$_SESSION["autentificado"] = true;//queda autenticado
$_SESSION["usuario"] = $nombreUsuario; // se asigna el nombre del usuario a la session
$_SESSION["rol"] = $id_cargo; //asignamos rol de usuario /admin =1, coordinado =2, defensor =3
$_SESSION["mensaje"] = ' ';
$_SESSION["foto"] = $fotoPerfil;
// $sqlPersonal = 'select id_personal,nombre,ap_paterno,ap_materno,curp,nup,nue,foto from personal where nue ='.$usuario;
$sqlPersonal = 'select id_personal,nombre,ap_paterno,ap_materno,curp,nup,nue,foto,materia,sistema,instancia
from personal inner join personal_campo using(id_personal)
inner join materia using(id_materia) where nue ='.$usuario;
$arrayPersonal = consulta($sqlPersonal);
$_SESSION["personal"] = $arrayPersonal;
echo'<script language="javascript">window.location="vistas/baseIndex.php"</script>';
//header("Location: ../Vistas/baseIndex.php");
}else{
echo '<p class="text-danger"><strong>Cuenta inactiva contacto al administrador</strong></p>';
}
}else{
echo '<p class="text-danger"><strong>No existe ninguna cuenta vinculada a ' . $usuario . '</strong></p>';
}
}else{
echo '<p class="text-danger"><strong>Contraseña incorrecta ******</strong></p>';
}
}
?>
<file_sep><?php
include '../../modelo/defensor/defensor.php';
/* $id_defensor = $_POST['id_personal'];
$expedientes = getNumExpedientes($id_defensor); */
if($_FILES['fileToUpload']['size'] != 0){
$nombreFoto = $_FILES["fileToUpload"]["name"];
$rutaFoto = $_FILES["fileToUpload"]["tmp_name"];
$carpeta='../../recursos/uploads/';
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$destino = $carpeta.basename($nombreFoto);
move_uploaded_file($rutaFoto,$destino);
}else{
$nombreFoto = $_POST['imagen'];
}
$defensor = Array(
"id_personal" =>$_POST['id_personal'],
"nombre" =>strtoupper($_POST['nombre']),
"ap_paterno" =>strtoupper($_POST['ap_paterno']),
"ap_materno" =>strtoupper($_POST['ap_materno']),
"curp" =>strtoupper($_POST['curp']),
"calle" =>strtoupper($_POST['calle']),
"numero_ext" =>$_POST['numero_ext'],
"numero_int" =>$_POST['numero_int'],
"colonia" =>strtoupper($_POST['colonia']),
"municipio" =>strtoupper($_POST['municipio']),
"telefono" =>$_POST['telefono'],
"correo_electronico" =>$_POST['correo_electronico'],
"foto" => $nombreFoto
);
$actualizaDefensor = actualiza_defensor($defensor);
$mensaje=['tipo'=>"exito",
'mensaje'=>"Se ha actualizado satisfactoriamente"];
// $dirigir="listar_defensor";
//print_r($actualizaDefensor);
if(!isset($_GET['tipo'])){
session_start();
$_SESSION['mensaje'] = $mensaje;
// $_SESSION['dirigir'] = $dirigir;
//return 200; //
header("location: ../../vistas/administrador/");
}else{
echo "json";
}
?>
<file_sep><?php
include_once('../../modelo/expediente.php');
include '../../libreria/herramientas.php';
$respuesta = Array(
"id_expediente" =>$_POST['id_expediente'],
"fecha_baja" =>$_POST['fecha_baja'],
"motivos" =>$_POST['motivoBaja'],
"estado" =>"BAJA",
"observaciones" =>$_POST['observacion']
);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);/// convierte todo a mayusculas
//$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
//if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
//print_r($respuesta);
{
// bajaExpediente($respuesta); se cambio por esto
setBajaActivoExpediente($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Baja de expediente exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
if(isset($_GET['pertenece']))
if($_GET['pertenece']=='admin')
{
$mensaje=['tipo'=>"exito",
'mensaje'=>"Baja exitoso"
];
$dirigir="asignar_defensor";
$_SESSION['mensaje'] = $mensaje;
header("location: ../../vistas/administrador/index.php");
}
else{
echo json_encode($mensaje);
}
?><file_sep>function funcionGlobalInformeAct(jsonInforme){
console.time('Test functionGlobalInformeAct');
var fechaI = document.getElementById('inputInicio').value;
var fechaFi = document.getElementById('inputFinal').value;
var nombreDef = jsonInforme[0]['Defensor']+' '+jsonInforme[0]['apDefP']+' '+jsonInforme[0]['apDefM'];
var fecha1 = new Date(fechaI);
var fecha2 = new Date(fechaFi);
var meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Nomviembre", "Diciembre"];
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
var pdfAct = {
watermark: { text: 'www oaxaca gob mx', color: 'gray', opacity: 0.3, bold: true, italics: false },
pageSize: 'A4',
pageOrientation: 'portrait',
header: {
margin: [105, 20, 100, 0],
columns: [
{
// usually you would use a dataUri instead of the name for client-side printing
// sampleImage.jpg however works inside playground so you can play with it
image: 'data:image/png;base64,' + base64, width: 400, height: 60
}
]
},
footer: function (currentPage, pageCount) {
return {
table: {
widths: ['*', 00],
body: [
[
{ text: 'Pág. ' + currentPage + ' de ' + pageCount + ' ', alignment: 'center', bold: true, color: 'gray' }
]
]
},
layout: 'noBorders',
};
},
// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [80, 60, 40, 60],
content: [
{
stack: [
'“2018, AÑO DE LA ERRADICACIÓN DEL TRABAJO INFANTIL”',
{
text: '<NAME>, <NAME>, Oax; ' + primerM + siguiente + '.\n' +
'Periodo de ' + fechaI + ' a ' + fechaFi, style: 'subheader'
},
],
style: 'header'
},
{ text: 'INFORME COMPLETO POR PERIODO', style: 'subheader2' },
{ text: '1.- ASESORÍAS JURÍDICAS', style: 'subheader2' },
{ text: 'Con el objetivo de contribuir a una justicia pronta, expedita e imparcial, durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' del presente año, la Defensoría Pública brindó ' + actividades['asesorias'] + ' servicios gratuitos de asesorías jurídicas generales, lo anterior se detalla de la siguiente manera:', style: 'textoJustificado' },
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorio y oral', style: 'tableHeader', alignment: 'center' },
],
['Asesorías simples Jurídicas', asesoriasTO['asesTradicional'], asesoriasTO['asesOral']],
]
}
},
{ text: 'Del total general de asesorías jurídicas, a continuación se desglosan los atributos de los beneficiarios:', style: 'textoJustificado' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Sexo', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Hombre', totalH, sexos['numMascT'], sexos['numMascO']],
['Mujer', totalM, sexos['numFemT'], sexos['numFemO']],
['Total', totalSexo, totalSexoT, totalSexoO]
]
}
},
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Género', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Lésbico', totalLesbico, generos['numLesbicoT'], generos['numLesbicoO']],
['Gay', totalGay, generos['numGayT'], generos['numGayO']],
['Bisexual', totalBisexual, generos['numBisexualT'], generos['numBisexualO']],
['Transexual', totalTransexual, generos['numTransexualT'], generos['numTransexualO']],
['Transgénero', totalTransgenero, generos['numTransgeneroT'], generos['numTransgeneroO']],
['Travestí', totalTravesti, generos['numTravestiT'], generos['numTravestiO']],
['Intersexual', totalIntersexual, generos['numIntersexualT'], generos['numIntersexualO']],
['Total', totalG, totalGenerosT, totalGenerosO]
]
}
},
{ text: '\n ', style: 'saltoLinea' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Edad', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', totalEdad1, edades['edades1T'], edades['edades1O']],
['25 A 29 AÑOS', totalEdad2, edades['edades2T'], edades['edades2O']],
['30 A 34 AÑOS', totalEdad3, edades['edades3T'], edades['edades3O']],
['35 A 39 AÑOS', totalEdad4, edades['edades4T'], edades['edades4O']],
['40 A 44 AÑOS', totalEdad5, edades['edades5T'], edades['edades5O']],
['45 A 49 AÑOS', totalEdad6, edades['edades6T'], edades['edades6O']],
['50 A 54 AÑOS', totalEdad7, edades['edades7T'], edades['edades7O']],
['55 A 59 AÑOS', totalEdad8, edades['edades8T'], edades['edades8O']],
['DE 60 O MAS AÑOS', totalEdad9, edades['edades9T'], edades['edades9O']],
['TOTAL', totalEdadS, totalEdadT,totalEdadO]
]
}
},
{
style: 'tableExample',
color: 'black',
table: {//etnias
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: etniasR
}
},
{ text: '', style: 'saltoLinea' }, { text: '\n\n', style: 'saltoLinea' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: idiomasR
}
},
{
style: 'tableExample',
color: 'black',
table: {
widths: ['auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Discapacidades', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', totalSen, discapacidades['numSensorialesT'], discapacidades['numSensorialesO']],
['Motrices', totalMot, discapacidades['numMotricesT'], discapacidades['numMotricesO']],
['Mentales', totalMen, discapacidades['numMentalesT'], discapacidades['numMentalesO']],
['Multiples', totalMul, discapacidades['numMultiplesT'], discapacidades['numMultiplesO']],
['Total', totalDiscapacidad, totalDisT, totalDisO]
]
}
},
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de asesorías jurídicas brindadas en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos en asesorías jurídicas, esto también por sistema. ', style: 'textoJustificado' },
{ text: '', style: 'saltoLinea' }, { text: '\n\n', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE ASESORÍAS JURÍDICAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Asesorías brindadas', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{ text: '\n ', style: 'saltoLinea' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE ASESORÍAS JURÍDICAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Asesorías brindadas', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{ text: '2.- AUDIENCIAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' del presente año, los defensores publicos asistieron a ' + actividades['audiencias'] + ' audiencias celebradas.', style: 'textoJustificado'
},
{ text: 'Por sistema__________ Sistema Tradicional: materia penal _____; materia civil ________; materia familiar _______; materia administrativa _______; materia agraria ________; materia ejecución de sanciones ________; tribunal de alzada _______. Sistema Acusatorio y oral: materia penal adultos __________; materia penal adolescentes ________; materia ejecución de sanciones ________.', style: 'textoJustificado' },
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de asistencia a audiencias en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos de asistencia en audiencias, esto también por sistema.', style: 'textoJustificado' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE AUDIENCIAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Asistencia \nde audiencias', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{ text: '\n ', style: 'saltoLinea' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE AUDIENCIAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Asistencia \nde audiencias', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{ text: '3.- VISITAS CARCELARÍAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ___ de _______ al ____ de ________ del presente año, los Defensores Públicos realizaron ___________ visitas carcelarias a sus internos.', style: 'textoJustificado'
},
{ text: 'Por sistema__________ Sistema Tradicional: materia penal _____; materia ejecución de sanciones ________ Sistema Acusatorio y oral: materia penal adultos __________; materia penal adolescentes ________; materia ejecución de sanciones ________.', style: 'textoJustificado' },
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de visitas carcelarias en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos en visitas carcelarias , esto también por sistema.', style: 'textoJustificado' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE VISITAS CARCELARÍAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Visitas \n Carcelarías', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{ text: '\n\n\n ', style: 'saltoLinea' },
{ text: '\n\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE VISITAS CARCELARÍAS' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [150, 'auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Defensor público', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Visitas \n Carcelarías', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].asesoriasTotal, defensores[0].juzgado, defensores[0].asesoriasT, defensores[0].asesoriasO],
[defensores[1].defensor, defensores[1].asesoriasTotal, defensores[1].juzgado, defensores[1].asesoriasT, defensores[1].asesoriasO],
[defensores[2].defensor, defensores[2].asesoriasTotal, defensores[2].juzgado, defensores[2].asesoriasT, defensores[2].asesoriasO],
[defensores[3].defensor, defensores[3].asesoriasTotal, defensores[3].juzgado, defensores[3].asesoriasT, defensores[3].asesoriasO],
[defensores[4].defensor, defensores[4].asesoriasTotal, defensores[4].juzgado, defensores[4].asesoriasT, defensores[4].asesoriasO],
[defensores[5].defensor, defensores[5].asesoriasTotal, defensores[5].juzgado, defensores[5].asesoriasT, defensores[5].asesoriasO],
[defensores[6].defensor, defensores[6].asesoriasTotal, defensores[6].juzgado, defensores[6].asesoriasT, defensores[6].asesoriasO],
[defensores[7].defensor, defensores[7].asesoriasTotal, defensores[7].juzgado, defensores[7].asesoriasT, defensores[7].asesoriasO],
[defensores[8].defensor, defensores[8].asesoriasTotal, defensores[8].juzgado, defensores[8].asesoriasT, defensores[8].asesoriasO],
[defensores[9].defensor, defensores[9].asesoriasTotal, defensores[9].juzgado, defensores[9].asesoriasT, defensores[9].asesoriasO]
]
}
},
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'C.c.p.-', style: ['quote', 'small'] },
{
text: 'Mtro. <NAME>.- Director de la Defensoría Pública del Estado de Oaxaca.- Para su conocimiento e intervención.- Presente.-C.P <NAME>.- Secretario Técnico.- Para mismo fin.- Presente Exp. y minutario.', style: ['quote', 'small']
}
]
]
}, layout: 'noBorders'
}
],
styles: {
header: {
fontSize: 8,
bold: false,
alignment: 'center',
margin: [0, 40, 0, 10]
},
subheader: {
fontSize: 10,
alignment: 'right',
margin: [0, 10, 0, 0]
},
textoJustificado: {
fontSize: 11,
alignment: 'justify',
margin: [0, 0, 15, 15],
},
subheader2: {
fontSize: 11,
alignment: 'left',
margin: [0, 0, 15, 15],
bold: 'true'
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
saltoLinea: {
margin: [0, 200, 0, 0]
},
quote: {
italics: true
},
small: {
fontSize: 8
}
},
defaultStyle: {
// alignment: 'justify'
}
}
console.timeEnd('Test functionGlobalInformeAct');
return pdfAct;
}
<file_sep><?php
include_once('../../modelo/usuarioServicio.php');
$listaUser = listar_usuarios();
$contenido = json_encode($listaUser);
?><file_sep><?php
include_once '../../modelo/usuarioServicio.php';
$id_expediente = $_GET['id_expediente'];
$informacion = getUsuarioServicioById($id_expediente);
$encode = json_encode($informacion);
echo $encode;
?><file_sep>var globalDatosEstadistico;
var imagen;
//google.visualization.events.addListener(chart, 'click', function () { f=chart.getImageURI();
//f.addEventListener('click',)
//document.getElementById('png').outerHTML = '<p onclick=debugBase64(f)>Printable version</p>';
// document.getElementById('button').outerHTML = '<a href="' + chart.getImageURI() + '" download="cute.jpg">Printable version</a>';
function gestionGrafica(elemento){
console.log("en elemnto ",elemento);
switch (elemento) {
case 'genero':
genero();
break;
case 'materia':
Materia();
break;
case 'discapacidad':
discapacidades();
break;
case 'idioma':
idioma();
break;
case 'expediente':
expediente();
break;
case 'etnia':
etnias();
break;
default:
break;
}
}
function discapacidades() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadistico.tablaDiscapacidadExp;
var oral=array.filter(function(x){return (x.sis=='ORAL')});
var tradicional=array.filter(function(x){return (x.sis=='TRADICIONAL')});
var grafica=[['Discapacidad en sistema tradicional','Hombre','Mujeres']];
tradicional.forEach(element => {
var arrayNew=[];
arrayNew.push(element.discapacidadUs);
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
grafica.push(arrayNew);
});
var graficatwo=[['Discapacidad en sistema oral','Hombre','Mujeres']];
oral.forEach(element => {
var arrayNew=[];
arrayNew.push(element.discapacidadUs);
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
graficatwo.push(arrayNew);
});
console.log("emprimiento la grafica ",grafica);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttontwo').empty();
// document.getElementById('buttontwo').outerHTML = '<a href="' + barchart.getImageURI() + '" download="grafica.jpg">Descargar</a>';
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de discapacidad
function etnias() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadistico.tablaEtniaExp;
var oral=array.filter(function(x){return (x.sis=='ORAL')});
var tradicional=array.filter(function(x){return (x.sis=='TRADICIONAL')});
var grafica=[['Etnias en sistema tradicional','Expediente','Hombre','Mujeres']];
tradicional.forEach(element => {
var arrayNew=[];
arrayNew.push(element.etniaUs);
arrayNew.push(parseInt(element.totalExp));
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
grafica.push(arrayNew);
});
var graficatwo=[['Etnias en sistema oral','Expediente','Hombre','Mujeres']];
oral.forEach(element => {
var arrayNew=[];
arrayNew.push(element.etniaUs);
arrayNew.push(parseInt(element.totalExp));
arrayNew.push(parseInt(element.hombres));
arrayNew.push(parseInt(element.mujeres));
graficatwo.push(arrayNew);
});
console.log("emprimiento la grafica ",grafica);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttonone').empty();
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de etnias
function genero() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadistico.tablaGeneroExp;
var oral=array.filter(function(x){return (x.sistema=='ORAL')});
var tradicional=array.filter(function(x){return (x.sistema=='TRADICIONAL')});
var grafica=[['Discapacidad en sistema tradicional','Total']];
tradicional.forEach(element => {
var arrayNew=[];
arrayNew.push(element.generoUs);
arrayNew.push(parseInt(element.totalUsuarios));
grafica.push(arrayNew);
});
var graficatwo=[['Discapacidad en sistema oral','total']];
oral.forEach(element => {
var arrayNew=[];
arrayNew.push(element.generoUs);
arrayNew.push(parseInt(element.totalUsuarios));
graficatwo.push(arrayNew);
});
console.log("emprimiento la grafica genero",grafica);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttonone').empty();
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de discapacidad
function idioma() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var tradicional=globalDatosEstadistico.tablaIdiomaExp;
var oral=globalDatosEstadistico.tablaIdiomaExp;
// var oral=array.filter(function(x){return (x.sis=='ORAL')});
// var tradicional=array.filter(function(x){return (x.sis=='TRADICIONAL')});
var grafica=[['Idiomas en sistema tradicional','Hombre','Mujeres']];
tradicional.forEach(element => {
var arrayNew=[];
arrayNew.push(element.idiomaUs);
arrayNew.push(parseInt(element.hombresT));
arrayNew.push(parseInt(element.mujeresT));
grafica.push(arrayNew);
});
var graficatwo=[['idiomas en sistema oral','Hombre','Mujeres']];
oral.forEach(element => {
var arrayNew=[];
arrayNew.push(element.idiomaUs);
arrayNew.push(parseInt(element.hombresO));
arrayNew.push(parseInt(element.mujeresO));
graficatwo.push(arrayNew);
});
console.log("emprimiento la grafica ",grafica);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttonone').empty();
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de idioma
function Materia() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadistico.tablaMateriaExp;
var grafica;//=[['Materia en sistema tradicional','Hombres','Mujeres'],
// ];
array.forEach(elemento => {
grafica= [['Materia en sistema tradicional','Expediente','Hombres','Mujeres'],
['Agrario',parseInt(elemento.agrarioTExp),parseInt(elemento.agrarioTH),parseInt(elemento.agrarioTM)],
['Amparos',parseInt(elemento.amparosTExp),parseInt(elemento.amparosTH),parseInt(elemento.amparosTM)],
['Civil',parseInt(elemento.civilTExp),parseInt(elemento.civilTH),parseInt(elemento.civilTM)],
['Ejecucion de sanciones',parseInt(elemento.ejecucionTExp),parseInt(elemento.ejecucionTH),parseInt(elemento.ejecucionTM)],
['Familiar',parseInt(elemento.familiarTExp),parseInt(elemento.familiarTH),parseInt(elemento.familiarTM)],
['Mercantil',parseInt(elemento.mercantilTExp),parseInt(elemento.mercantilTH),parseInt(elemento.mercantilTM)],
['Penal',parseInt(elemento.penalTExp),parseInt(elemento.penalTH),parseInt(elemento.penalTM)]
];
});
//var graficatwo=[['Materia en sistema oral','Hombres','Mujeres']];
var graficatwo;
array.forEach(element => {
graficatwo=[['Materia en sistema oral','Expediente','Hombres','Mujeres'],
['Penal',parseInt(element.penalOExp),parseInt(element.penalOH),parseInt(element.penalOM)]
];
});
console.log("emprimiento la grafica ",grafica);
console.log("emprimiento la grafica two ",graficatwo);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttonone').empty();
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de materia
function expediente() {
//google.charts.load('current', {'packages':['bar']});
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
var array=globalDatosEstadistico.tablaGeneralExp;
var tradicional=array.find(function(x){return (x.sistemaG==='TRADICIONAL')});
var oral=array.find(function(x){return (x.sistemaG==='ORAL')});
var grafica;//=[['Materia en sistema tradicional','Hombres','Mujeres'],
// ];
// tradicional.forEach(elemento => {
grafica= [['Expediente en sistema tradicional','Total expediente'],
['Baja falta de interes',parseInt(tradicional.expBajaFalta )],
['Baja por revocación',parseInt(tradicional.expBajaRevocacion)],
['Finalizados',parseInt(tradicional.expFinalizacion)],
['Iniciado',parseInt(tradicional.expIniciado )],
['Proceso',parseInt(tradicional.expProceso )]
];
//});
//var graficatwo=[['Materia en sistema oral','Hombres','Mujeres']];
var graficatwo;
// oral.forEach(element => {
graficatwo= [['Expediente en sistema oral','Total expediente'],
['Baja falta de interes',parseInt(tradicional.expBajaFalta )],
['Baja por revocación',parseInt(tradicional.expBajaRevocacion)],
['Finalizados',parseInt(tradicional.expFinalizacion)],
['Iniciado',parseInt(tradicional.expIniciado )],
['Proceso',parseInt(tradicional.expProceso )]
];
//});
console.log("emprimiento la grafica ",grafica);
console.log("emprimiento la grafica two ",graficatwo);
function drawChart() {
var data = google.visualization.arrayToDataTable(grafica);
var datatwo = google.visualization.arrayToDataTable(graficatwo);
var piechart_options = {title:'Grafica de tradicional',
subtitle:'fecha:2018-2018'};
var piechart = new google.visualization.ColumnChart(document.getElementById('columnchart_one'));
piechart.draw(data, piechart_options);
$('#buttonone').empty();
$('#buttonone').append( '<a href="' + piechart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
var barchart_options = {title:'Grafica de oral',
// legend: 'none'
};
//var chart = new google.visualization.Bar(document.getElementById('barchart_div'));
var barchart = new google.visualization.ColumnChart(document.getElementById('columnchart_two'));
//barchart.draw(data, barchart_options);
barchart.draw(datatwo, barchart_options);
$('#buttonone').empty();
$('#buttontwo').append( '<a href="' + barchart.getImageURI() + '" download="Grafica.jpg">Descargar</a>');
//barchart.draw(data, google.charts.Bar.convertOptions(barchart_options));
}
}// final funcion de materia
<file_sep><?php
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$defensor = Array(
"adscripcion" =>6,
"nue" =>'32122'
);
$url='http://localhost/defensoriaPublica/controlador/juzgado/actividad_juzgado.php';
$postfields = http_build_query( $defensor);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postfields,
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$this->assertEquals(200, intval($result));
}
}
?><file_sep><?php
// header('Content-Type: application/json');
//include '../../modelo/personal.php';
include '../../modelo/contraparte.php';
$listaContraparte= listar_contraparte();
$contrapartesByExpediente= getContrapartesById($_GET['id_expediente']);
echo json_encode($contrapartesByExpediente);
?><file_sep><?php
include_once('../../libreria/conexion.php');
//Definimos la funciones sobre el objeto crear_asesoria
function Registrar($asesoria){
$sql = "INSERT INTO asesoria ";
$sql.= "SET id_actividad='".$asesoria['id_actividad']."',";
$sql.= " latitud='".$asesoria['latitud']."', longitud='".$asesoria['longitud']."'";
echo $sql;
$lista=registro($sql);
return $lista;
}
?>
<file_sep><?php
include_once('../../modelo/defensor/defensor.php');
include_once('../../modelo/expediente.php');
include_once('../../modelo/respuesta/respuesta.php');
$listaExpedientes = listar_expedientes();
$contenido = json_encode($listaExpedientes);
//echo $_GET['idPersonal'];
if(isset($_GET['idPersonal'])){
$misExpedietnesDefensor=json_encode(listar_expediente_x_defensor($_GET['idPersonal']));
echo $misExpedietnesDefensor;
}
if(isset($_GET['xpregunta'])){
// $misExpedietnesDefensor=json_encode(listar_expediente_x_defensor($_GET['idPersonal']));
$misExpedietnesDefensor=listar_expediente_x_defensor($_GET['id_defensor']);
foreach ($misExpedietnesDefensor as $key => $value) {
$pregunta= respuestaPregunta($value['id_expediente']);
$misExpedietnesDefensor[$key]['observaciones']=$pregunta[sizeof($pregunta)-1]['observaciones'];
}
echo json_encode($misExpedietnesDefensor);
// $listaRespuestaPregunta= respuestaPregunta($_GET['id_expediente']);
// echo $_GET['id_expediente'];
// echo json_encode($listaRespuestaPregunta);
//echo $misExpedietnesDefensor;
}
?><file_sep><?php
//include '../../controlador/conexion.php';
include_once '../../libreria/conexion.php';
function getUsuarioServicioById($id_expediente){
$sql = "select * from usuario_servicio inner join detalle_usuario_expediente using(id_usuario_servicio) where id_expediente='".$id_expediente."'";
$lista = consulta($sql);
return $lista;
}
function getUsuarioByCurp($curp){
$sql = "select * from usuario_servicio where curp='".$curp."'";
$consulta = consulta($sql);
// echo $sql;
return $consulta;
}
//Definimos la funciones sobre el objeto crear_defensor
function crear_usuarioSevicio($objetoEntidad){
$sql = "INSERT INTO usuario_servicio ";
$sql.= "SET nombre='".$objetoEntidad['nombre']."', ap_materno='".$objetoEntidad['ap_materno']."',";
$sql.= "ap_paterno='".$objetoEntidad['ap_paterno']."', genero='".$objetoEntidad['genero']."',";
$sql.= "edad='".$objetoEntidad['edad']."', idioma='".$objetoEntidad['idioma']."',";
$sql.= "etnia='".$objetoEntidad['etnia']."', curp='".$objetoEntidad['curp']."',";
$sql.= "calle='".$objetoEntidad['calle']."', numero_ext='".$objetoEntidad['numero_ext']."',";
$sql.= "numero_int='".$objetoEntidad['numero_int']."', municipio='".$objetoEntidad['municipio']."',";
$sql.= "estadoProveniente='".$objetoEntidad['estado']."',sexo='".$objetoEntidad['sexo']."',";
$sql.= "telefono='".$objetoEntidad['telefono']."', correo_electronico='".$objetoEntidad['correo']."',";
$sql.= "discapacidad='".$objetoEntidad['discapacidad']."'";
echo $sql;
$lista=registro($sql);
// echo $lista;
return $lista;
}
//Definimos una funcion que acutualice al usuarioServicio
function actualizar_usuario_servicio($usuario_servicio){
$sql = "update usuario_servicio set ";
$sql.= "nombre='".$usuario_servicio['nombre']."',";
$sql.= "ap_paterno='".$usuario_servicio['apellido_paterno']."',";
$sql.= "ap_materno='".$usuario_servicio['apellido_materno']."',";
$sql.= "etnia='".$usuario_servicio['etnia']."',";
$sql.= "idioma='".$usuario_servicio['idioma']."',";
$sql.= "calle='".$usuario_servicio['calle']."',";
$sql.= "colonia='".$usuario_servicio['colonia']."',";
$sql.= "municipio='".$usuario_servicio['municipio']."',";
$sql.= "telefono='".$usuario_servicio['telefono']."',";
$sql.= "genero='".$usuario_servicio['genero']."',";
$sql.= "discapacidad='".$usuario_servicio['discapacidad']."',";
$sql.= "correo_electronico='".$usuario_servicio['email']."'";
$sql.=" where id_usuario_servicio='".$usuario_servicio['id_usuario_servicio']."'";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
//Definimos una funcion que borrar defensor
function eliminar_usuarioServicio($id_defensor){
//$sql = "DELETE from defensor where id_defensor = '".$id_defensor."'";
$sql = "UPDATE defensor as d inner join personal as p using (id_personal)
set d.estado = false, p.estado=false where id_defensor = '".$id_defensor."'";
$lista = consulta($sql);
return $lista;
}
function ultimoUsuarioCreado(){
$sql = mysql_query("SELECT MAX(id_defensor) AS id FROM usuario_servicio");
$id=consulta($sql);
return $id[0]['id'];
}
function listar_usuarios(){
$sql="SELECT id_usuario_servicio, nombre, ap_paterno,ap_materno,curp,etnia,colonia,municipio FROM usuario_servicio as u;";
$lista=consulta($sql);
return $lista;
}
function listar_usuarios_id($id_usuario_servicio){
$sql="SELECT * FROM usuario_servicio where id_usuario_servicio=".$id_usuario_servicio;
// echo $sql;
$lista=consulta($sql);
return $lista;
}
?>
<file_sep><?php
include_once('../../libreria/conexion.php');
function get_materia_instancia_sistema($materia,$instancia,$sistema){
$sql="SELECT id_materia,materia,instancia FROM materia
where materia ='".$materia."' and instancia =".$instancia." and sistema='".$sistema."'";
// echo $sql;
$lista=consulta($sql);
return $lista;
}
function get_materia_instancia(){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado) where id_cargo =4";
$lista=consulta($sql);
return $lista;
}
?><file_sep><?php
include '../../modelo/defensor/defensor.php';
//echo $_GET['cedula'];
$id_defensor = $_POST['id_personal'];
$defensor = getDefensorUpdate($id_defensor);//obtenerDefensorCedula($cedulaProf);
//print_r( $defensor);
$defensorEncode = json_encode($defensor);
echo $defensorEncode;
?><file_sep><?php if ( session_start()) {
if(isset($_SESSION["autentificado"]) == true) {
echo'<script language="javascript">window.location="vistas/baseIndex.php"</script>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Expires" content="0">
<meta http-equiv="Last-Modified" content="0">
<meta http-equiv="Cache-Control" content="no-cache, mustrevalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Defensoria publica del estado de oaxaca| </title>
<!-- Bootstrap -->
<link href="recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Font Awesome -->
<link href="recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<!-- NProgress -->
<link href="recursos/vendors/nprogress/nprogress.css" rel="stylesheet"/>
<!-- Animate.css -->
<link href="recursos/vendors/animatecss/animate.min.css" rel="stylesheet"/>
<!-- Custom Theme Style -->
<link href="recursos/css/custom.min.css" rel="stylesheet"/>
<script src="recursos/js/ajax/jquery.min.js"> </script>
<script src="recursos/js/jquery-1.11.2.min.js"></script>
<script src="recursos/js/modernizr.js"></script>
<script src="recursos/js/bootstrap.min.js"></script>
<script src="recursos/js/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="recursos/js/main.js"></script>
<script src="recursos/js/jquery-1.11.2.min.js"></script>
<script src="recursos/js/modernizr.js"></script>
<script src="recursos/js/bootstrap.min.js"></script>
<script src="recursos/js/main.js"></script>
<link rel="stylesheet" href="Recursos/css/beforeSend.css">
</head>
<body class="login">
<div>
<a class="hiddenanchor" id="signup"></a>
<a class="hiddenanchor" id="signin"></a>
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<form method="POST">
<p><img src="recursos/images/defensoriav1.png" width="300px" height="100px"/></p>
<div>
<input type="text" class="form-control" placeholder="Username" required="" name="username" id="usuarios_inicio"
onkeyup = "if (event.keyCode == 13) ingresarSistema()" maxlength="70"/>
</div>
<div>
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password"
onkeyup = "if (event.keyCode == 13) ingresarSistema()" name="password_txt" required="" maxlength="70"/>
</div>
<div>
<button id="ingresar" class="btn btn-primary btn-sm " type="button" onclick="ingresarSistema()" >
<i class="zmdi zmdi-arrow-right"> </i>
Iniciar Sesion
</button>
<div id="mensaje_index" style="background: #fff; border-radius: 1em;" class="group-material-login text-center">
</div>
</div>
<div class="clearfix"></div>
<div class="separator">
<div class="clearfix"></div>
<br/>
<div>
<p>©2018 All Rights Reserved. Defensoria publica de oaxaca Privacy and Terms</p>
</div>
</div>
</form>
</section>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
?>
<meta http-equiv="Contet-Type" name="" content="text/html; charset=iso-8859-1">
<script type='text/javascript'>
console.log("hola en este freme");
</script>
<script type="text/javascript" src="../../recursos/js/jquery-1.11.2.min.js"></script>
<!-- Bootstrap -->
<link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Font Awesome -->
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<!-- NProgress -->
<link href="../../recursos/vendors/nprogress/nprogress.css" rel="stylesheet"/>
<!-- iCheck -->
<link href="../../recursos/vendors/iCheck/skins/flat/green.css" rel="stylesheet"/>
<!-- Datatables -->
<link href="../../recursos/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet"/>
<script src="../../recursos/js/main.js"></script>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<!-- <script type="text/javascript" src="../../recursos/vendors/jquery/jquery-ui.js"></script>
--><link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Font Awesome -->
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<script src="../../recursos/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<style>
.embed-container {
position: relative;
padding-bottom: 56.25%;
height: 0;
overflow: hidden;
}
.embed-container iframe {
position: absolute;
top:0;
left: 0;
width: 100%;
height: 100%;
}
.mi-iframe {
width: 250px;
height: 50px;
}
/* CSS pantallas de 320px o superior */
@media (min-width: 320px) {
.mi-iframe {
width: 300px;
height: 150px;
}
}
/* CSS pantalla 768px o superior */
@media (min-width: 768px) {
.mi-iframe {
width: 500px;
height: 250px;
}
}
</style>
<!-- Custom Theme Style -->
<!-- <link href="../../recursos/css/custom.css" rel="stylesheet"/>
-->
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-6 col-sm-3 col-xs-12 " >Registro de Estudio</label></h1>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<!-- <form enctype="multipart/form-data" id="myform" method="post"> -->
<form enctype="multipart/form-data" autocomplete="off" id="myform" name="formEstudio" data-toggle="validator" role="form" class="" object="defensor" >
<div id="divExpediente" class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Perfil estudio<span class="">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required onkeyup="mayusculas(event, this)" type="text" name="perfil" id="perfil" data-error="se requiere del perfil" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
<div id="gradoDelito" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Instituto <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="text" pattern="[A-Za-z. ]+" onkeyup="mayusculas(event, this)" name="instituto" id="instituto" data-error="Solo letras" class="form-control col-md-7 col-xs-12">
</div></div> </div>
<div id="gradoDelito" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Descripcion del perfil <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<textarea rows="" cols="" required pattern="[A-Za-z. ]+" onkeyup="mayusculas(event, this)" name="descripcion_perfil_egreso" id="descripcion_perfil" data-error="Solo letras" class="form-control col-md-7 col-xs-12"></textarea>
</select>
</div></div> </div>
<div id="gradoDelito" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Especialidad <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="text" pattern="[A-Za-z. ]+" onkeyup="mayusculas(event, this)" name="especialidad" id="especialidad" data-error="Solo letras" class="form-control col-md-7 col-xs-12">
</div></div> </div>
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="delito">Grado de estudio<span class="">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select required="" id="grado_estudio" name="grado_escolaridad" class="form-control ">
<option value="">--SELECCIONE UNA OPCIÓN-</option>
<option value="MAESTRIA">MAESTRIA</option>
<option value="DOCTORADO">DOCTORADO</option>
<option value="LICENCIATURA">LICENCIATURA</option>
</select> <div class="help-block with-errors"></div> </div>
</div></div>
<!-- <div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="delito">Especialidad<span class="">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="text" pattern="[A-Za-z ]+" onkeyup="mayusculas(event, this)" name="instituto" id="especiad" data-error="Solo letras" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
-->
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="delito">Fecha de termino<span class="">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="date" name="fecha_termino" id="fecha_termino" data-error="Se requiere de una fecha" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="delito">Documento provatorio<span class="">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="file" name="documento_provatorio" id="documento_provatorio" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
<input type="text" name="usuarios" id="usuarios" style="display:none;" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="id_personal" id="id_personal" style="display:none;" value="<?php echo $_SESSION['personal'][0]["id_personal"]?>" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="tipoSistema" id="tipoSistema" style="display:none;" value="<?php echo $_SESSION['personal'][0]["sistema"]?>" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="tipoMateria" id="tipoMateria" style="display:none;" value="<?php echo $_SESSION['personal'][0]["materia"]?>" class="form-control col-md-7 col-xs-12"/>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="enviarFormEstudio" type ="button" class="btn btn-succes btn btn-success btn-lg" onclick="registroEscolaridad(event,this)" value="Registrar"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</div>
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/defensor/gestionEscolaridad.js"></script>
<script>
//$('#myform').validator()
</script>
<div id="contenedorMensaje" class='alert-dismissible fade in <?php echo $alert; ?>' role="alert">
</div><file_sep><?php
//include_once('../../controlador/juzgado/actividad_juzgado.php?tipo=listadoJuzgadoSeguimiento');
include_once('../../controlador/juzgado/actividad_juzgado.php');
?>
<script src="../../recursos/js/herramienta.js"></script>
<script>
function validarFecha(e, elemento) {
var fechas= document.getElementById("fechaNacimiento").value;
console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
var date = new Date(ano,mes,dia)
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
// $(".with-errors").append("<ul class='list-unstyled'><li>solo 4 digito en el a</li></ul>");
console.log("joijoiuiu");
return false;
}
if(ano < 1958 || ano > 1998)
{
console.log("fecha invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="fecha invalida";
error.appendChild(ul);
//alert("Es necesario que el año de la Fecha de Nacimiento, se encuentre entre " + (dtmHoy.getFullYear() - 120)+ " y " + dtmHoy.getFullYear())
// document.ejemploForma.stranio.focus()
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
console.log( date.getYear());
}
function validarCurps() {
// pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)";
var curpNombre=document.getElementById("nombre").value;
console.log("el nombre es ",curpNombre);
var curpApaterno=document.getElementById('aPaterno').value;
var curpAmaterno=document.getElementById('aMaterno').value;
var curpGenero=(((document.getElementById("genero").options[document.getElementById("genero").selectedIndex].value)==="masculino")?'H':'M');
var curpFecha= document.getElementById("fechaNacimiento").value.split('-');
//var fechas= document.getElementById("fecha").value;
var entidad=document.getElementById("entidad").options[document.getElementById("entidad").selectedIndex].value;
console.log(entidad);
var curp = generaCurp({
nombre : curpNombre,
apellido_paterno : curpApaterno,
apellido_materno : curpAmaterno,
sexo : curpGenero,
estado : entidad,
fecha_nacimiento : [curpFecha[2],curpFecha[1],curpFecha[0]]
});
console.log(curp.substr(0,13));
console.log("el rfc",validarRfc());
var claseCurp=document.getElementById("curp");
claseCurp.setAttribute("pattern",curp.substr(0,13)+'[A-Za-z]{3}[0-9]{2}');
}
function validarRfc() {
var rfcNombre=document.getElementById("nombre").value;
var rfcApaterno=document.getElementById('aPaterno').value;
var rfcAmaterno=document.getElementById('aMaterno').value;
var rfcFecha= document.getElementById("fechaNacimiento").value.split('-');
var query="apellidoM="+rfcAmaterno+"&apellidoP="+rfcApaterno+"&nombre="+rfcNombre+"&dia="+rfcFecha[2]+"&mes="+rfcFecha[1]+"&anno="+rfcFecha[0]
url="../../controlador/CalcularRfc.php?"+ query;//apellido_materno=GARCIA&apellido_paterno=HERNANDEZ&fecha=1988-03-17&nombre=OTHON&solo_homoclave=0"
$.ajax({
url: url,
type: "GET",
// data: "cveCurp=SALW941012HOCNPL04",
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function (data) {
var rfc=data;
var claserfc=document.getElementById("rfc");
console.log(rfc);
claserfc.setAttribute("pattern",rfc.trim());
}
});
}
</script>
<script>
function verificarCargo(e, elemento){
if(elemento.selectedIndex===2){
$("#materia").hide();
$("#instancia").hide();
}
if(elemento.selectedIndex===1){
$("#materia").show();
$("#instancia").show();
}
}
function verificarMateria(evento, elemento){
console.log("holas instancia",elemento.selectedIndex);
if((elemento.selectedIndex==1)||(elemento.selectedIndex==2)||(elemento.selectedIndex==3))
$("#instancia").show();
else
$("#instancia").hide();
}
function agrega(){
$('#menuContainer').load("coordinadorRegistrarJuzgado.php");
}
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Registro personal de campo</label></h1>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="agregarjuzado" onclick="agrega()">
<label ><h3>agregar Juzgado</h3></label></a>
</li>
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form id="myform" data-toggle="validator" role="form" class="example_form form-horizontal form-label-left" action ="../../controlador/defensor/registrar_Defensor.php?" object="defensor" method="post">
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Nombre<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="nombre" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ ]+" onkeyup="mayusculas(event, this)" maxlength="40" minlength="3" autofocus="autofocus" required class="form-control text-uppercase" data-error="se letras no máximo de 40 ni minímo de 3" placeholder="Nombre" name="nombre">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Nup<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" pattern="(\d{5})" data-error="solo número de 5 dígito" maxlength="5" minlength="5" class="form-control" required placeholder="nup" name="nup">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Apellido Paterno<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aPaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Paterno" name="apellido_paterno">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 "> Nue<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" pattern="[0-9]+" data-error="solo número de 5 dígito" maxlength="5" minlength="5" class="form-control" required placeholder="nue" name="nue">
<div class="help-block with-errors"></div> </div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-1 " >Apellido Materno<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aMaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Materno" name="apellido_materno">
<div class="help-block with-errors"></div> </div>
</div>
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Teléfono<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12" >
<input type="tel" pattern="([0-9]{13})|([0-9]{10})" maxlength="13" minlength="10" class="form-control " data-error=" solo numero telefonico" required placeholder="Telefono" name="telefono">
<div class="help-block with-errors"/></div>
</div>
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label for="inputEmail" class="control-label col-md-4 col-sm-3 col-xs-12 " >Fecha nacimiento<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="fechaNacimiento" type="date" onkeyup="validarFecha(event,this)" onblur="validarFecha(event,this)" title"fecha invalido" pattern="" data-error="fecha invalida" maxlength="50" class="form-control" required="" placeholder="Email" name="fecha">
<div class="help-block with-errors"></div>
</div>
</div>
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label for="inputEmail" class="control-label col-md-4 col-sm-3 col-xs-12 " >Email<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" title"correo invalido" pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$" data-error="correo invalido" maxlength="50" class="form-control" required="" placeholder="Email" name="email">
<div class="help-block with-errors"></div> </div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Entidad federativa de nacimiento</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select id="entidad" name="strEntidadNacimiento" class="select2_group form-control textbox">
<option value="">- Seleccione -</option>
<option value="AS">AGUASCALIENTES</option>
<option value="BC">BAJA CALIFORNIA</option>
<option value="BS">BAJA CALIFORNIA SUR</option>
<option value="CC">CAMPECHE</option>
<option value="CL">COAHUILA DE ZARAGOZA</option>
<option value="CM">COLIMA</option>
<option value="CS">CHIAPAS</option>
<option value="CH">CHIHUAHUA</option>
<option value="DF">DISTRITO FEDERAL</option>
<option value="DG">DURANGO</option>
<option value="GT">GUANAJUATO</option>
<option value="GR">GUERRERO</option> <option value="HG">HIDALGO</option> <option value="JC">JALISCO</option> <option value="MC">MEXICO</option> <option value="MN">MICHOACAN DE OCAMPO</option> <option value="MS">MORELOS</option> <option value="NT">NAYARIT</option> <option value="NL">NUEVO LEON</option> <option value="OC">OAXACA</option> <option value="PL">PUEBLA</option> <option value="QT">QUERETARO DE ARTEAGA</option> <option value="QR">QUINTANA ROO</option> <option value="SP">SAN LUIS POTOSI</option> <option value="SL">SINALOA</option> <option value="SR">SONORA</option> <option value="TC">TABASCO</option> <option value="TS">TAMAULIPAS</option> <option value="TL">TLAXCALA</option> <option value="VZ">VERACRUZ</option> <option value="YN">YUCATAN</option> <option value="ZS">ZACATECAS</option> <option value="NE">NACIDO EN EL EXTRANJERO</option></select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Puesto</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select onkeyup="verificarCargo(event,this)" onblur="verificarCargo(event,this)" name="puesto" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="4">defensor</option>
<!-- <option value="2">coordinador</option> -->
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Género<span class="required">*</span></label> </h4>
<div class="col-md-8 col-sm-8 col-xs-12">
<select required id="genero" onkeyup="validarCurps()" onblur="validarCurps()" name="genero" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="masculino">masculino</option>
<option value="femenino">femenino</option>
</select>
</div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Rfc<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="rfc" data-error="El rfc es invalido" onkeyup="mayusculas(event, this)" onblur="validarRfc()" maxlength="18" pattern=""class="form-control text-uppercase" required placeholder="Rfc" name="rfc">
<div class="help-block with-errors"></div> </div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Curp<span class="required">*</span></label></h4>
<div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="curp" data-error=": el formato debe ser alfanumerico con 18 digitos" onkeyup="mayusculas(event, this)" onblur="validarCurps()" maxlength="18" class="form-control text-uppercase" required placeholder="curp" name="curp">
<div class="help-block with-errors"></div>
</div>
</div>
<!-- CAPTURA DE ETNIA -->
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Etnia<span class="required">*</span></label></h4>
<div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="etnia" data-error=" el campo debe ser colo letras" onkeyup="mayusculas(event, this)" onblur="validarCurps()" maxlength="80" pattern="[A-Za-z0-9 éíóúūñÁÉÍÓÚÜÑ]+" class="form-control text-uppercase" novalidate placeholder="Etnia" name="etnia">
<div class="help-block with-errors"></div>
</div>
</div>
<!-- CAPTURA DE LENGUA E IDIOMA -->
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Idioma<span class="required">*</span></label></h4>
<div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="idioma" data-error="El campo debe ser solo letras" onkeyup="mayusculas(event, this)" onblur="validarCurps()" maxlength="80" pattern="[A-Za-z0-9 éíóúūñÁÉÍÓÚÜÑ]+" class="form-control text-uppercase" required placeholder="Idioma" name="idioma">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Adscripción</label> </h4>
<div class="col-md-8 col-sm-9 col-xs-12">
<select name="adscripcion" class="select2_group form-control">
<option value="">- Seleccione -</option>
<?php
$juzgadosRegion=json_decode($contenidojuzgado);
foreach($juzgadosRegion as $obj=>$valores){
// echo $obj."fsdfwegfwefwefwef";
echo ' <optgroup label="'.$obj.'">';
foreach($valores as $valor){
echo '<option value='.$valor->id_juzgado.'>'.$valor->nombre.'</option> ';
}
echo '</optgroup>';
}
?>
</select>
</div>
</div>
<div id="materia" class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<label class="control-label col-md-4 col-sm-3 col-xs-12" for="last-name">Materia <span class="required">*</span>
</label>
<div class="col-md-8 col-sm-6 col-xs-12">
<select required name="materia"onkeyup="verificarMateria(event,this)" onblur="verificarMateria(event,this)" class="select2_group form-control ">
<option value="">- Seleccione -</option>
<option value="Civil">Civil</option>
<option value="Familiar">Familiar</option>
<option value="Penal">Penal</option>
<option value="Agrario">Agrario</option>
<option value="Mercantil">Mercantil</option>
<option value="Amparo">Amparo</option>
<option value="Ejecucion">Ejecución de sanciones</option>
<option value="Adolescente">Adolescentes</option>
<option value="Mixto">Mixto</option>
</select>
</div>
</div>
<div id="instancia" class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<label class="control-label col-md-4 col-sm-3 col-xs-12" for="last-name">Instancia <span class="required">*</span>
</label>
<div class="col-md-8 col-sm-6 col-xs-12">
<select name="instancia" required class="select2_group form-control ">
<option value="1">1 Instancia</option>
<option value="2">2 Instancia</option>
</select>
</div>
</div>
<div id="sistema" class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<label class="control-label col-md-4 col-sm-3 col-xs-12" for="last-name">Sistema <span class="required">*</span>
</label>
<div class="col-md-8 col-sm-6 col-xs-12">
<select name="sistema" required class="select2_group form-control ">
<option value=""> --Seleccione--</option>
<option value="ORAL"> Acusatoria y Oral</option>
<option value="TRADICIONAL"> Tradicional</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Contraseña<span class="required">*</span></label></h4>
<div class="col-md-8 col-sm-9 col-xs-12">
<input type="password" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" data-error="debe contener al menos una mayúscula y número con minimo 8 carácter" min="8" max="20" class="form-control" required placeholder="contraseña" name="password">
<div class="help-block with-errors"></div>
</div>
</div>
<div id="gender" required class="btn-group" data-toggle="buttons">
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<button class="btn btn-primary btn btn-info btn-lg" type="reset">Limpiar</button>
<input type ="submit" class="btn btn-succes btn btn-success btn-lg" value="Guardar"/>
</div>
</div>
</form>
</div>
</div>
<!-- jQuery -->
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script>
-->
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/curp.js"></script>
<!-- Google Analytics -->
<script>
$('#myform').validator()
var curp2 = generaCurp({
nombre : 'Griselda',
apellido_paterno : 'Mendez',
apellido_materno : 'Cortes',
sexo : 'M',
estado : 'OC',
fecha_nacimiento : [17, 03, 1993]
});
console.log(curp2);
</script>
<file_sep>var conultas=document.getElementById('consultas');
conultas.addEventListener('click', realizandoConsulta, false);
function realizandoConsulta() {
$('#menuContainer').load("consultaPreguntas.php");
};
var datosGeneralesConsultas;
var listaNegra=['FECHA DE AUTO APERTURA A JUICIO','FECHA DE CONCLUIDO EL PERIODO DE DESAHOGO DE PRUEBAS',
'FECHA DE CONCLUSIÓN','FECHA DE CONCLUSIÓN DE DEFENSA','FECHA DE CONCLUSIÓN M.P',
'FECHA DE CUMPLIMIENTO DE LA EJECUTORIA','FECHA DE DESAHOGO',
'FECHA DE LA NOTIFICACIÓN DEL AUTO DE INICIO AL ACTOR','FECHA DE LA NOTIFICACIÓN DEL AUTO DE INICIO AL DEMANDADO',
'FECHA DE LA RESOLUCIÓN DE LA SENTENCIA O LECTURA DE FALLO','FECHA DE LA SENTENCIA',
'FECHA DE NOTIFICACION DE AUTO INICIO','FECHA DE NOTIFICACION DE LA PARTE OFENDIDA',
'FECHA DE NOTIFICACIÓN DE LA RESOLUCIÓN','FECHA DE NOTIFICACION DEL BENIFICIO',
'FECHA DE NOTIFICACION POR PARTE DE JUZGADO AL DEFENSOR','FECHA DE OFRECIMIENTO',
'FECHA DE PERIODO PROBATORIO','FECHA DE RESOLUCIÓN DEL TÉRMINO CONSTITUCIONAL',
'FECHA DE SENTENCIA 1° INSTANCIA','FECHA DE SENTENCIA 2° INSTANCIA',
'FECHA EN QUE COMPURGARA SU PENA EL SENTENCIADO','FECHA EN QUE FUE TURNADO AL JUEZ DE EJECUCION DE SANCIONES',
'FECHA EN QUE LIGITIMADA LA PARTE QUE INTERPUSO EL RECURSO','FECHA EN QUE SE DICTA LA RESOLUCION QUE SE RECURRE',
'FECHA EN QUE SE NOTIFICA LA RESOLUCION','FECHA INICIO','FECHA QUE SE LEVANTANTO LA SUSPENCIÓN DE LA EJECUCION DE LA PENA',
'JUZGADO DE ORIGEN','JUZGADO SENTENCIANTE','LUGAR DE RECLUSION','NÚMERO DE EXPEDIENTE',
'NUMERO DE LA ULTIMA REMISION PARCIAL DE PENA OTORGADA','PENA DE PRESION AL CUAL FUE SENTENCIADO',
'PLAZO PARA CIERRE DE INVESTIGACIÓN','SALA EN DONDE SE ENCUENTRA RADICADO','TIEMPO COMPURGADO A LA FECHA'
];
function seleccionarUnDefensorExpediente(val){//checkdefensor especifico
var desc = $('#botonDesc').get(0);
var rGeneralC = $('#radioCompleto').get(0).checked;
var rGeneralP = $('#radioPeriodo').get(0).checked;
var inicio = $('#inputInicio')[0].value;
var final = $('#inputFinal')[0].value;
var inputProject = $('#project').val();
if(val){
$('#checkSistema').hide(); //entonces muestra su input
$('#checkMateria').hide(); //entonces muestra su input
$('#checkRegion').hide(); //entonces muestra su input
$('#idCheckDefensor').removeAttr('style'); //entonces muestra su input
dataDefensor();
}else{
$('#checkSistema').show(); //entonces muestra su input
$('#checkMateria').show(); //entonces muestra su input
$('#checkRegion').show(); //entonces muestra su input
$("#idCheckDefensor").attr('style','display:none');
}
if(rGeneralC){
$("#divPeriodo").attr('style', 'display:none;');
if(val){//esta activada el check defensor esp?
if(inputProject != ''){
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}else{
desc.disabled= false;
return true;
}
}
if(rGeneralP){//esta activado por periodo
$("#divPeriodo").removeAttr('style');
if(val){//esta activada el check defensor esp?
if(myFunctionDate('') != false && inputProject != ''){
desc.disabled= false;
return true;
}
desc.disabled= true;
console.log('se congelo bpoton porque no hay');
return false;
}else{//check defensor esta desact
if (myFunctionDate('') != false){
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
desc.disabled= true;
return false;
}
}
function estadoInputExpediente(val){
var desc = $('#botonDesc').get(0);
var botonConsulta = $('#botonConsultarExpediente').get(0);
//var selectSistema = $('#selectSistema').val();
var check = $('#checkId').get(0).checked;
var rGeneralC = $('#radioCompleto').get(0).checked;
var rGeneralP = $('#radioPeriodo').get(0).checked;
/* var rParcialC = $('#inputRadio4').get(0).checked;
var rParcialP = $('#inputRadio3').get(0).checked; */
var inicio = $('#inputInicio')[0].value;
var final = $('#inputFinal')[0].value;
console.log('fuera del if dentro estadoIo=nput');
if(rGeneralC){//radio general completo
if(check){//check defensor unico
if(val != '' ){
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
desc.disabled= false;
return true;
}
if(rGeneralP){// radio general x periodo de tiempo
if(check){//check defensor unico
if(val != '' ){//input no vacio?
if(myFunctionDate('') != false) {
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
desc.disabled= true;
return false;
}else{
if(myFunctionDate('') != false) {
desc.disabled= false;
}
desc.disabled= true;
return false;
}
}
desc.disabled= true;
return false;
}
function estadoInputParcial(val){
var desc = $('#botonDesc').get(0);
var selectSistema = $('#selectSistema').val();
var check = $('#checkId').get(0).checked;
var rParcialC = $('#radioPeriodo').get(0).checked;
var rParcialP = $('#radioCompleto').get(0).checked;
var inicio = $('#inputInicio')[0].value;
var final = $('#inputFinal')[0].value;
console.log('fuera del if dentro estadoIo=nput');
if(rParcialC){//radio parcial completo
if(check){//check defensor unico
if(val != '' && selectSistema != '' ){
desc.disabled= false;
return true;
}
}else{
if(selectSistema != '' ){
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
}
if(rParcialP){// radio general x periodo de tiempo
if(check){//check defensor unico
if(val != '' ){//input no vacio?
if(myFunctionDate('') != false && selectSistema != '') {
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
desc.disabled= true;
return false;
}else{
if(myFunctionDate('') != false && selectSistema!='') {
desc.disabled= false;
return true;
}
desc.disabled= true;
return false;
}
desc.disabled= true;
return false;
}
}
function consultaExpediente(){
console.log("consutlados informacion");
var defensor=document.getElementById('usuarios').value;
var materia=document.getElementById('materia').value;
var sistema=document.getElementById('sistema').value;
var region=document.getElementById('region').value;
var fechaInicio=document.getElementById('inputInicio').value;
var fechaFinal=document.getElementById('inputFinal').value;
var consultaPor='defensor&defensor='+defensor;
var enviar=false;
console.log("viendo que regresa defesnro ",verificacionDefensorPeriodo());
if(verificacionDefensorPeriodo()===true){
defensor=document.getElementById('usuarios').value;
enviar=true;
}
if(verificacionMateriaSistema()){
console.log("se seleccion materia o sistema");
enviar=true;
console.log("que sera matria ",materia);
console.log("que sera sistema ",sistema);
if(sistema!==""&sistema!=="NINGUNO"&(materia===""|materia==="NINGUNO"))// SOLO POR SISTEMA
consultaPor='sistema&sistema='+sistema;
if(materia!==""&materia!=="NINGUNO"&(sistema===""|sistema==="NINGUNO"))//SOLO POR MATERIA
consultaPor='materia&materia='+materia;
// if(sistema!==""|sistema!=="NINGUNO")//POR SISTEMA MATERIA
if(sistema!=="NINGUNO"&materia!='NINGUNO')//POR SISTEMA MATERIA
consultaPor='sistemaMateria&materia='+materia+'&sistema='+sistema;
if(region!==""®ion!=="NINGUNO")// POR REGION
consultaPor='regionSistemaMateria®ion='+region+'&materia='+materia+'&sistema='+sistema;
}
if(enviar)
$.ajax({
url: "../../controlador/estadistica/consumoConsultas.php",
type: "GET",
// data: "consultaPor=defensor&defensor=" +defensor + "&fechaInicio=" + fechaInicio+ "&fechaFinal=" + fechaFinal,
data: "consultaPor="+consultaPor + "&fechaInicio=" + fechaInicio+ "&fechaFinal=" + fechaFinal,
success: function (data) {
console.log("recibo de datos ",data);
if (data != 0) {
datosGeneralesConsultas=data//GUARDANDO DATOS PARA FUTURO UTILIZACION
$('#tbodyConsultas').empty();
// console.log("valor del key ",data);
$.each(data, function (KEY, VALOR) {
console.log("en array ",VALOR);
// console.log("sacando el tama;;o ",VALOR.length);
var masculino;
var femenino;
var opcion="";
if(VALOR.length!==0){
// console.log("entrando a despues de leng",VALOR);
//console.log("entrando Y SACANDO a despues de leng",VALOR.length);
/* var masculino=VALOR.datosGenerales.sexo.MASCULINO;
var femenino=VALOR.datosGenerales.sexo.FEMENINO
var opcion=""
*/;
masculino=VALOR.datosGenerales.sexo.MASCULINO;
femenino=VALOR.datosGenerales.sexo.FEMENINO
//var opcion="";
// console.log("datos de los femni ".femenino);
}
if(masculino===undefined)
masculino=0;
if(femenino===undefined)
femenino=0;
if(VALOR.opciones!==undefined)
opcion='<option value="opciones">opción </option>';
var filtroAListaNegra=listaNegra.find(function(x){ return (x==KEY)});
if(filtroAListaNegra===undefined)// VERIFICO SI LA PREGUNTA NO ESTA EN LA LISTA NEGRA
$('#tbodyConsultas').append(
'<tr> ' +
'<td id="key">' + KEY + '</td>' +
'<td >'+(masculino+femenino)+'</td>' +
'<td>' + masculino+ '</td>' +
'<td>' +femenino + '</td>' +
'<td><select id="filtro1" style="width:150px;" class="form-control" name="users" onchange="filtroGenerales(this)">'+
'<option value="etnias" >Etnias</option>'+
'<option value="generos">Generos</option>'+
'<option value="discapacidad">Discapacidades</option>'+
'<option value="idiomas">Idiomas </option>'+
opcion+
'</select></td>'+
' </tr>'
);
});
} else {
$('#tbodyConsultas').empty();
botonDess.disabled = true;
}
}
});
// }
}
var opcionesSeleccionadoMomento;
function filtroOpcionesPregunta(elemento){
var valorKey = $(elemento).closest('tr').find('#key').text();
console.log("opcion seleccionado ",valorKey);
var keySeleccionado=opcionesSeleccionadoMomento[valorKey];
console.log("opciones ",keySeleccionado);
$('#tbodyConsultasOpciones').empty();
$('#tablaAnidaEnSegundaTabla').show();
var objetoEncontrado=keySeleccionado[elemento.value];
if(elemento.value==="opciones")
objetoEncontrado=keySeleccionado.opciones;
console.log("objetos encontrados ",objetoEncontrado);
console.log("ELEMENTO ",elemento.value);
if(elemento.value!=="generos")
$.each(objetoEncontrado, function (KEY, VALOR) {
// console.log(VALOR, ' valor ');
var masculino=parseInt(VALOR.MASCULINO);
var femenino=parseInt(VALOR.FEMENINO);
console.log("datos de los femni ".femenino);
// esta parte de aqui es si la pregunta tiene opciones
if(elemento.value==='opciones'){console.log("esta en opbcioens");
masculino=VALOR.sexo.MASCULINO;
femenino=VALOR.sexo.FEMENINO; }
//
if(masculino===undefined|isNaN(masculino))
masculino=0;
if(femenino===undefined|isNaN(femenino))
femenino=0;
$('.sexo').show();
$('#tbodyConsultasOpciones').append(
'<tr> ' +
'<td >' + KEY + '</td>' +
'<td >'+VALOR+'</td>' +
' </tr>'
);
});
else {
console.log("ES GENEROS");
$.each(objetoEncontrado, function (KEY, VALOR) {
// console.log(VALOR, ' valor ');
$('.sexo').hide();
$('#tbodyConsultasEspecificas').append(
'<tr> ' +
'<td >' + KEY + '</td>' +
'<td >'+VALOR+'</td>' +
' </tr>'
);
});
}
}
function filtroGenerales(elemento){
var valorKey = $(elemento).closest('tr').find('#key').text();
var keySeleccionado=datosGeneralesConsultas[valorKey];
var opciones=' ';
$('#tbodyConsultasEspecificas').empty();
var objetoEncontrado=keySeleccionado.datosGenerales[elemento.value];
$('#cabezeraOpcionesTabla2').hide();
// $('#tablaAnidaEnSegundaTabla').hide();
if(elemento.value==="opciones"){//CUANDO LA PREGUNTA TIENE OPCIONES
console.log("se selecciono opciones");
objetoEncontrado=keySeleccionado.opciones;
opcionesSeleccionadoMomento=objetoEncontrado;
$('#cabezeraOpcionesTabla2').show();
opciones='<td><select id="filtroOpciones" style="width:150px;" class="form-control" name="users" onchange="filtroOpcionesPregunta(this)">'+
'<option value="etnias" >Etnias</option>'+
'<option value="discapacidades">Discapacidades</option>'+
'<option value="idioma">Idiomas </option>'+
'</select></td>';
}
console.log("objetos encontrados ",objetoEncontrado);
console.log("ELEMENTO ",elemento.value);
if(elemento.value!=="generos")
$.each(objetoEncontrado, function (KEY, VALOR) {
// console.log(VALOR, ' valor ');
var masculino=parseInt(VALOR.MASCULINO);
var femenino=parseInt(VALOR.FEMENINO);
console.log("datos de los femni ".femenino);
// esta parte de aqui es si la pregunta tiene opciones
if(elemento.value==='opciones'){console.log("esta en opbcioens");
masculino=VALOR.sexo.MASCULINO;
femenino=VALOR.sexo.FEMENINO; }
//
if(masculino===undefined|isNaN(masculino))
masculino=0;
if(femenino===undefined|isNaN(femenino))
femenino=0;
$('.sexo').show();
$('#tbodyConsultasEspecificas').append(
'<tr> ' +
'<td id="key" >' + KEY + '</td>' +
'<td >'+(masculino+femenino)+'</td>' +
'<td>' + masculino+ '</td>' +
'<td>' +femenino + '</td>' +
opciones+
' </tr>'
);
});
else {
console.log("ES GENEROS");
$.each(objetoEncontrado, function (KEY, VALOR) {
// console.log(VALOR, ' valor ');
$('.sexo').hide();
$('#tbodyConsultasEspecificas').append(
'<tr> ' +
'<td >' + KEY + '</td>' +
'<td >'+VALOR+'</td>' +
' </tr>'
);
});
}
}
function verificacionMateriaSistema(){
var desc = $('#botonDesc').get(0);
var defensorSeleccionado = $('#usuarios').val();
var botonConsulta = $('#botonConsultarExpediente').get(0);
//var selectSistema = $('#selectSistema').val();
var check = $('#checkId').get(0).checked;//PARA VERIFICAR SI ESTA SELECCIONADO EL DEFENSOR
var consultaCompleta = $('#radioCompleto').get(0).checked;
var consultaPeriodo = $('#radioPeriodo').get(0).checked;
/* var rParcialC = $('#inputRadio4').get(0).checked;
var rParcialP = $('#inputRadio3').get(0).checked; */
var inicio = $('#inputInicio')[0].value;
var final = $('#inputFinal')[0].value;
var materia = $('#materia')[0].value;
var sistema = $('#sistema')[0].value;
var region = $('#region')[0].value;
if(check){//QUE NO ESTE SELECCIONADO DEFESENSOR
return false;
}
if((materia===''|materia==='NINGUNO')&(sistema===''|sistema==='NINGUNO')&(region===''|region==='NINGUNO')){
alert('Selecciona una materia, sistema o región');
return false;
}
// if((region!==''|region!=='NINGUNO')&((sistema===''|sistema==='NINGUNO')|(materia===''|materia==='NINGUNO'))){
if((region!=='NINGUNO')&(sistema==='NINGUNO')&(materia==='NINGUNO')){
alert('Selecciona una materia y un sistema ');
return false;
}
if((region!=='NINGUNO')&(sistema==='NINGUNO')){
alert('Selecciona una sistema');
return false;
}
if((region!=='NINGUNO')&(materia==='NINGUNO')){
alert('Selecciona una materia');
return false;
}
if(consultaCompleta){//radio general completo
if(!check){//QUE NO ESTE SELECCIONADO DEFESENSOR
return true;
}
return false;
}
if(consultaPeriodo){// radio general x periodo de tiempo
if(!check){//QUE NO ESTES SELECCIONADO DEFENSOR
// console.log("viendo el defensor-> ",defensorSeleccionado);
if(myFunctionDate('') != false) {//verificacion de fecha
desc.disabled= false;
return true;
}
desc.disabled= true;
alert("seleccione fecha correcto ");
return false;
}return false;
}
desc.disabled= true;
return false;
}
function verificacionDefensorPeriodo(){
var desc = $('#botonDesc').get(0);
var defensorSeleccionado = $('#usuarios').val();
var botonConsulta = $('#botonConsultarExpediente').get(0);
//var selectSistema = $('#selectSistema').val();
var check = $('#checkId').get(0).checked;//PARA VERIFICAR SI ESTA SELECCIONADO EL DEFENSOR
var consultaCompleta = $('#radioCompleto').get(0).checked;
var consultaPeriodo = $('#radioPeriodo').get(0).checked;
/* var rParcialC = $('#inputRadio4').get(0).checked;
var rParcialP = $('#inputRadio3').get(0).checked; */
var inicio = $('#inputInicio')[0].value;
var final = $('#inputFinal')[0].value;
//console.log('fuera del if dentro estadoIo=nput');
if(!check)
return false;// REGRESA INDICANDO QUE NO ES UN DEFENSOR
if(consultaCompleta){//radio general completo
if(check){//check defensor unico
if(defensorSeleccionado != '' ){
desc.disabled= false;
return true;
}
alert("seleccione un defensor ");
desc.disabled= true;
return false;
}
desc.disabled= false;
alert("seleccione un defensor o fecha ");
return true;
}
if(consultaPeriodo){// radio general x periodo de tiempo
if(check){//check defensor unico
// console.log("viendo el defensor-> ",defensorSeleccionado);
if(defensorSeleccionado != '' ){//input no vacio?
if(myFunctionDate('') != false) {//verificacion de fecha
desc.disabled= false;
return true;
}
desc.disabled= true;
console.log("dentro de defensor");
alert("seleccione fecha correcto ");
return false;
}
desc.disabled= true;
alert("seleccione un defensor o fecha ");
return false;
}else{
if(myFunctionDate('') != false) {
console.log("dentro de defensor");
alert("seleccione fecha correcto ");
desc.disabled= false;
}
desc.disabled= true;
return false;
}
}
desc.disabled= true;
return false;
}<file_sep><?php
include_once('../../modelo/usuarioServicio.php');
include '../../libreria/herramientas.php';
$respuesta = Array(
"id_usuario_servicio" =>$_POST['id_usuario_servicio'],
"nombre" =>$_POST['nombre'],
"apellido_paterno" =>$_POST['apellido_paterno'],
"apellido_materno" =>$_POST['apellido_materno'],
"etnia" =>$_POST['etnia'],
"idioma" =>$_POST['idioma'],
"telefono" =>$_POST['telefono'],
"genero" =>$_POST['genero'],
"discapacidad" =>$_POST['discapacidad'],
"calle" =>$_POST['calle'],
"etnia" =>$_POST['etnia'],
"municipio" =>$_POST['municipio'],
"colonia" =>$_POST['colonia'],
"email" =>$_POST['email'],
"numero" =>$_POST['numero']
);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);/// convierte todo a mayusculas
{actualizar_usuario_servicio($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Actualizacion exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
/* else
echo "el registro ya existe";
*/
?><file_sep><?php
include '../../modelo/actividad.php';
if(isset($_GET['observacion'])){
if(isset($_GET['idAct'])){
$id=$_GET['idAct'];
$obs = $_GET['observacion'];
$resul = updateObservacion($obs, $id);
$encode = json_encode($resul);
echo $encode;
}
}
?><file_sep><?php
function conectarse()
{
$servidor = "localhost";
$usuario = "u858616915_root";
$password = "<PASSWORD>";
$bd = "u858616915_defen";
$conectar = new mysqli($servidor, $usuario, $password, $bd);
return $conectar;
}
function consulta($sql, $conexion){
// $resultado = mysqli_query($conexion, $sql)or die(mysqli_error($conexion));
$resultado = $conexion->query($sql);
return $resultado;
}
$conexion = conectarse();
<file_sep><?php
include_once('../../modelo/usuarioServicio.php');
include_once('../../modelo/expediente.php');
if(isset($_GET['id_usuario_servicio'])){
$listaUser = listar_usuarios_id($_GET['id_usuario_servicio']);
$contenido = json_encode($listaUser);
echo $contenido;
}
if(isset($_GET['id_expediente'])){///muestro los usuario que tiene cada expedientes
$listaUser = listar_UsuarioServicioByExpediente($_GET['id_expediente']);
$contenido = json_encode($listaUser);
echo $contenido;
}
if(isset($_GET['term'])){//muestro todo los usuario para las busquedas del defensor
// header('Content-type: application/json');
echo json_encode(listar_usuarios());
//$var= '[ {"nombre":"juan","value":"pedro"},{"nombre":"juanito","value
// ":"pedros"}]';
// $var= '[ { "label": "Choice1", "value": "value1" },{ "label": "Choice2", "value": "value2" } ]';
// $var= '[ "juan","pedro","juanito","lopez"]';
//echo $var;
// print_r();
}
?><file_sep>SELECT * FROM bddefensoria.personal;
-- insert
-- insert admin
insert into personal values(1, 1, 1, '<NAME>', 'Herrera', 'Perez', 'CURP1234ABCD3214567', 'conocida', '123', '21', 'centro', 'oaxaca de juarez', '123','321', 'Masculino', '9511234567', '<EMAIL>', 'C:\xampp\htdocs\defensoriaPublica\foto.jpg');
-- insert coordinador
insert into personal values(2, 2, 2, 'Cesar', 'Aspra', 'Lopez', 'CURP1234ABCD3214567', 'conocida', '123', '21', 'centro', 'oaxaca de juarez', '123','321', 'Masculino', '9511234567', '<EMAIL>', 'C:\xampp\htdocs\defensoriaPublica\foto.jpg');
-- insert coordinador defensor
insert into personal values(3, 3, 3, 'user', 'ap paterno', 'ap materno', 'CURP1234ABCD3214567', 'conocida', '123', '21', 'centro', 'oaxaca de juarez', '123','321', 'Masculino', '9511234567', '<EMAIL>', 'C:\xampp\htdocs\defensoriaPublica\foto.jpg');
-- insert estadistica
insert into personal values(4, 4, 4, 'Griselda', 'Mendez', 'Cortes', 'CURP1234ABCD3214567', 'conocida', '123', '21', 'centro', 'oaxaca de juarez', '123','321', 'Masculino', '9511234567', 'admin<EMAIL>', 'C:\xampp\htdocs\defensoriaPublica\foto.jpg');
-- insert defensor
insert into personal values(5, 5, 5, 'NombreDefensor', 'ap paterno', 'ap materno', 'CURP1234ABCD3214567', 'conocida', '123', '21', 'centro', 'oaxaca de juarez', '123','321', 'Masculino', '9511234567', '<EMAIL>', 'C:\xampp\htdocs\defensoriaPublica\foto.jpg');
-- update
-- delete
delete from personal where id_personal =1;<file_sep>
$(document).ready(function () {
function checkNotificacion(){
$.ajax({
url: "../../controlador/expediente/checarNotificaciones.php",
type: "get",
success: function (data) {
//console.log(data, ' valor data');
if (data != 0) {
//alert(' Tienes '+data+' expedientes por asignar defensor!!');
$.notify(' <a id="linkListar"> Tienes</a>'+data+' Expedientes por asignar defensor!!');
var link=document.getElementById("linkListar");
link.addEventListener("click",function(){
$("#menuContainer").load("listarExpedientes.php");
},false);
} else {
}
}
});
}
setInterval(checkNotificacion, 10000);
var expedientesSinAtencion;
function getExpedienteSinAtender(){
$.ajax({
url: "../../controlador/coordinador/notificacionExpedienteSinAtencion.php",
type: "get",
success: function (data) {
//console.log(data, ' valor data');
if (data != 0) {
//alert(' Tienes '+data+' expedientes por asignar defensor!!');
//console.log('notiicacion exp ',data);
expedientesSinAtencion=data;
document.getElementById('cantidadExpediente').outerText=data.length;
// data.forEach(element =>
for (let index = 0; index < 3; index++) {
var element=data[index];
if(element!==undefined){
$('#menu1').append("<li> <a>"+
"<span >"+element.num_expediente+"</span>"+
//"<span class='time'>3 mins ago</span>"+
"</span>"+
"<span class='message'>"+
element.nombre+" "+element.ap_paterno+" "+element.ap_materno+
"</span>"+
" </a>"+
"</li>")
}
};//);
$('#menu1').append("<li> <div class='text-center'> <a>"+
"<strong id='notificacionExpSinAtencion'>Ver todas las notificaciones</strong>"+
//"<span class='time'>3 mins ago</span>"+
"<i class='fa fa-angle-right'></i>"+
" </a>"+
"</div></li>");
/* $.notify(' <a id="linkListar"> Existen '+data.length+' Expedientes sin continuidad por 2 meses !!</a>');
var link=document.getElementById("linkListar");
link.addEventListener("click",function(){
$("#menuContainer").load("listarExpedientes.php");
},false); */
var noti=document.getElementById('notificacionExpSinAtencion');
noti.addEventListener('click',function todasNotificacionExpediente() {
console.log("en notificacion de todas");
$("#exampleModalLong").modal('show');
$('#notificacionsSinAtencion').append("<address id='address'><address>");
expedientesSinAtencion.forEach(element => {
var telefono=element.telefono.replace(/[()]/g,'');
$('#address').append("<p>"+element.num_expediente+", "+element.nombre+" "+element.ap_paterno+" "+element.ap_materno+", "+ telefono+"</p><hr>");
});
},false);
}
}
});
}
getExpedienteSinAtender();
function notificacionExpedienteSinAtender() {
$.notify(' <a id="linkListar"> Existen '+expedientesSinAtencion.length+' Expedientes sin continuidad por 2 meses !!</a>');
var link=document.getElementById("linkListar");
link.addEventListener("click",function(){
$("#menuContainer").load("listarExpedientes.php");
},false);
}
//setInterval(notificacionExpedienteSinAtender, 10000);
// SE QUITO UN RATO LA NOTIFICACION
});<file_sep><?php
include '../../modelo/actividad.php';
if(isset($_GET['q'])){
$q = $_GET['q'];
switch ($q){
case 1: //asesoria
$lista = getActividadesAsesorias();
$encode = json_encode($lista);
echo $encode;
break;
case 2: //audiencia
$lista = getActividadesAudiencias();
$encode = json_encode($lista);
echo $encode;
break;
case 3: //visita carcelaria
$lista = getActividadesVisitas();
$encode = json_encode($lista);
echo $encode;
break;
case 4: //todos
$lista = getActividades();
$encode = json_encode($lista);
echo $encode;
break;
}
}
?><file_sep><?php
include_once('../../modelo/expediente.php');
header('Content-Type: application/json');
$notificaciones = notificacionExpedienteSinAtencion();
//print_r($notificaciones);
echo json_encode($notificaciones);
?><file_sep><?php
switch ((isset($_GET['realizar']) ? $_GET['realizar'] : '') )
{
case 'reporte_asesoria':
require_once("controlador/defensor/reporte_asesoria.php");
break;
case 'reporte_visitas':
require_once("controlador/defensor/reporte_visitas.php");
break;
case 'reporte_audiencia':
require_once("controlador/defensor/reporte_audiencia.php");
break;
case 'reporte_bitacora':
require_once("controlador/defensor/reporte_bitacora.php");
break;
default:
// require_once("layout_admin.php");
break;
}
?>
<file_sep><?php
include '../../modelo/defensor/defensor.php';
$id_defensor = $_GET['id_personal'];
$eliminarDefensor = eliminar_defensor($id_defensor);
echo json_encode($eliminarDefensor);
?><file_sep><?php
$usuario= $_POST["usuario_txt"];
include './conexion.php';
include './encriptador.php';
$sql = "select * from usuario where username = '$usuario';
$ejecutar_consulta = $conexion->query($sql);
$num_regs = $ejecutar_consulta->num_rows;
if($num_regs==0){
echo mensajeError("no tenemos registros de ".$usuario);
}else{
$registro = $ejecutar_consulta->fetch_assoc();
$password = utf8_encode(desencriptar($registro["password"]));
$usuario = utf8_encode($registro["username"]);
$nombre = utf8_encode($registro["username"]);
$mensaje = "Hola ".$nombre." te adjuntamos tus datos..\nCorreo: "
"\nUsuario: ".$usuario."\nContraseña: ".$password;
$send= mail($correo, "Recuperar contraseña GESO", $mensaje);
if($send){
echo mensajeSuccess("Se te envio tu contraseña a ".$correo);
}else{
echo mensajeError("error al enviar correo intente mas tarde");
}
}
function mensajeError($msj){
return '<p class="text-danger"><strong>'.$msj.'</strong></p>';
}
function mensajeSuccess($msj){
return '<p class="text-success"><strong>'.$msj.'</strong></p>';
}
<file_sep><?php
include '../../controlador/defensor/controlDefensor.php';
$defensor=json_decode($defensorZ);
foreach($defensor as $obj){
$nombreDef = $obj->nombre;
$ap_p = $obj->ap_paterno;
$ap_m = $obj->ap_materno;
$correo = $obj->corre_electronico;
$tel = $obj->telefono;
$nup = $obj->nup;
$nue = $obj->nue;
$curp = $obj->curp;
$cedula = $obj->cedula_profesional;
$juzgado = $obj->juzgado;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>ACTUALIZAR DEFENSOR</title>
<script src="../../recursos/js/main.js"></script>
</head>
<body>
<script>
function agrega(){
$('#menuContainer').load("coordinadorRegistrarJuzgado.html");
}
</script>
<div class="row">
<div class="col-md-6 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Actualizar datos de defensor</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="agregarjuzado" onclick="agrega()">Editar Juzgado</a>
</li>
<li><a href="#">Settings 2</a>
</li>
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br /><!-- action="agregarDefensor" -->
<!-- class="form-horizontal form-label-left input_mask" th:action="@{/defensor/agregarDefensor}" th:object="${defensor}" -->
<form action ="../../controlador/defensor/ctrlUpdate.php" method="post">
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="inputNombre" placeholder="Nombre" name="nombre"
value="<?php
echo $nombreDef;
?>">NOMBRE
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccess3" placeholder="apellido Paterno" name="apellido_paterno"
value="<?php
echo $ap_p;
?>">APELLIDO PATERNO
<span class="fa fa-user form-control-feedback right" aria-hidden="true"></span>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccessmaterno" placeholder="apellido materno" name="apellido_materno"
value="<?php
echo $ap_m;
?>">APELLIDO MATERNO
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control has-feedback-left" id="inputSuccess4" placeholder="Email" name="email"
value="<?php
echo $correo;
?>">CORREO ELECTRONICO
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccess5" placeholder="Telefono" name="telefono"
value="<?php
echo $tel;
?>">NUMERO TELEFONICO
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccess5" placeholder="nup" name="nup"
value="<?php
echo $nup;
?>">NUMERO NUP
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccess5" placeholder="nue" name="nue"
value="<?php
echo $nue;
?>">NUMERO NUE
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="text" class="form-control" id="inputSuccess5" placeholder="curp" name="curp"
value="<?php
echo $curp;
?>">CURP
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">No Cedula<span class="required">*</span></label>
<div class="col-md-9 col-sm-9 col-xs-12">
<input type="text" class="form-control" placeholder="numero cedula" name="num_cedula"
value="<?php
echo $cedula;
?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Juzgado <span class="required">*</span>
</label>
<div class="col-md-9 col-sm-9 col-xs-12">
<input class="date-picker form-control col-md-7 col-xs-12" required="required" placeholder="juzgado" name="juzgado" type="text"
value="<?php
echo $juzgado;
?>">
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<!-- <input type="submit"name="cancelar" class="btn btn-primary" value="Cancelar"></button>
--> <input class="btn btn-primary" type="submit" name="update"
value="Actualizar Datos"></input>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</body>
</html>
<file_sep><?php
session_start();
$idpersonal=$_SESSION['personal'];
//print_r($idpersonal[0]['id_personal']);
//include '../../controlador/defensor/controladorListarExp.php?idPersonal='.$idpersonal[0]['id_personal'];
//print_r($idpersonal);
//print_r($misExpedietnesDefensor);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Modulo Coordinador General</title>
<script src="../../recursos/js/main.js"></script>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<!-- <script type="text/javascript" src="../../recursos/vendors/jquery/jquery-ui.js"></script>
--><link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Font Awesome -->
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link href="../../recursos/css/custom.css" rel="stylesheet"/>
<script src="../../recursos/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../../recursos/js/main.js"></script><!--
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->
<!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
<script src="../../recursos/js/defensor/atendiendoDefensor.js"></script>
<link href="../../recursos/css/style.css" rel="stylesheet"/>
<script>
$(document).ready(function () {
cargarMisExpedientes(<?php echo $idpersonal[0]['id_personal']?>);
});
</script>
<body onload="">
<div class="x_content">
<h3 ><b>
<center>
LISTA EXPEDIENTES
</center>
</b>
</h3>
<div class="form-group">
<div class="left" style="width:45%;">
<input type="text" id="columna1" onkeyup="buscarXPrimerCampo()" class="form-control" placeholder="Nombre Defensor...">
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>LISTA DE EXPEDIENTES</h2>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<table id="example" class="table ui table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
<thead>
<tr >
<th > Num. Expediente </th>
<th > Delito </th>
<th > Tipo del delito </th>
<th > Observaciones </th>
<th > Accion </th>
</thead>
<tbody id='tebody' >
</tbody>
</table>
</div></div>
</div>
</div>
</div>
</div>
<!-- Button trigger modal -->
<div class="modal fade" id="mostrarusuarioServicio" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Usuario(s)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miUsuarioServicio" class="table-responsive x_content" title="infomación">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
--> <table id="exampleuser" class="table dt-responsive ui table" cellspacing="0" width="100%">
<thead>
<tr >
<th > Nombre </th>
<th > Apellido paterno </th>
<th > Apellido Materno </th>
<th > Teléfono </th>
<th > Acción </th>
</tr>
</thead>
<tbody id="datosUsuarioServicio">
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- FIN DE LO OTRO INIICIO PARA EDITAR CONTRAPARTE -->
<div class="modal fade" id="modalEditarUsuarioServicio" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Usuario(s)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miEditarUsuarioUsuario" class="table-responsive x_content" title="infomación detallada">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
-->
</div>
<form id="EditarUsuarioServicio" data-toggle="validator" role="form" class="example_form form-horizontal form-label-left"
enctype="multipart/form-data" object="defensor">
</form>
<div id="EditarContraparte">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- FIN DE LO OTRO INIICIO PARA DAR BAJA EXPEDIENTE -->
<div class="modal fade" id="modalBajaExpediente" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miEditarUsuarioUsuario" class="table-responsive x_content" title="infomación detallada">
</div>
<form id="formBajaExpediente" name="formBajaExpediente" data-toggle="validator" role="form" class="example_form form-horizontal form-label-left"
enctype="multipart/form-data" object="defensor">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-4">Fecha de baja<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="date" class="form-control " required="" id="fecha_baja" placeholder="Id personal" name="fecha_baja">
<span class ="help-block"> <span >
</div>
</div>
<div id="gradoTipoBaja" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Motivo de baja <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select required="" id="id_motivoBaja" name="motivoBaja" class="form-control ">
<option value="">--SELECCIONE UNA OPCIÓN-</option>
<option value="FALTA">Falta de interes</option>
<option value="REVOACION">Revocación del defensor</option>
</select>
</div></div> </div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-4">observación<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<textarea id="observacionBaja" required="" name="observacion" pattern="[A-Za-z0-9.,:áéíóú ]+" data-error="solo numeros o letras con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describa las observaciones de baja"></textarea>
<span class ="help-block"> <span >
</div>
</div>
<input class="" type="hidden" name="id_expedienteBaja" id="id_expedienteBaja" value=""></input>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input class="btn btn-succes btn btn-success btn-lg" type="button" name="botonUpdate" onclick="enviarBajaExpediente()" id="enviarBaja" value="Enviar"></input>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
</body>
</html>
<script src="../../recursos/js/defensor/gestionUsuarioServicio.js"></script>
<script>// $("#miUsuarioServicio").hide();</script>
<script>
// $('#miUsuarioServicio').dataTable();</script>
<file_sep><?php
include '../../controlador/defensor/controladorListarExp.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- Bootstrap -->
<title>Modulo Coordinador General</title>
<script src='../../recursos/vendors/pdfmake/build/pdfmake.min.js'></script>
<script src='../../recursos/vendors/pdfmake/build/vfs_fonts.js'></script>
<script src="../../recursos/js/main.js"></script>
<link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="../../recursos/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link href="../../recursos/css/custom.css" rel="stylesheet"/>
<script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script>
<link href="../../recursos/css/style.css" rel="stylesheet"/>
<script type="text/javascript" src="../../recursos/vendors/jquery/jquery-ui.js"></script>
<link rel="stylesheet" href="../../recursos/vendors/jquery/jquery-ui-themes-1.12.1/jquery-ui.css">
<script>showUser(3)</script>
<body>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><b>Lista de Expedientes </b></h2>
<div align="right">
<label>Busqueda
<input type="text" id="buscarCedula" onkeyup="buscarXCedula()" class="form-control" placeholder="Nombre Defensor..." aria-controls="datatable-responsive">
</label>
</div>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div id="datatable-responsive_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<div class="col-sm-3">
<div class="dataTables_length Filtro" id="datatable-responsive_length">
<label>Filtro 1
<select id="filtro1" style="width:150px;" class="form-control" name="users" onchange="showUser(this.value)" >
<option value="">Por estado</option>
<option value="1">Activos</option>
<option value="2">Inactivos</option>
<option value="3" selected="selected">Todos</option> \
</select></label>
</div>
</div>
<div class="col-sm-3">
<div class="dataTables_length Filtro" id="datatable-responsive_length">
<label>Filtro 2
<select style="width:230px;" id="filtro2" class="form-control" name="users" onchange="showMateria(this.value)" >
<option value="">Materia</option>
<option value="penal">Penal</option>
<option value="civil">Civil</option>
<option value="familiar">Familiar</option>
<option value="agrario">Agrario</option>
<option value="mercantil">Mercantil</option>
<option value="amparo">Amparos</option>
</select></label>
</div>
</div>
<div class="col-sm-4">
<div class="dataTables_length Filtro" id="datatable-responsive_length">
<button id = "botonDesc" class="btn btn-dark" onclick="descargarPDF();" style="margin-left: 50px;">
<i class="fa fa-download"></i> Generar PDF</button>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap dataTable no-footer dtr-inline"
cellspacing="0" width="100%" role="grid" aria-describedby="datatable-responsive_info" style="width: 100%;">
<thead>
<tr role="row">
<th class="sorting_asc" tabindex="0" aria-controls="datatable-responsive" rowspan="1" colspan="1"
style="width: 71px;" aria-label="Defensor: activate to sort column descending" aria-sort="ascending">NUM EXPEDIENTE</th>
<th width="100px" class="sorting" tabindex="0" aria-controls="datatable-responsive"
rowspan="1" colspan="1" style="width: 70px;" aria-label="Usuario: activate to sort column ascending">MATERIA</th>
<th class="sorting" tabindex="0" aria-controls="datatable-responsive" rowspan="1"
colspan="1" style="width: 155px;" aria-label="Fecha registro: activate to sort column ascending">FECHA DE REGISTRO</th>
<!-- <th class="sorting" tabindex="0" aria-controls="datatable-responsive" rowspan="1"
colspan="1" style="width: 155px;" aria-label="Estado: activate to sort column ascending">ESTADO EXP.</th> -->
<th class="sorting" tabindex="0" aria-controls="datatable-responsive" rowspan="1"
colspan="1" style="width: 66px;" aria-label="Observaciones: activate to sort column ascending">OBSERVACIONES</th>
<th class="sorting" tabindex="0" aria-controls="datatable-responsive" rowspan="1"
colspan="1" style="width: 28px;" aria-label="Acciones: activate to sort column ascending">ACCIONES</th>
</tr>
</thead>
<tbody id="tebody" >
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="dialogoCambio" > </div>
<div id="dialogoPreguntas" style="display:none;"> </div>
<div id="dialogoBaja" style="display:none;"> </div>
<div class="modal fade" id="modalVisualizarExpediente" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">información del expediente</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miFinalizar" class="table-responsive x_content" title="infomación">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
-->
</div>
<div class="x_content">
<div class="" role="tabpanel" data-example-id="togglable-tabs">
<ul id="myTab" class="nav nav-tabs bar_tabs" role="tablist">
<!-- <li role="presentation" class="active"><a href="#tab_content1" id="home-tab" role="tab" data-toggle="tab" aria-expanded="false">Seguimiento</a>
</li> -->
<li role="presentation" class="active"><a href="#tab_content2" id="home-tab" role="tab" data-toggle="tab" aria-expanded="false">Tarjeta Informativa</a>
</li>
<!-- <li role="presentation" class=""><a href="#tab_content2" role="tab" id="profile-tab" data-toggle="tab" aria-expanded="false">Resumen</a>
</li> -->
<!-- <li role="presentation" class=""><a href="#tab_content3" role="tab" id="profile-tab2" data-toggle="tab" aria-expanded="false">Profile</a>
--> </li>
</ul>
<div id="myTabContent" class="tab-content">
<!-- <div role="tabpanel" class="tab-pane fade active in" id="tab_content1" aria-labelledby="home-tab">
<p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher
synth. Cosby sweater eu banh mi, qui irure terr.</p>
</div> -->
<!-- <div role="tabpanel" class="tab-pane fade" id="tab_content2" aria-labelledby="profile-tab">
--><div role="tabpanel" class="tab-pane fade active in" id="tab_content2" aria-labelledby="home-tab">
<div style="word-wrap: break-word;">
<address id="id_tarjetaInformativa" >
Número de expediente: <p id="numExpediente"> </p>
Delito:<p id="delito"></p>
Esuario del servicio(s):<p id="usuarioServicio"></p>
Involucrado(s):<p id="involucrado"></p>
Situación actual:<p id="situacionActual"></p>
Acción a implementar:<p id="accionImplementar"></p>
Situación anterior:<p id="situacionAnterior"></p>
Acción a implementar:<p id="accionImplementarAnterior"></p>
</div>
</address>
</div>
</div>
</div>
</div>
<!-- <div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input class="btn btn-succes btn btn-success btn-lg" type="button" name="botonUpdate" onclick="finalizarExpedinte()" id="botonUpdate" value="finalizar"></input>
</div>
</div> -->
<div id="EditarContraparte">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
//require_once("conexion.php");
//include '../controlador/conexion.php';
include_once( '../../libreria/conexion.php');
function listar_juzgado_x_id($id){
$sql = "select * from juzgado where id_juzgado='".$id."'";
$consulta = consulta($sql);
return $consulta;
}
function listar_juzgado(){
$sql = "select id_juzgado,juzgado,region from juzgado ";
$consulta = consulta($sql);
return $consulta;
}
function crear_juzgado($objetoEntidad){
// echo $objetoEntidad[session_name()];
// global $conexion;
$sql = "INSERT INTO juzgado ";
$sql.= "SET juzgado='".$objetoEntidad['juzgado']."', region='".$objetoEntidad['region']."',";
$sql.= "calle='".$objetoEntidad['calle']."', num_juzgado='".$objetoEntidad['numero_juzgado']."',";
$sql.= " municipio='".$objetoEntidad['municipio']."',";
$sql.= "cp='".$objetoEntidad['cp']."', num_telefono='".$objetoEntidad['num_telefono']."',";
$sql.= "colonia='".$objetoEntidad['colonia']."', num_extension='".$objetoEntidad['numero_extension']."'";
//return consulta($sql, $conexion);
registro($sql);
print_r($sql);
}
?>
<file_sep><?php
include_once('../../libreria/conexion.php');
function listar_asesoria_x_id($id){
global $conexion;
$sql = "select * from asesoria where id='".$id."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
//Definimos la funciones sobre el objeto crear_asesoria
function crear_asesoria($asesoria){
$sql = "INSERT INTO asesoria ";
$sql.= "SET id_actividad='".$asesoria['id_actividad']."',";
$sql.= " latitud='".$asesoria['latitud']."', longitud='".$asesoria['longitud']."'";
echo $sql;
$lista=registro($sql);
return $lista;
}
?>
<file_sep><?php
include_once('../../modelo/expediente.php');
include_once('../../modelo/detalleContraparteExpediente.php');
include_once('../../modelo/contraparte.php');
include_once('../../modelo/personal.php');
header('Content-Type: application/json');
// $user = listar_preguntaConOpciones(9);
$id_expediente=$_GET['id_expediente'];
$id_personal=$_GET['id_personal'];
$respuestas = listar_x_idExpedienteAndDefensor($id_personal,$id_expediente);
$expediente = getExpedienteById($id_expediente);
//echo $_GET['id_materia'];
$tarjeta = Array( );
$tarjeta['expediente']=$expediente;
$tarjeta['respuestas']=$respuestas;
$tarjeta['usuarioServicio']=usuarioServicio($id_expediente);
$tarjeta['usuarioContraparte']=contraparte($id_expediente);
$tarjeta['personal']=personal($id_personal);
//print_r(listar_UsuarioServicioByExpediente(9));
echo json_encode($tarjeta);
function personal($id_personal){
$personal = Array( );
foreach (listar_personalById($id_personal) as $key => $value) {
$personal['nombreCompleto']=$value['nombre']." ".$value['ap_paterno']." ".$value['ap_materno'];
}
return $personal;
}
function usuarioServicio($id_expediente){
$personales = Array( );
foreach (listar_UsuarioServicioByExpediente($id_expediente) as $key => $value) {
$personal = Array( );
$personal['nombreCompleto']=$value['nombre']." ".$value['ap_paterno']." ".$value['ap_materno'];
$personal['etnia']=$value['etnia'];
$personal['idioma']=$value['idioma'];
$personal['edad']=$value['edad'];
$personales[$key]=$personal;
}
return $personales;
}
function contraparte($id_expediente){
$personales = Array( );
$contraparte= getContrapartesById($id_expediente);
if($contraparte!=0)
foreach ($contraparte as $key => $value) {
$personal = Array( );
$personal['nombreCompleto']=$value['nombre']." ".$value['apellido_paterno']." ".$value['apellido_materno'];
$personal['etnia']=$value['etnia'];
$personal['idioma']=$value['idioma'];
$personal['edad']=$value['edad'];
$personales[$key]=$personal; }
return $personales;
}
?><file_sep>$(document).ready(function () {
$('#tablaAsinacionExpedienteusuario').on('click', '.eliminar', function (evst) {
// var target= $(event.target);
var target= $(this);
//console.log(target);
var eliminar = $(this).closest('tr');
var id_usuarioEliminar = $(this).closest('tr')[0].children[0].getAttribute("id_usuario_eliminar");;
//console.log("id",id_usuarioEliminar);
var usuarios=$("#usuarios").val().split(",");
//console.log(usuarios);
usuarios.splice(usuarios.indexOf(id_usuarioEliminar),1);
$("#usuarios").val(usuarios.toString());
$(eliminar).remove();
$("#project").attr('disabled', false);
$("#project").val("");
});
});<file_sep><?php
include "../../Controlador/sesion.php";
//print_r( $_SESSION[session_name()]+" abcde123");
if($_SESSION["rol"] != 1 ){
header("Location: ../baseIndex.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Modulo ADMINISTRADOR</title>
<!-- <script src="https://maps.googleapis.com/maps/api/js?key=<KEY>"></script>
--> <link href="../../recursos/css/style.css" rel="stylesheet"/>
<!-- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> -->
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script>
--> <script src="../../recursos/js/jquery-1.11.2.min.js"></script>
<script src="../../recursos/js/administrador/notificarAdmin.js"></script>
<link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/nprogress/nprogress.css" rel="stylesheet"/>
<link href="../../recursos/vendors/iCheck/skins/flat/green.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet"/>
<link href="../../recursos/css/custom.css" rel="stylesheet"/>
</head>
<body class="nav-md" style="background-color:black;">
<div class="container body">
<div class="main_container">
<div class="col-md-3 left_col">
<div class="left_col scroll-view">
<div class="navbar nav_title" style="border: 0;">
<a href="index.php" class="site_title"><i class="fa "></i> <span>Defensoria publica</span></a>
</div>
<div class="clearfix"></div>
<!-- menu profile quick info -->
<div class="profile clearfix">
<div class="profile_pic">
<img src="../../recursos/images/img.jpg" alt="..." class="img-circle profile_img"/>
</div>
<div class="profile_info">
<span>Bienvenido,</span>
<?php //echo $_SESSION['usuario'] ?>
<input type="hidden" id="id_personalUser" name="" value="<?php echo $personal[0]['id_personal']?>">
</div>
</div>
<!-- /menu profile quick info -->
<br />
<!-- sidebar menu -->
<div id="sidebar-menu" class="main_menu_side hidden-print main_menu">
<div class="menu_section">
<ul class="nav side-menu">
<li><a><i class="fa fa-home"></i> Generar Informes <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu">
<li><a id="informeGAct">Generar I general de actividades</a></li>
<li><a id="informeGExp">Generar I general de expedientes</a></li>
<li><a id="informePAct">Generar I parcial de actividades</a></li>
<li><a id="informePExp">Generar I parcial de expedientes</a></li>
</ul>
</li>
<li><a><i class="fa fa-home"></i> Servicios Defensores <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu">
<li><a id="listarDefensores">Listar Defensores</a></li>
<li><a id="listarExpedientes">Listar Expedientes</a></li>
</ul>
</li>
<li><a><i class="fa fa-home"></i> Configuracion Personal <span class="fa fa-chevron-down"></span></a>
<ul class="nav child_menu">
<li><a id="registrarDefensor">Registrar personal</a></li>
<li><a id="registrarJuzgadoMenu">Registrar Juzgado</a></li>
<!-- <li><a id="cambiarAdscripcion">Cambiar Adscripcion Defensor</a></li> -->
<form action="../../action.php" method="post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Buscar Defensor(username)" name="busqueda">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</ul>
</li>
</ul>
</div>
</div>
<!-- /sidebar menu -->
<!-- /menu footer buttons -->
<div class="sidebar-footer hidden-small">
<a data-toggle="tooltip" data-placement="top" title="Salir" href="../../controlador/salir.php">
<span class="glyphicon glyphicon-off" aria-hidden="true"></span>
</a>
</div>
<!-- /menu footer buttons -->
</div>
</div>
<!-- top navigation -->
<div class="top_nav">
<div class="nav_menu">
<nav>
<div class="nav toggle">
<a id="menu_toggle"><i class="fa fa-bars"></i></a>
</div>
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<img src="../../recursos/images/img.jpg" alt=""/><?php// echo $_SESSION['usuario'] ?>
<span class=" fa fa-angle-down"></span>
</a>
<ul class="dropdown-menu dropdown-usermenu pull-right">
<li><a href="javascript:;"> Perfil</a></li>
<li>
<a href="javascript:;">
<span>Configuracion</span>
</a>
</li>
<li><a href="../../controlador/salir.php"><i class="fa fa-sign-out pull-right"></i> Salir</a></li>
</ul>
</li>
<li role="presentation" class="dropdown">
<a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-green" id="cantidadExpediente"></span>
</a>
<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
</ul>
</li>
</ul>
</nav>
</div>
</div>
<!-- /top navigation -->
<!-- page content -->
<div><h1 Bienvenido Coordinador </h1></div>
<div class="right_col" role="main">
<div class="">
<div class="page-title">
<div class="title_left">
<h3></h3>
</div>
<div class="title_right">
<div class="col-md-5 col-sm-5 col-xs-12 form-group pull-right top_search">
<div class="input-group">
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div id="dialogoNotificacion" title="Revisión Notificación?" ></div>
<?php
// echo isset($_SESSION['mensaje']);
if(isset($_SESSION['mensaje'])){
if(isset($_SESSION['mensaje']['tipo'])){
if($_SESSION['mensaje']['tipo']=='exito')
$alert='alert alert-success';
//$alert='alert alert-danger';
if($_SESSION['mensaje']['tipo']=='error')
$alert='alert alert-danger';
if($_SESSION['mensaje']['tipo']=='juzgado')
$alert='alert alert-danger';
}
?>
<div class='<?php echo $alert; ?>' role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></button>
<strong align="center">
<?php
echo (isset($_SESSION['mensaje']['mensaje'])?$_SESSION['mensaje']['mensaje']:"");
$_SESSION['mensaje']=[];
$_SESSION['mensaje']['tipo']='';
$_SESSION['mensaje']['mensaje']='';
?>
</strong>
</div>
<?php
}
?>
<div class="row" id="menuContainer">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div align ="center">
<img id="img_index_coord"src="../../recursos/images/LOGO_PRINCIPAL.png">
<p class="text-justify">
MISIÓN
<br/>
La misión de la Defensoría Pública es garantizar el derecho humano de acceso a la justicia a los sectores sociales que lo requieran, priorizando la atención a las personas de escasos recursos económicos y en situación de vulnerabilidad, a través de los servicios jurídicos de asesorías, patrocinio y defensa técnica, adecuada y diligente en materia penal, justicia especializada para adolescentes, civil, familiar, mercantil, agraria, administrativa y constitucional.
</p>
<p class="text-justify">
VISIÓN
<br/>
Ser una institución a la vanguardia que brinde servicios jurídicos con sensibilidad humana, ética y compromiso con la sociedad oaxaqueña, a fin de consolidar el Sistema de Justicia, la democracia, y el ejercicio pleno de la libertad, en un ambiente de equidad y respeto absoluto a los derechos humanos.
</p>
<p class="text-justify">
PRINCIPIOS
<br/>
Los principios que deben regir la conducta de los servidores públicos dependientes de la Defensoría Pública del Estado de Oaxaca, serán:
</p>
<?php
// echo $_SESSION['dirigir'];
if(isset($_SESSION['dirigir'])) {
switch ($_SESSION['dirigir']) {
case 'registrar_defensor':
$_SESSION['dirigir']="";?>
<script>
$('#menuContainer').children().remove();
$('#menuContainer').load("../usuarios/registrar.php");
</script>
<?php
break;
case 'listar_defensor':$_SESSION['dirigir']="";?>
<script>
$('#menuContainer').children().remove();
// $('#menuContainer').load("listarDefensores.php");/// probar con window.load o algo asi
</script>
<?php
break;
case 'cambioAdscripcion':
$_SESSION['dirigir']="";?>
<script>
$('#menuContainer').children().remove();
$('#menuContainer').load("cambiarAdscripcion.php"); </script>
<?php
break;
default:
// require_once("../usuario/registrar.php.php");
break;
}
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
<!-- inicion de dialogo de notificacion -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalCenterTitle"><b> Expedientes sin antención </b></h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="notificacionsSinAtencion" class="table-responsive x_content" title="infomación"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- fin del dialogo notificacion -->
<!-- footer content -->
<footer>
<div class="pull-right">
<a href="https://colorlib.com"></a>
</div>
<!-- <div class="col-md-4">
<div id="reportrange" class="pull-right" style="background: #fff; cursor: pointer; padding: 5px 10px; border: 1px solid #ccc">
<i class="glyphicon glyphicon-calendar fa fa-calendar"></i>
<span>December 30, 2014 - January 28, 2015</span> <b class="caret"></b>
</div> -->
<div class="clearfix"></div>
</footer>
<!-- /footer content -->
<script src="../../recursos/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../../recursos/vendors/fastclick/lib/fastclick.js"></script>
<script src="../../recursos/vendors/nprogress/nprogress.js"></script>
<script src="../../recursos/vendors/iCheck/icheck.min.js"></script>
<script src="../../recursos/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../../recursos/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<script src="../../recursos/vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
<script src="../../recursos/vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script>
<script src="../../recursos/vendors/datatables.net-buttons/js/buttons.flash.min.js"></script>
<script src="../../recursos/vendors/datatables.net-buttons/js/buttons.html5.min.js"></script>
<script src="../../recursos/vendors/datatables.net-buttons/js/buttons.print.min.js"></script>
<script src="../../recursos/vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script>
<script src="../../recursos/vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
<script src="../../recursos/vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
<script src="../../recursos/vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
<script src="../../recursos/vendors/datatables.net-scroller/js/dataTables.scroller.min.js"></script>
<script src="../../recursos/vendors/jszip/dist/jszip.min.js"></script>
<script src="../../recursos/vendors/pdfmake/build/pdfmake.min.js"></script>
<script src="../../recursos/vendors/pdfmake/build/vfs_fonts.js"></script>
<script src="../../recursos/js/custom.min.js"></script>
<script src="../../recursos/js/Gestion.js"></script>
<script src="../../recursos/js/main.js"></script>
<script src="../../recursos/js/herramienta.js"></script>
<script src="../../recursos/js/bootstrap.notify.js"></script>
</body>
</html>
<?php
if( $_SESSION['post_data'] == 1 ){
?>
<script>$("#menuContainer").load("listarExpedientes.php");</script>
<!-- <script>$("#exampleModalLong").modal('hide');</script> -->
<?php
unset($_SESSION['post_data']);
}
?>
<file_sep><?php
/* EJECUCION
FAMILIAR
AGRARIO
ADOLESCENTE */
include_once('../../modelo/conteo/pregunta.php');
//header('Content-Type: application/json');
$respuesta = Array( );
$respuestaConsultaMateria;
function constructorMateria($materia,$fechaInicio,$fechaFinal){
$thisMateria=$materia;
$thisFechaInicio='';
$thisFechaFinal='';
if(($fechaInicio!=""|$fechaInicio!=" ")&($fechaInicio!=" "|$fechaInicio!=""))
$thisFechaInicio=$fechaInicio;
if(($fechaFinal!=""|$fechaFinal!=" ")&($fechaFinal!=" "|$fechaFinal!=""))
$thisFechaFinal=$fechaFinal;
realizandoOperacionMateria($thisMateria,$thisFechaInicio,$thisFechaFinal);
/* echo "fdsfdsfs ".$thisDefensor;
echo "fechI ".$thisFechaInicio;
echo "\n fechaFinal ".$thisFechaFinal;
*/}
function realizandoOperacionMateria($materia,$fechaInicio,$fechaFinal){
//principalMateria('PENAL','',''); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
principalMateria($materia,$fechaInicio,$fechaFinal); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
//$preguntas=preguntasMateria(10);
$preguntas=preguntasMateriaAgrupadas($materia);// SIEMPRE MANDARLO EN MAYUSCULAS
$equals="";
//print_r($preguntas);
foreach ($preguntas as $key => $value) {
//print_r("\n preguntas ".$value['pregunta']);
if($value['pregunta']!=$equals){
$equals=$value['pregunta'];
$Arrayvalor =Array(); $array=Array();
// $array['datosGenerale']=fintrarPorPregunta($value['pregunta'],10);
$Arrayvalor=fintrarPorPregunta($value['pregunta'],10);//NOTA EL PARAMETRO 10 NO SIRVE Y HACE NADA
// print_r($Arrayvalor);
//$filtratoPorOpcion=filtralPorRespuesta($array['datosGenerales'],$valor['opcion']);
if($Arrayvalor!='0'){
$discapacidades=array_column( $Arrayvalor,'discapacidad');
$etnias=array_column( $Arrayvalor,'etnia');
$idioma=array_column( $Arrayvalor,'idioma');
$arrayGenerales['sexo']=array_count_values(array_column( $Arrayvalor,'sexo'));
// $arrayGenerales['idioma']=array_count_values(array_column( $Arrayvalor,'idioma'));
// $arrayGenerales['discapacidad']=array_count_values(array_column( $Arrayvalor,'discapacidad'));
$arrayGenerales['discapacidad']=filtradoGenerales('discapacidad',$discapacidades,$value['pregunta']);
$arrayGenerales['etnias']=filtradoGenerales('etnia',$etnias,$value['pregunta']);
$arrayGenerales['idiomas']=filtradoGenerales('idioma',$idioma,$value['pregunta']);
$arrayGenerales['generos']=array_count_values(array_column( $Arrayvalor,'genero'));
$arrayGenerales['respuesta']=array_count_values(array_column( $Arrayvalor,'respuesta'));
// $arrayGenerales['etnias']=array_count_values(array_column( $Arrayvalor,'etnia'));
//$array['datosGenerales']=fintrarPorPregunta($value['pregunta'],10);
//print_r($array['datosGenerales']);
// print_r($arrayGenerales);
$array['datosGenerales']=$arrayGenerales;
if($value['identificador']=="select"){
$arrayOpcion=Array();
$opciones=opcionesPorMateria($value['id_pregunta']);
// $ArrayRespuesta=Array();
foreach ($opciones as $llave => $valor) {
$filtratoPorOpciones=filtralPorRespuesta($Arrayvalor,$valor['opcion']);
$filtratoPorOpcion['sexo']=array_count_values(array_column( $filtratoPorOpciones,'sexo'));
$filtratoPorOpcion['idioma']=array_count_values(array_column( $filtratoPorOpciones,'idioma'));
$filtratoPorOpcion['discapacidades']=array_count_values(array_column( $filtratoPorOpciones,'discapacidad'));
$filtratoPorOpcion['etnias']=array_count_values(array_column( $filtratoPorOpciones,'etnia'));
$valores=$filtratoPorOpcion;
$arrayOpcion[$valor['opcion']]=$valores;
}
$array['opciones']=$arrayOpcion;
}
}
$respuesta[$value['pregunta']]=$array;// SE GUARDA EL VARLOR DE CADA UNO DE LAS PREGUNTAS
global $respuestaConsultaMateria;
$respuestaConsultaMateria=$respuesta;
}//final del if
}
//print_r( $respuesta);
}// FIN DE LA FUNCION OPERACIONMATERIA
function getRespuestaMateria(){
global $respuestaConsultaMateria;
return $respuestaConsultaMateria ;
}
//print_r( $preguntas);
/* $array = array (1, 3, 3, 5, 6);
$my_value = 3;
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } );
*/
function filtralPorRespuesta($array,$opcion){
return array_filter($array,function($respuesta) use ($opcion){
return ($respuesta['respuesta']==$opcion);
});
}
function funcionPerezoso(array $arr, $pregunta,callable $fn)
{
$arrayFiltrados=Array();
if($arr!=0)
foreach ($arr as $key => $valores) {
$retornoFucnion=$fn($valores,$pregunta);
$arrayFiltrados[$valores]=funcionContadoSexo($retornoFucnion);
}
return $arrayFiltrados;
}
function funcionContadoSexo($arr)
{ $arrays=Array();
if($arr!=0){
foreach ($arr as $key => $valores) {
$arrays[$valores['sexo']]=$valores['tsexo'];
}
}
return $arrays;
}
function filtradoGenerales($filtraPor,$array,$pregunta){
$funcionALLamar;
switch ($filtraPor) {
case 'idioma':
// return funcionPerezoso( $array, $pregunta,filtradoPorIdioma($valores,$pregunta));
return funcionPerezoso( $array, $pregunta,'filtradoPorIdioma');
break;
case 'etnia':
//return funcionPerezoso( $array, $pregunta,filtradoPorEtnia($valores,$pregunta));
return funcionPerezoso( $array, $pregunta,"filtradoPorEtnia");
break;
case 'discapacidad':
return funcionPerezoso( $array, $pregunta, 'filtradoPorDiscapacidad');
break;
default:
# code...
break;
}
}
?><file_sep><?php
include_once('../../modelo/defensor/defensor.php');
$listaDef = listar_defensores();
$contenido = json_encode($listaDef);
if(isset($_GET['term'])){//muestro todo los usuario para las busquedas del defensor
if(isset($_GET['sistema']) && isset($_GET['region']) && isset($_GET['materia'])){
switch($_GET['sistema']){
case'ALL':
$listaDef = listar_defensoresRM($_GET['region'],$_GET['materia']);
$contenido = json_encode($listaDef);
echo $contenido;
//print_r($_GET['region'].' ==== '.$_GET['materia']);
break;
default:
$listaDef = listar_defensoresSisRegMat($_GET['sistema'],$_GET['region'],$_GET['materia']);
$contenido = json_encode($listaDef);
//print_r($_GET['region'].' ==== '.$_GET['materia'].'===='.$_GET['sistema']);
echo $contenido;
break;
}
}
}
?><file_sep><?php
interface HomoclavePerson
{
function getFullNameForHomoclave();
}<file_sep><?php
echo 'lkdjaslkdjas';
?><file_sep><?php
include_once('../../modelo/contraparte.php');
include '../../libreria/herramientas.php';
$respuesta = Array(
"id_contraparte" =>$_POST['id_contraparte'],
"nombre" =>$_POST['nombre'],
"apellido_paterno" =>$_POST['apellido_paterno'],
"apellido_materno" =>$_POST['apellido_materno'],
"etnia" =>$_POST['etnia'],
"idioma" =>$_POST['idioma'],
"telefono" =>$_POST['telefono'],
"genero" =>$_POST['genero'],
"discapacidad" =>$_POST['discapacidad'],
"email" =>$_POST['email']
);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);/// convierte todo a mayusculas
//$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
//if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
//print_r($respuesta);
{actualizar_Contraparte($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Actualizacion exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
/* else
echo "el registro ya existe";
*/
?><file_sep>function verFinalizar(){
$("#modalFinalExpediente").modal('show');
}
function finalizarExpedinte(){
console.log("hola finalizar");
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
console.log("fdao ", document.getElementById('observacionFinal'));
var sendInfo = {
id_expediente:document.getElementById("numExpedienteGlobal").value,
fecha_final : document.getElementById('fecha_final').value,
observacion : document.getElementById('observacionFinal').value,
};
$.ajax({
type: "POST",
url: "../../controlador/expediente/finalizarExpediente.php",
dataType: "html",
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)
console.log($("#idMensaje"));
var alert="";
if(json['tipo']==="exito")
alert="alert alert-success";
//$alert='alert alert-danger';
if(json['tipo']==="error")
alert="alert alert-danger";
if(json['tipo']==="juzgado")
alert="alert alert-danger";
$("#contenedorMensaje").attr("class",""+alert);
$("#contenedorMensaje").append('<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">'+
'<div class="modal-dialog modal-dialog-centered" role="document">'+
'<div class="modal-content">'+
'<strong align="center" id="id_Mensaje" class="alert-dismissible fade in '+alert+'"></strong>'+
'<div class="modal-footer">'+
' <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>'+
'</div></div> </div></div>');
$("#id_Mensaje").text(json['mensaje']);
console.log(json['mensaje']," fue esto");
$('#exampleModalLong').modal('show');
console.log("ffef en always ",json['tipo']);
$("#modalFinalExpediente").modal('hide');
if(json['tipo']==="exito")
$("#registroContraparte").children().remove();
},
data: sendInfo
});
// $("#modalFinalExpediente").modal('hide');
}
var visualizar=document.getElementById("visualizarContraparte")
visualizar.addEventListener('click',verUsuarioContraparte,false);
function EnviarActualizacion(){
var sendInfo = {
id_contraparte : document.getElementById('id_contraparteEnviar').value,
nombre : document.getElementById('nombre').value,
apellido_paterno : document.getElementById('ap').value,
apellido_materno : document.getElementById('am').value,
etnia : document.getElementById('etnia').value,
idioma : document.getElementById('idioma').value,
telefono : document.getElementById('telefono').value,
genero : document.getElementById('genero').value,
discapacidad : document.getElementById('discapacidad').value,
email : document.getElementById('email').value
};
$.ajax({
type: "POST",
url: "../../controlador/expediente/actualizarContraparte.php",
dataType: "html",
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)
console.log($("#idMensaje"));
var alert="";
if(json['tipo']==="exito")
alert="alert alert-success";
//$alert='alert alert-danger';
if(json['tipo']==="error")
alert="alert alert-danger";
if(json['tipo']==="juzgado")
alert="alert alert-danger";
$("#contenedorMensaje").attr("class",""+alert);
$("#contenedorMensaje").append('<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">'+
'<div class="modal-dialog modal-dialog-centered" role="document">'+
'<div class="modal-content">'+
'<strong align="center" id="id_Mensaje" class="alert-dismissible fade in '+alert+'"></strong>'+
'<div class="modal-footer">'+
' <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>'+
'</div></div> </div></div>');
$("#id_Mensaje").text(json['mensaje']);
console.log(json['mensaje']," fue esto");
$('#exampleModalLong').modal('show');
console.log("ffef en always ",json['tipo']);
$("#modalEditarContraparte").modal('hide');
$("#modalContraparte").modal('hide');
if(json['tipo']==="exito")
$("#registroContraparte").children().remove();
},
data: sendInfo
});
}
function editarContraparte(elemento){
console.log("dentro del elemento ",elemento);
var id_contrparteEditar=elemento.getAttribute('idcontraparte');
console.log(id_contrparteEditar," id del contraparte");
$.ajax({
url: "../../controlador/expediente/obtenerContraparte.php",
type: "GET",
data: "id_contraparte="+id_contrparteEditar,
beforeSend:function(){
$('#modalEditarContraparte').modal('show');
},
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)[0]
console.log(json);
$("#EditarContraparte").children().remove();
$('#EditarContraparte').append(
'<div class="form-group">' +
'<label style="display:none;" class="control-label col-md-3 col-sm-3 col-xs-4"><span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="hidden" class="form-control " id="id_contraparteEnviar" placeholder="Id personal" name="id_contraparte"' +
'value="' + json.id_contraparte + '" readonly>' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Nombre<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="nombre" placeholder="Id personal" name="nombre"' +
'value="' + json.nombre + '">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Apellido paterno<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="ap" placeholder="apellido" name="ap"' +
'value="' + json.apellido_paterno + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Apellido materno<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="am" placeholder="apellido" name="am"' +
'value="' + json.apellido_materno + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Etnia<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="etnia" placeholder="Etnia" name="ap"' +
'value="' + json.etnia + '" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Lengua/idioma<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="idioma" placeholder="Idioma/etnia" name="ap"' +
'value="' + json.idioma + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Telefono<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="telefono" placeholder="Telefono" name="ap"' +
'value="' + json.telefono + '" pattern="([0-9]{13})|([0-9]{10})">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Genero<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="genero" placeholder="Genero" name="ap"' +
'value="' + json.genero + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Discapacidad<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="discapacidad" placeholder="Discapacidad" name="ap"' +
'value="' + json.discapacidad + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Email<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="email" placeholder="Email" name="ap" ' +
'value="' + json.email + '" pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">' +
'<input class="btn btn-succes btn btn-success btn-lg" type="button" name="botonUpdate" onclick="EnviarActualizacion()" id="botonUpdate" ' +
'value="Actualizar Datos"></input> ' +
'</div>' +
'</div>'
);
},complete:function(){
$('#modalEditarContraparte').modal('show');
}
});
} //FINAL DEL MENTO PAARA ACTUALIZAR
function verUsuarioContraparte(){
$("[class='active botonContraparte']").removeClass( "active botonContraparte" );
$(this).addClass( "active botonContraparte" );
var idexpedienteVer=document.getElementById("numExpedienteGlobal").value;
console.log("numer ex ", idexpedienteVer);
$.ajax({
url: "../../controlador/expediente/listarCompletaContraparte.php",
type: "GET",
data: "id_expediente="+idexpedienteVer,
beforeSend:function(){
},
success: function (data) {
//console.log(data);
var json=jQuery.parseJSON(data)
$("#verContraparte").children().remove();
$.each(json,function(key, valor) {
$('#verContraparte').append(
'<tr><td>'+valor.nombre+'</td>'+
'<td>'+valor.apellido_paterno+'</td>'+
'<td>'+valor.apellido_materno+'</td>'+
'<td>'+valor.idioma+'</td>'+
'<td>'+valor.etnia+'</td>'+
'<td><button type="button" class="btn btn-primary" onclick="editarContraparte(this)" idContraparte="'+valor.id_contraparte+'" id="id_contraparte" name="idContraparte">Editar</button></td>'+
'</tr>'
);
});
},complete:function(){
$('#modalContraparte').modal('show');
}
});
}<file_sep><?php
header('Content-Type: application/json');
include_once ('../../modelo/expediente.php');
$numExp = $_GET['numExp'];
$detalleExpediente = getExpedienteByNum($numExp);
$id_materia=$detalleExpediente[0]['id_materia'];
// print_r($id_materia);
$preguntasCompletaSobreMateria = listar_pregunta($id_materia);
$arrayIdPregunta=Array();
foreach ($preguntasCompletaSobreMateria as $key => $value) {
$arrayIdPregunta[]=$value['id_pregunta'];
}
//print_r($arrayIdPregunta[0]);
//print_r($detalleExpediente);
/* $array=array_filter($arrayIdPregunta,function($x) use ($detalleExpediente){
// print_r($detalleExpediente);
foreach ($detalleExpediente as $llave => $valor) {
return ($valor['id_pregunta']==$x);
}
});
print_r($array); */
/* return array_filter($array,function($respuesta) use ($opcion){
return ($respuesta['respuesta']==$opcion);
}); */
// echo $detalleExpediente;
$encode = json_encode($detalleExpediente);
$respuesta=Array(
'respuestas'=>$detalleExpediente,
'preguntas'=>$preguntasCompletaSobreMateria,
'totalPreguntas'=>count($preguntasCompletaSobreMateria),
'totalRespuestas'=>count($detalleExpediente),
);
// print_r($encode);
echo json_encode($respuesta);
?><file_sep>
<?php
include_once('RfcBuilder.php');
$builder = new RfcBuilder();
/* $rfc = $builder->name('eduardo')
->firstLastName('castañon')
->secondLastName('olguin')
->birthday(15, 04, 1968)
->build()
->toString();
*/
$rfc = $builder->name(isset($_GET['nombre']))
->firstLastName(isset($_GET['apellidoP']))
->secondLastName(isset($_GET['apellidoM']))
->birthday(isset($_GET['dia']), isset($_GET['mes']), isset($_GET['anno']))
->build()
->toString();
echo $rfc;
?><file_sep><?php
use PHPUnit\Framework\TestCase;
class StackTest extends PHPUnit_Framework_TestCase//TestCase
{
public function testPushAndPop ()
{ //registro de personal
$url='http://localhost/defensoriaPublica/controlador/defensor/registrar_Defensor.php';
//emula una visita a la vista de cambiar adscirpcion
visit($url)
// Requisitar el formulario
->keys('nombre','pepito')// ingresaso del nombre
->keys('apellid_paterno','lopez')// ingresaso del apellido
->keys('apellido_materno','perez')// ingresaso del apllidpo
->keys('telefono','9877878776')// ingresaso del telefon
->keys('email','<EMAIL>')// ingresaso del correo
->keys('nup','32122')// ingresaso del nup
->keys('nue','32132')// ingresaso del nue
->select('adscripcion', '6') //seleccion de adscripcion
->select('puesto','4')// selecion del puesto
->keys('genero','masculino')// ingresaso del genero
->keys('password', '<PASSWORD>') //ingreso contraseña
->select('genero', '6') //seleccion de genero
// Hacer clic en el boton agregar
->press('guardar'); // dar en guardar
waitForText(' registro exitso');
//actualizar juzgado
$url='http://localhost/defensoriaPublica/controlador/defensor/registrar_Defensor.php';
//emula una visita a la vista de cambiar adscirpcion
visit($url)
// Requisitar el formulario
->keys("id_defensor" ,'44')
->keys("nombre" ,"pepes")
->keys("ap_paterno" ,"lopez")
->keys("ap_materno" ,'garcia')
->keys( "curp" ,'curp')
->keys("calle" ,'emiliano')
->keys("numero_ext" ,'221')
->keys("numero_int" ,'23')
->keys("colonia" ,'oaxaca')
->keys( "municipio" ,'oaxaca')
->keys( "nup" ,'2334')
->keys("nue" ,'234')
->keys("genero" ,'masculino')
->keys("telefono" ,'988767879')
->keys( "<EMAIL>" ,'<EMAIL>')
->keys("cedula_profesional" ,'c3dul4Pr0f4io4L')
->keys("juzgado" ,'penal 1')
// Hacer clic en el boton agregar
->press('actualizar datos'); // dar en actualizar
waitForText(' registro actualizado')
/// eliminar personal
$url='http://localhost/defensoriaPublica/controlador/juzgado/controlDelDefesor.php';
//emula una visita a la vista de cambiar adscirpcion
visit($url)
// Requisitar el formulario
->select('id_defensor', '6') //seleccion de adscripcion
// Hacer clic en el boton agregar
->press('eliminar');
->select('confirmacion', 'si') //seleccion de adscripcion
waitForText('defensor eliminado ')
$url='http://localhost/defensoriaPublica/controlador/juzgado/actividad_juzgado.php';
//emula una visita a la vista de cambiar adscirpcion
visit($url)
// Requisitar el formulario
->keys('nue','32122')// ingresaso del nue
->select('adscripcion', '6') //seleccion de adscripcion
// Hacer clic en el boton agregar
->press('cambiar');
waitForText(' cambio de defensor exitso')
}
}
?><file_sep>
var varUsuario=[];
var datos = jQuery.parseJSON(window.Global_usuarios_servicios);
$.each(datos, function (KEY, VALOR) {
var temp={};
temp['label']=VALOR.nombre;
temp['apellidos']=VALOR.ap_paterno+" "+VALOR.ap_materno;
temp['desc']=VALOR.colonia+", "+VALOR.municipio;
temp['id_usuario']=VALOR.id_usuario_servicio;
temp['curp']=VALOR.curp;
// console.log(VALOR);
varUsuario.push(temp);
});
$( function() {
$( "#project" ).autocomplete({
minLength: 0,
source: varUsuario,
focus: function( event, ui ) {
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
// console.log(ui);
return false;
},
select: function( event, ui ) {
var usuario=ui.item.label+" "+ui.item.apellidos;
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
$( "#curp" ).val(ui.item.curp );
$( "#curpMostrado" ).val(ui.item.curp );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label +" "+item.apellidos+ "<br>" + item.desc + "</div>" )
.appendTo( ul );
};
} );
function validarFecha(e, elemento) {
var fechas= document.getElementById("fecha_registro").value;
//console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
var date = new Date()
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
return false;
}
if(ano <date.getFullYear() || ano > date.getFullYear())
{
console.log(" año invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="año invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(mes < date.getMonth()+1 || mes > date.getMonth()+1)
{
console.log("mes invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Mes invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(dia < date.getDate()-5 || dia > date.getDate())
{
console.log("fecha invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Dia invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
console.log( date.getYear());
}<file_sep><?php
define('BD_SERVIDOR', '127.0.0.1');
define('BD_NOMBRE', 'bddefensoria');
define('BD_USUARIO', 'root');
define('BD_PASSWORD', '');
$db = new PDO("mysql:host=".BD_SERVIDOR.";dbname=".BD_NOMBRE.";charset=utf8",BD_USUARIO,BD_PASSWORD);
function consulta($consulta){
global $db;
$sql = $db->prepare($consulta);
$sql->execute();
if($sql->rowCount()==0)
return 0;
if($sql->rowCount()>0)
//$datos = $sql->fetchAll(PDO::FETCH_ASSOC);
return $sql->fetchAll(PDO::FETCH_ASSOC);
//return $datos;
}
function consulta_obj($consulta){
global $db;
$sql = $db->prepare($consulta);
$sql->execute();
if($sql->rowCount()==0)
return 0;
if($sql->rowCount()>0)
//$datos = $sql->fetchAll(PDO::FETCH_ASSOC);
return $sql->fetchAll(PDO::FETCH_ARRAY);
//return $datos;
}
function registro($consulta){
global $db;
$sql=$db->prepare($consulta);
$sql->execute();
return $sql->rowCount();
}
//$this->id = $conexion->lastInsertId(); segun esto me devuelte el ultimo id creado
?>
<file_sep><?php
require_once("modelo/defensor.php");
require_once("modelo/materia.php");
require_once("modelo/usuario_servicio.php");
require_once("modelo/expediente.php");
require_once("modelo/siguimiento_caso.php");
require_once("modelo/juzgado.php");
require_once("modelo/asesoria.php");
$asesoria=['id_expediente'=>1,
'dia_asesoria'=>02,
'mes_asesoria'=>01,
'an_asesoria'=>2008];
$sql = "INSERT INTO proveedor ";
$sql.= "SET id_expediente='".$provedor['id_expediente']."', dia_asesoria='".$provedor['dia_asesoria']."',";
$sql.= "SET mes_asesoria='".$provedor['mes_asesoria']."', ano_asesoria='".$provedor['ano_asesoria']."',";
$sql.= "observaciones='".$provedor['observaciones']."'";
crear_asesoria($asesoria);
?>
<file_sep><?php
header('Content-Type: application/json');
include '../../modelo/personal.php';
include '../../modelo/defensor/defensor.php';
include '../../modelo/usuario_sistema.php';
include '../../libreria/herramientas.php';
$personal = Array(
"id_cargo" =>$_POST['puesto'],
"nombre" =>$_POST['nombre'],
"ap_paterno" =>$_POST['apellido_paterno'],
"ap_materno" =>$_POST['apellido_materno'],
"curp" =>$_POST['curp'],
"calle" =>"",
"numero_ext" =>"",
"numero_int" =>" ",
"colonia" =>"",
"municipio" =>"",
"nup" =>$_POST['nup'],
"nue" =>$_POST['nue'],
"genero" =>$_POST['genero'],
"telefono" =>$_POST['telefono'],
"correo" =>$_POST['email'],
"foto" =>" "
);
if(listar_defensor_x_nue($_POST['nue'])==0){
$mensaje=['tipo'=>"juzgado",
'mensaje'=>"no puedes tener mas de 1 coordinaodr en un juzgado"];
if(!vericar_coordinador($_POST['puesto'])){
crear_personal($personal);
$defensor=Array(
"id_juzgado"=>$_POST['adscripcion'],
"id_personal"=>ultimoPersonalCreatado()
);
crear_defensor($defensor);
$personal['username']=$_POST['nue'];
$personal['password']=encriptar($_POST['password']);
crear_usarioSistema($personal);
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
$didigir="listar_defensor";
$asunto = "Envio de Nip Acceso Al Sistemas ";
$mensaje = " accede a la siguiente pagina http://localhost/defensoriaPublica/ con tu contraseña: ".$personal['password'];
envio_correo($personal['correo'], $asunto, $mensaje);
}
}
else{
$mensaje=['tipo'=>"error",
'mensaje'=>"el personal con el nue o nup ya se encuentra registrado"];
$didigir="registrar_defensor";
}
// ultimoPersonalCreatado();
if(!isset($_GET['tipo'])){
session_start();
$_SESSION['mensaje'] = $mensaje;
header("location: ../../vistas/administrador/index.php?dirigir=".$didigir);
}
else{
echo "json";
}
function vericar_coordinador($puesto){
if($puesto=='2')
$verificador=listar_defensor_x_juzgado($_POST['adscripcion']);
if($verificador==0)
return false;
return true;
}
?><file_sep><?php
include '../../modelo/defensor/defensor.php';
if(isset($_GET['id_personal'])){
$id_def = $_GET['id_personal'];
$defensorX = getDefensorById($id_def);//obtenerDefensorCedula($cedulaProf);
$defensorZ = json_encode($defensorX);
echo $defensorZ;
}
////carga el defensor por materia
if(isset($_GET["materia"])){
$materia=$_GET["materia"];
$defensorPormateria= getDefensorPorMateria($materia);
echo json_encode($defensorPormateria);
}
////carga el personal_campo por juzgado
if(isset($_GET["id_personalPorJuzgado"])){
// header('Content-type: application/json');
$id_personal=$_GET["id_personalPorJuzgado"];
//echo "el idpersonal es igual a ".$id_personal;
$defensorPorJuzgado= getDefensorPorJuzgado($id_personal);
echo json_encode($defensorPorJuzgado);
}
?><file_sep><?php
include '../../modelo/querys/informes.php';
if((isset($_POST['sistema']) && isset($_POST['materia']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']) && isset($_POST['f1']) && isset($_POST['f2'])) ||
(isset($_POST['sistema']) && isset($_POST['region']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']) && isset($_POST['f1']) && isset($_POST['f2'])) ||
(isset($_POST['sistema']) && isset($_POST['region']) && isset($_POST['materia']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']) && isset($_POST['f1']) && isset($_POST['f2']))||
(isset($_POST['sistema']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']) && isset($_POST['f1']) && isset($_POST['f2']))){
$x = $_POST['filtro'];
$f1 = $_POST['f1'];
$f2=$_POST['f2'];
switch($x){
case 'MATERIA':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$mat = $_POST['materia'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id=$_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaMatNotSystemDefP($mat, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaMatSystemDefP($sis, $mat, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaMatNotSystemP($mat, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaMatSystemP($sis, $mat, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'REGION':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$reg = $_POST['region'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id=$_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaRegNotSystemDefP($reg, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaRegSystemDefP($sis, $reg, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaRegNotSystemP($reg, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaRegSystemP($sis, $reg, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'AMBAS':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$reg = $_POST['region'];
$mat = $_POST['materia'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id= $_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaAmbasNotSystemDefP($mat, $reg, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaAmbasSystemDefP($sis, $mat, $reg, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaAmbasNotSystemP($mat, $reg, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaAmbasSystemP($sis, $mat, $reg, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'NINGUNO':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id= $_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaNingunoNotSystemDefP($atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaNingunoSystemDefP($sis, $atrib, $id, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaNingunoNotSystemP($atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaNingunoSystemP($sis, $atrib, $f1, $f2);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
}
}
?>
<file_sep><?php
session_start();
//include_once( '../../controlador/juzgado/actividad_juzgado.php');
include_once( '../../controlador/defensor/controladorListaDef.php');
//include_once( '../../controlador/usuario_servicio/lisaUsuario.php');
?><!--
<script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script> -->
<script src="../../recursos/js/defensor/atendiendoDefensor.js"></script>
<script src="../../recursos/js/herramienta.js"></script>
<style>
.ui-autocomplete-loading {
background: white url("../../recursos/images/cargando.gif") right center no-repeat;
}
</style>
<script>
var varUsuario=[];
var datos = jQuery.parseJSON(window.Global_usuarios_servicios);
$.each(datos, function (KEY, VALOR) {
var temp={};
temp['label']=VALOR.nombre;
temp['apellidos']=VALOR.ap_paterno+" "+VALOR.ap_materno;
temp['desc']=VALOR.colonia+", "+VALOR.municipio;
temp['id_usuario']=VALOR.id_usuario_servicio;
// console.log(VALOR);
varUsuario.push(temp);
});
$( function() {
function log( message ) {
var usuario=message.item.label+" "+message.item.apellidos;
if($("#usuarios").val().indexOf(message.item.id_usuario)===-1){//PRIMERO CHECO SI ESQUE EL USUARIO NO FUE YA INSERTADO
var tr=document.createElement("tr");
// $( "<tr><td>" ).text( message ).prependTo( "#usuarioSeleccionados" );
var td=document.createElement("td");
tr.appendChild(td);
console.log(message);
// $( td ).text( message ).prependTo( "#usuarioSeleccionados" );
$( td ).text( usuario );// A ESTE TD LE ASIGO AL USUARIO DEL SERVICIO
td.setAttribute("id_usuario_eliminar",message.item.id_usuario);
$("#usuarioSeleccionados").append(tr);
var td2=document.createElement("td");
if($("#usuarios").val()==="")//? message.item.id_usuario: $("#usuarios").val()+","message.item.id_usuario);
$("#usuarios").val(message.item.id_usuario);
else
$("#usuarios").val($("#usuarios").val()+","+message.item.id_usuario);
$(td2).append("<button type='button' class='btn btn-primary eliminar col-md-7 col-xs-12'><span class='glyphicon glyphicon-remove' aria-hidden='true'> </span> </button>");
tr.appendChild(td2);
$("#project").val("");
}
$("#project").val("");//SIEMPRE LIMPIA EL INPUT DE BUSQUEDA // $( "#usuarioSeleccionados" ).scrollTop( 0 );
}///TERMINA LA FUCION
$( "#project" ).autocomplete({
minLength: 0,
source: varUsuario,
focus: function( event, ui ) {
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
return false;
},
select: function( event, ui ) {
var usuario=ui.item.label+" "+ui.item.apellidos;
log(ui);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label +" "+item.apellidos+ "<br>" + item.desc + "</div>" )
.appendTo( ul );
};
} );
</script>
<script>
function cambiarVista(){
var sistema=document.getElementById('tipoSistema').value;
var materia=document.getElementById('tipoMateria').value;
// console.log(sistema);
//console.log(materia);
if(sistema==="ORAL"&&materia==="PENAL"){
console.log("SE AGREGARA EL ELEMENTO TIPO DE EXPEDIENTE");
$("#divExpediente").after('<div id="divTipoExpediente" class="form-horizontal form-label-left"> <div class="form-group">'+
'<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Tipo de expediente <span class="required">*</span>'+
'</label>'+
'<div class="col-md-6 col-sm-6 col-xs-12">'+
'<select required="" id="tipo_expediente" name="tipo_expediente" class="form-control ">'+
'<option value="">--SELECCIONE UNA OPCIÓN--</option>'+
'<option value="LEGAJO">LEGAJO</option>'+
'<option value="CAUSA_PENAL">CAUSA PENAL</option>'+
'</select>'+
'</div></div> </div>');
}
}
cambiarVista();
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Crear Expediente</label></h1>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form autocomplete="off" id="myform" data-toggle="validator" role="form" class="" action ="../../controlador/expediente/registrarExpediente.php?tipo=html" object="defensor" method="post">
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Nombre de usuario(s)<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="text" value="{{curp}}"minlength="18" maxlength="18" name="curp" data-error="debe ser un formato de curp correcto" id="curp" pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)" required="required" class="form-control col-md-7 col-xs-12">
--><input autocomplete="cualquier-cosa" data-error="Seleccione al menos un usuario" type="text" id="project" required class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div></div>
</div></div>
<!-- usuario seleccionados -->
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue"><span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<table required="" id="tablaAsinacionExpedienteusuario" class="table table-striped ">
<tbody required="" id="usuarioSeleccionados" style="height: 200px; width:915px; overflow: auto;" class=" ui-widget-content"></tbody>
</table>
<div class="help-block with-errors"></div>
</div></div></div>
<div id="divExpediente" class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Numero de expediente<span class=""></span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required onkeyup="mayusculas(event, this)" type="text" name="expediente" id="expediente" data-error="Se requiere de un numero de expediente" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="delito">Delito<span class=""></span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input required type="text" pattern="[A-Za-z ]+" onkeyup="mayusculas(event, this)" onmouseout="verificarDelito(event,this)" onblur="verificarDelito(event,this)" name="delito" id="delito" data-error="Solo letras" class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div> </div>
</div></div>
<div id="gradoDelito" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Tipo de delito <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<select required="" id="id_gradodelito" name="grado_delito" class="form-control ">
<option value="">--SELECCIONE UNA OPCIÓN-</option>
<option value="DOLOSO">DOLOSO</option>
<option value="CULPOSO">CULPOSO</option>
</select>
</div></div> </div>
<input type="text" name="usuarios" id="usuarios" style="display:none;" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="defensor" id="defensor" style="display:none;" value="<?php echo $_SESSION['personal'][0]["id_personal"]?>" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="tipoSistema" id="tipoSistema" style="display:none;" value="<?php echo $_SESSION['personal'][0]["sistema"]?>" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="tipoMateria" id="tipoMateria" style="display:none;" value="<?php echo $_SESSION['personal'][0]["materia"]?>" class="form-control col-md-7 col-xs-12"/>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="asignarAdscripcion" type ="submit" class="btn btn-succes btn btn-success btn-lg" onmouseover="verificarDelito(event,this)" value="Crear Expediente"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</div>
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<script>
$('#gradoDelito').hide()
$('#myform').validator()
</script><file_sep><?php
header('Content-Type: application/json');
include '../../modelo/personal.php';
include '../../modelo/usuarioServicio.php';
include '../../libreria/herramientas.php';
$hoy = getdate();
$edadNumero=$hoy['year']-intval($_POST['fechaNacimiento']);
$usuario = Array(
"nombre" =>$_POST['nombre'],
"ap_paterno" =>$_POST['apellido_paterno'],
"ap_materno" =>$_POST['apellido_materno'],
"telefono" =>$_POST['telefono'],
"correo" =>$_POST['email'],
"calle" =>$_POST['calle'],
"numero_ext" =>$_POST['numero'],
"numero_int" =>"",
"colonia" =>$_POST['colonia'],
"municipio" =>$_POST['municipio'],
"curp" =>$_POST['curp'],
"estado" =>$_POST['estado'],
"edad" =>$edadNumero,
"etnia" =>$_POST['etnia'],
"idioma" =>$_POST['idioma'],
"fecha" =>"",
"genero" =>$_POST['genero'],
"discapacidad" =>$_POST['discapacidad'],
"sexo" =>$_POST['sexo']
);
$usuario = array_map( "cadenaToMayuscula",$usuario);
$mensaje=['tipo'=>"error",
'mensaje'=>"este usuario ya se encuentra registrado"];
$dirigir="registrar_usuario";
//sprint_r (getDefensorByCurp($_POST['curp']));
if(getUsuarioByCurp($_POST['curp'])==0){
crear_usuarioSevicio($usuario); //regresa 1 si regristro para validar tambien par validar si ya exite o res regisro correctamente
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"
];
$dirigir="asignar_defensor";
}
//print_r($usuario);
if(!isset($_GET['tipo'])){
session_start();
$_SESSION['mensaje'] = $mensaje;
$_SESSION['dirigir']=$dirigir;
header("location: ../../vistas/defensor/index.php");
}
else{
echo "json";
}
function vericar_coordinador($puesto){
if($puesto=='2')
$verificador=listar_defensor_x_juzgado($_POST['adscripcion']);
if($verificador==0)
return false;
return true;
}
?><file_sep><?php
include_once('../../modelo/conteo/pregunta.php');
header('Content-Type: application/json');
$respuesta = Array( );
$respuestaConsulta;
function tipoconstructorRegionSistemaMateria($region,$sistema,$materia,$fechaInicio,$fechaFinal){
$thisRegion=$region;
$thisFechaInicio='';
$thisFechaFinal='';
$thisSistema='';
$thisMateria='';
if(($fechaInicio!=""|$fechaInicio!=" ")&($fechaInicio!=" "|$fechaInicio!=""))
$thisFechaInicio=$fechaInicio;
if(($fechaFinal!=""|$fechaFinal!=" ")&($fechaFinal!=" "|$fechaFinal!=""))
$thisFechaFinal=$fechaFinal;
if(($sistema!=""|$sistema!=" ")&($sistema!=" "|$sistema!=""))
$thisSistema=$sistema;
if(($materia!=""|$materia!=" ")&($materia!=" "|$materia!=""))
$thisMateria=$materia;
//principalRegionSistemaMateria($thisRegion,$thisSistema,$thisMateria,$thisFechaInicio,$thisFechaFinal);
// preguntasRegionSistemaMateria($thisRegion,$thisSistema,$thisMateria);
realizandoOperacionRegionSistemaMateria($thisRegion,$thisSistema,$thisMateria,$thisFechaInicio,$thisFechaFinal);
}
function realizandoOperacionRegionSistemaMateria($region,$sistema,$materia,$thisFechaInicio,$fechaFinal){
// $listaPreguntas=aplicarConsultaDefensor(19,'',''); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
$listaPreguntas=principalRegionSistemaMateria($region,$sistema,$materia,$thisFechaInicio,$fechaFinal); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
echo "lista de preguntas \n";
print_r($listaPreguntas);
$preguntasConOpcion=preguntasRegionSistemaMateria($region,$sistema,$materia);
//print_r($preguntasConOpcion);
$equals="";
if($preguntasConOpcion!=0)
foreach ($preguntasConOpcion as $key => $value) {
if($value['pregunta']!=$equals){
$equals=$value['pregunta'];
$Arrayvalor =Array(); $array=Array();
// $array['datosGenerale']=filtrarPorPreguntaDefensor($value['pregunta'],19,'','');
$array['id_materia']=$listaPreguntas[0]['id_materia'];
// print_r($array);
// $Arrayvalor=filtrarPorPreguntaDefensor($value['pregunta'],19,'','');//se cmaio por abajo
$Arrayvalor=filtrarPorPreguntaDefensor($value['pregunta'],$defensor,$thisFechaInicio,$fechaFinal);
// print_r($Arrayvalor);
//$filtratoPorOpcion=filtralPorRespuesta($array['datosGenerales'],$valor['opcion']);
if($Arrayvalor!='0'){
//echo "aqui viene \n";
// print_r($Arrayvalor);
$discapacidades=array_column( $Arrayvalor,'discapacidad');
$etnias=array_column( $Arrayvalor,'etnia');
$idioma=array_column( $Arrayvalor,'idioma');
$genero=array_column( $Arrayvalor,'genero');
$arrayGenerales['sexo']=array_count_values(array_column( $Arrayvalor,'sexo'));
$arrayGenerales['discapacidad']=filtradoGenerales('discapacidad',$discapacidades,$value['pregunta'],$defensor,$thisFechaInicio,$fechaFinal);
$arrayGenerales['etnias']=filtradoGenerales('etnia',$etnias,$value['pregunta'],$defensor,$thisFechaInicio,$fechaFinal);
$arrayGenerales['idiomas']=filtradoGenerales('idioma',$idioma,$value['pregunta'],$defensor,$thisFechaInicio,$fechaFinal);
$arrayGenerales['generos']=array_count_values(array_column( $Arrayvalor,'genero'));
$arrayGenerales['respuesta']=array_count_values(array_column( $Arrayvalor,'respuesta'));
$array['datosGenerales']=$arrayGenerales;
if($value['identificador']=="select"){
$arrayOpcion=Array();
$opciones=opcionesPorMateria($value['id_pregunta']);
foreach ($opciones as $llave => $valor) {
$filtratoPorOpciones=filtralPorRespuesta($Arrayvalor,$valor['opcion']);
$filtratoPorOpcion['sexo']=array_count_values(array_column( $filtratoPorOpciones,'sexo'));
$filtratoPorOpcion['idioma']=array_count_values(array_column( $filtratoPorOpciones,'idioma'));
$filtratoPorOpcion['discapacidades']=array_count_values(array_column( $filtratoPorOpciones,'discapacidad'));
$filtratoPorOpcion['etnias']=array_count_values(array_column( $filtratoPorOpciones,'etnia'));
$valores=$filtratoPorOpcion;
$arrayOpcion[$valor['opcion']]=$valores;
}
$array['opciones']=$arrayOpcion;
}
}
$respuesta[$value['pregunta']]=$array;// SE GUARDA EL VARLOR DE CADA UNO DE LAS PREGUNTAS
//print_r( $respuesta);
//return $respuesta;
global $respuestaConsulta;
$respuestaConsulta=$respuesta;
}//final del if
}
}//fin realizando operacion
//print_r( $respuestaConsulta);
//$respuestaConsulta=$respuesta;
function getRespuesta(){
global $respuestaConsulta;
return $respuestaConsulta ;
}
//print_r( $preguntas);
function filtralPorRespuesta($array,$opcion){
return array_filter($array,function($respuesta) use ($opcion){
return ($respuesta['respuesta']==$opcion);
});
}
function funcionPerezoso(array $arr, $pregunta,$defensor,$fechaInicio,$fechaFina,callable $fn)
{ $arrayFiltrados=Array();
if($arr!=0)
foreach ($arr as $key => $valores) {
$retornoFucnion=$fn($valores,$pregunta,$defensor,$fechaInicio,$fechaFina);
$arrayFiltrados[$valores]=funcionContadoSexo($retornoFucnion);
}
return $arrayFiltrados;
}
function funcionContadoSexo($arr)
{ $arrays=Array();
//print_r($arr)
if($arr!=0){
foreach ($arr as $key => $valores) {
$arrays[$valores['sexo']]=$valores['tsexo'];
}
}
return $arrays;
}
function filtradoGenerales($filtraPor,$array,$pregunta,$defensor,$fechaInicio,$fechaFina){
$funcionALLamar;
// echo $fechaFina." se tiene en filtrado general";
switch ($filtraPor) {
case 'idioma':
// return funcionPerezoso( $array, $pregunta,filtradoPorIdioma($valores,$pregunta));
return funcionPerezoso( $array, $pregunta,$defensor,$fechaInicio,$fechaFina,'filtradoPorIdiomaDefensor');
break;
case 'etnia':
//return funcionPerezoso( $array, $pregunta,filtradoPorEtnia($valores,$pregunta));
return funcionPerezoso( $array, $pregunta,$defensor,$fechaInicio,$fechaFina,"filtradoPorEtniaDefensor");
break;
case 'discapacidad':
return funcionPerezoso( $array, $pregunta, $defensor,$fechaInicio,$fechaFina, 'filtradoPorDiscapacidadDefensor');
break;
default:
# code...
break;
}
}
function filtradoPorDiscapacidadDefensor($dicapacidad,$pregunta,$defensor,$fechaInicio,$fechaFina){
$sql="select sexo, count(sexo) as tsexo from (
select discapacidad, sexo from (".principalDefensor($defensor,$fechaInicio,$fechaFina)." ) as resultado
where p='".$pregunta."' ) as filtro
where discapacidad='".$dicapacidad."' group by sexo ;";
//echo $sql;
// echo "aqui se finaliza \n";
return consulta($sql);
}
function filtradoPorEtniaDefensor($etnia,$pregunta,$defensor,$fechaInicio,$fechaFina){
$sql="select sexo, count(sexo) as tsexo from (
select etnia, sexo from (".principalDefensor($defensor,$fechaInicio,$fechaFina)." ) as resultado
where p='".$pregunta."' ) as filtro
where etnia='".$etnia."' group by sexo ;";
// echo $sql;
return consulta($sql);
}
function filtradoPorIdiomaDefensor($idioma,$pregunta,$defensor,$fechaInicio,$fechaFina){
$sql="select sexo, count(sexo) as tsexo from (
select idioma, sexo from (".principalDefensor($defensor,$fechaInicio,$fechaFina)." )as resultado
where p='".$pregunta."' ) as filtro
where idioma='".$idioma."' group by sexo ;";
//echo $sql;
return consulta($sql);
}
?><file_sep><?php
include '../../controlador/juzgado/actividad_juzgado.php';
?>
<script>
function agrega(){
// $('#menuContainer').load("coordinadorRegistrarJuzgado.php");
}
</script>
<script src="../../recursos/js/herramienta.js"></script>
<script>
function validarFecha(e, elemento) {
var fechas= document.getElementById("fechaNacimiento").value;
console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
var date = new Date(ano,mes,dia)
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
// $(".with-errors").append("<ul class='list-unstyled'><li>solo 4 digito en el a</li></ul>");
console.log("joijoiuiu");
return false;
}
if(ano < 1958 || ano > 1998)
{
console.log("fecha invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="fecha invalida";
error.appendChild(ul);
//alert("Es necesario que el año de la Fecha de Nacimiento, se encuentre entre " + (dtmHoy.getFullYear() - 120)+ " y " + dtmHoy.getFullYear())
// document.ejemploForma.stranio.focus()
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
console.log( date.getYear());
}
function validarCurps() {
// pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)";
var curpNombre=document.getElementById("nombre").value;
console.log("el nombre es ",curpNombre);
var curpApaterno=document.getElementById('aPaterno').value;
var curpAmaterno=document.getElementById('aMaterno').value;
var curpGenero=(((document.getElementById("sexo").options[document.getElementById("sexo").selectedIndex].value)==="masculino")?'H':'M');
var curpFecha= document.getElementById("fechaNacimiento").value.split('-');
//var fechas= document.getElementById("fecha").value;
var entidad=document.getElementById("entidad").options[document.getElementById("entidad").selectedIndex].value;
console.log(entidad);
var curp = generaCurp({
nombre : curpNombre,
apellido_paterno : curpApaterno,
apellido_materno : curpAmaterno,
sexo : curpGenero,
estado : entidad,
fecha_nacimiento : [curpFecha[2],curpFecha[1],curpFecha[0]]
});
console.log(curp.substr(0,13));
var claseCurp=document.getElementById("curp");
claseCurp.value=curp;
claseCurp.setAttribute("pattern",curp.substr(0,13)+'[A-Za-z]{3}[0-9]{2}');
}
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Registro usuario del servicio</label></h1>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form id="myform" data-toggle="validator" role="form" class="form-horizontal form-label-left" action ="../../controlador/usuario_servicio/crearUsuario.php" object="defensor" method="post">
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Nombre<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="nombre" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ ]+" onkeyup="mayusculas(event, this)" maxlength="40" minlength="4" autofocus="autofocus" required class="form-control text-uppercase" data-error="se letras no máximo de 40 ni mánimo de 4" placeholder="Nombre" name="nombre">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >calle<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" onkeyup="mayusculas(event, this)" maxlength="50" minlength="4" data-error=": solo palabras de minimo 4 carácter "class="form-control" required placeholder="" name="calle">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Apellido Paterno<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aPaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Paterno" name="apellido_paterno">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 "> Número<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" pattern="[1-9][0-9]*" maxlength="5" minlength="1" data-error="solo numero intero con maxicmo 5 digito" class="form-control" required placeholder="" name="numero">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-1 " >Apellido Materno<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aMaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Materno" name="apellido_materno">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Email<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" data-error="correo invalido" class="form-control" pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$" required placeholder="Email" name="email">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Entidad federativa de nacimiento<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select id="entidad" name="estado" required class="select2_group form-control textbox">
<option value="">- Seleccione -</option>
<option value="AS">AGUASCALIENTES</option>
<option value="BC">BAJA CALIFORNIA</option>
<option value="BS">BAJA CALIFORNIA SUR</option>
<option value="CC">CAMPECHE</option>
<option value="CL">COAHUILA DE ZARAGOZA</option>
<option value="CM">COLIMA</option>
<option value="CS">CHIAPAS</option>
<option value="CH">CHIHUAHUA</option>
<option value="DF">DISTRITO FEDERAL</option>
<option value="DG">DURANGO</option>
<option value="GT">GUANAJUATO</option>
<option value="GR">GUERRERO</option> <option value="HG">HIDALGO</option> <option value="JC">JALISCO</option> <option value="MC">MEXICO</option> <option value="MN">MICHOACAN DE OCAMPO</option> <option value="MS">MORELOS</option> <option value="NT">NAYARIT</option> <option value="NL">NUEVO LEON</option> <option value="OC">OAXACA</option> <option value="PL">PUEBLA</option> <option value="QT">QUERETARO DE ARTEAGA</option> <option value="QR">QUINTANA ROO</option> <option value="SP">SAN LUIS POTOSI</option> <option value="SL">SINALOA</option> <option value="SR">SONORA</option> <option value="TC">TABASCO</option> <option value="TS">TAMAULIPAS</option> <option value="TL">TLAXCALA</option> <option value="VZ">VERACRUZ</option> <option value="YN">YUCATAN</option> <option value="ZS">ZACATECAS</option> <option value="NE">NACIDO EN EL EXTRANJERO</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Teléfono<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="telefono" type="text"pattern="([0-9]{13})|([0-9]{10})" class="form-control " data-error=": solo numero telefonico" required placeholder="" name="telefono">
<div class="help-block with-errors"></div> </div>
</div>
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label for="inputEmail" class="control-label col-md-4 col-sm-3 col-xs-12 " >Fecha nacimiento<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="fechaNacimiento" type="date" onkeyup="validarFecha(event,this)" onblur="validarFecha(event,this)" data-error="fecha invalido" pattern="" data-error="fecha invalida" maxlength="50" class="form-control" required="" placeholder="Email" name="fechaNacimiento">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Curp<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="curp" onkeyup="mayusculas(event, this)" onblur="validarCurps()" tidata-error=": el formato debe ser alfanumerico con 18 digitos" maxlength="18" pattern=""class="form-control text-uppercase" required placeholder="curp" name="curp">
<div class="help-block with-errors"></div> </div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Sexo<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select required id="sexo" onkeyup="validarCurps()" onblur="validarCurps()" name="sexo" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="masculino">masculino</option>
<option value="femenino">femenino</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Género<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select novalidate id="genero" onkeyup="validarCurps()" onblur="validarCurps()" name="genero" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="lesbico">Lésbico</option>
<option value="gay">Gay</option>
<option value="bisexual">Bisexual</option>
<option value="transexual">Transexual</option>
<option value="Transgenero">Transgénero</option>
<option value="Travesti">Travesti </option>
<option value="Intersexual">Intersexual </option>
<option value="Ninguno">Ninguno </option>
</select>
</div>
</div>
<!-- <div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Municipio<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input onkeyup="mayusculas(event, this)" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="municipio">
</div>
</div> -->
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Código postal<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<input type="text" data-error="solo numeros" pattern="[0-9 ]+" onmouseout="consumirCodigoPostal(this)" maxlength="10" minlength="1" class="form-control text-uppercase" required placeholder="" name="municipio">
<div class="help-block with-errors"></div>
</div></div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Discapacidad<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select required id="discapacidad" name="discapacidad" class="select2_group form-control">
<option value="ninguno">- Seleccione -</option>
<option value="sensorial">Discapacidades sensoriales y de la comunicación</option>
<option value="motrices"> Discapacidades motrices</option>
<option value="mental"> Discapacidades mentales</option>
<option value="multiples"> Discapacidades multiples </option>
<option value="ninguno"> Ninguno </option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Municipio<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input onkeyup="mayusculas(event, this)" id="municipio" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="municipio">
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Etnia</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select novalidate id="etnia" name="etnia" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="Mixteco">Mixteco</option>
<option value="Zapoteco">Zapoteco</option>
<option value="Amuzgos">Amuzgos</option>
<option value="Chatino">Chatino</option>
<option value="Chinantecos">Chinantecos</option>
<option value="Chochol">Chochol </option>
<option value="Chontales">Chontales </option>
<option value="Cuicatecos">Cuicatecos </option>
<option value="Huaves">Huaves </option>
<option value="Ixcatecos">Ixcatecos </option>
<option value="Mazatecos ">Mazatecos </option>
<option value="Mixe">Mixe </option>
<option value="Nahua">Nahua </option>
<option value="Triqui">Triqui </option>
<option value="Zoques">Zoques </option>
<option value="Chocholtecos">Chocholtecos </option>
<option value="Tacuates">Tacuates </option>
<option value="Afromexicano">Afromexicano </option>
<option value="Afromestizos">Afromestizos </option>
<option value="Tzotziles">Tzotziles </option>
<option value="Popoloca">Popoloca </option>
<option value="Ninguno">Ninguno </option>
</select>
</div>
</div>
<!-- <div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Edad<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" data-error=": solo numero mayor a 14 no maxicmo a 100 años" pattern="(1(00|[5-9])|([2-9]([0|1-9])))"class="form-control " required placeholder="" name="edad">
</div>
</div> -->
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Colonia<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" onkeyup="mayusculas(event, this)" id="colonia" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="colonia">
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Idioma/lengua</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input onkeyup="mayusculas(event, this)" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="idioma">
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<button class="btn btn-primary btn btn-info btn-lg" type="reset">Limpiar</button>
<input type ="submit" class="btn btn-succes btn btn-success btn-lg" value="Guardar"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</form>
</div>
</div>
<!--
<script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<!-- Google Analytics -->
<script>
$('#myform').validator()
var curp = generaCurp({
nombre : 'Juan',
apellido_paterno : 'Perez',
apellido_materno : 'Ramirez',
sexo : 'H',
estado : 'DF',
fecha_nacimiento : [31, 1, 1981]
});
console.log(curp);
</script><file_sep><?php
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$defensor = Array(
"id_cargo" =>4,
"nombre" =>'juan',
"apellido_paterno" =>'garcia',
"ap_materno" =>'lopez',
"curp" =>'CURP1234ABCD3214567',
"nup" =>'98783',
"nue" =>'89765',
"genero" =>'masculino',
"telefono" =>'9878787786',
"email" =>'<EMAIL>',
"puesto" =>'3',
"adscripcion" =>4,
"password" =>'<PASSWORD>'
);
$url='http://localhost/defensoriaPublica/controlador/defensor/registrar_Defensor.php';
$postfields = http_build_query( $defensor);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postfields,
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$this->assertEquals(200, intval($result));
}
}
?><file_sep><?php
// header('Content-Type: application/json');
//include '../../modelo/personal.php';
include '../../modelo/contraparte.php';
$listaContraparteEditar= getContraparteById($_GET['id_contraparte']);
echo json_encode($listaContraparteEditar);
?><file_sep><?php
//include '../../controlador/conexion.php';
//include '../../libreria/conexion.php';
include_once ('../../libreria/conexion.php');
function listar_personal(){
$sql="SELECT * FROM personal_campo inner join personal using(id_personal)
inner join juzgado using(id_juzgado)
inner join estudios using (id_personal)";
$lista=consulta($sql);
return $lista;
}
function listar_personalById($id_personal){
$sql="SELECT * FROM personal where id_personal= ".$id_personal;
$lista=consulta($sql);
return $lista;
}
//Definimos la funciones sobre el objeto crear_defensor
function crear_personal($objetoEntidad){
$sql ="select id_cargo from cargo where cargo='defensor'";
$idcargo= consulta($sql);
$sql = "INSERT INTO personal ";
$sql.= "SET id_cargo='".$objetoEntidad['id_cargo']."', nombre='".$objetoEntidad['nombre']."',";
$sql.= "ap_paterno='".$objetoEntidad['ap_paterno']."', ap_materno='".$objetoEntidad['ap_materno']."',";
$sql.= "curp='".$objetoEntidad['curp']."', calle='".$objetoEntidad['calle']."',";
$sql.= "numero_ext='".$objetoEntidad['numero_ext']."', numero_int='".$objetoEntidad['numero_int']."',";
$sql.= "colonia='".$objetoEntidad['colonia']."', municipio='".$objetoEntidad['municipio']."',";
$sql.= "nup='".$objetoEntidad['nup']."', nue='".$objetoEntidad['nue']."',";
$sql.= "genero='".$objetoEntidad['genero']."', telefono='".$objetoEntidad['telefono']."',";
$sql.= "correo_electronico='".$objetoEntidad['correo']."', foto='".$objetoEntidad['foto']."',";
$sql.= "etnia='".$objetoEntidad['etnia']."', idioma='".$objetoEntidad['idioma']."',";
$sql.= "rfc='".$objetoEntidad['rfc']."'";
//return consulta($sql, $conexion);
// echo $sql;
registro($sql);
}
//Definimos una funcion que acutualice al actualiza_defensor
function actualiza_personal($clientes){
global $conexion;
$sql = "UPDATE proveedor ";
$sql.= "SET id_juzgado='".$provedor['id_juzgado']."', id_estudio='".$provedor['id_estudio']."',";
$sql.= "numero_cedula_profesional='".$provedor['numero_cedula_profesional']."'";
return consulta($sql, $conexion);
}
//Definimos una funcion que borrar defensor
function borrar_personal($clientes){
global $conexion;
$sql = "DELETE proveedor ";
$sql.= "SET id_juzgado='".$provedor['id_juzgado']."', id_estudio='".$provedor['id_estudio']."',";
$sql.= "numero_cedula_profesional='".$provedor['numero_cedula_profesional']."'";
return consulta($sql, $conexion);
}
function ultimoPersonalCreatado(){
$sql = "SELECT MAX(id_personal) AS id FROM personal";
$id=consulta($sql);
// print_r($id);
return $id[0]['id'];
}
?>
<file_sep><?php
include '../../modelo/querys/informes.php';
if((isset($_POST['sistema']) && isset($_POST['materia']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos'])) ||
(isset($_POST['sistema']) && isset($_POST['region']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos'])) ||
(isset($_POST['sistema']) && isset($_POST['region']) && isset($_POST['materia']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']))||
(isset($_POST['sistema']) && isset($_POST['filtro']) && isset($_POST['check']) && isset($_POST['atributos']))){
$x = $_POST['filtro'];
switch($x){
case 'MATERIA':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$mat = $_POST['materia'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id=$_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaMatNotSystemDef($mat, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaMatSystemDef($sis, $mat, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaMatNotSystem($mat, $atrib);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaMatSystem($sis, $mat, $atrib);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'REGION':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$reg = $_POST['region'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id=$_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaRegNotSystemDef($reg, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaRegSystemDef($sis, $reg, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaRegNotSystem($reg, $atrib);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaRegSystem($sis, $reg, $atrib);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'AMBAS':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$reg = $_POST['region'];
$mat = $_POST['materia'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id= $_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaAmbasNotSystemDef($mat, $reg, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaAmbasSystemDef($sis, $mat, $reg, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaAmbasNotSystem($mat, $reg, $atrib);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaAmbasSystem($sis, $mat, $reg, $atrib);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
case 'NINGUNO':
$check = $_POST['check'];
$sis = $_POST['sistema'];
$atrib = $_POST['atributos'];
if($check=='true'){// por defensor
if(isset($_POST['id'])){
$id= $_POST['id'];
switch($sis){
case 'ALL':
$cons = consultaNingunoNotSystemDef($atrib, $id);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaNingunoSystemDef($sis, $atrib, $id);
$data = json_encode($cons);
echo $data;
break;
}
}
}else{//sin defensor y por materia
//$consulta = consultaMatSistema();
switch($sis){
case 'ALL':
$cons = consultaNingunoNotSystem($atrib);
$data = json_encode($cons);
echo $data;
break;
case 'TRADICIONAL' || 'ORAL':
$cons = consultaNingunoSystem($sis, $atrib);
$data = json_encode($cons);
echo $data;
break;
}
}
break;
}
}
?>
<file_sep> <title>Modulo Coordinador General</title>
<script src="../../recursos/js/main.js"></script>
<link rel="stylesheet" href="../../recursos/vendors/jquery/jquery-ui-themes-1.12.1/jquery-ui.css">
<!--
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<link href="../../recursos/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
<link href="../../recursos/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
<link href="../../recursos/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
<link href="../../recursos/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
<link href="../../recursos/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">
-->
<!-- <link href="../../recursos/css/style.css" rel="stylesheet"/>
-->
<!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
<script type="text/javascript" src="../../recursos/vendors/jquery/jquery-ui.js"></script>
<!-- <script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script>
--> <script src="../../recursos/js/administrador/atendiendoListarDefensor.js"></script>
<script src="../../recursos/js/main.js"></script>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<!-- <script type="text/javascript" src="../../recursos/vendors/jquery/jquery-ui.js"></script>
<link href="../../recursos/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Font Awesome -->
<link href="../../recursos/vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet"/>
<link href="../../recursos/css/custom.css" rel="stylesheet"/>
<script src="../../recursos/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../../recursos/js/main.js"></script><!--
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->
<!-- <link rel="stylesheet" href="/resources/demos/style.css"> -->
<script>
//$(document).ready(function () {
function tabla(){
//$('#example').DataTable();
$('#example').DataTable({
searching: false,
language: {
"decimal": "",
"emptyTable": "No hay datos",
"info": "mostrando _START_ a _END_ de _TOTAL_ pagina",
"infoEmpty": "mostrando 0 datos",
"infoFiltered": "(filtered from _MAX_ total entries)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "mostrar de _MENU_ paginas",
"loadingRecords": "Loading...",
"processing": "Processing...",
"search": "Buscar:",
"zeroRecords": "No matching records found",
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
}, "emptyTable": "No hay datos",
paginate: {
previous: 'Atras',
next: 'Siguiente'
},
aria: {
paginate: {
previous: 'Atras',
next: 'Siguiente'
}
}
},
}); $('.idPersonal').hide();
}
//});
</script>
<!-- <link href="../../recursos/css/style.css" rel="stylesheet"/>
-->
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><b>Lista de Defensores </b></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div id="datatable-responsive_wrapper" class="dataTables_wrapper form-inline dt-bootstrap no-footer">
<div class="row">
<div class="col-sm-6">
<div id="datatable-responsive_filter" class="dataTables_filter">
<label>Buscar por Defensor:
<input type="text" id="buscarCedula" onkeyup="buscarXCedula()" class="form-control" placeholder="Nombre Defensor..." aria-controls="datatable-responsive">
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div id="dialogo" title="Confirma eliminar"><span id="msnDialog" style="display:none"> Tiene al menos un expediente</span></div>
<table id="example" class="table nowrap ui table" cellspacing="0" width="100%">
<!-- <table id="example" class="table ui table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
-->
<!-- <table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap dataTable no-footer dtr-inline"
cellspacing="0" width="100%" role="grid" aria-describedby="datatable-responsive_info" style="width: 100%;">
--> <thead>
<tr role="row">
<th class="idPersonal">NUM</th>
<th>NOMBRE</th>
<th >A. PATERNO</th>
<th >A. MATERNO</th>
<th >LUGAR ADSCRIPCIÓN</th>
<th >ACCIONES</th>
</tr>
</thead>
<tbody id="tebody" >
<?php include '../../controlador/defensor/listatodosDefensores.php';
$defensores=json_decode($contenido);
//print_r($defensores);
foreach($defensores as $obj){
//print_r('=> '. $obj->estado);
if($obj->estado){
echo '<tr role="row" class="odd gradeA"> '. //OR oven || odd
'<td class="idPersonal" id="idPersonal" style="display:none; visibility:hidden;">'.$obj->id_personal.'</td>'.
'<td>'.strtoupper($obj->nombre).'</td>'.
'<td>'.strtoupper($obj->ap_paterno).'</td>'.
'<td>'.strtoupper($obj->ap_materno).'</td>'.
'<td>'.strtoupper($obj->juzgado).'</td>'.
'<td><button type="button" class="btn btn-primary botonExp" id="botonExp" name="expedientes">'.
'<span class="glyphicon glyphicon-th-list" title="Ver Expedientes"aria-hidden="true"> </span></button>'.
'<button type="button" class="btn btn-primary boton" id="boton" name="info">'.
'<span class="glyphicon glyphicon-user" title="Detalle del defensor"aria-hidden="true"> </span></button>'.
'<button type="button" class="btn btn-warning botonUp" id="botonUp" name="botonUp">'.
'<span class="glyphicon glyphicon-pencil" title="Editar Defensor" aria-hidden="true"></span></button>'.
'<button type="button" class="btn btn-danger botonDel" id="botonDel" name="botonDel">'.
'<span class="glyphicon glyphicon-trash" title="Dar de baja" aria-hidden="true"></span></button>'.
'</td> </tr>';
}
}
echo "<script> tabla() </script>"
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep><?php
include_once('../../modelo/defensor/juzgado.php');
$listaDef = listar_defensores();
$contenido = json_encode($listaDef);
?><file_sep><?php
include_once('../../controlador/defensor/controladorListaDef.php');
?>
<!-- ESTADISTICA Y HERRAMIENTAS MAS JQUERY UI-->
<script src="../../recursos/js/estadistica/atendiendoEstadistica.js"></script>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<script src="../../recursos/js/herramienta.js"></script>
<!-- PDFMAKE -->
<script src='../../recursos/vendors/pdfmake/build/pdfmake.min.js'></script>
<script src='../../recursos/vendors/pdfmake/build/vfs_fonts.js'></script>
<script src="../../recursos/js/coordinador/headerPDF.js"></script>
<!-- VALIDATOR Y CSS -->
<link href="../../recursos/css/custom.css" rel="stylesheet" />
<script src="../../recursos/js/jquery-validator.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
console.log( ' google');
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><b>Solicitar consulta de actividades<b></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br>
<form id="myform" data-toggle="validator" role="form" class="form-horizontal form-label-left" >
<label class="control-label " style="padding-left:300px;" >PERIODO
</label><br>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Fecha Inicio <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="date" id="inputInicio" required="required" data-error="Seleccione una fecha valida." class="form-control controlFecha" data-error="Debe ser menor a la fecha Final." name="inputInicio" onblur="myFunctionDate(this)" onkeyup="myFunctionDate(this)" step="1">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Fecha Final <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="date" id="inputFinal" name="inputFinal" required="required" data-error="Seleccione una fecha valida." class="form-control controlFecha" onblur="myFunctionDate(this)" onkeyup="myFunctionDate(this)" step="1">
<div class="help-block with-errors"></div>
<div id="labelFinal" class='block-help with-errors'></div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Sistema <span class="required">*</span>
</label>
<div class="col-md-4 col-sm-6 col-xs-12">
<select required="required" id="selectSistema" name="selectSistema" data-error="Seleccione un sistema." aria-controls="datatable-responsive" class="form-control input-sm" onchange="myFunctionDate(this.value)">
<option value="">Seleccione un sistema</option>
<option value="TRADICIONAL">Tradicional</option>
<option value="ORAL">Acusatorio y Oral</option>
<option value="JUSTICIA">Justicia para Adolecentes</option>
<option value="ALL">Todos</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group" id="checkDefensor" name="checkDefensor">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">Defensor en especifico? </label>
<div class="col-sm-1 ">
<input type="checkbox" unchecked id="checkDefensor" name="checkDefensor" class="form-control" onchange="seleccionarUnDefensor(this)" >
</div>
<div id="idCheckDefensor" name="idCheckDefensor" style="display:none;">
<div class="col-md-6 col-sm-6 col-xs-12">
<input data-error="Seleccione un defensor" type="text" id="project" required class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div>
</div>
<div class="form-horizontal form-label-left">
<div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue"><span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<table required="" id="tablaAsinacionExpedienteusuario" class="table table-striped ">
<tbody required="" id="usuarioSeleccionados" style="height: 200px; width:915px; overflow: auto;" class=" ui-widget-content"></tbody></table>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<input type="text" name="usuarios" id="usuarios" style="display:none;" class="form-control col-md-7 col-xs-12"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Consultas <span class="required">*</span>
</label>
<div class="col-md-4 col-sm-6 col-xs-12">
<select required="required" id="selectConsulta" name="selectConsulta" data-error="Seleccione un sistema." aria-controls="datatable-responsive" class="form-control input-sm" onchange="myFunctionDate(this.value)">
<option value="">Seleccione una consulta para las actividades</option>
<option value="NUM">Numero de actividades realizadas</option>
<option value="C2">Consulta2</option>
<option value="C3">Consulta3</option>
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row no-print">
<div class="col-xs-12">
<button class="btn btn-success pull-right" id="botonDesc" name ="botonDesc" disabled onclick="solicitarConsultaAct();" style="margin-right: 5px;">
<i class="fa fa-download"></i> Realizar consulta</button>
</div>
</div>
</form>
</div>
<div id="resultadoConsulta" name="resultadoConsulta" >
<div id="chart_div"></div>
</div>
</div>
</div>
<script src="../../recursos/js/jquery-validator.js"></script>
<script>
cargarInputDefensor();
$('#myform').validator();
</script>
<file_sep><?php
include_once('../../modelo/defensor/defensor.php');
$listaDef = listar_defensores();
$contenido = json_encode($listaDef);
if(isset($_GET['term'])){//muestro todo los usuario para las busquedas del defensor
echo $contenido;
}
?><file_sep><?php
// header('Content-Type: application/json');
//include '../../modelo/personal.php';
include '../../modelo/contraparte.php';
include '../../modelo/detalleContraparteExpediente.php';
include '../../libreria/herramientas.php';
$hoy = getdate();
$edadNumero=$hoy['year']-intval($_POST['fechaNacimiento']);
$usuario = Array(
"id_contraparte" =>$_POST['id_contraparte'],
"nombre" =>$_POST['nombre'],
"ap_paterno" =>$_POST['apellido_paterno'],
"ap_materno" =>$_POST['apellido_materno'],
"telefono" =>$_POST['telefono'],
"correo" =>$_POST['email'],
"calle" =>$_POST['calle'],
"numero_int" =>$_POST['calle'],
"numero_ext" =>"",
"colonia" =>$_POST['colonia'],
"municipio" =>$_POST['municipio'],
"curp" =>$_POST['curp'],
"estado" =>$_POST['estado'],
"edad" =>$edadNumero,
"fecha_nacimiento" =>$_POST['fechaNacimiento'],
"etnia" =>$_POST['etnia'],
"idioma" =>$_POST['idioma'],
"genero" =>$_POST['genero'],
"sexo" =>$_POST['sexo'],
"discapacidad" =>$_POST['discapacidad']
);
$detalle_contraparte=Array(
'id_expediente'=> $_POST['id_expediente'],
'id_contraparte'=>$_POST['id_contraparte'],
'tipo_contraparte'=>$_POST['tipo_contraparte'],
'parentesco'=>$_POST['parentesco']
);
//print_r($usuario);
//print_r($detalle_contraparte);
$usuario = array_map( "cadenaToMayuscula",$usuario);
$mensaje=['tipo'=>"error",
'mensaje'=>"este usuario ya se encuentra registrado en tu expediente"];
$dirigir="";
//sprint_r (getDefensorByCurp($_POST['curp']));
if(getContraparteById($_POST['id_contraparte'])==0){
crear_contraparte($usuario); //regresa 1 si regristro para validar tambien par validar si ya exite o res regisro correctamente
// alta_DetalleContraparte($detalle_contraparte);
}
if(getDetalleByContraparteAndExpediente($_POST['id_contraparte'],$_POST['id_expediente'])==0){
alta_DetalleContraparte($detalle_contraparte);
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"
];
}
//print_r($usuario);
if(!isset($_GET['tipo'])){
session_start();
print_r(json_encode($mensaje));
//$_SESSION['dirigir']=$dirigir;
// header("location: ../../vistas/defensor/index.php");
}
else{
echo "json";
}
?><file_sep><?php
function holaMundo(){
return 200;
}
?><file_sep><?php
include_once("../libreria/conexion.php");
/* function datosBasico($nue){
$sql='select id_personal,nombre,ap_paterno,ap_materno,curp,nup,nue,foto,materia,sistema,instancia
from personal inner join personal_campo using(id_personal)
inner join materia using(id_materia) where nue ='.$nue;
return consulta($sql);
} */
function datosBasico($user){
$sql='select id_personal,nue,nup,materia,sistema,instancia,id_materia
from personal inner join personal_campo using(id_personal)
inner join materia using(id_materia) where id_personal ='.$user;
return consulta($sql);
}
$datos=datosBasico($_GET['personal']);
echo json_encode($datos);
?><file_sep><?php
include_once('../../modelo/respuesta/respuesta.php');
include '../../libreria/herramientas.php';
$respuesta = Array(
"id_respuesta" =>$_POST['id_respuesta'],
"respuesta" =>$_POST['respuesta'],
"observaciones" =>$_POST['observacion'],
"accion_implementar" =>$_POST['accion_implementar']
);
//$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
//if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
//print_r($respuesta);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);/// convierte todo a mayusculas
{actualizarRespuestaPregunta($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Actualizacion exitoso"];
// echo "el registro es exitoso" ;
}
echo json_encode($mensaje);
/* else
echo "el registro ya existe";
*/
?><file_sep>$("#fileToUpload").change(function(){
$("butonUpdate").prop("disabled", this.files.length == 0);
});<file_sep><?php
include_once('../../modelo/conteo/pregunta.php');
//header('Content-Type: application/json');
$respuesta = Array( );
$respuestaOperacion;
// principalMateria(10,'',''); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
function constructorSistema($sistema,$fechaInicio,$fechaFinal){
$thisSistema=strtoupper ($sistema);
$thisFechaInicio='';
$thisFechaFinal='';
if(($fechaInicio!=""|$fechaInicio!=" ")&($fechaInicio!=" "|$fechaInicio!=""))
$thisFechaInicio=$fechaInicio;
if(($fechaFinal!=""|$fechaFinal!=" ")&($fechaFinal!=" "|$fechaFinal!=""))
$thisFechaFinal=$fechaFinal;
realizandoOperacionSistema($thisSistema,$thisFechaInicio,$thisFechaFinal);
}
function realizandoOperacionSistema($sistema,$fechaIncio,$fechaFinal){
//principalSistema('ORAL','',''); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
principalSistema($sistema,$fechaIncio,$fechaFinal); // PRIMERO CREAMOS LA VISTA EL CUAL SERA CONSUMIDO
//$preguntas=preguntasMateria(10);
// $preguntas=preguntasSistema('ORAL');// SIEMPRE MANDARLO EN MAYUSCULAS
$preguntas=preguntasSistema($sistema);// SIEMPRE MANDARLO EN MAYUSCULAS
$equals="";
foreach ($preguntas as $key => $value) {
if($value['pregunta']!=$equals){
$equals=$value['pregunta'];
$Arrayvalor =Array(); $array=Array();
// $array['datosGenerale']=fintrarPorPregunta($value['pregunta'],10);
$Arrayvalor=filtrarPorPreguntaSistema($value['pregunta'],' ',' ');
// print_r($Arrayvalor);
//$filtratoPorOpcion=filtralPorRespuestaSistema($array['datosGenerales'],$valor['opcion']);
if($Arrayvalor!='0'){
$discapacidades=array_column( $Arrayvalor,'discapacidad');
$etnias=array_column( $Arrayvalor,'etnia');
$idioma=array_column( $Arrayvalor,'idioma');
$arrayGenerales['sexo']=array_count_values(array_column( $Arrayvalor,'sexo'));
// $arrayGenerales['idioma']=array_count_values(array_column( $Arrayvalor,'idioma'));
// $arrayGenerales['discapacidad']=array_count_values(array_column( $Arrayvalor,'discapacidad'));
$arrayGenerales['discapacidad']=filtradoGeneralesSistema('discapacidad',$discapacidades,$value['pregunta']);
$arrayGenerales['etnias']=filtradoGeneralesSistema('etnia',$etnias,$value['pregunta']);
$arrayGenerales['idiomas']=filtradoGeneralesSistema('idioma',$idioma,$value['pregunta']);
$arrayGenerales['generos']=array_count_values(array_column( $Arrayvalor,'genero'));
$arrayGenerales['respuesta']=array_count_values(array_column( $Arrayvalor,'respuesta'));
// print_r($arrayGenerales);
// print_r($Arrayvalor);
$array['datosGenerales']=$arrayGenerales;
if($value['identificador']=="select"){
$arrayOpcion=Array();
$opciones=opcionesPorMateria($value['id_pregunta']);
foreach ($opciones as $llave => $valor) {
$filtratoPorOpciones=filtralPorRespuestaSistema($Arrayvalor,$valor['opcion']);
$filtratoPorOpcion['sexo']=array_count_values(array_column( $filtratoPorOpciones,'sexo'));
$filtratoPorOpcion['idioma']=array_count_values(array_column( $filtratoPorOpciones,'idioma'));
$filtratoPorOpcion['discapacidades']=array_count_values(array_column( $filtratoPorOpciones,'discapacidad'));
$filtratoPorOpcion['etnias']=array_count_values(array_column( $filtratoPorOpciones,'etnia'));
$valores=$filtratoPorOpcion;
$arrayOpcion[$valor['opcion']]=$valores;
}
$array['opciones']=$arrayOpcion;
}
}
$respuesta[$value['pregunta']]=$array;// SE GUARDA EL VARLOR DE CADA UNO DE LAS PREGUNTAS
global $respuestaOperacion;
$respuestaOperacion=$respuesta;// SE GUARDA EL VARLOR DE CADA UNO DE LAS PREGUNTAS
}//final del if
}
}//FIN DE LA FUNCION REALIZANDO OPERACION
//print_r( $respuesta);
function getRespuestaSistema(){
global $respuestaOperacion;
return $respuestaOperacion ;
}
/* $array = array (1, 3, 3, 5, 6);
$my_value = 3;
$filtered_array = array_filter($array, function ($element) use ($my_value) { return ($element != $my_value); } );
*/
function filtralPorRespuestaSistema($array,$opcion){
return array_filter($array,function($respuesta) use ($opcion){
return ($respuesta['respuesta']==$opcion);
});
}
function funcionPerezosoSistema(array $arr, $pregunta,callable $fn)
{
$arrayFiltrados=Array();
if($arr!=0)
foreach ($arr as $key => $valores) {
$retornoFucnion=$fn($valores,$pregunta);
$arrayFiltrados[$valores]=funcionContadoSexoSistema($retornoFucnion);
}
return $arrayFiltrados;
}
function funcionContadoSexoSistema($arr)
{ $arrays=Array();
if($arr!=0){
foreach ($arr as $key => $valores) {
$arrays[$valores['sexo']]=$valores['tsexo'];
}
}
return $arrays;
}
function filtradoGeneralesSistema($filtraPor,$array,$pregunta){
$funcionALLamar;
switch ($filtraPor) {
case 'idioma':
// return funcionPerezosoSistema( $array, $pregunta,filtradoPorIdioma($valores,$pregunta));
return funcionPerezosoSistema( $array, $pregunta,'filtradoPorSistemaIdioma');
break;
case 'etnia':
//return funcionPerezosoSistema( $array, $pregunta,filtradoPorSistemaEtnia($valores,$pregunta));
return funcionPerezosoSistema( $array, $pregunta,"filtradoPorSistemaEtnia");
break;
case 'discapacidad':
return funcionPerezosoSistema( $array, $pregunta, 'filtradoPorSistemaDiscapacidad');
break;
default:
# code...
break;
}
}
?><file_sep><?php
//include_once( '../../controlador/juzgado/actividad_juzgado.php');
include_once( '../../controlador/defensor/controladorListaDef.php');
session_start();
// print_r($_SESSION['personal']);
$id_personal = $_SESSION['personal'][0]['id_personal'];
$nombre = $_SESSION['personal'][0]['nombre'];
//echo $id_personal;
//echo $nombre;
?>
<script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script>
<script src="../../recursos/js/herramienta.js"></script>
<script>
function cargaDefensorPorMateria(e, elemento) {
/* $.ajax({
url: "../../controlador/defensor/controlDefensor.php",
type: "GET",
data: "materia="+elemento.options[elemento.selectedIndex].value,
beforeSend: function () {
// $('#menuContainer').load('listarDefensores.php');
},
success: function (data) {
//console.log('Success!! Eliminado defensor id = '+idDef);
// console.log(data);
var json=jQuery.parseJSON(data)
$("#asignarDefensor").children().remove();
$.each(json,function(key, valor) {
$("#asignarDefensor").append("<option value="+valor.id_personal+">"+valor.nombre+" "+valor.ap_paterno+" "+valor.ap_materno+" </option>");
console.log(valor);
});
}
}); */
}
function validarFecha(e, elemento) {
var fechas= document.getElementById("fecha_registro").value;
//console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
var date = new Date()
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
return false;
}
if(ano <date.getFullYear() || ano > date.getFullYear())
{
console.log(" año invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="año invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(mes < date.getMonth()+1 || mes > date.getMonth()+1)
{
console.log("mes invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Mes invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(dia < date.getDate()-5 || dia > date.getDate())
{
console.log("fecha invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Dia invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
console.log( date.getYear());
}
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Registro Actividad</label></h1>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form id="myform" data-toggle="validator"enctype="multipart/form-data" role="form" class="" action ="../../controlador/actividad/registroActividad.php?tipo=html" object="defensor" method="post">
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="curp">Curp de usuario<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" minlength="18" data-error="formato invalido" data-error="fecha invalida" maxlength="18" name="curp" id="curp" required="required" class="form-control col-md-7 col-xs-12" pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)">
<div class="help-block with-errors"></div></div>
</div>
</div>
<div class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " >Fecha de actividad <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="fecha_registro" type="date" onkeyup="validarFecha(event,this)" onblur="validarFecha(event,this)" data-error="fecha invalido" pattern="" data-error="fecha invalida" maxlength="50" class="form-control" required="" placeholder="Email" name="fechaRegistro">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!-- se requiere para identificar el tipo de actividad -->
<div id="actividad" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " >Actividad <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<select id="miactividad" required="" name="actividad" class="form-control " onblur="verificacionActividad(event,this)">
<option value="asesoria"> Asesoría</option>
<option value="visita">Visita carcelaria</option>
<option value="audiencia"> Audiencia</option>
</select>
</div>
</div> </div>
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Resultado u observación<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="textArea" name="resultado" minlength="10" maxlength="200" name="expediente" id="expediente" class="form-control col-md-7 col-xs-12">
--> <textarea id="resultado" name="resultado" onclick="verificacionActividad()" pattern="[a-z0-9.,:áéíóú ]+" data-error="solo numeros o letras en minisculas con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describre el resultado u observaciones"></textarea>
<div class="help-block with-errors"></div>
</div></div></div>
<div id="mycomprobante" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="comprobante" class="control-label col-md-3 col-sm-3 col-xs-12 " >Comprobante <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input data-error="" data-error="fecha invalida" maxlength="50" class="form-control" placeholder="cargar archivo" name="comprobante">
<input id="comprobante" class="inputfile" type="file" id="comprobante" name ="comprobante">
--> <input type="file" name="archivo" id="archivo"></input>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!--// se requiere para identificar al personal -->
<div id="personal" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " ></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="id_personal" type="text" name="id_personal" required="required" class="form-control col-md-7 col-xs-12" value="<?php echo $id_personal?>">
</div>
</div> </div>
<!--// se requiere para la ubicacion -->
<div id="myubicacion" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " ></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="ubicacion" type="text" name="ubicacion" class="form-control col-md-7 col-xs-12" value="" >
</div>
</div> </div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="asignarAdscripcion" type ="submit" class="btn btn-succes btn btn-success btn-lg" value="Registrar Actividad"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</div>
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/actividad/gestionActividad.js"></script>
<script>
$('#myform').validator()
$('#myubicacion').hide()
$('#personal').hide()
$('#mycomprobante').hide()
$('#resultado').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
</script><file_sep><?php
//include '../../controlador/conexion.php';
//include '../../libreria/conexion.php';
include_once ('../../libreria/conexion.php');
//Definimos la funciones sobre el objeto crear_defensor
function crear_usarioSistema($objetoEntidad){
$sql ="select id_cargo from cargo where cargo='defensor'";
$idcargo= consulta($sql);
$sql = "INSERT INTO usuario_sistema ";
$sql.= "SET username='".$objetoEntidad['username']."', password='".$objetoEntidad['password']."',";
$sql.= "estado=1";
//return consulta($sql, $conexion);
//echo $sql;
registro($sql);
}
//Definimos una funcion que acutualice al actualiza_defensor
function actualiza_usarioSistema($clientes){
global $conexion;
$sql = "UPDATE usuario_sistema ";
$sql.= "SET id_juzgado='".$provedor['id_juzgado']."', id_estudio='".$provedor['id_estudio']."',";
$sql.= "numero_cedula_profesional='".$provedor['numero_cedula_profesional']."'";
return consulta($sql, $conexion);
}
//Definimos una funcion que borrar defensor
function borrar_usarioSistema($clientes){
global $conexion;
$sql = "DELETE proveedor ";
$sql.= "SET id_juzgado='".$provedor['id_juzgado']."', id_estudio='".$provedor['id_estudio']."',";
$sql.= "numero_cedula_profesional='".$provedor['numero_cedula_profesional']."'";
return consulta($sql, $conexion);
}
function ultimousarioSistemaCreatado(){
$sql = "SELECT MAX(id_personal) AS id FROM personal";
$id=consulta($sql);
// print_r($id);
return $id[0]['id'];
}
?>
<file_sep><?php
require_once("modelo/defensor.php");
require_once("modelo/materia.php");
require_once("modelo/usuario_servicio.php");
require_once("modelo/expediente.php");
require_once("modelo/siguimiento_caso.php");
?>
<file_sep><?php
include_once('../../modelo/expediente.php');
//header('Content-Type: application/json');
if(isset($_GET['conOpcion'])) {
// $user = listar_preguntaConOpciones(9);
$user = listar_preguntaConOpciones($_GET['id_materia'],$_GET['id_expediente']);
//echo $_GET['id_materia'];
//foreach($user as $valor){
$newUser=array_filter($user, "noConstestadas");//FILTRO A TODO LOS QUE NO TIENEN RESPUESTA
//}
$pregunta = Array( );
$equals="";
foreach($newUser as $values){
// print_r($values['pregunta']);
// print_r( $values);
if($values['id_pregunta_materia']!=$equals){
$equals=$values['id_pregunta_materia'];
$valor =Array();
$valorOpcion =Array();
$valor['id_pregunta']=$values['id_pregunta'];
$valor['id_pregunta_materia']=$values['id_pregunta_materia'];
$valor['pregunta']=$values['pregunta'];
$valor['identificador']=$values['identificador'];
$valor['opcion']="";
}
if($values['opcion']=="")
$valorOpcion="";
else
array_push($valorOpcion, $values['opcion']);
$valor['opcion']=$valorOpcion;
// array_push($pregunta,$valor);
$pregunta[$values['id_pregunta_materia']]=$valor;
}
echo json_encode($pregunta);
}
if(isset($_GET['preguntas'])){//ESTE ERA SOLO PARA CUANDO SE REQUERIA LAS PREGUNTAS SIN LAS OPCIONES
//echo json_encode(listar_pregunta(9));
echo json_encode(listar_pregunta($_GET['id_materia']));
}
//echo "hola desde el controlador de preguntas";
//print_r($pregunta);
function noConstestadas($var){
return ($var['respuesta']=="");
}
?><file_sep><?php
header('Content-Type: application/json');
if(isset($_GET['consultaPor']))
if($_GET['consultaPor']=="defensor"){
include_once('../../controlador/estadistica/consultaDefensor.php');
tipoconstructor($_GET['defensor'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$pordefensor = getRespuesta();
echo json_encode($pordefensor);
}
if($_GET['consultaPor']=="sistema"){
include_once('../../controlador/estadistica/consultaSistema.php');
constructorSistema($_GET['sistema'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$pordefensor = getRespuestaSistema();
echo json_encode($pordefensor);
}
if($_GET['consultaPor']=="materia"){
include_once('../../controlador/estadistica/consultaMateria.php');
constructorMateria($_GET['materia'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$pordefensor = getRespuestaMateria();
echo json_encode($pordefensor);
}
if($_GET['consultaPor']=="sistemaMateria"){
include_once('../../controlador/estadistica/consultaSistemaMateria.php');
constructorSistemaMateria($_GET['sistema'],$_GET['materia'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$porsistemaMateria = getRespuestaSistemaMateria();
//print_r($porsistemaMateria);
echo json_encode($porsistemaMateria);
}
if($_GET['consultaPor']=="regionSistemaMateria"){
include_once('../../controlador/estadistica/consultaRegionSistemaMateria.php');
tipoconstructorRegionSistemaMateria($_GET['region'],$_GET['sistema'],$_GET['materia'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$porRegionSistemaMateria = getRespuestaRegionSistemaMateria();
//print_r($porsistemaMateria);
echo json_encode($porRegionSistemaMateria);
}
/* function getSistema(){
include_once('../../controlador/estadistica/consultaSistema.php');
//constructorSistema($_GET['sistema'],$_GET['fechaInicio'],$_GET['fechaFinal']);
//$pordefensor = getRespuestaSistema();
//return json_encode($pordefensor);
}
function getMateria(){
include_once('../../controlador/estadistica/consultaMateria.php');
constructorMateria($_GET['materia'],$_GET['fechaInicio'],$_GET['fechaFinal']);
$pordefensor = getRespuestaMateria();
echo json_encode($pordefensor);
} */
?><file_sep><?php
include '../../controlador/juzgado/actividad_juzgado.php';
?>
<script>
function cerrar(){
$('#registroContraparte').children().remove();
}
</script>
<script src="../../recursos/js/herramienta.js"></script>
<script>
var isNino=false;
var isFamiliar=false;
function validarFecha(e, elemento) {
var fechas= document.getElementById("fechaNacimiento").value;
console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
// var date = new Date(ano,mes,dia)
var date = new Date()
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
// $(".with-errors").append("<ul class='list-unstyled'><li>solo 4 digito en el a</li></ul>");
console.log("joijoiuiu");
return false;
}
// var anioMaximo=2000;//aplicando para adultos
// var anioMinimo=1937;// año minimo apliando para adultos
var anioMaximo=80;//aplicando para adultos
var anioMinimo=18;// año minimo apliando para adultos
if(isNino===true){
anioMaximo=17;//aplicando para ni;o
anioMinimo=05;// año minimo apliando para ni;o
}
console.log("is niño", isNino);
// if(ano <= (date.getFullYear()-5) || ano > 1998)
if(ano < (date.getFullYear()-anioMaximo) || ano >(date.getFullYear()-anioMinimo))
{
console.log("fecha que maximo", (date.getFullYear()-anioMaximo));
console.log("fecha que se minimo", (date.getFullYear()-anioMinimo));
console.log("fecha invalida");
// alert("Seleccione correctame el tipo de usuario a registrar")
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="fecha invalida";
error.appendChild(ul);
//alert("Es necesario que el año de la Fecha de Nacimiento, se encuentre entre " + (dtmHoy.getFullYear() - 120)+ " y " + dtmHoy.getFullYear())
// document.ejemploForma.stranio.focus()
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
}
var datosDelUsuario=JSON.parse(Global_user_basic)[0];
$("#divNino").hide();
$("#divEjecucion").hide();
$("#divFamiliar").hide();
if(datosDelUsuario.materia==="FAMILIAR"&datosDelUsuario.instancia==="1"){
$("#divNino").show();
var isFamiliar=$("#isNino").val();
$(function() {
$('#isNino').change(function() {
isNino=$(this).prop('checked');
console.log("es nino? ",$(this).prop('checked'));
validarFecha(null,document.getElementById('fechaNacimiento'));
})
})
}
if(datosDelUsuario.materia==="EJECUCION"){
$("#divEjecucion").show();
$(function() {
$('#isFamiliar').change(function() {
isFamiliar=$(this).prop('checked');
$("#divFamiliar").hide();
if(isFamiliar)
$("#divFamiliar").show();
// console.log("es familiar ",$(this).prop('checked'));
})
})
}
function validarCurps() {
// pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)";
var curpNombre=document.getElementById("nombre").value;
console.log("el nombre es ",curpNombre);
var curpApaterno=document.getElementById('aPaterno').value;
var curpAmaterno=document.getElementById('aMaterno').value;
var curpGenero=(((document.getElementById("sexo").options[document.getElementById("sexo").selectedIndex].value)==="masculino")?'H':'M');
var curpFecha= document.getElementById("fechaNacimiento").value.split('-');
//var fechas= document.getElementById("fecha").value;
var entidad=document.getElementById("entidad").options[document.getElementById("entidad").selectedIndex].value;
console.log(entidad);
var curp = generaCurp({
nombre : curpNombre,
apellido_paterno : curpApaterno,
apellido_materno : curpAmaterno,
sexo : curpGenero,
estado : entidad,
fecha_nacimiento : [curpFecha[2],curpFecha[1],curpFecha[0]]
});
console.log(curp.substr(0,13));
var claseCurp=document.getElementById("curp");
claseCurp.value=curp;
claseCurp.setAttribute("pattern",curp.substr(0,13)+'[A-Za-z]{3}[0-9]{2}');
var id_contraparte=document.getElementById("id_contraparte");
id_contraparte.value=curp
}
</script>
<script src="../../recursos/js/expediente/registrarContraparte.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Registro usuario de contraparte</label></h1>
<ul class="nav navbar-right panel_toolbox">
<li class="dropdown">
<button type="" onclick="cerrar()"><a class="close-link"><i class="fa fa-close"></i></a></button>
</li>
<li>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12"></label>
<div class="col-md-9 col-sm-9 col-xs-12">
<div class="" id="divNino">
<label>
<style> .toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<input type="checkbox" id="isNino" data-toggle="toggle" data-style="ios"> NIÑO(A)/ADOLECENTES?
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12"></label>
<div class="col-md-9 col-sm-9 col-xs-12">
<div class="" id="divEjecucion">
<label>
<style> .toggle.ios, .toggle-on.ios, .toggle-off.ios { border-radius: 20px; }
.toggle.ios .toggle-handle { border-radius: 20px; }
</style>
<input type="checkbox" id="isFamiliar" data-toggle="toggle" data-style="ios"> Es familiar?
</label>
</div>
</div>
</div>
<br/>
<!-- <form id="myform" data-toggle="validator" role="form" class="form-horizontal form-label-left" action ="../../controlador/expediente/registrarContraparte.php" object="defensor" method="post">
--> <form id="myform" name="formcontraparte" data-toggle="validator" role="form" class="form-horizontal form-label-left" object="defensor">
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Nombre<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="nombre" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ ]+" onkeyup="mayusculas(event, this)" maxlength="40" minlength="4" autofocus="autofocus" required class="form-control text-uppercase" data-error="se letras no máximo de 40 ni mánimo de 4" placeholder="Nombre" name="nombre">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >calle<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="calle" type="text" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" onkeyup="mayusculas(event, this)" maxlength="50" minlength="4" data-error=": solo palabras de minimo 4 carácter "class="form-control" required placeholder="" name="calle">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Apellido Paterno<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aPaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Paterno" name="apellido_paterno">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 "> Número<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" pattern="[1-9][0-9]*" maxlength="5" id="numero" minlength="1" data-error="solo numero intero con maxicmo 5 digito" class="form-control" required placeholder="" name="numero">
<div class="help-block with-errors"></div></div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-1 " >Apellido Materno<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="aMaterno" pattern="[a-zA-ZéėíóúūñÁÉÍÓÚÜÑ]+" onkeyup="mayusculas(event, this)" data-error="solo letras no máximo de 40 ni mánimo de 4" autofocus="autofocus" maxlength="40" minlength="4" required class="form-control text-uppercase" placeholder="Apellido Materno" name="apellido_materno">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Email<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="email" type="text" data-error="correo invalido" class="form-control" pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$" required placeholder="Email" name="email">
<div class="help-block with-errors"></div></div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Entidad federativa de nacimiento<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select id="entidad" name="estado" required class="select2_group form-control textbox">
<option value="">- Seleccione -</option>
<option value="AS">AGUASCALIENTES</option>
<option value="BC">BAJA CALIFORNIA</option>
<option value="BS">BAJA CALIFORNIA SUR</option>
<option value="CC">CAMPECHE</option>
<option value="CL">COAHUILA DE ZARAGOZA</option>
<option value="CM">COLIMA</option>
<option value="CS">CHIAPAS</option>
<option value="CH">CHIHUAHUA</option>
<option value="DF">DISTRITO FEDERAL</option>
<option value="DG">DURANGO</option>
<option value="GT">GUANAJUATO</option>
<option value="GR">GUERRERO</option> <option value="HG">HIDALGO</option> <option value="JC">JALISCO</option> <option value="MC">MEXICO</option> <option value="MN">MICHOACAN DE OCAMPO</option> <option value="MS">MORELOS</option> <option value="NT">NAYARIT</option> <option value="NL">NUEVO LEON</option> <option value="OC">OAXACA</option> <option value="PL">PUEBLA</option> <option value="QT">QUERETARO DE ARTEAGA</option> <option value="QR">QUINTANA ROO</option> <option value="SP">SAN LUIS POTOSI</option> <option value="SL">SINALOA</option> <option value="SR">SONORA</option> <option value="TC">TABASCO</option> <option value="TS">TAMAULIPAS</option> <option value="TL">TLAXCALA</option> <option value="VZ">VERACRUZ</option> <option value="YN">YUCATAN</option> <option value="ZS">ZACATECAS</option> <option value="NE">NACIDO EN EL EXTRANJERO</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 " >Teléfono<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="telefono" type="text"pattern="([0-9]{13})|([0-9]{10})" class="form-control " data-error=": solo numero telefonico" required placeholder="" name="telefono">
<div class="help-block with-errors"></div> </div>
</div>
<div class=" form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label for="inputEmail" class="control-label col-md-4 col-sm-3 col-xs-12 " >Fecha nacimiento<span class="required">*</span></label>
</h4><div class="col-md-8 col-sm-9 col-xs-12">
<input id="fechaNacimiento" type="date" onmouseout="validarFecha(event,this)" data-error="fecha invalido" pattern="" data-error="fecha invalida" maxlength="50" class="form-control" required="" placeholder="Fecha" name="fechaNacimiento">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="item form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Curp<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" id="curp" onkeyup="mayusculas(event, this)" onblur="validarCurps()" tidata-error=": el formato debe ser alfanumerico con 18 digitos" maxlength="18" pattern=""class="form-control text-uppercase" required placeholder="curp" name="curp">
<div class="help-block with-errors"></div> </div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Sexo<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select required id="sexo" onkeyup="validarCurps()" onblur="validarCurps()" name="sexo" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="masculino">masculino</option>
<option value="femenino">femenino</option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Género<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select novalidate id="genero" onkeyup="validarCurps()" onblur="validarCurps()" name="genero" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="lesbico">Lésbico</option>
<option value="gay">Gay</option>
<option value="bisexual">Bisexual</option>
<option value="transexual">Transexual</option>
<option value="Transgenero">Transgénero</option>
<option value="Travesti">Travesti </option>
<option value="Intersexual">Intersexual </option>
<option value="Ninguno">Ninguno </option>
</select>
</div>
</div>
<!-- <div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Municipio<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input onkeyup="mayusculas(event, this)" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="municipio">
</div>
</div> -->
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Código postal<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<input id="codigoPostal" type="text" data-error="solo numeros" pattern="[0-9 ]+" onmouseout="consumirCodigoPostal(this)" maxlength="10" minlength="1" class="form-control text-uppercase" required placeholder="" name="codigoPostal">
<div class="help-block with-errors"></div>
</div></div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Discapacidad<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select required id="discapacidad" name="discapacidad" data-error="solo numeros" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="sensorial">Discapacidades sensoriales y de la comunicación</option>
<option value="motrices"> Discapacidades motrices</option>
<option value="mental"> Discapacidades mentales</option>
<option value="multiples"> Discapacidades multiples </option>
<option value="ninguno"> Ninguno </option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Municipio<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input onkeyup="mayusculas(event, this)" id="municipio" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="municipio">
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Etnia</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<select novalidate id="etnia" name="etnia" class="select2_group form-control">
<option value="">- Seleccione -</option>
<option value="MIXTECO">MIXTECO</option>
<option value="ZAPOTECO">ZAPOTECO</option>
<option value="AMUZGOS">AMUZGOS</option>
<option value="CHATINO">CHATINO</option>
<option value="CHINANTECOS">CHINANTECOS</option>
<option value="CHOCHOL">CHOCHOL </option>
<option value="CHONTALES">CHONTALES </option>
<option value="CUICATECOS">CUICATECOS </option>
<option value="HUAVES">HUAVES </option>
<option value="IXCATECOS">IXCATECOS </option>
<option value="MAZATECOS ">MAZATECOS </option>
<option value="MIXE">MIXE </option>
<option value="NAHUA">NAHUA </option>
<option value="TRIQUI">TRIQUI </option>
<option value="ZOQUES">ZOQUES </option>
<option value="CHOCHOLTECOS">CHOCHOLTECOS </option>
<option value="TACUATES">TACUATES </option>
<option value="AFROMEXICANO">AFROMEXICANO </option>
<option value="AFROMESTIZOS">AFROMESTIZOS </option>
<option value="TZOTZILES">TZOTZILES </option>
<option value="POPOLOCA">POPOLOCA </option>
<option value="NINGUNO">NINGUNO </option>
</select>
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md-4 col-sm-3 col-xs-12 ">Colonia<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input type="text" onkeyup="mayusculas(event, this)" id="colonia" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="colonia">
</div>
</div>
<div class="form-group col-md-6 col-sm-6 col-xs-12 form-group ">
<h4><label class="control-label col-md-4 col-sm-3 col-xs-12 ">Idioma/lengua</label>
</h4> <div class="col-md-8 col-sm-9 col-xs-12">
<input id="idioma" onkeyup="mayusculas(event, this)" type="text" data-error=": solo letras de maximo 50 caracter" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" maxlength="50" minlength="3" class="form-control text-uppercase" required placeholder="" name="idioma">
</div>
</div>
<div id="divFamiliar" class="form-group col-md-7 col-sm-6 col-xs-12 form-group ">
<h4> <label class="control-label col-md- col-sm-3 col-xs-12 ">Tipo de parentesco<span class="required">*</span></label>
</h4> <div class="col-md-8 col-sm-8 col-xs-12">
<select required id="parentesco" name="parentesco" class="select2_group form-control">
<option value="NINGUNO">- Seleccione -</option>
<option value="HIJO">Hijo</option>
<option value="HIJA">Hija</option>
<option value="PAPÁ">Papá</option>
<option value="MAMÁ">Mamá</option>
<option value="ABUELO">Abuelo</option>
<option value="ABUELA">Abuela</option>
<option value="NIETO">Nieto</option>
<option value="NIETA">Nieta</option>
<option value="CUÑADA">Cuñada</option>
<option value="CUÑADO">Cuñado</option>
</select>
</div>
</div>
<input type="hidden" id="id_contraparte" name="id_contraparte" class="form-control text-uppercase" placeholder="" >
<input type="hidden" id="id_expediente_contraparte" name="id_expediente" value="<?php echo $_GET['id_expediente']?>"class="form-control text-uppercase" placeholder="" >
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<button class="btn btn-primary btn btn-info btn-lg" type="reset">Limpiar</button>
<input id ="enviarForm" type ="button" onclick="registrarContraparte()" class="btn btn-succes btn btn-success btn-lg" value="Guardar"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</form>
</div>
</div>
<!--
<script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<!-- Google Analytics -->
<script>
$('#myform').validator()
//$("#divFamiliar").hide();
</script><file_sep><?php
include_once( '../../controlador/defensor/controladorListaDef.php');
?>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<script src="../../recursos/js/administrador/atendiendoAdmin.js"></script>
<script src="../../recursos/js/herramienta.js"></script>
<script>
var varUsuario=[];
var datos = jQuery.parseJSON(window.Global_defensores);
$.each(datos, function (KEY, VALOR) {
var temp={};
if(VALOR.id_personal > 0){
temp['label']=VALOR.nombre;
temp['apellidos']=VALOR.ap_paterno+" "+VALOR.ap_materno;
temp['desc']=VALOR.colonia+", "+VALOR.municipio;
temp['id_usuario']=VALOR.id_personal;
//console.log(VALOR);
varUsuario.push(temp);
}
});
$( function() {
function log( message ) {
var usuario=message.item.label+" "+message.item.apellidos;
if($("#usuarios").val()!= " " || $("#usuarios").val()!= ""){//PRIMERO CHECO SI ESQUE EL USUARIO NO FUE YA INSERTADO
$('#usuarioSeleccionados').empty();
var tr=document.createElement("tr");
// $( "<tr><td>" ).text( message ).prependTo( "#usuarioSeleccionados" );
var td=document.createElement("td");
tr.appendChild(td);
$( td ).text( usuario );// A ESTE TD LE ASIGO AL USUARIO DEL SERVICIO
td.setAttribute("id_usuario_eliminar",message.item.id_usuario);
$("#usuarioSeleccionados").append(tr);
var td2=document.createElement("td");
$("#usuarios").val(message.item.id_usuario);
$(td2).append("<button type='button' class='btn btn-primary eliminar col-md-7 col-xs-12'><span class='glyphicon glyphicon-remove' aria-hidden='true'> </span> </button>");
tr.appendChild(td2);
//$("#project").text(usuario);
}
$("#project").attr('disabled', true);//SIEMPRE LIMPIA EL INPUT DE BUSQUEDA // $( "#usuarioSeleccionados" ).scrollTop( 0 );
}///TERMINA LA FUCION
$( "#project" ).autocomplete({
minLength: 0,
source: varUsuario,
focus: function( event, ui ) {
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
return false;
},
select: function( event, ui ) {
var usuario=ui.item.label+" "+ui.item.apellidos;
log(ui);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label +" "+item.apellidos+ "<br>" + item.desc + "</div>" )
.appendTo( ul );
};
} );
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h3><label class="control-label col-md-12 col-sm-3 col-xs-12 " >Cambio de Defensor</label></h3>
<div class="ln_solid"></div>
</div>
<div class="x_content">
<form class="" action ="../../controlador/defensor/cambiarDefensor.php" object="defensor" method="post">
<div class="form-horizontal form-label-left">
<div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Defensor<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input data-error="Seleccione un defensor" type="text" id="project" required class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-horizontal form-label-left">
<div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<table required="" id="tablaAsinacionExpedienteusuario" class="table table-striped ">
<tbody required="" id="usuarioSeleccionados" style="height: 200px; width:915px; overflow: auto;" class=" ui-widget-content"></tbody>
</table>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<input type="text" name="usuarios" id="usuarios" style="display:none;" class="form-control col-md-7 col-xs-12"/>
<input type="text" name="expedienteNum" id="expedienteNum" value="<?php echo $_GET['id_exp'] ?>" style="display:none;" class="form-control col-md-7 col-xs-12"/>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="asignarDefensor" type ="submit" class="btn btn-succes btn btn-success btn-lg" value="cambiar"/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<file_sep>Hola usted busca <?php echo htmlspecialchars($_POST['busqueda']); ?>
<file_sep><?php
include_once ('../../libreria/conexion.php');
//print_r(fintrarPor("etnia"));
function fintrarPor($fintroPor){
$sql="select ".$fintroPor.",count(".$fintroPor." ) as total, sexo, count(sexo) from(
select pre.pregunta,detalleUsuario.sexo, COUNT(detalleUsuario.sexo) AS tsexo, detalleUsuario.etnia as etnia, COUNT(detalleUsuario.etnia) AS indigena,
detalleUsuario.idioma, COUNT(detalleUsuario.idioma)as lengua, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where id_materia=10 group by sexo, etnia,idioma,res.respuesta ) as algo group by respuesta,sexo;";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
//print_r(fintrarPorRespuesta("JUZGADO PENAL DE ETLA",10));
function fintrarPorRespuesta($fintroPor,$princialPor){
/* $sql="select idioma, count(idioma) as total, sexo, count(sexo) as tsexo from(
select pre.pregunta,detalleUsuario.sexo, COUNT(detalleUsuario.sexo) AS tsexo, detalleUsuario.etnia as etnia, COUNT(detalleUsuario.etnia) AS indigena,
detalleUsuario.idioma, COUNT(detalleUsuario.idioma)as lengua, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where id_materia=10 group by sexo, etnia,idioma,res.respuesta ) as algo where respuesta=".$fintroPor." group by idioma,sexo;"; */
$sql="select idioma, count(idioma) as total, sexo, count(sexo) as tsexo from(
".principalMateria($princialPor)." where respuesta='".$fintroPor."' group by idioma,sexo;";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
function fintrarPorPregunta($fintroPor,$princialPor){// ME FILTRA TODO POR PREGUNTAS
/* $sql="select idioma, count(idioma) as total,sexo, count(sexo) as tsexo, algo.respuesta from(
".principalMateria($princialPor)." where pregunta='".$fintroPor."' group by idioma,sexo,algo.respuesta";
$lista = consulta($sql); */
$sql="select idioma, sexo, respuesta , discapacidad ,etnia,genero from vistaMateria
where pregunta='".$fintroPor."' ;";
$lista = consulta($sql);
//echo $sql;
// $sql ="select * from vistamateria";
//$lista = consulta($sql);
return $lista;
}
function filtrarPorPreguntaDefensor($fintroPor,$defensor,$fInicio,$fFinal){// ME FILTRA TODO POR PREGUNTAS PARA EL CASO DEL DEFENSOR
// $sql="select idioma, sexo, respuesta , discapacidad ,etnia from (".principalDefensor($defensor,$fInicio,$fFinal)."
$sql=" select id_materia, COALESCE(idioma,'0') as idioma,COALESCE(sexo,'0') as sexo, COALESCE(respuesta,'0') as respuesta ,
COALESCE(discapacidad,'0') as discapacidad, COALESCE(etnia,'0') as etnia, COALESCE(genero,'0') as genero from (".principalDefensor($defensor,$fInicio,$fFinal)."
) as resultado where p='".$fintroPor."' ;";
$lista = consulta($sql);
// $sql ="select * from vistamateria";
//$lista = consulta($sql);
//echo $sql;
return $lista;
}
function filtrarPorPreguntaRegionSistemaMateria($fintroPor,$region,$sistema,$materia,$fInicio,$fFinal){// ME FILTRA TODO POR PREGUNTAS PARA EL CASO DEL DEFENSOR
// $sql="select idioma, sexo, respuesta , discapacidad ,etnia from (".principalDefensor($defensor,$fInicio,$fFinal)."
$sql=" select id_materia, COALESCE(idioma,'0') as idioma,COALESCE(sexo,'0') as sexo, COALESCE(respuesta,'0') as respuesta ,
COALESCE(discapacidad,'0') as discapacidad, COALESCE(etnia,'0') as etnia, COALESCE(genero,'0') as genero from (".principalRegionSistemaMateria($region,$sistema,$materia,$fInicio,$fFinal)."
) as resultado where pregunta='".$fintroPor."' ;";
$lista = consulta($sql);
// $sql ="select * from vistamateria";
//$lista = consulta($sql);
// echo $sql;
return $lista;
}
function filtrarPorPreguntaSistema($fintroPor,$fInicio,$fFinal){// ME FILTRA TODO POR PREGUNTAS PARA EL CASO DEL DEFENSOR
// $sql="select idioma, sexo, respuesta , discapacidad ,etnia from (".principalDefensor($defensor,$fInicio,$fFinal)."
$sql=" select id_materia, COALESCE(idioma,'0') as idioma,COALESCE(sexo,'0') as sexo, COALESCE(respuesta,'0') as respuesta ,
COALESCE(discapacidad,'0') as discapacidad, COALESCE(etnia,'0') as etnia, COALESCE(genero,'0') as genero from vistaSistema
where pregunta='".$fintroPor."' ;";
$lista = consulta($sql);
// $sql ="select * from vistamateria";
//$lista = consulta($sql);
//echo $sql;
return $lista;
}
function filtrarPorPreguntaSistemaMateria($fintroPor,$fInicio,$fFinal){// ME FILTRA TODO POR PREGUNTAS PARA EL CASO DEL DEFENSOR
$sql=" select id_materia, COALESCE(idioma,'0') as idioma,COALESCE(sexo,'0') as sexo, COALESCE(respuesta,'0') as respuesta ,
COALESCE(discapacidad,'0') as discapacidad, COALESCE(etnia,'0') as etnia, COALESCE(genero,'0') as genero from vistaSistemaMateria
where pregunta='".$fintroPor."' ;";
$lista = consulta($sql);
//echo $sql;
return $lista;
}
function filtradoPorDiscapacidad($dicapacidad,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select discapacidad, sexo from vistaMateria
where pregunta='".$pregunta."' ) as filtro
where discapacidad='".$dicapacidad."' group by sexo ;";
return consulta($sql);
}
function filtradoPorEtnia($etnia,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select etnia, sexo from vistaMateria
where pregunta='".$pregunta."' ) as filtro
where etnia='".$etnia."' group by sexo ;";
// echo $sql;
return consulta($sql);
}
function filtradoPorIdioma($idioma,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select idioma, sexo from vistaMateria
where pregunta='".$pregunta."' ) as filtro
where idioma='".$idioma."' group by sexo ;";
//echo $sql;
return consulta($sql);
}
function filtradoPorSistemaDiscapacidad($dicapacidad,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select discapacidad, sexo from vistaSistema
where pregunta='".$pregunta."' ) as filtro
where discapacidad='".$dicapacidad."' group by sexo ;";
return consulta($sql);
}
function filtradoPorSistemaEtnia($etnia,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select etnia, sexo from vistaSistema
where pregunta='".$pregunta."' ) as filtro
where etnia='".$etnia."' group by sexo ;";
// echo $sql;
return consulta($sql);
}
function filtradoPorSistemaIdioma($idioma,$pregunta){
$sql="select sexo, count(sexo) as tsexo from (
select idioma, sexo from vistaSistema
where pregunta='".$pregunta."' ) as filtro
where idioma='".$idioma."' group by sexo ;";
//echo $sql;
return consulta($sql);
}
function principalMateria($materia,$fechaInicio,$fechaFinal){// ESTO ES SOLO PARA NO REPETIR ESTO LINEAS DE CODIGO MUCHAS VECES
/* select pre.pregunta,detalleUsuario.sexo, COUNT(detalleUsuario.sexo) AS tsexo, detalleUsuario.etnia as etnia, COUNT(detalleUsuario.etnia) AS indigena,
detalleUsuario.idioma, COUNT(detalleUsuario.idioma)as tidioma, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where id_materia=".$materia." group by sexo, etnia,idioma, pre.pregunta order by pregunta as algo ";
return $sql; */
// EL DROP IF EXISTS JAMAS SE DEBE BORRAR NI QUITAR PORQUE ES MUY NECESARIO QUE ESTE
$agregarFecha=" ";
if($fechaInicio!=" "&$fechaInicio!='')
$agregarFecha="and (res.fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFinal."')";
$sql=" drop view if exists vistaMateria;
create view vistaMateria as
select pre.pregunta,detalleUsuario.sexo, detalleUsuario.etnia as etnia,detalleUsuario.genero as genero,
detalleUsuario.idioma, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta,detalleUsuario.discapacidad,sistema,materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join materia using(id_materia)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where materia='".$materia."' ".$agregarFecha."
group by sexo, etnia, pre.pregunta , discapacidad order by pregunta ; ";
//echo $sql;
return consulta($sql);
}
//print_r(preguntasMateriaAgrupadas('civil'));
function preguntasMateriaAgrupadas($Nombremateria){// este se agrupa en todas las materia sin importar el sistema y instancia
$where="";
switch ($Nombremateria) {
case "PENAL" :
//echo "\n EN PENAL \n";
$where="where detalle.id_materia=1 or detalle.id_materia=2 or detalle.id_materia=10 or detalle.id_materia=11 or detalle.id_materia=25";
break;
case "CIVIL":
//echo "\n EN CIVIL \n";
$where="where detalle.id_materia=5 or detalle.id_materia=6 or detalle.id_materia=12 or detalle.id_materia=13";
break;
case 'EJECUCION':
//echo "\n EN EJECUCION \n";
$where="where detalle.id_materia=9 or detalle.id_materia=16 or detalle.id_materia=17";
break;
case 'FAMILIAR':
//echo "\n EN FAMILIAR \n";
$where="where detalle.id_materia=3 or detalle.id_materia=4 or detalle.id_materia=14 or detalle.id_materia=15";
break;
case 'AGRARIO':
//echo "\n EN AGRARIO \n";
$where="where detalle.id_materia=7 or detalle.id_materia=8 or detalle.id_materia=24";
break;
case 'ADOLESCENTE':
//echo "\n EN ADOLESCENTE \n";
$where="where detalle.id_materia=22 or detalle.id_materia=23";
break;
default:
# code...
break;
}
$sql=" select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion
FROM pregunta_materia as detalle
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)".$where."
group by pregunta;";
// echo "\nfina \n";
// echo $sql;
return consulta($sql);
}
function preguntasSistemaMateriaAgrupadas($Nombremateria,$sistema){// este se agrupa en todas las materia sin importar el sistema y instancia
/* $sql=" select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion
FROM pregunta_materia as detalle
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)".$where."
group by pregunta;"; */
$sql="select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion,sistema,materia
FROM pregunta_materia as detalle
inner join materia using(id_materia)
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)
where sistema='".$sistema."' and materia='".$Nombremateria."'
group by pregunta;";
// echo "\nfina \n";
// echo $sql;
return consulta($sql);
}
function preguntasSistema($sistema){
$sql="select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion,sistema
FROM pregunta_materia as detalle
inner join materia using(id_materia)
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)
where sistema='".$sistema."'
group by pregunta;";
return consulta($sql);
}
function preguntasMateria($idmateria){
/* $sql="select pre.pregunta
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
where id_materia=".$materia; */
$sql="select pre.id_pregunta, pre.pregunta, detalle.id_materia, detalle.id_pregunta_materia, detalle.identificador, op.opcion
FROM pregunta_materia as detalle
inner join pregunta as pre using(id_pregunta)
left join opcion as op using(id_pregunta)
where detalle.id_materia=".$idmateria;
return consulta($sql);
}
function preguntasRegionSistemaMateria($region,$sistema,$materia){
$and=" ";
if($sistema!=""&$sistema!="NINGUNO"&($materia==""|$materia=="NINGUNO"))
$and="and sistema='".$sistema."'";
if($materia!=""&$materia!="NINGUNO"&($sistema==""|$sistema=="NINGUNO"))
$and="and materia='".$materia."'";
if($materia!=""&$materia!="NINGUNO"&$sistema!=""&$sistema!="NINGUNO")
$and="or sistema='".$sistema."' or materia='".$materia."'";
// $and="and sistema='".$sistema."' and materia='".$materia."'";
$sql=" select preguntas.id_pregunta,preguntas.pregunta,preguntas.identificador,respuestas.*,opcion
from
(select id_pregunta,pregunta as pregunta,id_pregunta_materia,id_materia,identificador
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta) ) as preguntas
inner join
( select id_personal, per.id_materia, per.id_juzgado,per.juzgado,per.region,per.materia,per.sistema
from (select * from personal_campo inner join juzgado using(id_juzgado) inner join materia using(id_materia) ) as per
) as respuestas using (id_materia)
left join opcion as op on preguntas.id_pregunta=op.id_pregunta
# where region='".$region."'".$and."
group by pregunta, opcion ;";
//echo $sql;
return consulta($sql);
}
function opcionesPorMateria($id_pregunta){
$sql="select opcion from opcion where id_pregunta=".$id_pregunta;
return consulta($sql);
}
function aplicarConsultaDefensor($densor,$fechaInicio,$fechaFina){
/* $sql="
select p,id_pregunta as idP, respuesta as res,genero as generos, discapacidad as discapacidades, (select count(sexo) as h from (".
principalDefensor($densor,$fechaInicio,$fechaFina)."
) as hombre where hombre.respuesta=res and sexo='MASCULINO'
) as hombre
,(select count(sexo) as m from (".
principalDefensor($densor,$fechaInicio,$fechaFina)." )
as hombre where hombre.respuesta=res and sexo='FEMENINO') AS MUJER ,
(select count(genero) as m from (".
principalDefensor($densor,$fechaInicio,$fechaFina)." )
as hombre where hombre.respuesta=res and genero=generos) AS tgenero ,
(select count(genero) as m from (".
principalDefensor($densor,$fechaInicio,$fechaFina)." )
as hombre where hombre.respuesta=res and discapacidad=discapacidades) AS tdiscapaciad
from (". principalDefensor($densor,$fechaInicio,$fechaFina).") as e group by respuesta;
"; */
$sql=principalDefensor($densor,$fechaInicio,$fechaFina);
//echo $sql;
return consulta($sql);
}
function principalDefensor($defensor,$fechaInicio,$fechaFina){
$agregarFecha=" ";
if($fechaInicio!=" "&$fechaInicio!='')
$agregarFecha=" where (fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFina." ') ";
// $agregarFecha="and (res.fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFinal."')";
//select preguntas.p,respuestas.*, user.sexo, user.genero,user.etnia,user.idioma,user.discapacidad
$sql="
select preguntas.id_pregunta,preguntas.p,respuestas.*, user.sexo, user.genero,user.etnia,user.idioma,user.discapacidad
from
(select id_pregunta,pregunta as p,id_pregunta_materia,id_materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta) ) as preguntas
left join
(select tablaPregunta.id_personal,tablaPregunta.id_expediente,tablaPregunta.id_usuario_servicio,res.respuesta,res.fecha_registro,tablaPregunta.id_materia,res.id_pregunta_materia
from (select id_personal,exp.id_expediente,id_usuario_servicio, per.id_materia
from personal_campo as per inner join expediente as exp using(id_personal)
inner join detalle_usuario_expediente as detalleExp using(id_expediente) where id_personal=".$defensor." ) as tablaPregunta
left join respuesta as res on tablaPregunta.id_expediente=res.id_expediente ".$agregarFecha."
) as respuestas using (id_pregunta_materia) left join usuario_servicio as user using(id_usuario_servicio) where preguntas.id_materia=(
select tablaPregunta.id_materia
from (select id_personal,exp.id_expediente,id_usuario_servicio, per.id_materia
from personal_campo as per inner join expediente as exp using(id_personal)
inner join detalle_usuario_expediente as detalleExp using(id_expediente) where id_personal=".$defensor." ) as tablaPregunta
left join respuesta as res on tablaPregunta.id_expediente=res.id_expediente limit 1) ";
return $sql; // EN ESTA NO SE REALIZA LA CONSULTA EN FORMA DE VISTA PORQUE NO SE PERMITE SUBCONSULTA EN UNA VISTA
}
function aplicarConsultaRegionSistemaMateria($region,$sistema,$materia,$fechaInicio,$fechaFina){
$sql=principalRegionSistemaMateria($region,$sistema,$materia,$fechaInicio,$fechaFina);
// echo $sql;
return consulta($sql);
}
function principalRegionSistemaMateria($region,$sistema,$materia,$fechaInicio,$fechaFina){
$agregarFecha=" ";
$and=" ";
if($fechaInicio!=" "&$fechaInicio!='')
$agregarFecha=" where (fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFina." ') ";
// $agregarFecha="and (res.fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFinal."')";
//select preguntas.p,respuestas.*, user.sexo, user.genero,user.etnia,user.idioma,user.discapacidad
if($sistema!=""&$sistema!="NINGUNO"&($materia==""|$materia=="NINGUNO"))
$and="and sistema='".$sistema."'";
if($materia!=""&$materia!="NINGUNO"&($sistema==""|$sistema=="NINGUNO"))
$and="and materia='".$materia."'";
if($materia!=""&$materia!="NINGUNO"&$sistema!=""&$sistema!="NINGUNO")
$and="and sistema='".$sistema."' and materia='".$materia."'";
$sql="
select preguntas.id_pregunta,preguntas.pregunta,respuestas.*, user.sexo, user.genero,user.etnia,user.idioma,user.discapacidad
from
(select id_pregunta,pregunta as pregunta,id_pregunta_materia,id_materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta) ) as preguntas
left join
(select tablaPregunta.id_personal,tablaPregunta.id_expediente,tablaPregunta.id_usuario_servicio, tablaPregunta.juzgado,tablaPregunta.region,tablaPregunta.materia,tablaPregunta.sistema,res.respuesta,res.fecha_registro,tablaPregunta.id_materia,res.id_pregunta_materia
from (select id_personal,exp.id_expediente,id_usuario_servicio, per.id_materia, per.id_juzgado,per.juzgado,per.region,per.materia,per.sistema
from (select * from personal_campo inner join juzgado using(id_juzgado) inner join materia using(id_materia) ) as per inner join expediente as exp using(id_personal)
inner join detalle_usuario_expediente as detalleExp using(id_expediente) # where region='cañada'
) as tablaPregunta
inner join respuesta as res on tablaPregunta.id_expediente=res.id_expediente ".$agregarFecha."
) as respuestas using (id_pregunta_materia) left join usuario_servicio as user using(id_usuario_servicio) where region='".$region."' ".$and." ";
//echo $sql;
//echo "finalizao esta cosa \n" ;
//return consulta($sql);
return $sql; // EN ESTA NO SE REALIZA LA CONSULTA EN FORMA DE VISTA PORQUE NO SE PERMITE SUBCONSULTA EN UNA VISTA
}
function principalSistema($sistema,$fechaInicio,$fechaFinal){// ESTO ES SOLO PARA NO REPETIR ESTO LINEAS DE CODIGO MUCHAS VECES
// EL DROP IF EXISTS JAMAS SE DEBE BORRAR NI QUITAR PORQUE ES MUY NECESARIO QUE ESTE
$agregarFecha=" ";
if($fechaInicio!=" "&$fechaInicio!='')
$agregarFecha="and (res.fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFinal."')";
$sql=" drop view if exists vistaSistema;
create view vistaSistema as
select pre.pregunta,detalleUsuario.sexo, detalleUsuario.etnia as etnia, detalleUsuario.genero,
detalleUsuario.idioma, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta,detalleUsuario.discapacidad,sistema,materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join materia using(id_materia)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where sistema='".$sistema."' ".$agregarFecha."
group by sexo, etnia, pre.pregunta , discapacidad order by pregunta ; ";
// echo $sql;
return consulta($sql);
}
function principalSistemaMateria($sistema,$materia,$fechaInicio,$fechaFinal){// ESTO ES SOLO PARA NO REPETIR ESTO LINEAS DE CODIGO MUCHAS VECES
// EL DROP IF EXISTS JAMAS SE DEBE BORRAR NI QUITAR PORQUE ES MUY NECESARIO QUE ESTE
$agregarFecha=" ";
if($fechaInicio!=" "&$fechaInicio!='')
$agregarFecha="and (res.fecha_registro BETWEEN '".$fechaInicio."' and '".$fechaFinal."')";
/* select pre.pregunta,detalleUsuario.sexo, detalleUsuario.etnia as etnia, detalleUsuario.genero,
detalleUsuario.idioma, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta,detalleUsuario.discapacidad,sistema,materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join materia using(id_materia)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where sistema='tradicional' and materia='civil'
group by sexo, etnia, pre.pregunta , discapacidad order by pregunta ;
*/
$sql=" drop view if exists vistaSistemaMateria;
create view vistaSistemaMateria as
select pre.pregunta,detalleUsuario.sexo, detalleUsuario.etnia as etnia, detalleUsuario.genero,
detalleUsuario.idioma, exp.id_usuario_servicio, exp.id_expediente , preMateria.id_pregunta_materia
, preMateria.id_materia,res.respuesta,detalleUsuario.discapacidad,sistema,materia
from pregunta as pre inner join pregunta_materia as preMateria using(id_pregunta)
inner join materia using(id_materia)
inner join respuesta as res using(id_pregunta_materia)
left join detalle_usuario_expediente as exp using(id_expediente)
inner join usuario_servicio as detalleUsuario using(id_usuario_servicio)
where sistema='".$sistema."' and materia='".$materia."' ".$agregarFecha."
group by sexo, etnia, pre.pregunta , discapacidad order by pregunta ; ";
//echo $sql;
return consulta($sql);
}
?>
<file_sep><?php
header('Content-Type: application/json');
include '../../modelo/personal.php';
include '../../modelo/usuarioServicio.php';
include '../../libreria/herramientas.php';
include_once ('../../modelo/expediente.php');
include_once ('../../modelo/defensor/defensor.php');
include_once ('../../modelo/detalleExpediente_usuarioServicio.php');
//$usuario_servicio=getUsuarioByCurp($_POST['curp'])[0]['id_usuario_servicio'];
// $materia=listar_defensor_x_id($_POST['defensor'])[0]['materia'];
$materia=listar_defensor_x_id($_POST['defensor']);
//print_r($materia);
$usuario=explode(",",$_POST['usuarios'] );
$expediente = Array(
"id_defensor" =>$_POST['defensor'],
"num_expediente" =>((isset($_POST['expediente']))?$_POST['expediente']:""),
"nombre_delito" =>$_POST["delito"],
"tipo_expediente" =>$_POST["tipo_expediente"],
"grado_delito" =>$_POST["grado_delito"]
);
$expediente = array_map( "cadenaToMayuscula",$expediente);/// convierte todo a mayusculas
//////// CUANDO ES EJECUCION DE SANCIONES SE DEBE DE REGISTRAR LA FECHA EN QUE SE CREO EL EXPEDIENTE
$mensaje=['tipo'=>"error",
'mensaje'=>"expediente ya existe"];
$dirigir="asignar_defensor";
if((listar_x_num_expediente_($expediente['num_expediente'])==0)||($expediente['num_expediente']=="")){
//echo "validando ".existenciaUsuario($usuario,$materia[0]['id_materia']);
if(existenciaUsuario($usuario,$materia[0]['id_materia'])==false)
{// echo "entro valido personal materia";
alta_expediente($expediente);
foreach ($usuario as $key => $value) {
alta_DetalleExpedinte(ultimoExpedinteCreatado(),$value);
}
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
$dirigir="listar_Expediente";
}
else{
$mensaje=['tipo'=>"error",
'mensaje'=>" uno o varios usuarios ya cuenta con un defensor del mismo problema"];
$dirigir="asignar_defensor";
}
}
if(isset($_GET['tipo'])){
if($_GET['tipo']=="html"){
session_start();
// $_SESSION['mensaje'] = "registro exitoso";
$_SESSION['mensaje'] = $mensaje;
$_SESSION['dirigir'] = $dirigir;
// echo $mensaje['mensaje'];
header("location: ../../vistas/defensor/index.php");
}
else{
header('Content-Type: application/json');
echo "json";
}
}
function existenciaUsuario($usuarios,$materia){
foreach ($usuarios as $key => $value) {
$existencia= listar_expedienteByPersonalAndMateria($value,$materia);
// print_r($existencia);
if($existencia>0)
return true;
}
return false;
}
?><file_sep><?php
include_once('../../libreria/conexion.php');
function consultaMatNotSystem($mat, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaMatSystem($sis, $mat, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaRegNotSystem($reg, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','REGION','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','REGION','','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaRegSystem($sis, $reg, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaAmbasNotSystem($mat, $reg, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','AMBAS','','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaAmbasSystem($sis, $mat, $reg, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaNingunoNotSystem($atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaNingunoSystem($sis, $atrib){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','COMPLETO','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
case 'REGION':
$sql = "call bddefensoria.tablaExpRegionP('COMPLETO', 'SISTEMANIN', '', '".$sis."', '', '', '', '')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaMatNotSystemDef($mat, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaRegionExpDef'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','MATERIA','".$id."','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
return $lista;
}
function consultaMatSystemDef($sis, $mat, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaRegionExpDef'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaRegNotSystemDef($reg, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','REGION','".$id."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
return $lista;
}
function consultaRegSystemDef($sis, $reg, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaAmbasNotSystemDef($mat, $reg, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','AMBAS','".$id."','','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
return $lista;
}
function consultaAmbasSystemDef($sis, $mat, $reg, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaNingunoNotSystemDef($atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','COMPLETO','".$id."','','','','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
return $lista;
}
function consultaNingunoSystemDef($sis, $atrib, $id){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaMateriaExpDef'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETO','SISTEMANIN','".$id."','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaTopExpDef'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
///============================================================================================ PERIODO
function consultaMatNotSystemP($mat, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','MATERIA','','','".$mat."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','MATERIA','','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaMatSystemP($sis, $mat, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','SISTEMATERIA','','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaRegNotSystemP($reg, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','REGION','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
break;
case 'GENERO':
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETOPERIODO','MATERIA','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','REGION','','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaRegSystemP($sis, $reg, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','SISTEMAREG','','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaAmbasNotSystemP($mat, $reg, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','AMBAS','','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaAmbasSystemP($sis, $mat, $reg, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','SISTEMAMBAS','','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaNingunoNotSystemP($atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','COMPLETO','','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
return $lista;
}
function consultaNingunoSystemP($sis, $atrib, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExp'] = $l;
$sql = "call tablaExpGeneralP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExp'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExp'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExp'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExp'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExp'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExp'] = $l;
break;
case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETOPERIODO','COMPLETO','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
case 'REGION':
$sql = "call tablaExpRegionP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break;
case 'SEXO':
$sql = "call tablaExpSexoP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExp'] = $l;
break;
case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','SISTEMANIN','','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break;
}
}
// print_r($sql);
return $lista;
}
function consultaMatNotSystemDefP($mat, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','MATERIA','','','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/* case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','MATERIA','".$id."','','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
return $lista;
}
function consultaMatSystemDefP($sis, $mat, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('COMPLETO','SISTEMATERIA','','".$sis."','".$mat."','','','')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaRegionExpDef'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/* case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','SISTEMATERIA','".$id."','".$sis."','".$mat."','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
// print_r($sql);
return $lista;
}
function consultaRegNotSystemDefP($reg, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','REGIONF','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','REGION','".$id."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/*
case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','REGION','".$id."','','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
return $lista;
}
function consultaRegSystemDefP($sis, $reg, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','".$id."','".$sis."','','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/*
case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','SISTEMAREG','".$id."','".$sis."','','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
// print_r($sql);
return $lista;
}
function consultaAmbasNotSystemDefP($mat, $reg, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','MATERIA','','','','".$mat."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/* case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','AMBAS','".$id."','','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
return $lista;
}
function consultaAmbasSystemDefP($sis, $mat, $reg, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/*
case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMAREG','','".$sis."','".$mat."','".$reg."','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/*
case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','SISTEMAMBAS','".$id."','".$sis."','".$mat."','".$reg."','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
// print_r($sql);
return $lista;
}
function consultaNingunoNotSystemDefP($atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break;
*/
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','COMPLETO','','','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/* case 'TOP':
$sql = "call tablaExpTopP('DEFENSORPERIODO','COMPLETO','".$id."','','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
return $lista;
}
function consultaNingunoSystemDefP($sis, $atrib, $id, $fi, $ff){
$lista = array();
$sql = "call tablaExpActividadesP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaActExpDef'] = $l;
$sql = "call tablaExpGeneralP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneralExpDef'] = $l;
foreach($atrib as $val){
switch($val){
case 'ACTIVIDAD':
break;
case 'DISCAPACIDAD':
$sql = "call tablaExpDiscapacidadP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaDiscapacidadExpDef'] = $l;
break;
case 'EDAD':
$sql = "call tablaExpEdadP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEdadExpDef'] = $l;
break;
case 'ETNIA':
$sql = "call tablaExpEtniaP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaEtniaExpDef'] = $l;
break;
case 'GENERAL':
break;
case 'GENERO':
$sql = "call tablaExpGeneroP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaGeneroExpDef'] = $l;
break;
case 'IDIOMA':
$sql = "call tablaExpIdiomaP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaIdiomaExpDef'] = $l;
break;
/* case 'MATERIA':
$sql = "call tablaExpMateriaP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaMateriaExp'] = $l;
break; */
/* case 'REGION':
$sql = "call tablaExpRegionP('COMPLETO','SISTEMANIN','','".$sis."','','','','')";
$l = consulta($sql);
$lista['tablaRegionExp'] = $l;
break; */
case 'SEXO':
$sql = "call tablaExpSexoP('DEFENSORPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaSexoExpDef'] = $l;
break;
/* case 'TOP':
$sql = "call tablaExpTopP('COMPLETOPERIODO','SISTEMANIN','".$id."','".$sis."','','','".$fi."','".$ff."')";
$l = consulta($sql);
$lista['tablaTopExp'] = $l;
break; */
}
}
// print_r($sql);
return $lista;
}
?>
<file_sep><?php
include '../../modelo/defensor/defensor.php';
//echo $_GET['cedula'];
$id_def = $_GET['id_defensor'];
$defensorX = getDefensorById($id_def);//obtenerDefensorCedula($cedulaProf);
$defensorZ = json_encode($defensorX);
echo $defensorZ;
?><file_sep> <?php
require_once 'simpleTest/autorun.php';
require_once 'classes/Log.php';
class pruebaUnitaria extends UnitTestCase{
function __construct() {
parent::__construct('Test con Log');
}
// $holaMundo = new holaMundo();
function testPruebaUnitaria(){
$defensor = Array(
"id_defensor" =>'46',
"nombre" =>'pacho',
"ap_paterno" =>'f',
"ap_materno" =>'perez',
"curp" =>'K45P1234ABCD3214567',
"calle" =>'oaxaca',
"numero_ext" =>'23',
"numero_int" =>'2',
"colonia" =>'oaxaca',
"municipio" =>'san juan',
"nup" =>'3456',
"nue" =>'12365',
"genero" =>'masculino',
"telefono" =>'9378878787',
"corre_electronico" =>'<EMAIL>',
"cedula_profesional" =>'67767676767',
"juzgado" =>'fsdfss'
);
$actualizar= $this.get('/controlador/defensor/controlActualizar.php',$defensor,'submit');
//$this->assertTrue(300,holaMundo());
//@unlink('temp/test.log');
//$log = new Log('temp/test.log');
//$log->returnBool();
$this->assertEqual(201 ,returnBool());
//$this->assertTrue(file_exists('temp/test.log'));
}
}
?><file_sep><?php
//include_once( '../../controlador/juzgado/actividad_juzgado.php');
//include_once( '../../controlador/defensor/controladorListaDef.php');
session_start();
// print_r($_SESSION['personal']);
$id_personal = $_SESSION['personal'][0]['id_personal'];
$nombre = $_SESSION['personal'][0]['nombre'];
//echo $id_personal;
//echo $nombre;
?>
<script >
var resultadoConsulta;
function enviarRespuesta(elemento){
var respuesta =$(elemento).closest("#rrellenarPregunta").find("#opcionesRespuesta");
var observacion =$(elemento).closest("#rrellenarPregunta").find("#observacion");
var accion_implementar =$(elemento).closest("#rrellenarPregunta").find("#observacaccion_implementarion");
var id_pregunta =$(elemento).closest("#rrellenarPregunta").find("#id_pregunta");
var id_expediente =$(elemento).closest("#rrellenarPregunta").find("#id_expediente");
var sendInfo = {
id_pregunta : id_pregunta.val(),
id_expediente : id_expediente.val(),
respuesta : respuesta.val(),
observacion : observacion.val(),
accion_implementar : accion_implementar.val(),
};
// console.log("ENVIANDO DATOS DE ABAJO");
//console.log(sendInfo);
$.ajax({
type: "POST",
url: "../../controlador/expediente/seguimientoExpediente.php",
dataType: "html",
success: function (data) {
var json=jQuery.parseJSON(data)
console.log(data);
console.log($("#idMensaje"));
var alert="";
if(json['tipo']==="exito")
alert="alert alert-success";
//$alert='alert alert-danger';
if(json['tipo']==="error")
alert="alert alert-danger";
if(json['tipo']==="juzgado")
alert="alert alert-danger";
$("#contenedorMensaje").attr("class",""+alert);
$("#contenedorMensaje").append('<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">'+
'<div class="modal-dialog modal-dialog-centered" role="document">'+
'<div class="modal-content">'+
'<strong align="center" id="id_Mensaje" class="alert-dismissible fade in '+alert+'"></strong>'+
'<div class="modal-footer">'+
' <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>'+
'</div></div> </div></div>');
$("#id_Mensaje").text(json['mensaje']);
console.log(json['mensaje']," fue esto");
$('#exampleModalLong').modal('show');
console.log("ffef en always ",json['tipo']);
if(json['tipo']==="exito")
$("#rrellenarPregunta").children().remove();
},
data: sendInfo
});
}
function eventoPregunta(event,data){
var seleccionado = event.options[event.selectedIndex];
console.log(seleccionado);
$("#rrellenarPregunta").children().remove();
$("#rrellenarPregunta").show();
$("#registroContraparte").empty();
var tipo= seleccionado.getAttribute('tipo');
var typeData="";
if(tipo==="fecha")//AUNQUE TODO TIENEN EL id opcionesRespuesta SOLO ES UTIL CUANDO ESL TIPO ES select
typeData=" <input id='opcionesRespuesta' pattern='[A-Za-z0-9 éíóúūñÁÉÍÓÚÜÑ]+' respuesta='valor' type='date' name='respuesta' class='form-control col-md-7 col-xs-12' >";
if(tipo==="select")
typeData="<select id='opcionesRespuesta' respuesta='valor' required=' ' name='respuesta' class='form-control '></select>";
if(tipo==="texto")
typeData=" <input id='opcionesRespuesta' pattern='[A-Za-z0-9 éíóúūñÁÉÍÓÚÜÑ]+' respuesta='valor' type='text' name='respuesta' class='form-control col-md-7 col-xs-12' >";
var id_expediente= document.getElementById('numExpedienteGlobal').value;
$("#rrellenarPregunta").append(
'<input id="id_pregunta" type="hidden" name="id_pregunta" value="'+seleccionado.value+'" class="form-control col-md-7 col-xs-12" >'+
'<div class="form-horizontal form-label-left"> <div class="form-group">'+
'<label class="control-label col-md-3 col-sm-3 col-xs-12" for="respuesta">Respuesta'+
'<span class="required">*</span></label>'+
'<div id="idRespuestaCambio" class="col-md-6 col-sm-6 col-xs-12">'+
typeData+
'<div class="help-block with-errors"></div></div> </div> </div>'+
'<div class="form-horizontal form-label-left"> <div class="form-group">'+
'<label class="control-label col-md-3 col-sm-3 col-xs-12" for="curp">Observaciones'+
'<span class="required">*</span></label>'+
'<div class="col-md-6 col-sm-6 col-xs-12">'+
'<textarea id="observacion" name="observacion" pattern="[A-Za-z0-9.,:áéíóú ]+" data-error="solo numeros o letras con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describa las observaciones"></textarea>'+
'<div class="help-block with-errors"></div></div> </div> </div>'+
'<div class="form-horizontal form-label-left"> <div class="form-group">'+//ACCION A IMPLEMENTAR
'<label class="control-label col-md-3 col-sm-3 col-xs-12" for="curp">Acción a implementar'+
'<span class="required">*</span></label>'+
'<div class="col-md-6 col-sm-6 col-xs-12">'+
'<textarea id="observacaccion_implementarion" name="accion_implementar" pattern="[A-Za-z0-9.,:áéíóú ]+" data-error="solo numeros o letras con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describa la(s) accion que debe realizar "></textarea>'+
/*
'<input type="text" name="accion_implementar" class="form-control col-md-7 col-xs-12" >'+ */
'<div class="help-block with-errors"></div></div> </div> </div>'+//FIN DE ACCION A IMPLEMENTAR
'<input type="hidden" id="id_expediente" name="id_expediente" class="form-control col-md-7 col-xs-12" value='+id_expediente+' >'+// EL ID DE LA PREGUNTA
'<div class="form-group">'+
'<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">'+
'<input type ="button" class="btn btn-succes btn btn-success btn-lg" onclick="enviarRespuesta(this)" value="Registrar "/>'+
'</div> </div>'
);
//console.log(resultadoConsulta," EN DONDE BUSCAR");
// console.log(seleccionado.value," QUE BUSCAR");
//console.log(resultadoConsulta[seleccionado.value]);
var opciones=resultadoConsulta[seleccionado.value].opcion;
if(opciones!=""){
opciones.forEach(function(elemento) {
var opcion= $('<option value="'+elemento+'" name="opcionpregunta" > ').text(elemento);
$('#opcionesRespuesta').append(opcion);
});
}
if(seleccionado.value==="324"){
$("#idRespuestaCambio").children().remove();
$('#idRespuestaCambio').append("<select id='opcionesRespuesta' required=' ' name='respuesta' class='form-control '>"+
' <option value="">- Seleccione -</option> '+
' <option value="AS">AGUASCALIENTES</option>'+
' <option value="BC">BAJA CALIFORNIA</option>'+
' <option value="BS">BAJA CALIFORNIA SUR</option>'+
' <option value="CC">CAMPECHE</option> '+
' <option value="CL">COAHUILA DE ZARAGOZA</option>'+
' <option value="CM">COLIMA</option>'+
' <option value="CS">CHIAPAS</option>'+
' <option value="CH">CHIHUAHUA</option>'+
' <option value="DF">DISTRITO FEDERAL</option>'+
' <option value="DG">DURANGO</option>'+
' <option value="GT">GUANAJUATO</option>'+
' <option value="GR">GUERRERO</option> <option value="HG">HIDALGO</option> <option value="JC">JALISCO</option> <option value="MC">MEXICO</option> <option value="MN">MICHOACAN DE OCAMPO</option> <option value="MS">MORELOS</option> <option value="NT">NAYARIT</option> <option value="NL">NUEVO LEON</option> <option value="OC">OAXACA</option> <option value="PL">PUEBLA</option> <option value="QT">QUERETARO DE ARTEAGA</option> <option value="QR">QUINTANA ROO</option> <option value="SP">SAN LUIS POTOSI</option> <option value="SL">SINALOA</option> <option value="SR">SONORA</option> <option value="TC">TABASCO</option> <option value="TS">TAMAULIPAS</option> <option value="TL">TLAXCALA</option> <option value="VZ">VERACRUZ</option> <option value="YN">YUCATAN</option> <option value="ZS">ZACATECAS</option> <option value="NE">NACIDO EN EL EXTRANJERO</option></select>'+
"</select>");
}
if(tipo==="ignorado"){
$("#idRespuestaCambio").children().remove();
$('#idRespuestaCambio').append("<select id='opcionesRespuesta' required=' ' name='respuesta' class='form-control '>"+
' <option value="">- Seleccione -</option> '+
"</select>");
$.get("../../controlador/juzgado/actividad_juzgado.php?tipo=listadoJuzgadoSeguimiento",function(data){//PARA OBTENER LOS JUZGADO DE OAXACA
//console.log(data," los juzgados en seguimiento");
var temp="";
$.each(data, function (KEY, VALOR) {
//console.log("LA REGION ES ",VALOR);
temp=' <optgroup label="'+KEY+'">',
$.each(VALOR, function (LLAVE, JUZGADO) {
temp+= '<option value="'+JUZGADO['nombre']+'">'+JUZGADO['nombre']+'</option> '
}); temp+="</optgroup>";
$('#opcionesRespuesta').append(temp);
})//echo '</optgroup>';
});
}
}// CIERRE DE LA FUNCION */
console.log("lista de las preguntas...");
var user=JSON.parse(window.Global_user_basic);
var expe=window.num_expedienteGlobal;
console.log("num de expe ",expe);
function iniciarPregunta(elemento){
console.log("dentoro de la preguntas que se tiene que contestar");
$('#preguntas').empty();
$("#preguntasAmparo").empty();
$("#preguntas").hide();
$("#divInstancia").show();
var intancia=$(elemento).val();
console.log(" instancia seleccionada",intancia);
if(intancia!=undefined){
var materia=((intancia==='1')?7 :8);
console.log("materia que se selecciona",materia);
$('#preguntas').append(
'<div id="actividad" class=" form-horizontal form-label-left form-group "><div class="form-group ">'+
'<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " > Registrar/Actualizar datos para '+
'<span class="required">*</span></label>'+
'</h4><div class="col-md-6 col-sm-6 col-xs-12">'+
'<select id="opcionPreguntas" onchange="eventoPregunta(this)" required="" name="actividad" class="form-control " >'+
' </select> </div></div> </div> '
);
$.get("../../controlador/expediente/lista_preguntas.php?conOpcion=true&id_materia="+materia+"&id_expediente="+expe,function(data){
var jsonMisExp =JSON.parse(data);// jQuery.parseJSON(data);
resultadoConsulta=jsonMisExp;// guardo el formato json para usarlo posteriomente para crear los input
$("#opcionPreguntas").children().remove();
$.each(jsonMisExp, function (KEY, VALOR) {
var varpreguntas= $('<option value="'+VALOR.id_pregunta_materia+'" name="opcionpregunta" tipo="'+VALOR.identificador+'"> ').text(VALOR.pregunta);
$('#opcionPreguntas').append(varpreguntas);
});
});
$("#preguntas").show()
}//final del if para ver si no esta seleccionado
}
//iniciarPregunta();
function registrarAmparo(){
$("#preguntas").empty();
$("#preguntasAmparo").empty();
$("#preguntasAmparo").show();
$("#divInstancia").hide();
$('#preguntasAmparo').append(
'<div id="actividad" class=" form-horizontal form-label-left form-group "><div class="form-group ">'+
'<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " > Registrar amparo '+
'<span class="required">*</span></label>'+
'</h4><div class="col-md-6 col-sm-6 col-xs-12">'+
'<select id="opcionPreguntas" onchange="eventoPregunta(this)" required="" name="actividad" class="form-control " >'+
' </select> </div></div> </div> '
);
$.get("../../controlador/expediente/lista_preguntas.php?conOpcion=true&id_materia=24&id_expediente="+expe,function(data){
var jsonMisExp =JSON.parse(data);// jQuery.parseJSON(data);
resultadoConsulta=jsonMisExp;// guardo el formato json para usarlo posteriomente para crear los input
//console.log(resultadoConsulta)
$("#opcionPreguntas").children().remove();;
$.each(jsonMisExp, function (KEY, VALOR) {
var varpreguntas= $('<option value="'+VALOR.id_pregunta_materia+'" name="opcionpregunta" tipo="'+VALOR.identificador+'"> ').text(VALOR.pregunta);
$('#opcionPreguntas').append(varpreguntas);
});
});
}
</script>
<!-- page content -->
<div class="row">
<div class="col-md-12">
<div class="x_panel">
<div class="x_title">
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
<ul class="dropdown-menu" role="menu">
</ul>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a>
</li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content">
<section class="content invoice">
<!-- title row -->
<div class="row">
<div class="col-xs-7 invoice-header">
<h1>
Expediente.
</h1>
</div>
<!-- /.col -->
</div>
<div class="row invoice-info">
<div class="col-sm-12 invoice-col">
<address>
<ul class="nav nav-pills">
<li id="agregarContraparte" class="" role="presentation" type="li"><a href="#">Agregar contraparte</a></li>
<input style="display:none;"id="numExpedienteGlobal"></input>
<input style="display:none;"id="expediente"></input>
<li id="visualizarContraparte" role="presentation" class=" " type="li"><a href="#">Visualizar contrapartes</a></li>
<li id="respuestasContestadas" role="presentation" class=" " type="li"><a href="#"> Contestadas</a></li>
<li id="idSeguimiento" role="presentation" class="active botonContraparte" type="li"> <a href="#">Seguimiento</a></li>
<li id="registroAmparo" role="presentation" class=" " type="li" onclick="registrarAmparo()"><a href="#"> Registrar amparo</a></li>
<li id="finalizar" role="presentation" class=" " type="li" onclick="verFinalizar()"><a href="#"> Finalizar expediente</a></li>
</ul>
<!-- <button id="agregarContraparte" type="button">Agregar Contraparte</button>
<input style="display:none;"id="numExpedienteGlobal"></input>
<input style="display:none;"id="expediente"></input>
<button id="visualizarContraparte" type="button">Visualizar contrapartes</button>
<button id="respuestasContestadas" type="button"> Contestadas</button>
<button id="idSeguimiento" type="button"> seguimiento</button>
<button id="finalizar" type="button" onclick="verFinalizar()"> Finalizar expediente</button> -->
</address>
</div>
</div>
<div class="row">
<div class="col-xs-12 table">
<div id="divInstancia" class="form-horizontal form-label-left"> <div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="respuesta">Instancia
</label>
<div id="idRespuestaCambio" class="col-md-6 col-sm-6 col-xs-12">
<select id='agrarioIntancia' onchange="iniciarPregunta(this)" respuesta='valor' required=' ' class='form-control '>
<option value="NINGUNO" >- Seleccione -</option>
<option value="1">1 Instancia</option>
<option value="2">2 instancia</option>
</select>
<div class="help-block with-errors"></div></div> </div> </div>
<div id="preguntasAmparo"><!-- PREGUNTAS PARA AMPARO -->
</div>
<div id="preguntas"><!-- SE PINTA LAS PREGUNTAS QUE SE TIENE QUE CONTESTAR(RRELLENAR PREGUNTAS) -->
</div>
<!-- <div id="rrellenarPregunta">
</div> -->
<!-- <form id="rrellenarPregunta" data-toggle="validator"enctype="multipart/form-data" role="form" class="" action ="../../controlador/expediente/seguimientoExpediente.php" object="defensor" method="post">
-->
<form id="rrellenarPregunta" data-toggle="validator" enctype="multipart/form-data" role="form" class="" object="pregunta">
</form>
</div>
<!-- /.col -->
<div id="registroContraparte">
</div>
</div>
<!-- VISUALIZAR LOS USUARIOS DE CONTRAPARTE -->
<div class="modal fade" id="modalContraparte" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Usuario(s)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miUsuarioContraparte" class="table-responsive x_content" title="infomación">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
--> <table id="verContraparte" class="table dt-responsive ui table" cellspacing="0" width="100%">
<thead>
<tr >
<th > Nombre </th>
<th > Apellido paterno </th>
<th > Apellido Materno </th>
<th > Idioma/lengua </th>
<th > Etnia </th></tr>
</thead>
<tbody id="datosUsuarioServicio">
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div> <!-- FIN DE LO OTRO INIICIO PARA EDITAR CONTRAPARTE -->
<div class="modal fade" id="modalEditarContraparte" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Usuario(s)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miEditarUsuarioContraparte" class="table-responsive x_content" title="infomación">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
-->
<div id="EditarUsuarioContraparte">
</div>
</div>
<form id="EditarContraparte" data-toggle="validator" role="form" class="example_form form-horizontal form-label-left"
enctype="multipart/form-data" object="defensor">
</form>
<div id="EditarContraparte">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- FIN DE LO OTRO INIICIO PARA ver finalizar expediente -->
<div class="modal fade" id="modalFinalExpediente" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Finalizar</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="miFinalizar" class="table-responsive x_content" title="infomación">
<!-- <table id="exampleuser" lass="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
-->
<div id="EditarUsuarioContraparte">
</div>
</div>
<form id="FinalizarExpedinte" data-toggle="validator" role="form" class="example_form form-horizontal form-label-left"
enctype="multipart/form-data" object="defensor">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-4">Fecha de finalización<span class="required"></span></label>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<input type="date" class="form-control " id="fecha_final" placeholder="Id personal" name="nombre">
<span class ="help-block"> <span >
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-4">observación<span class="required"></span></label>
<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
<textarea id="observacionFinal" name="accion_implementar" pattern="[A-Za-z0-9.,:áéíóú ]+" data-error="solo numeros o letras con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describa la(s) accion que debe realizar "></textarea>
<span class ="help-block"> <span >
</div>
</div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input class="btn btn-succes btn btn-success btn-lg" type="button" name="botonUpdate" onclick="finalizarExpedinte()" id="botonUpdate" value="finalizar"></input>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
<!-- <button type="button" class="btn btn-primary">Save changes</button> -->
</div>
</div>
</div>
</div>
<!-- <button class="btn btn-default" onclick="window.print();"><i class="fa fa-print"></i> Print</button>
-->
</section>
</div>
</div>
</div>
</div>
<!-- <script src="../../recursos/vendors/jquery/dist/jquery.min.js"></script> -->
<!-- <script src="../../recursos/js/custom.min.js"></script> -->
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/defensor/atendiendoExpediente.js"></script>
<script src="../../recursos/js/expediente/gestionContraparte.js"></script>
<script src="../../recursos/js/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script>
$('#myform').validator()
$('#myubicacion').hide()
$('#personal').hide()
$('#mycomprobante').hide()
//$("#idSeguimiento").hide()
$("#preguntas").hide()
$('#resultado').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
</script><file_sep><?php
include '../../modelo/actividad.php';
$inicio = $_POST['ini'];
$final = $_POST['fin'];
$sys = $_POST['sistema'];
$con= $_POST['consulta'];
$resultCon = getActividadesConsulta($inicio, $final, $sys);
/* switch($con){
case 'NUM':
break;
} */
$encode = json_encode($resultCon);
echo $encode;
?><file_sep>
<?php
include_once('../libreria/rfc/RfcBuilder.php');
$builder = new RfcBuilder();
/* $rfc = $builder->name('eduardo')
->firstLastName('castañon')
->secondLastName('olguin')
->birthday(15, 04, 1968)
->build()
->toString();
*/
$rfc = $builder->name($_GET['nombre'])
->firstLastName($_GET['apellidoP'])
->secondLastName($_GET['apellidoM'])
->birthday($_GET['dia'],$_GET['mes'], $_GET['anno'])
->build()
->toString();
echo trim ($rfc, " \t\n\r\0\x0B" );
?><file_sep># defensoriaPublica
proyecto
<file_sep><?php
//header('Content-Type: application/json');
include '../../modelo/juzgado.php';
include '../../modelo/defensor/defensor.php';
$listaJuzgado = listar_juzgado();
$equals="";
$contenido = json_encode($listaJuzgado);
$user = json_decode($contenido);
$juzgado = Array( );
foreach($user as $values){
// if($values->region!=$equals){
if(isset($juzgado[$values->region])==false){
$equals=$values->region;
$valor =Array();
// $valor[]=juzgadosIdentificados($user,$values->region);
// $juzgado[$values->region]=$valor;
$juzgado[$values->region]=juzgadosIdentificados($user,$values->region);
}
/* $arrayJuzgado=Array();
$arrayJuzgado['id_juzgado']=$values->id_juzgado;
$arrayJuzgado['nombre']=$values->juzgado;
*/
// $valor[]=$arrayJuzgado;
/* $valor[]=juzgadosIdentificados($user,$values->region);
*/
}
$contenidojuzgado = json_encode($juzgado);
//print_r($juzgado);
//$mensaje="Registro exitoso";
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
if(isset($_POST['nue'])){
$nue=$_POST['nue'];
$mensaje=['tipo'=>"error",
'mensaje'=>"no existe defensor con el nue ".$nue];
$juzgado=$_POST['adscripcion'];
$defensor= listar_defensor_x_nue($nue);
if($defensor!=0){
$mensaje=['tipo'=>"exito",
'mensaje'=>"cambio existoso"];
actualizar_juzgado($juzgado,$defensor[0]['id_personal']);
}
}
if(isset($_GET['tipo'])){
if($_GET['tipo']=="listadoJuzgadoSeguimiento"){//ENVIA EL JSON A LA VISTA DE SEGUIMIENTO
echo $contenidojuzgado;
}
if($_GET['tipo']=="html"){
session_start();
// $_SESSION['mensaje'] = "registro exitoso";
$_SESSION['mensaje'] = $mensaje;
header("location: ../../vistas/administrador/index.php?dirigir=cambioAdscripcion");
}
else{
header('Content-Type: application/json');
// echo "json";
}
}
// print_r($contenidojuzgado);
/*$user = json_decode($contenidojuzgado);
foreach($user as $values=>$key)
{
print_r($values);
foreach($key as $valor)
{
echo $valor;
print_r($valor);
// echo "<br>";
}
}*/
function juzgadosIdentificados($array,$region){
$arrayJuzgado=Array();
foreach ($array as $value) {
if ($value->region===$region) {
$juzgado = Array( );
$juzgado['id_juzgado']=$value->id_juzgado;
$juzgado['nombre']=$value->juzgado;
$juzgado['region']=$value->region;
array_push($arrayJuzgado, $juzgado);
}
}
return $arrayJuzgado;
}
// print_r(json_decode($contenidojuzgado));
?><file_sep>function informeByDefParcialPeriodo(jsonInforme, selectAtributos){
console.time('Test functionGlobalInformeAct');
var fechaI = document.getElementById('inputInicio').value;
var fechaFi = document.getElementById('inputFinal').value;
var nombreDef = jsonInforme[0]['Defensor']+' '+jsonInforme[0]['apDefP']+' '+jsonInforme[0]['apDefM'];
var fecha1 = new Date(fechaI);
var fecha2 = new Date(fechaFi);
var meses = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Nomviembre", "Diciembre"];
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//console.log(selectAtributos, ' atributos desde el pdf');
var tablaSexo={}, tablaGenero={}, tablaEdad={}, tablaEtnia={}, tablaIdioma={}, tablaDiscapacidad={};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
for(var i=0; i<selectAtributos.length; i++){
switch(selectAtributos[i]){
case "SEXO":
tablaSexo = getTablaSexo(totalH, totalM,totalSexo,totalSexoT, totalSexoO,sexos['numMascT'], sexos['numMascO'],sexos['numFemT'], sexos['numFemO']);
break;
case "GENERO":
tablaGenero = getTablaGenero(totalLesbico, totalGay,totalBisexual,totalTransexual, totalTransgenero,totalTravesti,totalIntersexual, totalG,
generos['numLesbicoT'], generos['numLesbicoT'], generos['numGayT'], generos['numGayO'], generos['numBisexualT'], generos['numBisexualO'],
generos['numTransexualT'], generos['numTransexualO'],generos['numTransgeneroT'], generos['numTransgeneroO'], generos['numTravestiT'], generos['numTravestiO'],
generos['numIntersexualT'], generos['numIntersexualO']
);
break;
}
//console.log(selectAtributos[i]);
}
var pdfAct = {
watermark: { text: 'www oaxaca gob mx', color: 'gray', opacity: 0.3, bold: true, italics: false },
pageSize: 'A4',
pageOrientation: 'portrait',
header: {
margin: [105, 20, 100, 0],
columns: [
{
// usually you would use a dataUri instead of the name for client-side printing
// sampleImage.jpg however works inside playground so you can play with it
image: 'data:image/png;base64,' + base64, width: 400, height: 60
}
]
},
footer: function (currentPage, pageCount) {
return {
table: {
widths: ['*', 00],
body: [
[
{ text: 'Pág. ' + currentPage + ' de ' + pageCount + ' ', alignment: 'center', bold: true, color: 'gray' }
]
]
},
layout: 'noBorders',
};
},
// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [80, 60, 40, 60],
content: [
{
stack: [
'“2018, AÑO DE LA ERRADICACIÓN DEL TRABAJO INFANTIL”',
{
text: '<NAME>, <NAME>, Oax; ' + primerM + siguiente + '.\n' +
'Periodo de ' + fechaI + ' a ' + fechaFi, style: 'subheader'
},
],
style: 'header'
},
{ text: 'A continuación se presenta el informe del defensor: '+nombreDef, style: 'textoJustificado'},
{ text: "", style: 'textoJustificado'},
{ text: '1.- <NAME>', style: 'subheader2' },
{ text: 'Con el objetivo de contribuir a una justicia pronta, expedita e imparcial, durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' del presente año, la Defensoría Pública brindó ' + actividades['asesorias'] + ' servicios gratuitos de asesorías jurídicas generales de un defensor, lo anterior se detalla de la siguiente manera:', style: 'textoJustificado' },
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorio y oral', style: 'tableHeader', alignment: 'center' },
],
['Asesorías simples Jurídicas', asesoriasTO['asesTradicional'], asesoriasTO['asesOral']],
]
}
},
{ text: 'Del total general de asesorías jurídicas, a continuación se desglosan los atributos de los beneficiarios:', style: 'textoJustificado' },
tablaSexo,tablaGenero,
{ text: '\n ', style: 'saltoLinea' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Edad', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'TOTAL', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', totalEdad1, edades['edades1T'], edades['edades1O']],
['25 A 29 AÑOS', totalEdad2, edades['edades2T'], edades['edades2O']],
['30 A 34 AÑOS', totalEdad3, edades['edades3T'], edades['edades3O']],
['35 A 39 AÑOS', totalEdad4, edades['edades4T'], edades['edades4O']],
['40 A 44 AÑOS', totalEdad5, edades['edades5T'], edades['edades5O']],
['45 A 49 AÑOS', totalEdad6, edades['edades6T'], edades['edades6O']],
['50 A 54 AÑOS', totalEdad7, edades['edades7T'], edades['edades7O']],
['55 A 59 AÑOS', totalEdad8, edades['edades8T'], edades['edades8O']],
['DE 60 O MAS AÑOS', totalEdad9, edades['edades9T'], edades['edades9O']],
['TOTAL', totalEdadS, totalEdadT,totalEdadO]
]
}
},
{
style: 'tableExample',
color: 'black',
table: {//etnias
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: etniasR
}
},
{ text: '\n\n', style: 'saltoLinea' }, { text: '\n\n', style: 'saltoLinea' },
{
style: 'tableExample',
color: 'black',
table: {
widths: [200, 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: idiomasR
}
},
{
style: 'tableExample',
color: 'black',
table: {
widths: ['auto', 'auto', 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'Discapacidades', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', totalSen, discapacidades['numSensorialesT'], discapacidades['numSensorialesO']],
['Motrices', totalMot, discapacidades['numMotricesT'], discapacidades['numMotricesO']],
['Mentales', totalMen, discapacidades['numMentalesT'], discapacidades['numMentalesO']],
['Multiples', totalMul, discapacidades['numMultiplesT'], discapacidades['numMultiplesO']],
['Total', totalDiscapacidad, totalDisT, totalDisO]
]
}
},
{ text: '2.- AUDIENCIAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' del presente año, el defensor público '+nombreDef+' asistio a '+actividades['audiencias']+' audiencias celebradas.', style: 'textoJustificado'
},
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
{ text: '3.- VISITAS CARCELARÍAS', style: 'subheader2' },
{
text: 'Durante el periodo que comprende del ' + fecha1.getUTCDate() + ' de ' + meses[fecha1.getUTCMonth()] + ' al ' + fecha2.getUTCDate() + ' de ' + meses[fecha2.getUTCMonth()] + ' del presente año, el defensor público '+nombreDef+' asistio a '+actividades['visitas']+' visitas carcelarias a sus internos.', style: 'textoJustificado'
},
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'C.c.p.-', style: ['quote', 'small'] },
{
text: 'Mtro. <NAME>.- Director de la Defensoría Pública del Estado de Oaxaca.- Para su conocimiento e intervención.- Presente.-C.P <NAME>.- Secretario Técnico.- Para mismo fin.- Presente Exp. y minutario.', style: ['quote', 'small']
}
]
]
}, layout: 'noBorders'
}
],
styles: {
header: {
fontSize: 8,
bold: false,
alignment: 'center',
margin: [0, 40, 0, 10]
},
subheader: {
fontSize: 10,
alignment: 'right',
margin: [0, 10, 0, 0]
},
textoJustificado: {
fontSize: 11,
alignment: 'justify',
margin: [0, 0, 15, 15],
},
subheader2: {
fontSize: 11,
alignment: 'left',
margin: [0, 0, 15, 15],
bold: 'true'
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
saltoLinea: {
margin: [0, 200, 0, 0]
},
quote: {
italics: true
},
small: {
fontSize: 8
}
},
defaultStyle: {
// alignment: 'justify'
}
}
console.timeEnd('Test functionGlobalInformeAct');
return pdfAct;
}
<file_sep><?php
// Borra todas las variables de sesión
$_SESSION = array();
// Borra la cookie que almacena la sesión
if(isset($_COOKIE[session_name()]) {
setcookie(session_name(), '', time() - 42000, '/');
}
// Finalmente, destruye la sesión
session_destroy();
header("Location: ../index.php");
?>
<file_sep> var registrar=document.getElementById('registrarDefensor');
registrar.addEventListener('click',regDefensores,false);
function regDefensores(){
$('#menuContainer').load("../usuarios/registrar.php");
};
var informeGActivi=document.getElementById('informeGAct');
informeGActivi.addEventListener('click', informeActividades, false);
function informeActividades() {
$('#menuContainer').load("informeGActividades.php");
};
var informeGExped=document.getElementById('informeGExp');
informeGExped.addEventListener('click', informeGExpedientes, false);
function informeGExpedientes() {
$('#menuContainer').load("informeGExpedientes.php");
};
var informePActivi=document.getElementById('informePAct');
informePActivi.addEventListener('click', informePActividades, false);
function informePActividades() {
$('#menuContainer').load("informePActividades.php");
};
var informePExped=document.getElementById('informePExp');
informePExped.addEventListener('click', informePExpedientes, false);
function informePExpedientes() {
$('#menuContainer').load("informePExpedientes.php");
};
var listarDef = document.getElementById('listarDefensores');
listarDef.addEventListener('click', listaDefensores, false);
function listaDefensores() {
$('#menuContainer').load("listarDefensores.php");
};
var listarExp = document.getElementById('listarExpedientes');
listarExp.addEventListener('click', listarExpedientes, false);
function listarExpedientes() {
$('#menuContainer').load("listarExpedientes.php");
};
var juzgadoRegistro=document.getElementById('registrarJuzgadoMenu');
juzgadoRegistro.addEventListener('click', function () {
$('#menuContainer').load("coordinadorRegistrarJuzgado.php");
}, false);
/* var asignar=document.getElementById('cambiarAdscripcion');
asignar.addEventListener('click',asinar,false);
function asinar(){
$('#menuContainer').load("../administrador/cambiarAdscripcion.php");
} */
<file_sep>var globalHeaderPDF = '<KEY>//<KEY>';
<file_sep><?php
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase
{
public function testPushAndPop()
{
$url='http://localhost/defensoriaPublica/controlador/defensor/controladorListaDef.php';
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Content-type: application/x-www-form-urlencoded',
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
// echo $result;
$this->assertEquals(200, intval($result));
}
}
?><file_sep><?php
include '../../modelo/actividad.php';
if(isset($_POST['nue'])){
$fechaInicio =$_POST['fechaI'];
$fechaFinal = $_POST['fechaF'];
$nue = $_POST['nue'];
$informeGeneralActNue = getActividadesByFiltroNue($fechaInicio, $fechaFinal, $nue);
$informeEncodeNue = json_encode($informeGeneralActNue);
echo $informeEncodeNue;
}else {
if(isset($_POST['radio1'])){
$fi= $_POST['fechaI'];
$ff= $_POST['fechaF'];
if($_POST['check'] == 'true'){//informe por periodo y defensor en especifico
if(isset($_POST['defensor'])){
$def = $_POST['defensor'];
$informeByDefPeriodo = getActividadesByDefPeriodo($fi,$ff,$def);
$informeEncode = json_encode($informeByDefPeriodo);
print_r($informeEncode);
}
}else{//informe by periodo solamente
$informeByPeriodo = getActividadesByPeriodo($fi,$ff);
//print_r($informeByPeriodo);
$informeEncode = json_encode($informeByPeriodo);
print_r($informeEncode);
//echo 'kjashdkjahskdjhaskjh';
}
}
if(isset($_POST['radio2'])){
if($_POST['check'] == 'true'){//informe por periodo y defensor en especifico
if(isset($_POST['defensor'])){
$def = $_POST['defensor'];
$informeByDefCompleto = getActividadesByDefCompleto($def);
$informeEncode = json_encode($informeByDefCompleto);
print_r($informeEncode);
}
}else{
$informeActGCompleto = getActividadesGC();
$informeEncode = json_encode($informeActGCompleto);
print_r($informeEncode);
//echo 'kjashdkjahskdjhaskjh';
}
}
if(isset($_POST['radio3'])){
$fi= $_POST['fechaI'];
$ff= $_POST['fechaF'];
$sistema=$_POST['sistema'];
$atributos=$_POST['atributos'];
if($_POST['check'] == 'true'){//informe por periodo y defensor en especifico
if(isset($_POST['defensor'])){
$def = $_POST['defensor'];
$informeByDefPeriodoP = getActividadesByDefPeriodoP($fi,$ff,$def, $sistema, $atributos);
$informeEncode = json_encode($informeByDefPeriodoP);
print_r($informeEncode);
}
}else{
$informeByPeriodoCP = getActividadesByPeriodoCP($fi,$ff, $sistema, $atributos);
$informeEncode = json_encode($informeByPeriodoCP);
print_r($informeEncode);
}
}
if(isset($_POST['radio4'])){
$sistema=$_POST['sistema'];
$atributos=$_POST['atributos'];
if($_POST['check'] == 'true'){//informe por periodo y defensor en especifico
if(isset($_POST['defensor'])){
$def = $_POST['defensor'];
$informeByDefPC = getActividadesByDefPC($def, $sistema, $atributos);
$informeEncode = json_encode($informeByDefPC);
print_r($informeEncode);
}
}else{//informe by periodo solamente
$informePC = getActividadesPC($sistema, $atributos);
$informeEncode = json_encode($informePC);
print_r($informeEncode);
}
}
}
?>
<file_sep><?php
include '../../modelo/expediente.php';
$id_defensor = $_POST['usuarios'];
$id_expediente= $_POST['expedienteNum'];
$asigna= updateExpediente($id_defensor, $id_expediente);
DeleteNotificacion($id_expediente);
//echo $expedientes;
session_start();
$_SESSION['post_data'] = 1;
header('Location: ../../vistas/administrador/index.php');
//echo '<script>$("#dialogoCambio").dialog("close")</script>';
?><file_sep><?php
include_once('../../modelo/expediente.php');
$q = intval($_GET['q']);
$q2 = strtoupper($_GET['q2']);
if($q == "" && $q2 != ""){
//por materia
$lista_expedienteM = listar_expedientes_x_materia($q2);
$encode = json_encode($lista_expedienteM);
echo $encode;
}else if($q != "" && $q2 == ""){
//filtro por estado
$lista_expedienteE = listar_expedientes_x_estado($q);
$encode = json_encode($lista_expedienteE);
echo $encode;
}else if($q != "" && $q2 != ""){
//filtro estado y materia
$lista_expedienteEM = listar_expedientes_EM($q, $q2);
$encode = json_encode($lista_expedienteEM);
echo $encode;
}
?><file_sep><?php
//require_once ("PHPMailderAutoload.php");
//Definimos la funciones para trabajar en PHP
function test_input($cadena){
htmlspecialchars($cadena);
addslashes($cadena);
return $cadena;
}
function cadenaToMayuscula($dato){
if(validarCadena($dato))
return strtoupper($dato);
return $dato;
}
function validarCadena($dato){
$nuevoArray =Array();
if(is_numeric($dato))
return false;
if(filter_var($dato, FILTER_VALIDATE_EMAIL))
return false;
return $dato;
}
//funcion que envia un correo electronico
function envio_correo($dir_email, $asunto, $mensaje){
// ini_set('SMTP','smtp.gmail.com');
//ini_set('smtp_port',587);
$cabecera = "From: <<EMAIL>>";
$headers = "MIME-Version: 1.0/r/n";
$headers.= "Content-type: text/html; charset=iso-8859-1/r/n";
$headers.= $cabecera."/r/n";
mail($dir_email, $asunto, $mensaje, $cabecera);
/* $address = "<EMAIL>";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Host = " ";
$mail->Port = 465;
$mail->SetFrom("<EMAIL>",'bolsa de trabajo');
$mail->AddAddress($address);
$mail->Username = "<EMAIL>";
$mail->Password = "<PASSWORD>";
$mail->Subject = $asunto;
$mail->Body = $mensaje;
$mail->WordWrap=50;
if(!$mail->Send()) {
echo "no enviado";
} else {
echo "enviado";
} */
}
//funcion encriptar
function encriptar($password){
return password_hash($password,PASSWORD_DEFAULT);
}
?><file_sep><?php
include '../../modelo/consulta/consultas.php';
if(isset($_POST['filtro'])){
if($_POST['sistema'] == "ALL"){
$mat = getMaterias();
echo json_encode($mat);
}else{
if($_POST['filtro'] == 'AMBAS'){
$sis = $_POST['sistema'];
$mat = getMatRegion($sis);
echo json_encode($mat);
}
if($_POST['filtro'] == 'MATERIA'){
$sis = $_POST['sistema'];
$mat = getMateriaBySistema($sis);
echo json_encode($mat);
}
if($_POST['filtro'] == 'REGION'){
$sis = $_POST['sistema'];
$mat = getRegionBySistema($sis);
echo json_encode($mat);
}
}
}else {
}
?>
<file_sep><?php
include_once('../../modelo/defensor/defensor.php');
$listaDef = listar_defensores();
$contenido = json_encode($listaDef);
if(isset($_GET['term'])){
if(isset($_GET['sistema']) && isset($_GET['materia'])){
// print_r("imprimiendo datos queoijoi sisema ".$_GET['sistema'])." materia".isset($_GET['materia']);
switch($_GET['sistema']){
case 'ALL':
$listaDef = listar_defensoresMateria($_GET['materia']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'TRADICIONAL':
$listaDef = listar_defensoresSisMat($_GET['sistema'],$_GET['materia']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'ORAL':
$listaDef = listar_defensoresSisMat($_GET['sistema'],$_GET['materia']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
}
}
if(isset($_GET['sistema']) && isset($_GET['region'])){
switch($_GET['sistema']){
case'ALL':
$listaDef = listar_defensoresRegion($_GET['region']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'TRADICIONAL':
$listaDef = listar_defensoresSisReg($_GET['sistema'],$_GET['region']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'ORAL':
$listaDef = listar_defensoresSisReg($_GET['sistema'],$_GET['region']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
}
}
if(isset($_GET['sistema']) && !isset($_GET['region']) && !isset($_GET['materia'])){
switch($_GET['sistema']){
case'ALL':
$listaDef = listar_defensores();
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'TRADICIONA':
$listaDef = listar_defensoresSis($_GET['sistema']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
case 'ORAL':
$listaDef = listar_defensoresSis($_GET['sistema']);
$contenido = json_encode($listaDef);
echo $contenido;
break;
}
}
<<<<<<< HEAD
// echo $contenido;
}else{
// echo $contenido;
=======
}else{
//echo $contenido;
>>>>>>> 40a0c5151d8e9475b303dfdef1e845e96100e72d
}
?><file_sep>function informeCompletoParcialT(selAtrib){
console.log('apenad entro a informecompletoParcialT');
console.time('Test functionGlobalInformeAct');
var tablaSexo = {};
var tablaGenero = {};
var tablaDiscapacidades = {};
var tablaEdad = {};
var tablaIdiomas = {};
var tablaEtnias = {};
var top10Defensores = {};
top10Defensores = getTablaTopTen('TRADICIONAL');
var tablaGeneral = {};
tablaGeneral = getTablaGeneral('TRADICIONAL');
for(var i=0; i<selAtrib.length; i++){
switch(selAtrib[i]){
case 'SEXO':
tablaSexo = getTablaSexo('TRADICIONAL');
break;
case 'GENERO':
tablaGenero = getTablaGenero('TRADICIONAL');
break;
case 'EDAD':
tablaEdad = getTablaEdad('TRADICIONAL');
break;
case 'ETNIA':
tablaEtniaa = getTablaEtnias('TRADICIONAL');
break;
case 'IDIOMA':
tablaIdiomas = getTablaIdiomas('TRADICIONAL');
break;
case 'DISCAPACIDAD':
tablaDiscapacidades = getTablaDiscapacidad('TRADICIONAL');
break;
}
}
var pdfAct = {
watermark: { text: 'www oaxaca gob mx', color: 'gray', opacity: 0.3, bold: true, italics: false },
pageSize: 'A4',
pageOrientation: 'portrait',
header: {
margin: [105, 20, 100, 0],
columns: [
{
// usually you would use a dataUri instead of the name for client-side printing
// sampleImage.jpg however works inside playground so you can play with it
image: 'data:image/png;base64,' + base64, width: 400, height: 60
}
]
},
footer: function (currentPage, pageCount) {
return {
table: {
widths: ['*', 00],
body: [
[
{ text: 'Pág. ' + currentPage + ' de ' + pageCount + ' ', alignment: 'center', bold: true, color: 'gray' }
]
]
},
layout: 'noBorders',
};
},
// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [80, 60, 40, 60],
content: [
{
stack: [
'“2018, AÑO DE LA ERRADICACIÓN DEL TRABAJO INFANTIL”',
{
text: '<NAME>, <NAME>, Oax; ' + primerM + siguiente + '.\n' +
'Completo', style: 'subheader'
},
],
style: 'header'
},
{ text: '1.- ASESORÍAS JURÍDICAS', style: 'subheader2' },
{ text: 'Con el objetivo de contribuir a una justicia pronta, expedita e imparcial, la Defensoría Pública brindó ' + actividades['asesorias'] + ' servicios gratuitos de asesorías jurídicas generales, lo anterior se detalla de la siguiente manera:', style: 'textoJustificado' },
tablaGeneral,
{ text: 'Del total general de asesorías jurídicas, a continuación se desglosan los atributos de los beneficiarios:', style: 'textoJustificado' },
tablaSexo,
tablaGenero,
tablaEdad,
tablaEtnias,
tablaIdiomas,
tablaDiscapacidades,
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de asesorías jurídicas brindadas en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos en asesorías jurídicas, esto también por sistema. ', style: 'textoJustificado' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE ASESORÍAS JURÍDICAS' },
top10Defensores,
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE ASESORÍAS JURÍDICAS' },
getTablaTopTen('TRADICIONAL'),
{ text: '2.- AUDIENCIAS', style: 'subheader2' },
{
text: 'Los defensores publicos asistieron a ' + actividades['audiencias'] + ' audiencias celebradas.', style: 'textoJustificado'
},
{ text: 'Por sistema__________ Sistema Tradicional: materia penal _____; materia civil ________; materia familiar _______; materia administrativa _______; materia agraria ________; materia ejecución de sanciones ________; tribunal de alzada _______. Sistema Acusatorio y oral: materia penal adultos __________; materia penal adolescentes ________; materia ejecución de sanciones ________.', style: 'textoJustificado' },
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de asistencia a audiencias en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos de asistencia en audiencias, esto también por sistema.', style: 'textoJustificado' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE AUDIENCIAS' },
getTablaTopTen('TRADICIONAL'),
{ text: '\n ', style: 'saltoLinea' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE AUDIENCIAS' },
getTablaTopTen('TRADICIONAL'),
{ text: '3.- VISITAS CARCELARÍAS', style: 'subheader2' },
{
text: 'Los Defensores Públicos realizaron ___________ visitas carcelarias a sus internos.', style: 'textoJustificado'
},
{ text: 'Por sistema__________ Sistema Tradicional: materia penal _____; materia ejecución de sanciones ________ Sistema Acusatorio y oral: materia penal adultos __________; materia penal adolescentes ________; materia ejecución de sanciones ________.', style: 'textoJustificado' },
{ text: '* Mostrar listado de los 10 defensores públicos que reportan un alto número de visitas carcelarias en el periodo establecido en la búsqueda, así como los 10 defensores que reportan los números más bajos en visitas carcelarias , esto también por sistema.', style: 'textoJustificado' },
{ text: '\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON ALTO NÚMERO DE VISITAS CARCELARÍAS' },
getTablaTopTen('TRADICIONAL'),
{ text: '\n\n\n ', style: 'saltoLinea' },
{ text: '\n\n ', style: 'saltoLinea' },
{ text: '10 DEFENSORES CON UN BAJO NÚMERO DE VISITAS CARCELARÍAS' },
getTablaTopTen('TRADICIONAL'),
{
style: 'tableExample',
color: 'black',
table: {
headerRows: 1,
// keepWithHeaderRows: 1,
body: [
[
{ text: 'C.c.p.-', style: ['quote', 'small'] },
{
text: 'Mtro. <NAME>.- Director de la Defensoría Pública del Estado de Oaxaca.- Para su conocimiento e intervención.- Presente.-C.P <NAME>tos.- Secretario Técnico.- Para mismo fin.- Presente Exp. y minutario.', style: ['quote', 'small']
}
]
]
}, layout: 'noBorders'
}
],
styles: {
header: {
fontSize: 8,
bold: false,
alignment: 'center',
margin: [0, 40, 0, 10]
},
subheader: {
fontSize: 10,
alignment: 'right',
margin: [0, 10, 0, 0]
},
textoJustificado: {
fontSize: 11,
alignment: 'justify',
margin: [0, 0, 15, 15],
},
subheader2: {
fontSize: 11,
alignment: 'left',
margin: [0, 0, 15, 15],
bold: 'true'
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
},
saltoLinea: {
margin: [0, 200, 0, 0]
},
quote: {
italics: true
},
small: {
fontSize: 8
}
},
defaultStyle: {
// alignment: 'justify'
}
}
console.timeEnd('Test functionGlobalInformeAct');
return pdfAct;
}
function informeCompletoParcialO(jsonInforme){
}
function informeCompletoParcialJ(jsonInforme){
}
function informeCompletoParcialALL(jsonInforme){
}<file_sep><<<<<<< HEAD
-- MySQL dump 10.13 Distrib 5.7.12, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: bddefensoria
-- ------------------------------------------------------
-- Server version 5.5.5-10.1.31-MariaDB
/*!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 utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `asesorias`
--
DROP TABLE IF EXISTS `asesorias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `asesorias` (
`id_reporte` int(11) NOT NULL,
`foto` mediumblob NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_asesoriareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `asesorias`
--
LOCK TABLES `asesorias` WRITE;
/*!40000 ALTER TABLE `asesorias` DISABLE KEYS */;
/*!40000 ALTER TABLE `asesorias` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `audiencias`
--
DROP TABLE IF EXISTS `audiencias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `audiencias` (
`id_reporte` int(11) NOT NULL,
`latitud` decimal(10,0) NOT NULL,
`longitud` decimal(10,0) NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_audienciareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `audiencias`
--
LOCK TABLES `audiencias` WRITE;
/*!40000 ALTER TABLE `audiencias` DISABLE KEYS */;
/*!40000 ALTER TABLE `audiencias` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `bitacora`
--
DROP TABLE IF EXISTS `bitacora`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bitacora` (
`id_bitacora` int(11) NOT NULL AUTO_INCREMENT,
`pregunta` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id_bitacora`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `bitacora`
--
LOCK TABLES `bitacora` WRITE;
/*!40000 ALTER TABLE `bitacora` DISABLE KEYS */;
/*!40000 ALTER TABLE `bitacora` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `cargo`
--
DROP TABLE IF EXISTS `cargo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cargo` (
`id_cargo` int(11) NOT NULL AUTO_INCREMENT,
`cargo` varchar(20) NOT NULL,
PRIMARY KEY (`id_cargo`),
UNIQUE KEY `id_cargo_UNIQUE` (`id_cargo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `cargo`
--
LOCK TABLES `cargo` WRITE;
/*!40000 ALTER TABLE `cargo` DISABLE KEYS */;
/*!40000 ALTER TABLE `cargo` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `defensor`
--
DROP TABLE IF EXISTS `defensor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defensor` (
`id_defensor` int(11) NOT NULL AUTO_INCREMENT,
`id_juzgado` int(11) NOT NULL,
`id_personal` int(11) NOT NULL,
PRIMARY KEY (`id_defensor`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
KEY `fk_defensorjuzgado` (`id_juzgado`),
CONSTRAINT `fk_defensorjuzgado` FOREIGN KEY (`id_juzgado`) REFERENCES `juzgado` (`id_juzgado`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_defensorpersonal` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `defensor`
--
LOCK TABLES `defensor` WRITE;
/*!40000 ALTER TABLE `defensor` DISABLE KEYS */;
/*!40000 ALTER TABLE `defensor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `detalleperestudio`
--
DROP TABLE IF EXISTS `detalleperestudio`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `detalleperestudio` (
`id_personal` int(11) NOT NULL,
`id_estudios` int(11) NOT NULL,
KEY `id_personal` (`id_personal`),
KEY `id_estudios` (`id_estudios`),
CONSTRAINT `fk_estudiosdetalle` FOREIGN KEY (`id_estudios`) REFERENCES `estudios` (`id_estudios`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_personaldetalle` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `detalleperestudio`
--
LOCK TABLES `detalleperestudio` WRITE;
/*!40000 ALTER TABLE `detalleperestudio` DISABLE KEYS */;
/*!40000 ALTER TABLE `detalleperestudio` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `estudios`
--
DROP TABLE IF EXISTS `estudios`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `estudios` (
`id_estudios` int(11) NOT NULL AUTO_INCREMENT,
`grado_estudio` varchar(45) NOT NULL,
`fecha_termino` date NOT NULL,
`instituto` varchar(45) NOT NULL,
`plan_estudios` varchar(45) NOT NULL,
`descripcion_perfil_egreso` varchar(45) NOT NULL,
`cedula_profesional` varchar(20) DEFAULT NULL,
`perfil` varchar(20) DEFAULT NULL,
`documento_provatorio` mediumblob NOT NULL,
PRIMARY KEY (`id_estudios`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `estudios`
--
LOCK TABLES `estudios` WRITE;
/*!40000 ALTER TABLE `estudios` DISABLE KEYS */;
/*!40000 ALTER TABLE `estudios` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `expediente`
--
DROP TABLE IF EXISTS `expediente`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expediente` (
`id_expediente` int(11) NOT NULL AUTO_INCREMENT,
`num_expediente` varchar(20) NOT NULL,
`fecha_inicio` date NOT NULL,
`fecha_final` date NOT NULL,
`tipo_delito` char(3) NOT NULL,
`nombre_delito` varchar(20) NOT NULL,
`estado` char(2) NOT NULL,
PRIMARY KEY (`id_expediente`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `expediente`
--
LOCK TABLES `expediente` WRITE;
/*!40000 ALTER TABLE `expediente` DISABLE KEYS */;
/*!40000 ALTER TABLE `expediente` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `juzgado`
--
DROP TABLE IF EXISTS `juzgado`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `juzgado` (
`id_juzgado` int(11) NOT NULL AUTO_INCREMENT,
`juzgado` varchar(100) NOT NULL,
`region` varchar(20) NOT NULL,
`calle` varchar(15) NOT NULL,
`numero_ext` varchar(5) NOT NULL,
`numero_int` varchar(5) NOT NULL,
`municipio` varchar(15) NOT NULL,
`cp` varchar(6) NOT NULL,
`num_telefono` varchar(12) NOT NULL,
PRIMARY KEY (`id_juzgado`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `juzgado`
--
LOCK TABLES `juzgado` WRITE;
/*!40000 ALTER TABLE `juzgado` DISABLE KEYS */;
/*!40000 ALTER TABLE `juzgado` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `juzgado_materia`
--
DROP TABLE IF EXISTS `juzgado_materia`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `juzgado_materia` (
`id_juzgado` int(11) NOT NULL,
`id_materia` int(11) NOT NULL,
KEY `id_juzgado` (`id_juzgado`),
KEY `id_materia` (`id_materia`),
CONSTRAINT `fk_juzgadodetalle` FOREIGN KEY (`id_juzgado`) REFERENCES `juzgado` (`id_juzgado`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_materiadetalle` FOREIGN KEY (`id_materia`) REFERENCES `materia` (`id_materia`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `juzgado_materia`
--
LOCK TABLES `juzgado_materia` WRITE;
/*!40000 ALTER TABLE `juzgado_materia` DISABLE KEYS */;
/*!40000 ALTER TABLE `juzgado_materia` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `materia`
--
DROP TABLE IF EXISTS `materia`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `materia` (
`id_materia` int(11) NOT NULL AUTO_INCREMENT,
`id_sistema` int(11) NOT NULL,
`materia` varchar(45) NOT NULL,
`fase` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_materia`),
KEY `id_sistema` (`id_sistema`),
CONSTRAINT `fk_materiasistema` FOREIGN KEY (`id_sistema`) REFERENCES `sistema` (`id_sistema`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `materia`
--
LOCK TABLES `materia` WRITE;
/*!40000 ALTER TABLE `materia` DISABLE KEYS */;
/*!40000 ALTER TABLE `materia` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `personal`
--
DROP TABLE IF EXISTS `personal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal` (
`id_personal` int(11) NOT NULL AUTO_INCREMENT,
`id_cargo` int(11) NOT NULL,
`id_estudios` int(11) NOT NULL,
`nombre` varchar(45) NOT NULL,
`ap_paterno` varchar(45) NOT NULL,
`ap_materno` varchar(45) NOT NULL,
`curp` varchar(45) NOT NULL,
`calle` varchar(45) NOT NULL,
`numero_ext` varchar(45) NOT NULL,
`numero_int` varchar(45) NOT NULL,
`colonia` varchar(45) NOT NULL,
`municipio` varchar(15) NOT NULL,
`nup` varchar(45) NOT NULL,
`nue` varchar(45) NOT NULL,
`genero` varchar(45) NOT NULL,
`telefono` varchar(45) NOT NULL,
`corre_electronico` varchar(45) NOT NULL,
`foto` mediumblob NOT NULL,
PRIMARY KEY (`id_personal`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
UNIQUE KEY `id_cargo_UNIQUE` (`id_cargo`),
CONSTRAINT `fk_personalcargo` FOREIGN KEY (`id_cargo`) REFERENCES `cargo` (`id_cargo`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `personal`
--
LOCK TABLES `personal` WRITE;
/*!40000 ALTER TABLE `personal` DISABLE KEYS */;
/*!40000 ALTER TABLE `personal` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `reporte`
--
DROP TABLE IF EXISTS `reporte`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reporte` (
`id_reporte` int(11) NOT NULL AUTO_INCREMENT,
`id_expediente` int(11) NOT NULL,
`observaciones` varchar(255) DEFAULT NULL,
`fecha_registro` date NOT NULL,
PRIMARY KEY (`id_reporte`),
KEY `id_expediente` (`id_expediente`),
CONSTRAINT `fk_expRep` FOREIGN KEY (`id_expediente`) REFERENCES `expediente` (`id_expediente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `reporte`
--
LOCK TABLES `reporte` WRITE;
/*!40000 ALTER TABLE `reporte` DISABLE KEYS */;
/*!40000 ALTER TABLE `reporte` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `respuesta`
--
DROP TABLE IF EXISTS `respuesta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `respuesta` (
`id_bitacora` int(11) NOT NULL,
`id_reporte` int(11) NOT NULL,
KEY `id_reporte` (`id_reporte`),
KEY `id_bitacora` (`id_bitacora`),
CONSTRAINT `fk_respuestabitacora` FOREIGN KEY (`id_bitacora`) REFERENCES `bitacora` (`id_bitacora`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_respuestareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `respuesta`
--
LOCK TABLES `respuesta` WRITE;
/*!40000 ALTER TABLE `respuesta` DISABLE KEYS */;
/*!40000 ALTER TABLE `respuesta` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `seguimiento_caso`
--
DROP TABLE IF EXISTS `seguimiento_caso`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `seguimiento_caso` (
`id_seguimiento_caso` int(11) NOT NULL AUTO_INCREMENT,
`id_usuario_servicio` int(11) NOT NULL,
`id_defensor` int(11) NOT NULL,
PRIMARY KEY (`id_seguimiento_caso`),
KEY `id_usuario_servicio` (`id_usuario_servicio`),
KEY `id_defensor` (`id_defensor`),
CONSTRAINT `fk_seguimientodefensor_` FOREIGN KEY (`id_defensor`) REFERENCES `defensor` (`id_defensor`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_seguimientousuario` FOREIGN KEY (`id_usuario_servicio`) REFERENCES `usuario_servicio` (`id_usuario_servicio`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `seguimiento_caso`
--
LOCK TABLES `seguimiento_caso` WRITE;
/*!40000 ALTER TABLE `seguimiento_caso` DISABLE KEYS */;
/*!40000 ALTER TABLE `seguimiento_caso` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sistema`
--
DROP TABLE IF EXISTS `sistema`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sistema` (
`id_sistema` int(11) NOT NULL AUTO_INCREMENT,
`tipo_sistema` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_sistema`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sistema`
--
LOCK TABLES `sistema` WRITE;
/*!40000 ALTER TABLE `sistema` DISABLE KEYS */;
/*!40000 ALTER TABLE `sistema` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `usuario_servicio`
--
DROP TABLE IF EXISTS `usuario_servicio`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usuario_servicio` (
`id_usuario_servicio` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(25) NOT NULL,
`ap_materno` varchar(20) NOT NULL,
`ap_paterno` varchar(20) NOT NULL,
`genero` varchar(10) NOT NULL,
`edad` varchar(10) DEFAULT NULL,
`idioma` varchar(15) NOT NULL,
`etnia` varchar(15) NOT NULL,
`curp` varchar(18) NOT NULL,
`calle` varchar(15) NOT NULL,
`numero_ext` varchar(5) NOT NULL,
`numero_int` varchar(5) DEFAULT NULL,
`municipio` varchar(15) NOT NULL,
`nacionalidad` varchar(15) NOT NULL,
`lugar_nacimiento` varchar(30) NOT NULL,
`fecha_nacimiento` date NOT NULL,
`telefono` varchar(12) NOT NULL,
`correo_electronico` varchar(20) NOT NULL,
PRIMARY KEY (`id_usuario_servicio`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `usuario_servicio`
--
LOCK TABLES `usuario_servicio` WRITE;
/*!40000 ALTER TABLE `usuario_servicio` DISABLE KEYS */;
/*!40000 ALTER TABLE `usuario_servicio` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `usuario_sistema`
--
DROP TABLE IF EXISTS `usuario_sistema`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usuario_sistema` (
`id_usuario_sistema` int(11) NOT NULL AUTO_INCREMENT,
`id_personal` int(11) NOT NULL,
`username` varchar(45) NOT NULL,
`password` varchar(255) NOT NULL,
`estado` tinyint(1) NOT NULL,
PRIMARY KEY (`id_usuario_sistema`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
CONSTRAINT `fk_usuarioSispersonal` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `usuario_sistema`
--
LOCK TABLES `usuario_sistema` WRITE;
/*!40000 ALTER TABLE `usuario_sistema` DISABLE KEYS */;
/*!40000 ALTER TABLE `usuario_sistema` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `visitas_carcelarias`
--
DROP TABLE IF EXISTS `visitas_carcelarias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visitas_carcelarias` (
`id_reporte` int(11) NOT NULL,
`foto` mediumblob NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_visitareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `visitas_carcelarias`
--
LOCK TABLES `visitas_carcelarias` WRITE;
/*!40000 ALTER TABLE `visitas_carcelarias` DISABLE KEYS */;
/*!40000 ALTER TABLE `visitas_carcelarias` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-04-18 11:27:43
=======
-- MySQL dump 10.13 Distrib 5.7.12, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: bddefensoria
-- ------------------------------------------------------
-- Server version 5.5.5-10.1.31-MariaDB
/*!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 utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `asesorias`
--
DROP TABLE IF EXISTS `asesorias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `asesorias` (
`id_reporte` int(11) NOT NULL,
`foto` mediumblob NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_asesoriareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `asesorias`
--
LOCK TABLES `asesorias` WRITE;
/*!40000 ALTER TABLE `asesorias` DISABLE KEYS */;
/*!40000 ALTER TABLE `asesorias` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `audiencias`
--
DROP TABLE IF EXISTS `audiencias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `audiencias` (
`id_reporte` int(11) NOT NULL,
`latitud` decimal(10,0) NOT NULL,
`longitud` decimal(10,0) NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_audienciareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `audiencias`
--
LOCK TABLES `audiencias` WRITE;
/*!40000 ALTER TABLE `audiencias` DISABLE KEYS */;
/*!40000 ALTER TABLE `audiencias` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `bitacora`
--
DROP TABLE IF EXISTS `bitacora`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bitacora` (
`id_bitacora` int(11) NOT NULL AUTO_INCREMENT,
`pregunta` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id_bitacora`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `bitacora`
--
LOCK TABLES `bitacora` WRITE;
/*!40000 ALTER TABLE `bitacora` DISABLE KEYS */;
/*!40000 ALTER TABLE `bitacora` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `cargo`
--
DROP TABLE IF EXISTS `cargo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cargo` (
`id_cargo` int(11) NOT NULL AUTO_INCREMENT,
`cargo` varchar(20) NOT NULL,
PRIMARY KEY (`id_cargo`),
UNIQUE KEY `id_cargo_UNIQUE` (`id_cargo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `cargo`
--
LOCK TABLES `cargo` WRITE;
/*!40000 ALTER TABLE `cargo` DISABLE KEYS */;
/*!40000 ALTER TABLE `cargo` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `defensor`
--
DROP TABLE IF EXISTS `defensor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defensor` (
`id_defensor` int(11) NOT NULL AUTO_INCREMENT,
`id_juzgado` int(11) NOT NULL,
`id_personal` int(11) NOT NULL,
PRIMARY KEY (`id_defensor`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
KEY `fk_defensorjuzgado` (`id_juzgado`),
CONSTRAINT `fk_defensorjuzgado` FOREIGN KEY (`id_juzgado`) REFERENCES `juzgado` (`id_juzgado`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_defensorpersonal` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `defensor`
--
LOCK TABLES `defensor` WRITE;
/*!40000 ALTER TABLE `defensor` DISABLE KEYS */;
/*!40000 ALTER TABLE `defensor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `detalleperestudio`
--
DROP TABLE IF EXISTS `detalleperestudio`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `detalleperestudio` (
`id_personal` int(11) NOT NULL,
`id_estudios` int(11) NOT NULL,
KEY `id_personal` (`id_personal`),
KEY `id_estudios` (`id_estudios`),
CONSTRAINT `fk_estudiosdetalle` FOREIGN KEY (`id_estudios`) REFERENCES `estudios` (`id_estudios`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_personaldetalle` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `detalleperestudio`
--
LOCK TABLES `detalleperestudio` WRITE;
/*!40000 ALTER TABLE `detalleperestudio` DISABLE KEYS */;
/*!40000 ALTER TABLE `detalleperestudio` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `estudios`
--
DROP TABLE IF EXISTS `estudios`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `estudios` (
`id_estudios` int(11) NOT NULL AUTO_INCREMENT,
`grado_estudio` varchar(45) NOT NULL,
`fecha_termino` date NOT NULL,
`instituto` varchar(45) NOT NULL,
`plan_estudios` varchar(45) NOT NULL,
`descripcion_perfil_egreso` varchar(45) NOT NULL,
`cedula_profesional` varchar(20) DEFAULT NULL,
`perfil` varchar(20) DEFAULT NULL,
`documento_provatorio` mediumblob NOT NULL,
PRIMARY KEY (`id_estudios`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `estudios`
--
LOCK TABLES `estudios` WRITE;
/*!40000 ALTER TABLE `estudios` DISABLE KEYS */;
/*!40000 ALTER TABLE `estudios` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `expediente`
--
DROP TABLE IF EXISTS `expediente`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `expediente` (
`id_expediente` int(11) NOT NULL AUTO_INCREMENT,
`num_expediente` varchar(20) NOT NULL,
`fecha_inicio` date NOT NULL,
`fecha_final` date NOT NULL,
`tipo_delito` char(3) NOT NULL,
`nombre_delito` varchar(20) NOT NULL,
`estado` char(2) NOT NULL,
PRIMARY KEY (`id_expediente`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `expediente`
--
LOCK TABLES `expediente` WRITE;
/*!40000 ALTER TABLE `expediente` DISABLE KEYS */;
/*!40000 ALTER TABLE `expediente` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `juzgado`
--
DROP TABLE IF EXISTS `juzgado`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `juzgado` (
`id_juzgado` int(11) NOT NULL AUTO_INCREMENT,
`juzgado` varchar(100) NOT NULL,
`region` varchar(20) NOT NULL,
`calle` varchar(15) NOT NULL,
`numero_ext` varchar(5) NOT NULL,
`numero_int` varchar(5) NOT NULL,
`municipio` varchar(15) NOT NULL,
`cp` varchar(6) NOT NULL,
`num_telefono` varchar(12) NOT NULL,
PRIMARY KEY (`id_juzgado`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `juzgado`
--
LOCK TABLES `juzgado` WRITE;
/*!40000 ALTER TABLE `juzgado` DISABLE KEYS */;
/*!40000 ALTER TABLE `juzgado` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `juzgado_materia`
--
DROP TABLE IF EXISTS `juzgado_materia`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `juzgado_materia` (
`id_juzgado` int(11) NOT NULL,
`id_materia` int(11) NOT NULL,
KEY `id_juzgado` (`id_juzgado`),
KEY `id_materia` (`id_materia`),
CONSTRAINT `fk_juzgadodetalle` FOREIGN KEY (`id_juzgado`) REFERENCES `juzgado` (`id_juzgado`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_materiadetalle` FOREIGN KEY (`id_materia`) REFERENCES `materia` (`id_materia`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `juzgado_materia`
--
LOCK TABLES `juzgado_materia` WRITE;
/*!40000 ALTER TABLE `juzgado_materia` DISABLE KEYS */;
/*!40000 ALTER TABLE `juzgado_materia` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `materia`
--
DROP TABLE IF EXISTS `materia`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `materia` (
`id_materia` int(11) NOT NULL AUTO_INCREMENT,
`id_sistema` int(11) NOT NULL,
`materia` varchar(45) NOT NULL,
`fase` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_materia`),
KEY `id_sistema` (`id_sistema`),
CONSTRAINT `fk_materiasistema` FOREIGN KEY (`id_sistema`) REFERENCES `sistema` (`id_sistema`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `materia`
--
LOCK TABLES `materia` WRITE;
/*!40000 ALTER TABLE `materia` DISABLE KEYS */;
/*!40000 ALTER TABLE `materia` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `personal`
--
DROP TABLE IF EXISTS `personal`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `personal` (
`id_personal` int(11) NOT NULL AUTO_INCREMENT,
`id_cargo` int(11) NOT NULL,
`id_estudios` int(11) NOT NULL,
`nombre` varchar(45) NOT NULL,
`ap_paterno` varchar(45) NOT NULL,
`ap_materno` varchar(45) NOT NULL,
`curp` varchar(45) NOT NULL,
`calle` varchar(45) NOT NULL,
`numero_ext` varchar(45) NOT NULL,
`numero_int` varchar(45) NOT NULL,
`colonia` varchar(45) NOT NULL,
`municipio` varchar(15) NOT NULL,
`nup` varchar(45) NOT NULL,
`nue` varchar(45) NOT NULL,
`genero` varchar(45) NOT NULL,
`telefono` varchar(45) NOT NULL,
`corre_electronico` varchar(45) NOT NULL,
`foto` mediumblob NOT NULL,
PRIMARY KEY (`id_personal`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
UNIQUE KEY `id_cargo_UNIQUE` (`id_cargo`),
CONSTRAINT `fk_personalcargo` FOREIGN KEY (`id_cargo`) REFERENCES `cargo` (`id_cargo`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `personal`
--
LOCK TABLES `personal` WRITE;
/*!40000 ALTER TABLE `personal` DISABLE KEYS */;
/*!40000 ALTER TABLE `personal` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `reporte`
--
DROP TABLE IF EXISTS `reporte`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reporte` (
`id_reporte` int(11) NOT NULL AUTO_INCREMENT,
`id_expediente` int(11) NOT NULL,
`observaciones` varchar(255) DEFAULT NULL,
`fecha_registro` date NOT NULL,
PRIMARY KEY (`id_reporte`),
KEY `id_expediente` (`id_expediente`),
CONSTRAINT `fk_expRep` FOREIGN KEY (`id_expediente`) REFERENCES `expediente` (`id_expediente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `reporte`
--
LOCK TABLES `reporte` WRITE;
/*!40000 ALTER TABLE `reporte` DISABLE KEYS */;
/*!40000 ALTER TABLE `reporte` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `respuesta`
--
DROP TABLE IF EXISTS `respuesta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `respuesta` (
`id_bitacora` int(11) NOT NULL,
`id_reporte` int(11) NOT NULL,
KEY `id_reporte` (`id_reporte`),
KEY `id_bitacora` (`id_bitacora`),
CONSTRAINT `fk_respuestabitacora` FOREIGN KEY (`id_bitacora`) REFERENCES `bitacora` (`id_bitacora`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_respuestareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `respuesta`
--
LOCK TABLES `respuesta` WRITE;
/*!40000 ALTER TABLE `respuesta` DISABLE KEYS */;
/*!40000 ALTER TABLE `respuesta` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `seguimiento_caso`
--
DROP TABLE IF EXISTS `seguimiento_caso`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `seguimiento_caso` (
`id_seguimiento_caso` int(11) NOT NULL AUTO_INCREMENT,
`id_usuario_servicio` int(11) NOT NULL,
`id_defensor` int(11) NOT NULL,
PRIMARY KEY (`id_seguimiento_caso`),
KEY `id_usuario_servicio` (`id_usuario_servicio`),
KEY `id_defensor` (`id_defensor`),
CONSTRAINT `fk_seguimientodefensor_` FOREIGN KEY (`id_defensor`) REFERENCES `defensor` (`id_defensor`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_seguimientousuario` FOREIGN KEY (`id_usuario_servicio`) REFERENCES `usuario_servicio` (`id_usuario_servicio`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `seguimiento_caso`
--
LOCK TABLES `seguimiento_caso` WRITE;
/*!40000 ALTER TABLE `seguimiento_caso` DISABLE KEYS */;
/*!40000 ALTER TABLE `seguimiento_caso` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `sistema`
--
DROP TABLE IF EXISTS `sistema`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sistema` (
`id_sistema` int(11) NOT NULL AUTO_INCREMENT,
`tipo_sistema` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_sistema`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `sistema`
--
LOCK TABLES `sistema` WRITE;
/*!40000 ALTER TABLE `sistema` DISABLE KEYS */;
/*!40000 ALTER TABLE `sistema` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `usuario_servicio`
--
DROP TABLE IF EXISTS `usuario_servicio`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usuario_servicio` (
`id_usuario_servicio` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(25) NOT NULL,
`ap_materno` varchar(20) NOT NULL,
`ap_paterno` varchar(20) NOT NULL,
`genero` varchar(10) NOT NULL,
`edad` varchar(10) DEFAULT NULL,
`idioma` varchar(15) NOT NULL,
`etnia` varchar(15) NOT NULL,
`curp` varchar(18) NOT NULL,
`calle` varchar(15) NOT NULL,
`numero_ext` varchar(5) NOT NULL,
`numero_int` varchar(5) DEFAULT NULL,
`municipio` varchar(15) NOT NULL,
`nacionalidad` varchar(15) NOT NULL,
`lugar_nacimiento` varchar(30) NOT NULL,
`fecha_nacimiento` date NOT NULL,
`telefono` varchar(12) NOT NULL,
`correo_electronico` varchar(20) NOT NULL,
PRIMARY KEY (`id_usuario_servicio`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `usuario_servicio`
--
LOCK TABLES `usuario_servicio` WRITE;
/*!40000 ALTER TABLE `usuario_servicio` DISABLE KEYS */;
/*!40000 ALTER TABLE `usuario_servicio` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `usuario_sistema`
--
DROP TABLE IF EXISTS `usuario_sistema`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usuario_sistema` (
`id_usuario_sistema` int(11) NOT NULL AUTO_INCREMENT,
`id_personal` int(11) NOT NULL,
`username` varchar(45) NOT NULL,
`password` varchar(255) NOT NULL,
`estado` tinyint(1) NOT NULL,
PRIMARY KEY (`id_usuario_sistema`),
UNIQUE KEY `id_personal_UNIQUE` (`id_personal`),
CONSTRAINT `fk_usuarioSispersonal` FOREIGN KEY (`id_personal`) REFERENCES `personal` (`id_personal`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `usuario_sistema`
--
LOCK TABLES `usuario_sistema` WRITE;
/*!40000 ALTER TABLE `usuario_sistema` DISABLE KEYS */;
/*!40000 ALTER TABLE `usuario_sistema` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `visitas_carcelarias`
--
DROP TABLE IF EXISTS `visitas_carcelarias`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visitas_carcelarias` (
`id_reporte` int(11) NOT NULL,
`foto` mediumblob NOT NULL,
KEY `id_reporte` (`id_reporte`),
CONSTRAINT `fk_visitareporte` FOREIGN KEY (`id_reporte`) REFERENCES `reporte` (`id_reporte`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `visitas_carcelarias`
--
LOCK TABLES `visitas_carcelarias` WRITE;
/*!40000 ALTER TABLE `visitas_carcelarias` DISABLE KEYS */;
/*!40000 ALTER TABLE `visitas_carcelarias` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!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 */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-04-18 11:27:43
>>>>>>> bf38283aea2bbe94a479206d8b3ee6ce831f2c60
<file_sep><?php
header('Content-Type: application/json');
include_once ('../../modelo/actividad.php');
include_once('../../modelo/usuarioServicio.php');
include_once('../../modelo/asesoria.php');
include_once('../../modelo/visita.php');
include_once('../../modelo/audiencia.php');
$usuario_servicio=getUsuarioByCurp($_POST['curp'])[0]['id_usuario_servicio'];
//print_r(explode("-", "2018-01-09"));
$dia_registro=explode('-', $_POST['fechaRegistro'])[2];
$mes_registro=explode('-', $_POST['fechaRegistro'])[1];
$anio_registro=explode('-', $_POST['fechaRegistro'])[0];
$actividad = Array(
"id_personal_campo" =>$_POST['id_personal'],
"fecha_registro" =>$_POST['fechaRegistro'],
"id_usuario_servicio" =>$usuario_servicio,
"observacion" =>$_POST['resultado']
);
$mensaje=['tipo'=>"error",
'mensaje'=>"no existe el usuario con dicho curp"];
$dirigir="registrar_usario";
if($usuario_servicio)
{
crear_actividad($actividad);
// if($_POST["actividad"]=="asesoria"||$_POST["actividad"]=="visita"){
$id_actividadRegistrado=ultimoActividadRegistrado();
$ubicacion=explode(',',$_POST['ubicacion']);
//print_r($ubicacion);
$la=(count($ubicacion)==2)?$ubicacion[0]:"";
$long=(count($ubicacion)==2)?$ubicacion[1]:"";
// EN CASO DE QUE ES VISITAS Y CARGA EL COMPROBANTE(FOTO)
$nombreFoto="";
// echo "Error: " . $_FILES['archivo']['error'] ;
//echo "comprabante es =>".$_FILES["archivo"]["name"];
if(isset($_FILES['archivo']))
if ($_FILES['archivo']["error"] > 0)
{
// echo "Error: " . $_FILES['archivo']['error'] . "<br>";
$mensaje=['tipo'=>"error",
'mensaje'=>$_FILES['archivo']['error']];
$dirigir="registrar_actividad";
}
if($_FILES['archivo']['size'] != 0){
$nombreFoto = $_FILES["archivo"]["name"];
$rutaFoto = $_FILES["archivo"]["tmp_name"];
$carpeta='../../recursos/archivo/vistas';
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$destino = $carpeta.basename($nombreFoto);
move_uploaded_file($rutaFoto,$destino);
}
$actividadRealizada = Array(
"id_actividad" =>$id_actividadRegistrado,
"latitud" =>$la,
"longitud" =>$long,
"foto" =>$nombreFoto
);
// echo $_POST["actividad"];
if($_POST["actividad"]=="asesoria")
crear_asesoria($actividadRealizada);
if($_POST["actividad"]=="visita")
crear_visita($actividadRealizada);
if($_POST["actividad"]=="audiencia")
crear_audiencia($actividadRealizada);
print_r($actividadRealizada);
$mensaje=['tipo'=>"exito",
'mensaje'=>"Registro exitoso"];
$dirigir="registrar_actividad";
}
//////// CUANDO ES EJECUCION DE SANCIONES SE DEBE DE REGISTRAR LA FECHA EN QUE SE CREO EL EXPEDIENTE
/* $mensaje=['tipo'=>"error",
'mensaje'=>"expediente ya existe"];
$dirigir="asignar_defensor";
if((listar_x_num_expediente_($expediente['num_expediente'])==0)||($expediente['num_expediente']=="")){
echo "entro valido expediente".$expediente['num_expediente'];
if(listar_expedienteByPersonalAndMateria($expediente['id_usuario_servicio'],$expediente['materia'])==0)
{ echo "entro valido personal materia";
alta_expediente($expediente);
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
$dirigir="listar_Expediente";
}
else{
$mensaje=['tipo'=>"error",
'mensaje'=>"el usuario ya cuenta con un defensor del mismo problema"];
$dirigir="asignar_defensor";
}
} */
if(isset($_GET['tipo'])){
if($_GET['tipo']=="html"){
session_start();
// echo "solo ver";
$_SESSION['mensaje'] = $mensaje;
//$_SESSION['dirigir'] = $dirigir;
// echo $mensaje['mensaje'];
header("location: ../../vistas/defensor/index.php");
}
else{
header('Content-Type: application/json');
echo "json";
}
}
?><file_sep><?php
function testSavingUser()
{
$user = new User();
$user->setName('Miles');
$user->setSurname('Davis');
$user->save();
$this->assertEquals('<NAME>', $user->getFullName());
// $this->tester->seeInDatabase('users', ['name' => 'Miles', 'surname' => 'Davis']);
}<file_sep><?php
include_once('../../libreria/conexion.php');
function getMateriaBySistema($sis){
$sql="select distinct materia from materia where sistema='".$sis."'";
return consulta($sql);
}
function getMaterias(){
$sql="select distinct materia from materia";
return consulta($sql);
}
function getRegionBySistema($sis){
$sql="select distinct region from juzgado
inner join (
select * from
personal_campo as pc inner join
materia as ma using(id_materia)
)as tablaPer using(id_juzgado)
where tablaPer.sistema='".$sis."'";
return consulta($sql);
}
function getMatRegion($sis){
$lista = Array();
$lista['materia'] = getMateriaBySistema($sis);
$lista['region'] = getRegionBySistema($sis);
return $lista;
}
?>
<file_sep><?php
session_start();
//Evaluo que la sesion continue verificando una de las variables creadas en control.php, cuando esta ya no coincida con su valor inicial se redirije al archivo de salir.php
if (!$_SESSION["autentificado"]) {
header("Location: ../Controlador/salir.php");
}
<file_sep><?php
// header('Content-Type: application/json');
//include '../../modelo/personal.php';
include '../../modelo/respuesta/respuesta.php';
$listaRespuestaPregunta= respuestaPregunta($_GET['id_expediente']);
// echo $_GET['id_expediente'];
echo json_encode($listaRespuestaPregunta);
?><file_sep><?php
include '../../modelo/expediente.php';
$noti = checkNoti();
print_r($noti);
/*
session_start();
$_SESSION['post_data'] = 1; */
//header('Location: ../../vistas/administrador/index.php');
?><file_sep><?php
//include_once( '../../controlador/juzgado/actividad_juzgado.php');
session_start();
// print_r($_SESSION['personal']);
$id_personal = $_SESSION['personal'][0]['id_personal'];
$nombre = $_SESSION['personal'][0]['nombre'];
//echo $id_personal;
//echo $nombre;
?>
<!-- <script src="../../recursos/js/coordinador/atendiendoCoordinador.js"></script> -->
<script src="../../recursos/js/herramienta.js"></script>
<script src="../../recursos/js/defensor/actividad.js"></script>
<script>
/*
var varUsuario=[];
var datos = jQuery.parseJSON(window.Global_usuarios_servicios);
$.each(datos, function (KEY, VALOR) {
var temp={};
temp['label']=VALOR.nombre;
temp['apellidos']=VALOR.ap_paterno+" "+VALOR.ap_materno;
temp['desc']=VALOR.colonia+", "+VALOR.municipio;
temp['id_usuario']=VALOR.id_usuario_servicio;
temp['curp']=VALOR.curp;
// console.log(VALOR);
varUsuario.push(temp);
});
$( function() {
$( "#project" ).autocomplete({
minLength: 0,
source: varUsuario,
focus: function( event, ui ) {
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
// console.log(ui);
return false;
},
select: function( event, ui ) {
var usuario=ui.item.label+" "+ui.item.apellidos;
$( "#project" ).val(ui.item.label+" "+ ui.item.apellidos );
$( "#curp" ).val(ui.item.curp );
$( "#curpMostrado" ).val(ui.item.curp );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label +" "+item.apellidos+ "<br>" + item.desc + "</div>" )
.appendTo( ul );
};
} );
function validarFecha(e, elemento) {
var fechas= document.getElementById("fecha_registro").value;
//console.log(fechas);
var ano=fechas.split('-')[0];
var mes=fechas.split('-')[1];
var dia=fechas.split('-')[2];
// alert("fff");
var date = new Date()
// var error=elemento.parentElement.children[1];
var error=elemento.parentElement;
// removeChild
var ul=document.createElement('li');
// ul.setAttribute("class", "errors");
if(ano == "" || ano.length < 4 || ano.search(/\d{4}/) != 0)
{
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="solo 4 digito";
error.appendChild(ul);
return false;
}
if(ano <date.getFullYear() || ano > date.getFullYear())
{
console.log(" año invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="año invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(mes < date.getMonth()+1 || mes > date.getMonth()+1)
{
console.log("mes invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Mes invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
if(dia < date.getDate()-5 || dia > date.getDate())
{
console.log("fecha invalida");
$(".errors").remove();
ul.setAttribute("class", "errors");
ul.innerText="Dia invalida";
error.appendChild(ul);
return false;
}
else{
$(".errors").remove();
}
intMes = parseInt(dia);
intDia = parseInt(mes);
intano=parseInt(ano);
console.log( date.getYear());
}*/
</script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h1><label class="control-label col-md-4 col-sm-3 col-xs-12 " >Registro Actividad</label></h1>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br/>
<form id="myform" data-toggle="validator"enctype="multipart/form-data" role="form" class="" action ="../../controlador/actividad/registroActividad.php?tipo=html" object="defensor" method="post">
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Nombre de usuario<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="text" value="{{curp}}"minlength="18" maxlength="18" name="curp" data-error="debe ser un formato de curp correcto" id="curp" pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)" required="required" class="form-control col-md-7 col-xs-12">
--><input data-error="Seleccione al menos un usuario" type="text" id="project" required class="form-control col-md-7 col-xs-12">
<div class="help-block with-errors"></div></div>
</div></dib>
<!-- ESTE CURP SE OCULTA Y ES EL QUE SE ENVIA AL POST -->
<div id="div_curp" class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="curp">Curp de usuario<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="text" minlength="18" data-error="formato invalido" data-error="fecha invalida" maxlength="18" name="curp" id="curp" required="required" class="form-control col-md-7 col-xs-12" pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)">
--><input type="text" minlength="18" data-error="formato invalido" data-error="fecha invalida" maxlength="18" name="curp" id="curp" required="required" class="form-control col-md-7 col-xs-12" >
<div class="help-block with-errors"></div></div>
</div>
</div>
<!-- ESTE CURP SE OCULTA Y ES EL NO QUE SE ENVIA AL POST -->
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="curp">Curp de usuario<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="text" minlength="18" data-error="formato invalido" data-error="fecha invalida" maxlength="18" name="curp" id="curp" required="required" class="form-control col-md-7 col-xs-12" pattern="([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)">
--><input type="text" disabled minlength="18" data-error="formato invalido" data-error="fecha invalida" maxlength="18" name="curpMostrado" id="curpMostrado" novalidate class="form-control col-md-7 col-xs-12" >
<div class="help-block with-errors"></div></div>
</div>
</div>
<div class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " >Fecha de actividad <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="fecha_registro" type="date" onkeyup="validarFecha(event,this)" onblur="validarFecha(event,this)" data-error="fecha invalido" pattern="" data-error="fecha invalida" maxlength="50" class="form-control" required="" placeholder="Email" name="fechaRegistro">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!-- se requiere para identificar el tipo de actividad -->
<div id="actividad" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " >Actividad <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<select id="miactividad" required="" name="actividad" class="form-control " onblur="verificacionActividad(event,this)">
<option value="asesoria"> Asesoría</option>
<option value="visita">Visita carcelaria</option>
<option value="audiencia"> Audiencia</option>
</select>
</div>
</div> </div>
<div class="form-horizontal form-label-left"> <div class="form-group ">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="nue">Resultado u observación<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input type="textArea" name="resultado" minlength="10" maxlength="200" name="expediente" id="expediente" class="form-control col-md-7 col-xs-12">
--> <textarea id="resultado" name="resultado" onclick="verificacionActividad()" pattern="([A-Z|a-z])[a-z0-9.,:áéíóúñ ]+" data-error="solo numeros o letras en minisculas con minimo 10 caracter" rows="10" cols="150" minlength="10" maxlength="250" class="form-control col-md-7 col-xs-12" placeholder="describre el resultado u observaciones"></textarea>
<div class="help-block with-errors"></div>
</div></div></div>
<div id="mycomprobante" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="comprobante" class="control-label col-md-3 col-sm-3 col-xs-12 " >Comprobante <span class="required">*</span></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<!-- <input data-error="" data-error="fecha invalida" maxlength="50" class="form-control" placeholder="cargar archivo" name="comprobante">
<input id="comprobante" class="inputfile" type="file" id="comprobante" name ="comprobante">
--> <input type="file" name="archivo" id="archivo"></input>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<!--// se requiere para identificar al personal -->
<div id="personal" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " ></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="id_personal" type="text" name="id_personal" required="required" class="form-control col-md-7 col-xs-12" value="<?php echo $id_personal?>">
</div>
</div> </div>
<!--// se requiere para la ubicacion -->
<div id="myubicacion" class=" form-horizontal form-label-left form-group "><div class="form-group ">
<h4> <label for="inputEmail" class="control-label col-md-3 col-sm-3 col-xs-12 " ></label>
</h4><div class="col-md-6 col-sm-6 col-xs-12">
<input id="ubicacion" type="text" name="ubicacion" class="form-control col-md-7 col-xs-12" value="" >
</div>
</div> </div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="asignarAdscripcion" type ="submit" class="btn btn-succes btn btn-success btn-lg" value="Registrar Actividad"/>
<!-- <button type="submit" class="btn btn-success">Submit</button> -->
</div>
</div>
</div>
</form>
</div>
</div>
<script src="../../recursos/js/curp.js"></script>
<script src="../../recursos/js/jquery-validator.js"></script>
<script src="../../recursos/js/actividad/gestionActividad.js"></script>
<script>
$('#myform').validator()
$('#myubicacion').hide()
$('#personal').hide()
$('#mycomprobante').hide()
$('#div_curp').hide()
$('#resultado').keyup(validateTextarea);
function validateTextarea() {
var errorMsg = "Please match the format requested.";
var textarea = this;
var pattern = new RegExp('^' + $(textarea).attr('pattern') + '$');
// check each line of text
$.each($(this).val().split("\n"), function () {
// check if the line matches the pattern
var hasError = !this.match(pattern);
if (typeof textarea.setCustomValidity === 'function') {
textarea.setCustomValidity(hasError ? errorMsg : '');
} else {
// Not supported by the browser, fallback to manual error display...
$(textarea).toggleClass('error', !!hasError);
$(textarea).toggleClass('ok', !hasError);
if (hasError) {
$(textarea).attr('title', errorMsg);
} else {
$(textarea).removeAttr('title');
}
}
return !hasError;
});
}
</script><file_sep><?php
include '../../modelo/expediente.php';
$observacion = $_GET['observacion'];
$id_respuesta = $_GET['id_respuesta'];
$upObs = updateObservacionResp($id_respuesta,$observacion);
echo json_encode($upObs);
/* session_start();
$_SESSION['post_data'] = 1;
header('Location: ../../vistas/administrador/index.php'); */
?><file_sep><?php
include_once('../../libreria/conexion.php');
function listar_visitas_x_id($id){
global $conexion;
$sql = "select * from defensor where id='".$id."'";
$consulta = consulta($sql, $conexion);
return $consulta;
}
//Definimos la funciones sobre el objeto crear_visitas
function crear_visita($asesoria){
$sql = "INSERT INTO visitas_carcelarias ";
$sql.= "SET id_actividad='".$asesoria['id_actividad']."', foto='".$asesoria['foto']."'";
// $sql.= " latitud='".$asesoria['latitud']."', longitud='".$asesoria['longitud']."'";
echo $sql;
$lista=registro($sql);
return $lista;
}
?>
<file_sep><?php
include_once('../../libreria/conexion.php');
function listar_defensores(){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado) where id_cargo =4";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function registrarEstudio($objetoEntidad){
$sql="INSERT INTO escolaridad(id_personal,grado_escolaridad,fecha_termino,instituto,descripcion_perfil_egreso,cedula_profesional,";
$sql.="perfil,documento_provatorio,nombre_estudio,especialidad) values(";
$sql.="'".$objetoEntidad['id_personal']."',"."'".$objetoEntidad['grado_escolaridad']."',"."'".$objetoEntidad['fecha_termino']."',";
$sql.="'".$objetoEntidad['instituto']."',"."'".$objetoEntidad['descripcion_perfil_egreso']."',"."'".$objetoEntidad['cedula_profesional']."',";
$sql.="'".$objetoEntidad['perfil']."',"."'".$objetoEntidad['documento_provatorio']."',"."'".$objetoEntidad['nombre_estudio']."',";
$sql.="'".$objetoEntidad['especialidad']."')";
/* $sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado) where id_cargo =4";
*/
$lista=registro($sql);
//print_r($sql);
return $lista;
}
function listar_defensoresSis($sis){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,p.municipio,p.colonia
FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
where id_cargo =4 and ma.sistema='".$sis."' ";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function listar_defensoresSisMat($sis, $mat){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado) where id_cargo =4
and ma.sistema='".$sis."' and ma.materia='".$mat."'";
$lista=consulta($sql);
//print_r($sql.' sql sismat');
return $lista;
}
function listar_defensoresSisReg($sis, $reg){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado) where id_cargo =4
and ma.sistema='".$sis."' and j.region='".$reg."'";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function listar_defensoresSisRegMat($sis, $reg, $mat){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado) where id_cargo =4
and ma.sistema='".$sis."' and j.region='".$reg."' and ma.materia='".$mat."'";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function listar_defensoresRM($reg, $mat){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado) where id_cargo =4
and j.region='".$reg."' and ma.materia='".$mat."'";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function listar_defensoresMateria($mat){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado)
where id_cargo =4 and ma.materia='".$mat."'";
$lista=consulta($sql);
//print_r($sql.' only materiass');
return $lista;
}
function listar_defensoresRegion($reg){
$sql="SELECT id_personal, nombre, ap_paterno,ap_materno,estado,juzgado,p.municipio,p.colonia FROM personal_campo as d
inner join personal as p using(id_personal)
inner join materia as ma using(id_materia)
inner join juzgado as j using(id_juzgado)
where id_cargo =4 and j.region='".$reg."'";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
function listar(){
$sql="SELECT * FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado) where p.id_cargo =4";
$lista=consulta($sql);
return $lista;
}
function listar_defensores_estudios(){
$sql="SELECT * FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado)
inner join estudios using(id_personal) where id_cargo =4";
$lista=consulta($sql);
//print_r($sql);
return $lista;
}
/*
function numRegistros($sql){
return registro($sql);
} */
function getNumExpedientes($id_defensor){
$sql = 'SELECT * from expediente inner join personal_campo using(id_personal) where id_personal = "'.$id_defensor.'"';
$lista = registro($sql);
return $lista;
}
function getExpedientesById($id_defensor){
$sql="select p.foto,p.nombre as nomDef, p.ap_paterno as appDef, p.ap_materno as apmDef,
p.calle as calleDef,p.numero_int as numDef, p.telefono as telDef, p.correo_electronico as emailDef,
p.colonia as coloniaDef, p.municipio as muniDef,p.id_personal,
e.num_expediente, m.materia,e.fecha_inicio, e.id_expediente,e.fecha_final,e.nombre_delito,
e.tipo_delito,e.estado, e.motivos,e.observaciones
from expediente as e inner join personal as p using(id_personal)
inner join personal_campo using(id_personal)
inner join materia as m using(id_materia)
where id_cargo=4 and id_personal='".$id_defensor."' ";
$lista = consulta($sql);
return $lista;
}
function getDefensorById($id_defensor){
$sql="SELECT d.id_personal,p.nombre,p.ap_paterno,p.ap_materno, p.municipio, p.colonia, p.calle,p.numero_int,p.numero_ext, p.genero,p.telefono,p.correo_electronico,p.curp,p.foto, nup,nue,juzgado,perfil,cedula_profesional FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado)
inner join escolaridad using(id_personal) where id_cargo=4 and d.id_personal ='".$id_defensor."' ";
if(registro($sql) == 0){
$sql="SELECT p.nombre,p.ap_paterno,p.ap_materno, p.municipio, p.colonia, p.calle,p.numero_int,p.numero_ext, p.genero,p.telefono,p.correo_electronico,p.curp,p.foto, nup,nue,juzgado FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado)
where id_cargo=4 and d.id_personal ='".$id_defensor."' ";
$lista = consulta($sql);
return $lista;
}else
$lista = consulta($sql);
return $lista;
}
function getImagenById($id_defensor){
$sql="SELECT foto FROM personal_campo as d inner join personal as p using(id_personal)
inner join juzgado as j using(id_juzgado)
inner join escolaridad using(id_personal) where id_cargo=4 and d.id_personal ='".$id_defensor."' ";
$lista = consulta_obj($sql);
//echo 'si hace consulta';
return $lista;
}
function getDefensorUpdate($id_defensor){
$sql="SELECT * FROM personal_campo as d inner join personal as p using(id_personal)
where id_cargo=4 and d.id_personal ='".$id_defensor."' ";
$lista = consulta($sql);
return $lista;
}
function listar_defensor_x_id($id){
// global $conexion;
$sql = "select * from personal_campo INNER JOIN materia using(id_materia) where id_personal='".$id."'";
$lista = consulta($sql);
// echo $sql;
return $lista;
}
function listar_defensor_x_juzgado($juzgado){
$sql = "select * from personal_campo
inner join personal using(id_personal )
where id_cargo=2 and id_juzgado='".$juzgado."'";
$consulta = consulta($sql);
// echo $sql;
return $consulta;
}
function listar_defensor_x_nue($nue){
$sql = "select * from personal_campo inner join personal using (id_personal ) where nue='".$nue."'";
$consulta = consulta($sql);
// echo $sql;
return $consulta;
}
function listar_defensor_x_nup($nup){
$sql = "select * from personal_campo inner join personal using (id_personal ) where nue='".$nup."'";
$consulta = consulta($sql);
// echo $sql;
return $consulta;
}
function obtenerExpedientes($id_defensor){
$sql="SELECT * FROM expediente inner join personal_campo using(id_personal) WHERE
id_personal = '".$id_defensor."'";
$lista=consulta($sql);
return $lista;
}
function obtenerDefensorCedula($cedulaProf){
//echo 'entro a obtenerdefensorcedula ';
$sql="SELECT * FROM personal_campo inner join personal using(id_personal)
inner join juzgado using(id_juzgado)
inner join estudios using (id_estudios)
where cedula_profesional='guy87gbH5fASa'";
global $db;
$infor = $db->prepare($sql);
$infor->execute();
$datos = $infor->fetchAll(PDO::FETCH_ASSOC);
//$infor = consulta($sql);
return $datos;
}
function getDefensorPorMateria($materia){
$sql="SELECT id_personal, nombre, ap_paterno, ap_materno FROM personal inner join personal_campo using(id_personal) WHERE
materia = '".$materia."'";
$lista=consulta($sql);//print_r( $lista);
return $lista;
}
function getDefensorPorJuzgado($id_personal){
$sql="SELECT id_juzgado,id_personal,instancia,juzgado,region,municipio,calle,cp FROM personal_campo inner join juzgado using(id_juzgado) WHERE
id_personal = '".$id_personal."'";
$lista=consulta($sql);
//print_r( $lista);
return $lista;
}
//Definimos la funciones sobre el objeto crear_defensor
function crear_defensor($objetoEntidad){
$sql = "INSERT INTO personal_campo ";
$sql.= "SET id_juzgado='".$objetoEntidad['id_juzgado']."', id_personal='".$objetoEntidad['id_personal']."',";
$sql.= "id_materia='".$objetoEntidad['id_materia']."'";
// echo $sql;
$lista=registro($sql);
return $lista;
}
function actualizar_juzgado($id_juzgado,$id_defensor){
$sql = "UPDATE personal_campo ";
$sql.= " SET id_juzgado='".$id_juzgado."' where id_personal = ".$id_defensor;
echo $sql;
$lista=registro($sql);
return $lista;
}
//Definimos una funcion que acutualice al actualiza_defensor
function actualiza_defensor($defensor){
$sql = "UPDATE personal_campo as d inner join personal as p using(id_personal)".
"SET p.nombre='".$defensor['nombre']."', p.ap_paterno='".$defensor['ap_paterno']."', p.ap_materno='".$defensor['ap_materno']."',".
"p.curp='".$defensor['curp']."', p.calle='".$defensor['calle']."', p.numero_ext='".$defensor['numero_ext']."',".
"p.numero_int='".$defensor['numero_int']."',p.colonia='".$defensor['colonia']."',p.municipio='".$defensor['municipio']."',".
"p.telefono='".$defensor['telefono']."',".
"p.correo_electronico='".$defensor['correo_electronico']."', p.foto='".$defensor['foto']."'".
" where d.id_personal = '".$defensor['id_personal']."'";
$lista=consulta($sql);
//echo $defensor['id_defensor'].' => Ah sido actualizado';
//print_r($sql);
return $lista;
}
//Definimos una funcion que borrar defensor
function eliminar_defensor($id_defensor){
$newId= -1 * $id_defensor;
$sql = "select id_expediente from expediente inner join personal_campo
using (id_personal)
where id_personal ='".$id_defensor."'
limit 1";
$idExp = consulta($sql);
$id_exp = $idExp[0]['id_expediente'];
$sql = "select count(id_expediente) as num from expediente inner join personal_campo
using (id_personal)
where id_personal ='".$id_defensor."'";
$numExp = consulta($sql);
$num_exp = $numExp[0]['num'];
$sql = "insert into notificaciones (id_expediente, notificacion, fecha_registro) values('".$id_exp."', 'Existen ".$num_exp." expedientes que necesitan ser atendidos, ya!.','2018-06-11')";
$insert = consulta($sql);
$sql = "UPDATE personal_campo as d inner join personal as p using (id_personal)
set d.estado = false, d.id_personal ='".$newId."',p.id_personal ='".$newId."' where d.id_personal = '".$id_defensor."'";
$listaExp = consulta($sql);
return $listaExp;
}
function ultimoDefensorCreatado(){
/* $sql = mysql_query("SELECT MAX(id_defensor) AS id FROM defensor");
$id=consulta($sql);
return $id[0]['id']; */
$sql = "SELECT MAX(id_personal_campo) AS id FROM defensor";
$id=consulta($sql);
// print_r($id);
return $id[0]['id'];
}
?><file_sep>
function EnviarActualizacionUsuarioServicio(){
var sendInfo = {
id_usuario_servicio : document.getElementById('id_usuario_servicioEnviar').value,
nombre : document.getElementById('nombre').value,
apellido_paterno : document.getElementById('ap').value,
apellido_materno : document.getElementById('am').value,
telefono : document.getElementById('telefono').value,
email : document.getElementById('email').value,
calle : document.getElementById('calle').value,
municipio : document.getElementById('municipio').value,
colonia : document.getElementById('colonia').value,
etnia : document.getElementById('etnia').value,
idioma : document.getElementById('idioma').value,
genero : document.getElementById('genero').value,
numero : document.getElementById('numero').value,
discapacidad : document.getElementById('discapacidad').value,
};
$.ajax({
type: "POST",
url: "../../controlador/usuario_servicio/actualizarUsuario.php",
dataType: "html",
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)
console.log($("#idMensaje"));
var alert="";
if(json['tipo']==="exito")
alert="alert alert-success";
//$alert='alert alert-danger';
if(json['tipo']==="error")
alert="alert alert-danger";
if(json['tipo']==="juzgado")
alert="alert alert-danger";
$("#contenedorMensaje").attr("class",""+alert);
$("#contenedorMensaje").append('<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">'+
'<div class="modal-dialog modal-dialog-centered" role="document">'+
'<div class="modal-content">'+
'<strong align="center" id="id_Mensaje" class="alert-dismissible fade in '+alert+'"></strong>'+
'<div class="modal-footer">'+
' <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>'+
'</div></div> </div></div>');
$("#id_Mensaje").text(json['mensaje']);
console.log(json['mensaje']," fue esto");
$('#exampleModalLong').modal('show');
console.log("ffef en always ",json['tipo']);
$("#modalEditarUsuarioServicio").modal('hide');
$("#mostrarusuarioServicio").modal('hide');
if(json['tipo']==="exito")
$("#EditarUsuarioServicio").children().remove();
},
data: sendInfo
});
}
function editarUsuarioServicio(elemento){
console.log("dentro del elemento ",elemento);
var id_usuarioServicioEditar=elemento.getAttribute('id_usuario_servicio');
console.log(id_usuarioServicioEditar," del id_usuarioServicioEditar");
$.ajax({
url: "../../controlador/usuario_servicio//listaUsuario.php",
type: "GET",
data: "id_usuario_servicio=true&id_usuario_servicio="+id_usuarioServicioEditar,
beforeSend:function(){
$('#modalEditarUsuarioServicio').modal('show');
},
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)[0]
console.log(json);
$("#EditarUsuarioServicio").children().remove();
$('#EditarUsuarioServicio').append(
'<div class="form-group">' +
'<label style="display:none;" class="control-label col-md-3 col-sm-3 col-xs-4"><span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="hidden" class="form-control " id="id_usuario_servicioEnviar" placeholder="Id personal" name="id_contraparte"' +
'value="' + json.id_usuario_servicio + '" readonly>' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Nombre<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="nombre" placeholder="Id personal" name="nombre"' +
'value="' + json.nombre + '">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Apellido paterno<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="ap" placeholder="apellido" name="ap"' +
'value="' + json.ap_paterno + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Apellido materno<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="am" placeholder="apellido" name="am"' +
'value="' + json.ap_materno + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Municipio<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="municipio" placeholder="apellido" name="am"' +
'value="' + json.municipio + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Colonia<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="colonia" placeholder="apellido" name="am"' +
'value="' + json.colonia + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Calle<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="calle" placeholder="apellido" name="am"' +
'value="' + json.calle + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Numero<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="numero" placeholder="apellido" name="am"' +
'value="' + json.numero_ext + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>'+
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Etnia<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="etnia" placeholder="Etnia" name="ap"' +
'value="' + json.etnia + '" pattern="[a-zA-ZáéėíóúūñÁÉÍÓÚÜÑ ]+" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Lengua/idioma<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="idioma" placeholder="Idioma/etnia" name="ap"' +
'value="' + json.idioma + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Telefono<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="telefono" placeholder="Telefono" name="ap"' +
'value="' + json.telefono + '" pattern="([0-9]{13})|([0-9]{10})">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Genero<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="genero" placeholder="Genero" name="ap"' +
'value="' + json.genero + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Discapacidad<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="discapacidad" placeholder="Discapacidad" name="ap"' +
'value="' + json.discapacidad + '" >' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<label class="control-label col-md-3 col-sm-3 col-xs-4">Email<span class="required"></span></label>' +
'<div class="col-md-6 col-sm-6 col-xs-12 form-group has-feedback">' +
'<input type="text" class="form-control " id="email" placeholder="Email" name="ap" ' +
'value="' + json.correo_electronico + '" pattern="^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$">' +
'<span class ="help-block"> <span >' +
'</div>' +
'</div>' +
'<div class="form-group">' +
'<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">' +
'<input class="btn btn-succes btn btn-success btn-lg" type="button" name="botonUpdate" onclick="EnviarActualizacionUsuarioServicio()" id="botonUpdate" ' +
'value="Actualizar Datos"></input> ' +
'</div>' +
'</div>'
);
},complete:function(){
$('#modalEditarUsuarioServicio').modal('show');
}
});
}<file_sep><?php
include "../controlador/sesion.php";
//print_r( $_SESSION[session_name()]+" abcde123
//echo $_SESSION["usuario"] . ' => rol '.$_SESSION["rol"];
//echo"<script language='javascript'>alert( ' autentificado baseIndex=>'+ $_SESSION['autentificado'])</script>";
//echo"<script language='javascript'>alert( 'autentificado baseIndex=> rol ' + ". $_SESSION['rol'].")</script>";
if($_SESSION["autentificado"] == true){
if ($_SESSION["rol"] == 1) {//ROL -1- => ADMINISTRADOR cesar aspra
//header("Location: administrador/index.php");
echo'<script language="javascript">window.location="administrador/index.php"</script>';
}
if ($_SESSION["rol"] == 2) {//ROL -2- => COORDINADOR cordinador1 1234
//header("Location: coordinador/index.php");
echo'<script language="javascript">window.location="coordinador/index.php"</script>';
}
if ($_SESSION["rol"] == 3) {//ROL -2- => COORDINADOR cordinador1 1234
//header("Location: coordinador/index.php");
echo'<script language="javascript">window.location="estadistica/index.php"</script>';
}
if ($_SESSION["rol"] == 4) {//ROL -4- => defensor
//header("Location: coordinador/index.php");
echo'<script language="javascript">window.location="defensor/index.php"</script>';
}
}else{
//session_destroy();
//$_SESSION["autentificado"] = false;
header("Location: ../index.php");
}
?>
<file_sep><?php
include_once( '../../controlador/defensor/controladorListaDef.php');
?>
<script src="../../recursos/js/jquery-ui.1.12.1.js"></script>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 ">
<div class="x_panel">
<div class="x_title">
<h3><label class="control-label col-md-12 col-sm-3 col-xs-12 " >baja de expediente</label></h3>
</div>
<div class="x_content">
<form class="" action ="../../controlador/expediente/bajaExpediente.php?pertenece=admin" object="defensor" method="post">
<div class="form-horizontal form-label-left">
<div class="col-md-6 col-xs-12">
<label>Causa
<select id="causa" class="form-control" name="motivoBaja" onchange="validarSelect(this.value)">
<option value="">Materia</option>
<option value="REVOCACION">Revocación del defensor</option>
<option value="FALTA">Falta de interés</option>
</select>
</label>
<div id="mensajeSelectCausa" style="color:red;"></div>
</div>
<div class="col-md-6 col-xs-12">
<label>Fecha de baja
<input type="date" name="fecha_baja" value="">
</label>
<div id="mensajeSelectCausa" style="color:red;"></div>
</div>
<div class="col-md-6 col-xs-12">
<label>Observaciones
</label>
<textarea name="observacion"rows="" cols=""></textarea>
<div id="obser" style="color:red;"></div>
</div>
<br/>
<div id="selectMotivacion" class="col-md-7 col-xs-12">
</div>
<input type="text" name="id_expediente" id="expedienteNum" value="<?php echo $_GET['id_exp'] ?>" style="display:none;" class="form-control col-sm-2 col-xs-12"/>
</div>
<div class="form-group">
<div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
<input id="botonBajaExp" disabled name="botonBajaExp" type ="submit" class="btn btn-succes btn btn-success btn-lg" value="Dar de baja"/>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<file_sep>$(document).ready(function () {
var informeA=document.getElementById('registrarExpediente');
informeA.addEventListener('click', registroExpediente, false);
function registroExpediente() {
$('#menuContainer').load("registroUsuarioServicio.php");
};
var asignarCaso=document.getElementById('asignarCaso');
asignarCaso.addEventListener('click', asignarCasodefensor, false);
function asignarCasodefensor() {
$('#menuContainer').load("asignarDefensor.php");
};
var actividad=document.getElementById('registrarActividad');
actividad.addEventListener('click', registrarActividad, false);
function registrarActividad() {
$('#menuContainer').load("registrarActividad.php");
};
});
<file_sep>var base64 = globalHeaderPDF;
var jsonInf={};
var actividades;
var asesoriasTO, discapacidades;
var sexos, generos, etnias, etniasR, etniasSistema, edades, idiomasR, idiomas, idiomasSistema;
var totalH, totalM, totalSexoT, totalSexoO, totalSexo, totalSen, totalMot,totalMen, totalMul,
totalDisT,totalDisO, totalDiscapacidad;
var totalLesbico, totalGay, totalBisexual, totalTransexual,
totalTransgenero, totalTravesti, totalIntersexual,
totalGenerosT, totalGenerosO, totalG, totalEdadT,
totalEdadO, totalEdadS,totalEdad1, totalEdad2, totalEdad3, totalEdad4,
totalEdad5, totalEdad6, totalEdad7, totalEdad8, totalEdad9 ;
var fecha = new Date();
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var fechaF = fecha.toLocaleDateString("es-ES", options);
var primerM = fechaF.charAt(0).toUpperCase();
var siguiente = fechaF.slice(1).toLowerCase();
var defensores;
var totalHT;
var totalMT;
var totalHO;
var totalMO;
function constructor(jsonInforme){
jsonInf = jsonInforme;
actividades = getNumActividades(jsonInf);
}
function getTablaGeneral(valor){
switch(valor){
case 'TRADICIONAL':
var totalAsesorias =jsonInf['actBySistemaDef'][0].actAsesoria;
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 1;
tablaGeneral.body = [
[
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' }
],
['Asesorías simples Jurídicas',totalAsesorias, jsonInf['actBySistemaDef'][0].actAsesoria],
];
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
break;
case 'ORAL':
break;
default:
var totalAsesorias = parseInt(jsonInf['actBySistema'][1].actAsesoria) + parseInt(jsonInf['actBySistema'][0].actAsesoria);
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 1;
tablaGeneral.body = [
[
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorio y oral', style: 'tableHeader', alignment: 'center' },
],
['Asesorías simples Jurídicas',totalAsesorias, jsonInf['actBySistema'][1].actAsesoria, jsonInf['actBySistema'][0].actAsesoria],
];
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
break;
}
}
function getTablaSexo(valor){
//sexos = getNumSexoUsuarios(jsonInf);
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 2;
switch(valor){
case 'TRADICIONAL':
totalSexoT = parseInt(jsonInf['sexoBySistemaDef'][0].hombreAsesoria) + parseInt(jsonInf['sexoBySistemaDef'][0].mujerAsesoria);
tablaGeneral.widths= [100, 'auto'];
tablaGeneral.body = [
[
{ text: 'Sexo', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' }
],
['Hombre', jsonInf['sexoBySistemaDef'][0].hombreAsesoria],
['Mujer', jsonInf['sexoBySistemaDef'][0].mujerAsesoria],
['Total', totalSexoT]
];
break;
case 'ORAL':
tablaGeneral.widths= [100, 'auto'];
tablaGeneral.body = [
[
{ text: 'Sexo', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Oral', style: 'tableHeader', alignment: 'center' }
],
['Hombre', sexos['numMascO']],
['Mujer', sexos['numFemO']],
['Total', totalSexoO]
];
break;
case 'JUSTICIA':
tablaGeneral.widths= [100, 'auto'];
tablaGeneral.body = [
[
{ text: 'Sexo', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Justicia para adolecentes', style: 'tableHeader', alignment: 'center' }
],
['Hombre', '']
['Mujer', ''],
['Total', '']
];
break;
default:
if(jsonInf['sexoBySistema'][1] == undefined || jsonInf['sexoBySistema'][1] == null){
jsonInf['sexoBySistema'][1]={"hombreAsesoria":0, "mujerAsesoria":0};
}
var totalHombreAse= parseInt(jsonInf['sexoBySistema'][1].hombreAsesoria)+ parseInt(jsonInf['sexoBySistema'][0].hombreAsesoria);
var totalmujerAse= parseInt(jsonInf['sexoBySistema'][1].mujerAsesoria)+ parseInt(jsonInf['sexoBySistema'][0].mujerAsesoria);
var totalAsesoriasSexo = totalHombreAse + totalmujerAse;
tablaGeneral.widths= [100, 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Sexo', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Hombre', totalHombreAse, jsonInf['sexoBySistema'][1].hombreAsesoria, jsonInf['sexoBySistema'][0].hombreAsesoria],
['Mujer', totalmujerAse, jsonInf['sexoBySistema'][1].mujerAsesoria, jsonInf['sexoBySistema'][0].mujerAsesoria],
['Total', totalAsesoriasSexo, '', '']
];
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function getTablaGenero(valor){
//generos = getNumGeneroUsuarios(jsonInf);
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 2;
switch(valor){
case 'TRADICIONAL':
totalGenerosT = parseInt(jsonInf['generoBySistemaDef'][0].lesbicoAse)+parseInt(jsonInf['generoBySistemaDef'][0].gayAse)+
parseInt(jsonInf['generoBySistemaDef'][0].bisexualAse)+parseInt(jsonInf['generoBySistemaDef'][0].transexualAse)+
parseInt(jsonInf['generoBySistemaDef'][0].transgeneroAse)+parseInt(jsonInf['generoBySistemaDef'][0].travestiAse)+
parseInt(jsonInf['generoBySistemaDef'][0].interAse);
tablaGeneral.widths= [150, 'auto'];
tablaGeneral.body = [
[
{ text: 'Género', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' }
],
['Lésbico',jsonInf['generoBySistemaDef'][0].lesbicoAse],
['Gay', jsonInf['generoBySistemaDef'][0].gayAse],
['Bisexual', jsonInf['generoBySistemaDef'][0].bisexualAse],
['Transexual', jsonInf['generoBySistemaDef'][0].transexualAse],
['Transgénero', jsonInf['generoBySistemaDef'][0].transgeneroAse],
['Travestí', jsonInf['generoBySistemaDef'][0].travestiAse],
['Intersexual', jsonInf['generoBySistemaDef'][0].interAse],
['Total', totalGenerosT]
];
break;
case 'ORAL':
tablaGeneral.widths= [150, 'auto'];
tablaGeneral.body = [
[
{ text: 'Género', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Oral', style: 'tableHeader', alignment: 'center' }
],
['Lésbico',generos['numLesbicoO']],
['Gay', generos['numGayO']],
['Bisexual', generos['numBisexualO']],
['Transexual', generos['numTransexualO']],
['Transgénero', generos['numTransgeneroO']],
['Travestí', generos['numTravestiO']],
['Intersexual', generos['numIntersexualO']],
['Total', totalGenerosO]
];
break;
case 'JUSTICIA':
tablaGeneral.widths= [150, 'auto'];
tablaGeneral.body = [
[
{ text: 'Género', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
],
[
{},
{ text: 'Justicia para adolecentes', style: 'tableHeader', alignment: 'center' }
],
['Lésbico',''],
['Gay', ''],
['Bisexual',''],
['Transexual',''],
['Transgénero',''],
['Travestí', ''],
['Intersexual',''],
['Total', '']
];
break;
default:
if(jsonInf['generoBySistema'][1] == undefined || jsonInf['generoBySistema'][1] == null){
jsonInf['generoBySistema'][1]={"lesbicoAse":0, "bisexualAse":0,"gayAse":0, "interAse":0,
"transexualAse":0, "transgeneroAse":0, "travestiAse":0};
}
totalLesbico = parseInt(jsonInf['generoBySistema'][1].lesbicoAse)+ parseInt(jsonInf['generoBySistema'][0].lesbicoAse);
totalBisexual = parseInt(jsonInf['generoBySistema'][1].bisexualAse)+ parseInt(jsonInf['generoBySistema'][0].bisexualAse);
totalGay = parseInt(jsonInf['generoBySistema'][1].gayAse)+ parseInt(jsonInf['generoBySistema'][0].gayAse);
totalIntersexual = parseInt(jsonInf['generoBySistema'][1].interAse)+ parseInt(jsonInf['generoBySistema'][0].interAse);
totalTransexual = parseInt(jsonInf['generoBySistema'][1].transexualAse)+ parseInt(jsonInf['generoBySistema'][0].transexualAse);
totalTransgenero = parseInt(jsonInf['generoBySistema'][1].transgeneroAse)+ parseInt(jsonInf['generoBySistema'][0].transgeneroAse);
totalTravesti = parseInt(jsonInf['generoBySistema'][1].travestiAse)+ parseInt(jsonInf['generoBySistema'][0].travestiAse);
totalG = totalLesbico + totalBisexual + totalGay + totalIntersexual + totalTransgenero + totalTransexual + totalTravesti;
tablaGeneral.widths= [150, 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Género', rowSpan: 2, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{}, {}
],
[
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional', style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorío y oral', style: 'tableHeader', alignment: 'center' }
],
['Lésbico', totalLesbico, jsonInf['generoBySistema'][1].lesbicoAse, jsonInf['generoBySistema'][0].lesbicoAse],
['Gay', totalGay, jsonInf['generoBySistema'][1].gayAse, jsonInf['generoBySistema'][0].gayAse],
['Bisexual', totalBisexual, jsonInf['generoBySistema'][1].bisexualAse, jsonInf['generoBySistema'][0].bisexualAse],
['Transexual', totalTransexual, jsonInf['generoBySistema'][1].transexualAse, jsonInf['generoBySistema'][0].transexualAse],
['Transgénero', totalTransgenero, jsonInf['generoBySistema'][1].transgeneroAse, jsonInf['generoBySistema'][0].transgeneroAse],
['Travestí', totalTravesti, jsonInf['generoBySistema'][1].travestiAse, jsonInf['generoBySistema'][0].travestiAse],
['Intersexual', totalIntersexual, jsonInf['generoBySistema'][1].interAse, jsonInf['generoBySistema'][0].interAse],
['Total', totalG, '','']
];
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
//console.log(tabla);
return tabla;
}
function getTablaEdad(valor){
//edades = getNumEdadUsuarios(jsonInf);
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
switch(valor){
case 'TRADICIONAL':
totalEdad1 = parseInt(jsonInf['edadBySistemaDef'][0].edad18_24H)+parseInt(jsonInf['edadBySistemaDef'][0].edad18_24M);
totalEdad2 = parseInt(jsonInf['edadBySistemaDef'][0].edad25_29H)+parseInt(jsonInf['edadBySistemaDef'][0].edad25_29M);
totalEdad3 = parseInt(jsonInf['edadBySistemaDef'][0].edad30_34H)+parseInt(jsonInf['edadBySistemaDef'][0].edad30_34M);
totalEdad4 = parseInt(jsonInf['edadBySistemaDef'][0].edad35_39H)+parseInt(jsonInf['edadBySistemaDef'][0].edad35_39M);
totalEdad5 = parseInt(jsonInf['edadBySistemaDef'][0].edad40_44H)+parseInt(jsonInf['edadBySistemaDef'][0].edad40_44M);
totalEdad6 = parseInt(jsonInf['edadBySistemaDef'][0].edad45_49H)+parseInt(jsonInf['edadBySistemaDef'][0].edad45_49M);
totalEdad7 = parseInt(jsonInf['edadBySistemaDef'][0].edad50_54H)+parseInt(jsonInf['edadBySistemaDef'][0].edad50_54M);
totalEdad8 = parseInt(jsonInf['edadBySistemaDef'][0].edad55_59H)+parseInt(jsonInf['edadBySistemaDef'][0].edad55_59M);
totalEdad9 = parseInt(jsonInf['edadBySistemaDef'][0].edad60MasH)+parseInt(jsonInf['edadBySistemaDef'][0].edad60MasM);
totalEdadT = totalEdad1 + totalEdad2+totalEdad3 + totalEdad4+totalEdad5 + totalEdad6+totalEdad7 + totalEdad8+totalEdad9;
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Edad', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', totalEdad1, jsonInf['edadBySistemaDef'][0].edad18_24H,jsonInf['edadBySistemaDef'][0].edad18_24M],
['25 A 29 AÑOS', totalEdad2, jsonInf['edadBySistemaDef'][0].edad25_29H,jsonInf['edadBySistemaDef'][0].edad25_29M],
['30 A 34 AÑOS', totalEdad3, jsonInf['edadBySistemaDef'][0].edad30_34H,jsonInf['edadBySistemaDef'][0].edad30_34M],
['35 A 39 AÑOS', totalEdad4, jsonInf['edadBySistemaDef'][0].edad35_39H,jsonInf['edadBySistemaDef'][0].edad35_39M],
['40 A 44 AÑOS', totalEdad5, jsonInf['edadBySistemaDef'][0].edad40_44H,jsonInf['edadBySistemaDef'][0].edad40_44M],
['45 A 49 AÑOS', totalEdad6, jsonInf['edadBySistemaDef'][0].edad45_49H,jsonInf['edadBySistemaDef'][0].edad45_49M],
['50 A 54 AÑOS', totalEdad7, jsonInf['edadBySistemaDef'][0].edad50_54H,jsonInf['edadBySistemaDef'][0].edad50_54M],
['55 A 59 AÑOS', totalEdad8, jsonInf['edadBySistemaDef'][0].edad55_59H,jsonInf['edadBySistemaDef'][0].edad55_59M],
['DE 60 O MAS AÑOS', totalEdad9, jsonInf['edadBySistemaDef'][0].edad60MasH,jsonInf['edadBySistemaDef'][0].edad60MasM],
['TOTAL', totalEdadT,'','']
];
break;
case 'ORAL':
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Edad', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Oral',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', edades['edades1O'],edades['edades1OH'],edades['edades1OM']],
['25 A 29 AÑOS', edades['edades2O'],edades['edades2OH'],edades['edades2OM']],
['30 A 34 AÑOS', edades['edades3O'],edades['edades3OH'],edades['edades3OM']],
['35 A 39 AÑOS', edades['edades4O'],edades['edades4OH'],edades['edades4OM']],
['40 A 44 AÑOS', edades['edades5O'],edades['edades5OH'],edades['edades5OM']],
['45 A 49 AÑOS', edades['edades6O'],edades['edades6OH'],edades['edades6OM']],
['50 A 54 AÑOS', edades['edades7O'],edades['edades7OH'],edades['edades7OM']],
['55 A 59 AÑOS', edades['edades8O'],edades['edades8OH'],edades['edades8OM']],
['DE 60 O MAS AÑOS', edades['edades9O'],edades['edades9OH'],edades['edades9OM']],
['TOTAL', totalEdadO,totalHO,totalMO]
];
break;
case 'JUSTICIA':
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Edad', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Justicia para Adolecentes',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', '','',''],
['25 A 29 AÑOS', '','',''],
['30 A 34 AÑOS', '','',''],
['35 A 39 AÑOS', '','',''],
['40 A 44 AÑOS', '','',''],
['45 A 49 AÑOS', '','',''],
['50 A 54 AÑOS', '','',''],
['55 A 59 AÑOS', '','',''],
['DE 60 O MAS AÑOS','','',''],
['TOTAL', '','','']
];
break;
default:
if(jsonInf['edadBySistema'][1] == undefined || jsonInf['edadBySistema'][1] == null){
jsonInf['edadBySistema'][1]={"totalSistema":0, "edad18_24H":0,"edad18_24M":0,"edad25_29H":0,"edad25_29M":0,"edad30_34H":0,"edad30_34M":0,"edad35_39H":0,"edad35_39M":0,"edad40_44H":0,"edad40_44M":0,
"edad45_49H":0,"edad45_49M":0,"edad50_54H":0,"edad50_54M":0,"edad55_59H":0,"edad55_59M":0,"edad60MasH":0,"edad60MasM":0};
}
var totalT1824 = parseInt(jsonInf['edadBySistema'][1].edad18_24H)+parseInt(jsonInf['edadBySistema'][1].edad18_24M);
var totalO1824 = parseInt(jsonInf['edadBySistema'][0].edad18_24H)+parseInt(jsonInf['edadBySistema'][0].edad18_24M);
var totalT2529 = parseInt(jsonInf['edadBySistema'][1].edad25_29H)+parseInt(jsonInf['edadBySistema'][1].edad25_29M);
var totalO2529 = parseInt(jsonInf['edadBySistema'][0].edad25_29H)+parseInt(jsonInf['edadBySistema'][0].edad25_29M);
var totalT3034 = parseInt(jsonInf['edadBySistema'][1].edad30_34H)+parseInt(jsonInf['edadBySistema'][1].edad30_34M);
var totalO3034 = parseInt(jsonInf['edadBySistema'][0].edad30_34H)+parseInt(jsonInf['edadBySistema'][0].edad30_34M);
var totalT3539 = parseInt(jsonInf['edadBySistema'][1].edad35_39H)+parseInt(jsonInf['edadBySistema'][1].edad35_39M);
var totalO3539 = parseInt(jsonInf['edadBySistema'][0].edad35_39H)+parseInt(jsonInf['edadBySistema'][0].edad35_39M);
var totalT4044 = parseInt(jsonInf['edadBySistema'][1].edad40_44H)+parseInt(jsonInf['edadBySistema'][1].edad40_44M);
var totalO4044 = parseInt(jsonInf['edadBySistema'][0].edad40_44H)+parseInt(jsonInf['edadBySistema'][0].edad40_44M);
var totalT4549 = parseInt(jsonInf['edadBySistema'][1].edad45_49H)+parseInt(jsonInf['edadBySistema'][1].edad45_49M);
var totalO4549 = parseInt(jsonInf['edadBySistema'][0].edad45_49H)+parseInt(jsonInf['edadBySistema'][0].edad45_49M);
var totalT5054 = parseInt(jsonInf['edadBySistema'][1].edad50_54H)+parseInt(jsonInf['edadBySistema'][1].edad50_54M);
var totalO5054 = parseInt(jsonInf['edadBySistema'][0].edad50_54H)+parseInt(jsonInf['edadBySistema'][0].edad50_54M);
var totalT5559 = parseInt(jsonInf['edadBySistema'][1].edad55_59H)+parseInt(jsonInf['edadBySistema'][1].edad55_59M);
var totalO5559 = parseInt(jsonInf['edadBySistema'][0].edad55_59H)+parseInt(jsonInf['edadBySistema'][0].edad55_59M);
var totalT60 = parseInt(jsonInf['edadBySistema'][1].edad60MasH)+parseInt(jsonInf['edadBySistema'][1].edad60MasM);
var totalO60 = parseInt(jsonInf['edadBySistema'][0].edad60MasH)+parseInt(jsonInf['edadBySistema'][0].edad60MasM);
totalEdad1 = totalT1824 + totalO1824;
totalEdad2 = totalT2529 + totalO2529;
totalEdad3 = totalT3034 + totalO3034;
totalEdad4 = totalT3539 + totalO3539;
totalEdad5 = totalT4044 + totalO4044;
totalEdad6 = totalT4549 + totalO4549;
totalEdad7 = totalT5054 + totalO5054;
totalEdad8 = totalT5559 + totalO5559;
totalEdad9 = totalT60 + totalO60;
totalEdadS = totalEdad1 + totalEdad2 + totalEdad3 + totalEdad4 + totalEdad5 + totalEdad6 + totalEdad7 + totalEdad8 + totalEdad9;
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto','auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Edad', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
],
[
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['18 A 24 AÑOS', totalEdad1, totalT1824, jsonInf['edadBySistema'][1].edad18_24H,jsonInf['edadBySistema'][1].edad18_24M, totalO1824,jsonInf['edadBySistema'][0].edad18_24H,jsonInf['edadBySistema'][0].edad18_24M],
['25 A 29 AÑOS', totalEdad2, totalT2529, jsonInf['edadBySistema'][1].edad25_29H,jsonInf['edadBySistema'][1].edad25_29M, totalO2529,jsonInf['edadBySistema'][0].edad25_29H,jsonInf['edadBySistema'][0].edad25_29M],
['30 A 34 AÑOS', totalEdad3, totalT3034, jsonInf['edadBySistema'][1].edad30_34H,jsonInf['edadBySistema'][1].edad30_34M, totalO3034,jsonInf['edadBySistema'][0].edad30_34H,jsonInf['edadBySistema'][0].edad30_34M],
['35 A 39 AÑOS', totalEdad4, totalT3539, jsonInf['edadBySistema'][1].edad35_39H,jsonInf['edadBySistema'][1].edad35_39M, totalO3539,jsonInf['edadBySistema'][0].edad35_39H,jsonInf['edadBySistema'][0].edad35_39M],
['40 A 44 AÑOS', totalEdad5, totalT4044, jsonInf['edadBySistema'][1].edad40_44H,jsonInf['edadBySistema'][1].edad40_44M, totalO4044,jsonInf['edadBySistema'][0].edad40_44H,jsonInf['edadBySistema'][0].edad40_44M],
['45 A 49 AÑOS', totalEdad6, totalT4549, jsonInf['edadBySistema'][1].edad45_49H,jsonInf['edadBySistema'][1].edad45_49M, totalO4549,jsonInf['edadBySistema'][0].edad45_49H,jsonInf['edadBySistema'][0].edad45_49M],
['50 A 54 AÑOS', totalEdad7, totalT5054, jsonInf['edadBySistema'][1].edad50_54H,jsonInf['edadBySistema'][1].edad50_54M, totalO5054,jsonInf['edadBySistema'][0].edad50_54H,jsonInf['edadBySistema'][0].edad50_54M],
['55 A 59 AÑOS', totalEdad8, totalT5559, jsonInf['edadBySistema'][1].edad55_59H,jsonInf['edadBySistema'][1].edad55_59M, totalO5559,jsonInf['edadBySistema'][0].edad55_59H,jsonInf['edadBySistema'][0].edad55_59M],
['DE 60 O MAS AÑOS',totalEdad9, totalT60, jsonInf['edadBySistema'][1].edad60MasH,jsonInf['edadBySistema'][1].edad60MasM, totalO60, jsonInf['edadBySistema'][0].edad60MasH,jsonInf['edadBySistema'][0].edad60MasM],
['TOTAL', totalEdadS, '','','', '','','']
];
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function generarCuerpoTop(){
var totalFinal = 0;
var sourceData = jsonInf['topDefensoresBySystema'];
console.log(sourceData, ' VALORRRRR SOURCE DATA');
console.log(jsonInf, ' COMPLETO');
//var listaDef = getListaDef(sourceData);
var bodyData = [];
bodyData.push(
[{ text: 'Defensor', style: 'tableHeader', alignment: 'center' },
{ text: 'Juzgado', style: 'tableHeader', alignment: 'center' },
{ text: 'Asesorias', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M', style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', style: 'tableHeader', alignment: 'center' }
]
);
sourceData.forEach(function(VAL) {
totalFinal += parseInt(VAL.asesoriaPorSistema);
var dataRow = [];
dataRow.push(VAL.nombreP, VAL.nombreJuz, VAL.asesoriaPorSistema, VAL.hombres, VAL.mujeres, VAL.sistemaM);
bodyData.push(dataRow);
});
bodyData.push(['TOTAL', '---', totalFinal,'---','---','---']);
console.log(bodyData, ' bodydata tooop defensores');
return bodyData;
}
function generarCuerpoEtniasT(){
var totalFinal = 0;
var sourceData = jsonInf['etniaBySistemaDef'];
var listaEtnias = getNumEtniasUsuarios(sourceData);
console.log(sourceData, ' SOURCE DATAAAA');
console.log(listaEtnias, ' LISTA ETNIA');
var bodyData = [];
bodyData.push(
[
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
]
);
bodyData.push(
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
]
);
bodyData.push(
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
]
);
for(var i=0; i<listaEtnias.length; i++){
sourceData.forEach(function(VAL) {
if(listaEtnias[i].etnia == VAL.etniaU){
//var totalT = parseInt(VAL.etniaHombreT) + parseInt(VAL.etniaMujerT);
//var totalO = parseInt(VAL.etniaHombreO) + parseInt(VAL.etniaMujerO);
totalFinal += parseInt(VAL.asesoriaPorSistema);
var dataRow = [];
dataRow.push(listaEtnias[i].etnia, VAL.asesoriaPorSistema, VAL.etniaHombreT, VAL.etniaMujerT);
bodyData.push(dataRow);
}
});
}
bodyData.push(['TOTAL', totalFinal, ' ',' ']);
//console.log(bodyData, ' bodydata');
return bodyData;
}
function generarCuerpoEtnias(){
var totalFinal = 0;
var sourceData = jsonInf['etniaBySistema'];
var listaEtnias = getNumEtniasUsuarios(sourceData);
var bodyData = [];
bodyData.push(
[{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}]
);
bodyData.push(
[{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}]
);
bodyData.push(
[{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }]
);
for(var i=0; i<listaEtnias.length; i++){
sourceData.forEach(function(VAL) {
if(listaEtnias[i].etnia == VAL.etniaU){
var totalT = parseInt(VAL.etniaHombreT) + parseInt(VAL.etniaMujerT);
var totalO = parseInt(VAL.etniaHombreO) + parseInt(VAL.etniaMujerO);
totalFinal += parseInt(VAL.asesoriaPorSistema);
var dataRow = [];
dataRow.push(listaEtnias[i].etnia, VAL.asesoriaPorSistema, totalT, VAL.etniaHombreT, VAL.etniaMujerT, totalO, VAL.etniaHombreO, VAL.etniaMujerO);
bodyData.push(dataRow);
}
});
}
bodyData.push(['TOTAL', totalFinal, ' ',' ',' ',' ',' ',' ']);
//console.log(bodyData, ' bodydata');
return bodyData;
}
function getTablaEtnias(valor){
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
//console.log(generarCuerpoEtnias(), 'cuerpo funcioin generar cuerpo etnias');
switch(valor){
case 'TRADICIONAL':
return {
style : 'tableExample',
color : 'black',
table:{
widths: ['auto', 'auto', 'auto', 'auto'],
headerRows: 3,
body: generarCuerpoEtniasT()
}
}
break;
case 'ORAL':
tablaGeneral.widths= [150, 'auto', 'auto', 'auto'];
//tablaGeneral.body = generarRowsEtnias(etnias, etniasSistema, valor);
tablaGeneral.body=
[
[
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorio Oral',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['','','','']
];
break;
case 'JUSTICIA':
tablaGeneral.widths= [150, 'auto', 'auto', 'auto'];
//tablaGeneral.body = generarRowsEtnias(etnias, etniasSistema, valor);
tablaGeneral.body=
[
[
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Justicia para adolecentes',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['','','','']
];
break;
default:
return {
style : 'tableExample',
color : 'black',
table:{
widths: ['auto', 'auto', 'auto', 'auto','auto', 'auto', 'auto','auto'],
headerRows: 3,
body: generarCuerpoEtnias()
}
}
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function generarCuerpoIdiomasT(){
var totalFinal = 0;
var sourceData = jsonInf['idiomaBySistemaDef'];
var listaIdiomas = getNumIdiomasUsuarios(sourceData);
var bodyData = [];
bodyData.push(
[{ text: 'Idioma o Lengua', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}]
);
bodyData.push(
[{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}]
);
bodyData.push(
[{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }]
);
for(var i=0; i<listaIdiomas.length; i++){
sourceData.forEach(function(VAL) {
if(listaIdiomas[i].idioma == VAL.idiomaU){
//var totalT = parseInt(VAL.idiomaHombreT) + parseInt(VAL.idiomaMujerT);
//var totalO = parseInt(VAL.idiomaHombreO) + parseInt(VAL.idiomaMujerO);
totalFinal += parseInt(VAL.asesoriaPorSistema);
var dataRow = [];
//console.log(listaIdiomas[i].idioma, VAL.asesoriaPorSistema, totalT, VAL.idiomaHombreT, VAL.idiomaMujerT, totalO, VAL.idiomaHombreO, VAL.idiomaMujerO);
dataRow.push(listaIdiomas[i].idioma, VAL.asesoriaPorSistema, VAL.idiomaHombreT, VAL.idiomaMujerT);
bodyData.push(dataRow);
}
});
}
bodyData.push(['TOTAL', totalFinal, ' ',' ']);
//console.log(bodyData, ' bodydata');
return bodyData;
}
function generarCuerpoIdiomas(){
var totalFinal = 0;
var sourceData = jsonInf['idiomaBySistema'];
var listaIdiomas = getNumIdiomasUsuarios(sourceData);
var bodyData = [];
bodyData.push(
[{ text: 'Idiomas o Lenguas', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}]
);
bodyData.push(
[{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}]
);
bodyData.push(
[{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }]
);
for(var i=0; i<listaIdiomas.length; i++){
sourceData.forEach(function(VAL) {
if(listaIdiomas[i].idioma == VAL.idiomaU){
var totalT = parseInt(VAL.idiomaHombreT) + parseInt(VAL.idiomaMujerT);
var totalO = parseInt(VAL.idiomaHombreO) + parseInt(VAL.idiomaMujerO);
totalFinal += parseInt(VAL.asesoriaPorSistema);
var dataRow = [];
//console.log(listaIdiomas[i].idioma, VAL.asesoriaPorSistema, totalT, VAL.idiomaHombreT, VAL.idiomaMujerT, totalO, VAL.idiomaHombreO, VAL.idiomaMujerO);
dataRow.push(listaIdiomas[i].idioma, VAL.asesoriaPorSistema, totalT, VAL.idiomaHombreT, VAL.idiomaMujerT, totalO, VAL.idiomaHombreO, VAL.idiomaMujerO);
bodyData.push(dataRow);
}
});
}
bodyData.push(['TOTAL', totalFinal, ' ',' ',' ',' ',' ',' ']);
//console.log(bodyData, ' bodydata');
return bodyData;
}
function getTablaIdiomas(valor){
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
//console.log(generarCuerpoEtnias(), 'cuerpo funcioin generar cuerpo etnias');
switch(valor){
case 'TRADICIONAL':
return {
style : 'tableExample',
color : 'black',
table:{
widths: ['auto', 'auto', 'auto', 'auto'],
headerRows: 3,
body: generarCuerpoIdiomasT()
}
}
break;
case 'ORAL':
tablaGeneral.widths= [150, 'auto', 'auto', 'auto'];
//tablaGeneral.body = generarRowsEtnias(etnias, etniasSistema, valor);
tablaGeneral.body=
[
[
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Acusatorio Oral',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['','','','']
];
break;
case 'JUSTICIA':
tablaGeneral.widths= [150, 'auto', 'auto', 'auto'];
//tablaGeneral.body = generarRowsEtnias(etnias, etniasSistema, valor);
tablaGeneral.body=
[
[
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Justicia para adolecentes',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['','','','']
];
break;
default:
return {
style : 'tableExample',
color : 'black',
table:{
widths: ['auto', 'auto', 'auto', 'auto','auto', 'auto', 'auto','auto'],
headerRows: 3,
body: generarCuerpoIdiomas()
}
}
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function getTablaDiscapacidad(valor){
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
switch(valor){
case 'TRADICIONAL':
var dis=jsonInf['discapacidadBySistemaDef'];
totalFinal = parseInt(dis[0].tablaSensorial)+
parseInt(dis[0].tablaMotriz)+
parseInt(dis[0].tablaMental)+
parseInt(dis[0].tablaMultiple)+
parseInt(dis[0].tablaNinguno);
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[0].tablaSensorial, dis[0].tablaSensorialM, dis[0].tablaSensorialF ],
['Motrices', dis[0].tablaMotriz, dis[0].tablaMotrizM, dis[0].tablaMotrizF ],
['Mentales', dis[0].tablaMental, dis[0].tablaMentalM, dis[0].tablaMentalF ],
['Multiples', dis[0].tablaMultiple, dis[0].tablaMultipleM, dis[0].tablaMultipleF ],
['Ninguno', dis[0].tablaNinguno, dis[0].tablaNingunoM, dis[0].tablaNingunoF ],
['Total', totalFinal,'','']
];
break;
case 'ORAL':
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Oral',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', discapacidades['numSensorialesO'],discapacidades['numSMO'],discapacidades['numSFO']],
['Motrices', discapacidades['numMotricesO'],discapacidades['numMMO'],discapacidades['numMFO']],
['Mentales', discapacidades['numMentalesO'],discapacidades['numMEMO'],discapacidades['numMEFO']],
['Multiples', discapacidades['numMultiplesO'],discapacidades['numMUMO'],discapacidades['numMUFO']],
['Total', totalDisO,'','']
];
break;
case 'JUSTICIA':
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Justicia para adolecentes',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', '','',''],
['Motrices', '','',''],
['Mentales', '','',''],
['Multiples', '','',''],
['Total','','','']
];
break;
default:
var dis=jsonInf['discapacidadBySistema'];
var lista = getListaDiscapacidad();
dis = validarDiscapacidad(dis);
var totalSenT,totalSenO, totalMotT, totalMotO, totalMenT, totalMenO, totalMulT, totalMulO, totalNinT,totalNinO,
totalSen, totalMot, totalMen, totalMul, totalNin, totalFinal;
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto','auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
],
[
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[0].tablaSensorial, dis[0].tablaSensorialM, dis[0].tablaSensorialF ],
['Motrices', dis[0].tablaMotriz, dis[0].tablaMotrizM, dis[0].tablaMotrizF ],
['Mentales', dis[0].tablaMental, dis[0].tablaMentalM, dis[0].tablaMentalF ],
['Multiples', dis[0].tablaMultiple, dis[0].tablaMultipleM, dis[0].tablaMultipleF ],
['Ninguno', dis[0].tablaNinguno, dis[0].tablaNingunoM, dis[0].tablaNingunoF ],
['Total', totalFinal,'','']
];
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function getTablaDiscapacidad2(valor){
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
switch(valor){
case 'TRADICIONAL':
var dis=jsonInf['discapacidadBySistema'];
totalFinal = parseInt(dis[0].tablaSensorial)+
parseInt(dis[0].tablaMotriz)+
parseInt(dis[0].tablaMental)+
parseInt(dis[0].tablaMultiple)+
parseInt(dis[0].tablaNinguno);
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[0].tablaSensorial, dis[0].tablaSensorialM, dis[0].tablaSensorialF ],
['Motrices', dis[0].tablaMotriz, dis[0].tablaMotrizM, dis[0].tablaMotrizF ],
['Mentales', dis[0].tablaMental, dis[0].tablaMentalM, dis[0].tablaMentalF ],
['Multiples', dis[0].tablaMultiple, dis[0].tablaMultipleM, dis[0].tablaMultipleF ],
['Ninguno', dis[0].tablaNinguno, dis[0].tablaNingunoM, dis[0].tablaNingunoF ],
['Total', totalFinal,'','']
];
break;
case 'ORAL':
var dis=jsonInf['discapacidadBySistema'];
totalFinal = parseInt(dis[0].tablaSensorial)+
parseInt(dis[0].tablaMotriz)+
parseInt(dis[0].tablaMental)+
parseInt(dis[0].tablaMultiple)+
parseInt(dis[0].tablaNinguno);
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Oral',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[0].tablaSensorial, dis[0].tablaSensorialM, dis[0].tablaSensorialF ],
['Motrices', dis[0].tablaMotriz, dis[0].tablaMotrizM, dis[0].tablaMotrizF ],
['Mentales', dis[0].tablaMental, dis[0].tablaMentalM, dis[0].tablaMentalF ],
['Multiples', dis[0].tablaMultiple, dis[0].tablaMultipleM, dis[0].tablaMultipleF ],
['Ninguno', dis[0].tablaNinguno, dis[0].tablaNingunoM, dis[0].tablaNingunoF ],
['Total', totalFinal,'','']
];
break;
case 'JUSTICIA':
var dis=jsonInf['discapacidadBySistema'];
totalFinal = parseInt(dis[0].tablaSensorial)+
parseInt(dis[0].tablaMotriz)+
parseInt(dis[0].tablaMental)+
parseInt(dis[0].tablaMultiple)+
parseInt(dis[0].tablaNinguno);
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[0].tablaSensorial, dis[0].tablaSensorialM, dis[0].tablaSensorialF ],
['Motrices', dis[0].tablaMotriz, dis[0].tablaMotrizM, dis[0].tablaMotrizF ],
['Mentales', dis[0].tablaMental, dis[0].tablaMentalM, dis[0].tablaMentalF ],
['Multiples', dis[0].tablaMultiple, dis[0].tablaMultipleM, dis[0].tablaMultipleF ],
['Ninguno', dis[0].tablaNinguno, dis[0].tablaNingunoM, dis[0].tablaNingunoF ],
['Total', totalFinal,'','']
];
break;
default:
var dis=jsonInf['discapacidadBySistema'];
var lista = getListaDiscapacidad();
dis = validarDiscapacidad(dis);
var totalSenT,totalSenO, totalMotT, totalMotO, totalMenT, totalMenO, totalMulT, totalMulO, totalNinT,totalNinO,
totalSen, totalMot, totalMen, totalMul, totalNin, totalFinal;
tablaGeneral.widths= ['auto', 'auto', 'auto', 'auto','auto', 'auto', 'auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Discapacidades', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
],
[
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
],
[
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
['Sensoriales y de la comunicación', dis[2]['totalSensorialS'], dis[0]['tablaSensorial'],dis[0]['tablaSensorialM'],dis[0]['tablaSensorialF'],dis[1]['tablaSensorial'], dis[1]['tablaSensorialM'],dis[1]['tablaSensorialF']],
['Motrices', dis[2]['totalMotrizS'], dis[0]['tablaMotriz'], dis[0]['tablaMotrizM'], dis[0]['tablaMotrizF'], dis[1]['tablaMotriz'], dis[1]['tablaMotrizM'], dis[1]['tablaMotrizF']],
['Mentales', dis[2]['totalMentalS'], dis[0]['tablaMental'], dis[0]['tablaMentalM'], dis[0]['tablaMentalF'], dis[1]['tablaMental'], dis[1]['tablaMentalM'], dis[1]['tablaMentalF']],
['Multiples', dis[2]['totalMultipleS'], dis[0]['tablaMultiple'], dis[0]['tablaMultipleM'], dis[0]['tablaMultipleF'], dis[1]['tablaMultiple'], dis[1]['tablaMultipleM'], dis[1]['tablaMultipleF']],
['Ninguno', dis[2]['totalNingunoS'], dis[0]['tablaNinguno'], dis[0]['tablaNingunoM'], dis[0]['tablaNingunoF'], dis[1]['tablaNinguno'], dis[1]['tablaNingunoM'], dis[1]['tablaNingunoF']],
['Total', dis[2]['totalFinal'], '','','','','','']
];
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function getListaDiscapacidad(){
var et=[];
et.push('NINGUNO');
et.push('SENSORIALES');
et.push('MOTRICES');
et.push('MENTALES');
et.push('MULTIPLES');
return et;
}
function validarDiscapacidad(data){
var sis;
if(data[1]==undefined ||data[1]==null){
if(data[0].matSistemaG=="TRADICIONAL"){
sis="ORAL";
}else{
sis="TRADICIONAL"
}
data[1]={
"discapTotal":0,
"matSistemaG":sis,
"tablaMental":0,
"tablaMentalF":0,
"tablaMentalM":0,
"tablaMotriz":0,
"tablaMotrizF":0,
"tablaMotrizM":0,
"tablaMultiple":0,
"tablaMultipleF":0,
"tablaMultipleM":0,
"tablaNinguno":0,
"tablaNingunoF":0,
"tablaNingunoM":0,
"tablaSensorial":0,
"tablaSensorialF":0,
"tablaSensorialM":0
};
}
var men=0, mot=0, mul=0, nin=0, sen=0, tot=0;
$.each(data, function(k,v){
men += parseInt(v.tablaMental);
mot += parseInt(v.tablaMotriz);
mul += parseInt(v.tablaMultiple);
nin += parseInt(v.tablaNinguno);
sen += parseInt(v.tablaSensorial);
tot = (men+mot+mul+nin+sen);
data[2]={
"totalMentalS":men,
"totalMotrizS":mot,
"totalMultipleS":mul,
"totalNingunoS":nin,
"totalSensorialS":sen,
"totalFinal":tot
};
});
return data;
}
function getTablaTopTen(valor){
//def = jsonInf['topDefensoresBySystema'];
var tabla ={};
var tablaGeneral={};
tablaGeneral.headerRows= 3;
//console.log(valor, ' valor sistema elegido');
switch(valor){
case 'TRADICIONAL':
tablaGeneral.widths= ['auto', 'auto', 'auto','auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Defensor público', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{},
{ text: 'Total',rowSpan:2,style: 'tableHeader', alignment: 'center'},
{ text: 'Tradicional', colSpan:2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'H',style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].juzgado, defensores[0].asesoriasT,defensores[0].asesoriaHT,defensores[0].asesoriaFT],
[defensores[1].defensor, defensores[1].juzgado, defensores[1].asesoriasT,defensores[1].asesoriaHT,defensores[1].asesoriaFT],
[defensores[2].defensor, defensores[2].juzgado, defensores[2].asesoriasT,defensores[2].asesoriaHT,defensores[2].asesoriaFT],
[defensores[3].defensor, defensores[3].juzgado, defensores[3].asesoriasT,defensores[3].asesoriaHT,defensores[3].asesoriaFT],
[defensores[4].defensor, defensores[4].juzgado, defensores[4].asesoriasT,defensores[4].asesoriaHT,defensores[4].asesoriaFT],
[defensores[5].defensor, defensores[5].juzgado, defensores[5].asesoriasT,defensores[5].asesoriaHT,defensores[5].asesoriaFT]
/* [defensores[6].defensor, defensores[6].juzgado, defensores[6].asesoriasT,defensores[6].asesoriaHT,defensores[6].asesoriaFT],
[defensores[7].defensor, defensores[7].juzgado, defensores[7].asesoriasT,defensores[7].asesoriaHT,defensores[7].asesoriaFT],
[defensores[8].defensor, defensores[8].juzgado, defensores[8].asesoriasT,defensores[8].asesoriaHT,defensores[8].asesoriaFT],
[defensores[9].defensor, defensores[9].juzgado, defensores[9].asesoriasT,defensores[9].asesoriaHT,defensores[9].asesoriaFT] */
];
break;
case 'ORAL':
tablaGeneral.widths= ['auto', 'auto', 'auto','auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Defensor público', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{},
{ text: 'Total',rowSpan:2,style: 'tableHeader', alignment: 'center'},
{ text: 'Oral', colSpan:2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'H',style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].juzgado, defensores[0].asesoriasO,defensores[0].asesoriaHO,defensores[0].asesoriaFO],
[defensores[1].defensor, defensores[1].juzgado, defensores[1].asesoriasO,defensores[1].asesoriaHO,defensores[1].asesoriaFO],
[defensores[2].defensor, defensores[2].juzgado, defensores[2].asesoriasO,defensores[2].asesoriaHO,defensores[2].asesoriaFO],
[defensores[3].defensor, defensores[3].juzgado, defensores[3].asesoriasO,defensores[3].asesoriaHO,defensores[3].asesoriaFO],
[defensores[4].defensor, defensores[4].juzgado, defensores[4].asesoriasO,defensores[4].asesoriaHO,defensores[4].asesoriaFO],
[defensores[5].defensor, defensores[5].juzgado, defensores[5].asesoriasO,defensores[5].asesoriaHO,defensores[5].asesoriaFO],
[defensores[6].defensor, defensores[6].juzgado, defensores[6].asesoriasO,defensores[6].asesoriaHO,defensores[6].asesoriaFO],
[defensores[7].defensor, defensores[7].juzgado, defensores[7].asesoriasO,defensores[7].asesoriaHO,defensores[7].asesoriaFO],
[defensores[8].defensor, defensores[8].juzgado, defensores[8].asesoriasO,defensores[8].asesoriaHO,defensores[8].asesoriaFO],
[defensores[9].defensor, defensores[9].juzgado, defensores[9].asesoriasO,defensores[9].asesoriaHO,defensores[9].asesoriaFO]
];
break;
case 'JUSTICIA':
tablaGeneral.widths= ['auto', 'auto', 'auto','auto', 'auto'];
tablaGeneral.body = [
[
{ text: 'Defensor público', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Lugar de adscripción', rowSpan: 3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},{}
],
[
{},
{},
{ text: 'Total',rowSpan:2,style: 'tableHeader', alignment: 'center'},
{ text: 'Justicia para adolecentes', colSpan:2, style: 'tableHeader', alignment: 'center' },
{}
],
[
{},
{},
{},
{ text: 'H',style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
],
[defensores[0].defensor, defensores[0].juzgado, '','',''],
[defensores[1].defensor, defensores[1].juzgado, '','',''],
[defensores[2].defensor, defensores[2].juzgado, '','',''],
[defensores[3].defensor, defensores[3].juzgado, '','',''],
[defensores[4].defensor, defensores[4].juzgado, '','',''],
[defensores[5].defensor, defensores[5].juzgado, '','',''],
[defensores[6].defensor, defensores[6].juzgado, '','',''],
[defensores[7].defensor, defensores[7].juzgado, '','',''],
[defensores[8].defensor, defensores[8].juzgado, '','',''],
[defensores[9].defensor, defensores[9].juzgado, '','','']
];
break;
default:
return {
style : 'tableExample',
color : 'black',
table:{
widths: ['auto', 'auto', 'auto','auto', 'auto', 'auto'],
headerRows: 1,
body: generarCuerpoTop()
}
}
break;
}
tabla.style = 'tableExample';
tabla.color = 'black';
tabla.table = tablaGeneral;
return tabla;
}
function getDefensores(jsonInforme) {
var numHT, numHO, numFT, numFO;
var arrDefensores = [];
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['defensor'] = VALOR.Defensor+' '+ VALOR.appDef+' '+ VALOR.apmDef;
obj['idDef'] = VALOR.idDef;
obj['asesoriasT'] = 0;
obj['asesoriasO'] = 0;
obj['asesoriasTotal'] = 0;
obj['juzgado'] = '';
arrDefensores.push(obj);
});
var hash = {};
arrDefensores = arrDefensores.filter(function (current) {
var exists = !hash[current.defensor] || false;
hash[current.defensor] = true;
return exists;
});
$.each(arrDefensores, function (LLAVE, VAL) {
var aseT=0, aseO=0, audT=0,audO=0, visT=0, visO=0;
numHT=0, numHO=0,numFT=0, numFO=0;
$.each(jsonInforme, function (KEY, VALOR) {
if(VAL.idDef == VALOR.idDef){
if(VALOR.sistema == 'TRADICIONAL'){
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if(VALOR.sexo == 'MASCULINO'){
numHT++;
}else{
numFT++;
}
aseT++;
arrDefensores[LLAVE].asesoriasT = aseT;
}
}else{
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if(VALOR.sexo == 'MASCULINO'){
numHO++;
}else{
numFO++;
}
aseO++;
arrDefensores[LLAVE].asesoriasO = aseO;
}
}
arrDefensores[LLAVE].asesoriaHT=numHT;
arrDefensores[LLAVE].asesoriaFT=numFT;
arrDefensores[LLAVE].asesoriaHO = numHO;
arrDefensores[LLAVE].asesoriaFO = numFO;
arrDefensores[LLAVE].juzgado = VALOR.juzgado;
arrDefensores[LLAVE].asesoriasTotal = aseT + aseO;
}
});
});
arrDefensores.sort(function (a, b) {
if (a.asesoriasTotal < b.asesoriasTotal) {
return 1;
}
if (a.asesoriasTotal > b.asesoriasTotal) {
return -1;
}
// a must be equal to b
return 0;
});
//console.log(arrDefensores);
return arrDefensores;
}
function getNumAsesoriasTO(jsonInforme) {
var asesorias = {};
var numAseT = 0;
var numAseO = 0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if (VALOR.sistema === 'TRADICIONAL') {
numAseT++;
}
if (VALOR.sistema === 'ORAL') {
numAseO++;
}
}
});
asesorias['asesTradicional'] = numAseT;
asesorias['asesOral'] = numAseO;
return asesorias;
}
function getNumSexoUsuarios(jsonInforme) {
var sexos = {};
var numMascT = 0;
var numFemT = 0;
var numMascO = 0;
var numFemO = 0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if (VALOR.sistema == 'TRADICIONAL') {
if (VALOR.sexo == 'MASCULINO') {
numMascT++;
} else if (VALOR.sexo == 'FEMENINO') {
numFemT++;
}
}
if (VALOR.sistema == 'ORAL') {
if (VALOR.sexo == 'MASCULINO') {
numMascO++;
} else if (VALOR.sexo == 'FEMENINO') {
numFemO++;
}
}
}
});
sexos['numMascT'] = numMascT;
sexos['numFemT'] = numFemT;
sexos['numMascO'] = numMascO;
sexos['numFemO'] = numFemO;
return sexos;
}
function getNumDiscapacidadUsuarios(jsonInforme) {
var discapacidades = {};
var numSMT=0, numSFT=0, numMMT=0,numMFT=0, numMEMT=0, numMEFT=0, numMUMT=0,numMUFT=0;
var numSMO=0, numSFO=0, numMMO=0,numMFO=0, numMEMO=0, numMEFO=0, numMUMO=0,numMUFO=0;
var numSensorialesT = 0,numMotricesT = 0, numMentalesT = 0, numMultiplesT=0;
var numSensorialesO = 0,numMotricesO = 0, numMentalesO = 0, numMultiplesO=0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if (VALOR.sistema == 'TRADICIONAL') {
switch(VALOR.discapacidadU){
case 'SENSORIALES':
numSensorialesT++;
if(VALOR.sexo == 'MASCULINO'){
numSMT++;
}else
numSFT++;
break;
case 'MOTRICES':
numMotricesT++;
if(VALOR.sexo == 'MASCULINO'){
numMMT++;
}else
numMFT++;
break;
case 'MENTALES':
numMentalesT++;
if(VALOR.sexo == 'MASCULINO'){
numMEMT++;
}else
numMEFT++;
break;
case 'MULTIPLES':
numMultiplesT++;
if(VALOR.sexo == 'MASCULINO'){
numMUMT++;
}else
numMUFT++;
break;
}
}
if (VALOR.sistema == 'ORAL') {
switch(VALOR.discapacidadU){
case 'SENSORIALES':
numSensorialesO++;
if(VALOR.sexo == 'MASCULINO'){
numSMO++;
}else
numSFO++;
break;
case 'MOTRICES':
numMotricesO++;
if(VALOR.sexo == 'MASCULINO'){
numMMO++;
}else
numMFO++;
break;
case 'MENTALES':
numMentalesO++;
if(VALOR.sexo == 'MASCULINO'){
numMEMO++;
}else
numMEFO++;
break;
case 'MULTIPLES':
numMultiplesO++;
if(VALOR.sexo == 'MASCULINO'){
numMUMO++;
}else
numMUFO++;
break;
}
}
}
});
discapacidades['numSensorialesT'] = numSensorialesT;
discapacidades['numSMT']=numSMT;
discapacidades['numSFT']=numSFT;
discapacidades['numMotricesT'] = numMotricesT;
discapacidades['numMMT']=numMMT;
discapacidades['numMFT']=numMFT;
discapacidades['numMentalesT'] = numMentalesT;
discapacidades['numMEMT']=numMEMT;
discapacidades['numMEFT']=numMEFT;
discapacidades['numMultiplesT'] = numMultiplesT;
discapacidades['numMUMT']=numMUMT;
discapacidades['numMUFT']=numMUFT;
discapacidades['numSensorialesO'] = numSensorialesO;
discapacidades['numSMO']=numSMO;
discapacidades['numSFO']=numSFO;
discapacidades['numMotricesO'] = numMotricesO;
discapacidades['numMMO']=numMMO;
discapacidades['numMFO']=numMFO;
discapacidades['numMentalesO'] = numMentalesO;
discapacidades['numMEMO']=numMEMO;
discapacidades['numMEFO']=numMEFO;
discapacidades['numMultiplesO'] = numMultiplesO;
discapacidades['numMUMO']=numMUMO;
discapacidades['numMUFO']=numMUFO;
return discapacidades;
}
function getNumGeneroUsuarios(jsonInforme) {
var generos = {};
var numLesbicoT = 0;
var numLesbicoO = 0;
var numGayT = 0, numGayO = 0;
var numBisexualT = 0, numBisexualO = 0;
var numTransexualT = 0, numTransexualO = 0;
var numTransgeneroT = 0, numTransgeneroO = 0;
var numTravestiT = 0, numTravestiO = 0;
var numIntersexualT = 0, numIntersexualO = 0;
//console.log(jsonInforme);
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
if (VALOR.sistema == 'TRADICIONAL') {
//console.log(' entro filtro TRADICIONAL');
if (VALOR.generoU == 'LESBICO') {
numLesbicoT++;
//console.log(numLesbicoT, ' numLesbicoTradicional');
}
if (VALOR.generoU == 'GAY') {
numGayT++;
}
if (VALOR.generoU == 'BISEXUAL') {
numBisexualT++;
//console.log(numBisexualT, ' numbisexualTradicional')
}
if (VALOR.generoU == 'TRANSEXUAL') {
numTransexualT++;
}
if (VALOR.generoU == 'TRANSGENERO') {
numTransgeneroT++;
}
if (VALOR.generoU == 'TRAVESTI') {
numTravestiT++;
}
if (VALOR.generoU == 'INTERSEXUAL') {
numIntersexualT++;
}
}
if (VALOR.sistema == 'ORAL') {
//console.log(' entro a ORAL');
if (VALOR.generoU == 'LESBICO') {
numLesbicoO++;
// console.log(numLesbicoO, ' numLesbicoOral');
}
if (VALOR.generoU == 'GAY') {
numGayO++;
}
if (VALOR.generoU == 'BISEXUAL') {
numBisexualO++;
}
if (VALOR.generoU == 'TRANSEXUAL') {
numTransexualO++;
}
if (VALOR.generoU == 'TRANSGENERO') {
numTransgeneroO++;
}
if (VALOR.generoU == 'TRAVESTI') {
numTravestiO++;
}
if (VALOR.generoU == 'INTERSEXUAL') {
numIntersexualO++;
}
}
}
});
generos['numLesbicoT'] = numLesbicoT;
generos['numGayT'] = numGayT;
generos['numBisexualT'] = numBisexualT;
generos['numTransexualT'] = numTransexualT;
generos['numTransgeneroT'] = numTransgeneroT;
generos['numTravestiT'] = numTravestiT;
generos['numIntersexualT'] = numIntersexualT;
generos['numLesbicoO'] = numLesbicoO;
generos['numGayO'] = numGayO;
generos['numBisexualO'] = numBisexualO;
generos['numTransexualO'] = numTransexualO;
generos['numTransgeneroO'] = numTransgeneroO;
generos['numTravestiO'] = numTravestiO;
generos['numIntersexualO'] = numIntersexualO;
//console.log(generos);
return generos;
}
function getNumEdadUsuarios(jsonInforme) {
var edades = {};
var num07T = 0, num07O = 0;
var num812T = 0, num812O = 0;
var num1318T = 0, num1318O = 0;
var num1925T = 0, num1925O = 0;
var num2630T = 0, num2630O = 0;
var num3190T = 0, num3190O = 0;
var num1T = 0, num1O = 0;
var num2T = 0, num2O = 0;
var num3T = 0, num3O = 0;
var hT1=0,hT2=0,hT3=0,hT4=0,hT5=0,hT6=0,hT7=0,hT8=0,hT9=0,
mT1=0,mT2=0,mT3=0,mT4=0,mT5=0,mT6=0,mT7=0,mT8=0,mT9=0,
hO1=0,hO2=0,hO3=0,hO4=0,hO5=0,hO6=0,hO7=0,hO8=0,hO9=0,
mO1=0,mO2=0,mO3=0,mO4=0,mO5=0,mO6=0,mO7=0,mO8=0,mO9=0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
switch(VALOR.sistema){
case'TRADICIONAL':
if (VALOR.edadU >= 18 && VALOR.edadU <= 24) {
num07T++;
if(VALOR.sexo== 'MASCULINO' ){
hT1++;
}else{
mT1++;
}
}
if (VALOR.edadU >= 25 && VALOR.edadU <= 29) {
num812T++;
if(VALOR.sexo== 'MASCULINO' ){
hT2++;
}else{
mT2++;
}
}
if (VALOR.edadU >= 30 && VALOR.edadU <= 34) {
num1318T++;
if(VALOR.sexo== 'MASCULINO' ){
hT3++;
}else{
mT3++;
}
}
if (VALOR.edadU >= 35 && VALOR.edadU <= 39) {
num1925T++;
if(VALOR.sexo== 'MASCULINO' ){
hT4++;
}else{
mT4++;
}
}
if (VALOR.edadU >= 40 && VALOR.edadU <= 44) {
num2630T++;
if(VALOR.sexo== 'MASCULINO' ){
hT5++;
}else{
mT5++;
}
}
if (VALOR.edadU >= 45 && VALOR.edadU <= 49) {
num3190T++;
if(VALOR.sexo== 'MASCULINO' ){
hT6++;
}else{
mT6++;
}
}
if (VALOR.edadU >= 50 && VALOR.edadU <= 54) {
num1T++;
if(VALOR.sexo== 'MASCULINO' ){
hT7++;
}else{
mT7++;
}
}
if (VALOR.edadU >= 55 && VALOR.edadU <= 59) {
num2T++;
if(VALOR.sexo== 'MASCULINO' ){
hT8++;
}else{
mT8++;
}
}
if (VALOR.edadU >= 60) {
num3T++;
if(VALOR.sexo== 'MASCULINO' ){
hT9++;
}else{
mT9++;
}
}
break;
case 'ORAL':
if (VALOR.edadU >= 18 && VALOR.edadU <= 24) {
num07O++;
if(VALOR.sexo== 'MASCULINO' ){
hO1++;
}else{
mO1++;
}
}
if (VALOR.edadU >= 25 && VALOR.edadU <= 29) {
num812O++;
if(VALOR.sexo== 'MASCULINO' ){
hO2++;
}else{
mO2++;
}
}
if (VALOR.edadU >= 30 && VALOR.edadU <= 34) {
num1318O++;
if(VALOR.sexo== 'MASCULINO' ){
hO3++;
}else{
mO3++;
}
}
if (VALOR.edadU >= 35 && VALOR.edadU <= 39) {
num1925O++;
if(VALOR.sexo== 'MASCULINO' ){
hO4++;
}else{
mO4++;
}
}
if (VALOR.edadU >= 40 && VALOR.edadU <= 44) {
num2630O++;
if(VALOR.sexo== 'MASCULINO' ){
hO5++;
}else{
mO5++;
}
} if (VALOR.edadU >= 45 && VALOR.edadU <= 49) {
num3190O++;
if(VALOR.sexo== 'MASCULINO' ){
hO6++;
}else{
mO6++;
}
}
if (VALOR.edadU >= 50 && VALOR.edadU <= 54) {
num1O++;
if(VALOR.sexo== 'MASCULINO' ){
hO7++;
}else{
mO7++;
}
}
if (VALOR.edadU >= 55 && VALOR.edadU <= 59) {
num2O++;
if(VALOR.sexo== 'MASCULINO' ){
hO8++;
}else{
mO8++;
}
}
if (VALOR.edadU >= 60) {
num3O++;
if(VALOR.sexo== 'MASCULINO' ){
hO9++;
}else{
mO9++;
}
}
break;
}
}
});
edades['edades1T'] = num07T;
edades['edades1tH'] = hT1;
edades['edades1tM'] = mT1;
edades['edades2T'] = num812T;
edades['edades2tH'] = hT2;
edades['edades2tM'] = mT2;
edades['edades3T'] = num1318T;
edades['edades3tH'] = hT3;
edades['edades3tM'] = mT3;
edades['edades4T'] = num1925T;
edades['edades4tH'] = hT4;
edades['edades4tM'] = mT4;
edades['edades5T'] = num2630T;
edades['edades5tH'] = hT5;
edades['edades5tM'] = mT5;
edades['edades6T'] = num3190T;
edades['edades6tH'] = hT6;
edades['edades6tM'] = mT6;
edades['edades7T'] = num1T;
edades['edades7tH'] = hT7;
edades['edades7tM'] = mT7;
edades['edades8T'] = num2T;
edades['edades8tH'] = hT8;
edades['edades8tM'] = mT8;
edades['edades9T'] = num3T;
edades['edades9tH'] = hT9;
edades['edades9tM'] = mT9;
edades['edades1O'] = num07O;
edades['edades1OH'] = hO1;
edades['edades1OM'] = mO1;
edades['edades2O'] = num812O;
edades['edades2OH'] = hO2;
edades['edades2OM'] = mO2;
edades['edades3O'] = num1318O;
edades['edades3OH'] = hO3;
edades['edades3OM'] = mO3;
edades['edades4O'] = num1925O;
edades['edades4OH'] = hO4;
edades['edades4OM'] = mO4;
edades['edades5O'] = num2630O;
edades['edades5OH'] = hO5;
edades['edades5OM'] = mO5;
edades['edades6O'] = num3190O;
edades['edades6OH'] = hO6;
edades['edades6OM'] = mO6;
edades['edades7O'] = num1O;
edades['edades7OH'] = hO7;
edades['edades7OM'] = mO7;
edades['edades8O'] = num2O;
edades['edades8OH'] = hO8;
edades['edades8OM'] = mO8;
edades['edades9O'] = num3O;
edades['edades9OH'] = hO9;
edades['edades9OM'] = mO9;
return edades;
}
function getArrayIdiomasSystem(jsonInforme) {
var arrIdiomas = [];
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['idioma'] = VALOR.idiomaU;
obj['pos'] = 0;
arrIdiomas[KEY] = obj;
});
var hash = {};
arrIdiomas = arrIdiomas.filter(function (current) {
var exists = !hash[current.idioma] || false;
hash[current.idioma] = true;
return exists;
});
return arrIdiomas;
}
function getArrayEtniasSystem(jsonInforme) {
var arrEtnias = [];
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['etnia'] = VALOR.etniaU;
obj['pos'] = 0;
arrEtnias[KEY] = obj;
});
var hash = {};
arrEtnias = arrEtnias.filter(function (current) {
var exists = !hash[current.etnia] || false;
hash[current.etnia] = true;
return exists;
});
return arrEtnias;
}
function getIdiomasBySistema(arrIdiomas, jsonInforme) {
var arr = []; //contendra la cantidad de etnias por sistema arr['TRADICIONAL'] arr['ORAL']
var arrTradicional = {};
var arrOral = {};
var contaMT,contaFT, contaMO, contaFO;
//console.log(arrEtnias, jsonInforme);
for (var i = 0; i < arrIdiomas.length; i++) {
contaMT=0,contaFT=0, contaMO=0, contaFO=0;
arrTradicional[arrIdiomas[i]['idioma']] = 0;
arrOral[arrIdiomas[i]['idioma']] = 0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.sistema == 'TRADICIONAL') {
if (arrIdiomas[i]['idioma'] == VALOR.idiomaU) {
//console.log(arrIdiomas[i]['idioma'], ' valor IDIOMAAAAA');
arrTradicional[arrIdiomas[i]['idioma']] += 1;
if(VALOR.sexo == 'MASCULINO'){
contaMT++;
}else{
contaFT++;
}
}
} else if (VALOR.sistema == 'ORAL') {
if (arrIdiomas[i]['idioma'] == VALOR.idiomaU) {
arrOral[arrIdiomas[i]['idioma']] += 1;
if(VALOR.sexo == 'MASCULINO'){
contaMO++;
}else{
contaFO++;
}
}
}
});
arrTradicional[arrIdiomas[i]['idioma']+'MT'] = contaMT;
arrTradicional[arrIdiomas[i]['idioma']+'FT'] = contaFT;
arrOral[arrIdiomas[i]['idioma']+'MO'] = contaMO;
arrOral[arrIdiomas[i]['idioma']+'FO'] = contaFO;
}
arr.push(arrTradicional);
arr.push(arrOral);
return arr;
}
function getEtniasBySistema(arrEtnias, jsonInforme) {
var arr = []; //contendra la cantidad de etnias por sistema arr['TRADICIONAL'] arr['ORAL']
var arrTradicional = {};
var arrOral = {};
//console.log(arrEtnias, jsonInforme);
for (var i = 0; i < arrEtnias.length; i++) {
var contaMT=0,contaFT=0, contaMO=0, contaFO=0;
arrTradicional[arrEtnias[i]['etnia']] = 0;
arrOral[arrEtnias[i]['etnia']] = 0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.sistema == 'TRADICIONAL') {
if (arrEtnias[i]['etnia'] == VALOR.etniaU) {
arrTradicional[arrEtnias[i]['etnia']] += 1;
if(VALOR.sexo == 'MASCULINO'){
contaMT++;
}else{
contaFT++;
}
}
} else if (VALOR.sistema == 'ORAL') {
if (arrEtnias[i]['etnia'] == VALOR.etniaU) {
arrOral[arrEtnias[i]['etnia']] += 1;
if(VALOR.sexo == 'MASCULINO'){
contaMO++;
}else{
contaFO++;
}
}
}
});
arrTradicional[arrEtnias[i]['etnia']+'MT'] = contaMT;
arrTradicional[arrEtnias[i]['etnia']+'FT'] = contaFT;
arrOral[arrEtnias[i]['etnia']+'MO'] = contaMO;
arrOral[arrEtnias[i]['etnia']+'FO'] = contaFO;
}
arr.push(arrTradicional);
arr.push(arrOral);
return arr;
}
function getNumIdiomasUsers(arrIdiomas, jsonInforme) {
var arr = [];
//console.log(arrEtnias, ' arr etnias');
for (var i = 0; i < arrIdiomas.length; i++) {
$.each(jsonInforme, function (KEY, VALOR) {
//console.log(i, arrEtnias[i]['etnia'], arrEtnias[i]['pos']);
//console.log(VALOR.etniaU, ' etnias json');
if (arrIdiomas[i]['idioma'] == VALOR.idiomaU) {
//console.log(arrEtnias[i]['pos'], ' arretniasvalor Pos');
var obj = {};
arrIdiomas[i]['pos'] += 1;
obj[arrIdiomas[i]['idioma']] = arrIdiomas[i]['pos'];
arr[i] = obj;
}
});
}
//console.log(arr, ' valor arr');
return arr;//contiene las filas pero solo nombre de la etnia y su cantidad total en ambos sistemas
// falta por sistema
}
function getNumEtniasUsers(arrEtnias, jsonInforme) {
var arr = [];
var ite = 0;
//console.log(arrEtnias, ' arr etnias');
for (var i = 0; i < arrEtnias.length; i++) {
$.each(jsonInforme, function (KEY, VALOR) {
//console.log(i, arrEtnias[i]['etnia'], arrEtnias[i]['pos']);
//console.log(VALOR.etniaU, ' etnias json');
if (arrEtnias[i]['etnia'] == VALOR.etniaU) {
//console.log(arrEtnias[i]['pos'], ' arretniasvalor Pos');
var obj = {};
arrEtnias[i]['totalT'] += 1;
obj[arrEtnias[i]['etnia']] = arrEtnias[i]['pos'];
switch(VALOR.sistema){
case 'TRADICIONAL':
arrEtnias[i]['totalTra'] += 1;
obj[arrEtnias[i]['tradicional']] = arrEtnias[i]['totalTra'];
break;
case 'ORAL':
arrEtnias[i]['totalOral'] += 1;
obj[arrEtnias[i]['oral']] = arrEtnias[i]['totalOral'];
break;
}
arr.push(obj);
}
});
}
//console.log(arr, ' valor arr');
return arr;//contiene las filas pero solo nombre de la etnia y su cantidad total en ambos sistemas
// falta por sistema
}
function getNumIdiomasUsuarios(jsonInforme) {
var arrIdiomas = [];
var idiomas;
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['idioma'] = VALOR.idiomaU;
arrIdiomas[KEY] = obj;
});
//console.log(arrEtnias, ' VALOR ETNIA');
var hash = {};
arrIdiomas = arrIdiomas.filter(function (current) {
var exists = !hash[current.idioma] || false;
hash[current.idioma] = true;
return exists;
});
//aqui arrEtnias ya tiene filtrado las etnias
//idiomas = getNumIdiomasUsers(arrIdiomas, jsonInforme);
return arrIdiomas;
}
function getListaDef(jsonInforme) {
var arrDefs = [];
var defs;
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['defensor'] = VALOR.nombreP;
arrDefs[KEY] = obj;
});
//console.log(arrEtnias, ' VALOR ETNIA');
var hash = {};
arrDefs = arrDefs.filter(function (current) {
var exists = !hash[current.defensor] || false;
hash[currentm.defensor] = true;
return exists;
});
//aqui arrEtnias ya tiene filtrado las etnias
//etnias = getNumEtniasUsers(arrEtnias, jsonInforme);
return arrDefs;
}
function getNumEtniasUsuarios(jsonInforme) {
var arrEtnias = [];
var etnias;
$.each(jsonInforme, function (KEY, VALOR) {
var obj = {};
obj['etnia'] = VALOR.etniaU;
arrEtnias[KEY] = obj;
});
//console.log(arrEtnias, ' VALOR ETNIA');
var hash = {};
arrEtnias = arrEtnias.filter(function (current) {
var exists = !hash[current.etnia] || false;
hash[current.etnia] = true;
return exists;
});
//aqui arrEtnias ya tiene filtrado las etnias
//etnias = getNumEtniasUsers(arrEtnias, jsonInforme);
return arrEtnias;
}
function generarRowsIdiomas(jsonData, idiomasSistema) {
//console.log(etniasSistema[0]['CHATINO'], ' cuantos chatino tradicional ');
var body = new Array();
var rowHeader1 = [], rowHeader2 = [],rowHeader3 = [];
rowHeader1.push(
{ text: 'Idioma o Lengua', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
);
rowHeader2.push(
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
);
rowHeader3.push(
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
);
body.push(rowHeader1);
body.push(rowHeader2);
body.push(rowHeader3);
var content = [];
var totalF = 0, totalT = 0, totalO = 0;
for (var obj in jsonData) {
if (jsonData.hasOwnProperty(obj)) {
for (var prop in jsonData[obj]) {
if (jsonData[obj].hasOwnProperty(prop)) {
content = [prop, jsonData[obj][prop], idiomasSistema[0][prop], idiomasSistema[0][prop+'MT'],idiomasSistema[0][prop+'FT'],idiomasSistema[1][prop],idiomasSistema[1][prop+'MO'],idiomasSistema[1][prop+'FO']];
body.push(content);
totalF += jsonData[obj][prop];
totalT += idiomasSistema[0][prop];
totalO += idiomasSistema[1][prop];
}
}
}
}
content = ['TOTAL', totalF, totalT, '','',totalO,'',''];
body.push(content);
return body;
}
function generarRowsEtnias(jsonData, etniasSistema, valor) {
//console.log(etniasSistema[0]['CHATINO'], ' cuantos chatino tradicional ');
var body = new Array();
var rowHeader1 = [], rowHeader2 = [], rowHeader3=[];
switch(valor){
case 'TRADICIONAL':
rowHeader1.push(
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
);
rowHeader2.push(
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
);
rowHeader3.push(
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
);
body.push(rowHeader1);
body.push(rowHeader2);
body.push(rowHeader3);
var content = [];
var totalF = 0, totalT = 0, totalO = 0;
for (var obj in jsonData) {
if (jsonData.hasOwnProperty(obj)) {
for (var prop in jsonData[obj]) {
if (jsonData[obj].hasOwnProperty(prop)) {
content = [prop, jsonData[obj][prop], etniasSistema[0][prop],etniasSistema[0][prop+'MT'],etniasSistema[0][prop+'FT'], etniasSistema[1][prop],etniasSistema[1][prop+'MO'],etniasSistema[1][prop+'FO']];
body.push(content);
totalF += jsonData[obj][prop];
totalT += etniasSistema[0][prop];
totalO += etniasSistema[1][prop];
}
}
}
}
content = ['TOTAL', totalF, totalT,'','', totalO,'',''];
body.push(content);
break;
case 'ORAL':
break;;
case 'JUSTICIA':
break;
default:
rowHeader1.push(
{ text: 'Etnias', rowSpan:3, style: 'tableHeader', alignment: 'center' },
{ text: 'Sistema de justicia', colSpan:7, style: 'tableHeader', alignment: 'center' },
{},{},{},{},{},{}
);
rowHeader2.push(
{},
{ text: 'Total', rowSpan:2, style: 'tableHeader', alignment: 'center' },
{ text: 'Tradicional',colSpan: 3, style: 'tableHeader', alignment: 'center' },
{},
{},
{ text: 'Acusatorío y oral', colSpan:3, style: 'tableHeader', alignment: 'center' },
{},
{}
);
rowHeader3.push(
{},
{},
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' },
{ text: 'Total', style: 'tableHeader', alignment: 'center' },
{ text: 'H', style: 'tableHeader', alignment: 'center' },
{ text: 'M',style: 'tableHeader', alignment: 'center' }
);
body.push(rowHeader1);
body.push(rowHeader2);
body.push(rowHeader3);
var content = [];
var totalF = 0, totalT = 0, totalO = 0;
for (var obj in jsonData) {
if (jsonData.hasOwnProperty(obj)) {
for (var prop in jsonData[obj]) {
if (jsonData[obj].hasOwnProperty(prop)) {
content = [prop, jsonData[obj][prop], etniasSistema[0][prop],etniasSistema[0][prop+'MT'],etniasSistema[0][prop+'FT'], etniasSistema[1][prop],etniasSistema[1][prop+'MO'],etniasSistema[1][prop+'FO']];
body.push(content);
totalF += jsonData[obj][prop];
totalT += etniasSistema[0][prop];
totalO += etniasSistema[1][prop];
}
}
}
}
content = ['TOTAL', totalF, totalT,'','', totalO,'',''];
body.push(content);
break;
}
return body;
}
function getNumActividades(jsonInforme) {
console.log(jsonInforme, " jsonnInforme ");
var actividades = {};
var numAses = 0;
var numAuds = 0;
var numVis = 0;
$.each(jsonInforme, function (KEY, VALOR) {
if (VALOR.latAse != null || VALOR.longAse != undefined) {
numAses++;
}
if (VALOR.latAud != null || VALOR.longAud != undefined) {
numAuds++;
}
if (VALOR.fotoVis != null || VALOR.fotoVis != undefined) {
numVis++;
}
});
actividades['asesorias'] = numAses;
actividades['audiencias'] = numAuds;
actividades['visitas'] = numVis;
console.log("valor devuelto en func acividades ", actividades);
return actividades;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<file_sep><?php
include_once('../../libreria/conexion.php');
function getDetalleByContraparteAndExpediente($id_contraparte,$id_expediente){
$sql = "select * from contraparte_expediente
where id_expediente=".$id_expediente."
and id_contraparte='".$id_contraparte."'";
$lista = consulta($sql);
return $lista;
}
function alta_DetalleContraparte($objeto){
$sql = "INSERT INTO contraparte_expediente ";
$sql.= " SET id_expediente='".$objeto['id_expediente']."', id_contraparte='".$objeto['id_contraparte']."', ";
$sql.= " tipo_contraparte='".$objeto['tipo_contraparte']."', ";
$sql.= " parentesco='".$objeto['parentesco']."' ";
// echo $sql;
$lista=registro($sql);
return $lista;
}
?><file_sep>SELECT * FROM bddefensoria.cargo;
-- INSERT
INSERT INTO cargo VALUES (1, 'admin');
INSERT INTO cargo VALUES (2, 'coordinador');
INSERT INTO cargo VALUES (3, 'coordinador_defensor');
INSERT INTO cargo VALUES (4, 'estadistica');
INSERT INTO cargo VALUES (5, 'defensor');
-- UPDATE
-- DELETE
<file_sep><?php
include_once('../../modelo/expediente.php');
$respuesta = Array(
"id_expediente" =>$_GET['id_expediente'],
"fecha_baja" =>"",
"motivos" =>"",
"estado" =>"PROCESO",
"observaciones" =>""
);
//$verificarRegistro=existeRespuestaExpediente($_POST['id_expediente'],$_POST['id_pregunta']);
//if($verificarRegistro==0)// 0 INDICA QUE NO EXITE LA RESPUESTA A UNA PREGUNTA DE UN DICHO EXPEDIENTE
//print_r($respuesta);
{setBajaActivoExpediente($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Activacion de expediente exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
?><file_sep><?php
header('Content-Type: application/json');
include '../../modelo/personal.php';
include '../../modelo/defensor/defensor.php';
include '../../modelo/usuario_sistema.php';
include '../../libreria/herramientas.php';
include '../../modelo/materia.php';
///verifica si el puesto es de defensor
$materia=($_POST["puesto"]==2)?"coordinador":$_POST["materia"];
//echo $_POST["materia"];
//echo $_POST["instancia"];
//echo $_POST["nue"];
$personal = Array(
"id_cargo" =>$_POST['puesto'],
"nombre" =>$_POST['nombre'],
"ap_paterno" =>$_POST['apellido_paterno'],
"ap_materno" =>$_POST['apellido_materno'],
"curp" =>$_POST['curp'],
"calle" =>"",
"numero_ext" =>"",
"numero_int" =>" ",
"colonia" =>"",
"municipio" =>"",
"nup" =>$_POST['nup'],
"nue" =>$_POST['nue'],
"rfc" =>$_POST['rfc'],
"genero" =>$_POST['genero'],
"telefono" =>$_POST['telefono'],
"correo" =>$_POST['email'],
"etnia" =>$_POST['etnia'],
"idioma" =>$_POST['idioma'],
"foto" =>" "
);
// crear_juzgado($juzgado);
// echo isset($_GET['tipo']);
print_r($personal);
$personal = array_map( "cadenaToMayuscula",$personal);/// convierte todo a mayusculas
if(listar_defensor_x_nue($_POST['nue'])==0){
$mensaje=['tipo'=>"juzgado",
'mensaje'=>"no puedes tener mas de 1 coordinaodr en un juzgado"];
$didigir="registrar_defensor";
if(!vericar_coordinador($_POST['puesto'])){
crear_personal($personal);
$id_materia= get_materia_instancia_sistema($_POST["materia"],$_POST["instancia"],$_POST["sistema"]);
// print_r($id_materia);
$defensor=Array(
"id_juzgado"=>$_POST['adscripcion'],
"id_materia" =>$id_materia[0]['id_materia'],
"id_personal"=>ultimoPersonalCreatado()
);
crear_defensor($defensor);
$personal['username']=$_POST['nue'];
$personal['password']=encriptar($_POST['password']);
crear_usarioSistema($personal);
$mensaje=['tipo'=>"exito",
'mensaje'=>"registro existoso"];
$didigir="listar_defensor";
$asunto = "Envio de Nip Acceso Al Sistemas ";
$email = " accede a la siguiente pagina http://localhost/defensoriaPublica/ con tu contraseña: ".$_POST['password'];
envio_correo($personal['correo'], $asunto, $email);
}
}
else{
$mensaje=['tipo'=>"error",
'mensaje'=>"el personal con el nup ya se encuentra registrado"];
$didigir="registrar_defensor";
}
// ultimoPersonalCreatado();
if(!isset($_GET['tipo'])){
session_start();
$_SESSION['mensaje'] = $mensaje;
$_SESSION['dirigir']=$didigir;
header("location: ../../vistas/administrador/index.php");
}
else{
echo "json";
}
function vericar_coordinador($puesto){
// print_r (listar_defensor_x_juzgado($_POST['adscripcion']));
if($puesto=='2')
if(listar_defensor_x_juzgado($_POST['adscripcion']))
return true;
return false;
}
?><file_sep>
function mayusculas(e, elemento) {
tecla=(document.all) ? e.keyCode : e.which;
elemento.value = elemento.value.toUpperCase();
// console.log(elemento.value);
}
function fechaTermino(){
var date= Date();
console.log(fecha,"fecha");
document.getElementById('fecha_termino').value
}
function registroEscolaridad(){
/* var isFamiliar=$("#isFamiliar").prop('checked')
var tipoContraparte=(isFamiliar===true)?"FAMILIAR":"NINGUNO";
*/
var person=document.getElementById('id_personal').value;
console.log(person," mostrano al personal");
var sendInfo = {
"id_personal" :document.getElementById('id_personal').value,
"perfil" :document.getElementById('perfil').value,
"grado_escolaridad" :document.getElementById('grado_estudio').value,
"fecha_termino" :document.getElementById('fecha_termino').value,
"instituto" :document.getElementById('instituto').value,
"documento_provatorio" :document.getElementById('documento_provatorio').value,
//"nombre_estudio" :"",
"descripcion_perfil_egreso" :document.getElementById('descripcion_perfil').value,
// "cedula_profesional" :"",
"especialidad" :document.getElementById('especialidad').value
};
var correcto=true;
console.log("datos a enviar ",sendInfo);
Object.entries(sendInfo).forEach(([key, value]) => {//recorro el arreglo y verifico si hay alguno que este vacio
// console.log("FFEE", ((`${value}`)==="")); // "a 5", "b 7", "c 9"
if((`${value}`)===""){
correcto=false;
// console.log("dentro", ((`${value}`)==="")); // "a 5", "b 7", "c 9"
$("#enviarFormEstudio").attr("type","submit");
return false
}else
$("enviarFormEstudio").attr("type","button");
return true;
});
var formData = new FormData(document.getElementById("myform"));
// formData.append("dato", "valor");
if(correcto===true)
$.ajax({
type: "POST",
url: "../../controlador/defensor/registrarEstudio.php",
dataType: "html",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
var json=jQuery.parseJSON(data)
console.log(data);
var alert="";
if(json['tipo']==="exito")
alert="alert alert-success";
//$alert='alert alert-danger';
if(json['tipo']==="error")
alert="alert alert-danger";
if(json['tipo']==="juzgado")
alert="alert alert-danger";
$("#contenedorMensaje").attr("class",""+alert);
$("#contenedorMensaje").append('<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">'+
'<div class="modal-dialog modal-dialog-centered" role="document">'+
'<div class="modal-content">'+
'<strong align="center" id="id_Mensaje" class="alert-dismissible fade in '+alert+'"></strong>'+
'<div class="modal-footer">'+
' <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>'+
'</div></div> </div></div>');
$("#id_Mensaje").text(json['mensaje']);
console.log(json['mensaje']," fue esto");
$('#exampleModalLong').modal('show');
console.log("ffef en always ",json['tipo']);
//if(json['tipo']==="exito")
// $("#registroContraparte").children().remove();
},
// data: sendInfo
data: formData
});
/* $.ajax({
url: "../../controlador/expediente/registrarContraparte.php",
type: "POST",
data: {id_contraparte:"fff"},
beforeSend: function(xhrObj){
// xhrObj.setRequestHeader("Content-Type","application/json");
/// xhrObj.setRequestHeader("Accept","application/json");
//xhrObj.setRequestHeader("X-Mashape-Key","<KEY>");
},
dataType: "json",
success: function (data) {
console.log(data)
/* var json=jQuery.parseJSON(data)
$.each(json,function(key, valor) {
localizarPorGeocoder(valor.juzgado);
console.log(valor);
}); */
/* }
});//FINAL DE AJAX */
}<file_sep><?php
include_once('../../modelo/defensor/defensor.php');
include '../../libreria/herramientas.php';
$respuesta = Array(
"id_personal" =>$_POST['id_personal'],
"perfil" =>$_POST['perfil'],
"grado_escolaridad" =>$_POST['grado_escolaridad'],
"fecha_termino" =>$_POST['fecha_termino'],
"instituto" =>$_POST['instituto'],
// "documento_provatorio" =>$_POST['documento_provatorio'],
"nombre_estudio" =>"",
"descripcion_perfil_egreso" =>$_POST['descripcion_perfil_egreso'],
"cedula_profesional" =>"",
"especialidad" =>$_POST['especialidad']
);
$respuesta = array_map( "cadenaToMayuscula",$respuesta);/// convierte todo a mayusculas
$nombreArchivo="";
// echo "Error: " . $_FILES['archivo']['error'] ;
//echo "comprabante es =>".$_FILES["archivo"]["name"];
if(isset($_FILES['documento_provatorio']))
if ($_FILES['documento_provatorio']["error"] > 0)
{
// echo "Error: " . $_FILES['archivo']['error'] . "<br>";
$mensaje=['tipo'=>"error",
'mensaje'=>$_FILES['documento_provatorio']['error']];
$dirigir="registrar_actividad";
}
if($_FILES['documento_provatorio']['size'] != 0){
$nombreArchivo = $_FILES["documento_provatorio"]["name"];
$rutaFoto = $_FILES["documento_provatorio"]["tmp_name"];
$carpeta='../../recursos/archivo/documentoProvatorio/';
if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);
}
$destino = $carpeta.basename($nombreArchivo);
move_uploaded_file($rutaFoto,$destino);
}
$respuesta['documento_provatorio']=$nombreArchivo;
{registrarEstudio($respuesta);
$mensaje=['tipo' =>"exito",
'mensaje'=>"Actualizacion exitoso"];
// echo "el registro es exitoso" ;
}
//print_r($respuesta);
echo json_encode($mensaje);
/* else
echo "el registro ya existe";
*/
?> | f5f8f4a759b3ba20484d11f6fa59b664f6b0218f | [
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 143 | PHP | wilfridoSantos/defensoriaPublica | bfe8f0ef5f8b34e3cbe58973e91dd203ae295ecd | d1df3f7f7de032e937dc44f54222a37c028657e0 |
refs/heads/master | <repo_name>georgercarder/Sudoku_in_React<file_sep>/src/prev/game.js
import React from 'react';
import './index.css';
import Board from './board';
class Game extends React.Component {
constructor(props){
super(props);
this.state={
prepuzzle: this.props.puzzles[Math.floor(Math.random()*30)].puzzle,
rank: 2,
prerank: 2,
difficulty: 5,
predifficulty: 5,
squares: Array(16).fill(null),
red: Array(16).fill(null),
win: false,
message: null,
status: <h3>push 'start' to start game</h3>,
startorclear: 'start',
started: 0,
puzzles: this.props.puzzles,
};
}
setRank(){
if(this.state.prerank===2){
this.setState({prerank: 3})
} else {
this.setState({prerank: 2})
}
}
setDiff(){
var predifficulty = this.state.predifficulty
this.setState({predifficulty: (predifficulty%6)+1})
}
load(){
this.findPuzzle(this.state.prerank,this.state.predifficulty);
this.setState({
rank: this.state.prerank,
difficulty: this.state.predifficulty,
/*squares,red:Array(this.state.prerank**4).fill(null)*/
win: false,
message: null,
startorclear: 'start',
started: 0,
})
setTimeout(function() {this.start()}.bind(this),1)
}
findPuzzle(rank,diff){
var l = this.state.puzzles.length
var found = false
var r = 0
while(found === false){
r = Math.floor(Math.random()*l)
if(this.state.puzzles[r].rank===rank && this.state.puzzles[r].difficulty===diff){
this.setState({prepuzzle: this.state.puzzles[r].puzzle.slice()})
found = true
}
}
}
startorclear(){
if(this.state.startorclear==='start'){
return(<h3>start</h3>);
} else {
return(<h3>clear</h3>);
}
}
start(){
if(this.state.startorclear==='start'){
const red=this.state.red.slice()
const squares= this.state.squares.slice();
var puzzle=this.state.prepuzzle;
/*[1,4,0,0,0,0,0,0,3,0,1,0,0,0,2,0]*/
for(var i=0;i<this.state.rank**4;i++){
if(puzzle[i]!==0){
squares[i]=puzzle[i]
red[i]=puzzle[i]
} else {
squares[i]=null
red[i]=null
}
}
this.setState({
squares: squares,
red: red,
started: 1,
startorclear: "clear",
}, () => this.changeStatus());
} else {
this.setState({
squares: Array(this.state.rank**4).fill(null),
red: Array(this.state.rank**4).fill(null),
win: false,
checking: 0,
message: null,
startorclear: 'start',
started: 0,
}, () => this.changeStatus());
}
}
handleClick(i){
const squares = this.state.squares.slice();
squares[i]=(squares[i]%this.state.rank**2)+1;
this.setState({squares: squares});
}
changeStatus(){
if(this.state.started!==1){
this.setState({status: <h3>Push 'start' to start game</h3>})
} else if (this.state.win===false&&this.state.message!==1){
this.setState({status: <h3>game in progress</h3>});
} else if (this.state.win===false&&this.state.message===1){
this.setState({status: <h3>nope, keep trying</h3>});
}else {
this.setState({status: <h3>SUDOKU WINNER!</h3>});
}
}
gamecheck(){
//this.state.squares
var SQUARES=this.state.squares.slice()
var rank=this.state.rank
// ROWS COLUMNS BOXES
var decision=true
// rows
let set = new Set()
for(var i=0;i<(rank**2);i++){
set.clear()
for(var j=0;j<=(rank**2);j++){
set.add(SQUARES[j+i*(rank**2)])
}
if(set.size<(rank**2)){
decision=false
break
}
}
// cols
for(var j=0;j<(rank**2);j++){
set.clear()
for(var i=0;i<=(rank**2);i++){
set.add(SQUARES[j+i*(rank**2)])
}
if(set.size<(rank**2)){
decision=false
break
}
}
// boxes will be difficult...
var b = 0
let box = new Set()
while(b<rank**2){
for(var i=0;i<rank;i++){
for(var j=0;j<rank;j++){
box.clear()
for(var ii=rank*i;ii<rank*(i+1);ii++){
for(var jj=rank*j;jj<rank*(j+1);jj++){
box.add(SQUARES[jj+(rank**2)*ii])
b=b+1
}
}
if(box.size<(rank**2)){
decision=false
break
}
}
if(decision===false){
break
}
}
if(decision===false){
break
}
}
if( decision===true ){
this.setState({
win: true,
red: this.state.squares
}, () => this.changeStatus());
} else {
this.setState({
win: false,
message:1
}, () => this.changeStatus());
setTimeout(function() {this.setState({message: 2}, () => this.changeStatus())}.bind(this),1200)
}
}
render() {
const welcome = '<NAME>ine';
return (
<div>
<div className="welcome">
<h1>{welcome}</h1>
</div>
<div className="dashboard">
<div className="button" onClick={() => this.setRank()}>
<h3>rank {this.state.prerank}</h3>
</div>
<div className="button" onClick={() => this.setDiff()}>
<h3>difficulty {this.state.predifficulty}</h3>
</div>
<div className="button" onClick={() => this.load()}>
<h3>select</h3>
</div>
<div className="button" onClick={() => this.start()}>
{this.startorclear()}
</div>
<div className="button" onClick={() => this.gamecheck()}>
<h3>check</h3>
</div>
</div>
<div className="status">
{this.state.status}
</div>
<div className="gamePad">
<div className="game" >
<Board
rank={this.state.rank}
difficulty={this.state.difficulty}
squares={this.state.squares}
red={this.state.red}
gamestatus={() => this.gamestatus()}
onClick={(i) => this.handleClick(i)}
/>
</div>
</div>
</div>
);
}
}
export default Game;
<file_sep>/src/prev/redsquare.js
import React from 'react';
import './index.css';
function RedSquare(props){
return(
<button className="redsquare">
{props.value}
</button>
);
}
export default RedSquare;
<file_sep>/README.md
# Sudoku in React
##This repo consists of the front end to this project.
As for the back end, Sudoku puzzles generated and stocked into a MongoDB by
python scripts in the following repos:
[https://github.com/georgercarder/sudokugridgen](https://github.com/georgercarder/sudokugridgen)
[https://github.com/georgercarder/genpuzzles](https://github.com/georgercarder/genpuzzles)
sudokugridgen has been published on PyPi
| 479a7c38025a7f08abbbd64175d6f596163663b5 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | georgercarder/Sudoku_in_React | 9ef4e6fcb6eaf21846ee4a0411a683e353a4f829 | 453bfcb055c9e07c6848786744506f9321b89f17 |
refs/heads/main | <repo_name>DavidCasc/4001_Final<file_sep>/makefile
all: DB_Server DB_Editor ATM interestCalculator
DB_Server: DB_Server.c shared.h
gcc DB_Server.c -o DB_Server -lm
DB_Editor: DB_Editor.c
gcc DB_Editor.c -o DB_Editor -lm
ATM: ATM.c
gcc ATM.c -o ATM -lm
interestCalculator: interestCalculator.c
gcc interestCalculator.c -o interestCalculator -lm
<file_sep>/DB_Editor.c
#include "shared.h"
void SIGINT_handler(int);
int main() {
/* Input Variables */
char accountNum[BUFSIZ];
char pinNum[BUFSIZ];
char accountBal[BUFSIZ];
char buffer[BUFSIZ];
/* MISC */
struct message_t pin_data;
size_t size;
//Variable for IPC
int msgid, shmid;
//Create semaphore for rates shared memory
int ratessemid;
struct sembuf p = { 0, -1, SEM_UNDO};
struct sembuf v = { 0, +1, SEM_UNDO};
//Create message queue
msgid = msgget((key_t) toDB_key, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Create shared memory
shmid = shmget((key_t) ratesKey, sizeof(struct rates_t),0666 | IPC_CREAT);
if (shmid == -1){
fprintf(stderr, "shmget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Attach shared memory
struct rates_t *rates = (struct rates_t*) shmat(shmid,(void*)0,0);
if (rates ==(void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
//Create a semaphore for the shared memory for the variable rates
ratessemid = semget((key_t)ratesSemKey, 1, 0600 | IPC_CREAT);
if(ratessemid < 0){
printf("Failed to create semaphore\n");
exit(-1);
}
//set the initial rates
if(semop(ratessemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
rates->negInterest = 0.02;
rates->posInterest = 0.01;
if(semop(ratessemid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Install signal
if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
//Run infinitely
while (1) {
/* Enter a main menu where you can choose to edit interest or add account*/
printf("Press \"I\" to change Interest Rates and \"A\" to add account:");
fflush(stdin);
fgets(buffer, BUFSIZ, stdin);
/* If editing the interest is chosen create a new menu */
if(strncmp(buffer,"I",1) == 0){
//Get user input for the positive rate
printf("What is the new positive interest rate(1 = 1%%):");
char posRate[BUFSIZ];
fgets(posRate, BUFSIZ, stdin);
//Convert to percent
float posFloat = atof(posRate);
posFloat = posFloat/100;
//Get input for the negative rate
printf("What is the new negative interest rate(1= 1%%):");
char negRate[BUFSIZ];
fgets(negRate, BUFSIZ, stdin);
//Convert to percent
float negFloat = atof(negRate);
negFloat = negFloat/100;
/* Enter the critical code and lock the share memory*/
if(semop(ratessemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
//Update the rates
rates->negInterest = negFloat;
rates->posInterest = posFloat;
//Unlock the shared memory
if(semop(ratessemid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
}
/* Enter a form to create a new account */
else if(strncmp(buffer,"A",1) ==0) {
//Get input for the Account number
printf("Please Enter Account Number:");
fflush(stdin);
fgets(accountNum, BUFSIZ, stdin);
//Get input for the pin number
printf("Please Enter PIN Number:");
fflush(stdin);
fgets(pinNum, BUFSIZ, stdin);
//Get input for the funds available
printf("Please Enter Available Funds:");
fflush(stdin);
fgets(accountBal, BUFSIZ, stdin);
//convert the \n to commas
accountNum[strcspn(accountNum, "\n")] = ',';
pinNum[strcspn(pinNum, "\n")] = ',';
accountBal[strcspn(accountBal, "\n")] = '\0';
//create the message to send to the DB Server
size = strlen(accountNum) + strlen(pinNum) + strlen(accountBal) + strlen("DB_UPDATE,") + 2;
char *message = malloc(size);
strncpy(message, "DB_UPDATE,", strlen("DB_UPDATE,"));
size = strlen("DB_UPDATE,");
strncpy(message + size, accountNum, strlen(accountNum));
size = strlen("DB_UPDATE,") + strlen(accountNum);
strncpy(message + size, pinNum, strlen(pinNum));
size = strlen("DB_UPDATE,") + strlen(accountNum) + strlen(pinNum);
strncpy(message + size, accountBal, strlen(accountBal));
printf("Message: %s\n", message);
//Copy string to message and send
strcpy(pin_data.msg_text, message);
pin_data.msg_type = 1;
if (msgsnd(msgid, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
printf("Before free\n");
free(message);
printf("After free\n");
}
}
}
void SIGINT_handler(int sig)
{
exit(1);
}
<file_sep>/DB_Server.c
#include "shared.h"
void SIGINT_handler(int);
int main(){
//Create variables for tracking the new pids
pid_t pid_interest, pid_editor;
pid_editor = fork();
/* Local Store Variables */
struct account_t *localStore = NULL;
int returnAddress;
/* File references */
FILE *DBFile;
FILE *DBTemp;
FILE *logFile;
char* DBFileStr = "./DB.txt";
char* DBTempStr = "./DB_temp.txt";
char* logStr = "./deadlockslog.txt";
char *line = NULL;
size_t len = 0;
ssize_t read;
/* Semaphore Variables */
int semid, ratessemid, logsemid;
union semun u, ratessem, logssem;
struct sembuf p = { 0, -1, SEM_UNDO};
struct sembuf v = { 0, +1, SEM_UNDO};
/* Variables for shared memory */
int shmid;
struct rates_t *rates;
/* Variables for Message queues */
int toATMqueue;
int toDBqueue;
/* MISC */
int accountFound = 0; //Flag for if the account is found
int running = 1; //flag for main loop
struct message_t msgData; //Create a message for the message queue
//Fork to start the editor process
switch(pid_editor){
case -1:
printf("fork failed\n");
exit(0);
/* Child Process */
case 0:
execv("DB_Editor", NULL);
break;
/* Parent Process */
default:
break;
}
/* Create message queue for outward (to ATM) messages */
toATMqueue = msgget((key_t) toATM_key, 0666 | IPC_CREAT);
if (toATMqueue == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
/* Create message queue for inward (to Server) messages*/
toDBqueue = msgget((key_t) toDB_key, 0666 | IPC_CREAT);
if (toDBqueue == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
/* Set up semaphore for the database text file */
/* Create semaphore for accesing the database text file*/
semid = semget((key_t)dbSemKey, 1, 0600 | IPC_CREAT);
if(semid < 0){
printf("Failed to create semaphore\n");
exit(-1);
}
//Initialize semaphore with a value of one
u.val = 1;
//Set the Value
if (semctl(semid, 0, SETVAL, u) < 0) {
fprintf(stderr, "semctl failed with error: %d\n", errno);
}
//Fork to start the interestCalculator
pid_interest = fork();
switch(pid_interest){
case -1:
printf("Fork Failed\n");
exit(-1);
case 0:
execv("interestCalculator", NULL);
break;
default:
break;
}
/* Set up a semaphore for the shared memory for the variable rates */
//get IPC for sem
ratessemid = semget((key_t)ratesSemKey, 1, 0600 | IPC_CREAT);
if(ratessemid < 0){
printf("Failed to create semaphore\n");
exit(-1);
}
//Initialize a the variable rates semaphore to a value of 1
ratessem.val = 1;
//Set the value
if (semctl(ratessemid, 0, SETVAL, ratessem) < 0) {
fprintf(stderr, "semctl failed with error: %d\n", errno);
}
/* Create shared memory for the variable interest rate */
shmid = shmget((key_t) ratesKey, sizeof(struct rates_t),0666 | IPC_CREAT);
if (shmid == -1){
fprintf(stderr, "shmget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Attach shared memory
rates = (struct rates_t*) shmat(shmid,(void*)0,0);
if (rates ==(void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
/* Create the semaphore for the logs text file */
logsemid = semget((key_t)logSemKey, 1, 0600 | IPC_CREAT);
if(logsemid < 0){
printf("Failed to create semaphore\n");
exit(-1);
}
//Initialize a semaphore for the logs
logssem.val = 1;
//set the value of the semaphore
if (semctl(logsemid, 0, SETVAL, logssem) < 0) {
fprintf(stderr, "semctl logs failed with error: %d\n", errno);
}
//Install signal
if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
//Running infinitely taking from inwards queue
while(running){
/* Receive next message (regardless of type) from message queue */
if (msgrcv(toDBqueue, (void *) &msgData, BUFSIZ, 0, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Add block to get which ATM sent this (return address)
//Get return address
returnAddress = msgData.msg_type;
/* If this is a balance message */
if (strcmp(msgData.msg_text, "BALANCE") == 0) {
struct account_t * account = getAccount(localStore, msgData.msg_type);
account = updateAccount(account);
char *balance = balanceToString(account->balance);
strcpy(msgData.msg_text, balance);
//Send Balance response on the outward queue
if (msgsnd(toATMqueue, (void *) &msgData, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
/* If there is a withdraw message */
else if(strncmp(msgData.msg_text,"WITHDRAW",8) == 0){
//Get float value from the inward message
float withdrawlAmount = atof(msgData.msg_text + 9);
//Find existing account
struct account_t* account = getAccount(localStore, returnAddress);
account = updateAccount(account);
//Check if the balance is insufficient
if(account->balance < withdrawlAmount){
//Send NSF message on the outward queue
strcpy(msgData.msg_text, "NSF");
if (msgsnd(toATMqueue, (void *) &msgData, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
/* There are sufficient funds, continue with withdraw */
else {
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requesting access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Decrement the counter to block access to the db*/
if(semop(semid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Open database files */
DBFile = fopen(DBFileStr, "r");
DBTemp = fopen(DBTempStr, "w");
//tracking variables
int totalAccounts = 0;
//Find the total number of lines that corresponds to the number of accounts in the db
//Increments if there is a new line
while((read = getline(&line, &len, DBFile)) != -1) {
totalAccounts++;
}
//Close and reopen to refresh file
fclose(DBFile);
DBFile = fopen(DBFileStr, "r");
//Iterate through the accounts in the text file
for(int i = 0; i< totalAccounts; i++) {
//read the line
getline(&line, &len, DBFile);
//Malloc and store account line read in
char *tempmessage = calloc(strlen(line), sizeof(char));
strcpy(tempmessage, line);
//Edit balance if it is the correct account
if (strncmp(tempmessage, account->accountNumber, 5) == 0) {
account->balance = account->balance - withdrawlAmount;
fprintf(DBTemp, "%s", accountToString(account));
if (i != totalAccounts) {
fprintf(DBTemp, "\n");
}
} else {
fprintf(DBTemp, "%s", tempmessage);
}
//Free tempmessage in memory
free(tempmessage);
}
//Close files
fclose(DBFile);
fclose(DBTemp);
//Change the database temp to the db file
remove(DBFileStr);
rename(DBTempStr, DBFileStr);
/* Increment the counter unblock access to the db */
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Send the FUNDS_OK message back to ATM
strcpy(msgData.msg_text, "FUNDS_OK");
if (msgsnd(toATMqueue, (void *) &msgData, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
}
/* If there is a withdraw message */
else if(strncmp(msgData.msg_text,"DEPOSIT",7) == 0){
//Turn the inward message to float
float depositAmount = atof(msgData.msg_text + 8);
//Find the account in local store
struct account_t* account = getAccount(localStore, returnAddress);
account = updateAccount(account);
/* Edit DB to reflect deposit */
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requested access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Decrement the counter to block the access to the db
if(semop(semid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Open database files */
DBFile = fopen(DBFileStr, "r");
DBTemp = fopen(DBTempStr, "w");
//tracking variables
int totalAccounts = 0;
//Decrements if there is a new line
while((read = getline(&line, &len, DBFile)) != -1) {
totalAccounts++;
}
//Close and reopen to refresh file
fclose(DBFile);
DBFile = fopen(DBFileStr, "r");
//Increment through the accounts in the text file
for(int i = 0; i< totalAccounts; i++) {
//read the line
getline(&line, &len, DBFile);
//Malloc and store account line read in
char *tempmessage = calloc(strlen(line), sizeof(char));
strcpy(tempmessage, line);
//Edit balance if it is the correct account
if (strncmp(tempmessage, account->accountNumber, 5) == 0) {
account->balance = account->balance + depositAmount;
fprintf(DBTemp, "%s", accountToString(account));
if (i != totalAccounts) {
fprintf(DBTemp, "\n");
}
} else {
fprintf(DBTemp, "%s", tempmessage);
}
//Free tempmessage in memory
free(tempmessage);
}
//Close files
fclose(DBFile);
fclose(DBTemp);
//Change the database temp to the db file
remove(DBFileStr);
rename(DBTempStr, DBFileStr);
//Increment the counter to unblock access to the database
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Send the FUNDS_OK message back to ATM
strcpy(msgData.msg_text, "DEPOSIT_OK");
if (msgsnd(toATMqueue, (void *) &msgData, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
/* If there is an update from the DB Editor*/
else if(strncmp(msgData.msg_text, "DB_UPDATE",9) == 0){
printf("Message: %s\n", msgData.msg_text);
//create an accounts from the message
struct account_t* newAccount = createAccount(msgData.msg_text + 10);
//create a string representation of the account
char* newAccountStr = accountToString(newAccount);
free(newAccount);
printf("New line: %s\n", newAccountStr);
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requested access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Decrements counter and blocks the access to the db
if(semop(semid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Open database files */
DBFile = fopen(DBFileStr, "a");
//Append to the text file
fprintf(DBFile, "%s\n", newAccountStr);
printf("before\n");
free(newAccountStr);
printf("after\n");
//Close file
fclose(DBFile);
//Increments counter to unblock access to the db
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
}
/* Delete Node if the ATM Closes*/
else if(strncmp(msgData.msg_text, "X", 1) == 0){
//localStore = deleteNode(localStore, msgData.msg_type);
kill(pid_interest, SIGINT);
kill(pid_editor, SIGINT);
killATM(localStore);
deleteMsgQueue(toATMqueue);
deleteMsgQueue(toDBqueue);
if(shmdt(rates) == -1){
fprintf(stderr, "shdt fail\n");
exit(EXIT_FAILURE);
}
if(shmctl(shmid, IPC_RMID, 0) == -1) {
fprintf(stderr, "shmctl failed\n");
exit(EXIT_FAILURE);
}
exit(1);
}
/* Handle Loan Message */
else if(strncmp(msgData.msg_text, "LOAN",4) == 0){
//Get loan amount from message;
float loanAmount = atof(msgData.msg_text+5);
//Get account from local storage
struct account_t *account = getAccount(localStore, msgData.msg_type);
account = updateAccount(account);
//Calculate debt with interest
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requested access to Rates Shared Memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Gain lock of interest rates shm
if(semop(ratessemid, &p, 1) < 0)
{
perror("semop p failed \n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to Rates Shared Memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Edit the loan amount to add interest
loanAmount = loanAmount + (loanAmount * rates->negInterest);
account->balance = account->balance - loanAmount;
/* Edit DB to reflect loan */
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requested access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Decrement the counter to block the access to the db
if(semop(semid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Release Lock on the shared memory for the rates
if(semop(ratessemid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to Rates Shared Memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Open database files */
DBFile = fopen(DBFileStr, "r");
DBTemp = fopen(DBTempStr, "w");
//tracking variables
int totalAccounts = 0;
//Decrements if there is a new line
while((read = getline(&line,&len,DBFile)) != -1) {
totalAccounts++;
}
//Close and reopen to refresh file
fclose(DBFile);
DBFile = fopen(DBFileStr, "r");
//Increment through the accounts in the text file
for(int i = 0; i< totalAccounts; i++) {
//read the line
getline(&line, &len, DBFile);
//Malloc and store account line read in
char *tempmessage = calloc(strlen(line), sizeof(char));
strcpy(tempmessage, line);
//Edit balance if it is the correct account
if (strncmp(tempmessage, account->accountNumber, 5) == 0) {
fprintf(DBTemp, "%s", accountToString(account));
if (i != totalAccounts) {
fprintf(DBTemp, "\n");
}
} else {
fprintf(DBTemp, "%s", tempmessage);
}
//Free tempmessage in memory
free(tempmessage);
}
//Close files
fclose(DBFile);
fclose(DBTemp);
//Change the database temp to the db file
remove(DBFileStr);
rename(DBTempStr, DBFileStr);
//Increment the counter to unblock access to the database
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Send the FUNDS_OK message back to ATM
strcpy(msgData.msg_text, "LOAN_OK");
if (msgsnd(toATMqueue, (void *) &msgData, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
/* If there is a login message*/
else{
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Requested access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Decrement the counter to block access to the db
if(semop(semid, &p, 1) < 0)
{
perror("semop p failed \n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//create an account
struct account_t* acc = createLoginAccount(msgData.msg_text);
acc->returnAddress = returnAddress;
//Open the Database text file
DBFile = fopen("./DB.txt", "r+");
/*Check if account exists in database */
while ((read = getline(&line, &len, DBFile)) != -1) {
int size = strlen(line); //Get length of the line
//Create an account from the db
struct account_t* accLine = createAccountFromLine(line);
/* Check if this account number matches the one we're looking for */
if(strcmp(accLine->accountNumber, acc->accountNumber) == 0){
//If user provided pin matches database pin (with encryption)
accountFound = 1;
//decrypt the pins
int atmPin = atoi(acc->pin);
int dbPin = atoi(accLine->pin);
dbPin++;
if(atmPin == dbPin){
/* Send OK message back to ATM */
struct message_t okMessage;
strcpy(okMessage.msg_text, "OK\0");
okMessage.msg_type = acc->returnAddress;
//Send message to ATM through IPC message queue
if (msgsnd(toATMqueue, (void *) &okMessage, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//Create node in local store
acc->balance = accLine->balance;
strncpy(acc->pin, accLine->pin, 3);
localStore = addNode(localStore, acc);
} else{
acc->loginAttempts++; //Wrong attempt, increment login attempts!
/* Send fail message to ATM through IPC message queue */
struct message_t failMessage;
strcpy(failMessage.msg_text, "PIN_WRONG");
failMessage.msg_type = acc->returnAddress;
//Send message to ATM through IPC message queue
if (msgsnd(toATMqueue, (void *) &failMessage, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
/* If this is the 3rd wrong attempt, block the account */
if(acc->loginAttempts >= 3){
//Edit the db to put an x as the first character
//Open both original file and temp file
DBFile = fopen(DBFileStr, "r");
DBTemp = fopen(DBTempStr, "w");
/* Read file to determine total accounts (lines) in database */
int totalAccounts = 0;
while((read = getline(&line, &len, DBFile)) != -1) {
totalAccounts++;
}
/* Now update database by using temp file to reflect edits */
fclose(DBFile);
DBFile = fopen("./DB.txt", "r");
for (int i = 0; i < totalAccounts; i++) {
getline(&line, &len, DBFile);
char* tempMessage = calloc(strlen(line), sizeof(char));
strcpy(tempMessage, line);
if(strncmp(tempMessage, acc->accountNumber, 5) == 0){
strncpy(tempMessage, "X", 1);
}
fprintf(DBTemp, "%s", tempMessage);
free(tempMessage);
}
/* Close both database files after edit is done, move temp to DB */
fclose(DBFile);
fclose(DBTemp);
/* Change the database temp file to file */
remove("./DB.txt");
rename("./DB_temp.txt", "DB.txt");
}
}
}
deleteAccount(accLine);
}
//Increment counter / call signal
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "DB_SERVER: Released access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* If the user provided account was not found, send appropriate message back to ATM */
if(!accountFound){
/* Send account not found message to ATM through IPC message queue */
struct message_t failMessage;
strcpy(failMessage.msg_text, "ANF");
failMessage.msg_type = acc->returnAddress;
//Send message to ATM through IPC message queue
if (msgsnd(toATMqueue, (void *) &failMessage, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
}
accountFound = 0; //Reset flag
}
}
return 0;
}
void SIGINT_handler(int sig)
{
exit(1);
}
<file_sep>/interestCalculator.c
#include "shared.h"
void SIGINT_handler(int sig);
int main(){
/* File references */
FILE *DBFile;
FILE *DBTemp;
FILE *logFile;
char* DBFileStr = "./DB.txt";
char* DBTempStr = "./DB_temp.txt";
char* logStr = "./deadlockslog.txt";
size_t len;
char *line;
ssize_t read;
/* Semaphore Variables*/
int semid, ratesSemID, logsemid;
struct sembuf p = { 0, -1, SEM_UNDO};
struct sembuf v = { 0, +1, SEM_UNDO};
/* Shared Memory Variables */
int shmid;
/* MISC */
int running = 1;
pid_t pid;
//Get Semaphore for the shared memory in db.txt
semid = semget((key_t)dbSemKey, 1, 0600 | IPC_CREAT);
if ((semid < 0)) {
printf("Failed to create semaphore \n");
exit(-1);
}
//Get Semaphore for the share memory of the variable rates
ratesSemID = semget((key_t)ratesSemKey, 1, 0600 | IPC_CREAT);
if(ratesSemID < 0){
printf("Failed to create semaphore\n");
exit(-1);
}
//Create shared memory
shmid = shmget((key_t) ratesKey, sizeof(struct rates_t),0666 | IPC_CREAT);
if (shmid == -1){
fprintf(stderr, "shmget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Attach shared memory
struct rates_t *rates = (struct rates_t*) shmat(shmid,(void*)0,0);
if (rates == (void *)-1) {
fprintf(stderr, "shmat failed\n");
exit(EXIT_FAILURE);
}
//Install signal
if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
/* Create the semaphore for the logs text file */
logsemid = semget((key_t)logSemKey, 1, 0600 | IPC_CREAT);
if(logsemid < 0){
printf("Failed to get logs semaphore\n");
exit(-1);
}
while(running){
//Fork to create a timer that triggers every minute
pid = fork();
switch(pid) {
/* If there is an error exit*/
case -1:
printf("Fork Failed\n");
exit(-1);
/* The child waits a minute then exits*/
case 0:
sleep(60);
exit(0);
/* Parent waits for child to exit then calculates interest */
default:
break;
}
//wait for the signal from the child
wait(0);
//Decrement the counter which will wait and lock access to the db
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Requesting access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
if(semop(semid, &p, 1) < 0) {
fprintf(stderr, "semop failed with error: %d\n", errno);
perror("semop p failed \n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Gained access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
sleep(30); //Sleep to increase the chances of deadlock
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Requesting access to rates shared memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Decrement the counter which will wait and lock the access to the variable rates
if(semop(ratesSemID, &p, 1) < 0) {
fprintf(stderr, "semop failed with error: %d\n", errno);
perror("semop p failed \n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Gained Access to rates shared memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
/* Open database files */
DBFile = fopen(DBFileStr, "r");
DBTemp = fopen(DBTempStr, "w");
//tracking variables
int totalAccounts = 0;
//Increments if there is a new line
while ((read = getline(&line, &len, DBFile)) != -1 ) {
totalAccounts++;
}
//Close and reopen to refresh file
fclose(DBFile);
DBFile = fopen(DBFileStr, "r");
for (int i = 0; i < totalAccounts; i++) {
//read the line
getline(&line, &len, DBFile);
//Malloc and store account line read in
char *tempstring = calloc(strlen(line), sizeof(char));
strcpy(tempstring, line);
struct account_t *account = createAccountFromLine(tempstring);
//Edit the account balance by adding or subtracting the interest
if (account->balance < 0) {
account->balance = account->balance - (account->balance * rates->negInterest);
} else {
account->balance = account->balance + (account->balance * rates->posInterest);
}
if (i != totalAccounts) {
fprintf(DBTemp, "%s\n", accountToString(account));
} else {
fprintf(DBTemp, "%s", accountToString(account));
}
deleteAccount(account);
}
//Close files
fclose(DBFile);
fclose(DBTemp);
//Change the database temp to the db file
remove(DBFileStr);
rename(DBTempStr, DBFileStr);
//Increment the counter to unlock the shared memory for the variable rates
if(semop(ratesSemID, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Releasing access to rates shared memory\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
//Increment the counter to unlock the shared memory db.txt
if(semop(semid, &v, 1) < 0)
{
perror("semop v failed\n");
exit(-1);
}
//Log semaphore state in shared logs file
if(semop(logsemid, &p, 1) < 0)
{
perror("semop p failed\n");
exit(-1);
}
logFile = fopen(logStr, "a");
fprintf(logFile, "INTERESTCALCULATOR: Releasing access to DB Text File\n");
fclose(logFile);
if(semop(logsemid, &v, 1) < 0)
{
perror("semop v failed \n");
exit(-1);
}
}
}
void SIGINT_handler(int sig)
{
exit(1);
}
<file_sep>/shared.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/sem.h>
#include <signal.h>
#include <math.h>
#if defined(__linux__)
#include <wait.h>
//Defines the union semun as required
union semun {
int val;
struct semid_ds* buf;
unsigned short *array;
};
#endif
struct message_t {
long int msg_type;
char msg_text[BUFSIZ];
};
struct account_t{
char* accountNumber;
char* pin;
float balance;
int returnAddress;
int loginAttempts;
struct account_t* next;
};
struct rates_t{
float posInterest;
float negInterest;
};
int toDB_key = 1234;
int toATM_key = 4321;
int dbSemKey = 1235;
int ratesKey = 1236;
int ratesSemKey = 1237;
int logSemKey = 1238;
/**
* Assumes message is in the format:
* [AccountNum][PIN][Balance]
* @param message
* @return
*/
struct account_t* createAccount(char* message){
struct account_t* acc = calloc(1,sizeof(struct account_t));
acc->accountNumber = (char *) calloc(5, sizeof(char));
acc->pin = (char *) calloc(3, sizeof(char));
strncpy(acc->accountNumber, message, 5);
strncpy(acc->pin, message+6, 3);
acc->balance = atof(message+10);
acc->returnAddress = -1;
acc->loginAttempts = 0;
acc->next = NULL;
return acc;
}
struct account_t* createLoginAccount(char*message){
struct account_t* acc = calloc(1,sizeof(struct account_t));
acc->accountNumber = calloc(5,sizeof(char));
acc->pin = calloc(3, sizeof(char));
strncpy(acc->accountNumber, message, 5);
strncpy(acc->pin, message + 6, 3);
return acc;
}
/**
* Assumes message is in the format:
* [AccountNum][PIN][Balance]
* @param message
* @return
*/
struct account_t* createAccountFromLine(char* message){
struct account_t* acc = calloc(1,sizeof(struct account_t));
acc->accountNumber = calloc(5,sizeof(char));
acc->pin = calloc(3,sizeof(char));
strncpy(acc->accountNumber, message, 5);
strncpy(acc->pin, message + 6, 3);
acc->balance = atof(message+10);
acc->returnAddress = -1;
acc->loginAttempts = 0;
return acc;
}
/**
* This function will deallocate memory associated with
* account
* @param acc
*/
void deleteAccount(struct account_t* acc){
free(acc->accountNumber);
free(acc->pin);
free(acc);
}
char * balanceToString(float balance){
int digits = floor (log10 (abs ((int)balance))) + 1;
char* str = calloc((digits + 3), sizeof(char));
sprintf (str, "%.2f", balance);
return str;
}
/**
* This function is used to convert the account struct to a string to be stored
* in the database and also for printing
* @param acc
* @return
*/
char * accountToString(struct account_t* acc){
char* balance = balanceToString(acc->balance);
char * accStr = calloc((strlen(acc->pin) + strlen(acc->accountNumber) + strlen(balance) + 2),sizeof(char));
strcat(accStr, acc->accountNumber);
strcat(accStr, ",");
strcat(accStr, acc->pin);
strcat(accStr, ",");
strcat(accStr, balance);
free(balance);
return accStr;
}
/**
* This function will free all the memory allocated by malloc
* for the node
* @param node The node to be deleted
*/
struct account_t * deleteNode(struct account_t* head, int returnAddress){
struct account_t *curr;
struct account_t *prev;
for(curr = head; curr != NULL; curr=curr->next){
if(curr->returnAddress == returnAddress){
/* If the node is the head */
if(curr == head){
head = curr->next;
break;
}
/* If the node in the middle */
else if(curr->next != NULL) {
prev->next = curr->next;
curr->next = NULL;
break;
}
/* If the node is at the end */
else {
prev->next = NULL;
curr->next = NULL;
break;
}
}
prev = curr;
}
deleteAccount(curr);
return head;
}
struct account_t * addNode(struct account_t *head, struct account_t* newNode){
newNode->next = head;
head = newNode;
return head;
}
struct account_t * getAccount(struct account_t *head, int returnAddress){
struct account_t *curr;
for(curr = head; curr != NULL; curr=curr->next){
if(curr->returnAddress == returnAddress){
return curr;
}
}
return NULL;
}
struct account_t* updateAccount(struct account_t *src){
struct account_t *temp;
char *line = NULL;
size_t len = 0;
ssize_t read;
FILE *DBFile;
DBFile = fopen("./DB.txt", "r");
/* Read file to determine total accounts (lines) in database */
int totalAccounts = 0;
char currChar;
currChar = getc(DBFile);
while((read = getline(&line, &len, DBFile)) != -1){
totalAccounts++;
}
/* Now update database by using temp file to reflect edits */
fclose(DBFile);
DBFile = fopen("./DB.txt", "r");
for (int i = 0; i < totalAccounts; i++) {
getline(&line, &len, DBFile);
char* tempMessage = calloc(strlen(line), sizeof(char));
strcpy(tempMessage, line);
temp = createAccountFromLine(tempMessage);
if(strncmp(temp->accountNumber, src->accountNumber, 5) == 0){
src->balance = temp->balance;
fclose(DBFile);
return src;
}
}
/* Close both database files after edit is done, move temp to DB */
fclose(DBFile);
return NULL;
}
void printAccounts(struct account_t *head){
if(head == NULL){
printf("List is empty\n");
}
for(struct account_t* curr = head; curr != NULL; curr = curr->next){
printf("Account Number: %s\n", head->accountNumber);
printf("Pin: %s\n", head->pin);
printf("Balance: %f\n", head->balance);
printf("Return Address: %d\n", head->returnAddress);
printf("Login Attempts: %d\n", head->loginAttempts);
}
}
void killATM(struct account_t* head){
for(struct account_t* curr = head; curr != NULL; curr = curr->next){
kill(curr->returnAddress, SIGINT);
}
}
void deleteMsgQueue(int msgid){
if(msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, "msgctl failed\n");
exit(EXIT_FAILURE);
}
}
<file_sep>/ATM.c
#include "shared.h"
void SIGINT_handler(int sig);
/*
* The atm component will run in an infinite loop until the user presses
* X.
*/
int main() {
/* Input variables*/
char accountNum[BUFSIZ];
char pin[BUFSIZ];
char buffer[BUFSIZ];
char amountWithdrawn[BUFSIZ];
char *concat;
size_t size;
/* Flags and Counters */
int loggedin = 0;
int loginAttempts = 0;
/* Message data */
struct message_t pin_data;
int messageType = getpid();
//Create toATM message queue
int toATMqueue = msgget((key_t) toATM_key, 0666 | IPC_CREAT);
if (toATMqueue == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Create toDB message queue
int toDBqueue = msgget((key_t) toDB_key, 0666 | IPC_CREAT);
if (toDBqueue == -1) {
fprintf(stderr, "msgget failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//Install signal
if (signal(SIGINT, SIGINT_handler) == SIG_ERR) {
printf("SIGINT install error\n");
exit(1);
}
//Start an infinte loop
while (1) {
while (!loggedin) {
//Poll for user input for account number
if(loginAttempts == 0) {
printf("Please Enter Account Number:");
fflush(stdin);
fgets(accountNum, BUFSIZ, stdin);
}
//Exit if the user chooses X
if(strncmp(accountNum, "X", 1) == 0){
strcpy(pin_data.msg_text, "X");
pin_data.msg_type = messageType;
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
break;
}
//Poll for user input for the pin number
printf("Please Enter Pin Number:");
fflush(stdin);
fgets(pin, BUFSIZ, stdin);
//Concatenate the two strings together to send message
if(loginAttempts == 0) {
accountNum[strcspn(accountNum, "\n")] = ',';
}
pin[strcspn(pin, "\n")] = '\0';
size = strlen(accountNum) + strlen(pin) + 2;
concat = (char *) malloc(sizeof(char) * size);
if (concat == NULL) {
exit(0);
}
strncpy(concat, accountNum, strlen(accountNum));
strncpy(concat + strlen(accountNum), pin, strlen(pin));
//Generate message for queue
pin_data.msg_type = messageType;
strcpy(pin_data.msg_text, concat);
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//Wait for a message back from the db server
if (msgrcv(toATMqueue, (void *) &pin_data, BUFSIZ, messageType, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
//move to next while loop if correct
if (strncmp(pin_data.msg_text, "OK\0", 3) == 0) {
loggedin = 1;
//do not increment if account was not found
} else if(strncmp(pin_data.msg_text, "ANF", 3) == 0) {
printf("Account was not found, try again.\n");
continue;
//increment the counter if the account was found but pin was wrong
}else {
loginAttempts++;
if(loginAttempts >= 3){
printf("Account is blocked\n");
loginAttempts = 0;
}
}
}
//Create a while loop for when the user is logged in
while (loggedin) {
//Create a menu option for user to select
printf("Press \"B\" for Balance or \"W\" for Withdrawals or \"D\" for Deposit \"L\" to apply for a loan \" or \"X\" to Quit:");
fflush(stdin);
fgets(buffer, BUFSIZ, stdin);
//Handle if the user chooses to view balance
if (strncmp(buffer, "B", 1) == 0) {
//Create a message for balance
pin_data.msg_type = messageType;
strcpy(pin_data.msg_text, "BALANCE\0");
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//listen for the message back with the balance
if (msgrcv(toATMqueue, (void *) &pin_data, BUFSIZ, messageType, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
printf("Current Balance is: %s\n", pin_data.msg_text);
}
//Handle if the user wants to withdraw
else if(strncmp(buffer, "W", 1) == 0){
//Create console ouotput for the menu option
printf("How much are you going to withdraw:");
fflush(stdin);
fgets(amountWithdrawn, BUFSIZ, stdin);
//Realloc so that the message can be concatenated to be sent off
size = strlen(amountWithdrawn) + strlen("WITHDRAW,") + 2;
concat = realloc(concat, size);
amountWithdrawn[strcspn(amountWithdrawn, "\n")] = '\0';
strcpy(concat, "WITHDRAW,");
strcat(concat, amountWithdrawn);
//Transfer the concatenated message into the message body
strcpy(pin_data.msg_text, concat);
pin_data.msg_type = messageType;
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//Wait for a response back for the Server
if (msgrcv(toATMqueue, (void *) &pin_data, BUFSIZ, messageType, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
if (strncmp(pin_data.msg_text, "NSF\0", 4) == 0) {
printf("There are not enough funds.\n");
} else {
printf("Money is being dispensed.\n");
}
}
else if(strncmp(buffer, "D", 1) == 0){
//Create console ouotput for the menu option
printf("How much are you going to deposit:");
fflush(stdin);
fgets(amountWithdrawn, BUFSIZ, stdin);
//Realloc so that the message can be concatenated to be sent off
size = strlen(amountWithdrawn) + strlen("DEPOSIT,") + 2;
concat = realloc(concat, size);
amountWithdrawn[strcspn(amountWithdrawn, "\n")] = '\0';
strcpy(concat, "DEPOSIT,");
strcat(concat, amountWithdrawn);
//Transfer the concatenated message into the message body
strcpy(pin_data.msg_text, concat);
pin_data.msg_type = messageType;
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//Wait for a response back for the Server
if (msgrcv(toATMqueue, (void *) &pin_data, BUFSIZ, messageType, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
if (strncmp(pin_data.msg_text, "DEPOSIT_OK", 10) == 0) {
printf("Funds have been deposited into your account!\n");
}
}
/* Handle Loan */
else if(strncmp(buffer, "L", 1) == 0){
//Create console ouotput for the menu option
printf("How much are you going to take out as a loan:");
fflush(stdin);
fgets(amountWithdrawn, BUFSIZ, stdin);
//Realloc so that the message can be concatenated to be sent off
size = strlen(amountWithdrawn) + strlen("LOAN,") + 2;
concat = realloc(concat, size);
amountWithdrawn[strcspn(amountWithdrawn, "\n")] = '\0';
strcpy(concat, "LOAN,");
strcat(concat, amountWithdrawn);
//Transfer the concatenated message into the message body
strcpy(pin_data.msg_text, concat);
pin_data.msg_type = messageType;
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
//Wait for a response back for the Server
if (msgrcv(toATMqueue, (void *) &pin_data, BUFSIZ, messageType, 0) == 0) {
fprintf(stderr, "msgrcv failed with error: %d\n", errno);
exit(EXIT_FAILURE);
}
if (strncmp(pin_data.msg_text, "LOAN_OK", 10) == 0) {
printf("Loan Granted!\n");
}
}
//Exit if the user chooses X
else if(strncmp(buffer, "X", 1) == 0){
strcpy(pin_data.msg_text, "X");
pin_data.msg_type = messageType;
if (msgsnd(toDBqueue, (void *) &pin_data, 500, 0) == -1) {
fprintf(stderr, "msgsnd failed\n");
exit(EXIT_FAILURE);
}
break;
}
}
return 0;
}
}
void SIGINT_handler(int sig)
{
exit(1);
}<file_sep>/README.txt
This system was not tested on linux lab machine. Built and tested on RPi and Ubuntu
System Summary
DB_Server
DB_Editor
ATM
interestCalculator
C Files:
-DB_Server.c
-DB_Editor.c
-ATM.c
-interestCalculator.c
Executable Files:
-DB_Server
-DB_Editor
-ATM
-interestCalculator
Misc. Files:
-DB.txt
-deadlocklogs.txt
NOTE: Ensure Executable file names match list above
SETUP
1) Convert makefile.txt to makefile
2) run make
START UP
1) Open a minimum of two terminal windows
2) Type the following in commmand line:
"./DB_Server"
This will start up the DB_Server, DB_Editor, and interestCalculator.
3) In a separate window, type the following to start the ATM:
"./ATM"
4) Repeat step 3 for the desired amount of ATM's
HOW TO LOGIN
1) Type 5 digit account number and press enter (i.e. 00117)
2) Type 3 digit account pin and press enter (i.e. 260)
3) If pin is wrong, enter new pin. If returned to the account number field, account doesn't exist
HOW TO GET ACCOUNT BALANCE
1) Once logged in type "B" and press enter (Menu entries are case sensitive)
2) Account Balance should be displayed on screen
HOW TO WITHDRAW MONEY
1) Once logged in type "W" and press enter (Menu entries are case sensitive)
2) Enter amount to withdraw
3) Money will either be withdrawn or NSF message will be displayed
HOW TO DEPOSIT MONEY
1) Once logged in type "D" and press enter (Menu entries are case sensitive)
2) Enter amount to deposit
3) Deposit message will be displayed on screen
HOW TO APPLY FOR A LOAN
1) Once logged in type "L" and press enter (Menu entries are case sensitive)
2) Enter amount of loan
3) Loan message will be displayed on screen
HOW TO ENTER NEW ACCOUNT INTO DATABASE
1) Navigate to the window that is running the DB_Server
2) Enter 5 digit account number (i.e. 12345)
3) Enter 3 digit account pin (i.e. 678)
4) Enter desired balance
5) The account should reflect in the database
HOW TO GENERATE DEADLOCK
1) Wait 60 seconds for the interestCalculator to obtain lock on the database text file
2) Within 30 seconds of step one, finish loan application at ATM
3) If steps 1 and 2 are done correctly, the DB_Server should be process the request during the 30 seconds
4) Deadlock creates, check logs.
| 04542b79cffbe1e1cc22bdf6c92fccac92ccb470 | [
"Text",
"C",
"Makefile"
] | 7 | Makefile | DavidCasc/4001_Final | ed242c3abeab8083441a8ca50fb233c094ff3656 | ae9594fc632a88497db33e5236b08d1457a09b33 |
refs/heads/main | <repo_name>apeso00/MazeGame<file_sep>/Assets/Scripts/CountdownController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CountdownController : MonoBehaviour
{
public int countdownTime;
GameObject gm;
Text countdownText;
// Start is called before the first frame update
void Start()
{
if(gm==null){
gm=GameObject.FindGameObjectWithTag("GameController");
}
countdownText=GetComponent<Text>();
StartCoroutine(CountdownToStart());
}
IEnumerator CountdownToStart(){
while(countdownTime>0){
countdownText.text=countdownTime.ToString();
yield return new WaitForSeconds(1);
countdownTime--;
}
countdownText.text="GO!";
yield return new WaitForSeconds(1f);
gm.GetComponent<GameManager>().BeginGame();
this.gameObject.SetActive(false);
}
}
<file_sep>/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour
{
// Start is called before the first frame update
int score;
public GameObject mainCanvas;
public GameObject player;
public GameObject gameOverCanvas;
public Text scoreText;
public Text timeDisplay;
public float totalTime;
enum GameStates {isPaused,Playing};
GameStates gameState= GameStates.isPaused;
static int overallScore;
static int currentLevel;
void Start()
{
if(currentLevel==0){
score=0;
}
else{
score=overallScore;
}
mainCanvas.SetActive(true);
gameOverCanvas.SetActive(false);
if(player==null){
player=GameObject.FindGameObjectWithTag("Player");
}
timeDisplay.gameObject.SetActive(false);
player.GetComponent<PlayerController>().FreezePlayer(true);
}
// Update is called once per frame
void Update()
{
switch(gameState){
case GameStates.isPaused:
break;
case GameStates.Playing:
totalTime-=Time.deltaTime;
timeDisplay.text=totalTime.ToString("0.0");
if(totalTime < 0){
totalTime=0;
mainCanvas.SetActive(false);
gameOverCanvas.SetActive(true);
player.GetComponent<PlayerController>().FreezePlayer(true);
}
break;
}
}
public void CollectCoin(int value){
score+=value;
scoreText.text=score.ToString();
}
public void BeginGame(){
timeDisplay.gameObject.SetActive(true);
player.GetComponent<PlayerController>().FreezePlayer(false);
gameState=GameStates.Playing;
}
private void OnTriggerEnter(Collider other){
if(other.gameObject.tag== "Player" && currentLevel<2){
currentLevel++;
overallScore=score;
SceneManager.LoadScene(currentLevel);
}
}
}
| 5e1b633763283bc0126c0889bba207821ee414dc | [
"C#"
] | 2 | C# | apeso00/MazeGame | 1ba81421304a75aa9f86c859da15b527ffd182cf | 5a4095ae60b6215dd6b80eb72d00cfe80415a5b2 |
refs/heads/master | <file_sep>public class sum
{
public static void main(String[] args)
{
int a,b, c;
a=10;
b=20;
c=20;
c=a+b+c;
System.out.println("Sum of 3 numbers: "+c);
}
}
<file_sep>class {
[B[A[B[A[A[A[A[A[B[A[B[A[B[A[B[A[B[B[B[C[C[C[C[C sum {[D[D[D[C1[C
[A[Bpublic static void main(String args[]){
ss
asdga
sd
[A[B
vim sum.javai
exit
| 676b16825a51f88a131b7df5652314f0ab31c118 | [
"Java"
] | 2 | Java | SRIRAMBS1/Devprogram1 | 6561b9212d70889297ebac4c36a26e64f103a28e | de145ec37378bc7a197a43d78f497933b861a213 |
refs/heads/master | <file_sep>import React from 'react';
export const MovieDetails = (props) => {
if(!props) return null;
return(
<p>{props.show_title}</p>
)
}<file_sep>import React from 'react';
class MovieSelect extends React.Component {
constructor( props ) {
super( props )
this.state = {
selectedIndex: undefined
}
}
render() {
const options = this.props.movies.map(( movie, index ) =>{
return <option value={ index } key={ index }>{ movie.show_title }</option>
})
return(
<select required>
<option value="" selected> Select Movie</option>
{ options }
</select>
)
}
}
export default MovieSelect
<file_sep>var express = require('express');
var app = express();
var path = require('path');
app.get('/', function ( req, res ) {
res.sendFile(path.join(__dirname + '/client/build/index.html'))
})
app.use(express.static('client/build'));
var server = app.listen( 3003, function () {
console.log("server running on 3003");
});<file_sep>import React from 'react'
import ReactDOM from 'react-dom'
import Container from './containers/Container.jsx';
window.onload = function () {
ReactDOM.render(
<Container/>, document.getElementById('app')
)
} | a28706d898751220ab96f5a92f474f92faa117d3 | [
"JavaScript"
] | 4 | JavaScript | danie16arrido/tarantinopolis | 27c5f98ece79f9d2390b2a1a3800900be4296813 | d3e4ebf9946d2ebd0f5d73d81fe4b33de968f394 |
refs/heads/master | <file_sep>/*
Rikaisan-universal
Copyright (C) 2018 eyeS Code
http://code.google.com/p/rikaisan-universal
---
Originally based on Rikaikun
by Erek Speed
Copyright (C) 2010 Erek Speed
http://code.google.com/p/rikaikun/
---
Originally based on Rikaichan 1.07
by <NAME>
http://www.polarcloud.com/
---
Originally based on RikaiXUL 0.4 by <NAME>
http://www.rikai.com/
http://rikaixul.mozdev.org/
---
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
---
Please do not change or remove any of the copyrights or links to web pages
when modifying any of the files. - Jon
*/
chrome.browserAction.onClicked.addListener(rcxMain.inlineToggle);
chrome.tabs.onSelectionChanged.addListener(rcxMain.onTabSelect);
chrome.runtime.onMessage.addListener(
function(request, sender, response) {
switch(request.type) {
case 'enable?':
console.log('enable?');
rcxMain.onTabSelect(sender.tab.id);
break;
case 'xsearch':
console.log('xsearch');
var e = rcxMain.search(request.text, request.dictOption);
response(e);
break;
/* case 'nextDict':
console.log('nextDict');
rcxMain.nextDict();
break;*/
case 'resetDict':
console.log('resetDict');
rcxMain.resetDict();
break;
case 'translate':
console.log('translate');
var e = rcxMain.dict.translate(request.title);
response(e);
break;
case 'makehtml':
console.log('makehtml');
var html = rcxMain.dict.makeHtml(request.entry);
response(html);
break;
case 'switchOnlyReading':
console.log('switchOnlyReading');
if(rcxMain.config.onlyreading == 'true')
rcxMain.config.onlyreading = 'false';
else
rcxMain.config.onlyreading = 'true';
localStorage['onlyreading'] = rcxMain.config.onlyreading;
break;
case 'copyToClip':
console.log('copyToClip');
rcxMain.copyToClip(sender.tab, request.entry);
break;
default:
console.log(request);
}
});
if(initStorage("v0.8.92", true)) {
// v0.7
initStorage("popupcolor", "blue");
initStorage("highlight", true);
// v0.8
// No changes to options
// V0.8.5
initStorage("textboxhl", false);
// v0.8.6
initStorage("onlyreading", false);
// v0.8.8
if (localStorage['highlight'] == "yes")
localStorage['highlight'] = "true";
if (localStorage['highlight'] == "no")
localStorage['highlight'] = "false";
if (localStorage['textboxhl'] == "yes")
localStorage['textboxhl'] = "true";
if (localStorage['textboxhl'] == "no")
localStorage['textboxhl'] = "false";
if (localStorage['onlyreading'] == "yes")
localStorage['onlyreading'] = "true";
if (localStorage['onlyreading'] == "no")
localStorage['onlyreading'] = "false";
initStorage("copySeparator", "tab");
initStorage("maxClipCopyEntries", "7");
initStorage("lineEnding", "n");
initStorage("minihelp", "true");
initStorage("disablekeys", "false");
initStorage("kanjicomponents", "true");
for (i = 0; i*2 < rcxDict.prototype.numList.length; i++) {
initStorage(rcxDict.prototype.numList[i*2], "true")
}
// v0.8.92
initStorage("popupDelay", "150");
initStorage("showOnKey", "");
}
/**
* Initializes the localStorage for the given key.
* If the given key is already initialized, nothing happens.
*
* @author Teo (GD API Guru)
* @param key The key for which to initialize
* @param initialValue Initial value of localStorage on the given key
* @return true if a value is assigned or false if nothing happens
*/
function initStorage(key, initialValue) {
var currentValue = localStorage[key];
if (!currentValue) {
localStorage[key] = initialValue;
return true;
}
return false;
}
rcxMain.config = {};
rcxDict.prototype.language = localStorage[`language`];
rcxMain.config.css = localStorage["popupcolor"];
rcxMain.config.highlight = localStorage["highlight"];
rcxMain.config.textboxhl = localStorage["textboxhl"];
rcxMain.config.onlyreading = localStorage["onlyreading"];
rcxMain.config.copySeparator = localStorage["copySeparator"];
rcxMain.config.maxClipCopyEntries = localStorage["maxClipCopyEntries"];
rcxMain.config.lineEnding = localStorage["lineEnding"];
rcxMain.config.minihelp = localStorage["minihelp"];
rcxMain.config.popupDelay = parseInt(localStorage["popupDelay"]);
rcxMain.config.disablekeys = localStorage["disablekeys"];
rcxMain.config.showOnKey = localStorage["showOnKey"];
rcxMain.config.kanjicomponents = localStorage["kanjicomponents"];
rcxMain.config.kanjiinfo = new Array(rcxDict.prototype.numList.length/2);
for (i = 0; i*2 < rcxDict.prototype.numList.length; i++) {
rcxMain.config.kanjiinfo[i] = localStorage[rcxDict.prototype.numList[i*2]];
}
<file_sep>/*
Rikaisan-universal
Copyright (C) 2018 eyeS Code
http://code.google.com/p/rikaisan-universal
---
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
---
Please do not change or remove any of the copyrights or links to web pages
when modifying any of the files. - Jon
*/
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('language').addEventListener("change", lingua);
});
function lingua(){
var e = document.getElementById("language");
var itemSelecionado = e.options[e.selectedIndex].value;
if(itemSelecionado == '1'){
document.getElementById('ling').innerHTML='Selecione seu idioma:';
document.getElementById('language').options[0].innerHTML='Inglês';
document.getElementById('language').options[1].innerHTML='Português';
document.getElementById('language').options[2].innerHTML='Espanhol';
document.getElementById('popupcolor').options[0].innerHTML="Azul";
document.getElementById('popupcolor').options[1].innerHTML="Azul claro";
document.getElementById('popupcolor').options[2].innerHTML="Preto";
document.getElementById('popupcolor').options[3].innerHTML="Amarelo";
document.getElementById('general').innerHTML="Geral";
document.getElementById('popupclr').innerHTML="Cor do Popup";
document.getElementById('dpl').innerHTML="Localização Default do popup";
document.getElementById('popupLocation').options[1].innerHTML="Canto superior esquerdo";
document.getElementById('popupLocation').options[2].innerHTML="Canto inferior direito";
document.getElementById('rlt').innerHTML="Realçar Texto";
document.getElementById('rtb').innerHTML="Realce o texto dentro de caixas de texto";
document.getElementById('eds').innerHTML="Ocultar definições e mostrar apenas leitura";
document.getElementById('smh').innerHTML="Mostrar mini ajuda";
document.getElementById('spwd').innerHTML="Mostrar pop-up com atraso";
document.getElementById('milis').innerHTML="milissegundos";
document.getElementById('keybor').innerHTML="Teclado";
document.getElementById('mpo').innerHTML= "Mostrar pop-up apenas na tecla pressionada";
document.getElementById('nu').innerHTML="Não usado";
document.getElementById('kwp').innerHTML="Teclas quando o pop-up é visível";
document.getElementById('apl').innerHTML="Localização de popup alternativo";
document.getElementById('mpld').innerHTML="Mover o local do popup para baixo";
document.getElementById('ctc').innerHTML="Copiar para área de transferência";
document.getElementById('hsd').innerHTML="Ocultar / mostrar definições";
document.getElementById('sdd').innerHTML="Trocar dicionários";
document.getElementById('ppc').innerHTML="Caractere anterior";
document.getElementById('ncc').innerHTML="Próximo caractere";
document.getElementById('nww').innerHTML="Próxima palavra";
document.getElementById('dtk').innerHTML="Desativar essas teclas";
document.getElementById('kdic').innerHTML="Dicionário de Kanji"
document.getElementById('dispi').innerHTML="Informação exibida:";
document.getElementById('kcc').innerHTML="Componentes Kanji";
document.getElementById('ctcc').innerHTML="Copiar para área de transferência";
document.getElementById('ledg').innerHTML="Final da linha:";
document.getElementById('fisp').innerHTML="Separador de campo:";
document.getElementById('copySeparator').options[1].innerHTML="Vírgula";
document.getElementById('copySeparator').options[2].innerHTML="Espaço";
document.getElementById('mee').innerHTML="Número máximo de entradas:";
document.getElementById('submit').value="Salvar";
}else if(itemSelecionado == '0'){
document.getElementById('ling').innerHTML='Select your language:';
document.getElementById('language').options[0].innerHTML='English';
document.getElementById('language').options[1].innerHTML='Portuguese';
document.getElementById('language').options[1].innerHTML='Spanish';
document.getElementById('popupcolor').options[0].innerHTML="Blue";
document.getElementById('popupcolor').options[1].innerHTML="Light Blue";
document.getElementById('popupcolor').options[2].innerHTML="Black";
document.getElementById('popupcolor').options[3].innerHTML="Yellow";
document.getElementById('general').innerHTML="General";
document.getElementById('popupclr').innerHTML="Popup color";
document.getElementById('dpl').innerHTML="Default popup location";
document.getElementById('popupLocation').options[1].innerHTML="Top Left";
document.getElementById('popupLocation').options[2].innerHTML="Bottom Right";
document.getElementById('rlt').innerHTML="Highlight text";
document.getElementById('rtb').innerHTML="Highlight text inside of text boxes";
document.getElementById('eds').innerHTML="Hide definitions and show only reading";
document.getElementById('smh').innerHTML="Show mini help";
document.getElementById('spwd').innerHTML="Show popup with delay";
document.getElementById('milis').innerHTML="milliseonds";
document.getElementById('keybor').innerHTML="Keyboard";
document.getElementById('mpo').innerHTML= "Show popup only on pressed key";
document.getElementById('nu').innerHTML="Not used";
document.getElementById('kwp').innerHTML="Keys when popup is visible";
document.getElementById('apl').innerHTML="Alternate popup location";
document.getElementById('mpld').innerHTML="Move popup location down";
document.getElementById('ctc').innerHTML="Copy to clipboard";
document.getElementById('hsd').innerHTML="Hide/show definitions";
document.getElementById('sdd').innerHTML="Switch dictionaries";
document.getElementById('ppc').innerHTML="Previous character";
document.getElementById('ncc').innerHTML="Next character";
document.getElementById('nww').innerHTML="Next word";
document.getElementById('dtk').innerHTML="Disable these keys";
document.getElementById('kdic').innerHTML="Kanji Dictionary"
document.getElementById('dispi').innerHTML="Displayed information:";
document.getElementById('kcc').innerHTML="Kanji Components";
document.getElementById('ctcc').innerHTML="Copy to Clipboard";
document.getElementById('ledg').innerHTML="Line ending:";
document.getElementById('fisp').innerHTML="Field separtor:";
document.getElementById('copySeparator').options[1].innerHTML="Common";
document.getElementById('copySeparator').options[2].innerHTML="Space";
document.getElementById('mee').innerHTML="Maximun entries:";
document.getElementById('submit').value="Save";
}else{
document.getElementById('ling'). innerHTML = 'Seleccione su idioma:';
document.getElementById('language').options[0].innerHTML ='Inglés';
document.getElementById('language').options[1].innerHTML ="Portuguesa";
document.getElementById('language').options[2].innerHTML = "Español";
document.getElementById('popupcolor').options[0].innerHTML ="Azul.";
document.getElementById('popupcolor').options[1].innerHTML = "Azul claro";
document.getElementById('popupcolor').options[2].innerHTML = "Negro";
document.getElementById('popupcolor').options[3].innerHTML = "Amarillo.";
document.getElementById('general').innerHTML = "General";
document.getElementById('popupclr').innerHTML = "Color del popup";
document.getElementById('dpl').innerHTML = "Ubicación predeterminada del popup";
document.getElementById('popupLocation').options[1].innerHTML = "Canto superior izquierdo";
document.getElementById('popupLocation'). options[2].innerHTML = "Canto inferior derecho";
document.getElementById('rlt').innerHTML = "Resaltar texto";
document.getElementById('rtb').innerHTML = "Resalte el texto dentro de los cuadros de texto";
document.getElementById('eds').innerHTML = "Ocultar definiciones y mostrar sólo lectura";
document.getElementById('smh').innerHTML = "Mostrar mini ayuda";
document.getElementById('spwd').innerHTML = "Mostrar pop-up con retraso";
document.getElementById('milis').innerHTML = "milisegundos";
document.getElementById('keybor').innerHTML = "teclado.";
document.getElementById('mpo').innerHTML = "Mostrar pop-up sólo en la tecla presionada";
document.getElementById('nu').innerHTML = "No utilizado";
document.getElementById('kwp').innerHTML = "Teclas cuando el pop-up es visible";
document.getElementById('apl').innerHTML = "Ubicación de popup alternativo";
document.getElementById('mpld').innerHTML = "Mover la ubicación del popup hacia abajo";
document.getElementById('ctc').innerHTML = "Copiar al portapapeles";
document.getElementById('hsd').innerHTML = "Ocultar / mostrar definiciones";
document.getElementById('sdd').innerHTML = "Cambiar diccionarios";
document.getElementById('ppc').innerHTML = "Carácter anterior";
document.getElementById('ncc').innerHTML = "Siguiente carácter";
document.getElementById('nww').innerHTML = "Siguiente palabra";
document.getElementById('dtk').innerHTML = "Desactivar estas teclas";
document.getElementById('kdic').innerHTML = "Diccionario de Kanji"
document.getElementById('dispi').innerHTML = "Información mostrada:";
document.getElementById('kcc').innerHTML = "Componentes Kanji";
document.getElementById('ctcc').innerHTML = "Copiar al portapapeles";
document.getElementById('ledg').innerHTML = "Final de línea:";
document.getElementById('fisp').innerHTML = "Separador de campo:";
document.getElementById('copySeparator').options[1].innerHTML = "coma.";
document.getElementById('copySeparator').options[2].innerHTML ="espacio";
document.getElementById('mee').innerHTML = "Número máximo de entradas:";
document.getElementById('submit').value = "Guardar";
}
} | 149c946f3472eaa21cc43bcd803faa577db31f50 | [
"JavaScript"
] | 2 | JavaScript | eyescoder/rikaisan-universal | 94fe05a378a2484cbe5cb65c84cd1ba489a5a875 | c4bf0a4af31fa72042254d772fcf1c9e2c73142c |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0003_auto_20160111_2342'),
]
operations = [
migrations.AddField(
model_name='list',
name='description',
field=models.CharField(default='', max_length=256),
preserve_default=False,
),
]
<file_sep>import request from 'reqwest';
import reqwest from 'reqwest'
import when from 'when';
import {JWT_REFRESH_URL, LOGIN_URL, PATIENT_SIGNUP_URL, PHYSICIAN_SIGNUP_URL} from '../constants/LoginConstants';
import LoginActions from '../actions/LoginActions';
import cookie from 'react-cookie';
class AuthService {
login(email, password) {
return this.handleAuth(when(request({
url: LOGIN_URL,
method: 'POST',
crossOrigin: true,
headers: {'X-CSRFToken': cookie.load('csrftoken')},
type: 'json',
data: {
email, password
}
})));
}
logout(path='/') {
LoginActions.logoutUser(path);
}
signup(data) {
return this.handleAuth(when(request({
url: data.role == 0 ? PATIENT_SIGNUP_URL : PHYSICIAN_SIGNUP_URL,
method: 'POST',
crossOrigin: true,
contentType: 'application/json',
headers: {'X-CSRFToken': cookie.load('csrftoken')},
type: 'json',
data: JSON.stringify(data)
})));
}
handleAuth(loginPromise) {
return loginPromise
.then(function(response) {
var jwt = response.token;
LoginActions.loginUser(jwt);
return true;
});
}
// Now, make the actual request
runRequest(refreshPromise, path, method, data) {
return refreshPromise
.then(function(response) {
var jwt = response.token;
LoginActions.updateToken(jwt);
return jwt;
}).catch(function(response) {return response;} ).then(
function(jwt) {
return reqwest({
url: path,
method: method,
crossOrigin: true,
contentType: 'application/json',
headers: {'Authorization' : 'JWT ' + jwt},
type: 'json',
data: JSON.stringify(data)}).then(function(response) { return response;} )
});
}
// First, refresh the JWT
makeAuthRequest(currentJWT, path, method, data) {
return this.runRequest(when(request({
url: JWT_REFRESH_URL,
method: 'POST',
crossOrigin: true,
contentType: 'application/json',
type: 'json',
data: '{"token":"' + currentJWT + '"}'
})), path, method, data);
}
}
export default new AuthService()
<file_sep>from rest_framework import serializers
from apiapp.models import MyUser, Candidate, List, CandidateDistinction
from django.core.exceptions import ValidationError
class UserSerializer(serializers.ModelSerializer):
user_uuid = serializers.UUIDField(read_only=True, source='uuid')
email_address = serializers.EmailField(source='email', write_only=True)
class Meta:
model = MyUser
fields = ('user_uuid', 'first_name', 'last_name', 'email_address',
'password')
extra_kwargs = {'password': {'write_only': True}}
def validate_email_address(self, value):
queryset = MyUser.objects.filter(email=value)
if queryset.exists():
raise ValidationError('This email address is already in use \
by another account.')
return value
class CandidateSerializer(serializers.ModelSerializer):
user = UserSerializer()
distinctions = serializers.SerializerMethodField()
class Meta:
model = Candidate
fields = ('user', 'score', 'current_company', 'current_title',
'distinctions')
def get_distinctions(self, obj):
distinction_data = []
for d in obj.distinctions.all():
x = {"text": d.text, "quantity":
CandidateDistinction.objects.get(
candidate=obj, distinction=d).quantity}
distinction_data.append(x)
return distinction_data
class ListSerializer(serializers.ModelSerializer):
title = serializers.CharField()
description = serializers.CharField()
class Meta:
model = List
fields = ('title', 'description')
<file_sep>dj-database-url==0.3.0
dj-static==0.0.6
Django==1.8.6
django-extensions==1.5.9
django-toolbelt==0.0.1
django-webpack-loader==0.2.2
djangorestframework==3.3.1
gunicorn==19.3.0
psycopg2==2.6.1
six==1.10.0
static3==0.6.1
<file_sep>import '!style!css!less!./Header.less';
import React from 'react';
import {Routehandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import RouterContainer from '../../services/RouterContainer'
export default class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
}
componentDidUpdate() {
}
render() {
return (
<div id="header-component" className="ui inverted menu">
<div className="ui container">
<a id="logo-text" href="/" className="header item">
LeaderRank
</a>
</div>
</div>
)
}
}
<file_sep>from django.views.generic import TemplateView
from django.conf import settings
from apiapp.models import Candidate, MyUser, List
from rest_framework.permissions import AllowAny
from rest_framework import viewsets, mixins
from rest_framework.response import Response
from apiapp.serializers import CandidateSerializer, ListSerializer
from django.shortcuts import get_object_or_404
from rest_framework.decorators import detail_route, list_route
import datetime
class NoDataView(TemplateView):
template_name = settings.DEFAULT_INDEX_PATH
class ListViewSet(viewsets.GenericViewSet):
serializer_class = ListSerializer
permission_classes = (AllowAny,)
model = List
@list_route()
def search(self, request, pk=None):
queryset = List.objects.all()
location = self.request.query_params.get('location', None)
list_name = self.request.query_params.get('list_name', None)
list = get_object_or_404(queryset, location=location, name=list_name)
serializer = ListSerializer(list)
return Response(serializer.data)
class CandidateViewSet(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin,
mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = CandidateSerializer
permission_classes = (AllowAny,)
model = Candidate
def get_queryset(self):
queryset = Candidate.objects.all().filter(
user__is_active=True, visible=True).order_by('score')
location = self.request.query_params.get('location', None)
if location is not None:
queryset = queryset.filter(list__location=location)
list_name = self.request.query_params.get('list_name', None)
if list_name is not None:
queryset = queryset.filter(list__name=list_name)
return queryset
# def list(self, request, *args, **kwargs):
# print(123)
# candidates = Candidate.objects.all().filter(
# user__is_active=True).filter(
# visible=True).order_by('rank')
# serializer = CandidateSerializer(candidates, many=True)
# return Response(serializer.data)
def retrieve(self, request, pk):
queryset = MyUser.objects.all()
user = get_object_or_404(queryset, pk=pk)
queryset = Candidate.objects.all()
candidate = get_object_or_404(queryset, user=user)
serializer = CandidateSerializer(candidate)
return Response(serializer.data)
@detail_route(methods=['get'])
def passwordviewseen(self, request, pk=None):
queryset = MyUser.objects.all()
user = get_object_or_404(queryset, pk=pk)
queryset = Candidate.objects.all()
candidate = get_object_or_404(queryset, user=user)
candidate.password_view_seen_timestamp = datetime.datetime.now()
candidate.save()
serializer = CandidateSerializer(candidate)
return Response(serializer.data)
@detail_route(methods=['get'])
def preclaimviewseen(self, request, pk=None):
queryset = MyUser.objects.all()
user = get_object_or_404(queryset, pk=pk)
queryset = Candidate.objects.all()
candidate = get_object_or_404(queryset, user=user)
candidate.preclaim_view_seen = datetime.datetime.now()
candidate.save()
serializer = CandidateSerializer(candidate)
return Response(serializer.data)
@detail_route(methods=['post'])
def password(self, request, pk=None):
queryset = MyUser.objects.all()
user = get_object_or_404(queryset, pk=pk)
user.set_password(request.data['password'])
user.save()
queryset = Candidate.objects.all()
candidate = get_object_or_404(queryset, user=user)
candidate.password_submitted_timestamp = datetime.datetime.now()
candidate.save()
serializer = CandidateSerializer(candidate)
return Response(serializer.data)
@detail_route(methods=['post'])
def accomplishments(self, request, pk=None):
queryset = MyUser.objects.all()
user = get_object_or_404(queryset, pk=pk)
queryset = Candidate.objects.all()
candidate = get_object_or_404(queryset, user=user)
candidate.accomplishments_submitted_timestamp = datetime.datetime.now()
candidate.status = request.data['status']
candidate.accomplishments = request.data['accomplishments']
candidate.save()
serializer = CandidateSerializer(candidate)
return Response(serializer.data)
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0010_auto_20160214_2151'),
]
operations = [
migrations.CreateModel(
name='CandidateDistinction',
fields=[
('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)),
('quantity', models.IntegerField()),
],
),
migrations.RemoveField(
model_name='candidate',
name='distinctions',
),
migrations.RemoveField(
model_name='distinction',
name='quantity',
),
migrations.AddField(
model_name='candidatedistinction',
name='candidate',
field=models.ForeignKey(to='apiapp.Candidate'),
),
migrations.AddField(
model_name='candidatedistinction',
name='distinction',
field=models.ForeignKey(to='apiapp.Distinction'),
),
]
<file_sep>from django.db import models
from django.contrib.auth.models import \
BaseUserManager, AbstractBaseUser, PermissionsMixin
import uuid
from json import JSONEncoder
from uuid import UUID
class MyUserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
if not email:
raise ValueError('Users must have an email address')
if not first_name:
raise ValueError('Users must have a first name')
if not last_name:
raise ValueError('Users must have a last name')
user = self.model(
email=self.normalize_email(email),
)
user.first_name = first_name
user.last_name = last_name
user.set_password(<PASSWORD>)
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name, last_name):
"""
Creates and saves a superuser with the given email,
password.
"""
user = self.create_user(email, password=<PASSWORD>,
first_name=first_name, last_name=last_name)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser, PermissionsMixin):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)
first_name = models.CharField(max_length=32)
last_name = models.CharField(max_length=32)
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = MyUserManager()
address = models.CharField(max_length=128, blank=True)
state = models.CharField(max_length=64, blank=True)
city = models.CharField(max_length=64, blank=True)
country = models.CharField(max_length=64, blank=True)
join_date = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
# The user is identified by their email address
return self.first_name + " " + self.last_name
def get_short_name(self):
# The user is identified by their email address
return self.first_name
def __str__(self): # __unicode__ on Python 2
return self.email
class List(models.Model):
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)
name = models.CharField(max_length=32)
title = models.CharField(max_length=256)
description = models.CharField(max_length=256)
location = models.CharField(max_length=32)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name + ' (' + self.location + ')'
class Distinction(models.Model):
list = models.ForeignKey(List)
text = models.CharField(max_length=320)
def __str__(self):
return self.text + ' (' + str(self.list) + ' )'
class Candidate(models.Model):
user = models.OneToOneField(MyUser, unique=True)
score = models.DecimalField(max_digits=10, decimal_places=7, null=True)
current_company = models.CharField(max_length=128, blank=True)
current_title = models.CharField(max_length=256, blank=True)
list = models.ForeignKey(List)
distinctions = models.ManyToManyField('Distinction',
through='CandidateDistinction')
linkedin_url = models.CharField(max_length=256, blank=True, null=True)
visible = models.BooleanField(default=True)
preclaim_view_seen = models.DateTimeField(blank=True, null=True)
password_view_seen_timestamp = models.DateTimeField(blank=True, null=True)
password_submitted_timestamp = models.DateTimeField(blank=True, null=True)
accomplishments_submitted_timestamp =\
models.DateTimeField(blank=True, null=True)
STATUS = (
('SL', 'Maybe'),
('JL', 'Yes'),
('NI', 'No')
)
status = models.CharField(max_length=2, choices=STATUS, blank=True)
accomplishments = models.TextField(blank=True, null=True)
class Meta:
ordering = ['score']
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name + ', ' \
+ self.current_company + ', ' + self.current_title
class CandidateDistinction(models.Model):
candidate = models.ForeignKey(Candidate)
distinction = models.ForeignKey(Distinction)
quantity = models.IntegerField()
JSONEncoder_olddefault = JSONEncoder.default
def JSONEncoder_newdefault(self, o):
if isinstance(o, UUID):
return str(o)
return JSONEncoder_olddefault(self, o)
JSONEncoder.default = JSONEncoder_newdefault
<file_sep>import '!style!css!less!./Home.less';
import {Routehandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import ReactMixin from 'react-mixin';
import React from 'react/addons';
import cookie from 'react-cookie';
import ContentEditable from "react-contenteditable";
import RouterContainer from '../../services/RouterContainer'
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
ga('send', 'pageview', '/');
RouterContainer.get().transitionTo('/newyork/email-marketers');
}
render() {
return (
<div>LeaderRank</div>
)
}
}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0011_auto_20160214_2205'),
]
operations = [
migrations.AddField(
model_name='candidate',
name='distinctions',
field=models.ManyToManyField(through='apiapp.CandidateDistinction', to='apiapp.Distinction'),
),
]
<file_sep>from django.conf.urls import include, url, patterns
from django.contrib import admin
from rest_framework.routers import SimpleRouter
from apiapp import views
router = SimpleRouter(trailing_slash=False)
router.register(r'candidates', views.CandidateViewSet, 'Candidate')
router.register(r'lists', views.ListViewSet, 'List')
urlpatterns = patterns(
'',
url(r'^', include(router.urls)),
url(r'^$', views.NoDataView.as_view()), # root
url(r'^admin/', include(admin.site.urls)),
url(r'^claim', views.NoDataView.as_view()),
url(r'^(?P<location>).+/(?P<list_name>.+)$', views.NoDataView.as_view()),
)
<file_sep>import '!style!css!less!./Footer.less';
import React from 'react';
import {Routehandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import RouterContainer from '../../services/RouterContainer'
export default class Footer extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
}
componentDidUpdate() {
}
render() {
return (
<div id="footer-component" className="ui inverted menu">
<div className="ui inverted vertical footer segment">
<div className="ui container">
<div className="ui stackable inverted grid">
<div className="five wide column">
</div>
<div className="three wide column">
<h4 className="ui inverted header">Company</h4>
<div className="ui inverted link list">
<a href="#" className="item">About us</a>
<a href="#" className="item">Team</a>
<a href="#" className="item">Media guide</a>
</div>
</div>
<div className="three wide column">
<h4 className="ui inverted header">Resources</h4>
<div className="ui inverted link list">
<a href="#" className="item">FAQ</a>
<a href="#" className="item">Contact us</a>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
<file_sep>import React from 'react';
import Router from 'react-router';
import {DefaultRoute, Route, RouteHandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import RouterContainer from './services/RouterContainer.js'
import LoginActions from './actions/LoginActions.js'
import LoginStore from './stores/LoginStore.js'
import AuthService from './services/AuthService'
import '!style!css!less!./index.less';
import List from './components/List/List';
import Claim from './components/Claim/Claim'
import Home from './components/Home/Home'
import Header from './components/Header/Header'
import Footer from './components/Footer/Footer'
export default class App extends React.Component {
constructor() {
super()
this.state = this._getLoginState();
}
_getLoginState() {
return {
userLoggedIn: LoginStore.isLoggedIn(),
user: LoginStore.isLoggedIn() == true ? LoginStore.user : '',
jwt: LoginStore.isLoggedIn() == true ? LoginStore.jwt : '',
};
}
// This means that when the loginstore emits an event,
// it will run the changelistener which is tied to onchange
// which runs setState thereby updating the component.
componentDidMount() {
if (typeof data !== "undefined")
{
this.setState({data: data});
}
this.changeListener = this._onChange.bind(this);
LoginStore.addChangeListener(this.changeListener);
}
_onChange() {
this.setState(this._getLoginState());
}
componentWillUnmount() {
LoginStore.removeChangeListener(this.changeListener);
}
// When this happens, the auth service calls the store. The store
// invalides the JWT and emits an event.
logout(e) {
e.preventDefault();
AuthService.logout();
}
render() {
return (
<div>
<RouteHandler
data={this.state.data}
userLoggedIn={this.state.userLoggedIn}
user={this.state.user}
logout={this.logout} />
</div>
)
}
}
export default class FullSizeContainer extends React.Component {
render() {
return (
<div>
<Header />
<div className="ui main container" id="full-size-container">
<RouteHandler/>
</div>
<Footer />
</div>
)
}
}
export default class PaddedContainer extends React.Component {
render() {
return (
<div id="padded-container">
<RouteHandler/>
</div>
)
}
}
var routes = (
<Route name="app" path="/" handler={App}>
<Route handler={FullSizeContainer}>
<Route name="claim" path="claim/:user_id" handler={Claim} />
<Route name="list" path=":location/:list_name" handler={List} />
<DefaultRoute handler={Home} name="home"/>
</Route>
</Route>
);
var router = Router.create({
routes: routes,
location: Router.HistoryLocation,
scrollBehavior: {
updateScrollPosition: function updateScrollPosition() {
var hash = window.location.hash;
if (hash) {
var element = document.querySelector(hash);
if (element) {
element.scrollIntoView();
}
} else {
window.scrollTo(0, 0);
}
}
}
});
RouterContainer.set(router);
router.run(function (Handler) {
React.render(<Handler data={$('script#app-data').text()}/>, document.getElementById('react-app'));
});
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0013_auto_20160214_2339'),
]
operations = [
migrations.AlterModelOptions(
name='candidate',
options={'ordering': ['score']},
),
migrations.AddField(
model_name='candidate',
name='score',
field=models.DecimalField(null=True, max_digits=10, decimal_places=7),
),
migrations.AlterUniqueTogether(
name='candidate',
unique_together=set([]),
),
migrations.RemoveField(
model_name='candidate',
name='rank',
),
]
<file_sep>export default {
LOGIN_URL: '/api-token-auth',
JWT_REFRESH_URL: '/api-token-refresh',
LOGIN_USER: 'LOGIN_USER',
LOGOUT_USER: 'LOGOUT_USER'
}
<file_sep>import '!style!css!less!./Claim.less';
import {Routehandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import ReactMixin from 'react-mixin';
import React from 'react/addons';
import cookie from 'react-cookie';
import ContentEditable from "react-contenteditable";
import RouterContainer from '../../services/RouterContainer'
export default class Claim extends React.Component {
constructor(props) {
super(props);
this.state = {
password: '',
candidate: null,
html: '<ul ref="aaa" tabIndex="1" contentEditable="true"><li></li></ul>',
accomplishments: null,
status: null
}
}
componentDidMount() {
$('.ui.form#password').form({
fields: {
password: {
identifier : 'password',
rules: [
{
type : 'empty',
prompt : 'Please enter your password'
},
{
type : 'length[6]',
prompt : 'Your password must be at least 6 characters'
}
]
}
},
inline: true,
onSuccess: this.handleValidForm.bind(this)
});
ga('send', 'pageview', this.props.params.user_id);
$.get('/candidates/' + this.props.params.user_id + '/passwordviewseen', function(result) {
this.setState({
candidate: result
});
}.bind(this));
$.get('/candidates/' + this.props.params.user_id, function(result) {
this.setState({
candidate: result
});
}.bind(this));
var secretLookingRadio = $(React.findDOMNode(this.refs.secretLookingRadio));
secretLookingRadio.checkbox('enable');
secretLookingRadio.checkbox('setting', 'onChange', this.handleSecretlyLooking.bind(this));
var justLookingRadio = $(React.findDOMNode(this.refs.justLookingRadio));
justLookingRadio.checkbox('enable');
justLookingRadio.checkbox('setting', 'onChecked', this.handleJustLooking.bind(this));
var notInterestedRadio = $(React.findDOMNode(this.refs.notInterestedRadio));
notInterestedRadio.checkbox('enable');
notInterestedRadio.checkbox('setting', 'onChecked', this.handleNotInterested.bind(this));
}
handleSecretlyLooking() {
$("#next-opportunity").show();
this.setState({status: 'SL'});
}
handleJustLooking() {
$("#next-opportunity").show();
this.setState({status: 'JL'});
}
handleNotInterested() {
$("#next-opportunity").hide();
this.setState({status: 'NI'});
}
submitAccomplishments() {
var accomplishmentsButton = $(React.findDOMNode(this.refs.accomplishmentsButton));
accomplishmentsButton.addClass("loading");
$.ajax({
url: "/candidates/" + this.props.params.user_id + "/accomplishments",
data: {"accomplishments": JSON.stringify(this.state.accomplishments), "status": this.state.status},
type: "POST",
headers: {'X-CSRFToken': cookie.load('csrftoken')},
success: function(data) {
RouterContainer.get().transitionTo('/');
}.bind(this)
});
}
handleValidForm(e) {
e.preventDefault();
var claimButton = $(React.findDOMNode(this.refs.claimButton));
claimButton.addClass("loading");
$.ajax({
url: "/candidates/" + this.props.params.user_id + "/password",
data: {"password": <PASSWORD>},
type: "POST",
headers: {'X-CSRFToken': cookie.load('csrftoken')},
success: function(data) {
var claimDiv = $(React.findDOMNode(this.refs.claimDiv));
claimDiv
.transition({
animation : 'fade right',
duration : 500,
onComplete : function() {
var accomplishmentsDiv = $(React.findDOMNode(this.refs.accomplishmentsDiv));
accomplishmentsDiv
.transition({
animation : 'fade left',
duration : 500,
onComplete : function() {
}
});
}.bind(this)
});
}.bind(this)
});
}
handleKeyDown(event) {
console.log(event.keyCode);
if (event.nativeEvent.keyCode == 8 || event.nativeEvent.keyCode == 13) {
if ($(event.target).find('li').first()[0].innerHTML === "<br>")
event.preventDefault();
if (event.nativeEvent.keyCode == 13) {
if ($(event.target).find('li').last()[0].innerHTML === "<br>")
event.preventDefault();
}
}
}
handleChange(event) {
var accomplishments = [];
for (var i=0; i<$(event.target).find('li').length; ++i) {
var element = $(event.target).find('li')[i];
if (element.innerText !== "\n")
accomplishments.push(element.innerText);
}
this.setState({accomplishments: accomplishments})
}
handleNextOpportunityChange(e) {
this.setState({accomplishments: e.target.value});
}
render() {
var formClasses = "ui large form" + (this.state.candidate == null ? " loading" : "");
var first_name = this.state.candidate == null ? "" : this.state.candidate.user.first_name;
var textareaStyle = {
outline: 0
};
return (
<div>
<div ref="claimDiv" id="claim-component">
<div className="ui center aligned grid">
<div className="column">
<form id="password" className={formClasses}>
<div className="ui stacked segment" >
<div className="ui huge header" >
<div id="claim-your" className="content">{first_name}, Claim your LeaderRank Profile!</div>
</div>
<div className="ui divider"></div>
<div className="ui left aligned tiny header" >
<div id="" className="content">Our goal is to promote top-performing professionals, like you, at the top of their game. Claim your profile to:</div>
<ul>
<li>Improve your rank by adding more information to your profile</li>
<li>Generate awareness of your rank with top companies</li>
<li>Get help from us during your next salary negotiation</li>
</ul>
</div>
<div className="field">
<div className="ui big left icon input" >
<i className="lock icon"></i>
<input type="password" valueLink={this.linkState('password')} name="password" placeholder="<PASSWORD> password"/>
</div>
</div>
<div className="ui fluid big green submit button" ref="claimButton">Claim</div>
</div>
</form>
</div>
</div>
</div>
<div ref="accomplishmentsDiv" className="hidden transition" id="accomplishments-component">
<div className="ui grid">
<div id="finish-profile" className="column">
<div className="ui stacked segment" >
<div className="ui center aligned huge header" >
<div className="content">Finish your profile</div>
</div>
<div className="ui divider"></div>
<div className="ui aligned form">
Are you interested in exploring job opportunities?
<br/>
<br/>
<div className="field">
<div ref="justLookingRadio" className="ui radio checkbox">
<input type="radio" name="frequency" checked={this.state.status == "JL" ? "checked" : ""}/>
<label>Yes, looking to switch jobs soon</label>
</div>
</div>
<div className="field">
<div ref="secretLookingRadio" className="ui radio checkbox">
<input type="radio" name="frequency" checked={this.state.status == "SL" ? "checked" : ""}/>
<label>Maybe, if the right one came along</label>
</div>
</div>
<div className="field">
<div ref="notInterestedRadio" className="ui radio checkbox">
<input type="radio" name="frequency" checked={this.state.status == "NI" ? "checked" : ""}/>
<label>Not at all</label>
</div>
</div>
<div id="next-opportunity" ref="next-opportunity">
<br/>
What are the most important things you're looking for in your next opportunity?
<br/>
<br/>
<div className="field">
<textarea rows="2" onChange={this.handleNextOpportunityChange.bind(this)}>{this.state.accomplishments}</textarea>
</div>
</div>
</div>
<br/>
<div className="ui fluid big green submit button" onClick={this.submitAccomplishments.bind(this)} ref="accomplishmentsButton">Update</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
ReactMixin(Claim.prototype, React.addons.LinkedStateMixin);
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0006_candidate_preclaim_view_seen'),
]
operations = [
migrations.AlterField(
model_name='candidate',
name='status',
field=models.CharField(max_length=2, blank=True, choices=[('SL', 'Maybe'), ('JL', 'Yes'), ('NI', 'No')]),
),
]
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='List',
fields=[
('uuid', models.UUIDField(serialize=False, primary_key=True, default=uuid.uuid4, editable=False)),
('name', models.CharField(max_length=32)),
('location', models.CharField(max_length=32)),
('created', models.DateTimeField(auto_now_add=True)),
],
),
migrations.AddField(
model_name='candidate',
name='list',
field=models.ForeignKey(to='apiapp.List', default=None),
preserve_default=False,
),
]
<file_sep>from rest_framework.views import exception_handler
def custom_exception_handler(exception, context):
response = exception_handler(exception, context)
return response
<file_sep>import '!style!css!less!./List.less';
import React from 'react';
import {Routehandler, Link} from 'react-router';
import Helmet from 'react-helmet';
import RouterContainer from '../../services/RouterContainer'
export default class List extends React.Component {
constructor(props) {
super(props);
this.state = {
candidates: null,
list_data: null
}
}
componentDidMount() {
$(React.findDOMNode(this.refs.listCategory)).dropdown({
onChange:function(value, text) {
// RouterContainer.get().transitionTo('/newyork/' + value);
window.location.href = '/newyork/' + value;
}
});
$(React.findDOMNode(this.refs.listCategory)).dropdown('set selected', this.props.params.list_name);
$(React.findDOMNode(this.refs.listLocation)).dropdown();
ga('send', 'pageview', this.props.params.listName);
$.get('/lists/search?location=' + this.props.params.location + "&list_name=" + this.props.params.list_name, function(result) {
this.setState({
list_data: result
});
}.bind(this));
var user_id = RouterContainer.get().getCurrentQuery().user_id
$.get('/candidates?location=' + this.props.params.location + "&list_name=" + this.props.params.list_name, function(result) {
this.setState({
candidates: this.processCandidates(result, user_id),
});
// Smooth scroll down
if (user_id != null) {
$('html, body').animate({
scrollTop: $("#" + user_id).offset().top
}, 2000);
$.get('/candidates/' + user_id + '/preclaimviewseen', function(result) {
}.bind(this));
}
}.bind(this));
$(React.findDOMNode(this.refs.methodologyModal)).modal({detachable: false});
}
componentDidUpdate() {
}
handleClaimClick(user_id, e) {
e.preventDefault();
RouterContainer.get().transitionTo('/claim/' + user_id);
}
// If the user_id is not null, show the button and
// deemphasize everything else
processCandidates(candidates_data, user_id) {
return (
candidates_data.map(function(s, i) {
var claim_button = null;
var blurred = "";
if (user_id != null) {
if (s.user.user_uuid == user_id)
claim_button = <a onClick={this.handleClaimClick.bind(this, user_id)} href="#" className="ui blue button large">Claim my profile</a>;
else
blurred = "blurred";
}
return [
<tbody>
<tr id={s.user.user_uuid} className={blurred}>
<td>
<h1 className="ui center aligned header">{s.score}</h1>
</td>
<td className="single line">
<h2 className="ui center aligned header">{s.user.first_name + " " + s.user.last_name}</h2>
</td>
<td className="center aligned">
{s.current_company}
</td>
<td className="center aligned">
{s.current_title}
</td>
<td className="center aligned">
{s.claim_button}
</td>
<td className="center aligned">
<a onClick={this.handleDetailsClick.bind(this)} href="#" className="ui button large">Details</a>
</td>
</tr>
<tr id={s.user.user_uuid} className={blurred}>
<td colspan="6">
<table>
dsfdsf
</table>
</td>
</tr>
</tbody>
]
}.bind(this)))
}
handleMethodologyClick(e) {
e.preventDefault();
$(React.findDOMNode(this.refs.methodologyModal)).modal('show');
}
handleDetailsClick(e) {
e.preventDefault();
}
render() {
var formClasses = "ui form" + (this.state.candidates == null || this.state.list_data == null ? " loading" : "");
return (
<form className={formClasses}>
<div id='list-component'>
<Helmet title="LeaderRank" />
<div className="ui vertical masthead center aligned ">
<div id="top-header" className="ui text container">
<h1 className="ui header center aligned ">
{this.state.list_data == null ? "" : this.state.list_data.title}
</h1>
<h2 className="ui header center aligned">
{this.state.list_data == null ? "" : this.state.list_data.description}
</h2>
</div>
<h4 className="ui header center aligned">
<a onClick={this.handleMethodologyClick.bind(this)} href="#" ref="methodology-link">Learn more about our ranking methodology</a>
</h4>
<div ref="methodologyModal" className="ui modal">
<i className="close icon"></i>
<div className="header">
Our methodology
</div>
<div className="content">
<div id="selling-points" className="ui relaxed center aligned grid">
<div className="four wide column">
<i className="huge checkmark icon"></i>
<div className="selling-point">
<h3>Top 3%</h3>
<h4>We've selected professionals who have succeeded in their jobs at the highest levels of performance.</h4>
</div>
</div>
<div className="four wide column">
<i className="huge filter icon"></i>
<div className="selling-point">
<h3>Multiple data sources</h3>
<h4>We go beyond the resume and evaluate the full picture. We look at success and quality of execution in each role, and how much the job function contributed to company success.</h4>
</div>
</div>
<div className="four wide column">
<i className="huge remove circle icon"></i>
<div className="selling-point">
<h3>Objective</h3>
<h4>We use criteria designed for each job role and standardized across list members. We rely heavily on verified third party data.</h4>
</div>
</div>
</div>
</div>
<div className="actions">
<div className="ui positive right button">
Close
</div>
</div>
</div>
</div>
<div id="list" className="ui container large form">
<div className="two fields">
<div className="two wide field">
<select ref="listCategory" id="category" className="ui dropdown">
<option value="email-marketers">Email marketers</option>
<option value="data-scientists">Data scientists</option>
</select>
</div>
<div id="list-location" className="one wide field">
<select ref="listLocation" className="ui dropdown">
<option selected value="new-york">New York</option>
</select>
</div>
</div>
<table id="list-table" className="ui large very padded table">
<thead>
<tr>
<th className="two wide center aligned">Rank</th>
<th className="three wide center aligned">Name</th>
<th className="four wide center aligned">Employer</th>
<th className="four wide center aligned">Title</th>
<th className="one wide center aligned"></th>
<th className="two wide center aligned"></th>
</tr>
</thead>
{this.state.candidates}
</table>
</div>
<br/>
<br/>
<br/>
<br/>
<div id="send-nom-div" className="ui center aligned grid">
<div className="eight wide column">
<div className="ui raised segment">
<p>Know someone who deserves to be on this list? <button id="send-nom-btn" className="ui blue small button">Send a nomination</button> </p>
</div>
</div>
</div>
<div id="methodology-div" className="ui center aligned grid">
<div className="eight wide column">
For more about our methodlogy, read here.
</div>
</div>
</div>
</form>
)
}
}
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apiapp', '0008_candidate_linkedin_url'),
]
operations = [
migrations.CreateModel(
name='Distinction',
fields=[
('id', models.AutoField(serialize=False, verbose_name='ID', auto_created=True, primary_key=True)),
('text', models.CharField(max_length=320)),
('quantity', models.IntegerField()),
('list', models.ForeignKey(to='apiapp.List')),
],
),
migrations.AddField(
model_name='candidate',
name='distinctions',
field=models.ManyToManyField(null=True, to='apiapp.Distinction', blank=True),
),
]
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='MyUser',
fields=[
('password', models.CharField(verbose_name='password', max_length=128)),
('last_login', models.DateTimeField(null=True, blank=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, verbose_name='superuser status', help_text='Designates that this user has all permissions without explicitly assigning them.')),
('uuid', models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4, serialize=False)),
('first_name', models.CharField(max_length=32)),
('last_name', models.CharField(max_length=32)),
('email', models.EmailField(unique=True, verbose_name='email address', max_length=255)),
('is_active', models.BooleanField(default=True)),
('is_admin', models.BooleanField(default=False)),
('is_staff', models.BooleanField(default=False)),
('address', models.CharField(blank=True, max_length=128)),
('state', models.CharField(blank=True, max_length=64)),
('city', models.CharField(blank=True, max_length=64)),
('country', models.CharField(blank=True, max_length=64)),
('join_date', models.DateTimeField(auto_now_add=True)),
('groups', models.ManyToManyField(blank=True, related_query_name='user', to='auth.Group', related_name='user_set', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, related_query_name='user', to='auth.Permission', related_name='user_set', help_text='Specific permissions for this user.', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Candidate',
fields=[
('id', models.AutoField(primary_key=True, auto_created=True, verbose_name='ID', serialize=False)),
('rank', models.IntegerField()),
('current_company', models.CharField(blank=True, max_length=128)),
('current_title', models.CharField(blank=True, max_length=256)),
('visible', models.BooleanField(default=True)),
('password_view_seen_timestamp', models.DateTimeField(null=True, blank=True)),
('password_submitted_timestamp', models.DateTimeField(null=True, blank=True)),
('accomplishments_submitted_timestamp', models.DateTimeField(null=True, blank=True)),
('status', models.CharField(blank=True, max_length=2, choices=[('SL', 'Secretly looking'), ('JL', 'Just looking')])),
('accomplishments', models.TextField(null=True, blank=True)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>from django.contrib import admin
from apiapp.models import MyUser, Candidate, List, Distinction, CandidateDistinction
class CandidateDistinctionInline(admin.TabularInline):
model = CandidateDistinction
extra = 3 # how many rows to show
class MyUserInline (admin.TabularInline):
model = Candidate
class CandidateAdmin(admin.ModelAdmin):
inlines = (CandidateDistinctionInline,)
list_display = admin.ModelAdmin.list_display + ("list", "score", "current_company", "current_title", "linkedin_url", "visible", "status", "accomplishments", "preclaim_view_seen", "password_view_seen_timestamp", "password_submitted_timestamp", "accomplishments_submitted_timestamp", )
list_editable = admin.ModelAdmin.list_editable + ("list", "score", "current_company", "current_title", "linkedin_url", "visible", "status", "accomplishments", "preclaim_view_seen", "password_view_seen_timestamp", "password_submitted_timestamp", "accomplishments_submitted_timestamp", )
class MyUserAdmin(admin.ModelAdmin):
inlines = (MyUserInline,)
admin.site.register(MyUser, MyUserAdmin)
admin.site.register(List)
admin.site.register(Distinction)
admin.site.register(Candidate, CandidateAdmin)
# Register your models here.
| 7dcd8de622405f81c97fdcab6b4c64e6194f137b | [
"JavaScript",
"Python",
"Text"
] | 23 | Python | dopeboy/leaderboard | 6430881177615925640eb25233083cee632226dd | 5182aa65543ea5fee4a2af5a19ca0560593ae77b |
refs/heads/master | <file_sep>package com.example.demo.config;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomFilter implements Filter {
private static Logger logger = LoggerFactory.getLogger(CustomFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
logger.info("Init");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
logger.info("Init");
chain.doFilter(request, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
logger.info("Init");
}
}
| 5e4d702e793ea97740bb5c04f673bd155b256f30 | [
"Java"
] | 1 | Java | zhangqianvvip/SpringSecurity-3 | f091763e5f0b7cf8a3d91958e59ab2a4b6269dcc | eb88475d202be9090a8f0398c44ae98eb86ec3b3 |
refs/heads/master | <repo_name>rossense/RossenseConstruction<file_sep>/subscription.class.php
<?php
/*
Rossense Construction - Subscription
Version : 1.0
Author : rossense
Email : <EMAIL>
Site : http://www.rossense.com/
GitHub : http://www.github.com/rossense/RossenseConstruction
License : MIT License
*/
/*
* DATABASE CONFIGURATION
*/
//Define Database Constants
//Server e.g 127.0.0.1 <localhost> or remote server's domain name or ip
define("DB_HOST","localhost");
//Database name on the host
define("DB_NAME","subscription");
//Database User
define("DB_USER","root");
//Defined User's Password
define("DB_PASS","");
/*Subscription Class*/
class Subscription{
private $db_host;
private $db_name;
private $db_user;
private $db_pass;
//Connection Link
private $connection;
//Result
private $result;
const ALREADY=2;
const SUCCESS=1;
const FAIL=0;
const INVALID_EMAIL=0;
public function __construct(){
$this->db_host=DB_HOST;
$this->db_name=DB_NAME;
$this->db_user=DB_USER;
$this->db_pass=DB_PASS;
//open connection
$this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
if (!$this->connection) {
die("Cannot connect to the database " . mysql_error());
}
//select db
mysql_select_db($this->db_name, $this->connection)||die("Database Not Found!");
//set character set of the connection
}
/**
* @param $query that will be executed
*/
private function execute($query) {
//execute the query
$this->result = mysql_query($query, $this->connection) ;
}
/**
* Subscribe
* @param $email subscriber's email
* @return int mysql_insert_id must be greater than 1
*/
public function subscribe($email){
//prevent sql injections
$email=addslashes(stripslashes($email));
$query="INSERT INTO email_list (id,email) VALUES(NULL,'$email')";
mysql_query($query, $this->connection);
return mysql_insert_id($this->connection);
}
/**
* Check email exists or not
* @param $email subscriber's email
* @return bool
* @throws Exception
*/
public function existEmail($email){
$query="SELECT * FROM email_list WHERE email='".$email."'";
$result = mysql_query($query, $this->connection);
if($result){
$record= mysql_fetch_assoc($result);
//fetch record from email_list
if(isset($record["email"]))return true;
else return false;
}
throw new Exception("Checking Email Exception");
}
/**
* Check the email address is valid or not
* @static
* @param $email subscriber's email address
* @return bool true if the email address is valid, otherwise false.
*/
static function isValidEmail($email){
if (preg_match("/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i", $email))
return true;
else return false;
}
}
| 7cd511fcb70bfe28123804acf95bad2d1e2211b3 | [
"PHP"
] | 1 | PHP | rossense/RossenseConstruction | 19b452459e9d81fdf961b7c47dcb09263c232a42 | 4161524a35cb35137b2055a5edbb2228f8ec2ed7 |
refs/heads/master | <repo_name>talonx/aws-rss-alerts<file_sep>/README.md
# aws-rss-alerts
Polls the RSS feeds from the AWS status page. The output can be piped to various alerting systems, which will be developed as plugins.
<file_sep>/awsfeedparser.py
import feedparser as fp
import argparse
import time
class AWSStatus(object):
OK = 0
WARNING = 1
CRITICAL = 2
def __init__(self):
self.states = {}
def add_status(self, reg, svc, state, details):
self.states.get(reg, {})[svc] = (state, details)
class AWSFeedParser(object):
# Not strictly AWS regions, yet, but more of geo-regions
REGIONS = ['us', 'ap', 'eu', 'sa']
STALE_THRESHOLD_SECONDS = 6 * 60 * 60 # 6 hours
INFORMATIONAL = 'Informational message: '
SERVICE_NORMAL = 'Service is operating normally: '
def __init__(self):
self.regs = {}
for r in self.REGIONS:
fname = r + '.txt'
with open(fname) as f:
lines = f.readlines()
self.regs[r] = lines
# print self.regs
def _log(self, mes):
print mes
# TODO replace this with a dict
def _wanted(self, svcs, line):
for svc in svcs:
if svc in line:
return True
return False
def parse(self, regions=[], svcs=[]):
for r in regions:
lines = self.regs[r]
filtered = [l for l in lines if self._wanted(regions, l)]
filtered = [l for l in lines if self._wanted(svcs, l)]
print filtered
for line in lines:
for svc in svcs:
if svc not in line:
continue
print "Getting feed for", line
feed = fp.parse(line)
if 'entries' not in feed:
self._log("Empty feed")
continue
entries = feed['entries']
if len(entries) == 0:
self._log("Empty feed")
continue
# published_parsed is in UTC
lastpubtime = time.mktime(entries[0]['published_parsed'])
curtime = time.mktime(time.gmtime())
diff = curtime - lastpubtime
if diff > self.STALE_THRESHOLD_SECONDS:
self._log("Old entries present")
continue
for entry in feed['entries']:
self._log(entry['title'])
pubtime = time.mktime(entry['published_parsed'])
curtime = time.mktime(time.gmtime())
self._log("Found something")
print "-----------------------"
def main():
parser = argparse.ArgumentParser(description='Process the region and service names')
parser.add_argument('--regions', help="comma separated list of region names - us, eu, ap, sa")
parser.add_argument('--services', help="comma separated list of service names - ec2, s3 etc")
args = parser.parse_args()
regs = args.regions.split(',')
svcs = args.services.split(',')
p = AWSFeedParser()
p.parse(regs, svcs)
if __name__ == '__main__':
main()
| 3bb104f9d941fe9d5f0c0a97ce2cceba3da8bec7 | [
"Markdown",
"Python"
] | 2 | Markdown | talonx/aws-rss-alerts | cad4f25317dbb6541fa2519485cd17a787d6d21c | 545b47c28aa843cb6400a0d75cbd07ee4bd558e4 |
refs/heads/master | <repo_name>liuchang001-abc/ssm<file_sep>/heima_ssm/heima_ssm_service/src/main/java/com/panku/ssm/service/IProductService.java
package com.panku.ssm.service;
import com.panku.ssm.domain.Product;
import java.util.List;
public interface IProductService {
/**
* 查询所有的产品
*
* @return
*/
public List<Product> findAll() throws Exception;
}
| 11049729af18449e3062185755123fe9cb5c895a | [
"Java"
] | 1 | Java | liuchang001-abc/ssm | b1075be1abf64995a3b54a1c0f1d78e68a8c73b5 | 7ea1b09af1c6e60be4c5e46908a0bced716146fd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.