branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>alfonsorognoni/test_jest<file_sep>/fizzBuzz.js
function fizzBuzz(start = 1, stop = 100)
{
let result = '';
if (stop < start || start < 0 || stop < 0) {
throw new Error('Invalid arguments');
}
for (let i = start; i <= stop; i++) {
if (i % 3 === 0 && i % 5 === 0) {
result += 'FizzBuzz';
continue;
}
if (i % 3 === 0) {
result += 'Fizz';
continue;
}
if (i % 5 === 0) {
result += 'Buzz';
continue;
}
result += i;
}
return result;
}
export default fizzBuzz;<file_sep>/README.md
# # JS Developer Coding Exemplar
## Test fizzBuzz function
In the project directory, run:
npm install
then to run test use:
npm run test
|
11aab707dcbf2f6c72d81ec259fe4fff69eab7b1
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
alfonsorognoni/test_jest
|
058bdf9404feb37ef8e6211452f5c1e99a3a2fdd
|
4db0949aafa0f0c7074a877c185470711c04c6cf
|
refs/heads/master
|
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Etat extends Model
{
public $timestamps = false;
protected $fillable = [
'idpartie', 'carteg1', 'carted1', 'carteg2', 'carted2', 'carteg3', 'carted3', 'carteg4', 'carted4', 'defausse',
'nbdefausse', 'nbpioche'
];
public static function creerEtatBidon($idpartie) {
Etat::create(['idpartie' => $idpartie, 'carteg1' => 1, 'carted1' => 8, 'carteg2' => -1, 'carted2' => -1, 'carteg3' => -1, 'carted3' => -1, 'carteg4' => -1, 'carted4' => -1, 'defausse' => 2,
'nbdefausse' => 1, 'nbpioche' => 13]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Partie;
class Tour extends Model {
public $timestamps = false;
protected $fillable = [
'idpartie', 'nbtour', 'idjoueur', 'typeaction', 'idvictime', 'typecarte'
];
public static function nouveauTour($idpartie) {
$tour=Tour::where('nbtour',\DB::table('tours')->max('nbtour'))->get()->first();
if ($tour) {
return $tour->nbtour+1;
} else {
return 1;
}
}
public static function quiPeutFaireQuoi($idpartie) {
$idpiocheur=self::quiPeutPiocher($idpartie);
if ($idpiocheur != -1) {
return "C'est au joueur ".$idpiocheur." de piocher";
}
$iddefausseur=self::quiPeutDefausser($idpartie);
if ($iddefausseur != -1) {
return "C'est au joueur ".$iddefausseur." de défausser";
}
}
//typeaction 1 piocher / 2 défausser
public static function quiPeutPiocher($idpartie) {
$partie=Partie::getPartie($idpartie);
$tour=Tour::where('nbtour',\DB::table('tours')->max('nbtour'))->get()->first();
if ($tour) {
if ($tour->idjoueur == $partie->idj1) {
if ($tour->typeaction == 2) {
return 2;
} else {
return -1;
}
} else {
if ($tour->typeaction == 2) {
return 1;
} else {
return -1;
}
}
} else {
return 1;
}
}
public static function quiPeutDefausser() {
$tour=Tour::where('nbtour',\DB::table('tours')->max('nbtour'))->get()->first();
if ($tour) {
if ($tour->idjoueur == 1) {
if ($tour->typeaction == 1) {
return 1;
} else {
return -1;
}
} else {
if ($tour->typeaction == 1) {
return 2;
} else {
return -1;
}
}
} else {
return -1;
}
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEtatsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('etats', function (Blueprint $table) {
$table->increments('id');
$table->integer('idpartie');
$table->integer('carteg1');
$table->integer('carted1');
$table->integer('carteg2');
$table->integer('carted2');
$table->integer('carteg3');
$table->integer('carted3');
$table->integer('carteg4');
$table->integer('carted4');
$table->integer('defausse');
$table->integer('nbdefausse');
$table->integer('nbpioche');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('etats');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Utilisateur;
use App\Etat;
use App\Main;
use App\Partie;
use App\Defausse;
use App\Pioche;
class ControlleurEtats extends Controller
{
public static function etatPartie($idpartie) {
$etat=array();
$etat['type']=1;
$partie=Partie::getPartie($idpartie);
$idj1=$partie->idj1;
$idj2=$partie->idj2;
$mainj1=Main::getMain($idpartie,$idj1);
$mainj2=Main::getMain($idpartie,$idj2);
$defausse=Defausse::cardOntTheTop($idpartie);
$nbpioche=Pioche::nbPioche($idpartie);
$nbdefausse=Defausse::nbDefausse($idpartie);
$etat['idpartie']=$idpartie;
if ($mainj1 && $mainj1->carteg != -1) {
$etat['carteg1']=9;
} else {
$etat['carteg1']=-1;
}
if ($mainj1 && $mainj1->carted != -1) {
$etat['carted1']=9;
} else {
$etat['carted1']=-1;
}
if ($mainj2 && $mainj2->carteg != -1) {
$etat['carteg2']=9;
} else {
$etat['carteg2']=-1;
}
if ($mainj2 && $mainj2->carted != -1) {
$etat['carted2']=9;
} else {
$etat['carted2']=-1;
}
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
$idutilisateur=$utilisateur->id;
if ($mainj1 && $mainj1->idjoueur == $idutilisateur) {
if ($etat['carteg1'] != -1) {
$etat['carteg1']=$mainj1->carteg;
}
if ($etat['carted1'] != -1) {
$etat['carted1']=$mainj1->carted;
}
} else if ($mainj2 && $mainj2->idjoueur == $idutilisateur) {
if ($etat['carteg2'] != -1) {
$etat['carteg2']=$mainj2->carteg;
}
if ($etat['carted2'] != -1) {
$etat['carted2']=$mainj2->carted;
}
}
}
$etat['carted3']=-1;
$etat['carteg3']=-1;
$etat['carted4']=-1;
$etat['carteg4']=-1;
$etat['defausse']=$defausse;
$etat['nbdefausse']=$nbdefausse;
$etat['nbpioche']=$nbpioche;
return $etat;
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Utilisateur extends Model
{
public $timestamps = false;
protected $attributes = array(
'idpartie' => -1
);
protected $fillable = [
'pseudo', 'token', 'idpartie',
];
public static function creerUtilisateur($pseudo) {
//String à hasher, il contient un sel, le temps actuel et un nombre aléatoire
$stringToHash="azez5f6ze5".time().rand();
$token=hash("sha256",$stringToHash);
setcookie('pseudo',$pseudo,0,'/');
setcookie('token',$token,0,'/');
Utilisateur::create(["pseudo" => $pseudo, 'token' => $token]);
}
public static function getUtilisateurFromPseudo($pseudo) {
return Utilisateur::where('pseudo', $pseudo)->get()->first();
}
public static function getUtilisateurFromPseudoToken($pseudo,$token) {
//TODO Ajouter un where pour le token
$utilisateur=Utilisateur::where('pseudo', $pseudo)->get()->first();
if ($utilisateur && ($utilisateur->token == $token)) {
return $utilisateur;
} else {
return false;
}
}
public static function detruireCookiesUtilisateur() {
setcookie("pseudo", "", time() - 3600,'/');
setcookie("token", "", time() - 3600,'/');
}
public function annulerPseudo() {
$this->delete();
}
public function aUnePartie() {
if ($this->idpartie == -1) {
return false;
} else {
return true;
}
}
public function assignerAUnePartie($idpartie) {
$this->idpartie=$idpartie;
$this->save();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Utilisateur;
class Welcome extends Controller
{
//Retourne la vue de l'accueil pour les nouveaux et les joueurs sans parties
//Sinon redirige le joueur vers sa partie
public static function welcome() {
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
if ($utilisateur) {
if ($utilisateur->aUnePartie()) {
header('Location: /partie/'.$utilisateur->idpartie.'/',true,302);
exit();
} else {
return view('welcome');
}
} else {
return view('welcome');
}
} else {
return view('welcome');
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Utilisateur;
class ValiderPseudo extends Controller
{
public function validerPseudo($pseudo) {
$reponse=array('type' => 1);
if (strlen($pseudo) < 4) {
$reponse['pseudoOk']=false;
$reponse['reason']='Le pseudo est inférieur à 4 caractères';
} else {
if (Utilisateur::getUtilisateurFromPseudo($pseudo)) {
$reponse['pseudoOk']=false;
$reponse['reason']='Quelqu\'un a déjà ce pseudo';
} else {
Utilisateur::creerUtilisateur($pseudo);
$reponse['pseudoOk']=true;
}
}
return $reponse;
}
public function annulerPseudo() {
$reponse=array('type' => 2);
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
if ($utilisateur) {
$utilisateur->annulerPseudo();
$reponse['annulerPseudoOk']=true;
} else {
$reponse['annulerPseudoOk']=false;
$reponse['reason']='Ce n\'est pas votre pseudo';
}
} else {
$reponse['annulerPseudoOk']=false;
$reponse['reason']='Vous n\'avez pas de pseudo ou vous n\'avez pas de jeton d\'authentification';
}
Utilisateur::detruireCookiesUtilisateur();
return $reponse;
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Pioche extends Model
{
public $timestamps = false;
protected $fillable = [
'idpartie', 'position', 'typecarte'
];
public static function initialiserPioche($idpartie) {
for ($i=1;$i<=5;$i++) {
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 1]);
}
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 2]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 2]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 3]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 3]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 4]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 4]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 5]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 5]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 6]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 7]);
Pioche::create(["idpartie" => $idpartie, "position" => 0, "typecarte" => 8]);
//Melange de la pioche
for($i=1;$i<=16;$i++){
$cartepioche=Pioche::where('idpartie', $idpartie)->where('position', 0)->get()->random();
$cartepioche->position=$i;
$cartepioche->save();
}
}
//Au début faire tirerCarte($id,-1)
public static function tirerCarte($idpartie,$idjoueur) {
$size=Pioche::where('idpartie',$idpartie)->get()->count();
if ($size > 0) {
$carte=Pioche::where('idpartie', $idpartie)->where('position', 1)->get()->first();
$typecarte=$carte->typecarte;
//Suppression de la carte de la Pioche
$carte->delete();
//Décalage de toutes les positions
$size=Pioche::where('idpartie',$idpartie)->get()->count();
for($i=0;$i<$size;$i++){
$carte=Pioche::where('idpartie',$idpartie)->get()[$i];
$carte->position=$carte->position-1;
$carte->save();
}
//Si l'idjoueur n'est pas spécifié la carte va directement dans la défausse
if ($idjoueur == -1) {
Defausse::defausserCarte($idpartie,$typecarte,-1);
} else {
//On ajoute la carte à la main du joueur
Main::tirerCarte($idpartie,$idjoueur,$typecarte);
}
}
}
public static function nbPioche($idpartie) {
return Pioche::where('idpartie',$idpartie)->get()->count();
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Main extends Model
{
public $timestamps = false;
protected $attributes = array(
'carteg' => -1, 'carted' => -1
);
protected $fillable = [
'idpartie', 'idjoueur', 'carteg', 'carted'
];
public static function getMain($idpartie, $idjoueur) {
return Main::where('idpartie',$idpartie)->where('idjoueur',$idjoueur)->get()->first();
}
public static function initialiserMains($idpartie,$nbjoueurs) {
$idj1=Partie::getPartie($idpartie)->idj1;
$idj2=Partie::getPartie($idpartie)->idj2;
Main::create(["idpartie" => $idpartie, "idjoueur" => $idj1]);
Main::create(["idpartie" => $idpartie, "idjoueur" => $idj2]);
if ($nbjoueurs >= 3) {
$idj3=Partie::getPartie($idpartie)->idj3;
Main::create(["idpartie" => $idpartie, "idjoueur" => $idj3]);
}
if ($nbjoueurs == 4) {
$idj4=Partie::getPartie($idpartie)->idj4;
Main::create(["idpartie" => $idpartie, "idjoueur" => $idj4]);
}
}
/*public static function getMain($idpartie, $idjoueur) {
return Main::where('idpartie',$idpartie)->where('idjoueur',$idjoueur)->get()->first();
}*/
public static function tirerCarte($idpartie,$idjoueur,$typecarte) {
$main=Main::where('idpartie',$idpartie)->where('idjoueur',$idjoueur)->get()->first();
if ($main->carteg == -1) {
$main->carteg=$typecarte;
$main->save();
} else if ($main->carted == -1) {
$main->carted=$typecarte;
$main->save();
}
}
public static function defausserCarte($idpartie,$idjoueur,$typecarte) {
$main=Main::where('idpartie',$idpartie)->where('idjoueur',$idjoueur)->get()->first();
if ($main->carteg == $typecarte) {
$main->carteg=$main->carted;
$main->carted=-1;
} else if ($main->carted == $typecarte) {
$main->carted=-1;
}
$main->save();
}
public function retournerCarte($idcarte) {
$idcarte=$idcarte%2;
if ($idcarte == 0) {
return $this->carteg;
} else {
return $this->carted;
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Utilisateur;
use App\Partie;
use App\Pioche;
use App\Main;
class ControlleurParties extends Controller {
public static function toutesLesParties() {
$reponse=array('type' => 3);
$parties=Partie::toutesLesParties();
$i=0;
foreach ($parties as $partie) {
$reponse[$i]=$partie;
$i=$i+1;
}
$reponse['taille']=$i;
return $reponse;
}
public function creerPartie($nbjoueurs) {
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
if ($utilisateur && !($utilisateur->aUnePartie())) {
$idpartie=Partie::creerPartie($pseudo,$nbjoueurs);
$utilisateur->assignerAUnePartie($idpartie);
header('Location: /partie/'.$idpartie.'/',true,302);
exit();
} else {
//Vous n'êtes plus connecté ou alors vous êtes déjà dans une partie
//Vue par defaut
return view('welcome');
}
} else {
//Vous n'êtes plus connecté
//Vue par défaut
return view('welcome');
}
}
public function rejoindrePartie($idpartie) {
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
if ($utilisateur && !($utilisateur->aUnePartie())) {
$partie=Partie::getPartie($idpartie);
if ($partie) {
$ok=$partie->rejoindrePartie($pseudo);
if ($ok) {
$utilisateur->assignerAUnePartie($idpartie);
if ($partie->isPartiePleine()) {
//A utiliser quand la partie est lancée
Pioche::initialiserPioche($partie->idpartie);
Main::initialiserMains($partie->idpartie,$partie->nbjoueurs);
Pioche::tirerCarte($idpartie,$partie->idj1);
Pioche::tirerCarte($idpartie,$utilisateur->id);
}
header('Location: /partie/'.$idpartie.'/',true,302);
exit();
} else {
//Vous ne pouvez pas rejoindre cette partie
//Vue partie
return view('welcome');
}
} else {
//La partie n'existe plus
//Vue partie
return view('welcome');
}
} else if ($utilisateur && ($utilisateur->idpartie == $idpartie)) {
header('Location: /partie/'.$idpartie.'/',true,302);
exit();
} else {
//Vous n'êtes pas connecté mais vous avez déjà une partie
//Vue par défaut
return view('welcome');
}
} else {
//Vous n'êtes pas connecté mais vous avez déjà une partie
//Vue par défaut
return view('welcome');
}
}
}
?>
<file_sep># love_letter
Modelisation of a basic card game<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Utilisateur;
use App\Pioche;
use App\Defausse;
use App\Tour;
use App\Partie;
use App\Main;
class ControlleurAction extends Controller {
public static function piocher($idpartie) {
$etat=array();
$etat['type']=2;
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
$partie=Partie::getPartie($idpartie);
if ($partie->idj1 == $utilisateur->id) {
if (Tour::quiPeutPiocher($idpartie) == 1) {
Pioche::tirerCarte($idpartie,$utilisateur->id);
Tour::create(['idpartie' => $idpartie, 'nbtour' => Tour::nouveauTour($idpartie), 'idjoueur' => $utilisateur->id, 'typeaction' => 1, 'idvictime' => -1, 'typecarte' => -1]);
} else {
$etat['text']=Tour::quiPeutFaireQuoi($idpartie);
}
} else if ($partie->idj2 == $utilisateur->id) {
if (Tour::quiPeutPiocher($idpartie) == 2) {
Pioche::tirerCarte($idpartie,$utilisateur->id);
Tour::create(['idpartie' => $idpartie, 'nbtour' => Tour::nouveauTour($idpartie), 'idjoueur' => $utilisateur->id, 'typeaction' => 1, 'idvictime' => -1, 'typecarte' => -1]);
} else {
$etat['text']=Tour::quiPeutFaireQuoi($idpartie);
}
}
} else {
$etat['text']="Vous n'êtes pas un joueur actif sur cette partie";
}
return $etat;
}
public static function defausser($idpartie, $idcarte) {
$etat=array();
$etat['type']=2;
if (isset($_COOKIE['pseudo']) && isset($_COOKIE['token'])) {
$pseudo=$_COOKIE['pseudo'];
$token=$_COOKIE['token'];
$utilisateur=Utilisateur::getUtilisateurFromPseudoToken($pseudo,$token);
$partie=Partie::getPartie($idpartie);
if ($partie->idj1 == $utilisateur->id) {
if (Tour::quiPeutDefausser($idpartie) == 1) {
if ($idcarte == 0 || $idcarte == 1) {
$main=Main::getMain($idpartie,$utilisateur->id);
$typecarte=$main->retournerCarte($idcarte);
Defausse::defausserCarte($idpartie,$typecarte,$utilisateur->id);
Tour::create(['idpartie' => $idpartie, 'nbtour' => Tour::nouveauTour($idpartie), 'idjoueur' => $utilisateur->id, 'typeaction' => 2, 'idvictime' => -1, 'typecarte' => -1]);
} else {
$etat['text']="Vous ne pouvez pas défausser les cartes d'un autre joueur";
}
} else {
$etat['text']=Tour::quiPeutFaireQuoi($idpartie);
}
} else if ($partie->idj2 == $utilisateur->id) {
if (Tour::quiPeutDefausser($idpartie) == 2) {
if ($idcarte == 2 || $idcarte == 3) {
$main=Main::getMain($idpartie,$utilisateur->id);
$typecarte=$main->retournerCarte($idcarte);
Defausse::defausserCarte($idpartie,$typecarte,$utilisateur->id);
Tour::create(['idpartie' => $idpartie, 'nbtour' => Tour::nouveauTour($idpartie), 'idjoueur' => $utilisateur->id, 'typeaction' => 2, 'idvictime' => -1, 'typecarte' => -1]);
} else {
$etat['text']="Vous ne pouvez pas défausser les cartes d'un autre joueur";
}
} else {
$etat['text']=Tour::quiPeutFaireQuoi($idpartie);
}
}
} else {
$etat['text']="Vous n'êtes pas un joueur actif sur cette partie";
}
return $etat;
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePartiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('parties', function (Blueprint $table) {
$table->increments('idpartie');
$table->string('nomj1');
$table->string('nomj2');
$table->string('nomj3');
$table->string('nomj4');
$table->integer('idj1');
$table->integer('idj2');
$table->integer('idj3');
$table->integer('idj4');
$table->integer('nbjoueurs');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('parties');
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDefaussesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('defausses', function (Blueprint $table) {
$table->increments('id');
$table->integer('idpartie');
$table->integer('position'); //1-16 (1 signifie haut de la défausse)
$table->integer('typecarte'); //1-8 le type de la carte défaussé
$table->integer('idjoueur'); //L'id du joueur qui a défaussé sa carte
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('defausses');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Defausse extends Model
{
public $timestamps = false;
protected $fillable = [
'idpartie', 'position', 'typecarte', 'idjoueur'
];
public static function defausserCarte($idpartie,$typecarte,$idjoueur) {
//Décalage de toutes les positions
$size=Defausse::where('idpartie',$idpartie)->get()->count();
for($i=0;$i<$size;$i++){
$carte=Defausse::where('idpartie',$idpartie)->get()[$i];
$carte->position=$carte->position+1;
$carte->save();
}
Defausse::create(['idpartie' => $idpartie, 'position' => 1, 'typecarte' => $typecarte, 'idjoueur' => $idjoueur]);
//Si l'idjoueur n'est pas spécifié la carte va directement dans la défausse
if ($idjoueur != -1) {
Main::defausserCarte($idpartie,$idjoueur,$typecarte);
Defausse::appliquerEffet($idpartie,$idjoueur,$typecarte);
}
}
public static function appliquerEffet($idpartie,$idjoueur,$typecarte) {
//Roi 6
if ($typecarte == 6) {
$partie=Partie::getPartie($idpartie);
$partie->echangerMain($partie->idj1,$partie->idj2);
}
}
public static function nbDefausse($idpartie) {
return Defausse::where('idpartie',$idpartie)->get()->count();
}
public static function cardOntTheTop($idpartie) {
if (Defausse::nbDefausse($idpartie) > 0) {
return Defausse::where('idpartie',$idpartie)->where('position',1)->get()->first()->typecarte;
} else {
return -1;
}
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
//Pour le 11 décembre
use Controllers\ValiderPseudo;
Route::get('/',"Welcome@welcome");
Route::get('/play', function () {
return view('play');
});
Route::get('/name/{pseudo}',"ValiderPseudo@validerPseudo");
Route::get('/cancelname/',"ValiderPseudo@annulerPseudo");
Route::get('/creerPartie/{nbjoueurs}',"ControlleurParties@creerPartie");
Route::get('/rejoindrePartie/{idpartie}',"ControlleurParties@rejoindrePartie");
//Utilisé par l'AJAX de welcome.js pour avoir périodiquement les parties
Route::get('/parties',"ControlleurParties@toutesLesParties");
Route::get('/partie/{idpartie}', function() {
return view('play');
});
Route::get('/partie/{idpartie}/update', 'ControlleurEtats@etatPartie');
Route::get('/partie/{idpartie}/action/piocher', 'ControlleurAction@piocher');
Route::get('/partie/{idpartie}/action/defausser/{idcarte}', 'ControlleurAction@defausser');
//Route::get('/update',)
//Ici une rediraction vers un controlleur qui renvoie un objet Etat (en json)
//avec un filtre des cartes selon le joueur
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Partie extends Model
{
public $timestamps = false;
protected $primaryKey = 'idpartie';
protected $attributes = array(
'nomj2' => '', 'nomj3' => '', 'nomj4' => '', 'idj2' => -1, 'idj3' => -1, 'idj4' => -1
);
protected $fillable = [
'idpartie', 'nomj1', 'nomj2', 'nomj3', 'nomj4', 'nbjoueurs', 'idj1', 'idj2', 'idj3', 'idj4'
];
//Dès qu'un utilisateur créé une partie, il la rejoint
public static function creerPartie($pseudo,$nbjoueurs) {
$idj1=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$partie=Partie::create(['nomj1' => $pseudo, 'nbjoueurs' => $nbjoueurs, 'idj1' => $idj1]);
$idpartie=$partie->idpartie;
return $idpartie;
}
public static function getPartie($idpartie) {
return Partie::where('idpartie', $idpartie)->get()->first();
}
public static function toutesLesParties() {
return Partie::all();
}
public function echangerMain($idj1,$idj2) {
$main1=Main::getMain($this->idpartie,$idj1);
$main2=Main::getMain($this->idpartie,$idj2);
$cartetemp=$main1->carteg;
$main1->carteg=$main2->carteg;
$main2->carteg=$cartetemp;
$cartetemp=$main1->carted;
$main1->carted=$main2->carted;
$main2->carted=$cartetemp;
$main1->save();
$main2->save();
}
public function isPartiePleine() {
if (($this->nbjoueurs == 2) && ($this->idj1 != -1) && ($this->idj2 != -1)) {
return true;
} else if (($this->nbjoueurs == 3) && ($this->idj1 != -1) && ($this->idj2 != -1) && ($this->idj3 != -1)) {
return true;
} else if (($this->nbjoueurs == 4) && ($this->idj1 != -1) && ($this->idj2 != -1) && ($this->idj3 != -1) && ($this->idj4 != -1)) {
return true;
}
}
public function rejoindrePartie($pseudo) {
//Un joueur ne pas rejoindre plusieurs fois une partie
if ($this->nomj1 == $pseudo || $this->nomj2 == $pseudo || $this->nomj3 == $pseudo || $this->nomj4 == $pseudo) {
return false;
}
if ($this->nbjoueurs == 2) {
if (empty($this->nomj2)) {
$this->nomj2=$pseudo;
$this->idj2=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
return false;
}
} else if ($this->nbjoueurs == 3) {
if (empty($this->nomj2)) {
$this->nomj2=$pseudo;
$this->idj2=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
if (empty($this->nomj3)) {
$this->nomj3=$pseudo;
$this->idj3=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
return false;
}
}
} else {
if (empty($this->nomj2)) {
$this->nomj2=$pseudo;
$this->idj2=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
if (empty($this->nomj3)) {
$this->nomj3=$pseudo;
$this->idj3=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
if (empty($this->nomj4)) {
$this->nomj4=$pseudo;
$this->idj4=Utilisateur::getUtilisateurFromPseudo($pseudo)->id;
$this->save();
return true;
} else {
return false;
}
}
}
}
}
}
|
19b7ea8fef6bc7eba036fe8f0c737c121f36ba43
|
[
"Markdown",
"PHP"
] | 17
|
PHP
|
Kleyment/love_letter
|
611c77760f7c5e51f2f688e0b8c87a7a63180faf
|
26e4a7a0eec0885587985121db789abc8004b7e6
|
refs/heads/master
|
<file_sep><?php
session_start();
include('controller/c_WorldHistory.php');
$c_worldHistory = new c_WorldHistory();
$content = $c_worldHistory->index();
$slide = $content['slide'];
$menu = $content['menu'];
$first_new = $content['first_new'];
$content = $c_worldHistory->CTGD_option();
$CTGD = $content['CTGD'];
if(isset($_POST['post'])){
$MaCTGD = $_POST['MaCTGD'];
$TieuDe = $_POST['title'];
$TomtatSK = $_POST['post_summary'];
$NoiDung = $_POST['post_content'];
$HinhSK = $_POST['image'];
$video = $_POST['video'];
$c_worldHistory->post($MaCTGD,$TieuDe,$TomtatSK,$NoiDung,$HinhSK,$video);
}
?>
<!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">
<meta name="keywords" content="footer, address, phone, icons" />
<title>World History - Detail Information</title>
<!-- CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="public/css/footer-distributed-with-address-and-phones.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="public/css/custom.css">
<link rel="stylesheet" href="public/css/detail-custom.css">
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse"
aria-expanded="false">
<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.php">
<img id="nav_logo" src="public/images/nav_logo.png" alt="nav_logo">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="index.php">Trang chủ</a></li>
<?php
$i=0;
foreach($menu as $m){
?>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"><?=$m->TenTL?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
$submenu = explode(',', $m->GiaiDoan);
foreach($submenu as $isubmenu){
list($ma,$ten,$tenkhongdau) = explode(':', $isubmenu);
?>
<li><a href="types.php?MaCTGD=<?=$first_new[$i]->MaCTGD?>"><?=$ten?></a></li>
<?php
$i++;
}
?>
</ul>
<?php
}
?>
</li>
<li><a href="index.php#contact-us">Liên hệ</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
<!-- Page Content -->
<div class="container">
<!-- slider -->
<div class="row carousel-holder">
<div class="col-md-2">
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading" style="font-size: 20px; font-weight: bold;">Thêm bài viết</div>
<div class="panel-body">
<form method="POST" action="#">
<div style="margin-bottom:15px;">
<label>Chọn mục bài viết thuộc:</label>
<select name="MaCTGD" class="form-control">
<?php
foreach($CTGD as $ctgd){
?>
<option value="<?=$ctgd->MaCTGD?>"><?=$ctgd->TenCTGD?></option>
<?php
}
?>
</select>
</div>
<div style="margin-bottom:15px;">
<label>Tiêu đề bài viết</label>
<input type="text" class="form-control" placeholder="Nhập tiêu đề bài viết" name="title" aria-describedby="basic-addon1"
>
</div>
<div style="margin-bottom:15px;">
<label>Tóm tắt:</label>
<textarea name="post_summary" id="post_summary" rows="10" cols="150"></textarea>
<script>
CKEDITOR.replace('post_summary');
</script>
</div>
<div style="margin-bottom:15px;">
<label>Nội dung:</label>
<textarea name="post_content" id="post_content" rows="10" cols="150"></textarea>
<script>
CKEDITOR.replace('post_content');
</script>
</div>
<div style="margin-bottom:15px;">
<label>Hình đại diện cho bài viết:</label>
<input type="text" class="form-control" placeholder="Nhập tiêu đề bài viết" name="image" aria-describedby="basic-addon1"
>
</div>
<div style="margin-bottom:15px;">
<label>Link video:</label>
<input type="text" class="form-control" placeholder="Nhập link video cho bài viết (nếu có)" name="video" aria-describedby="basic-addon1"
>
</div>
<button type="submit" id="post-button" name="post" class="btn btn-success">Đăng bài viết</button>
</form>
<?php
if(isset($_SESSION['post_error'])){
echo "<div class='alert alert-danger'>".($_SESSION['post_error'])."</div>";
}
if(isset($_SESSION['post_success'])){
echo "<div class='alert .alert-success'>".($_SESSION['post_success'])."</div>";
}
?>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
<!-- end slide -->
</div>
<!-- end Page Content -->
<!-- footer -->
<footer class="footer-distributed">
<div class="footer-left">
<img src="public/images/footer_logo.png" alt="">
<p class="footer-links">
<a href="#">Trang Chủ</a>
·
<?php
foreach($menu as $m){
?>
<a href="#"><?=$m->TenTL?></a>
·
<?php
}
?>
<a href="#">Liên hệ</a>
</p>
<p class="footer-company-name">Nhóm 18 © 2018</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<p><span>Khu phố 6, phường Linh Trung</span>Quận Th<NAME>, Tp.H<NAME></p>
</div>
<div>
<i class="fa fa-phone"></i>
<p>(08) 37251993</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
<div class="footer-right">
<p class="footer-company-about">
<span>Thông tin về nhóm:</span>
<p class="group-member">Nhóm bao gồm 5 thành viên:</p>
<p class="group-member">15520801: Dương Văn Thanh</p>
<p class="group-member">15520680: Phạm Ngọc Quân</p>
<p class="group-member">15520679: Nguyễn Trung Quân</p>
<p class="group-member">15520693: Trần Hưng Quang</p>
<p class="group-member">14520708: Lê Ngọc Hoàng Phước</p>
</p>
<div class="footer-icons">
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-github"></i></a>
</div>
</div>
</footer>
<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript" src="public/js/bootstrap.min.js"></script>
</body>
</html>
<file_sep>$(document).ready(function(){
$(document).scroll(function(){
//alert($(document).scrollTop());
if($(document).scrollTop()>0)
$('.navbar').addClass('navbar-scroll');
else
$('.navbar').removeClass('navbar-scroll');
});
});
<file_sep>
$(document).ready(function(){
$(".menu1").next('ul').toggle();
$(".menu1").click(function(event) {
$(this).next("ul").toggle(500);
});
$('#btnSearch').click(function(){
$('#txtSearch').fadeToggle();
});
$('#txtSearch').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
var keyword = $('#txtSearch').val();
$.post("search.php",{tukhoa:keyword},function(data){
$('#datasearch').html(data);
});
}
});
});<file_sep># World-History-Website
Website về lịch sử thế giới (Đồ án giữa kỳ môn Bảo trì phần mềm)
<file_sep><?php
session_start();
include('controller/c_WorldHistory.php');
$c_worldHistory = new c_WorldHistory();
$content = $c_worldHistory->index();
$slide = $content['slide'];
$menu = $content['menu'];
$first_new = $content['first_new'];
$doc = $content['doc'];
if(isset($_POST['Login'])){
$login_email = $_POST['login_email'];
$login_password = $_POST['login_password'];
$user = $c_worldHistory->login_account($login_email, md5($login_password));
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="footer, address, phone, icons" />
<title>World History</title>
<!-- CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="public/css/footer-distributed-with-address-and-phones.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="public/css/custom.css">
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse"
aria-expanded="false">
<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.php">
<img id="nav_logo" src="public/images/nav_logo.png" alt="nav_logo">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">Trang chủ</a></li>
<?php
$i=0;
foreach($menu as $m){
?>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"><?=$m->TenTL?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
$submenu = explode(',', $m->GiaiDoan);
foreach($submenu as $isubmenu){
list($ma,$ten,$tenkhongdau) = explode(':', $isubmenu);
?>
<li><a href="types.php?MaCTGD=<?=$first_new[$i]->MaCTGD?>"><?=$ten?></a></li>
<?php
$i++;
}
?>
</ul>
<?php
}
?>
</li>
<li><a href="#contact-us">Liên hệ</a></li>
<?php
if(isset($_SESSION['user_name'])){
?>
<li class="dropdown">
<a class="down-toggle" data-toggle="dropdown" href="#"><?=$_SESSION['user_name']?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
if($_SESSION['user_name']=="admin"){
?>
<li><a href="post.php">Đăng bài</a></li>
<?php
}
?>
<li><a href="logout.php">Đăng xuất</a></li>
</ul>
</li>
<?php
}else{
?>
<li class="dropdown">
<a class="dropdown-toggle glyphicon glyphicon-user" data-toggle="dropdown" href="#"><span class="caret"></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="btnLogin-Account">Đăng nhập</a></li>
<li><a href="signup.php">Đăng ký</a></li>
</ul>
</li>
<?php
}
?>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
<article>
<!-- carousel -->
<div id="carousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<?php
for($i=0; $i<count($slide); $i++){
if($i==0){
?>
<li data-target="#carousel" data-slide-to="<?=$i?>" class="active"></li>
<?php
}else{
?>
<li data-target="#carousel" data-slide-to="<?=$i?>"></li>
<?php
}
}
?>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
<?php
for($i=0; $i<count($slide); $i++){
if($i==0){
?>
<div class="item active">
<img src="public/images/slide/<?=$slide[$i]->hinh?>">
</div>
<?php
}
else{
?>
<div class="item">
<img src="public/images/slide/<?=$slide[$i]->hinh?>">
</div>
<?php
}
}
?>
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#carousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div id="content">
<div class="container-fluid">
<!-- Grid system -->
<?php
$tenTL='';
for($i=0; $i<count($doc); $i++){
if($tenTL!=$doc[$i]->TenTL){
if($i>0){
?>
</div>
<?php
}
$tenTL = $doc[$i]->TenTL;
?>
<div class="row">
<h3 class="item-type-title" id="<?=$doc[$i]->TenKhongDauTL?>"><?=$doc[$i]->TenTL?></h3>
<?php
}
?>
<div class="col-md-4 col-sm-6 col-xs-12">
<a href="types.php?MaCTGD=<?=$first_new[$i]->MaCTGD?>" class="thumbnail">
<i class="fa fa-plus"></i>
<?=$doc[$i]->TomtatGD?>
<div class="item-title"><?=$doc[$i]->TenGD?></div>
</a>
</div>
<?php
}
?>
</div>
<!--Contact us-->
<div class="row" id="contact-us">
<p id="contact-us-title">Liên hệ với chúng tôi</p>
<form action="#">
<div class="col-md-6">
<div class="form-col">
<label class="form-row">Họ và tên:</label>
<input class="form-row" type="text" name="contact_name">
</div>
<div class="form-col">
<label class="form-row">Địa chỉ email:</label>
<input class="form-row" type="text" name="contact_email">
</div>
<div class="form-col">
<label class="form-row">Nội dung:</label>
<textarea class="form-row" id="contact-us-content"></textarea>
</div>
<input class="form-col" type="button" name="submit" value="Gửi lời nhắn">
<blockquote>Xin chân thành cám ơn bạn đã đóng góp ý kiến!</blockquote>
</div>
<div class="col-md-6">
<blockquote>Chúng tôi cố gắng cung cấp những thông tin chính xác nhất đến với quý độc giả, trong quá trình hoạt động không tránh được sơ xuất, mọi thắc mắc đóng góp vui lòng hay gửi cho chúng tôi theo mẫu. Mọi ý kiến, đóng góp của bạn sẽ giúp cải thiện chất lượng của website. Chúc quý đọc giả có phút giây thư giản và những hiểu biết bổ ích!</br>Xin chân thành cám ơn!</blockquote>
<a href="#abc" class="thumbnail">
<img src="public/images/Lich-su-the-gioi-World-History.jpg" alt="">
</a>
</div>
</form>
</div>
</div>
</div>
</article>
<!-- footer -->
<footer class="footer-distributed">
<div class="footer-left">
<img src="public/images/footer_logo.png" alt="">
<p class="footer-links">
<a href="#">Trang Chủ</a>
·
<?php
foreach($menu as $m){
?>
<a href="#<?=$m->TenKhongDauTL?>"><?=$m->TenTL?></a>
·
<?php
}
?>
<a href="#">Liên hệ</a>
</p>
<p class="footer-company-name">Nhóm 18 © 2018</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<p><span>Khu phố 6, phường Linh Trung</span>Quận Thủ Đức, Tp.Hồ Chí Minh</p>
</div>
<div>
<i class="fa fa-phone"></i>
<p>(08) 37251993</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
<div class="footer-right">
<p class="footer-company-about">
<span>Thông tin về nhóm:</span>
<p class="group-member">Nhóm bao gồm 5 thành viên:</p>
<p class="group-member">15520801: <NAME></p>
<p class="group-member">15520680: <NAME></p>
<p class="group-member">15520679: <NAME></p>
<p class="group-member">15520693: <NAME></p>
<p class="group-member">14520708: <NAME> Hoàng Phước</p>
</p>
<div class="footer-icons">
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-github"></i></a>
</div>
</div>
</footer>
<div class="container-fluid">
<div id="modal-dialog">
<div class="modal-content col-md-6">
<div class="row">
<div class="close-modal glyphicon glyphicon-remove"></div>
<h3 class="modal-title">Đăng nhập</h3>
<a href="#row" class="thumbnail modal-image">
<img src="public/images/login.png"/>
</a>
<p class="item-info">Đọc giải vui lòng điền đầu đủ thông tin để đăng nhập tài khoản!</p>
<form method="POST" action="#">
<div class="form-col">
<label class="form-row">Tài khoản: </label>
<input class="form-row" type="text" name="login_email" placeholder="Nhập tên tài khoản">
</div>
<div class="form-col">
<label class="form-row">Mật khẩu: </label>
<input class="form-row" type="password" name="login_password" placeholder="<PASSWORD>">
</div>
<?php
if(isset($_SESSION['user_error'])){
?>
<script language="javascript">
alert("Sai thông tin đăng nhập");
</script>
<?php
unset($_SESSION['user_error']);
}
?>
<div class="form-row" id="sign-up">
<a herf="signup.php" id="signup-link" style="z-index: 10;">Quên mật khẩu</a>
</div>
<table id="login-button-component">
<tr>
<td><input type="submit" name="Login" value="Đăng nhập"></td>
<td><input id="btnCancel-Login" type="button" name="Cancel" value="Hủy"></td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript" src="public/js/bootstrap.min.js"></script>
<script language="javascript" src="public/js/custom.js"></script>
<script language="javascript" src="public/js/menu-follow.js"></script>
</body>
</html>
<file_sep><?php
include('controller/c_WorldHistory.php');
$c_worldHistory = new c_WorldHistory();
if(isset($_POST['tukhoa'])){
$key = $_POST['tukhoa'];
$content = $c_worldHistory->_search($key);
$types_content = $content['search_content'];
//$paginationHTML = $content['paginationHTML'];
}
?>
<div class="panel panel-default">
<div class="panel-heading">
<h4><b>Tìm thấy <?=count($types_content)?> bài viết với từ "<?=$key?>"</b></h4>
</div>
<?php
for($i=0; $i<count($types_content); $i++){
?>
<div class="row-item row new-item">
<div class="col-md-3">
<a href="detail.php?MaSK=<?=$types_content[$i]->MaSK?>">
<br>
<img width="200px" height="200px" class="img-responsive" src="<?=$types_content[$i]->HinhSK?>" alt="">
</a>
</div>
<div class="col-md-9">
<h3><?=$types_content[$i]->TieuDe?></h3>
<p><?=$types_content[$i]->TomtatSK?></p>
<a class="btn btn-primary" href="detail.php?MaSK=<?=$types_content[$i]->MaSK?>">Xem chi tiết<span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
<div class="break"></div>
</div>
<?php
}
?>
<!-- Pagination -->
<!--<div class="row text-center">
<div class="col-lg-12">
<?=$paginationHTML?>
</div>
</div>-->
<!-- end Pagination -->
</div><file_sep><?php
session_start();
include('controller/c_WorldHistory.php');
$c_worldHistory = new c_WorldHistory();
$content = $c_worldHistory->detail();
$menu = $content['menu'];
$first_new = $content['first_new'];
$detail_content = $content['detail_content'];
$comment = $content['comment'];
$regar_info = $content['regar_info'];
$highlight_info = $content['highlight_info'];
if(isset($_POST['Login'])){
$login_email = $_POST['login_email'];
$login_password = $_POST['login_password'];
$user = $c_worldHistory->login_account($login_email, md5($login_password));
}
if(isset($_POST['binhluan'])){
if(isset($_SESSION['user_id'])){
$MaSK = $_POST['MaSK'];
$MaND = $_SESSION['user_id'];
$NoiDungBL = $_POST['NoiDungBL'];
$addcomment = $c_worldHistory->comment($MaSK,$MaND,$NoiDungBL);
}else{
$_SESSION['not_login_yet'] = "Vui lòng đăng nhập để thêm bình luận";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="footer, address, phone, icons" />
<title>World History - Detail Information</title>
<!-- CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="public/css/footer-distributed-with-address-and-phones.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="public/css/custom.css">
<link rel="stylesheet" href="public/css/detail-custom.css">
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed"
data-toggle="collapse" data-target="#navbar-collapse"
aria-expanded="false">
<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.php">
<img id="nav_logo" src="public/images/nav_logo.png" alt="nav_logo">
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="index.php">Trang chủ</a></li>
<?php
$i=0;
foreach($menu as $m){
?>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#"><?=$m->TenTL?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
$submenu = explode(',', $m->GiaiDoan);
foreach($submenu as $isubmenu){
list($ma,$ten,$tenkhongdau) = explode(':', $isubmenu);
?>
<li><a href="types.php?MaCTGD=<?=$first_new[$i]->MaCTGD?>"><?=$ten?></a></li>
<?php
$i++;
}
?>
</ul>
<?php
}
?>
</li>
<li><a href="index.php#contact-us">Liên hệ</a></li>
<?php
if(isset($_SESSION['user_name'])){
?>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><?=$_SESSION['user_name']?><span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<?php
if($_SESSION['user_name']=="admin"){
?>
<li><a href="post.php">Đăng bài</a></li>
<?php
}
?>
<li><a href="logout.php">Đăng xuất</a></li>
</ul>
</li>
<?php
}else{
?>
<li class="dropdown">
<a class="dropdown-toggle glyphicon glyphicon-user" data-toggle="dropdown" href="#"><span class="caret"></a>
<ul class="dropdown-menu" role="menu">
<li><a href="#" id="btnLogin-Account">Đăng nhập</a></li>
<li><a href="signup.php">Đăng ký</a></li>
</ul>
</li>
<?php
}
?>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
<!-- Page Content -->
<div class="container-fluid">
<div class="row">
<!-- Blog Post Content Column -->
<div class="col-md-9 content">
<div class="main-content">
<!-- Blog Post -->
<!-- Title -->
<h1><?=$detail_content->TieuDe?></h1>
<!-- Author -->
<p class="lead">
by <a href="#"><NAME></a>
</p>
<ol class="breadcrumb">
<li><a href="#"><?=$detail_content->TenTL?></a></li>
<li><a href="#"><?=$detail_content->TenGD?></a></li>
<li><a href="#"><?=$detail_content->TenCTGD?></a></li>
</ol>
<p class="view">Số lượt xem: <?=$detail_content->SoLuotXem?></p>
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#content">Nội dung</a></li>
<li><a data-toggle="tab" href="#video">Video</a></li>
</ul>
<div class="tab-content">
<div id="content" class="tab-pane fade in active">
<!-- Preview Image -->
<img class="img-responsive" style="margin: 0 auto" src="<?=$detail_content->HinhSK?>" alt="">
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span> Posted on <?=$detail_content->created_at?></p>
<!-- Post Content -->
<p class="lead">
<?=$detail_content->NoiDung?>
</p>
</div>
<div id="video" class="tab-pane fade">
<div class="img-responsive">
<?php
if($detail_content->Video!=NULL){
?>
<video src="<?=$detail_content->Video?>" controls="controls" style="width:100%; height: auto"></video>
<?php
}else{
?>
<blockquote>Hiện tại chưa cập nhật video ứng với nội dung này</blockquote>
<?php
}
?>
</div>
</div>
<hr>
<!-- Blog Comments -->
<!-- Comments Form -->
<div class="well" id="comment">
<h4>Viết bình luận ...<span class="glyphicon glyphicon-pencil"></span></h4>
<form role="form" method="post" action="#">
<input type="hidden" name="MaSK" value="<?=$detail_content->MaSK?>">
<div class="form-group">
<textarea class="form-control" rows="3" name="NoiDungBL"></textarea>
</div>
<input id="btnComment" type="submit" name="binhluan" value="Gửi bình luận">
<div class="clear"></div>
</form>
</div>
<!-- Posted Comments -->
<?php
if(isset($_SESSION['not_login_yet'])){
echo "<div class='alert alert-danger'>".$_SESSION['not_login_yet']."</div>";
}
?>
<!-- Comment -->
<?php
foreach($comment as $cm){
?>
<div class="media">
<a class="pull-left" href="#">
<img class="media-object" src="public/images/men_user.png" alt="">
</a>
<div class="media-body">
<h4 class="media-heading">
<span style="font-weight: bold; font-size: 18px"><?=$cm->TenND?></span>
<span style="font-size: 10px"><?=$cm->created_at?></span>
</h4>
<p><?=$cm->NoiDungBL?></p>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
<!-- Blog Sidebar Widgets Column -->
<div class="col-md-3 aside-bar">
<div class="panel panel-default">
<div class="panel-heading"><b>Tin liên quan</b></div>
<div class="panel-body">
<!-- item -->
<?php
foreach($regar_info as $regar){
?>
<div class="row" style="margin-top: 10px; padding: 0 15px">
<div class="col-md-5">
<a href="detail.php?MaSK=<?=$regar->MaSK?>">
<img class="img-responsive" src="<?=$regar->HinhSK?>" alt="">
</a>
</div>
<div class="col-md-7">
<a href="detail.php?MaSK=<?=$regar->MaSK?>"><b><?=$regar->TieuDe?></b></a>
</div>
<!--<p><?=$hi->TomTatSK?></p>-->
<div class="break"></div>
</div>
<!-- end item -->
<?php
}
?>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading"><b>Tin nổi bật</b></div>
<div class="panel-body">
<!-- item -->
<?php
foreach($highlight_info as $hi){
?>
<div class="row" style="margin-top: 10px; padding: 0 15px">
<div class="col-md-5">
<a href="detail.php?MaSK=<?=$hi->MaSK?>">
<img class="img-responsive" src="<?=$hi->HinhSK?>" alt="">
</a>
</div>
<div class="col-md-7">
<a href="detail.php?MaSK=<?=$hi->MaSK?>"><b><?=$hi->TieuDe?></b></a>
</div>
<!--<p><?=$hi->TomTatSK?></p>-->
<div class="break"></div>
</div>
<!-- end item -->
<?php
}
?>
</div>
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- end Page Content -->
<!-- footer -->
<footer class="footer-distributed">
<div class="footer-left">
<img src="public/images/footer_logo.png" alt="">
<p class="footer-links">
<a href="#">Trang Chủ</a>
·
<?php
foreach($menu as $m){
?>
<a href="#"><?=$m->TenTL?></a>
·
<?php
}
?>
<a href="#">Liên hệ</a>
</p>
<p class="footer-company-name">Nhóm 18 © 2018</p>
</div>
<div class="footer-center">
<div>
<i class="fa fa-map-marker"></i>
<p><span>Khu phố 6, phường Linh Trung</span>Quận Thủ Đức, Tp.Hồ Chí Minh</p>
</div>
<div>
<i class="fa fa-phone"></i>
<p>(08) 37251993</p>
</div>
<div>
<i class="fa fa-envelope"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
<div class="footer-right">
<p class="footer-company-about">
<span>Thông tin về nhóm:</span>
<p class="group-member">Nhóm bao gồm 5 thành viên:</p>
<p class="group-member">15520801: Dương Văn Thanh</p>
<p class="group-member">15520680: Phạm Ngọc Quân</p>
<p class="group-member">15520679: Nguyễn Trung Quân</p>
<p class="group-member">15520693: Trần Hưng Quang</p>
<p class="group-member">14520708: L<NAME></p>
</p>
<div class="footer-icons">
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-linkedin"></i></a>
<a href="#"><i class="fa fa-github"></i></a>
</div>
</div>
</footer>
<div class="container-fluid">
<div id="modal-dialog">
<div class="modal-content col-md-6">
<div class="row">
<div class="close-modal glyphicon glyphicon-remove"></div>
<h3 class="modal-title">Đăng nhập</h3>
<a href="#row" class="thumbnail modal-image">
<img src="public/images/login.png"/>
</a>
<p class="item-info">Đọc giải vui lòng điền đầu đủ thông tin để đăng nhập tài khoản!</p>
<form method="POST" action="#">
<div class="form-col">
<label class="form-row">Tài khoản: </label>
<input class="form-row" type="text" name="login_email" placeholder="Nhập tên tài khoản">
</div>
<div class="form-col">
<label class="form-row">Mật khẩu: </label>
<input class="form-row" type="<PASSWORD>" name="login_password" placeholder="<PASSWORD>">
</div>
<?php
if(isset($_SESSION['user_error'])){
?>
<script language="javascript">
alert("Sai thông tin đăng nhập");
</script>
<?php
unset($_SESSION['user_error']);
}
?>
<div class="form-row" id="sign-up">
<a herf="signup.php">Quên mật khẩu</a>
</div>
<table id="login-button-component">
<tr>
<td><input type="submit" name="Login" value="Đăng nhập"></td>
<td><input id="btnCancel-Login" type="button" name="Cancel" value="Hủy"></td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
<!-- JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="public/js/bootstrap.min.js"></script>
<script language="javascript" src="public/js/custom.js"></script>
</body>
</html><file_sep><?php
session_start();
include("controller/c_WorldHistory.php");
$c_worldHistory = new c_WorldHistory();
$c_worldHistory->logout_account();
?><file_sep>$(document).ready(function(){
$('#btnLogin-Account').click(function(){
$('.modal-dialog').css('transform','translate(0,-25%)');
$('.modal-content').css('top',$(document).scrollTop()+70);
$('.modal-content').fadeIn();
});
$('.close-modal').click(function(){
$('.modal-content').fadeOut();
});
$('#btnCancel-Login').click(function(){
$('.modal-content').fadeOut();
});
});
<file_sep><?php
include('database.php');
class m_WorldHistory extends database{
function getSlide(){
$sql = "SELECT * FROM slide";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay gia tri cac the menu
function getMenu(){
$sql = "SELECT tl.TenTL, tl.TenKhongDauTL, GROUP_CONCAT(gd.MaGD,':', gd.TenGD,':', gd.TenKhongDauGD) AS GiaiDoan FROM theloai tl INNER JOIN giaidoan gd ON tl.MaTL = gd.MaTL GROUP BY tl.MaTL";
$this->setQuery($sql);
return $this->loadAllRows();
}
function getFirstNew(){
$sql = "SELECT gd.MaGD, ctgd.MaCTGD FROM giaidoan gd, chitietgiaidoan ctgd WHERE gd.MaGD = ctgd.MaGD GROUP BY gd.MaGD";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay thong tin tom tat cua tung giai doan
function getDoc(){
$sql = "SELECT tl.TenTL, tl.TenKhongDauTL, gd.TenGD, gd.TomtatGD FROM theloai tl INNER JOIN giaidoan gd ON tl.MaTL = gd.MaTL";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay menu aside trong trang types
function getTypesMenu(){
$sql="SELECT gd.TenGD, ctgd.MaCTGD, ctgd.TenCTGD FROM giaidoan gd, chitietgiaidoan ctgd WHERE gd.MaGD = ctgd.MaGD";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay toan bo cac mau tin trong chi tiet giai doan (CTGD)
function getTypesContent($_MaCTGD, $position=-1, $limitOfPage=-1){
$sql="SELECT ctgd.TenCTGD, sk.MaSK, sk.TieuDe, sk.HinhSK, sk.TomtatSK FROM chitietgiaidoan ctgd, sukien sk WHERE ctgd.MaCTGD = sk.MaCTGD AND ctgd.MaCTGD = $_MaCTGD";
if($position>-1 && $limitOfPage>1){
$sql .=" limit $position, $limitOfPage";
}
$this->setQuery($sql);
return $this->loadAllRows(array($_MaCTGD));
}
//Lay bai viet chi tiet
function getDetailContent($_MaSK){
$sql="SELECT tl.TenTL, gd.TenGD, ctgd.TenCTGD, sk.MaSK, sk.TieuDe, sk.HinhSK, sk.NoiDung, sk.SoLuotXem, sk.Video, sk.created_at FROM theloai tl, giaidoan gd, chitietgiaidoan ctgd, sukien sk WHERE tl.MaTL = gd.MaTL AND gd.MaGD = ctgd.MaGD AND ctgd.MaCTGD = sk.MaCTGD AND sk.MaSK=$_MaSK";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay binh luan cua bai viet
function getComment($_MaSK){
$sql="SELECT bl.NoiDungBL, bl.created_at, nd.TenND FROM sukien sk, binhluan bl, nguoidung nd WHERE sk.MaSK = bl.MaSK AND bl.MaND = nd.MaND AND sk.MaSK = $_MaSK";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay tin lien quan
function getRegarInfo($_MaSK){
$sql="SELECT sk.MaSK, sk.TieuDe, sk.HinhSK FROM sukien sk WHERE sk.MaCTGD = (SELECT sk1.MaCTGD FROM sukien sk1 WHERE sk1.MaSK = $_MaSK) AND sk.MaSK!=$_MaSK LIMIT 4";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Lay tin noi bat
function getHighlightInfo(){
$sql="SELECT sk.MaSK, sk.TieuDe, sk.HinhSK FROM sukien sk ORDER BY sk.SoLuotXem DESC limit 6";
$this->setQuery($sql);
return $this->loadAllRows();
}
//Them comment vao bai viet
function addComment($MaSK,$MaND,$NoiDungBL){
$sql="INSERT INTO binhluan(MaSK,MaND,NoiDungBL) VALUES(?,?,?)";
$this->setQuery($sql);
return $this->execute(array($MaSK,$MaND,$NoiDungBL));
}
//Them luot xem
function increaseView($_MaSK){
$sql="UPDATE sukien SET SoLuotXem = SoLuotXem+1 WHERE MaSK=?";
$this->setQuery($sql);
return $this->execute(array($_MaSK));
}
//search
function search($key){
$sql = "SELECT ctgd.TenCTGD, sk.MaSK, sk.TieuDe, sk.HinhSK, sk.TomtatSK FROM sukien sk, chitietgiaidoan ctgd WHERE sk.MaCTGD = ctgd.MaCTGD AND (sk.TieuDe like '%$key%' OR sk.TomtatSK like '%$key%')";
$this->setQuery($sql);
return $this->loadAllRows(array($key));
}
/*function search($key,$position=-1,$limitOfPage=-1){
$sql = "SELECT ctgd.TenCTGD, sk.MaSK, sk.TieuDe, sk.HinhSK, sk.TomtatSK FROM sukien sk, chitietgiaidoan ctgd WHERE sk.MaCTGD = ctgd.MaCTGD AND (sk.TieuDe like '%$key%' OR sk.TomtatSK like '%$key%')";
if($position>-1 && $limitOfPage>1){
$sql .=" limit $position, $limitOfPage";
}
$this->setQuery($sql);
return $this->loadAllRows(array($key));
}*/
function signup($TenND, $Email, $Password){
if($TenND==""||$Email==""||$Password=="")
return 0;
$sql = "INSERT INTO nguoidung(TenND,Email,Password) VALUES(?,?,?)";
$this->setQuery($sql);
$result = $this->execute(array($TenND, $Email, md5($Password)));
if($result){
return $this->getLastId();
}else{
return 0;
}
}
function login($Email, $md5_Password){
$sql = "SELECT * FROM nguoidung WHERE Email = '$Email' and Password = '$<PASSWORD>'";
$this->setQuery($sql);
return $this->loadRow(array($Email,$md5_Password));
}
function getCTGD(){
$sql = "SELECT MaCTGD, TenCTGD FROM chitietgiaidoan";
$this->setQuery($sql);
return $this->loadAllRows();
}
function addpost($MaCTGD,$TieuDe,$TomtatSK,$NoiDung,$HinhSK,$video){
$sql = "INSERT INTO sukien(MaCTGD,TieuDe,TomtatSK,NoiDung,HinhSK,video) VALUES(?,?,?,?,?,?)";
$this->setQuery($sql);
$result = $this->execute(array($MaCTGD,$TieuDe,$TomtatSK,$NoiDung,$HinhSK,$video));
if($result){
return $this->getLastId();
}else{
return 0;
}
}
}
?><file_sep><?php
include('model/m_WorldHistory.php');
include('model/pager.php');
class c_WorldHistory{
public function index(){
$m_worldHistory = new m_WorldHistory();
$slide = $m_worldHistory->getSlide();
$menu = $m_worldHistory->getMenu();
$first_new = $m_worldHistory->getFirstNew();
$doc = $m_worldHistory->getDoc();
return array('slide'=>$slide,'menu'=>$menu,'first_new'=>$first_new, 'doc'=>$doc);
}
public function types(){
$_MaCTGD = $_GET['MaCTGD'];
$m_worldHistory = new m_WorldHistory();
$menu = $m_worldHistory->getMenu();
$first_new = $m_worldHistory->getFirstNew();
$types_menu = $m_worldHistory->getTypesMenu();
$types_content = $m_worldHistory->getTypesContent($_MaCTGD);
//Phan cac trang con cho tung mau tin
$current_page = (isset($_GET['page']))?$_GET['page']:1;
$pagination = new pagination(count($types_content),$current_page, 3, 10);
$paginationHTML = $pagination->showPagination();
//Gioi han so trang
$limitOfPage = $pagination->get_nItemOnPage();
$position = ($current_page-1)*$limitOfPage;
$types_content = $m_worldHistory->getTypesContent($_MaCTGD, $position, $limitOfPage);
return array('menu'=>$menu, 'first_new'=>$first_new, 'types_menu'=>$types_menu, 'types_content'=>$types_content, 'paginationHTML'=>$paginationHTML);
}
public function detail(){
$_MaSK = $_GET['MaSK'];
$m_worldHistory = new m_WorldHistory();
$menu = $m_worldHistory->getMenu();
$first_new = $m_worldHistory->getFirstNew();
$detail_content = $m_worldHistory->getDetailContent($_MaSK);
$comment = $m_worldHistory->getComment($_MaSK);
$regar_info = $m_worldHistory->getRegarInfo($_MaSK);
$highlight_info = $m_worldHistory->getHighlightInfo();
$m_worldHistory->increaseView($_MaSK);
return array('menu'=>$menu, 'first_new'=>$first_new, 'detail_content'=>$detail_content[0], 'comment'=>$comment, 'regar_info'=>$regar_info, 'highlight_info'=>$highlight_info);
}
public function comment($MaSK,$MaND,$NoiDungBL){
$m_worldHistory = new m_WorldHistory();
$comment = $m_worldHistory->addComment($MaSK,$MaND,$NoiDungBL);
header('Location:'.$_SERVER['HTTP_REFERER'].'#comment');
}
public function _search($key){
$m_worldHistory = new m_WorldHistory();
$search_content = $m_worldHistory->search($key);
//Phan cac trang con cho tung mau tin
/*$current_page = (isset($_GET['page']))?$_GET['page']:1;
$pagination = new pagination(count($search_content),$current_page, 3, 10);
$paginationHTML = $pagination->showPagination();
//Gioi han so trang
$limitOfPage = $pagination->get_nItemOnPage();
$position = ($current_page-1)*$limitOfPage;
$search_content = $m_worldHistory->search($key, $position, $limitOfPage);*/
return array('search_content'=>$search_content/*, 'paginationHTML'=>$paginationHTML*/);
}
public function signup_account($TenND, $Email, $Password){
$m_worldHistory = new m_WorldHistory();
$MaND = $m_worldHistory->signup($TenND, $Email, $Password);
if($MaND!=0){
$_SESSION['success'] = "Đăng kí thành công";
header('location:index.php');
if(isset($_SESSION['error'])){
unset($_SESSION['error']);
}
}else{
$_SESSION['error'] = "Đăng kí thất bại";
header('location:signup.php');
}
}
public function login_account($Email, $Password){
$m_worldHistory = new m_WorldHistory();
$user = $m_worldHistory->login($Email, $Password);
if($user == true){
$_SESSION['user_name'] = $user->TenND;
$_SESSION['user_id'] = $user->MaND;
header('Location:'.$_SERVER['HTTP_REFERER']);
if(isset($_SESSION['user_error'])){
unset($_SESSION['user_error']);
}
if(isset($_SESSION['not_login_yet'])){
unset($_SESSION['not_login_yet']);
}
}else{
$_SESSION['user_error'] = "Sai thông tin đăng nhập";
header('Location:'.$_SERVER['HTTP_REFERER']);
}
}
public function logout_account(){
session_destroy();
header('Location:'.$_SERVER['HTTP_REFERER']);
}
public function CTGD_option(){
$m_worldHistory = new m_WorldHistory();
$CTGD = $m_worldHistory->getCTGD();
return array('CTGD'=>$CTGD);
}
public function post($MaCTGD,$TieuDe,$TomtatSK,$NoiDung,$HinhSK,$video){
$m_worldHistory = new m_WorldHistory();
$MaND = $m_worldHistory->addpost($MaCTGD,$TieuDe,$TomtatSK,$NoiDung,$HinhSK,$video);
if($MaND!=0){
$_SESSION['post_success'] = "Thêm bài viết thành công";
header('location:post.php');
if(isset($_SESSION['post_error'])){
unset($_SESSION['post_error']);
}
}else{
$_SESSION['post_error'] = "Thêm bài viết thất bại";
header('location:post.php');
}
}
}
?>
|
be4141c535b3cdc4c42bb0fc5e941cf034f66cd9
|
[
"JavaScript",
"Markdown",
"PHP"
] | 11
|
PHP
|
yyater97/World-History-Website
|
9e3b34376d6cf1e06eb9c7fc7c1e88995a5d4332
|
97538bc92e4caf3af40d35f804c02cf83bfd815f
|
refs/heads/master
|
<repo_name>SuperHenry2333/maml_new<file_sep>/maml.py
""" Code for the MAML algorithm and network definitions. """
from __future__ import print_function
import numpy as np
import sys
import tensorflow as tf
try:
import special_grads
except KeyError as e:
print('WARN: Cannot define MaxPoolGrad, likely already defined for this version of tensorflow: %s' % e,
file=sys.stderr)
from tensorflow.python.platform import flags
from utils import mse, xent, conv_block, normalize
FLAGS = flags.FLAGS
class MAML:
def __init__(self, dim_input, dim_output, num_images_per_class, num_classes,poison_num=1,poison_example=None):
""" must call construct_model() after initializing MAML! """
self.dim_input = dim_input
self.dim_output = dim_output
self.update_lr = FLAGS.update_lr
self.meta_lr = tf.placeholder_with_default(FLAGS.meta_lr, ())
self.poison_lr=FLAGS.poison_lr
self.classification = False
self.poison_num=poison_num
self.num_classes=num_classes
self.num_images_per_task=num_images_per_class*num_classes
if FLAGS.train:
if FLAGS.mode=='train_with_poison':
self.poisonx = tf.Variable(poison_example, trainable=True,dtype='float32')
elif FLAGS.mode=='train_poison':
self.poisonx = tf.get_variable("poisonx",
shape=[self.num_images_per_task, self.dim_input],
initializer=tf.zeros_initializer, trainable=True,dtype='float32')
elif FLAGS.mode=='train_with_noise':
self.poisonx = tf.random_uniform(name='noise',
shape=[self.num_images_per_task, self.dim_input],
minval=0.0, maxval=1.0,dtype='float32')
else:
self.poisonx=None
else:
self.poisonx=None
self.poisony =tf.range(self.num_images_per_task,dtype='int32') % self.num_classes
# print('jjjjjjjjjjjjjjjjjjjjjj')
# print(self.poisony.shape)
if FLAGS.datasource == 'omniglot':
self.loss_func = xent
self.classification = True
if FLAGS.conv:
self.dim_hidden = FLAGS.num_filters
self.forward = self.forward_conv
self.construct_weights = self.construct_conv_weights
else:
self.dim_hidden = [256, 128, 64, 64]
self.forward=self.forward_fc
self.construct_weights = self.construct_fc_weights
self.channels = 1
self.img_size = int(np.sqrt(self.dim_input/self.channels))
else:
raise ValueError('Unrecognized data source.')
def construct_model(self, input_tensors, prefix='metatrain_'):
self.inputa = input_tensors['inputa']
self.inputb = input_tensors['inputb']
self.labela = input_tensors['labela']
self.labelb = input_tensors['labelb']
###session for debug###########
# self.sess=tf.Session()
##################################
# if 'poison' in prefix:
# # self.poisonx2=tf.get_variable("poisonx2",shape=[self.poison_num,self.num_images_per_task,self.dim_input],initializer=tf.truncated_normal_initializer,trainable=True)
# # self.poisonx=tf.clip_by_value(self.poisonx_,0.0,1.0)
# # self.poisonx=tf.minimum(tf.maximum(self.poisonx,0.0),1.0)
# self.poisony=tf.one_hot(tf.tile(tf.reshape(tf.range(self.num_images_per_task)%self.num_classes,[1,self.num_images_per_task]),[self.poison_num,1]),depth=self.num_classes)
# self.inputa = tf.concat([self.poisonx1,self.inputa[self.poison_num:,:,:]],0)
# self.labela = tf.concat([self.poisony,self.labela[self.poison_num:,:,:]],0)
# self.inputb = tf.concat([self.poisonx2,self.inputb[self.poison_num:,:,:]],0)
# self.labelb = tf.concat([self.poisony,self.labelb[self.poison_num:,:,:]],0)
if prefix=='train_poison':
self.inputa_test = input_tensors['inputa_test']
self.inputb_test = input_tensors['inputb_test']
self.labela_test = input_tensors['labela_test']
self.labelb_test = input_tensors['labelb_test']
# elif prefix=='train_with_noise':
# self.poisonx1=tf.random_uniform(name='noise1',shape=[self.poison_num,self.num_images_per_task,self.dim_input],minval=0.0,maxval=1.0)
# self.poisonx2=tf.random_uniform(name='noise2',shape=[self.poison_num,self.num_images_per_task,self.dim_input],minval=0.0,maxval=1.0)
# self.poisony = tf.one_hot(
# tf.tile(tf.reshape(tf.range(self.num_images_per_task) % self.num_classes, [1, self.num_images_per_task]),
# [self.poison_num, 1]), depth=self.num_classes)
# self.inputa = tf.concat([self.poisonx1, self.inputa[self.poison_num:, :, :]], 0)
# self.inputb = tf.concat([self.poisonx2, self.inputb[self.poison_num:, :, :]], 0)
# self.labela = tf.concat([self.poisony, self.labela[self.poison_num:, :, :]], 0)
# self.labelb = tf.concat([self.poisony, self.labelb[self.poison_num:, :, :]], 0)
with tf.variable_scope('model', reuse=None) as training_scope:
if 'weights' in dir(self):
training_scope.reuse_variables()
else:
# Define the weights
self.weights = self.construct_weights()
# outputbs[i] and lossesb[i] is the output and loss after i+1 gradient updates
# lossesa, outputas, lossesb, outputbs = [], [], [], []
# accuraciesa, accuraciesb = [], []
num_updates = FLAGS.num_updates
# outputbs = [[]]*num_updates
# lossesb = [[]]*num_updates
# accuraciesb = [[]]*num_updates
def task_metalearn_(inp, weights,reuse=True,stop_grad=True,fw=True):
""" Perform gradient descent for one task in the meta-batch. """
inputa, inputb, labela, labelb = inp
# print("inputa hhhhhhhhhhh")
# print(inputa.shape)
task_outputbs, task_lossesb = [], []
if self.classification:
task_accuraciesb = []
task_outputa = self.forward(inputa, weights, reuse=reuse) # only reuse on the first iter
task_lossa = self.loss_func(task_outputa, labela)
grads = tf.gradients(task_lossa, list(weights.values()))
if stop_grad:
grads = [tf.stop_gradient(grad) for grad in grads]
gradients = dict(zip(weights.keys(), grads))
fast_weights = dict(zip(weights.keys(), [weights[key] - self.update_lr*gradients[key] for key in weights.keys()]))
output = self.forward(inputb, fast_weights, reuse=True)
task_outputbs.append(output)
task_lossesb.append(self.loss_func(output, labelb))
for j in range(num_updates - 1):
loss = self.loss_func(self.forward(inputa, fast_weights, reuse=True), labela)
grads = tf.gradients(loss, list(fast_weights.values()))
if stop_grad:
grads = [tf.stop_gradient(grad) for grad in grads]
gradients = dict(zip(fast_weights.keys(), grads))
fast_weights = dict(zip(fast_weights.keys(), [fast_weights[key] - self.update_lr*gradients[key] for key in fast_weights.keys()]))
output = self.forward(inputb, fast_weights, reuse=True)
task_outputbs.append(output)
task_lossesb.append(self.loss_func(output, labelb))
# deta=dict(zip(fast_weights.keys(),[fast_weights[key]-weights[key] for key in fast_weights.keys()]))
task_output = [task_outputa, task_outputbs, task_lossa, task_lossesb]
if self.classification:
task_accuracya = tf.contrib.metrics.accuracy(tf.argmax(tf.nn.softmax(task_outputa), 1), tf.argmax(labela, 1))
for j in range(num_updates):
task_accuraciesb.append(tf.contrib.metrics.accuracy(tf.argmax(tf.nn.softmax(task_outputbs[j]), 1), tf.argmax(labelb, 1)))
task_output.extend([task_accuracya, task_accuraciesb])
if fw:
task_output.append(fast_weights)
return task_output
if FLAGS.norm is not 'None':
# to initialize the batch norm vars, might want to combine this, and not run idx 0 twice.
unused = task_metalearn_(inp=(self.inputa[0], self.inputb[0], self.labela[0], self.labelb[0]),weights=self.weights, reuse=False,fw=False)
if prefix!='train_poison' and (not FLAGS.reptile):
def task_metalearn(inp):
return task_metalearn_(inp,weights=self.weights,stop_grad=True,fw=False,reuse=True)
out_dtype = [tf.float32, [tf.float32]*num_updates, tf.float32, [tf.float32]*num_updates]
if self.classification:
out_dtype.extend([tf.float32, [tf.float32]*num_updates])
result = tf.map_fn(task_metalearn, elems=(self.inputa, self.inputb, self.labela, self.labelb), dtype=out_dtype, parallel_iterations=FLAGS.meta_batch_size)
if self.classification:
outputas, outputbs, lossesa, lossesb, accuraciesa, accuraciesb =result
else:
outputas, outputbs, lossesa, lossesb, accuraciesa, accuraciesb =result
else:
if prefix == 'train_poison':
sg = False
else:
sg = True
if self.classification:
outputas, outputbs, lossesa, lossesb, accuraciesa, accuraciesb,new_weights = [],[],[],[],[],[],[]
for itr in range(FLAGS.meta_batch_size):
a,b,c,d,e,f,g=task_metalearn_(inp=(self.inputa[itr], self.inputb[itr], self.labela[itr], self.labelb[itr]),weights=self.weights,reuse=True,stop_grad=sg)
outputas.append(a)
outputbs.append(b)
lossesa.append(c)
lossesb.append(d)
accuraciesa.append(e)
accuraciesb.append(f)
new_weights.append(g)
self.accuraciesa=accuraciesa
lossesb = tf.transpose(lossesb,[1,0,2])
accuraciesb = tf.transpose(accuraciesb,[1,0])
else:
outputas, outputbs, lossesa, lossesb,new_weights= [], [], [], [],[]
for itr in range(FLAGS.meta_batch_size):
a, b, c, d ,e= task_metalearn_(inp=(self.inputa[itr], self.inputb[itr], self.labela[itr], self.labelb[itr]),weights=self.weights,reuse=True,stop_grad=sg)
outputas.append(a)
outputbs.append(b)
lossesa.append(c)
lossesb.append(d)
new_weights.append(e)
lossesb = tf.transpose(lossesb,[1,0,2])
## Performance & Optimization
if 'train' in prefix:
def get_median(v):
mid = v.get_shape()[-1] // 2 + 1
return tf.nn.top_k(v, mid).values[...,-1]
if FLAGS.median:
new_weights = dict(zip(self.weights.keys(),
[get_median(tf.concat([tf.expand_dims(weight[key],-1) for weight in new_weights],axis=-1)) for key
in self.weights.keys()]))
else:
new_weights=dict(zip(self.weights.keys(),[sum([ weight[key] for weight in new_weights])/FLAGS.meta_batch_size for key in self.weights.keys()]))
new_weights=dict(zip(self.weights.keys(),[self.weights[key]+self.meta_lr*(new_weights[key]-self.weights[key]) for key in self.weights.keys()]))
reptile_ops=[tf.assign(self.weights[key], new_weights[key]) for key in self.weights.keys() ]
reptile_op=tf.group(*reptile_ops)
# if not FLAGS.reptile:
self.total_loss1 = total_loss1 = tf.reduce_sum(lossesa) / tf.to_float(FLAGS.meta_batch_size)
self.total_losses2 = total_losses2 = [tf.reduce_sum(lossesb[j]) / tf.to_float(FLAGS.meta_batch_size) for j in range(num_updates)]
# after the map_fn
self.outputas, self.outputbs = outputas, outputbs
if self.classification:
self.total_accuracy1 = total_accuracy1 = tf.reduce_sum(accuraciesa) / tf.to_float(FLAGS.meta_batch_size)
self.total_accuracies2 = total_accuracies2 = [tf.reduce_sum(accuraciesb[j]) / tf.to_float(FLAGS.meta_batch_size) for j in range(num_updates)]
self.pretrain_op = tf.train.AdamOptimizer(self.meta_lr).minimize(total_loss1,var_list=list(self.weights.values()))
if FLAGS.metatrain_iterations > 0:
if FLAGS.reptile:
self.metatrain_op=reptile_op
else:
optimizer = tf.train.AdamOptimizer(self.meta_lr)
self.gvs = gvs = optimizer.compute_gradients(self.total_losses2[FLAGS.num_updates - 1],
var_list=list(self.weights.values()))
if FLAGS.datasource == 'miniimagenet':
gvs = [(tf.clip_by_value(grad, -10, 10), var) for grad, var in gvs]
self.metatrain_op = optimizer.apply_gradients(gvs)
if prefix=='train_poison':
assert FLAGS.reptile
if FLAGS.reptile:
weights_star=new_weights
else:
gvs = tf.gradients(self.total_losses2[FLAGS.num_updates - 1],list(self.weights.values()))
if FLAGS.datasource == 'miniimagenet':
gvs = [(tf.clip_by_value(grad, -10, 10), var) for grad, var in gvs]
gradients = dict(zip(self.weights.keys(), gvs))
weights_star = dict(
zip(self.weights.keys(), [self.weights[key] - self.meta_lr * gradients[key] for key in self.weights.keys()]))
def task_metalearn_star(inp):
return task_metalearn_(inp, weights=weights_star, stop_grad=True,fw=False)
# self.metatrain_op = optimizer.apply_gradients(gvs)
out_dtype = [tf.float32, [tf.float32] * num_updates, tf.float32, [tf.float32] * num_updates]
if self.classification:
out_dtype.extend([tf.float32, [tf.float32] * num_updates])
result = tf.map_fn(task_metalearn_star, elems=(self.inputa_test, self.inputb_test, self.labela_test, self.labelb_test),
dtype=out_dtype, parallel_iterations=FLAGS.meta_batch_size)
if self.classification:
outputas_test, outputbs_test, lossesa_test, lossesb_test, accuraciesa_test, accuraciesb_test = result
else:
outputas_test, outputbs_test, lossesa_test, lossesb_test = result
self.total_losses2_test = total_losses2_test = [tf.reduce_sum(lossesb_test[j]) / tf.to_float(FLAGS.meta_batch_size) for
j in range(num_updates)]
optimizer = tf.train.AdamOptimizer(self.poison_lr)
self.gvs_poison = gvs_poison = optimizer.compute_gradients(-self.total_losses2_test[FLAGS.num_updates - 1],var_list=[self.poisonx])
if FLAGS.datasource == 'miniimagenet':
gvs_poison = [(tf.clip_by_value(grad, -10, 10), var) for grad, var in gvs_poison]
self.poison_op = optimizer.apply_gradients(gvs_poison)
clipped_poison=tf.clip_by_value(self.poisonx,0.0,1.0)
self.clip_poison_op=tf.assign(self.poisonx,clipped_poison)
else:
self.metaval_total_loss1 = total_loss1 = tf.reduce_sum(lossesa) / tf.to_float(FLAGS.meta_batch_size)
self.metaval_total_losses2 = total_losses2 = [tf.reduce_sum(lossesb[j]) / tf.to_float(FLAGS.meta_batch_size) for j in range(num_updates)]
if self.classification:
self.metaval_total_accuracy1 = total_accuracy1 = tf.reduce_sum(accuraciesa) / tf.to_float(FLAGS.meta_batch_size)
self.metaval_total_accuracies2 = total_accuracies2 =[tf.reduce_sum(accuraciesb[j]) / tf.to_float(FLAGS.meta_batch_size) for j in range(num_updates)]
## Summaries
tf.summary.scalar(prefix+'Pre-update loss', total_loss1)
if self.classification:
tf.summary.scalar(prefix+'Pre-update accuracy', total_accuracy1)
for j in range(num_updates):
tf.summary.scalar(prefix+'Post-update loss, step ' + str(j+1), total_losses2[j])
if self.classification:
tf.summary.scalar(prefix+'Post-update accuracy, step ' + str(j+1), total_accuracies2[j])
### Network construction functions (fc networks and conv networks)
def construct_fc_weights(self):
weights = {}
weights['w1'] = tf.Variable(tf.truncated_normal([self.dim_input, self.dim_hidden[0]], stddev=0.01))
weights['b1'] = tf.Variable(tf.zeros([self.dim_hidden[0]]))
for i in range(1,len(self.dim_hidden)):
weights['w'+str(i+1)] = tf.Variable(tf.truncated_normal([self.dim_hidden[i-1], self.dim_hidden[i]], stddev=0.01))
weights['b'+str(i+1)] = tf.Variable(tf.zeros([self.dim_hidden[i]]))
weights['w'+str(len(self.dim_hidden)+1)] = tf.Variable(tf.truncated_normal([self.dim_hidden[-1], self.dim_output], stddev=0.01))
weights['b'+str(len(self.dim_hidden)+1)] = tf.Variable(tf.zeros([self.dim_output]))
return weights
def forward_fc(self, inp, weights, reuse=False):
hidden = normalize(tf.matmul(inp, weights['w1']) + weights['b1'], activation=tf.nn.relu, reuse=reuse, scope='0')
for i in range(1,len(self.dim_hidden)):
hidden = normalize(tf.matmul(hidden, weights['w'+str(i+1)]) + weights['b'+str(i+1)], activation=tf.nn.relu, reuse=reuse, scope=str(i+1))
return tf.matmul(hidden, weights['w'+str(len(self.dim_hidden)+1)]) + weights['b'+str(len(self.dim_hidden)+1)]
def construct_conv_weights(self):
weights = {}
dtype = tf.float32
conv_initializer = tf.contrib.layers.xavier_initializer_conv2d(dtype=dtype)
fc_initializer = tf.contrib.layers.xavier_initializer(dtype=dtype)
k = 3
weights['conv1'] = tf.get_variable('conv1', [k, k, self.channels, self.dim_hidden], initializer=conv_initializer, dtype=dtype)
weights['b1'] = tf.Variable(tf.zeros([self.dim_hidden]))
weights['conv2'] = tf.get_variable('conv2', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype)
weights['b2'] = tf.Variable(tf.zeros([self.dim_hidden]))
weights['conv3'] = tf.get_variable('conv3', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype)
weights['b3'] = tf.Variable(tf.zeros([self.dim_hidden]))
weights['conv4'] = tf.get_variable('conv4', [k, k, self.dim_hidden, self.dim_hidden], initializer=conv_initializer, dtype=dtype)
weights['b4'] = tf.Variable(tf.zeros([self.dim_hidden]))
if FLAGS.datasource == 'miniimagenet':
# assumes max pooling
weights['w5'] = tf.get_variable('w5', [self.dim_hidden*5*5, self.dim_output], initializer=fc_initializer)
weights['b5'] = tf.Variable(tf.zeros([self.dim_output]), name='b5')
else:
weights['w5'] = tf.Variable(tf.random_normal([self.dim_hidden, self.dim_output]), name='w5')
weights['b5'] = tf.Variable(tf.zeros([self.dim_output]), name='b5')
return weights
def forward_conv(self, inp, weights, reuse=False, scope=''):
# reuse is for the normalization parameters.
channels = self.channels
inp = tf.reshape(inp, [-1, self.img_size, self.img_size, channels])
hidden1 = conv_block(inp, weights['conv1'], weights['b1'], reuse, scope+'0')
hidden2 = conv_block(hidden1, weights['conv2'], weights['b2'], reuse, scope+'1')
hidden3 = conv_block(hidden2, weights['conv3'], weights['b3'], reuse, scope+'2')
hidden4 = conv_block(hidden3, weights['conv4'], weights['b4'], reuse, scope+'3')
if FLAGS.datasource == 'miniimagenet':
# last hidden layer is 6x6x64-ish, reshape to a vector
hidden4 = tf.reshape(hidden4, [-1, np.prod([int(dim) for dim in hidden4.get_shape()[1:]])])
else:
hidden4 = tf.reduce_mean(hidden4, [1, 2])
return tf.matmul(hidden4, weights['w5']) + weights['b5']
<file_sep>/gen_data.sh
GPU=1
way=5
shot=5
metatrain_iterations=50000
meta_batch_size=5
dataset=omniglot
meta_lr=0.01
update_lr=0.5
poison_lr=0.1
num_updates=10
reptile=True
train=True
mode='train_label_flip'
resume=False
save_poison_ep=50
median=False
noise_rate=0.2
if [ $mode == 'train_with_poison' ]
then
logdir=logs/${dataset}${way}way${shot}shot/train_poisonreptile/
else
logdir=logs/${dataset}${way}way${shot}shot/${mode}reptile/
fi
echo $logdir
poison_itr=48700
poison_dir=../poison_reptile_2/logs/omniglot5way5shot/train_poisonreptile/cls_5.mbs_5.ubs_5.numstep10.updatelr0.5.poison_lr0.1batchnorm/poisonx_50.npy
export TF_XLA_FLAGS=--tf_xla_cpu_global_jit
CUDA_VISIBLE_DEVICES=$GPU python main_gen_data.py --datasource=$dataset --metatrain_iterations=$metatrain_iterations --meta_batch_size=$meta_batch_size --update_batch_size=$shot --update_lr=$update_lr --num_updates=$num_updates --logdir=$logdir --reptile=$reptile --mode=$mode --train=$train --resume=$resume --poison_itr=$poison_itr --poison_lr=$poison_lr --meta_lr=$meta_lr --save_poison_ep=$save_poison_ep --median=$median --poison_dir=$poison_dir --noise_rate=$noise_rate
<file_sep>/test_tfrecord.py
import csv
import numpy as np
import pickle
import random
import tensorflow as tf
from tqdm import trange
from data_generator_rcd import DataGenerator
from maml import MAML
from tensorflow.python.platform import flags
from math import isnan
dataset = tf.data.TFRecordDataset(['train_own.tfrecords'])
def dgcae_example_feature(example_proto):
features={}<file_sep>/data_generator_rcd.py
""" Code for loading data. """
import numpy as np
import os
import random
import tensorflow as tf
from tensorflow.python.platform import flags
from utils import get_images
from tqdm import trange
FLAGS = flags.FLAGS
class DataGenerator(object):
"""
Data Generator capable of generating batches of sinusoid or Omniglot data.
A "class" is considered a class of omniglot digits or a particular sinusoid function.
"""
def __init__(self, num_samples_per_class, batch_size, config={}):
"""
Args:
num_samples_per_class: num samples to generate per class in one batch
batch_size: size of meta batch size (e.g. number of functions)
"""
self.batch_size = batch_size
self.num_samples_per_class = num_samples_per_class
self.num_classes = 1 # by default 1 (only relevant for classification problems)
if 'omniglot' in FLAGS.datasource:
self.num_classes = config.get('num_classes', FLAGS.num_classes)
self.img_size = config.get('img_size', (28, 28))
self.dim_input = np.prod(self.img_size)
self.dim_output = self.num_classes
# data that is pre-resized using PIL with lanczos filter
data_folder = config.get('data_folder', './data/omniglot')
character_folders = [os.path.join(data_folder, family, character) \
for family in os.listdir(data_folder) \
if os.path.isdir(os.path.join(data_folder, family)) \
for character in os.listdir(os.path.join(data_folder, family))]
random.seed(1)
random.shuffle(character_folders)
num_val = 0
num_train = config.get('num_train', 1200) - num_val
self.metatrain_character_folders = character_folders[:num_train]
if FLAGS.test_set:
self.metaval_character_folders = character_folders[num_train+num_val:]
else:
self.metaval_character_folders = character_folders[num_train:num_train+num_val]
self.rotations = config.get('rotations', [0, 90, 180, 270])
else:
raise ValueError('Unrecognized data source')
def make_data_tensor(self, train=True,poison=None,sess=None):
if train:
folders = self.metatrain_character_folders
# number of tasks, not number of meta-iterations. (divide by metabatch size to measure)
num_total_batches = 5000
else:
folders = self.metaval_character_folders
num_total_batches = 1000
# make list of files
print('Generating filenames')
all_filenames = []
for _ in trange(num_total_batches):
sampled_character_folders = random.sample(folders, self.num_classes)
random.shuffle(sampled_character_folders)
labels_and_images = get_images(sampled_character_folders, range(self.num_classes), nb_samples=self.num_samples_per_class, shuffle=False)
# make sure the above isn't randomized order
labels = [li[0] for li in labels_and_images]
filenames = [li[1] for li in labels_and_images]
all_filenames.extend(filenames)
# make queue for tensorflow to read from
filename_queue = tf.train.string_input_producer(tf.convert_to_tensor(all_filenames), shuffle=False)
print('Generating image processing ops')
image_reader = tf.WholeFileReader()
_, image_file = image_reader.read(filename_queue)
image = tf.image.decode_png(image_file)
image.set_shape((self.img_size[0],self.img_size[1],1))
image = tf.reshape(image, [self.dim_input])
image = tf.cast(image, tf.float32) / 255.0
image = 1.0 - image # invert
num_preprocess_threads = 1 # TODO - enable this to be set to >1
min_queue_examples = 256
examples_per_batch = self.num_classes * self.num_samples_per_class
batch_image_size = examples_per_batch
print('Batching images')
images = tf.train.batch(
[image],
batch_size = batch_image_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_image_size,
)
print(images)
all_image_batches, all_label_batches = [], []
print('Manipulating image data to be right shape')
# for i in trange(self.batch_size):
image_batch = images
if FLAGS.datasource == 'omniglot':
# omniglot augments the dataset by rotating digits to create new classes
# get rotation per class (e.g. 0,1,2,0,0 if there are 5 classes)
rotations = tf.multinomial(tf.log([[1., 1.,1.,1.]]), self.num_classes)
label_batch = tf.convert_to_tensor(labels)
pred=tf.random_uniform(shape=[],minval=0,maxval=1)<FLAGS.noise_rate
new_list, new_label_list = [], []
for k in range(self.num_samples_per_class):
class_idxs = tf.range(0, self.num_classes) #[num_classes]
class_idxs = tf.random_shuffle(class_idxs)
true_idxs = class_idxs*self.num_samples_per_class + k # idx of kth sample in each class
new_list.append(tf.gather(image_batch,true_idxs))
# if FLAGS.datasource == 'omniglot': # and FLAGS.train:
# new_list[-1] = tf.stack([tf.reshape(tf.image.rot90(
# tf.reshape(new_list[-1][ind], [self.img_size[0],self.img_size[1],1]),
# k=tf.cast(rotations[0,class_idxs[ind]], tf.int32)), (self.dim_input,))
# for ind in range(self.num_classes)])
new_label_list.append(tf.gather(label_batch, true_idxs))
new_list = tf.concat(new_list, 0) # has shape [self.num_classes*self.num_samples_per_class, self.dim_input]
new_label_list = tf.concat(new_label_list, 0)
# sess = tf.Session()
# if i==0 and train:
# print('hhhhhhhhhhhhhhhhhhhhhhh')
# # sess=tf.Session()
# tf.train.start_queue_runners()
# sess.run(class_idxs)
# print(new_list)
# samplex = sess.run(new_list)
# print('hhhhhhhhhhhhhhhhhhhhhhh')
# sampley = sess.run(tf.random.shuffle(new_label_list))
# print('Label flipped Label flippedLabel flippedLabel flippedLabel flippedLabel flippedLabel flippedLabel flipped')
# if ('noise' in FLAGS.mode or 'poison' in FLAGS.mode) and train:
# new_list=tf.cond(pred,lambda :poison[0],lambda :new_list)
# new_label_list=tf.cond(pred,lambda :poison[1],lambda :new_label_list)
# elif 'label_flip' in FLAGS.mode and train:
# new_list=tf.cond(pred,lambda :samplex,lambda :new_list)
# new_label_list=tf.cond(pred,lambda :sampley,lambda :new_label_list)
# all_image_batches.append(new_list)
# all_label_batches.append(new_label_list)
#
#
# all_image_batches = tf.stack(all_image_batches)
# all_label_batches = tf.stack(all_label_batches)
# all_label_batches = tf.one_hot(all_label_batches, self.num_classes)
return new_list, new_label_list
def generate_sinusoid_batch(self, train=True, input_idx=None):
# Note train arg is not used (but it is used for omniglot method.
# input_idx is used during qualitative testing --the number of examples used for the grad update
amp = np.random.uniform(self.amp_range[0], self.amp_range[1], [self.batch_size])
phase = np.random.uniform(self.phase_range[0], self.phase_range[1], [self.batch_size])
outputs = np.zeros([self.batch_size, self.num_samples_per_class, self.dim_output])
init_inputs = np.zeros([self.batch_size, self.num_samples_per_class, self.dim_input])
for func in range(self.batch_size):
init_inputs[func] = np.random.uniform(self.input_range[0], self.input_range[1], [self.num_samples_per_class, 1])
if input_idx is not None:
init_inputs[:,input_idx:,0] = np.linspace(self.input_range[0], self.input_range[1], num=self.num_samples_per_class-input_idx, retstep=False)
outputs[func] = amp[func] * np.sin(init_inputs[func]-phase[func])
return init_inputs, outputs, amp, phase
|
2e2a98d4459b3b6da2c37ba78d739a72fd2dccb7
|
[
"Python",
"Shell"
] | 4
|
Python
|
SuperHenry2333/maml_new
|
376b37b612dc23c0f0b34390a13ad3ea0ec0f7cb
|
f7356ea2be4305fbf306b7f5d85d5d1ecd70d5ab
|
refs/heads/main
|
<repo_name>GOJABoop/Portfolio<file_sep>/src/sections/index.js
export * from './Navbar';
export * from './Hero';
export * from './ProjectsSection';
export * from './TechnologiesSection';
export * from './ContactSection';
export * from './Footer';
export * from './Main';
<file_sep>/src/sections/Hero.jsx
import { LineTerminal } from '../components';
export const Hero = () => {
return (
<section className="bg-[url('/assets/hero2.jpg')] pt-20" id="about">
<div className="grid max-w-screen-xl px-4 py-8 mx-auto lg:gap-8 xl:gap-0 lg:py-16 lg:grid-cols-12">
<div className=" mr-auto place-self-center lg:col-span-7">
<h1 className="max-w-2xl mb-4 text-4xl text-slate-200 font-extrabold tracking-tight leading-none md:text-5xl xl:text-6xl">Hi, I'm <NAME></h1>
<p className="max-w-2xl text-justify mb-6 text-xl font-light text-slate-100 lg:mb-8 md:text-lg dark:text-gray-400">I am an enthusiastic student who is about to finish his university career, where I have carried out some projects. I am excited about this industry, its world and the knowledge that underpins it, I love to continually learn and put new knowledge into practice. I am currently learning and React JS in depth and Node JS. I am interested in web development, machine learning, and computer simulations.</p>
<a href="#projects" className="bg-gradient-to-r from-purple-500 to-blue-500 inline-flex items-center justify-center px-5 py-3 mr-3 text-base font-medium text-center text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 transition ease-in-out delay-150 hover:-translate-y-1 hover:scale-110 duration-700">
Get started
<svg className="w-5 h-5 ml-2 -mr-1" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fillRule="evenodd" d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z" clipRule="evenodd"></path></svg>
</a>
</div>
<div className="mt-4 lg:mt-0 lg:col-span-5 lg:flex">
<div className="w-full coding inverse-toggle px-5 pt-4 shadow-lg text-gray-100 text-sm font-mono subpixel-antialiased bg-gray-800 pb-6 pt-4 rounded-lg leading-normal overflow-hidden">
<div className="top mb-2 flex">
<div className="h-3 w-3 bg-red-500 rounded-full"></div>
<div className="ml-2 h-3 w-3 bg-orange-300 rounded-full"></div>
<div className="ml-2 h-3 w-3 bg-green-500 rounded-full"></div>
</div>
<LineTerminal message={ 'apt-get Autodidact'}/>
<LineTerminal message={ 'apt-get Teamwork'}/>
<LineTerminal message={ 'apt-get Communication'}/>
<LineTerminal message={ 'apt-get Time management'}/>
<LineTerminal message={ 'apt-get Flexibility'}/>
<LineTerminal message={ 'apt-get Orientation to results'}/>
<LineTerminal message={ 'apt-get hire me!!!'}/>
</div>
</div>
</div>
</section>
)
}
<file_sep>/src/App.jsx
import { Navbar, Main } from './sections'
export const App = () => {
return (
<>
<Navbar/>
<Main/>
</>
)
}<file_sep>/src/sections/Navbar.jsx
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import logo from '../../assets/logo.svg';
export const Navbar = () => {
const [toggleMenu, setToggleMenu] = useState(true);
const onClickButton = ({ reference }) => {
setToggleMenu(!toggleMenu);
transition
}
return (
<nav className="flex items-center justify-between flex-wrap bg-neutral-900 p-6 fixed top-0 w-full">
<div className="flex items-center flex-shrink-0 mr-6">
<img src={logo} className="fill-white h-8 w-9 mr-2" alt="logo" />
<span className="text-2xl tracking-tight font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-purple-500 to-blue-500">GOJAx64</span>
</div>
<div className="block lg:hidden">
<button onClick={ onClickButton } className="flex items-center px-3 py-2 border border-blue-500 rounded text-white hover:text-white hover:border-blue-500">
<svg className="fill-current h-3 w-3" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><title>Menu</title><path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z"/></svg>
</button>
</div>
<div id='menuNavbar' className={ `w-full block flex-grow lg:flex lg:items-center lg:w-auto text-center lg:text-right ${ toggleMenu ? 'hidden' : '' }`}>
<div className="text-base lg:flex-grow">
<a onClick={ onClickButton } href="/#about" className="block mt-4 lg:inline-block lg:mt-0 text-purple-500 hover:text-purple-200 mr-4">
About me
</a>
<a onClick={ onClickButton } href="/#projects" className="block mt-4 lg:inline-block lg:mt-0 text-slate-100 hover:text-purple-200 mr-4">
Projects
</a>
<a onClick={ onClickButton } href="/#technologies" className="block mt-4 lg:inline-block lg:mt-0 text-slate-100 hover:text-purple-200 mr-4">
Technologies
</a>
<a onClick={ onClickButton } href="/#contact" className="block mt-4 lg:inline-block lg:mt-0 text-slate-100 hover:text-purple-200 mr-4">
Contact
</a>
</div>
{/* <div>
<button href="#" className="bg-gradient-to-r from-purple-500 to-blue-500 rounded-md inline-block text-sm px-3 py-2 leading-none border rounded border-black hover:border-transparent hover:text-slate-300 mt-4 lg:mt-0">Download CV</button>
</div> */}
</div>
</nav>
)
}
<file_sep>/src/components/GridTechnologies.jsx
import javascript from '../../assets/icons/javascript.svg';
import cpp from '../../assets/icons/cpp.svg';
import c_sharp from '../../assets/images/c_sharp.png';
import python from '../../assets/icons/python.svg';
import java from '../../assets/icons/java.svg';
import react from '../../assets/icons/react.svg';
import laravel from '../../assets/icons/laravel.svg';
import mysql from '../../assets/icons/mysql.svg';
import postgresql from '../../assets/icons/postgresql.svg';
import html from '../../assets/icons/html.svg';
import css from '../../assets/icons/css.svg';
import tailwind from '../../assets/icons/tailwind.svg';
export const GridTechnologies = () => {
return (
<div className={`mx-2 py-4 text-center lg:mx-24 border border-slate-400 rounded-xl`}>
<div className={`grid grid-cols-3 sm:grid-cols-4 sm:mx-4 lg:grid-cols-12 gap-5 lg:mx-1 place-items-center`}>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={javascript}
alt={'javascript'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={cpp}
alt={'cpp'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={c_sharp}
alt={'c_sharp'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={python}
alt={'python'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={java}
alt={'java'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={react}
alt={'react'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={laravel}
alt={'laravel'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={mysql}
alt={'mysql'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={postgresql}
alt={'postgresql'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={html}
alt={'html'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={css}
alt={'css'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={tailwind}
alt={'tailwind'}
/>
</div>
</div>
)
}
<file_sep>/src/components/Card.jsx
export const Card = ({ name, description, linkRepo, img }) => {
return (
<a href={linkRepo} target="blank" className="flex items-center mx-4 bg-slate-300 rounded-lg border border-slate-500 shadow-md md:mx-0 md:flex-row md:w-full hover:bg-slate-200 hover:border-slate-900">
<img className="object-cover w-18 h-20 ml-2 rounded-t-lg md:rounded-none md:rounded-l-lg" src={ img } alt={ name } />
<div className="flex flex-col justify-between p-4 leading-normal">
<h5 className='text-left mb-1 text-2xl font-bold tracking-tight text-transparent bg-clip-text bg-gradient-to-r from-purple-900 to-blue-900'>{ name }</h5>
<p className="mb-0.5 italic text-gray-700 text-left">{ description }</p>
</div>
</a>
)
}
<file_sep>/src/components/GridTools.jsx
import git from '../../assets/icons/git.svg';
import github from '../../assets/icons/github.svg';
import jira from '../../assets/icons/jira.svg';
import slack from '../../assets/icons/slack.svg';
import terminal from '../../assets/icons/terminal.svg';
import linux from '../../assets/icons/linux.svg';
export const GridTools = () => {
return (
<div className={`mx-2 py-4 text-center lg:mx-7 border border-slate-400 rounded-xl`}>
<div className={`grid grid-cols-3 sm:grid-cols-4 sm:mx-4 lg:grid-cols-6 gap-5 lg:mx-1 place-items-center`}>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={git}
alt={'git'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={github}
alt={'github'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={jira}
alt={'jira'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={slack}
alt={'slack'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={terminal}
alt={'terminal'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={linux}
alt={'linux'}
/>
</div>
</div>
)
}<file_sep>/src/data/stackTechonologies.js
export const mainTechnologies = ['javascript', 'java', 'python', 'cpp', 'react','node','laravel', 'mysql', 'postgresql', 'html', 'css', 'tailwind'];
export const tools = ['git', 'github', 'jira', 'slack', 'terminal', 'linux'];
export const currentLearnign = ['ai', 'typescript', 'node', 'docker', 'jest', 'mongodb'];<file_sep>/src/sections/ProjectsSection.jsx
import { GridProjects } from '../components';
export const ProjectsSection = () => {
return (
<section className='bg-slate-400' id="projects">
<div className='py-5 bg-neutral-900 text-center'>
<h1 className=" text-2xl font-extrabold tracking-tight md:text-4xl text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-blue-700">Most Representative Projects</h1>
</div>
<div className="pt-4 px-4 mx-auto max-w-screen-xl text-center lg:pb-7 lg:px-12">
<p className="mb-2 text-xl font-normal text-justify text-gray-800 md:text-center lg:text-xl sm:px-10 xl:px-50">In each project I give my best and despite being personal or school projects I try to develop them in such a way that an end user can use them in their day to day in an optimal, clear and simple way, in addition to applying the fundamentals and knowledge that I have in computer science and software development.</p>
</div>
<GridProjects/>
</section>
)
}
<file_sep>/src/sections/TechnologiesSection.jsx
import { GridTechnologies, GridCurrentLearning, GridTools } from '../components';
export const TechnologiesSection = () => {
return (
<section className='bg-slate-300 pb-5' id="technologies">
<div className='py-6 bg-neutral-900 text-center'>
<h1 className=" text-2xl font-extrabold tracking-tight md:text-4xl text-transparent bg-clip-text bg-gradient-to-r from-purple-400 to-blue-700">Technologies</h1>
</div>
<div className="py-6 px-4 mx-auto max-w-screen-xl text-center lg:pb-6 lg:px-12">
<h1 className=" mb-1 text-xl font-extrabold tracking-tight leading-none text-gray-900 md:text-4xl lg:text-4xl">Main Lenguages and Frameworks</h1>
<p className="text-xl font-normal text-justify text-gray-500 md:text-center lg:text-xl sm:px-16 xl:px-50">These are the lenguages, frameworks and databases with which I feel most comfortable.</p>
</div>
<GridTechnologies />
<div className='mx-1 py-4 mt-2 lg:mt-6 text-center lg:mx-24 '>
<div className={`grid grid-cols-1 sm:grid-cols-2 sm:mx-4 lg:grid-cols-2 gap-5 lg:mx-1 place-items-center`}>
<div className="py-1 px-2 mx-auto max-w-screen-xl text-center">
<h1 className="mb-4 text-xl font-extrabold tracking-tight leading-none text-gray-900 md:text-4xl lg:text-4xl">Current Learning</h1>
<p className="mb-2 text-xl font-normal text-justify text-gray-500 md:text-center lg:text-xl sm:px-16 xl:px-50">Currently I'm learnig this technologies or tools you can see projects in my GitHub.</p>
<GridCurrentLearning />
</div>
<div className='py-1 px-2 mx-auto max-w-screen-xl text-center'>
<h1 className="mb-4 text-xl font-extrabold tracking-tight leading-none text-gray-900 md:text-5xl lg:text-4xl">Tools</h1>
<p className="mb-2 text-xl font-normal text-justify text-gray-500 md:text-center lg:text-xl sm:px-16 xl:px-50">I've worked with these tools and I feel comfortable with them.</p>
<GridTools/>
</div>
</div>
</div>
</section>
)
}<file_sep>/src/components/index.js
export * from './Card';
export * from './GridProjects';
export * from './LineTerminal';
export * from './GridTechnologies';
export * from './GridCurrentLearning';
export * from './GridTools';<file_sep>/README.md
# Portfolio
My personal page, where I present some of my projects and work, Developed with React JS and Tailwind CSS.
To initialize execute
```
yarn
```
to run as develop
```
yarn dev
```
you can see the page published in [GOJAx64](https://gojax64.netlify.app/)
<file_sep>/src/components/GridCurrentLearning.jsx
import ai from '../../assets/icons/ai.svg';
import typescript from '../../assets/icons/typescript.svg';
import node from '../../assets/icons/node.svg';
import docker from '../../assets/icons/docker.svg';
import jest from '../../assets/icons/jest.svg';
import mongodb from '../../assets/icons/mongodb.svg';
export const GridCurrentLearning = () => {
return (
<div className={`mx-2 py-4 text-center lg:mx-7 border border-slate-400 rounded-xl`}>
<div className={`grid grid-cols-3 sm:grid-cols-4 sm:mx-4 lg:grid-cols-6 gap-5 lg:mx-1 place-items-center`}>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={ai}
alt={'ai'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={typescript}
alt={'typescript'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={node}
alt={'node'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={docker}
alt={'docker'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={jest}
alt={'jest'}
/>
<img
className="w-16 h-16 transition ease-in-out delay-300 lg:hover:-translate-y-1 lg:hover:scale-110 duration-300"
src={mongodb}
alt={'mongodb'}
/>
</div>
</div>
)
}
|
f4bf7c67e8720b9c8f31e4842b5bea87ca9ac056
|
[
"JavaScript",
"Markdown"
] | 13
|
JavaScript
|
GOJABoop/Portfolio
|
9e174ee83035f4293e9a8f36dc1f15bf2373757d
|
231b72497ebcd9e6ba3f40f3b516d4bca5abc600
|
refs/heads/master
|
<repo_name>dmanning23/DepthBasics_KinectMonogame<file_sep>/Game1.cs
using Microsoft.Kinect;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
namespace DepthBasics_KinectMonogame
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
/// <summary>
/// Active Kinect sensor
/// </summary>
private KinectSensor sensor;
/// <summary>
/// Intermediate storage for the depth data received from the camera
/// </summary>
private DepthImagePixel[] depthPixels;
/// <summary>
/// the texture to write to
/// </summary>
Texture2D pixels;
/// <summary>
/// temp buffer to hold convert kinect data to color objects
/// </summary>
Color[] pixelData_clear;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
pixels = new Texture2D(graphics.GraphicsDevice,
640,
480, false, SurfaceFormat.Color);
pixelData_clear = new Color[640 * 480];
for (int i = 0; i < pixelData_clear.Length; ++i)
pixelData_clear[i] = Color.Black;
// Look through all sensors and start the first connected one.
// This requires that a Kinect is connected at the time of app startup.
// To make your app robust against plug/unplug,
// it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit (See components in Toolkit Browser).
foreach (var potentialSensor in KinectSensor.KinectSensors)
{
if (potentialSensor.Status == KinectStatus.Connected)
{
this.sensor = potentialSensor;
break;
}
}
if (null != this.sensor)
{
// Turn on the depth stream to receive depth frames
this.sensor.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
// Allocate space to put the depth pixels we'll receive
this.depthPixels = new DepthImagePixel[this.sensor.DepthStream.FramePixelDataLength];
// Add an event handler to be called whenever there is new depth frame data
this.sensor.DepthFrameReady += this.SensorDepthFrameReady;
sensor.SkeletonStream.Enable();
// Start the sensor!
try
{
this.sensor.Start();
//sensor.ColorStream.CameraSettings.BacklightCompensationMode = BacklightCompensationMode.CenterOnly;
}
catch (IOException)
{
this.sensor = null;
}
}
//if (null == this.sensor)
//{
// this.statusBarText.Text = Properties.Resources.NoKinectReady;
//}
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
if (null != this.sensor)
{
this.sensor.Stop();
}
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// TODO: Add your update logic here
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
pixels.SetData<Color>(pixelData_clear);
spriteBatch.Begin();
spriteBatch.Draw(pixels, new Vector2(0, 0), null, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
/// <summary>
/// Event handler for Kinect sensor's DepthFrameReady event
/// </summary>
/// <param name="sender">object sending the event</param>
/// <param name="e">event arguments</param>
private void SensorDepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame != null)
{
// Copy the pixel data from the image to a temporary array
depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);
// Get the min and max reliable depth for the current frame
int minDepth = depthFrame.MinDepth;
int maxDepth = depthFrame.MaxDepth;
//Get the depth delta
int depthDelta = maxDepth - minDepth;
// Convert the depth to RGB
for (int depthIndex = 0; depthIndex < depthPixels.Length; depthIndex++)
{
// Get the depth for this pixel
short depth = depthPixels[depthIndex].Depth;
//convert to a range that will fit in one byte
byte intensity = 0;
if (depth >= minDepth && depth <= maxDepth)
{
intensity = (byte)(byte.MaxValue - ((depth * byte.MaxValue) / depthDelta));
}
//set the color
pixelData_clear[depthIndex].R = intensity;
pixelData_clear[depthIndex].G = intensity;
pixelData_clear[depthIndex].B = intensity;
}
}
}
}
}
}
|
0b5510cf98869a561e790ff93c4c6002c183b5ba
|
[
"C#"
] | 1
|
C#
|
dmanning23/DepthBasics_KinectMonogame
|
58d66f8124d66a949ceaa7c932b213b19090646e
|
19accdaecab5620515e305a13a8baa7bd9175f3f
|
refs/heads/master
|
<file_sep>const gulp = require('gulp');
const elm = require('gulp-elm');
const flatten = require('gulp-flatten');
gulp.task('default', ['elm', 'html']);
gulp.task('elm', _ => {
return gulp.src('src/frontend/Main.elm')
.pipe(elm())
.pipe(gulp.dest('build/'));
});
gulp.task('html', _ => {
return gulp.src(['./src/frontend/index.html', './src/frontend/styles.css'])
.pipe(flatten())
.pipe(gulp.dest('./build'));
});
|
8b606f75d0899c39c2e7c538f2fcf356d84a0bae
|
[
"JavaScript"
] | 1
|
JavaScript
|
ryantriangles/disc-log
|
40312cd5aa54ad9730c28f8c78ca53b7c83ca38f
|
f90323ef18264a4935792c441ee01f75420f9bd9
|
refs/heads/master
|
<file_sep>use_frameworks!
platform :ios, '8.0'
target 'KYUtilityKit_Example' do
pod 'KYUtilityKit', :path => '../'
target 'KYUtilityKit_Tests' do
inherit! :search_paths
end
end
|
b2fe631698f73bc04eda1301a0ce804ce2f88ce8
|
[
"Ruby"
] | 1
|
Ruby
|
echoingtech/KYUtilityKit
|
890a45a8bd48ab4c610c644a6713ba49b9cf8fd2
|
2f9e92298aeb27ca4982265e8ecc98c128106c3a
|
refs/heads/master
|
<file_sep>// Generated by BUCKLESCRIPT VERSION 4.0.1100, PLEASE EDIT WITH CARE
'use strict';
var Reprocessing = require("/Users/chihching/reprocessing-fruit-ninja/node_modules/reprocessing/lib/js/src/Reprocessing.js");
Reprocessing.hotreload(undefined, "src/index.re");
/* Not a pure module */
|
ddf555bdf5641ff8140ddb9bd1a2c338a5c60c66
|
[
"JavaScript"
] | 1
|
JavaScript
|
eyeccc/reprocessing-fruit-ninja
|
74641484afb1314898f4244fa29f9e1c1883b647
|
fbf5584e404beb3a6634325df62a8e05f2a8a091
|
refs/heads/master
|
<file_sep>#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
CREATE USER avenuecode WITH PASSWORD '<PASSWORD>' NOCREATEDB;
CREATE DATABASE avenuecode_database OWNER avenuecode;
EOSQL
<file_sep>package com.avenuecode.entities.mappers;
import com.avenuecode.dtos.RoutesDto;
import com.avenuecode.entities.Routes;
import com.avenuecode.entities.mappers.commons.BeanMapper;
import org.mapstruct.Mapper;
@Mapper
public interface RoutesBeanMapper extends BeanMapper<Routes, RoutesDto> {
}
<file_sep>package com.avenuecode.mediators;
import com.avenuecode.AvenueCodeAssessmentApplication;
import com.avenuecode.dtos.RoutesDto;
import com.avenuecode.dtos.RoutesDtoFixture;
import com.avenuecode.entities.Graph;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AvenueCodeAssessmentApplication.class)
@ActiveProfiles("test")
public class GraphMediatorIT {
@Autowired
private GraphMediator mediator;
//~-- createGraph
@Test
public void createTest() {
List<RoutesDto> routesDtos = RoutesDtoFixture.newRoutesDtoFixtureList();
assertThat(mediator.createGraph(routesDtos)).isNotNull();
}
//~-- getGraph
@Test
public void getGraphTest() {
List<RoutesDto> routesDtos = RoutesDtoFixture.newRoutesDtoFixtureList();
Long id = mediator.createGraph(routesDtos).getId();
assertThat(mediator.getGraph(id)).isNotNull();
}
}<file_sep>create sequence graph_seq start 1 increment 1;
create sequence route_seq start 1 increment 1;
create table graph (graph_id int8 not null, primary key (graph_id));
create table routes (id int8 not null, distance int4 not null, source varchar(255) not null, target varchar(255) not null, graph_id int8, primary key (id));
alter table routes add constraint FKdwya4k3o8bd2hum4qvdmhto0y foreign key (graph_id) references graph;<file_sep>package com.avenuecode.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PathsDto {
private List<String> path;
}
<file_sep>package com.avenuecode.exceptions.handlers.dtos;
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class ErrorDto {
private String message;
}
<file_sep>package com.avenuecode.dtos;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RoutesDto {
private String source;
private String target;
private int distance;
}
<file_sep>package com.avenuecode;
import com.avenuecode.rest.controllers.commons.RestControllerIT;
import org.junit.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class AvenueCodeAssessmentApplicationIT extends RestControllerIT {
@Test
public void httpStatusOkToHealhCheck() throws Exception {
mockMvc.perform(get("/health")
.contentType(contentType))
.andExpect(status().isOk());
}
}<file_sep>package com.avenuecode.entities.mappers;
import com.avenuecode.dtos.RoutesDto;
import com.avenuecode.entities.Routes;
import com.avenuecode.entities.RoutesFixture;
import org.junit.Before;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class RoutesBeanMapperTest {
private RoutesBeanMapper mapper;
@Before
public void before() {
this.mapper = Mappers.getMapper(RoutesBeanMapper.class);
}
@Test
public void adaptAllFields() {
Routes routes = RoutesFixture.newRoutesFixtureAB();
RoutesDto routesDto = mapper.toTarget(routes);
assertThat(routesDto.getSource()).isEqualTo(routes.getSource());
assertThat(routesDto.getTarget()).isEqualTo(routes.getTarget());
assertThat(routesDto.getDistance()).isEqualTo(routes.getDistance());
}
}<file_sep>package com.avenuecode.rest.dtos;
import java.util.Arrays;
import java.util.List;
public class PathRouteDtoFixture {
public static List<PathRouteDto> pathRoutes2Stops() {
return Arrays.asList(routeAC1(), routeAC2());
}
public static List<PathRouteDto> pathRoutes3Stops() {
return Arrays.asList(routeAC1(), routeAC2(), routeAC3());
}
public static PathRouteDto routeAC1() {
return PathRouteDto.builder()
.distance(9)
.path(Arrays.asList("A", "B", "C"))
.found(true)
.build();
}
public static PathRouteDto routeAC2() {
return PathRouteDto.builder()
.distance(13)
.path(Arrays.asList("A", "D", "C"))
.found(true)
.build();
}
public static PathRouteDto routeAC3() {
return PathRouteDto.builder()
.distance(14)
.path(Arrays.asList("A", "E", "B", "C"))
.found(true)
.build();
}
}<file_sep>FROM java:8
ADD target/java-challenge.jar /
EXPOSE 8080
EXPOSE 8787
ENTRYPOINT java -Dspring.profiles.active=${PROFILE} -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n -Dserver.port=8080 -jar java-challenge.jar<file_sep>package com.avenuecode.entities.mappers;
import com.avenuecode.entities.Graph;
import com.avenuecode.entities.GraphFixture;
import com.avenuecode.rest.dtos.GraphDto;
import org.junit.Before;
import org.junit.Test;
import org.mapstruct.factory.Mappers;
import static org.assertj.core.api.Assertions.assertThat;
public class GraphBeanMapperTest {
private GraphBeanMapper mapper;
@Before
public void before() {
this.mapper = Mappers.getMapper(GraphBeanMapper.class);
}
@Test
public void adaptAllFields() {
Graph graph = GraphFixture.newGraphFixture();
GraphDto graphDto = mapper.toTarget(graph);
assertThat(graph.getId()).isEqualTo(graphDto.getId());
assertThat(graphDto.getRoutes()).isNotNull();
assertThat(graphDto.getRoutes()).isNotEmpty();
}
}<file_sep>package com.avenuecode.services;
import com.avenuecode.dtos.RoutesDto;
import com.avenuecode.entities.Graph;
import com.avenuecode.entities.mappers.RoutesBeanMapper;
import com.avenuecode.exceptions.GraphCreationException;
import com.avenuecode.exceptions.GraphNotFoundException;
import com.avenuecode.repositories.GraphRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class GraphService {
@Autowired
private GraphRepository repository;
@Autowired
private RoutesBeanMapper routesMapper;
public Graph create(List<RoutesDto> routes) {
return Optional.of(repository.save(buildGraph(routes)))
.orElseThrow(() -> new GraphCreationException("An error occurred when trying to create graph."));
}
public Graph get(Long id) {
return Optional.ofNullable(repository.findOne(id))
.orElseThrow(() -> new GraphNotFoundException("There is no graph present on database"));
}
private Graph buildGraph(List<RoutesDto> routes) {
return Graph.builder()
.routes(routesMapper.fromSource(routes))
.build();
}
}
<file_sep>package com.avenuecode.rest.dtos;
import com.avenuecode.dtos.RoutesDtoFixture;
public class GraphDtoFixture {
public static GraphDto newGraphDtoFixture() {
return GraphDto.builder()
.id(1L)
.routes(RoutesDtoFixture.newRoutesDtoFixtureList())
.build();
}
}
|
661b9e60618c0673c31d81a8c4742c204a0f99f6
|
[
"Java",
"SQL",
"Dockerfile",
"Shell"
] | 14
|
Shell
|
alveesrenan/lannister-carriage-services
|
fa9e797056d603b5a5e2e85d4c9115c4152812fa
|
e1859a410feb2994e9f1ea88a5a4b686a476ceec
|
refs/heads/master
|
<file_sep># !/usr/bin/env python
# Created by: Manuel
# Created on: November 2019
# this is "The Hello World" program on the PyBadge
def main():
# this function prints to the screen and console
print("\n\n\n") # 3 blank lines
print("Hello, World")
while True:
# repeat forever, or you turn it off!
pass # jsut a place holder
if __name__ == "__main__":
main()
|
7460ae4fe1eedb06e1e37ed2673c9fed9c970ee7
|
[
"Python"
] | 1
|
Python
|
manuel-garcia-yuste/ICS3UR-FP1
|
1ba9e9121accc092141527059fba0a584c69a260
|
a8442a5bc2c2187d4f3f3f1f8f3bc2b6588ddbbc
|
refs/heads/master
|
<repo_name>it-academy-htp/demo-samples<file_sep>/GlobalMotorcycleServiceModule/MotorcycleConsole/Program.cs
using GlobalMotorcycleServiceModule;
using System;
namespace MotorcycleConsole
{
class Program
{
static void Main(string[] args)
{
MotorcycleService service = new MotorcycleService();
MyConsoleMotorcycle myConsoleMotorcycle = new MyConsoleMotorcycle("Honda");
//Let's Drive
myConsoleMotorcycle.StartEngine();
myConsoleMotorcycle.Move(1_000);
myConsoleMotorcycle.Move(5_000);
myConsoleMotorcycle.StopEngine();
myConsoleMotorcycle = null;
service = null;
//Let's Drive one more time
service = new MotorcycleService();
myConsoleMotorcycle = new MyConsoleMotorcycle("Honda");
myConsoleMotorcycle.StartEngine();
myConsoleMotorcycle.Move(1_000);
myConsoleMotorcycle.Move(5_000);
myConsoleMotorcycle.StopEngine();
myConsoleMotorcycle = null;
service = null;
//Let's Drive one more time
service = new MotorcycleService();
myConsoleMotorcycle = new MyConsoleMotorcycle("Honda");
myConsoleMotorcycle.StartEngine();
}
#region CustomLogic
static void GoToService(int totalDistance)
{
Console.WriteLine($"Time to go moto Service. Current Distance of your bike: {totalDistance}");
}
#endregion
}
}
<file_sep>/GlobalMotorcycleServiceModule/MotorcycleConsole/MyConsoleMotorcycle.cs
using GlobalMotorcycleServiceModule;
using System;
using System.Collections.Generic;
using System.Text;
namespace MotorcycleConsole
{
sealed class MyConsoleMotorcycle
{
public string Model { get; set; }
public static int Odometer { get; set; }
public int DailyDistance { get; set; }
public MyConsoleMotorcycle()
{
}
public MyConsoleMotorcycle(string name)
{
Model = name;
}
public void StartEngine()
{
Console.WriteLine();
Console.WriteLine("Engine started.");
}
public void Move(int distance)
{
DailyDistance += distance;
Console.WriteLine($"Move to {distance}km.");
}
public void StopEngine()
{
Odometer += DailyDistance;
MotorcycleService.TotalDistance += Odometer;
Console.WriteLine("Engine stopped.");
Console.WriteLine($"Total distance: {Odometer}km.");
}
}
}
<file_sep>/GlobalMotorcycleServiceModule/GlobalMotorcycleServiceModule/MotorcycleService.cs
using System;
namespace GlobalMotorcycleServiceModule
{
public delegate void MotoServiceDelegate(int totalDistance);
public class MotorcycleService
{
public static int TotalDistance { get; set; }
public MotorcycleService()
{
CheckDistance();
}
void CheckDistance()
{
if (TotalDistance >= 10_000)
{
NotifyAboutService();
}
}
private void NotifyAboutService()
{
//TODO: invoke notifucation to appropriate motocycle
throw new NotImplementedException();
}
}
}
|
8beb655ab43a173c247de5221f2f148745a48a61
|
[
"C#"
] | 3
|
C#
|
it-academy-htp/demo-samples
|
162b17821c961f4c41148418058f84775e34e433
|
f1804a8035a459c7860ad9f273608acce91ca390
|
refs/heads/master
|
<file_sep>SPA made with JS, HTML5, CSS3(SCSS). JS code is written in the "older version" just to make it work on IE but modern one is also in the js file but commented out :)
Page is fully responsive.
<file_sep>
'use strict';
//gallery handler
(function () {
var currentImage = document.querySelectorAll('.main-img img');
var images = document.querySelectorAll('.imgs');
images = [].slice.call(images);
images.forEach(function(element) {
element.addEventListener('click', function(e) {
var boxNumber = this.className.slice(-1)-1;
if(e.target.nodeName === "IMG") {
currentImage[boxNumber].src = e.target.src;
};
});
});
})();
//smooth scroll
(function($) {
$(document).ready(function(){
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
var targetOffset = $(hash).offset().top - 80;
if(hash ==="#aboutUs"){
targetOffset += 80;
}
$('html, body').animate({
scrollTop: targetOffset
}, 800, function(){
});
}
});
});
})(jQuery);
// gallery switcher
(function(){
var gallerySection = document.querySelector('.products');
gallerySection.addEventListener('click',function(e){
var select = document.querySelector('.select-active');
var title = document.querySelector('.select-title');
var selectList = document.querySelector('.select');
if(e.target === select && !(e.target.classList.contains('clicked'))){
select.querySelector('.triangle').classList.toggle('clicked');
select.querySelector('.triangle').innerHTML = "▲";
selectList.style.display = 'block';
} else {
select.querySelector('.triangle').innerHTML = "▼";
selectList.style.display = 'none';
}
var options = selectList.querySelectorAll('.select-option');
for ( var i = 0 ; i < options.length ; i++ ){
options[i].addEventListener('click', function () {
title.innerHTML = this.innerHTML;
for ( var i = 0 ; i < options.length ; i++){
if( this === options[i]){
changeGallery(i);
}
}
})
}
function changeGallery (index) {
var galleries = document.querySelectorAll('.galleryWrapper');
for ( var i = 0 ; i < galleries.length ; i++){
if (i == index) {
galleries[i].className = "galleryWrapper active";
} else {
galleries[i].className = "galleryWrapper";
}
}
}
})
})();
//gallerySwitcher desktop
(function(){
var galleryCategories = document.querySelectorAll('.gallerySwitcher ul li');
var galleryWrapper = document.querySelectorAll('.galleryWrapper');
galleryCategories = [].slice.call(galleryCategories);
galleryCategories.forEach(function(singleCategory,i) {
singleCategory.addEventListener('click', function (){
galleryWrapper = [].slice.call(galleryWrapper);
galleryWrapper.forEach(function(singleBox) {
return singleBox.classList.remove('active');
})
galleryWrapper[i].classList.add('active');
})
})
})();
//activated category underline
(function(){
var galleryCategories = document.querySelectorAll('.gallerySwitcher ul li');
galleryCategories = [].slice.call(galleryCategories);
galleryCategories.forEach(function(singleCategory) {
singleCategory.addEventListener('click', function(){
galleryCategories.forEach(function(activatedCategory){
activatedCategory.classList.remove("currentlyActive");
})
singleCategory.classList.add("currentlyActive");
})
})
})();<file_sep>
'use strict';
//Function responsible for class addition
(function () {
const nav = document.querySelector('.navbar');
window.addEventListener('scroll',function () {
if(window.pageYOffset > 0){
nav.classList.add('sticky');
} else{
nav.classList.remove('sticky');
}
});
})();
//MobileMenu handler
(function () {
var hamburger = document.querySelector('.hamburger');
var nav = document.querySelector('.navbar');
var toggleMenu = function toggleMenu(e) {
var menuList = document.querySelector('.menuList');
if (!menuList.classList.contains('mobile') && e.target == hamburger) {
menuList.classList.add('mobile');
hamburger.classList.add('animatedMobileMenu');
} else {
menuList.classList.remove('mobile');
hamburger.classList.remove('animatedMobileMenu');
}
};
document.body.addEventListener('click', toggleMenu);
})();
|
b824d8374f5b9efd3130dd909483c24ae7dbc4a9
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
AdamKniec/newRegosteel
|
6374602d8b1938136c5dab77471423c96528655b
|
bdb58c1c2e86a113faaf48e1c85bd19b81a0d75b
|
refs/heads/master
|
<file_sep># Autoform jQuery Knob
This is a simple integration of the excellent [jQuery Knob](https://github.com/aterrien/jQuery-Knob/) plugin for Meteor [Autoform](https://github.com/aldeed/meteor-autoform).
## Installation
meteor add jameslefrere:autoform-jquery-knob
## Schema
An example field in the form's schema:
height:
type: Number
optional: true
decimal: true
min: 0
max: 250
autoform:
type: "knob"
step: 0.5
angleOffset: 20
...etc.
##Options
Behaviors:
* min : min value | default=0.
* max : max value | default=100.
* step : step size | default=1.
* angleOffset : starting angle in degrees | default=0.
* angleArc : arc size in degrees | default=360.
* stopper : stop at min & max on keydown/mousewheel | default=true.
* readOnly : disable input and events | default=false.
* rotation : direction of progression | default=clockwise.
UI:
* cursor : display mode "cursor", cursor size could be changed passing a numeric value to the option, default width is used when passing boolean value "true" | default=gauge.
* thickness : gauge thickness.
* lineCap : gauge stroke endings. | default=butt, round=rounded line endings
* width : dial width.
* displayInput : default=true | false=hide input.
* displayPrevious : default=false | true=displays the previous value with transparency.
* fgColor : foreground color.
* inputColor : input value (number) color.
* font : font family.
* fontWeight : font weight.
* bgColor : background color.
Thanks to https://github.com/aterrien and https://github.com/aldeed!<file_sep>Package.describe({
name: "jameslefrere:autoform-jquery-knob",
summary: "jQuery Knob input type for Autoform",
git: "https://github.com/jameslefrere/meteor-autoform-jquery-knob.git",
version: "0.1.0"
});
Package.onUse(function(api) {
api.versionsFrom("METEOR@1.0");
api.use(["jquery", "coffeescript", "templating", "aldeed:autoform@4.2.2"], "client");
api.addFiles([
"lib/jQuery-Knob/js/jquery.knob.js",
"afKnob.html",
"afKnob.coffee"
], "client");
});
|
cd52bdd0048ae956fcd69daa5dd2eb6d7099f62e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
JamesLefrere/meteor-autoform-jquery-knob
|
922d9580bf70a6a196ad8f8e17279a04b761035b
|
87fb08dc0e752a2448c4d7da2f53c3833d9e5443
|
refs/heads/master
|
<file_sep>const arr = [0, 10, 3, 5];
const number = document.getElementById("number");
const send = document.getElementById("send");
const showAnswer = document.querySelector("#answer");
let index;
send.addEventListener("click", function () {
showAnswer.innerHTML = "";
for (var i = 0; i < arr.length; i++) {
if (arr[i] === parseInt(number.value)) {
index = "the number is located on index " + i;
}
}
if (index === undefined) {
showAnswer.innerHTML = "not found"
} else {
showAnswer.innerHTML = index;
}
number.value = "";
});
<file_sep># linear-search
Linear search is an algorithm that looks through your data structure such as an array
until it finds the value you are looking for.
For Example lets say you have an array:
var arr = [0, 10, 3, 5].
Now lets say we want to get the value of 3.
well if we do a Linear search we will go through every single number in the array
until we find the the number 3.
now we can get the index.
we can use a for loop for this.
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 3) {
return i
or
return arr.indexOf(arr[i])
}
}
this will return the index of the number we are looking for
|
e75f64ef8cec09459a3e5ec59ca59af8a3080428
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
colorlessenergy/linear-search
|
125f2112644ac5f511bc2e82b2a9b10415d51f5e
|
900e912dbd4f731046c9c75bb59e707e6a857a03
|
refs/heads/master
|
<file_sep>var React = require('react');
module.exports = React.createClass({
getImage: function() {
return 'img/products/' + this.props.data.id + '.png';
},
getTitle: function() {
return this.props.data.title;
},
getPrice: function() {
return this.props.data.currencyFormat + ' ' + this.props.data.price.toFixed(2).replace(".", ",");
},
getInstallments: function() {
var installments = this.props.data.installments;
if (installments <= 1) {
return '';
}
var price = Math.ceil(this.props.data.price / this.props.data.installments * 100) / 100;
return 'ou ' + installments + ' X de ' + this.props.data.currencyFormat + ' ' + price.toFixed(2).replace(".", ",");
},
render: function() {
var image = this.getImage();
var title = this.getTitle();
var price = this.getPrice();
var installments = this.getInstallments();
return (
<div className="showcaseProduct" onClick={this.props.onClick}>
<div className="productImage">
<img src={image} />
</div>
<div className="productTitle">
{title}
</div>
<div className="productPrice">
{price}
</div>
<div className="productInstallments">
{installments}
</div>
</div>
);
}
});
<file_sep># Stack & Tools
## [Node.js](https://nodejs.org/)
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
## [npm](https://www.npmjs.com/)
npm is the package manager for JavaScript. Find, share, and reuse packages of code from hundreds of thousands of developers — and assemble them in powerful new ways.
## [Express](http://expressjs.com/)
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
## [webpack](https://webpack.github.io/)
webpack is a module bundler, it takes modules with dependencies and generates static assets representing those modules.
## [Babel](https://babeljs.io/)
Babel is a compiler for writing next generation JavaScript.
## [React](https://facebook.github.io/react/index.html)
React is a JavaScript library for building user interfaces.
## [jQuery](https://jquery.com/)
jQuery is a fast, small, and feature-rich JavaScript library.
## [EventEmitter](https://github.com/Olical/EventEmitter)
Event based JavaScript for the browser.
## [lodash](https://lodash.com/)
A modern JavaScript utility library delivering modularity, performance, & extras.
<file_sep># TODO
- [x] Create a static server in order to access the JSON data provided.
- [x] Retrieve JSON data in front-end.
- [x] Render a list of products.
- [x] Add items to cart.
- [x] Remove items from cart.
- [x] See the products added to the cart.
- [x] Persist data on page reload.
- [x] Create build/run instructions.
- [ ] Slice images from PSD.
- [ ] Create styles for the layout.
- [ ] Add unit tests.
|
d0c38767c1fa3d0a432798a622cc44321365b545
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
fpedroso/front-end-recruitment
|
73827dec4ec946e979eee251294c93802c4cb20c
|
af951bb75057a62f4f539d7949242045a6b07a80
|
refs/heads/master
|
<file_sep>import React from 'react';
import ButtonSet from 'components/ButtonSet';
import inputHandler from 'actions/inputHandler';
import logMessage from 'actions/logMessage';
/*
** Creates a connected set of buttons from the given set of internal values and display values
*/
const createButtonSet = (buttons, spacing = false) => {
return (
<ButtonSet
buttons={buttons}
spacing={spacing}
onClick={(label, value) => {
return (dispatch) => {
dispatch(logMessage({ author: 'YOU', body: label }));
dispatch(inputHandler(value));
};
}}
/>
);
}
export default createButtonSet;<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { Checkbox } from 'react-bootstrap';
let CheckboxComponent = ({ label, value, isChecked, onClick, dispatch }) => {
return (
<Checkbox
type='checkbox'
value={value}
checked={isChecked}
onChange={() => dispatch(onClick(value))}
>
{label}
</Checkbox>
);
};
export default connect()(CheckboxComponent);<file_sep>/*
** Dispatch this to add a message to the log
*/
const logMessage = (message) => {
return (dispatch) => {
if ((typeof message.body === 'string' && message.body !== '') || typeof message.body !== 'string') {
console.log(message.author + ' sent a message.');
dispatch({
type: 'LOG_MESSAGE',
value: message
});
}
};
};
export default logMessage;<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { Row, Col } from 'react-bootstrap';
const formatLog = (log) => {
let len = log.length;
return log.map((elem, index) => {
let offset = typeof elem.body === 'string' && elem.author === 'YOU' ? 1 : 0;
let size = typeof elem.body === 'string' ? 11 : 12;
let style = typeof elem.body === 'string' && elem.author === 'YOU' ? { textAlign:'right' } : { textAlign:'left'};
let message = (
<div
style={{
border: typeof elem.body === 'string' ? '1px solid #2797b7' : 'none',
borderRadius:'5px',
backgroundColor: elem.author === 'TILYBOT' ? 'white' : '#2797b7',
color: elem.author === 'TILYBOT' ? 'black' : 'white',
padding:'5px',
marginTop:'2px',
wordWrap:'break-word',
whiteSpace:'pre-wrap'
}}
>
{elem.body}
</div>
);
if (typeof elem.body === 'string') {
message = (
<div style={{ display:'inline-block', maxWidth:'100%' }} >
<img src={elem.author === 'TILYBOT' ? 'submarine.png' : 'blank_profile.png'} alt={'No img found :('} style={{ height:'20px', width:'auto' }} />
<br />
{message}
</div>
);
}
return (
<Row key={len - index}>
<Col xsOffset={offset} smOffset={offset} mdOffset={offset} xs={size} sm={size} md={size} style={{ padding:'5px 25px' }}>
<div style={style}>{message}</div>
</Col>
</Row>
);
});
}
class LogComponent extends React.Component {
componentDidUpdate() {
this.refs.log.scrollTop = this.refs.log.scrollHeight;
}
render() {
return (
<div ref='log' style={{ overflowY:'scroll', overflowX:'hidden', height:'90%' }}>{formatLog(this.props.log)}</div>
);
}
}
export default connect(
(state) => { return { log: state.log }; },
(dispatch) => { return { dispatch }; }
)(LogComponent);<file_sep>/*
** Set containing values corresponding to the checkboxes that are checked
**
** Checkbox is toggled when TOGGLE_CHECK is dispatched
*/
const checked = (state, action) => {
if (typeof state === 'undefined')
return [];
if (action.type === 'TOGGLE_CHECK') {
if (state.findIndex((elem) => elem === action.value) === -1)
return [...state, action.value];
else
return state.filter((elem) => elem !== action.value);
} else if (action.type === 'CLEAR_CHECKED') {
return [];
}
return state;
};
export default checked;<file_sep>export default [
'TILR_WELCOME',
'JOB_FAMILY',
'OCCUPATIONS',
'WORK_TYPE',
'DISTANCE',
'TRANSPORTATION',
'DISCOVERY',
'APP_OVERVIEW',
'BACKGROUND',
'PAYROLL',
'TILR_CLOSING',
].map((elem) => {
return { eventName: elem, params: {} };
});<file_sep>import inputHandler from 'actions/inputHandler';
import logMessage from 'actions/logMessage';
/*
** The onSubmit handler for text input. Dispatch this within the onSubmit function in the text input component.
*/
const textSubmitHandler = (input) => {
return (dispatch) => {
dispatch(logMessage({
author: 'YOU',
body: input
}));
dispatch(inputHandler(input));
};
};
export default textSubmitHandler;<file_sep>import api from "api";
import nextAction from "actions/nextAction";
import logMessage from "actions/logMessage";
import getTilybotPayload from "helpers/getTilybotPayload";
import createButtonSet from "helpers/createButtonSet";
import createCheckboxForm from "helpers/createCheckboxForm";
/*
** Dispatch this with the user's input when the user submits input
*/
const inputHandler = (input) => {
return async (dispatch, getState) => {
try {
if (input !== '') {
let res = await api.textRequest(input, {
contexts: [
{
name: "creds",
parameters: getState().user,
lifespan: 1
}
]
});
if (res.data.status.code !== 200)
throw new Error("Api.Ai didn't return a proper response; Check if the webhook URL is correct!");
let payload = getTilybotPayload(res.data.result.fulfillment);
dispatch({ type: 'ENABLE_TEXT' });
if (payload.hasOwnProperty("skills")) {
payload.skills.forEach((elem) => {
dispatch({
type: "ENQUEUE_FRONT",
value: {
eventName: "RATE_SKILL",
params: {
skill: elem
}
}
});
});
}
if (payload.hasOwnProperty("messages")) {
payload.messages.forEach((elem) => {
let body;
switch(elem.type) {
case "text":
body = elem.body;
break;
case "buttons-stack":
body = createButtonSet(elem.options, true);
dispatch({ type: 'DISABLE_TEXT' });
break;
case "buttons-row":
body = createButtonSet(elem.options, false);
dispatch({ type: 'DISABLE_TEXT' });
break;
case "checkbox":
body = createCheckboxForm(elem.options);
dispatch({ type: 'DISABLE_TEXT' });
break;
case "error":
body = elem.body;
console.log(JSON.stringify(res.data.result.parameters.error));
break;
default: break;
}
dispatch(logMessage({
author: "TILYBOT",
body
}));
});
}
if (payload.hasOwnProperty("next") && payload.next)
dispatch(nextAction());
}
} catch (err) {
console.log(err);
}
};
};
export default inputHandler;<file_sep>This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
You can find the most recent version of the guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
This is a sample client/front-end for tilybot. Documentation on response/payload formatting should be included in the `tilybot-webservice` README. Use the helper function `getTilybotPayload` to extract the payload from a response. The components should be fairly replaceable, with the attributes/props required being the only thing that must be consistent.
## Api.Ai
To make a request to Api.Ai, import `api`. The imported object has methods `textRequest` and `eventRequest`.
### textRequest(query[, data])
Calling `textRequest` will send a request with the given `query` to the Api.Ai agent. The response returned should contain a `tilybot` payload (something went wrong with the intent if not). Data to be passed along can include additional `contexts` (a `creds` context with user authentication info should usually be included).
### eventRequest(eventName[, data[, eventParams]])
Calling `eventRequest` will send a request and trigger an intent by the given `eventName`. The response returned should contain a `tilybot` payload (something went wrong with the intent if not). Data to be passed along can include additional `contexts` (a `creds` context with user authentication info should usually be included). Additional parameters can also be included in the `eventParams` parameter as a set of key-value pairs.
## Actions
### inputHandler(input)
Handles all of the processes that user input should entail (including sending a textRequest to Api.Ai and handling the response).
### logMessage(message)
Adds a message by `author` to the message log. `message` should have the following structure:
{
'author': "TILYBOT",
'body': "Hello world"
}
The `author` is either **TILYBOT** or **YOU**.
### nextAction()
If the received payload contains a `next` entry with value `true` then the next action queued up (if one exists) will be sent as an eventRequest immediately. Handling is otherwise the same as `inputHandler`.
### textSubmitHandler(input)
Adds the user's message to the message log and dispatched `inputHandler(input)` to handle the message.<file_sep>import React from 'react';
import { connect } from 'react-redux';
import nextAction from 'actions/nextAction';
import InputComponent from 'components/InputComponent';
import LogComponent from 'components/LogComponent';
class MessengerComponent extends React.Component {
componentDidMount() {
this.props.dispatch(nextAction());
}
render() {
return (
<div id='message-interface' style={{ height:'80vh' }}>
<LogComponent />
<InputComponent onSubmit={this.props.onSubmit} />
</div>
);
}
}
export default connect()(MessengerComponent);<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import ReduxThunk from 'redux-thunk';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Grid, Row, Col } from 'react-bootstrap';
import rootReducer from 'reducers';
import MessengerComponent from 'components/MessengerComponent';
import textSubmitHandler from 'actions/textSubmitHandler';
ReactDOM.render(
<Provider store={createStore(rootReducer, applyMiddleware(ReduxThunk))}>
<Grid style={{ padding:'50px' }}>
<Row>
<Col xsOffset={2} smOffset={2} mdOffset={3} xs={8} sm={8} md={6}>
<MessengerComponent onSubmit={textSubmitHandler} />
</Col>
</Row>
</Grid>
</Provider>,
document.getElementById('root')
);<file_sep>import React from 'react';
import ButtonComponent from 'components/ButtonComponent';
import { ButtonGroup } from 'react-bootstrap';
const createButtons = (buttons, onClick) => {
return buttons.map((elem) => (
<ButtonComponent
label={elem.label}
value={elem.value}
key={ typeof elem.value === 'string' ? elem.value : JSON.stringify(elem.value) }
onClick={onClick}
/>
));
}
const ButtonSet = ({ buttons, spacing, onClick }) => {
return (
<ButtonGroup vertical={spacing} block={spacing}>
{createButtons(buttons, onClick)}
</ButtonGroup>
);
};
export default ButtonSet;<file_sep>export default (fulfillment) => {
if (fulfillment.hasOwnProperty("data"))
return fulfillment.data.tilybot;
let messageObj = fulfillment.messages.find((elem) => elem.type === 4 && elem.payload.hasOwnProperty("tilybot"));
if (messageObj !== undefined)
return messageObj.payload.tilybot;
return {
messages: [
{
type: 'text',
body: fulfillment.speech
}
]
};
};<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { FormGroup, FormControl, InputGroup, Button, Glyphicon } from 'react-bootstrap';
const InputComponent = ({ textDisabled, onSubmit, dispatch }) => {
let input;
return (
<form onSubmit={(event) => {
event.preventDefault();
dispatch(onSubmit(input.value.trim()));
input.value = '';
}}
>
<FormGroup>
<InputGroup>
<FormControl
disabled={textDisabled}
inputRef={node => { input = node; }}
type="text" placeholder={textDisabled ? 'Use the buttons!' : "Say something!"}
/>
<InputGroup.Button>
<Button
disabled={textDisabled}
type='submit'
bsStyle='primary'
style={{ backgroundColor:'#2797b7', borderColor:'#1f7a93' }}
>
<Glyphicon glyph='send' />
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
</form>
);
};
export default connect(
(state) => { return { textDisabled: state.textDisabled }; },
(dispatch) => { return { dispatch }; }
)(InputComponent);<file_sep>import React from 'react';
import { connect } from 'react-redux';
import { Button } from 'react-bootstrap';
const ButtonComponent = ({ label, value, onClick, spacing = false, dispatch }) => {
return (
<Button
bsSize='sm'
onClick={(event) => {
event.preventDefault();
dispatch(onClick(label, value));
}}
block={spacing}
style={{ whiteSpace:'pre-wrap' }}
>
{label}
</Button>
);
};
export default connect()(ButtonComponent);<file_sep>import Axios from 'axios';
import { v4 } from 'uuid';
const QUERY = '/query?v=20150910';
const sessionId = v4();
const _apiaiClient = Axios.create({
baseURL: process.env.REACT_APP_API_URL,
timeout: process.env.REACT_APP_TIMEOUT,
headers: {
Authorization: 'Bearer 50f3c6c2097e46d4979c6efb5190b91d'
}
});
export default {
textRequest: async (query, data = {}) => _apiaiClient.post(
QUERY,
{
query: query,
lang:'en',
sessionId,
...data
}
),
eventRequest: async (eventName, data = {}, eventParams = {}) => _apiaiClient.post(
QUERY,
{
event: {
name: eventName,
data: eventParams
},
lang:'en',
sessionId,
...data
}
)
};<file_sep>import { combineReducers } from "redux";
import checked from "./checked";
import log from "./log";
import queue from "./queue";
import textDisabled from "./textDisabled";
import user from "./user";
export default combineReducers({ checked, log, textDisabled, queue, user });
|
01ee9290fea472dcef91744650803934219348b2
|
[
"JavaScript",
"Markdown"
] | 17
|
JavaScript
|
tilr-corp/tilybot-client
|
89bf58e62a9b8f1d681405f1d92aeb69b261fae7
|
2865c8f8734eba9ae29aa4afd62d0c42b0523cb0
|
refs/heads/master
|
<file_sep># DumpMash Collection Points Scrape from Pulse
Scrape garbage collection point location information from pulse article.
## Useage
Install scrapy and firebase_admin
```
pip install scrapy
pip install firebase_admin
```
clone the repository and make the necessary changes in the [pulse.py](pulselocations/spiders/pulse.py)
Lines 12 [channge to firebase service file json ] and 14 [replace with firebase database]
```
git clone https://github.com/isharaux/dumpmash-pulse-scrape.git
cd dumpmash-pulse-scrape
python scrapy crawl pulse
```
<file_sep># -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
import uuid
class PulseSpider(scrapy.Spider):
name = 'pulse'
allowed_domains = ['pulse.lk']
start_urls = ['https://www.pulse.lk/everythingelse/list-for-recyclers-in-sri-lanka/']
cred = credentials.Certificate('[FIREBASE SERVICE FILE]')
firebase_admin.initialize_app(cred, {
'databaseURL' : '[FIREBASE URL]'
})
def parse(self, response):
dis = []
entries = []
for districts in response.xpath('//p/span/strong/text()').extract():
result = ''.join([i for i in districts if not (i.isdigit() or i == ".")])
dis.append(result.lstrip())
yield {"title": result.lstrip()}
print("districts",dis)
for tbody_id,tbody in enumerate(response.xpath('//table/tbody').extract()):
header_read = False
for row_id,tr in enumerate(Selector(text = tbody).xpath('//tr').extract()):
tr_val = {"id":str(uuid.uuid4()),"latitude":0,"longitude":0,"imgPath":"../../../../assets/img/Environmental-awareness.png","collector":"","contactDetails":[], "address":"","city":"","collectableMaterials":[],"district":"","contactPerson":[], "province":"Western"}
if header_read:
for td_id, td in enumerate(Selector(text = tr).xpath('//td').extract()):
spaned = []
for span in enumerate(Selector(text = td).xpath('//span/text()').extract()):
spaned.append(span)
#print("span" + str(span) + " data id:" + str(td_id))
if td_id == 0:
tr_val["collector"] = span[1]
tr_val["district"] = dis[tbody_id]
elif td_id == 1:
if any(char.isdigit() for char in span[1]):
tr_val["contactDetails"].append({"contact":span[1]})
else:
tr_val["contactPerson"] = {"person":span[1]}
elif td_id == 2:
tr_val["address"] = span[1]
tr_val["city"] = span[1].split(" ")[len(span[1].split(" ")) - 1]
elif td_id == 3:
for material in span[1].split("/"):
tr_val["collectableMaterials"].append({"collectable_material":material})
print(tr_val)
entries.append(tr_val)
else:
header_read = True
root = db.reference()
new_user = root.child('collection').set(entries)
# tr_val.append(value)
# print("count:" + str(counter) + " value:" + value)
# if(len(tr_val) > 0):
# entry.append({"Institution": tr_val[0],"contact":tr_val[1],"address":tr_val[2],"material":tr_val[3],"district":dis[tbody_id]})
# yield {"Institution": tr_val[0],"contact":tr_val[1],"address":tr_val[2],"material":tr_val[3],"district":dis[tbody_id]}
|
ab5bf3afaf5667d9c6ec7cd0fd2d9ee8c852f253
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
arcslash/dumpmash-pulse-scrape
|
f4fe25e4b67bc9da3b6b4ee3a6053171cb86a5ee
|
fea8b35683ead0cba6bcb5aaf661fe7e58b506d9
|
refs/heads/master
|
<file_sep>/*
Template: Car Dealer - The Best Car Dealer Automotive Responsive HTML5 Template
Author: <EMAIL>
Version: 1.0
Design and Developed by: <EMAIL>
NOTE:
*/
/*================================================
[ Table of contents ]
================================================
:: Predefined Variables
:: Preloader
:: Mega menu
:: Search Bar
:: Owl carousel
:: Counter
:: Slider range
:: Countdown
:: Tabs
:: Accordion
:: List group item
:: Slick slider
:: Mgnific Popup
:: PHP contact form
:: Placeholder
:: Isotope
:: Scroll to Top
:: POTENZA Window load and functions
======================================
[ End table content ]
======================================*/
//POTENZA var
var POTENZA = {};
(function($){
"use strict";
/*************************
Predefined Variables
*************************/
var $window = $(window),
$document = $(document),
$body = $('body'),
$fullScreen = $('.fullscreen') || $('.section-fullscreen'),
$halfScreen = $('.halfscreen');
//Check if function exists
$.fn.exists = function () {
return this.length > 0;
};
/*************************
Full Screen
*************************/
POTENZA.screenSizeControl = function () {
if ($fullScreen.exists()) {
$fullScreen.each(function () {
var $elem = $(this),
elemHeight = $window.height();
if($window.width() < 768 ) $elem.css('height', elemHeight/ 0.9);
else $elem.css('height', elemHeight);
});
}
if ($halfScreen.exists()) {
$halfScreen.each(function () {
var $elem = $(this),
elemHeight = $window.height();
$elem.css('height', elemHeight / 1.5);
});
}
};
/****************************************************
POTENZA Window load and functions
****************************************************/
//Window load functions
$window.load(function () {
});
$window.resize(function() {
POTENZA.screenSizeControl();
});
//Document ready functions
$document.ready(function () {
POTENZA.screenSizeControl();
});
})(jQuery);
<file_sep><?php
session_start();
if(isset($_POST['name']) && isset($_POST['mail']) && isset($_POST['msg']))
{
$name=$_POST['name'];
$to=$_POST['mail'];
$message=$_POST['msg'];
if (!$name) {
$errmsg[] = '<p>Please enter Name</p>';
}
if (!$to) {
$errmsg[] = '<p>Please enter email address</p>';
}
else if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
$errmsg[] = '<p>Please enter a valid email address</p>';
}
if (!$message) {
$errmsg[] = '<p>Please enter Message</p>';
}
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$subject="New Contact";
$toEmail="<EMAIL>";
// More headers
$headers .= 'From: <<EMAIL>>' . "\r\n";
$msg="From : ".$name."<br/>";
$msg.="Email :".$to."<br/>";
$msg.="Message :".$message."<br/>";
if(empty($errmsg)){
if(mail($toEmail,$subject,$msg,$headers))
{
$result='<div class="alert alert-success"><p>Successful</p></div>';
$data = array(
'status' => 'success',
'msg' => $result
);
}
else
{
$result='<div class="alert alert-danger"><p>Mail is not send.Error Occured</p></div>';
$data = array(
'status' => 'error',
'msg' => $result
);
}
}
else
{
$errors=implode(' ',$errmsg);
$result='<div class="alert alert-danger">'.$errors.'</div>';
$data = array(
'status' => 'error',
'msg' => $result
);
}
echo json_encode($data);
}
?>
|
a66b74081c19341bb539bd325aea3315951af8b9
|
[
"JavaScript",
"PHP"
] | 2
|
JavaScript
|
mroloff09/landing_page
|
fa15103fd286676ef125c5742d7fb6a3df457144
|
62f3ef51c8a07b24cb5e273b56c8bfa5e7d127ad
|
refs/heads/master
|
<repo_name>eunhye4422/9.23<file_sep>/10.1/제이쿼리/js/script.js
$('.posts li').on('click',function(){
console.log('dpdpp')
var index = $(this).index();
$('.post_content div').eq(index).show();
$('.post_content div').eq(index).siblings().hide;
})
//var doc= document;
//var menu = doc.getElementById('menu').getElementsByTagName('li');
//
//var mainDis = doc.querySelector('.main').querySelectorAll('.page');
//console.log(mainDis[0])
//
//
//function mainDisplay(){
//
//}
//
//
//for (var i = 0; i < menu.length; i++){
//
// menu[i].addEventListener('click',function(){
// menu[i].style.background = "#fff";
//
//
// })
//
//}<file_sep>/원래download/react-project - 복사본/src/index.js
import React from 'react'; // react 쓸수 있는 환경 만들어줌
import ReactDOM from 'react-dom'; // jsx 사용하면 html 만들수 있게
//import App from './App'; //. ; 나
import Web from './Wep';
ReactDOM.render(<Web />,document.getElementById('root'));
//map, filter
//1. map
//var a = [10,20,30, 40];
//var nArr = [];
//
//for (var i = 0; i < a.length; i++){
//
// nArr.push(a[i]*2);
//
//}
//
//console.log(nArr);
//console.log(a);
// 매개변수 function의 첫번째 매개변수 : 해당값 두번째 매ㅐ변수 : 순서
//[10,20,30,40].map(function(v,i){
//var nArr = a.map(function(v,i){
//
// console.log(v);
// console.log(i);
//
// return v * 2;
//
//}); // nArr는 자연스럽게 배열됨
//es6문법
//const nArr = a.map((v,i)=> v * 2) // return밖에 없을 땐 return 안써도 된다
//2. filter
//var a = [10,20,30, 40];
//var nArr = a.filter(function(v,i){
//
// return v > 20; // test 조건을 반환한다.
//
//});
//const nArr = a.filter((v,i)=>v>20);
//
//console.log(nArr);
//console.log(a); // a가 새로운 것으로 바뀌는게 아니다.
//
<file_sep>/part5/noneReact/js/script.js
var doc= document;
//doc.getElementById('add').addEventListener('click',function(){
//
// var value = doc.getElementById('stack').value;
// var list = doc.getElementById('stackList');
//
// var item = doc.createElement('div');
// item.innerHTML = value;
//
//
// list.appendChild(item);
//})
//
//
//$('#add').on('click',function(){
//
//
// var value = $('#stack').val();
// var list = $('#stackList');
//
// var item = $('<div>');
// item.text(value);
//
// list.append(item);
//
//})
var item = ['HTML','CSS'];
function view(arr){
$('#stackList').empty().append(tag);
for (var i = 0; i > arr.length; i ++){
var tag = $('<div>').text(arr[i]);
arr[i];
}
}
$('#add').on('click',function(){
var value = $('#stack').val();
item.push(value);
view(item);
})
view(view);
//var item1 = $('<di>').text(item[0])
//var item1 = $('<di>').text(item[1])
//
//
//$('#stackList').append(item1);
//$('#stackList').append(item2);
//
//
//
//$('#add').on('click',function(){
//
// var value = $('#stack').val()
//
// item.push(value);
//
// var tag = $('<div>').text(value);
//
// var stack = $('#stackList').val()
//
//
//})<file_sep>/10.1/여러ㅓ페이지/js/script.js
var doc= document;
var menu = doc.getElementById('menu').getElementsByTagName('li');
var mainDis = doc.querySelector('.main').querySelectorAll('.page');
console.log(mainDis[0])
function mainDisplay(){
}
for (var i = 0; i < menu.length; i++){
menu[i].addEventListener('click',function(){
menu[i].style.background = "#fff";
})
}<file_sep>/README.md
# 9.23
9.23 study - node ..
<file_sep>/10.1리액트/router/src/components/Header.js
import React, {Component} from 'react';
import { NavLink } from 'react-router-dom';
class Header extends Component {
render(){
return (
<div className = "header">
<h1>my blog</h1>
<div className="menu">
<NavLink exact to="/"
activeClassName="active">홈</NavLink>
<NavLink to="/about/dmsgP"
activeClassName="active">소개</NavLink>
<NavLink to="/post"
activeClassName="active">포스트</NavLink>
</div>
</div>
)
}
}
export default Header;
|
cdfc409a985bd3f120540b789a96b0c418940e0b
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
eunhye4422/9.23
|
b45d52b3d36a4c9389ae76aee9b388e86b4893d9
|
45c7d171e3967a3923d36cc09655d17f5aea3aa4
|
refs/heads/master
|
<file_sep>def create_an_empty_array
my_array=Array.new
end
def create_an_array
my_array = Array.new(4) { |i| i += 1 }
end
def add_element_to_end_of_array(array, element)
array=array << element
end
def add_element_to_start_of_array(array, element)
array=array.unshift(element)
end
def remove_element_from_end_of_array(array)
array=array.pop
end
def remove_element_from_start_of_array(array)
array=array.shift
end
def retreive_element_from_index(array, index_number)
thing=array[index_number]
end
def retreive_first_element_from_array(array)
thing=array.first
end
def retreive_last_element_from_array(array)
thing=array.last
end
|
e6728d3c6624db640841adf95a9dfb7ea3be82ad
|
[
"Ruby"
] | 1
|
Ruby
|
lawrend/array-CRUD-lab-v-000
|
29519a88cfd94a686bf06bb39f78e368205b6593
|
8d0a57a1c01763da65d04ed61309bfba75ffe4c8
|
refs/heads/master
|
<file_sep>package com.jorge.exam;
public class Order {
String value = "t";
public int a(int a){ return 2;};
public int a(){ return 2;};
final String value1 = "1";
static String value2 = "2";
String value3 = "3";
final String value4;
{
//value1 = "d"; //No se puede, value1 es FINAL y ya está inicializada arriba.
value2 = "e"; //Aunque value2 sea estática, podemos meterla en este inicializador no estático
value3 = "f";
value4 = "g"; //Se puede, aunque sea final aún no se ha inicializado en ningún sitio
}
static {
//value1 = "h"; //No se puede, value1 es FINAL y ya está inicializada arriba
value2 = "i";
//value3 = "j"; //No se puede, value3 tendría que ser estática
//value4 = "k"; //No se puede, está inicializada ene l inicializador de instancia de arriba
}
{
value += "a";
}
{
value += "c";
}
public Order() {
value += "b";
}
public Order(String s) {
value += s;
}
public static void main(String[] args) {
Order order = new Order("f"); //Aquí order vale tacf pero value es tac
order = new Order(); //Aquí machacamos lo que valía order porun nuevo valor. value es tac y llama al constructor que añade una b a value, luego order es tacb
System.out.println(order.value); //RES: tacb
}
}
<file_sep>package com.jorge.main;
import com.jorge.animal.Swam;
//public class Bird extends Swam { //ERRORRRR ciclo detectado: Swam está heredando de Bird, luego Bird no puede heredar de Swam
public class Bird {
protected String text = "Quack";
protected void makeNoise(){
System.out.println("NOISE: " + text);
Swam swam = new Swam();
System.out.println(swam.text); //De esta forma se está accediendo a la porpiedad swam de esta misma clase (BIrd)
//a través de instanciar el objeto Swam, el cual tiene acceso a la prpiedad text de Bird porque hereda
//de Bird y text es protected.. Es decir, Bird accede a su propia propiedad text através de Swam
//System.out.println(swam.textSwam);//ERRORRRRRRRR desde Bird no podemos acceder a la propiedad protected de Swam textSwam ya que
//Bird ni hereda de Swam (es al revés, Swam hereda de Bird) ni están en el mismo paquete
}
}
|
f4f58567bfa0aca8bf8ea4a2c1af696e695cbafd
|
[
"Java"
] | 2
|
Java
|
Yorso/oca2
|
ddd45da07ee20df6053ea4dbac34d376a92cd65f
|
58f690efa7689cdf0c1722bc54dac50bfccbeb35
|
refs/heads/main
|
<file_sep>package com.husd.controller.project;
import com.husd.domain.Req;
import com.husd.domain.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.InputStreamSource;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.io.InputStream;
/**
* 应用管理
*/
@RestController
@RequestMapping("/project")
@Api(tags = "项目管理")
public class ProjectController {
@GetMapping("/listByProjectId")
@ApiOperation(value = "查询项目")
public Resp listByProjectId(@RequestBody Req req) {
return new Resp();
}
@PostMapping("/list/detail")
@ApiOperation(value = "查看项目详情")
public Resp listDetail(@RequestBody Req req) {
return new Resp();
}
@PutMapping("/add")
@ApiOperation(value = "新增项目")
public Resp add(@RequestBody Req req) {
return new Resp();
}
@PutMapping("/upload")
@ApiOperation(value = "上传")
public Resp upload(InputStreamSource inputStreamSource) {
return new Resp();
}
@PutMapping("/upload2")
@ApiOperation(value = "上传")
public Resp upload2(File file) {
return new Resp();
}
@PutMapping("/upload3")
@ApiOperation(value = "上传")
public Resp upload3(InputStream inputStream) {
return new Resp();
}
}
<file_sep>package com.husd.postman.domain.request;
public class PostmanHeader {
}
<file_sep>package com.husd.postman.domain.request;
public class PostmanBodyOptions {
private PostmanBodyOptionsRaw raw;
public PostmanBodyOptionsRaw getRaw() {
return raw;
}
public void setRaw(PostmanBodyOptionsRaw raw) {
this.raw = raw;
}
}
<file_sep>package com.husd.postman.util;
import com.husd.postman.domain.PostmanInfo;
import com.husd.postman.domain.PostmanItemWithFolder;
import com.husd.postman.domain.PostmanItemWithoutFolder;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.ArrayList;
import java.util.List;
public class PostmanUtil {
public static PostmanInfo postman_info_v2_1_0_json(String id, String name) {
PostmanInfo postmanInfo = new PostmanInfo();
postmanInfo.set_postman_id(id);
postmanInfo.setName(name);
postmanInfo.setSchema("https://schema.getpostman.com/json/collection/v2.1.0/collection.json");
return postmanInfo;
}
public static PostmanItemWithoutFolder postman_item(String name, String url, RequestMethod method, String json) {
PostmanItemWithoutFolder postmanItem = new PostmanItemWithoutFolder();
postmanItem.setName(name);
postmanItem.setRequest(PostmanRawUtil.postman_item_request_raw(url, method, json));
postmanItem.setResponse(new ArrayList<>());
return postmanItem;
}
public static PostmanItemWithFolder postman_item_folder(String folderName, String urlName, String url, RequestMethod requestMethod, String json) {
PostmanItemWithFolder postmanItem = new PostmanItemWithFolder();
postmanItem.setName(folderName);
List<PostmanItemWithoutFolder> item = new ArrayList<>();
item.add(postman_item(urlName, url, requestMethod, json));
postmanItem.setItem(item);
return postmanItem;
}
}
<file_sep>package com.husd.postman.domain;
/**
* v2.1.0
*/
public class PostmanItem {
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>package com.husd.postman.domain;
import java.util.List;
/**
* v2.1.0
* 这个是带目录的结构
*/
public class PostmanItemWithFolder extends PostmanItem {
private List<PostmanItemWithoutFolder> item;
public List<PostmanItemWithoutFolder> getItem() {
return item;
}
public void setItem(List<PostmanItemWithoutFolder> item) {
this.item = item;
}
}
<file_sep>server.port=8080
spring.profiles.active=local
swagger.enable=true<file_sep>package com.husd.domain;
public class Resp {
private String name;
private String age;
}
<file_sep>package com.husd.postman.domain;
import java.util.List;
/**
* v2.1.0
* 这个是不带目录的结构
*/
public class PostmanItemWithoutFolder extends PostmanItem {
private PostmanItemRequest request;
private List<PostmanItemResponse> response;
public PostmanItemRequest getRequest() {
return request;
}
public void setRequest(PostmanItemRequest request) {
this.request = request;
}
public List<PostmanItemResponse> getResponse() {
return response;
}
public void setResponse(List<PostmanItemResponse> response) {
this.response = response;
}
}
<file_sep># postman-tool
## 背景
后台开发人员写完接口之后,很多时候会去postman里模拟下接口请求,如果接口很多,
并且入参比较复杂,写这个就很麻烦,偶尔研究了一下postman的导入导出,发现可以用
工具来做,所以诞生了这个工具。
这个工具可以一键生成postman的文件,导入之后,就是你项目的所有的接口请求。
## 使用方法
前提是你的项目使用了spring boot和swagger。
建议在类上使用: @Api(tags = "应用管理")
在方法上使用 :@ApiOperation(value = "查询项目下的所有的应用")
- 复制com.husd.postman下的所有代码,到你的项目里
- 打开 PostmanControllerTest.java 修改一些报错,一般是应用的启动类名字不对, 执行generatePostmanFile这个方法
就会生成postman的导出
- 把生成的文件 测试postman工具01.json 导入postman就可以了。
## 注意事项
- 生成的文件,名字和目录都可以改,在PostmanControllerTest.java这个类里有注释。
- 稍做修改,这个类就可以请求系统里的所有接口,可以用做简单的冒烟测试。
- 缺少什么类,直接到pom.xml里去找就可以了,依赖不多。
- 默认生成的url,是用的postman的变量,需要设置下 your_url 即可

可以在这里设置变量:

- 导入:

我的postman是macos版本的,windows版本的postman是在文件菜单下,有个导入功能。
## 其它
开发团队的1个人生成完文件,就可以删除代码了,把生成的文件共享给大家即可。
欢迎关注我的博客: http://www.epoooll.com/
|
68f5b309930b82795c59a7c2d15cf8f89982241b
|
[
"Markdown",
"Java",
"INI"
] | 10
|
Java
|
husd/postman-tool
|
7b2eb3ef106caa0997a2e52429e3faadad12effb
|
84ffd4658f7a5edb8361c45c168068bd9d35e6ab
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import 'rxjs/add/operator/first';
@Component({
moduleId: module.id,
selector: 'seed-simple',
templateUrl: './simple.component.html',
styleUrls: ['./simple.component.scss']
})
export class SimpleComponent implements OnInit {
constructor(private translate: TranslateService) { }
ngOnInit() {
}
sayHello() {
// Hard coded hello message
// alert('One hello to rule them all');
// Hello message with translation
this.translate.get('simple.message').first()
.subscribe(message => alert(message));
}
}
<file_sep>import { Routes } from '@angular/router';
// app
import { HomeComponent } from './components/home/home.component';
import { SimpleComponent } from '../simple/simple.component';
export const HomeRoutes: Routes = [
{
path: 'home',
component: HomeComponent
},
{
path: 'simple',
component: SimpleComponent
},
{
path: 'about',
loadChildren: 'app/+about/about.module#AboutModule'
},
{
path: 'lazy',
loadChildren: 'app/lazy-cat/lazy-cat.module#LazyCatModule'
},
{
path: 'infinite',
loadChildren: 'app/infinite/infinite.module#InfiniteModule'
}
];
<file_sep>import { NgModule } from '@angular/core';
import { SHARED_MODULES, COMPONENT_DECLARATIONS } from './infinite.common';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
@NgModule({
imports: [
...SHARED_MODULES,
InfiniteScrollModule
],
declarations: [
...COMPONENT_DECLARATIONS
],
})
export class InfiniteModule { }
<file_sep>// vendor dependencies
import { TranslateModule } from '@ngx-translate/core';
// app
import { SharedModule } from '../shared';
import { RouterModule } from '../common';
import { InfiniteRoutes } from './infinite.routes';
import { InfiniteComponent } from './components/infinite/infinite.component';
import { ItemTemplateComponent } from './components/item-template/item-template.component';
export const SHARED_MODULES: any[] = [
SharedModule,
RouterModule.forChild(<any>InfiniteRoutes),
TranslateModule.forChild(),
];
export const COMPONENT_DECLARATIONS: any[] = [
InfiniteComponent, ItemTemplateComponent
];
<file_sep>import { Routes } from '@angular/router';
// app
import { LazyCatComponent } from './components/lazy-cat/lazy-cat.component';
export const LazyCatRoutes: Routes = [
{
path: '',
component: LazyCatComponent
}
];
<file_sep>import { Routes } from '@angular/router';
// app
import { InfiniteComponent } from './components/infinite/infinite.component';
export const InfiniteRoutes: Routes = [
{
path: '',
component: InfiniteComponent
}
];
<file_sep>import { Component, OnInit } from '@angular/core';
import { Observable as RxObservable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
@Component({
moduleId: module.id,
selector: 'seed-infinite',
templateUrl: './infinite.component.html',
styleUrls: ['./infinite.component.scss']
})
export class InfiniteComponent implements OnInit {
items: string[] = [];
itemIndex = 0;
constructor() {
}
ngOnInit() {
this.addItems(20);
}
addItems(count: number) {
for (let i = 0; i < count; i++, this.itemIndex++) {
this.items.push('item-' + this.itemIndex);
}
}
}
|
3cdd2e3d66c19919b77f6e28abf8a42d17e4d109
|
[
"TypeScript"
] | 7
|
TypeScript
|
theinternetgy/angular-native-seed-examples
|
6fdde4e33e9ab92095748b39039c8c32aef96eed
|
45e8d0f30da1f584d6b7d31c0a339b8e964f1f6e
|
refs/heads/master
|
<file_sep>class AdminController < ApplicationController
include AdminHelper
def new
if signed_in?
redirect_to blogs_path
end
end
def create
if !request_user.nil? && authenticate(request_user)
sign_in request_user
redirect_to blogs_path
else
render 'new'
end
end
def destroy
sign_out
redirect_to blogs_path
end
private
def request_user
@user = User.find_by_email params[:admin][:email].downcase
end
def authenticate user
User.authenticate(user.password, params[:admin][:password])
end
end
<file_sep>class AddColumnToComments < ActiveRecord::Migration
def change
add_column :comments, :commenter, :string, :null => false
add_column :comments, :email, :string, :null => false
end
end
<file_sep>class CommentsController < ApplicationController
include AdminHelper, CommentsHelper
before_filter :sign_in_user, only: :destroy
def create
@comment = Comment.new
if signed_in?
author_comment @comment
@comment[:content] = params[:comment][:content]
else
@comment = Comment.new(params[:comment])
end
thing.comments << @comment
redirect_to thing
end
def destroy
@comment = thing.comments.find params[:id]
if @comment.destroy
render json:{success: true}
end
end
private
def find_blog
find_model(Blog, blog_id)
end
def find_picture
find_model(Picture, picture_id)
end
def find_model(model, value)
@thing = model.find value
end
def thing
if is_blog?
@thing = find_blog
elsif is_picture?
@thing = find_picture
end
end
def is_blog?
blog_id.present?
end
def is_picture?
!picture_id.present?
end
def blog_id
params[:blog_id]
end
def picture_id
params[:picture_id]
end
end
<file_sep>class Comment < ActiveRecord::Base
belongs_to :blog
belongs_to :picture
validates :commenter, presence: true
attr_accessible :commenter, :content, :email, :website
end
<file_sep>class BlogsController < ApplicationController
include ApplicationHelper, AdminHelper
before_filter :sign_in_user, except: [:index, :show, :like]
before_filter :find_blog, only: [:show, :edit, :update, :destroy, :like]
caches_page :show
def index
@blogs = Blog.paginate(page: params[:page], per_page:5).order("created_at DESC")
end
def new
@blog = Blog.new
end
def create
@blog = Blog.new params[:blog]
label_tag @blog
if @blog.save
redirect_to @blog
else
render 'new'
end
end
def show
render status:404 unless @blog
end
def update
expire_page action: :show
label_tag @blog
if @blog.update_attributes params[:blog]
redirect_to @blog
end
end
def destroy
if @blog.destroy
render json:{success: true}
else
render json:{success: false}
end
end
def like
@blog.like_count += 1
if @blog.save
render json: @blog.like_count
end
end
def find_blog
@blog = Blog.find params[:id]
end
end
<file_sep>class Blog < ActiveRecord::Base
has_and_belongs_to_many :tags
has_many :comments, dependent: :delete_all
validates :title, presence: true
attr_accessible :content, :title, :tags
before_save :default_values
def has_pre?
Blog.first != self
end
def pre_blog
Blog.where("id < ?", self).order("id DESC").first
end
def has_next?
Blog.last != self
end
def next_blog
Blog.where("id > ?", self).order("id ASC").first
end
def default_values
self.like_count ||= 0
end
def self.recent_blogs(index = 3)
Blog.order("id DESC").limit(index)
end
def bref_content(range = 1000)
self.content.instance_eval do |t|
return t.to_s.strip[0, range] if t.length > range
t.to_s
end
end
end
<file_sep>class ChangeColumnToComments < ActiveRecord::Migration
def up
remove_column :comments, :commenter
remove_column :comments, :email
end
end
<file_sep>#SweetHome
###annotation
This is a web project just for fun
no need to care or even to fork
by [落在深海][1]

[1]:http://braavos.me "落在深海"
<file_sep>module CommentsHelper
def author_comment comment
if current_user
comment[:email] = current_user.email
comment[:website] = current_user.website
comment[:commenter] = current_user.username
end
return comment
end
end
<file_sep>class Picture < ActiveRecord::Base
has_and_belongs_to_many :tags
attr_accessible :description, :avatar
has_many :comments, dependent: :delete_all
mount_uploader :avatar, AvatarUploader
before_save :default_values
def default_values
self.like_count ||= 0
end
end
<file_sep>module ApplicationHelper
require "digest/md5"
require 'kramdown'
def title page_title
return base_title unless page_title.present?
page_title
end
def base_title
"Lacuna's Blog"
end
def html_view text
Kramdown::Document.new(text).to_html.gsub("\n", "\r") if text.present?
end
def updated_time target
target.updated_at.localtime.to_s(:db) unless target.nil?
end
def label_tag(thing, tags = params[:tags].split('#tag#'))
thing.tags = []
tags.each do |tag|
thing.tags << process_tag(tag.to_s)
end
end
def process_tag tag
@tag = Tag.where("name = ?", tag)
return Tag.new(name: tag) unless @tag.present?
@tag
end
end
<file_sep>class RemoveFileNameFromPicture < ActiveRecord::Migration
def change
remove_column :pictures, :filename
end
end
<file_sep>class AddlikesToPictures < ActiveRecord::Migration
def up
add_column :pictures, :like_count, :integer
end
def down
end
end
<file_sep>class CreatePicturesTags < ActiveRecord::Migration
create_table :pictures_tags do |t|
t.belongs_to :picture
t.belongs_to :tag
end
end
<file_sep>$(document).ready(function(){
var viewHight = $(document).height(),
viewWidth = $(document).width(),
windowWidth = $(window).width();
centreZone = {
"left": viewWidth/2,
"top": viewHight/2
};
var WIDE_SCREEN = 1024,
NARROW_SCREEN = 640;
//Loading display
$(document).ajaxSend(function(){
Loading.display();
});
//Loading hide
$(document).ajaxStop(function(){
Loading.hide();
});
//ScrollTop display, Aside position attr
$(function(){
$(window).scroll(function(){
var scrollHight = $(window).scrollTop();
if (scrollHight > 50 && windowWidth > WIDE_SCREEN) {
$("aside .tag-editor").css("position", "fixed");
$screentop = $(".screen-top");
if (scrollHight > 800) {
$screentop.fadeIn(100);
}else{
$screentop.fadeOut(100);
}
}else{
$("aside .tag-editor").css("position", "absolute");
}
});
});
//Navigate active
var path = document.location.pathname;
var pathArray = path.split("/");
if(path === "/"){
$(".main-nav").children("li:first").attr("class", "active");
}else{
for (var i = 0; i < pathArray.length; i++) {
$(".main-nav").find("a[href*='"+pathArray[i] + "']")
.parent("li").attr("class", "active");
};
}
//Picture
var Picture = function(){
var $picLayer = $('<div id="pic-layer">'
+'<div class="view-mid">'
+'<a href="javascript:;" id="pre_pic" class="pic-nav icon-angle-left"/>'
+'<div id="pic-view">'
+'<img/></div>'
+'<a href="javascript:;" id="next_pic" class="pic-nav icon-angle-right"/>'
+'</div></div>'),
$img = $picLayer.find("img");
return {
add: function(id, url){
if (url != undefined) {
$picLayer.attr("data", id);
$img.attr("src", url).load(function(){
Picture.resize();
});
$("body").append($picLayer);
};
},
resize: function(){
$("#pic-view").css({"margin-top": (viewHight - $img.height())/2,
"width":$img.width()});
},
remove: function(){
$("#pic-layer").remove();
},
replaceWith: function(id){
$.ajax({
url: "/pictures/"+ id,
type: "GET",
dataType: "json",
success: function(data){
$picLayer.attr("data", id);
$img.attr("src", data.avatar.url).load(function(){
Picture.resize();
});
},
error: function(data){
console.log("shit");
}
});
},
existed: function(){
if($("#pic-layer").length > 0){
return true;
}
}
}
}();
//Picture navigation
(function(){
$(document).on("click", "#pre_pic", function(){
Picture.replaceWith(Number($("#pic-layer").attr("data")) - 1);
});
$(document).on("click", "#next_pic", function(){
Picture.replaceWith(Number($("#pic-layer").attr("data"))+ 1);
});
})();
//Loading spin
var Loading = function(){
var $tip = $('<i class="loading icon-spinner icon-spin"/>');
$tip.css(centreZone);
return {
display: function(){
$("body").append($tip);
},
hide: function(){
$(".loading").remove();
}
}
}();
//Item display
if(windowWidth > WIDE_SCREEN){
$(".pic_list img").click(function(){
var tId = $(this).parents("picture").attr("id");
$.ajax({
url: "/pictures/" + tId,
type: "GET",
dataType: "json",
success: function(data){
Picture.add(tId, data.avatar.url);
}
});
});
//Item remove
$(document).on("click", "#pic-layer", function(event){
var target = $(event.target);
if(!target.is("img") && !target.is("a") && Picture.existed() === true){
Picture.remove();
}
});
};
//Delete a blog
$(".delete-blog").click(function(){
var $article = $(this).parents("article");
$.ajax({
url: "/blogs/" + $article.attr("id"),
type : "DELETE",
success: function(data){
delSucc(data, $article);
}
});
return false;
});
//Comment hover mark for delete
var $comItem = $(".comments").find(".item"),
$delCom = $(".delete-comment");
$comItem.hover(function(){
$(this).find($delCom).stop().fadeIn();
},function(){
$(this).find($delCom).stop().fadeOut();
});
//Delete a comment
$(document).on("click",".delete-comment", function(){
var $comment = $(this).parents("li.item");
$.ajax({
url: $(this).attr("href"),
type: "DELETE",
success: function(data){
delSucc(data, $comment);
}
});
return false;
});
var delSucc = function(data, $dom){
if (data.success === true) {
$dom.fadeOut();
};
};
//Like the blog or a picture
$(".likeIt").click(function(){
var $picture = $(this).parents("picture"),
$article = $(this).parents("article"),
tLength = $article.length || $picture.length,
$count = $(this).siblings(".like-counts"),
urlRoute,
tId;
if (tLength == 0) {
return false;
}else{
if ($article.length > 0) {
urlRoute = "/blogs/";
tId = $article.attr("id");
}
if ($picture.length > 0) {
urlRoute = "/pictures/";
tId = $picture.attr("id");
}
}
$.ajax({
url: urlRoute + tId + "/like",
type:"POST",
success: function(data){
$count.html(data);
}
});
return false;
});
//Pagination
$(function(){
$(".previous_page, .next_page").bind("page_display", function(){
if ($(this).hasClass("disabled")) {
$(this).css("display","none");
};
});
$(".previous_page, .next_page").trigger("page_display");
})
//Scroll to top
$(".screen-top").click(function(){
$("body, html").animate({scrollTop: 0}, 1000);
return false;
});
//Tag part
var Tag = function(){
return{
enabled: function($dom){
$dom.removeClass("tag-disabled");
$dom.removeAttr("disabled");
},
disabled: function($dom){
$dom.addClass("tag-disabled");
$dom.attr("disabled","disabled");
},
addTo: function(className, val, $target){
var tag = document.createElement("tag");
tag.innerHTML = val;
tag.className = className;
$(tag).appendTo($target);
},
remove: function($dom){
$dom.remove();
},
refresh: function($save_tag, spliter, $selectTags, $existTags){
var tags_val = "", tag_token;
$selectTags.find("tag").each(function(){
tag_token = $(this).text() + spliter;
var $selected_tags = $selectTags.children("tag"),
$exist_tags = $existTags.find("tag");
for (var i = 0; i < $exist_tags.length; i++) {
if($(this).text() === $exist_tags.eq(i).text()){
Tag.disabled($exist_tags.eq(i));
}
};
tags_val += tag_token;
$save_tag.val(tags_val);
});
},
refreshData: function(){
this.refresh($("#hid_tag"), "#tag#", $(".selected-tags"), $(".exist-tags"));
}
}
}()
//Tag init
Tag.refreshData();
//Tag actions
$("#new-tag").bind("input",function(){
$("#hid_swap").text($(this).val());
});
$("#new-tag").on("change", function(event){
if($(this).val().trim()!= ""){
Tag.addTo("sld-tag", $(this).val(), $(".selected-tags"));
Tag.refreshData();
}
$(this).val("");
});
$("#new-tag").on("keypress", function(event){
var _keyCode = event.which? event.which : event.keyCode;
if(_keyCode == 13){
if($(this).val().trim()!= ""){
Tag.addTo("sld-tag", $(this).val(), $(".selected-tags"));
Tag.refreshData();
}
$(this).val("");
return false;
}
});
$(document).on("click", ".selected-tags tag", function(){
var tagText = $(this).text().trim();
if(tagText != ""){
$(".exist-tags").find("tag").each(function(){
if($(this).text() === tagText){
Tag.enabled($(this));
}
});
Tag.remove($(this));
Tag.refreshData();
}
});
$(".exist-tags").children("tag").click(function(){
if (!$(this).hasClass("tag-disabled")) {
Tag.addTo("sld-tag", $(this).text(), $(".selected-tags"));
Tag.disabled($(this));
Tag.refreshData();
};
});
$(".subcheck").on("keypress", stopSubmit);
function stopSubmit(event){
var _keyCode = event.which? event.which : event.keyCode;
if(_keyCode == 13){
if(event && event.preventDefault){
event.preventDefault();
}else{
window.event.returnValue = false;
}
return false;
}
}
//Thumb picture's hover action
if(windowWidth > WIDE_SCREEN){
var $thumb_info = $(".pic-info");
$(".index-content picture").hover(function(){
$(this).find($thumb_info).stop().fadeIn();
},function(){
$(this).find($thumb_info).stop().fadeOut();
});
}
})<file_sep>class PicturesController < ApplicationController
include ApplicationHelper, AdminHelper
before_filter :find_picture, only: [:show, :edit, :update, :destroy, :like]
before_filter :sign_in_user, except: [:index, :show, :like]
def index
@pics = Picture.paginate(page: params[:page], per_page:10).order("created_at DESC")
end
def new
@pic = Picture.new
end
def edit
end
def create
@pic = Picture.new params[:picture]
label_tag @pic
if @pic.save
redirect_to picture_path(@pic)
else
render 'new'
end
end
def show
respond_to do |format|
format.html
format.json { render json: @pic.avatar }
end
end
def update
label_tag @pic
###
end
def destroy
end
def like
@pic.like_count += 1
if @pic.save
render json: @pic.like_count
end
end
def find_picture
@pic = Picture.find params[:id]
end
end
<file_sep>class User < ActiveRecord::Base
attr_accessible :email, :password, :username
before_create :create_remember_token
def User.authenticate(userPasswd, loginPasswd)
if userPasswd == loginPasswd
return true
else
return false
end
end
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt token
Digest::SHA1.hexdigest token.to_s
end
private
def create_remember_token
self.remember_token = User.encrypt User.new_remember_token
end
end
<file_sep>class ApplicationController < ActionController::Base
protect_from_forgery
def upload
# binding.pry
upload_io = params[:pic]
content_type = "application/json"
if is_image? upload_io.content_type
filePath = root_url + "imgs/uploads/"+upload_io.original_filename
File.open(Rails.root.join('public/imgs', 'uploads', upload_io.original_filename), 'w:UTF-8') do |file|
file.write(upload_io.read.force_encoding("utf-8"))
end
render text: {"success"=> true, "filePath"=>filePath}.to_json
else
render text: {"success"=> false}.to_json
end
end
private
def rename name
if filename.present?
# require 'uuidools'
# filename.sub()
end
end
def is_image? type
image_type = ["image/jpeg", "image/png", "image/gif"]
if type.blank?
false
else
image_type.include? type
end
end
def write_file filename
File.open(Rails.root.join('public/imgs', 'uploads', filename), 'w:UTF-8') do |file|
file.write(upload_io.read.force_encoding("utf-8"))
end
end
end
<file_sep>class Tag < ActiveRecord::Base
has_and_belongs_to_many :blogs
has_and_belongs_to_many :pictures
attr_accessible :name
end
<file_sep>class RemoveColumnFromPictures < ActiveRecord::Migration
def up
remove_attachment :pictures, :avatar
end
def down
end
end
|
82812c8ad91fffcc0809ae9710a42a88732d47f7
|
[
"Markdown",
"JavaScript",
"Ruby"
] | 20
|
Ruby
|
jerryshew/SweetHome
|
973c4524e96573cfce38000844dd4b9b02baeffc
|
32de6c7d191dbe07a8444b022cadf7c6f91cd6e6
|
refs/heads/master
|
<repo_name>tiantiantian808/test3<file_sep>/EclipseWorkspace/Test1/src/com/daidai/Mytest.java
package com.daidai;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class Mytest {
public static void main(String args[]) throws ParseException {
// 根据判定条件给出乘客的距离起飞时间短近程度得分
Scanner sc = new Scanner(System.in);
/* SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");//如2016-08-10 20:40
System.out.println("请输入乘客出票时间:");
String ticketout_time=sc.next();//出票时间
String fromDate = simpleFormat.format( ticketout_time);
String ticketout_time=sc.next();//出票时间
String str1=rs.getString(ticketout_time);
String fromDate = simpleFormat.format(str1);
System.out.println("请输入乘客起飞时间:");
String flight_time=sc.next();//起飞时间
String toDate = simpleFormat.format( flight_time);
String flight_time=sc.next();//起飞时间
String str2=rs.getString(flight_time);
String toDate = simpleFormat.format(str2);
long from = simpleFormat.parse(fromDate).getTime();
long to = simpleFormat.parse(toDate).getTime();
int days = (int) ((to - from)/(1000 * 60 * 60 * 24));
float v5=0;
if(days<1)
{v5=8/36;}
else if (days>1&&days<7)
{v5=7/36;}
else if(days>7&&days<15)
{v5=6/36;}
else if(days>15&&days<30)
{v5=5/36;}
else if(days>30&&days<60)
{v5=4/36;}
else if(days>60&&days<120)
{v5=3/36;}
else if(days>120&&days<365)
{v5=2/36;}
else if(days>365)
{v5=1/36;}
System.out.println("乘客距离起飞时间距离程度短近得分为:"+v5);*/
//根据判定条件给出票面等级得分
System.out.println("请输入舱位等级:");
String level=sc.next();//舱位等级
char bm=level.charAt(0);
System.out.println(bm);
float v6=0;
if(bm=='P'||bm=='F'||bm=='A')
{
System.out.println(bm);
v6=(float)(5/15);
System.out.println(v6);
}
/* else if(bm=='J'||bm=='C'||bm=='D'||bm=='Z'||bm=='R')
{
v6=4/15;
}
else if(level=="G"||level=="E"||level=="Y")
{
v6=3/15;
}
else if(level=="B"||level=="M"||level=="U"||level=="H"||level=="Q"||level=="V")
{
v6=2/15;
}
else if(level=="W"||level=="S"||level=="T"||level=="L"||level=="K"||level=="N")
{
v6=1/15;
}*/
System.out.println("乘客舱位等级得分为:"+v6);
}
}
<file_sep>/EclipseWorkspace/ID3/src/org/dom4j/io/XMLWriter.java
package org.dom4j.io;
public class XMLWriter {
}
<file_sep>/EclipseWorkspace/.metadata/version.ini
#Sat Mar 18 09:19:27 CST 2017
org.eclipse.core.runtime=2
org.eclipse.platform=4.5.0.v20150603-2000
|
5e6b77ab254bde7d38aab1558752c576cb27adf1
|
[
"Java",
"INI"
] | 3
|
Java
|
tiantiantian808/test3
|
be8e4de66d6f80d2ebce6d1601e5016fa58ccbfb
|
96226c9f8ce44bffad8710dd2f6f587597930a2e
|
refs/heads/master
|
<repo_name>Tonmaiipc/Python-Codes<file_sep>/NonRecursiveTowerOfHanoi7Lines.py
max = int(raw_input()); moves = {}
def ABC(max,n,i):
if (max%2==0)^(n%2==0) == True: return 'BCA'[i%3]
else: return 'CBA'[i%3]
for n in range(1,max+1):
for i in range(0, 2**(max-n)): moves[2**(n-1) + (2**n)*(i)] = str(n)+ABC(max,n,i)
for i in range(1,2**max): print moves[i],
<file_sep>/Select-Sort.py
_ = raw_input()
lis = [ int(i) for i in raw_input().split() ]
res = []
while True:
if lis == []: break
min = lis.pop(0)
for i in range(0, len(lis)):
if min <= lis[i]: pass
else:
lis.append(min)
min = lis.pop(i)
res.append(min)
print lis, res
print 'end'
<file_sep>/binaryGen.py
from sys import stdin
stone = map(int,stdin.read().split())
count = stone.pop(0)
stone.sort()
x = 0
min = float('inf')
while x <= int('1'*count,2)/2:
bin = map(int,list("{0:b}".format(x).zfill(count)))
#print bin
p1 = sum([a*b for a,b in zip(bin,stone)])
bin = [(1-b)*(b**b) for b in bin]
#print bin
p2 = sum([a*b for a,b in zip(bin,stone)])
#print p1, p2
dif = abs(p1-p2)
if dif < min: min = dif
x += 1
print min
<file_sep>/Bubble-Sort.py
num = int(raw_input())
lis = [ int(i) for i in raw_input().split()]
def logic(a,b):
if a > b:
return b, a, 1
else:
return a, b, 0
def run(lis):
for i in range(0,num-1):
a,b, c = logic(lis[i],lis[i+1])
lis[i] = a; lis[i+1] = b
global set
set += c
print lis
handle = True
while handle == True:
set = 0
run(lis)
if set == 0:
break
<file_sep>/Insert-Sort.py
from sys import stdin
inp = [int(i) for i in stdin.read().split()]
inp.pop(0)
for i in range(1,len(inp)):
if inp[i-1] > inp[i]:
#print inp
pick = inp.pop(i)
temp = inp[0:i]
for j in range(0,i)[::-1]:
if j == 0 and pick <temp[0]:
a = [pick]
temp = a + temp[j:]
inp = temp + inp[i:]
print inp
break
if pick > temp[j]:
a = temp[0:j+1]
a.append(pick)
temp = a + temp[j+1:]
inp = temp + inp[i:]
print inp
break
<file_sep>/README.md
## Tower of Hanoi Note
2: 1B 2C 1C
3: 1C 2B 1B 3C 1A 2C 1C
4: 1B 2C 1C 3B 1A 2B 1B 4C 1C 2A 1A 3C 1B 2C 1C
5: 1C 2B 1B 3C 1A 2C 1C 4B 1B 2A 1A 3B 1C 2B 1B 5C 1A 2C 1C 3A 1B 2A 1A 4C 1C 2B 1B 3C 1A 2C 1C
2: 1 2 1
3: 1 2 1 3 1 2 1
4: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
5: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
6: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1
2: 1 2 1
3: 1 2 1 3 1 2 1
4: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
5: 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
# this describe the nth disc that's used on the move
2: B C C
3: C B B C A C C
4: B C C B A B B C C A A C B C C
5: C B B C A C C B B A A B C B B C A C C A B A A C C B B C A C C
# this describe the destiny of the nth disc move
even odd = +B
even even = -C
odd odd = -C
odd even = +B
total move = 2^(m-1)
total number of 1 piece = 2^(max-n) ; max = max pieces, n= piece no.
1: 1,3,5,7 (2^0+2*i)
2: 2,6,10,14 (2^1+2^2*i)
3: 4,12,20,28 (2^2+2^3*i)
4: 8,24,40,56 (2^3+2^4*i)
5: 16,48,80,112 (+32)
ith position of n in all moves = 2^(n-1) + 2^n * i ; i = ith position in n.
(the move of the nth disc appear after every 2^n. when multiplied by i, the result is the next number of move that requires the nth disc)
# position of the nth disc in the serial of moves (above)
# notice that for each discs, it moves in either B->C->A or C->B->A fashion
<file_sep>/primeNum.py
m = int(raw_input())
hold =[2,3]
print 2,3,
for i in range(4,m+1):
for x in hold:
if i%x == 0:
break
else:
if x == hold[-1]:
hold.append(i)
print i,
continue
<file_sep>/primeTable.py
max = int(raw_input())
def primer(num,row):
prime = None
for i in range(0,max):
a,b = row[i]
if a%num == 0 and b == 0:
b = 1
row[i] = (a,b)
prime = num
else: continue
return row, prime
row = [(i,0) for i in range(1,max+1)]
primes = []
for ele in range(2,max+1):
row, prime = primer(ele,row)
if prime != None:
primes.append(prime)
for ele in primes:
if ele != primes[-1]: print ele,
else: print ele
for i in range(0,max/10+1):
if row[10*i:10*i+10] != []:
print row[10*i:10*i+10]
<file_sep>/fibonanciGen.py
def fibo(n,m):
if n-2 <=0:
if m != 0 : print 1, 1,
return 1
else:
sum = fibo(n-1,m) + fibo(n-2,m*0)
if m != 0 : print sum,
return sum
n = int(raw_input())
fibo(n,1)
<file_sep>/TowerOfHanoi.py
def moveNum(max):
moves = {}
for n in range(1,max+1): # n = piece no.
maxPiece = 2**(max-n)
for i in range(0, maxPiece):
moves[2**(n-1) + (2**n)*(i)] = n
return moves
def isEven(num):
if num%2 == 0:
iseven = True
else:
iseven = False
return iseven
def ABC(xor, count):
if xor == False: #-C
if count == 1:
abc= 'C'
elif count == 2:
abc= 'B'
elif count == 3:
abc= 'A'
count = 0
else:
print "error"
if xor == True: #+B
if count == 1:
abc= 'B'
elif count == 2:
abc= 'C'
elif count == 3:
abc= 'A'
count = 0
else:
print "error"
return abc,count
def alpha(moves, max):
turn = 2 ** max - 1
counter = {}
for i in range(1, turn+1):
if moves[i] in counter:
counter[moves[i]] += 1
else:
counter[moves[i]] = 1
abc, counter[moves[i]] = ABC(isEven(max)^isEven(moves[i]),counter[moves[i]])
moves[i] = str(moves[i])+abc
return moves
max = int(raw_input('No. of pieces:'))
moves = alpha(moveNum(max), max)
for i in range(1, 2**max):
print moves[i],
|
b5e6ea683f31ae0ce1f54641cde52aaecf6edeb6
|
[
"Markdown",
"Python"
] | 10
|
Python
|
Tonmaiipc/Python-Codes
|
322eec4f961057458cb0af38ed6dc30dc156db67
|
85dfa2538e8dcb7d9ebd0079cef7f2767e08c1b9
|
refs/heads/master
|
<file_sep>package com.jiuhe.atcrowdfunding.controller;
import com.jiuhe.atcrowdfunding.bean.BaseResponse;
import com.jiuhe.atcrowdfunding.bean.Page;
import com.jiuhe.atcrowdfunding.domain.User;
import com.jiuhe.atcrowdfunding.service.UserService;
import com.jiuhe.atcrowdfunding.util.CollectionUtil;
import com.jiuhe.atcrowdfunding.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;
@RestController
@RequestMapping("/user")
public class UserController {
//TODO 异常,日志
private static Logger logger = LoggerFactory.getLogger(UserController.class);
private UserService userService;
@RequestMapping(value = "update", method = RequestMethod.POST)
public BaseResponse updateUser(
@RequestParam("account") String account,
@RequestParam("name") String name,
@RequestParam("email") String email) {
userService.updateUser(account, name, email);
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping(value = "get", method = RequestMethod.POST)
public BaseResponse getUser(@RequestParam("account") String account) {
User user = userService.getUserByAccount(account);
return BaseResponse.SUCCESS_RESPONSE.put("user", user);
}
@RequestMapping("/check-account")
public BaseResponse checkAccount(@RequestParam("account") String account) {
boolean flag = userService.checkAccount(account);
if (!flag) {
return BaseResponse.ERROR_RESPONSE;
}
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping("/add")
public BaseResponse addUser(
@RequestParam("account") String account,
@RequestParam("name") String name,
@RequestParam("email") String email) {
if (StringUtil.isEmpty(account)) {
return BaseResponse.newErrorResponse("请输入账号!");
}
if (!userService.checkAccount(account)) {
logger.warn("账号重复无法新增该用户,账号:[{}]", account);
return BaseResponse.newErrorResponse("账号重复无法新增该用户!");
}
if (StringUtil.isEmpty(name)) {
return BaseResponse.newErrorResponse("请输入姓名!");
}
userService.addUser(account, name, email);
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public BaseResponse deleteUser(@RequestParam("accounts") List<String> accounts) {
if (CollectionUtil.isEmpty(accounts)) {
return BaseResponse.ERROR_RESPONSE;
}
userService.removeUser(accounts);
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping("/query-page")
public Page<User> queryPage(
@RequestParam("offset") Integer offset,
@RequestParam("limit") Integer limit,
@RequestParam("query") String query) {
if (offset == null || offset < 0) {
offset = 0;
}
if (limit == null || limit <= 0) {
limit = 10;
}
return userService.getPage(offset, limit, query);
}
@RequestMapping("/logout")
public BaseResponse logout(HttpSession session) {
logger.info("用户[{}]退出成功!", session.getAttribute("username"));
session.invalidate();
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping("/login")
public BaseResponse login(String username, String password, HttpSession session) {
if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
return BaseResponse.newErrorResponse("登录失败,请输入用户名或者密码!");
}
int count = userService.login(username, password);
if (count == 0) {
return BaseResponse.ERROR_RESPONSE;
}
session.setAttribute("username", username);
logger.info("账号[{}]登录成功!", username);
return BaseResponse.SUCCESS_RESPONSE;
}
@RequestMapping("/info")
public BaseResponse getUserInfo(HttpSession session) {
return BaseResponse.SUCCESS_RESPONSE.put("username", session.getAttribute("username"));
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
}
<file_sep># atcrowdfunding
rbac test
<file_sep>package com.jiuhe.atcrowdfunding.bean;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Getter
@Setter
@ToString
@NoArgsConstructor
public class Page<T> {
public static final Page EMPTY = null;
// private Integer offset;
// private Integer limit;
private int total;
private List<T> rows;
}
<file_sep>package com.jiuhe.atcrowdfunding.util;
public class ReflectUtil {
}
<file_sep>function order_number(value, row, index) {
//获取每页显示的数量
var pageSize = $('#tb_users').bootstrapTable('getOptions').pageSize;
//获取当前是第几页
var pageNumber = $('#tb_users').bootstrapTable('getOptions').pageNumber;
//返回序号,注意index是从0开始的,所以要加上1
return pageSize * (pageNumber - 1) + index + 1;
}
function operate() {
var roleStr = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";
var editStr = "<button type='button' class='btn btn-primary btn-xs'><i class=' glyphicon glyphicon-pencil'></i></button>";
var removeStr = "<button type='button' class='btn btn-danger btn-xs'><i class=' glyphicon glyphicon-remove'></i></button>";
return roleStr + editStr + removeStr;
}
function init_data() {
init_user_info();
// initList(1, 10);
}
//初始化右上角登录名
function init_user_info() {
$.ajax({
url: "/atcrowdfunding/user/info",
type: "post",
data: {},
success: function (data) {
if (data.statusCode === 0) {
layer.msg("系统错误,请稍后再试!", {time: 1500, icon: 5, shift: 6});
}
if (data.statusCode === 1) {
$("button:first span:first").text(data.data.username);
}
}
});
}
function delete_user(account_array) {
$.ajax({
url: "/atcrowdfunding/user/delete",
type: "post",
data: {"accounts": account_array},
traditional: true, //当传递js数组时,防止jQuery的深度序列化参数对象
success: function (data) {
if (data.statusCode === 0) {
layer.msg("系统错误,请稍后再试!", {time: 1500, icon: 5, shift: 6});
}
if (data.statusCode === 1) {
$("#tb_users").bootstrapTable("refresh", {
silent: true //静态刷新
});
}
}
});
}
<file_sep>// 常用js函数
function isEmpty(str) {
return str == "";
}
// function trim(str){
//
//
//
// }<file_sep>function init_data() {
$.ajax({
url: "/atcrowdfunding/user/get",
type: "post",
data: {},
traditional: true,
success: function (data) {
if (data.statusCode === 0) {
layer.msg(data.message, {time: 1500, icon: 5, shift: 6});
}
if (data.statusCode === 1) {
}
}
});
}<file_sep>package com.jiuhe.atcrowdfunding.util;
public class JsonUtil {
}
<file_sep>package com.jiuhe.atcrowdfunding.domain;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.util.Date;
@Getter
@Setter
@NoArgsConstructor
@ToString
public class User {
private Integer id;
private String account;
private String username;
private String password;
private String email;
private Boolean isDeleted;
private Date createTime;
}
|
57e4957d7ae86b2161e36335e6e9404ba1059cc8
|
[
"Markdown",
"Java",
"JavaScript"
] | 9
|
Java
|
Num17/atcrowdfunding
|
bad6d5f1096ee66b2939fdf929b6e188e79d1d3c
|
5487ac8709f48fca92b3a3f4ffef8dfbf67c34cc
|
refs/heads/master
|
<repo_name>goodsogi/GoogleAnalyticsPythonTest<file_sep>/SendEventToGoogleAnalyticsTest.py
from PlusGoogleAnalyticsManager import HitClient
# Set your Google Analytics Tracking Id here
GA_ID = "UA-116081388-1"
def run():
hit_client = HitClient(GA_ID)
try:
# Test with required params only
r = hit_client.send_hit(
"event",
event_category="orange",
event_action="want",
)
print(str(r))
except (Exception) as ex:
print(ex)
# # Test with optional params included
# r = hit_client.send_hit(
# "event",
# event_category="Users",
# event_action="New Registration w Value",
# user_id="uy6rafdye7",
# event_label="JP",
# event_value="7",
# )
#
#
# # Test with optional params included
# r = hit_client.send_hit(
# "transaction",
# revenue="2160",
# currency="JPY",
# user_id="uy6Rafdye7",
# shipping="500",
# tax="160",
# affiliation="Test Category",
# transaction_id="XXXtesttransid01",
# )
#
# # Test with required params only
# r = hit_client.send_hit(
# "transaction",
# revenue="999",
# currency="MYR",
# )
if __name__ == "__main__":
run()
|
d8e19a6035209b77d08e2afbc424a65908be4934
|
[
"Python"
] | 1
|
Python
|
goodsogi/GoogleAnalyticsPythonTest
|
35d5768bd56d4c027e59bc7ff0d6053f5c2b2788
|
263f55700b8cfa60b65c906244129c047f2b0377
|
refs/heads/8.x-1.x-dev
|
<file_sep><?php
/**
* @file
* Contains \Drupal\interswitch_donate\DonationInterface.
*/
namespace Drupal\interswitch_donate;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface defining a Donation entity.
*/
interface DonationInterface extends ContentEntityInterface, EntityOwnerInterface {
}
|
866b4b9bfd83173cab535892f4499fdbec27c15a
|
[
"PHP"
] | 1
|
PHP
|
timplunkett/interswitch_donate
|
ae7b84a22a5adbb653148ef698153528c50e0049
|
9cdf03c845c13bcc6818750abb37033896fccfb0
|
refs/heads/master
|
<repo_name>iseabock/pollapp<file_sep>/app/controllers/answers_controller.rb
class AnswersController < ApplicationController
def results
@answer_id = params["poll_answer"].values[0]
@poll_id = params["poll_id"]
@answers = Answer.all.order("vote_count DESC")
@question_id = Poll.find(params["poll_id"])
@total = 0
Answer.increment_vote_count(@answer_id)
@answers.each do |answer|
vote_count = answer["vote_count"] ? answer["vote_count"] : 0
@total = @total + vote_count
end
redirect_to :controller => 'answers', :action => 'show_results', :answers_id => @answer_id, :question_id => @question_id, :total => @total
end
def show_results
@answers = Answer.all.order("vote_count DESC")
@question = Poll.find_by_id(params[:question_id])
@total = params[:total]
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def answer_params
params.require(:answer).permit(:poll_id, :answer, :vote_count)
end
end
<file_sep>/app/models/answer.rb
class Answer < ActiveRecord::Base
belongs_to :poll
def self.increment_vote_count id
Answer.update_counters(id, :vote_count => 1)
end
end
|
354a8346d6b25e62877b995a67c7cc3bb469b816
|
[
"Ruby"
] | 2
|
Ruby
|
iseabock/pollapp
|
b482654702ab6ceb06bec92073d81b77dd4c0130
|
5604a7ca9f35245ab4a293b88276568798c92bca
|
refs/heads/master
|
<repo_name>LachowskiTomekPL/tomeklachowski-kodilla-java1<file_sep>/kodilla-testing/src/test/java/com/kodilla/testing/shape/ShapeCollectorTestSuite.java
package com.kodilla.testing.shape;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class ShapeCollectorTestSuite {
@Test
public void testAddShapeToCollector(){
ShapeCollector shapeCollector = new ShapeCollector();
int shapesElementsBefore = shapeCollector.showFigures().size();
Shape circle = new Circle();
shapeCollector.addFigure(circle);
int shapesElementsAfter = shapeCollector.showFigures().size();
Assert.assertEquals(shapesElementsBefore+1, shapesElementsAfter);
}
@Test
public void testRemoveShapeToCollector(){
ShapeCollector shapeCollector = new ShapeCollector();
Shape circle = new Circle();
shapeCollector.addFigure(circle);
int shapesElementsBefore = shapeCollector.showFigures().size();
shapeCollector.removeFigure(circle);
int shapesElementsAfter = shapeCollector.showFigures().size();
Assert.assertEquals(shapesElementsBefore-1, shapesElementsAfter);
}
@Test
public void testGetShapeToCollector(){
ShapeCollector shapeCollector = new ShapeCollector();
Shape circle = new Circle();
Shape triangle = new Triangle();
Shape square = new Square();
shapeCollector.addFigure(circle);
shapeCollector.addFigure(triangle);
shapeCollector.addFigure(square);
Shape gotShape = shapeCollector.getFigure(1);
Assert.assertEquals(triangle.getShapeName(), gotShape.getShapeName());
}
}
<file_sep>/kodilla-testing/src/main/java/com/kodilla/testing/collection/OddNumbersExterminator.java
package com.kodilla.testing.collection;
import java.util.ArrayList;
public class OddNumbersExterminator {
public ArrayList<Integer> exterminate(ArrayList<Integer> numbers){
for(int i=0; i<numbers.size();i++){
int value;
value = numbers.get(i);
if((value%2)==0){
numbers.add(value);
}
}
return numbers;
}
}
|
fa54cda6594024f329a53bf0297e85d1faf531d1
|
[
"Java"
] | 2
|
Java
|
LachowskiTomekPL/tomeklachowski-kodilla-java1
|
522b8d53e8c0bdd8eb9e7859dcae83f6e6a7fb39
|
f61ea3d5845b4c9255cd88362702bc177a816e6e
|
refs/heads/master
|
<repo_name>fengweijp/autorest<file_sep>/src/modeler/AutoRest.Swagger/Validation/AnonymousTypes.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
public class AnonymousTypes : TypedRule<SwaggerObject>
{
/// <summary>
/// An <paramref name="entity"/> fails this rule if it doesn't have a reference (meaning it's defined inline)
/// </summary>
/// <param name="entity">The entity to validate</param>
/// <returns></returns>
public override bool IsValid(SwaggerObject entity) => entity == null || !string.IsNullOrEmpty(entity.Reference);
public override ValidationExceptionName Exception => ValidationExceptionName.AnonymousTypesDiscouraged;
}
}
<file_sep>/src/core/AutoRest.Core/Validation/Rule.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
using System;
using System.Linq;
using System.Globalization;
using AutoRest.Core.Logging;
namespace AutoRest.Core.Validation
{
/// <summary>
/// Defines validation logic for an object
/// </summary>
public abstract class Rule
{
protected Rule()
{
}
/// <summary>
/// The name of the exception that describes this rule
/// </summary>
public abstract ValidationExceptionName Exception { get; }
/// <summary>
/// Returns the validation messages resulting from validating this object
/// </summary>
/// <param name="entity">The object to validate</param>
/// <returns></returns>
public abstract IEnumerable<ValidationMessage> GetValidationMessages(object entity);
/// <summary>
/// Creates an exception for the given <paramref name="exceptionName"/>, using the <paramref name="messageValues"/> format parameters
/// </summary>
/// <param name="exceptionName"></param>
/// <param name="messageValues"></param>
/// <returns></returns>
protected static ValidationMessage CreateException(ValidationExceptionName exceptionName, params object[] messageValues)
{
ValidationMessage validationMessage;
ValidationExceptionName[] ignore = new ValidationExceptionName[] { };
if (ignore.Any(id => id == exceptionName))
{
validationMessage = new ValidationMessage()
{
Severity = LogEntrySeverity.Info,
Message = string.Empty
};
}
else if (ValidationExceptionConstants.Info.Messages.ContainsKey(exceptionName))
{
validationMessage = new ValidationMessage()
{
Severity = LogEntrySeverity.Info,
Message = string.Format(CultureInfo.InvariantCulture, ValidationExceptionConstants.Info.Messages[exceptionName], messageValues)
};
}
else if (ValidationExceptionConstants.Warnings.Messages.ContainsKey(exceptionName))
{
validationMessage = new ValidationMessage()
{
Severity = LogEntrySeverity.Warning,
Message = string.Format(CultureInfo.InvariantCulture, ValidationExceptionConstants.Warnings.Messages[exceptionName], messageValues)
};
}
else if (ValidationExceptionConstants.Errors.Messages.ContainsKey(exceptionName))
{
validationMessage = new ValidationMessage()
{
Severity = LogEntrySeverity.Error,
Message = string.Format(CultureInfo.InvariantCulture, ValidationExceptionConstants.Errors.Messages[exceptionName], messageValues)
};
}
else
{
throw new NotImplementedException();
}
validationMessage.ValidationException = exceptionName;
return validationMessage;
}
}
}
<file_sep>/src/core/AutoRest.Core/Validation/RecursiveObjectValidator.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace AutoRest.Core.Validation
{
/// <summary>
/// A validator that traverses an object graph, applies validation rules, and logs validation messages
/// </summary>
public class RecursiveObjectValidator
{
public RecursiveObjectValidator()
{
}
public IEnumerable<ValidationMessage> GetValidationExceptions(object entity)
{
return RecursiveValidate(entity, new List<RuleAttribute>());
}
private IEnumerable<ValidationMessage> RecursiveValidate(object entity, IEnumerable<RuleAttribute> collectionRules)
{
if (entity != null)
{
if (entity is IList)
{
// Recursively validate each list item and add the item index to the location of each validation message
IList<dynamic> list = ((IList)entity).Cast<dynamic>().ToList();
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
foreach (ValidationMessage exception in RecursiveValidate(list[i], collectionRules))
{
exception.Path.Add($"[{i}]");
yield return exception;
}
}
}
}
else if (entity is IDictionary)
{
// Recursively validate each dictionary entry and add the entry key to the location of each validation message
IDictionary<string, dynamic> dict = ((IDictionary)entity).Cast<dynamic>().ToDictionary(entry => (string)entry.Key, entry => entry.Value);
if (dict != null && entity.IsValidatableDictionary())
{
foreach (var pair in dict)
{
foreach (ValidationMessage exception in RecursiveValidate(pair.Value, collectionRules))
{
exception.Path.Add(pair.Key);
yield return exception;
}
}
}
}
else if (entity.GetType().IsClass && entity.GetType() != typeof(string))
{
// Validate objects by running class rules against the object and recursively against properties
foreach(var exception in ValidateObjectValue(entity, collectionRules))
{
yield return exception;
}
foreach(var exception in ValidateObjectProperties(entity))
{
yield return exception;
}
}
}
yield break;
}
private IEnumerable<ValidationMessage> ValidateObjectValue(object entity, IEnumerable<RuleAttribute> collectionRules)
{
// Get any rules defined for the class of the entity
var classRules = entity.GetType().GetCustomAttributes<RuleAttribute>(true);
// Combine the class rules with any rules that apply to the collection that the entity is part of
classRules = collectionRules.Concat(classRules);
// Apply each rule for the entity
return classRules.SelectMany(rule => rule.GetValidationMessages(entity));
}
private IEnumerable<ValidationMessage> ValidateObjectProperties(object entity)
{
// Go through each validatable property
foreach (var prop in entity.GetValidatableProperties())
{
// Get the value of the property from the entity
var value = prop.GetValue(entity);
// Get any rules defined on this property and apply them to the property value
var propertyRules = prop.GetCustomAttributes<RuleAttribute>(true);
foreach (var rule in propertyRules)
{
foreach (var exception in rule.GetValidationMessages(value))
{
exception.Path.Add(prop.Name);
yield return exception;
}
}
// Recursively validate the value of the property (passing any rules to inherit)
var inheritableRules = prop.GetCustomAttributes<CollectionRuleAttribute>(true);
foreach (var exception in RecursiveValidate(value, inheritableRules))
{
exception.Path.Add(prop.Name);
yield return exception;
}
}
yield break;
}
}
internal static class RulesExtensions
{
private static readonly Type JsonExtensionDataType = typeof(JsonExtensionDataAttribute);
/// <summary>
/// Gets an enumerable of properties for <paramref name="entity"/> that can be validated
/// </summary>
/// <param name="entity">The object to get properties for</param>
/// <returns></returns>
internal static IEnumerable<PropertyInfo> GetValidatableProperties(this object entity)
{
if (entity == null)
{
return new List<PropertyInfo>();
}
return entity.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance)
.Where(prop => !Attribute.IsDefined(prop, JsonExtensionDataType))
.Where(prop => prop.PropertyType != typeof(object));
}
/// <summary>
/// Determines if a dictionary can be validated by running rules
/// </summary>
/// <param name="entity">The object to check</param>
/// <returns></returns>
internal static bool IsValidatableDictionary(this object entity)
{
if (entity == null)
{
return false;
}
// Dictionaries of type <string, object> cannot be validated, because the object could be infinitely deep.
// We only want to validate objects that have strong typing for the value type
var dictType = entity.GetType();
return dictType.IsGenericType &&
dictType.GenericTypeArguments.Count() >= 2 &&
dictType.GenericTypeArguments[1] != typeof(object);
}
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/DescriptiveDescriptionRequired.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace AutoRest.Swagger.Validation
{
internal static class DescriptiveDescriptionsExtensions
{
private static IEnumerable<string> ImpermissibleDescriptions = new List<string>()
{
"description"
};
/// <summary>
/// Determines if the string is a value that is not allowed (case insensitive)
/// </summary>
internal static bool IsImpermissibleValue(this string description)
{
return ImpermissibleDescriptions.Any(s => s.Equals(description, System.StringComparison.InvariantCultureIgnoreCase));
}
}
public class DescriptiveDescriptionRequired : TypedRule<string>
{
/// <summary>
/// This test passes if the <paramref name="description"/> is not just empty or whitespace and not explictly blocked
/// </summary>
/// <param name="description"></param>
/// <returns></returns>
public override bool IsValid(string description)
=> !string.IsNullOrWhiteSpace(description) && !description.IsImpermissibleValue();
public override ValidationExceptionName Exception => ValidationExceptionName.DescriptiveDescription;
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/AnonymousParameterTypes.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
public class AnonymousParameterTypes : TypedRule<SwaggerParameter>
{
private static AnonymousTypes AnonymousTypesRule = new AnonymousTypes();
/// <summary>
/// An entity fails this rule if it has a schema, and that schema is an anonymous type
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(SwaggerParameter entity) =>
entity == null || entity.Schema == null || AnonymousTypesRule.IsValid(entity.Schema);
public override ValidationExceptionName Exception => ValidationExceptionName.AnonymousTypesDiscouraged;
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/RefNoSiblings.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
internal static class SwaggerObjectExtensions
{
internal static bool DefinesInlineProperties(this SwaggerObject entity)
{
return entity.Description != null
|| entity.Items != null
|| entity.Type != null;
}
}
public class RefNoSiblings : TypedRule<SwaggerObject>
{
/// <summary>
/// This rule passes if the entity does not have both a reference and define properties inline
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(SwaggerObject entity)
=> entity == null || string.IsNullOrEmpty(entity.Reference) || !entity.DefinesInlineProperties();
public override ValidationExceptionName Exception => ValidationExceptionName.RefsMustNotHaveSiblings;
}
}
<file_sep>/src/core/AutoRest.Core/Validation/ValidationMessage.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Logging;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace AutoRest.Core.Validation
{
public class ValidationMessage
{
private IList<string> _path = new List<string>();
public ValidationExceptionName ValidationException { get; set; }
public string Message { get; set; }
public LogEntrySeverity Severity { get; set; }
public IList<string> Path
{
get { return this._path; }
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}: {1}\n Location: Path: {2}", ValidationException, Message, string.Join("->", Path.Reverse()));
}
}
}
<file_sep>/src/generator/AutoRest.Ruby.Azure.Tests/RspecTests/lro_spec.rb
# encoding: utf-8
$: << 'RspecTests/Generated/lro'
require 'rspec'
require 'generated/lro'
include LroModule
include LroModule::Models
describe 'Long Running Operation' do
before(:all) do
base_url = ENV['StubServerURI']
dummyToken = '<PASSWORD>'
credentials = MsRest::TokenCredentials.new(dummyToken)
test_client = AutoRestLongRunningOperationTestService.new(credentials, base_url)
test_client.long_running_operation_retry_timeout = 0
@lros_client = test_client.lros
@product = Product.new
@product.location = "West US"
@sku = Sku.new
@sku.name = 'doesNotMatter'
@sku.id = 'doesNotMatter'
end
# Happy path tests
it 'should wait for succeeded status for create operation' do
result = @lros_client.put201creating_succeeded200(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should rise error on "failed" operation result' do
expect { @lros_client.put201creating_failed200(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should wait for succeeded status for update operation' do
result = @lros_client.put200updating_succeeded204(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should rise error on "canceled" operation result' do
expect { @lros_client.put200acceptedcanceled200(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should retry on 202 server response in POST request' do
result = @lros_client.post202retry200(@product).value!
expect(result.response.status).to eq(200)
end
it 'should not retry on 202 server response in POST request' do
result = @lros_client.post202no_retry204(@product).value!
expect(result.response.status).to eq(204)
end
it 'should serve success response on initial PUT request' do
result = @lros_client.put200succeeded(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should serve success response on initial request without provision state' do
result = @lros_client.put200succeeded_no_state(@product).value!
expect(result.body.id).to eq("100")
expect(result.body.provisioning_state).to eq(nil)
end
it 'should serve 202 on initial response and status response without provision state' do
result = @lros_client.put202retry200(@product).value!
expect(result.body.id).to eq("100")
expect(result.body.provisioning_state).to eq(nil)
end
it 'should serve success response on initial DELETE request' do
result = @lros_client.delete204succeeded().value!
expect(result.response.status).to eq(204)
end
it 'should return payload on POST async request' do
result = @lros_client.post200with_payload().value!
expect(result.body.id).to eq(1)
end
it 'should succeed for put async retry' do
result = @lros_client.put_async_retry_succeeded(@product).value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for put async no retry' do
result = @lros_client.put_async_no_retry_succeeded(@product).value!
expect(result.response.status).to eq(200)
end
it 'should fail for put async retry' do
expect { @lros_client.put_async_retry_failed(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should fail for put async no retry canceled' do
expect { @lros_client.put_async_no_retrycanceled(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should succeed for post async retry' do
result = @lros_client.post_async_retry_succeeded(@product).value!
expect(result.response.status).to eq(200)
end
it 'should succeed for post async no retry' do
result = @lros_client.post_async_no_retry_succeeded(@product).value!
expect(result.response.status).to eq(200)
end
it 'should fail for post async retry' do
expect { @lros_client.post_async_retry_failed(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should fail for post async retry canceled' do
expect { @lros_client.post_async_retrycanceled(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should succeed for put no header in retry' do
result = @lros_client.put_no_header_in_retry(@product).value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for put async no header in retry' do
result = @lros_client.put_async_no_header_in_retry(@product).value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for delete no header in retry' do
result = @lros_client.delete_no_header_in_retry().value!
expect(result.response.status).to eq(204)
end
it 'should succeed for delete async no header in retry' do
result = @lros_client.delete_async_no_header_in_retry().value!
expect(result.response.status).to eq(200)
end
it 'should succeed for put sub resource' do
result = @lros_client.put_sub_resource(@product).value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for put async sub resource' do
result = @lros_client.put_async_sub_resource(@product).value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for put non resource' do
result = @lros_client.put_non_resource(@sku).value!
expect(result.response.status).to eq(200)
expect(result.body.id).to eq('100')
expect(result.body.name).to eq('sku')
end
it 'should succeed for put async non resource' do
result = @lros_client.put_async_non_resource(@sku).value!
expect(result.response.status).to eq(200)
expect(result.body.id).to eq('100')
expect(result.body.name).to eq('sku')
end
it 'should succeed for delete provisioning 202 accepted 200' do
result = @lros_client.delete_provisioning202accepted200succeeded().value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for delete provisioning 202 deleting failed 200' do
result = @lros_client.delete_provisioning202deleting_failed200().value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Failed")
end
it 'should succeed for delete provisioning 202 deleting canceled 200' do
result = @lros_client.delete_provisioning202deletingcanceled200().value!
expect(result.response.status).to eq(200)
expect(result.body.provisioning_state).to eq("Canceled")
end
it 'should succeed for delete 204' do
result = @lros_client.delete204succeeded().value!
expect(result.response.status).to eq(204)
end
it 'should succeed for delete 202 retry 200' do
result = @lros_client.delete202retry200().value!
expect(result.response.status).to eq(200)
end
it 'should succeed for delete 202 no retry 204' do
result = @lros_client.delete202no_retry204().value!
expect(result.response.status).to eq(204)
end
it 'should succeed for delete async retry' do
result = @lros_client.delete_async_retry_succeeded().value!
expect(result.response.status).to eq(200)
end
it 'should succeed for delete async no retry' do
result = @lros_client.delete_async_no_retry_succeeded().value!
expect(result.response.status).to eq(200)
end
it 'should fail for delete async retry failed' do
expect { @lros_client.delete_async_retry_failed().value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should fail for delete async retry canceled' do
expect { @lros_client.delete_async_retrycanceled().value! }.to raise_error(MsRestAzure::AzureOperationError)
end
end
describe 'Long Running Operation with retry' do
before(:all) do
base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
credentials = MsRest::TokenCredentials.new(dummyToken)
test_client = AutoRestLongRunningOperationTestService.new(credentials, base_url)
test_client.long_running_operation_retry_timeout = 0
@lroretrys_client = test_client.lroretrys
@product = Product.new
@product.location = "West US"
end
# Retryable errors
it 'should retry PUT request on 500 response' do
result = @lroretrys_client.put201creating_succeeded200(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should retry PUT request on 500 response for async operation' do
result = @lroretrys_client.put_async_relative_retry_succeeded(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should retry DELETE request for provisioning status' do
result = @lroretrys_client.delete_provisioning202accepted200succeeded().value!
expect(result.response.status).to eq(200)
end
it 'should retry DELETE request on 500 response' do
result = @lroretrys_client.delete202retry200().value!
expect(result.response.status).to eq(200)
end
it 'should retry POST request on 500 response' do
result = @lroretrys_client.post202retry200(@product).value!
expect(result.response.status).to eq(200)
end
it 'should retry POST request on 500 response for async operation' do
result = @lroretrys_client.post_async_relative_retry_succeeded(@product).value!
expect(result.response.status).to eq(200)
end
it 'should retry on 500 server response in PUT request' do
result = @lroretrys_client.put_async_relative_retry_succeeded(@product).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should retry on 500 server response in DELETE request' do
result = @lroretrys_client.delete_async_relative_retry_succeeded().value!
expect(result.response.status).to eq(200)
end
end
describe 'Long Running Operation with ads' do
before(:all) do
base_url = ENV['StubServerURI']
dummyToken = '<PASSWORD>'
credentials = MsRest::TokenCredentials.new(dummyToken)
test_client = AutoRestLongRunningOperationTestService.new(credentials, base_url)
test_client.long_running_operation_retry_timeout = 0
@lroads_client = test_client.lrosads
@product = Product.new
@product.location = "West US"
end
# Sad path tests
it 'should rise error on response 400 for PUT request' do
expect { @lroads_client.put_non_retry400(@product).value! }.to raise_exception(MsRest::HttpOperationError)
end
it 'should rise error if 400 response comes in the middle of PUT operation' do
expect { @lroads_client.put_non_retry201creating400(@product).value! }.to raise_error(MsRestAzure::AzureOperationError)
end
it 'should rise error if 400 response comes in the middle of async PUT operation' do
expect { @lroads_client.put_async_relative_retry400(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on response 400 for DELETE request' do
expect { @lroads_client.delete_non_retry400().value! }.to raise_exception(MsRest::HttpOperationError)
end
it 'should rise error if 400 response comes in the middle of DELETE operation' do
expect{ @lroads_client.delete_async_relative_retry400().value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if 400 response comes from POST request' do
expect{ @lroads_client.post_non_retry400(@product).value! }.to raise_exception(MsRest::HttpOperationError)
end
it 'should rise error on response 400 for POST request' do
expect{ @lroads_client.post202non_retry400(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if 400 response comes in the middle of async POST operation' do
expect{ @lroads_client.post_async_relative_retry400(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no provisioning state in payload provided on PUT request' do
expect{ @lroads_client.put_error201no_provisioning_state_payload(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no state provided on PUT request' do
expect{ @lroads_client.put_async_relative_retry_no_status(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no provisioning state in payload provided on async PUT request' do
expect{ @lroads_client.put_async_relative_retry_no_status_payload(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid JSON response on initial request' do
expect{ @lroads_client.put200invalid_json(@product).value! }.to raise_exception(MsRest::DeserializationError)
end
it 'should rise error on invalid endpoint received in initial PUT request' do
expect{ @lroads_client.put_async_relative_retry_invalid_header(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid JSON response in status polling request during PUT operation' do
expect{ @lroads_client.put_async_relative_retry_invalid_json_polling(@product).value! }.to raise_exception(MsRest::DeserializationError)
end
it 'should rise error on invalid Location and Retry-After headers during DELETE operation' do
expect{ @lroads_client.delete202retry_invalid_header().value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid endpoint received in initial DELETE request' do
expect{ @lroads_client.delete_async_relative_retry_invalid_header().value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid JSON response in status polling request during DELETE operation' do
expect{ @lroads_client.delete_async_relative_retry_invalid_json_polling().value! }.to raise_exception(MsRest::DeserializationError)
end
it 'should rise error on invalid Location and Retry-After headers during POST operation' do
expect{ @lroads_client.post202retry_invalid_header(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid endpoint received in initial POST request' do
expect{ @lroads_client.post_async_relative_retry_invalid_header(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error on invalid JSON response in status polling request during POST operation' do
expect{ @lroads_client.post_async_relative_retry_invalid_json_polling(@product).value! }.to raise_exception(MsRest::DeserializationError)
end
it 'should not rise error on DELETE operation with 204 response without location provided' do
result = @lroads_client.delete204succeeded().value!
expect(result.response.status).to eq(204)
end
it 'should rise error on no status provided for DELETE async operation' do
expect{ @lroads_client.delete_async_relative_retry_no_status().value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no location provided' do
pending 'fails for in travis'
fail
expect { @lroads_client.post202no_location(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no payload provided on POST async retry request' do
expect{ @lroads_client.post_async_relative_retry_no_payload(@product).value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
it 'should rise error if no payload provided on DELETE non retry request' do
expect{ @lroads_client.delete202non_retry400().value! }.to raise_exception(MsRestAzure::AzureOperationError)
end
end
describe 'Long Running Operation with custom header' do
before(:all) do
base_url = ENV['StubServerURI']
dummyToken = '<PASSWORD>'
credentials = MsRest::TokenCredentials.new(dummyToken)
test_client = AutoRestLongRunningOperationTestService.new(credentials, base_url)
test_client.long_running_operation_retry_timeout = 0
@lros_custom_header_client = test_client.lros_custom_header
@product = Product.new
@product.location = "West US"
@custom_header = { 'x-ms-client-request-id' => '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0' }
end
it 'should succeed for custom header put async' do
result = @lros_custom_header_client.put_async_retry_succeeded(@product, @custom_header).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for custom header post async' do
result = @lros_custom_header_client.post_async_retry_succeeded(@product, @custom_header).value!
expect(result.response.status).to eq(200)
end
it 'should succeed for custom header put' do
result = @lros_custom_header_client.put201creating_succeeded200(@product, @custom_header).value!
expect(result.body.provisioning_state).to eq("Succeeded")
end
it 'should succeed for custom header post' do
result = @lros_custom_header_client.post202retry200(@product, @custom_header).value!
expect(result.response.status).to eq(200)
end
end<file_sep>/src/modeler/AutoRest.Swagger/Validation/ClientNameRequired.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
public class ClientNameRequired : TypedRule<SwaggerObject>
{
public override bool IsValid(SwaggerObject entity)
{
bool valid = true;
object clientName = null;
if (entity != null && entity.Extensions != null && entity.Extensions.TryGetValue("x-ms-client-name", out clientName))
{
var ext = clientName as Newtonsoft.Json.Linq.JContainer;
if (ext != null && (ext["name"] == null || string.IsNullOrEmpty(ext["name"].ToString())))
{
valid = false;
}
else if (string.IsNullOrEmpty(clientName as string))
{
valid = false;
}
}
return valid;
}
public override ValidationExceptionName Exception => ValidationExceptionName.NonEmptyClientName;
}
}
<file_sep>/src/core/AutoRest.Core/Validation/ValidationExceptionName.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace AutoRest.Core.Validation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xms")]
public enum ValidationExceptionName
{
None = 0,
DescriptionRequired,
NonEmptyClientName,
DefaultMustBeInEnum,
RefsMustNotHaveSiblings,
AnonymousTypesDiscouraged,
OneUnderscoreInOperationId,
DefaultResponseRequired,
XmsPathsMustOverloadPaths,
DescriptiveDescription,
OperationIdNounsNotInVerbs,
}
}<file_sep>/src/modeler/AutoRest.Swagger.Tests/SwaggerModelerValidationTests.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.IO;
using System.Linq;
using Xunit;
using System.Collections.Generic;
using AutoRest.Core.Validation;
using AutoRest.Core.Logging;
using AutoRest.Core;
namespace AutoRest.Swagger.Tests
{
internal static class AssertExtensions
{
internal static void AssertOnlyValidationWarning(this IEnumerable<ValidationMessage> messages, ValidationExceptionName exception)
{
AssertOnlyValidationMessage(messages.Where(m => m.Severity == LogEntrySeverity.Warning), exception);
}
internal static void AssertOnlyValidationMessage(this IEnumerable<ValidationMessage> messages, ValidationExceptionName exception)
{
Assert.Equal(1, messages.Count());
Assert.Equal(exception, messages.First().ValidationException);
}
}
[Collection("Validation Tests")]
public class SwaggerModelerValidationTests
{
private IEnumerable<ValidationMessage> ValidateSwagger(string input)
{
var modeler = new SwaggerModeler(new Settings
{
Namespace = "Test",
Input = input
});
IEnumerable<ValidationMessage> messages = new List<ValidationMessage>();
modeler.Build(out messages);
return messages;
}
/// <summary>
/// Verifies that a clean Swagger file does not result in any validation errors
/// </summary>
[Fact]
public void CleanFileValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "clean-complex-spec.json"));
Assert.Empty(messages.Where(m => m.Severity >= LogEntrySeverity.Warning));
}
[Fact]
public void MissingDescriptionValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "definition-missing-description.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.DescriptionRequired);
}
[Fact]
public void DefaultValueInEnumValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "default-value-not-in-enum.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.DefaultMustBeInEnum);
}
[Fact]
public void EmptyClientNameValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "empty-client-name-extension.json"));
messages.AssertOnlyValidationWarning(ValidationExceptionName.NonEmptyClientName);
}
[Fact]
public void RefSiblingPropertiesValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "ref-sibling-properties.json"));
messages.AssertOnlyValidationWarning(ValidationExceptionName.RefsMustNotHaveSiblings);
}
[Fact]
public void NoResponsesValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "operations-no-responses.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.DefaultResponseRequired);
}
[Fact]
public void AnonymousSchemasDiscouragedValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "anonymous-response-type.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.AnonymousTypesDiscouraged);
}
[Fact]
public void AnonymousParameterSchemaValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "anonymous-parameter-type.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.AnonymousTypesDiscouraged);
}
[Fact]
public void OperationGroupSingleUnderscoreValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "operation-group-underscores.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.OneUnderscoreInOperationId);
}
[Fact]
public void MissingDefaultResponseValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "operations-no-default-response.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.DefaultResponseRequired);
}
[Fact]
public void XMSPathNotInPathsValidation()
{
var messages = ValidateSwagger(Path.Combine("Swagger", "Validation", "xms-path-not-in-paths.json"));
messages.AssertOnlyValidationMessage(ValidationExceptionName.XmsPathsMustOverloadPaths);
}
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/DescriptionRequired.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
public class DescriptionRequired : TypedRule<SwaggerObject>
{
/// <summary>
/// This rule fails if the description is null and the reference is null (since the reference could have a description)
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(SwaggerObject entity)
=> entity == null || entity.Description != null || !string.IsNullOrEmpty(entity.Reference);
public override ValidationExceptionName Exception => ValidationExceptionName.DescriptionRequired;
}
}
<file_sep>/src/core/AutoRest.Core/Validation/ValidationExceptionConstants.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Properties;
using System.Collections.Generic;
namespace AutoRest.Core.Validation
{
public static class ValidationExceptionConstants
{
public static class Info
{
public static readonly IReadOnlyDictionary<ValidationExceptionName, string> Messages = new Dictionary<ValidationExceptionName, string>
{
{ ValidationExceptionName.AnonymousTypesDiscouraged, Resources.AnonymousTypesDiscouraged },
};
}
public static class Warnings
{
public static readonly IReadOnlyDictionary<ValidationExceptionName, string> Messages = new Dictionary<ValidationExceptionName, string>
{
{ ValidationExceptionName.DescriptionRequired, Resources.MissingDescription },
{ ValidationExceptionName.NonEmptyClientName, Resources.EmptyClientName },
{ ValidationExceptionName.RefsMustNotHaveSiblings, Resources.ConflictingRef },
{ ValidationExceptionName.DefaultResponseRequired, Resources.NoDefaultResponse },
{ ValidationExceptionName.XmsPathsMustOverloadPaths, Resources.XMSPathBaseNotInPaths },
{ ValidationExceptionName.DescriptiveDescription, Resources.DescriptionNotDescriptive },
{ ValidationExceptionName.OperationIdNounsNotInVerbs, Resources.OperationIdNounInVerb },
};
}
public static class Errors
{
public static readonly IReadOnlyDictionary<ValidationExceptionName, string> Messages = new Dictionary<ValidationExceptionName, string>
{
{ ValidationExceptionName.DefaultMustBeInEnum, Resources.InvalidDefault },
{ ValidationExceptionName.OneUnderscoreInOperationId, Resources.OnlyOneUnderscoreAllowedInOperationId },
};
}
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/XmsPathsInPath.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
using System.Collections.Generic;
using System.Linq;
namespace AutoRest.Swagger.Validation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Xms")]
public class XmsPathsInPath : TypedRule<ServiceDefinition>
{
public override IEnumerable<ValidationMessage> GetValidationMessages(ServiceDefinition entity)
{
return entity?.CustomPaths?.Keys
.Where(customPath => !entity.Paths.ContainsKey(GetBasePath(customPath)))
.Select(basePath => CreateException(Exception, basePath))
?? Enumerable.Empty<ValidationMessage>();
}
private static string GetBasePath(string customPath)
{
var index = customPath.IndexOf('?');
if (index == -1)
{
return customPath;
}
return customPath.Substring(0, index);
}
public override ValidationExceptionName Exception => ValidationExceptionName.XmsPathsMustOverloadPaths;
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/OperationIdSingleUnderscore.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Linq;
using AutoRest.Core.Validation;
namespace AutoRest.Swagger.Validation
{
public class OperationIdSingleUnderscore : TypedRule<string>
{
/// <summary>
/// This rule passes if the entity contains no more than 1 underscore
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(string entity)
=> entity != null && entity.Count(c => c == '_') <= 1;
public override ValidationExceptionName Exception => ValidationExceptionName.OneUnderscoreInOperationId;
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/DefaultResponseRequired.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
using System.Collections.Generic;
namespace AutoRest.Swagger.Validation
{
public class DefaultResponseRequired : TypedRule<IDictionary<string, OperationResponse>>
{
/// <summary>
/// This rule fails if the <paramref name="entity"/> lacks responses or lacks a default response
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(IDictionary<string, OperationResponse> entity)
=> entity != null && entity.ContainsKey("default");
public override ValidationExceptionName Exception => ValidationExceptionName.DefaultResponseRequired;
}
}
<file_sep>/src/modeler/AutoRest.Swagger/Validation/DefaultInEnum.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using AutoRest.Core.Validation;
using AutoRest.Swagger.Model;
namespace AutoRest.Swagger.Validation
{
internal static class EnumDefaultExtensions
{
/// <summary>
/// Determines if the SwaggerObject has both a default and an enum defined
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
internal static bool HasDefaultAndEnum(this SwaggerObject entity)
{
return !string.IsNullOrEmpty(entity.Default) && entity.Enum != null;
}
/// <summary>
/// Determines if the default value appears in the enum
/// </summary>
internal static bool EnumContainsDefault(this SwaggerObject entity)
{
return entity.Enum.Contains(entity.Default);
}
}
public class EnumContainsDefault : TypedRule<SwaggerObject>
{
/// <summary>
/// An <paramref name="entity"/> fails this rule if it has both default defined and enum and the default isn't in the enum
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public override bool IsValid(SwaggerObject entity) =>
entity == null || !entity.HasDefaultAndEnum() || entity.EnumContainsDefault();
public override ValidationExceptionName Exception => ValidationExceptionName.DefaultMustBeInEnum;
}
}
|
52b23a18d02f8887f68745514fc35349651d1e78
|
[
"C#",
"Ruby"
] | 17
|
C#
|
fengweijp/autorest
|
34f56eaa0dece0f471b2b30202af1e223864b0e1
|
de9d40a4378dc29d2b55d5645eb79fb67f893b64
|
refs/heads/master
|
<file_sep>n=int(input("Enter the start range:"))
m=int(input("Enter the end range:"))
def na(d):
print(d**2)
for i in range(n,m+1):
na(i);
<file_sep>n=int(input("enter the first range:"))
m=int(input("enter the last range:"))
total=0
for i in range(n,m):
total+=i
print("the total is" ,total)
<file_sep>import random
a=(random.randrange(1,10))
def ran(b,count):
if(count!=4):
b=int(input("Enter your guessed no:"))
if(b==a):
print("your guessing is right")
else:
print("your guessing is wrong")
count+=1
ran(b,count);
else:
print("u lost")
print("the correct no is:",a)
count=1
ran(a,count);
<file_sep>import random
a=(random.randrange(1,4))
def rps(b,q):
if(b==q):
print("its a draw")
elif(b==1 and q==2):
print("u lose")
elif(b==1 and q==3):
print("u win")
elif(b==2 and q==1):
print("u won")
elif(b==2 and q==3):
print("u won")
elif(b==3 and q==1):
print("u won")
elif(b==3 and q==2):
print("u lose")
str='y'
while(str=='y' or str=='Y'):
print("1.rock","2.paper","3.scissor")
c=int(input("enter your choice"))
rps(a,c);
str=input("Do u want to continue(y/n)?")
<file_sep>str='y'
while(str=='y' or str=='Y'):
a=int(input("Enter the a:"))
b=int(input("Enter the b:"))
<file_sep>n=int(input("enter the starting range:"))
m=int(input("enter the ending range:"))
sum=0
for num in range(n, m + 1):
if num % 2 == 0:
sum=sum+num
print(sum)
<file_sep>n= int(input("start range: "))
m=int(input("end range: "))
sum = 0
for num in range(n, m + 1):
i = 0
for i in range(2, num):
if (int(num % i) == 0):
i = num
break;
#If the number is prime then add it.
if i is not num:
sum += num
print("Sum of all prime numbers from" ,n, "to" ,m, ":", sum)
<file_sep>def taxi():
src=float(input("Enter the Source:"))
if(src<0):
taxi();
des=float(input("Enter the Destination:"))
total_km=0
total_km=float(des-src)
choice(total_km);
def choice(a):
if(a>0):
print("Total kilometer is:",a,"km")
print("1.Macro","2.Micro","3.Prime")
c=int(input("Make ur choice:"))
if(c==1):
macro(a);
elif(c==2):
micro(a);
elif(c==3):
prime(a);
else:
print("Invalid")
print("Please make a valid choice")
choice(a);
else:
print("Invalid")
taxi();
def macro(a):
a*=10
print("The cost for your travel is:",a,"Rs")
def micro(a):
a*=20
print("The cost for your travel is:",a,"Rs")
def prime(a):
a*=20
print("The cost for your travel is:",a,"Rs")
str='y'
while(str=='y' or str=='Y'):
taxi();
str=input("Do u want to continue(y/n)?")
<file_sep>str='y'
while(str=='y' or str=='Y'):
src=int(input("Enter the Source:"))
des=int(input("Enter the Destination:"))
total_km=des-src
print("Total kilometer is:",total_km,"km")
print("1.Micro","2.Micro","3.Prime")
c=int(input("Make ur choice:"))
if(c==1):
money=total_km*10
print("The cost for your travel is:",money,"Rs")
elif(c==2):
money=total_km*20
print("The cost for your travel is:",money,"Rs")
elif(c==3):
money=total_km*30
print("The cost for your travel is:",money,"Rs")
else:
print("Please make a choice")
str=input("Do u want to continue(y/n)?")
|
b8baed88074d8bdb08432dfec00bb08dfc16f97a
|
[
"Python"
] | 9
|
Python
|
Sanlook/guvi
|
441e1b63178767dea06c35b734e559cc13774cb7
|
0d8e1ebcc1f7ca0d733747b4e710c5c5593ba532
|
refs/heads/master
|
<file_sep># DonAM
Web Project
Development of a web application for a restaurant service where you can see the menu and contact, pick food and send orders and post comments about the service only if you are login with an account. Using HTML, CSS, Php, Javascript and Bootsrap components.
<file_sep>CREATE TABLE Users (
fName VARCHAR(30) NOT NULL,
lName VARCHAR(30) NOT NULL,
username VARCHAR(50) NOT NULL PRIMARY KEY,
passwrd VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
);
CREATE TABLE Reviews (
idReview timestamp(4) NOT NULL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
review VARCHAR(200) NOT NULL
);
CREATE TABLE Ordenes (
idOrden timestamp(4) NOT NULL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
paquete VARCHAR(200) NOT NULL,
comentarios VARCHAR(200) NOT NULL,
precio INT(200) NOT NULL,
personas INT(50) NOT NULL
);
INSERT INTO Users(fName, lName, username, passwrd, email)
VALUES ('Gala', 'Ramos', 'galita12', 'galita21', '<EMAIL>'),
('Yarely', 'Mercado', 'ymercado', 'yarely96', '<EMAIL>');
<file_sep>/*$(document).ready(function(){
var jsonToSend = {
"action" : "COOKIESERVICE"
};
$.ajax({
url: "./data/applicationLayer.php",
type: "POST",
data : jsonToSend,
dataType: "json",
success : function(dataReceived){
$("#username").val(dataReceived.cookieUsername);
},
error : function(errorMessage){
//alert(errorMessage.statusText);
}
});
//Login
$("#login").on("click", validateLogin);
function validateLogin() {
var valid= true;
var name1, passw;
name1 = $("#username").val();
passw = $("#password").val();
console.log(name1, passw);
if (name1 == ""){
$("#errorUsername").text("Please fill in your username");
valid = false;
}
if(passw == ""){
$("#errorPassword").text("Please fill in your password");
valid = false;
}
if (valid){
var username = $("#username").val();
var password = $("#password").val();
if (username != "" && password != ""){
var jsonToSend = {
"uName": username,
"uPassword": <PASSWORD>,
"rememberMe" : $("#remember").is(":checked"),
"action" : "LOGIN"
};
console.log(jsonToSend);
$.ajax({
url: "./data/applicationLayer.php",
type: "POST",
data: jsonToSend,
ContentType: "application/json",
dataType: "json",
success: function(data){
alert("Welcome back " + data.firstname + " " + data.lastname);
document.getElementById('LoginPop').style.display = "none";
document.getElementById('showLogin').style.display = "none";
document.getElementById('showRegist').style.display = "none";
mostrarCarrito();
//document.getElementsByClassName('logoutButton').style.display = "";
},
error: function(error){
alert(error.statusText);
console.log("error");
}
});
}
}
}
//Registration
$("#registration").on("click", validateSubmit);
function validateSubmit() {
var valid= true;
var fname, lname, uname, mail, passw, passwconf;
fname = $("#firstName").val();
lname = $("#lastName").val();
uname = $("#userName").val();
mail = $("#email").val();
passw = $("#password2").val();
passwconf = $("#passwordConf").val();
if (fname == ""){
$("#errorFirstName").text("Please fill in your first name");
valid = false;
}
if(lname == ""){
$("#errorLastName").text("Please fill in your last name");
valid = false;
}
if (uname == ""){
$("#errorUsername2").text("Please fill in your username");
valid = false;
}
if(mail == ""){
$("#errorEmail").text("Please fill in your email");
valid = false;
}
if (passw == ""){
$("#errorPassword2").text("Please fill in your password");
valid = false;
}
if(passwconf == ""){
$("#errorPasswordConfirmation").text("Please fill in your password confirmation");
valid = false;
}
if (passwconf != "" && passwconf!= passw){
$("#errorPasswordConfirmation").text("Incorrect password confirmation");
valid = false;
}
if (fname != ""){
$("#errorFirstName").text("");
}
if(lname != ""){
$("#errorLastName").text("");
}
if (uname != ""){
$("#errorUsername2").text("");
}
if(mail != ""){
$("#errorEmail").text("");
}
if (passwconf != "" && passwconf == passw){
$("#errorPasswordConfirmation").text("");
}
if(passw != ""){
$("#errorPassword2").text("");
}
if(valid){
var fname = $("#firstName").val();
var lname = $("#lastName").val();
var username = $("#userName").val();
var email = $("#email").val();
var password = $("#password2").val();
var jsonToSend = {
"fname" : fname,
"lname" : lname,
"username" : username,
"email" : email,
"passwrd" : <PASSWORD>,
"action" : "REGISTRATION"
};
$.ajax({
url : "./data/applicationLayer.php",
type : "POST",
data : jsonToSend,
ContentType: "application/json",
dataType: "json",
success: function(data){
alert("Bienvenido");
console.log("hola");
},
error: function(error){
console.log(error.statusText);
}
}
);
}
}
});*/
<file_sep><?php
header('Content-type: application/json');
header('Accept: application/json');
require_once __DIR__ . '/dataLayer.php';
$action = $_POST["action"];
switch($action)
{
case "LOGIN" : loginFunction();
break;
case "REGISTRATION" : registrationFunction();
break;
case "SESSIONSERVICE" : sessionService();
break;
case "DELETESESSIONSERVICE" : deleteSessionService();
break;
case "COOKIESERVICE" : cookieService();
break;
case "ADDREVIEW" : addReviewFunction();
break;
case "LOADREVIEWS" : loadReviewsFunction();
break;
case "AGREGARCARRITO" : agregarCarritoFunction();
break;
case "MOSTRARCARRITO" : mostrarCarritoFunction();
break;
}
function loginFunction()
{
$uName = $_POST["uName"];
$rememberMe = $_POST["rememberMe"];
$loginResponse = attemptLogin($uName, $rememberMe);
if ($loginResponse["MESSAGE"] == "SUCCESS")
{
$decryptedPassword = decryptPassword($loginResponse['password']);
$uPassword = $_POST["uPassword"];
if($decryptedPassword == $uPassword)
{
$response = array("firstname"=>$loginResponse["firstname"], "lastname"=>$loginResponse["lastname"]);
echo json_encode($response);
}
}
else
{
genericErrorFunction($loginResponse["MESSAGE"]);
}
}
function decryptPassword($password)
{
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$iv_size = @mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$ciphertext_dec = base64_decode($password);
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
$password = @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
$count = 0;
$length = strlen($password);
for($i = $length - 1; $i >= 0; $i --)
{
if(ord($password{$i}) == 0)
{
$count ++;
}
}
$password = substr($password, 0, $length - $count);
return $password;
}
function genericErrorFunction($errorCode)
{
switch($errorCode)
{
case "500" : header("HTTP/1.1 500 Bad connection, portal down");
die("The server is down, we couldn't stablish the data base connection.");
break;
case "406" : header("HTTP/1.1 406 User not found.");
die("Wrong credentials provided.");
}
}
function registrationFunction()
{
$userFirstName = $_POST['fname'];
$userLastName = $_POST['lname'];
$userName = $_POST['username'];
$userEmail = $_POST['email'];
$userPassword = encryptPassword();
$registrationResponse = attemptRegistration($userFirstName, $userLastName, $userName, $userPassword, $userEmail);
if ($registrationResponse["MESSAGE"] == "SUCCESS")
{
echo json_encode("New record created successfully");
}
else
{
genericErrorFunction($registrationResponse["MESSAGE"]);
}
}
function encryptPassword()
{
$userPassword = $_POST['<PASSWORD>'];
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
$key_size = strlen($key);
$plaintext = $userPassword;
$iv_size = @mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = @mcrypt_create_iv($iv_size, MCRYPT_RAND);
$ciphertext = @mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
$ciphertext = $iv . $ciphertext;
$userPassword = base64_encode($ciphertext);
return $userPassword;
}
function sessionService()
{
session_start();
if (isset($_SESSION['firstname']) && isset($_SESSION['lastname']))
{
echo json_encode(array('fName' => $_SESSION['firstname'], 'lName' => $_SESSION['lastname'], 'username' => $_SESSION['username']));
}
else
{
header('HTTP/1.1 406 Favor de iniciar sesion.');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}
}
function deleteSessionService()
{
session_start();
if (isset($_SESSION['firstname']) && isset($_SESSION['lastname']))
{
unset($_SESSION['firstname']);
unset($_SESSION['lastname']);
unset($_SESSION['username']);
session_destroy();
echo json_encode(array('success' => 'Session deleted'));
}
else
{
header('HTTP/1.1 406 Session not found yet.');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}
}
function cookieService()
{
if (isset($_COOKIE['cookieUsername'])){
echo json_encode(array('cookieUsername' => $_COOKIE['cookieUsername']));
}
else
{
header('HTTP/1.1 406 Cookie not set yet.');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
}
}
function addReviewFunction()
{
session_start();
$username = $_SESSION["username"];
$review = $_POST["review"];
$reviewResponse = attemptReview($username, $review);
if ($reviewResponse["MESSAGE"] == "SUCCESS")
{
echo json_encode(array("username"=>$reviewResponse["username"]));
}
else
{
genericErrorFunction($reviewResponse["MESSAGE"]);
}
}
function loadReviewsFunction()
{
$loadReviewResponse = attemptLoadReviews();
echo json_encode($loadReviewResponse);
}
function agregarCarritoFunction()
{
session_start();
$username = $_SESSION["username"];
$paquete = $_POST["paquete"];
$comentarios = $_POST["comentarios"];
$numPersonas = $_POST["numPersonas"];
$agregarCarritoResponse = attemptAgregarCarrito($username, $paquete, $comentarios, $numPersonas);
if ($agregarCarritoResponse["MESSAGE"] == "SUCCESS")
{
echo json_encode(array('success' => 'Saved'));
}
else
{
genericErrorFunction($agregarCarritoResponse["MESSAGE"]);
}
}
function mostrarCarritoFunction()
{
session_start();
$username = $_SESSION["username"];
$mostrarCarritoResponse = attemptMostrarCarrito($username);
echo json_encode($mostrarCarritoResponse);
}
?>
<file_sep><?php
function databaseConnection()
{
$servername = "localhost";
$username = "root";
$password = "<PASSWORD>";
$dbname = "DonAM";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
return null;
}
else
{
return $conn;
}
}
function attemptLogin($userName, $rememberMe)
{
$connection = databaseConnection();
if ($connection != null)
{
$sql = "SELECT * FROM Users WHERE username = '$userName'";
$result = $connection->query($sql);
if ($result->num_rows > 0)
{
if ($rememberMe == true)
{
setcookie("cookieUsername", $userName);
}
while ($row = $result->fetch_assoc())
{
$response = array("firstname"=>$row["fName"], "lastname"=>$row["lName"], "password"=>$row["<PASSWORD>"], "MESSAGE"=>"SUCCESS");
session_start();
if (! isset($_SESSION['firstname']))
{
$_SESSION['firstname'] = $row['fName'];
}
if (! isset($_SESSION['lastname']))
{
$_SESSION['lastname'] = $row['lName'];
}
if(! isset($_SESSION['username']))
{
$_SESSION['username'] = $row['username'];
}
}
$connection->close();
return $response;
}
else
{
$connection->close();
return array("MESSAGE"=>"406");
}
}
else
{
return array("MESSAGE"=>"500");
}
}
function attemptRegistration($userFirstName, $userLastName, $userName, $userPassword, $userEmail)
{
$connection = databaseConnection();
if ($connection != null)
{
$sql = "SELECT username FROM Users WHERE username = '$userName'";
$result = $connection->query($sql);
if ($result->num_rows > 0)
{
header('HTTP/1.1 409 Conflict, Username already in use please select another one');
die("Username already in use.");
}
else
{
$sql = "INSERT INTO Users (fName, lName, username, passwrd, email) VALUES ('$userFirstName', '$userLastName', '$userName', '$userPassword', '$userEmail')";
if (mysqli_query($connection, $sql))
{
$response = array("MESSAGE"=>"SUCCESS");
session_start();
if (! isset($_SESSION['firstname']))
{
$_SESSION['firstname'] = $userFirstName;
}
if (! isset($_SESSION['lastname']))
{
$_SESSION['lastname'] = $userLastName;
}
if (! isset($_SESSION['username']))
{
$_SESSION['username'] = $userName;
}
$connection->close();
return $response;
}
else
{
$connection->close();
return array("MESSAGE"=>"500");
}
}
}
else {
return array("MESSAGE"=>"500");
}
}
function attemptReview($username, $review)
{
$connection = databaseConnection();
if($connection != null)
{
$sql = "SELECT username FROM Users WHERE username = '$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0){
$sql = "INSERT INTO Reviews(username, review)
VALUES ('$username', '$review');";
if (mysqli_query($connection, $sql))
{
$response = array("username" => $username, "MESSAGE"=>"SUCCESS");
$connection->close();
return $response;
}
else
{
$connection->close();
return array("MESSAGE"=>"500");
}
}
}
else {
return array("MESSAGE"=>"500");
}
}
function attemptLoadReviews()
{
$connection = databaseConnection();
if ($connection != null)
{
$sql = "SELECT username, review FROM Reviews";
$result = $connection->query($sql);
$response = array();
if($result->num_rows > 0){
$response = array();//"MESSAGE"=>"SUCCESS");
while($row = mysqli_fetch_assoc($result)){
$response[] = $row;
}
$connection->close();
return $response;
}
else{
$connection->close();
return array("MESSAGE"=>"500");
}
}
else {
return array("MESSAGE"=>"500");
}
}
function attemptAgregarCarrito($username, $paquete, $comentarios, $numPersonas)
{
$connection = databaseConnection();
if($connection != null)
{
$sql = "SELECT username FROM Users WHERE username = '$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0){
$sql = "INSERT INTO Ordenes(username, paquete, comentarios, precio, personas)
VALUES ('$username', '$paquete', '$comentarios', $numPersonas * 70, '$numPersonas');";
if (mysqli_query($connection, $sql))
{
$response = array("MESSAGE"=>"SUCCESS");
$connection->close();
return $response;
}
else
{
$connection->close();
return array("MESSAGE"=>"500");
}
}
}
else {
return array("MESSAGE"=>"500");
}
}
function attemptMostrarCarrito($username)
{
$connection = databaseConnection();
if($connection != null)
{
$sql = "SELECT * FROM Ordenes WHERE username = '$username'";
$result = $connection->query($sql);
$response = array();
if ($result->num_rows > 0)
{
$response = array();
while ($row = mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$connection->close();
return $response;
}
else
{
$connection->close();
return array("MESSAGE"=>"406");
}
}
else
{
return array("MESSAGE"=>"500");
}
}
?>
|
f6195fa9246f83521a11d2a425d8720139a8bc27
|
[
"Markdown",
"SQL",
"JavaScript",
"PHP"
] | 5
|
Markdown
|
GalaRamos/DonAM
|
00c26e81a84dcce0f9443f0242dde6b0e18c0800
|
7fdf9544ba5c1aa5468baba25000fffe4571ee3c
|
refs/heads/master
|
<repo_name>DevinMui/git-slack<file_sep>/bot.js
var SlackBot = require('slackbots');
var mongoose = require('mongoose')
var exec = require('child_process').exec
mongoose.connect("mongodb://localhost/gitslack")
// define the schema for our user model
var channelsSchema = mongoose.Schema({
channel_id: String,
name: String
});
var Channel = mongoose.model('Channel', channelsSchema);
// create a bot
var bot = new SlackBot({
token: '<KEY>', // Add a bot https://my.slack.com/services/new/bot and put the token
name: 'gitslack'
});
bot.on('start', function() {
for(var i=0;i<bot.channels.length;i++){
if(bot.channels[i].is_member){
var id = bot.channels[i].id
var name = bot.channels[i].name
Channel.findOne({ channel_id: bot.channels[i].id}, function(err, channel){
if(!channel){
new Channel({
channel_id: id,
name: name
}).save(function(){
console.log("Joined: "+ name)
})
}
})
}
}
bot.postMessageToChannel('server', "Hey, I'm GitSlack. I can control the server! Just mention me with a simple message like `@gitslack deploy production`.")
});
bot.on('message', function(data) {
// all ingoing events https://api.slack.com/rtm
if(data.type==='channel_joined'){
new Channel({
channel_id: data.channel.id,
name: data.channel.name
}).save(function(){
console.log("Joined " + data.channel.name)
})
}
if(data.type==='message' && data.user!==bot.self.id){
var text = data.text.split(" ")
if(text[0]==="<@"+bot.self.id+">"){
if(text[1]==="deploy"){
if(text[2]==="production"){
Channel.findOne({channel_id: data.channel}, function(err, channel){
var name = channel.name
console.log("GitSlack invoked in channel " + name)
bot.postMessageToChannel(name, "Pulling from Github...")
exec("cd ../loaf && git pull", function(){
bot.postMessageToChannel(name, "Killing server...")
exec("ps aux | grep -i 'node app.js' | awk '{print $2}' | xargs sudo kill -9", function(){
bot.postMessageToChannel(name, "Restarting server...")
exec("cd ../loaf && (printf '\n' | sudo nohup node app.js > log.out &)", function(){
console.log("Done?")
bot.postMessageToChannel(name, "Done!")
})
})
})
})
}
}
}
}
});
|
37e16f94b779e29136fffc0d39c5864d9a730c20
|
[
"JavaScript"
] | 1
|
JavaScript
|
DevinMui/git-slack
|
69eb86c58e5fbfcedbb66d28df22d879805513d7
|
b88c040aff8b88866efe53870c4e2e15a98d5c42
|
refs/heads/master
|
<repo_name>Jobayer-Ahmed/URL-Shortener-Microservice<file_sep>/README.md
# URL-Shortener-Microservice
freeCodeCamp Backend Project: Apis and Microservices Projects - URL Shortener Microservice

**Website:** [Click Here](http://chotokoro.surge.sh/)
## To use:
```js
git clone https://github.com/Jobayer-Ahmed/URL-Shortener-Microservice.git //clone repository
cd URL-Shortener-Microservice //goto the project directory.
npm install //install dependencies
node app.js //run app.js file
```
### to short url just go to [your server]/url/[your url]
### To redirect: [your server url]/[short-url]
##### Thank you
<file_sep>/app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
const urlModels = require('./models/url.js');
mongoose.connect('mongodb://mickeyvai:<EMAIL>:35251/freecodecamp-url-shortener');
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*"); // "*" for public access and www.example.com for specific uses
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
app.get('/url/:shortURL(*)', (req, res, next) => {
let mainUrl = req.params.shortURL;
const url_validator = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/gm;
if (url_validator.test(mainUrl) === true) {
let number = Math.floor(Math.random()*40)+1;
const getRandomString = (len, an) =>{
an = an&&an.toLowerCase();
let str="", i=0, min=an=="a"?10:0, max=an=="n"?10:62;
for(;i++<len;){
let r = Math.random()*(max-min)+min <<0;
str += String.fromCharCode(r+=r>9?r<36?55:61:48);
}
return str;
}
let data = new urlModels (
{
original_url: mainUrl,
shortner_url: getRandomString(number, 'A')
}
);
data.save((err) => {
if (err) {
return res.send('Error');
}
});
return res.json({
original_url: data.original_url,
short_url: data.shortner_url
});
}
let data = new urlModels({
original_url: mainUrl,
shortner_url: 'InvalidURL'
})
return res.json(data);
})
app.get('/:redirectURL', (req, res, next) => {
let redirectUrl = req.params.redirectURL, url_validator = /(http(s?))\:\/\//gi;
urlModels.findOne({'shortner_url': redirectUrl}, (error, respond) => {
if (error) {
return res.send('Error reading Database')
}
if (url_validator.test(respond.original_url)) {
res.redirect(301, respond.original_url)
} else {
res.redirect(301, `http://${respond.original_url}`);
}
})
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`App is listen on port ${PORT}`);
})
|
66a46042f2890944c76c79cc6866a4e51c3a63fc
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
Jobayer-Ahmed/URL-Shortener-Microservice
|
084e88444afc6822f6664eb581904620ebf35584
|
baba261462cfe8b084ab6503b08b481015e575dd
|
refs/heads/master
|
<repo_name>Orphist/pixelprinter<file_sep>/lib/extensions/shopify_login_protection_ext.rb
module ShopifyLoginProtection
def shopify_session
if session[:shopify].blank? or shop_overwritten?
original_request = "#{request.path}?#{request.query_string}"
session[:return_to] = original_request
redirect_to :controller => 'login', :action => 'index', :shop => params[:shop]
return
end
ActiveResource::Base.site = session[:shopify].site
ShopifyAPI::Shop.cached = Rails.cache.fetch("shops/#{session[:shopify].url}", :expires_in => 5.minutes) { session[:shopify].shop }
set_timezone
yield
ensure
ActiveResource::Base.site = nil
ShopifyAPI::Shop.cached = nil
end
private
def shop_overwritten?
return false if params[:shop].blank?
params[:shop] != session[:shopify].url && "#{params[:shop]}.myshopify.com" != session[:shopify].url
end
def set_timezone
# deal with ill formatted timezone string currently provided by Shopify
Time.zone = ShopifyAPI::Shop.cached.timezone.gsub(/\(.+\) |amp;/, '')
end
end<file_sep>/app/helpers/order_helper.rb
module OrderHelper
def order_status(order)
content_tag :span, order.financial_status, :class => "o-status o-#{order.financial_status}"
end
end<file_sep>/app/controllers/orders_controller.rb
class OrdersController < ApplicationController
protect_from_forgery :except => 'print'
around_filter :shopify_session
def index
# this is needed for Shopify's application links, because they append the id param with
# a question mark (/orders?id=123) instead of rails nested style (/orders/123)
redirect_to :action => 'show', :id => params[:id] if params[:id].present?
# get latest 3 orders
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
# get all printing templates for the current shop
@tmpls = shop.templates
end
def show
@safe = params[:safe]
if @safe
flash[:notice] = "Safe mode allows you to edit templates that cause the page to break when previewed."
end
@order = ShopifyAPI::Order.find(params[:id])
respond_to do |format|
format.html do
@tmpls = shop.templates
end
format.js do
# AJAX preview, loads in modal Dialog
@tmpl = shop.templates.find(params[:template_id])
@rendered_template = @tmpl.render(@order.to_liquid)
render :partial => 'preview', :locals => {:tmpl => @tmpl, :rendered_template => @rendered_template, :safe => @safe}
end
end
end
def print
@all_templates = shop.templates
@printed_templates = @all_templates.find(params[:print_templates])
@all_templates.each { |tmpl| tmpl.update_attribute(:default, @printed_templates.include?(tmpl)) }
head 200
end
end<file_sep>/app/models/print_template.rb
require 'rexml/document'
class PrintTemplate < ActiveRecord::Base
belongs_to :shop
has_many :versions, :class_name => 'PrintTemplateVersion', :dependent => :delete_all, :order => 'version DESC'
validates_presence_of :body, :shop_id
validates_length_of :name, :within => 2..24
validates_length_of :body, :maximum => 64.kilobytes, :message => 'cannot exceed 64kb in length'
validates_uniqueness_of :name, :scope => :shop_id
before_update :store_current_version
attr_protected :shop_id
default_scope :order => "id ASC"
MAX_TEMPLATES_PER_SHOP = 10
TOO_MUCH_TEMPLATES_ERROR = "Maximum number of templates is #{MAX_TEMPLATES_PER_SHOP}! You need to delete another template before you are able to create a new one."
def self.create_from_file(template_name)
content = File.read("#{RAILS_ROOT}/db/printing/#{template_name}.liquid")
create(:name => template_name.to_s.gsub(/[_-]/, ' ').capitalize, :body => content)
end
def parse
Liquid::Template.parse(body)
end
def check_syntax
body_with_escaped_ampersands = body.gsub(/& /, '&')
REXML::Document.new("<body>#{body_with_escaped_ampersands}</body>")
parse
return true
rescue REXML::ParseException => e
rexml_msg = e.message.split("\n").first
if rexml_msg =~ /REXML::ParseException: /
rexml_msg.gsub!("#<REXML::ParseException: ", '').gsub!(" (got \"body\")", '')
end
return false, rexml_msg
rescue RuntimeError => e
return false, e.message
rescue Liquid::SyntaxError
return false, e
end
def render(assigns)
parse.render(assigns, [MoneyFilter, StringProcessingFilter, ShopFilter, TagFilter, WeightFilter, JsonFilter])
end
def highest_version_number
versions.maximum(:version) || 0
end
def version_numbers
@version_numbers ||= versions.find(:all, :select => [ "version" ], :order => 'version DESC').collect(&:version)
end
def rollback(version)
if version = versions.find_by_version(version)
self.body = version.body
else
raise ActiveRecord::RecordNotFound, "Could not find version #{version}"
end
end
protected
def validate
if shop.templates.count > MAX_TEMPLATES_PER_SHOP
errors.add_to_base(TOO_MUCH_TEMPLATES_ERROR)
else
success, message = check_syntax
errors.add_to_base(message) unless success
end
end
private
def store_current_version
return unless body_changed?
versions.create(:body => body_was, :version => highest_version_number + 1)
end
end
<file_sep>/app/models/print_template_version.rb
class PrintTemplateVersion < ActiveRecord::Base
belongs_to :print_template
end<file_sep>/test/unit/print_template_version_test.rb
require 'test_helper'
class PrintTemplateVersionTest < ActiveSupport::TestCase
should "delete templates older than 3 months" do
PrintTemplateVersion.create :created_at => 2.weeks.ago
PrintTemplateVersion.create :created_at => 3.months.ago + 1.days
PrintTemplateVersion.create :created_at => 10.months.ago
assert_difference "PrintTemplateVersion.count", -1 do
PrintTemplateVersion.delete_all("created_at < DATE_SUB(UTC_TIMESTAMP(), INTERVAL 3 MONTH)")
end
end
end<file_sep>/lib/tasks/cleanup.rake
namespace :cleanup do
desc 'Delete old template versions'
task :print_template_versions => :environment do
tmpls = PrintTemplateVersion.delete_all("created_at < DATE_SUB(UTC_TIMESTAMP(), INTERVAL 3 MONTH)")
# puts "Deleted #{tmpls.size} templates."
end
end
<file_sep>/test/functional/print_templates_controller_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class PrintTemplatesControllerTest < ActionController::TestCase
tests PrintTemplatesController
before do
ActiveResource::Base.site = 'http://any-url-for-testing'
ShopifyAPI::Shop.stubs(:current).returns(shop)
login_session(:germanbrownies)
@tmpl = print_templates(:quotation_mark_in_title)
@tmpl_params = {:print_template => {:name => @tmpl.name, :body => @tmpl.body, :shop_id => @tmpl.shop_id}}
@params = {:format => :js}
end
context "create" do
before do
@new_template_params = {:print_template => {:name => "Quotation mark's test", :body => @tmpl.body, :shop_id => @tmpl.shop_id}}
end
should "have no problems with single quotation marks in title" do
post :create, @params.merge(@new_template_params)
assert_response_include "Messenger.notice(\"Successfully created new template named Quotation mark's test.\");"
end
should "insert a checkbox and a label via JS" do
post :create, @params.merge(@new_template_params)
tmpl = assigns(:tmpl)
# make sure the quotes are escaped (via inspect), and remove the very first and last quote
assert_response_include "<input id=\"template-checkbox-#{tmpl.id}\"".inspect[1..-2]
assert_response_include "<label for=\"template-checkbox-#{tmpl.id}\">Quotation mark's test</label>".inspect[1..-2]
end
should "insert an empty preview container at the end of the preview div on the page" do
post :create, @params.merge(@new_template_params)
tmpl = assigns(:tmpl)
assert_response_include "$(\"#preview\").append(\"<div id='preview-#{tmpl.id}'></div>\");"
end
end
context "update" do
should "have no problems with single quotation marks in title" do
put :update, @params.merge(@tmpl_params.merge(:id => @tmpl.id))
assert_response_include "Messenger.notice(\"Successfully updated template named #{@tmpl.name}.\");"
end
end
end<file_sep>/test/unit/helpers/money_helper_test.rb
require File.dirname(__FILE__) + '/../../test_helper'
class MoneyHelperTest < ActiveSupport::TestCase
before do
ActiveResource::Base.site = 'http://any-url-for-testing'
@european_shop = shop('shop.xml', {'money_format' => "€{{amount}}", 'money_with_currency_format' => "€{{amount}} EUR"})
@us_shop = shop('shop.xml', {'money_format' => "${{amount}}", 'money_with_currency_format' => "${{amount}} USD", 'currency' => "USD"})
end
context "MoneyFilter" do
before do
@filter = Object.new.extend(MoneyFilter)
end
should "cache the shop in MoneyFilter and not fetch the shop twice via ActiveResource" do
ShopifyAPI::Shop.stubs(:cached).returns(@european_shop)
@filter.money(1000)
end
should "invalidate the cached shop in MoneyFilter when a money filter is called " do
# get Shop once in order#to_liquid and once in MoneyHelper#shop
ShopifyAPI::Shop.stubs(:cached).returns(@us_shop)
assert_equal "$10.00", @filter.money(1000)
ShopifyAPI::Shop.stubs(:cached).returns(@european_shop)
# simulate a new liquid render action by including the filter again in a new object
# this will reset the instance variables (i.e. the cached remote shop)
@filter = Object.new.extend(MoneyFilter)
assert_equal "€10.00", @filter.money(1000)
end
context "European shop" do
before do
ShopifyAPI::Shop.stubs(:cached).returns(@european_shop)
end
should "render money for Fixnum value in Euros" do
assert_equal "€10.00", @filter.money(1000)
end
should "render money with currency for Fixnum values in Euros" do
assert_equal "€10.00 EUR", @filter.money_with_currency(1000)
end
should "render money for String value in Euros" do
assert_equal "€10.00", @filter.money("1000")
end
should "render money with currency for String values in Euros" do
assert_equal "€10.00 EUR", @filter.money_with_currency("1000")
end
end
context "US Shop" do
before do
ShopifyAPI::Shop.stubs(:cached).returns(@us_shop)
end
should "render money for fixnum values in $" do
assert_equal "$10.00", @filter.money(1000)
end
should "render money with currency for fixnum values in $" do
assert_equal "$10.00 USD", @filter.money_with_currency(1000)
end
end
end
context "MoneyHelper" do
before do
@helper = Object.new.extend(MoneyHelper)
ShopifyAPI::Shop.stubs(:cached).returns(@us_shop)
end
should "convert to dollar amount per default for a cents string" do
assert_equal "$10.00", @helper.money("1000")
end
should "convert to dollar amount per default for a cents number" do
assert_equal "$10.00", @helper.money(1000)
end
should "be able to convert to cent amount for a dollar string" do
assert_equal "$10.00", @helper.money("10.00", true)
end
should "be able to convert to cent amount for a dollar number" do
assert_equal "$10.00", @helper.money(10, true)
end
end
end<file_sep>/db/migrate/20130710165325_add_templates_exported_to_shops.rb
class AddTemplatesExportedToShops < ActiveRecord::Migration
def self.up
add_column :shops, :templates_exported, :boolean, :default => false
end
def self.down
remove_column :shops, :templates_exported
end
end
<file_sep>/test/unit/print_template_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class PrintTemplateTest < ActiveSupport::TestCase
before do
ActiveResource::Base.site = 'http://any-url-for-testing'
@local_shop = shops(:germanbrownies)
@remote_us_shop = shop('shop.xml', {'currency' => "USD", 'money_format' => "$ {{amount}}"})
@remote_european_shop = shop('shop.xml', {'currency' => "EUR", 'money_format' => "€{{amount}}"})
end
context "validate" do
should "not allow the same name for the same shop" do
assert @local_shop.templates.create(:name => "My name", :body => "whatever").valid?
assert_not @local_shop.templates.create(:name => "My name", :body => "something else").valid?
end
should "allow the same name for different shops" do
assert @local_shop.templates.create(:name => "My name", :body => "whatever").valid?
assert Shop.create(:url => "www.differentshop.com").templates.create(:name => "My name", :body => "something else").valid?
end
should "not allow more than 10 templates per shop" do
@local_shop.templates.destroy_all
10.times do |i|
assert @local_shop.templates.create(:name => "Template ##{i}", :body => "something").valid?
end
assert_not @local_shop.templates.create(:name => "Template #11", :body => "something").valid?
end
context "body" do
should "not be valid when larger than 64 kb" do
template = shops(:germanbrownies).templates.build(
:name => 'too_large_test',
:body => '0' * 65.kilobytes
)
assert !template.valid?
assert template.errors.on(:body)
end
should "not be saved when providing not well-formed HTML (unclosed elements)" do
tmpl = print_templates(:unclosed_tags)
assert_not tmpl.valid?
end
should "provide detailed error message for non well-formed HTML" do
tmpl = print_templates(:unclosed_tags)
tmpl.save
assert 1, tmpl.errors.size
assert_equal "Missing end tag for 'div'", tmpl.errors.full_messages.to_sentence
end
should "not be invalid when encountering an unescaped ampersand with trailing space" do
tmpl = print_templates(:unescaped_ampersand)
assert tmpl.valid?
end
end
end
context "#create_from_file" do
should "not create new record if saved already with same name" do
# saving should fail, because other tests already created an instance in the DB (no duplicate names!)
assert_not @local_shop.templates.create_from_file(:invoice).valid?
end
should "save body and name from that serialized template" do
template = @local_shop.templates.create_from_file(:invoice)
assert_equal 'Invoice', template.name
assert_equal File.read("#{RAILS_ROOT}/db/printing/invoice.liquid"), template.body
end
end
context "#rollback" do
should "revert the contents of the template to the specified version" do
template = print_templates(:custom_invoice)
template.rollback(1)
assert_equal print_template_versions(:invoice_v1).body, template.body
end
should "raise ArgumentError when version could not be found" do
assert_raises(ActiveRecord::RecordNotFound) do
template = print_templates(:custom_invoice)
template.rollback(1000)
end
end
end
context "#versions" do
before do
@packing_slip = print_templates(:packing_slip)
end
should "#version_numbers return the correct version numbers" do
expected = @packing_slip.versions.collect(&:version).sort.reverse
assert_equal expected, @packing_slip.version_numbers
end
should "create version after update" do
@packing_slip.body += "More data..."
assert_difference 'PrintTemplateVersion.count', +1 do
@packing_slip.save
end
end
should "correctly increment version numbers when updating" do
assert_difference "PrintTemplateVersion.count", 2 do
@packing_slip.body = "First change"
assert @packing_slip.save
@packing_slip.body = "Second change"
assert @packing_slip.save
end
assert_equal [2, 1], @packing_slip.version_numbers
end
end
end<file_sep>/app/models/order_calculations.rb
module OrderCalculations
def tax_shipping?
shop.tax_shipping?
end
def calculate_total_line_items_price
line_items.to_ary.sum(0) { |i| i.price * i.quantity }
end
def calculate_subtotal_price
total_line_items_price - total_discounts
end
def calculate_total_price
sum = shipping_price + subtotal_price
sum += total_tax unless taxes_included?
sum
end
def calculate_total_tax
calculator = TaxCalculator.new(shipping_address || location || {})
calculator.calculate_tax_on(tax_shipping? ? subtotal_price + shipping_price : subtotal_price,
:tax_included_in_price => taxes_included?
).total
end
def shipping_price
shipping_line ? shipping_line.price : BigDecimal.new(0)
end
def shipping_title
shipping_line ? shipping_line.title : ''
end
# added from the Order model
def recalculate(options = {})
self.total_line_items_price = calculate_total_line_items_price
self.subtotal_price = calculate_subtotal_price
self.total_price = calculate_total_price
end
# TODO: probably get rid of all the discount stuff
def apply_discount(discount)
# Block against discount being applied after an order has been authorized
return if placed?
unless applied_discount.nil?
raise DiscountError, "Only a single discount can be applied to an order"
end
unless discount.requirements_met_by?(self)
raise DiscountError, "The discount does not meet the requirements set by the shop for this order"
end
transaction do
discount = AppliedDiscount.new(
:order => self,
:amount => discount.calculate_discount(self),
:discount => discount,
:code => discount.code
)
self.applied_discount = discount
self.total_discounts = applied_discount.amount
recalculate(:recalculate_taxes => true)
save!
end
end
def discount_amount
applied_discount? ? applied_discount.amount : Money.empty
end
def discount_code
applied_discount? ? applied_discount.code : ''
end
def applied_discount?
applied_discount
end
end<file_sep>/config/routes.rb
ActionController::Routing::Routes.draw do |map|
map.connect 'templates/export', :controller => 'print_templates', :action => 'export'
map.all '*', :controller => 'login', :action => 'byebye'
# map.root :controller => 'login'
# map.logout '/logout', :controller => 'login', :action => 'logout'
#
# map.resources :orders, :only => [:index, :show], :member => {:preview => :get, :print => :post}
#
# map.resources :print_templates, :as => 'templates'
#
# map.connect ':controller/:action/:id'
# map.connect ':controller/:action/:id.:format'
end
<file_sep>/test/unit/shop_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class ShopTest < ActiveSupport::TestCase
before do
@shop = Shop.create
end
context "on_create" do
should "add default templates when created" do
assert_equal 3, @shop.templates.count
end
should "have invoice selected per default" do
assert_equal true, @shop.templates.find_by_name('invoice').default
end
end
end
<file_sep>/Gemfile
source :gemcutter
gem "rails", "2.3.18"
gem "rake", "0.8.7"
gem 'liquid', '2.3.0', :git => 'git://github.com/Shopify/liquid.git', :ref => '6ebdded'
group :production do
gem "memcached", "0.18.0"
end
group :development do
gem "mysql"
gem "mongrel"
end
group :test do
gem "mocha"
gem "context"
end
gem 'gembeat', '~> 0.0.1'
gem 'json'<file_sep>/app/controllers/application_controller.rb
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
before_filter :find_app_shop
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
protected
def shop
Shop.find_or_create_by_url(current_shop.try(:url))
end
# Show 404 page with better error explanation when an Order or Template can't be found
def rescue_action_in_public(exception)
if exception.is_a?(ActiveResource::ResourceNotFound) || exception.is_a?(ActiveRecord::RecordNotFound)
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
else
super
end
end
def find_app_shop
@app_shop ||= shop
end
end
<file_sep>/app/helpers/money_helper.rb
module MoneyHelper
def money(money, convert_from_cents = false)
MoneyHelper.format(shop.money_format, money, shop.currency, convert_from_cents)
end
def money_with_currency(money, convert_from_cents = false)
MoneyHelper.format(shop.money_with_currency_format, money, shop.currency, convert_from_cents)
end
def self.format(args, amount, currency = nil, convert_from_cents = false)
cents = amount.is_a?(String) ? amount.to_f : amount
return '' unless cents
cents = (cents * 100).to_i if convert_from_cents
args.gsub(/\{\{\s*\w+\s*\}\}/) do |format|
case format
when /\bamount_no_decimals?\b/
format_with_delimiters(cents, 0)
when /\bamount_with_comma_separator\b/
format_with_delimiters(cents, 2, '.', ',')
when /\bcurrency\b/
currency
else
format_with_delimiters(cents, 2)
end
end
end
private
def self.format_with_delimiters(cents, precision = 2, thousands = ',', decimal = '.')
parts = sprintf("%.#{precision}f", cents / 100.0).split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{thousands}")
parts.join(decimal)
end
def shop
ShopifyAPI::Shop.cached
end
end<file_sep>/test/functional/orders_controller_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class OrdersControllerTest < ActionController::TestCase
tests OrdersController
before do
ActiveResource::Base.site = 'http://any-url-for-testing'
@invoice = print_templates(:invoice)
@js_template = print_templates(:javascript_content)
ShopifyAPI::Shop.stubs(:current).returns(shop)
ShopifyAPI::Order.stubs(:find).with('1').returns(order)
login_session(:germanbrownies)
end
context "show" do
context "without template_id param" do
should "display templates in sidebar ordered by newest template at the bottom" do
get :show, {:id => 1}
assert_response :ok
templates = assigns(:tmpls)
assert_equal "Invoice", templates.first.name
end
end
context "with template_id param" do
should "render the preview of the provided template for this order" do
get :show, {:id => 1, :template_id => @invoice.id, :format => 'js'}
assert_response :ok
end
end
end
context "not logged in" do
should "redirect to index action if no shop is provided" do
get :show, {:id => 1}, {}
assert_redirected_to :controller => 'login', :action => 'index'
end
should "redirect to authenticate action if shop is provided" do
get :show, {:id => 1, :shop => "german-brownies.myshopify.com"}, {}
assert_redirected_to :controller => 'login', :action => 'index', :shop => "german-brownies.myshopify.com"
end
end
context "already logged in" do
should "render show action if no different shop is provided" do
get :show, {:id => 1}
assert_response :ok
assert_template 'show'
end
should "render show action if same shop is provided" do
get :show, {:id => 1, :shop => "german-brownies.myshopify.com"}
assert_response :ok
assert_template 'show'
end
should "render show action if same shop name (without full url) is supplied" do
get :show, {:id => 1, :shop => "german-brownies"}
assert_template 'show'
end
should "redirect to authenticate action if different shop is provided" do
get :show, {:id => 1, :shop => "american-brownies.myshopify.com"}
assert_redirected_to :controller => 'login', :action => 'index', :shop => "american-brownies.myshopify.com"
end
end
context "without safe param" do
should "NOT set save mode in controller" do
get :show, {:id => 1}
assert_not assigns(:safe)
end
should "should render javascript in templates" do
get :show, {:id => 1, :template_id => @js_template, :format => 'js'}
assert_response_include "<script type=\"text/javascript\">"
end
end
context "with safe param" do
should "set save mode in controller" do
get :show, {:id => 1, :safe => true}
assert assigns(:safe)
end
should "should NOT render javascript in templates" do
get :show, {:id => 1, :template_id => @js_template, :safe => true, :format => 'js'}
assert_not @response.body.include?("<script type=\"text/javascript\">")
end
end
end<file_sep>/app/liquid/filters/shop_filter.rb
module ShopFilter
def asset_url(input)
"http://static.shopify.com/s/files/#{resources_dir}/assets/#{input}"
end
def files_url(input)
"http://static.shopify.com/s/files/#{resources_dir}/files/#{input}"
end
def global_asset_url(input)
req = @context.registers[:request]
"http://static.shopify.com/s/global/#{input}"
end
def shopify_asset_url(input)
"http://static.shopify.com/s/shopify/#{input}"
end
def script_tag(url)
%(<script src="#{url}" type="text/javascript"></script>)
end
def stylesheet_tag(url, media="all")
%(<link href="#{url}" rel="stylesheet" type="text/css" media="#{media}" />)
end
def link_to(link, url, title="")
%|<a href="#{url}" title="#{title}">#{link}</a>|
end
def img_tag(url, alt="")
%|<img src="#{url}" alt="#{alt}" />|
end
def link_to_vendor(vendor)
if vendor
link_to vendor, url_for_vendor(vendor), vendor
else
'Unknown Vendor'
end
end
def link_to_type(type)
if type
link_to type, url_for_type(type), type
else
'Unknown Vendor'
end
end
def url_for_vendor(vendor_title)
"#{ShopifyAPI::Shop.cached.url}/admin/collections/vendors?q=#{CGI.escape(vendor_title)}"
end
def url_for_type(type_title)
"#{ShopifyAPI::Shop.cached.url}/admin/collections/types?q=#{CGI.escape(type_title)}"
end
def product_img_url(url, style = 'small')
unless url =~ /^\/?products\/([\w\-\_]+)\.(\w{2,4})/
raise ArgumentError, 'filter "product_img_url" can only be called on product images'
end
case style
when 'original'
"http://static.shopify.com/s/files/#{resources_dir}/#{url}"
when 'grande', 'large', 'medium', 'small', 'thumb', 'icon'
"http://static.shopify.com/s/files/#{resources_dir}/products/#{$1}_#{style}.#{$2}"
else
raise ArgumentError, 'valid parameters for filter "size" are: original, grande, large, medium, small, thumb and icon '
end
end
# Accepts a number, and two words - one for singular, one for plural
# Returns the singular word if input equals 1, otherwise plural
def pluralize(input, singular, plural)
input == 1 ? singular : plural
end
def resources_dir
shop_id = ShopifyAPI::Shop.cached.id
resources_dir = "1/" << ("%08d" % shop_id).scan(/..../).join('/')
end
end
<file_sep>/public/javascripts/application.js
function usingOldIE() {
return navigator.userAgent.match(/MSIE [567]/i) != null
}
Debug = function() {
// set to true to print all insertedportant javascript debug messages
// set to false to skip all debug messages (for production and browsers without Firebug)
var debug = false;
return {
log: function(text) {
if (debug) { console.log(text); }
}
};
}();
Templates = function() {
var _order = null;
var _templates = null;
var editmode = false;
var safemode = false;
/* private methods */
var togglePrintButton = function() {
if (_templates.length > 0) {
$("#print-start").hide();
$("#print-button").show();
var pluralize = _templates.length == 1 ? "document" : "documents";
$("#template-amount").html(_templates.length + " " + pluralize);
} else {
$("#print-button").hide();
$("#print-start").show();
}
};
var toggleInlinePreview = function(template) {
// preview div, which could be already inserted (cached in DOM)
var templatePreview = $("#inline-preview-" + template);
// is template selected?
if (_templates.indexOf(template) > -1) {
if (templatePreview.length > 0) {
templatePreview.show();
scrollToPreview(template);
} else {
loadInlinePreview(template);
}
} else {
templatePreview.hide();
}
};
var loadInlinePreview = function(template) {
var checkbox = $("#template-item-" + template + " :checkbox").disable();
// this is a dirty fix, because the link doesn't listen to moveout-events any more, so it doesn't get hidden, which looks weird
$("#template-delete-link-" + template).hide();
Status.show();
var requestUrl = "/orders/" + _order + "?template_id=" + template;
if (safemode) {
requestUrl += "&safe=true";
}
$.get(requestUrl, null, function(data) { checkbox.enable(); Status.hide(); $("#preview-" + template).html(data); scrollToPreview(template); });
};
var scrollToPreview = function(id) {
var targetOffset = $("#preview-" + id + " .preview-content").offset().top;
$('html,body').animate({scrollTop: targetOffset - 50}, 500);
};
var sendPrintNotification = function() {
$.ajax({
url: '/orders/' + _order + '/print',
data: $("#selected-templates").serialize(),
type: 'post'
});
};
/* public methods */
return {
initialize: function(order) {
_order = order;
_templates = [];
safemode = false;
},
checkAll: function() {
$("#selected-templates :checkbox").each(function() {
Templates.updateSelection($(this));
});
},
updateSelection: function(checkbox) {
var template = checkbox.val();
if (checkbox.attr('checked')) {
Debug.log("template-checkbox-" + template + " selected.");
if (_templates.indexOf(template) == -1) {
_templates.push(template);
}
} else {
Debug.log("template-checkbox-" + template + " deselected.");
var position = _templates.indexOf(template);
if (position > -1) { _templates.splice(position, 1); }
}
togglePrintButton();
toggleInlinePreview(template);
},
print: function() {
// Workaround for Chrome as it won't execute the print statement right after the AJAX call if invoked directly
setTimeout(sendPrintNotification, 0);
window.print();
},
select: function(template, selection) {
var checkbox = $('#template-item-' + template + " :checkbox");
checkbox.attr('checked', selection);
Templates.updateSelection(checkbox);
},
toggleEditMode: function() {
editmode = !editmode;
// disable animations for Internet Explorer < 8
if(usingOldIE()) {
$(".template-options").toggle();
$(".new-template").toggle();
} else {
$(".template-options").toggle(350);
$(".new-template").slideToggle();
}
var linkImage = $(".template-editmode a img");
if (editmode) {
linkImage.data("old-image", linkImage.attr('src')); /* Remember original link image */
linkImage.data("old-title", linkImage.attr('title'));
linkImage.attr('src', '/images/button-done.png');
linkImage.attr('title', 'Done with editing templates');
} else {
linkImage.attr("src", linkImage.data("old-image")); /* Restore original link image */
linkImage.attr("title", linkImage.data("old-title")); /* Restore original link image */
}
},
safeMode: function () {
safemode = true;
}
};
}();
// Usage: Dialog.open() and Dialog.close()
// Opens a div as a modal dialog which you need to fill yourself first
Dialog = function() {
var dlg = "#modal-dialog";
var options = {modal: true};
var percent = function(amount, percentage) {
return (amount / 100) * percentage;
};
var resizeTextArea = function() {
var dialogHeight = parseInt($(dlg).height());
var elementsHeight = 0;
$(dlg + " .fixed").each(function(index, elem){
var height = parseInt($(elem).height());
elementsHeight += height;
});
var heightModifier = 60;
var textAreaHeight = dialogHeight - elementsHeight - heightModifier; /*margin*/
Debug.log("DialogHeight: " + dialogHeight + "\nElementsHeight: " + elementsHeight + "\nTextAreaHeight: " + textAreaHeight);
$("#template_editor").height(textAreaHeight);
};
return {
open: function(title) {
var width = $(window).width();
var height = $(window).height();
// open with 80% width and height
$(dlg).dialog(jQuery.extend(options, {width: percent(width, 80), height: percent(height, 80)}, {title: title, resize: resizeTextArea, open: resizeTextArea}));
$(dlg).dialog('open');//.bind("dialogopen resize", resizeTextArea);
},
close: function() {
$(dlg).empty();
$(dlg).dialog('destroy');
}
};
}();
// Shopify Javascript Messenger
/*-------------------- Messenger Functions ------------------------------*/
// Messenger is used to manage error messages and notices
//
Messenger = function() {
var autohide_error = null;
var autohide_notice = null;
// Responsible for fading notices level messages in the dom
var fadeNotice = function() {
$('#flashnotice').fadeOut();
autohide_notice = null;
};
// Responsible for fading error messages in the DOM
var fadeError = function() {
$('#flasherrors').fadeOut();
autohide_error = null;
};
return {
// Notice-level messages. See Messenger.error for full details.
notice: function(message) {
$('#flashnotice').html(message);
$('#flashnotice').fadeIn();
if (autohide_notice != null) { clearTimeout(autohide_notice); }
autohide_notice = setTimeout(fadeNotice, 5000);
},
// When given an error message show it on the screen.
// This message will auto-hide after a specified amount of miliseconds
error: function(message) {
$('#flasherrors').html(message);
$('#flasherrors').fadeIn();
if (autohide_error != null) { clearTimeout(autohide_error); }
autohide_error = setTimeout(fadeError, 5000);
}
};
}();
// Status.show() shows a permanent Growl-like notification.
// Repeating calls to show() will leave the same first notification open.
// Status.hide() closes it again. Make sure to call hide() for EACH time you call show()!
Status = function() {
var count = 0;
return {
show: function(text) {
// don't show more than one notice at a time
if (count < 1) {
$("#notice-item-wrapper").fadeIn();
}
count++;
Debug.log("Called Status.show, count is now: " + count);
},
hide: function() {
if (count <= 1) {
$("#notice-item-wrapper").fadeOut();
count = 1;
}
count--;
Debug.log("Called Status.hide, count is now: " + count);
},
reset: function() {
count = 0;
}
};
}();<file_sep>/db/migrate/20090529202856_create_shop_url_remove_shop_name.rb
class CreateShopUrlRemoveShopName < ActiveRecord::Migration
def self.up
remove_column :shops, :name
add_column :shops, :url, :string
add_index :shops, :url
end
def self.down
add_column :shops, :name, :string
remove_column :shops, :url
remove_index :shops, :url
end
end
<file_sep>/app/models/shop.rb
class Shop < ActiveRecord::Base
has_many :templates, :class_name => "PrintTemplate"
after_create :create_base_templates
private
# Create 3 templates as a starting point for the user
def create_base_templates
templates.create_from_file(:invoice).update_attribute(:default, true)
templates.create_from_file(:packing_slip)
templates.create_from_file(:variable_reference)
end
end
<file_sep>/vendor/plugins/shopify_app/install.rb
puts
puts "Shopify App Generator"
puts "---------------------"
puts
puts "To get started, first register your app as a Shopify Partner:"
puts
puts " * Go to http://www.shopify.com/partners and create or login to your Partner account."
puts " * Jump over to the Apps tab and hit the “Create a new app button”"
puts " (Make sure to set the Return URL to http://localhost:3000/login/finalize during development)"
puts " * Run ./script/generate shopify_app <api_key> <secret>"
puts " * Set up a test shop to install your app in (do this on the Partner site)"
puts " * Run ./script/server"
puts " * Visit http://localhost:3000 and use the test shop’s URL to install this app"
puts<file_sep>/db/migrate/20090605160611_update_content_of_unmodified_default_templates.rb
class UpdateContentOfUnmodifiedDefaultTemplates < ActiveRecord::Migration
TEMPLATES = %w( invoice packing_slip variable_reference )
NEW_CONTENTS = TEMPLATES.inject({}) do |memo, template|
memo[template] = File.read("#{RAILS_ROOT}/db/printing/#{template}.liquid")
memo
end
# Hashes of old default template contents that are save to overwrite, because they haven't been changed by the user yet
ORIGINAL_MD5 = { "invoice" => ["3cbe75be4e5559a0643581bb48c43222", "cb44126c6c299701fef22058670ae34f", "77975982a6f49bc2eebf3248f4aaddbf"],
"packing_slip" => ["84054e0b1b3659a969c0d3b984aff8e7", "cbaba8dfbcc4b64955b7ed12c708a4ea", "5546720aa939062cae7b63861663c331"],
"variable_reference" => ["caa1eb749f63a296ebddf9019ba188c8", "328811bd3ee651c26f1e1c46bc8850eb", "b1775d4c8c17320f45a3d40601562f02"]
}
def self.up
transaction do
TEMPLATES.each do |template|
PrintTemplate.update_all(["body = ?", NEW_CONTENTS[template]], ["md5(body) IN (?)", ORIGINAL_MD5[template]])
end
end
end
def self.down
# can't be reversed
end
end<file_sep>/lib/tasks/backup.rake
namespace :db do
desc 'Download the database from Heroku and store it in a SQLite file'
task :backup => :environment do
today = Date.today.strftime("%m_%d_%y")
filename = "#{RAILS_ROOT}/db/backup/pixelprinter_backup_#{today}"
puts "Backing up database to #{filename}"
puts `heroku db:pull sqlite://#{filename}`
end
end<file_sep>/test/unit/order_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class OrderTest < ActiveSupport::TestCase
before do
ActiveResource::Base.site = 'http://any-url-for-testing'
end
context "generating an example order" do
before do
@order = order
end
should "be an instance of ShopifyAPI::Order" do
assert_instance_of(ShopifyAPI::Order, @order)
end
should "have an address of type ShopifyAPI::Address" do
assert_kind_of(ShopifyAPI::Address, @order.shipping_address)
end
should "have at least one line item" do
assert @order.line_items.size > 0
assert_instance_of(ShopifyAPI::LineItem, @order.line_items.first)
end
should "have at least one tax line" do
assert @order.tax_lines.size > 0
assert_instance_of(ShopifyAPI::TaxLine, @order.tax_lines.first)
end
end
context "#to_liquid" do
before do
@order = order
shop = stub(:name => "My Store", :currency => "USD", :money_format => "$ {{amount}}", :to_liquid => {'name' => "My Store"})
ShopifyAPI::Shop.stubs(:cached).returns(shop)
@liquid = @order.to_liquid
@order_with_one_note_attribute = order('example_order_one_note_attribute.xml')
@order_with_no_note_attribute = order('example_order_no_note_attribute.xml')
end
should "respond to #to_liquid" do
@order = ShopifyAPI::Order.new
assert_respond_to(@order, :to_liquid)
end
should "return the current shop with shop_name" do
assert_equal "My Store", @liquid['shop_name']
end
should "return the current shop with shop.name" do
assert_equal "My Store", @liquid['shop']['name']
end
should "return total price as cents" do
assert_equal '1960', @liquid['total_price'].to_s
end
should "return line item name" do
assert_equal "Shopify T-Shirt", @liquid['line_items'].first.name
end
should "return tax line price" do
assert_equal "2.65", @liquid['tax_lines'].first.price.to_s
end
should "return tax line rate" do
assert_equal "0.1563", @liquid['tax_lines'].first.rate.to_s
end
should "return tax line title" do
assert_equal "Taxes", @liquid['tax_lines'].first.title.to_s
end
should "return customer email with customer.email" do
assert_equal '<EMAIL>', @liquid['customer']['email']
end
should "return note" do
assert_instance_of Hash, @liquid['attributes']
assert_equal "My note", @liquid['note']
end
should "return all attributes as a Hash" do
assert_instance_of Hash, @liquid['attributes']
assert_equal "first attr value", @liquid['attributes']['First attribute']
assert_equal "second attr value", @liquid['attributes']['Second attribute']
end
should "return nil if Order doesn't have note attributes" do
assert_equal nil, @order_with_no_note_attribute.to_liquid['attributes']
end
should "return a Hash with one key if Order has only one note attribute" do
assert_equal "first attr value", @order_with_one_note_attribute.to_liquid['attributes']['First attribute']
end
end
end<file_sep>/app/liquid/filters/string_processing_filter.rb
module StringProcessingFilter
def handleize(input)
input.to_s.to_handle
end
alias :handle :handleize
# does to_handle first -- not the same as active_support camelcase!
def camelize(input)
input.to_s.to_handle.gsub(/-/,"_").camelize
end
alias :camelcase :camelize
end<file_sep>/test/test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class ActiveSupport::TestCase
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
# Every Active Record database supports transactions except MyISAM tables
# in MySQL. Turn off transactional fixtures in this case; however, if you
# don't care one way or the other, switching from MyISAM to InnoDB tables
# is recommended.
#
# The only drawback to using transactional fixtures is when you actually
# need to test transactions. Since your test is bracketed by a transaction,
# any transactions started in your code will be automatically rolled back.
self.use_transactional_fixtures = true
# Instantiated fixtures are slow, but give you @david where otherwise you
# would need people(:david). If you don't want to migrate your existing
# test cases which use the @david style and don't mind the speed hit (each
# instantiated fixtures translates to a database query per test method),
# then set this back to true.
self.use_instantiated_fixtures = false
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
protected
def order(file = 'example_order.xml')
order_xml = load_data(file)
ShopifyAPI::Order.new(Hash.from_xml(order_xml)['order'])
end
def shop(file = 'shop.xml', overwrites = {})
shop_xml = load_data(file)
shop_hash = Hash.from_xml(shop_xml)['shop'].merge(overwrites)
ShopifyAPI::Shop.new(shop_hash)
end
def login_session(shop_fixture)
shop = shops(shop_fixture)
Shop.stubs(:find_by_url).returns(shop)
@request.session[:shopify] = ShopifyAPI::Session.new(shop.url, 'somerandomtoken')
end
# ====================
# Custom Assertions
#
def assert_not(expression)
assert_block("Expected <#{expression}> to be false!") { not expression }
end
def assert_response_include(code)
assert_block("Expected the response <#{@response.body}> to include the following content: <#{code}>") do
@response.body.include?(code)
end
end
private
def load_data(file)
File.read("#{Rails.root}/test/data/#{file}")
end
end
<file_sep>/app/liquid/filters/money_filter.rb
module MoneyFilter
def money(money)
MoneyHelper.format(shop.money_format, money, shop.currency)
end
def money_with_currency(money)
MoneyHelper.format(shop.money_with_currency_format, money, shop.currency)
end
def money_no_decimals(money)
MoneyHelper.format(shop.money_format, money, shop.currency, true)
end
def money_without_currency(money)
sprintf("%.2f", money.to_i/100.0)
end
private
def shop
ShopifyAPI::Shop.cached
end
end<file_sep>/vendor/plugins/shopify_app/lib/shopify_login_protection.rb
module ShopifyLoginProtection
def shopify_session
if session[:shopify]
begin
# session[:shopify] set in LoginController#finalize
ActiveResource::Base.site = session[:shopify].site
yield
ensure
ActiveResource::Base.site = nil
end
else
session[:return_to] = request.request_uri
redirect_to :controller => 'login'
end
end
def current_shop
session[:shopify]
end
end<file_sep>/app/helpers/print_template_helper.rb
module PrintTemplateHelper
def rollback_link(template_name)
link_to_remote "Older revisions…", {
:url => {
:action => 'fetch_versions',
:template_name => template_name
},
:before => "$('#rollback-link').replaceWith('<span id=\"rollback-link\">Loading…</span>')",
:success => "$('#rollback-link').replaceWith('View revision:')"
}, { :id => 'rollback-link' }
end
def version_options_for_select(versions)
options = [["Current", ""]]
options.concat(versions)
options_for_select(options)
end
end<file_sep>/app/helpers/application_helper.rb
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def shop_admin_url(sub_page = nil)
sub_page = "/#{sub_page}" if sub_page
"https://#{current_shop.url}/admin#{sub_page}"
end
def shopify_order_url(order)
"#{shop_admin_url}/orders/#{order.id}"
end
end
<file_sep>/vendor/plugins/shopify_app/lib/shopify_api.rb
require 'ostruct'
require 'digest/md5'
module ShopifyAPI
module Countable
def count(options = {})
Integer(get(:count, options))
end
end
#
# The Shopify API authenticates each call via HTTP Authentication, using
# * the application's API key as the username, and
# * a hex digest of the application's shared secret and an
# authentication token as the password.
#
# Generation & acquisition of the beforementioned looks like this:
#
# 0. Developer (that's you) registers Application (and provides a
# callback url) and receives an API key and a shared secret
#
# 1. User visits Application and are told they need to authenticate the
# application first for read/write permission to their data (needs to
# happen only once). User is asked for their shop url.
#
# 2. Application redirects to Shopify : GET <user's shop url>/admin/api/auth?api_key=<API key>
# (See Session#create_permission_url)
#
# 3. User logs-in to Shopify, approves application permission request
#
# 4. Shopify redirects to the Application's callback url (provided during
# registration), including the shop's name, and an authentication token in the parameters:
# GET client.com/customers?shop=snake-oil.myshopify.com&t=a94a110d86d2452eb3e2af4cfb8a3828
#
# 5. Authentication password computed using the shared secret and the
# authentication token (see Session#computed_password)
#
# 6. Profit!
# (API calls can now authenticate through HTTP using the API key, and
# computed password)
#
# LoginController and ShopifyLoginProtection use the Session class to set Shopify::Base.site
# so that all API calls are authorized transparently and end up just looking like this:
#
# # get 3 products
# @products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
#
# # get latest 3 orders
# @orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
#
# As an example of what your LoginController should look like, take a look
# at the following:
#
# class LoginController < ApplicationController
# def index
# # Ask user for their #{shop}.myshopify.com address
# end
#
# def authenticate
# redirect_to ShopifyAPI::Session.new(params[:shop]).create_permission_url
# end
#
# # Shopify redirects the logged-in user back to this action along with
# # the authorization token t.
# #
# # This token is later combined with the developer's shared secret to form
# # the password used to call API methods.
# def finalize
# shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
# if shopify_session.valid?
# session[:shopify] = shopify_session
# flash[:notice] = "Logged in to shopify store."
#
# return_address = session[:return_to] || '/home'
# session[:return_to] = nil
# redirect_to return_address
# else
# flash[:error] = "Could not log in to Shopify store."
# redirect_to :action => 'index'
# end
# end
#
# def logout
# session[:shopify] = nil
# flash[:notice] = "Successfully logged out."
#
# redirect_to :action => 'index'
# end
# end
#
class Session
cattr_accessor :api_key
cattr_accessor :secret
cattr_accessor :protocol
self.protocol = 'https'
attr_accessor :url, :token, :name
def self.setup(params)
params.each { |k,value| send("#{k}=", value) }
end
def initialize(url, token = nil, params = nil)
self.url, self.token = url, token
if params && params[:signature]
unless self.class.validate_signature(params) && params[:timestamp].to_i > 24.hours.ago.utc.to_i
raise "Invalid Signature: Possible malicious login"
end
end
self.class.prepare_url(self.url) unless url.blank?
end
def shop
Shop.current
end
def create_permission_url
"http://#{url}/admin/api/auth?api_key=#{api_key}"
end
# Used by ActiveResource::Base to make all non-authentication API calls
#
# (ShopifyAPI::Base.site set in ShopifyLoginProtection#shopify_session)
def site
"#{protocol}://#{api_key}:#{computed_password}@#{url}/admin"
end
def valid?
[url, token].all?
end
private
# The secret is computed by taking the shared_secret which we got when
# registring this third party application and concating the request_to it,
# and then calculating a MD5 hexdigest.
def computed_password
Digest::MD5.hexdigest(secret + token.to_s)
end
def self.prepare_url(url)
url.gsub!(/https?:\/\//, '') # remove http:// or https://
url.concat(".myshopify.com") unless url.include?('.') # extend url to myshopify.com if no host is given
end
def self.validate_signature(params)
return false unless signature = params[:signature]
sorted_params = params.except(:signature, :action, :controller).collect{|k,v|"#{k}=#{v}"}.sort.join
Digest::MD5.hexdigest(secret + sorted_params) == signature
end
end
class Base < ActiveResource::Base
extend Countable
end
# Shop object. Use Shop.current to receive
# the shop. Since you can only ever reference your own
# shop this model does not have a .find method.
#
class Shop < Base
def self.current
find(:one, :from => "/admin/shop.xml")
end
end
# Custom collection
#
class CustomCollection < Base
def products
Product.find(:all, :params => {:collection_id => self.id})
end
def add_product(product)
Collect.create(:collection_id => self.id, :product_id => product.id)
end
def remove_product(product)
collect = Collect.find(:first, :params => {:collection_id => self.id, :product_id => product.id})
collect.destroy if collect
end
end
class SmartCollection < Base
def products
Product.find(:all, :params => {:collection_id => self.id})
end
end
# For adding/removing products from custom collections
class Collect < Base
end
class Address < Base
def street
string = address1
string += " #{address2}" if address2
string
end
end
class ShippingAddress < Address
end
class BillingAddress < Address
end
class LineItem < Base
def variant
Variant.find(variant_id, :params => {:product_id => product_id})
end
def product
Product.find(product_id)
end
end
class ShippingLine < Base
end
class Order < Base
def close; load_attributes_from_response(post(:close)); end
def open; load_attributes_from_response(post(:open)); end
def transactions
Transaction.find(:all, :params => { :order_id => id })
end
def capture(amount = "")
Transaction.create(:amount => amount, :kind => "capture", :order_id => id)
end
end
class Product < Base
# Share all items of this store with the
# shopify marketplace
def self.share; post :share; end
def self.unshare; delete :share; end
# compute the price range
def price_range
prices = variants.collect(&:price)
format = "%0.2f"
if prices.min != prices.max
"#{format % prices.min} - #{format % prices.max}"
else
format % prices.min
end
end
def collections
CustomCollection.find(:all, :params => {:product_id => self.id})
end
def smart_collections
SmartCollection.find(:all, :params => {:product_id => self.id})
end
def add_to_collection(collection)
collection.add_product(self)
end
def remove_from_collection(collection)
collection.remove_product(self)
end
end
class Variant < Base
self.prefix = "/admin/products/:product_id/"
def product
Product.find(product_id)
end
end
class Image < Base
self.prefix = "/admin/products/:product_id/"
# generate a method for each possible image variant
[:pico, :icon, :thumb, :small, :medium, :large, :original].each do |m|
reg_exp_match = "/\\1_#{m}.\\2"
define_method(m) { src.gsub(/\/(.*)\.(\w{2,4})/, reg_exp_match) }
end
def attach_image(data, filename = nil)
attributes['attachment'] = Base64.encode64(data)
attributes['filename'] = filename unless filename.nil?
end
end
class Transaction < Base
self.prefix = "/admin/orders/:order_id/"
end
class Fulfillment < Base
self.prefix = "/admin/orders/:order_id/"
end
class Country < Base
end
class Page < Base
end
class Blog < Base
def articles
Article.find(:all, :params => { :blog_id => id })
end
end
class Article < Base
self.prefix = "/admin/blogs/:blog_id/"
end
class Comment < Base
def remove; load_attributes_from_response(post(:remove)); end
def ham; load_attributes_from_response(post(:ham)); end
def spam; load_attributes_from_response(post(:spam)); end
def approve; load_attributes_from_response(post(:approve)); end
end
class Province < Base
self.prefix = "/admin/countries/:country_id/"
end
class Redirect < Base
end
# Assets represent the files that comprise your theme.
# There are different buckets which hold different kinds
# of assets, each corresponding to one of the folders
# within a theme's zip file: layout, templates, and
# assets. The full key of an asset always starts with the
# bucket name, and the path separator is a forward slash,
# like layout/theme.liquid or assets/bg-body.gif.
#
# Initialize with a key:
# asset = ShopifyAPI::Asset.new(:key => 'assets/special.css')
#
# Find by key:
# asset = ShopifyAPI::Asset.find('assets/image.png')
#
# Get the text or binary value:
# asset.value # decodes from attachment attribute if necessary
#
# You can provide new data for assets in a few different ways:
#
# * assign text data for the value directly:
# asset.value = "div.special {color:red;}"
#
# * provide binary data for the value:
# asset.attach(File.read('image.png'))
#
# * set a URL from which Shopify will fetch the value:
# asset.src = "http://mysite.com/image.png"
#
# * set a source key of another of your assets from which
# the value will be copied:
# asset.source_key = "assets/another_image.png"
class Asset < ActiveResource::Base
self.primary_key = 'key'
# find an asset by key:
# ShopifyAPI::Asset.find('layout/theme.liquid')
def self.find(*args)
if args[0].is_a?(Symbol)
super
else
find(:one, :from => "/admin/assets.xml", :params => {:asset => {:key => args[0]}})
end
end
# For text assets, Shopify returns the data in the 'value' attribute.
# For binary assets, the data is base-64-encoded and returned in the
# 'attachment' attribute. This accessor returns the data in both cases.
def value
attributes['value'] ||
(attributes['attachment'] ? Base64.decode64(attributes['attachment']) : nil)
end
def attach(data)
self.attachment = Base64.encode64(data)
end
def destroy #:nodoc:
connection.delete(element_path(:asset => {:key => key}), self.class.headers)
end
def new? #:nodoc:
false
end
def self.element_path(id, prefix_options = {}, query_options = nil) #:nodoc:
prefix_options, query_options = split_options(prefix_options) if query_options.nil?
"#{prefix(prefix_options)}#{collection_name}.#{format.extension}#{query_string(query_options)}"
end
def method_missing(method_symbol, *arguments) #:nodoc:
if %w{value= attachment= src= source_key=}.include?(method_symbol)
wipe_value_attributes
end
super
end
private
def wipe_value_attributes
%w{value attachment src source_key}.each do |attr|
attributes.delete(attr)
end
end
end
class RecurringApplicationCharge < ActiveResource::Base
def self.current
find(:all).find{|charge| charge.status == 'active'}
end
def cancel
load_attributes_from_response(self.destroy)
end
end
class ApplicationCharge < ActiveResource::Base
end
end<file_sep>/lib/tasks/templates.rake
namespace :templates do
desc 'Get MD5 hash of current printing templates'
task :hashes => :environment do
['invoice', 'packing_slip', 'variable_reference'].each do |tmpl|
path = "#{RAILS_ROOT}/db/printing/#{tmpl}.liquid"
content = File.read(path)
hash = Digest::MD5.hexdigest(content)
puts "#{hash} -> #{tmpl}"
end
end
end
<file_sep>/app/controllers/login_controller.rb
class LoginController < ApplicationController
def byebye
render :file => "#{RAILS_ROOT}/public/index.html"
end
def index
# don't ask user for his #{shop}.myshopify.com address if it is already provided
redirect_to :controller => 'login', :action => "authenticate", :shop => params[:shop] if params[:shop].present?
end
def authenticate
if params[:shop].blank?
flash[:error] = "You entered a blank domain, please try again."
redirect_to(:back)
else
if Shop.find_by_url(myshopify_url(params[:shop]))
session.delete :new_user
redirect_to ShopifyAPI::Session.new(params[:shop]).create_permission_url
else
block_new_shop
end
end
end
# Shopify redirects the logged-in user back to this action along with
# the authorization token t.
#
# This token is later combined with the developer's shared secret to form
# the password used to call API methods.
def finalize
shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
if shopify_session.valid?
session[:shopify] = shopify_session
if Shop.find_by_url(shopify_session.url)
session.delete :new_user
flash[:notice] = "Successfully logged into shopify store."
redirect_to session.delete(:return_to) || '/orders'
else
block_new_shop
end
else
flash[:error] = "Could not log into Shopify store."
redirect_to :action => 'index'
end
end
def logout
session[:shopify] = nil
flash[:notice] = "Successfully logged out."
redirect_to :action => 'index'
end
private
def myshopify_url(url)
if url =~ /\w+\.myshopify\.com\z/
url
else
"#{url}.myshopify.com"
end
end
def block_new_shop
flash[:error] = "PixelPrinter has been deprecated. Please <a href='http://apps.shopify.com/order-printer'>install Order Printer</a> instead."
session[:new_user] = true
redirect_to :action => 'index'
end
end
<file_sep>/lib/extensions/string_ext.rb
class String
# used in liquid filters
def to_handle
result = ActiveSupport::Inflector.transliterate(self)
result.downcase!
# remove apostrophe and bracets
result.gsub!(/[\'\"\(\)\[\]]/, '')
# strip all non word chars
result.gsub!(/\W/, ' ')
# replace all white space sections with a dash
result.gsub!(/\ +/, '-')
# trim dashes
result.gsub!(/(-+)$/, '')
result.gsub!(/^(-+)/, '')
result
end
end<file_sep>/db/migrate/20090604190626_create_print_template_versions.rb
class CreatePrintTemplateVersions < ActiveRecord::Migration
def self.up
create_table :print_template_versions do |t|
t.integer :print_template_id
t.text :body
t.datetime :created_at
t.integer :version, :default => 0
t.string :snapshot
end
end
def self.down
drop_table :print_template_versions
end
end
<file_sep>/app/liquid/filters/tag_filter.rb
module TagFilter
def link_to_tag(label, tag)
"<a title=\"Show tag #{tag}\" href=\"#{shop_url}/collections/#{@context['handle']}/#{tag}\">#{label}</a>"
end
def highlight_active_tag(tag, css_class='active')
if @context['current_tags'].include?(tag)
"<span class=\"#{css_class}\">#{tag}</span>"
else
tag
end
end
def link_to_add_tag(label, tag)
tags = (@context['current_tags'] + [tag]).uniq
"<a title=\"Show tag #{tag}\" href=\"#{shop_url}/collections/#{@context['handle']}/#{tags.join("+")}\">#{label}</a>"
end
def link_to_remove_tag(label, tag)
tags = (@context['current_tags'] - [tag]).uniq
"<a title=\"Show tag #{tag}\" href=\"#{shop_url}/collections/#{@context['handle']}/#{tags.join("+")}\">#{label}</a>"
end
private
def shop_url
"#{ShopifyAPI::Shop.cached.url}/admin"
end
end
<file_sep>/config/initializers/app_settings.rb
APP_NAME = "PixelPrinter"<file_sep>/test/functional/login_controller_test.rb
require File.dirname(__FILE__) + '/../test_helper'
class LoginControllerTest < ActionController::TestCase
tests LoginController
before do
@request_origin = "http://coming.from/here"
@request.env["HTTP_REFERER"] = @request_origin
end
context "when not logged in" do
context "index" do
should "show index template" do
get :index
assert_template 'index'
end
should "redirect to authenticate action if shop is provided" do
get :index, :shop => "german-brownies"
assert_redirected_to :action => 'authenticate', :shop => "german-brownies"
end
end
context "authenticate" do
should "redirect back if no shop is provided" do
get :authenticate
assert_redirected_to @request_origin
end
should "redirect back if blank shop is provided" do
get :authenticate, {:shop => ''}
assert_redirected_to @request_origin
end
end
end
context "when logged in" do
before do
login_session(:germanbrownies)
end
context "authenticate" do
should "redirect back if no shop is provided" do
get :authenticate
assert_redirected_to @request_origin
end
should "redirect to shop's permission url if a shop is provided" do
get :authenticate, {:shop => 'german-brownies'}
assert_redirected_to ShopifyAPI::Session.new('german-brownies').create_permission_url
end
end
context "finalize" do
before do
@return_url = "/orders?id=123&shop=german-brownies"
end
should "redirect to stored return url in session" do
get :finalize, {:shop => 'german-brownies', :t => '1234'}, @request.session.merge(:return_to => @return_url)
assert_redirected_to @return_url
end
end
end
end<file_sep>/app/controllers/print_templates_controller.rb
class PrintTemplatesController < ApplicationController
around_filter :shopify_session, :except => :export
before_filter :authenticate, :only => :export
def index
@tmpls = shop.templates
respond_to do |format|
format.html
format.xml do
render :xml => @tmpls
end
end
end
def show
# Not used at the moment (see orders/show)
@tmpl = shop.templates.find(params[:id])
@order = ShopifyAPI::Order.find(params[:order_id])
end
def new
@tmpl = shop.templates.new
if params[:id]
original = shop.templates.find(params[:id])
@tmpl.name = original.name + "--COPY"
@tmpl.body = original.body
end
# render RJS template
end
def create
@tmpl = shop.templates.build(params[:print_template])
if @tmpl.save
# render RJS template
else
render :update do |page|
error = @tmpl.errors.full_messages.to_sentence
page << "Messenger.error(\"Error: #{escape_javascript(error)}.\");"
end
end
end
def edit
@tmpls = shop.templates
@tmpl = @tmpls.find(params[:id])
# render RJS template
end
def update
@tmpl = shop.templates.find(params[:id])
if @tmpl.update_attributes(params[:print_template])
# render RJS template
else
render :update do |page|
error = @tmpl.errors.full_messages.to_sentence
page << "Messenger.error(\"Error: #{escape_javascript(error)}.\");"
end
end
end
def destroy
@tmpl = shop.templates.find(params[:id])
@tmpl.destroy
respond_to do |format|
format.html do
redirect_to :action => 'index'
end
format.js do
# render RJS template
end
format.xml do
head :ok
end
end
end
def fetch_versions
@tmpl = shop.templates.find_by_name(params[:template_name])
respond_to do |format|
format.js
end
end
def rollback_template
@tmpl = shop.templates.find_by_name(params[:template_name])
@tmpl.rollback(params[:template_version]) if params[:template_version].present?
render :update do |page|
page << "$('#template_editor').val(#{@tmpl.body.inspect});"
end
end
def export
if params[:shop].present? && shop = Shop.find_by_url(params[:shop])
shop.update_attribute(:templates_exported, true)
render :xml => shop.templates.to_xml(:only => [:name, :body, :default]), :status => 200
else
head :not_found
end
end
private
def authenticate
authenticate_or_request_with_http_basic do |user, pass|
user == ENV['PIXELPRINTER_EXPORT_USERNAME'] &&
pass == ENV['<PASSWORD>']
end
end
end
<file_sep>/lib/extensions/shopify_api_ext.rb
module ShopifyAPI
module PriceConversion
def to_cents(amount)
(amount.to_f * 100).round
end
end
class Shop < Base
cattr_accessor :cached
def to_liquid
{
'name' => name,
'email' => email,
'address' => address1,
'city' => city,
'zip' => zip,
'country' => country,
'phone' => phone,
'province' => province,
'owner' => shop_owner
}
end
end
class Address < Base
def to_liquid
address_hash = Hash.from_xml(to_xml)
# is either shipping address or billing address
address_hash[address_hash.keys.first].merge('street' => street)
end
def street
string = address1
string += " #{address2}" if address2
string
end
end
class ShippingAddress < Address
end
class BillingAddress < Address
end
class Order < Base
include OrderCalculations
include PriceConversion
def self.lookup(id)
Rails.cache.fetch("orders/#{id}", :expires_in => 1.hour) do
find(id)
end
end
def shipping_line
case shipping_lines.size
when 0
nil
when 1
shipping_lines.first
else
title = shipping_lines.collect(&:title).to_sentence
price = shipping_lines.to_ary.sum(&:price)
{:title => title, :price => to_cents(price)}
end
end
def to_liquid
fulfilled, unfulfilled = line_items.partition {|item| item.fulfilled?}
shop = Shop.cached
{
'id' => id,
'created_at' => created_at.in_time_zone,
'name' => name,
'email' => email,
'gateway' => gateway,
'order_name' => name,
'order_number' => number,
'shop_name' => shop.name,
'subtotal_price' => to_cents(subtotal_price),
'total_price' => to_cents(total_price),
'tax_price' => to_cents(total_tax),
'tax_lines' => tax_lines,
'shipping_price' => shipping_price,
'shipping_address' => shipping_address,
'billing_address' => billing_address,
'line_items' => line_items,
'fulfilled_line_items' => fulfilled,
'unfulfilled_line_items' => unfulfilled,
'shipping_methods' => shipping_lines,
'shipping_method' => shipping_line,
'note' => note,
'attributes' => note_attributes,
'customer' => {'email' => email, 'name' => billing_address.name},
'shop' => shop.to_liquid,
'total_discounts' => to_cents(total_discounts),
'financial_status' => financial_status,
'fulfillment_status' => fulfillment_status,
'payment_details' => payment_details,
'credit_card' => payment_details, # keep credit_card for legacy reasons because it was named like that intially on the shopify side
'discounts' => discounts,
'discounts_savings' => discounts.present? && discounts.first.savings,
'discounts_amount' => discounts.present? && discounts.first.amount
}
end
private
def shipping_address
attributes['shipping_address']
end
def shipping_price
shipping_line && to_cents(shipping_line.price)
end
def note_attributes
[attributes['note_attributes']].flatten.inject({}) do |memo, attr|
memo[attr.name] = attr.value
memo
end
end
def payment_details
details = attributes['payment_details']
number = details && details.credit_card_number
company = details && details.credit_card_company
{
'number' => number,
'credit_card_number' => number,
'company' => company,
'credit_card_company' => company
}
end
def discounts
return nil if discount_codes.empty?
discount_codes.map do |discount_code|
Discount.new(discount_code.attributes)
end
end
def line_items
items = super
items.each do |item|
item.order_id = self.id
end
items
end
class Discount < Base
include PriceConversion
def savings
amount.to_f * -1
end
def to_liquid
{
'amount' => to_cents(amount),
'savings' => to_cents(savings),
'code' => code,
'title' => code
}
end
end
end
class LineItem < Base
include PriceConversion
def to_liquid
{
'id' => id,
'title' => name,
'price' => to_cents(price),
'line_price' => (to_cents(price) * quantity),
'quantity' => quantity,
'sku' => sku,
'grams' => grams,
'vendor' => vendor,
'variant_id' => variant_id,
'variant' => lambda { variant },
'product' => lambda { product },
'fulfillment'=> lambda { last_successful_fulfillment },
'properties' => line_item_properties
}
end
def variant
@variant ||= Variant.lookup(variant_id, product_id)
end
def product
@product ||= Product.lookup(product_id)
end
def order
@order ||= Order.lookup(order_id)
end
def fulfilled?
fulfillment_status == 'fulfilled'
end
def last_successful_fulfillment
@fulfillment ||= begin
sorted_fulfillments = order.fulfillments.sort{|a, b| b.created_at <=> a.created_at}
sorted_fulfillments.find do |fulfillment|
fulfillment.line_items.any?{|item| item.variant_id == self.variant_id }
end
end
end
def line_item_properties
return properties if properties.first.is_a?(Array)
properties.map do |properties_array|
[properties_array.name, properties_array.value]
end
end
end
class Product < Base
def self.lookup(id)
Rails.cache.fetch("products/#{id}", :expires_in => 1.hour) do
find(id)
end
end
def to_liquid
{
'id' => id,
'title' => title,
'handle' => handle,
'content' => body_html,
'description' => body_html,
'vendor' => vendor,
'type' => product_type,
'variants' => variants.collect(&:to_liquid),
'images' => images.collect(&:to_liquid),
'featured_image' => images.first,
'tags' => all_tags,
'price' => price_range,
'url' => "/products/#{handle}",
'options' => options.collect(&:name)
}
end
def all_tags
tags.blank? ? [] : tags.split(",").collect(&:strip)
end
end
class Image < Base
def to_liquid
src.match(/\/(products\/.*)\?/)[0]
end
end
class Variant < Base
include PriceConversion
def self.lookup(id, product_id)
Rails.cache.fetch("products/#{product_id}/variants/#{id}", :expires_in => 1.hour) do
find(id, {:params => {:product_id => product_id}})
end
end
# truncated (as opposed to Shopify's model) for simplicity
def to_liquid
{
'id' => id,
'title' => title,
'option1' => option1,
'option2' => option2,
'option3' => option3,
'price' => to_cents(price),
'weight' => grams,
'compare_at_price' => to_cents(compare_at_price),
'inventory_quantity' => inventory_quantity,
'sku' => sku
}
end
end
class ShippingLine < Base
include PriceConversion
def to_liquid
{'title' => title, 'price' => to_cents(price)}
end
end
class TaxLine < Base
include PriceConversion
def to_liquid
{
'price' => to_cents(price),
'rate' => rate,
'title' => title
}
end
end
class Fulfillment < Base
def to_liquid
{
'tracking_number' => tracking_number,
'tracking_company' => tracking_company,
'created_at' => created_at
#'tracking_url' => tracking_url
}
end
end
# TODO: remove this, and see if Heroku still can't find ShopifyAPI::Product::Option (it worked locally somehow with adding theclass)
class Product < Base
class Option < Base
def to_liquid
name
end
def to_s
name
end
end
end
end
|
01ff3cb2b6095f6569845d246c7a75044a15a592
|
[
"JavaScript",
"Ruby"
] | 42
|
Ruby
|
Orphist/pixelprinter
|
4370a50ac3b50ee297fd69d064f25aa633923065
|
99d70c6517902f4f11fc48930264f5204067e326
|
refs/heads/master
|
<repo_name>django-tagtools/djtt-tagging<file_sep>/tagging/management/commands/normalize_tags.py
from django.core.management.base import BaseCommand, CommandError
from tagging.models import Tag
from tagging.utils import TagNameNormalizer
class Command(BaseCommand):
help = 'Normalizes all tag names using the current normalization settings'
def handle(self, *args, **options):
for tag in Tag.objects.all():
normalized_name = TagNameNormalizer.normalize(tag.name)
if normalized_name == tag.name:
self.stdout.write('Skipping: %s\n' % tag.name)
continue
try:
existing_tag = Tag.objects.get(name=normalized_name)
self.stdout.write('Merging: %s => %s\n' %
(tag.name, existing_tag.name)
)
tag.merge_into(existing_tag)
continue
except Tag.DoesNotExist:
self.stdout.write('Renaming: %s => %s\n' %
(tag.name, normalized_name)
)
tag.name = normalized_name
tag.save()
self.stdout.write('Done normalizing tags names.\n')<file_sep>/README.txt
=======================
Django TagTools Tagging
=======================
This is a generic tagging application for Django projects, originally based
off of brosner/django-tagging which is no longer maintained. Our intent is
to maintain an upgrade path from django-tagging through the use of South
migrations.
In an effort to help keep a Django tagging project moving forward and not
stagnate like many others, this project has been put under a GitHub "organization".
The idea being that if the current maintainers no longer can maintain it, that
the baton can be easily passed on to someone else.
For installation instructions, see the file "INSTALL.txt" in this directory; for
instructions on how to use this application, and on what it provides, see the
file "overview.txt" in the "docs/" directory.
What Is New
===========
The following is a summary of what has changed since forking from django-tagging:
* Support has been dropped for legacy Django. This works on Django 1.3+,
anything less than that is not being tested.
* Tag name normalization has been added. You can now specify via a setting that
all tags be stored as upper-case, lower-case, or capitalized regardless of how
the user enters them in. A Django managment function has been added to normalize
all tags based on your current setting.
* Basic synonym support has been added. Tags can now have a series of synonyms
attached to them. Any time a synonym is used when adding a tag to a piece of
content, it will be replaced with the tag when the object is saved.
* Tags now have a display name. If you want to override the display of a tags
name, fill in the display name in the tag admin. The Tag model now has a
get_display_name method which will get the display name (if it exists) or the
regular tag name otherwise.
Contributors
============
Sponsorship for the Django TagTools project has been provided by:
Ground Truth Trekking (http://www.groundtruthtrekking.org)
Based on the original code, written by:
<NAME> <<EMAIL>>
Enhanced by:
<NAME> (http://www.outside<EMAIL>) <<EMAIL>><file_sep>/tagging/admin.py
from django.contrib import admin
from tagging.models import Tag, TaggedItem, Synonym
from tagging.forms import TagAdminForm
class SynonymInline(admin.TabularInline):
model = Synonym
class TagAdmin(admin.ModelAdmin):
form = TagAdminForm
inlines = [SynonymInline,]
admin.site.register(TaggedItem)
admin.site.register(Tag, TagAdmin)<file_sep>/tagging/settings.py
"""
Convenience module for access of custom tagging application settings,
which enforces default settings when the main settings module does not
contain the appropriate settings.
"""
from django.conf import settings
#
# The maximum length of a tag's name.
#
MAX_TAG_LENGTH = getattr(settings, 'MAX_TAG_LENGTH', 50)
#
# Whether or not tage case should be normalized. Supported values are either
# False or one of the method names in utils.TagNameNormalizer (i.e. upper_case,
# lower_case, and capwords).
#
# Backwards compatibility is provided for the old FORCE_LOWERCASE_TAGS
# configuration option.
#
if hasattr(settings, 'FORCE_LOWERCASE_TAGS') and settings.FORCE_LOWERCASE_TAGS:
NORMALIZE_TAG_CASE = 'lower_case'
else:
NORMALIZE_TAG_CASE = getattr(settings, 'NORMALIZE_TAG_CASE', False)
|
ee5ed56835ce5586f5fd87112f7cb928396c9bba
|
[
"Python",
"Text"
] | 4
|
Python
|
django-tagtools/djtt-tagging
|
d1306a80ef5c4b87f46c85ea50c7e23ae3f9a389
|
e4f667edd18da937b8060273ea08029a9478991b
|
refs/heads/master
|
<file_sep><?php
namespace App\Repositories;
use App\Models\Task;
use InfyOm\Generator\Common\BaseRepository;
class TaskRepository extends BaseRepository
{
/**
* @var array
*/
protected $fieldSearchable = [
'title',
'description',
'priority_id',
'user_id',
'to_user_id',
'task_start',
'task_end',
'active'
];
/**
* Configure the Model
**/
public function model()
{
return Task::class;
}
}
<file_sep># adminlte-generator
### Boilerplate of Laravel with InfyOm Laravel Generator for AdminLTE Templates
# infiOm_tasks
|
0efe8c459e6d4b9350316df612af54f9df15854d
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
jsagithub/infiOm_tasks
|
f8094b9d4c687e3107437df958e287ffa3d8c57b
|
185899bc7ce4584ce3995d0930947d5439db7445
|
HEAD
|
<repo_name>GR2015/pythonBasic<file_sep>/day2/exercise/print.py
#coding=utf-8
#打印口图形
print "打印口图形n=2"
n=2
for i in range(n):
print '*',
print '*',
print ""
print "打印口图形n=4"
n=4
for i in range(n):
for j in range(n):
if j==0 or i==0:
print "*",
elif j==n-1 or i==n-1:
print "*",
else:
print " ",
print "\n"
print "打印N图形"
n=3
for i in range(n):
for j in range(n):
if j==0 or j==n-1 or i==j:
print "*",
else:
print " ",
print "\n"
#****打印4*4正方形
print "打印4*4正方形"
n=4
for i in range(n):
for j in range(n):
print '*',
print ""
#****打印三角形
print "打印三角形"
n=4
for i in range(n):
for j in range(i+1):
print '*',
print ""
#打印X图形
print "打印X图形n=3"
n=3
for i in range(n):
for j in range(n):
if i==j:
print "*",
elif i+j==n-1:
print "*",
else:
print " ",
print "\n"
print "打印X图形n=4"
n=4
for i in range(n):
for j in range(n):
if i==j:
print "*",
elif i+j==n-1:
print "*",
else:
print " ",
print "\n"
<file_sep>/day4/class/3.py
#coding=utf-8
def giveChange(itemPrice,giveMoney):
m=giveMoney-itemPrice
if m!=0:
listy=[1,2,5,10,20]
listy.sort()
listy.reverse()
dictx={}
for i in listy:
x=m/i
m=m%i
dictx[i]=x
for k,v in dictx.items():
print "%dÕÅ%d" %(v,k)
else:
print "no money left"
giveChange(2,100)<file_sep>/day3/class/3.py
#coding=utf-8
def max(list):
'''your code'''
''' return max value of list'''
max=list[0]
sec=list[0]
for i in list:
if i>max:
sec=max
max=i
elif i>sec:
sec=i
print sec
return sec,max
a=[2,3,6,5,4,7]
max(a)
<file_sep>/day3/hw1.py
#coding=utf-8
#一个字符串 list,每个元素是 1 个 ip,输出出现次数最多的 ip
def mostIP(lista):
dip={}
#IP和个数保存到字典中
for i in lista:
if dip.has_key(i):
dip[i]+=1
else:
dip[i]=1
#IP个数保存到列表中,排序,取最后一个即最大
listv=[]
for k,v in dip.items():
listv.append(v)
listv.sort()
max=listv[-1]
#返回字典中值最大的key,即IP
#可能存在多个IP出现次数相同,所以使用list保存
listk=[]
for k in dip.keys():
if dip[k]==max:
listk.append(k)
return listk
a=["10.1.0.1","10.1.0.2","10.1.0.1","10.1.2.58","10.1.0.2"]
print "a=",a
print "出现次数最多的IP为:", mostIP(a)<file_sep>/day4/redsun.py
from graphics import *
win = Window("redSun")
canvas = CanvasFrame(win, 300,300)
center = Point(100,100)
redius = 50
c = Circle(center,redius)
c.draw(canvas)
c.setFill("red")
win.mainloop()<file_sep>/day3/class/2.py
#coding=utf-8
def add(x,*y):
a=x
for i in y:
a+=i
print a
#return a
def sub(x,*y):
s=x
for i in y:
s-=i
print s
return s
def multi(x,*y):
m=x
for i in y:
m*=i
print m
return m
def div(x,*y):
d=x
for i in y:
if i==0:
print "³ýÊý²»ÄÜΪ0"
break
else:
d=d/i
print d
return d
add(1,2,3,4,5)
sub(1,2,3,4,5)
multi(1,2,3,4,5)
div(60,2,3,4,5)
div(1,0,2,3,4,5)
<file_sep>/day4/car.py
from graphics import *
win = Window("car")
canvas = CanvasFrame(win, 300,300)
p1 = Point(50,50)
p2 = Point(150,100)
sq = Rectangle(p1,p2)
sq.draw(canvas)
center = Point(75,113)
redius = 13
clo = Circle(center,redius)
clo.draw(canvas)
clo.setFill("black")
center = Point(75,113)
redius = 10
cli = Circle(center,redius)
cli.draw(canvas)
cli.setFill("white")
cro=clo.clone()
cro.draw(canvas)
cri=cli.clone()
cri.draw(canvas)
cro.move(45,0)
cri.move(45,0)
'''len=canvas.width-p2.x
carlen=p2.x-p1.x
step=1
for i in range(20):
sq.move(step,0)
cro.move(step,0)
cri.move(step,0)
clo.move(step,0)
cli.move(step,0)'''
#sq.move(13,0)
win.mainloop()
<file_sep>/day2/exercise/for.py
#´òӡżÊý
for i in range(10):
if i%2==0:
print "odd number is:",i
<file_sep>/day3/hw2.py
#coding=utf-8
#写一个函数,识别输入字符串是否符合 python 语法的变量名
#包含字母,下划线,和数字
#以字母和下划线开始
def isVariable(s):
if s[0]>="a" and s[0]<="z" or s[0]>="A" and s[0]<="Z" or s[0]=="_":
for i in s:
if i>="0" and i<="9":
flag=True
elif i>="a" and i<="z" or i>="A" and i<="Z":
flag=True
elif i=="_":
flag=True
else:
flag=False
break
else:
flag=False
return flag
str=raw_input("请输入变量名:")
print isVariable(str)
<file_sep>/day4/class/0.py
#coding=utf-8
class Caculator(object):
def __init__(self):
#self.x=x
#self.y=y
n=1
def add(self,x,y):
return x+y
def sub(self,x,y):
return x-y
def multi(self,x,y):
return x*y
def div(self,x,y):
if y==0:
print "³ýÊý²»ÄÜΪ0"
else:
return x/y
s=Caculator()
print s.add(5,2)
print s.sub(5,2)
print s.multi(5,2)
print s.div(5,2)<file_sep>/day2/exercise/1.py
a=range(10)
#list1
for i in a:
print i
#list2
for idx,i in enumerate(a): #枚举函数,输入序列,输出索引,和索引对应的元素
print idx,i
#list3
a='abcdefg'
for idx in range(len(a)):
print idx,a[idx]
#list4
cnt=0
for i in a:
print cnt,i
cnt+=1
#list5
cnt=0
while cnt<len(a):
print cnt,a[cnt]
cnt+=1
#dict
<file_sep>/day4/square.py
from graphics import *
win = Window("Square")
canvas = CanvasFrame(win, 300,300)
p1 = Point(50,50)
p2 = Point(60,60)
sq = Rectangle(p1,p2)
sq.draw(canvas)
win.mainloop()
<file_sep>/day4/class/c.py
from a import *
from b import *
import a
reload(a)
print var1
print a.var1<file_sep>/day3/class/5.py
#coding=utf-8
#f(0)=0,f(1)=1,f(n)=f(n-1)+f(n-2)
'''def f(n):
if n==0:
return 0
elif n==1:
return 1
else:
result=f(n-1)+f(n-2)
return result
print f(50)'''
d={}
for i in range(0,50):
d[i] = -1
d[0] = 0
d[1] = 1
def f(n):
if(n<=0):
return 0
elif (n==1):
return 1
else:
#m = f(n-1) + f(n-2)
if d[n-1] != -1: #如果d[n-1]没有赋值,重新执行
m1 = d[n-1]
else:
m1 = f(n-1)
if d[n-2] != -1:
m2 = d[n-2]
else:
m2 = f(n-2)
m = m1+m2
d[n] = m
return m
<file_sep>/day4/class/try.py
'''a=100
b='200'
try :
print a+b
except TypeError:
print "type wrong"'''
def functionName(level):
if level<1:
raise Exception('Invalid level!',level)
print functionName(0)
'''try:
print 1
except "Invalid level!":
print 2
else:
print 3'''
<file_sep>/day4/class/2.py
def f(a,n,x):
s0=a+"0"
s=""
for i in range(1,n+1):
s+=a+str(n)+'*'+x+'^'+str(n)+'+'
n-=1
return s+s0
a="a"
n=5
x="x"
print f(a,5,x)
'''#from songxia
def f(a,n,x):
sum=''
#N=n+1
for i in range(n+1):
if n==0:
sum+=a+str(n)+'*'+x+'^'+str(n)
else:
sum+=a+str(n)+'*'+x+'^'+str(n)+'+'
n-=1
return sum
n=3
x=4
print f('a',n,'x')'''
<file_sep>/day2/hw4.py
#coding=utf-8
'''
检查密码
passwd='<PASSWORD>'
密码强度第一题:
强 >=8 并且 密码包含字母和数字
中 >=8, 或者包含字母,或者数字
弱 <8 ,包含字母或者数字
c1 : 长度>=8
c2: 包含字母
c3: 包含数字
强:满足c1,c2,c3
中:满足c1 and (c2 or c3)
弱:满足c2 or c3
密码强度第二题:
c1 : 长度>=8
c2: 包含数字
c3: 包含!@#¥%
强:满足c1,c2,c3
中: 满足2个条件
弱:满足1个条件
'''
#密码强度第一题
passwd='<PASSWORD>'
#passwd=raw_input("请输入密码:")
x=len(passwd)
if x>=8:
flagc1=True
else:
flagc1=False
for i in passwd:
if i >='a' and i <='z' or i >='A' and i <='Z':
flagc2=True
break
else:
flagc2=False
for i in passwd:
if i >='0' and i <='9':
flagc3=True
break
else:
flagc3=False
while (flagc1):
if (flagc2 and flagc3):
print "密码强度为:强"
break
elif (flagc2 or flagc3):
print "密码强度为:中"
break
else:
print "密码包含非字母数字字符"
break
while (flagc1==False):
if (flagc2 or flagc3):
print "密码强度为:弱"
break
else:
print "密码包含非字母数字字符"
break
#密码强度第二题:
passwd='<PASSWORD>'
#passwd=raw_input("请输入密码:")
x=len(passwd)
if x>=8:
flagc1=True
c1=1
else:
flagc1=False
c1=0
for i in passwd:
if i in "!@#¥%":
flagc2=True
c2=1
break
else:
flagc2=False
c2=0
for i in passwd:
if i >='0' and i <='9':
flagc3=True
c3=1
break
else:
flagc3=False
c3=0
c=c1+c2+c3
if c==3:
print "强"
elif c==2:
print "中"
elif c==1:
print "弱"
else:
print "太弱"<file_sep>/day2/hw3.py
#coding=utf-8
#二分查找
x=[1,2,3,4,5,6,7,85,223]
find=3
max=len(x)
min=0
count=1
while(1):
idx =(min+max)/2
if find>x[idx]:
min=x[idx]
count+=1
elif find<x[idx]:
max=x[idx]
count+=1
else:
print "猜%d次猜对的,%d的索引是%d" %(count,x[idx],idx)
break<file_sep>/day3/class/0.py
#coding=utf-8
#用递归的方式求列表的和
#l=[1,2,3,4,5]
#f(n) = f(n-1) + l[n-1]
#n=len(n)
def f(n):
for i in range(len(n)):
if n==0:
return l[-1]
else:
result=f(n-1) + l[n-1]
return result
l=[1,2,3,4,5]
print f(l)
所有字符在单词列表里,返回true
否则返回false
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = '<PASSWORD>'
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
####### YOUR CODE HERE ######
pass # This tells your code to skip this function; delete it when you
# start working on this function
for i in secret_word:
if i in lettters_guessed":
flag=True
else:
return False
break
return flag<file_sep>/day1/homework/5.py
#coding=utf-8
s="abcdefghijklmnopqrstuvwxyz"
print s
print "字符串左移3位:",s[3:]+s[:3]
#扩展1:原串分别左移2位和右移2位怎么做?
print "字符串左移2位:",s[2:]+s[:2]
print "字符串右移2位:",s[len(s)-2:]+s[:len(s)-2]
'''扩展2:从键盘接受一个字符串和移位的长度(可以是负数),对一个字符串进行移位,如输入 ‘abcde’ 1 表示右移1位(负数表示左移),结果为’bcdea’
'''
a=raw_input("请输入字符串:")
b=int(raw_input("请输入移动位数(正数表示右移,负数表示左移):"))
le=len(a)
if b>=0:
print "右移 %d 位" %b
print a[le-b:]+a[:le-b]
else:
b=abs(b)
print "左移 %d 位" %b
print a[b:]+a[:b]<file_sep>/day3/class/4.py
#coding=utf-8
ÐèÒªÐÞ¸Ä
'''172.16.58.3
0 ~ 255'''
import sys
def isValidIp(ip):
iplist=ip.split(".")
if len(iplist)!=4:
return False
for i in iplist:
if (int(i)>=0 and int(i)<=255):
flag=True
else:
flag=False
break
return flag
print isValidIp("255.255.200.1")
print isValidIp("255.a.a.a")
<file_sep>/day1/homework/1.py
a=' | | '
b='--------'
i=3
while (i>=1):
print a
i-=1
if i<>0:
print b<file_sep>/day4/class/Caculator.py
#coding=utf-8
class Caculator(object):
def __init__(self,x,y):
self.x=x
self.y=y
def add(self):
return self.x+self.y
def sub(self):
return self.x-self.y
def multi(self):
return self.x*self.y
def div(self):
if self.y==0:
print "³ýÊý²»ÄÜΪ0"
else:
return self.x/self.y
s=Caculator(5,2)
print s.add()
print s.sub()
print s.multi()
print s.div()<file_sep>/day3/hangman_template.py
#coding=utf-8
# Name:
# Section:
# 6.189 Project 1: Hangman template
# hangman_template.py
# Import statements: DO NOT delete these! DO NOT write code above this!
from random import randrange
from string import *
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
# Import hangman words
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print "Loading word list from file..."
# inFile: file
#inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
#line = inFile.readline()
# wordlist: list of strings
wordlist = split(line)
print " ", len(wordlist), "words loaded."
print 'Enter play_hangman() to play a game of hangman!'
return wordlist
# actually load the dictionary of words and point to it with
# the words_dict variable so that it can be accessed from anywhere
# in the program
#words_dict = load_words()
# Run get_word() within your program to generate a random secret word
# by using a line like this within your program:
# secret_word = get_word()
def get_word():
"""
Returns a random word from the word list
"""
word=words_dict[randrange(0,len(words_dict))]
return word
# end of helper code
# -----------------------------------
# CONSTANTS
MAX_GUESSES = 6
# GLOBAL VARIABLES
secret_word = 'claptrap'
letters_guessed = []
# From part 3b:
def word_guessed():
'''
Returns True if the player has successfully guessed the word,
and False otherwise.
'''
global secret_word
global letters_guessed
####### YOUR CODE HERE ######
pass # This tells your code to skip this function; delete it when you
# start working on this function
for i in secret_word:
if i in letters_guessed:
flag=True
else:
flag=False
break
return flag
def print_guessed():
'''
Prints out the characters you have guessed in the secret word so far
'''
global secret_word
global letters_guessed
####### YOUR CODE HERE ######
pass # This tells your code to skip this function; delete it when you
# start working on this function
lista=["-"]*len(secret_word)
for idxi,i in enumerate(set(letters_guessed)):
for idxj,j in enumerate(secret_word):
if i==j:
lista[idxj]=secret_word[idxj]
print "current guess result:%s" %join(lista,"")
def play_hangman():
# Actually play the hangman game
global secret_word
global letters_guessed
# Put the mistakes_made variable here, since you'll only use it in this function
mistakes_made = 0
# Update secret_word. Don't uncomment this line until you get to Step 8.
# secret_word = get_word()
####### YOUR CODE HERE ######
while True:
s=raw_input("please enter a character:\n")
current_letter=lower(s[0])
letters_guessed.append(current_letter)
if word_guessed():
print "You win!The word is:%s" %secret_word
break
else:
if current_letter not in secret_word:
mistakes_made+=1
print_guessed()
print "guess left:%d" %(MAX_GUESSES-mistakes_made)
if MAX_GUESSES-mistakes_made==0:
print "You lose!"
return None
play_hangman()<file_sep>/day1/homework/2.py
import math
print "3*5/(2+3)=",3*5/(2+3)
print "math.sqrt(7+9)*2=",math.sqrt(7+9)*2
print "math.sqrt(7+9)*2=",math.pow((4-7),3)
print "math.sqrt(math.sqrt(-19+100))=",math.sqrt(math.sqrt(-19+100))
print "angle_test=",math.sin(math.pi/4)+(math.cos(math.pi/4))/2
print "ceiling_test=",math.ceil(276/19)+2*math.log(12,7)
<file_sep>/day3/class/1.py
#coding=utf-8
'''def changeme(mylist):
"修改传入的列表"
mylist.append([1,2,3,4])
print "函数内取值:",mylist
return'''
'''mylist=[10,20,30]
changeme(mylist)
print "函数外取值",mylist'''
'''def f(a)
a=1
#return a
a=2
f(a)
print a'''
def f(a,b,c,d):
print a,b,c,d
y=f(1,2,3,4)
def printinfo(name,age=35):
print "Name:",name
print "Age:",age
return'''
'''>>> printinfo(age=50,name="miki")
Name: miki
Age: 50
>>> printinfo(name="miki")
Name: miki
Age: 35
>>> printinfo('tom')
Name: tom
Age: 35
>>> printinfo('tom',15)
Name: tom
Age: 15'''
'''def printinfo(arg1,*vartuple):
print "输出"
print arg1
for var in vartuple:
print var
return
printinfo(10)
printinfo(70,60,50)
c=6
def print2(a,b,*d,**e):
print a,b,c,d,e'''
def add(x,y):
print x+y
return
def sub(x,y):
print x-y
return
def multi(x,y):
print x*y
return
def div(x,y):
if y==0:
print "除数不能为0"
else:
print x/y
return
add(10,5)
sub(10,5)
multi(10,5)
div(10,5)
div(1,0)
exp(x) 返回e的x次幂(ex),
sqrt(x) 返回数字x的平方根
import math
def hw1(x):
return x*math.exp(-x)+math.sqrt(1-math.exp(-x))
hw1(2)<file_sep>/day4/class/1.py
#coding=utf-8
import math
def math2(a,b,c):
if b*b-4*a*c<0:
return False
elif b*b-4*a*c==0:
x1=-(b/(2*a))
x2=-(b/(2*a))
return x1,x2
else:
x1=(-b+math.sqrt(b*b-4*a*c))/2*a
x2=(-b-math.sqrt(b*b-4*a*c))/2*a
return x1,x2
print math2(2,6,3)<file_sep>/day1/hello.py
#coding=utf8
print "hello word!"
<file_sep>/day2/exercise/list.py
#方法1
lista=[4,3,6]
i=1
n=len(lista)
while i<n:
lista[i]+=lista[i-1]
i+=1
lista
#方法2
lista=[4,3,6]
num=0
for idx,i in enumerate(lista):
print num,idx
num+=i
lista[idx]=num
print lista
#不改变原列表
a=[4,3,6]
b=[]
num=0
for index,i in enumerate(a):
num+=i
b.append(num)
print b
#[1,2,3,4,5,6] 变为[0,1,3,6,10,15]
a=[1,2,3,4,5,6]
new=[]
num=0
for index,i in enumerate(a):
new.append(num)
num+=a[index]
print index,i,num
print new
#奇数变平方,偶数不变[1,2,3,4,8,7,22,23]
lista=[1,2,3,4,8,7,22,23]
listb=[]
for i in lista:
if i%2==0:
listb.append(i)
else:
listb.append(i**2)
print listb
list =[1,2,3,4,8,7, 22,33, 88]
list1=[]
for i in list:
if (i%2) != 0:#或者for i%2==1
i=i*i
list1.append(i)
else :
list1.append(i)
print list1
a=['abc','efg','hij']
for i in a:
for j in i:
print i,j
#****打印4*4正方形
for i in range(4):
for j in range(4):
print '*',
print ""
*
**
***
****
n=4
for i in range(n):
for j in range(i+1):
print '*',
print ""
打印口图形
n=2
**
**
n=2
for i in range(n):
print '*'*n,
print ""
打印X图形
n=3
* *
*
* *
0,0 0.1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
x=y
x+y=2
n=3
for i in range(n):
for j in range(n):
if i==j:
print "*",
elif i+j==n-1:
print "*",
else:
print " ",
print "\n"
#如果在print末尾加逗号的话,是不会输出回车了,但是会自动输出一个空格
#用格式控制,print "%d%s" % (12,'world')
#本题中不打*坐标打印出三个空格
n=4
* *
**
**
* *
0,0 0,3
1,1 1,2
2,1 2,2
3,0 3,3
x=y
x+y=4
n=4
for i in range(n):
for j in range(n):
if i==j:
print "*",
elif i+j==n-1:
print "*",
else:
print " ",
print "\n"
a=[1,2,3]
b=[2,3,4]
c=[]
#1
for i in a:
for j in b:
if i==j:
c.append(j)
print c
#2
>>> c=[]
>>> for i in a:
... if i in b:
... c.append(i)
...
>>> c
[2, 3]
for letter in 'python':
if letter == 'h':
break
print 'current letter:',letter
所有元素and结果
a=[True,False.True,False]
c=True
for i in a:
c = c and i
print c
所有元素or结果
a=[True,False.True,False]
c=False
for i in a:
c=c or i
print c
s=raw_input('please input a number:\n')
t=int(s)
g=28
g=28
while (1):
s=raw_input('please input a number:\n')
t=int(s)
if t > g:
print 'bigger'
elif t < g:
print 'less'
else:
print 'right'
break
#!/usr/bin/python
#coding=utf-8
import random
randNum = random.randint(1,100)
print "*****************猜数游戏开始*****************"
n = 0
while 1 :
try :
receiveNum = int(raw_input("please input a positive integer x:"))
print "\n"
except :
print "please input a positive integer!\nGame Over!!!"
if receiveNum == randNum :
print "Congratulation,You Win!!!"
n += 1
print "\nA total of %d steps" %(n)
print "**********Game Over************"
break
elif receiveNum > randNum :
print "Bigger!!!\nPlease try again!!!"
n += 1
continue
else :
print "Small!!!\nPlease try again!!!"
n += 1
continue
for idx,i in enumerate(x):
二分查找
x=[1,2,3,4,5,6,7,85,223]
find=3
idx =len(x)/2
x[idx] >find, 0-m-1
x[idx] < find m- -1
128内猜7次
b=range(100)
find=44
idx=len(b)/2
for i in b:
if b[idx]>find:
print "bigger"
idx=len(idx)/2
continue
elif b[idx]<find:
print "less"
idx=(len(idx)+len(idx)/2)/2
continue
else:
print "right!"
break
s='asdfbc'
aoeiu
1. s 是否包含元字符,结果是True还是False
2. s是不是仅由元字符组成?
aoe
True
#1
a=False
s='asdfbc'
for i in s:
if i in 'aoeiuAOEIU':
a=True
break
else:
a=False
print a
#2
flag=False
s='asdfbc'
for i in s:
if i not in 'aoeiuAOEIU':
flag=True
break
else:
flag=False
continue
if flag==True:
print "not only aoeiuAOEIU"
else:
print "only aoeiuAOEIU"
#计数
#s=raw_input("please enter:")
s='asADAfdsfdsafdsaf123233223'
lcount=dcount=scount=ocount=0
for i in s:
if ord(i)>=65 and ord(i)<=122:
lcount+=1
elif ord(i)>=48 and ord(i)<=57:
dcount+=1
elif ord(i)==32:
scount+=1
else:
ocount+=1
print "number of letter is %d \nnumber of digital is %d \nnumber of space is %d \nnumber of other is %d" %(lcount,dcount,scount,ocount)
if ch >='a' and ch <='z' or ch >='A' and ch <='Z'
if ch >='0' and ch <='9'
检查密码
passwd='<PASSWORD>'
强 >=8 并且 密码包含字母和数字
中 >=8, 或者包含字母,或者数字
弱 <8 ,包含字母或者数字
密码强度第二题:
c1 : 长度>=8
c2: 包含数字
c3: 包含!@#¥%
强:满足c1,c2,c3
中: 满足2个条件
弱:满足条件
弱:满足1个条件
s=raw_input("please enter:")
if len(s)>=8:
for i in s:
if ((i >='a' and i <='z' or i >='A' and i <='Z') and (i >='0' and i <='9')):
print "high"
elif ((i >='a' and i <='z' or i >='A' and i <='Z') or (i >='0' and i <='9')):
print "media"
else:
if (i >='a' and i <='z' or i >='A' and i <='Z') or (i >='0' and i <='9'))
print "low"
s='dsfaf12234'
if len(s)>=8:
for i in s:
if ((i >='a' and i <='z' or i >='A' and i <='Z') or (i >='0' and i <='9')):
if ((i >='a' and i <='z' or i >='A' and i <='Z') and (i >='0' and i <='9')):
print "high"
else:
print "media"
1、循环遍历词典d,得到当前的k,v
2 、 之前有没有出现过,如出现了sd[v] +=1 ,如果没出现,sd[v]=1
3、print sd
d={'a':1,'b':2,'c':1,'d':3}
sd={}
for k,v in d.items():
if sd.has_key(v):
print sd
sd[v]+=1
else:
sd[v]=1
print sd
作业:
【冒泡】谢老师
打印N,口的图案
12、作业3 剩余部分
2分查找
【冒泡】谢老师 2015/8/15 17:44:56
day2\hw1.py
day2\hw2.py
day2\hw3.py
c=a and b
<file_sep>/day4/class/class.py
#coding=utf-8
#定义类
class Employee(object):
empCount=0
def __init__(self,name,salary): #构造函数,self一定有,只本身,name,salary是参数
self.name=name
self.salary=salary
Employee.empCount+=1
def displayCount(self):
print "Total Emplyee %d" %Employee.empCount
def displayEmployee(self):
print "Name:",self.name,",Salary:",self.salary
#创建实例
emp1 = Employee('tom',21)
emp2 = Employee('test',50)
#调用方法
emp1.displayEmployee()
#调用属性
print emp1.name
print "Total Emplyee %d" %Employee.empCount
<file_sep>/day4/class/b.py
#-----
var1=200
print var1<file_sep>/day1/homework/4.py
a_list=[3,5,6,12]
print a_list[0]
print a_list[3]
print a_list[1:]
print a_list
a_list.reverse()
print a_list
a_list=[3, 5, 6, 12]
b_list=[]
for i in a_list:
i*=3
b_list.append(i)
print b_list
a_list=[3, 5, 6, 12]
b_list=[]
for i in a_list:
if i%2==0:
t=True
else:
t=False
b_list.append(t)
print b_list
<file_sep>/day2/hw2.py
#coding=utf-8
#对一个list的所有元素求and,or,not
#对2个list的对应元素求and,or,生成结果list
# 一个list的所有元素求and
a=[True,False,True]
c=True
for i in a:
c=c and i
print c,
print""
# 一个list的所有元素求or
a=[True,False,True]
d=False
for i in a:
d=d or i
print d,
print""
# 一个list的所有元素求not
a=[True,False,True]
e=True
for i in a:
e=not i
print e,
print""
#2个list的对应元素求and
a=[True,False,True]
b=[True,True,True]
f=[]
for i in range(len(a)):
f.append(a[i] and b[i])
print "a and b=",f
#2个list的对应元素求or
a=[True,False,True]
b=[True,True,True]
g=[]
for i in range(len(a)):
g.append(a[i] or b[i])
print "a or b=",g
<file_sep>/day4/class/test.py
'''import calc
print calc.add(1,2)'''
from calc import sub
print sub(2,1)
<file_sep>/day3/hw3.py
#coding=utf-8
#写2个函数分别统计一个字符串里面所有字母,数字的个数
def countAlpha(s):
numAlpha=0
for i in s:
if i>="a" and i<="z" or i>="A" and i<="Z":
numAlpha+=1
return numAlpha
def countNum(s):
numDigit=0
for i in s:
if i>="0" and i<="9":
numDigit+=1
return numDigit
s=raw_input("请输入字符串:")
print "字母个数为:%d,数字个数为:%d" %(countAlpha(s),countNum(s))
<file_sep>/day4/class/calc.py
#coding=utf-8
def add(x,y):
return x+y
def sub(x,y):
return x-y
def multi(x,y):
return x*y
def div(x,y):
if y==0:
print "³ýÊý²»ÄÜΪ0"
else:
return x/y
if __name__ == "__main__":
assert 3==add(1,2)
assert 5==sub(6,1)
assert 9==multi(3,3)
assert 2==div(4,2)
<file_sep>/day2/exercise/jiaobingcha.py
#coding=utf-8
#求2个列表A,B的交、并、差
a=[1,2,3]
b=[2,3,4]
c=[]
#交
print "a=",a
print "b=",b
print "交"
for i in a:
if i in b:
c.append(i)
print c
#并
print "并"
d=[]
for i in a:
if i not in b:
d.append(i)
d.extend(b)
print d
#差
print "差"
e=[]
f=[]
for i in a:
if i not in b:
e.append(i)
print "a-b=",e
for j in b:
if j not in a:
f.append(j)
print "b-a=",f
<file_sep>/day4/Queue.py
#coding=utf-8
#队列类实现
class Queue(object):
def __init__(self,size):
self.size=size
self.queue=[]
def enqueue(self,item):
if self.isfull():
print "队列已满"
else:
self.queue.append(item)
def dequeue(self):
if self.isempty():
print "队列是空的"
else:
del self.queue[0]
def getSize(self):
return len(self.queue)
def isfull(self):
if len(self.queue)==self.size:
return True
else:
return False
def isempty(self):
if len(self.queue)==0:
return True
else:
return False
def __str__(self):
return str(self.queue)
queue1=Queue(10)
print queue1.getSize()
print queue1.isempty()
print queue1.dequeue()
for i in range(10):
queue1.enqueue(i)
print queue1
print queue1.getSize()
print queue1.isfull()
print queue1.enqueue(10)
print queue1.dequeue()
print queue1.getSize()
print queue1
<file_sep>/day3/class/conAdd.py
#coding=utf-8
#用递归的方式求列表的和
def f(n):
idx=len(l)
if n-1<0:
return l[-1]
elif n>idx:
n=idx
return f(idx)
else:
return f(n-1)+l[n-1]
l=[2,3,4,1,3,4,3,6,4]
for i in range(len(l)):
print "f(%d)=%d" %(i,f(i))
<file_sep>/day2/exercise/while.py
#!/usr/bin/python
#´òÓ¡ÆæÊý
count=0
while(count <=9):
if (count%2<>0):
print "The count is:",count
count=count+1
print "Good bye!"
|
785d004e1dad84422eefb4f63d6e99a2b78059ac
|
[
"Python"
] | 40
|
Python
|
GR2015/pythonBasic
|
b4fe4d4b366a5fd7b8db8fdb3e46a4d8b0d97ac1
|
189c9d68069976c8f7adeb6bdff6adec19d215a5
|
refs/heads/master
|
<repo_name>dmyersturnbull/codons<file_sep>/src/main/java/org/beng183/codons/Species.java
package org.beng183.codons;
/**
* The name of a species.
* @author dmyersturnbull
*/
public enum Species {
E_COLI("E. coli"), S_CEREVISIAE("S. cerevisiae");
private final String name;
private Species(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
<file_sep>/src/main/java/org/beng183/codons/SimpleDataRetrievalSystem.java
package org.beng183.codons;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.align.util.AtomCache;
import org.biojava.bio.structure.scop.BerkeleyScopInstallation;
import org.biojava.bio.structure.scop.ScopDatabase;
import org.biojava.bio.structure.scop.ScopDomain;
import org.biojava3.core.sequence.DNASequence;
import org.biojava3.core.sequence.io.FastaReaderHelper;
/**
* A simple {@link DataRetrievalSystem} that uses Entrez to fetch genetic sequences,
* and the UniProt mapping service to map between gene names, PDB identifiers, and domain identifiers.
* @author dmyersturnbull
*/
public class SimpleDataRetrievalSystem implements DataRetrievalSystem {
static class ParameterNameValue {
private final String name;
private final String value;
public ParameterNameValue(String name, String value) throws LoadException {
try {
this.name = URLEncoder.encode(name, "UTF-8");
this.value = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new LoadException(e);
}
}
}
private static final Logger logger = LogManager.getLogger(SimpleDataRetrievalSystem.class.getName());
private static final String UNIPROT_SERVER = "http://www.uniprot.org/";
private static final String ENTREZ_EFETCH_URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&rettype=fasta&retmode=text&id=";
static String run(String tool, ParameterNameValue[] params) throws LoadException {
StringBuilder message = new StringBuilder("[");
for (int i = 0; i < params.length; i++) {
message.append(params[i].name + "=" + params[i].value);
if (i < params.length - 1) message.append("; ");
}
message.append("]");
logger.debug("Query " + tool + " with " + message);
StringBuilder locationBuilder = new StringBuilder(UNIPROT_SERVER + tool + "/?");
for (int i = 0; i < params.length; i++) {
if (i > 0) locationBuilder.append('&');
locationBuilder.append(params[i].name).append('=').append(params[i].value);
}
String location = locationBuilder.toString();
URL url;
try {
url = new URL(location);
} catch (MalformedURLException e) {
throw new LoadException(e);
}
HttpURLConnection conn = null;
try {
// submit
conn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
conn.setDoInput(true);
logger.trace("Connecting...");
conn.connect();
// wait for a response
int status = conn.getResponseCode();
while (true) {
int wait = 0;
String header = conn.getHeaderField("Retry-After");
if (header != null) wait = Integer.valueOf(header);
if (wait == 0) break;
logger.trace("Waiting (" + wait + ")...");
conn.disconnect();
Thread.sleep(wait * 1000);
conn = (HttpURLConnection) new URL(location).openConnection();
conn.setDoInput(true);
conn.connect();
status = conn.getResponseCode();
}
if (status == HttpURLConnection.HTTP_OK) {
logger.trace("Received HTTP 200.");
InputStream stream = conn.getInputStream();
URLConnection.guessContentTypeFromStream(stream);
StringBuilder sb = new StringBuilder();
String line = "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.separator"));
}
}
return sb.toString();
} else {
throw new LoadException("Mapping failed. Got response " + conn.getResponseMessage());
}
} catch (IOException | InterruptedException e) {
throw new LoadException(e);
} finally {
if (conn != null) conn.disconnect();
}
}
private AtomCache cache;
private ScopDatabase scop;
// TODO these should really be soft caches
private Map<String, String> geneToPdbId = new HashMap<>();
private Map<String, WeakReference<String>> geneToSequence = new HashMap<>();
public SimpleDataRetrievalSystem() {
cache = new AtomCache();
scop = new BerkeleyScopInstallation();
}
@Override
public List<ScopDomain> getDomainsFromGeneName(String name) throws LoadException {
logger.info("Finding domains for gene " + name + "...");
String pdbId = getPdbIdFromEntrezId(name);
if (pdbId == null) throw new LoadException("Gene " + name + " not found");
List<ScopDomain> domains = scop.getDomainsForPDB(pdbId);
StringBuilder message = new StringBuilder();
for (int i = 0; i < domains.size(); i++) {
message.append(domains.get(i).getScopId());
if (i < domains.size() - 1) message.append(", ");
}
logger.info("Found scop Ids " + message.toString() + " for gene " + name);
return domains;
}
@Override
public String getGeneticSequenceFromName(String name) throws LoadException {
logger.info("Retrieving sequence for gene " + name + "...");
if (geneToSequence.containsKey(name)) {
String ans = geneToSequence.get(name).get();
if (ans != null) return ans;
}
String uniProtId = getUniProtIdFromEntrezId(name);
String id = getRefSeqIdFromUniProtId(uniProtId);
LinkedHashMap<String, DNASequence> sequences = downloadSequences(id, name);
Iterator<DNASequence> iterator = sequences.values().iterator();
if (!iterator.hasNext()) throw new LoadException("Did not find a sequence for gene with name " + name);
String sequence = iterator.next().getSequenceAsString();
geneToSequence.put(name, new WeakReference<String>(sequence));
logger.info("Found sequence of length " + sequence.length() + " for gene " + name);
return sequence;
}
static LinkedHashMap<String, DNASequence> downloadSequences(String refSeqId, String geneName) throws LoadException {
// http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=nuccore&id=34577062,24475906&rettype=fasta&retmode=text
URL url;
try {
url = new URL(ENTREZ_EFETCH_URL + refSeqId);
} catch (MalformedURLException e) {
throw new LoadException("Couldn't query for gene sequence for the gene with name " + geneName, e);
}
LinkedHashMap<String, DNASequence> sequences = new LinkedHashMap<>();
InputStream stream;
try {
stream = url.openStream();
} catch (IOException e) {
throw new LoadException("Couldn't load URL " + url + " for gene with name " + geneName, e);
}
try {
sequences = FastaReaderHelper.readFastaDNASequence(stream);
} catch (Exception e) {
throw new LoadException("Couldn't load gene sequence for the gene with name " + geneName, e);
}
return sequences;
}
static String getUniProtIdFromEntrezId(String entrezId) throws LoadException {
String uniProtIdData = run("mapping", new ParameterNameValue[] { new ParameterNameValue("from", "P_ENTREZGENEID"),
new ParameterNameValue("to", "ACC"), new ParameterNameValue("format", "tab"),
new ParameterNameValue("query", entrezId) });
String uniProtId;
try {
uniProtId = parse(uniProtIdData);
} catch (LoadException e) {
throw new LoadException("Couldn't get UniProt Id from [" + uniProtIdData + "] for gene " + entrezId);
}
return uniProtId;
}
static String getRefSeqIdFromUniProtId(String uniProtId) throws LoadException {
String refseqData = SimpleDataRetrievalSystem.run("mapping", new ParameterNameValue[] { new ParameterNameValue("from", "ACC+ID"),
new ParameterNameValue("to", "REFSEQ_NT_ID"), new ParameterNameValue("format", "tab"),
new ParameterNameValue("query", uniProtId) });
String id = SimpleDataRetrievalSystem.parse(refseqData);
return id;
}
private String getPdbIdFromEntrezId(String name) throws LoadException {
if (geneToPdbId.get(name) != null) return geneToPdbId.get(name);
String uniProtId = getUniProtIdFromEntrezId(name);
String pdbIdData = run("mapping", new ParameterNameValue[] { new ParameterNameValue("from", name),
new ParameterNameValue("to", "PDB_ID"), new ParameterNameValue("format", "tab"),
new ParameterNameValue("query", uniProtId) });
String pdbId;
try {
pdbId = parse(pdbIdData);
} catch (LoadException e) {
throw new LoadException("Couldn't get PDB Id from [" + pdbIdData + "] for gene " + name + " (from UniProtId " + uniProtId + ")");
}
geneToPdbId.put(name, pdbId);
return pdbId;
}
static String parse(String data) throws LoadException {
try {
return data.split(System.getProperty("line.separator"))[1].split("\t")[1];
} catch (RuntimeException e) {
throw new LoadException("Couldn't parse output " + data, e);
}
}
@Override
public Structure getStructureFromGeneName(String name) throws LoadException {
logger.info("Finding PDB structure for gene " + name + "...");
String pdbId = getPdbIdFromEntrezId(name);
if (pdbId == null) throw new LoadException("PDB Id for " + name + " not found");
Structure structure = null;
try {
structure = cache.getStructure(pdbId);
} catch (IOException | StructureException e) {
throw new LoadException("Couldn't load structure from PDB Id" + pdbId, e);
}
logger.info("Found PDB Id " + structure.getPDBHeader().getIdCode() + " for gene " + name);
return structure;
}
}
<file_sep>/src/main/java/org/beng183/codons/SimpleCorrelations.java
package org.beng183.codons;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.math3.linear.BlockRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.util.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.biojava.bio.structure.Atom;
import org.biojava.bio.structure.AtomPositionMap;
import org.biojava.bio.structure.Calc;
import org.biojava.bio.structure.Group;
import org.biojava.bio.structure.ResidueNumber;
import org.biojava.bio.structure.ResidueRange;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.StructureTools;
import org.biojava.bio.structure.scop.ScopDomain;
import org.biojava.bio.structure.secstruc.SecStruc;
import org.biojava.bio.structure.secstruc.SecStrucGroup;
import org.biojava.bio.structure.secstruc.SecStrucState;
import org.biojava.bio.structure.secstruc.SecStrucType;
/**
* A class to determine the correlation between codon usage bias and something else.
* So far, this includes:
* <ul>
* <li>domain boundaries</li>
* <li>α versus β SSEs</li>
* <li>sequence length</li>
* <li>root mean squared deviation of the residues</li>
* </ul>
* Methods that evaluate the correlation between codon usage bias and a binary variable output an {@link Evaluation} object to describe the correlation.
* @author dmyersturnbull
*
*/
public class SimpleCorrelations {
public static void main(String[] args) throws AnalysisException, IOException {
if (args.length != 1) {
System.err.println("Usage: " + SimpleCorrelations.class.getSimpleName() + " list-of-ids-file");
return;
}
logger.info("Initializing data retrieval system");
DataRetrievalSystem retrieval = new SiftsDataRetrievalSystem();
logger.info("Initializing codon weight system");
CodonWeightSystem weighter = SimpleCodonWeightSystem.createForSpecies(Species.S_CEREVISIAE);
logger.info("Initializing correlations-finder");
SimpleCorrelations corr = new SimpleCorrelations(weighter, retrieval);
logger.info("Parsing gene identifiers");
corr.setNames(new File(args[0]));
// printHeader("domains");
// Evaluation domains = corr.evaluateNearDomainBoundaries(5);
// System.out.println(domains);
// printHeader("strands");
// Evaluation strands = corr.evaluateWithinBetaSheets();
// System.out.println(strands);
printHeader("sparseness");
RealMatrix sparseness = corr.correlateSparseness();
System.out.println(printMatrix(sparseness));
printHeader("length");
RealMatrix length = corr.correlateLength();
System.out.println(printMatrix(length));
}
/**
* An object that calculates a numerical value from a structure.
* This value can then be correlated against the total codon weight of the sequence.
* @author dmyersturnbull
*/
public interface StructureCalculator {
/**
* Calculates the value.
* @param structure The structure of the whole protein
* @param ca An array of C-α atoms in {@code structure}
* @param geneticSequence The genetic sequence; should probably be used only in an auxiliary way
*/
double calculate(Structure structure, Atom[] ca, String geneticSequence) throws Exception;
}
/**
* A description of the correlation between codon usage bias and a binary variable.
* @author dmyersturnbull
*/
public static class Evaluation {
// each pair is indexed by (positive, negative) (which is (true, false))
List<Pair<DescriptiveStatistics, DescriptiveStatistics>> stats = new ArrayList<>();
void add(DescriptiveStatistics positive, DescriptiveStatistics negative) {
stats.add(new Pair<DescriptiveStatistics, DescriptiveStatistics>(positive, negative));
}
/**
* Returns statistics about the <em>means</em> of the <em>negative</em> proteins
* For example, if "positive" is β-sheet and "negative" is α-helix of n proteins,
* this will return statistics of the n-dimensional vector containing the
* <em>mean codon usage bias</em> for each protein. The mean for a protein x is the
* mean codon usage bias among α-helical residues.
*/
public DescriptiveStatistics getNegativeMeans() {
DescriptiveStatistics means = new DescriptiveStatistics();
for (Pair<DescriptiveStatistics, DescriptiveStatistics> pair : stats) {
means.addValue(pair.getSecond().getMean());
}
return means;
}
/**
* Returns statistics about the <em>standard deviations</em> of the <em>negative</em> proteins
* For example, if "positive" is β-sheet and "negative" is α-helix of n proteins,
* this will return statistics of the n-dimensional vector containing the
* <em>standard deviation of codon usage bias</em> for each protein. The standard deviation
* for a protein x is the standard deviation of codon usage bias among α-helical residues.
*/
public DescriptiveStatistics getNegativeStandardDeviations() {
DescriptiveStatistics means = new DescriptiveStatistics();
for (Pair<DescriptiveStatistics, DescriptiveStatistics> pair : stats) {
means.addValue(pair.getSecond().getStandardDeviation());
}
return means;
}
/**
* @see #getNegativeMeans()
*/
public DescriptiveStatistics getPositiveMeans() {
DescriptiveStatistics means = new DescriptiveStatistics();
for (Pair<DescriptiveStatistics, DescriptiveStatistics> pair : stats) {
means.addValue(pair.getFirst().getMean());
}
return means;
}
/**
* @see #getNegativeStandardDeviations()
*/
public DescriptiveStatistics getPositiveStandardDeviations() {
DescriptiveStatistics means = new DescriptiveStatistics();
for (Pair<DescriptiveStatistics, DescriptiveStatistics> pair : stats) {
means.addValue(pair.getFirst().getStandardDeviation());
}
return means;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("positive: " + getPositiveMeans().getMean() + "; ");
sb.append("negative: " + getNegativeMeans().getMean());
return sb.toString();
}
}
private static final Logger logger = LogManager.getLogger(SimpleCorrelations.class.getName());
private List<String> names;
private DataRetrievalSystem retrieval;
private CodonWeightSystem weighter;
public SimpleCorrelations(CodonWeightSystem codonWeighter, DataRetrievalSystem retrievalSystem) {
super();
this.weighter = codonWeighter;
this.retrieval = retrievalSystem;
}
/**
* Correlates codon usage bias with sequence length.
* @see #correlate(StructureCalculator)
*/
public RealMatrix correlateLength() throws AnalysisException {
return correlate(new StructureCalculator() {
@Override
public double calculate(Structure structure, Atom[] ca, String geneticSequence) throws Exception {
return ca.length;
}
});
}
/**
* Correlates codon usage bias with the average distance of an atom to its closest neighbor.
* <pre>
* E[ min{|i-j| : j≠i in S } : i in S]
* </pre>
* This should give an estimate of inverse density, without normalization for length.
* @see #correlate(StructureCalculator)
*/
public RealMatrix correlateSparseness() throws AnalysisException {
return correlate(new StructureCalculator() {
@Override
public double calculate(Structure structure, Atom[] ca, String geneticSequence) throws Exception {
return superpositionDistance(ca, ca);
}
});
}
/**
* Correlates the total codon usage bias of each structure against some other value, as calculated by {@code calculator}.
* @return A PearsonsCorrelation object with codon usage bias in the first column and the calculated value in the second
*/
public RealMatrix correlate(StructureCalculator calculator) throws AnalysisException {
double[] calculatedValue = new double[names.size()];
double[] weights = new double[names.size()];
for (int x = 0; x < names.size(); x++) {
String name = names.get(x);
try {
String geneticSequence = retrieval.getGeneticSequenceFromName(name);
Structure structure = retrieval.getStructureFromGeneName(name);
Atom[] ca = StructureTools.getAtomCAArray(structure);
if (ca.length != geneticSequence.length() / 3) {
logger.warn(name + " has " + ca.length + " C-α atoms but " + (geneticSequence.length()/3) + " codons");
}
calculatedValue[x] = calculator.calculate(structure, ca, geneticSequence);
weights[x] = sumWeight(geneticSequence) / (geneticSequence.length() / 3);
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
RealMatrix matrix = new BlockRealMatrix(names.size(), 2);
matrix.setColumn(0, calculatedValue);
matrix.setColumn(1, weights);
return matrix;
}
/**
* Evaluates codon usage bias between two classes:
* <ul>
* <li>Residues within a sequence distance of nResiduesAround from any domain boundary, inclusive (positive), and</li>
* <li>Residues outside of a sequence distance of nResiduesAround from any domain boundary (negative)</li>
* </ul>
* @param nResiduesAround
* @return An Evaluation object, with "positive" being near domain boundaries, and "negative" being outside
* @throws AnalysisException
*/
public Evaluation evaluateNearDomainBoundaries(int nResiduesAround) throws AnalysisException {
if (names == null) {
throw new IllegalArgumentException("Must set names first");
}
Evaluation eval = new Evaluation();
for (String name : names) {
DescriptiveStatistics positive = new DescriptiveStatistics();
DescriptiveStatistics negative = new DescriptiveStatistics();
try {
String geneticSequence = retrieval.getGeneticSequenceFromName(name);
Structure structure = retrieval.getStructureFromGeneName(name);
Atom[] ca = StructureTools.getAtomCAArray(structure);
if (ca.length != geneticSequence.length() / 3) {
throw new AnalysisException("Failed on gene " + name + " because it has " + ca.length + " C-α atoms but " + (geneticSequence.length()/3) + " codons");
}
List<ScopDomain> domains = retrieval.getDomainsFromGeneName(name);
if (domains.size() < 2) {
logger.info("Skipping " + name + " because only " + domains.size() + " domain(s) were found");
continue;
}
for (ScopDomain domain : domains) {
AtomPositionMap atomPositionMap = new AtomPositionMap(ca);
List<String> rangeStrings = domain.getRanges();
List<ResidueRange> ranges = ResidueRange.parseMultiple(rangeStrings);
ResidueNumber lastResidue = ranges.get(ranges.size() - 1).getEnd();
for (int i = 0; i < ca.length; i++) {
Atom atom = ca[i];
Group group = atom.getGroup();
double codonWeight = weighter.getCodonWeight(getCodon(geneticSequence, i));
if (group != null) {
ResidueNumber residueNumber = group.getResidueNumber();
int length = atomPositionMap.calcLength(residueNumber, lastResidue);
if (length <= nResiduesAround) {
positive.addValue(codonWeight);
} else {
negative.addValue(codonWeight);
}
}
}
}
logger.info("For gene " + name + ": bias near boundaries is " + String.format("%1$.4f", positive.getMean()) + ", bias outside is " + String.format("%1$.4f", negative.getMean()));
eval.add(positive, negative);
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
return eval;
}
/**
* Sets the list of gene identifiers to run on.
* <strong>Must be called before any evaluation.</strong>
* @param file A file containing a line-by-line list of gene identifiers
* @throws IOException
* @see #setNames(List)
*/
public void setNames(File file) throws IOException {
names = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
if (!line.isEmpty() && !line.startsWith(";")) names.add(line);
}
}
}
/**
* Sets the list of gene identifiers to run on.
* <strong>Must be called before any evaluation.</strong>
* @see #setNames(File)
*/
public void setNames(List<String> names) {
this.names = names;
}
/**
* Evaluates codon usage bias between two classes:
* <ul>
* <li>Residues within β-sheets (positive), and</li>
* <li>Residues within other residues (negative)</li>
* </ul>
* @param nResiduesAround
* @return An Evaluation object, with "positive" within β-sheets, and "negative" being not within β-sheets
* @throws AnalysisException
*/
public Evaluation evaluateWithinBetaSheets() throws AnalysisException {
if (names == null) {
throw new IllegalArgumentException("Must set names first");
}
Evaluation eval = new Evaluation();
for (String name : names) {
DescriptiveStatistics positive = new DescriptiveStatistics();
DescriptiveStatistics negative = new DescriptiveStatistics();
try {
String geneticSequence = retrieval.getGeneticSequenceFromName(name);
Structure structure = retrieval.getStructureFromGeneName(name);
Atom[] ca = StructureTools.getAtomCAArray(structure);
if (ca.length != geneticSequence.length() / 3) {
throw new AnalysisException("Failed on gene " + name + " (" + structure.getPDBHeader().getIdCode() + ") because it has " + ca.length + " C-α atoms but " + (geneticSequence.length()/3) + " codons");
}
SecStruc ss = new SecStruc();
try {
ss.assign(structure);
} catch (StructureException e) {
throw new AnalysisException("Failed assigning secondary structure", e);
}
Map<ResidueNumber, SecStrucState> map = new HashMap<>();
SecStrucGroup[] ssgs = ss.getGroups();
for (SecStrucGroup ssg : ssgs) {
SecStrucState state = (SecStrucState) ssg.getProperty("secstruc");
map.put(ssg.getResidueNumber(), state);
}
for (int i = 0; i < ca.length; i++) {
Atom atom = ca[i];
Group group = atom.getGroup();
String codon = getCodon(geneticSequence, i);
if (codon == null) {
logger.warn("Codon #" + i + " does not exist");
continue;
}
double codonWeight = weighter.getCodonWeight(codon);
if (group != null) {
ResidueNumber residueNumber = group.getResidueNumber();
SecStrucType type = map.get(residueNumber).getSecStruc();
if (type.equals(SecStrucType.bridge) || type.equals(SecStrucType.extended)) {
positive.addValue(codonWeight);
} else {
negative.addValue(codonWeight);
}
}
}
eval.add(positive, negative);
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
}
}
return eval;
}
private double superpositionDistance(Atom[] ca1, Atom[] ca2) throws StructureException {
double total = 0;
for (int i = 0; i < ca1.length; i++) {
for (int j = 0; j < ca2.length; j++) {
total += Calc.getDistanceFast(ca1[i], ca2[j]);
}
}
return Math.sqrt(total) / ca1.length / ca1.length;
}
/**
* Calculates the sum of the codon weights in the sequence.
*/
private double sumWeight(String geneticSequence) {
double weightSum = 0;
for (int i = 0; i < geneticSequence.length() / 3; i++) {
double codonWeight = weighter.getCodonWeight(getCodon(geneticSequence, i));
weightSum += codonWeight;
}
return weightSum;
}
/**
* Returns the {@code nRead}th codon’s 3-letter code.
*/
private String getCodon(String geneticSequence, int nReads) {
if (geneticSequence.length() < (nReads + 1) * 3) {
return null;
}
return geneticSequence.substring(nReads * 3, (nReads + 1) * 3);
}
private static String printMatrix(RealMatrix matrix) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matrix.getRowDimension(); i++) {
for (int j = 0; j < matrix.getColumnDimension(); j++) {
sb.append((String.format("%1$6.4f", matrix.getEntry(i, j))));
sb.append("\t");
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
private static void printHeader(String name) {
System.out.println(repeat(System.getProperty("line.separator"), 10));
System.out.println(repeat("-", 80));
System.out.println(repeat("-", 40 - name.length()/2) + name + repeat("-", 40 - name.length()/2));
System.out.println(repeat("-", 80));
}
private static String repeat(String s, int x) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < x; i++) sb.append(s);
return sb.toString();
}
}
<file_sep>/src/main/java/org/beng183/codons/SiftsDataRetrievalSystem.java
package org.beng183.codons;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.StructureException;
import org.biojava.bio.structure.align.util.AtomCache;
import org.biojava.bio.structure.scop.BerkeleyScopInstallation;
import org.biojava.bio.structure.scop.ScopDatabase;
import org.biojava.bio.structure.scop.ScopDomain;
import org.biojava3.core.sequence.DNASequence;
/**
* A simple {@link DataRetrievalSystem} that uses Entrez to fetch genetic sequences,
* and the <a href="http://www.ebi.ac.uk/pdbe/docs/sifts/">SIFTS</a> to map between gene names, PDB identifiers, and domain identifiers.
* @author dmyersturnbull
*/
public class SiftsDataRetrievalSystem implements DataRetrievalSystem {
private static final Logger logger = LogManager.getLogger(SiftsDataRetrievalSystem.class.getName());
private Map<String, WeakReference<String>> geneToSequence = new HashMap<>();
private Map<String, String> chainIds = new HashMap<>();
private Map<String, String> scopIds = new HashMap<>();
private Map<String, String> entrezToUniProt = new HashMap<>();
private Map<String, String> entrezToRefSeq = new HashMap<>();
private AtomCache cache;
private ScopDatabase scop;
public SiftsDataRetrievalSystem() {
cache = new AtomCache();
scop = new BerkeleyScopInstallation();
try {
readScopMapping();
readChainMapping();
} catch (IOException e) {
throw new RuntimeException("Couldn't load SIFTS mapping", e);
}
}
private void readChainMapping() throws IOException {
File file = new File("src/main/resources/pdb_chain_uniprot.tsv");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
if (line.isEmpty() || line.startsWith("#") || line.startsWith("PDB")) continue;
String[] parts = line.split("\t");
String pdbId = parts[0];
String chainId = parts[1];
String uniProtId = parts[2];
String seqresStart = parts[3];
String seqresEnd = parts[4];
String pdbStart = parts[5];
String pdbEnd = parts[6];
String uniprotStart = parts[7];
String uniprotEnd = parts[8];
chainIds.put(uniProtId, pdbId + "." + chainId);
// chainIds.put(uniProtId, pdbId + "." + chainId + "_" + pdbStart + "-" + pdbEnd);
}
}
}
private void readScopMapping() throws IOException {
File file = new File("src/main/resources/pdb_chain_scop_uniprot.tsv");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
if (line.isEmpty() || line.startsWith("#") || line.startsWith("PDB")) continue;
String[] parts = line.split("\t");
String pdbId = parts[0];
String chainId = parts[1];
String uniProtId = parts[2];
int sunId = Integer.parseInt(parts[3]);
String scopId = parts[4];
scopIds.put(uniProtId, scopId);
}
}
}
@Override
public String getGeneticSequenceFromName(String name) throws LoadException {
logger.info("Retrieving sequence for gene " + name + "...");
if (geneToSequence.containsKey(name)) {
String ans = geneToSequence.get(name).get();
if (ans != null) return ans;
}
String uniProtId = getUniProtId(name);
String refSeqId = getRefSeqId(uniProtId);
LinkedHashMap<String, DNASequence> sequences = SimpleDataRetrievalSystem.downloadSequences(refSeqId, name);
Iterator<DNASequence> iterator = sequences.values().iterator();
if (!iterator.hasNext()) throw new LoadException("Did not find a sequence for gene with name " + name);
String sequence = iterator.next().getSequenceAsString();
geneToSequence.put(name, new WeakReference<String>(sequence));
logger.info("Found sequence of length " + sequence.length() + " for gene " + name);
return sequence;
}
@Override
public Structure getStructureFromGeneName(String name) throws LoadException {
logger.info("Finding PDB structure for gene " + name + "...");
String uniProtId = getUniProtId(name);
String pdbId = chainIds.get(uniProtId);
if (pdbId == null) throw new LoadException("PDB Id for gene " + name + " (UniProtId=" + uniProtId + ") not found");
try {
return cache.getStructure(pdbId);
} catch (IOException | StructureException e) {
throw new LoadException("Couldn't load structure from PDB Id" + pdbId, e);
}
}
@Override
public List<ScopDomain> getDomainsFromGeneName(String name) throws LoadException {
logger.info("Finding domains for gene " + name + "...");
String uniProtId = getUniProtId(name);
String scopId = scopIds.get(uniProtId);
if (scopId == null) {
return null;
}
ScopDomain domain = scop.getDomainByScopID(scopId);
List<ScopDomain> domains = new ArrayList<ScopDomain>();
domains.add(domain);
logger.info("Found scop Id " + scopId + " for gene " + name);
return domains;
}
private String getUniProtId(String entrez) throws LoadException {
String uniProtId = entrezToUniProt.get(entrez);
if (uniProtId == null) {
uniProtId = SimpleDataRetrievalSystem.getUniProtIdFromEntrezId(entrez);
entrezToUniProt.put(entrez, uniProtId);
}
return uniProtId;
}
private String getRefSeqId(String uniProtId) throws LoadException {
String refSeqId = entrezToRefSeq.get(uniProtId);
if (refSeqId == null) {
refSeqId = SimpleDataRetrievalSystem.getRefSeqIdFromUniProtId(uniProtId);
entrezToRefSeq.put(uniProtId, refSeqId);
}
return refSeqId;
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.beng183.codons</groupId>
<artifactId>codons</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>codons</name>
<properties>
<maven.build.timestamp.format>yyyy-MM-dd_HHmm</maven.build.timestamp.format>
<timestamp>${maven.build.timestamp}</timestamp>
<project.build.targetEncoding>UTF-8</project.build.targetEncoding>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jdk.version>1.7</jdk.version>
</properties>
<repositories>
<repository>
<id>com.springsource.repository.bundles.release</id>
<name>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</name>
<url>http://repository.springsource.com/maven/bundles/release</url>
</repository>
<repository>
<id>com.springsource.repository.bundles.external</id>
<name>SpringSource Enterprise Bundle Repository - External Bundle Releases</name>
<url>http://repository.springsource.com/maven/bundles/external</url>
</repository>
<repository>
<id>psidev.psi.mi</id>
<name>EBI psidev</name>
<url>http://www.ebi.ac.uk/intact/maven/nexus/content/repositories/ebi-repo/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
<repository>
<id>org.biojava</id>
<name>BioJava</name>
<url>http://biojava.org/download/maven/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta8</version>
</dependency>
<dependency>
<groupId>org.biojava</groupId>
<artifactId>biojava3-structure</artifactId>
<version>3.0.8-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.biojava</groupId>
<artifactId>biojava3-alignment</artifactId>
<version>3.0.6-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.2</version>
</dependency>
</dependencies>
<scm>
<developerConnection>https://github.com/dmyersturnbull/codons</developerConnection>
<connection>git://github.com/dmyersturnbull/codons</connection>
<url>https://github.com/dmyersturnbull/codons</url>
</scm>
<issueManagement>
<url>https://github.com/dmyersturnbull/codons/issues</url>
<system>Github</system>
</issueManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<fork>true</fork>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<maxmem>2000m</maxmem>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.14.1</version>
<configuration>
<argLine>-Xms256m -Xmx2000M</argLine>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*.properties</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
</includes>
</resource>
</resources>
</build>
</project>
<file_sep>/README.md
codons
======
BENG 183 project: codon usage bias and protein structure
|
c0ba4d3c11b19b71b0cc6d51151f960c832fad89
|
[
"Markdown",
"Java",
"Maven POM"
] | 6
|
Java
|
dmyersturnbull/codons
|
d127f6fc77cce22c087fd07908ccc9db6fe519e8
|
5c2afb30308162908e44eca03b2e07b615d28fa9
|
refs/heads/master
|
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/21
* Time: 上午1:26
*/
namespace Inhere\Queue;
/**
* Interface QueueInterface
* @package Inhere\Queue
*
* @property string $driver
*/
interface QueueInterface
{
/**
* Priorities
*/
const PRIORITY_HIGH = 0;
const PRIORITY_NORM = 1;
const PRIORITY_LOW = 2;
const PRIORITY_LOW_SUFFIX = '_low';
const PRIORITY_HIGH_SUFFIX = '_high';
/**
* Events list
*/
const EVENT_BEFORE_PUSH = 'beforePush';
const EVENT_AFTER_PUSH = 'afterPush';
const EVENT_ERROR_PUSH = 'errorPush';
const EVENT_BEFORE_POP = 'beforePop';
const EVENT_AFTER_POP = 'afterPop';
const EVENT_ERROR_POP = 'errorPop';
/**
* push data
* @param mixed $data
* @param int $priority
* @return bool
*/
public function push($data, $priority = self::PRIORITY_NORM): bool;
/**
* pop data
* @param null|int $priority If is Null, pop all queue data by priority.
* @param bool $block Whether block pop
* @return mixed
*/
public function pop($priority = null, $block = false);
/**
* @param int $priority
* @return int
*/
public function count($priority = self::PRIORITY_NORM);
/**
* @return string|int
*/
public function getId();
/**
* @return array
*/
public function getChannels();
/**
* @return array
*/
public function getIntChannels();
/**
* @return string
*/
public function getDriver(): string;
/**
* @return int
*/
public function getErrCode(): int;
/**
* @return string
*/
public function getErrMsg(): string;
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/31
* Time: 下午8:08
*/
namespace Inhere\Queue\Driver;
use Inhere\Library\Helpers\PhpHelper;
use Inhere\Shm\ShmMap;
/**
* Class ShmQueue - shared memory queue
* @package Inhere\Queue\Driver
*/
class ShmQueue extends BaseQueue
{
/**
* @var ShmMap[]
*/
private $queues = [];
/**
* shm options
* @var array
*/
private $options = [
'size' => 256000,
'project' => 's', // shared memory, semaphore NOTICE: Length can be only one
'tmpDir' => '/tmp', // tmp path
];
/**
* {@inheritDoc}
* @throws \LogicException
*/
protected function init()
{
parent::init();
$this->driver = Queue::DRIVER_SHM;
if ($this->id <= 0) {
// 定义共享内存,信号量key
$this->id = PhpHelper::ftok(__FILE__, $this->options['project']);
}
// create queues
$this->queues = new \SplFixedArray(count($this->getPriorities()));
}
/**
* @param $data
* @param int $priority
* @return bool
* @throws \RuntimeException
*/
protected function doPush($data, $priority = self::PRIORITY_NORM)
{
if (!$this->isPriority($priority)) {
$priority = self::PRIORITY_NORM;
}
return $this->createQueue($priority)->rPush($data);
}
/**
* {@inheritDoc}
* @throws \RuntimeException
*/
protected function doPop($priority = null, $block = false)
{
// 只想取出一个 $priority 队列的数据
if ($this->isPriority($priority)) {
// $priority 级别的队列还未初始化。
// $queue = $this->createQueue($priority);
if (!$this->hasQueue($priority)) {
return null;
}
return $this->queues[$priority]->lPop();
}
$data = null;
foreach ($this->queues as $pri => $queue) {
// $queue = $queue ?: $this->createQueue($pri);
if (!$queue) {
continue;
}
if (false !== ($data = $queue->lPop())) {
break;
}
}
// reset($this->queues);
return $data;
}
public function count($priority = self::PRIORITY_NORM)
{
if ($queue = $this->queues[$priority]) {
return $queue->count();
}
return 0;
}
/**
* @param int $priority
* @return bool
*/
public function hasQueue($priority = self::PRIORITY_NORM)
{
return $this->queues[$priority] !== null;
}
/**
* {@inheritDoc}
*/
public function close()
{
parent::close();
foreach ($this->queues as $key => $queue) {
if ($queue) {
$queue->close();
$this->queues[$key] = null;
}
}
}
/**
* create queue if it not exists.
* @param int $priority
* @return ShmMap
* @throws \RuntimeException
*/
protected function createQueue($priority)
{
if (!$this->queues[$priority]) {
$config = $this->getOptions();
$config['key'] = $this->intChannels[$priority];
$this->queues[$priority] = new ShmMap($config);
}
return $this->queues[$priority];
}
/**
* @return ShmMap[]
*/
public function getQueues()
{
return $this->queues;
}
/**
* @param int $priority
* @return ShmMap|false
*/
public function getQueue($priority = self::PRIORITY_NORM)
{
if (!isset($this->getPriorities()[$priority])) {
return false;
}
return $this->queues[$priority];
}
/**
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* @param array $options
*/
public function setOptions(array $options)
{
$this->options = array_merge($this->options, $options);
}
}
<file_sep><?php
/**
* @from https://github.com/matyhtf/framework/blob/master/libs/Swoole/Queue/MsgQ.php
*/
namespace Inhere\Queue\Driver;
/**
* Class SysVQueue - by system v message queue
* @package Inhere\Queue\Driver
*/
class SysVQueue extends BaseQueue
{
/**
* @var \SplFixedArray
*/
private $queues = [];
/**
* @var int
*/
private $msgType = 1;
/**
* project ID of the sys v msg.
* NOTICE: Length can be only one
* @var int|string
*/
private $project = 0;
/**
* @var bool
*/
private $blocking = true;
/**
* buffer Size 8192 65525
* @var int
*/
private $bufferSize = 2048;
/**
* @var bool
*/
private $removeOnClose = true;
/**
* {@inheritDoc}
* @throws \RuntimeException
*/
protected function init()
{
// php --rf msg_send
if (!function_exists('msg_receive')) {
throw new \RuntimeException(
'To enable System V semaphore,shared-memory,messages support compile PHP with the option --enable-sysvsem --enable-sysvshm --enable-sysvmsg.',
-500
);
}
parent::init();
$this->driver = Queue::DRIVER_SYSV;
if ($this->id <= 0) {
$this->id = ftok(__FILE__, $this->project);
}
// 初始化队列列表. 使用时再初始化需要的队列
$this->queues = new \SplFixedArray(count($this->getPriorities()));
}
/**
* {@inheritdoc}
*/
protected function doPush($data, $priority = self::PRIORITY_NORM)
{
// $blocking = true 如果队列满了,这里会阻塞
// bool msg_send(
// resource $queue, int $msgtype, mixed $message
// [, bool $serialize = true [, bool $blocking = true [, int &$errorcode ]]]
// )
if (!$this->isPriority($priority)) {
$priority = self::PRIORITY_NORM;
}
// create queue if it not exists.
return msg_send(
$this->createQueue($priority),
$this->msgType,
$data,
false,
$this->blocking,
$this->errCode
);
}
/**
* {@inheritDoc}
*/
protected function doPop($priority = null, $block = false)
{
// bool msg_receive(
// resource $queue, int $desiredmsgtype, int &$msgtype, int $maxsize,
// mixed &$message [, bool $unserialize = true [, int $flags = 0 [, int &$errorcode ]]]
// )
// 只想取出一个 $priority 队列的数据
if ($this->isPriority($priority)) {
// $priority 级别的队列还未初始化。
if (!$this->hasQueue($priority)) {
return null;
}
$flags = $block ? 0 : (MSG_IPC_NOWAIT | MSG_NOERROR);
$success = msg_receive(
$this->queues[$priority],
0, // 0 $this->msgType,
$this->msgType, // $this->msgType,
$this->bufferSize,
$data,
false,
// 0: 默认值,无消息后会阻塞等待。(要取多个队列数据时,不能用它,不然无法读取后面两个队列的数据)
// MSG_IPC_NOWAIT 无消息后不等待
// MSG_EXCEPT
// MSG_NOERROR 消息超过大小限制时,截断数据而不报错
$flags,
$this->errCode
);
if ($success) {
return $data;
}
return null;
}
$data = null;
foreach ($this->queues as $pri => $queue) {
if (($data = $this->doPop($pri)) !== null) {
break;
}
}
return $data;
}
public function count($priority = self::PRIORITY_NORM)
{
if ($queue = $this->queues[$priority]) {
$stat = msg_stat_queue($queue);
return $stat['msg_qnum'];
}
return 0;
}
/**
* @param int $priority
* @return bool
*/
public function hasQueue($priority = self::PRIORITY_NORM)
{
return $this->queues[$priority] !== null;
}
/**
* create queue if it not exists.
* @param int $priority
* @return resource
*/
protected function createQueue($priority)
{
if (!$this->queues[$priority]) {
$key = $this->getIntChannels()[$priority];
$this->queues[$priority] = msg_get_queue($key);
}
return $this->queues[$priority];
}
/**
* @return \SplFixedArray
*/
public function getQueues()
{
return $this->queues;
}
/**
* @param int $priority
* @return resource|false
*/
public function getQueue($priority = self::PRIORITY_NORM)
{
if (!isset($this->getPriorities()[$priority])) {
return false;
}
return $this->queues[$priority];
}
/**
* @return array
*/
public function allQueues()
{
$aQueues = [];
exec('ipcs -q', $aQueues);
return $aQueues;
}
/**
* Setting the queue option
* @param array $options
* @param int $queue
*/
public function setQueueOptions(array $options = [], $queue = self::PRIORITY_NORM)
{
msg_set_queue($this->queues[$queue], $options);
}
/**
* @param int $id
* @return bool
*/
public function exist($id)
{
return msg_queue_exists($id);
}
/**
* close
*/
public function close()
{
parent::close();
foreach ($this->queues as $key => $queue) {
if ($queue) {
if ($this->removeOnClose) {
msg_remove_queue($queue);
}
$this->queues[$key] = null;
}
}
}
/**
* @return array
*/
public function getStats()
{
$stats = [];
foreach ($this->queues as $queue) {
$stats[] = msg_stat_queue($queue);
}
return $stats;
}
/**
* @param int $queue
* @return array
*/
public function getStat($queue = self::PRIORITY_NORM)
{
return msg_stat_queue($this->queues[$queue]);
}
//////////////////////////////////////////////////////////////////////
/// getter/setter method
//////////////////////////////////////////////////////////////////////
/**
* @param int $id
* @return $this
*/
public function setId($id)
{
$this->id = (int)$id;
return $this;
}
/**
* @return int
*/
public function getMsgType(): int
{
return $this->msgType;
}
/**
* @param int $msgType
*/
public function setMsgType(int $msgType)
{
$this->msgType = $msgType;
}
/**
* @return int|string
*/
public function getProject()
{
return $this->project;
}
/**
* @param int|string $project
*/
public function setProject($project)
{
if ($project = trim($project)) {
$this->project = $project{0};
}
}
/**
* @return bool
*/
public function isBlocking(): bool
{
return $this->blocking;
}
/**
* @param bool $blocking
*/
public function setBlocking($blocking = true)
{
$this->blocking = (bool)$blocking;
}
/**
* @return int
*/
public function getBufferSize(): int
{
return $this->bufferSize;
}
/**
* @param int $bufferSize
*/
public function setBufferSize(int $bufferSize)
{
$this->bufferSize = $bufferSize;
}
/**
* @return bool
*/
public function isRemoveOnClose(): bool
{
return $this->removeOnClose;
}
/**
* @param bool $removeOnClose
*/
public function setRemoveOnClose($removeOnClose = true)
{
$this->removeOnClose = (bool)$removeOnClose;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/21
* Time: 上午1:45
*/
namespace Inhere\Queue\Driver;
use MyLib\ObjUtil\Obj;
use MyLib\SimpleEvent\LiteEventTrait;
/**
* Class BaseQueue
* @package Inhere\Queue\Driver
*/
abstract class BaseQueue extends StdObject implements QueueInterface
{
use LiteEventTrait;
/**
* @var string
*/
protected $driver;
/**
* The queue id(name)
* @var string|int
*/
protected $id;
/**
* @var int
*/
protected $errCode = 0;
/**
* @var string
*/
protected $errMsg;
/**
* whether serialize data
* @var bool
*/
protected $serialize = true;
/**
* data serializer like 'serialize' 'json_encode'
* @var callable
*/
protected $serializer = 'serialize';
/**
* data deserializer like 'unserialize' 'json_decode'
* @var callable
*/
protected $deserializer = 'unserialize';
/**
* @var callable
*/
private $pushFailHandler;
/**
* @var array
*/
protected $channels = [];
/**
* @var array
*/
protected $intChannels = [];
/**
* MsgQueue constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
Obj::init($config);
// init property
$this->getChannels();
$this->getIntChannels();
}
/**
* {@inheritDoc}
*/
public function push($data, $priority = self::PRIORITY_NORM): bool
{
$status = false;
$this->fire(self::EVENT_BEFORE_PUSH, [$data, $priority]);
try {
$status = $this->doPush($this->encode($data), $priority);
$this->fire(self::EVENT_AFTER_PUSH, [$data, $priority, $status]);
} catch (\Exception $e) {
$this->errCode = $e->getCode() !== 0 ? $e->getCode() : __LINE__;
$this->errMsg = $e->getMessage();
$this->fire(self::EVENT_ERROR_PUSH, [$e, $data, $priority, $this]);
}
return $status;
}
/**
* @param string $data Encoded data string
* @param int $priority
* @return bool
*/
abstract protected function doPush($data, $priority = self::PRIORITY_NORM);
/**
* {@inheritDoc}
*/
public function pop($priority = null, $block = false)
{
$data = null;
$this->fire(self::EVENT_BEFORE_POP, [$priority, $this]);
try {
if ($data = $this->doPop($priority, $block)) {
$data = $this->decode($data);
}
$this->fire(self::EVENT_AFTER_POP, [$data, $priority, $this]);
} catch (\Exception $e) {
$this->errCode = $e->getCode() !== 0 ? $e->getCode() : __LINE__;
$this->errMsg = $e->getMessage();
$this->fire(self::EVENT_ERROR_POP, [$e, $priority, $this]);
}
return $data;
}
/**
* @param null $priority
* @param bool $block
* @return string Raw data string
*/
abstract protected function doPop($priority = null, $block = false);
//////////////////////////////////////////////////////////////////////
/// helper method
//////////////////////////////////////////////////////////////////////
/**
* get Priorities
* @return array
*/
public function getPriorities(): array
{
return [
self::PRIORITY_HIGH,
self::PRIORITY_NORM,
self::PRIORITY_LOW,
];
}
/**
* @param int $priority
* @return bool
*/
public function isPriority($priority)
{
if (null === $priority) {
return false;
}
return in_array((int)$priority, $this->getPriorities(), true);
}
/**
* @return array
*/
public function getChannels()
{
if (!$this->channels) {
$this->channels = [
self::PRIORITY_HIGH => $this->id . self::PRIORITY_HIGH_SUFFIX,
self::PRIORITY_NORM => $this->id,
self::PRIORITY_LOW => $this->id . self::PRIORITY_LOW_SUFFIX,
];
}
return $this->channels;
}
/**
* @return array
*/
public function getIntChannels()
{
if (!$this->intChannels) {
$id = (int)$this->id;
$this->intChannels = [
self::PRIORITY_HIGH => $id + self::PRIORITY_HIGH,
self::PRIORITY_NORM => $id + self::PRIORITY_NORM,
self::PRIORITY_LOW => $id + self::PRIORITY_LOW,
];
}
return $this->intChannels;
}
/**
* @param mixed $data
* @return mixed
*/
protected function encode($data)
{
if (!$this->serialize || !($cb = $this->serializer)) {
return $data;
}
// return base64_encode(serialize($data));
return $cb($data);
}
/**
* @param mixed $data
* @return mixed
*/
protected function decode($data)
{
if (!$this->serialize || !($cb = $this->deserializer)) {
return $data;
}
return $cb($data);
}
/**
* close
*/
public function close()
{
$this->clearEvents();
}
/**
* __destruct
*/
public function __destruct()
{
$this->close();
}
//////////////////////////////////////////////////////////////////////
/// getter/setter method
//////////////////////////////////////////////////////////////////////
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param int|string $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @return bool
*/
public function isSerialize(): bool
{
return $this->serialize;
}
/**
* @param bool $serialize
*/
public function setSerialize($serialize = true)
{
$this->serialize = (bool)$serialize;
}
/**
* @return callable
*/
public function getSerializer(): callable
{
return $this->serializer;
}
/**
* @param callable $serializer
*/
public function setSerializer(callable $serializer)
{
$this->serializer = $serializer;
}
/**
* @return callable
*/
public function getDeserializer(): callable
{
return $this->deserializer;
}
/**
* @param callable $deserializer
*/
public function setDeserializer(callable $deserializer)
{
$this->deserializer = $deserializer;
}
/**
* @return callable
*/
public function getPushFailHandler(): callable
{
return $this->pushFailHandler;
}
/**
* @param callable $pushFailHandler
*/
public function setPushFailHandler(callable $pushFailHandler)
{
$this->pushFailHandler = $pushFailHandler;
}
/**
* @return int
*/
public function getErrCode(): int
{
return $this->errCode;
}
/**
* @return string
*/
public function getErrMsg(): string
{
return $this->errMsg;
}
/**
* @return string
*/
public function getDriver(): string
{
return $this->driver;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/29
* Time: 上午11:05
*/
use Inhere\Queue\QueueInterface;
require dirname(__DIR__) . '/../../autoload.php';
$q = \Inhere\Queue\Queue::make([
'driver' => 'sysv', // shm sysv php
'id' => 12,
'serializer' => 'serialize',
'deserializer' => 'unserialize',
]);
//var_dump($q);
echo "driver is: {$q->getDriver()}\n\n";
$r[] = $q->push('n1');
$r[] = $q->push('n2');
$r[] = $q->push(['n3-array-value']);
$r[] = $q->push('h1', QueueInterface::PRIORITY_HIGH);
$r[] = $q->push('l1', QueueInterface::PRIORITY_LOW);
$r[] = $q->push('n4');
//var_dump($r);
$i = 6;
while ($i--) {
var_dump($q->pop());
usleep(50000);
}
<file_sep># php 的队列实现
php的队列使用包装, 默认自带支持 `高 high` `中 norm` `低 low` 三个级别的队列操作。
- `DbQueue` 基于数据库(mysql/sqlite)的队列实现
- `PhpQueue` 基于 php `SplQueue` 实现
- `RedisQueue` 基于 redis 实现 - 操作具有原子性,并发操作不会有问题
- `ShmQueue` 基于共享内存实现 - 操作会自动加锁,并发操作不会有问题
- `SysVQueue` 基于 *nix 系统的 system v message 实现. php 需启用 `--enable-sysvmsg` 通常是默认开启的 :)
## 安装
- composer
```json
{
"require": {
"inhere/queue": "dev-master"
}
}
```
- 直接拉取
```bash
git clone https://gitee.com/inhere/php-queue.git // gitee
git clone https://github.com/inhere/php-queue.git // github
```
## 使用
```php
// file: example/queue.php
use Inhere\Queue\QueueInterface;
// require __DIR__ . '/autoload.php';
$q = \Inhere\Queue\Queue::make([
'driver' => 'sysv', // shm sysv php
'id' => 12,
]);
//var_dump($q);
$q->push('n1');
$q->push('n2');
$q->push(['n3-array-value']);
$q->push('h1', QueueInterface::PRIORITY_HIGH);
$q->push('l1', QueueInterface::PRIORITY_LOW);
$q->push('n4');
$i = 6;
while ($i--) {
var_dump($q->pop());
usleep(50000);
}
```
run `php example/queue.php`. output:
```
% php example/queue.php 17-06-11 - 22:36:01
driver is sysv
string(2) "h1"
string(2) "n1"
string(2) "n2"
array(1) {
[0] =>
string(11) "n3-array-value"
}
string(2) "n4"
string(2) "l1"
```
## 其他
system v 内存查看:
```bash
ipcs
ipcs -a // 命令可以查看当前使用的共享内存、消息队列及信号量所有信息
ipcs -p // 命令可以得到与共享内存、消息队列相关进程之间的消息
ipcs -u // 命令可以查看各个资源的使用总结信息
ipcs -q // 只查看消息队列
ipcs -qa // 查看消息队列,并显示更多信息
```
删除共享内存:
```bash
$ ipcrm
usage: ipcrm [-q msqid] [-m shmid] [-s semid]
[-Q msgkey] [-M shmkey] [-S semkey] ...
```
## License
MIT
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/7/2
* Time: 下午1:46
*/
namespace Inhere\Queue;
/**
* Interface ExtendQueueInterface
* @package Inhere\Queue
*/
interface ExtendQueueInterface
{
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/29
* Time: 上午10:36
*/
namespace Inhere\Queue;
use Inhere\Queue\Driver\DbQueue;
use Inhere\Queue\Driver\PhpQueue;
use Inhere\Queue\Driver\RedisQueue;
use Inhere\Queue\Driver\ShmQueue;
use Inhere\Queue\Driver\SysVQueue;
/**
* Class Queue - queue factory
* @package Inhere\Queue
*/
final class Queue
{
const DRIVER_DB = 'db';
const DRIVER_PHP = 'php';
// const DRIVER_LDB = 'levelDb';
// const DRIVER_RDB = 'rocksDb';
const DRIVER_SHM = 'shm';
const DRIVER_SYSV = 'sysv';
const DRIVER_REDIS = 'redis';
/**
* driver map
* @var array
*/
private static $driverMap = [
'db' => DbQueue::class,
'php' => PhpQueue::class,
'sysv' => SysVQueue::class,
'shm' => ShmQueue::class,
'redis' => RedisQueue::class,
];
/**
* @param string $driver
* @param array $config
* @return QueueInterface
*/
public static function make(array $config = [], $driver = '')
{
if (!$driver && isset($config['driver'])) {
$driver = $config['driver'];
unset($config['driver']);
}
if ($driver && ($class = self::getDriverClass($driver))) {
return new $class($config);
}
return new PhpQueue($config);
}
/**
* @param $driver
* @return mixed|null
*/
public static function getDriverClass($driver)
{
return self::$driverMap[$driver] ?? null;
}
/**
* @return array
*/
public static function getDriverMap(): array
{
return self::$driverMap;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/21
* Time: 上午1:45
*/
namespace Inhere\Queue\Driver;
/**
* Class PhpQueue
* @package Inhere\Queue\Driver
*/
class PhpQueue extends BaseQueue
{
/**
* @var \SplQueue[]
*/
private $queues = [];
/**
* {@inheritdoc}
*/
protected function init()
{
parent::init();
$this->driver = Queue::DRIVER_PHP;
if (!$this->id) {
$this->id = $this->driver;
}
// create queues
$this->queues = new \SplFixedArray(count($this->getPriorities()));
}
/**
* {@inheritDoc}
*/
protected function doPush($data, $priority = self::PRIORITY_NORM)
{
if (!$this->isPriority($priority)) {
$priority = self::PRIORITY_NORM;
}
$this->createQueue($priority)->enqueue($data); // can use push().
return true;
}
/**
* {@inheritDoc}
*/
protected function doPop($priority = null, $block = false)
{
// 只想取出一个 $priority 队列的数据
if ($this->isPriority($priority)) {
// $priority 级别的队列还未初始化。
// $queue = $this->createQueue($priority);
if (!$this->hasQueue($priority)) {
return null;
}
return $this->queues[$priority]->dequeue();
}
$data = null;
foreach ($this->queues as $pri => $queue) {
// $queue = $queue ?: $this->createQueue($pri);
if (!$queue) {
continue;
}
// valid()
if (!$queue->isEmpty()) {
$data = $queue->dequeue();// can use shift().
break;
}
}
// reset($this->queues);
return $data;
}
public function count($priority = self::PRIORITY_NORM)
{
if ($queue = $this->queues[$priority]) {
return $queue->count();
}
return 0;
}
/**
* @param int $priority
* @return bool
*/
public function hasQueue($priority = self::PRIORITY_NORM)
{
return $this->queues[$priority] !== null;
}
/**
* create queue if it not exists.
* @param int $priority
* @return \SplQueue
*/
protected function createQueue($priority)
{
if (!$this->queues[$priority]) {
$this->queues[$priority] = new \SplQueue();
$this->queues[$priority]->setIteratorMode(\SplQueue::IT_MODE_DELETE);
}
return $this->queues[$priority];
}
/**
* @return \SplQueue[]
*/
public function getQueues()
{
return $this->queues;
}
/**
* @param int $priority
* @return \SplQueue|false
*/
public function getQueue($priority = self::PRIORITY_NORM)
{
if (!isset($this->getPriorities()[$priority])) {
return false;
}
return $this->queues[$priority];
}
/**
* @param int $priority
* @return array|null
*/
public function getStat($priority = self::PRIORITY_NORM)
{
if ($q = $this->getQueue($priority)) {
return [
'num' => $q->count(),
];
}
return null;
}
/**
* close
*/
public function close()
{
parent::close();
foreach ($this->getPriorities() as $p) {
$this->queues[$p] = null;
}
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/6/10
* Time: 上午12:32
*/
namespace Inhere\Queue\Util;
/**
* Class PushFailedLoader
* @package Inhere\Queue\Util
*/
class PushFailedLoader
{
/**
* PushFailedLoader constructor.
* @param string $file failed data save file
*/
public function __construct($file)
{
$this->file = new \SplFileObject($file);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/6/10
* Time: 上午12:18
*/
namespace Inhere\Queue\Util;
use Inhere\Queue\QueueInterface;
/**
* Class EventHandler
* @package Inhere\Queue\Util
*/
class EventHandler
{
/**
* @var string
*/
public $savePath;
public $fileExt = '.data';
/**
* @param $data
* @param $priority
* @param QueueInterface $queue
*/
public function onFail($data, $priority, QueueInterface $queue)
{
file_put_contents($this->getFile(), json_encode([
'time' => time(),
'priority' => $priority,
'driver' => $queue->getDriver(),
'id' => $queue->getId(),
'intId' => $queue->getChannels()[$priority],
'strId' => $queue->getIntChannels()[$priority],
'data' => $data,
]));
}
/**
* @return string
*/
public function getFile()
{
if (!$this->savePath) {
$this->savePath = dirname(__DIR__);
}
return $this->savePath . DIRECTORY_SEPARATOR . 'failed_' . date('Ymd') . $this->fileExt;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/21
* Time: 上午1:45
*/
namespace Inhere\Queue\Driver;
/**
* Class DbQueue
* @package Inhere\Queue\Driver
*/
class DbQueue extends BaseQueue
{
/**
* @var \PDO
*/
private $db;
/**
* @var string
*/
private $table = 'msg_queue';
protected function init()
{
$this->driver = Queue::DRIVER_DB;
if (!$this->id) {
$this->id = $this->driver;
}
}
/**
* {@inheritdoc}
*/
protected function doPush($data, $priority = self::PRIORITY_NORM)
{
return $this->db->exec(sprintf(
"INSERT INTO {$this->table} (`queue`, `data`, `priority`, `created_at`) VALUES (%s, %s, %d, %d)",
$this->id,
$data,
$priority,
time()
));
}
/**
* {@inheritDoc}
*/
protected function doPop($priority = null, $block = false)
{
if (!$this->isPriority($priority)) {
$sql = "SELECT `id`,`data` FROM {$this->table} WHERE queue = %s ORDER BY `priority` ASC, `id` DESC LIMIT 1";
$sql = sprintf($sql, $this->id);
} else {
$sql = "SELECT `id`,`data` FROM {$this->table} WHERE queue = %s AND `priority` = %d ORDER BY `priority` ASC, `id` DESC LIMIT 1";
$sql = sprintf($sql, $this->id, $priority);
}
$data = null;
$st = $this->db->query($sql);
if ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
$data = $row['data'];
}
return $data;
}
/**
* @param int $priority
* @return int
*/
public function count($priority = self::PRIORITY_NORM)
{
$count = 0;
$sql = sprintf("SELECT COUNT(*) AS `count` FROM {$this->table} WHERE `priority` = %d", $priority);
$st = $this->db->query($sql);
if ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
$count = $row['count'];
}
return $count;
}
/**
* {@inheritDoc}
*/
public function close()
{
parent::close();
$this->db = null;
}
/**
* @return string
*/
public function getTable(): string
{
return $this->table;
}
/**
* @param string $table
*/
public function setTable(string $table)
{
$this->table = $table;
}
/**
* @return \PDO
*/
public function getDb(): \PDO
{
return $this->db;
}
/**
* @param \PDO $db
*/
public function setDb(\PDO $db)
{
$this->db = $db;
}
/**
*
* ```php
* $dqe->createTable($dqe->createMysqlTableSql());
* ```
* @param string $sql
* @return int
*/
public function createTable($sql)
{
return $this->db->exec($sql);
}
/**
* @return string
*/
public function createMysqlTableSql()
{
$tName = $this->table;
return <<<EOF
CREATE TABLE IF NOT EXISTS `$tName` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`queue` CHAR(48) NOT NULL COMMENT 'queue name',
`data` TEXT NOT NULL COMMENT 'task data',
`priority` TINYINT(2) UNSIGNED NOT NULL DEFAULT 1,
`created_at` INT(10) UNSIGNED NOT NULL,
`started_at` INT(10) UNSIGNED NOT NULL DEFAULT 0,
`finished_at` INT(10) UNSIGNED NOT NULL DEFAULT 0,
KEY (`queue`, `created_at`),
PRIMARY KEY (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
EOF;
}
/**
* @return int
*/
public function createSqliteTableSql()
{
$tName = $this->table;
return <<<EOF
CREATE TABLE IF NOT EXISTS `$tName` (
`id` INTEGER PRIMARY KEY NOT NULL,
`queue` CHAR(48) NOT NULL COMMENT 'queue name',
`data` TEXT NOT NULL COMMENT 'task data',
`priority` INTEGER(2) NOT NULL DEFAULT 1,
`created_at` INTEGER(10) NOT NULL,
`started_at` INTEGER(10) NOT NULL DEFAULT 0,
`finished_at` INTEGER(10) NOT NULL DEFAULT 0
);
CREATE INDEX idxQueue on $tName(queue);
CREATE INDEX idxCreatedAt on $tName(created_at);
EOF;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017/5/21
* Time: 上午1:45
*/
namespace Inhere\Queue\Driver;
/**
* Class RedisQueue
* - 操作具有原子性。并发操作不会有问题
*
* @package Inhere\Queue\Driver
*/
class RedisQueue extends BaseQueue
{
/**
* redis
* @var \Redis
*/
private $redis;
protected function init()
{
$this->driver = Queue::DRIVER_REDIS;
if (!$this->id) {
$this->id = $this->driver;
}
}
/**
* {@inheritDoc}
*/
protected function doPush($data, $priority = self::PRIORITY_NORM)
{
if (!$this->isPriority($priority)) {
$priority = self::PRIORITY_NORM;
}
return $this->redis->lPush($this->channels[$priority], $data);
}
/**
* {@inheritDoc}
*/
protected function doPop($priority = null, $block = false)
{
// 只想取出一个 $priority 队列的数据
if ($this->isPriority($priority)) {
$channel = $this->channels[$priority];
return $this->redis->rPop($channel);
// return $block ? $this->redis->brPop([$channel], 3) : $this->redis->rPop($channel);
}
$data = null;
foreach ($this->channels as $channel) {
if ($data = $this->redis->rPop($channel)) {
break;
}
}
return $data;
}
/**
* @param int $priority
* @return int
*/
public function count($priority = self::PRIORITY_NORM)
{
$channel = $this->channels[$priority];
return $this->redis->lLen($channel);
}
/**
* @return \Redis
*/
public function getRedis(): \Redis
{
return $this->redis;
}
/**
* @param \Redis $redis
*/
public function setRedis(\Redis $redis)
{
$this->redis = $redis;
}
}
|
f37e20eec7aa8ba0dcb3cc58afa9a76f0f6f2fd6
|
[
"Markdown",
"PHP"
] | 13
|
PHP
|
phppkg/queue
|
61eb3787cda32b469382c8430a663ea2154dc288
|
5fc0bfaddb7848de42512a8ab102e8924108109d
|
refs/heads/master
|
<repo_name>manikandanravi94/Export-Excel-Audit-PDF<file_sep>/src/main/java/com/audit/service/ExcelReaderService.java
package com.audit.service;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.audit.exception.ExcelAppException;
import com.audit.model.TaxAmount;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
@Service
public class ExcelReaderService {
public static final String PURCHASE = "Purchase";
public static final String EXPENSE = "Expense";
public static final String ASSETS = "Assets";
public static final String SALES = "Sales";
public static final String CASH_SALES = "Cash Sales";
public static final String SCRAP_SALES = "Scrap Sales";
public static final Double[] CENT_ARRAY = {0.05, 0.12, 0.18, 0.28};
public Map<String, Map<Double, TaxAmount>> getDealerTXN(Workbook workBook, String dealerType) throws EncryptedDocumentException, IOException {
System.out.println("Total no. of sheets available in workbook" + workBook.getNumberOfSheets());
Sheet purchaseSheet = workBook.getSheetAt(1);
Iterator<Row> rowIterator = purchaseSheet.rowIterator();
Map<String, Map<Double, TaxAmount>> txnCummulativeMap = new HashMap<>();
Map<Double, TaxAmount> purchaseAmtMap = new HashMap<>();
Map<Double, TaxAmount> expenseAmtMap = new HashMap<>();
Map<Double, TaxAmount> assetsAmtMap = new HashMap<>();
while (rowIterator.hasNext()) {
Row purchaseSheetRow = rowIterator.next();
if (dealerType.equals(purchaseSheetRow.getCell(5).getStringCellValue())) {
if (PURCHASE.equals(purchaseSheetRow.getCell(1).getStringCellValue())) {
addCummulativeTaxAmountIntoMap(purchaseSheetRow, purchaseAmtMap);
} else if (EXPENSE.equals(purchaseSheetRow.getCell(1).getStringCellValue())) {
addCummulativeTaxAmountIntoMap(purchaseSheetRow, expenseAmtMap);
} else if (ASSETS.equals(purchaseSheetRow.getCell(1).getStringCellValue())) {
addCummulativeTaxAmountIntoMap(purchaseSheetRow, assetsAmtMap);
}
}
}
addMissedGSTAmt(purchaseAmtMap);
addMissedGSTAmt(expenseAmtMap);
addMissedGSTAmt(assetsAmtMap);
txnCummulativeMap.put(PURCHASE, purchaseAmtMap);
txnCummulativeMap.put(EXPENSE, expenseAmtMap);
txnCummulativeMap.put(ASSETS, assetsAmtMap);
return txnCummulativeMap;
}
private void addMissedGSTAmt(Map<Double, TaxAmount> currentMap) {
for(Double cent: CENT_ARRAY){
if(!currentMap.containsKey(cent)){
currentMap.put(cent,new TaxAmount());
}
}
}
public Map<String, Map<Double, TaxAmount>> getSalesTXN(Workbook workBook) throws EncryptedDocumentException, IOException {
System.out.println("Total no. of sheets available in workbook" + workBook.getNumberOfSheets());
Sheet salesSheet = workBook.getSheetAt(2);
Iterator<Row> rowIterator = salesSheet.rowIterator();
Map<String, Map<Double, TaxAmount>> txnCummulativeMap = new HashMap<>();
Map<Double, TaxAmount> registeredSaleMap = new HashMap<>();
Map<Double, TaxAmount> unregisteredSaleMap = new HashMap<>();
Map<Double, TaxAmount> scrapSaleMap = new HashMap<>();
while (rowIterator.hasNext()) {
Row salesSheetRow = rowIterator.next();
if (SALES.equals(salesSheetRow.getCell(1).getStringCellValue())) {
addCummulativeSalesAmtIntoMap(salesSheetRow, registeredSaleMap);
} else if (CASH_SALES.equals(salesSheetRow.getCell(1).getStringCellValue())) {
addCummulativeSalesAmtIntoMap(salesSheetRow, unregisteredSaleMap);
} else if (SCRAP_SALES.equals(salesSheetRow.getCell(1).getStringCellValue())) {
addCummulativeSalesAmtIntoMap(salesSheetRow, scrapSaleMap);
}
}
txnCummulativeMap.put(SALES, registeredSaleMap);
txnCummulativeMap.put(CASH_SALES, unregisteredSaleMap);
txnCummulativeMap.put(SCRAP_SALES, scrapSaleMap);
return txnCummulativeMap;
}
private void addCummulativeSalesAmtIntoMap(Row currentRow, Map<Double, TaxAmount> currentMap){
for (Double cent : CENT_ARRAY) {
System.out.println("Testing"+currentRow.getCell(10).getNumericCellValue());
if (cent.equals(currentRow.getCell(9).getNumericCellValue())) {
if (currentMap.containsKey(cent)) {
TaxAmount taxAmount = currentMap.get(cent);
taxAmount.setIGSTAmt(taxAmount.getIGSTAmt().add(checkType(currentRow.getCell(10)),new MathContext(2)));
taxAmount.setSGSTAmt(taxAmount.getSGSTAmt().add(checkType(currentRow.getCell(11)),new MathContext(2)));
taxAmount.setCGSTAmt(taxAmount.getCGSTAmt().add(checkType(currentRow.getCell(12)),new MathContext(2)));
} else {
TaxAmount taxAmount = new TaxAmount();
taxAmount.setIGSTAmt(checkType(currentRow.getCell(10)));
taxAmount.setSGSTAmt(checkType(currentRow.getCell(11)));
taxAmount.setCGSTAmt(checkType(currentRow.getCell(12)));
currentMap.put(cent, taxAmount);
}
break;
}
}
}
private void addCummulativeTaxAmountIntoMap(Row currentRow, Map<Double, TaxAmount> currentMap) {
for (Double cent : CENT_ARRAY) {
if (cent.equals(currentRow.getCell(14).getNumericCellValue())) {
if (currentMap.containsKey(cent)) {
TaxAmount taxAmount = currentMap.get(cent);
taxAmount.setIGSTAmt(taxAmount.getIGSTAmt().add(checkType(currentRow.getCell(15)),new MathContext(2)));
taxAmount.setSGSTAmt(taxAmount.getSGSTAmt().add(checkType(currentRow.getCell(16)),new MathContext(2)));
taxAmount.setCGSTAmt(taxAmount.getCGSTAmt().add(checkType(currentRow.getCell(17)),new MathContext(2)));
} else {
TaxAmount taxAmount = new TaxAmount();
taxAmount.setIGSTAmt(checkType(currentRow.getCell(15)));
taxAmount.setSGSTAmt(checkType(currentRow.getCell(16)));
taxAmount.setCGSTAmt(checkType(currentRow.getCell(17)));
currentMap.put(cent, taxAmount);
}
break;
}
}
}
private BigDecimal checkType(Cell currentcell) {
BigDecimal value = new BigDecimal(0);
try {
switch (currentcell.getCellType().name()) {
case "NUMERIC":
value = BigDecimal.valueOf(currentcell.getNumericCellValue());
break;
case "STRING":
value = new BigDecimal(currentcell.getStringCellValue(),new MathContext(2));
break;
case "FORMULA":
switch (currentcell.getCachedFormulaResultType().name()) {
case "NUMERIC":
System.out.println("numeric value testing:" + currentcell.getNumericCellValue());
value = BigDecimal.valueOf(currentcell.getNumericCellValue());
break;
case "STRING":
System.out.println("string value testing" + currentcell.getStringCellValue());
value = new BigDecimal(currentcell.getStringCellValue(),new MathContext(2));
break;
}
break;
default:
throw new ExcelAppException("Input cell is not in the accepted format", currentcell.getRowIndex(), currentcell.getColumnIndex());
}
} catch (ExcelAppException e) {
System.out.println("Exception occured during conversion at the following row number" + e.getRowNumber() + "at the following cell" + e.getColumnIndex());
}
return value;
}
}
<file_sep>/README.md
# Export-Excel-Audit-PDF
Created to generate audit report as PDF from excel audit input. Friend's requirement
<file_sep>/src/main/java/com/audit/TaxAuditApplication.java
package com.audit;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import com.audit.model.TaxAmount;
import com.audit.service.ExcelWriterService;
import com.audit.service.PDFWriterService;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import com.audit.service.ExcelReaderService;
@SpringBootApplication(scanBasePackages = "com.audit.*")
public class TaxAuditApplication {
public static final String filePath = "C:\\input\\GSTSummary.xlsx";
public static void main(String[] args) throws EncryptedDocumentException, IOException {
ApplicationContext context = SpringApplication.run(TaxAuditApplication.class, args);
ExcelReaderService excelReaderService = context.getBean(ExcelReaderService.class);
Workbook workBook = WorkbookFactory.create(new File(filePath));
Map<String, Map<Double, TaxAmount>> cummulativeTxn4RegistrdDealer = excelReaderService.getDealerTXN(workBook, "Registered");
Map<String, Map<Double, TaxAmount>> cummulativeTxn4NotRegistrdDealer = excelReaderService.getDealerTXN(workBook, "Unregistered");
Map<String, Map<Double, TaxAmount>> salesCummulativeTXN = excelReaderService.getSalesTXN(workBook);
ExcelWriterService excelWriterService=context.getBean(ExcelWriterService.class);
excelWriterService.writeDataIntoExcel(cummulativeTxn4RegistrdDealer);
// PDFWriterService pdfWriterService =context.getBean(PDFWriterService.class);
// pdfWriterService.writeDataIntoPdf(cummulativeTxn4RegistrdDealer);
System.out.println("started application");
}
}
<file_sep>/src/main/java/com/audit/model/PurchaseDTO.java
package com.audit.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class PurchaseDTO {
private String category;
private LocalDate createdDate;
private String invoiceNO;
private String purchaseType;
private String partyType;
private String gstNO;
private String rcm;
private String party;
private String hsnCode;
private BigDecimal goodsValue;
private String discount;
private String taxableValue;
private String freight;
private String taxRate;
private BigDecimal igst;
private BigDecimal sgst;
private BigDecimal cgst;
private BigDecimal purchaseTotal;
}
|
bedd7174fe8363e97631f927a8ec9d467ada8153
|
[
"Markdown",
"Java"
] | 4
|
Java
|
manikandanravi94/Export-Excel-Audit-PDF
|
f68b9598a610dfe71fcf57b8381a479eb7177e41
|
bee11f78051ae4d467ad7325a54174e5fdec845e
|
refs/heads/master
|
<repo_name>l-grem/ttt-6-position-taken-rb-q-000<file_sep>/lib/position_taken.rb
def position_taken?(board, position)
if board[position] == " "
taken = false
elsif board[position] == ""
taken = false
elsif board[position] == nil
taken = false
else
taken = true
end
end
|
c38c3a8476a76c2e1e29b9478c1b34c1fe14faec
|
[
"Ruby"
] | 1
|
Ruby
|
l-grem/ttt-6-position-taken-rb-q-000
|
b4b34c5192069e02d69a00956aa5d61b58eac10c
|
4f1d1719ed95cb6662a3730626bc7ca2ecd809e7
|
refs/heads/master
|
<repo_name>Sweetman/codeforce<file_sep>/282A.java
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception{
Scanner input = new Scanner(System.in);
int lines = input.nextInt();
input.nextLine();
String word = "";
int result = 0;
for(int i = 0; i < lines; i++){
word = input.nextLine();
if(word.charAt(1) == '+')
result++;
if(word.charAt(1) == '-')
result--;
}
System.out.println(result);
}
}<file_sep>/71A.java
import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args) throws Exception{
Scanner input = new Scanner(System.in);
int numWords = input.nextInt();
input.nextLine();
String word = "";
StringBuilder result;
for(int i = 0; i<numWords; i++){
result = new StringBuilder();
word = input.nextLine();
if(word.length() > 10){
result.append(word.charAt(0));
result.append(word.length()-2);
result.append(word.charAt(word.length()-1));
}
else
result.append(word);
System.out.println(result.toString());
}
}
}<file_sep>/116A.java
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception{
Scanner input = new Scanner(System.in);
int lines = input.nextInt();
int total = 0;
int max = 0;
for(int i = 0; i < lines; i++){
total -= input.nextInt();
total += input.nextInt();
if(max < total)
max = total;
}
System.out.println(max);
}
}
|
dc2591e6a92b31c322daaf7a610ec6590946f60a
|
[
"Java"
] | 3
|
Java
|
Sweetman/codeforce
|
57c2d43d5ca5b4600b932e8b5e0f06e153486085
|
af1db7f077da38b7d41a63d1014e9542d01d066d
|
refs/heads/master
|
<file_sep>var container = document.getElementById("container");
let x = 0;
function createTable(num) {
var div = document.createElement("div");
div.id = "table";
div.setAttribute("name", num);
container.appendChild(div);
setActive(div)
}
function size(amount) {
for(let i = 0; amount > i; i++) {
createTable(x+i);
for(let x = 1; amount > x; x++) {
createTable(x+i);
}
}
}
function setActive(div) {
div.addEventListener("mouseover", () => {
div.style.backgroundColor = 'black';
})
}
function removeTable() {
container.innerHTML = "";
size(16);
}
size(16);
<file_sep>A Etch-A-Sketch webpage
|
fe4efda6dba7dc3e06186552d0b3133251719ab4
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
MasonK21/Etch-A-Sketch
|
dfa1d500f01a345825730f48099b45aea533ed17
|
7fab8107097f6d64a355288461c4cddfb451783f
|
refs/heads/master
|
<file_sep>class VideosController < ApplicationController
before_action :authenticate_user_or_admin, only:[:index]
PER = 9
def index
if current_user && current_user.is_quit == true
redirect_to retire_logout_path
end
@new_video = Video.new
# @videos = Video.page(params[:page]).per(9)
# @q = current_user.videos.ransack(params.[:q])
@videos = Video.all.order('id DESC').page(params[:page]).per(9)
@video_favorites_count = Video.joins(:favorites).group(:id).count
@video_favorites_ids = Hash[@video_favorites_count.sort_by{|_, v| -v }].keys
end
def new
end
def destroy
@video=Video.find(params[:id])
@video.destroy
redirect_to videos_path
end
def about
end
def show
@video = Video.find(params[:id])
@chat = @video.chats.limit(10).order('created_at desc')
end
def create
@video = Video.new(video_params)
@video.user_id = current_user.id
@video.save
end
private
def video_params
params.require(:video).permit(:video, :video_content)
# paramsに渡してあげる。
#params.require(:モデル名).permit(:カラム名)
end
def authenticate_user_or_admin
if user_signed_in? or admin_signed_in?
# ok
else
authenticate_user!
end
end
end
<file_sep>
document.addEventListener('turbolinks:load', function(){
if(App.room != undefined){
App.room.unsubscribe();
}
App.room = App.cable.subscriptions.create({ channel: 'RoomChannel', room: $('#messages').data('room_id') },{
connected: function() {
this.cable = window.ActionCable.createConsumer();
this.cable.subscriptions.create('RoomChannel', this.sessionChannelCallback);
console.log('connected')
// Called when the subscription is ready for use on the server
},
disconnected: function() {
console.log('disconnected')
// Called when the subscription has been terminated by the server
},
received: function(message) {
console.log(message)
$('#messages ul').prepend(message['message'])
$("#messages > ul > li:nth-child(11)").remove();
},
speak: function(content) {
console.log(content)
return this.perform('speak', {message: content});
}
});
const input = document.getElementById('chat-input')
const button = document.getElementById('button')
if(input && button){
button.addEventListener('click', function(){
const content = input.value
App.room.speak(content)
input.value = ''
})
}
})
<file_sep>class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.update(user_params)
redirect_to user_path(current_user)
end
def is_quit
@user = User.find(params[:id])
@user.is_quit = true
if @user.update(video_params)
redirect_to user_path(@user)
else
render :show
end
end
def cancel
@user = current_user
end
private
def video_params
params.require(:user).permit(:password)
# paramsに渡してあげる。
#params.require(:モデル名).permit(:カラム名)
end
end<file_sep>Rails.application.routes.draw do
root "videos#index"
devise_for :users
devise_for :admins, controllers: {
registrations: 'admins/registrations',
sessions: 'admins/sessions'
}
namespace :admin do
resources :videos, controller: 'videos',only: [:index] do
resources :favorites
end
end
resources :videos,only: [:index] do
resources :favorites
end
get 'video/categorys'
get '/cancel' => 'users#cancel',as: 'cancel'
patch 'users/:id/retire' => 'users#is_quit',as: 'user_retire'
# get 'user_logout' => 'de'
get 'videos/about'
# HTTPメソッド "URL" => 'アクション名#コントローラ名'
devise_scope :user do
# get 'users/signuplist' => 'users/registrations#signuplist'
get '/retire_logout' => 'devise/sessions#destroy', as: 'retire_logout'
# ↓な気もしますのでrails routesコマンドなどで確認してください
# get 'signuplist' => 'users/registrations#signuplist'
end
# index, new, create, destory, update edit =>これら6つはresources
resources :users, :create_categories, :chats, :admins, :video_categories, :videos
mount ActionCable.server => '/cable'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
<file_sep>class AdminsController < ApplicationController
def index
redirect_to user_path(@user)
end
end
<file_sep>class CategorysController < ApplicationController
end
<file_sep>class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak(data)
chat = Chat.create!(message: data['message'],user_id: 1 ,video_id: params['room'])
# template = ApplicationController.renderer.render(partial: 'chats/chat', locals: {chat: chat})
# ActionCable.server.broadcast "room_channel_#{message.room_id}", message: render_message(message)
end
end
<file_sep>class ChatsController < ApplicationController
def show
@messages = Chat.all
end
end<file_sep>class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
before_action :set_search
def after_sign_in_path_for(resource)
case resource
when User
videos_path
when Admin
admin_videos_path
end
end
def set_search
@q = Video.ransack(params[:q])
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:family_name, :name, :family_kana, :first_kana, :email, :password])
devise_parameter_sanitizer.permit(:sign_in, keys: [:email, :password])
# devise_parameter_sanitizer.permit(:sign_in, keys: [:username])
# devise_parameter_sanitizer.permit(:sign_in, keys: [:username])
devise_parameter_sanitizer.permit(:account_update, keys: [:username, :is_quit,:password])
end
end
<file_sep>class VideoCategory < ApplicationRecord
has_many :videos
has_many :categorys
end
<file_sep>class Category < ApplicationRecord
belongs_to :video_categorys
end
<file_sep>class FavoritesController < ApplicationController
def create
video = Video.find(params[:video_id])
favorites = current_user.favorites.new(video_id: video.id)
# binding.pry
favorites.save
redirect_to video_path(video.id)
end
def destroy
video = Video.find(params[:video_id])
favorites = current_user.favorites.find_by(video_id: video.id)
favorites.destroy
redirect_to video_path(params[:video_id])
end
end
<file_sep>class Favorite < ApplicationRecord
belongs_to :video
belongs_to :user
end
<file_sep>class Admin::VideosController < ApplicationController
def destory
end
end
<file_sep>class Video < ApplicationRecord
has_many :chats
has_many :favorites
belongs_to :user
has_many :video_categorys
mount_uploader :video, VideoUploader
def favorited_by?(user)
# binding.pry
favorites.where(user_id: user.id).exists?
end
end
<file_sep>class Chat < ApplicationRecord
belongs_to :video
belongs_to :user
after_create_commit { MessageBroadcastJob.perform_later self }
end
|
553d200300bd4eae2ee6f6a7891d8e174672e15b
|
[
"JavaScript",
"Ruby"
] | 16
|
Ruby
|
yuzuki-0903/yuzukiTube
|
7326d11d2ee91b3e836be1d25dfe9229aee4afbc
|
9c9dcaff06e7a432d8e621fccc1e4f19938b8b31
|
refs/heads/master
|
<repo_name>roadman/setup_script<file_sep>/chef_install
#!/bin/bash
vagrant plugin install vagrant-omnibus
rbenv exec gem install chef berkshelf knife-solo --no-doc --no-ri
<file_sep>/fabric_install
#!/bin/bash
sudo yum install make gcc
sudo yum install python python-devel
sudo easy_install fabric
<file_sep>/z_install
#!/bin/sh
cd /etc/profile.d/
if [ ! -f z.sh ];then
sudo wget wget https://raw.github.com/rupa/z/master/z.sh
fi
exit
<file_sep>/gitflow_install
#!/bin/bash
# linux
cd $HOME
wget --no-check-certificate -q -O - https://github.com/nvie/gitflow/raw/develop/contrib/gitflow-installer.sh | sudo bash
<file_sep>/jq_install
#!/bin/sh
cd /usr/local/bin
if [ -f jq ]; then
exit
fi
sudo wget wget http://stedolan.github.io/jq/download/linux64/jq
sudo chmod a+x jq
exit
<file_sep>/xbuild_install
#!/usr/bin/env bash
cd $HOME
if [ -d xbuild ];then
echo "git clone skip: xbuild exists."
else
git clone https://github.com/tagomoris/xbuild.git
fi
echo
declare -A INS_LANGS
INS_LANGS=(\
["perl"]="5.18.2" \
["ruby"]="2.0.0-p353" \
["python"]="2.7.6")
# ["node"]="v0.10.26" \
# ["php"]="5.5.10" \
for INS_LANG in $(echo ${!INS_LANGS[@]})
do
INS_VER=${INS_LANGS[$INS_LANG]}
INS_VER_PATH=$(echo "$INS_VER" | cut -d"." -f1-2)
INS_PATH="$HOME/local/$INS_LANG-$INS_VER_PATH"
INS_CMD="xbuild/install $INS_LANG $INS_VER $INS_PATH"
if [ -d $INS_PATH ];then
echo "install $INS_LANG $INS_VER skip. $INS_PATH exists."
echo
continue
fi
echo "#-> install $INS_LANG $INS_VER"
echo "# $ $INS_CMD"
echo
$INS_CMD
echo
done
exit
<file_sep>/rbenv_install
#!/bin/bash
#sudo yum install openssl-devel
cd $HOME
git clone https://github.com/sstephenson/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
#exec $SHELL -l
source ~/.bash_profile
git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build
rbenv install 2.0.0-p353
rbenv rehash
rbenv global 2.0.0-p353
rbenv exec gem install capistrano
<file_sep>/pyenv_install
#!/bin/bash
cd $HOME
git clone git://github.com/yyuu/pyenv.git ~/.pyenv
echo 'export PATH="$HOME/.pyenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bash_profile
pyenv install 3.3.0
pyenv rehash
pyenv global 3.3.0
<file_sep>/plenv_install
#!/bin/bash
#sudo yum install git -y
if [ ! -e /dev/fd ] ;then
sudo ln -s /proc/self/fd /dev/fd
fi
cd $HOME
git clone git://github.com/tokuhirom/plenv.git ~/.plenv/
git clone git://github.com/tokuhirom/Perl-Build.git ~/.plenv/plugins/perl-build/
echo 'export PATH=~/.plenv/bin:~/.plenv/shims/:$PATH' >> ~/.bashrc
#exec $SHELL -l
source ~/.bashrc
plenv install 5.18.2 -Dusethreads
plenv global 5.18.2
plenv install-cpanm
plenv rehash
while read -p "carton install ?[y/n] " yn ; do
case $yn in
[Yy]* )
plenv exec cpanm Carton
plenv rehash
break
;;
[Nn]* )
break
;;
esac
done
|
ab18ec6b5edadf0e49f1a8596a1c8fd4c0280299
|
[
"Shell"
] | 9
|
Shell
|
roadman/setup_script
|
16b7376e4c1270aa192103676b86888def17f13c
|
fa6b80848a7c71f753d5d0a6caab364a2319d772
|
refs/heads/master
|
<repo_name>EONIQ/spree_gateway<file_sep>/app/models/spree/order_decorator.rb
Spree::Order.class_eval do
# Redefine Payment States
# self.send(:remove_const, :PAYMENT_STATES)
PAYMENT_STATES = %w(balance_due credit_owed failed paid void disputed)
# Reset validator for payment state
_validators.delete(:payment_state)
_validate_callbacks.each do |callback|
if callback.raw_filter.respond_to? :attributes
callback.raw_filter.attributes.delete :payment_state
end
end
validates :payment_state, inclusion: { in: PAYMENT_STATES, allow_blank: true }
end<file_sep>/app/models/spree/credit_card_decorator.rb
Spree::CreditCard.class_eval do
def actions
%w{capture void credit dispute}
end
end<file_sep>/app/models/spree/payment_method_decorator.rb
Spree::PaymentMethod.class_eval do
after_update :update_stripe_api_key, if: :stripe_payment_method?
def stripe_payment_method?
method_type == 'stripegateway'
end
def update_stripe_api_key
Stripe.api_key = Spree::PaymentMethod.where(type: 'Spree::Gateway::StripeGateway').first.try(:preferred_secret_key)
end
end<file_sep>/app/models/spree/order_updater_decorator.rb
Spree::OrderUpdater.class_eval do
# Add disputed to payemnt state
# Updates the +payment_state+ attribute according to the following logic:
#
# paid when +payment_total+ is equal to +total+
# balance_due when +payment_total+ is less than +total+
# credit_owed when +payment_total+ is greater than +total+
# failed when most recent payment is in the failed state
# void when order is canceled and +payment_total+ is equal to zero
# disputed when +payment_total+ is less than +total+ and one of the payment is disputed
#
# The +payment_state+ value helps with reporting, etc. since it provides a quick and easy way to locate Orders needing attention.
def update_payment_state
last_state = order.payment_state
if order.outstanding_balance > 0 && payments.present? && payments.disputed.size > 0
order.payment_state = 'disputed'
elsif payments.present? && payments.valid.size == 0
order.payment_state = 'failed'
elsif order.canceled? && order.payment_total == 0
order.payment_state = 'void'
else
order.payment_state = 'balance_due' if order.outstanding_balance > 0
order.payment_state = 'credit_owed' if order.outstanding_balance < 0
order.payment_state = 'paid' if !order.outstanding_balance?
end
order.state_changed('payment') if last_state != order.payment_state
order.payment_state
end
end<file_sep>/app/models/spree/payment/processing_decorator.rb
Spree::Payment::Processing.module_eval do
def cancel!
if !disputed?
response = payment_method.cancel(response_code)
handle_response(response, :void, :failure)
end
end
end<file_sep>/app/models/spree/payment_decorator.rb
Spree::Payment.class_eval do
INVALID_STATES = %w(failed invalid disputed withdrawn).freeze
scope :disputed, -> { with_state(['disputed', 'withdrawn']) }
scope :completed, -> { with_state(['completed', 'reinstated']) }
scope :disputed, -> { with_state('disputed') }
scope :reinstated, -> { with_state('reinstated') }
# Redefine state
state_machine initial: :checkout do
state :disputed, :reinstated
event :dispute do
transition from: [:completed], to: :disputed
end
event :reinstate do
transition from: [:disputed], to: :reinstated
end
state :reinstated
event :reinstate do
transition from: [:disputed], to: :reinstated
end
state :withdrawn
event :withdraw do
transition from: [:disputed], to: :withdrawn
end
after_transition to: [:disputed, :reinstated, :withdrawn] do |payment, transition|
payment.update_order
end
end
def can_dispute?
completed?
end
end<file_sep>/config/initializers/stripe.rb
require "stripe"
require "stripe_event"
Stripe.api_key = Spree::PaymentMethod.where(type: 'Spree::Gateway::StripeGateway').first.try(:preferred_secret_key)
StripeEvent.configure do |events|
events.subscribe 'charge.dispute.created' do |event|
Spree::Payment.where(response_code: event.data.object.charge).all.collect(&:dispute)
end
events.subscribe 'charge.dispute.funds_reinstated' do |event|
Spree::Payment.where(response_code: event.data.object.charge).all.collect(&:reinstate)
end
events.subscribe 'charge.dispute.funds_withdrawn' do |event|
Spree::Payment.where(response_code: event.data.object.charge).all.collect(&:withdraw)
end
end
|
98650ec05772d7b09f964f8462dd1412efb1bf1b
|
[
"Ruby"
] | 7
|
Ruby
|
EONIQ/spree_gateway
|
e7e17439c48c8d75dca0040b4d1c1aef2dc71413
|
c4681c7a69715d5b04f8eb0cb8d4cef4c743b48b
|
refs/heads/master
|
<file_sep>class ChangeUri < ActiveRecord::Migration
def change
change_column :tweets, :uri, :string, :null => true
end
end
<file_sep>source "https://rubygems.org"
gem "rails", "~> 4.0.0"
gem "sass-rails", "~> 4.0.0"
gem "coffee-rails", "~> 4.0.0"
#gem "turbolinks"
gem "jbuilder", "~> 1.0.1"
group :production do
gem "mysql2"
gem "unicorn"
end
group :development, :test do
gem "sqlite3"
gem "puma"
end
gem "uglifier", ">= 1.0.3"
gem "therubyracer", "~> 0.10.2", require: "v8"
gem "bootstrap-sass", "~> 3.0"
gem "figaro"
gem "bootstrap_form"
gem "rake", "~> 0.9.3.beta.1"
gem "will_paginate"
gem "will_paginate-bootstrap"
gem "font-awesome-rails"
# javascript mapping
gem 'leaflet-rails'
# twitter API to search tweets
gem 'twitter'
# reading EXIF data
gem 'exifr'
# searching instagram
gem 'faraday', '~> 0.8.0'
gem 'instagram'
# acct management
gem 'devise'
gem 'cancan'
gem 'omniauth-twitter'
gem 'omniauth-facebook'
gem 'omniauth-instagram'
gem 'uuidtools'
group :test do
gem "shoulda"
end
group :development, :test do
gem "rspec-rails"
gem "simplecov"
gem "factory_girl_rails"
gem "capybara"
end
group :development do
gem "rails3-generators"
gem "better_errors"
gem "binding_of_caller"
gem "meta_request"
gem "pry"
gem "pry-rails"
end
<file_sep>class Ability
include CanCan::Ability
def initialize(user)
case
when user.nil?
can :read, Tweet
when user.role?(:admin)
can :manage, Tweet
can [ :read, :create, :update, :admin ], User
can [ :lock, :destroy ], User do |target_user|
target_user != user
end
else
can :read, Tweet
can :create, Tweet
can [ :update, :destroy ], Tweet do |tweet|
tweet.try(:user) == user
end
can :show, User
end
end
end
<file_sep>require 'twitter'
require 'uri'
require 'tempfile'
require 'exifr'
def find_image_url(text)
URI.extract(text).each do |uri|
uri = "http://distilleryimage8.ak.instagram.com/9df735305a1111e3a78d12f4d430b315_8.jpg"
t = Tempfile.open("sickseastar")
t.binmode
resp = Net::HTTP.get_response(URI.parse(uri))
if resp['content-type'] =~ /image/
puts resp['content-type']
t.write(resp.body)
case resp['content-type']
when "image/jpeg"
pp EXIFR::JPEG.new(t.path).exif.lat
when "image/tiff"
pp EXIFR::TIFF.new(t.path).exif
end
end
end
end
namespace :import do
desc "import from twitter"
task :twitter => :environment do
client = Twitter::REST::Client.new do |config|
config.consumer_key ="3RxqXSt4dMu4Yp2y1bniAQ"
config.consumer_secret = "<KEY>"
end
%w{sickstarfish sickseastar sickseastars deadstarfish deadseastar deadseastars}.each do |tag|
client.search("#{tag} -rt").each do |tweet|
t = Tweet.new(
:tweet_type => "twitter",
:uri => tweet.uri.normalize.to_s,
:full_text => tweet.full_text,
:user_name => tweet.user.name,
:user_image_uri => tweet.user.profile_image_uri,
)
pp tweet.coordinates
# t.image_url(find_image_url(t.full_text))
# pp t
# :lat
# :lng
# :image_uri
# t.save!
end
end
end
desc "import from instagram"
task :instagram => :environment do
Instagram.configure do |config|
config.client_id = ENV['INSTAGRAM_CLIENT_ID']
config.client_secret = ENV['INSTAGRAM_CLIENT_SECRET']
end
%w{sickstarfish sickseastar sickseastars deadstarfish deadseastar deadseastars nosickstarfish nosickseastar nosickseastars beachstarfish beachseastar beachseastars sickurchin sickurchins urchinwasting}.each do |tag|
Instagram.tag_recent_media(tag).each do |media|
next unless media.location && media.user
next unless media.type == "image"
t = Tweet.new(
:tweet_type => "instagram",
:uri => media.link,
:full_text => media.caption.text,
:user_name => media.user.username,
:user_image_uri => media.user.profile_picture,
:lat => media.location.latitude,
:lng => media.location.longitude,
:image_uri => media.images.thumbnail.url,
)
t.save rescue nil
end
end
end
end
<file_sep>class User < ActiveRecord::Base
has_and_belongs_to_many :roles
has_many :authorizations, :dependent => :destroy
validates_presence_of :name
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
devise :omniauth_providers => [:facebook, :twitter, :instagram]
devise :case_insensitive_keys => [ :email ]
#
# CANCAN SECTION
#
# roles are stored CamelCase, but can be accessed through lowercase, underscored symbols
def role?(role)
return !!roles.find_by_name(role.to_s.camelize)
end
def set_roles(roles)
roles = roles.map{|r| Role.find_by_name(r.to_s.camelize)}
end
def add_role(role)
role_name = role.to_s.camelize
roles << Role.find_by_name(role_name) unless role?(role_name)
end
def remove_role(role)
role_name = role.to_s.camelize
roles - [ Role.find_by_name(role_name) ]
end
def lock
add_role(:locked)
end
def unlock
remove_role(:locked)
end
end
<file_sep>json.extract! @thing, :name, :description, :created_at, :updated_at
<file_sep>class Init < ActiveRecord::Migration
def change
drop_table :things
create_table :tags do |t|
t.string :tag_type # eg "twitter", "facebook", "instagram"
t.decimal :lat, :precision => 15, :scale => 10
t.decimal :lng, :precision => 15, :scale => 10
# twitter.uri
t.string :uri
# twitter.full_text
t.string :full_text
# twitter.user.name
t.string :user_name
# twitter user.profile_image_uri
t.string :user_image_uri
# image_uri
t.string :image_uri
t.timestamps
end
add_index :tags, [:lat, :lng]
end
end
<file_sep>class <%= controller_class_name %>Controller < ApplicationController
respond_to :html, :json
def index
@<%= plural_table_name %> = <%= class_name %>.paginate(:page => params[:page], :per_page => 25)
respond_with(@<%= plural_table_name %>)
end
def show
@<%= singular_table_name %> = <%= class_name %>.find(params[:id])
respond_with(@<%= singular_table_name %>)
end
def new
@<%= singular_table_name %> = <%= class_name %>.new
respond_with(@<%= singular_table_name %>)
end
def edit
@<%= singular_table_name %> = <%= class_name %>.find(params[:id])
respond_with(@<%= singular_table_name %>)
end
def create
@<%= singular_table_name %> = <%= class_name %>.new(params[:<%= singular_table_name %>])
if @<%= orm_instance.save %>
flash[:notice] = '<%= human_name %> was successfully created.'
else
flash[:error] = 'There was a problem saving the <%= human_name %>.'
end
respond_with(@<%= singular_table_name %>)
end
def update
@<%= singular_table_name %> = <%= class_name %>.find(params[:id])
if @<%= orm_instance.update_attributes("params[:#{singular_table_name}]") %>
flash[:notice] = '<%= human_name %> was successfully updated.'
else
flash[:error] = 'There was a problem updating the <%= human_name %>.'
end
respond_with(@<%= singular_table_name %>)
end
def destroy
@<%= singular_table_name %> = <%= class_name %>.find(params[:id])
@<%= orm_instance.destroy %>
flash[:notice] = 'Successfully destroyed <%= human_name %>.'
respond_with(@<%= singular_table_name %>)
end
end
<file_sep>class Tweet < ActiveRecord::Base
TWEET_TYPES = [ "twitter", "instagram", "facebook", "manual" ]
validates :hide, inclusion: [true, false]
validates :tweet_type, inclusion: TWEET_TYPES
validates :lat, :numericality => { :greater_than_or_equal_to => -90, :less_than_or_equal_to => 90 }, :presence => true
validates :lng, :numericality => { :greater_than_or_equal_to => -180, :less_than_or_equal_to => 180 }, :presence => true
# validates_presence_of :uri
validates_presence_of :full_text
# validates_presence_of :user_name
# validates_presence_of :user_image_uri # what about default twitter image?
# validates_presence_of :image_uri
validates :uri, length: { minimum: 1, allow_nil: true }
validates_uniqueness_of :uri, allow_nil: true
end
<file_sep>require 'delegate'
class BoundedTweetQuery < SimpleDelegator
def initialize(options = {})
bb = options[:bb]
relation = Tweet.all
relation = relation.where("lng >= ? and lat >= ? and lng <= ? and lat <= ?", *bb.split(",")) if bb
super(relation)
end
end
<file_sep># Be sure to restart your server when you modify this file.
Sickstarfish::Application.config.session_store :cookie_store, key: '_sickstarfish_session'
<file_sep>Sickstarfish::Application.routes.draw do
devise_for :users, :path => "",
:controllers => {
:omniauth_callbacks => "omniauth_callbacks",
:registrations => "registrations"
},
:path_names => { :sign_in => "login", :sign_out => "logout", :sign_up => "register" }
# must come after devise_for
resources :users do
member do
post 'lock'
end
end
root to: 'home#index'
get "home/index"
get "static/about"
get "static/disease"
get "static/faq"
get "static/help"
get "static/contact"
resources :tweets
end
<file_sep>class RenameTagType < ActiveRecord::Migration
def change
rename_column :tweets, :tag_type, :tweet_type
end
end
|
f7ec552b8e5c84736b5c038d4dd12daaa77036f0
|
[
"Ruby"
] | 13
|
Ruby
|
lamont-granquist/sickstarfish
|
14b5b5fbcb6a12009367d35d4102bc78f093c94d
|
da96796d810cd74092000a8ca345d0e7ad62de6b
|
refs/heads/main
|
<file_sep>#include <iostream>
using namespace std;
class str3WP
{
public:
void str1(char nbi[11])
{
nbi[10] = '\0';
cout << nbi[0]<<"$"<<nbi[1]<<"$"<<nbi[2]<<"$"<<nbi[3]<<"$"<<nbi[4]<<"$"<<nbi[5]<<"$"<<nbi[6]<<"$"<<nbi[7]<<"$"<<nbi[8]<<"$"<<nbi[9]<<"$"<<nbi[10];
}
void str2(char hbok[11])
{
hbok[10] = '\0';
cout << hbok[0]<<"z"<<hbok[1]<<"y"<<hbok[2]<<"x"<<hbok[3]<<"w"<<hbok[4]<<"v"<<hbok[5]<<"u"<<hbok[6]<<"t"<<hbok[7]<<"s"<<hbok[8]<<"r"<<hbok[9]<<"q"<<hbok[10];
}
void str3(char tve[11])
{
tve[10] = '\0';
cout << tve[0]<<tve[1]<<tve[2]<<tve[3]<<tve[4]<<"a"<<tve[5]<<tve[6]<<tve[7]<<tve[8]<<tve[9]<<tve[10];
}
};
int main()
{
str3WP test;
int td;
/*
char su[10];
for (int r = 0 ; r < 10 ; r++)
{
cout << "enter char 44 ";
cin >> su;
}
*/
//test.str1(su);
//test.str2(su);
//test.str3(su);
char kn[10] = {'u' , 'S' , 'c' , 'C' , 'v' , 'a' , 'p' , 'm' , '<' , 'k'};
test.str1(kn);
}
|
b20fe76cd5b62e1f1e21e4305d8663e51b91e2ea
|
[
"C++"
] | 1
|
C++
|
arianchemist/cryptographyA1
|
15615366c564a09c01fa7b0543ba80748139a507
|
1075dccfe0f9ed3c026f75b7fb69e9cefe074c8c
|
refs/heads/master
|
<repo_name>wklTomorrow/basic<file_sep>/leetcode/leetCode61.js
/*
1,2,3,4,5 k=2
4,5,1,2,3
*/
function createNode() {
this.next = null
this.size = 0
}
function LinkNode(val) {
this.val = val
this.next = null
}
createNode.prototype.getSize = function(n) {
let v = this.next
for (let i = 0; i <= this.size; i++) {
if (n == i) {
return v
}
v = v.next
}
}
createNode.prototype.add = function(val) {
if (this.size == 0 ) {
this.next = new LinkNode(val)
} else {
let v = this.getSize(this.size - 1)
v.next = new LinkNode(val)
}
this.size ++
return this
}
let zz = new createNode()
zz.add(1).add(2).add(3).add(4).add(5)
// console.log(zz.next)
function rotate(head, val) {
let len = 1
let b = head
while(b && b.next) {
b = b.next
len++
}
let move = len - val % len - 1
let a = head
while (move > 0) {
a = a.next
move--
}
b.next = head
let ss = a.next
a.next = null
return ss
}
console.log(rotate(zz.next, 2))
// function rotate(val, k) {
// let len = 1
// let b = val
// while(b && b.next) {
// b = b.next
// len++
// }
// let move = len - k % len
// let a = val
// while(--move > 0) {
// a = a.next
// }
// b.next = val
// let newHead = a.next
// a.next = null
// return newHead
// }
// console.log(rotate(zz.next, 2))
<file_sep>/Encapsulation/study_webpack/loader/index.js
const loaderUtils = require('loader-utils');
module.exports = function(source) {
// 获取
const options = loaderUtils.getOptions(this);
// this.callback({
// Error
// })
console.log(options, source);
// 关闭该 Loader 的缓存功能
this.cacheable(false);
// source 为 compiler 传递给 Loader 的一个文件的原内容
// 该函数需要返回处理后的内容,这里简单起见,直接把原内容返回了,相当于该 Loader 没有做任何转换
return source.replace('world', 'tomorrow');
};
<file_sep>/Encapsulation/webpack_new/src/utils/public.js
exports.a = 10;<file_sep>/leetcode/leetCode215.js
/*
数组中第k个最大元素
*/
let arr = [3,2,1,5,6,4]
let a = [3,2,3,1,2,4,5,5,6]
const getNum = (arr, k) => {
let obj = {}
for (let i = 0; i < arr.length; i++) {
let n = arr[i]
if (obj[n]) {
obj[n] + 1
} else {
obj[n] = 1
}
}
let bArr = Object.keys(obj)
bArr.sort((x, y) => x - y)
return bArr[bArr.length - k]
}
<file_sep>/leetcode/leetCode141.js
/*
环形链表
head=[3,2,0,-4], pos = 1
*/
function createNode() {
this.next = null
this.size = 0
}
function LinkNode(val) {
this.val = val
this.next = null
}
createNode.prototype.getSize = function(n) {
let v = this.next
for (let i = 0; i <= this.size; i++) {
if (n == i) {
return v
}
v = v.next
}
}
createNode.prototype.add = function(val) {
if (this.size == 0 ) {
this.next = new LinkNode(val)
} else {
let v = this.getSize(this.size - 1)
v.next = new LinkNode(val)
}
this.size ++
return this
}
var ss = new createNode()
let s1 = ss.add(3).add(4).add(2)
const hasCircle = (head) => {
let val = head
let map = new Map()
while(val && val.next) {
if (map.has(val)) return true
map.set(head, true)
val = val.next
}
}
const circle = (head) => {
let val1 = head
let val2 = head
while (val2) {
if (val2.next === null) return false
val2 = val2.next.next
val1 = val1.next
if (val1 === val2) {
return true
}
}
return false
}<file_sep>/Encapsulation/axios/axiosTest/axios1.js
/**
* axios
* axios({
* type: 'get',
* data: {}
* })
* axios.get(url, params)
*/
/**
* 请求、响应拦截器
* axios.interceptors.request.use(resolve, reject)
* axios.interceptors.response.use(resolve, reject)
*/
class Interceptor {
constructor() {
this.handle = []
}
use(successFn, failFn) {
this.handle.push({
successFn,
failFn
})
}
}
class _axios {
constructor() {
this.interceptors = {
request: new Interceptor(),
response: new Interceptor()
}
}
request(config) {
let queue = [this.senParams.bind(this), null]
this.interceptors.request.handle.forEach(fn => {
queue.unshift(fn.successFn, fn.failFn)
})
this.interceptors.response.handle.forEach(fn => {
queue.push(fn.successFn, fn.failFn)
})
// 把参数传递下去
let promise = Promise.resolve(config)
while (queue.length) {
promise = promise.then(queue.shift(), queue.shift())
}
return promise
}
senParams({
method = 'POST',
data = {},
url = ''
}) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open(method, url, true)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.response)
}
}
xhr.send(data)
})
}
}
let methods = ['GET', 'POST', 'PUT', 'DELETE']
methods.forEach(method => {
_axios.prototype[method] = function() {
return this.request({
method,
...arguments[0]
})
}
})
const createAxios = function() {
let axios = new _axios()
let req = axios.request.bind(axios)
extentds(req, _axios.prototype, axios)
extentds(req, axios)
return req
}
/**
* 原型继承工具函数
*/
function extentds(current, target, context) {
for (let i in target) {
if (target.hasOwnProperty(i)) {
if (typeof target[i] === 'function') {
current[i] = target[i].bind(context)
} else {
current[i] = target[i]
}
}
}
}
window.axios = new createAxios();<file_sep>/leetcode/shuffle.js
/*
洗牌算法
*/
let arrs = [1,2,3,4,5,6,7,8,9,10]
const getArr = (arr) => {
let newArr = []
for (let i = 0; i < arr.length;) {
let j = Math.floor(Math.random() * (arr.length - i))
newArr.push(arr[j])
arr.splice(j, 1)
}
console.log(newArr)
}
getArr(arrs)<file_sep>/my/meeting.md
# meeting
## 1、关于新建对象的三种方式比较
```javascript
let a = {} // 对象字面量,直接复制
let b = Object.created(null)
let c = new Object() // 本质上通过构造函数进行方法调用
// a与c只是初始化的过程有区别 后者通过构造函数创建对象,前者直接创建json对象,都是创建空对象
```
---
## 2、VUE数组相应式
> + 为什么不能监听数组的变化
> - 不是```Object.defineProperty```问题
> - vue响应式是通过```set```进行监听的,
> - 对于新增的属性,需要重新手动调用obverse
> - vue初始化数组,为每个对象添加getter与setter
> + 可监听的数组变化
> - ```push```
> - ```unshift```
> - ```pop```
> - ```shift```
> - ```reverse```
> - ```sort```
> - ```splice```
> + ```Object.defineProperty 与Proxy```
> - 第一个是只劫持对象属性,新增属性的时候还要进行define,来进行劫持,```proxy```是直接代理
> - 第一种对新增属性是要手动进行Observe的,所以在新增属性的时候需要重新遍历进行劫持,```proxy```是直接通过```set(target, propKey, value, receiver)```进行拦截
---
## 3、关于let、const块级作用域的理解
+ 在js中,只有两个作用域,函数作用域,全局作用域,ES6中新增了块级作用域,只要是{}就是块级作用域,if语句,for语句也是块级作用域
+ let、const,不可以跨块访问,var属性可以跨块访问,但不能跨函数作用域进行访问
---
## 4、封装new操作符
```javascript
/**
* new操作符封装
* @params {function} fn
* @params {array} arg
*/
function _new(fn, ...arg) {
let obj = Object.create(fn.prototype)
let ret = fn.apply(obj, arg)
return (typeof ret === 'function' || typeof ret === 'object') ? ret : obj
}
```
---
## 5、bind,call,apply函数的封装,函数的柯里化
```javascript
/**
* call操作符
*/
Function.prototype._call = function(objs) {
let obj = objs || window
obj.fn = this
obj.fn(...[...arguments].slice(1))
delete obj.fn
}
function say(s,y) {
console.log(this.a + this.b, s + y)
}
let objs = {
a: 1,
b: 2
}
say._call(objs, 3, 4)
/**
* apply操作符
*/
Function.prototype._apply = function(objs) {
let obj = objs || window
obj.fn = this
obj.fn(...arguments[1])
delete obj.fn
}
function say(s,y) {
console.log(this.a + this.b, s + y)
}
let objs = {
a: 1,
b: 2
}
say._apply(objs, [3, 4])
/**
* bind操作符
*/
Function.prototype._bind = function(oThis) {
let fn = this
let arg = [...arguments].slice(1)
return function () {
fn.apply(oThis, arg)
}
}
/**
* 柯里化函数
*/
function curry(fn, ...res) {
let len = fn.length
let arg = [...res]
return function () {
arg.push(...arguments)
if (arg.length < len) {
return curry.call(this, fn, arg)
}
return fn.apply(undefined, arg)
}
}
let fn = function(a, b, c) {
return a + b + c
}
let fn1 = new curry(fn, 1)
console.log(fn1(2,3))
```
## 6、webpack相关
> webpack: loader相关
> webpack与gulp区别
- gulp强调的是前端开发流程,一个流程中有多个task,按照顺序执行
- webpack是一个前端模块化工具,把所有的文件打包成生成所需的文件<file_sep>/leetcode/leetCode20.js
/*
有效的括号数
{},(),【】
*/
const getFlag = str => {
if (str % 2 == 1) {
return false
}
let arr = []
for (let i = 0; i < str.length; i++) {
if (str[i] === '(') {
arr.push(')')
} else if (str[i] === '{') {
arr.push('}')
} else if (str[i] === '[') {
arr.push(']')
} else if (arr.pop() !== str[i]) {
return false
}
}
return !arr.length
}
const getStr = str => {
let obj = {
'(': ')',
'{': '}',
'[': ']'
}
let newArr = []
for (let i = 0; i < str.length; i++) {
if (obj[str[i]]) {
newArr.push(obj[str[i]])
} else {
if (newArr.pop() !== str[i]) {
return false
}
}
}
return newArr.length == 0
}<file_sep>/jsStudy/promise.js
function myPromise(fn) {
let _this = this
_this.status = 'pending'
_this.resolveArr = []
_this.rejectArr = []
_this.value = null
_this.reason = null
function resolve(val) {
setTimeout(() => {
if (_this.status === 'pending') {
_this.value = val
_this.status = 'fulFilled'
_this.resolveArr.forEach(Fn => {
_this.value = Fn(_this.value)
})
}
})
}
function reject(val) {
setTimeout(() => {
if (_this.status === 'pending') {
_this.reason = val
_this.status = 'rejected'
_this.rejectArr.forEach(Fn => {
_this.reason = Fn(_this.reason)
})
}
})
}
try {
fn(resolve, reject)
} catch(e) {
reject(e)
}
}
myPromise.prototype.then = function(resolveThen, rejectThen) {
let _this = this
typeof resolveThen === 'function' && _this.resolveArr.push(resolveThen)
typeof rejectThen === 'function' && _this.rejectArr.push(rejectThen)
return _this
}
<file_sep>/leetcode/leetCode14.js
/*
最长公共前缀
['flower', 'flow', 'flight'] // 'fl'
*/
let arr = ['flower', 'flow', 'flight']
function getThis(arr) {
let str = ''
for (let i = 0; i < arr[0].length; i++) {
str += arr[0][i]
let flag = true
for (let j = 0; j < arr.length; j++) {
if (arr[j].indexOf(str) === -1) {
flag = false
break
}
}
if (!flag) {
str = str.replace(str[str.length - 1], '')
break
}
}
return str
}
console.log(getThis(arr))
// 分治法
function getStr (arr) {
return devide(arr, 0 , arr.length - 1)
}
function devide(arr, left, right) {
if (left === right) {
return arr[left]
}
let len = Math.floor((right + left) / 2)
let l = devide(arr, left, len)
let r = devide(arr, len + 1, right)
return compare(l, r)
}
function compare(left, right) {
let min = Math.min(left.length, right.length)
for (let i = 0; i < min; i++) {
if (left[i] !== right[i]) {
return left.slice(0, i)
}
}
return left.slice(0, min)
}
console.log(getStr(arr))<file_sep>/Encapsulation/other_html/animate.js
(
function(fn) {
fn()
}
)(function() {
function Query(dom) {
return new Query.fn.init(dom)
}
Query.fn = Query.prototype = {
constructor: Query,
getRandom: function(num) {
return parseInt(Math.random() * num)
},
start: function(opt) {
let option = {
height: this.height,
width: this.width,
leftSpeed: 20,
topSpeed: 10,
num: 1000,
msg: '*',
font: '18px Arial',
colorMax: 255,
time: 100,
}
if (opt !== null && Object.prototype.toString.call(opt) === '[object Objcet]') {
option = {
...option,
...opt
}
}
let _this = this
if (!this.numArr.length) this.numArr = Array.from({length: option.num}, x => ({}))
this.ctx.clearRect(0, 0, option.width, option.height);
for (let i = 0; i < this.numArr.length; i++) {
if (!Object.keys(this.numArr[i]).length) {
this.numArr[i] = {
r: this.getRandom(option.colorMax),
g: this.getRandom(option.colorMax),
b: this.getRandom(option.colorMax),
left: this.getRandom(option.width),
leftLen: this.getRandom(option.leftSpeed),
top: this.getRandom(option.height),
topLen: this.getRandom(option.topSpeed)
}
}
let leftLens = this.numArr[i].left + this.numArr[i].leftLen
let topLens = this.numArr[i].top + this.numArr[i].topLen
this.numArr[i] = {
...this.numArr[i],
left: leftLens > option.width ? 0 : leftLens,
top: topLens > option.height ? 0 : topLens
}
this.ctx.font = option.font;
this.ctx.fillStyle = `rgb(${this.numArr[i].r}, ${this.numArr[i].g}, ${this.numArr[i].b})`
this.ctx.fillText(option.msg, this.numArr[i].left, this.numArr[i].top);
}
setTimeout(function () {
return function() {
_this.start(_this.numArr.length)
}
}(), option.time);
}
}
Query.fn.init = function(dom) {
this.dom = document.getElementById(dom.slice(1))
this.ctx = this.dom.getContext("2d");
let {offsetHeight, offsetWidth} = this.dom
this.height = offsetHeight
this.width = offsetWidth
this.numArr = []
}
Query.fn.init.prototype = Query.fn
window.$ = Query
})<file_sep>/leetcode/leetCode101.js
/*
对称二叉树
*/
// 实现二叉树
class Node {
constructor(key) {
this.data = key
this.left = null
this.right = null
}
}
class BST {
constructor() {
this.root = null
}
insert(data) {
let node = new Node(data)
const insertNode = (node, newNode) => {
if (newNode.data < node.data) {
if (node.left) {
insertNode(node.left, newNode)
} else {
node.left = newNode
}
} else {
if (node.right) {
insertNode(node.right, newNode)
} else {
node.right = newNode
}
}
}
if (this.root) {
insertNode(this.root, node)
} else {
this.root = node
}
}
}
let node = new BST()
// let arr = [1,2,2,3,4,4,3]
let arr = [8,3,10,1,6,14,4,7,13]
arr.forEach(e => {
node.insert(e)
})
const isSymmetric = function(node) {
if (!node) {
return true
}
const leftAndRight = function(left, right) {
if (!left && !right) {
return true
}
if (!left || !right) return false
if (left.data !== right.data) {
return false
}
return leftAndRight(left.left, left.right) && leftAndRight(right.left, right.right)
}
return leftAndRight(node.root.left, node.root.right)
}
console.log(isSymmetric(node))
<file_sep>/leetcode/leetCode06.js
/*
Z字形变换
给定一个字符与一个数值
循环行数为2n - 2
h o
e wr
l o l
l d
*/
let str = 'helloworld'
/**
*
* @param {Sting} str
* @param {Number} num
*/
const getStr = (str, num) => {
let len = str.length
let count = 2 * num - 2
let arr = Array.from({length: num}, x => '')
for (let i = 0; i < len; i++) {
let r = i % count
arr[r > num - 1 ? count - r : r] += str[i]
}
return arr.join('')
}
console.log(getStr(str, 3))<file_sep>/leetcode/leetCode22.js
/*
括号生成问题
左括号与右括号,生成对问题
*/
const getNum = (num) => {
let arr = []
getMax(num, num, '', arr)
return arr
}
const getMax = (left, right, str, arr) => {
if (right > left) return
if (left === 0 && right === 0) {
arr.push(str)
} else {
if (left > 0) {
getMax(left - 1, right, str +')', arr)
}
if (right > 0) {
getMax(left, right - 1, str + '(', arr)
}
}
}
// var list = []
// let F = function (n) {
// if (list[n]) {
// return list[n]
// }
// let res = []
// if (n == 0 || n == 1) {
// list[0] = ['']
// list[1] = ['()']
// return list[n]
// }
// for (let i = 0; i < n; i++) {
// let cur = F(i)
// let remain = F(n - i - 1)
// // console.log(cur, remain)
// for (let z = 0; z < cur.length; z++) {
// // let str = '(' + cur[z] + ')'
// let str = '(' + cur[z] + ')'
// for (let j = 0; j < remain.length; j++) {
// str = str + remain[j]
// res.push(str)
// }
// }
// }
// list[n] = res
// return list[n]
// }
// console.log(F(3))
let F = function(n) {
let arr = [n, n]
function getThis(a, cur) {
let curArr = [...a]
let left = []
let right = []
if (curArr[0] > curArr[1]) {
return []
} else if (curArr[1] === 0) {
return [')']
} else {
if (curArr[0] === 0) {
curArr[1]--
right = getThis(curArr, ')')
for (let i = 0; i < right.length; i++) {
right[i] = cur + right[i]
}
return right
} else {
curArr[0]--
left = getThis(curArr, '(')
for (let i = 0; i < left.length; i++) {
left[i] = cur + left[i]
}
curArr[0]++
curArr[1]--
right = getThis(curArr, ')')
for (let i = 0; i < right.length; i++) {
right[i] = cur + right[i]
}
return left.concat(right)
}
}
}
return getThis(arr, '')
}
console.log(F(3))
// var generateParenthesis = function (n) {
// let res = [];
// // cur :当前字符 left:当前字符左括号 right:当前字符右括号
// const help = (cur, left, right) => {
// if (cur.length === 2 * n) {
// res.push(cur);
// return;
// }
// if (left < n) {
// help(cur + "(", left + 1, right)
// }
// if (right < left) {
// help(cur + ")", left, right + 1);
// }
// };
// help("", 0, 0);
// return res;
// };
console.log(getNum(3))<file_sep>/Encapsulation/eventBus/event.js
/**
* vue event
* event.emit()
* event.on()使用
* this.emit(name, param1, param2...)
* this.on(name, cb(e) {
* console.log(e)
* })
*/
let events = {}
module.exports = {
emit(name, ...args) {
events[name].forEach(item => {
item(args)
})
},
on(name, cb) {
events[name] ? events[name].push(cb)
: events[name] = Object.assign([], [cb])
},
remove(name) {
events[name] && delete events[name]
},
getThis() {
return events
}
}<file_sep>/Encapsulation/cookie/疑问.md
## es6 class 继承 子组件未调用supenthis<file_sep>/leetcode/leetCode374.js
/*
返回前k个频出现的数字
*/
/**
*
* @param {array} arr
* @param {number} num
*/
const getNum = (arr, num) => {
let newArr = Array.from(new Set(arr))
let map = new Map()
for (let i = 0; i < arr.length; i++) {
if (map.has(arr[i])) {
map.set(arr[i], map.get(arr[i]) + 1 )
} else {
map.set(arr[i], 1)
}
}
newArr.sort((a, b) => {
return map.get(b) - map.get(a)
})
return newArr.splice(0, num)
}
console.log(getNum([1,2,3,1,2,4], 2))<file_sep>/Encapsulation/axios/utils.js
// export function extend (a, b, context) {
// for (let key in b) {
// if (b.hasOwnProperty(key)) {
// if (typeof b[key] === 'function') {
// a[key] = b[key].bind(context);
// } else {
// a[key] = b[key];
// }
// }
// }
// }
exports.extend = function(a, b, context) {
for (let key in b) {
if (b.hasOwnProperty(key)) {
if (typeof b[key] === 'function') {
a[key] = b[key].bind(context);
} else {
a[key] = b[key];
}
}
}
}
<file_sep>/leetcode/leetCode16.js
/*
最接近的三数之和
[-1, 2, 1, -4] tar = 1 val = 2
*/
let arr = [-1, 2, 1, -4]
const getMax = (arr, val) => {
let min
for (let i = 0; i < arr.length; i++) {
let s = i + 1
let end = arr.length - 1
while(s < end) {
let num = arr[i] + arr[end] + arr[s] - val
min = min ? Math.abs(min) > Math.abs(num) ? num : min : num
end--
}
}
return min + val
}
console.log(getMax(arr, 1))<file_sep>/leetcode/leetCode09.js
/*
回文数
*/
/**
*
* @param {numbe} num
*/
const isNum = (num) => {
if (num < 0) {
return false
}
}
/**
*
* @param {*} num
* @param {*} n
* @returns 第n位
*/
const getNum = (num, n) => {
let zz = Math.floor(num % Math.pow(10, n) / Math.pow(10, n - 1))
return zz
}<file_sep>/leetcode/arrayAllSort.js
const arr = [1, 2, 3, 4]
function getArr(arr) {
if (!arr.length) return []
let allArr = []
for (let i = 0; i < arr.length; i++) {
let splArr = JSON.parse(JSON.stringify(arr))
splArr.splice(i, 1)
let a = getArr(splArr)
if (a.length) {
a.forEach(ele => {
allArr.push(arr[i] + '' + ele)
})
} else {
allArr = [arr[i]]
}
}
return allArr
}
console.log(getArr(arr))<file_sep>/demo/vuex.js
import * as types from '../mutation-types'
import api from '../../api/energyConsum'
import store from '../'
import { type } from 'os'
const getState = () => ({
eleList: [],
eleMetricList: [],
branchVlueList: [],
})
export const state = getState()
export const actions = {
async getPointByDevice({ commit, state }, params) {
let { data } = await api.getPointByDevice(params)
commit(types.BRANCH_VALUE_LIST, data)
return data
},
async getBranchValueType({ commit, state }, params) {
let {data} = await api.getBranchValueType(params)
return data
},
async getBranchValueDevice({ commit, state }, params) {
let {data} = await api.getBranchValueDevice(params)
return data
},
async getProcessList({ commit, state }, params) {
let {data} = await api.getProcessList(params)
return data
},
async getCalculateTypeList({ commit, state }, params) {
let {data} = await api.getCalculateTypeList(params)
return data
},
async getCalculateCharts({ commit, state }, params) {
let {data} = await api.getCalculateCharts(params)
return data
},
async republish({ commit, state }, params) {
let data = await api.republish(params)
return data
},
async getAllTagTypeList({ commit, state }, params) {
let {data} = await api.getAllTagTypeList(params)
return data
},
async getTagInstanceList({ commit, state }, params) {
let data = await api.getTagInstanceList(params)
return data
},
async getPeriodList({ commit, state }, params) {
let data = await api.getPeriodList(params)
return data
},
async drawTree({ commit, state }, params) {
let data = await api.drawTree(params)
return data
},
async treeTagCode({ commit, state }, params) {
let {data} = await api.treeTagCode(params)
return data
},
async getPublicDataType({ commit, state }, params) {
let {data} = await api.getPublicDataType(params)
return data
},
async getPublicDataList({ commit, state }, params) {
let {data} = await api.getPublicDataList(params)
return data
},
async isConfirm({ commit, state }, params) {
let info = store.state.layout.systemInfo
params.aliasCode = info.STATION_ID
let data = await api.isConfirm(params)
return data
},
async updateUnit({ commit, state }, params) {
let {data} = await api.updateUnit(params)
return data
},
async checkPointAndChg({ commit, state }, params) {
let {data} = await api.checkPointAndChg(params)
return data
},
async getEnergyTree({ commit, state }, params) {
let data = await api.getEnergyTree(params)
return data
},
async updateEnergyTree({ commit, state }, params) {
let data = await api.updateEnergyTree(params)
return data
},
async createEnergyRootTree({ commit, state }, params) {
let data = await api.createEnergyRootTree(params)
return data
},
async deleteEnergyTree({ commit, state }, params) {
let { data } = await api.deleteEnergyTree(params)
return data
},
async createEnergyTree({ commit, state }, params) {
let data = await api.createEnergyTree(params)
return data
},
async getAttrById({ commit, state }, params) {
let data = await api.getAttrById(params)
return data
},
async updateAttrValue({ commit, state }, params) {
let data = await api.updateAttrValue(params)
return data
},
async deleteTreeNode({ commit, state }, params) {
let data = await api.deleteTreeNode(params)
return data
},
async getMesurePoint({ commit, state }, params) {
let data = await api.getMesurePoint(params)
return data
},
async getCalculateInfo({ commit, state }, params) {
let { data } = await api.getCalculateInfo(params)
return data
},
async getDeviceObjInfo({ commit, state }, params) {
let { data } = await api.getDeviceObjInfo(params)
return data
},
async getPointBaseInfo({ commit, state }, params) {
let info = store.state.layout.systemInfo
let { data } = await api.getPointBaseInfo(params)
return data
},
async calculateEditAdd({ commit, state }, params) {
let info = store.state.layout.systemInfo
params.creator = info.USER_NAME
params.aliasCode = info.STATION_ID
let data = await api.calculateEditAdd(params)
return data
},
async getYData({ commit, state }, params) {
let info = store.state.layout.systemInfo
params.creator = info.USER_NAME
params.stationId = info.STATION_ID
let { data } = await api.getYData(params)
return data
},
async createHumanPoint({ commit, state }, params) {
let { data } = await api.createHumanPoint(params)
return data
},
async createPoint({ commit, state }, params) {
let { data } = await api.createPoint(params)
return data
},
async createPointValue({ commit, state }, params) {
let { data } = await api.createPointValue(params)
return data
},
async deleteHumanPoint({ commit, state }, params) {
let { data } = await api.deleteHumanPoint(params)
return data
},
async editPointValue({ commit, state }, params) {
let data = await api.editPointValue(params)
return data
},
async deleteComputeItem({ commit, state }, params) {
let data = await api.deleteComputeItem(params)
return data
},
async compareTime({ commit, state }, params) {
let data = await api.compareTime(params)
return data
},
async getTagList({ commit, state }, params) {
let { data } = await api.getTagList(params)
return data
},
async getNTagList({ commit, state }, params) {
let { data } = await api.getNTagList(params)
return data
},
async getDeviceInfoByCode({ commit, state }, params) {
let { data } = await api.getDeviceInfoByCode(params)
return data
},
async getElectricTypeList({ commit, state }) {
let { data } = await api.getElectricTypeList()
commit(types.ELEC_LIST, data)
return data
},
async saveBranchPoint({ commit, state }, params) {
let data = await api.saveBranchPoint(params)
return data
},
async updateTrdCode({commit, state}, params) {
let data = await api.updateTrdCode(params)
return data
},
async getLabelType({commit, state}, params) {
let { data } = await api.getLabelType(params)
return data
},
async getLabelName({commit, state}, params) {
let { data } = await api.getLabelName(params)
return data
},
async getDeviceGroupList({commit, state}, params) {
let { data } = await api.getDeviceGroupList(params)
return data
},
async getDeviceTagList({commit, state}, params) {
let { data } = await api.getDeviceTagList(params)
return data
},
async updateDeviceTagTrd({commit, state}, params) {
let { data } = await api.updateDeviceTagTrd(params)
return data
},
async getDeviceListBySystemCodeAndGroupType({commit, state}, params) {
let { data } = await api.getDeviceListBySystemCodeAndGroupType(params)
return data
},
async createGroup({commit, state}, params) {
let { data } = await api.createGroup(params)
return data
},
async editPointUnit({commit, state}, params) {
let { data } = await api.editPointUnit(params)
return data
},
async getAllDeviceByStationAngId({commit, state}, params) {
let { data } = await api.getAllDeviceByStationAngId(params)
return data
},
async createDeviceTreeRootAndChil({commit, state}, params) {
let { data } = await api.createDeviceTreeRootAndChil(params)
return data
},
async getDeviceTypeByStationId({commit, state}, params) {
let { data } = await api.getDeviceTypeByStationId(params)
return data
},
// async onDeleteDeviceTreeByTreeIdAndDeviceId({commit, state}, params) {
// let { data } = await api.onDeleteDeviceTreeByTreeIdAndDeviceId(params)
// return data
// },
async onDeleteTreeNode({commit, state}, params) {
let { data } = await api.onDeleteTreeNode(params)
return data
},
async getEleInfoByDevice({commit, state}, params) {
let { data } = await api.getEleInfoByDevice(params)
return data
},
async onGetEleMetric({commit, state}, params) {
let { data } = await api.onGetEleMetric(params)
commit(types.ELE_METRIC_LIST, data)
return data
},
async onSaveEleRelation({commit, state}, params) {
let data = await api.onSaveEleRelation(params)
return data
},
async onGetPowerFactorStandard({commit, state}, params) {
let { data } = await api.onGetPowerFactorStandard(params)
return data
},
async onGetPolyPoint({commit, state}, params) {
let { data } = await api.onGetPolyPoint(params)
return data
},
async onGetPolyDevice({commit, state}, params) {
let { data } = await api.onGetPolyDevice(params)
return data
},
async onGetPolyDeviceRange({commit, state}, params) {
let { data } = await api.onGetPolyDeviceRange(params)
return data
},
async onGetAttrByDeviceGroupId({commit, state}, params) {
let data = await api.onGetAttrByDeviceGroupId(params)
return data
},
async onSavePolyFormula({commit, state}, params) {
let data = await api.onSavePolyFormula(params)
return data
},
async onUpdatePointNameByCode({commit, state}, params) {
let data = await api.onUpdatePointNameByCode(params)
return data
},
}
export const mutations = {
[types.ELEC_LIST](state, data) {
state.eleList = data
},
[types.ELE_METRIC_LIST](state, data) {
state.eleMetricList = data
},
[types.BRANCH_VALUE_LIST](state, list) {
state.branchVlueList = list;
}
}
export default {
state,
actions,
mutations
}
<file_sep>/Encapsulation/webpack_new/src/another.js
const a = require('./utils/public')
console.log(a, 'another')
console.log('another')<file_sep>/my/ts.md
## base
- typeof
```javascript
interface Person {
name: string,
age: number
}
const sem: Person = { name: 'hello', age: 30 }
type s = typeof sem // Person
```<file_sep>/Encapsulation/axios/axios.js
// axios(config);
function extend (a, b, context) {
for (let key in b) {
if (b.hasOwnProperty(key)) {
if (typeof b[key] === 'function') {
a[key] = b[key].bind(context);
} else {
a[key] = b[key];
}
}
}
}
class InterceptorsManage {
constructor() {
this.handle = [];
}
use(onFulField, onReject) {
this.handle.push({
onFulField,
onReject
})
}
}
class Axios {
constructor() {
this.interceptors = {
response: new InterceptorsManage(),
request: new InterceptorsManage()
}
};
request(config) {
const chain = [this.sendAjax.bind(this), undefined];
this.interceptors.request.handle.forEach(interceptor => {
chain.unshift(interceptor.onFulField, interceptor.onReject);
});
this.interceptors.response.handle.forEach(interceptor => {
chain.push(interceptor.onFulField, interceptor.onReject);
});
let promise = Promise.resolve(config);
while(chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
sendAjax(config) {
return new Promise((resolve, reject) => {
const {data = {}, url = '', method = 'get' } = config;
let xml = new XMLHttpRequest();
xml.open(method, url, true);
xml.onreadystatechange = () => {
if (xml.readyState === 4 && xml.status === 200) {
resolve(xml.responseText);
}
};
xml.send(JSON.stringify(data));
})
}
}
// axios.methods(get, post, delete)
const Methods = ['get', 'post', 'put'];
Methods.forEach(method => {
Axios.prototype[method] = function () {
return this.request({
method: method,
...arguments[0]
});
}
})
function CreateAxios() {
let axios = new Axios();
let req = axios.request.bind(axios);
extend(req, Axios.prototype, axios);
extend(req, axios);
return req;
}
window.axios = new CreateAxios();
// axios.get(url, parmas)<file_sep>/es/es7+es8.md
## 1、ES7
- Array.prototype.includes
- 能够查到NaN
- +0、-0被认为相等
- 求幂运算符
> 3 ** 2 === Math.pow(3, 2)
- async/await
```javascript
let sayHello = async function sayHello() {
let hi = 'hello world'//等同于return Promise.resolve(hi);
return hi
}
sayHello().then(res => {
console.log(res)
}).catch(err => {
console.log(err.message);
})
```
- Object.entries()
- 会自动忽略symbol
- ```javascript
let obj = {foo: 1, bar: 2}
let map1 = new Map([['foo', 1], ['bar', 2]])
let map2 = new Map(Object.entries(obj))
```
- 会自动按照数组对象下标进行排序
```javascript
Object.entries({ 3: 'a', 4: 'b', 1: 'c' }) // [[1, 'c'], [3, 'a'], [4, 'b']]
```
- Object.values()(根entries一致,返回按照下标进行排序的数组) && Object.keys()
- 字符串填充(padStart, padEnd)
- ```javascript
'Vue'.padEnd(10, '_*') //'Vue_*_*_*_'
'React'.padEnd(10, 'Hello') //'ReactHello'
'JavaScript'.padEnd(10, 'Hi') //'JavaScript'
'JavaScript'.padEnd(8, 'Hi') //'JavaScript'
```
- Object.getOwnPropertyDescriptors()
----
## 2、ES8
- Decrator
<file_sep>/leetcode/leetCode72.js
/*
最小编辑距离,包含插入,替换,删除操作
word1 = 'hello'
word2 = 'llo'
*/
function exchangeWord(str1, str2) {
let len1 = str1.length
let len2 = str2.length
let newArr = Array.from({length: len1}, x => [])
for (let i = 0; i <= len1; i++) {
newArr[i] = Array.from({length: len2}, x=> [])
for (let j = 0; j <= len2; j++) {
if (j === 0) {
newArr[i][j] = i
} else if (i === 0) {
newArr[i][j] = j
} else {
let count = 1
if (len1[i] === len2[j]) {
count = 0
}
newArr[i][j] = Math.min(newArr[i][j - 1] + 1, newArr[i - 1][j] + 1, newArr[i - 1][j - 1] + count)
}
}
}
console.log(newArr)
return newArr[len1][len2]
}
console.log(exchangeWord('hello', 'lo'))<file_sep>/leetcode/leetCode21.js
/*
合并两个有序链表
*/
const merge = (a, b) => {
let head = null
while (a.next && b.next) {
if (a.value > b.value) {
head.next = b.value
b = b.next
head.next.next = null
} else {
head.next = a.value
a = a.next
head.next.next = null
}
}
if (a.next) {
head.next = a.next
}
if (b.next) {
head.next = b.next
}
}
var mergeTwoLists = function(l1, l2) {
var newL = new ListNode() // 新建链表
var res = newL
while(l1 !== null && l2 !== null){ //循环链表 比较大小进行赋值
if(l1.val < l2.val){
newL.next = l1
l1=l1.next // next到下一位(这点很重要)
} else {
newL.next = l2
l2=l2.next //同上,很重要
}
newL = newL.next // next到下一位,重要
}
newL.next = (l1 === null) ? l2 : l1 // 当其中一个循环完毕后,将另一个直接赋值过去
return res.next
};<file_sep>/leetcode/leetCode283.js
/*
移动0
*/
/**
*
*/
function moveZero(arr) {
if (arr.length) {
let index = 0
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== 0) {
arr[index] = arr[i]
index++
}
}
while (index < arr.length) {
arr[index] = 0
index ++
}
}
return arr
}<file_sep>/leetcode/leetCode26.js
/*
删除排序数组中的重复项
nums = [1,1,2] 返回2,[1,2]
*/
let arr = [0,0,1,1,2,2,3,3]
function onDeleteArr(arr) {
let num = 0
arr.map((ele, index) => {
if (index != 0) {
if (ele !== arr[index - 1]) {
arr[num] = ele
num++
}
} else {
num++
}
})
return num
}
console.log(onDeleteArr([1,1]))<file_sep>/leetcode/leetCode73.js
/**
* 矩阵清0
*/
/*
*/
let arr = [
[1,2,3],
[4,0,6],
[7,8,9]
]
const getArr = arr => {
let newArr = []
for(let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (arr[i][j] === 0) {
newArr.push([i, j])
}
}
}
console.log(newArr)
}
getArr(arr)
/*
反转链表
1,2,3,4,5
5,4,3,2,1
let a = head
while(a && a.next) {
let end = a.next
a.next = a.next.next
end.next = head
head = end
}
*/<file_sep>/Encapsulation/webpack_new/dist/another.bundle.js
webpackJsonp([1],{
/***/ 2:
/***/ (function(module, exports, __webpack_require__) {
const a = __webpack_require__(0)
console.log(a, 'another')
console.log('another')
/***/ })
},[2]);<file_sep>/leetcode/BST.js
let arr = [11,7,5,3,6,9,8,10,20,14,12,25,18]
/*
js实现顺序二叉树
前序遍历 => 1.访问根节点; 2.访问左子树; 3.访问右子树
中序遍历 =>
1.访问左子树(先访问左子树中的左子树,再访问左子树中的右子树);
2.访问根
3.访问右子树(先访问右子树中的左子树,再访问右子树中的右子树)
可以起到排序作用
后序遍历 =>
1.访问左子树。(先访问左子树中的左子树,再访问左子树中的右子树)
2.访问右子树。(先访问右子树中的左子树,再访问右子树中的右子树)
3.访问根
*/
class Node {
constructor(data) {
this.data = data
this.left = null
this.right = null
}
}
function BST(arr) {
this.root = null
}
BST.prototype.insert = function(value) {
if (this.root) {
this.insertNode(this.root, new Node(value))
} else {
this.root = new Node(value)
}
}
BST.prototype.insertNode = function(root, node) {
if (root.data > node.data) {
if (root.left) {
this.insertNode(root.left, node)
} else {
root.left = node
}
} else {
if (root.right) {
this.insertNode(root.right, node)
} else {
root.right = node
}
}
}
// 中序遍历
BST.prototype.midOrder = function () {
let midArr = []
const getMid = (node) => {
if (node) {
getMid(node.left)
midArr.push(node.data)
getMid(node.right)
}
}
getMid(this.root)
return midArr
}
// 前序遍历
BST.prototype.preOrder = function() {
let preArr = []
const getPre = node => {
if (node) {
preArr.push(node.data)
getPre(node.left)
getPre(node.right)
}
}
getPre(this.root)
return preArr
}
// 后序遍历
BST.prototype.endOrder = function() {
let endArr = []
const getEnd = node => {
if (node) {
getEnd(node.left)
getEnd(node.right)
endArr.push(node.data)
}
}
getEnd(this.root)
return endArr
}
// 查找最小值
BST.prototype.getMin = function() {
const min = (node) => {
return node.left ? min(node.left) : node.data
}
return min(this.root)
}
// 查找最大值
BST.prototype.getMax = function() {
const max = (node) => {
return node.right ? max(node.right) : node.data
}
return max(this.root)
}
// 查找特定的节点值
BST.prototype.getValue = function(val) {
const getV = function(v) {
if (v.data === val) {
return v
} else {
if (v.data > val) {
return getV(v.left)
} else {
return getV(v.right)
}
}
}
return getV(this.root)
}
// 删除节点,并返回新的二叉树
BST.prototype.deleteNode = function(node) {
if (node === this.root.data) {
this.root = null
}
const deleteN = (root) => {
if (root) {
if (root.left.data === node) {
root.left = null
}
if (root.right.data === node) {
root.right = null
}
}
}
deleteN(this.root)
return this.root
}
let bst = new BST()
// bst.insert(10)
arr.forEach(ele => {
bst.insert(ele)
})
console.log(bst)
<file_sep>/leetcode/leetCode03.js
/*
最长无重复字串
abcabcab // abc
*/
let str = 'abcabcd'
const longStr = str => {
let arr = [], max = 0
for (let i = 0; i < str.length; i++) {
let s = str.charAt(i)
let index = arr.indexOf(s)
if (index !== -1) {
arr.splice(0, 1)
}
arr.push(s)
max = Math.max(arr.length, max)
}
return max
}
console.log(longStr(str))
const longMap = str => {
let map = new Map(), max = 0
for (let i = 0, j = 0; i < str.length; i++) {
if (map.has(str[i])) {
j = Math.max(map.get(str[i]) + 1, j)
}
max = Math.max(max, i - j + 1)
map.set(str[i], i)
}
return max
}
console.log(longMap(str))
// 'abca'
const longSlice = function(str) {
let max = 0
for (let i = 0, j = 0; j < str.length; j++) {
let index = str.slice(i, j).indexOf(str[j])
if (index !== -1) {
i = i + index + 1
}
max = Math.max(max, j - i + 1)
}
return max
}
console.log(longSlice(str))<file_sep>/others/study.md
# hello world
***
## 1、明天
+ hello *hello*
* hello __hello__
- hello
- hello
* hello __hello__
+ hello **hello*
***
## 2、后天
* hello
> hello
> hello
> hello
* hello
```javaScript
function x() {
return ture
}
```
* 这是一个链接 [百度链接](www.baidu.com)
* table
| 标题一 | 标题二 | 标题三 |
| ---: | :--- | :---: |
| 内容 | 内容 | 内容 |
| 内容 | 内容 | 内容 |
***
+ hello *hello*
* hello __hello__
- hello
- hello
* hello __hello__
+ hello **hello*
***
## 标题三
1、hello
- hello
`javascript`
- hello
2、hello<file_sep>/leetcode/leetCode189.js
/* 输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入: [-1,-100,3,99] 和 k = 2
输出: [3,99,-1,-100]
解释:
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。 */
let arr = [1, 2, 3, 4, 5, 6, 7], k = 3
// function getSize(arr, num) {
// const a1 = arr.slice(0, Math.abs(arr.length - num))
// const a2 = arr.slice(Math.abs(arr.length - num))
// return a2.concat(a1)
// }
// function rotate(arr, num) {
// for (let i = 0; i < num; i++) {
// let count = arr[arr.length - 1]
// for (let j = arr.length - 1; j > 0; j--) {
// arr[j] = arr[j - 1]
// }
// arr[0] = count
// }
// return arr
// }
const rotate = (arr, k) => {
let n = k % arr.length
// 数组先进行反转,后面再次进行反转
rotateChil(arr, 0, arr.length - 1)
rotateChil(arr, 0, n - 1)
rotateChil(arr, n, arr.length - 1)
return arr
}
function rotateChil(arr, start, end) {
while (start < end) {
;[arr[start], arr[end]] = [arr[end], arr[start]]
start++
end--
}
}
let arr1 = [1, 2],n = 3
console.log(rotate(arr, k))
console.log(rotate(arr1, n))<file_sep>/js/FZ.js
/**
* 加法运算
* @param {number} a
* @param {number} b
* @returns {number}
*/
function go(a, b) {
return a + b
}
/*
熟悉mac注释
*/
/**
* 封装
* @param {Object}} options
*/
async function Ajax(options = {
url: 'http://www.baidu.com',
methods: 'POST',
data: {},
success: function(e) {
console.log(e)
},
fail: function(e) {
console.log(e)
}
}) {
let value = await returnPromise()
options.success(value)
// return returnPromise().then(res => {
// options.success(res)
// })
}
const returnPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1000)
}, 1000);
})
}
let zz = Ajax(
{
success: function(e) {
console.log(`hello ${e}`)
}
}
)
console.log(zz, 1111)<file_sep>/leetcode/leetCode945.js
/**
* 使数组唯一的最小增量
* [1,1,2,2,3,7]
*/
let arr = [1,1,2,2,3,7]
const getMin = a => {
let min = 0
for (let i = 0; i < a.length; i++) {
let index = a.indexOf(a[i])
let last = a.lastIndexOf(a[i])
min += (last - index)
while (index !== last) {
index ++
a[index] ++
}
}
console.log(min)
}
getMin(arr)<file_sep>/leetcode/leetCode763.js
/*
划分字母区间
尽可能多的划分区间
*/
/**
*
* @param {String} str
*/
function getMax(str) {
let res = []
for (let i = 0; i < str.length;) {
if (str.lastIndexOf(str[i]) === i) {
res.push(1)
i++
} else {
let maxIndex = str.lastIndexOf(str[i])
for(let j = i+1; j < maxIndex; j++) {
maxIndex = str.lastIndexOf(str[j]) > maxIndex ? str.lastIndexOf(str[j]) : maxIndex
}
res.push(maxIndex-i+1)
i = maxIndex + 1
}
}
return res
}
console.log(getMax('ababcbacadefegdehijhklij'))<file_sep>/leetcode/leetCode05.js
/*
最长的回文串
*/
const getMaxStr = str => {
let s = ''
const getStr = (left, right) => {
while(left >= 0 && right < str.length && str[left] === str[right]) {
if (right - left + 1 >= s.length) {
s = str.slice(left, right + 1)
}
left--
right++
}
}
for (let i = 0; i < str.length; i++) {
getStr(i, i + 1)
getStr(i - 1, i + 1)
}
return s
}
console.log(getMaxStr('bb'))<file_sep>/my/reg.js
/*
正则学习
*/
// let reg = /([a-z]+)([A-Z])+/
// let reg = /[a-z]/g
// let reg = /[1-9][0-9]?/g // 匹配两位数
// let str = '111'
// let str = 'abcD'
// console.log(reg.test(str))
// console.log(str.match(reg))
let str = '<h1>hello world</h1>'
let reg = /<.*?>/
console.log(str.match(reg))
<file_sep>/Encapsulation/function/es6.js
function test(obj, prop, other) {
console.log(obj, prop, other)
}
test({name: 10}, {age: +'test'})
test({name: 10})<file_sep>/leetcode/leetCode43.js
/*
两个字符串相乘
123
456
56088
*/
const getNum = (a, b) => {
let arrNum = [0]
for (let i = 0 ; i < a.length; i++) {
let curA = a[a.length - i - 1]
for (let j = 0; j < b.length; j++) {
let curB = b[b.length - j - 1]
let val = curA * curB
let pos = arrNum[i + j] ? arrNum[i + j] + val : val
arrNum[i + j] = pos % 10
if (val >= 10) {
arrNum[i + j + 1] = arrNum[i + j + 1] ? arrNum[i + j + 1] + Math.floor(pos / 10) : Math.floor(pos / 10)
}
}
}
console.log(arrNum.reverse())
}
getNum('123', '6')
getNum('123', '50')
getNum('123', '456')
/**
* 第二种
*/
const getMax = (arr, arr2) => {
let arrNum = Array.from({length: arr.length + arr2.length}, x => 0)
for (let i = arr.length - 1; i >= 0; i--) {
for (let j = arr2.length - 1; j >= 0; j--) {
const sum = arr[i + j + 1] + arr[i] * arr[j]
arrNum[i + j + 1] = sum % 10
arrNum[i + j] += sum / 10 | 0
}
}
console.log(arrNum)
}
getMax('123', '456')<file_sep>/leetcode/leetCode42.js
/*
接雨水
[0,1,0,2,1,0,1,3,2,1,2,1] //6
*/
let arr = [0,1,0,2,1,0,1,3,2,1,2,1]
const rain = arr => {
let left = 0
let right = arr.length - 1
let leftMax = 0
let rightMax = 0
let count = 0
while(left <= right) {
leftMax = Math.max(leftMax, arr[left])
rightMax = Math.max(rightMax, arr[right])
if (arr[left] < arr[right]) {
count += leftMax - arr[left]
left++
} else {
count += rightMax - arr[right]
right--
}
}
return count
}
// console.log(rain(arr))
// console.log(rain([1,0,2]))
function getRain(arr) {
let i = 0
let j = i + 1
let num = 0
while (i <= j && j <= arr.length - 1) {
if (arr[i] == 0 && i !== j) {
i++
j++
} else if (arr[j] >= arr[i] && i !== j) {
let count = i
while (count < j) {
num += arr[i] - arr[count]
count++
}
i = j
j++
} else if (i !== j) {
let flag = false
for (let z = i + 1; z < arr.length; z++) {
if (arr[z] >= arr[i]) {
flag = true
break
}
}
if (!flag) {
i++
} else {
j++
}
} else {
j++
}
}
return num
}
// console.log(getRain(arr))
// console.log(getRain([0,1,0,2,1,0,1,3,2,1,2,1]))<file_sep>/newCode/lc2.js
// 计算逆波表达式
/*
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
let arr = ["2", "1", "+", "3", "*"]
let arr1 = ["4", "13", "5", "/", "+"]
const getNum = arr => {
let newArr = []
let obj = ['-', '+', '*', '/']
let value = 0
for (let i = 0; i < arr.length; i++) {
if (obj.includes(arr[i])) {
if (newArr.length >= 2) {
let a = newArr.pop()
let b = newArr.pop()
let count = 0
if (arr[i] === '-') {
count = b - a
} else if (arr[i] === '+') {
count = parseInt(b) + parseInt(a)
} else if (arr[i] === '*') {
count = b * a
} else {
count = b / a
}
newArr.push(count)
value = count
}
} else {
newArr.push(arr[i])
}
}
return value
}
console.log(getNum(arr))
console.log(getNum(arr1))<file_sep>/leetcode/leetCode02.js
function createNode() {
this.next = null
this.size = 0
}
function LinkNode(val) {
this.val = val
this.next = null
}
createNode.prototype.getSize = function(n) {
let v = this.next
for (let i = 0; i <= this.size; i++) {
if (n == i) {
return v
}
v = v.next
}
}
createNode.prototype.add = function(val) {
if (this.size == 0 ) {
this.next = new LinkNode(val)
} else {
let v = this.getSize(this.size - 1)
v.next = new LinkNode(val)
}
this.size ++
return this
}
var ss = new createNode()
let s1 = ss.add(3).add(4).add(2)
var a = new createNode()
let s2 = a.add(5).add(6).add(4)
console.log(s1.next, s2.next)
const fn = (a1, a2) => {
let sum
let s1 = 0
let v = 0
var zz = new createNode()
while(a1 || a2) {
a1.val = a1.val ? a1.val : 0
a2.val = a2.val ? a2.val : 0
sum = a1.val + a2.val + s1
if (sum >= 10) {
sum = sum % 10
s1 = 1
} else {
s1 = 0
}
zz.add(sum)
a1 = a1.next ? a1.next : null
a2 = a2.next ? a2.next : null
}
return zz
}
console.log(fn(s1.next, s2.next))<file_sep>/leetcode/leetCode1277.js
/*
统计正方形的个数
正方形边长为
*/
let arr1 = [
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
let arr2 = [
[1,0,1],
[1,1,0],
[1,1,0]
]
const getArr = arr => {
let len1 = arr.length
let len2 = arr[0].length
let min = Math.min(len1, len2)
let newArr = Array.from({length: len1 + 1}, x => 0)
for (let i = 0; i < len1; i++) {
newArr[i] = Array.from({length: len2 + 1}, x => 0)
}
for (let i = 0; i <= len1; i++) {
for (let j = 0; j <= len2; j++) {
let num = 0
if (arr[i][j]) {
num += 1
let a = i + 1
let b = j + 1
while(a <= min && b <= min) {
if (arr[a][j] && arr[i][b] && arr[a][b]) {
num += 1
a++
b++
} else {
break
}
}
}
newArr[i][j] = num
}
}
console.log(newArr)
}
getArr(arr1)<file_sep>/my/mySql.md
## 1、download
> https://dev.mysql.com/downloads/file/?id=496745<file_sep>/leetcode/dom.js
/**
* 插入dom元素
*/
const fn = () => {
console.log('hello')
let dom = document.getElementById('myDiv')
let div = document.createElement('DIV')
let test = document.createTextNode('hello world')
let attr = document.createAttribute('style')
attr.value = "color: red; height: 100px; width: 100px; border: 1px solid red"
div.setAttributeNode(attr)
div.appendChild(test)
// div.setAttribute('style', '')
let inP = document.createElement('select')
inP.setAttribute('selectedIndex', 1)
inP.setAttribute('id', 'select')
inP.style.width = '100px'
let content = [
{ name: 'test1', code: '1' },
{ name: 'test2', code: '2' },
{ name: 'test3', code: '3' },
]
content.forEach(ele => {
let doms = document.createElement('option')
doms.setAttribute('label', ele.name)
doms.setAttribute('value', ele.code)
inP.appendChild(doms)
if (ele.code === '2') {
doms.setAttribute('selected', 'selected')
}
})
div.appendChild(inP)
//
let btn = document.createElement('button')
btn.innerText = '点我获取当前选中的值'
btn.setAttribute('title', 'button')
btn.addEventListener('click', function(e) {
let doms = document.getElementById('select')
console.log(doms.value)
})
let span = document.createElement('SPAN')
span.innerText = 'span'
div.appendChild(btn)
div.appendChild(span)
dom.appendChild(div)
let d1 = document.createElement('div')
let a = document.createAttribute('style')
a.value = 'color: red; height: 100px; width: 100px; border: 1px solid red'
d1.setAttributeNode(a)
const list = [
'li',
'wang',
'hello'
]
let u = document.createElement('ul')
list.forEach(ele => {
let li = document.createElement('li')
li.innerText = ele
u.appendChild(li)
})
d1.appendChild(u)
dom.appendChild(d1)
}
window.fn = fn<file_sep>/Encapsulation/study_webpack/plugins/index.js
class BasicPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
console.log(this.options);
// compiler.plugin('emit', function(compilation, callback) {
// // console.log(compilation.chunks);
// console.log(compilation.assets[0]);
// callback();
// })
// 监听文件变化
// compiler.plugin('watch-run', (watching, callback) => {
// // 获取发生变化的文件列表
// const changedFiles = watching.compiler.watchFileSystem.watcher.mtimes;
// // changedFiles 格式为键值对,键为发生变化的文件路径。
// if (changedFiles[filePath] !== undefined) {
// // filePath 对应的文件发生了变化
// }
// callback();
// });
}
}
module.exports = BasicPlugin;<file_sep>/Encapsulation/webpack_new/dist/app.bundle.js
webpackJsonp([0],[
/* 0 */,
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
const a = __webpack_require__(0)
console.log(a, 'app')
console.log('hello world')
/***/ })
],[1]);<file_sep>/node/thirdApi.js
let http = require('http');
// let util = require("util");
http.get('https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code',
(res)=>{
let data = "";
res.on("data",(chunk)=>{
data += chunk;
});
res.on("end",()=>{
let result = JSON.parse(data);
console.log(result)
// console.log("result:"+util.inspect(result)); //调试打印信息 输出的信息: result:{result:-11,data:'',msg:'没有登录'}
})
res.on("error",(e)=>{
console.log(`错误:${e.message}`)
})
})<file_sep>/leetcode/leetCode64.js
/*
最小路径之和
*/
let arr = [
[1,3,1],
[4,5,1],
[3,6,1]
]
const getMin = arr => {
let len1 = arr.length
let len2 = arr[0].length
let newArr = Array.from({length: len1}, x => 0)
for (let i = 0; i < len1; i++) {
newArr[i] = Array.from({length: len2}, x => 0)
newArr[i][0] = arr[i][0]
if (i > 0) {
newArr[i][0] = newArr[i][0] + newArr[i - 1][0]
}
}
for (let i = 0; i < len2; i++) {
newArr[0][i] = arr[0][i]
if (i > 0) {
newArr[0][i] = newArr[0][i] + newArr[0][i - 1]
}
}
for (let i = 1; i < len1; i++) {
for (let j = 1; j < len2; j++) {
newArr[i][j] = Math.min(arr[i][j] + newArr[i - 1][j], arr[i][j] + newArr[i][j - 1])
}
}
return newArr[len1 - 1][len2 - 1]
}
console.log(getMin(arr))<file_sep>/jsStudy/vueStudy.js
let w = {
target: function(newVal, val) {
console.log(newVal, val)
}
}
let uid = 0
function defineReactive(data, key, value) {
let dep = new Dep()
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get: function() {
dep.depend()
return value
},
set: function(val) {
if (val === value) {
return
}
dep.notify(value, val)
value = val
}
})
}
class Dep {
static target() {
console.log(arguments)
}
constructor() {
this.id = ++uid
this.subArr = []
}
addSub(value) {
this.subArr.push(value)
}
depend(value) {
if (Dep.target) {
this.addSub(Dep.target)
}
}
notify() {
const subs = this.subArr.slice()
for (let i = 0; i < subs.length; i++) {
subs[i](arguments)
}
}
}
let obj = {
name: 'test',
params: {
age: 10,
}
}
defineReactive(obj, 'name', obj.name)
console.log(obj.name)
obj.name = 'hello'<file_sep>/leetcode/leetCode07.js
/*
整数反转
*/
/**
*
* @param {number} num
*/
function reverse(num) {
let flag = 1
if (num < 0) {
flag = -1
}
let arr = Math.abs(num).toString().split('').reverse()
arr.map(e => {
if (e != 0) {
return e
}
})
return arr.join('') * flag
}
/**
*
* @param {number} num
*/
const getNum = (num) => {
let val = ''
while(num > 0) {
val = val + (num % 10 == 0 ? val ? 0 : '' : num % 10)
num = Math.floor(num / 10)
}
return val
}<file_sep>/gt/reg.js
let str = new Date().toLocaleDateString()
let reg = /(?<year>\d{4}).(?<month>\d{2}).(?<day>\d{2})/g
str.replace(reg, function() {
return RegExp.$1 + 'nian' + RegExp.$2 + 'yue' + RegExp.$3 + 'ri'
}) // "2020nian10yue22ri"
function dateFormat(timestamp, format) {
if (!format) {
format = "YYYY-MM-dd hh:mm:ss";
}
timestamp = parseInt(timestamp);
let timer = new Date(timestamp)
var date = {
'Y': timer.getFullYear(),
'M': timer.getMonth() + 1,
'd': timer.getDate(),
'h': timer.getHours(),
'm': timer.getMinutes(),
's': timer.getSeconds()
}
let newString = format
format.replace(/(Y|M|d|h|m|s)+/g, function(...index) {
newString = newString.replace(index[0], date[index[1]])
})
return newString;
}
console.log(dateFormat(new Date().getTime()))<file_sep>/leetcode/sort.js
/*
十大排序算法
*/
let arr = [1, 10, 2, 3, 9, 7, 8, 4, 5, 6]
// 1、选择排序
/*
找到数组中最小的那个元素
将它和数组的第一个元素交换位置(如果第一个元素就是最小元素那么它就和自己交换)。其次,在剩下的元素中找到最小的元素,将它与数组的第二个元素交换位置
时间复杂度o(n^2)
*/
function selectSort(arr) {
if (arr.length < 2) {
return arr
}
for (let i = 0; i < arr.length; i++) {
let min = i
for (let j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j
}
}
;[arr[min], arr[i]] = [arr[i], arr[min]]
}
return arr
}
// console.log(selectSort(arr))
// 2、插入排序
/*
当我们给无序数组做排序的时候,为了要插入元素,我们需要腾出空间,将其余所有元素在插入之前都向右移动一位,这种算法我们称之为插入排序。
时间复杂度o(n^2)
*/
function insertSort(arr) {
if (arr.length < 2) {
return arr
}
for (let i = 1; i < arr.length; i++) {
let tem = arr[i]
let k = i - 1
while (k >= 0 && arr[i] < arr[k]) {
k--
}
for (let j = i; j > k + 1; j--) {
arr[j] = arr[j - 1]
}
arr[k + 1] = tem
}
return arr
}
// console.log(insertSort(arr))
// 3、冒泡排序
/*
把第一个元素与第二个元素比较,如果第一个比第二个大,则交换他们的位置。接着继续比较第二个与第三个元素,如果第二个比第三个大,则交换他们的位置….
我们对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对,这样一趟比较交换下来之后,排在最右的元素就会是最大的数。
时间复杂度o(n^2)
*/
function bubbleSort(arr) {
if (arr.length < 2) {
return arr
}
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
}
}
return arr
}
// console.log(bubbleSort(arr))
// 4、希尔排序
/*
插入排序的一种改良,n = arr.length / 2
时间复杂度O(nlog(n))
*/
function shellSort(arr) {
if (arr.length < 2) {
return arr
}
let n = Math.floor(arr.length / 2)
while(n > 0) {
for (let i = 0; i < arr.length - n; i++) {
if (arr[i] > arr[i + n]) {
;[arr[i], arr[i + n]] = [arr[i + n], arr[i]]
}
}
n = Math.floor(n / 2)
}
return arr
}
// console.log(shellSort(arr))
// 5、归并排序
/*
将一个大的无序数组有序,我们可以把大的数组分成两个,然后对这两个数组分别进行排序,
之后在把这两个数组合并成一个有序的数组。由于两个小的数组都是有序的,所以在合并的时候是很快的。
通过递归的方式将大的数组一直分割,直到数组的大小为 1,此时只有一个元素,那么该数组就是有序的了,
之后再把两个数组大小为1的合并成一个大小为2的,再把两个大小为2的合并成4的 ….. 直到全部小的数组合并起来。
*/
function mergeSort(arr) {
if (arr.length < 2) {
return arr
}
let n = Math.floor(arr.length / 2)
let left = mergeSort(arr.slice(0, n))
let right = mergeSort(arr.slice(n))
return mergeArr(left, right)
}
const mergeArr = (left, right) => {
let newArr = []
while(left.length && right.length) {
if (left[0] > right[0]) {
newArr.push(right.shift())
} else {
newArr.push(left.shift())
}
}
while (left.length) {
newArr.push(left.shift())
}
while (right.length) {
newArr.push(right.shift())
}
return newArr
}
// console.log(mergeSort(arr))
// 6、快速排序
/*
找中间元素,大于中间的放右边,小于的放左边
时间复杂度(nlog(n)
*/
function quickSort(arr) {
if (arr.length < 2) {
return arr
}
let mid = Math.floor(arr.length / 2)
let cur = arr[mid]
let left = []
let right = []
for (let i = 0; i < arr.length; i++) {
if (arr[i] < cur) {
left.push(arr[i])
}
if (arr[i] > cur) {
right.push(arr[i])
}
}
return quickSort(left).concat(cur, ...quickSort(right))
}
// console.log(quickSort(arr))
// 7、堆排序
/*
堆的特点就是堆顶的元素是一个最值,大顶堆的堆顶是最大值,小顶堆则是最小值。
堆排序就是把堆顶的元素与最后一个元素交换,
交换之后破坏了堆的特性,我们再把堆中剩余的元素再次构成一个大顶堆,然后再把堆顶元素与最后第二个元素交换….如此往复下去,等到剩余的元素只有一个的时候,此时的数组就是有序的了。
时间复杂度nlog(n)
*/
function heapSort(arr) {
let n = Math.floor(arr.length / 2)
for (let i = n; i >= 0; i--) {
heap_sort(arr, i , arr.length - 1)
}
for (let j = arr.length - 1; j > 1; j--) {
exchage(arr, 0, j)
heap_sort(arr, 0, j - 1)
}
return arr
}
function exchage(arr, i, j) {
;[arr[i], arr[j]] = [arr[j], arr[i]]
}
const heap_sort = function (arr, start, end) {
let left = start * 2 + 1
let right = start * 2 + 2
let cur = start
if (left < end && arr[cur] < arr[left]) {
cur = left
}
if (right < end && arr[cur] < arr[right]) {
cur = right
}
if (start != cur) {
exchage(arr, start, cur)
heap_sort(arr, cur, end)
}
}
// console.log(heapSort(arr))
// 8、计数排序
/*
计数排序是一种适合于最大值和最小值的差值不是不是很大的排序。
基本思想:就是把数组元素作为数组的下标,然后用一个临时数组统计该元素出现的次数
时间复杂度 n + k(k表示需要排序的数组下标)
*/
function countingSort(arr) {
let max = arr[0]
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]
}
}
let maxArr = Array.from({length: max + 1}, x => 0)
for (let i = 0; i < arr.length; i++) {
maxArr[arr[i]] ++
}
let newArr = []
for (let j = 0; j < maxArr.length; j ++) {
while(maxArr[j] > 0) {
newArr.push(j)
maxArr[j]--
}
}
return newArr
}
// console.log(countingSort(arr))
// 9、桶排序
/*
桶排序就是把最大值和最小值之间的数进行瓜分
10 个区间,10个区间对应10个桶,我们把各元素放到对应区间的桶中去,再对每个桶中的数进行排序,可以采用归并排序,也可以采用快速排序之类的。
*/
function bucketSort(arr) {
let n = Math.floor(arr.length / 2)
let k = 3
let newArr = Array.from({length: n}, x => [])
for (let i = 0; i < arr.length; i++) {
let zz = Math.floor(arr[i] / k)
newArr[zz].push(arr[i])
}
for (let i = 0; i < newArr.length; i++) {
qSort(newArr[i])
}
return [].concat(...newArr)
}
const qSort = (arr) => {
if (arr.length) {
for (let i = 1; i < arr.length; i++) {
let cur = arr[i]
let k = i - 1
while(k >= 0 && arr[k] > cur) {
arr[k + 1] = arr[k]
k --
}
arr[k + 1] = cur
}
}
}
// console.log(bucketSort(arr))
// 10、基数排序(桶排序的翻版)
/* 基数排序的排序思路是这样的:先以个位数的大小来对数据进行排序,接着以十位数的大小来多数进行排序,接着以百位数的大小……
时间复杂度kn
*/
function radixSort(arr) {
let maxArr = Array.from({length: 10}, x => [])
let max = arr[0]
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i]
}
}
let num = 10
for (;num <= max * 10; num *= 10) {
for (let i = 0; i < arr.length; i++) {
let curNum
if (arr[i] >= num) {
curNum = Math.floor(arr[i] % num) / (num / 10)
} else {
curNum = Math.floor(arr[i] / (num / 10))
}
maxArr[curNum].push(arr[i])
}
arr = [].concat(...maxArr)
maxArr = Array.from({length: 10}, x => [])
}
return arr
}
console.log(radixSort([10, 1, 2, 22, 50, 100, 120, 1000, 200]))
// console.log(radixSort(arr))
<file_sep>/jsStudy/ajax.js
import qs from 'qs'
const request = (options = {
url: '',
methods: 'GET',
success: function() {},
error: function() {},
data: {}
}) => {
let xhr = new XMLHttpRequest()
xhr.open(options.methods, options.methods === 'POST' ? options.url : options.url + '?' + qs.stringify(data), true)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
options.success(xhr.response)
} else {
options.error()
}
}
}
xhr.send(options.methods === 'POST' ? data : null)
}
request({
url: '',
methods: 'GET',
success: function(e) {
console.log(e)
},
error: function(e) {
console.log(e)
}
})<file_sep>/leetcode/leetCode15.js
/*
三数之和
[-1, 0, 1, 2, -1, -4]
[-1, 0, 1]
[-1, -1, 2]
*/
let arr = [-1, 0, 1, 2, -1, -4]
function getNum(arr) {
let map = new Map()
let arrs = []
let obj = {}
arr.sort((a, b) => a - b)
for (let i = 0; i < arr.length; i++) {
let start = i + 1
let end = arr.length - 1
while(start < end) {
if (arr[start] + arr[i] + arr[end] > 0) {
end--
} else if (arr[start] + arr[i] + arr[end] < 0) {
start++
} else {
let newArr = [arr[i], arr[start], arr[end]]
if (!obj[newArr]) {
obj[newArr] = 1
}
start++
end--
while(start < end && arr[start] === arr[start + 1]) {
start++
}
while(start < end && arr[end] === arr[end -1]) {
end--
}
}
}
}
return Object.keys(obj)
}
console.log(getNum(arr))<file_sep>/leetcode/leetCode138.js
// 复制带有随机指针的链表
function createNode() {
this.next = null
this.size = 0
}
function LinkNode(val) {
this.val = val
this.next = null
}
createNode.prototype.getSize = function(n) {
let v = this.next
for (let i = 0; i <= this.size; i++) {
if (n == i) {
return v
}
v = v.next
}
}
createNode.prototype.add = function(val) {
if (this.size == 0 ) {
this.next = new LinkNode(val)
} else {
let v = this.getSize(this.size - 1)
v.next = new LinkNode(val)
}
this.size ++
return this
}
createNode.prototype.to = function() {
let arr = []
let v = this.next
while(v) {
arr.push(v.val)
v = v.next
}
return arr.join('->')
}<file_sep>/Encapsulation/study_webpack/webpack.config.js
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');
const UglifyJSPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const BasicPlugin = require('./plugins/index');
const LogWebpackPlugin = require('./plugins/LogWebpackPlugin');
module.exports = {
// JavaScript 执行入口文件
entry: './main.js',
output: {
// 把所有依赖的模块合并输出到一个 bundle.js 文件
filename: 'bundle.js',
// 输出文件都放到 dist 目录下
path: path.resolve(__dirname, './dist'),
},
resolve: {
extensions: ['.js', '.json']
},
watch: true,
watchOptions: {
// 不监听的文件或文件夹,支持正则匹配
// 默认为空
ignored: /node_modules/,
// 监听到变化发生后会等300ms再去执行动作,防止文件更新太快导致重新编译频率太高
// 默认为 300ms
aggregateTimeout: 300,
// 判断文件是否发生变化是通过不停的去询问系统指定文件有没有变化实现的
// 默认每秒问 1000 次
poll: 1000
},
module: {
rules: [
{
test: /.js$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: ['babel-loader']
},
{
test: /.js$/,
include: path.resolve(__dirname, './loader/test.js'),
use: [{
loader: path.resolve(__dirname, './loader/index.js'),
options: {
type: 1,
value: 'tomorrow'
}
}]
},
// {
// // 用正则去匹配要用该 loader 转换的 CSS 文件
// test: /\.css$/,
// use: ExtractTextPlugin.extract({
// // 转换 .css 文件需要使用的 Loader
// use: ['css-loader'],
// }),
// }
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
}
]
},
// plugins: [
// new ExtractTextPlugin({
// // 从 .js 文件中提取出来的 .css 文件的名称
// filename: `[name]_[contenthash:8].css`,
// }),
// ]
plugins: [
new HotModuleReplacementPlugin(),
// 压缩输出的 JS 代码
new UglifyJSPlugin({
compress: {
// 在UglifyJs删除没有用到的代码时不输出警告
warnings: false,
// 删除所有的 `console` 语句,可以兼容ie浏览器
// drop_console: true,
// 内嵌定义了但是只用到一次的变量
collapse_vars: true,
// 提取出出现多次但是没有定义成变量去引用的静态值
reduce_vars: true,
},
output: {
// 最紧凑的输出
beautify: false,
// 删除所有的注释
comments: false,
}
}),
new BasicPlugin({
name: 'tomorrow',
target: 'do something'
}),
new LogWebpackPlugin(function() {
// Webpack 模块完成转换成功
console.log('emit 事件发生啦,所有模块的转换和代码块对应的文件已经生成好~')
} , function() {
// Webpack 构建成功,并且文件输出了后会执行到这里,在这里可以做发布文件操作
console.log('done 事件发生啦,成功构建完成~')
})
],
devServer: {
host: '0.0.0.0',
port: 1000,
open: false
},
devtool: 'source-map'
};<file_sep>/leetcode/leetCode53.js
/*
最长的连续子序列和
*/
let arr = [-2,1,-3,4,-1,2,1,-5,4]
const getNum = arr => {
let num = 0
let max = 0
for (let i = 0; i < arr.length; i++) {
if (max + arr[i] > 0) {
max = max + arr[i]
num = Math.max(num, max)
} else {
max = 0
}
}
return num
}
console.log(getNum(arr))<file_sep>/leetcode/leetCode258.js
/*
各位相加,相加完之后,数值为个位数则返回
*/
/**
*
* @param {number} num
*/
const getNum = (num) => {
let numStr = num.toString()
if (numStr.length > 1) {
str = numStr.split('').reduce((a, b) => parseInt(a) + parseInt(b))
numStr = str.toString().length > 1 ? getNum(parseInt(str)) : str
}
return numStr
}<file_sep>/demo/study.md
# Study
## BFC概念(块级格式化上下文)
### 触发BFC
+ body根元素
+ 浮动元素
+ 绝对定位元素: position(absolute, fixed)
+ display 为inline-block、table-cells、flex
+ overflow除了visible以外的值(hidden, auto, scroll)
### BFC特性及应用
+ 同一个 BFC 下外边距会发生折叠
+ BFC 可以包含浮动的元素(清除浮动)
+ BFC 可以阻止元素被浮动元素覆盖<file_sep>/leetcode/leetCode206.js
/*
1,2,3,4,5
5,4,3,2,1
*/
function createNode() {
this.next = null
this.size = 0
}
function LinkNode(val) {
this.val = val
this.next = null
}
createNode.prototype.getSize = function(n) {
let v = this.next
for (let i = 0; i <= this.size; i++) {
if (n == i) {
return v
}
v = v.next
}
}
createNode.prototype.add = function(val) {
if (this.size == 0 ) {
this.next = new LinkNode(val)
} else {
let v = this.getSize(this.size - 1)
v.next = new LinkNode(val)
}
this.size ++
return this
}
createNode.prototype.to = function() {
let arr = []
let v = this.next
while(v) {
arr.push(v.val)
v = v.next
}
return arr.join('->')
}
var ss = new createNode()
ss.add(1).add(2).add(3).add(4).add(5)
console.log(ss.to())
function rotate(head) {
let a1 = head
let b = head
while(a1 && a1.next) {
let end = a1.next
a1.next = a1.next.next
end.next = head
head = end
}
return head
}
console.log(rotate(ss.next))
// 迭代法
// 1,2,3,4,5
// function rotate(head) {
// let a1 = head
// while(a1 && a1.next) {
// let end = a1.next
// a1.next = a1.next.next
// end.next = head
// head = end
// }
// return head
// }
// console.log(rotate(ss.next))
// 递归法
// function fn(head) {
// if (head && !head.next) return head
// let newCode = fn(head.next)
// head.next.next = head
// head.next = null
// return newCode
// }
// console.log(fn(ss.next).to())<file_sep>/leetcode/leetCode209.js
/*
长度最小的子数组
nums = [2,3,1,2,4,3];s=7 return 2
双指针
*/
let arr = [2,3,1,2,4,3,7]
const getMin = (arr, count) => {
let num = 0
for (let j = 0, i = j + 1; i <= arr.length; i++) {
let curArr = arr.slice(j, i)
if (curArr.reduce((x, y) => x + y) === count) {
num = num === 0 ? curArr.length : Math.min(curArr.length, num)
}
if (i === arr.length) {
j++
i = j
}
}
return num
}
console.log(getMin(arr, 7))
const getArr = (arr, count) => {
let num = Infinity
let head = 0
let end = head + 1
let curVal = 0
while(end < arr.length) {
curVal += arr[end]
if (curVal > count) {
curVal -=arr[head]
head ++
} else if (curVal < count) {
end++
} else {
num = Math.min(end - head + 1, num)
end++
head = end
curVal = 0
}
}
return num
}
console.log(getMin(arr, 7))<file_sep>/Encapsulation/lifeTime/node.js
const express = require('express')
let app = express();
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
app.get('/getInfo', function(request, response){
let data = {
'username':'前端严选',
'age':'2'
};
response.json(data);
});
app.listen(3000, function(){
console.log("服务器启动");
});<file_sep>/leetcode/leetCode347.js
/*
前k个高频元素
*/
const getNum = (arr, k) => {
let obj = {}
for (let i = 0; i < arr.length; i++) {
let n = arr[i]
if (obj[n]) {
obj[n] += 1
} else {
obj[n] = 1
}
}
let bArr = Object.keys(obj)
bArr.sort((x, y) => obj[x] - obj[y])
return bArr[bArr.length - k]
}
<file_sep>/demo/api.js
(function(){
let objes = {}
let jQuery = function(dom) {
let domEle = document.querySelectorAll(dom)
return new jQuery.fn.init(domEle[0])
}
jQuery.fn = jQuery.prototype = {
construct: jQuery,
init: function (dom) {
this.dom = dom
console.log(this)
return this
},
html: function() {
this.dom.style.color = 'red'
return this
}
}
jQuery.sayName = function() {
console.log('wang')
}
jQuery.fn.extend = jQuery.extend = function (obj) {
for (let i in obj) {
this[i] = obj[i]
}
return this
}
jQuery.fn.extend({
each: function() {
return this
}
})
jQuery.extend({
ajax: function() {
console.log(this)
}
})
jQuery.fn.init.prototype = jQuery.fn
window.$ = jQuery
})()<file_sep>/leetcode/leetCode118.js
/*
杨辉三角
let arr = [
[1],
[1,1],
[1,2,1],
[1,3,3,1]
]
*/
/**
* 返回杨辉三角形
* @param {number} num
*/
const getArr = num => {
let newArr = Array.from({length: num}, x => [])
for (let i = 0; i < num; i++) {
newArr[i] = Array.from({length: i + 1}, x => 1)
}
for (let i = 2; i < num; i++) {
for (let j = 1; j < newArr[i].length - 1; j++) {
newArr[i][j] = newArr[i - 1][j - 1] + newArr[i - 1][j]
}
}
console.log(newArr)
}
getArr(5)
<file_sep>/Encapsulation/proto/proto.js
/**
* 原型链与原型的
*/
/**
* function 测试
* @param {any} name
*/
function TestFunction(name) {
this.name = name;
}
let fn = new TestFunction('test');
/**
* 打印fn原型
*/
console.log(
fn.__proto__,
fn.__proto__ === TestFunction.prototype, // true
TestFunction.prototype,
TestFunction.prototype.constructor === TestFunction, // true
TestFunction.prototype.__proto__,
TestFunction.prototype.__proto__ === Object.prototype, // true
Object.prototype.__proto__ === null // true
);
/**
* 打印Function相关原型
*/
console.log(
TestFunction.__proto__ === Function.prototype,
Function.prototype.constructor === Function,
Function.__proto__ === Function.prototype
)
/**
* Objcet实例
*/
let obj = new Object({
name: 'wang',
age: 10
})
let obj2 = {
name: 'wang',
age: 10
}
// console.log(obj, obj2)
/**
* 打印实例对象原型属性
*/
console.log(
obj.__proto__ === Object.prototype,
Object.prototype.constructor === Object,
Object.__proto__ === Function.prototype,
Function.prototype.__proto__ === Object.prototype
)
|
28124d5728c7edf0ee9251ae09436d674190f437
|
[
"JavaScript",
"Markdown"
] | 72
|
JavaScript
|
wklTomorrow/basic
|
a7808701bdcc15e252347f1546bedc9a35e30540
|
c901c223195b344aa47374117180c351a4a94162
|
refs/heads/master
|
<repo_name>annarice/model_adequacy_dev<file_sep>/copy_for_sanity.py
import os
import gzip, tarfile
import shutil
from utils import *
l = []
for i in range(1000):
l.append(str(i))
lst = ["Aloe","Phacelia","Lupinus","Hypochaeris","Brassica","Pectis","Crepis","Hordeum"]
lst = ["Pectis"]
d = model_per_genus()
for genus in lst:
model = d.get(genus)
untargz("/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/zipped.tar.gz")
for i in range(50,100):
dest_dir = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/"
if not os.path.exists(dest_dir):
res = os.system("mkdir -p " + dest_dir) # -p allows recusive mkdir in case one of the upper directories doesn't exist
counts_source = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/simCounts.txt"
counts_dest = dest_dir + "counts.txt"
os.system("cp -rf " + counts_source + " " + counts_dest)
dest_genus = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/"
if not os.path.exists(dest_genus):
res = os.system("mkdir -p " + dest_genus)
tree_source = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/tree_1"
tree_dest = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/tree_1"
os.system("cp -rf " + tree_source + " " + tree_dest)
#targz_dir(out_dir, l, "zipped.tar.gz", True)
targz_dir("/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/", l, "zipped.tar.gz", True)<file_sep>/analysis/get_stats.py
import sys
sys.path.append("../")
from defs import *
from utils import *
def calculate_statistics(counts,filename, tree_file, simulated_counts_file = False, tree_file2 = None):
'''
:param counts: list of counts
:param filename: output file to where the stats will be printed
:param tree_file: for parsimony (fitch) and time-parsimony calculations
:param simulated_counts_file: if supplied - stats are calculated on simulations
:param tree_file2: if supplied - stats are calculated on simulations, a different tree file that needs to be corrected (CE bug - semicolon)
:return: list of statistics representing the counts
'''
# variance
v = round(np.var(counts),2)
# range = max - min
r = max(counts) - min(counts)
# enthropy, calculates the probabilities
d = {}
for i in counts:
d[i] = counts.count(i)
prob_lst = [x / len(counts) for x in list(d.values())]
e = sc.entropy(prob_lst)
# unique counts
counts_set = set(counts)
u = len(counts_set)
# parsimony
p = fitch(tree_file,simulated_counts_file)
if tree_file2 is not None:
fix_tree_file2(tree_file2) # add semicolon
tmp_tree_file = tree_file2
else:
tmp_tree_file = tree_file
try:
a = acctran(tmp_tree_file)
except:
a = 0
lst_of_stats = [v, e, r, u, p, a]
round_stats = [round(x,2) for x in lst_of_stats]
with open(filename, "w+") as stats:
stats.write(','.join([str(x) for x in round_stats]))
return (round_stats)
def fitch (tree_file, c = False):
t = Tree(tree_file, format = 1)
score = 0
'''
if c: # if there's a counts file, the analysis is of a simulated dataset
d = {}
with open(c, "r") as counts:
for line in counts:
line = line.strip()
if line.startswith(">"):
key = line[1:]
else:
val = line
d[key] = val
'''
if c:
d = create_counts_hash(c)
for node in t.traverse("postorder"):
if not node.is_leaf(): # internal node
lst = [] # list version
intersect, union = None, None
for child in node.get_children():
if child.is_leaf(): # if the child is a tip - parse number from tip label
if c: # if there is a dictionary --> take the number from it --> the tree is a simulated tree
name = re.search("(.*)\-\d+", child.name)
if name:
num = {int(d.get(name.group(1)))}
else: # the tree is the original tree
tmp = re.search("(\d+)", child.name)
if tmp: # there is a number at the tip, and not X
num = {int(tmp.group(1))}
else: # if the child is an internal node - take number
num = child.name
lst.append(num)
intersect = lst[0] & lst[1]
union = lst[0] | lst[1]
if len(intersect) == 0:
result = union
score += 1
else:
result = intersect
node.name = result
return(score)
def acctran(t):
command = "unset R_HOME; Rscript "
script = "/analysis/phangorn.R "
arg = t
cmd = command + script + arg
res = subprocess.Popen(cmd, shell=True, cwd=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
out, err = res.communicate()
res = float(out[3:].strip())
return(res)<file_sep>/fitch.py
from ete3 import Tree
import regex as re
import argparse
parser = argparse.ArgumentParser(description="Calculates the number of intersections of trait in internal nodes")
parser.add_argument('--tree', '-t', help='Newick tree with traits in the tip label, e.g., mlAncestors.tree',required=True)
args = parser.parse_args()
tree_file = args.tree
t = Tree(tree_file, format = 1)
score = 0
score = fitch(score,t)
def fitch(score,t):
for node in t.traverse("postorder"):
node.add_feature("state",0)
if not node.is_leaf(): # internal node
lst = []
intersect, union = None, None
for child in node.get_children():
if child.is_leaf(): # if the child is a tip - parse number from tip label
tmp = re.search("(\d+)",child.name)
num = {int(tmp.group(1))}
#child.name = num
child.state = num
else: # if the child is an internal node - take number
num = child.state
lst.append(num)
intersect = lst[0] & lst[1]
union = lst[0] | lst[1]
if len(intersect) == 0:
result = union
score += 1
else:
result = intersect
node.state = result
print(str(score))
return(t)
def distance_of_change(tmp_tree,tmp_node):
if tmp_node.is_root():
return(0)
else:
return(tmp_tree.get_distance(tmp_node.name) + (tmp_node.dist*0.5))
def fitch_original(score,t):
for node in t.traverse("postorder"):
if not node.is_leaf(): # internal node
lst = [] # list version
intersect, union = None, None
for child in node.get_children():
#print(child.name)
if child.is_leaf(): # if the child is a tip - parse number from tip label
tmp = re.search("(\d+)",child.name)
num = {int(tmp.group(1))}
else: # if the child is an internal node - take number
num = child.name
lst.append(num)
intersect = lst[0] & lst[1]
union = lst[0] | lst[1]
#print ("intersect " + str(intersect))
#print("union " + str(union))
if len(intersect) == 0:
result = union
score += 1
else:
result = intersect
node.name = result
print(node.name)
print(str(score))<file_sep>/sh_wrapper_sanity.py
import os
from utils import *
script = "~/model_adequacy/code/sanity.py"
lang = "python"
models = ["CONST_RATE","CONST_RATE_NO_DUPL","BASE_NUM","BASE_NUM_DUPL"]
lst = ["Aloe","Phacelia","Lupinus","Hypochaeris","Brassica","Pectis","Crepis","Hordeum"]
lst = ["Pectis"]
queue = "itaym"
d = model_per_genus()
for genus in lst:
tested_model = d.get(genus)
tree = "~/model_adequacy/sanity/" + genus + "/tree_1"
wd = "~/model_adequacy/sanity/" + genus + "/" + tested_model + "/adequacy_test/"
for model in models:
for i in range(50,100):
name = genus + "." + model + str(i) + ".Sanity"
cmd = "-c " + wd + " -t " + tree + " -m " + model + " -ns " + str(i) + " -ce /groups/itay_mayrose/itaymay/code/chromEvol/chromEvol_source-current/chromEvol -g " + genus
os.system("python ~/create_sh.py " + "-name " + name + " -l " + lang + " -s " + script + " -q " + queue + " -p \'" + cmd + "\'")<file_sep>/get_likelihoods.py
# nested models should get lower LL
# first look in the sanity folders:
# read the /groups/itay_mayrose/annarice/model_adequacy/sanity/Justicia/CONST_RATE/adequacy_test/0/CONST_RATE/chromEvol.res file
# search for "LogLikelihood" in the file and take the number after it
# if not in the sanity folder then look at:
# result_sum in the case of a non-sanity checks
import argparse
import regex as re
import csv
# args
parser = argparse.ArgumentParser(description="produce sh files for running model adequacy, either in regular or sanity mode")
parser.add_argument('--nsims', '-n', help='Number of simulations',required=False) # in sanity --> 50
parser.add_argument('--genera', '-f', help='Genera file',required=True)
#parser.add_argument('--models_defined', '-md', help='define which models to run',required=False) # in sanity --> CONST_RATE_NO_DUPL,CONST_RATE,CONST_RATE_DEMI_EST,CONST_RATE_DEMI
parser.add_argument('--sanity_flag', '-sf', help='Genera file',required=True)
args = parser.parse_args()
nsims = int(args.nsims)
filename = args.genera
#models_defined = args.models_defined
#models = models_defined.split(",") # returns a list
sanity_flag = int(args.sanity_flag)
nested_const = ["CONST_RATE_NO_DUPL","CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST"]
nested_base = ["BASE_NUM","BASE_NUM_DUPL"]
ALL_MODELS = ["CONST_RATE_NO_DUPL","CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","BASE_NUM","BASE_NUM_DUPL"]
outfile = "/groups/itay_mayrose/annarice/model_adequacy/sanity/LL_test2.csv"
def get_liks(tested_model, i):
d = {"CONST_RATE_NO_DUPL": 0, "CONST_RATE": 0, "CONST_RATE_DEMI": 0, "CONST_RATE_DEMI_EST": 0, "BASE_NUM": 0,"BASE_NUM_DUPL": 0}
for model in ALL_MODELS:
if sanity_flag == 1:
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + tested_model + "/adequacy_test/" + str(i) + "/" + model + "/chromEvol.res"
else:
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + model + "/result_sum"
try:
with open(results_sum, "r") as CE_res:
for line in CE_res:
tmp_line = re.search("LogLikelihood = (.*)", line)
if tmp_line:
LL = float(tmp_line.group(1))
d[model] = LL
except:
pass
if d.get("CONST_RATE") == 0 and d.get("BASE_NUM") == 0: # assuming these two models must have results. If not - don't write to the csv file
return(None)
row = [genus, str(i)]
for m in ALL_MODELS:
row.append(d.get(m))
if (d.get("CONST_RATE_NO_DUPL") > d.get("CONST_RATE") or d.get("CONST_RATE") > d.get(
"CONST_RATE_DEMI") or d.get("CONST_RATE_DEMI") > d.get("CONST_RATE_DEMI_EST") \
or d.get("BASE_NUM") > d.get("BASE_NUM_DUPL")) and d.get("CONST_RATE_NO_DUPL") != 0:
row.append(1)
else:
row.append(0)
return(row)
# MAIN
with open (outfile,"w+") as output:
header = ["Genus","Ind","CONST_RATE_NO_DUPL","CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","BASE_NUM","BASE_NUM_DUPL","LL_flag"]
writer = csv.writer(output)
writer.writerow(header)
with open(filename, "r") as genera:
for genus in genera:
genus = genus.strip()
if sanity_flag == 1: # summary dir
if genus == "Jasminum" or genus == "Fragaria" or genus == "Ourisia":
tested_model = "BASE_NUM"
if genus == "Malus" or genus == "Parnassia" or genus == "Noccaea" or genus == "Justicia":
tested_model = "CONST_RATE"
if genus == "Clarkia" or genus == "Rubia" or genus == "Buxus":
tested_model = "CONST_RATE_DEMI"
for i in range(nsims):
row = get_liks(tested_model,i)
if row != None:
writer.writerow(row)
else: # non-sanity dirs
continue
'''
for i in range(nsims):
d = {"CONST_RATE_NO_DUPL": 0, "CONST_RATE": 0, "CONST_RATE_DEMI": 0, "CONST_RATE_DEMI_EST": 0,"BASE_NUM": 0, "BASE_NUM_DUPL": 0}
for model in ALL_MODELS:
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + tested_model + "/adequacy_test/" + str(i) + "/" + model + "/chromEvol.res"
try:
with open(results_sum, "r") as CE_res:
for line in CE_res:
tmp_line = re.search("LogLikelihood = (.*)", line)
if tmp_line:
LL = float(tmp_line.group(1))
d[model] = LL
except:
pass
if d.get("CONST_RATE") == 0 and d.get("BASE_NUM") == 0: # assuming these two models must have results. If not - don't write to the csv file
continue
row = [genus, str(i)]
for m in ALL_MODELS:
row.append(d.get(m))
if (d.get("CONST_RATE_NO_DUPL") > d.get("CONST_RATE") or d.get("CONST_RATE") > d.get("CONST_RATE_DEMI") or d.get("CONST_RATE_DEMI") > d.get("CONST_RATE_DEMI_EST") \
or d.get("BASE_NUM") > d.get("BASE_NUM_DUPL")) and d.get("CONST_RATE_NO_DUPL") != 0:
row.append(1)
else:
row.append(0)
writer.writerow(row)
'''<file_sep>/various_codes.py
import os
lst = ["Acanthus", "Acer", "Actinidia", "Alisma","Allium", "Aloe", "Aphelandra", "Barleria", "Carlowrightia", "Conophytum", "Echinodorus",
"Elytraria", "Iris", "Justicia", "Mesembryanthemum","Narcissus", "Phyllobolus", "Prunus","Psilocaulon", "Ruellia", "Sagittaria", "Sambucus",
"Solanum", "Strobilanthes", "Tetramerium", "Thunbergia", "Viburnum"]
for genus in lst:
source = "/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/" + genus + "/" + genus + "_Chromevol_prune/chromevol_out/infer/infer_tree_1"
dest = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/"
counts = "/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/" + genus + "/" + genus + "_Chromevol_prune/chromevol_out/" + genus + ".counts_edit"
dest_counts = dest + genus + ".counts_edit"
os.system("cp -rf " + source + " " + dest)
os.system("cp -rf " + counts + " " + dest)
filename = "/groups/itay_mayrose/annarice/model_adequacy/genera/genera_sample"
with open (filename, "r") as genera:
for genus in genera:
genus = genus.strip()
source = "/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/" + genus + "/" + genus + "_Chromevol_prune/chromevol_out/infer/infer_tree_1"
dest = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/"
counts = "/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/" + genus + "/" + genus + "_Chromevol_prune/chromevol_out/" + genus + ".counts_edit"
dest_counts = dest + genus + ".counts_edit"
os.system("cp -rf " + source + " " + dest)
os.system("cp -rf " + counts + " " + dest)
## /groups/itay_mayrose/annarice/model_adequacy/Acer/CONST_RATE/adequacy_test/1 ---> range(10), data, and add tree
import os
import gzip, tarfile
import shutil
l = []
for i in range(1000):
l.append(str(i))
lst = ["Aloe","Lilium","Arctostaphylos","Gossypium","Eulophia","Tillandsia","Polygonatum","Rhododendron","Magnolia",
"Lathyrus","Camellia","Paphiopedilum","Mentzelia","Ornithogalum","Iris","Caragana","Acer","Agrostis","Begonia","Habenaria"]
lst = ["Aloe","Phacelia","Lupinus","Hypochaeris","Crepis","Pectis","Chlorophytum","Achillea"]
lst = ["Aloe"]
d = {"Aloe":"CONST_RATE","Phacelia":"CONST_RATE","Lupinus":"CONST_RATE_NO_DUPL","Hypochaeris":"CONST_RATE_NO_DUPL",
"Crepis":"BASE_NUM","Pectis":"BASE_NUM","Chlorophytum":"BASE_NUM_DUPL","Achillea":"BASE_NUM_DUPL"}
for genus in lst:
model = d.get(genus)
'''
if genus == "Rhododendron" or genus == "Magnolia" or genus == "Lathyrus" or genus == "Camellia" or genus == "Paphiopedilum" or genus == "Mentzelia" or genus == "Ornithogalum":
model = "BASE_NUM"
if genus == "Aloe" or genus == "Lilium" or genus == "Arctostaphylos" or genus == "Gossypium" or genus == "Eulophia" or genus == "Tillandsia" or genus == "Polygonatum":
model = "CONST_RATE"
if genus == "Iris" or genus == "Caragana" or genus == "Acer" or genus == "Agrostis" or genus == "Begonia" or genus == "Habenaria":
model = "CONST_RATE_DEMI"
'''
untargz("/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/zipped.tar.gz")
for i in range(50):
dest_dir = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/"
if not os.path.exists(dest_dir):
res = os.system("mkdir -p " + dest_dir) # -p allows recusive mkdir in case one of the upper directories doesn't exist
counts_source = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/simCounts.txt"
counts_dest = dest_dir + "counts.txt"
os.system("cp -rf " + counts_source + " " + counts_dest)
dest_genus = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/"
if not os.path.exists(dest_genus):
res = os.system("mkdir -p " + dest_genus)
tree_source = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/tree_1"
tree_dest = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/tree_1"
os.system("cp -rf " + tree_source + " " + tree_dest)
#targz_dir(out_dir, l, "zipped.tar.gz", True)
targz_dir("/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/", l, "zipped.tar.gz", True)
######################################################################################################################
###################################### run model adequacy for a list of genera #######################################
######################################################################################################################
for genus in lst:
cmd = "module load python/python-anaconda3.6.5; module load perl/perl-5.28.1; python ~/model_adequacy/code/main.py -c ~/model_adequacy/ -m BASE_NUM,BASE_NUM_DUPL,CONST_RATE,CONST_RATE_DEMI,CONST_RATE_DEMI_EST,CONST_RATE_NO_DUPL -id " + genus + " -nt 1 -ns 100 -ce /bioseq/chromEvol/chromEvol.exe"
os.system(cmd)
######################################################################################################################
############################################## delete file from all dirs #############################################
######################################################################################################################
for genus in lst:
filename = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/runtime_max_chr_sim_num.csv"
os.system("rm " + filename)
######################################################################################################################
################################### summarize to a single file all runtime results ###################################
######################################################################################################################
import pandas as pd
def get_counts(filename):
'''
reads the .counts_edit file and extracts the counts
:param filename: supplied by the user
:return: list of counts
'''
with open(filename, "r") as tmp_counts_file:
counts = []
for line in tmp_counts_file:
line = line.strip()
if line.startswith('>'):
continue
else:
if line=="x":
continue
counts.append(int(line))
return (counts)
out_file = "/groups/itay_mayrose/annarice/model_adequacy/genera_runtime_fixed.csv"
outfile = open(out_file, "a")
outfile.write("Model,Max,nsims,time,Variance,Entropy,Range,Unique_counts" + "\n")
for genus in lst:
direc = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/"
data = pd.read_csv(direc + "result_sum", sep="\t", header=None)
tmp = data.loc[data[3] == 0, 0].values[0]
counts = get_counts(direc + genus + ".counts_edit")
tips = len(counts)
filename = direc + "runtime_iterated_fixed.csv"
with open(filename, "r") as runtime:
all_lines = runtime.read()
outfile.write(genus + "," + tmp + "," + str(tips) + "\n")
outfile.write(all_lines)
outfile.close()
for genus in lst:
cmd = "grep -R --include='simEvents.txt' 'Total number of transitions to max chromosome: [^0]' " + output_dir
tmp = os.system(cmd)
f = open(working_dir + "/increasing_max_chr.txt", "w")
f.write("Iteration number " + str(mult) + ", Max number is currently " + str(max_for_sim))
f.close()
if tmp != 0: # did not hit upper bound
break # no need to keep increasing the max number
#grep -R --include="simEvents.txt" "Total number of transitions to max chromosome:" /groups/itay_mayrose/annarice/model_adequacy/Actinidia/BASE_NUM/adequacy_test/
# summarize
######################################################################################################################
################################### summarize results of fixed chr number ###################################
######################################################################################################################
lst = ["Acer", "Aloe", "Echinodorus", "Justicia", "Prunus","Ruellia", "Sagittaria", "Sambucus", "Strobilanthes"]
for genus in lst:
cmd = "module load python/python-anaconda3.6.5; module load perl/perl-5.28.1; python ~/model_adequacy/code/main.py -c ~/model_adequacy/ -m BASE_NUM,BASE_NUM_DUPL,CONST_RATE,CONST_RATE_DEMI,CONST_RATE_DEMI_EST,CONST_RATE_NO_DUPL -id " + genus + " -nt 1 -ns 100 -ce /bioseq/chromEvol/chromEvol.exe"
os.system(cmd)
# perform KS test on each pair
from scipy import stats
for genus in lst:
two = "/groups/itay_mayrose/annarice/model_adequacy/"+genus+"/BASE_NUM/adequacy_test/dist_200"
eight = "/groups/itay_mayrose/annarice/model_adequacy/"+genus+"/BASE_NUM/adequacy_test/dist_800"
with open(two,"r") as f1:
f1d1 = eval(f1.readline())
f1d2 = eval(f1.readline())
f1d3 = eval(f1.readline())
f1d4 = eval(f1.readline())
with open(eight, "r") as f2:
f2d1 = eval(f2.readline())
f2d2 = eval(f2.readline())
f2d3 = eval(f2.readline())
f2d4 = eval(f2.readline())
res1 = stats.ks_2samp(f1d1, f2d1)
res2 = stats.ks_2samp(f1d2, f2d2)
res3 = stats.ks_2samp(f1d3, f2d3)
res4 = stats.ks_2samp(f1d4, f2d4)
if res1[1]<0.05:
print(genus + " - statistic number 1 is different")
else:
print(genus + " - statistic number 1 is equal")
if res2[1]<0.05:
print(genus + " - statistic number 2 is different")
else:
print(genus + " - statistic number 2 is equal")
if res3[1]<0.05:
print(genus + " - statistic number 3 is different")
else:
print(genus + " - statistic number 3 is equal")
if res4[1]<0.05:
print(genus + " - statistic number 4 is different")
else:
print(genus + " - statistic number 4 is equal")
######################################################################################################################
################################################## summarize sanity checks ###########################################
######################################################################################################################
import numpy as np
import scipy.stats as sc
def get_counts(filename):
'''
reads the .counts_edit file and extracts the counts
:param filename: supplied by the user
:return: list of counts
'''
with open(filename, "r") as tmp_counts_file:
counts = []
for line in tmp_counts_file:
line = line.strip()
if line.startswith('>'):
continue
else:
if line=="x":
continue
counts.append(int(line))
return (counts)
def calculate_statistics(counts):
'''
given list of counts produces statistics: variance,min,max,entropy
########## ADD MP OF NUMBER OF TRANSITIONS
:param counts: list of chromosome numbers
:return: list of statistics representing the counts
'''
# variance
v = np.var(counts)
# range = max - min
r = max(counts) - min(counts)
# enthropy, calculates the probabilities
d = {}
for i in counts:
d[i] = counts.count(i)
prob_lst = [x / len(counts) for x in list(d.values())]
e = sc.entropy(prob_lst)
# unique counts
counts_set = set(counts)
u = len(counts_set)
return ([v, e, r, u])
def test_adequacy(sim_stats, stats):
'''
go over each statistic in the list and see if is adequate
'''
adequacy_lst = []
stat_lst = []
for i in range(len(stats)):
sim_stat_dist = [x[i] for x in sim_stats] # simulated ith distribution, x the item in each simulated list
print ("**********************************************")
print(sim_stat_dist)
print ("**********************************************")
stat_star_upper = np.percentile(sim_stat_dist, 97.5) # calculate the upper limit
stat_star_lower = np.percentile(sim_stat_dist, 2.5) # calculate the lower limit
model = 0
if stats[i] <= stat_star_upper and stats[i] >= stat_star_lower:
model = 1
adequacy_lst.append(model)
stat_lst.append(stats[i])
return (adequacy_lst,stat_lst)
lst = ["Acer", "Aloe", "Echinodorus", "Justicia", "Prunus","Ruellia", "Sagittaria", "Sambucus", "Strobilanthes"]
models = ["CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST", "CONST_RATE_NO_DUPL"]
out_file = "/groups/itay_mayrose/annarice/model_adequacy/sanity.csv"
outfile = open(out_file, "a")
outfile.write("Simulated_under,model2,nsim,genus,variance,entropy,range,unique_counts" + "\n")
for genus in lst:
for model1 in models:
ma_filename = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/" + model1 + "/adequacy_test/" + model1 + "_MA.res"
for i in range(10):
for model2 in models:
sanity_results = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/" + model1 + "/adequacy_test/" + str(i) + "/sanity/adequacy_test/dist_vec_" + model2
with open(sanity_results,"r") as ma:
sim_dist = ma_dist.readlines() # list of distributions
sim_dist = [x.strip() for x in sim_dist]
sanity_counts_file = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/" + model1 + "/" + "adequacy_test/" + str(i) + "/simCounts.txt"
sanity_original_counts = get_counts(sanity_counts_file)
sanity_original_counts_statistics = calculate_statistics(sanity_original_counts)
sanity_original_adequacy_results, stats_results = test_adequacy(sim_dist, sanity_original_counts_statistics) # take sanity_original_adequacy_results
sanity_ma_string = ",".join(str(sanity_original_adequacy_results))
sanity_ma_string = ", ".join(map(str, sanity_original_adequacy_results))
outfile.write(model1 + "," + model2 + "," + str(i) + "," + genus + "," + sanity_ma_string)
#sanity_filename = "/groups/itay_mayrose/annarice/model_adequacy/" + genus + "/" + model1 + "/adequacy_test/" + str(i) + "/sanity/adequacy_test/" + model2 + "_MA.res"
if model1=="CONST_RATE":
break
import csv
import regex as re
from data_processing import best_model
models = ["CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","CONST_RATE_NO_DUPL","BASE_NUM","BASE_NUM_DUPL"]
genera_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/genera"
summary_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/summary_best_model.csv"
with open(summary_file, "w+") as writeFile:
header = ["Genus", "Best_model","Variance","Entropy","Range","Unique","Parsimony"]
writer = csv.writer(writeFile)
writer.writerow(header)
with open (genera_file,"r") as genera:
for genus in genera:
genus = genus.strip()
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/result_sum"
models = best_model.get_best_model(results_sum)
models = models.split(",") # returns a list
for model in models:
adequacy_filename = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/adequacy_vec"
try:
with open(adequacy_filename, "r") as adequacy_f:
tmp = adequacy_f.readline()
tmp = tmp[1:-1:]
'''
if re.search("0", tmp):
adequate = 0
else:
adequate = 1
'''
row = [genus,model,tmp]
writer.writerow(row)
except:
print("No result for " + genus)
continue
###################################################################################################
#################################### REMOVE FOLDERS MASSIVELY #####################################
###################################################################################################
import os
import argparse
import pandas as pd
import csv
import gzip, tarfile
import shutil
def get_best_model(filename):
data = pd.read_csv(filename, sep="\t", header=None)
tmp = data.loc[data[3] == 0,0].values[0]
return tmp # the name of the best model
def targz_dir(outer_dir, dirs_list, dest_zip_filename, delete_after_zipping):
cwd = os.getcwd()
os.chdir(outer_dir)
tarw = tarfile.open(dest_zip_filename, "w:gz")
for dirname in dirs_list:
if os.path.exists(dirname):
tarw.add(dirname)
tarw.close()
if delete_after_zipping:
for dirname in dirs_list:
try:
shutil.rmtree(dirname)
except:
pass
os.chdir(cwd)
filename = "/groups/itay_mayrose/annarice/model_adequacy/genera/genera"
all_models = ["BASE_NUM","BASE_NUM_DUPL","CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","CONST_RATE_NO_DUPL"] # all models
l = []
for i in range(1000):
l.append(str(i))
with open (filename, "r") as genera:
for genus in genera:
genus = genus.strip()
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/result_sum"
models = get_best_model(results_sum)
models = models.split(",") # returns a list
#models = list(set(all_models) - set(models)) # run on all models that are not the best model
for model in models:
out_dir = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/"
os.system("python ~/create_sh.py " + "-name " + genus + " -l " + python + " -s " + script + " -p \'" + cmd + "\'")
try:
print("trying " + genus)
targz_dir(out_dir, l, "zipped.tar.gz", True)
except:
print("passing " + genus)
pass
cmd = "-c " + wd + " -m " + model + " -id " + genus + " -nt 1 -ns " + str(nsims) + " -ce /bioseq/chromEvol/chromEvol.e<file_sep>/zip_previous_genera.py
###################################################################################################
#################################### REMOVE FOLDERS MASSIVELY #####################################
###################################################################################################
import os
import argparse
import gzip, tarfile
import shutil
def get_best_model(filename):
data = pd.read_csv(filename, sep="\t", header=None)
tmp = data.loc[data[3] == 0,0].values[0]
return tmp # the name of the best model
def targz_dir(outer_dir, dirs_list, dest_zip_filename, delete_after_zipping):
cwd = os.getcwd()
os.chdir(outer_dir)
tarw = tarfile.open(dest_zip_filename, "w:gz")
for dirname in dirs_list:
if os.path.exists(dirname):
tarw.add(dirname)
tarw.close()
if delete_after_zipping:
for dirname in dirs_list:
try:
shutil.rmtree(dirname)
except:
pass
os.chdir(cwd)
### ARGS
parser = argparse.ArgumentParser(description="zip model adequacy simulations that were already produced")
parser.add_argument('--out_dir', '-o', help='Outer dir',required=True)
args = parser.parse_args()
out_dir = args.out_dir
l = []
for i in range(1000):
l.append(str(i))
try:
targz_dir(out_dir,l,"zipped.tar.gz",True)
except:
pass
<file_sep>/analysis/test_adequacy.py
import sys
sys.path.append("../")
from defs import *
from utils import *
from data_processing import process_data
from analysis import get_stats
from scipy import linalg
from scipy import stats as st
def create_simulated_stats_distribution(out_dir,nsims,main_res_dir): #[v, e, r, u]
'''
after simulating n simulations, calculate the statistics from each dataset and create a list of lists containing the stats
:param out_dir: where the simulations are located
:param nsims: number of simulations
:param main_res_dir: CE results directory
:return: list of lists of statistics
'''
simulated_counts_stats_dist = []
for i in range(nsims): # for each simulation
sim_counts = process_data.get_counts(out_dir + str(i) + "/simCounts.txt",out_dir + str(i))
simulated_counts_statistics = get_stats.calculate_statistics(sim_counts,out_dir + str(i) + "/simStats", main_res_dir + tree_with_counts,out_dir + str(i) + "/simCounts.txt",out_dir + str(i) + "/simTree.phr")
simulated_counts_stats_dist.append(simulated_counts_statistics)
return simulated_counts_stats_dist
def handle_distributions(dist,stats,res,filename1,filename2):
'''
print distributions and results to files
:param dist: distribution of statistics - list of lists
:param stats: original statistics
:param res: adequacy results (0/1 vector)
:param filename1: a file to print the distributions of all statistics (stats_dist_sims)
:param filename2: a file to print the adequacy 0/1 vector (adequacy_vec)
:return:
'''
with open(filename1, "w") as distribution_file:
for i in range (len(stats)):
sim_stat_dist = [round(x[i],4) for x in dist]
distribution_file.write(str(sim_stat_dist))
distribution_file.write("\n")
with open(filename2,"w") as dist_vec:
dist_vec.write(str(res))
def test_adequacy(sim_stats, stats,filename1,filename2):
'''
go over the stats and test the final adequacy per statistic
:param sim_stats: statistics distributions
:param stats: original statistics
:param filename: percentiles calculated from the distributions
:return: (1) a vector of 0/1 representing in/adequacy of each statistic
(2) the original statistics that were found to be adequate
'''
adequacy_lst = []
stat_lst = []
true_percentiles = []
with open(filename1, "w+") as percentiles:
for i in range(len(stats)):
sim_stat_dist = [x[i] for x in sim_stats] # simulated ith distribution, x the item in each simulated list; sim_stat_dist is a single statistic distribution
stat_star_upper = np.percentile(sim_stat_dist, 97.4) # calculate the upper limit #### >97.4
stat_star_lower = np.percentile(sim_stat_dist, 2.6) # calculate the lower limit ### <2.6
model = 1
#if stats[i] <= stat_star_upper and stats[i] >= stat_star_lower: #if stats[i] <= stat_star_upper and stats[i] >= stat_star_lower
# model = 1
if stats[i] > stat_star_upper or stats[i] < stat_star_lower:
model = 0
adequacy_lst.append(model)
stat_lst.append(stats[i])
percentiles.write(str(round(stat_star_lower, 4)) + "," + str(round(stat_star_upper, 4)) + "\n")
x = st.percentileofscore(sim_stat_dist, stats[i], kind="mean")
true_percentiles.append(x)
with open(filename2,"w") as true_percentiles_file:
res_str = str(true_percentiles)
true_percentiles_file.write(res_str[1:-1:])
return (adequacy_lst,stat_lst)
def post_analysis(adequacy_results,stats_results,model_name,filename,id):
with open(filename, "w+") as results_file:
if all(x==1 for x in adequacy_results):
print ("In " + id + ", " + model_name + " is adequate for all statistics", file = results_file)
for i in range(len(stats_results)):
print (str(statistics_names[i] + " = " + str(stats_results[i])), file = results_file)
return adequacy_results
print("In " + id + ", " + model_name + " is: ", file = results_file)
for i in range(len(adequacy_results)):
if adequacy_results[i]==0:
print ("Not adequate for " + str(statistics_names[i]), file = results_file)
if adequacy_results[i]==1:
print ("Adequate for " + str(statistics_names[i]), file = results_file)
return adequacy_results
def model_adequacy(out_dir,orig_counts_stats, model_name,max_for_sims,nsims,id,main_res_dir):
sim_dist = create_simulated_stats_distribution (out_dir,nsims,main_res_dir)
adequacy_results,stats_results = test_adequacy(sim_dist, orig_counts_stats,out_dir + "percentiles_" + model_name,out_dir + "true_percentiles")
handle_distributions(sim_dist, orig_counts_stats,adequacy_results, out_dir + "stats_dist_sims", out_dir + "adequacy_vec")
results_lst = post_analysis(adequacy_results,stats_results, model_name, out_dir + model_name + "_MA.res",id)
l = []
for i in range(nsims):
l.append(str(i))
targz_dir(out_dir, l, "zipped.tar.gz", True)
return results_lst<file_sep>/tmp_code.py
# python /groups/itay_mayrose/annarice/model_adequacy/code/tmp_code.py /groups/itay_mayrose/annarice/model_adequacy/ce_trial counts
# params: (1) working_dir (2) genus (3) n
# simulate data under the best model and its inferred parameters
# get statistics on simulated data
# get distribution of statistics of simulated data (null distribution)
# In case the real value of the summary statistic significantly deviates from the null distribution, the model is deemed inadequate for the data at hand.
import os
import numpy as np
import scipy.stats as sc
import pandas as pd
from scipy.spatial.distance import mahalanobis
import regex as re
def get_counts(filename):
with open(filename, "r") as counts_file:
counts_lst = []
for line in counts_file:
line = line.strip()
if line.startswith('>'):
continue
else:
counts_lst.append(int(line))
return (counts_lst)
def get_anc_counts(filename):
with open(filename, "r") as counts_file:
for line in counts_file:
line = line.strip()
counts_lst = re.findall("\-(\d+)[\]:]",line) # number after - and before : shold return list
def create_cnt_stats(counts_lst):
l = len(counts_lst) # length
v = np.var(counts_lst) # variance
mi = min(counts_lst)
ma = max(counts_lst)
# enthropy, calculates the probabilities
d = {}
for i in counts_lst:
d[i] = counts_lst.count(i)
prob_lst = [x / len(counts_lst) for x in list(d.values())]
e = sc.entropy(prob_lst)
return ([l, v, mi, ma, e])
def get_events_numbers(simEventsFile):
events_lst = []
for line in open(simEventsFile):
rec = line.strip()
if rec.startswith('Total'): # gain, loss, duplication, demi-duplication, base number transitions, transitions to max
match = re.search("(\d+)")
events_lst.append(match.group(1))
return (events_lst)
def get_best_model(filename):
with open (filename,"r") as models_summary:
data = pd.read_table(models_summary,header=None)
best_model_row = data.loc[data[3] == 0,0] # best model, the one with deltaAIC = 0
return (best_model_row)
def handle_sim_datasets(dir1,n): # dir1 = simulations dir, n = simulations number,
'''
for each simulated dataset call create_cnt_stats and store the results in a list (list of lists)
'''
lst_of_sim_stats = []
for i in range(n):
sim_cnts = get_counts(str(i)+"/simCounts.txt")
tmp = create_cnt_stats(sim_cnts)
lst_of_sim_stats.append(tmp)
return lst_of_sim_stats
def test_adequacy (sim_stats,stats):
''' go over each statistic in the list and see if is adequate'''
adequacy_lst = []
for i in range(len(stats)):
sim_stat_dist = [x[i] for x in sim_stats] # simulated ith distribution, x the item in each simulated list
stat_star_upper = np.percentile(sim_stat_dist,97.5) # calculate the upper limit
stat_star_lower = np.percentile(sim_stat_dist,2.5) # calculate the lower limit
model = 0
if stats[i]<=stat_star_upper and stats[i]>=stat_star_lower:
model = 1
adequacy_lst.append(model)
return adequacy_lst
if __name__ == '__main__':
working_dir = "D:/Dropbox/MyDocs/lab/model_adequacy"
genus = "Vernonanthura"
#file1 = "/chromevol_out/infer/infer_tree_1/result_sum" # ---> best model + model parameters
#file2 = "/chromevol_out/infer/infer_tree_1/simulation/param_sim_1" # ---> simulation control file
dir1 = "chromevol_out/infer/infer_tree_1/simulation/dir_sim_1" # ---> where the simulations are
n = 10 # number of simulations
statistics = ["length","variance","min","max","entropy"]
os.chdir(working_dir)
extant_counts = get_counts(genus + ".counts_edit") # extant_counts is a numeric list containing all extant counts (tip counts) as provided from the user
all_counts = get_anc_counts("mlAncestors.tree") # all_counts retrieves all counts of the tree, including the internal nodes
stats = create_cnt_stats(extant_counts) # get statistics on real data (empirical)
# best_model_row = get_best_model(file1) # get the best model and its optimized parameters
os.chdir(dir1)
sim_stats = handle_sim_datasets(dir1,n) # read simulated datasets
results = test_adequacy(sim_stats,stats)
for i in range(len(results)):
if results[i]==0:
print ("Model not adequate for " + statistics[i])
#print ([x[i] for x in sim_stats])
#print(stats[i])
if all(x==1 for x in results):
print ("Model is adequate for all statistics")
'''
def create_CE_control_file(filename,params_names,params):
d = {}
for i in range(len(params_names)):
d[params_names[i]] = params[i]
with open (filename,"r") as control_file:
for key in d:
##if # regex, if numeric value, print as number and not str --- why??
control_file.write(key,d[key])
'''
<file_sep>/create_plots_for_web.R
args = commandArgs(trailingOnly=TRUE)
setwd(args[1])
stats_ind = c(1,2,3,4)
stats_names = c("Variance","Entropy","Parsimony score","Parsimony score vs. time slope")
# read distributions
dists = read.table("stats_dist_sims",sep=c(","),stringsAsFactors = F)
dists$V1 = as.numeric(gsub( "\\[", "", as.character(dists$V1)) )
dists[,ncol(dists)] = as.numeric(gsub( "\\]", "", as.character(dists[,ncol(dists)])))
dists = as.matrix(dists)
# read original stats
orig_stats = read.table("orig_stats",sep=",",stringsAsFactors = F)
orig_stats = orig_stats[stats_ind]
names(orig_stats) = stats_names
# read percentiles
percentiles = read.table(paste("percentiles",args[2],sep="_"),sep=",", stringsAsFactors = F)
# read true percentiles
true_p = read.table("true_percentiles", sep=",", stringsAsFactors = F)
true_p = true_p[stats_ind]
names(true_p) = stats_names
pdf("dists.pdf")
par(mfrow = c(2,2))
for (i in stats_ind){
y = hist(dists[i,], main = paste(stats_names[i]), ylab = "", xlab = "")
mtext(paste("95% confidence bounds: ","[",percentiles[i,1],"--",percentiles[i,2],"]","\n",
"True statistic: ",orig_stats[i]," Percentile: ",true_p[1,i],sep=""), line = -0.5, cex = 0.8)
segments(x0=as.numeric(orig_stats[i]),y0=0,x1=as.numeric(orig_stats[i]),y1=max(y$counts)*0.9,col="red",lwd=3)
segments(x0=as.numeric(percentiles[i,1]),y0=0,x1=as.numeric(percentiles[i,1]),y1=max(y$counts)*0.9,col="blue",lty=2)
segments(x0=as.numeric(percentiles[i,2]),y0=0,x1=as.numeric(percentiles[i,2]),y1=max(y$counts)*0.9,col="blue",lty=2)
}
dev.off()
#### tails of distribution<file_sep>/sanity_summarize.py
import numpy as np
import scipy.stats as sc
import re
from utils import *
from defs import *
import csv
def initialize_parameters():
d = {}
for item in params_for_summary:
d[item] = 0
return d
genera = ["Aloe", "Phacelia", "Lupinus", "Hypochaeris", "Brassica", "Pectis", "Hordeum", "Crepis"]
models = ["CONST_RATE","CONST_RATE_NO_DUPL","BASE_NUM","BASE_NUM_DUPL"]
params_for_summary = ["_lossConstR", "_gainConstR", "_duplConstR", "_demiPloidyR", "_baseNumber", "_baseNumberR","_maxBaseTransition"]
header = ["Simulated_under", "model2", "nsim", "genus", "variance", "entropy", "range", "unique_counts", "fitch", "time",
"loss", "gain", "dupl", "demi", "base", "baseR", "max_trans", "sum_all","sum"]
home_dir = "/groups/itay_mayrose/annarice/model_adequacy/sanity/"
out_file = home_dir + "sanity_summarize_tree_two_runs_trial.csv"
models_d = model_per_genus()
with open(out_file , "w+") as writeFile:
writer = csv.writer(writeFile)
writer.writerow(header)
for genus in genera:
model1 = models_d.get(genus)
for i in range(100):
for model2 in models:
row = [model1, model2, str(i), genus]
general_path = "/".join([home_dir,genus,model1,"adequacy_test",str(i),model2,"adequacy_test"])
sanity_results = general_path + adequacy_vector
if os.path.exists(sanity_results):
with open(sanity_results, "r") as ma:
res = ma.read()
res = str_to_lst(res, "int")
row.extend(res)
sum_all = sum(res)
sum_partial = res[0] + res[1] + res[4] + res[5]
d = initialize_parameters() # get param names according to the current model
params_file = general_path + sim_control
params_dict_from_file = return_parameters_dict(params_file)
for item in params_for_summary:
if item in params_dict_from_file.keys():
d[item] = params_dict_from_file[item]
row.append(d[item])
row.extend([sum_all, sum_partial])
writer.writerow(row)
else:
print(genus, str(i), model2, " is missing")
continue
<file_sep>/analysis/phangorn.R
require(phytools)
require(phangorn)
# arguments: (1) working_dir (2) number of iterations (1 for original counts, n for simulations)
# output: list of calculated statistic N times
args = commandArgs(trailingOnly=TRUE)
working_dir = args[1]
iter = args[2]
calculate_stat = function(tree){
counts = c()
for (i in 1:(tree$Nnode+1)){
counts = c(counts, as.numeric(gsub("[^0-9]", "", tree$tip.label[i])))
tree$tip.label[i] = gsub('-[0-9]+', '', tree$tip.label[i])
}
mat_data = matrix(counts,dimnames = list(tree$tip.label,NULL), nrow=length(counts), byrow=TRUE)
data = phyDat(mat_data, type = "USER", levels = unique(counts))
tmp = acctran(tree,data)
#mat = as.data.frame(cbind(tree$edge,tree$edge.length,tmp$edge.length,0))
#names(mat) = c("begin","end","length","parsimony","time")
tmp_mat = as.data.frame(cbind(tmp$edge,tmp$edge.length))
names(tmp_mat) = c("begin","end","parsimony")
tree_mat = as.data.frame(cbind(tree$edge,tree$edge.length))
names(tree_mat) = c("begin","end","time")
mat = merge(tree_mat, tmp_mat, by=c("begin","end"))
mat$time = 0
distances = dist.nodes(tree)
root_ind = which(node.depth.edgelength(tree)==0)
for (i in 1:nrow(mat)){
end = mat$end[i]
mat$time[i] = distances[root_ind,end]
}
x = mat$time
y = mat$parsimony
lm = lm(y~x)
result = round(lm$coefficients[2],2)
names(result) = NULL
#results_lst = append(results_lst,result)
return(result)
}
results_lst = c()
if (iter==1){
tree_file = "tree_with_counts.tree"
tree = read.newick(paste(working_dir,tree_file,sep="/"))
results_lst = calculate_stat(tree)
} else {
tree_file = "simTree.phr"
for (n in (1:iter)-1){
tree = read.newick(paste(working_dir,n,"simTree.phr",sep="/"))
stat = try(calculate_stat(tree))
if (inherits(stat,'try-error')){
next
}
results_lst = append(results_lst,stat)
}
}
cat(results_lst)
<file_sep>/summarize_events.py
from utils import *
import re
import csv
# for each genus that is in the sanity checks summarize its sim events for the 50 original sims.
models_d = model_per_genus()
lst = ["Aloe","Phacelia","Lupinus","Hypochaeris","Brassica","Pectis","Chlorophytum","Hordeum","Crepis"]
sanity_models = ["BASE_NUM_DUPL","CONST_RATE_NO_DUPL","CONST_RATE","BASE_NUM"]
output_file = "/groups/itay_mayrose/annarice/model_adequacy/sanity/sim_events_summary2.csv"
with open (output_file, "w+") as out_file:
header = ["genus","model","sim","root","base_num","gain","loss","dupl","base","BASE_NUM_DUPL","CONST_RATE_NO_DUPL","CONST_RATE","BASE_NUM"]
writer = csv.writer(out_file)
writer.writerow(header)
for genus in lst:
model = models_d.get(genus)
params_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/param_sim"
freq_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/root_freq"
base_num = "0"
root_num = "0"
with open (params_file,"r") as params:
for line in params:
tmp_line = re.search("_baseNumber\s(\d+)",line)
if tmp_line: # there's a base_numer
base_num = tmp_line.group(1)
break
targz_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/adequacy_test/zipped.tar.gz"
tar = tarfile.open(targz_file)
for i in range(50):
events_lst = []
adequacy_lst = []
sim_events = str(i) + "/simEvents.txt"
sim_tree = str(i) + "/simTree.phr"
for member in tar.getmembers():
if member.name == sim_events:
f = tar.extractfile(member)
content = f.read()
lines = content.splitlines()
for line in lines:
line_decoded = line.decode('utf-8')
tmp_line = re.search("Total number of (gain|loss|duplication|base number) (events|transitions)\:\s(\d+.*)",line_decoded)
if tmp_line:
events_lst.append(tmp_line.group(3))
continue
if member.name == sim_tree:
f = tar.extractfile(member)
content = f.read()
content = content.decode('utf-8')
tmp = re.search("N1-(\d+)", content)
if tmp:
root_num = tmp.group(1)
for sanity in sanity_models:
adequacy_vec = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/" + sanity + "/adequacy_test/adequacy_vec"
adequacy = get_adequacy_from_vec(adequacy_vec)
adequacy_lst.append(adequacy)
row = [genus,model,i,root_num,base_num,','.join(events_lst),adequacy_lst]
writer.writerow(row)
<file_sep>/defs.py
# IMPORTS
import regex as re
import os
import pandas as pd
import numpy as np
import scipy as sp
import scipy.stats as sc
from scipy import linalg
from scipy.stats import chi2
import sys,argparse,platform
from ete3 import Tree
import csv
import subprocess
from shutil import copyfile
CE_res_filename = "/chromEvol.res" # this name needs to be concatenated to the model's name as a directory
expectation_file = "/expectations.txt"
mlAncTree = "/mlAncestors.tree"
tree_with_counts = "/tree_with_counts.tree"
tree_wo_counts = "/tree_wo_counts.tree"
root_freq_filename = "/root_freq"
sim_control = "/param_sim"
statistics_names = ["Variance", "Entropy", "Range", "Unique_counts", "Parsimony", "Time_parsimony"]
### ARGS
def get_arguments():
parser = argparse.ArgumentParser(description='tests model adequacy of selected ChromEvol model')
parser.add_argument('--main_res_dir', '-c', help='home directory of ChromEvol results',required=True)
parser.add_argument('--model_name', '-m', help='the model tested for adequacy', required=True)
parser.add_argument('--job_id', '-id', help='job ID or Genus name', required=True)
parser.add_argument('--num_of_trees', '-nt', help='number of trees in the original ChromEvol run',required=False, default=1)
parser.add_argument('--sims_per_tree', '-ns', help='number of simulations for the adequacy test per original tree',required=False,default=1)
parser.add_argument('--CE_path', '-ce', help='ChromEvol executable path',required=False, default = "/groups/itay_mayrose/itaymay/code/chromEvol/chromEvol_source-current/chromEvol")
parser.add_argument('--params', '-p', help='parameters file from user for simulations', required=False, default="")
parser.add_argument('--counts', '-co', help='counts file', required=True)
parser.add_argument('--sanity', '-s', help='counts file', required=False, default=0)
parser.add_argument('--results', '-r', help='counts file', required=False, default=0)
# parse arga
args = parser.parse_args()
id = args.job_id
main_res_dir = args.main_res_dir
in_model = args.model_name
in_model = in_model.split(",")
num_of_trees = int(args.num_of_trees)
sims_per_tree = int(args.sims_per_tree)
CE_path = args.CE_path
params_from_user = args.params
counts_file = args.counts
sanity_flag = int(args.sanity)
results_flag = int(args.results)
return(id,main_res_dir,in_model,num_of_trees,sims_per_tree,CE_path,params_from_user,counts_file,sanity_flag,results_flag)<file_sep>/data_processing/best_model.py
from defs import *
#import pandas as pd
def get_best_model(filename):
data = pd.read_csv(filename, sep="\t", header=None)
tmp = data.loc[data[3] == 0,0].values[0]
return tmp # the name of the best model
#def create_freq_file(line,freqs,upper_bound):
def create_freq_file(line, freqs):
tmp = line
# write the tmp to a file, with the aid of emp_data
with open(freqs, "w+") as root_freq:
text = tmp.split()
first = re.search("F\[(\d+)\]", text[0])
first = int(first.group(1))
last = re.search("F\[(\d+)\]", text[-1])
last = int(last.group(1))
#for i in range(1, first):
# print("F[" + str(i) + "]=0", file=root_freq)
for i in range(0, last - first + 1):
print(text[i], file=root_freq)
#for i in range(last + 1, upper_bound):
# print("F[" + str(i) + "]=0", file=root_freq)
#def get_params(filename, freqs, upper_bound):
def get_params(filename, freqs):
'''
produce a dictionary of parameters
'''
params_dict = {}
line_cntr = 0
with open(filename, "r") as params_file:
for line in params_file:
line_cntr = line_cntr + 1
if line_cntr == 6: # reached the parameters part
line = line.strip()
tree_length = re.search("(\d+)", line).group(1)
params_dict["_simulationsTreeLength"] = tree_length
if line_cntr > 15: # reached the parameters part
line = line.strip()
tmp = re.search("(^[^F].*)\s(.*)",line) # the line doesn't start with F, indicating the root frequencies results
if tmp:
key = tmp.group(1)
val = int(tmp.group(2)) if key=="BASE_NUMBER" else float(tmp.group(2))
params_dict[key] = val # key = name of parameter, val = parameter's value
else: # reached the root frequencies part
#create_freq_file(line,freqs,upper_bound)
create_freq_file(line, freqs)
break
d = {}
d = {"LOSS_CONST": "_lossConstR", "GAIN_CONST": "_gainConstR", "DUPL": "_duplConstR","BASE_NUMBER_R": "_baseNumberR", "BASE_NUMBER": "_baseNumber", "HALF_DUPL":"_demiPloidyR"}
for key in d:
if key in params_dict:
params_dict[key]
params_dict[d[key]] = params_dict[key]
del params_dict[key]
return (params_dict)
<file_sep>/utils.py
import gzip, tarfile
import os
import shutil
import pandas as pd
import re
from ete3 import Tree
from data_processing import process_data
def targz_dir(outer_dir, dirs_list, dest_zip_filename, delete_after_zipping):
cwd = os.getcwd()
os.chdir(outer_dir)
tarw = tarfile.open(dest_zip_filename, "w:gz")
for dirname in dirs_list:
if os.path.exists(dirname):
tarw.add(dirname)
tarw.close()
if delete_after_zipping:
for dirname in dirs_list:
try:
shutil.rmtree(dirname)
except:
pass
os.chdir(cwd)
def untargz(zip_file_dest, delete_after_extracting=False):
"""
:param filepath_pattern: the names of the files to validate existence. The blanks are in {}
:return: the filepath of a concatenated file for all
"""
dirpath, zip_filename = os.path.split(zip_file_dest)
cwd = os.getcwd()
os.chdir(dirpath)
tarx = tarfile.open(zip_file_dest, "r:gz")
tarx.extractall(dirpath)
tarx.close()
os.chdir(cwd)
if delete_after_extracting:
os.remove(zip_file_dest)
def get_best_model(filename):
data = pd.read_csv(filename, sep="\t", header=None)
tmp = data.loc[data[3] == 0,0].values[0]
return tmp # the name of the best model
def average(lst):
return sum(lst) / len(lst)
def get_counts(filename):
'''
reads the .counts_edit file and extracts the counts
:param filename: supplied by the user
:return: list of counts
'''
with open(filename, "r") as tmp_counts_file:
counts = []
for line in tmp_counts_file:
line = line.strip()
if line.startswith('>'):
continue
else:
if line=="x":
continue
counts.append(int(line))
return (counts)
def model_per_genus():
'''
this is instead of running "get_best_model"
:return: dictionary of common genera I use for validations and their best supported model
'''
d = {"Aloe": "CONST_RATE", "Phacelia": "CONST_RATE", "Lupinus": "CONST_RATE_NO_DUPL","Hypochaeris": "CONST_RATE_NO_DUPL",
"Crepis": "BASE_NUM_DUPL", "Pectis": "BASE_NUM", "Chlorophytum": "BASE_NUM_DUPL", "Achillea": "BASE_NUM","Stachys": "BASE_NUM_DUPL", "Eryngium": "BASE_NUM_DUPL",
"Brassica": "BASE_NUM", "Hordeum": "BASE_NUM_DUPL", "Curcuma": "BASE_NUM", "Pilosella": "BASE_NUM_DUPL"}
return(d)
def get_adequacy_from_vec(filename):
with open(filename, "r") as adequacy_f:
tmp = adequacy_f.readline()
if re.search("0", tmp):
return(0)
else:
return(1)
def str_to_lst(str,type_flag):
str = str.strip()
if str[0]=="[":
str = str[1:-1]
if type_flag == "int":
lst = list(map(int, str.split(",")))
if type_flag == "float":
lst = list(map(float, str.split(",")))
return(lst)
def fix_tree_file2(tree_file2):
'''
a patch that fixes a bug in ChromEvol which produces a .phr tree file without a semicolon at the end.
:param tree_file2:
:return: the same tree file with a semicolon at the end
'''
with open(tree_file2, "a") as add:
add.write(";")
def create_counts_hash(counts_file):
'''
puts all counts from a typical counts file (>taxa \n number) in a hash.
If there are counts that are X the function returns two hashes and a set of the taxa to prune.
:param counts_file:
:return:(2) d -- hash without counts that are "X"
'''
d = {}
with open (counts_file,"r") as counts_handler:
for line in counts_handler:
line = line.strip()
if line.startswith('>'): # taxon name
name = line[1:]
else:
if line != "x":
num = int(line)
d[name] = num
return(d)
<file_sep>/create_thresholds_distribution.py
import regex as re
from utils import *
import statistics
import os
import csv
import pandas as pd
# genera list
genera_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/genera"
# wd
wd = "/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/"
dp_lst = []
pp_lst = []
counter = 0
genera_lst = []
def get_threshold(filename):
with open(filename, "r") as threshold_file:
for line in threshold_file:
tmp = re.search("#.*:\s(\d+\.?\d*)", line)
if tmp:
threshold = tmp.group(1)
threshold = float(threshold)
return(threshold)
def get_tar_threshold(handler):
f = tar.extractfile(handler)
content = f.read()
lines = content.splitlines()
last_line = lines[-1].decode('utf-8')
tmp = re.search("#.*:\s(\d+\.?\d*)", last_line)
if tmp:
threshold = tmp.group(1)
threshold = float(threshold)
return (threshold)
def get_threshold_from_file(genus,filename):
#with open (filename,"r") as thresholds:
with open (genera_file,"r") as genera:
for genus in genera:
genus = genus.strip()
print(genus)
dp_file = wd + genus + "/" + genus + "_Chromevol_prune/chromevol_out/thresholds_DP"
pp_file = wd + genus + "/" + genus + "_Chromevol_prune/chromevol_out/thresholds_PP"
try:
dp = get_threshold(dp_file)
dp_lst.append(dp)
pp = get_threshold(pp_file)
pp_lst.append(pp)
counter += 1
genera_lst.append(genus)
except:
try:
new_path = wd + genus + ".tar.gz"
dest = "/groups/itay_mayrose/annarice/model_adequacy/for_unzip/" + genus + ".tar.gz"
os.system("cp -rf " + new_path + " " + dest)
tar = tarfile.open(dest)
for member in tar.getmembers():
if member.name == dp_file[1:]:
dp = get_tar_threshold(member)
dp_lst.append(dp)
if member.name == pp_file[1:]:
pp = get_tar_threshold(member)
pp_lst.append(pp)
counter += 1
genera_lst.append(genus)
except:
pass
output_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/thresholds_test.csv"
with open (output_file, "w+") as results:
header = ["Genus", "DP","PP"]
writer = csv.writer(results)
writer.writerow(header)
for i in range(counter):
row = [genera_lst[i],dp_lst[i],pp_lst[i]]
writer.writerow(row)
print(counter)
print("DP average: " + str(average(dp_lst)) + "\n")
print("PP average: " + str(average(pp_lst)) + "\n")
print("DP median: " + str(statistics.median(dp_lst)) + "\n")
print("PP average: " + str(statistics.median(pp_lst)) + "\n")
'''
results.write(str(counter) + " genera\n")
results.write("DP list:\n")
results.write(str(dp_lst) + "\n")
results.write("PP list:\n")
results.write(str(pp_lst) + "\n")
results.write("*******************\n")
results.write("DP average: " + str(average(dp_lst)) + "\n")
results.write("*******************\n")
results.write("PP average: " + str(average(pp_lst)) + "\n")
results.write("*******************\n")
results.write("DP median: " + str(statistics.median(dp_lst)) + "\n")
results.write("*******************\n")
results.write("PP average: " + str(statistics.median(pp_lst)) + "\n")
'''
<file_sep>/main_for_web.py
import os
from utils import *
from defs import *
from data_processing import process_data
from data_processing import best_model
from data_processing import simulations
from analysis import get_stats
from analysis import test_adequacy
if __name__ == '__main__':
id, main_res_dir, in_model, num_of_trees, sims_per_tree, CE_path, params_from_user, counts_file, sanity_flag, results_flag = get_arguments()
m = len(in_model)
for k in range(m): # run over all models or a single model
model = in_model[k]
if sanity_flag == 1:
main_res_dir = main_res_dir + model
output_dir = main_res_dir + "/adequacy_test/"
for i in range(num_of_trees):
if not os.path.exists(output_dir):
res = os.system("mkdir -p " + output_dir) # -p allows recusive mkdir in case one of the upper directories doesn't exist
original_counts = process_data.get_counts(counts_file, main_res_dir)
if path.exists(main_res_dir + "/NO_NEED_FOR_MA"):
exit()
process_data.match_counts_to_tree(main_res_dir + mlAncTree, main_res_dir)
original_counts_statistics = get_stats.calculate_statistics(original_counts, output_dir + "orig_stats",
main_res_dir + tree_with_counts)
max_for_simulations = simulations.run_MA(main_res_dir, output_dir + sim_control, main_res_dir,
output_dir, original_counts, model, sims_per_tree,
main_res_dir + tree_wo_counts, CE_path)
adequacy_lst = test_adequacy.model_adequacy(output_dir, original_counts_statistics, model,
max_for_simulations, sims_per_tree, id, main_res_dir)
path = os.path.dirname(sys.argv[0])
os.system("Rscript " + path + "/create_plots_for_web.R " + output_dir + " " + model)<file_sep>/data_processing/process_data.py
import sys
sys.path.append("../")
from defs import *
from utils import *
def match_counts_to_tree(tree_file,dir):
'''
Receives the mlAncTree file which has in its tips names + counts.
Receives the main_res_dir to which the new trees and counts will be written
:param tree_file:
:return:(1) tree_wo_counts without X taxa and without counts in their tip names
(2) tree_with_counts without X taxa and with counts in the tips
'''
t = Tree(tree_file, format=1)
tips_to_prune = []
all_tips = []
for leaf in t:
all_tips.append(leaf.name)
name_with_x = re.search(".*\-X", leaf.name)
if name_with_x:
tips_to_prune.append(leaf.name)
t.prune(list(set(all_tips) - set(tips_to_prune)))
t.write(format=1, outfile=dir + tree_with_counts)
for leaf in t:
name = re.search("(.*)\-[\d]", leaf.name)
leaf.name = name.group(1)
t.write(format=6, outfile=dir + tree_wo_counts) # write with branch lengths
def match_counts_to_tree2(tree_file,counts,new_counts,new_tree):
# recieve tree_1 and counts and
t = Tree(tree_file, format=1)
tree_flag = 0
to_be_pruned = []
tips = []
tips_orig = []
for leaf in t:
name = re.search("(.*)\-[\dX]", leaf.name)
tip = name.group(1)
tips.append(tip)
tips_orig.append(leaf.name)
tmp = {}
with open(counts, "r") as counts_file:
for line in counts_file:
line = line.strip()
if line.startswith('>'):
name = line[1:]
else:
if line != "x":
tmp[name] = int(line)
else:
to_be_pruned.append(name)
tree_flag = 1
to_be_pruned = [x + "-X" for x in to_be_pruned]
with open(new_counts, "w+") as handle:
for key in tmp:
if key in tips: # count on the tree
handle.write(">" + key + "\n")
handle.write(str(tmp.get(key)) + "\n")
if tree_flag == 1: # the tree was pruned - re-write it
t.prune(list(set(tips_orig) - set(to_be_pruned)))
t.write(format=1, outfile=new_tree)
else:
t.write(format=1, outfile=new_tree)
def handle_tree(tree_file,tip_to_prune):
'''
currently not in use.
:param tree_file:
:param tip_to_prune:
:return:
'''
t = Tree(tree_file, format=1)
tips = [leaf.name for leaf in t]
t.prune(list(set(tips) - set([tip_to_prune])))
t.write(format=1, outfile=tree_file)
def get_counts(filename,main_res_dir):
'''
reads the .counts_edit file and extracts the counts
:param filename: supplied by the user
:return: list of counts
'''
with open(filename, "r") as tmp_counts_file:
counts = []
for line in tmp_counts_file:
line = line.strip()
if line.startswith('>'):
continue
else:
if line=="x":
continue
counts.append(int(line))
if len(set(counts))== 1: # no counts variability, do not apply MA
open(main_res_dir + "/NO_NEED_FOR_MA", 'a').close()
return (counts)<file_sep>/sh_wrapper.py
import os
import argparse
import csv
from utils import *
from data_processing import best_model
### ARGS
parser = argparse.ArgumentParser(description="produce sh files for running model adequacy, either in regular or sanity mode")
parser.add_argument('--nsims', '-n', help='Number of simulations',required=True)
parser.add_argument('--sanity', '-s', help='Regular mode = 0, sanity mode = 1',required=False, default = 0)
parser.add_argument('--genera', '-f', help='Genera file',required=True)
parser.add_argument('--script', '-c', help='Script path',required=True)
parser.add_argument('--models_flag', '-m', help='models flag. options: ALL, BEST, OTHERS, DEFINED',required=False, default = "BEST") # options: ALL, BEST, OTHERS, DEFINED
parser.add_argument('--models_defined', '-md', help='names of models to test',required=False) # if DEFINED give model's name(s)
parser.add_argument('--results_flag', '-r', help='results flag. Previous results to use = 1, otherwise = 0',required=False, default = 0) # use previous simulations results
parser.add_argument('--queue_name', '-q', help='queue name',required=False, default = "itaym") # use previous simulations results
args = parser.parse_args()
nsims = int(args.nsims)
sanity = int(args.sanity)
filename = args.genera
script = args.script
models_flag = args.models_flag
models_defined = args.models_defined
results_flag = int(args.results_flag)
queue = args.queue_name
lang = "python"
all_models = ["BASE_NUM","BASE_NUM_DUPL","CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","CONST_RATE_NO_DUPL"] # all models
counts_file = ".counts_edit"
d = model_per_genus()
with open (filename, "r") as genera:
with open("/groups/itay_mayrose/annarice/model_adequacy/genera/summary_genera_jan_20.csv", "w+") as writeFile:
header = ["Genus", "Model"]
writer = csv.writer(writeFile)
writer.writerow(header)
for genus in genera:
genus = genus.strip()
if models_flag == "ALL":
models = all_models
if models_flag == "BEST":
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/result_sum"
models = best_model.get_best_model(results_sum)
models = models.split(",") # returns a list
if models_flag == "OTHERS":
models = list(set(all_models) - set(models)) # run on all models that are not the best model
if models_flag == "DEFINED":
models = models_defined.split(",") # returns a list
tested_model = d.get(genus)
for model in models:
if sanity == 1:
for i in range(50,100): # NEED THIS FOR MA ON SANITY
name = genus + str(i) + "." + model
wd = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + tested_model + "/adequacy_test/" + str(i) + "/"
check_path = wd + model + "/adequacy_test/"
#if os.path.isdir(check_path) and os.listdir(check_path): # already executed - prevent from running over
#continue
co = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + tested_model + "/adequacy_test/" + str(i) + "/counts.txt"
tree = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/tree_1"
cmd = "-c " + wd + " -m " + model + " -id " + genus + " -nt 1 -ns " + str(
nsims) + " -ce /groups/itay_mayrose/itaymay/code/chromEvol/chromEvol_source-current/chromEvol -co " + co + " -s " + str(
sanity) + " -r " + str(results_flag)
os.system("python ~/create_sh.py " + "-name " + name + " -l " + lang + " -s " + script + " -q " + queue + " -p \'" + cmd + "\'")
else:
name = genus + "." + model
wd = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/"
co = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + genus + counts_file
tree = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/tree_1"
cmd = "-c " + wd + " -m " + model + " -id " + genus + " -nt 1 -ns " + str(
nsims) + " -ce /groups/itay_mayrose/itaymay/code/chromEvol/chromEvol_source-current/chromEvol -co " + co + " -s " + str(
sanity) + " -r " + str(results_flag)
row = [genus, models]
writer.writerow(row)
os.system("python ~/create_sh.py " + "-name " + name + " -l " + lang + " -s " + script + " -q " + queue + " -p \'" + cmd + "\'")<file_sep>/test.py
from ete3 import Tree
import re
def create_bntpv(expFile, mlAncTree, baseNum):
with open(expFile,'r') as expFile_f:
perNode_EXPECTATIONS_lines=[]
look_for_end=0
for line in expFile_f:
if "#ALL EVENTS EXPECTATIONS PER NODE" in line and look_for_end == 0:
look_for_end = 1 #stop when you find the next #+++++++++++++++++++++++++++++ line
if look_for_end == 1 and "#++++++++++++++++++++++++" in line:
break
if look_for_end == 1:
if "#ALL EVENTS EXPECTATIONS PER NODE" not in line and "BASE-NUMBER" not in line:
perNode_EXPECTATIONS_lines.append(line.strip())
expFile_f.close()
btnodes=dict()
for item in perNode_EXPECTATIONS_lines:
item_split = item.split()
node = item_split[0]
weight = float(item_split[5])
if weight > 0.1:
if weight > 1: weight = 1
btnodes[node] = weight
if not btnodes:
return "%d=1.00"%baseNum
# if for some reason there are no base transition events
#if not btnodes.values():
# baseNum=1
# return baseNum
### for each node, find the base transition
transitions = dict() # will contain all transitions found in data (value is # of times transition was found)
tree_test=Tree(mlAncTree, format=1)
for node in tree_test.traverse("postorder"):
nodeid = re.search("\[?([^\-]+)-([^\]]+)\]?", node.name)
nodeName = nodeid.group(1)
if nodeid.group(2) is not 'x' and nodeid.group(2) is not 'X':
nodeCount = int(nodeid.group(2))
else:
nodeCount = nodeid.group(2)
# if node has base num transition
if nodeName in btnodes.keys():
ancestor = node.up
ancestorid = re.search("\[?([^\-]+)-([^\]]+)\]?", ancestor.name)
ancestorName = ancestorid.group(1)
if ancestorid.group(2) is not 'x' and ancestorid.group(2) is not 'X':
ancestorCount = int(ancestorid.group(2))
else:
ancestorCount = ancestorid.group(2)
# if both node and parent have counts
if nodeCount is not 'x' and nodeCount is not 'X' and ancestorCount is not 'x' and ancestorCount is not 'X':
#Need to add the posibility of probabilities vector !!!
transition = nodeCount - ancestorCount # may include gains\losses
realTrans = round(transition /baseNum) * baseNum
# add transition to hash
if realTrans > 0:
if realTrans in transitions.keys():
transitions[realTrans] += btnodes[nodeName]
else:
transitions[realTrans] = btnodes[nodeName]
else:
btnodes[nodeName] = "NA"
# in case no transitions were found, give transition by base number prob of 1
if not transitions:
transitions[baseNum] = 1.00
### calculate probabilities
allTransitions = list(transitions.values())
totalTrans = sum(allTransitions)
# remove rare transitions (less then 0.05)
for key in transitions.keys():
if (transitions[key]/totalTrans < 0.05):
del transitions[key]
# create final probs hash
probsHash=dict()
for key in transitions.keys():
res=float(transitions[key]/totalTrans)
finalProb = "%.2f" %res # limited to 2 decimal digits
probsHash[key] = float(finalProb)
# make sure probs sum to 1
allProbs = list(probsHash.values())
probSum = sum(allProbs)
diff = 1-probSum
if diff != 0:
# complete or substract to 1 on a random prob
transitions = list(probsHash.keys())
randTrans = transitions[0]
probsHash[randTrans] += diff
# create probs vector
vector = ""
for key in probsHash.keys():
vector+= str(key) + '=' + str(probsHash[key]) + '_'
vector = vector[:-1]
return vector
if __name__ == '__main__':
x = create_bntpv("/groups/itay_mayrose/annarice/model_adequacy/genera/Potentilla/BASE_NUM_DUPL/expectations.txt", "/groups/itay_mayrose/annarice/model_adequacy/genera/Potentilla/BASE_NUM_DUPL/mlAncestors.tree", 7)
print(x)
<file_sep>/find_saturation.py
# from the stats_dist_sims take the Xth 100 sims in each statistics and calculate their percentiles
# calculate the epsilon from the real percentiles -- get two vecs of epsilons an plot them against the nsims
import numpy as np
genera = ["Acer","Justicia","Sambucus"]
genera = ["Annona"]
for genus in genera:
i = "1"
if genus=="Justicia":
i = "7"
i = "0" # for other genera
filename = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/CONST_RATE/adequacy_test/" + i + "/CONST_RATE/adequacy_test_10000/stats_dist_sims"
with open(filename,"r") as dist_sims:
res = dist_sims.read()
res = res.split("\n")
filename = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/CONST_RATE/adequacy_test/" + i + "/CONST_RATE/adequacy_test_10000/percentiles_CONST_RATE"
with open(filename, "r") as original_percentiles:
all_orig_perc = original_percentiles.read()
all_orig_perc = all_orig_perc.split("\n")
for j in range(4): # for each statistic
lst = res[j][1:-1].split(",")
lst = [float(x) for x in lst]
orig_perc = all_orig_perc[j].split(",")
orig_perc = [float(x) for x in orig_perc]
res_upper = []
res_lower = []
print("orig_perc_upper " + str(orig_perc[1]))
print("orig_perc_lower " + str(orig_perc[0]))
print(genus)
for n in range(0, len(lst), 100):
print("0" + "-" + str(n+99))
dist = lst[0:n+100]
stat_star_upper = round(np.percentile(dist, 97.5),4) # calculate the upper limit
stat_star_lower = round(np.percentile(dist, 2.5),4) # calculate the lower limit
print(str(stat_star_lower) + "," + str(stat_star_upper))
res_upper.append(round(stat_star_upper-orig_perc[1],4))
res_lower.append(round(stat_star_lower - orig_perc[0],4))
print(res_upper)
print(res_lower)
<file_sep>/data_processing/params_processing.py
from defs import *
from data_processing import best_model
if sanity==1:
d["mainType"] = "Optimize_Model"
d["_dataFile"] = data_file
d["_maxChrNum"] = -10
d["_minChrNum"] = -1
else:
d["mainType"] = "mainSimulate"
d["_freqFile"] = freq_file
d["_simulationsIter"] = 100
d["_simulationsJumpsStats"] = "expStats.txt"
d["_maxChrNumForSimulations"] = max(counts) * 10
d["_simulationsTreeLength"] = 4
d["_outDir"] = outDir
d["_treeFile"] = tree_file
d["_logFile"] = "log.txt"
d["_logValue"] = 6
d["_maxChrNum"] = -10
d["_minChrNum"] = -1
d["_maxOptimizationIterations"] = 5
d["_epsilonLLimprovement"] = 0.01
d["_optimizeIterNum"] = "0,1,3"
d["_optimizePointsNum"] = "5,2,1"
d["_branchMul"] = 1
def initialize_defaults():
'''
initialize parameters default values
:return: parameters dictionary with fixed parameters
'''
d = {}
d["_maxChrNum"] = -10
d["_minChrNum"] = -1
d["_branchMul"] = 999
d["_simulationsNum"] = 1000
d["_logFile"] = "log.txt"
d["_logValue"] = 6
d["_maxOptimizationIterations"] = 5
d["_epsilonLLimprovement"] = 0.01
d["_optimizeIterNum"] = "0,1,3"
d["_optimizePointsNum"] = "5,2,1"
d["_simulationsIter"] = 100
d["_simulationsTreeLength"] = 4
return d
def create_user_param_dict(filename):
d = {}
with open(filename, "r") as params_file:
for line in params_file:
line = line.strip()
name = re.search("(.*)\s(.*)",line).group(1)
val = re.search("(.*)\s(.*)", line).group(2)
d[name] = val
return d
def create_params_dict(outDir, dataFile, treeFile, params_from_user):
d = initialize_defaults()
d["_mainType"] = "mainSimulate"
d["_outDir"] = outDir
if os.path.isfile(dataFile):
d["_dataFile"] = dataFile
d["treeFile"] = treeFile
if os.path.isfile(params_from_user):
tmp_d = create_user_param_dict(params_from_user)
else:
#########################>>>>>>>>>>>>>>>>>>>> need model for path names, but user don't necessarily specify model >>>>>>>>>>>>>>>######################
tmp_d = best_model.get_params(main_res_dir + model + CE_res_filename,main_res_dir + model + root_freq_filename,max(counts) * 10) # parse from existing CE results file
bntpv_vec = create_bntpv(main_res_dir + model_name + expectation_file, main_res_dir + model_name + mlAncTree,d["_baseNumber"])
d["_baseTransitionProbs"] = bntpv_vec
d["_maxChrNumForSimulations"] = max(counts) * 10
# d = {**d, **tmp_d}
return d
<file_sep>/main.py
from utils import *
from defs import *
from data_processing import process_data
from data_processing import best_model
from data_processing import simulations
from analysis import get_stats
from analysis import test_adequacy
if __name__ == '__main__':
id, main_res_dir, in_model, num_of_trees, sims_per_tree, CE_path, params_from_user, counts_file, sanity_flag, results_flag = get_arguments()
m = len(in_model)
for k in range(m): # run over all models or a single model
model = in_model[k]
if sanity_flag == 1:
main_res_dir = main_res_dir + model
output_dir = main_res_dir + "/adequacy_test/"
for i in range(num_of_trees):
if not os.path.exists(output_dir):
res = os.system("mkdir -p " + output_dir) # -p allows recusive mkdir in case one of the upper directories doesn't exist
original_counts = process_data.get_counts(counts_file,main_res_dir)
if os.path.exists(main_res_dir + "/NO_NEED_FOR_MA"):
exit()
process_data.match_counts_to_tree(main_res_dir + mlAncTree,main_res_dir)
original_counts_statistics = get_stats.calculate_statistics(original_counts, output_dir + "orig_stats",main_res_dir + tree_with_counts)
if results_flag == 1: #use existing results
targz_file = output_dir + "/zipped.tar.gz"
untargz(targz_file) # unzip results
nsims_prev = sum(os.path.isdir(os.path.join(output_dir, i)) for i in os.listdir(output_dir))
if sims_per_tree != nsims_prev:
print ("***Mismatch between number of requested simulations and number of existing simulations. Working with existing number of results")
sims_per_tree = nsims_prev
max_for_simulations = 200
else:
max_for_simulations = simulations.run_MA(main_res_dir, output_dir + sim_control, main_res_dir,
output_dir, original_counts, model, sims_per_tree,
main_res_dir + tree_wo_counts, CE_path)
adequacy_lst = test_adequacy.model_adequacy(output_dir, original_counts_statistics, model,
max_for_simulations, sims_per_tree, id, main_res_dir)
### original
'''
if sanity_flag == 1:
output_dir = main_res_dir + model + "/adequacy_test/"
else:
output_dir = main_res_dir + "/adequacy_test/"
if not os.path.exists(output_dir):
res = os.system("mkdir -p " + output_dir) # -p allows recusive mkdir in case one of the upper directories doesn't exist
original_counts = process_data.get_counts(counts_file)
if len(set(original_counts))==1: # no variety in counts file - similar counts - no need for model adequacy
open(output_dir + "NO_NEED_FOR_MA", 'a').close()
exit()
if sanity_flag == 1:
original_counts_statistics = get_stats.calculate_statistics(original_counts, output_dir + "orig_stats", main_res_dir + model + mlAncTree)
else:
original_counts_statistics = get_stats.calculate_statistics(original_counts, output_dir + "orig_stats",main_res_dir + mlAncTree)
if results_flag == 1: #use existing results
targz_file = output_dir + "/zipped.tar.gz"
untargz(targz_file) # unzip results
nsims_prev = sum(os.path.isdir(os.path.join(output_dir, i)) for i in os.listdir(output_dir))
if sims_per_tree != nsims_prev:
print ("***Mismatch between number of requested simulations and number of existing simulations. Working with existing number of results")
sims_per_tree = nsims_prev
max_for_simulations = 200
else:
if sanity_flag == 1:
max_for_simulations = simulations.run_MA(main_res_dir + model,output_dir + sim_control,main_res_dir + model, output_dir,original_counts,model,sims_per_tree,tree_full_path,CE_path)
else:
max_for_simulations = simulations.run_MA(main_res_dir, output_dir + sim_control,main_res_dir, output_dir, original_counts,model,sims_per_tree,tree_full_path,CE_path)
if sanity_flag == 1:
adequacy_lst = test_adequacy.model_adequacy(output_dir,original_counts_statistics, model,max_for_simulations,sims_per_tree,id, main_res_dir + model)
else:
adequacy_lst = test_adequacy.model_adequacy(output_dir, original_counts_statistics, model,max_for_simulations, sims_per_tree, id,main_res_dir)
'''<file_sep>/sanity.py
# module load python/python-anaconda3-5.3.0; module load perl/perl-5.28.1; python ~/model_adequacy/code/sanity.py -c ~/model_adequacy/Acer/CONST_RATE/adequacy_test/ -t ~/model_adequacy/Acer/tree_1 -m CONST_RATE -ns 2 -ce /bioseq/chromEvol/chromEvol.exe
import argparse
import os
from utils import *
from data_processing import process_data
os.system("module load python/python-anaconda3-5.3.0")
parser = argparse.ArgumentParser(description='sanity')
parser.add_argument('--main_res_dir', '-c', help='home directory of ChromEvol results',required=True) # ~/model_adequacy/genus/model/adequacy_test (wd)
parser.add_argument('--tree', '-t', help='',required=True) # ~/model_adequacy/genus/tree_1
parser.add_argument('--model_name', '-m', help='the model tested for adequacy', required=True)
parser.add_argument('--sims_per_tree', '-ns', help='number of simulations for the adequacy test per original tree',required=False,default=1) # on which sims to run sanity check (range from 0 to -ns)
parser.add_argument('--CE_path', '-ce', help='ChromEvol executable path',required=False, default = "~/model_adequacy/chromEvol")
parser.add_argument('--genus', '-g', help='',required=False)
args = parser.parse_args()
main_res_dir = args.main_res_dir # /groups/itay_mayrose/annarice/model_adequacy/sanity/Acer/CONST_RATE/adequacy_test/
tree = args.tree
model = args.model_name
sims_per_tree = int(args.sims_per_tree)
CE_path = args.CE_path
genus = args.genus
def create_CE_control(CE_control_file,out_dir,data_file,tree_file, model):
with open(CE_control_file, "w+") as control_file:
print ("_mainType Optimize_Model", file = control_file)
print("_outDir " + out_dir, file = control_file) # adequacy_QA dir
print("_dataFile " + data_file, file = control_file) # simulated data
print("_treeFile " + tree_file, file = control_file) # use original tree
print("_logFile log.txt", file = control_file)
print("_maxChrNum -10", file = control_file)
print("_minChrNum -1", file = control_file)
print("_branchMul 999", file = control_file)
print("_simulationsNum 1000", file = control_file)
print("_logValue 6", file = control_file)
print("_maxOptimizationIterations 5", file = control_file)
print("_epsilonLLimprovement 0.01", file = control_file)
print("_optimizePointsNum 10,2,1", file = control_file)
print("_optimizeIterNum 0,1,3", file = control_file)
print("_gainConstR 1", file = control_file)
print("_lossConstR 1", file = control_file)
if model == "CONST_RATE_DEMI":
print("_duplConstR 1", file = control_file)
print("_demiPloidyR -2", file = control_file)
if model == "CONST_RATE_DEMI_EST":
print("_duplConstR 1", file = control_file)
print("_demiPloidyR 1", file = control_file)
if model == "CONST_RATE":
print("_duplConstR 1", file = control_file)
if model == "BASE_NUM":
print("_baseNumberR 1", file = control_file)
counts = get_counts(data_file)
print("_baseNumber " + str(max(3,min(counts))), file = control_file)
print("_bOptBaseNumber 1", file = control_file)
if model == "BASE_NUM_DUPL":
print("_duplConstR 1", file = control_file)
print("_baseNumberR 1", file = control_file)
counts = get_counts(data_file)
print("_baseNumber " + str(max(3,min(counts))), file = control_file)
print("_bOptBaseNumber 1", file = control_file)
# CE_control_file,out_dir,data_file,tree_file, model
if __name__ == '__main__':
i = sims_per_tree
output_dir = main_res_dir + str(i) + "/" + model + "/"
if not os.path.exists(output_dir):
res = os.system("mkdir -p " + output_dir)
counts = main_res_dir + str(i) + "/" + "counts.txt"
new_counts = main_res_dir + str(i) + "/" + "counts.txt"
create_CE_control(output_dir + model + ".params",output_dir,counts,tree,model)
os.system('"' + CE_path + '" ' + output_dir + model + ".params")
<file_sep>/simulations_exp.py
from utils import *
import argparse
import regex as re
# args
parser = argparse.ArgumentParser()
parser.add_argument('--nsims', '-n', help='Number of simulations',required=True)
parser.add_argument('--genera', '-f', help='Genera file',required=True)
parser.add_argument('--model', '-m', help='models flag',required=True)
parser.add_argument('--working_dir', '-wd', help='models flag',required=True)
args = parser.parse_args()
nsims = int(args.nsims)
filename = args.genera
model = args.model
wd = args.working_dir
l = []
for i in range(nsims):
l.append(str(i))
with open (filename, "r") as genera:
for genus in genera:
genus = genus.strip()
file = wd + "/" + genus + "/" + model + "/adequacy_test/zipped.tar.gz"
untargz(file)
param_file = wd + "/" + genus + "/" + model + "/adequacy_test/param_sim"
params_dict = {"tree_factor":1, "gain_events":0, "loss_events":0, "duplication_events":0, "demi-dulications_events":0, "base_number_transitions":0, "transitions_to_max_chromosome":0}
with open (param_file, "r") as params:
for line in params:
tmp_line = re.search("_simulationsTreeLength (\d+)", line) # tree multiplication
if tmp_line:
params_dict["tree_factor"] = int(tmp_line.group(1))
continue
tmp_line = re.search("_lossConstR (.*)", line) # loss
if tmp_line:
params_dict["loss_events"] = float(tmp_line.group(1))
continue
tmp_line = re.search("_gainConstR (.*)", line) # gain
if tmp_line:
params_dict["gain_events"] = float(tmp_line.group(1))
continue
tmp_line = re.search("_duplConstR (.*)", line) # gain
if tmp_line:
params_dict["duplication_events"] = float(tmp_line.group(1))
continue
tmp_line = re.search("_baseNumberR (.*)", line)
if tmp_line:
params_dict["base_number_transitions"] = float(tmp_line.group(1))
continue
tmp_line = re.search("_demiPloidyR (.*)", line)
if tmp_line:
params_dict["demi-dulications_events"] = float(tmp_line.group(1))
continue
d = {}
for i in range(nsims):
simEvents = wd + "/" + genus + "/" + model + "/adequacy_test/" + str(i) + "/simEvents.txt"
with open (simEvents, "r") as se:
for line in se:
tmp_line = re.search("Total number of (.*): (\d+)", line)
if tmp_line:
key = tmp_line.group(1)
key = key.replace(" ", "_")
val = int(tmp_line.group(2))
if key not in d.keys():
d[key] = [val]
else:
d[key].append(val)
print ("****" + genus + ", " + model + "****")
print ("expected, simulated")
for key in d.keys():
num_events = round(params_dict["tree_factor"] * params_dict[key],2)
print(key + ":" + str(num_events) + ", " + str(round(average(d[key]),2)))
out_dir = wd + "/" + genus + "/" + model + "/adequacy_test/"
targz_dir(out_dir, l, "zipped.tar.gz", True)<file_sep>/check_adequacy_impact.py
import pandas as pd
import regex as re
import argparse
import os
import gzip, tarfile
from utils import *
from scipy import stats
import csv
#from create_thresholds_distribution import get_threshold
# args
parser = argparse.ArgumentParser(description="")
parser.add_argument('--nsims', '-n', help='Number of simulations',required=True)
parser.add_argument('--genera', '-f', help='Genera file',required=True)
parser.add_argument('--models_defined', '-md', help='define which models to run',required=False)
parser.add_argument('--results_file', '-re', help='define which models to run',required=True)
args = parser.parse_args()
nsims = int(args.nsims)
filename = args.genera
models_defined = args.models_defined
models = models_defined.split(",") # returns a list
res_file = args.results_file
orig_numbers_filename = "/simCountsAllNodes.txt"
orig_dupl_filename = "/simEvents.txt"
inferred_numbers_filename = "/mlAncestors.tree"
inferred_expec_filename = "/expectations.txt"
l = []
for i in range(nsims):
l.append(str(i))
d = model_per_genus()
def get_measure(filename,measure):
with open(filename,"r") as measure_file:
### root_num
if error_measure == "root_num":
tmp = measure_file.readline()
if measure == "orig":
num = int(measure_file.readline())
else: # inferred
tmp = re.search("\[N1-(\d+)", tmp)
num = int(tmp.group(1))
return (num)
### total_dupl
if error_measure == "total_dupl":
num = 0
for line in measure_file:
tmp_line = re.search("Total number of duplication events\:\s(\d+.*)", line)
if tmp_line:
num = num + round(float(tmp_line.group(1)))
tmp_line = re.search("Total number of demi.*\:\s(\d+.*)",line)
if tmp_line:
num = num + round(float(tmp_line.group(1)))
tmp_line = re.search("Total number of.* trans.*\:\s(\d+.*)",line)
if tmp_line:
num = num + round(float(tmp_line.group(1)))
return (num)
### internal_nodes
if error_measure == "internal_nodes":
if measure == "orig":
tmp = measure_file.read()
tmp = re.findall(">N\d+\n(\d+)", tmp, re.M) # internal nodes
return(list(map(int, tmp)))
else: # inferred
line = measure_file.readline()
tmp = re.findall("N\d+\-(\d+)",line)
tmp = tmp[::-1]
return(list(map(int, tmp)))
### branch_dupl
if error_measure == "branch_dupl":
lst = []
flag = 0
for line in measure_file:
if line=="\n":
continue
if measure == "orig":
tmp_line = re.search("^#N.+(du|base)",line)
else:
tmp_line = re.search("^NODE", line)
if tmp_line:
flag = 1
continue
if measure == "orig":
if flag == 1 and not line.startswith("Total number of"):
x = re.search("(.*)\:", line)
lst.append(x.group(1))
else:
flag = 0
else:
if flag == 1 and not line.startswith("#+++++++++++++++++++++++++++++"):
x = line.split()
if len(x) == 6: # base_num model
if float(x[3]) > 0.5 or float(x[4]) > 0.5 or float(x[5]) > 0.5:
lst.append(x[0])
else: # other models
if float(x[3]) > 0.5 or float(x[4]) > 0.5:
lst.append(x[0])
else:
flag = 0
return(lst)
if error_measure == "inference":
lst = []
flag = 0
for line in measure_file:
tmp_line = re.search("^LEAF",line)
if tmp_line:
flag = 1
continue
if flag == 1:
x = line.split()
if len(x) == 6: # base_num model
if float(x[3]) > SET_PP or float(x[4]) > SET_PP or float(x[5]) > SET_PP:
lst.append(x[0])
else: # other models
if float(x[3]) > SET_PP or float(x[4]) > SET_PP:
lst.append(x[0])
else:
flag = 0
return(lst)
def initialize_lsts():
lst1 = [] # vector of original multiple counts in each simulation
ad_lst = []
inad_lst = []
return (lst1,ad_lst, inad_lst)
l = []
for i in range(1000):
l.append(str(i))
thresholds = pd.read_csv('/groups/itay_mayrose/annarice/model_adequacy/genera/thresholds.csv', sep=',')
with open(res_file , "w+") as writeFile:
header = ["Genus", "Best_model", "Error_measure", "Adequate", "Inadequate","len_ad","len_inad","mean_ad","mean_inad","T-stat","PV"]
writer = csv.writer(writeFile)
writer.writerow(header)
with open (filename, "r") as genera:
for genus in genera:
genus = genus.strip()
print(genus)
tested_model = d.get(genus)
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/result_sum"
best_model = get_best_model(results_sum)
wd = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + best_model + "/adequacy_test/"
wd2 = "/groups/itay_mayrose/annarice/model_adequacy/sanity/" + genus + "/" + best_model + "/adequacy_test/"
out_dir = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + tested_model + "/adequacy_test/"
targz_file = out_dir + "/zipped.tar.gz"
#print(out_dir)
if not os.path.isdir(out_dir + "0/"):
untargz(targz_file)
error_measure_lst = ["internal_nodes", "root_num", "total_dupl", "branch_dupl", "inference"]
try:
SET_PP = float(thresholds[thresholds['Genus'] == genus]["PP"])
except:
error_measure_lst = ["internal_nodes", "root_num", "inference"]
SET_PP = 0.51
for error_measure in error_measure_lst:
print(error_measure)
multiple_counts, adequate_diff, inadequate_diff = initialize_lsts()
for i in range(nsims):
if error_measure == "root_num" or error_measure == "internal_nodes":
measure_fullpath = wd + str(i) + orig_numbers_filename
if error_measure == "total_dupl" or error_measure == "branch_dupl" or error_measure == "inference":
#SET_PP = get_threshold("/groups/itay_mayrose/michaldrori/MSA_JmodelTree/output_MD/" + genus + "/" + genus + "_Chromevol_prune/chromevol_out/thresholds_PP") # outer function that fetches the genus' threshold
measure_fullpath = wd + str(i) + orig_dupl_filename
orig_num = get_measure(measure_fullpath,"orig")
#print("orig***** " + str(orig_num))
model = best_model
#print(models)
#for model in models:
for x in range(1):
if error_measure == "root_num" or error_measure == "internal_nodes":
inferred_fullpath = wd2 + str(i) + "/" + model + inferred_numbers_filename
if error_measure == "total_dupl" or error_measure == "branch_dupl" or error_measure == "inference":
inferred_fullpath = wd2 + str(i) + "/" + model + inferred_expec_filename
inferred_num = get_measure(inferred_fullpath, "inferred")
#print("inferred * " + str(inferred_num))
adequacy_filename = wd2 + str(i) + "/" + model + "/adequacy_test/adequacy_vec"
with open (adequacy_filename,"r") as adequacy_f:
tmp = adequacy_f.readline()
# remove range and unique counts statistics
tmp = tmp[1:-1]
tmp = tmp.split(", ")
#if re.search("0",tmp):
if tmp[2]=="0" or tmp[3]=="0": # inadequate model
if error_measure == "internal_nodes": # difference between two lists
tmp_lst = [abs(x1 - x2) for (x1, x2) in zip(orig_num, inferred_num)]
tmp_lst = sum(tmp_lst)
inadequate_diff.append(tmp_lst)
elif error_measure == "branch_dupl" or error_measure == "inference":
tmp_lst = set(orig_num).symmetric_difference(set(inferred_num))
inadequate_diff.append(len(tmp_lst))
else: # single measure
inadequate_diff.append(abs(orig_num-inferred_num))
else:
if error_measure == "internal_nodes": # difference between two lists
tmp_lst = [abs(x1 - x2) for (x1, x2) in zip(orig_num, inferred_num)]
tmp_lst = sum(tmp_lst)
adequate_diff.append(tmp_lst)
elif error_measure == "branch_dupl" or error_measure == "inference":
tmp_lst = set(orig_num).symmetric_difference(set(inferred_num))
adequate_diff.append(len(tmp_lst))
else: # single measure
adequate_diff.append(abs(orig_num-inferred_num))
#print("***** " + genus + ", " + error_measure + " *****")
#print ("Adequate list differences" + str(adequate_diff))
#print ("Inadequate list differences" + str(inadequate_diff))
if len(adequate_diff)==0 or len(inadequate_diff)==0:
if len(adequate_diff)==0:
row = [genus, best_model, error_measure, adequate_diff, inadequate_diff, len(adequate_diff),
len(inadequate_diff), "NA",
str(round(average(inadequate_diff), 2)), "NA", "NA"]
else:
row = [genus, best_model, error_measure, adequate_diff, inadequate_diff, len(adequate_diff),
len(inadequate_diff), str(round(average(adequate_diff), 2)),
"NA", "NA", "NA"]
#print ("Adequate diff " + str(round(average(adequate_diff),2)))
#print ("Inadequate diff " + str(round(average(inadequate_diff),2)))
else:
t_stat, p_val = stats.ttest_ind(adequate_diff,inadequate_diff,equal_var = False)
row = [genus, best_model, error_measure, adequate_diff, inadequate_diff, len(adequate_diff),len(inadequate_diff), str(round(average(adequate_diff), 2)),str(round(average(inadequate_diff), 2)), str(round(t_stat, 2)), str(round(p_val, 2))]
#print("statistic: " + str(round(t_stat,2)))
#print("pv: " + str(round(p_val, 2)))
#row = [genus, best_model, error_measure, adequate_diff, inadequate_diff,len(adequate_diff),len(inadequate_diff),str(round(average(adequate_diff),2)),str(round(average(inadequate_diff),2)),str(round(t_stat,2)),str(round(p_val, 2))]
writer.writerow(row)
targz_dir(out_dir, l, "zipped.tar.gz", True)<file_sep>/summarize_best_models_statistics.py
import csv
import regex as re
from data_processing import best_model
from data_processing import process_data
from defs import *
import argparse
from utils import *
parser = argparse.ArgumentParser(description="Summerize best_model results of statistics and true percentiles")
parser.add_argument('--genera', '-f', help='Genera file',required=True)
parser.add_argument('--summary', '-s', help='output file',required=True)
models = ["CONST_RATE","CONST_RATE_DEMI","CONST_RATE_DEMI_EST","CONST_RATE_NO_DUPL","BASE_NUM","BASE_NUM_DUPL"]
wanted_keys = ["_lossConstR","_gainConstR","_duplConstR","_demiPloidyR","_baseNumberR","_simulationsTreeLength"]
args = parser.parse_args()
genera_file = args.genera
summary_file = args.summary
with open(summary_file, "w+") as writeFile:
header = ["Genus", "Best_model","Variance","Entropy","Range","Unique","Parsimony","Time","Loss","Gain","Dupl","Demi","BaseR","tree_length",
"variance_perc","entropy_perc","range_perc","unique_perc","fitch_perc","time_perc"]
writer = csv.writer(writeFile)
writer.writerow(header)
with open (genera_file,"r") as genera:
for genus in genera:
genus = genus.strip()
results_sum = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/result_sum"
models = best_model.get_best_model(results_sum)
models = models.split(",") # returns a list
for model in models:
path = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + model + "/"
flag_file = path + "adequacy_test/NO_NEED_FOR_MA"
if os.path.isfile(flag_file):
continue
CE_res = path + "/chromEvol.res"
root_freq = path + "/root_freq"
percentiles = path + "adequacy_test/true_percentiles"
count_file = "/groups/itay_mayrose/annarice/model_adequacy/genera/" + genus + "/" + genus + ".counts_edit"
parameters_dictionary = best_model.get_params(CE_res, root_freq)
adequacy_filename = path + "adequacy_test/adequacy_vec"
row = [genus, model]
try:
with open(adequacy_filename, "r") as adequacy_f:
tmp = adequacy_f.readline()
row.extend(str_to_lst(tmp,"int"))
for key in wanted_keys:
row.append(parameters_dictionary.get(key, 0))
with open(percentiles, "r") as perc:
res = perc.read()
row.extend(str_to_lst(res, "float"))
writer.writerow(row)
except:
print("No result for " + genus)
continue<file_sep>/data_processing/simulations.py
import sys
sys.path.append("../")
from defs import *
from data_processing import best_model
def initialize_defaults(output_dir,max_for_sim,nsims,tree_full_path):
d = {}
d["_mainType"] = "mainSimulate"
d["_outDir"] = output_dir
d["_treeFile"] = tree_full_path
d["_simulationsJumpsStats"] = "expStats.txt"
if nsims > 0:
d["_simulationsIter"] = nsims
else:
d["_simulationsIter"] = 100
d["_maxChrNumForSimulations"] = max_for_sim
d["_simulationsTreeLength"] = 4
d["_branchMul"] = 1
return d
def parse_params_from_res_file(d,paramFile,freqFile,expFile, mlAncTree,model_name,orig_counts): # paramFile is where the parameters are found (e.g., CE results file)
parameters_dictionary = best_model.get_params(paramFile,freqFile)
d["_freqFile"] = freqFile
if parameters_dictionary.get("_baseNumber",0)!=0: # a base number model
#d["_baseTransitionProbs"] = create_bntpv(expFile, mlAncTree, parameters_dictionary["_baseNumber"])
#d["_maxBaseTransition"] = max(orig_counts) - min(orig_counts)
d["_maxBaseTransition"] = max(max(orig_counts) - min(orig_counts), parameters_dictionary.get("_baseNumber"))
if model_name=="CONST_RATE_DEMI":
d["_demiPloidyR"] = parameters_dictionary.get("_duplConstR",0)
d.update(parameters_dictionary)
return d
def create_control_file(filename, working_dir,output_dir,max_for_sim,nsims,model_name,tree_full_path,orig_counts):
# 1. d = initialize (outDir, main_res_dir + model_name + expectation_file, main_res_dir + model_name + mlAncTree)
# 2. parse res file OR receive parameters from user (d, model_name)
d = initialize_defaults(output_dir,max_for_sim,nsims,tree_full_path)
d = parse_params_from_res_file(d,working_dir + CE_res_filename,working_dir + root_freq_filename,working_dir + expectation_file, working_dir + mlAncTree,model_name,orig_counts)
with open(filename, "w+") as control_file:
for key in d.keys():
control_file.write(key + " " + str(d[key]))
control_file.write("\n")
def run_MA(main_res_dir,filename,working_dir,output_dir,orig_counts,model_name,nsims,tree_full_path,CE_path): #run_MA(output_dir + sim_control,main_res_dir + model, output_dir,original_counts)
real_max = max(orig_counts)
init_max_for_sim = max(real_max, min(real_max*10,200))
# get max chr allowed
with open(main_res_dir + CE_res_filename,"r") as res_file:
for line in res_file:
line = line.strip()
tmp = re.search("max chromosome allowed: (\d+)", line)
if tmp:
max_allowed = int(tmp.group(1))
break
for mult in range(10): # x is the factor by which we increase the previous _maxChrNumForSimulations
max_for_sim = 100 * mult + init_max_for_sim
if (max_for_sim < max_allowed):
max_for_sim = max_allowed
create_control_file(filename, working_dir, output_dir, max_for_sim,nsims,model_name,tree_full_path,orig_counts)
os.system('"' + CE_path + '" ' + filename)
cmd = "grep -R --include='simEvents.txt' 'Total number of transitions to max chromosome: [^0]' " + output_dir
tmp = os.system(cmd)
f = open(working_dir + "/increasing_max_chr.txt", "w")
f.write("Iteration number " + str(mult) + ", Max number is currently " + str(max_for_sim))
f.close()
if tmp != 0: # did not hit upper bound
break # no need to keep increasing the max number
return(max_for_sim)
#----------------------------------------------------------------------------------------------------------#
# creates the base number transitions probability vector for simulations
def create_bntpv(expFile, mlAncTree, baseNum,model_name):
with open(expFile,'r') as expFile_f:
perNode_EXPECTATIONS_lines=[]
look_for_end=0
for line in expFile_f:
if "#ALL EVENTS EXPECTATIONS PER NODE" in line and look_for_end == 0:
look_for_end = 1 #stop when you find the next #+++++++++++++++++++++++++++++ line
if look_for_end == 1 and "#++++++++++++++++++++++++" in line:
print("Done copy evenets lines !!!")
break
if look_for_end == 1:
if "#ALL EVENTS EXPECTATIONS PER NODE" not in line and "BASE-NUMBER" not in line:
perNode_EXPECTATIONS_lines.append(line.strip())
expFile_f.close()
btnodes=dict()
if DEBUG_FLAG == 1: print("create_bntpv model is: %s\n" %model_name)
if model_name == 'BASE_NUM':
for item in perNode_EXPECTATIONS_lines:
item_split = item.split()
node = item_split[0]
dupl_weight = float(item_split[3]) # Correction Oct 2019 (if Dupl is 1 then auto we set Base num to 1)
weight = float(item_split[5])
if weight > 0.1 or dupl_weight > 0.5:
if dupl_weight > 0.5:
weight = dupl_weight
elif weight > 1:
weight = 1
btnodes[node] = weight
if not btnodes: # if for some reason there are no base transition events
if DEBUG_FLAG == 1: print("btnodes is empty so vector is %d=1.00" % baseNum)
return "%d=1.00" % baseNum
elif model_name == 'BASE_NUM_DUPL':
for item in perNode_EXPECTATIONS_lines:
item_split = item.split()
node = item_split[0]
weight = float(item_split[5])
if weight > 0.1:
if weight > 1:
weight = 1
btnodes[node] = weight
if not btnodes: # if for some reason there are no base transition events
if DEBUG_FLAG == 1: print("btnodes is empty so vector is %d=1.00"%baseNum )
return "%d=1.00"%baseNum
if DEBUG_FLAG == 1:
print("btnodes[node_name] printout:\n")
for node_name in btnodes.keys():
print("Node: %s, weight: %.2f\n" % (node_name,btnodes[node_name]))
### for each node, find the base transition
transitions = dict() # will contain all transitions found in data (value is # of times transition was found)
tree_test=Tree(mlAncTree, format=1)
for node in tree_test.traverse("postorder"):
nodeid = re.search("\[?([^\-]+)-([^\]]+)\]?", node.name)
nodeName = nodeid.group(1)
if nodeid.group(2) is not 'x' and nodeid.group(2) is not 'X':
nodeCount = int(nodeid.group(2))
else:
nodeCount = nodeid.group(2)
# if node has base num transition
if nodeName in btnodes.keys():
ancestor = node.up
ancestorid = re.search("\[?([^\-]+)-([^\]]+)\]?", ancestor.name)
ancestorName = ancestorid.group(1)
if ancestorid.group(2) is not 'x' and ancestorid.group(2) is not 'X':
ancestorCount = int(ancestorid.group(2))
else:
ancestorCount = ancestorid.group(2)
# if both node and parent have counts
if nodeCount is not 'x' and nodeCount is not 'X' and ancestorCount is not 'x' and ancestorCount is not 'X':
#Need to add the posibility of probabilities vector !!!
transition = nodeCount - ancestorCount # may include gains\losses
realTrans = round(transition /baseNum) * baseNum
# add transition to hash
if realTrans > 0:
if realTrans in transitions.keys():
transitions[realTrans] += btnodes[nodeName]
else:
transitions[realTrans] = btnodes[nodeName]
else:
btnodes[nodeName] = "NA"
# in case no transitions were found, give transition by base number prob of 1
if not transitions:
transitions[baseNum] = 1.00
### calculate probabilities
allTransitions = list(transitions.values())
totalTrans = sum(allTransitions)
# remove rare transitions (less then 0.05)
transitions_copy = transitions.copy()
for key in transitions.keys():
if (transitions[key]/totalTrans < 0.05):
del transitions_copy[key]
#copy the edited dictionary back to the original one:
transitions = transitions_copy.copy()
# create final probs hash
probsHash=dict()
for key in transitions.keys():
res=float(transitions[key]/totalTrans)
finalProb = "%.2f" %res # limited to 2 decimal digits
probsHash[key] = float(finalProb)
# make sure probs sum to 1
allProbs = list(probsHash.values())
probSum = sum(allProbs)
diff = 1-probSum
if diff != 0:
# complete or substract to 1 on a random prob
transitions = list(probsHash.keys())
randTrans = transitions[0]
probsHash[randTrans] += diff
# create probs vector
vector = ""
for key in probsHash.keys():
vector+= str(key) + '=' + str(probsHash[key]) + '_'
vector = vector[:-1]
return vector
|
3f2cd75d685164c973bfbed60bcf14d85ca0e005
|
[
"Python",
"R"
] | 29
|
Python
|
annarice/model_adequacy_dev
|
a013987c4ffd6712e0dd9d2796a5bd4e0cceb568
|
da2150581c2c4704d3ff837b314233e272723ee8
|
refs/heads/develop
|
<file_sep>package com.reo.running.mvvm_training
data class Message(var thanksMessage: String = "")<file_sep># -Voluntary_Training_MVVM
MVVMの学習用です
<file_sep>package com.reo.running.mvvm_training
import androidx.databinding.ObservableField
class MainViewModel {
var message = ObservableField("thanks")
fun buttonClicked() {
message.set("thanks a lot")
}
}
|
e97cb1d8ec8152eac77cb463b021051426da9d4d
|
[
"Markdown",
"Kotlin"
] | 3
|
Kotlin
|
lion-king-IT/-Voluntary_Training_MVVM
|
97419a6577cf35e21a2191e888cd438d09ac25d2
|
5e2cd5cc117ddcd40125eb10ad0e8de8c44e7478
|
refs/heads/master
|
<file_sep>// maintAct.ts
// maintAct page for manipulating data
import { Component, OnInit } from '@angular/core';
import { ActivesService } from '../services/actives.service';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'maintAct-cmp',
templateUrl: 'maintAct.html'
})
export class MaintActComponent {
actives: any = [];
active: any = '';
selectedActive: any = '';
deletedActive: any = '';
constructor(private activesService: ActivesService, private router: Router){
}
// on load of page
ngOnInit() {
this.activesService.getActives().subscribe(data => {
this.actives = data.objects;
});
}
// opens edit actives modal
openEditActiveModal(active: any){
this.selectedActive = active;
$('#editActiveModal').modal("show");
}
// opens delete active modal
openDeleteActiveModal(active: any){
this.deletedActive = active;
$('#deleteActiveModal').modal("show");
}
// actions for edit active submission
onEditSubmit(value: any){
this.activesService.updateActive(value).subscribe(data => {
$('#editActiveModal').modal("hide");
// this.router.navigateByUrl('menu'); //may need later
});
}
//actions for closing edit active modal without saving
closeEditActiveModal(){
// this.router.navigateByUrl('/menu'); //may need later
$('#editActiveModal').modal("hide");
window.location.reload();
}
//actions for delete active modal
deleteActive(value: any){
this.activesService.deleteActive(value).subscribe(data => {
console.log(data);
$('#deleteActiveModal').modal("hide");
window.location.reload();
// this.router.navigateByUrl('menu');
});
}
}<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// signup.form.ts
//The form structure for adding an user
var SignupForm = (function () {
function SignupForm(name, email, username, password) {
this.name = name;
this.email = email;
this.username = username;
this.password = <PASSWORD>;
}
return SignupForm;
}());
exports.SignupForm = SignupForm;
<file_sep>// login.ts
// Page for the admin to login
import { Component, OnInit } from '@angular/core';
import { LoginForm } from './login.form';
import { UsersService } from '../services/users.service';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'login-cmp',
templateUrl: 'login.html'
})
export class LoginComponent {
constructor(
private usersService: UsersService,
private authService: AuthService,
private router: Router ){
this.usersService.getUsers().subscribe(users => {
console.log(users);
});
}
user = new LoginForm('', '');
//Actions upon submission
onSubmit(value: any){
this.authService.authenticate(value).subscribe(data => {
if(data = 'Success'){
console.log(value.login);
this.usersService.getId(value.login).subscribe(id => {
localStorage.setItem('userId', id.id);
localStorage.setItem('userName', id.name);
localStorage.setItem('userEmail', id.email);
localStorage.setItem('userUsername', id.username);
console.log(id);
});
this.router.navigateByUrl('profile'); //redirect to the profile page in success case
}
});
}
}<file_sep>// signup.ts
//The add user page
import { Component } from '@angular/core';
import { SignupForm } from './signup.form';
import { UsersService } from '../services/users.service';
@Component({
moduleId: module.id,
selector: 'signup-cmp',
templateUrl: 'signup.html'
})
export class SignupComponent {
constructor(private usersService: UsersService){
this.usersService.getUsers().subscribe(users => {
console.log(users);
});
}
user = new SignupForm('', '', '', '');
// actions upon submission of the form
onSubmit(value: any){
console.log(value);
this.usersService.addUser(value).subscribe(data => {
console.log(data);
$('#signup').modal("hide");
});
}
}<file_sep>// home.ts
// User page
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'home-cmp',
templateUrl: 'home.html'
})
export class HomeComponent implements OnInit {
ngOnInit() {
}
}
<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var deleteGameModalForm = (function () {
function deleteGameModalForm(date, opponent, location, spursscore, oppscore) {
this.date = date;
this.opponent = opponent;
this.location = location;
this.spursscore = spursscore;
this.oppscore = oppscore;
}
return deleteGameModalForm;
}());
exports.deleteGameModalForm = deleteGameModalForm;
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
backend.api.v1.endpoints
~~~~~~~~~~~~~~~~~~~~~~~~
This module implements the REST API v1 endpoints of this application.
"""
from backend import restless
from backend.api.v1 import URL
from backend.models import User, Vehicle, Active
# ENDPOINT: /api/v1/users
restless.create_api(User, methods = ['GET', 'POST', 'DELETE', 'PUT'],
url_prefix = URL,
collection_name = 'users',
results_per_page = 0)
# ENDPOINT: /api/v1/vehicles
restless.create_api(Vehicle, methods = ['GET', 'POST', 'DELETE', 'PUT'],
url_prefix = URL,
collection_name = 'vehicles',
results_per_page = 0)
# ENDPOINT: /api/v1/actives
restless.create_api(Active, methods = ['GET', 'POST', 'DELETE', 'PUT'],
url_prefix = URL,
collection_name = 'actives',
results_per_page = 0)<file_sep>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var games_service_1 = require("../services/games.service");
var editGameModalComponent = (function () {
function editGameModalComponent(gamesService) {
this.gamesService = gamesService;
this.submitted = false;
}
editGameModalComponent.prototype.onSubmit = function (value) {
this.submitted = true;
this.gamesService.updateGame(value).subscribe(function (data) {
$('#editGameModal').modal("hide");
//window.location.reload();
// this.router.navigateByUrl('menu');
});
};
editGameModalComponent.prototype.closeEditGameModal = function () {
$('#editGameModal').modal("hide");
// window.location.reload();
};
return editGameModalComponent;
}());
__decorate([
core_1.Input(),
__metadata("design:type", Object)
], editGameModalComponent.prototype, "game", void 0);
editGameModalComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'editGameModal-cmp',
templateUrl: 'editGameModal.html'
}),
__metadata("design:paramtypes", [games_service_1.GamesService])
], editGameModalComponent);
exports.editGameModalComponent = editGameModalComponent;
<file_sep>//navbar3.ts
//The navbar for the login page
import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'navbar3-cmp',
templateUrl: 'navbar3.html'
})
export class navbar3Component {
}
<file_sep>// addVehicleModal.form.ts
export class addVehicleModalForm {
constructor(
public make: string,
public model: string,
public year: number,
public color: string,
public pdriver: string,
public nickname: string
) { }
}<file_sep>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// menu.ts
// menu page for manipulating data
var core_1 = require("@angular/core");
var games_service_1 = require("../services/games.service");
var router_1 = require("@angular/router");
var MenuComponent = (function () {
function MenuComponent(gamesService, router) {
this.gamesService = gamesService;
this.router = router;
this.games = [];
this.game = '';
this.selectedGame = '';
this.deletedGame = '';
}
// on load of page
MenuComponent.prototype.ngOnInit = function () {
var _this = this;
this.gamesService.getGames().subscribe(function (data) {
_this.games = data.objects;
});
};
// opens edit game modal
MenuComponent.prototype.openEditGameModal = function (game) {
this.selectedGame = game;
$('#editGameModal').modal("show");
};
// opens delete gmae modal
MenuComponent.prototype.openDeleteGameModal = function (game) {
this.deletedGame = game;
$('#deleteGameModal').modal("show");
};
// actions for edit game submission
MenuComponent.prototype.onEditSubmit = function (value) {
this.gamesService.updateGame(value).subscribe(function (data) {
$('#editGameModal').modal("hide");
// this.router.navigateByUrl('menu'); //may need later
});
};
//actions for closing edit game modal without saving
MenuComponent.prototype.closeEditGameModal = function () {
// this.router.navigateByUrl('/menu'); //may need later
$('#editGameModal').modal("hide");
window.location.reload();
};
//actions for delete game modal
MenuComponent.prototype.deleteGame = function (value) {
this.gamesService.deleteGame(value).subscribe(function (data) {
console.log(data);
$('#deleteGameModal').modal("hide");
window.location.reload();
// this.router.navigateByUrl('menu');
});
};
return MenuComponent;
}());
MenuComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'menu-cmp',
templateUrl: 'menu.html'
}),
__metadata("design:paramtypes", [games_service_1.GamesService, router_1.Router])
], MenuComponent);
exports.MenuComponent = MenuComponent;
<file_sep>// actives.services.ts
//The service to manipulate actives in the database
import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ActivesService {
url: string = '/api/v1/actives'; //so only one change needs to be made if modified
constructor(private http: Http){
}
//Requests all of the actives in the database
getActives(){
return this.http.get(this.url).map(res => res.json());
}
//requests a single active in the database
getActive(id: any){
return this.http.get(this.url + "/" + id).map(res => res.json());
}
//adds a active to the database
addActive(value: any){
console.log(value + "in services");
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.post(this.url, valueString, options).map(res => res.json());
}
//deletes a active from the database
deleteActive(value: any){
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.delete(this.url + "/" + value, options).map(res => res.json());
}
//updates a active from the database
updateActive(value: any){
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.put(this.url + "/" + value.id, valueString, options).map(res => res.json());
}
}<file_sep>//navbar2.ts
//The navbar for the admin
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'navbar2-cmp',
templateUrl: 'navbar2.html'
})
export class navbar2Component {
// opens onLogout
onLogout(){
localStorage.clear();
}
}
<file_sep>// login.form.ts
//login form structure
export class LoginForm {
constructor(
public login: string,
public password: string
) { }
}<file_sep>// profile.ts
// profile page for manipulating data
import { Component, OnInit } from '@angular/core';
import { VehiclesService } from '../services/vehicles.service';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
selector: 'profile-cmp',
templateUrl: 'profile.html'
})
export class ProfileComponent {
vehicles: any = [];
vehicle: any = '';
selectedVehicle: any = '';
deletedVehicle: any = '';
constructor(private vehiclesService: VehiclesService, private router: Router){
}
// on load of page
ngOnInit() {
this.vehiclesService.getVehicles().subscribe(data => {
this.vehicles = data.objects;
});
}
// opens edit vehicle modal
openEditVehicleModal(vehicle: any){
this.selectedVehicle = vehicle;
$('#editVehicleModal').modal("show");
}
// opens delete vehicle modal
openDeleteVehicleModal(vehicle: any){
this.deletedVehicle = vehicle;
$('#deleteVehicleModal').modal("show");
}
// actions for edit vehicle submission
onEditSubmit(value: any){
this.vehiclesService.updateVehicle(value).subscribe(data => {
$('#editVehicleModal').modal("hide");
// this.router.navigateByUrl('menu'); //may need later
});
}
//actions for closing edit vehicle modal without saving
closeEditVehicleModal(){
// this.router.navigateByUrl('/menu'); //may need later
$('#editVehicleModal').modal("hide");
window.location.reload();
}
//actions for delete vehicle modal
deleteVehicle(value: any){
this.vehiclesService.deleteVehicle(value).subscribe(data => {
console.log(data);
$('#deleteVehicleModal').modal("hide");
window.location.reload();
// this.router.navigateByUrl('menu');
});
}
}<file_sep>// addActiveModal.form.ts
export class addActiveModalForm {
constructor(
public mtype: string,
public date: string,
public mechanic: string
) { }
}<file_sep>from flask import request, make_response, jsonify
from backend import app
from backend.api.v1 import URL
from backend.models import User
# @app.route(URL + '/<user>', methods=['GET'])
# def getId(user):
# app.logger.info(login)
# #user = User.query.filter_by(username=login).first()
# # user = User.query.filter_by(username=username).first()
# app.logger.info(username)
# # if username:
# # return user.id
@app.route(URL + '/<user>', methods=['GET'])
def getId(user):
user = User.query.filter_by(username=user).first()
jsonUser = {}
jsonUser['id'] = user.id
jsonUser['name'] = user.name
jsonUser['email'] = user.email
jsonUser['username'] = user.username
return make_response(jsonify(jsonUser), 200)<file_sep>// addVehicleModal.ts
// add a vehicle to the database
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { addVehicleModalForm } from './addVehicleModal.form';
import { VehiclesService } from '../services/vehicles.service';
import { UsersService } from '../services/users.service';
@Component({
moduleId: module.id,
selector: 'addVehicleModal-cmp',
templateUrl: 'addVehicleModal.html'
})
export class addVehicleModalComponent {
constructor(private vehiclesService: VehiclesService, private router: Router){
}
vehicle = new addVehicleModalForm('', '', 0, '', '', '');
// Actions for form submission
onSubmit(value: any){
console.log(value); //for troubleshooting purposes
this.vehiclesService.addVehicle(value).subscribe(data => {
console.log(data); //for troubleshooting purposes
$('#addVehicleModal').modal("hide"); //hides modal
window.location.reload();
// this.router.navigateByUrl('menu'); // may need later
});
}
}<file_sep>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// actives.services.ts
//The service to manipulate actives in the database
var core_1 = require("@angular/core");
var http_1 = require("@angular/http");
require("rxjs/add/operator/map");
var ActivesService = (function () {
function ActivesService(http) {
this.http = http;
this.url = '/api/v1/actives'; //so only one change needs to be made if modified
}
//Requests all of the actives in the database
ActivesService.prototype.getActives = function () {
return this.http.get(this.url).map(function (res) { return res.json(); });
};
//requests a single active in the database
ActivesService.prototype.getActive = function (id) {
return this.http.get(this.url + "/" + id).map(function (res) { return res.json(); });
};
//adds a active to the database
ActivesService.prototype.addActive = function (value) {
console.log(value + "in services");
var valueString = JSON.stringify(value);
var header = new http_1.Headers({ 'Content-Type': 'application/json' });
var options = new http_1.RequestOptions({ headers: header });
return this.http.post(this.url, valueString, options).map(function (res) { return res.json(); });
};
//deletes a active from the database
ActivesService.prototype.deleteActive = function (value) {
var header = new http_1.Headers({ 'Content-Type': 'application/json' });
var options = new http_1.RequestOptions({ headers: header });
return this.http.delete(this.url + "/" + value, options).map(function (res) { return res.json(); });
};
//updates a active from the database
ActivesService.prototype.updateActive = function (value) {
var valueString = JSON.stringify(value);
var header = new http_1.Headers({ 'Content-Type': 'application/json' });
var options = new http_1.RequestOptions({ headers: header });
return this.http.put(this.url + "/" + value.id, valueString, options).map(function (res) { return res.json(); });
};
return ActivesService;
}());
ActivesService = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [http_1.Http])
], ActivesService);
exports.ActivesService = ActivesService;
<file_sep>// vehicles.services.ts
//The service to manipulate vehicles in the database
import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class VehiclesService {
url: string = '/api/v1/vehicles'; //so only one change needs to be made if modified
constructor(private http: Http){
}
//Requests all of the vehicles in the database
getVehicles(){
return this.http.get(this.url).map(res => res.json());
}
//requests a single vehicle in the database
getVehicle(id: any){
return this.http.get(this.url + "/" + id).map(res => res.json());
}
//adds a vehicle to the database
addVehicle(value: any){
console.log(value + "in services");
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.post(this.url, valueString, options).map(res => res.json());
}
//deletes a vehicle from the database
deleteVehicle(value: any){
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.delete(this.url + "/" + value, options).map(res => res.json());
}
//updates a vehicle from the database
updateVehicle(value: any){
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.put(this.url + "/" + value.id, valueString, options).map(res => res.json());
}
}<file_sep>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// addgameModal.ts
// add a game to the database
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var addGameModal_form_1 = require("./addGameModal.form");
var games_service_1 = require("../services/games.service");
var addGameModalComponent = (function () {
function addGameModalComponent(gamesService, router) {
this.gamesService = gamesService;
this.router = router;
this.game = new addGameModal_form_1.addGameModalForm('', '', '', 0, 0);
}
// Actions for form submission
addGameModalComponent.prototype.onSubmit = function (value) {
this.gamesService.addGame(value).subscribe(function (data) {
console.log(data); //for troubleshooting purposes
$('#addGameModal').modal("hide"); //hides modal
window.location.reload();
// this.router.navigateByUrl('menu'); // may need later
});
};
return addGameModalComponent;
}());
addGameModalComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'addGameModal-cmp',
templateUrl: 'addGameModal.html'
}),
__metadata("design:paramtypes", [games_service_1.GamesService, router_1.Router])
], addGameModalComponent);
exports.addGameModalComponent = addGameModalComponent;
<file_sep>// auth.services.ts
//The service for authenticating the username and password for logging in
import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
url: string = '/api/v1/auth'; //so only one change needs to be made if modified
constructor(private http: Http){
}
authenticate(value: any){
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
console.log(valueString); //for troubleshooting purposes
return this.http.post(this.url, valueString, options).map(res => res.json());
}
}<file_sep>//users.service.ts
//The service to manipulate users in the database
import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UsersService {
url: string = '/api/v1/users'; //so only one change needs to be made if modified
constructor(private http: Http){
}
//requests all the users in the database
getUsers(){
return this.http.get(this.url).map(res => res.json());
}
//requests a singular user in the database
getUser(id: any){
return this.http.get(this.url + "/" + id).map(res => res.json());
}
//adds a user to the database
addUser(value: any) {
let valueString = JSON.stringify(value);
let header = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: header });
return this.http.post(this.url, valueString, options).map(res => res.json());
}
//requests the id for a singular user in the database
getId(username: any){
return this.http.get("api/v1/" + username).map(res => res.json());
}
}<file_sep>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// addVehicleModal.ts
// add a vehicle to the database
var core_1 = require("@angular/core");
var router_1 = require("@angular/router");
var addVehicleModal_form_1 = require("./addVehicleModal.form");
var vehicles_service_1 = require("../services/vehicles.service");
var addVehicleModalComponent = (function () {
function addVehicleModalComponent(vehiclesService, router) {
this.vehiclesService = vehiclesService;
this.router = router;
this.vehicle = new addVehicleModal_form_1.addVehicleModalForm('', '', 0, '', '', '');
}
// Actions for form submission
addVehicleModalComponent.prototype.onSubmit = function (value) {
console.log(value); //for troubleshooting purposes
this.vehiclesService.addVehicle(value).subscribe(function (data) {
console.log(data); //for troubleshooting purposes
$('#addVehicleModal').modal("hide"); //hides modal
window.location.reload();
// this.router.navigateByUrl('menu'); // may need later
});
};
return addVehicleModalComponent;
}());
addVehicleModalComponent = __decorate([
core_1.Component({
moduleId: module.id,
selector: 'addVehicleModal-cmp',
templateUrl: 'addVehicleModal.html'
}),
__metadata("design:paramtypes", [vehicles_service_1.VehiclesService, router_1.Router])
], addVehicleModalComponent);
exports.addVehicleModalComponent = addVehicleModalComponent;
<file_sep>// addActiveModal.ts
// add a active to the database
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { addActiveModalForm } from './addActiveModal.form';
import { VehiclesService } from '../services/vehicles.service';
import { UsersService } from '../services/users.service';
import { ActivesService } from '../services/actives.service';
@Component({
moduleId: module.id,
selector: 'addActiveModal-cmp',
templateUrl: 'addActiveModal.html'
})
export class addActiveModalComponent {
constructor(private activesService: ActivesService, private router: Router){
}
active = new addActiveModalForm('', '', '');
// Actions for form submission
onSubmit(value: any){
console.log(value); //for troubleshooting purposes
this.activesService.addActive(value).subscribe(data => {
console.log(data); //for troubleshooting purposes
$('#addActiveModal').modal("hide"); //hides modal
window.location.reload();
// this.router.navigateByUrl('menu'); // may need later
});
}
}<file_sep>// autotracker
import { NgModule, ApplicationRef, Input } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { AgmCoreModule } from 'angular2-google-maps/core';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home';
import { LoginComponent } from './login/login';
import { SignupComponent } from './signup/signup';
import { ProfileComponent } from './profile/profile';
import { MaintActComponent } from './maintAct/maintAct';
import { addVehicleModalComponent } from './addVehicleModal/addVehicleModal';
import { addActiveModalComponent } from './addActiveModal/addActiveModal';
import { navbarComponent } from './navbar/navbar';
import { navbar2Component } from './navbar2/navbar2';
import { navbar3Component } from './navbar3/navbar3';
import { UsersService } from './services/users.service';
import { AuthService } from './services/auth.service';
import { VehiclesService } from './services/vehicles.service';
import { ActivesService } from './services/actives.service';
// Routes to jump to
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'profile', component: ProfileComponent},
{ path: 'maintact', component: MaintActComponent }
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
HttpModule,
FormsModule,
AgmCoreModule.forRoot({
apiKey: '<KEY>'
// apiKey: '<KEY>'//old key
})
],
declarations: [
AppComponent,
HomeComponent,
LoginComponent,
SignupComponent,
ProfileComponent,
MaintActComponent,
addVehicleModalComponent,
addActiveModalComponent,
navbarComponent,
navbar2Component,
navbar3Component
],
providers: [
UsersService,
AuthService,
VehiclesService,
ActivesService
],
bootstrap: [ AppComponent ]
})
export class AppModule {}<file_sep>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// addVehicleModal.form.ts
var addVehicleModalForm = (function () {
function addVehicleModalForm(make, model, year, color, pdriver, nickname) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.pdriver = pdriver;
this.nickname = nickname;
}
return addVehicleModalForm;
}());
exports.addVehicleModalForm = addVehicleModalForm;
|
29fdd2623740e6784b9777c753403f8425994700
|
[
"JavaScript",
"Python",
"TypeScript"
] | 27
|
TypeScript
|
kberger03/autotracker
|
71aeab32b9b15fa2dc50778a81f10d66e5c5fa0a
|
17476da2d35228c25b90a94973bd3aa7ef2bb143
|
refs/heads/master
|
<file_sep>VERSION=2.1.14
<file_sep><?php
// Twitch authentication requires an oath token for logging in to the IRC chat. You can generate
// a token at: https://twitchapps.com/tmi/
// if you plan to use the Bot under a different username than your personal account, make sure that when you
// use the above tool and get redirected to Twitch to authenticate, you provide the dedicated Twitch account for the Bot.
// please check the README.md for more info.
$config['oath_pass'] = '<PASSWORD>';
//oauth:yx6wvzn4naamkpqp4jxs21bqkshp80
//identifiant client
//<KEY>
//secret
//<KEY>
// Fill in the username associated to the account you used to generate the oath token
// for the previous step.
$config['nickname'] = 'woolrick';
// Fill in the name of the Twitch Channel you want the Bot to connect to. You can use the name you see
// in the URL of your stream, for example if your stream is : https://www.twitch.tv/abc123, you need
// to fill in: abc123
$config['channel'] = 'woolrick';
// FIll in your Twitch App details. Needed for querying the Twitch API (find out if viewer is a channel's sub, change streams title, etc).
$config['app_client_id'] = 'zfqu70q1j0ilbqr448xx8c774zi3gl';
$config['app_client_secret'] = '<KEY>';
<file_sep><?php
// define your Computer's timezone. Accepted values can be found at: http://php.net/manual/en/timezones.php
$config['timezone'] = 'UTC';
// to configure the Bot to suppress any messages being sent out, set to TRUE:
$config['listen_only_mode'] = FALSE;
// bot essential commands definition:
$config['admin_addcommand_keyword'] = '!addcmd';
$config['admin_editcommand_keyword'] = '!editcmd';
$config['admin_removecommand_keyword'] = '!removecmd';
$config['admin_addadmin_keyword'] = '!addadmin';
$config['admin_removeadmin_keyword'] = '!removeadmin';
$config['helpcommand_keyword'] = '!help';
$config['uptimecommand_keyword'] = '!uptime';
$config['helpcommandbet_keyword'] = '!bethelp';
// reply format:
// set to
// 1: to reply to users command with @<username>
// 2: to reply to users command with <username>
// 3: to reply to users command without reference to the user who triggered the response.
$config['reply_format'] = 3;
// Twitch Oauth token scope: read more at: https://dev.twitch.tv/docs/authentication/#scopes
$config['oath_token_scope'] = 'chat_login+channel_editor+channel_check_subscription';
// periodic messages config:
$config['admin_addperiodicmsg_keyword'] = '!addperiodicmsg';
$config['admin_removeperiodicmsg_keyword'] = '!removeperiodicmsg';
// to enable the feature, set the threshold to a value greater than 0 seconds:
$config['periodic_messages_interval_seconds'] = 600;
// quotes config:
$config['admin_addquote_keyword'] = '!addquote';
$config['admin_removequote_keyword'] = '!removequote';
$config['quote_keyword'] = '!quote';
// giveaways config:
// for Admins:
$config['admin_giveaway_start_keyword'] = '!giveaway-start';
$config['admin_giveaway_stop_keyword'] = '!giveaway-end';
// $config['admin_giveaway_subs_start_keyword'] = '!giveaway-subs-start';
// $config['admin_giveaway_subs_stop_keyword'] = '!giveaway-subs-end';
$config['admin_giveaway_find_winner_keyword'] = '!giveaway-winner';
$config['admin_giveaway_status_keyword'] = '!giveaway-status';
$config['admin_giveaway_reset_keyword'] = '!giveaway-reset';
// for viewers to join:
$config['giveaway_join_keyword'] = '!giveaway';
// if you want to suppress Bot responses to same commands for a few seconds,
// set the desired thresh in seconds. If you want to disable this feature, set the value to 0 seconds.
$config['duplicate_message_cuttoff_seconds'] = 20;
// logging information:
// just how to name the log files
$config['log_file_prefix'] = 'ChocoboBot';
$config['log_file_prefix_IRC'] = 'ChocoboBot_IRC';
$config['log_file_prefix_TwitchAPI'] = 'ChocoboBot_TwitchAPI';
// The name that you want the bot to identify itself in your Twitch Chat.
$config['bot_name'] = 'ChocoboBot';
// Polls config:
//
$config['poll_help_message'] = '<poll\'s duration in minutes> <free text describing the poll>';
$config['admin_makepoll_keyword'] = '!poll-start';
$config['admin_cancelpoll_keyword'] = '!poll-cancel';
$config['votecommand_keyword'] = '!vote';
$config['new_poll_announcement_message'] = 'New poll is running';
$config['poll_closure_announcement_message'] = 'Poll was closed.';
$config['admin_poll_getwinner'] = '!poll-winner';
// Bets config:
//
$config['admin_startbet_keyword'] = '!startbet';
$config['admin_endbet_keyword'] = '!endbet';
$config['admin_cancelbet_keyword'] = '!cancelbet';
$config['bet_place_keyword'] = '!bet';
$config['bet_maximum_allowed_amount'] = 1000; // 0 for unlimited max amount
$config['betstart_announcement_message'] = 'Bet is open!';
$config['betend_announcement_message'] = 'Bet has ended.';
$config['bet_accept_period_over_announcement_message'] = 'Bet period is over, no more bets will be accepted.';
$config['bet_help_message'] = 'Betting work => !bet <Value to bet> <GP amount bet cost> |
Place a bet on value <Value to bet> for <GP amount bet cost> to win more GP points.
Example : !bet 41 150 where 41 is the order of Chocobo number 4 in first and 1 in second for 150 ChocoKWEH.
List of possible bet : 12 13 14 15 16 23 24 25 26 34 35 36 45 46 56';
// loyalty config:
//
// how many points a viewers is awarded per check interval. if you set it to 0, feature is disabled:
$config['loyalty_points_per_interval'] = 5;
$config['loyalty_currency'] = 'GP';
$config['loyalty_check_interval'] = 120; // in seconds
$config['loyalty_points_welcome_award'] = 1000; // amount of LP(Loyality point) => GP awarded to new viewers
$config['loyaltypoints_keyword'] = '!gp';
// twitch API related commands:
$config['admin_twitchapi_set_stream_title'] = '!title';
$config['admin_twitchapi_set_stream_game'] = '!game';
$config['admin_twitchapi_is_user_a_sub'] = '!issub';
// twitch VIP commands:
$config['admin_addvip_command'] = '!addvip';
$config['admin_removevip_command'] = '!removevip';
|
f6f78f80cc258632484d96f2cf3dd373afb90692
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
rmarcou/twitchbotbet
|
42bd9375b47bb10bf8b5e54b8fb44234527584d6
|
4035f000ef9c2c5d225170ef1ecc01134792f87f
|
refs/heads/master
|
<file_sep>public class hello01 {
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 100);
System.out.println("数组中的各个随机数是:"+ a[i] );
}
int b = a[0];
for (int i : a) {
// if (a[j] < b) b = a[j];
b = Math.min(b, i);
System.out.println("b值:" + b);
}
System.out.println("最小的一个值:"+ b );
}
}
<file_sep>import java.util.Arrays;
public class hello07 {
public static void main(String[] args) {
int a[][] = new int[5][8];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = (int) (Math.random() * 100);
System.out.print(a[i][j] + " ");
}
System.out.println();
int[] b = Arrays.copyOfRange(a[i], 0, 8);
Arrays.sort(b);
System.out.println(Arrays.toString(b));
}
}
}
<file_sep>public class hello02 {
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * 100);
System.out.println("数组中的各个随机数是:"+ a[i] );
}
reverse(a, a.length);
}
public static void reverse(int[] a, int n){
int[] b = new int[n];
int j = n;
for (int i = 0; i < n ; i++) {
b[j - 1]= a[i];
j--;
}
for (int k : b) {
System.out.println("反转数组中的各个随机数是:" + k);
}
}
}
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>Hello World</p>
<p>你好,世界!</p>
<h1>大标题</h1>
<h2>小一点的标题</h2>
<h3>再小一点的标题</h3>
<h4>更小一点的标题</h4>
<h1>标题1</h1>
<br/>
<br/>
<br/>
<h1>标题2前面有3个换行</h1>
<p>这是一个水平线,有渲染效果,但是没有文本内容</p>
<hr/>
<h1 >未设置居中的标题</h1>
<!--align属性用于对齐-->
<h1 align="center">居中标题</h1>
</body>
</html>
|
020fa4e746894e83dce86ba7465de060bbea6ac6
|
[
"Java",
"HTML"
] | 4
|
Java
|
daveme0816/how2j_basic
|
353ca2e1f99357fa29fdb75eaa68556823e04531
|
e6d47c5fb65e73d7294f8ed033b55d4e4b8ebe96
|
refs/heads/master
|
<repo_name>miloszrak/Insectify-Shop<file_sep>/src/components/Layout/Layout.style.jsx
import { makeStyles } from '@material-ui/core'
export default makeStyles(theme => ({
header: {
borderBottom: '2px solid black',
}
}))<file_sep>/src/components/pages/UnauthorizedRoots/UnauthorizedRoots.jsx
import React from 'react'
import { Route } from "react-router-dom"
import LoginForm from '../Login/LoginForm'
import RegisterForm from '../Register/RegisterForm'
import Home from '../Home'
function UnauthorizedRoots() {
return (
<div>
<Route exact path="/" component={Home}/>
<Route path="/login" component={LoginForm}/>
<Route path="/register" component={RegisterForm}/>
</div>
)
}
export default UnauthorizedRoots<file_sep>/src/App.jsx
import React, { useState } from 'react';
import useStyle from './App.style'
import Layout from './components/Layout'
import AuthContext from './services/Auth/AuthContext'
function App() {
const [user, setUser] = useState()
const classes = useStyle()
return (
<AuthContext.Provider value={{user, setUser}}>
<Layout/>
</AuthContext.Provider>
);
}
export default App;
<file_sep>/src/theme/theme.js
import { createMuiTheme } from '@material-ui/core/styles'
const theme = createMuiTheme({
/*
palette: {
primary: {
dark: '#0f0f0f',
light: '#FF0000',
main: '#1f1f1f',
contrastText: '#FFFFFF',
background: {
dark: '#0f0f0f',
light: '#999999',
main: '#1f1f1f',
},
},
text: {
primary: 'rgba(0, 255, 0, 0.87)',
secondary: 'red',
main: 'blue',
disabled: 'pink',
hint: 'yellow',
},
action: {
disabled: 'yellow',
active: 'yellow',
hover: 'yellow',
}
},
*/
})
export default theme<file_sep>/src/components/pages/Register/RegisterForm/RegisterForm.style.jsx
import { makeStyles } from '@material-ui/core'
export default makeStyles(theme => ({
background: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
minHeight: '100vh',
},
content: {
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
backgroundColor: 'lightgrey',
padding: '30px',
borderRadius: '8px',
},
input: {
margin: '10px',
}
}))<file_sep>/src/components/pages/AuthorizedRoots/index.js
export { default } from './AuthorizedRoots'<file_sep>/src/components/pages/Login/LoginForm/LoginForm.jsx
import React, { useState, useContext } from 'react'
import { TextField, Button, } from '@material-ui/core'
import useStyle from './LoginForm.style'
import http from '../../../../utils/http'
import AuthContext from '../../../../services/Auth/AuthContext'
function LoginForm() {
const {user, setUser} = useContext(AuthContext)
const classes = useStyle()
const [values, setValues] = useState({
email: '',
password: '',
})
function handleChange(event) {
setValues({
...values,
[event.target.name]: event.target.value,
})
}
async function submit(event) {
event.preventDefault()
console.log(user, setUser)
const result = await http.post('/login', values)
http.defaults.headers.common['Authorization'] = `Bearer ${result.token}`
if (Boolean(result.user)) {
//setUser(user)
setUser({
firstName: 'Bartosz',
lastName: 'Rak',
email: '<EMAIL>',
zipCode: '11-666',
})
}
}
return (
<div className={classes.background}>
<form className={classes.content}>
<TextField name="email" onChange={handleChange} className={classes.input} type="email" label="username"/>
<TextField name="password" onChange={handleChange} className={classes.input} type="password" label="password"/>
<Button onClick={submit} type="submit">Go!</Button>
</form>
</div>
)
}
export default LoginForm<file_sep>/src/components/Layout/Layout.jsx
import React, { useContext } from 'react'
import { BrowserRouter as Router, Link} from "react-router-dom"
import useStyle from './Layout.style'
import AuthContext from '../../services/Auth/AuthContext';
import AuthorizedRoots from '../pages/AuthorizedRoots'
import UnauthorizedRoots from '../pages/UnauthorizedRoots'
function Layout() {
const {user, setUser} = useContext(AuthContext)
const classes = useStyle()
return(
<Router>
<div className={classes.header}>
<ul>
<Link to="/">Home</Link>
<Link to="/login">Log In</Link>
<Link to="/register">Register</Link>
</ul>
</div>
<div>
{user ? (
<AuthorizedRoots/>
) : (
<UnauthorizedRoots/>
)}
</div>
</Router>
)
}
export default Layout
|
5f49b62706ed8aa73da5d8d2b82d2b1b348ba4cb
|
[
"JavaScript"
] | 8
|
JavaScript
|
miloszrak/Insectify-Shop
|
5182dd5bd5293c21b6e5d2909ddaad235c523611
|
9a4cefae1d436c4d3bc3d7758a73b741559a5abd
|
refs/heads/master
|
<repo_name>MoshiXu/Study<file_sep>/QuickSortAlgorithm.java
package com.in28minutes.spring.basics.springin5steps;
public class QuickSortAlgorithm implements SortAlgorithm{
/*
public int[] sort(int[] numbers) {
//quick sort
return numbers;
}
*/
public String sort(int[] numbers) {
//quick sort
return "QUICK";
}
}
<file_sep>/README.md
# ReactStudy
study how to React as a beginner
<file_sep>/BinarySearchImpl.java
package com.in28minutes.spring.basics.springin5steps;
public class BinarySearchImpl {
private SortAlgorithm sortAlgorithm;
public BinarySearchImpl(SortAlgorithm sortAlgorithm) {
super();
this.sortAlgorithm = sortAlgorithm;
}
public int binarySearch(int[]numbers,int numberToSearchFor) {
//BubbleSortAlgorithm bubbleSortAlgorithm=new BubbleSortAlgorithm();
//int[] sortedNumbers=sortAlgorithm.sort(numbers);
String sortedNumber=sortAlgorithm.sort(numbers);
//int[] sortedNumbers=bubbleSortAlgorithm.sort(numbers);
System.out.print(sortAlgorithm);
//search the array
return 3;
//quick sort
}
}
<file_sep>/SpringIn5StepsApplication.java
package com.in28minutes.spring.basics.springin5steps;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringIn5StepsApplication {
public static void main(String[] args) {
BinarySearchImpl binarySearch=new BinarySearchImpl(new QuickSortAlgorithm());
int result=binarySearch.binarySearch(new int[] {12, 4,6},3);
System.out.println("\n"+result);
SpringApplication.run(SpringIn5StepsApplication.class, args);
}
}
|
e34fcbaa16437837b3757e66ca8702645eb1bdd3
|
[
"Markdown",
"Java"
] | 4
|
Java
|
MoshiXu/Study
|
7b95da1e69b54627e3db5f26ce114a8028d9bd61
|
46c80a8b2c552fc4db053ba9de38173e740b6fbb
|
refs/heads/master
|
<repo_name>B-Rich/WatsonBox<file_sep>/app/models/item.rb
class Item < ActiveRecord::Base
attr_accessible :box_id, :description, :name, :owner_id, :picture
belongs_to :box
end
<file_sep>/app/models/box.rb
class Box < ActiveRecord::Base
attr_accessible :description, :name, :user_id, :picture
has_many :items
belongs_to :user
end
<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :authkey, :authkey2, :email, :name
has_many :boxes
end
|
3d602c8821818fc1b57ae2ff868cf16c2a0c3576
|
[
"Ruby"
] | 3
|
Ruby
|
B-Rich/WatsonBox
|
b92e13344a592bf8a3d4b5c751296e6422d494a3
|
9b6b865b2551512b45b690f5bfce5bbf977ef3fc
|
refs/heads/master
|
<repo_name>My-Particularities-techniques/Horizone<file_sep>/Horizone/Migrations/201912191306148_ChangePronoun.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChangePronoun : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Bibliographies", "Pronoun_Id", "dbo.Pronouns");
DropForeignKey("dbo.PronounNumbers", "Pronoun_Id", "dbo.Pronouns");
DropForeignKey("dbo.PronounNumbers", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.Pronouns", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.Pronouns", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.Pronouns", "WordSubClassId", "dbo.WordSubClasses");
DropIndex("dbo.Bibliographies", new[] { "Pronoun_Id" });
DropIndex("dbo.Pronouns", new[] { "TochLanguageId" });
DropIndex("dbo.Pronouns", new[] { "WordClassId" });
DropIndex("dbo.Pronouns", new[] { "WordSubClassId" });
DropIndex("dbo.PronounNumbers", new[] { "Pronoun_Id" });
DropIndex("dbo.PronounNumbers", new[] { "Number_Id" });
AddColumn("dbo.Pronouns", "DictionaryId", c => c.Int(nullable: false));
AddColumn("dbo.Pronouns", "Number_Id", c => c.Int());
CreateIndex("dbo.Pronouns", "DictionaryId");
CreateIndex("dbo.Pronouns", "Number_Id");
AddForeignKey("dbo.Pronouns", "DictionaryId", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.Pronouns", "Number_Id", "dbo.Numbers", "Id");
DropColumn("dbo.Bibliographies", "Pronoun_Id");
DropColumn("dbo.Pronouns", "TochWord");
DropColumn("dbo.Pronouns", "Sanskrit");
DropColumn("dbo.Pronouns", "English");
DropColumn("dbo.Pronouns", "Francaise");
DropColumn("dbo.Pronouns", "German");
DropColumn("dbo.Pronouns", "Latin");
DropColumn("dbo.Pronouns", "Chinese");
DropColumn("dbo.Pronouns", "TochLanguageId");
DropColumn("dbo.Pronouns", "WordClassId");
DropColumn("dbo.Pronouns", "WordSubClassId");
DropColumn("dbo.Pronouns", "EquivalentTA");
DropColumn("dbo.Pronouns", "EquivalentTB");
DropColumn("dbo.Pronouns", "TochCommon");
DropColumn("dbo.Pronouns", "TochCorrespondence");
DropColumn("dbo.Pronouns", "EquivalentInOther");
DropColumn("dbo.Pronouns", "DerivedFrom");
DropColumn("dbo.Pronouns", "RelatedLexemes");
DropColumn("dbo.Pronouns", "RootCharacter");
DropColumn("dbo.Pronouns", "InternalRootVowel");
DropColumn("dbo.Pronouns", "Stem");
DropColumn("dbo.Pronouns", "StemClass");
DropColumn("dbo.Pronouns", "Visible");
DropTable("dbo.PronounNumbers");
}
public override void Down()
{
CreateTable(
"dbo.PronounNumbers",
c => new
{
Pronoun_Id = c.Int(nullable: false),
Number_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Pronoun_Id, t.Number_Id });
AddColumn("dbo.Pronouns", "Visible", c => c.Boolean(nullable: false));
AddColumn("dbo.Pronouns", "StemClass", c => c.String());
AddColumn("dbo.Pronouns", "Stem", c => c.String());
AddColumn("dbo.Pronouns", "InternalRootVowel", c => c.String());
AddColumn("dbo.Pronouns", "RootCharacter", c => c.String());
AddColumn("dbo.Pronouns", "RelatedLexemes", c => c.String());
AddColumn("dbo.Pronouns", "DerivedFrom", c => c.String());
AddColumn("dbo.Pronouns", "EquivalentInOther", c => c.String());
AddColumn("dbo.Pronouns", "TochCorrespondence", c => c.String());
AddColumn("dbo.Pronouns", "TochCommon", c => c.String());
AddColumn("dbo.Pronouns", "EquivalentTB", c => c.String());
AddColumn("dbo.Pronouns", "EquivalentTA", c => c.String());
AddColumn("dbo.Pronouns", "WordSubClassId", c => c.Int(nullable: false));
AddColumn("dbo.Pronouns", "WordClassId", c => c.Int(nullable: false));
AddColumn("dbo.Pronouns", "TochLanguageId", c => c.Int(nullable: false));
AddColumn("dbo.Pronouns", "Chinese", c => c.String());
AddColumn("dbo.Pronouns", "Latin", c => c.String());
AddColumn("dbo.Pronouns", "German", c => c.String());
AddColumn("dbo.Pronouns", "Francaise", c => c.String());
AddColumn("dbo.Pronouns", "English", c => c.String());
AddColumn("dbo.Pronouns", "Sanskrit", c => c.String());
AddColumn("dbo.Pronouns", "TochWord", c => c.String(nullable: false));
AddColumn("dbo.Bibliographies", "Pronoun_Id", c => c.Int());
DropForeignKey("dbo.Pronouns", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.Pronouns", "DictionaryId", "dbo.DictionaryTocharians");
DropIndex("dbo.Pronouns", new[] { "Number_Id" });
DropIndex("dbo.Pronouns", new[] { "DictionaryId" });
DropColumn("dbo.Pronouns", "Number_Id");
DropColumn("dbo.Pronouns", "DictionaryId");
CreateIndex("dbo.PronounNumbers", "Number_Id");
CreateIndex("dbo.PronounNumbers", "Pronoun_Id");
CreateIndex("dbo.Pronouns", "WordSubClassId");
CreateIndex("dbo.Pronouns", "WordClassId");
CreateIndex("dbo.Pronouns", "TochLanguageId");
CreateIndex("dbo.Bibliographies", "Pronoun_Id");
AddForeignKey("dbo.Pronouns", "WordSubClassId", "dbo.WordSubClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.Pronouns", "WordClassId", "dbo.WordClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.Pronouns", "TochLanguageId", "dbo.TochLanguages", "Id", cascadeDelete: false);
AddForeignKey("dbo.PronounNumbers", "Number_Id", "dbo.Numbers", "Id", cascadeDelete: false);
AddForeignKey("dbo.PronounNumbers", "Pronoun_Id", "dbo.Pronouns", "Id", cascadeDelete: false);
AddForeignKey("dbo.Bibliographies", "Pronoun_Id", "dbo.Pronouns", "Id");
}
}
}
<file_sep>/Horizone/Models/News.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class News
{
public int Id { get; set; }
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[AllowHtml]
[Display(Name = "Summary", ResourceType = typeof(StaticResource.Resources))]
public string Summary { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "DateModifier",ResourceType = typeof(StaticResource.Resources))]
public DateTime Date {
get {
return DateTime.Now;
}
}
[AllowHtml]
[Display(Name = "Link",ResourceType = typeof(StaticResource.Resources))]
public string Content{ get; set; }
[Display(Name = "Views", ResourceType = typeof(StaticResource.Resources))]
[Range(0, 10000, ErrorMessageResourceName = "Positive", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public int View { get; set; }
[Display(Name = "Topic", ResourceType = typeof(StaticResource.Resources))]
public int TopicId { get; set; }
[ForeignKey("TopicId")]
public Topic Topic { get; set; }
[Display(Name = "PublishedBy", ResourceType = typeof(StaticResource.Resources))]
public int CollaboratorId { get; set; }
[ForeignKey("CollaboratorId")]
public Collaborator Collaborator { get; set; }
public ICollection<Comment> Comments { get; set; }
public ICollection<ImageNews> ImageNewses { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
}
}<file_sep>/Horizone/Models/AnalyseMaterial.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class AnalyseMaterial
{
public int Id { get; set; }
[Display(Name = "Index", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Index { get; set; }
[Display(Name = "ImageUV", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageUV> ImageUVs { get; set; }
[Display(Name = "OtherImage", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageAnalyse> ImageAnalyses { get; set; }
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
public int Order { get; set; }
}
}<file_sep>/Horizone/Models/ReverseDictionary.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class ReverseDictionary
{
public int Id { get; set; }
[Display(Name = "Words", ResourceType = typeof(StaticResource.Resources))]
public string Word { get; set; }
[Display(Name = "Symbol", ResourceType = typeof(StaticResource.Resources))]
public string SymbolPrefix { get; set; }
[Display(Name = "Reverse", ResourceType = typeof(StaticResource.Resources))]
public string ReverseWord { get; set; }
[Display(Name = "Symbol", ResourceType = typeof(StaticResource.Resources))]
public string SymbolSufix { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/BibliographiesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class BibliographiesController : BaseController
{
// GET: BackOffice/Bibliographies
public ActionResult Index(int page = 1, int pageSize = 40)
{
return View(db.Bibliographys.OrderBy(x => x.Id).ToPagedList(page, pageSize));
}
public ActionResult Book(int page = 1, int pageSize = 12)
{
var bibliographys = db.Bibliographys;
foreach (var item in db.Bibliographys)
if (item.Book) bibliographys.Add(item);
return View(bibliographys.OrderBy(x => x.Title).ToPagedList(page, pageSize));
}
// GET: BackOffice/Bibliographies/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/Bibliographies/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Author,PublicationDate,Title,Journal,UlrBibliography,Book")] Bibliography bibliography)
{
if (ModelState.IsValid)
{
db.Bibliographys.Add(bibliography);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bibliography);
}
// GET: BackOffice/Bibliographies/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bibliography bibliography = db.Bibliographys.Include("ImageBooks").SingleOrDefault(x => x.Id ==id);
if (bibliography == null)
{
return HttpNotFound();
}
return View(bibliography);
}
// POST: BackOffice/Bibliographies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Author,PublicationDate,Title,Journal,UlrBibliography,Book")] Bibliography bibliography)
{
db.Entry(bibliography).State = EntityState.Modified;
db.Bibliographys.Include("ImageBooks").SingleOrDefault(x => x.Id == bibliography.Id);
if (ModelState.IsValid)
{
db.Entry(bibliography).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(bibliography);
}
// GET: BackOffice/Bibliographies/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bibliography bibliography = db.Bibliographys.Include("ImageBooks").SingleOrDefault(x => x.Id == id);
if (bibliography == null)
{
return HttpNotFound();
}
return View(bibliography);
}
// POST: BackOffice/Bibliographies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Bibliography bibliography = db.Bibliographys.Include("ImageBooks").SingleOrDefault(x => x.Id == id);
db.Bibliographys.Remove(bibliography);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageBook();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.BibliographyId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageBooks.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "Bibliographies", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "Collaborations", new { id = id });
}
// GET
public ActionResult DeletePicture(int id, int idcollaboration)
{
ImageCollaboration image = db.ImageCollaborations.Find(id);
db.ImageCollaborations.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "Collaborations", new { id = idcollaboration });
}
}
}
<file_sep>/Horizone/Controllers/FontBibliographiesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Models;
using PagedList;
using Rotativa;
namespace Horizone.Controllers
{
public class FontBibliographiesController : BaseController
{
// GET: FontBibliographies
public ActionResult Bibliographie(int page = 1, int pageSize = 40)
{
var bibliographys = db.Bibliographys;
foreach (var item in db.Bibliographys)
if (!item.Book) bibliographys.Add(item);
return View(bibliographys.OrderBy(x => x.Id).ToPagedList(page, pageSize));
}
public ActionResult Abbreviation(int page = 1, int pageSize = 40)
{
return View(db.Abreviations.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult Book()
{
var bibliographys = db.Bibliographys;
foreach (var item in db.Bibliographys)
if (item.Book) bibliographys.Add(item);
return View(bibliographys.Include("ImageBooks").OrderBy(x => x.Title).ToList());
}
public ActionResult PrintAllReport()
{
var report = new ActionAsPdf("Bibliographie");
return report;
}
public ActionResult PrintAbreviation()
{
var report = new ActionAsPdf("Abbreviation");
return report;
}
// GET: FontBibliographies/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Bibliography bibliography = db.Bibliographys.Find(id);
if (bibliography == null)
{
return HttpNotFound();
}
return View(bibliography);
}
// GET: Bibliographies/Search/
public ActionResult Search(string search)
{
IEnumerable<Bibliography> bibliographies = db.Bibliographys;
if (!string.IsNullOrWhiteSpace(search))
{
bibliographies = bibliographies.Where(x => x.Author.Contains(search)
|| x.Title.Contains(search) || x.Journal.Contains(search));
//|| x.PublicationDate.Contains(search));
}
if (bibliographies.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("Search", bibliographies.ToList());
}
public ActionResult SearchAbreviation(string search)
{
IEnumerable<Abreviation> abreviations = db.Abreviations;
if (!string.IsNullOrWhiteSpace(search))
{
abreviations = abreviations.Where(x => x.Symbol == search);
}
if (abreviations.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchAbreviation", abreviations.ToList());
}
// GET: BackOffice/Verbs/Details/5
public ActionResult DetailsAbbreviation(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Abreviation abreviation = db.Abreviations.SingleOrDefault(y => y.Id == id);
if (abreviation == null)
{
return HttpNotFound();
}
return View(abreviation);
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/AbbreviationDictionariesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class AbbreviationDictionariesController : BaseController
{
// GET: BackOffice/AbbreviationDictionaries
public ActionResult Index(int page = 1, int pageSize = 30)
{
return View(db.AbbreviationDictionaries.OrderBy(x=>x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult OtherAbbreviation(int page = 1, int pageSize = 30)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.OtherAbbreviation == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationGrammatical(int page = 1, int pageSize = 30)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.GrammaticalAbbreviation == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationLanguage(int page = 1, int pageSize = 30)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.AbbreviationsLanguage == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationManuscript(int page = 1, int pageSize = 30)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.AbbreviationManuscript == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
// GET: BackOffice/Verbs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AbbreviationDictionary abbreviationDictionary = db.AbbreviationDictionaries.SingleOrDefault(y => y.Id == id);
if (abbreviationDictionary == null)
{
return HttpNotFound();
}
return View(abbreviationDictionary);
}
// GET: BackOffice/AbbreviationDictionaries/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/AbbreviationDictionaries/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Symbol,Description,OtherAbbreviation, AbbreviationManuscript,AbbreviationsLanguage, GrammaticalAbbreviation")] AbbreviationDictionary abbreviationDictionary)
{
if (ModelState.IsValid)
{
db.AbbreviationDictionaries.Add(abbreviationDictionary);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(abbreviationDictionary);
}
// GET: BackOffice/AbbreviationDictionaries/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AbbreviationDictionary abbreviationDictionary = db.AbbreviationDictionaries.Find(id);
if (abbreviationDictionary == null)
{
return HttpNotFound();
}
return View(abbreviationDictionary);
}
// POST: BackOffice/AbbreviationDictionaries/Edit/5
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Symbol,Description,OtherAbbreviation, AbbreviationManuscript,AbbreviationsLanguage, GrammaticalAbbreviation")] AbbreviationDictionary abbreviationDictionary)
{
if (ModelState.IsValid)
{
db.Entry(abbreviationDictionary).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(abbreviationDictionary);
}
// GET: BackOffice/AbbreviationDictionaries/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AbbreviationDictionary abbreviationDictionary = db.AbbreviationDictionaries.Find(id);
if (abbreviationDictionary == null)
{
return HttpNotFound();
}
return View(abbreviationDictionary);
}
// POST: BackOffice/AbbreviationDictionaries/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
AbbreviationDictionary abbreviationDictionary = db.AbbreviationDictionaries.Find(id);
db.AbbreviationDictionaries.Remove(abbreviationDictionary);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchAbbreviation(string search)
{
IEnumerable<AbbreviationDictionary> abbreviationDictionarys = db.AbbreviationDictionaries;
IEnumerable<Abreviation> abbreviations = db.Abreviations;
List<SearchResult> searchResults = new List<SearchResult>();
foreach (var item in db.SearchResults)
{
db.SearchResults.Remove(item);
}
if (!string.IsNullOrWhiteSpace(search))
{
abbreviationDictionarys = db.AbbreviationDictionaries.Where(x => x.Symbol == search);
if (abbreviationDictionarys.Count() != 0)
{
foreach (var item in abbreviationDictionarys)
{
searchResults.Add(new SearchResult() { NameTable = "AbbreviationDictionaries", IdResult = item.Id, Summary = item.Description });
}
}
abbreviations = db.Abreviations.Where(x => x.Symbol == search);
if (abbreviations.Count() != 0)
{
foreach (var item in abbreviations)
{
searchResults.Add(new SearchResult() { NameTable = "Abbreviations", IdResult = item.Id, Summary = (item.Symbol + " - " + item.Description) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchAbbreviation", db.SearchResults.ToList());
}
}
}
<file_sep>/Horizone/Migrations/201904271527418_AddcolumeGender.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddcolumeGender : DbMigration
{
public override void Up()
{
AddColumn("dbo.Genders", "NameGender", c => c.String());
AddColumn("dbo.People", "ConjugatedPerson", c => c.String());
}
public override void Down()
{
DropColumn("dbo.People", "ConjugatedPerson");
DropColumn("dbo.Genders", "NameGender");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/ActivitiesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ActivitiesController : BaseController
{
// GET: BackOffice/Activities
public ActionResult Index()
{
var activitys = db.Activitys.Include(a => a.Language).Include(a => a.Topic);
return View(activitys.ToList());
}
public ActionResult Symposia()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 14);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
public ActionResult ConferencesAndSeminar()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 13 || x.Topic.Id == 9);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
public ActionResult Missions()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 15);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
// GET: BackOffice/Activities/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Activity activity = db.Activitys.Include("language").Include("Topic").SingleOrDefault(x=>x.Id==id);
if (activity == null)
{
return HttpNotFound();
}
return View(activity);
}
// GET: BackOffice/Activities/Create
public ActionResult Create()
{
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol");
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicEn");
return View();
}
// POST: BackOffice/Activities/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DateofActivity,Place,NameActivity,Description,UlrActivity,Picture,TopicId,LanguageId")] Activity activity)
{
if (ModelState.IsValid)
{
db.Activitys.Add(activity);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", activity.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicEn", activity.TopicId);
return View(activity);
}
// GET: BackOffice/Activities/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Activity activity = db.Activitys.SingleOrDefault(x => x.Id==id);
if (activity == null)
{
return HttpNotFound();
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", activity.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicEn", activity.TopicId);
return View(activity);
}
// POST: BackOffice/Activities/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DateofActivity,Place,NameActivity,Description,UlrActivity,Picture,TopicId,LanguageId")] Activity activity)
{
db.Entry(activity).State = EntityState.Modified;
db.Activitys.SingleOrDefault(x => x.Id == activity.Id);
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", activity.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicEn", activity.TopicId);
return View(activity);
}
// GET: BackOffice/Activities/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Activity activity = db.Activitys.Find(id);
if (activity == null)
{
return HttpNotFound();
}
return View(activity);
}
// POST: BackOffice/Activities/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Activity activity = db.Activitys.Find(id);
db.Activitys.Remove(activity);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/SearchResult.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class SearchResult
{
public int Id { get; set; }
[Display(Name = "Source", ResourceType = typeof(StaticResource.Resources))]
public string NameTable { set; get; }
[Display(Name = "IndexSource", ResourceType = typeof(StaticResource.Resources))]
public int IdResult { set; get; }
[Display(Name = "Summary", ResourceType = typeof(StaticResource.Resources))]
public string Summary { set; get; }
}
}<file_sep>/Horizone/Models/Case.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Case
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string NameCase { get; set; }
[Display(Name = "CaseEn", ResourceType = typeof(StaticResource.Resources))]
public string NameCaseEn { get; set; }
[Display(Name = "CaseFr", ResourceType = typeof(StaticResource.Resources))]
public string NameCaseFr { get; set; }
[Display(Name = "CaseZh", ResourceType = typeof(StaticResource.Resources))]
public string NameCaseZh { get; set; }
[Display(Name = "Word", ResourceType = typeof(StaticResource.Resources))]
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<NounAdjective> NounAdjectives { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Pronoun> Pronouns { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/LinkAndPressesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class LinkAndPressesController : BaseController
{
// GET: BackOffice/LinkAndPresses
public ActionResult Index()
{
var linkAndPresses = db.LinkAndPresses.Include(l => l.Language);
return View(linkAndPresses.ToList());
}
//pour ficher dans menu Link page d'acceil
[ChildActionOnly]
public ActionResult Link()
{
var linkAndPresses = db.LinkAndPresses;
foreach (var item in db.LinkAndPresses)
{
if (item.Order != 4)
linkAndPresses.Add(item);
}
return PartialView(linkAndPresses.ToList());
}
//pour travail dans bureau
public ActionResult Press()
{
var linkAndPresses = db.LinkAndPresses;
foreach (var item in db.LinkAndPresses)
{
if (item.Order == 4)
linkAndPresses.Add(item);
}
return View(linkAndPresses.ToList());
}
// GET: BackOffice/LinkAndPresses/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LinkAndPress linkAndPress = db.LinkAndPresses.Find(id);
if (linkAndPress == null)
{
return HttpNotFound();
}
return View(linkAndPress);
}
// GET: BackOffice/LinkAndPresses/Create
public ActionResult Create()
{
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol");
return View();
}
// POST: BackOffice/LinkAndPresses/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,Link,Order,Status,Target,Press,LanguageId")] LinkAndPress linkAndPress)
{
if (ModelState.IsValid)
{
db.LinkAndPresses.Add(linkAndPress);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", linkAndPress.LanguageId);
return View(linkAndPress);
}
// GET: BackOffice/LinkAndPresses/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LinkAndPress linkAndPress = db.LinkAndPresses.Find(id);
if (linkAndPress == null)
{
return HttpNotFound();
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", linkAndPress.LanguageId);
return View(linkAndPress);
}
// POST: BackOffice/LinkAndPresses/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Link,Order,Status,Target,Press,LanguageId")] LinkAndPress linkAndPress)
{
if (ModelState.IsValid)
{
db.Entry(linkAndPress).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", linkAndPress.LanguageId);
return View(linkAndPress);
}
// GET: BackOffice/LinkAndPresses/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LinkAndPress linkAndPress = db.LinkAndPresses.Find(id);
if (linkAndPress == null)
{
return HttpNotFound();
}
return View(linkAndPress);
}
// POST: BackOffice/LinkAndPresses/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
LinkAndPress linkAndPress = db.LinkAndPresses.Find(id);
db.LinkAndPresses.Remove(linkAndPress);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/PaperColorsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class PaperColorsController : BaseController
{
// GET: BackOffice/PaperColors
public ActionResult Index()
{
return View(db.PaperColors.ToList());
}
// GET: BackOffice/PaperColors/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/PaperColors/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,PaperColorEn,PaperColorFr,PaperColorZh")] PaperColor paperColor)
{
if (ModelState.IsValid)
{
db.PaperColors.Add(paperColor);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(paperColor);
}
// GET: BackOffice/PaperColors/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PaperColor paperColor = db.PaperColors.Find(id);
if (paperColor == null)
{
return HttpNotFound();
}
return View(paperColor);
}
// POST: BackOffice/PaperColors/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,PaperColorEn,PaperColorFr,PaperColorZh")] PaperColor paperColor)
{
if (ModelState.IsValid)
{
db.Entry(paperColor).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(paperColor);
}
// GET: BackOffice/PaperColors/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PaperColor paperColor = db.PaperColors.Find(id);
if (paperColor == null)
{
return HttpNotFound();
}
return View(paperColor);
}
// POST: BackOffice/PaperColors/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
PaperColor paperColor = db.PaperColors.Find(id);
db.PaperColors.Remove(paperColor);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/CollaboratorsController.cs
using Horizone.Controllers;
using Horizone.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Admin")]
public class CollaboratorsController : BaseController
{
// GET: BackOffice/Collaborators
public ActionResult Index()
{
List<Collaborator> clients = db.Collaborators.ToList();
return View(clients);
}
// GET: BackOffice/Collaborators/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Collaborator collaborator = db.Collaborators.Find(id);
if (collaborator == null)
{
return HttpNotFound();
}
return View(collaborator);
}
}
}<file_sep>/Horizone/Models/Collaboration.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Collaboration
{
public int Id { get; set; }
[StringLength(20, MinimumLength = 1, ErrorMessageResourceName = "MaxLength20", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "Title", ResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(30, MinimumLength = 2, ErrorMessageResourceName = "MaxLength30", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "LastName", ResourceType = typeof(StaticResource.Resources))]
public string LastName { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(30, MinimumLength = 2, ErrorMessageResourceName = "MaxLength30", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "FirstName", ResourceType = typeof(StaticResource.Resources))]
public string FirstName { get; set; }
[AllowHtml]
[Display(Name ="Fonction", ResourceType = typeof(StaticResource.Resources))]
public string FonctionEn { get; set; }
[AllowHtml]
[Display(Name = "Fonction", ResourceType = typeof(StaticResource.Resources))]
public string FonctionFr { get; set; }
[AllowHtml]
[Display(Name = "Fonction", ResourceType = typeof(StaticResource.Resources))]
public string FonctionZh { get; set; }
[AllowHtml]
[Display(Name = "Affiliation", ResourceType = typeof(StaticResource.Resources))]
public string AffiliationFr { get; set; }
[AllowHtml]
[Display(Name = "Affiliation", ResourceType = typeof(StaticResource.Resources))]
public string AffiliationEn { get; set; }
[AllowHtml]
[Display(Name = "Affiliation", ResourceType = typeof(StaticResource.Resources))]
public string AffiliationZh { get; set; }
[Display(Name = "CVName")]
public string CV { get; set; }
[Display(Name = "Email", ResourceType = typeof(StaticResource.Resources))]
public string Email { get; set; }
[Display(Name = "Publications", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Publication> Publications { get; set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageCollaboration> ImageCollaborations { get; set; }
[Display(Name = "Team", ResourceType = typeof(StaticResource.Resources))]
public Boolean Team { get; set; }
[Display(Name = "AssociatedResearcher", ResourceType = typeof(StaticResource.Resources))]
public Boolean AssociatedResearcher { get; set; }
[Display(Name = "Collaborator", ResourceType = typeof(StaticResource.Resources))]
public Boolean Collaborator { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
[Display(Name = "Order", ResourceType = typeof(StaticResource.Resources))]
public int Order { get; set; }
}
}<file_sep>/Horizone/Models/AboutProject.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class AboutProject
{
public int Id { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "DateModifier", ResourceType = typeof(StaticResource.Resources))]
public DateTime DateModifier
{
get
{
return DateTime.Now;
}
}
[AllowHtml]
[Display(Name = "Aim", ResourceType = typeof(StaticResource.Resources))]
public string Aim { get; set; }
[AllowHtml]
[Display(Name = "Funding", ResourceType = typeof(StaticResource.Resources))]
public string Funding { get; set; }
[AllowHtml]
[Display(Name = "Programing", ResourceType = typeof(StaticResource.Resources))]
public string Programing { get; set; }
[AllowHtml]
[Display(Name = "Feedback", ResourceType = typeof(StaticResource.Resources))]
public string Feedback { get; set; }
[AllowHtml]
[Display(Name = "Contact", ResourceType = typeof(StaticResource.Resources))]
public string Contact { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageProject> ImageProjects { get; set; }
}
}<file_sep>/Horizone/Models/Personne.cs
using Horizone.Validators;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public abstract class Personne
{
public int Id { get; set; }
[StringLength(20, MinimumLength = 1, ErrorMessageResourceName = "MaxLength20", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "Title", ResourceType = typeof(StaticResource.Resources))]
[Index("IX_PersonneUnique", 1, IsUnique = true)]
public string Title { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(30, MinimumLength = 2, ErrorMessageResourceName = "MaxLength30", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "LastName", ResourceType = typeof(StaticResource.Resources))]
[Index("IX_PersonneUnique", 2, IsUnique = true)]
public string LastName { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(30, MinimumLength = 2, ErrorMessageResourceName = "MaxLength30", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "FirstName", ResourceType = typeof(StaticResource.Resources))]
[Index("IX_PersonneUnique", 3, IsUnique = true)]
public string FirstName { get; set; }
[RegularExpression(@"^([0-9])*\s*$", ErrorMessageResourceName = "OnlyNumbers", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(20, MinimumLength = 3, ErrorMessageResourceName = "MaxLength20", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "PhoneNumber", ResourceType = typeof(StaticResource.Resources))]
public string PhoneNumber { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/SieveMarksController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class SieveMarksController : BaseController
{
// GET: BackOffice/SieveMarks
public ActionResult Index()
{
return View(db.SieveMarks.ToList());
}
// GET: BackOffice/SieveMarks/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/SieveMarks/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,SieveMarkEn,SieveMarkFr,SieveMarkZh")] SieveMark sieveMark)
{
if (ModelState.IsValid)
{
db.SieveMarks.Add(sieveMark);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(sieveMark);
}
// GET: BackOffice/SieveMarks/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SieveMark sieveMark = db.SieveMarks.Find(id);
if (sieveMark == null)
{
return HttpNotFound();
}
return View(sieveMark);
}
// POST: BackOffice/SieveMarks/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,SieveMarkEn,SieveMarkFr,SieveMarkZh")] SieveMark sieveMark)
{
if (ModelState.IsValid)
{
db.Entry(sieveMark).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(sieveMark);
}
// GET: BackOffice/SieveMarks/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
SieveMark sieveMark = db.SieveMarks.Find(id);
if (sieveMark == null)
{
return HttpNotFound();
}
return View(sieveMark);
}
// POST: BackOffice/SieveMarks/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
SieveMark sieveMark = db.SieveMarks.Find(id);
db.SieveMarks.Remove(sieveMark);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/RulingColor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace Horizone.Models
{
public class RulingColor
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "RulingColorEn", ResourceType = typeof(StaticResource.Resources))]
public string RulingColorEn { get; set; }
[AllowHtml]
[Display(Name = "RulingColorFr", ResourceType = typeof(StaticResource.Resources))]
public string RulingColorFr { get; set; }
[AllowHtml]
[Display(Name = "RulingColorZh", ResourceType = typeof(StaticResource.Resources))]
public string RulingColorZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/AbreviationsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class AbreviationsController : BaseController
{
// GET: BackOffice/Abreviations
public ActionResult Index(int page = 1, int pageSize = 20)
{
return View(db.Abreviations.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
// GET: BackOffice/Verbs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Abreviation abbreviation = db.Abreviations.SingleOrDefault(y => y.Id == id);
if (abbreviation == null)
{
return HttpNotFound();
}
return View(abbreviation);
}
// GET: BackOffice/Abreviations/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/Abreviations/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Symbol,Description,Link")] Abreviation abreviation)
{
if (ModelState.IsValid)
{
db.Abreviations.Add(abreviation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(abreviation);
}
// GET: BackOffice/Abreviations/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Abreviation abreviation = db.Abreviations.Find(id);
if (abreviation == null)
{
return HttpNotFound();
}
return View(abreviation);
}
// POST: BackOffice/Abreviations/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Symbol,Description,Link")] Abreviation abreviation)
{
if (ModelState.IsValid)
{
db.Entry(abreviation).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(abreviation);
}
// GET: BackOffice/Abreviations/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Abreviation abreviation = db.Abreviations.Find(id);
if (abreviation == null)
{
return HttpNotFound();
}
return View(abreviation);
}
// POST: BackOffice/Abreviations/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Abreviation abreviation = db.Abreviations.Find(id);
db.Abreviations.Remove(abreviation);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/LanguageStage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class LanguageStage
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "LanguageStageEn", ResourceType = typeof(StaticResource.Resources))]
public string LanguageStageEn { get; set; }
[AllowHtml]
[Display(Name = "LanguageStageFr", ResourceType = typeof(StaticResource.Resources))]
public string LanguageStageFr { get; set; }
[AllowHtml]
[Display(Name = "LanguageStageZh", ResourceType = typeof(StaticResource.Resources))]
public string LanguageStageZh { get; set; }
}
}<file_sep>/Horizone/Models/Valency.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Valency
{
public int Id { get; set; }
[Display(Name = "Valency", ResourceType = typeof(StaticResource.Resources))]
public string AbbreviationValency { get; set; }
[Display(Name = "ValencyEn", ResourceType = typeof(StaticResource.Resources))]
public string ValencyEn { get; set; }
[Display(Name = "ValencyFr", ResourceType = typeof(StaticResource.Resources))]
public string ValencyFr { get; set; }
[Display(Name = "ValencyZh", ResourceType = typeof(StaticResource.Resources))]
public string ValencyZh { get; set; }
}
}<file_sep>/Horizone/Models/ImageBook.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class ImageBook
{
public int Id { get; set; }
[Display(Name = "Name", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(150)]
public string Name { get; set; }
[Required]
[StringLength(20)]
public string ContentType { get; set; }
[AllowHtml]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public byte[] Content { get; set; }
[Display(Name = "Book", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public int BibliographyId { get; set; }
[ForeignKey("BibliographyId")]
public Bibliography Bibliography { get; set; }
}
}<file_sep>/Horizone/Models/SourceStory.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
namespace Horizone.Models
{
public class SourceStory
{
public int Id { get; set; }
[Display(Name = "SourceStory", ResourceType = typeof(StaticResource.Resources))]
public string SourceEn { get; set; }
[Display(Name = "SourceStory", ResourceType = typeof(StaticResource.Resources))]
public string SourceFr { get; set; }
[Display(Name = "SourceStory", ResourceType = typeof(StaticResource.Resources))]
public string SourceZh { get; set; }
}
}<file_sep>/Horizone/Controllers/FontTochPhrasesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Models;
using Rotativa;
namespace Horizone.Controllers
{
public class FontTochPhrasesController : BaseController
{
// GET: FontTochPhrases
public ActionResult Index()
{
var tochPhrases = db.TochPhrases.Include(t => t.TochLanguage);
return View(tochPhrases.ToList());
}
// GET: FontTochPhrases/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochPhrase tochPhrase = db.TochPhrases.Include("TochLanguage").SingleOrDefault(x=>x.Id==id);
if (tochPhrase == null)
{
return HttpNotFound();
}
return View(tochPhrase);
}
public ActionResult PrintPhrase()
{
var report = new ActionAsPdf("Index");
return report;
}
public ActionResult Search(string search)
{
IEnumerable<TochPhrase> tochPhrases = db.TochPhrases;
if (!string.IsNullOrWhiteSpace(search))
{
tochPhrases = db.TochPhrases.Include("TochLanguage").Where(x => x.Phrase.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese !=null && x.Chinese.Contains(search)));
}
if (tochPhrases.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("Search", tochPhrases.ToList());
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/LanguageDetailsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class LanguageDetailsController : BaseController
{
// GET: BackOffice/LanguageDetails
public ActionResult Index()
{
return View(db.LanguageDetails.ToList());
}
// GET: BackOffice/LanguageDetails/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/LanguageDetails/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,LanguageDetailEn,LanguageDetailFr,LanguageDetailZh")] LanguageDetail languageDetail)
{
if (ModelState.IsValid)
{
db.LanguageDetails.Add(languageDetail);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(languageDetail);
}
// GET: BackOffice/LanguageDetails/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LanguageDetail languageDetail = db.LanguageDetails.Find(id);
if (languageDetail == null)
{
return HttpNotFound();
}
return View(languageDetail);
}
// POST: BackOffice/LanguageDetails/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,LanguageDetailEn,LanguageDetailFr,LanguageDetailZh")] LanguageDetail languageDetail)
{
if (ModelState.IsValid)
{
db.Entry(languageDetail).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(languageDetail);
}
// GET: BackOffice/LanguageDetails/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LanguageDetail languageDetail = db.LanguageDetails.Find(id);
if (languageDetail == null)
{
return HttpNotFound();
}
return View(languageDetail);
}
// POST: BackOffice/LanguageDetails/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
LanguageDetail languageDetail = db.LanguageDetails.Find(id);
db.LanguageDetails.Remove(languageDetail);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/VisualAid.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class VisualAid
{
public int Id { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "Help", ResourceType = typeof(StaticResource.Resources))]
public string Aids { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[Display(Name = "Photography", ResourceType = typeof(StaticResource.Resources))]
public Boolean Photography { get; set; }
[Display(Name = "Glossary", ResourceType = typeof(StaticResource.Resources))]
public Boolean Glosary { get; set; }
[Display(Name = "Question", ResourceType = typeof(StaticResource.Resources))]
public Boolean Question { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
}
}<file_sep>/Horizone/Models/Bibliography.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Bibliography
{
public int Id { get; set; }
[Display(Name = "Author", ResourceType = typeof(StaticResource.Resources))]
[StringLength(150, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Author { get; set; }
[Display(Name = "PublicationDate", ResourceType = typeof(StaticResource.Resources))]
[StringLength(10, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string PublicationDate { get; set; }
[AllowHtml]
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[AllowHtml]
[Display(Name = "Newspaper", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Journal { get; set; }
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string UlrBibliography { get; set; }
[Display(Name = "Book", ResourceType = typeof(StaticResource.Resources))]
public Boolean Book { get; set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageBook> ImageBooks { get; set; }
[Display(Name = "TochStory", ResourceType = typeof(StaticResource.Resources))]
public ICollection<TochStory> TochStories { get; set; }
[Display(Name = "TochPhrase", ResourceType = typeof(StaticResource.Resources))]
public ICollection<TochPhrase> TochPhrases { get; set; }
[Display(Name = "Manuscript", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Manuscript> Manuscripts { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/PartnerAndRelationsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class PartnerAndRelationsController : BaseController
{
// GET: BackOffice/PartnerAndRelations
public ActionResult Index()
{
return View(db.PartnerAndRelations.Include("ImagePartners").ToList());
}
public ActionResult Partner()
{
var partnerAndRelations = db.PartnerAndRelations;
foreach (var item in db.PartnerAndRelations)
if (item.Partner) partnerAndRelations.Add(item);
return View(partnerAndRelations.Include("ImagePartners").OrderBy(x => x.Order).ToList());
}
public ActionResult Relation()
{
var partnerAndRelations = db.PartnerAndRelations;
foreach (var item in db.PartnerAndRelations)
if (item.Relation) partnerAndRelations.Add(item);
return View(partnerAndRelations.Include("ImagePartners").OrderBy(x => x.Order).ToList());
}
// GET: BackOffice/PartnerAndRelations/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PartnerAndRelation partnerAndRelation = db.PartnerAndRelations.Include("ImagePartners").SingleOrDefault(x=>x.Id==id);
if (partnerAndRelation == null)
{
return HttpNotFound();
}
return View(partnerAndRelation);
}
// GET: BackOffice/PartnerAndRelations/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/PartnerAndRelations/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Description,Link,Partner,Relation,Order,Visible")] PartnerAndRelation partnerAndRelation)
{
if (ModelState.IsValid)
{
db.PartnerAndRelations.Add(partnerAndRelation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(partnerAndRelation);
}
// GET: BackOffice/PartnerAndRelations/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PartnerAndRelation partnerAndRelation = db.PartnerAndRelations.Include("ImagePartners").SingleOrDefault(x => x.Id == id);
if (partnerAndRelation == null)
{
return HttpNotFound();
}
return View(partnerAndRelation);
}
// POST: BackOffice/PartnerAndRelations/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,Description,Link,Partner,Relation,Order,Visible")] PartnerAndRelation partnerAndRelation)
{
db.Entry(partnerAndRelation).State = EntityState.Modified;
db.PartnerAndRelations.Include("ImagePartners").SingleOrDefault(x => x.Id == partnerAndRelation.Id);
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(partnerAndRelation);
}
// GET: BackOffice/PartnerAndRelations/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PartnerAndRelation partnerAndRelation = db.PartnerAndRelations.Include("ImagePartners").SingleOrDefault(x => x.Id == id);
if (partnerAndRelation == null)
{
return HttpNotFound();
}
return View(partnerAndRelation);
}
// POST: BackOffice/PartnerAndRelations/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
PartnerAndRelation partnerAndRelation = db.PartnerAndRelations.Include("ImagePartners").SingleOrDefault(x => x.Id == id);
db.PartnerAndRelations.Remove(partnerAndRelation);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImagePartner();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.PartnerAndRelationId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImagePartners.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "PartnerAndRelations", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "PartnerAndRelations", new { id = id });
}
public ActionResult DeletePicture(int id, int idPartnerAndRelations)
{
ImagePartner image = db.ImagePartners.Find(id);
db.ImagePartners.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "PartnerAndRelations", new { id = idPartnerAndRelations });
}
}
}
<file_sep>/Horizone/Models/Format.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Format
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "FormatEn", ResourceType = typeof(StaticResource.Resources))]
public string FormatEn { get; set; }
[AllowHtml]
[Display(Name = "FormatFr", ResourceType = typeof(StaticResource.Resources))]
public string FormatFr { get; set; }
[AllowHtml]
[Display(Name = "FormatZh", ResourceType = typeof(StaticResource.Resources))]
public string FormatZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/CollaborationsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class CollaborationsController : BaseController
{
// GET: BackOffice/Collaborations
public ActionResult Index()
{
return View(db.Collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x=>x.Order).ToList());
}
// GET: BackOffice/Collaborations/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Collaboration collaboration = db.Collaborations.Include("Publications").Include("ImageCollaborations").SingleOrDefault(x => x.Id == id);
if (collaboration.Publications.Count() == 0)
collaboration.Publications = db.Publications.Where(x => x.Title == "No visible").ToList();
if (collaboration == null)
{
return HttpNotFound();
}
return View(collaboration);
}
// GET: BackOffice/Collaborations/Create
public ActionResult Create()
{
MultiSelectList PValues = new MultiSelectList(db.Publications, "Id", "Title");
ViewBag.Publications = PValues;
return View();
}
// POST: BackOffice/Collaborations/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,LastName,FirstName,FonctionFr,AffiliationFr,FonctionEn,AffiliationEn,FonctionZh,AffiliationZh,CV,Email,Team,AssociatedResearcher,Collaborator,Visible,Order")] Collaboration collaboration, int[] PublicationId)
{
if (ModelState.IsValid)
{
if (PublicationId.Count() > 0)
collaboration.Publications = db.Publications.Where(x => PublicationId.Contains(x.Id)).ToList();
if (PublicationId.Count() == 0)
collaboration.Publications = db.Publications.Where(x => x.Title == "No visible").ToList();
db.Collaborations.Add(collaboration);
db.SaveChanges();
return RedirectToAction("Index");
}
MultiSelectList PValues = new MultiSelectList(db.Publications, "Id", "Title");
ViewBag.Publications = PValues;
return View(collaboration);
}
// GET: BackOffice/Collaborations/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Collaboration collaboration = db.Collaborations.Include("ImageCollaborations").Include("Publications").SingleOrDefault(x => x.Id == id);
if (collaboration == null)
{
return HttpNotFound();
}
MultiSelectList PValues = new MultiSelectList(db.Publications, "Id", "Title", collaboration.Publications.Select(x => x.Id));
ViewBag.Publications = PValues;
return View(collaboration);
}
// POST: BackOffice/Collaborations/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,LastName,FirstName,FonctionFr,AffiliationFr,FonctionEn,AffiliationEn,FonctionZh,AffiliationZh,CV,Email,Team,AssociatedResearcher,Collaborator,Visible,Order")] Collaboration collaboration, int[] PublicationId)
{
db.Entry(collaboration).State = EntityState.Modified;
db.Collaborations.Include("ImageCollaborations").Include("Publications").SingleOrDefault(x => x.Id == collaboration.Id);
if (ModelState.IsValid)
{
if (PublicationId != null)
collaboration.Publications = db.Publications.Where(x => PublicationId.Contains(x.Id)).ToList();
else
collaboration.Publications = db.Publications.Where(x => x.Title == "No visible").ToList();
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Publications = new MultiSelectList(db.Publications, "Id", "Title");
return View(collaboration);
}
// GET: BackOffice/Collaborations/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Collaboration collaboration = db.Collaborations.Include("ImageCollaborations").Include("Publications").SingleOrDefault(x => x.Id == id);
if (collaboration == null)
{
return HttpNotFound();
}
return View(collaboration);
}
// POST: BackOffice/Collaborations/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Collaboration collaboration = db.Collaborations.Include("ImageCollaborations").Include("Publications").SingleOrDefault(x => x.Id == id);
db.Collaborations.Remove(collaboration);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Team()
{
var collaborations = db.Collaborations;
foreach (var item in collaborations)
if (item.Team) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
public ActionResult Collaboration()
{
var collaborations = db.Collaborations;
foreach (var item in collaborations)
if (item.Collaborator) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
public ActionResult AssociatedResearcher()
{
var collaborations = db.Collaborations;
foreach (var item in collaborations)
if (item.AssociatedResearcher) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageCollaboration();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.CollaborationId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageCollaborations.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "Collaborations", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "Collaborations", new { id = id });
}
[HttpPost]
public ActionResult UpLoadCv(HttpPostedFileBase file,int id)
{
try
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
db.Collaborations.Find(id).CV = fileName;
db.SaveChanges();
fileName = id + "123-" + fileName;
string filePath = Path.Combine(Server.MapPath("~/Equipe"), fileName);
file.SaveAs(filePath);
}
Display( "Upload file successfully");
return RedirectToAction("edit", "Collaborations", new { id = id });
}
catch
{
Display(" File is not saved");
return RedirectToAction("edit", "Collaborations", new { id = id });
}
}
private List<string> GetFiles()
{
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/ "));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
public FileResult DownLoad(int? id)
{
Collaboration collaboration = db.Collaborations.Find(id);
var fullPath = "~/Equipe/" +id+ "123-"+ collaboration.CV;
return File(fullPath, "application/CV-Download", Path.GetFileName(fullPath));
}
// GET
public ActionResult DeletePicture(int id, int idcollaboration)
{
ImageCollaboration image = db.ImageCollaborations.Find(id);
db.ImageCollaborations.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "Collaborations", new { id = idcollaboration });
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/CommentsController.cs
using Horizone.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Net;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class CommentsController : BaseController
{
// GET: BackOffice/Comments
public ActionResult Index()
{
var comments = db.Comments.Include("News").Include("Client");
return View(comments.ToList());
}
// GET: BackOffice/Topics/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Comment comment = db.Comments.Find(id);
if (comment == null)
{
return HttpNotFound();
}
return View(comment);
}
// POST: BackOffice/Topics/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Comment comment = db.Comments.Find(id);
db.Comments.Remove(comment);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/AboutProjectsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class AboutProjectsController : BaseController
{
// GET: BackOffice/AboutProjects
public ActionResult Index()
{
var aboutProjets = db.AboutProjets.Include(a => a.Language);
return View(aboutProjets.ToList());
}
// GET: BackOffice/AboutProjects/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AboutProject aboutProject = db.AboutProjets.Find(id);
if (aboutProject == null)
{
return HttpNotFound();
}
return View(aboutProject);
}
// GET: BackOffice/AboutProjects/Create
public ActionResult Create()
{
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol");
return View();
}
// POST: BackOffice/AboutProjects/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Aim,Funding,Programing,Feedback,Contact,LanguageId")] AboutProject aboutProject)
{
if (ModelState.IsValid)
{
db.AboutProjets.Add(aboutProject);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", aboutProject.LanguageId);
return View(aboutProject);
}
// GET: BackOffice/AboutProjects/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AboutProject aboutProject = db.AboutProjets.Include("ImageProjects").SingleOrDefault(x => x.Id == id);
if (aboutProject == null)
{
return HttpNotFound();
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", aboutProject.LanguageId);
return View(aboutProject);
}
// POST: BackOffice/AboutProjects/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Aim,Funding,Programing,Feedback,Contact,LanguageId")] AboutProject aboutProject)
{
db.Entry(aboutProject).State = EntityState.Modified;
db.AboutProjets.Include("ImageProjects").SingleOrDefault(x => x.Id == aboutProject.Id);
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", aboutProject.LanguageId);
return View(aboutProject);
}
// GET: BackOffice/AboutProjects/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AboutProject aboutProject = db.AboutProjets.Include("ImageProjects").SingleOrDefault(x=>x.Id==id);
if (aboutProject == null)
{
return HttpNotFound();
}
return View(aboutProject);
}
// POST: BackOffice/AboutProjects/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
AboutProject aboutProject = db.AboutProjets.Include("ImageProjects").SingleOrDefault(x => x.Id == id);
db.AboutProjets.Remove(aboutProject);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageProject();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.AboutProjectId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageProjets.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "AboutProjects", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "AboutProjects", new { id = id });
}
public ActionResult DeletePicture(int id, int idProject)
{
ImageProject image = db.ImageProjets.Find(id);
db.ImageProjets.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "AboutProjects", new { id = idProject });
}
}
}
<file_sep>/Horizone/Models/TochLanguage.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class TochLanguage
{
public int Id { get; set; }
[Display(Name = "TochLanguage", ResourceType = typeof(StaticResource.Resources))]
public string Language { get; set; }
}
}<file_sep>/Horizone/Models/Material.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Material
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "MaterialEn", ResourceType = typeof(StaticResource.Resources))]
public string MaterialEn { get; set; }
[AllowHtml]
[Display(Name = "MaterialFr", ResourceType = typeof(StaticResource.Resources))]
public string MaterialFr { get; set; }
[AllowHtml]
[Display(Name = "MaterialZh", ResourceType = typeof(StaticResource.Resources))]
public string MaterialZh { get; set; }
}
}<file_sep>/Horizone/Models/Mood.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Mood
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string AbbreviationsMood { get; set; }
[Display(Name = "Mood", ResourceType = typeof(StaticResource.Resources))]
public string MoodEn { get; set; }
[Display(Name = "Mood", ResourceType = typeof(StaticResource.Resources))]
public string MoodFr { get; set; }
[Display(Name = "Mood", ResourceType = typeof(StaticResource.Resources))]
public string MoodZh { get; set; }
}
}<file_sep>/Horizone/Migrations/201912191518183_ChangeVerbNounAdj.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class ChangeVerbNounAdj : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.Bibliographies", "NounAdjective_Id", "dbo.NounAdjectives");
DropForeignKey("dbo.Bibliographies", "Verb_Id", "dbo.Verbs");
DropForeignKey("dbo.VerbNumbers", "Verb_Id", "dbo.Verbs");
DropForeignKey("dbo.VerbNumbers", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.Verbs", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.Verbs", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.Verbs", "WordSubClassId", "dbo.WordSubClasses");
DropForeignKey("dbo.NounAdjectiveNumbers", "NounAdjective_Id", "dbo.NounAdjectives");
DropForeignKey("dbo.NounAdjectiveNumbers", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.NounAdjectives", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.NounAdjectives", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.NounAdjectives", "WordSubClassId", "dbo.WordSubClasses");
DropIndex("dbo.Bibliographies", new[] { "NounAdjective_Id" });
DropIndex("dbo.Bibliographies", new[] { "Verb_Id" });
DropIndex("dbo.NounAdjectives", new[] { "TochLanguageId" });
DropIndex("dbo.NounAdjectives", new[] { "WordClassId" });
DropIndex("dbo.NounAdjectives", new[] { "WordSubClassId" });
DropIndex("dbo.Verbs", new[] { "TochLanguageId" });
DropIndex("dbo.Verbs", new[] { "WordClassId" });
DropIndex("dbo.Verbs", new[] { "WordSubClassId" });
DropIndex("dbo.VerbNumbers", new[] { "Verb_Id" });
DropIndex("dbo.VerbNumbers", new[] { "Number_Id" });
DropIndex("dbo.NounAdjectiveNumbers", new[] { "NounAdjective_Id" });
DropIndex("dbo.NounAdjectiveNumbers", new[] { "Number_Id" });
AddColumn("dbo.NounAdjectives", "DictionaryId", c => c.Int(nullable: false));
AddColumn("dbo.NounAdjectives", "Number_Id", c => c.Int());
AddColumn("dbo.Verbs", "DictionaryId", c => c.Int(nullable: false));
AddColumn("dbo.Verbs", "Number_Id", c => c.Int());
CreateIndex("dbo.NounAdjectives", "DictionaryId");
CreateIndex("dbo.NounAdjectives", "Number_Id");
CreateIndex("dbo.Verbs", "DictionaryId");
CreateIndex("dbo.Verbs", "Number_Id");
AddForeignKey("dbo.Verbs", "DictionaryId", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectives", "DictionaryId", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectives", "Number_Id", "dbo.Numbers", "Id");
AddForeignKey("dbo.Verbs", "Number_Id", "dbo.Numbers", "Id");
DropColumn("dbo.Bibliographies", "NounAdjective_Id");
DropColumn("dbo.Bibliographies", "Verb_Id");
DropColumn("dbo.NounAdjectives", "TochWord");
DropColumn("dbo.NounAdjectives", "Sanskrit");
DropColumn("dbo.NounAdjectives", "English");
DropColumn("dbo.NounAdjectives", "Francaise");
DropColumn("dbo.NounAdjectives", "German");
DropColumn("dbo.NounAdjectives", "Latin");
DropColumn("dbo.NounAdjectives", "Chinese");
DropColumn("dbo.NounAdjectives", "TochLanguageId");
DropColumn("dbo.NounAdjectives", "WordClassId");
DropColumn("dbo.NounAdjectives", "WordSubClassId");
DropColumn("dbo.NounAdjectives", "EquivalentTA");
DropColumn("dbo.NounAdjectives", "EquivalentTB");
DropColumn("dbo.NounAdjectives", "TochCommon");
DropColumn("dbo.NounAdjectives", "TochCorrespondence");
DropColumn("dbo.NounAdjectives", "EquivalentInOther");
DropColumn("dbo.NounAdjectives", "DerivedFrom");
DropColumn("dbo.NounAdjectives", "RelatedLexemes");
DropColumn("dbo.NounAdjectives", "RootCharacter");
DropColumn("dbo.NounAdjectives", "InternalRootVowel");
DropColumn("dbo.NounAdjectives", "Stem");
DropColumn("dbo.NounAdjectives", "StemClass");
DropColumn("dbo.NounAdjectives", "Visible");
DropColumn("dbo.Verbs", "TochWord");
DropColumn("dbo.Verbs", "Sanskrit");
DropColumn("dbo.Verbs", "English");
DropColumn("dbo.Verbs", "Francaise");
DropColumn("dbo.Verbs", "German");
DropColumn("dbo.Verbs", "Latin");
DropColumn("dbo.Verbs", "Chinese");
DropColumn("dbo.Verbs", "TochLanguageId");
DropColumn("dbo.Verbs", "WordClassId");
DropColumn("dbo.Verbs", "WordSubClassId");
DropColumn("dbo.Verbs", "EquivalentTA");
DropColumn("dbo.Verbs", "EquivalentTB");
DropColumn("dbo.Verbs", "TochCommon");
DropColumn("dbo.Verbs", "TochCorrespondence");
DropColumn("dbo.Verbs", "EquivalentInOther");
DropColumn("dbo.Verbs", "DerivedFrom");
DropColumn("dbo.Verbs", "RelatedLexemes");
DropColumn("dbo.Verbs", "RootCharacter");
DropColumn("dbo.Verbs", "InternalRootVowel");
DropColumn("dbo.Verbs", "Stem");
DropColumn("dbo.Verbs", "StemClass");
DropColumn("dbo.Verbs", "Visible");
DropTable("dbo.VerbNumbers");
DropTable("dbo.NounAdjectiveNumbers");
}
public override void Down()
{
CreateTable(
"dbo.NounAdjectiveNumbers",
c => new
{
NounAdjective_Id = c.Int(nullable: false),
Number_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.NounAdjective_Id, t.Number_Id });
CreateTable(
"dbo.VerbNumbers",
c => new
{
Verb_Id = c.Int(nullable: false),
Number_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Verb_Id, t.Number_Id });
AddColumn("dbo.Verbs", "Visible", c => c.Boolean(nullable: false));
AddColumn("dbo.Verbs", "StemClass", c => c.String());
AddColumn("dbo.Verbs", "Stem", c => c.String());
AddColumn("dbo.Verbs", "InternalRootVowel", c => c.String());
AddColumn("dbo.Verbs", "RootCharacter", c => c.String());
AddColumn("dbo.Verbs", "RelatedLexemes", c => c.String());
AddColumn("dbo.Verbs", "DerivedFrom", c => c.String());
AddColumn("dbo.Verbs", "EquivalentInOther", c => c.String());
AddColumn("dbo.Verbs", "TochCorrespondence", c => c.String());
AddColumn("dbo.Verbs", "TochCommon", c => c.String());
AddColumn("dbo.Verbs", "EquivalentTB", c => c.String());
AddColumn("dbo.Verbs", "EquivalentTA", c => c.String());
AddColumn("dbo.Verbs", "WordSubClassId", c => c.Int(nullable: false));
AddColumn("dbo.Verbs", "WordClassId", c => c.Int(nullable: false));
AddColumn("dbo.Verbs", "TochLanguageId", c => c.Int(nullable: false));
AddColumn("dbo.Verbs", "Chinese", c => c.String());
AddColumn("dbo.Verbs", "Latin", c => c.String());
AddColumn("dbo.Verbs", "German", c => c.String());
AddColumn("dbo.Verbs", "Francaise", c => c.String());
AddColumn("dbo.Verbs", "English", c => c.String());
AddColumn("dbo.Verbs", "Sanskrit", c => c.String());
AddColumn("dbo.Verbs", "TochWord", c => c.String(nullable: false));
AddColumn("dbo.NounAdjectives", "Visible", c => c.Boolean(nullable: false));
AddColumn("dbo.NounAdjectives", "StemClass", c => c.String());
AddColumn("dbo.NounAdjectives", "Stem", c => c.String());
AddColumn("dbo.NounAdjectives", "InternalRootVowel", c => c.String());
AddColumn("dbo.NounAdjectives", "RootCharacter", c => c.String());
AddColumn("dbo.NounAdjectives", "RelatedLexemes", c => c.String());
AddColumn("dbo.NounAdjectives", "DerivedFrom", c => c.String());
AddColumn("dbo.NounAdjectives", "EquivalentInOther", c => c.String());
AddColumn("dbo.NounAdjectives", "TochCorrespondence", c => c.String());
AddColumn("dbo.NounAdjectives", "TochCommon", c => c.String());
AddColumn("dbo.NounAdjectives", "EquivalentTB", c => c.String());
AddColumn("dbo.NounAdjectives", "EquivalentTA", c => c.String());
AddColumn("dbo.NounAdjectives", "WordSubClassId", c => c.Int(nullable: false));
AddColumn("dbo.NounAdjectives", "WordClassId", c => c.Int(nullable: false));
AddColumn("dbo.NounAdjectives", "TochLanguageId", c => c.Int(nullable: false));
AddColumn("dbo.NounAdjectives", "Chinese", c => c.String());
AddColumn("dbo.NounAdjectives", "Latin", c => c.String());
AddColumn("dbo.NounAdjectives", "German", c => c.String());
AddColumn("dbo.NounAdjectives", "Francaise", c => c.String());
AddColumn("dbo.NounAdjectives", "English", c => c.String());
AddColumn("dbo.NounAdjectives", "Sanskrit", c => c.String());
AddColumn("dbo.NounAdjectives", "TochWord", c => c.String(nullable: false));
AddColumn("dbo.Bibliographies", "Verb_Id", c => c.Int());
AddColumn("dbo.Bibliographies", "NounAdjective_Id", c => c.Int());
DropForeignKey("dbo.Verbs", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.NounAdjectives", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.NounAdjectives", "DictionaryId", "dbo.DictionaryTocharians");
DropForeignKey("dbo.Verbs", "DictionaryId", "dbo.DictionaryTocharians");
DropIndex("dbo.Verbs", new[] { "Number_Id" });
DropIndex("dbo.Verbs", new[] { "DictionaryId" });
DropIndex("dbo.NounAdjectives", new[] { "Number_Id" });
DropIndex("dbo.NounAdjectives", new[] { "DictionaryId" });
DropColumn("dbo.Verbs", "Number_Id");
DropColumn("dbo.Verbs", "DictionaryId");
DropColumn("dbo.NounAdjectives", "Number_Id");
DropColumn("dbo.NounAdjectives", "DictionaryId");
CreateIndex("dbo.NounAdjectiveNumbers", "Number_Id");
CreateIndex("dbo.NounAdjectiveNumbers", "NounAdjective_Id");
CreateIndex("dbo.VerbNumbers", "Number_Id");
CreateIndex("dbo.VerbNumbers", "Verb_Id");
CreateIndex("dbo.Verbs", "WordSubClassId");
CreateIndex("dbo.Verbs", "WordClassId");
CreateIndex("dbo.Verbs", "TochLanguageId");
CreateIndex("dbo.NounAdjectives", "WordSubClassId");
CreateIndex("dbo.NounAdjectives", "WordClassId");
CreateIndex("dbo.NounAdjectives", "TochLanguageId");
CreateIndex("dbo.Bibliographies", "Verb_Id");
CreateIndex("dbo.Bibliographies", "NounAdjective_Id");
AddForeignKey("dbo.NounAdjectives", "WordSubClassId", "dbo.WordSubClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectives", "WordClassId", "dbo.WordClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectives", "TochLanguageId", "dbo.TochLanguages", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectiveNumbers", "Number_Id", "dbo.Numbers", "Id", cascadeDelete: false);
AddForeignKey("dbo.NounAdjectiveNumbers", "NounAdjective_Id", "dbo.NounAdjectives", "Id", cascadeDelete: false);
AddForeignKey("dbo.Verbs", "WordSubClassId", "dbo.WordSubClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.Verbs", "WordClassId", "dbo.WordClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.Verbs", "TochLanguageId", "dbo.TochLanguages", "Id", cascadeDelete: false);
AddForeignKey("dbo.VerbNumbers", "Number_Id", "dbo.Numbers", "Id", cascadeDelete: false);
AddForeignKey("dbo.VerbNumbers", "Verb_Id", "dbo.Verbs", "Id", cascadeDelete: false);
AddForeignKey("dbo.Bibliographies", "Verb_Id", "dbo.Verbs", "Id");
AddForeignKey("dbo.Bibliographies", "NounAdjective_Id", "dbo.NounAdjectives", "Id");
}
}
}
<file_sep>/Horizone/Models/ManufaturingDefect.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class ManufaturingDefect
{
public int Id { get; set; }
[Display(Name = "ManufaturingDefect", ResourceType = typeof(StaticResource.Resources))]
public string ManufaturingDefectEn { get; set; }
[Display(Name = "ManufaturingDefect", ResourceType = typeof(StaticResource.Resources))]
public string ManufaturingDefectFr { get; set; }
[Display(Name = "ManufaturingDefect", ResourceType = typeof(StaticResource.Resources))]
public string ManufaturingDefectZh { get; set; }
}
}<file_sep>/Horizone/Controllers/FontManuscriptsController.cs
using Horizone.Models;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Net;
using Horizone.Controllers;
using Rotativa;
namespace Horizone.Controllers
{
public class FontManuscriptsController : BaseController
{
// GET: Manuscripts
public ActionResult Index(int page = 1, int pageSize = 200)
{
var manuscripts = db.Manuscripts.Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool);
return View(manuscripts.OrderBy(x => x.Index).ToPagedList(page, pageSize));
}
public ActionResult PrintIndex()
{
var report = new ActionAsPdf("Index");
return report;
}
public ActionResult PrintManuscript(int? id)
{
var report = new ActionAsPdf("Details", new { id = id });
return report;
}
public ActionResult AnalyseMaterial()
{
return View(db.AnalyseMaterials.Include("ImageUVs").Include("ImageAnalyses").ToList());
}
// GET: BackOffice/AnalyseMacroscopics
public ActionResult IndexAnalyseMacroscopic()
{
var analyseMacroscopics = db.AnalyseMacroscopics.Include(a => a.Catalogie).Include(a => a.ChainLinesVisibility).Include(a => a.Drying).Include(a => a.FiberDirection).Include(a => a.FiberDistribution).Include(a => a.Format).Include(a => a.GenderManuscript).Include(a => a.LaidLinesRegularity).Include(a => a.ManufaturingDefect).Include(a => a.Map).Include(a => a.PaperColor).Include(a => a.PreparationPaperBeforeUsing).Include(a => a.Restore).Include(a => a.Ruling).Include(a => a.RulingColor).Include(a => a.Script).Include(a => a.SieveMark).Include(a => a.State).Include(a => a.TochLanguage).Include(a => a.WritingTool);
return View(analyseMacroscopics.ToList());
}
public ActionResult MacroscopicDetails(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Include("TransmittedLights").SingleOrDefault(x => x.Id == id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult MacroscopicAnalyse(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult PageLayout(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult SheetDescription(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
// GET: BackOffice/Manuscripts/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/layout/5
public ActionResult LayoutManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Description/5
public ActionResult OverallDescriptions(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Script/5
public ActionResult ScriptManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Text/5
public ActionResult TextContents(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Language/5
public ActionResult TextLanguages(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Materiel/5
public ActionResult MaterialManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
public ActionResult Search(string search)
{
IEnumerable<Manuscript> manuscripts = db.Manuscripts.Include("Catalogie").Include("Map").Include("ImageManuscripts").Include("State").Include("DescriptionManuscript").Include("RemarkAdd").Include("Format").Include("Ruling").Include("RulingColor").Include("RulingDetail").Include("Material").Include("PaperColor").Include("WritingTool").Include("AlignmentType").Include("Script").Include("ScriptAdd").Include("LanguageStage").Include("Tochlanguage").Include("LanguageDetail").Include("GenderManuscript").Include("SubGenderManuscript").Include("Metric").Include("Bibliographys");
if (!string.IsNullOrWhiteSpace(search))
{
manuscripts = db.Manuscripts.Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).Where(x => x.Transliteration.Contains(search)
|| x.Index.Contains(search) || x.Transcription.Contains(search) || x.TochLanguage.Language.Contains(search));
}
if (manuscripts.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("Search", manuscripts.ToList());
}
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/DashBoardsController.cs
using Horizone.Controllers;
using Horizone.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class DashBoardsController : BaseController
{
// GET: BackOffice/DashBoards
public ActionResult Index()
{
return View();
}
public ActionResult Logout()
{
Session.Remove("ADMINISTRATOR");
return RedirectToAction("index", "home", new { area = "" });
}
//Pour menu About
public ActionResult About()
{
var aboutProjets = db.AboutProjets.Include("Language").Include("ImageProjects");
return View(aboutProjets.ToList());
}
//Presentation pour homepage
[ChildActionOnly]
public ActionResult PresenteProject()
{
var aboutProjets = db.AboutProjets.Include("ImageProjects").Include("Language");
return PartialView(aboutProjets.ToList());
}
[ChildActionOnly]
public ActionResult LatestStory()
{
var latestStories = db.TochStorys.Include("ThemeStory").Include("SourceStory");
return PartialView(latestStories.OrderByDescending(x => x.Id).Take(3).ToList());
}
//Presentation pour tous menus
[ChildActionOnly]
public ActionResult PresentationTochPhrase()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationTochStory()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationManuscript()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationDictionaryTocharian()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationActivity()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
public ActionResult PresentationAboutUs()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationBibliography()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationVisualAid()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult Address()
{
var aboutProjets = db.AboutProjets.Include("Language");
return PartialView(aboutProjets.ToList());
}
public ActionResult AboutUs()
{
var collaborations = db.Collaborations;
foreach (var item in collaborations)
if (item.Team) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
// GET: FrontContact/Create
public ActionResult Contact()
{
var aboutProjets = db.AboutProjets.Include("Language");
return View(aboutProjets.ToList());
}
[ChildActionOnly]
public ActionResult PageActivity()
{
var activitys = db.Activitys.Include("Language");
return PartialView(activitys.OrderByDescending(x => x.DateofActivity).Take(5).ToList());
}
[ChildActionOnly]
public ActionResult PagePublication()
{
return PartialView(db.Publications.OrderByDescending(x => x.Id).Take(5).ToList());
}
// 3 news have max view
[ChildActionOnly]
public ActionResult News()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses");
return PartialView(news.OrderByDescending(x => x.View).Take(3).ToList());
}
// 1 latest news
[ChildActionOnly]
public ActionResult LatestNewsFr()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x => x.LanguageId == 1);
if (news.Count() != 0)
{
ViewBag.NewsIdFr = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
[ChildActionOnly]
public ActionResult LatestNewsEn()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x => x.LanguageId == 2);
if (news.Count() != 0)
{
ViewBag.NewsIdEn = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
[ChildActionOnly]
public ActionResult LatestNewsZh()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x => x.LanguageId == 3);
if (news.Count() != 0)
{
ViewBag.NewsIdZh = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
public ActionResult Help()
{
var visualAids = db.VisualAids.Include(v => v.Language);
var question = db.VisualAids.Include(v => v.Language).Where(x => x.Question == true);
ViewBag.Aide = new SelectList(question, "Id", "Aids");
return View(visualAids.ToList());
}
[ChildActionOnly]
public ActionResult Map()
{
ViewBag.Place = new SelectList(db.ImageMaps, "Id", "NamePicture");
return PartialView(db.Maps.Include("ImageMaps").OrderBy(x => x.NamePicture).ToList());
}
[ChildActionOnly]
public ActionResult SearchMap(string search)
{
IEnumerable<Map> maps = db.Maps.Include("ImageMap");
if (!string.IsNullOrWhiteSpace(search))
{
maps = maps.Where(x => x.NamePicture == search);
}
if (maps.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return PartialView("Map", maps.OrderBy(x => x.NamePicture).ToList());
}
public ActionResult SearchQuestion(string search)
{
IEnumerable<VisualAid> visualAids = db.VisualAids.Where(x => x.Question == true);
if (!string.IsNullOrWhiteSpace(search))
{
visualAids = visualAids.Where(x => x.Aids.Contains(search));
}
if (visualAids.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchQuestion", visualAids.ToList());
}
//Press
[ChildActionOnly]
public ActionResult InPresse()
{
var linkAndPresses = db.LinkAndPresses;
foreach (var item in db.LinkAndPresses)
{
if (item.Press)
linkAndPresses.Add(item);
}
return PartialView(linkAndPresses.ToList());
}
public ActionResult SearchBibliography(string search)
{
IEnumerable<Bibliography> bibliographies = db.Bibliographys;
if (!string.IsNullOrWhiteSpace(search))
{
bibliographies = bibliographies.Where(x => x.Author.Contains(search)
|| x.Journal.Contains(search)
|| x.Title.Contains(search));
}
if (bibliographies.Count() == 0)
{
Display("Aucun résultat");
}
return View("SearchBibliography", bibliographies.ToList());
}
//For vocabularies
public ActionResult SearchWord(string search)
{
RefreshSearch();
if (!string.IsNullOrWhiteSpace(search))
{
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("WordClass").Include("WordSubClass").Include("TochLanguage").Where(x => x.Word.Contains(search)
|| (x.EquivalentTA != null && x.EquivalentTA.Contains(search))
|| (x.EquivalentTB != null && x.EquivalentTB.Contains(search))
|| (x.Sanskrit != null && x.Sanskrit.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))); ;
IEnumerable<NamePlace> namePlaces = db.NamePlaces.Where(x => x.Place.Contains(search)); ;
IEnumerable<ProperNoun> properNouns = db.ProperNouns.Where(x => x.Name.Contains(search));
List<SearchResult> searchResults = new List<SearchResult>();
if (namePlaces.Count() != 0)
{
foreach (var item in namePlaces)
{
searchResults.Add(new SearchResult() { NameTable = "NamePlaces", IdResult = item.Id, Summary = string.IsNullOrEmpty(item.DescriptionEn) ? item.Place : item.Place + " - " + item.DescriptionEn });
}
}
if (dictionaryTocharians.Count() != 0)
{
foreach (var item in dictionaryTocharians)
{
string[] myStrings = new string[] { item.Word, item.TochLanguage.Language, item.WordClass.ClassEn, item.WordSubClass.SubClassEn, item.English, item.Francaise, item.German, item.Latin, item.Chinese };
searchResults.Add(new SearchResult() { NameTable = "DictionaryTocharians", IdResult = item.Id, Summary = string.Join(" - ", myStrings.Where(str => !string.IsNullOrEmpty(str))) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchWord", db.SearchResults.ToList());
}
public ActionResult RefreshSearch()
{
foreach (var item in db.SearchResults)
{
db.SearchResults.Remove(item);
}
db.SaveChanges();
return RedirectToAction("SearchIndex");
}
public ActionResult SearchIndex(string search)
{
RefreshSearch();
if (!string.IsNullOrWhiteSpace(search))
{
IEnumerable<TochStory> tochStories = db.TochStorys.Include("SourceStory").Include("ThemeStory").Where(x => (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.Content != null && x.Content.Contains(search))
|| (x.SourceStory.SourceEn != null && x.SourceStory.SourceEn.Contains(search))
|| (x.Name != null && x.Name.Contains(search))
|| (x.Description != null && x.Description.Contains(search))
|| (x.ThemeStory.ThemeEn != null && x.ThemeStory.ThemeEn.Contains(search))
|| (x.ThemeStory.ThemeFr != null && x.ThemeStory.ThemeFr.Contains(search))
|| (x.ThemeStory.ThemeZn != null && x.ThemeStory.ThemeZn.Contains(search)));
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("TochLanguage").Include("WordClass").Include("WordSubClass").Where(x => x.Word.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search)));
IEnumerable<TochPhrase> tochPhrases = db.TochPhrases.Include("TochLanguage").Where(x => x.Phrase.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search)));
IEnumerable<Manuscript> manuscripts = db.Manuscripts.Include("Catalogie").Include("TochLanguage").Where(x => x.Index.Contains(search)
|| x.Catalogie.Name.Contains(search)
|| (x.Title != null && x.Title.Contains(search))
|| (x.Transcription != null && x.Transcription.Contains(search))
|| x.TochLanguage.Language.Contains(search));
IEnumerable<Bibliography> bibliographys = db.Bibliographys.Where(x => x.Title.Contains(search)
|| x.Journal.Contains(search)
|| x.Author.Contains(search));
IEnumerable<NamePlace> namePlaces = db.NamePlaces.Where(x => x.Place.Contains(search));
IEnumerable<ProperNoun> properNouns = db.ProperNouns.Where(x => (x.Name != null && x.Name.Contains(search)));
IEnumerable<SearchResult> results = db.SearchResults;
List<SearchResult> searchResults = new List<SearchResult>();
if (tochStories.Count() != 0)
{
foreach (var item in tochStories)
{
searchResults.Add(new SearchResult() { NameTable = "TochStorys", IdResult = item.Id, Summary = item.Name.Substring(0, Math.Min(40, item.Name.Length)) });
}
}
if (properNouns.Count() != 0)
{
foreach (var item in properNouns)
{
searchResults.Add(new SearchResult() { NameTable = "ProperNouns", IdResult = item.Id, Summary = item.Name });
}
}
if (namePlaces.Count() != 0)
{
foreach (var item in namePlaces)
{
searchResults.Add(new SearchResult() { NameTable = "NamePlaces", IdResult = item.Id, Summary = string.IsNullOrEmpty(item.DescriptionEn) ? item.Place : item.Place + " - " + item.DescriptionEn });
}
}
if (dictionaryTocharians.Count() != 0)
{
foreach (var item in dictionaryTocharians)
{
string[] myStrings = new string[] { item.WordClass.ClassEn, ":", item.WordSubClass.SubClassEn, item.Word, item.TochLanguage.Language, item.English, item.Francaise, item.German, item.Latin, item.Chinese };
searchResults.Add(new SearchResult() { NameTable = "DictionaryTocharians", IdResult = item.Id, Summary = string.Join(" - ", myStrings.Where(str => !string.IsNullOrEmpty(str))) });
}
}
if (tochPhrases.Count() != 0)
{
foreach (var item in tochPhrases)
{
searchResults.Add(new SearchResult() { NameTable = "TochPhrases", IdResult = item.Id, Summary = item.Phrase.Substring(0, Math.Min(40, item.Phrase.Length)) });
}
}
if (manuscripts.Count() != 0)
{
foreach (var item in manuscripts)
{
searchResults.Add(new SearchResult() { NameTable = "Manuscripts", IdResult = item.Id, Summary = item.Transcription.Substring(0, Math.Min(40, item.Transliteration.Length)) });
}
}
if (bibliographys.Count() != 0)
{
foreach (var item in bibliographys)
{
searchResults.Add(new SearchResult() { NameTable = "Bibliographys", IdResult = item.Id, Summary = item.Title.Substring(0, Math.Min(40, item.Title.Length)) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchIndex", db.SearchResults.ToList());
}
public ActionResult SearchDictionary(string search)
{
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("WordClass").Include("WordSubClass").Include("TochLanguage");
if (!string.IsNullOrWhiteSpace(search))
{
dictionaryTocharians = dictionaryTocharians.Where(x => x.Word.Contains(search)
|| (x.EquivalentTA != null && x.EquivalentTA.Contains(search))
|| (x.EquivalentTB != null && x.EquivalentTB.Contains(search))
|| (x.Sanskrit != null && x.Sanskrit.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))); ;
}
if (dictionaryTocharians.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = dictionaryTocharians.Count();
ViewBag.Search = search;
return View("SearchDictionary", dictionaryTocharians.OrderBy(x => x.Word.ToList()));
}
//For edit and create
[ChildActionOnly]
public ActionResult SpecialCharacter()
{
return PartialView();
}
//Form search common
[ChildActionOnly]
public ActionResult SearchForm()
{
return PartialView();
}
}
}
<file_sep>/Horizone/Models/DictionaryTocharian.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Horizone.Models
{
public class DictionaryTocharian
{
//Common
public int Id { get; set; }
[Display(Name = "Tocharian", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Word { get; set; }
[Display(Name = "Sanskrit", ResourceType = typeof(StaticResource.Resources))]
public string Sanskrit { get; set; }
[Display(Name = "English", ResourceType = typeof(StaticResource.Resources))]
public string English { get; set; }
[Display(Name = "French", ResourceType = typeof(StaticResource.Resources))]
public string Francaise { get; set; }
[Display(Name = "German", ResourceType = typeof(StaticResource.Resources))]
public string German { get; set; }
[Display(Name = "Latin", ResourceType = typeof(StaticResource.Resources))]
public string Latin { get; set; }
[Display(Name = "Chinese", ResourceType = typeof(StaticResource.Resources))]
public string Chinese { get; set; }
[Display(Name = "WordClass", ResourceType = typeof(StaticResource.Resources))]
public int WordClassId { get; set; }
[ForeignKey("WordClassId")]
public WordClass WordClass { get; set; }
[Display(Name = "WordSubClass", ResourceType = typeof(StaticResource.Resources))]
public int WordSubClassId { get; set; }
[ForeignKey("WordSubClassId")]
public WordSubClass WordSubClass { get; set; }
[Display(Name = "TochLanguage", ResourceType = typeof(StaticResource.Resources))]
public int TochLanguageId { get; set; }
[ForeignKey("TochLanguageId")]
public TochLanguage TochLanguage { get; set; }
[Display(Name = "EquivalentTocharianA", ResourceType = typeof(StaticResource.Resources))]
public string EquivalentTA { get; set; }
[Display(Name = "EquivalentTocharianB", ResourceType = typeof(StaticResource.Resources))]
public string EquivalentTB { get; set; }
[Display(Name = "TochCommon", ResourceType = typeof(StaticResource.Resources))]
public string TochCommon { get; set; }
[Display(Name = "TochCorrespondence", ResourceType = typeof(StaticResource.Resources))]
public string TochCorrespondence { get; set; }
[Display(Name = "EquivalentInOther", ResourceType = typeof(StaticResource.Resources))]
public string EquivalentInOther { get; set; }
[Display(Name = "DerivedFrom", ResourceType = typeof(StaticResource.Resources))]
public string DerivedFrom { get; set; }
[Display(Name = "RelatedLexemes", ResourceType = typeof(StaticResource.Resources))]
public string RelatedLexemes { get; set; }
[Display(Name = "RootCharacter", ResourceType = typeof(StaticResource.Resources))]
public string RootCharacter { get; set; }
[Display(Name = "InternalRootVowel", ResourceType = typeof(StaticResource.Resources))]
public string InternalRootVowel { get; set; }
[Display(Name = "Stem", ResourceType = typeof(StaticResource.Resources))]
public string Stem { get; set; }
[Display(Name = "StemClass", ResourceType = typeof(StaticResource.Resources))]
public string StemClass { get; set; }
[Display(Name = "Number", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Number> Numbers { get; set; }
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Bibliography> Bibliographys { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
}
}<file_sep>/Horizone/Controllers/HomeController.cs
using Horizone.Models;
using Newtonsoft.Json.Linq;
using Rotativa;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace Horizone.Controllers
{
public class HomeController : BaseController
{
//Menu standard
public ActionResult Index()
{
return View();
}
[ChildActionOnly]
public ActionResult SpecialCharacter()
{
return PartialView();
}
public ActionResult About()
{
var aboutProjets = db.AboutProjets.Include(a => a.Language);
return View(aboutProjets.ToList());
}
public ActionResult Contact()
{
var aboutProjets = db.AboutProjets.Include(a => a.Language);
return View(aboutProjets.ToList());
}
//Menu Aide
public ActionResult Aide()
{
var visualAids = db.VisualAids.Include(v => v.Language);
var question = db.VisualAids.Include(v => v.Language).Where(x => x.Question == true);
ViewBag.Aide = new SelectList(question, "Id", "Aids");
return View(visualAids.ToList());
}
//Pas fait//
public ActionResult Photographs()
{
return View();
}
//Pas fait
public ActionResult Glossary()
{
return View();
}
[ChildActionOnly]
public ActionResult Map()
{
ViewBag.Place = new SelectList(db.ImageMaps, "Id", "NamePicture");
return PartialView(db.Maps.Include("ImageMaps").OrderBy(x => x.NamePicture).ToList());
}
//Presentation pour homepage
[ChildActionOnly]
public ActionResult PresenteProject()
{
// var currentCulture = Session[CommonConstants.CurrentCulture];
//var symbolLanguage = currentCulture.ToString();
var aboutProjets = db.AboutProjets.Include("ImageProjects").Include("Language");
return PartialView(aboutProjets.ToList());
}
[ChildActionOnly]
public ActionResult LatestStory()
{
var latestStories = db.TochStorys.Include("ThemeStory").Include("SourceStory");
return PartialView(latestStories.OrderByDescending(x => x.Id).Take(3).ToList());
}
//Presentation pour tous menus
[ChildActionOnly]
public ActionResult PresentationTochPhrase()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationTochStory()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationManuscript()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationDictionaryTocharian()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationActivity()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
public ActionResult PresentationAboutUs()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationBibliography()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
[ChildActionOnly]
public ActionResult PresentationVisualAid()
{
return PartialView(db.Presentations.Include(a => a.Language).ToList());
}
//Menu about us
public ActionResult AboutUs()
{
var collaborations = db.Collaborations;
foreach (var item in collaborations)
if (item.Team) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
public ActionResult Collaboration()
{
var collaborations = db.Collaborations;
foreach (var item in db.Collaborations)
if (item.Collaborator) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
public ActionResult AssociatedResearcher()
{
var collaborations = db.Collaborations;
foreach (var item in db.Collaborations)
if (item.AssociatedResearcher) collaborations.Add(item);
return View(collaborations.Include("Publications").Include("ImageCollaborations").OrderBy(x => x.Order).ToList());
}
public ActionResult Partner()
{
var partnerAndRelations = db.PartnerAndRelations;
foreach (var item in db.PartnerAndRelations)
if (item.Partner) partnerAndRelations.Add(item);
return View(partnerAndRelations.Include("ImagePartners").OrderBy(x => x.Order).ToList());
}
public ActionResult RelationInternational()
{
var partnerAndRelations = db.PartnerAndRelations;
foreach (var item in db.PartnerAndRelations)
if (item.Relation) partnerAndRelations.Add(item);
return View(partnerAndRelations.Include("ImagePartners").OrderBy(x => x.Order).ToList());
}
public FileResult DownLoad(int id)
{
var collaborations = db.Collaborations;
var fullPath = "~/Equipe/" + id + "123-" + collaborations.Find(id).CV;
return File(fullPath, "application/CV-Download", Path.GetFileName(fullPath));
}
//Link
[ChildActionOnly]
public ActionResult LinkMenu()
{
return PartialView(db.LinkAndPresses.ToList());
}
//Press
[ChildActionOnly]
public ActionResult Presse()
{
return PartialView(db.LinkAndPresses.ToList());
}
//TochStory
public ActionResult TochHistoire()
{
return View(db.TochStorys.Include("SourceStory").Include("ThemeStory").OrderBy(x => x.Name).ToList());
}
// GET: BackOffice/TochStories/Details/5
public ActionResult DetailsStory(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochStory tochStory = db.TochStorys.Include("SourceStory").Include("ThemeStory").SingleOrDefault(x => x.Id == id);
if (tochStory == null)
{
return HttpNotFound();
}
return View(tochStory);
}
public ActionResult ThemeStory()
{
return View(db.ThemeStorys);
}
public ActionResult NamePlace()
{
return View(db.NamePlaces.OrderBy(x => x.Place).ToList());
}
public ActionResult PlaceInStory()
{
return View("NamePlace",db.NamePlaces.Where(x => x.InStory == true).OrderBy(x => x.Place).ToList());
}
public ActionResult ProperNoun()
{
return View(db.ProperNouns.OrderBy(x => x.Name).ToList());
}
public ActionResult NameInStory()
{
return View("ProperNoun",db.ProperNouns.Where(x=>x.InStory==true).OrderBy(x => x.Name).ToList());
}
public ActionResult SourceStory()
{
IEnumerable<SourceStory> sourceStories = db.SourceStorys;
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
sourceStories.OrderBy(x => x.SourceEn.ToList());
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
sourceStories.OrderBy(x => x.SourceFr.ToList());
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
sourceStories.OrderBy(x => x.SourceZh.ToList());
}
return View(sourceStories);
}
// Search
public ActionResult SearchName(string search)
{
IEnumerable<ProperNoun> properNouns = db.ProperNouns;
if (!string.IsNullOrWhiteSpace(search))
{
properNouns = properNouns.Where(x => x.Name.Contains(search));
}
if (properNouns.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchName", properNouns.OrderBy(x => x.Name).ToList());
}
public ActionResult SearchTheme(string search)
{
IEnumerable<ThemeStory> themeStorys = db.ThemeStorys;
if (!string.IsNullOrWhiteSpace(search))
{
themeStorys = themeStorys.Where(x => x.ThemeEn.Contains(search)
|| x.ThemeFr.Contains(search) || x.ThemeZn.Contains(search));
}
if (themeStorys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
themeStorys.OrderBy(x => x.ThemeEn).ToList();
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
themeStorys.OrderBy(x => x.ThemeFr).ToList();
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
themeStorys.OrderBy(x => x.ThemeZn).ToList();
}
return View("SearchTheme", themeStorys);
}
public ActionResult SearchStory(string search)
{
IEnumerable<TochStory> tochStories = db.TochStorys.Include("SourceStory").Include("ThemeStory");
if (!string.IsNullOrWhiteSpace(search))
{
tochStories = tochStories.Where(x => (x.Content != null && x.Content.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.SourceStory.SourceEn != null && x.SourceStory.SourceEn.Contains(search))
|| (x.SourceStory.SourceFr != null && x.SourceStory.SourceFr.Contains(search))
|| (x.SourceStory.SourceZh != null && x.SourceStory.SourceZh.Contains(search))
|| (x.Name != null && x.Name.Contains(search))
|| (x.SourceStory.SourceEn != null && x.Description.Contains(search))
|| (x.ThemeStory.ThemeEn != null && x.ThemeStory.ThemeEn.Contains(search))
|| (x.ThemeStory.ThemeFr != null && x.ThemeStory.ThemeFr.Contains(search))
|| (x.ThemeStory.ThemeZn != null && x.ThemeStory.ThemeZn.Contains(search)));
}
if (tochStories.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchStory", tochStories.OrderBy(x => x.Name).ToList());
}
public ActionResult RefreshSearch()
{
foreach (var item in db.SearchResults)
{
db.SearchResults.Remove(item);
}
db.SaveChanges();
return RedirectToAction("SearchIndex");
}
public ActionResult SearchIndex(string search)
{
RefreshSearch();
if (!string.IsNullOrWhiteSpace(search))
{
IEnumerable<TochStory> tochStories = db.TochStorys.Include("SourceStory").Include("ThemeStory").Where(x => (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.Content != null && x.Content.Contains(search))
|| (x.SourceStory.SourceEn != null && x.SourceStory.SourceEn.Contains(search))
|| (x.Name != null && x.Name.Contains(search))
|| (x.Description != null && x.Description.Contains(search))
|| (x.ThemeStory.ThemeEn != null && x.ThemeStory.ThemeEn.Contains(search))
|| (x.ThemeStory.ThemeFr != null && x.ThemeStory.ThemeFr.Contains(search))
|| (x.ThemeStory.ThemeZn != null && x.ThemeStory.ThemeZn.Contains(search)));
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("TochLanguage").Include("WordClass").Include("WordSubClass").Where(x => x.Word.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search)));
IEnumerable<TochPhrase> tochPhrases = db.TochPhrases.Include("TochLanguage").Where(x => x.Phrase.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search)));
IEnumerable<Manuscript> manuscripts = db.Manuscripts.Include("Catalogie").Include("TochLanguage").Where(x => x.Index.Contains(search)
|| x.Catalogie.Name.Contains(search)
|| (x.Title != null && x.Title.Contains(search))
|| (x.Transcription != null && x.Transcription.Contains(search))
|| x.TochLanguage.Language.Contains(search));
IEnumerable<Bibliography> bibliographys = db.Bibliographys.Where(x => x.Title.Contains(search)
|| x.Journal.Contains(search) || x.Author.Contains(search));
IEnumerable<NamePlace> namePlaces = db.NamePlaces.Where(x => x.Place.Contains(search));
IEnumerable<ProperNoun> properNouns = db.ProperNouns.Where(x => (x.Name != null && x.Name.Contains(search)));
IEnumerable<SearchResult> results = db.SearchResults;
List<SearchResult> searchResults = new List<SearchResult>();
if (tochStories.Count() != 0) {
foreach (var item in tochStories)
{
searchResults.Add(new SearchResult() { NameTable = "TochStorys", IdResult = item.Id, Summary = item.Name.Substring(0,Math.Min(40,item.Name.Length)) });
}
}
if (properNouns.Count() != 0)
{
foreach (var item in properNouns)
{
searchResults.Add(new SearchResult() { NameTable = "ProperNouns", IdResult = item.Id, Summary = item.Name });
}
}
if (namePlaces.Count() != 0)
{
foreach (var item in namePlaces)
{
searchResults.Add(new SearchResult() { NameTable = "NamePlaces", IdResult = item.Id, Summary = string.IsNullOrEmpty(item.DescriptionEn) ? item.Place : item.Place + " - " + item.DescriptionEn });
}
}
if (dictionaryTocharians.Count() != 0)
{
foreach (var item in dictionaryTocharians)
{
string[] myStrings = new string[] { item.Word, item.TochLanguage.Language, item.WordClass.ClassEn, item.WordSubClass.SubClassEn, item.English, item.Francaise, item.German, item.Latin, item.Chinese };
searchResults.Add(new SearchResult() { NameTable = "DictionaryTocharians", IdResult = item.Id, Summary = string.Join(" - ", myStrings.Where(str => !string.IsNullOrEmpty(str)))});
}
}
if (tochPhrases.Count() != 0)
{
foreach (var item in tochPhrases)
{
searchResults.Add(new SearchResult() { NameTable = "TochPhrases", IdResult = item.Id, Summary = item.Phrase.Substring(0,Math.Min(40, item.Phrase.Length)) });
}
}
if (manuscripts.Count() != 0)
{
foreach (var item in manuscripts)
{
searchResults.Add(new SearchResult() { NameTable = "Manuscripts", IdResult = item.Id, Summary = item.Transcription.Substring(0,Math.Min(40, item.Transliteration.Length)) });
}
}
if (bibliographys.Count() != 0)
{
foreach (var item in bibliographys)
{
searchResults.Add(new SearchResult() { NameTable = "Bibliographys", IdResult = item.Id, Summary = item.Title.Substring(0,Math.Min(40, item.Title.Length)) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchIndex",db.SearchResults.ToList());
}
[ChildActionOnly]
public ActionResult SearchMap(string search)
{
IEnumerable<Map> maps = db.Maps.Include("ImageMap");
if (!string.IsNullOrWhiteSpace(search))
{
maps = maps.Where(x => x.NamePicture == search);
}
if (maps.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return PartialView("Map", maps.OrderBy(x => x.NamePicture).ToList());
}
public ActionResult SearchQuestion(string search)
{
IEnumerable<VisualAid> visualAids = db.VisualAids.Where(x => x.Question == true);
if (!string.IsNullOrWhiteSpace(search))
{
visualAids = visualAids.Where(x => x.Aids.Contains(search));
}
if (visualAids.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchQuestion", visualAids.ToList());
}
//Form search common
[ChildActionOnly]
public ActionResult SearchForm()
{
return PartialView();
}
public ActionResult PrintHistoire(int? id)
{
var report = new ActionAsPdf("DetailsStory", new { id = id });
return report;
}
//Activity sur menu
public ActionResult Activity()
{
var activitys = db.Activitys.Include("Language").Include("Topic");
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
//Activity Home page
[ChildActionOnly]
public ActionResult PageActivity()
{
var activitys = db.Activitys.Include("Language").Include("Topic");
return PartialView(activitys.OrderByDescending(x => x.Id).Take(3).ToList());
}
public ActionResult Symposia()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 14);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
public ActionResult Publications()
{
return View(db.Publications.OrderByDescending(x => x.Id).ToList());
}
[ChildActionOnly]
public ActionResult PagePublication()
{
return PartialView(db.Publications.OrderByDescending(x => x.Id).Take(3).ToList());
}
public ActionResult ConferencesAndSeminar()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 13 || x.Topic.Id == 9);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
public ActionResult Missions()
{
var activitys = db.Activitys.Include("Language").Include("Topic").Where(x => x.Topic.Id == 15);
return View(activitys.OrderByDescending(x => x.Id).ToList());
}
}
}<file_sep>/Horizone/Models/NamePlace.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class NamePlace
{
public int Id { get; set; }
[Display(Name = "NamePlaces", ResourceType = typeof(StaticResource.Resources))]
public string Place { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionEn { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionFr { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionZh { get; set; }
[Display(Name = "TochStory", ResourceType = typeof(StaticResource.Resources))]
public Boolean InStory { get; set; }
}
}<file_sep>/Horizone/Controllers/VocabulariesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Horizone.Models;
using PagedList;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Net;
using Horizone.Controllers;
using Rotativa;
namespace Horizone.Controllers
{
public class VocabulariesController : BaseController
{
// GET: Vocabularies
public ActionResult Vocabulaire(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers");
return View(dictionaryTocharians.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
public ActionResult Parallel(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
public ActionResult TocharianA(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Where(x =>x.TochLanguage.Language.Contains("TA")).Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.EquivalentTA).ToPagedList(page, pageSize));
}
public ActionResult TocharianB(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Where(x => x.TochLanguage.Language.Contains("TB")).Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.EquivalentTB).ToPagedList(page, pageSize));
}
public ActionResult Verb()
{
var verbs = db.Verbs.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Persons").Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Verb");
return View(verbs.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult Adverb()
{
var otherWords = db.OtherWords.Include(d => d.DictionaryTocharian).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.Numbers).Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Adverb" || x.DictionaryTocharian.WordSubClass.SubClassEn == "Adverb");
return View(otherWords.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult Noun()
{
var nounAdjectives = db.NounAdjectives.Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Noun").Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Cases").Include("Genders");
return View(nounAdjectives.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult Pronoun()
{
var pronouns = db.Pronouns.Include(d => d.DictionaryTocharian).Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Cases").Include("Genders").Include("Persons").Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Pronoun");
return View(pronouns.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult Adjective()
{
var nounAdjectives = db.NounAdjectives.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Cases").Include("Genders").Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Adjective");
return View(nounAdjectives.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult OtherWord()
{
var otherWords = db.OtherWords.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers);
return View(otherWords.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
public ActionResult Abbreviation(int page = 1, int pageSize = 200)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.OtherAbbreviation == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationGrammatical(int page = 1, int pageSize = 200)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.GrammaticalAbbreviation == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationLanguage(int page = 1, int pageSize = 200)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x => x.AbbreviationsLanguage == true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult AbbreviationManuscript(int page = 1, int pageSize = 200)
{
var abbreviationDictionaries = db.AbbreviationDictionaries.Where(x=>x.AbbreviationManuscript==true);
return View(abbreviationDictionaries.OrderBy(x => x.Symbol).ToPagedList(page, pageSize));
}
public ActionResult Reverse(int page = 1, int pageSize = 200)
{
var reverseDictionaries = db.ReverseDictionaries;
return View(reverseDictionaries.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
public ActionResult PrintVocabulaire()
{
var report = new ActionAsPdf("Vocabulaire");
return report;
}
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers").SingleOrDefault(y => y.Id == id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
return View(dictionaryTocharian);
}
public ActionResult DetailsVerb(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Verb verb = db.Verbs.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Persons").SingleOrDefault(y => y.Id == id);
if (verb == null)
{
return HttpNotFound();
}
return View(verb);
}
public ActionResult DetailsOtherWord(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
OtherWord otherWord = db.OtherWords.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).SingleOrDefault(y => y.Id == id);
if (otherWord == null)
{
return HttpNotFound();
}
return View(otherWord);
}
public ActionResult DetailsNoun(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NounAdjective nounAdjective = db.NounAdjectives.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Cases").Include("Genders").SingleOrDefault(y => y.Id == id);
if (nounAdjective == null)
{
return HttpNotFound();
}
return View(nounAdjective);
}
public ActionResult DetailsPronoun(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pronoun pronoun = db.Pronouns.Include(d => d.DictionaryTocharian.TochLanguage).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass).Include(d => d.DictionaryTocharian.Numbers).Include("Cases").Include("Genders").Include("Persons").SingleOrDefault(y => y.Id == id);
if (pronoun == null)
{
return HttpNotFound();
}
return View(pronoun);
}
public ActionResult RefreshSearch()
{
foreach (var item in db.SearchResults)
{
db.SearchResults.Remove(item);
}
db.SaveChanges();
return RedirectToAction("SearchWord");
}
public ActionResult SearchWord(string search)
{
RefreshSearch();
if (!string.IsNullOrWhiteSpace(search))
{
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("WordClass").Include("WordSubClass").Include("TochLanguage").Where(x => x.Word.Contains(search)
|| (x.EquivalentTA != null && x.EquivalentTA.Contains(search))
|| (x.EquivalentTB != null && x.EquivalentTB.Contains(search))
|| (x.Sanskrit != null && x.Sanskrit.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))); ;
IEnumerable<NamePlace> namePlaces = db.NamePlaces.Where(x => x.Place.Contains(search)); ;
IEnumerable<ProperNoun> properNouns = db.ProperNouns.Where(x => x.Name.Contains(search));
List<SearchResult> searchResults = new List<SearchResult>();
if (properNouns.Count() != 0)
{
foreach (var item in properNouns)
{
searchResults.Add(new SearchResult() { NameTable = "ProperNouns", IdResult = item.Id, Summary = item.Name });
}
}
if (namePlaces.Count() != 0)
{
foreach (var item in namePlaces)
{
searchResults.Add(new SearchResult() { NameTable = "NamePlaces", IdResult = item.Id, Summary = string.IsNullOrEmpty(item.DescriptionEn) ? item.Place : item.Place + " - " + item.DescriptionEn });
}
}
if (dictionaryTocharians.Count() != 0)
{
foreach (var item in dictionaryTocharians)
{
string[] myStrings = new string[] { item.Word, item.TochLanguage.Language, item.WordClass.ClassEn, item.WordSubClass.SubClassEn, item.English, item.Francaise, item.German, item.Latin, item.Chinese };
searchResults.Add(new SearchResult() { NameTable = "DictionaryTocharians", IdResult = item.Id, Summary = string.Join(" - ", myStrings.Where(str => !string.IsNullOrEmpty(str))) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchWord", db.SearchResults.ToList());
}
public ActionResult SearchAbbreviation(string search)
{
IEnumerable<AbbreviationDictionary> abbreviationDictionarys = db.AbbreviationDictionaries;
IEnumerable<Abreviation> abbreviations = db.Abreviations;
List<SearchResult> searchResults = new List<SearchResult>();
foreach (var item in db.SearchResults)
{
db.SearchResults.Remove(item);
}
if (!string.IsNullOrWhiteSpace(search))
{
abbreviationDictionarys = db.AbbreviationDictionaries.Where(x => x.Symbol == search);
if (abbreviationDictionarys.Count() != 0)
{
foreach (var item in abbreviationDictionarys)
{
searchResults.Add(new SearchResult() { NameTable = "AbbreviationDictionaries", IdResult = item.Id, Summary = item.Symbol + " - " + item.Description });
}
}
abbreviations = db.Abreviations.Where(x => x.Symbol == search);
if (abbreviations.Count() != 0)
{
foreach (var item in abbreviations)
{
searchResults.Add(new SearchResult() { NameTable = "Abbreviations", IdResult = item.Id, Summary = (item.Symbol + " - " + item.Description) });
}
}
foreach (var item in searchResults)
{
db.SearchResults.Add(item);
db.SaveChanges();
}
}
ViewBag.Search = search;
return View("SearchAbbreviation", db.SearchResults.ToList());
}
public ActionResult SearchNounAdjective(string search)
{
IEnumerable<NounAdjective> nounAdjectives = db.NounAdjectives.Include(d => d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
nounAdjectives = nounAdjectives.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (nounAdjectives.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = nounAdjectives.Count();
ViewBag.Search = search;
return View("SearchNounAdjective", nounAdjectives.ToList());
}
public ActionResult SearchPronoun(string search)
{
IEnumerable<Pronoun> pronouns = db.Pronouns.Include(d => d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
pronouns = pronouns.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (pronouns.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = pronouns.Count();
ViewBag.Search = search;
return View("SearchPronoun", pronouns.ToList());
}
public ActionResult SearchVerb(string search)
{
IEnumerable<Verb> verbs = db.Verbs.Include(d => d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
verbs = verbs.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (verbs.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = verbs.Count();
ViewBag.Search = search;
return View("SearchVerb", verbs.ToList());
}
// GET: BackOffice/Verbs/Details/5
public ActionResult DetailsAbbreviationDictionary(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AbbreviationDictionary abbreviationDictionary = db.AbbreviationDictionaries.SingleOrDefault(y => y.Id == id);
if (abbreviationDictionary == null)
{
return HttpNotFound();
}
return View(abbreviationDictionary);
}
public ActionResult SearchReverse(string search)
{
IEnumerable<ReverseDictionary> reverseDictionarys = db.ReverseDictionaries;
if (!string.IsNullOrWhiteSpace(search))
{
reverseDictionarys = reverseDictionarys.Where(x=>x.ReverseWord.Contains(search));
}
if (reverseDictionarys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchReverse", reverseDictionarys.ToList());
}
public ActionResult SearchEnd(string search)
{
IEnumerable<ReverseDictionary> reverseDictionarys = db.ReverseDictionaries;
if (!string.IsNullOrWhiteSpace(search))
{
int i = search.Length;
reverseDictionarys = reverseDictionarys.Where(x => x.ReverseWord.Length >=i && x.ReverseWord.Substring(x.ReverseWord.Length-i,i) ==search);
}
if (reverseDictionarys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchReverse", reverseDictionarys.ToList());
}
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/AnalyseMaterialsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class AnalyseMaterialsController : BaseController
{
// GET: BackOffice/AnalyseMaterials
public ActionResult Index()
{
return View(db.AnalyseMaterials.Include("ImageUVs").Include("ImageAnalyses").ToList());
}
// GET: BackOffice/AnalyseMaterials/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMaterial analyseMaterial = db.AnalyseMaterials.Find(id);
if (analyseMaterial == null)
{
return HttpNotFound();
}
return View(analyseMaterial);
}
// GET: BackOffice/AnalyseMaterials/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/AnalyseMaterials/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Index,Description,Order")] AnalyseMaterial analyseMaterial)
{
if (ModelState.IsValid)
{
db.AnalyseMaterials.Add(analyseMaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(analyseMaterial);
}
// GET: BackOffice/AnalyseMaterials/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMaterial analyseMaterial = db.AnalyseMaterials.Find(id);
if (analyseMaterial == null)
{
return HttpNotFound();
}
return View(analyseMaterial);
}
// POST: BackOffice/AnalyseMaterials/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Index,Description,Order")] AnalyseMaterial analyseMaterial)
{
if (ModelState.IsValid)
{
db.Entry(analyseMaterial).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(analyseMaterial);
}
// GET: BackOffice/AnalyseMaterials/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMaterial analyseMaterial = db.AnalyseMaterials.Find(id);
if (analyseMaterial == null)
{
return HttpNotFound();
}
return View(analyseMaterial);
}
// POST: BackOffice/AnalyseMaterials/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
AnalyseMaterial analyseMaterial = db.AnalyseMaterials.Find(id);
db.AnalyseMaterials.Remove(analyseMaterial);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageAnalyse();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.AnalyseMaterialId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageAnalyses.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "AnalyseMaterials", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "AnalyseMaterials", new { id = id });
}
public ActionResult DeletePicture(int id, int idAnalyseMaterial)
{
ImageAnalyse image = db.ImageAnalyses.Find(id);
db.ImageAnalyses.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "AnalyseMaterials", new { id = idAnalyseMaterial });
}
[HttpPost]
public ActionResult AddPictureUV(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageUV();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.AnalyseMaterialId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageUVs.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "AnalyseMaterials", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "AnalyseMaterials", new { id = id });
}
public ActionResult DeletePictureUV(int id, int idAnalyseMaterial)
{
ImageUV image = db.ImageUVs.Find(id);
db.ImageUVs.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "AnalyseMaterials", new { id = idAnalyseMaterial });
}
}
}
<file_sep>/Horizone/Models/FiberDistribution.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class FiberDistribution
{
public int Id { get; set; }
[Display(Name = "FiberDistribution", ResourceType = typeof(StaticResource.Resources))]
public string DistributionEn { get; set; }
[Display(Name = "FiberDistribution", ResourceType = typeof(StaticResource.Resources))]
public string DistributionFr { get; set; }
[Display(Name = "FiberDistribution", ResourceType = typeof(StaticResource.Resources))]
public string DistributionZh { get; set; }
}
}<file_sep>/Horizone/Models/TochStory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class TochStory
{
public int Id { get; set; }
[Display(Name = "NameStory", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MaxLength500", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Name { get; set; }
[Display(Name = "SourceStory", ResourceType = typeof(StaticResource.Resources))]
public int SourceStoryId { get; set; }
[ForeignKey("SourceStoryId")]
public SourceStory SourceStory { get; set; }
[Display(Name = "ThemeStory", ResourceType = typeof(StaticResource.Resources))]
public int ThemeStoryId { get; set; }
[ForeignKey("ThemeStoryId")]
public ThemeStory ThemeStory { get; set; }
[Display(Name = "PlasticRepresentation", ResourceType = typeof(StaticResource.Resources))]
public string PlasticRepresentation { get; set; }
[Display(Name = "MainFindSpot", ResourceType = typeof(StaticResource.Resources))]
public string MainFindSpot { get; set; }
[AllowHtml]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "Content")]
public string Content { get; set; }
[AllowHtml]
[Display(Name = "English", ResourceType = typeof(StaticResource.Resources))]
public string English { get; set; }
[AllowHtml]
[Display(Name = "French", ResourceType = typeof(StaticResource.Resources))]
public string Francaise { get; set; }
[AllowHtml]
[Display(Name = "Chinese", ResourceType = typeof(StaticResource.Resources))]
public string Chinese { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Bibliography> Bibliographys { get; set; }
}
}<file_sep>/Horizone/Models/Presentation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Presentation
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "AboutUs", ResourceType = typeof(StaticResource.Resources))]
public string AboutUs { get; set; }
[AllowHtml]
[Display(Name = "TochPhrase", ResourceType = typeof(StaticResource.Resources))]
public string TochPhrase { get; set; }
[AllowHtml]
[Display(Name = "TochStory", ResourceType = typeof(StaticResource.Resources))]
public string TochStory { get; set; }
[AllowHtml]
[Display(Name = "Manuscript", ResourceType = typeof(StaticResource.Resources))]
public string Manuscript { get; set; }
[AllowHtml]
[Display(Name = "Activity", ResourceType = typeof(StaticResource.Resources))]
public string Activity { get; set; }
[AllowHtml]
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public string Bibliography { get; set; }
[AllowHtml]
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public string DictionaryTocharian { get; set; }
[AllowHtml]
[Display(Name = "Help", ResourceType = typeof(StaticResource.Resources))]
public string VisualAids { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
}
}<file_sep>/Horizone/Models/Publication.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Publication
{
public int Id { get; set; }
[Display(Name = "PublicationDate", ResourceType = typeof(StaticResource.Resources))]
[StringLength(10, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string PublicationDate { get; set; }
[AllowHtml]
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[AllowHtml]
[Display(Name = "Newspaper", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Journal { get; set; }
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string UlrBibliography { get; set; }
[Display(Name = "PublicationIndividual", ResourceType = typeof(StaticResource.Resources))]
public Boolean PublicationIndividual { get; set; }
[Display(Name = "Project", ResourceType = typeof(StaticResource.Resources))]
public Boolean PublicationProjet { get; set; }
[Display(Name = "Collaboration", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Collaboration> Collaborations { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/NewsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using Microsoft.AspNet.Identity;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class NewsController : BaseController
{
// GET: BackOffice/News
public ActionResult Index()
{
var newses = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic);
return View(newses.ToList());
}
// GET: BackOffice/News/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
News news = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic).Include(n => n.ImageNewses).SingleOrDefault(x => x.Id == id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
// GET: BackOffice/News/Create
public ActionResult Create()
{
ViewBag.CollaboratorId = new SelectList(db.Collaborators,"Id","FirstName");
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol");
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicFr", "TopicEn");
return View();
}
// POST: BackOffice/News/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Title,Summary,Content,View,TopicId,CollaboratorId,LanguageId")] News news)
{
if (ModelState.IsValid)
{
db.Newses.Add(news);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CollaboratorId = new SelectList(db.Collaborators, "Id", "FirstName", news.CollaboratorId);
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Symbol", news.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicFr", "TopicEn", news.TopicId);
return View(news);
}
// GET: BackOffice/News/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
News news = db.Newses.Include("ImageNewses").SingleOrDefault(x => x.Id == id);
if (news == null)
{
return HttpNotFound();
}
ViewBag.CollaboratorId = new SelectList(db.Collaborators, "Id", "FirstName", news.CollaboratorId);
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Name", news.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicFr", "TopicEn", news.TopicId);
return View(news);
}
// POST: BackOffice/News/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Summary,Content,View,TopicId,CollaboratorId,LanguageId")] News news)
{
db.Entry(news).State = EntityState.Modified;
db.Newses.Include("ImageNewses").Include("Language").Include("Topic").Include("Collaborator").SingleOrDefault(x => x.Id == news.Id);
if (ModelState.IsValid)
{
db.Entry(news).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CollaboratorId = new SelectList(db.Collaborators, "Id", "FirstName", news.CollaboratorId);
ViewBag.LanguageId = new SelectList(db.Languages, "Id", "Name", news.LanguageId);
ViewBag.TopicId = new SelectList(db.Topics, "Id", "TopicFr", "TopicEn", news.TopicId);
return View(news);
}
// GET: BackOffice/News/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
News news = db.Newses.Include("ImageNewses").Include("Comments").SingleOrDefault(x => x.Id == id);
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
[ChildActionOnly]
public ActionResult ListComment(int? id)
{
var comments = db.Comments.Include("News").Include("Client").Where(x => x.NewsId == id);
ViewBag.NewsId = id;
return PartialView(comments.OrderByDescending(x => x.Id).ToList());
}
public ActionResult NewComment(string search, int id)
{ string userId = User.Identity.GetUserId();
var comment = new Comment();
Client client = db.Clients.Include("ApplicationUser").SingleOrDefault(x => x.UserId == userId);
if (id != 0)
{
comment.Content = search;
comment.Date = DateTime.Now;
comment.NewsId = id;
comment.ClientId = client.Id;
}
if (ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(comment);
}
// POST: BackOffice/News/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
News news = db.Newses.Include("ImageNewses").Include("Comments").SingleOrDefault(x => x.Id == id);
db.Newses.Remove(news);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageNews();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.NewsId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageNews.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "News", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "News", new { id = id });
}
// GET
public ActionResult DeletePicture(int id, int idnews)
{
ImageNews image = db.ImageNews.Find(id);
db.ImageNews.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "News", new { id = idnews });
}
}
}
<file_sep>/Horizone/Models/Language.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Language
{
public int Id { get; set; }
[StringLength(20, MinimumLength = 2, ErrorMessageResourceName = "MaxLength20", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Symbol { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
[StringLength(40, MinimumLength = 1, ErrorMessageResourceName = "MaxLength40", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Name { get; set; }
public bool IsDefault { get; set; }
}
}<file_sep>/Horizone/Models/Person.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Person
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string ConjugatedPerson { get; set; }
[Display(Name = "PersonEn", ResourceType = typeof(StaticResource.Resources))]
public string ConjugatedPersonEn { get; set; }
[Display(Name = "PersonFr", ResourceType = typeof(StaticResource.Resources))]
public string ConjugatedPersonFr { get; set; }
[Display(Name = "PersonZh", ResourceType = typeof(StaticResource.Resources))]
public string ConjugatedPersonZh { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Verb> Verbs { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Pronoun> Pronouns { get; set; }
}
}<file_sep>/Horizone/Models/WordSubClass.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class WordSubClass
{
public int Id { get; set; }
[Display(Name = "WordSubClass", ResourceType = typeof(StaticResource.Resources))]
public string SubClass { get; set; }
[Display(Name = "WordSubClassEn", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string SubClassEn { get; set; }
[Display(Name = "WordSubClassFr", ResourceType = typeof(StaticResource.Resources))]
public string SubClassFr { get; set; }
[Display(Name = "WordSubClassZh", ResourceType = typeof(StaticResource.Resources))]
public string SubClassZh { get; set; }
[Display(Name = "WordClass", ResourceType = typeof(StaticResource.Resources))]
public int WordClassId { get; set; }
[ForeignKey("WordClassId")]
public WordClass WordClass { get; set; }
}
}<file_sep>/Horizone/Models/LanguageDetail.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class LanguageDetail
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "LanguageDetailEn", ResourceType = typeof(StaticResource.Resources))]
public string LanguageDetailEn { get; set; }
[AllowHtml]
[Display(Name = "LanguageDetailFr", ResourceType = typeof(StaticResource.Resources))]
public string LanguageDetailFr { get; set; }
[AllowHtml]
[Display(Name = "LanguageDetailZh", ResourceType = typeof(StaticResource.Resources))]
public string LanguageDetailZh { get; set; }
}
}<file_sep>/Horizone/Models/ScriptType.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class ScriptType
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "ScriptType", ResourceType = typeof(StaticResource.Resources))]
public string NameType { get; set; }
}
}<file_sep>/Horizone/Models/Dashboard.cs
using Horizone.Validators;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Dashboard
{
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/ManuscriptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ManuscriptsController : BaseController
{
// GET: BackOffice/Manuscripts
public ActionResult Index(int page = 1, int pageSize = 200)
{
var manuscripts = db.Manuscripts.Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool);
return View(manuscripts.OrderBy(x => x.Id).ToPagedList(page, pageSize));
}
// GET: BackOffice/Manuscripts/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x=>x.Catalogie).Include(x=>x.Map).Include(y => y.ImageManuscripts).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m=>m.Id==id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/layout/5
public ActionResult LayoutManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Description/5
public ActionResult OverallDescriptions(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Script/5
public ActionResult ScriptManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m=>m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Language/5
public ActionResult TextLanguages(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Details/Materiel/5
public ActionResult MaterialManuscripts(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
public ActionResult TextContents(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include(x => x.Catalogie).Include(x => x.Map).Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).SingleOrDefault(m => m.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Create
public ActionResult Create()
{
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture");
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name");
ViewBag.AlignmentTypeId = new SelectList(db.AlignmentTypes, "Id", "AlignmentTypeEn");
ViewBag.DescriptionManuscriptId = new SelectList(db.DescriptionManuscripts, "Id", "DescriptionEn");
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn");
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn");
ViewBag.LanguageDetailId = new SelectList(db.LanguageDetails, "Id", "LanguageDetailEn");
ViewBag.LanguageStageId = new SelectList(db.LanguageStages, "Id", "LanguageStageEn");
ViewBag.MaterialId = new SelectList(db.Materials, "Id", "MaterialEn");
ViewBag.MetricId = new SelectList(db.Metrics, "Id", "MetricEn");
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn");
ViewBag.RemarkAddId = new SelectList(db.RemarkAdds, "Id", "RemarkEn");
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn");
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn");
ViewBag.RulingDetailId = new SelectList(db.RulingDetails, "Id", "RulingDetailEn");
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn");
ViewBag.ScriptAddId = new SelectList(db.ScriptAdds, "Id", "ScriptAddEn");
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn");
ViewBag.SubGenderManuscriptId = new SelectList(db.SubGenderManuscripts, "Id", "SubGenderEn");
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language");
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn");
ViewBag.Bibliographys = new SelectList(db.Bibliographys, "Id", "Title");
return View();
}
// POST: BackOffice/Manuscripts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,CatalogieId,Index,Collection,Siglum,Joint,OtherSiglum,ExpeditionCode, MapId,SpecificFindSpot,StateId,DescriptionManuscriptId,RemarkAddId,LeafNumber,SizeHeight,Completeness,SizeWidth,NumberOfLine,LineDistance,FormatId,RulingId,RulingColorId,RulingDetailId,StringholeHeight,StringholeWidth,DistanceStringholeRight,DistanceStringholeLeft,InterruptedLine,Transliteration,Transcription,English,Francaise,Chinese,Editor,References,PhilologicalCommentary,MaterialId,PaperColorId,PaperThickness,WritingToolId,AlignmentTypeId,ModuleWidth,ModuleHeight,AvCharPerLigne,NibThickness,ScriptId,ScriptAddId,TochLanguageId,LanguageStageId,LanguageDetailId,GenderManuscriptId,SubGenderManuscriptId,Title,Passage,Parallel,MetricId,Tune,Cetom,Visible")] Manuscript manuscript, int[] BibliographyId)
{
if (BibliographyId.Count() > 0)
manuscript.Bibliographys = db.Bibliographys.Where(x => BibliographyId.Contains(x.Id)).ToList();
if (ModelState.IsValid)
{
db.Manuscripts.Add(manuscript);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", manuscript.MapId);
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name", manuscript.CatalogieId);
ViewBag.AlignmentTypeId = new SelectList(db.AlignmentTypes, "Id", "AlignmentTypeEn", manuscript.AlignmentTypeId);
ViewBag.DescriptionManuscriptId = new SelectList(db.DescriptionManuscripts, "Id", "DescriptionEn", manuscript.DescriptionManuscriptId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", manuscript.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", manuscript.GenderManuscriptId);
ViewBag.LanguageDetailId = new SelectList(db.LanguageDetails, "Id", "LanguageDetailEn", manuscript.LanguageDetailId);
ViewBag.LanguageStageId = new SelectList(db.LanguageStages, "Id", "LanguageStageEn", manuscript.LanguageStageId);
ViewBag.MaterialId = new SelectList(db.Materials, "Id", "MaterialEn", manuscript.MaterialId);
ViewBag.MetricId = new SelectList(db.Metrics, "Id", "MetricEn", manuscript.MetricId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", manuscript.PaperColorId);
ViewBag.RemarkAddId = new SelectList(db.RemarkAdds, "Id", "RemarkEn", manuscript.RemarkAddId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", manuscript.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", manuscript.RulingColorId);
ViewBag.RulingDetailId = new SelectList(db.RulingDetails, "Id", "RulingDetailEn", manuscript.RulingDetailId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", manuscript.ScriptId);
ViewBag.ScriptAddId = new SelectList(db.ScriptAdds, "Id", "ScriptAddEn", manuscript.ScriptAddId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", manuscript.StateId);
ViewBag.SubGenderManuscriptId = new SelectList(db.SubGenderManuscripts, "Id", "SubGenderEn", manuscript.SubGenderManuscriptId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", manuscript.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", manuscript.WritingToolId);
ViewBag.Bibliographys = new SelectList(db.Bibliographys, "Id", "Title");
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Include("ImageManuscripts").SingleOrDefault(x => x.Id == id);
if (manuscript == null)
{
return HttpNotFound();
}
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", manuscript.MapId);
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name");
ViewBag.AlignmentTypeId = new SelectList(db.AlignmentTypes, "Id", "AlignmentTypeEn", manuscript.AlignmentTypeId);
ViewBag.DescriptionManuscriptId = new SelectList(db.DescriptionManuscripts, "Id", "DescriptionEn", manuscript.DescriptionManuscriptId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", manuscript.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", manuscript.GenderManuscriptId);
ViewBag.LanguageDetailId = new SelectList(db.LanguageDetails, "Id", "LanguageDetailEn", manuscript.LanguageDetailId);
ViewBag.LanguageStageId = new SelectList(db.LanguageStages, "Id", "LanguageStageEn", manuscript.LanguageStageId);
ViewBag.MaterialId = new SelectList(db.Materials, "Id", "MaterialEn", manuscript.MaterialId);
ViewBag.MetricId = new SelectList(db.Metrics, "Id", "MetricEn", manuscript.MetricId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", manuscript.PaperColorId);
ViewBag.RemarkAddId = new SelectList(db.RemarkAdds, "Id", "RemarkEn", manuscript.RemarkAddId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", manuscript.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", manuscript.RulingColorId);
ViewBag.RulingDetailId = new SelectList(db.RulingDetails, "Id", "RulingDetailEn", manuscript.RulingDetailId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", manuscript.ScriptId);
ViewBag.ScriptAddId = new SelectList(db.ScriptAdds, "Id", "ScriptAddEn", manuscript.ScriptAddId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", manuscript.StateId);
ViewBag.SubGenderManuscriptId = new SelectList(db.SubGenderManuscripts, "Id", "SubGenderEn", manuscript.SubGenderManuscriptId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", manuscript.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", manuscript.WritingToolId);
ViewBag.Bibliographys = new SelectList(db.Bibliographys, "Id", "Title");
return View(manuscript);
}
// POST: BackOffice/Manuscripts/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,CatalogieId,Index,Collection,Siglum,Joint,OtherSiglum,ExpeditionCode,MapId,SpecificFindSpot,StateId,DescriptionManuscriptId,RemarkAddId,LeafNumber,SizeHeight,Completeness,SizeWidth,NumberOfLine,LineDistance,FormatId,RulingId,RulingColorId,RulingDetailId,StringholeHeight,StringholeWidth,DistanceStringholeRight,DistanceStringholeLeft,InterruptedLine,Transliteration,Transcription,English,Francaise,Chinese,Editor,References,PhilologicalCommentary,MaterialId,PaperColorId,PaperThickness,WritingToolId,AlignmentTypeId,ModuleWidth,ModuleHeight,AvCharPerLigne,NibThickness,ScriptId,ScriptAddId,TochLanguageId,LanguageStageId,LanguageDetailId,GenderManuscriptId,SubGenderManuscriptId,Title,Passage,Parallel,MetricId,Tune,Cetom,Visible")] Manuscript manuscript, int[] BibliographyId)
{
db.Entry(manuscript).State = EntityState.Modified;
db.Manuscripts.Include("Catalogie").Include("Map").Include("ImageManuscripts").Include("State").Include("DescriptionManuscript").Include("RemarkAdd").Include("Format").Include("Ruling").Include("RulingColor").Include("RulingDetail").Include("Material").Include("PaperColor").Include("WritingTool").Include("AlignmentType").Include("Script").Include("ScriptAdd").Include("LanguageStage").Include("Tochlanguage").Include("LanguageDetail").Include("GenderManuscript").Include("SubGenderManuscript").Include("Metric").Include("Bibliographys").SingleOrDefault(x => x.Id == manuscript.Id);
if (ModelState.IsValid)
{
if (BibliographyId != null)
manuscript.Bibliographys = db.Bibliographys.Where(x => BibliographyId.Contains(x.Id)).ToList();
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", manuscript.MapId);
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name", manuscript.CatalogieId);
ViewBag.AlignmentTypeId = new SelectList(db.AlignmentTypes, "Id", "AlignmentTypeEn", manuscript.AlignmentTypeId);
ViewBag.DescriptionManuscriptId = new SelectList(db.DescriptionManuscripts, "Id", "DescriptionEn", manuscript.DescriptionManuscriptId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", manuscript.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", manuscript.GenderManuscriptId);
ViewBag.LanguageDetailId = new SelectList(db.LanguageDetails, "Id", "LanguageDetailEn", manuscript.LanguageDetailId);
ViewBag.LanguageStageId = new SelectList(db.LanguageStages, "Id", "LanguageStageEn", manuscript.LanguageStageId);
ViewBag.MaterialId = new SelectList(db.Materials, "Id", "MaterialEn", manuscript.MaterialId);
ViewBag.MetricId = new SelectList(db.Metrics, "Id", "MetricEn", manuscript.MetricId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", manuscript.PaperColorId);
ViewBag.RemarkAddId = new SelectList(db.RemarkAdds, "Id", "RemarkEn", manuscript.RemarkAddId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", manuscript.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", manuscript.RulingColorId);
ViewBag.RulingDetailId = new SelectList(db.RulingDetails, "Id", "RulingDetailEn", manuscript.RulingDetailId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", manuscript.ScriptId);
ViewBag.ScriptAddId = new SelectList(db.ScriptAdds, "Id", "ScriptAddEn", manuscript.ScriptAddId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", manuscript.StateId);
ViewBag.SubGenderManuscriptId = new SelectList(db.SubGenderManuscripts, "Id", "SubGenderEn", manuscript.SubGenderManuscriptId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", manuscript.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", manuscript.WritingToolId);
ViewBag.Bibliographys = new SelectList(db.Bibliographys, "Id", "Title");
return View(manuscript);
}
// GET: BackOffice/Manuscripts/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Manuscript manuscript = db.Manuscripts.Find(id);
if (manuscript == null)
{
return HttpNotFound();
}
return View(manuscript);
}
// POST: BackOffice/Manuscripts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Manuscript manuscript = db.Manuscripts.Find(id);
db.Manuscripts.Remove(manuscript);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Search(string search)
{
IEnumerable<Manuscript> manuscripts = db.Manuscripts.Include("Catalogie").Include("Map").Include("ImageManuscripts").Include("State").Include("DescriptionManuscript").Include("RemarkAdd").Include("Format").Include("Ruling").Include("RulingColor").Include("RulingDetail").Include("Material").Include("PaperColor").Include("WritingTool").Include("AlignmentType").Include("Script").Include("ScriptAdd").Include("LanguageStage").Include("Tochlanguage").Include("LanguageDetail").Include("GenderManuscript").Include("SubGenderManuscript").Include("Metric").Include("Bibliographys");
if (!string.IsNullOrWhiteSpace(search))
{
manuscripts = db.Manuscripts.Include(m => m.AlignmentType).Include(m => m.DescriptionManuscript).Include(m => m.Format).Include(m => m.GenderManuscript).Include(m => m.LanguageDetail).Include(m => m.LanguageStage).Include(m => m.Material).Include(m => m.Metric).Include(m => m.PaperColor).Include(m => m.RemarkAdd).Include(m => m.Ruling).Include(m => m.RulingColor).Include(m => m.RulingDetail).Include(m => m.Script).Include(m => m.Script.ScriptType).Include(m => m.ScriptAdd).Include(m => m.State).Include(m => m.SubGenderManuscript).Include(m => m.TochLanguage).Include(m => m.WritingTool).Where(x => x.Transliteration.Contains(search)
|| x.Index.Contains(search) || x.Transcription.Contains(search) || x.TochLanguage.Language.Contains(search));
}
if (manuscripts.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("Search", manuscripts.ToList());
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageManuscript();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.ManuscriptId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageManuscripts.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "Manuscripts", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "Manuscripts", new { id = id });
}
// GET
public ActionResult DeletePicture(int id, int idmanuscript)
{
ImageManuscript image = db.ImageManuscripts.Find(id);
db.ImageManuscripts.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "Manuscripts", new { id = idmanuscript });
}
}
}
<file_sep>/Horizone/Models/Number.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Number
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string WordNumber { get; set; }
[Display(Name = "NumberEn", ResourceType = typeof(StaticResource.Resources))]
public string WordNumberEn { get; set; }
[Display(Name = "NumberFr", ResourceType = typeof(StaticResource.Resources))]
public string WordNumberFr { get; set; }
[Display(Name = "NumberEn", ResourceType = typeof(StaticResource.Resources))]
public string WordNumberZh { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<NounAdjective> NounAdjectives { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Verb> Verbs { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<OtherWord> OtherWords { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Pronoun> Pronouns { get; set; }
}
}<file_sep>/Horizone/Models/Pronoun.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Pronoun
{
public int Id { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public int DictionaryId { get; set; }
[ForeignKey("DictionaryId")]
public DictionaryTocharian DictionaryTocharian { get; set; }
[Display(Name = "Case", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Case> Cases { get; set; }
[Display(Name = "Gender", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Gender> Genders { get; set; }
[Display(Name = "Person", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Person> Persons { get; set; }
}
}<file_sep>/Horizone/Models/DescriptionManuscript.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class DescriptionManuscript
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "DescriptionEn", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionEn { get; set; }
[AllowHtml]
[Display(Name = "DescriptionFr", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionFr { get; set; }
[AllowHtml]
[Display(Name = "DescriptionZh", ResourceType = typeof(StaticResource.Resources))]
public string DescriptionZh { get; set; }
}
}<file_sep>/Horizone/Models/PreparationPaperBeforeUsing.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class PreparationPaperBeforeUsing
{
public int Id { get; set; }
[Display(Name = "PreparationPaperBeforeUsing", ResourceType = typeof(StaticResource.Resources))]
public string PreparationEn { get; set; }
[Display(Name = "PreparationPaperBeforeUsing", ResourceType = typeof(StaticResource.Resources))]
public string PreparationFr { get; set; }
[Display(Name = "PreparationPaperBeforeUsing", ResourceType = typeof(StaticResource.Resources))]
public string PreparationZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/ScriptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ScriptsController : BaseController
{
// GET: BackOffice/Scripts
public ActionResult Index()
{
var scripts = db.Scripts.Include(s => s.ScriptType);
return View(scripts.ToList());
}
public ActionResult Brahmi()
{
var scripts = db.Scripts.Include(s => s.ScriptType).Where(s => s.ScriptType.Id == 1);
return View(scripts.ToList());
}
public ActionResult Kharosthi()
{
var scripts = db.Scripts.Include(s => s.ScriptType).Where(s => s.ScriptType.Id == 2);
return View(scripts.ToList());
}
public ActionResult Ductus()
{
var scripts = db.Scripts.Include(s => s.ScriptType).Where(s=>s.ScriptType.Id == 3);
return View(scripts.ToList());
}
// GET: BackOffice/Scripts/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Script script = db.Scripts.Find(id);
if (script == null)
{
return HttpNotFound();
}
return View(script);
}
// GET: BackOffice/Scripts/Create
public ActionResult Create()
{
ViewBag.ScriptTypeId = new SelectList(db.ScriptTypes, "Id", "NameType");
return View();
}
// POST: BackOffice/Scripts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,ScriptEn,ScriptFr,ScriptZh,ScriptTypeId")] Script script)
{
if (ModelState.IsValid)
{
db.Scripts.Add(script);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScriptTypeId = new SelectList(db.ScriptTypes, "Id", "NameType", script.ScriptTypeId);
return View(script);
}
// GET: BackOffice/Scripts/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Script script = db.Scripts.Find(id);
if (script == null)
{
return HttpNotFound();
}
ViewBag.ScriptTypeId = new SelectList(db.ScriptTypes, "Id", "NameType", script.ScriptTypeId);
return View(script);
}
// POST: BackOffice/Scripts/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,ScriptEn,ScriptFr,ScriptZh,ScriptTypeId")] Script script)
{
if (ModelState.IsValid)
{
db.Entry(script).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ScriptTypeId = new SelectList(db.ScriptTypes, "Id", "NameType", script.ScriptTypeId);
return View(script);
}
// GET: BackOffice/Scripts/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Script script = db.Scripts.Find(id);
if (script == null)
{
return HttpNotFound();
}
return View(script);
}
// POST: BackOffice/Scripts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Script script = db.Scripts.Find(id);
db.Scripts.Remove(script);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/ReverseDictionariesController.cs
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ReverseDictionariesController : BaseController
{
// GET: BackOffice/ReverseDictionaries
public ActionResult Index(int page = 1, int pageSize = 20)
{
return View(db.ReverseDictionaries.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
// GET: BackOffice/ReverseDictionaries/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReverseDictionary reverseDictionary = db.ReverseDictionaries.Find(id);
if (reverseDictionary == null)
{
return HttpNotFound();
}
return View(reverseDictionary);
}
//Update a word in dictionary
public ActionResult EditReverse(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReverseDictionary reverseDictionary = db.ReverseDictionaries.Find(id);
if (reverseDictionary != null)
{
string reverse = String.Empty;
char[] cArray = reverseDictionary.ReverseWord.ToCharArray();
for (int i = cArray.Length - 1; i > -1; i--)
{
switch (cArray[i])
{
case ')':
reverse += '(';
break;
case '(':
reverse += ')';
break;
case 'ā':
reverse += 'ā';
reverse += 'y';
reverse += 'y';
reverse += 'y';
break;
case 'ä':
reverse += 'ä';
reverse += 'z';
reverse += 'z';
reverse += 'z';
break;
default:
reverse += cArray[i];
break;
}
}
reverseDictionary.Word = reverse;
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: BackOffice/ReverseDictionaries/Create
public ActionResult SortReverse()
{
IEnumerable<ReverseDictionary> reverseDictionaries = db.ReverseDictionaries;
string reverse = String.Empty;
foreach (var item in reverseDictionaries)
{
EditReverse(item.Id);
}
db.SaveChanges();
return View(reverseDictionaries);
}
// GET: BackOffice/ReverseDictionaries/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/ReverseDictionaries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Word,SymbolPrefix,ReverseWord,SymbolSufix")] ReverseDictionary reverseDictionary)
{
char[] cArray = reverseDictionary.ReverseWord.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
if (cArray[i] == ')')
{
reverse += '(';
}
else if (cArray[i] == '(')
{
reverse += ')';
}
else
reverse += cArray[i];
}
reverseDictionary.Word = reverse;
if (ModelState.IsValid)
{
db.ReverseDictionaries.Add(reverseDictionary);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reverseDictionary);
}
// GET: BackOffice/ReverseDictionaries/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReverseDictionary reverseDictionary = db.ReverseDictionaries.Find(id);
if (reverseDictionary == null)
{
return HttpNotFound();
}
return View(reverseDictionary);
}
// POST: BackOffice/ReverseDictionaries/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Word,SymbolPrefix,ReverseWord,SymbolSufix")] ReverseDictionary reverseDictionary)
{
if (ModelState.IsValid)
{
db.Entry(reverseDictionary).State = EntityState.Modified;
char[] cArray = reverseDictionary.ReverseWord.ToCharArray();
string reverse = String.Empty;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverse += cArray[i];
}
reverseDictionary.Word = reverse;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reverseDictionary);
}
// GET: BackOffice/ReverseDictionaries/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ReverseDictionary reverseDictionary = db.ReverseDictionaries.Find(id);
if (reverseDictionary == null)
{
return HttpNotFound();
}
return View(reverseDictionary);
}
// POST: BackOffice/ReverseDictionaries/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ReverseDictionary reverseDictionary = db.ReverseDictionaries.Find(id);
db.ReverseDictionaries.Remove(reverseDictionary);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchReverse(string search)
{
IEnumerable<ReverseDictionary> reverseDictionarys = db.ReverseDictionaries;
if (!string.IsNullOrWhiteSpace(search))
{
reverseDictionarys = reverseDictionarys.Where(x => x.ReverseWord.Contains(search));
}
if (reverseDictionarys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchReverse", reverseDictionarys.ToList());
}
public ActionResult SearchEnd(string search)
{
IEnumerable<ReverseDictionary> reverseDictionarys = db.ReverseDictionaries;
if (!string.IsNullOrWhiteSpace(search))
{
int i = search.Length;
reverseDictionarys = reverseDictionarys.Where(x => x.ReverseWord.Length >= i && x.ReverseWord.Substring(x.ReverseWord.Length - i, i) == search);
}
if (reverseDictionarys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchReverse", reverseDictionarys.ToList());
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/AnalyseMacroscopicsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class AnalyseMacroscopicsController : BaseController
{
// GET: BackOffice/AnalyseMacroscopics
public ActionResult Index()
{
var analyseMacroscopics = db.AnalyseMacroscopics.Include(a => a.Catalogie).Include(a => a.ChainLinesVisibility).Include(a => a.Drying).Include(a => a.FiberDirection).Include(a => a.FiberDistribution).Include(a => a.Format).Include(a => a.GenderManuscript).Include(a => a.LaidLinesRegularity).Include(a => a.ManufaturingDefect).Include(a => a.Map).Include(a => a.PaperColor).Include(a => a.PreparationPaperBeforeUsing).Include(a => a.Restore).Include(a => a.Ruling).Include(a => a.RulingColor).Include(a => a.Script).Include(a => a.SieveMark).Include(a => a.State).Include(a => a.TochLanguage).Include(a => a.WritingTool);
return View(analyseMacroscopics.ToList());
}
// GET: BackOffice/AnalyseMacroscopics/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Include("TransmittedLights").SingleOrDefault(x => x.Id == id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult MacroscopicAnalyse(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult PageLayout(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
public ActionResult SheetDescription(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Find(id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
// GET: BackOffice/AnalyseMacroscopics/Create
public ActionResult Create()
{
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name");
ViewBag.ChainLinesVisibilityId = new SelectList(db.ChainLinesVisibilitys, "Id", "ChainLinesVisibilityEn");
ViewBag.DryingId = new SelectList(db.Dryings, "Id", "DryingEn");
ViewBag.FiberDirectionId = new SelectList(db.FiberDirections, "Id", "DirectionEn");
ViewBag.FiberDistributionId = new SelectList(db.FiberDistributions, "Id", "DistributionEn");
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn");
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn");
ViewBag.LaidLinesRegularityId = new SelectList(db.LaidLinesRegularitys, "Id", "LaidLinesRegularityEn");
ViewBag.ManufaturingDefectId = new SelectList(db.ManufaturingDefects, "Id", "ManufaturingDefectEn");
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture");
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn");
ViewBag.PreparationPaperBeforeUsingId = new SelectList(db.PreparationPaperBeforeUsings, "Id", "PreparationEn");
ViewBag.RestoreId = new SelectList(db.Restores, "Id", "RestoreEn");
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn");
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn");
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn");
ViewBag.SieveMarkId = new SelectList(db.SieveMarks, "Id", "SieveMarkEn");
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn");
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language");
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn");
return View();
}
// POST: BackOffice/AnalyseMacroscopics/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,CatalogieId,Index,MapId,EstimatedDateProduction,PlaceProduction,Title,GenderManuscriptId,StateId,TochLanguageId,FormatId,NumberOfHoles,Description,AverageThickness,Correction,SheetCondition,NeedForConservation,Observation,RestoreId,RulingId,NumberOfLine,ScriptId,PageFrame,PaperColorId,WritingToolId,SoftQuality,RattleQuality,Transparency,SurfaceAspect,RulingColorId,CoatingDecayingCondition,ClayOrSandParticules,SurfaceOnBothSides,FiberDistributionId,NumberLayer,SieveMarkId,FiberDirectionId,LaidLinesRegularityId,NumberChainLinePerCm,ChainLinesVisibilityId,SpaceBetweenLines,DryingId,PreparationPaperBeforeUsingId,ManufaturingDefectId,Visible")] AnalyseMacroscopic analyseMacroscopic)
{
if (ModelState.IsValid)
{
db.AnalyseMacroscopics.Add(analyseMacroscopic);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name", analyseMacroscopic.CatalogieId);
ViewBag.ChainLinesVisibilityId = new SelectList(db.ChainLinesVisibilitys, "Id", "ChainLinesVisibilityEn", analyseMacroscopic.ChainLinesVisibilityId);
ViewBag.DryingId = new SelectList(db.Dryings, "Id", "DryingEn", analyseMacroscopic.DryingId);
ViewBag.FiberDirectionId = new SelectList(db.FiberDirections, "Id", "DirectionEn", analyseMacroscopic.FiberDirectionId);
ViewBag.FiberDistributionId = new SelectList(db.FiberDistributions, "Id", "DistributionEn", analyseMacroscopic.FiberDistributionId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", analyseMacroscopic.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", analyseMacroscopic.GenderManuscriptId);
ViewBag.LaidLinesRegularityId = new SelectList(db.LaidLinesRegularitys, "Id", "LaidLinesRegularityEn", analyseMacroscopic.LaidLinesRegularityId);
ViewBag.ManufaturingDefectId = new SelectList(db.ManufaturingDefects, "Id", "ManufaturingDefectEn", analyseMacroscopic.ManufaturingDefectId);
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", analyseMacroscopic.MapId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", analyseMacroscopic.PaperColorId);
ViewBag.PreparationPaperBeforeUsingId = new SelectList(db.PreparationPaperBeforeUsings, "Id", "PreparationEn", analyseMacroscopic.PreparationPaperBeforeUsingId);
ViewBag.RestoreId = new SelectList(db.Restores, "Id", "RestoreEn", analyseMacroscopic.RestoreId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", analyseMacroscopic.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", analyseMacroscopic.RulingColorId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", analyseMacroscopic.ScriptId);
ViewBag.SieveMarkId = new SelectList(db.SieveMarks, "Id", "SieveMarkEn", analyseMacroscopic.SieveMarkId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", analyseMacroscopic.StateId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", analyseMacroscopic.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", analyseMacroscopic.WritingToolId);
return View(analyseMacroscopic);
}
// GET: BackOffice/AnalyseMacroscopics/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.Include("TransmittedLights").SingleOrDefault(x => x.Id == id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name", analyseMacroscopic.CatalogieId);
ViewBag.ChainLinesVisibilityId = new SelectList(db.ChainLinesVisibilitys, "Id", "ChainLinesVisibilityEn", analyseMacroscopic.ChainLinesVisibilityId);
ViewBag.DryingId = new SelectList(db.Dryings, "Id", "DryingEn", analyseMacroscopic.DryingId);
ViewBag.FiberDirectionId = new SelectList(db.FiberDirections, "Id", "DirectionEn", analyseMacroscopic.FiberDirectionId);
ViewBag.FiberDistributionId = new SelectList(db.FiberDistributions, "Id", "DistributionEn", analyseMacroscopic.FiberDistributionId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", analyseMacroscopic.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", analyseMacroscopic.GenderManuscriptId);
ViewBag.LaidLinesRegularityId = new SelectList(db.LaidLinesRegularitys, "Id", "LaidLinesRegularityEn", analyseMacroscopic.LaidLinesRegularityId);
ViewBag.ManufaturingDefectId = new SelectList(db.ManufaturingDefects, "Id", "ManufaturingDefectEn", analyseMacroscopic.ManufaturingDefectId);
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", analyseMacroscopic.MapId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", analyseMacroscopic.PaperColorId);
ViewBag.PreparationPaperBeforeUsingId = new SelectList(db.PreparationPaperBeforeUsings, "Id", "PreparationEn", analyseMacroscopic.PreparationPaperBeforeUsingId);
ViewBag.RestoreId = new SelectList(db.Restores, "Id", "RestoreEn", analyseMacroscopic.RestoreId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", analyseMacroscopic.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", analyseMacroscopic.RulingColorId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", analyseMacroscopic.ScriptId);
ViewBag.SieveMarkId = new SelectList(db.SieveMarks, "Id", "SieveMarkEn", analyseMacroscopic.SieveMarkId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", analyseMacroscopic.StateId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", analyseMacroscopic.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", analyseMacroscopic.WritingToolId);
return View(analyseMacroscopic);
}
// POST: BackOffice/AnalyseMacroscopics/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,CatalogieId,Index,MapId,EstimatedDateProduction,PlaceProduction,Title,GenderManuscriptId,StateId,TochLanguageId,FormatId,NumberOfHoles,Description,AverageThickness,Correction,SheetCondition,NeedForConservation,Observation,RestoreId,RulingId,NumberOfLine,ScriptId,PageFrame,PaperColorId,WritingToolId,SoftQuality,RattleQuality,Transparency,SurfaceAspect,RulingColorId,CoatingDecayingCondition,ClayOrSandParticules,SurfaceOnBothSides,FiberDistributionId,NumberLayer,SieveMarkId,FiberDirectionId,LaidLinesRegularityId,NumberChainLinePerCm,ChainLinesVisibilityId,SpaceBetweenLines,DryingId,PreparationPaperBeforeUsingId,ManufaturingDefectId,Visible")] AnalyseMacroscopic analyseMacroscopic)
{
if (ModelState.IsValid)
{
db.Entry(analyseMacroscopic).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CatalogieId = new SelectList(db.Catalogies, "Id", "Name", analyseMacroscopic.CatalogieId);
ViewBag.ChainLinesVisibilityId = new SelectList(db.ChainLinesVisibilitys, "Id", "ChainLinesVisibilityEn", analyseMacroscopic.ChainLinesVisibilityId);
ViewBag.DryingId = new SelectList(db.Dryings, "Id", "DryingEn", analyseMacroscopic.DryingId);
ViewBag.FiberDirectionId = new SelectList(db.FiberDirections, "Id", "DirectionEn", analyseMacroscopic.FiberDirectionId);
ViewBag.FiberDistributionId = new SelectList(db.FiberDistributions, "Id", "DistributionEn", analyseMacroscopic.FiberDistributionId);
ViewBag.FormatId = new SelectList(db.Formats, "Id", "FormatEn", analyseMacroscopic.FormatId);
ViewBag.GenderManuscriptId = new SelectList(db.GenderManuscripts, "Id", "NameGenderEn", analyseMacroscopic.GenderManuscriptId);
ViewBag.LaidLinesRegularityId = new SelectList(db.LaidLinesRegularitys, "Id", "LaidLinesRegularityEn", analyseMacroscopic.LaidLinesRegularityId);
ViewBag.ManufaturingDefectId = new SelectList(db.ManufaturingDefects, "Id", "ManufaturingDefectEn", analyseMacroscopic.ManufaturingDefectId);
ViewBag.MapId = new SelectList(db.Maps, "Id", "NamePicture", analyseMacroscopic.MapId);
ViewBag.PaperColorId = new SelectList(db.PaperColors, "Id", "PaperColorEn", analyseMacroscopic.PaperColorId);
ViewBag.PreparationPaperBeforeUsingId = new SelectList(db.PreparationPaperBeforeUsings, "Id", "PreparationEn", analyseMacroscopic.PreparationPaperBeforeUsingId);
ViewBag.RestoreId = new SelectList(db.Restores, "Id", "RestoreEn", analyseMacroscopic.RestoreId);
ViewBag.RulingId = new SelectList(db.Rulings, "Id", "RulingEn", analyseMacroscopic.RulingId);
ViewBag.RulingColorId = new SelectList(db.RulingColors, "Id", "RulingColorEn", analyseMacroscopic.RulingColorId);
ViewBag.ScriptId = new SelectList(db.Scripts, "Id", "ScriptEn", analyseMacroscopic.ScriptId);
ViewBag.SieveMarkId = new SelectList(db.SieveMarks, "Id", "SieveMarkEn", analyseMacroscopic.SieveMarkId);
ViewBag.StateId = new SelectList(db.States, "Id", "StateEn", analyseMacroscopic.StateId);
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", analyseMacroscopic.TochLanguageId);
ViewBag.WritingToolId = new SelectList(db.WritingTools, "Id", "WritingToolEn", analyseMacroscopic.WritingToolId);
return View(analyseMacroscopic);
}
// GET: BackOffice/AnalyseMacroscopics/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.SingleOrDefault(x => x.Id == id);
if (analyseMacroscopic == null)
{
return HttpNotFound();
}
return View(analyseMacroscopic);
}
// POST: BackOffice/AnalyseMacroscopics/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
AnalyseMacroscopic analyseMacroscopic = db.AnalyseMacroscopics.SingleOrDefault(x => x.Id == id);
db.AnalyseMacroscopics.Remove(analyseMacroscopic);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new TransmittedLight();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.AnalyseMacroscopicId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.TransmittedLights.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "AnalyseMacroscopics", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "AnalyseMacroscopics", new { id = id });
}
// GET
public ActionResult DeletePicture(int id, int idanalyseMacroscopic)
{
TransmittedLight image = db.TransmittedLights.Find(id);
db.TransmittedLights.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "AnalyseMacroscopics", new { id = idanalyseMacroscopic});
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/PersonsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Models;
using Horizone.Controllers;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class PersonsController : BaseController
{
// GET: BackOffice/Persons
public ActionResult Index()
{
return View(db.Persons.ToList());
}
// GET: BackOffice/Persons/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/Persons/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,ConjugatedPerson,ConjugatedPersonEn,ConjugatedPersonFr,ConjugatedPersonZh")] Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
// GET: BackOffice/Persons/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.Persons.Find(id);
if (person == null)
{
return HttpNotFound();
}
return View(person);
}
// POST: BackOffice/Persons/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,ConjugatedPerson,ConjugatedPersonEn,ConjugatedPersonFr,ConjugatedPersonZh")] Person person)
{
if (ModelState.IsValid)
{
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
// GET: BackOffice/Persons/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Person person = db.Persons.Find(id);
if (person.DictionaryTocharians?.Count() > 0)
{
Display("Impossible, Cases en cours", MessageType.ERROR);
return RedirectToAction("Index");
}
if (person == null)
{
return HttpNotFound();
}
return View(person);
}
// POST: BackOffice/Persons/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Person person = db.Persons.Find(id);
db.Persons.Remove(person);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/AlignmentType.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class AlignmentType
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "AlignmentTypeEn", ResourceType = typeof(StaticResource.Resources))]
public string AlignmentTypeEn { get; set; }
[AllowHtml]
[Display(Name = "AlignmentTypeFr", ResourceType = typeof(StaticResource.Resources))]
public string AlignmentTypeFr { get; set; }
[AllowHtml]
[Display(Name = "AlignmentTypeZh", ResourceType = typeof(StaticResource.Resources))]
public string AlignmentTypeZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/NounAdjectivesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
public class NounAdjectivesController : BaseController
{
// GET: BackOffice/NounAdjectives
public ActionResult Index(int page = 1, int pageSize = 200)
{
var nounAdjectives = db.NounAdjectives
.Include(n => n.DictionaryTocharian)
.Include(n => n.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.Numbers)
.Include("Genders").Include("Cases");
return View(nounAdjectives.OrderBy(x => x.DictionaryTocharian.Word).ToPagedList(page, pageSize));
}
public ActionResult IndexNoun(int page = 1, int pageSize = 200)
{
var nounAdjectives = db.NounAdjectives
.Include(n => n.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(n => n.DictionaryTocharian.Numbers)
.Include("Cases").Include("Genders").Where(n => n.DictionaryTocharian.WordClass.Id == 2); ;
return View(nounAdjectives.OrderBy(x => x.DictionaryTocharian.Word).ToPagedList(page, pageSize));
}
// GET: BackOffice/NounAdjectives
public ActionResult IndexAdjective(int page = 1, int pageSize = 200)
{
var nounAdjectives = db.NounAdjectives
.Include(n => n.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(n => n.DictionaryTocharian.Numbers)
.Include("Cases").Include("Genders").Where(n=>n.DictionaryTocharian.WordClass.Id==4);
return View(nounAdjectives.OrderBy(x => x.DictionaryTocharian.Word).ToPagedList(page, pageSize));
}
// GET: BackOffice/NounAdjectives/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NounAdjective nounAdjective = db.NounAdjectives
.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Genders").Include("Cases").SingleOrDefault(p => p.Id == id);
if (nounAdjective == null)
{
return HttpNotFound();
}
return View(nounAdjective);
}
// GET: BackOffice/NounAdjectives/Create
public ActionResult Create()
{
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x=>x.WordClassId == 2 || x.WordClassId == 4).OrderBy(x=>x.Word), "Id", "Word");
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x=>x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x=>x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
return View();
}
// POST: BackOffice/NounAdjectives/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DictionaryId")] NounAdjective nounAdjective, int[] CaseId, int[] GenderId)
{
if (ModelState.IsValid)
{
if (CaseId.Count() == 0)
{ nounAdjective.Cases = db.Cases.Where(x => x.Id == 1).ToList(); }
else
{
nounAdjective.Cases = db.Cases.Where(x => CaseId.Contains(x.Id)).ToList();
}
if (GenderId.Count() == 0)
{
nounAdjective.Genders = db.Genders.Where(x => x.Id == 1).ToList();
}
else
{
nounAdjective.Genders = db.Genders.Where(x => GenderId.Contains(x.Id)).ToList();
}
db.NounAdjectives.Add(nounAdjective);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 2 || x.WordClassId == 4).OrderBy(x => x.Word), "Id", "Word");
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
return View(nounAdjective);
}
// GET: BackOffice/NounAdjectives/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NounAdjective nounAdjective = db.NounAdjectives
.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Genders").Include("Cases").SingleOrDefault(p => p.Id == id);
if (nounAdjective == null)
{
return HttpNotFound();
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 2 || x.WordClassId == 4).OrderBy(x => x.Word), "Id", "Word",nounAdjective.DictionaryId);
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
return View(nounAdjective);
}
// POST: BackOffice/NounAdjectives/Edit/5
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DictionaryId")] NounAdjective nounAdjective, int[] CaseId, int[] GenderId)
{
if (ModelState.IsValid)
{
db.Entry(nounAdjective).State = EntityState.Modified;
if (CaseId != null)
nounAdjective.Cases = db.Cases.Where(x => CaseId.Contains(x.Id)).ToList();
if (GenderId != null)
nounAdjective.Genders = db.Genders.Where(x => GenderId.Contains(x.Id)).ToList();
if (nounAdjective.Cases.Count() == 0)
nounAdjective.Cases = db.Cases.Where(x => x.NameCaseEn == "No Case").ToList();
if (nounAdjective.Genders.Count() == 0)
nounAdjective.Genders = db.Genders.Where(x => x.NameGenderEn == "No Gender").ToList();
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 2 || x.WordClassId == 4).OrderBy(x => x.Word), "Id", "Word",nounAdjective.DictionaryId);
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
return View(nounAdjective);
}
// GET: BackOffice/NounAdjectives/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NounAdjective nounAdjective = db.NounAdjectives.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include("Genders").Include("Cases")
.SingleOrDefault(p => p.Id == id);
if (nounAdjective == null)
{
return HttpNotFound();
}
return View(nounAdjective);
}
// POST: BackOffice/NounAdjectives/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
NounAdjective nounAdjective = db.NounAdjectives
.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(p => p.DictionaryTocharian.Numbers)
.Include("Genders").Include("Cases").SingleOrDefault(p => p.Id == id);
db.NounAdjectives.Remove(nounAdjective);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchDictionary(string search)
{
IEnumerable<NounAdjective> nounAdjectives = db.NounAdjectives.Include(d=>d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
nounAdjectives = nounAdjectives.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (nounAdjectives.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = nounAdjectives.Count();
ViewBag.Search = search;
return View("SearchDictionary", nounAdjectives.ToList());
}
}
}
<file_sep>/Horizone/Migrations/201906190735271_init.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class init : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbbreviationDictionaries",
c => new
{
Id = c.Int(nullable: false, identity: true),
Symbol = c.String(),
Description = c.String(),
OtherAbbreviation = c.Boolean(nullable: false),
AbbreviationManuscript = c.Boolean(nullable: false),
AbbreviationsLanguage = c.Boolean(nullable: false),
GrammaticalAbbreviation = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AboutProjects",
c => new
{
Id = c.Int(nullable: false, identity: true),
Aim = c.String(),
Funding = c.String(),
Programing = c.String(),
Feedback = c.String(),
Contact = c.String(),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.Index(t => t.LanguageId);
CreateTable(
"dbo.ImageProjects",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
AboutProjectId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AboutProjects", t => t.AboutProjectId, cascadeDelete: false)
.Index(t => t.AboutProjectId);
CreateTable(
"dbo.Languages",
c => new
{
Id = c.Int(nullable: false, identity: true),
Symbol = c.String(maxLength: 20),
Name = c.String(maxLength: 40),
IsDefault = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Abreviations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Symbol = c.String(),
Description = c.String(),
Link = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Activities",
c => new
{
Id = c.Int(nullable: false, identity: true),
DateofActivity = c.String(nullable: false),
Place = c.String(nullable: false),
NameActivity = c.String(nullable: false),
Description = c.String(),
UlrActivity = c.String(),
Picture = c.String(),
TopicId = c.Int(nullable: false),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.ForeignKey("dbo.Topics", t => t.TopicId, cascadeDelete: false)
.Index(t => t.TopicId)
.Index(t => t.LanguageId);
CreateTable(
"dbo.Topics",
c => new
{
Id = c.Int(nullable: false, identity: true),
TopicEn = c.String(nullable: false, maxLength: 40),
TopicFr = c.String(nullable: false, maxLength: 40),
TopicZh = c.String(nullable: false, maxLength: 40),
Activity = c.Boolean(nullable: false),
News = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AlignmentTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
AlignmentTypeEn = c.String(),
AlignmentTypeFr = c.String(),
AlignmentTypeZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AnalyseMacroscopics",
c => new
{
Id = c.Int(nullable: false, identity: true),
CatalogieId = c.Int(nullable: false),
Index = c.String(nullable: false),
MapId = c.Int(nullable: false),
EstimatedDateProduction = c.String(),
PlaceProduction = c.String(),
Title = c.String(),
GenderManuscriptId = c.Int(nullable: false),
StateId = c.Int(nullable: false),
TochLanguageId = c.Int(nullable: false),
FormatId = c.Int(nullable: false),
NumberOfHoles = c.Int(nullable: false),
Description = c.String(),
AverageThickness = c.String(),
Correction = c.Boolean(nullable: false),
SheetCondition = c.String(),
NeedForConservation = c.String(),
Observation = c.String(),
RestoreId = c.Int(nullable: false),
RulingId = c.Int(nullable: false),
NumberOfLine = c.Int(nullable: false),
ScriptId = c.Int(nullable: false),
PageFrame = c.String(),
PaperColorId = c.Int(nullable: false),
WritingToolId = c.Int(nullable: false),
SoftQuality = c.Boolean(nullable: false),
RattleQuality = c.Boolean(nullable: false),
Transparency = c.Boolean(nullable: false),
SurfaceAspect = c.String(),
RulingColorId = c.Int(nullable: false),
CoatingDecayingCondition = c.String(),
ClayOrSandParticules = c.Boolean(nullable: false),
SurfaceOnBothSides = c.Boolean(nullable: false),
FiberDistributionId = c.Int(nullable: false),
NumberLayer = c.String(),
SieveMarkId = c.Int(nullable: false),
FiberDirectionId = c.Int(nullable: false),
LaidLinesRegularityId = c.Int(nullable: false),
NumberChainLinePerCm = c.Int(nullable: false),
ChainLinesVisibilityId = c.Int(nullable: false),
SpaceBetweenLines = c.String(),
DryingId = c.Int(nullable: false),
PreparationPaperBeforeUsingId = c.Int(nullable: false),
ManufaturingDefectId = c.Int(nullable: false),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Catalogies", t => t.CatalogieId, cascadeDelete: false)
.ForeignKey("dbo.ChainLinesVisibilities", t => t.ChainLinesVisibilityId, cascadeDelete: false)
.ForeignKey("dbo.Dryings", t => t.DryingId, cascadeDelete: false)
.ForeignKey("dbo.FiberDirections", t => t.FiberDirectionId, cascadeDelete: false)
.ForeignKey("dbo.FiberDistributions", t => t.FiberDistributionId, cascadeDelete: false)
.ForeignKey("dbo.Formats", t => t.FormatId, cascadeDelete: false)
.ForeignKey("dbo.GenderManuscripts", t => t.GenderManuscriptId, cascadeDelete: false)
.ForeignKey("dbo.LaidLinesRegularities", t => t.LaidLinesRegularityId, cascadeDelete: false)
.ForeignKey("dbo.ManufaturingDefects", t => t.ManufaturingDefectId, cascadeDelete: false)
.ForeignKey("dbo.Maps", t => t.MapId, cascadeDelete: false)
.ForeignKey("dbo.PaperColors", t => t.PaperColorId, cascadeDelete: false)
.ForeignKey("dbo.PreparationPaperBeforeUsings", t => t.PreparationPaperBeforeUsingId, cascadeDelete: false)
.ForeignKey("dbo.Restores", t => t.RestoreId, cascadeDelete: false)
.ForeignKey("dbo.Rulings", t => t.RulingId, cascadeDelete: false)
.ForeignKey("dbo.RulingColors", t => t.RulingColorId, cascadeDelete: false)
.ForeignKey("dbo.Scripts", t => t.ScriptId, cascadeDelete: false)
.ForeignKey("dbo.SieveMarks", t => t.SieveMarkId, cascadeDelete: false)
.ForeignKey("dbo.States", t => t.StateId, cascadeDelete: false)
.ForeignKey("dbo.TochLanguages", t => t.TochLanguageId, cascadeDelete: false)
.ForeignKey("dbo.WritingTools", t => t.WritingToolId, cascadeDelete: false)
.Index(t => t.CatalogieId)
.Index(t => t.MapId)
.Index(t => t.GenderManuscriptId)
.Index(t => t.StateId)
.Index(t => t.TochLanguageId)
.Index(t => t.FormatId)
.Index(t => t.RestoreId)
.Index(t => t.RulingId)
.Index(t => t.ScriptId)
.Index(t => t.PaperColorId)
.Index(t => t.WritingToolId)
.Index(t => t.RulingColorId)
.Index(t => t.FiberDistributionId)
.Index(t => t.SieveMarkId)
.Index(t => t.FiberDirectionId)
.Index(t => t.LaidLinesRegularityId)
.Index(t => t.ChainLinesVisibilityId)
.Index(t => t.DryingId)
.Index(t => t.PreparationPaperBeforeUsingId)
.Index(t => t.ManufaturingDefectId);
CreateTable(
"dbo.Bibliographies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Author = c.String(maxLength: 150),
PublicationDate = c.String(maxLength: 10),
Title = c.String(maxLength: 500),
Journal = c.String(maxLength: 500),
UlrBibliography = c.String(maxLength: 500),
Book = c.Boolean(nullable: false),
AnalyseMacroscopic_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AnalyseMacroscopics", t => t.AnalyseMacroscopic_Id)
.Index(t => t.AnalyseMacroscopic_Id);
CreateTable(
"dbo.DictionaryTocharians",
c => new
{
Id = c.Int(nullable: false, identity: true),
Word = c.String(nullable: false),
English = c.String(),
Francaise = c.String(),
German = c.String(),
Latin = c.String(),
Chinese = c.String(),
WordClassId = c.Int(nullable: false),
WordSubClassId = c.Int(nullable: false),
TochLanguageId = c.Int(nullable: false),
EquivalentTA = c.String(),
EquivalentTB = c.String(),
EquivalentInOther = c.String(),
DerivedFrom = c.String(),
RelatedLexemes = c.String(),
RootCharacter = c.String(),
InternalRootVowel = c.String(),
NominateMasculineSingular = c.String(),
NominateMasculineDual = c.String(),
NominateMasculinePlural = c.String(),
NominateFeminineSingular = c.String(),
NominateFeminineDual = c.String(),
NominateFemininePlural = c.String(),
NominateNeuterSingular = c.String(),
NominateNeuterDual = c.String(),
NominateNeuterPlural = c.String(),
ObliqueMasculineSingular = c.String(),
ObliqueMasculineDual = c.String(),
ObliqueMasculinePlural = c.String(),
ObliqueFeminineSingular = c.String(),
ObliqueFeminineDual = c.String(),
ObliqueFemininePlural = c.String(),
ObliqueNeuterSingular = c.String(),
ObliqueNeuterDual = c.String(),
ObliqueNeuterPlural = c.String(),
VocativeMasculineSingular = c.String(),
VocativeMasculineDual = c.String(),
VocativeMasculinePlural = c.String(),
VocativeFeminineSingular = c.String(),
VocativeFeminineDual = c.String(),
VocativeFemininePlural = c.String(),
VocativeNeuterSingular = c.String(),
VocativeNeuterDual = c.String(),
VocativeNeuterPlural = c.String(),
GenitiveMasculineSingular = c.String(),
GenitiveMasculineDual = c.String(),
GenitiveMasculinePlural = c.String(),
GenitiveFeminineSingular = c.String(),
GenitiveFeminineDual = c.String(),
GenitiveFemininePlural = c.String(),
GenitiveNeuterSingular = c.String(),
GenitiveNeuterDual = c.String(),
GenitiveNeuterPlural = c.String(),
LocativeMasculineSingular = c.String(),
LocativeMasculineDual = c.String(),
LocativeMasculinePlural = c.String(),
LocativeFeminineSingular = c.String(),
LocativeFeminineDual = c.String(),
LocativeFemininePlural = c.String(),
LocativeNeuterSingular = c.String(),
LocativeNeuterDual = c.String(),
LocativeNeuterPlural = c.String(),
AblativeMasculineSingular = c.String(),
AblativeMasculineDual = c.String(),
AblativeMasculinePlural = c.String(),
AblativeFeminineSingular = c.String(),
AblativeFeminineDual = c.String(),
AblativeFemininePlural = c.String(),
AblativeNeuterSingular = c.String(),
AblativeNeuterDual = c.String(),
AblativeNeuterPlural = c.String(),
AllativeMasculineSingular = c.String(),
AllativeMasculineDual = c.String(),
AllativeMasculinePlural = c.String(),
AllativeFeminineSingular = c.String(),
AllativeFeminineDual = c.String(),
AllativeFemininePlural = c.String(),
AllativeNeuterSingular = c.String(),
AllativeNeuterDual = c.String(),
AllativeNeuterPlural = c.String(),
PerlativeMasculineSingular = c.String(),
PerlativeMasculineDual = c.String(),
PerlativeMasculinePlural = c.String(),
PerlativeFeminineSingular = c.String(),
PerlativeFeminineDual = c.String(),
PerlativeFemininePlural = c.String(),
PerlativeNeuterSingular = c.String(),
PerlativeNeuterDual = c.String(),
PerlativeNeuterPlural = c.String(),
InstrumentalMasculineSingular = c.String(),
InstrumentalMasculineDual = c.String(),
InstrumentalMasculinePlural = c.String(),
InstrumentalFeminineSingular = c.String(),
InstrumentalFeminineDual = c.String(),
InstrumentalFemininePlural = c.String(),
InstrumentalNeuterSingular = c.String(),
InstrumentalNeuterDual = c.String(),
InstrumentalNeuterPlural = c.String(),
ComitativeMasculineSingular = c.String(),
ComitativeMasculineDual = c.String(),
ComitativeMasculinePlural = c.String(),
ComitativeFeminineSingular = c.String(),
ComitativeFeminineDual = c.String(),
ComitativeFemininePlural = c.String(),
ComitativeNeuterSingular = c.String(),
ComitativeNeuterDual = c.String(),
ComitativeNeuterPlural = c.String(),
CausativeMasculineSingular = c.String(),
CausativeMasculineDual = c.String(),
CausativeMasculinePlural = c.String(),
CausativeFeminineSingular = c.String(),
CausativeFeminineDual = c.String(),
CausativeFemininePlural = c.String(),
CausativeNeuterSingular = c.String(),
CausativeNeuterDual = c.String(),
CausativeNeuterPlural = c.String(),
Stem = c.String(),
StemClass = c.String(),
VoiceId = c.Int(nullable: false),
ValencyId = c.Int(nullable: false),
TenseAndAspectId = c.Int(nullable: false),
MoodId = c.Int(nullable: false),
PronounSuffix = c.String(),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Moods", t => t.MoodId, cascadeDelete: false)
.ForeignKey("dbo.TenseAndAspects", t => t.TenseAndAspectId, cascadeDelete: false)
.ForeignKey("dbo.TochLanguages", t => t.TochLanguageId, cascadeDelete: false)
.ForeignKey("dbo.Valencies", t => t.ValencyId, cascadeDelete: false)
.ForeignKey("dbo.Voices", t => t.VoiceId, cascadeDelete: false)
.ForeignKey("dbo.WordClasses", t => t.WordClassId, cascadeDelete: false)
.ForeignKey("dbo.WordSubClasses", t => t.WordSubClassId, cascadeDelete: false)
.Index(t => t.WordClassId)
.Index(t => t.WordSubClassId)
.Index(t => t.TochLanguageId)
.Index(t => t.VoiceId)
.Index(t => t.ValencyId)
.Index(t => t.TenseAndAspectId)
.Index(t => t.MoodId);
CreateTable(
"dbo.Cases",
c => new
{
Id = c.Int(nullable: false, identity: true),
NameCase = c.String(),
NameCaseEn = c.String(),
NameCaseFr = c.String(),
NameCaseZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Genders",
c => new
{
Id = c.Int(nullable: false, identity: true),
NameGender = c.String(),
NameGenderEn = c.String(),
NameGenderFr = c.String(),
NameGenderZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Moods",
c => new
{
Id = c.Int(nullable: false, identity: true),
AbbreviationsMood = c.String(),
MoodEn = c.String(),
MoodFr = c.String(),
MoodZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Numbers",
c => new
{
Id = c.Int(nullable: false, identity: true),
WordNumber = c.String(),
WordNumberEn = c.String(),
WordNumberFr = c.String(),
WordNumberZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.People",
c => new
{
Id = c.Int(nullable: false, identity: true),
ConjugatedPerson = c.String(),
ConjugatedPersonEn = c.String(),
ConjugatedPersonFr = c.String(),
ConjugatedPersonZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TenseAndAspects",
c => new
{
Id = c.Int(nullable: false, identity: true),
Tense = c.String(),
TenseEn = c.String(),
TenseFr = c.String(),
TenseZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TochLanguages",
c => new
{
Id = c.Int(nullable: false, identity: true),
Language = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Valencies",
c => new
{
Id = c.Int(nullable: false, identity: true),
AbbreviationValency = c.String(),
ValencyEn = c.String(),
ValencyFr = c.String(),
ValencyZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Voices",
c => new
{
Id = c.Int(nullable: false, identity: true),
AbbreviationVoice = c.String(),
VoiceEn = c.String(),
VoiceFr = c.String(),
VoiceZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.WordClasses",
c => new
{
Id = c.Int(nullable: false, identity: true),
Class = c.String(),
ClassEn = c.String(nullable: false),
ClassFr = c.String(),
ClassZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.WordSubClasses",
c => new
{
Id = c.Int(nullable: false, identity: true),
SubClass = c.String(),
SubClassEn = c.String(nullable: false),
SubClassFr = c.String(),
SubClassZh = c.String(),
WordClassId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.WordClasses", t => t.WordClassId, cascadeDelete: false)
.Index(t => t.WordClassId);
CreateTable(
"dbo.ImageBooks",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
BibliographyId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Bibliographies", t => t.BibliographyId, cascadeDelete: false)
.Index(t => t.BibliographyId);
CreateTable(
"dbo.Manuscripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
CatalogieId = c.Int(nullable: false),
Index = c.String(nullable: false),
Collection = c.String(),
Siglum = c.String(),
Joint = c.String(),
OtherSiglum = c.String(),
ExpeditionCode = c.String(),
MapId = c.Int(nullable: false),
SpecificFindSpot = c.String(),
StateId = c.Int(nullable: false),
DescriptionManuscriptId = c.Int(nullable: false),
RemarkAddId = c.Int(nullable: false),
LeafNumber = c.String(),
SizeHeight = c.String(),
Completeness = c.String(),
SizeWidth = c.String(),
NumberOfLine = c.Int(nullable: false),
LineDistance = c.String(),
FormatId = c.Int(nullable: false),
RulingId = c.Int(nullable: false),
RulingColorId = c.Int(nullable: false),
RulingDetailId = c.Int(nullable: false),
StringholeHeight = c.String(),
StringholeWidth = c.String(),
DistanceStringholeRight = c.String(),
DistanceStringholeLeft = c.String(),
InterruptedLine = c.String(),
Transliteration = c.String(),
Transcription = c.String(),
English = c.String(),
Francaise = c.String(),
Chinese = c.String(),
Editor = c.String(),
References = c.String(),
PhilologicalCommentary = c.String(),
MaterialId = c.Int(nullable: false),
PaperColorId = c.Int(nullable: false),
PaperThickness = c.String(),
WritingToolId = c.Int(nullable: false),
AlignmentTypeId = c.Int(nullable: false),
ModuleWidth = c.String(),
ModuleHeight = c.String(),
AvCharPerLigne = c.String(),
NibThickness = c.String(),
ScriptId = c.Int(nullable: false),
ScriptAddId = c.Int(nullable: false),
TochLanguageId = c.Int(nullable: false),
LanguageStageId = c.Int(nullable: false),
LanguageDetailId = c.Int(nullable: false),
GenderManuscriptId = c.Int(nullable: false),
SubGenderManuscriptId = c.Int(nullable: false),
Title = c.String(),
Passage = c.String(),
Parallel = c.String(),
MetricId = c.Int(nullable: false),
Tune = c.String(),
Cetom = c.String(),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AlignmentTypes", t => t.AlignmentTypeId, cascadeDelete: false)
.ForeignKey("dbo.Catalogies", t => t.CatalogieId, cascadeDelete: false)
.ForeignKey("dbo.DescriptionManuscripts", t => t.DescriptionManuscriptId, cascadeDelete: false)
.ForeignKey("dbo.Formats", t => t.FormatId, cascadeDelete: false)
.ForeignKey("dbo.GenderManuscripts", t => t.GenderManuscriptId, cascadeDelete: false)
.ForeignKey("dbo.LanguageDetails", t => t.LanguageDetailId, cascadeDelete: false)
.ForeignKey("dbo.LanguageStages", t => t.LanguageStageId, cascadeDelete: false)
.ForeignKey("dbo.Maps", t => t.MapId, cascadeDelete: false)
.ForeignKey("dbo.Materials", t => t.MaterialId, cascadeDelete: false)
.ForeignKey("dbo.Metrics", t => t.MetricId, cascadeDelete: false)
.ForeignKey("dbo.PaperColors", t => t.PaperColorId, cascadeDelete: false)
.ForeignKey("dbo.RemarkAdds", t => t.RemarkAddId, cascadeDelete: false)
.ForeignKey("dbo.Rulings", t => t.RulingId, cascadeDelete: false)
.ForeignKey("dbo.RulingColors", t => t.RulingColorId, cascadeDelete: false)
.ForeignKey("dbo.RulingDetails", t => t.RulingDetailId, cascadeDelete: false)
.ForeignKey("dbo.Scripts", t => t.ScriptId, cascadeDelete: false)
.ForeignKey("dbo.ScriptAdds", t => t.ScriptAddId, cascadeDelete: false)
.ForeignKey("dbo.States", t => t.StateId, cascadeDelete: false)
.ForeignKey("dbo.SubGenderManuscripts", t => t.SubGenderManuscriptId, cascadeDelete: false)
.ForeignKey("dbo.TochLanguages", t => t.TochLanguageId, cascadeDelete: false)
.ForeignKey("dbo.WritingTools", t => t.WritingToolId, cascadeDelete: false)
.Index(t => t.CatalogieId)
.Index(t => t.MapId)
.Index(t => t.StateId)
.Index(t => t.DescriptionManuscriptId)
.Index(t => t.RemarkAddId)
.Index(t => t.FormatId)
.Index(t => t.RulingId)
.Index(t => t.RulingColorId)
.Index(t => t.RulingDetailId)
.Index(t => t.MaterialId)
.Index(t => t.PaperColorId)
.Index(t => t.WritingToolId)
.Index(t => t.AlignmentTypeId)
.Index(t => t.ScriptId)
.Index(t => t.ScriptAddId)
.Index(t => t.TochLanguageId)
.Index(t => t.LanguageStageId)
.Index(t => t.LanguageDetailId)
.Index(t => t.GenderManuscriptId)
.Index(t => t.SubGenderManuscriptId)
.Index(t => t.MetricId);
CreateTable(
"dbo.Catalogies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.DescriptionManuscripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
DescriptionEn = c.String(),
DescriptionFr = c.String(),
DescriptionZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Formats",
c => new
{
Id = c.Int(nullable: false, identity: true),
FormatEn = c.String(),
FormatFr = c.String(),
FormatZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.GenderManuscripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
NameGenderEn = c.String(),
NameGenderFr = c.String(),
NameGenderZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ImageManuscripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
ManuscriptId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Manuscripts", t => t.ManuscriptId, cascadeDelete: false)
.Index(t => t.ManuscriptId);
CreateTable(
"dbo.LanguageDetails",
c => new
{
Id = c.Int(nullable: false, identity: true),
LanguageDetailEn = c.String(),
LanguageDetailFr = c.String(),
LanguageDetailZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.LanguageStages",
c => new
{
Id = c.Int(nullable: false, identity: true),
LanguageStageEn = c.String(),
LanguageStageFr = c.String(),
LanguageStageZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Maps",
c => new
{
Id = c.Int(nullable: false, identity: true),
NamePicture = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ImageMaps",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
MapId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Maps", t => t.MapId, cascadeDelete: false)
.Index(t => t.MapId);
CreateTable(
"dbo.Materials",
c => new
{
Id = c.Int(nullable: false, identity: true),
MaterialEn = c.String(),
MaterialFr = c.String(),
MaterialZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Metrics",
c => new
{
Id = c.Int(nullable: false, identity: true),
MetricEn = c.String(),
MetricFr = c.String(),
MetricZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.PaperColors",
c => new
{
Id = c.Int(nullable: false, identity: true),
PaperColorEn = c.String(),
PaperColorFr = c.String(),
PaperColorZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.RemarkAdds",
c => new
{
Id = c.Int(nullable: false, identity: true),
RemarkEn = c.String(),
RemarkFr = c.String(),
RemarkZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Rulings",
c => new
{
Id = c.Int(nullable: false, identity: true),
RulingEn = c.String(),
RulingFr = c.String(),
RulingZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.RulingColors",
c => new
{
Id = c.Int(nullable: false, identity: true),
RulingColorEn = c.String(),
RulingColorFr = c.String(),
RulingColorZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.RulingDetails",
c => new
{
Id = c.Int(nullable: false, identity: true),
RulingDetailEn = c.String(),
RulingDetailFr = c.String(),
RulingDetailZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Scripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
ScriptEn = c.String(),
ScriptFr = c.String(),
ScriptZh = c.String(),
ScriptTypeId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.ScriptTypes", t => t.ScriptTypeId, cascadeDelete: false)
.Index(t => t.ScriptTypeId);
CreateTable(
"dbo.ScriptTypes",
c => new
{
Id = c.Int(nullable: false, identity: true),
NameType = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ScriptAdds",
c => new
{
Id = c.Int(nullable: false, identity: true),
ScriptAddEn = c.String(),
ScriptAddFr = c.String(),
ScriptAddZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.States",
c => new
{
Id = c.Int(nullable: false, identity: true),
StateEn = c.String(),
StateFr = c.String(),
StateZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SubGenderManuscripts",
c => new
{
Id = c.Int(nullable: false, identity: true),
SubGenderEn = c.String(),
NameGenderFr = c.String(),
NameGenderZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.WritingTools",
c => new
{
Id = c.Int(nullable: false, identity: true),
WritingToolEn = c.String(),
WritingToolFr = c.String(),
WritingToolZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TochPhrases",
c => new
{
Id = c.Int(nullable: false, identity: true),
Phrase = c.String(nullable: false),
English = c.String(),
Francaise = c.String(),
Chinese = c.String(),
TochLanguageId = c.Int(nullable: false),
DerivedFrom = c.String(),
RelatedLexemes = c.String(),
Description = c.String(),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.TochLanguages", t => t.TochLanguageId, cascadeDelete: false)
.Index(t => t.TochLanguageId);
CreateTable(
"dbo.TochStories",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 500),
SourceStoryId = c.Int(nullable: false),
ThemeStoryId = c.Int(nullable: false),
PlasticRepresentation = c.String(),
MainFindSpot = c.String(),
Content = c.String(nullable: false),
English = c.String(),
Francaise = c.String(),
Chinese = c.String(),
Description = c.String(),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.SourceStories", t => t.SourceStoryId, cascadeDelete: false)
.ForeignKey("dbo.ThemeStories", t => t.ThemeStoryId, cascadeDelete: false)
.Index(t => t.SourceStoryId)
.Index(t => t.ThemeStoryId);
CreateTable(
"dbo.NamePlaces",
c => new
{
Id = c.Int(nullable: false, identity: true),
PlaceEn = c.String(),
PlaceFr = c.String(),
PlaceZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ProperNouns",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SourceStories",
c => new
{
Id = c.Int(nullable: false, identity: true),
Source = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ThemeStories",
c => new
{
Id = c.Int(nullable: false, identity: true),
ThemeEn = c.String(),
ThemeFr = c.String(),
ThemeZn = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ChainLinesVisibilities",
c => new
{
Id = c.Int(nullable: false, identity: true),
ChainLinesVisibilityEn = c.String(),
ChainLinesVisibilityFr = c.String(),
ChainLinesVisibilityZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Dryings",
c => new
{
Id = c.Int(nullable: false, identity: true),
DryingEn = c.String(),
DryingFr = c.String(),
DryingZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.FiberDirections",
c => new
{
Id = c.Int(nullable: false, identity: true),
DirectionEn = c.String(),
DirectionFr = c.String(),
DirectionZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.FiberDistributions",
c => new
{
Id = c.Int(nullable: false, identity: true),
DistributionEn = c.String(),
DistributionFr = c.String(),
DistributionZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.LaidLinesRegularities",
c => new
{
Id = c.Int(nullable: false, identity: true),
LaidLinesRegularityEn = c.String(),
LaidLinesRegularityFr = c.String(),
LaidLinesRegularityZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ManufaturingDefects",
c => new
{
Id = c.Int(nullable: false, identity: true),
ManufaturingDefectEn = c.String(),
ManufaturingDefectFr = c.String(),
ManufaturingDefectZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.PreparationPaperBeforeUsings",
c => new
{
Id = c.Int(nullable: false, identity: true),
PreparationEn = c.String(),
PreparationFr = c.String(),
PreparationZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Restores",
c => new
{
Id = c.Int(nullable: false, identity: true),
RestoreEn = c.String(),
RestoreFr = c.String(),
RestoreZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SieveMarks",
c => new
{
Id = c.Int(nullable: false, identity: true),
SieveMarkEn = c.String(),
SieveMarkFr = c.String(),
SieveMarkZh = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.TransmittedLights",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
AnalyseMacroscopicId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AnalyseMacroscopics", t => t.AnalyseMacroscopicId, cascadeDelete: false)
.Index(t => t.AnalyseMacroscopicId);
CreateTable(
"dbo.AnalyseMaterials",
c => new
{
Id = c.Int(nullable: false, identity: true),
Index = c.String(nullable: false),
Description = c.String(),
Order = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ImageAnalyses",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
AnalyseMaterialId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AnalyseMaterials", t => t.AnalyseMaterialId, cascadeDelete: false)
.Index(t => t.AnalyseMaterialId);
CreateTable(
"dbo.ImageUVs",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
AnalyseMaterialId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AnalyseMaterials", t => t.AnalyseMaterialId, cascadeDelete: false)
.Index(t => t.AnalyseMaterialId);
CreateTable(
"dbo.Clients",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
Title = c.String(maxLength: 20),
LastName = c.String(nullable: false, maxLength: 30),
FirstName = c.String(nullable: false, maxLength: 30),
PhoneNumber = c.String(nullable: false, maxLength: 20),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId)
.Index(t => new { t.Title, t.LastName, t.FirstName }, unique: true, name: "IX_PersonneUnique");
CreateTable(
"dbo.Users",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.UserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId);
CreateTable(
"dbo.UserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: false)
.Index(t => t.UserId);
CreateTable(
"dbo.UserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.Roles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.Collaborations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(maxLength: 20),
LastName = c.String(nullable: false, maxLength: 30),
FirstName = c.String(nullable: false, maxLength: 30),
FonctionEn = c.String(),
FonctionFr = c.String(),
FonctionZh = c.String(),
AffiliationFr = c.String(),
AffiliationEn = c.String(),
AffiliationZh = c.String(),
CV = c.String(),
Email = c.String(),
Team = c.Boolean(nullable: false),
AssociatedResearcher = c.Boolean(nullable: false),
Collaborator = c.Boolean(nullable: false),
Visible = c.Boolean(nullable: false),
Order = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.ImageCollaborations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
CollaborationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Collaborations", t => t.CollaborationId, cascadeDelete: false)
.Index(t => t.CollaborationId);
CreateTable(
"dbo.Publications",
c => new
{
Id = c.Int(nullable: false, identity: true),
PublicationDate = c.String(maxLength: 10),
Title = c.String(maxLength: 500),
Journal = c.String(maxLength: 500),
UlrBibliography = c.String(maxLength: 500),
PublicationIndividual = c.Boolean(nullable: false),
PublicationProjet = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Collaborators",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
Title = c.String(maxLength: 20),
LastName = c.String(nullable: false, maxLength: 30),
FirstName = c.String(nullable: false, maxLength: 30),
PhoneNumber = c.String(nullable: false, maxLength: 20),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => new { t.Title, t.LastName, t.FirstName }, unique: true, name: "IX_PersonneUnique");
CreateTable(
"dbo.News",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(nullable: false),
Summary = c.String(),
Content = c.String(),
View = c.Int(nullable: false),
TopicId = c.Int(nullable: false),
CollaboratorId = c.Int(nullable: false),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Collaborators", t => t.CollaboratorId, cascadeDelete: false)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.ForeignKey("dbo.Topics", t => t.TopicId, cascadeDelete: false)
.Index(t => t.TopicId)
.Index(t => t.CollaboratorId)
.Index(t => t.LanguageId);
CreateTable(
"dbo.Comments",
c => new
{
Id = c.Int(nullable: false, identity: true),
Content = c.String(),
NewsId = c.Int(nullable: false),
UserId = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Users", t => t.UserId)
.ForeignKey("dbo.News", t => t.NewsId, cascadeDelete: false)
.Index(t => t.NewsId)
.Index(t => t.UserId);
CreateTable(
"dbo.ImageNews",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
NewsId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.News", t => t.NewsId, cascadeDelete: false)
.Index(t => t.NewsId);
CreateTable(
"dbo.ImagePartners",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 150),
ContentType = c.String(nullable: false, maxLength: 20),
Content = c.Binary(nullable: false),
PartnerAndRelationId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.PartnerAndRelations", t => t.PartnerAndRelationId, cascadeDelete: false)
.Index(t => t.PartnerAndRelationId);
CreateTable(
"dbo.PartnerAndRelations",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
Description = c.String(),
Link = c.String(),
Partner = c.Boolean(nullable: false),
Relation = c.Boolean(nullable: false),
Order = c.Int(nullable: false),
Visible = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.LinkAndPresses",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(),
Link = c.String(),
Order = c.Int(nullable: false),
Press = c.Boolean(nullable: false),
Status = c.Byte(nullable: false),
Target = c.String(),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.Index(t => t.LanguageId);
CreateTable(
"dbo.Presentations",
c => new
{
Id = c.Int(nullable: false, identity: true),
AboutUs = c.String(),
TochPhrase = c.String(),
TochStory = c.String(),
Manuscript = c.String(),
Activity = c.String(),
Bibliography = c.String(),
DictionaryTocharian = c.String(),
VisualAids = c.String(),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.Index(t => t.LanguageId);
CreateTable(
"dbo.ReverseDictionaries",
c => new
{
Id = c.Int(nullable: false, identity: true),
Word = c.String(),
ReverseWord = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Roles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.VisualAids",
c => new
{
Id = c.Int(nullable: false, identity: true),
Aids = c.String(nullable: false),
Description = c.String(),
Photography = c.Boolean(nullable: false),
Map = c.Boolean(nullable: false),
LanguageId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Languages", t => t.LanguageId, cascadeDelete: false)
.Index(t => t.LanguageId);
CreateTable(
"dbo.DictionaryTocharianBibliographies",
c => new
{
DictionaryTocharian_Id = c.Int(nullable: false),
Bibliography_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.DictionaryTocharian_Id, t.Bibliography_Id })
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.ForeignKey("dbo.Bibliographies", t => t.Bibliography_Id, cascadeDelete: false)
.Index(t => t.DictionaryTocharian_Id)
.Index(t => t.Bibliography_Id);
CreateTable(
"dbo.CaseDictionaryTocharians",
c => new
{
Case_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Case_Id, t.DictionaryTocharian_Id })
.ForeignKey("dbo.Cases", t => t.Case_Id, cascadeDelete: false)
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.Index(t => t.Case_Id)
.Index(t => t.DictionaryTocharian_Id);
CreateTable(
"dbo.GenderDictionaryTocharians",
c => new
{
Gender_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Gender_Id, t.DictionaryTocharian_Id })
.ForeignKey("dbo.Genders", t => t.Gender_Id, cascadeDelete: false)
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.Index(t => t.Gender_Id)
.Index(t => t.DictionaryTocharian_Id);
CreateTable(
"dbo.NumberDictionaryTocharians",
c => new
{
Number_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Number_Id, t.DictionaryTocharian_Id })
.ForeignKey("dbo.Numbers", t => t.Number_Id, cascadeDelete: false)
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.Index(t => t.Number_Id)
.Index(t => t.DictionaryTocharian_Id);
CreateTable(
"dbo.PersonDictionaryTocharians",
c => new
{
Person_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Person_Id, t.DictionaryTocharian_Id })
.ForeignKey("dbo.People", t => t.Person_Id, cascadeDelete: false)
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.Index(t => t.Person_Id)
.Index(t => t.DictionaryTocharian_Id);
CreateTable(
"dbo.ManuscriptBibliographies",
c => new
{
Manuscript_Id = c.Int(nullable: false),
Bibliography_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Manuscript_Id, t.Bibliography_Id })
.ForeignKey("dbo.Manuscripts", t => t.Manuscript_Id, cascadeDelete: false)
.ForeignKey("dbo.Bibliographies", t => t.Bibliography_Id, cascadeDelete: false)
.Index(t => t.Manuscript_Id)
.Index(t => t.Bibliography_Id);
CreateTable(
"dbo.TochPhraseBibliographies",
c => new
{
TochPhrase_Id = c.Int(nullable: false),
Bibliography_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.TochPhrase_Id, t.Bibliography_Id })
.ForeignKey("dbo.TochPhrases", t => t.TochPhrase_Id, cascadeDelete: false)
.ForeignKey("dbo.Bibliographies", t => t.Bibliography_Id, cascadeDelete: false)
.Index(t => t.TochPhrase_Id)
.Index(t => t.Bibliography_Id);
CreateTable(
"dbo.TochStoryBibliographies",
c => new
{
TochStory_Id = c.Int(nullable: false),
Bibliography_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.TochStory_Id, t.Bibliography_Id })
.ForeignKey("dbo.TochStories", t => t.TochStory_Id, cascadeDelete: false)
.ForeignKey("dbo.Bibliographies", t => t.Bibliography_Id, cascadeDelete: false)
.Index(t => t.TochStory_Id)
.Index(t => t.Bibliography_Id);
CreateTable(
"dbo.NamePlaceTochStories",
c => new
{
NamePlace_Id = c.Int(nullable: false),
TochStory_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.NamePlace_Id, t.TochStory_Id })
.ForeignKey("dbo.NamePlaces", t => t.NamePlace_Id, cascadeDelete: false)
.ForeignKey("dbo.TochStories", t => t.TochStory_Id, cascadeDelete: false)
.Index(t => t.NamePlace_Id)
.Index(t => t.TochStory_Id);
CreateTable(
"dbo.ProperNounTochStories",
c => new
{
ProperNoun_Id = c.Int(nullable: false),
TochStory_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.ProperNoun_Id, t.TochStory_Id })
.ForeignKey("dbo.ProperNouns", t => t.ProperNoun_Id, cascadeDelete: false)
.ForeignKey("dbo.TochStories", t => t.TochStory_Id, cascadeDelete: false)
.Index(t => t.ProperNoun_Id)
.Index(t => t.TochStory_Id);
CreateTable(
"dbo.PublicationCollaborations",
c => new
{
Publication_Id = c.Int(nullable: false),
Collaboration_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Publication_Id, t.Collaboration_Id })
.ForeignKey("dbo.Publications", t => t.Publication_Id, cascadeDelete: false)
.ForeignKey("dbo.Collaborations", t => t.Collaboration_Id, cascadeDelete: false)
.Index(t => t.Publication_Id)
.Index(t => t.Collaboration_Id);
}
public override void Down()
{
DropForeignKey("dbo.VisualAids", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.UserRoles", "RoleId", "dbo.Roles");
DropForeignKey("dbo.Presentations", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.LinkAndPresses", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.ImagePartners", "PartnerAndRelationId", "dbo.PartnerAndRelations");
DropForeignKey("dbo.News", "TopicId", "dbo.Topics");
DropForeignKey("dbo.News", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.ImageNews", "NewsId", "dbo.News");
DropForeignKey("dbo.Comments", "NewsId", "dbo.News");
DropForeignKey("dbo.Comments", "UserId", "dbo.Users");
DropForeignKey("dbo.News", "CollaboratorId", "dbo.Collaborators");
DropForeignKey("dbo.Collaborators", "UserId", "dbo.Users");
DropForeignKey("dbo.PublicationCollaborations", "Collaboration_Id", "dbo.Collaborations");
DropForeignKey("dbo.PublicationCollaborations", "Publication_Id", "dbo.Publications");
DropForeignKey("dbo.ImageCollaborations", "CollaborationId", "dbo.Collaborations");
DropForeignKey("dbo.Clients", "UserId", "dbo.Users");
DropForeignKey("dbo.UserRoles", "UserId", "dbo.Users");
DropForeignKey("dbo.UserLogins", "UserId", "dbo.Users");
DropForeignKey("dbo.UserClaims", "UserId", "dbo.Users");
DropForeignKey("dbo.ImageUVs", "AnalyseMaterialId", "dbo.AnalyseMaterials");
DropForeignKey("dbo.ImageAnalyses", "AnalyseMaterialId", "dbo.AnalyseMaterials");
DropForeignKey("dbo.AnalyseMacroscopics", "WritingToolId", "dbo.WritingTools");
DropForeignKey("dbo.TransmittedLights", "AnalyseMacroscopicId", "dbo.AnalyseMacroscopics");
DropForeignKey("dbo.AnalyseMacroscopics", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.AnalyseMacroscopics", "StateId", "dbo.States");
DropForeignKey("dbo.AnalyseMacroscopics", "SieveMarkId", "dbo.SieveMarks");
DropForeignKey("dbo.AnalyseMacroscopics", "ScriptId", "dbo.Scripts");
DropForeignKey("dbo.AnalyseMacroscopics", "RulingColorId", "dbo.RulingColors");
DropForeignKey("dbo.AnalyseMacroscopics", "RulingId", "dbo.Rulings");
DropForeignKey("dbo.AnalyseMacroscopics", "RestoreId", "dbo.Restores");
DropForeignKey("dbo.AnalyseMacroscopics", "PreparationPaperBeforeUsingId", "dbo.PreparationPaperBeforeUsings");
DropForeignKey("dbo.AnalyseMacroscopics", "PaperColorId", "dbo.PaperColors");
DropForeignKey("dbo.AnalyseMacroscopics", "MapId", "dbo.Maps");
DropForeignKey("dbo.AnalyseMacroscopics", "ManufaturingDefectId", "dbo.ManufaturingDefects");
DropForeignKey("dbo.AnalyseMacroscopics", "LaidLinesRegularityId", "dbo.LaidLinesRegularities");
DropForeignKey("dbo.AnalyseMacroscopics", "GenderManuscriptId", "dbo.GenderManuscripts");
DropForeignKey("dbo.AnalyseMacroscopics", "FormatId", "dbo.Formats");
DropForeignKey("dbo.AnalyseMacroscopics", "FiberDistributionId", "dbo.FiberDistributions");
DropForeignKey("dbo.AnalyseMacroscopics", "FiberDirectionId", "dbo.FiberDirections");
DropForeignKey("dbo.AnalyseMacroscopics", "DryingId", "dbo.Dryings");
DropForeignKey("dbo.AnalyseMacroscopics", "ChainLinesVisibilityId", "dbo.ChainLinesVisibilities");
DropForeignKey("dbo.AnalyseMacroscopics", "CatalogieId", "dbo.Catalogies");
DropForeignKey("dbo.Bibliographies", "AnalyseMacroscopic_Id", "dbo.AnalyseMacroscopics");
DropForeignKey("dbo.TochStories", "ThemeStoryId", "dbo.ThemeStories");
DropForeignKey("dbo.TochStories", "SourceStoryId", "dbo.SourceStories");
DropForeignKey("dbo.ProperNounTochStories", "TochStory_Id", "dbo.TochStories");
DropForeignKey("dbo.ProperNounTochStories", "ProperNoun_Id", "dbo.ProperNouns");
DropForeignKey("dbo.NamePlaceTochStories", "TochStory_Id", "dbo.TochStories");
DropForeignKey("dbo.NamePlaceTochStories", "NamePlace_Id", "dbo.NamePlaces");
DropForeignKey("dbo.TochStoryBibliographies", "Bibliography_Id", "dbo.Bibliographies");
DropForeignKey("dbo.TochStoryBibliographies", "TochStory_Id", "dbo.TochStories");
DropForeignKey("dbo.TochPhrases", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.TochPhraseBibliographies", "Bibliography_Id", "dbo.Bibliographies");
DropForeignKey("dbo.TochPhraseBibliographies", "TochPhrase_Id", "dbo.TochPhrases");
DropForeignKey("dbo.Manuscripts", "WritingToolId", "dbo.WritingTools");
DropForeignKey("dbo.Manuscripts", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.Manuscripts", "SubGenderManuscriptId", "dbo.SubGenderManuscripts");
DropForeignKey("dbo.Manuscripts", "StateId", "dbo.States");
DropForeignKey("dbo.Manuscripts", "ScriptAddId", "dbo.ScriptAdds");
DropForeignKey("dbo.Manuscripts", "ScriptId", "dbo.Scripts");
DropForeignKey("dbo.Scripts", "ScriptTypeId", "dbo.ScriptTypes");
DropForeignKey("dbo.Manuscripts", "RulingDetailId", "dbo.RulingDetails");
DropForeignKey("dbo.Manuscripts", "RulingColorId", "dbo.RulingColors");
DropForeignKey("dbo.Manuscripts", "RulingId", "dbo.Rulings");
DropForeignKey("dbo.Manuscripts", "RemarkAddId", "dbo.RemarkAdds");
DropForeignKey("dbo.Manuscripts", "PaperColorId", "dbo.PaperColors");
DropForeignKey("dbo.Manuscripts", "MetricId", "dbo.Metrics");
DropForeignKey("dbo.Manuscripts", "MaterialId", "dbo.Materials");
DropForeignKey("dbo.Manuscripts", "MapId", "dbo.Maps");
DropForeignKey("dbo.ImageMaps", "MapId", "dbo.Maps");
DropForeignKey("dbo.Manuscripts", "LanguageStageId", "dbo.LanguageStages");
DropForeignKey("dbo.Manuscripts", "LanguageDetailId", "dbo.LanguageDetails");
DropForeignKey("dbo.ImageManuscripts", "ManuscriptId", "dbo.Manuscripts");
DropForeignKey("dbo.Manuscripts", "GenderManuscriptId", "dbo.GenderManuscripts");
DropForeignKey("dbo.Manuscripts", "FormatId", "dbo.Formats");
DropForeignKey("dbo.Manuscripts", "DescriptionManuscriptId", "dbo.DescriptionManuscripts");
DropForeignKey("dbo.Manuscripts", "CatalogieId", "dbo.Catalogies");
DropForeignKey("dbo.ManuscriptBibliographies", "Bibliography_Id", "dbo.Bibliographies");
DropForeignKey("dbo.ManuscriptBibliographies", "Manuscript_Id", "dbo.Manuscripts");
DropForeignKey("dbo.Manuscripts", "AlignmentTypeId", "dbo.AlignmentTypes");
DropForeignKey("dbo.ImageBooks", "BibliographyId", "dbo.Bibliographies");
DropForeignKey("dbo.DictionaryTocharians", "WordSubClassId", "dbo.WordSubClasses");
DropForeignKey("dbo.WordSubClasses", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.DictionaryTocharians", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.DictionaryTocharians", "VoiceId", "dbo.Voices");
DropForeignKey("dbo.DictionaryTocharians", "ValencyId", "dbo.Valencies");
DropForeignKey("dbo.DictionaryTocharians", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.DictionaryTocharians", "TenseAndAspectId", "dbo.TenseAndAspects");
DropForeignKey("dbo.PersonDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.PersonDictionaryTocharians", "Person_Id", "dbo.People");
DropForeignKey("dbo.NumberDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.NumberDictionaryTocharians", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.DictionaryTocharians", "MoodId", "dbo.Moods");
DropForeignKey("dbo.GenderDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.GenderDictionaryTocharians", "Gender_Id", "dbo.Genders");
DropForeignKey("dbo.CaseDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.CaseDictionaryTocharians", "Case_Id", "dbo.Cases");
DropForeignKey("dbo.DictionaryTocharianBibliographies", "Bibliography_Id", "dbo.Bibliographies");
DropForeignKey("dbo.DictionaryTocharianBibliographies", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.Activities", "TopicId", "dbo.Topics");
DropForeignKey("dbo.Activities", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.AboutProjects", "LanguageId", "dbo.Languages");
DropForeignKey("dbo.ImageProjects", "AboutProjectId", "dbo.AboutProjects");
DropIndex("dbo.PublicationCollaborations", new[] { "Collaboration_Id" });
DropIndex("dbo.PublicationCollaborations", new[] { "Publication_Id" });
DropIndex("dbo.ProperNounTochStories", new[] { "TochStory_Id" });
DropIndex("dbo.ProperNounTochStories", new[] { "ProperNoun_Id" });
DropIndex("dbo.NamePlaceTochStories", new[] { "TochStory_Id" });
DropIndex("dbo.NamePlaceTochStories", new[] { "NamePlace_Id" });
DropIndex("dbo.TochStoryBibliographies", new[] { "Bibliography_Id" });
DropIndex("dbo.TochStoryBibliographies", new[] { "TochStory_Id" });
DropIndex("dbo.TochPhraseBibliographies", new[] { "Bibliography_Id" });
DropIndex("dbo.TochPhraseBibliographies", new[] { "TochPhrase_Id" });
DropIndex("dbo.ManuscriptBibliographies", new[] { "Bibliography_Id" });
DropIndex("dbo.ManuscriptBibliographies", new[] { "Manuscript_Id" });
DropIndex("dbo.PersonDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.PersonDictionaryTocharians", new[] { "Person_Id" });
DropIndex("dbo.NumberDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.NumberDictionaryTocharians", new[] { "Number_Id" });
DropIndex("dbo.GenderDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.GenderDictionaryTocharians", new[] { "Gender_Id" });
DropIndex("dbo.CaseDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.CaseDictionaryTocharians", new[] { "Case_Id" });
DropIndex("dbo.DictionaryTocharianBibliographies", new[] { "Bibliography_Id" });
DropIndex("dbo.DictionaryTocharianBibliographies", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.VisualAids", new[] { "LanguageId" });
DropIndex("dbo.Roles", "RoleNameIndex");
DropIndex("dbo.Presentations", new[] { "LanguageId" });
DropIndex("dbo.LinkAndPresses", new[] { "LanguageId" });
DropIndex("dbo.ImagePartners", new[] { "PartnerAndRelationId" });
DropIndex("dbo.ImageNews", new[] { "NewsId" });
DropIndex("dbo.Comments", new[] { "UserId" });
DropIndex("dbo.Comments", new[] { "NewsId" });
DropIndex("dbo.News", new[] { "LanguageId" });
DropIndex("dbo.News", new[] { "CollaboratorId" });
DropIndex("dbo.News", new[] { "TopicId" });
DropIndex("dbo.Collaborators", "IX_PersonneUnique");
DropIndex("dbo.Collaborators", new[] { "UserId" });
DropIndex("dbo.ImageCollaborations", new[] { "CollaborationId" });
DropIndex("dbo.UserRoles", new[] { "RoleId" });
DropIndex("dbo.UserRoles", new[] { "UserId" });
DropIndex("dbo.UserLogins", new[] { "UserId" });
DropIndex("dbo.UserClaims", new[] { "UserId" });
DropIndex("dbo.Users", "UserNameIndex");
DropIndex("dbo.Clients", "IX_PersonneUnique");
DropIndex("dbo.Clients", new[] { "UserId" });
DropIndex("dbo.ImageUVs", new[] { "AnalyseMaterialId" });
DropIndex("dbo.ImageAnalyses", new[] { "AnalyseMaterialId" });
DropIndex("dbo.TransmittedLights", new[] { "AnalyseMacroscopicId" });
DropIndex("dbo.TochStories", new[] { "ThemeStoryId" });
DropIndex("dbo.TochStories", new[] { "SourceStoryId" });
DropIndex("dbo.TochPhrases", new[] { "TochLanguageId" });
DropIndex("dbo.Scripts", new[] { "ScriptTypeId" });
DropIndex("dbo.ImageMaps", new[] { "MapId" });
DropIndex("dbo.ImageManuscripts", new[] { "ManuscriptId" });
DropIndex("dbo.Manuscripts", new[] { "MetricId" });
DropIndex("dbo.Manuscripts", new[] { "SubGenderManuscriptId" });
DropIndex("dbo.Manuscripts", new[] { "GenderManuscriptId" });
DropIndex("dbo.Manuscripts", new[] { "LanguageDetailId" });
DropIndex("dbo.Manuscripts", new[] { "LanguageStageId" });
DropIndex("dbo.Manuscripts", new[] { "TochLanguageId" });
DropIndex("dbo.Manuscripts", new[] { "ScriptAddId" });
DropIndex("dbo.Manuscripts", new[] { "ScriptId" });
DropIndex("dbo.Manuscripts", new[] { "AlignmentTypeId" });
DropIndex("dbo.Manuscripts", new[] { "WritingToolId" });
DropIndex("dbo.Manuscripts", new[] { "PaperColorId" });
DropIndex("dbo.Manuscripts", new[] { "MaterialId" });
DropIndex("dbo.Manuscripts", new[] { "RulingDetailId" });
DropIndex("dbo.Manuscripts", new[] { "RulingColorId" });
DropIndex("dbo.Manuscripts", new[] { "RulingId" });
DropIndex("dbo.Manuscripts", new[] { "FormatId" });
DropIndex("dbo.Manuscripts", new[] { "RemarkAddId" });
DropIndex("dbo.Manuscripts", new[] { "DescriptionManuscriptId" });
DropIndex("dbo.Manuscripts", new[] { "StateId" });
DropIndex("dbo.Manuscripts", new[] { "MapId" });
DropIndex("dbo.Manuscripts", new[] { "CatalogieId" });
DropIndex("dbo.ImageBooks", new[] { "BibliographyId" });
DropIndex("dbo.WordSubClasses", new[] { "WordClassId" });
DropIndex("dbo.DictionaryTocharians", new[] { "MoodId" });
DropIndex("dbo.DictionaryTocharians", new[] { "TenseAndAspectId" });
DropIndex("dbo.DictionaryTocharians", new[] { "ValencyId" });
DropIndex("dbo.DictionaryTocharians", new[] { "VoiceId" });
DropIndex("dbo.DictionaryTocharians", new[] { "TochLanguageId" });
DropIndex("dbo.DictionaryTocharians", new[] { "WordSubClassId" });
DropIndex("dbo.DictionaryTocharians", new[] { "WordClassId" });
DropIndex("dbo.Bibliographies", new[] { "AnalyseMacroscopic_Id" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "ManufaturingDefectId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "PreparationPaperBeforeUsingId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "DryingId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "ChainLinesVisibilityId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "LaidLinesRegularityId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "FiberDirectionId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "SieveMarkId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "FiberDistributionId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "RulingColorId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "WritingToolId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "PaperColorId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "ScriptId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "RulingId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "RestoreId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "FormatId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "TochLanguageId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "StateId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "GenderManuscriptId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "MapId" });
DropIndex("dbo.AnalyseMacroscopics", new[] { "CatalogieId" });
DropIndex("dbo.Activities", new[] { "LanguageId" });
DropIndex("dbo.Activities", new[] { "TopicId" });
DropIndex("dbo.ImageProjects", new[] { "AboutProjectId" });
DropIndex("dbo.AboutProjects", new[] { "LanguageId" });
DropTable("dbo.PublicationCollaborations");
DropTable("dbo.ProperNounTochStories");
DropTable("dbo.NamePlaceTochStories");
DropTable("dbo.TochStoryBibliographies");
DropTable("dbo.TochPhraseBibliographies");
DropTable("dbo.ManuscriptBibliographies");
DropTable("dbo.PersonDictionaryTocharians");
DropTable("dbo.NumberDictionaryTocharians");
DropTable("dbo.GenderDictionaryTocharians");
DropTable("dbo.CaseDictionaryTocharians");
DropTable("dbo.DictionaryTocharianBibliographies");
DropTable("dbo.VisualAids");
DropTable("dbo.Roles");
DropTable("dbo.ReverseDictionaries");
DropTable("dbo.Presentations");
DropTable("dbo.LinkAndPresses");
DropTable("dbo.PartnerAndRelations");
DropTable("dbo.ImagePartners");
DropTable("dbo.ImageNews");
DropTable("dbo.Comments");
DropTable("dbo.News");
DropTable("dbo.Collaborators");
DropTable("dbo.Publications");
DropTable("dbo.ImageCollaborations");
DropTable("dbo.Collaborations");
DropTable("dbo.UserRoles");
DropTable("dbo.UserLogins");
DropTable("dbo.UserClaims");
DropTable("dbo.Users");
DropTable("dbo.Clients");
DropTable("dbo.ImageUVs");
DropTable("dbo.ImageAnalyses");
DropTable("dbo.AnalyseMaterials");
DropTable("dbo.TransmittedLights");
DropTable("dbo.SieveMarks");
DropTable("dbo.Restores");
DropTable("dbo.PreparationPaperBeforeUsings");
DropTable("dbo.ManufaturingDefects");
DropTable("dbo.LaidLinesRegularities");
DropTable("dbo.FiberDistributions");
DropTable("dbo.FiberDirections");
DropTable("dbo.Dryings");
DropTable("dbo.ChainLinesVisibilities");
DropTable("dbo.ThemeStories");
DropTable("dbo.SourceStories");
DropTable("dbo.ProperNouns");
DropTable("dbo.NamePlaces");
DropTable("dbo.TochStories");
DropTable("dbo.TochPhrases");
DropTable("dbo.WritingTools");
DropTable("dbo.SubGenderManuscripts");
DropTable("dbo.States");
DropTable("dbo.ScriptAdds");
DropTable("dbo.ScriptTypes");
DropTable("dbo.Scripts");
DropTable("dbo.RulingDetails");
DropTable("dbo.RulingColors");
DropTable("dbo.Rulings");
DropTable("dbo.RemarkAdds");
DropTable("dbo.PaperColors");
DropTable("dbo.Metrics");
DropTable("dbo.Materials");
DropTable("dbo.ImageMaps");
DropTable("dbo.Maps");
DropTable("dbo.LanguageStages");
DropTable("dbo.LanguageDetails");
DropTable("dbo.ImageManuscripts");
DropTable("dbo.GenderManuscripts");
DropTable("dbo.Formats");
DropTable("dbo.DescriptionManuscripts");
DropTable("dbo.Catalogies");
DropTable("dbo.Manuscripts");
DropTable("dbo.ImageBooks");
DropTable("dbo.WordSubClasses");
DropTable("dbo.WordClasses");
DropTable("dbo.Voices");
DropTable("dbo.Valencies");
DropTable("dbo.TochLanguages");
DropTable("dbo.TenseAndAspects");
DropTable("dbo.People");
DropTable("dbo.Numbers");
DropTable("dbo.Moods");
DropTable("dbo.Genders");
DropTable("dbo.Cases");
DropTable("dbo.DictionaryTocharians");
DropTable("dbo.Bibliographies");
DropTable("dbo.AnalyseMacroscopics");
DropTable("dbo.AlignmentTypes");
DropTable("dbo.Topics");
DropTable("dbo.Activities");
DropTable("dbo.Abreviations");
DropTable("dbo.Languages");
DropTable("dbo.ImageProjects");
DropTable("dbo.AboutProjects");
DropTable("dbo.AbbreviationDictionaries");
}
}
}
<file_sep>/Horizone/Models/ImageManuscript.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Horizone.Models
{
public class ImageManuscript
{
public int Id { get; set; }
[Display(Name = "Name", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(150)]
public string Name { get; set; }
[Required]
[StringLength(20)]
public string ContentType { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public byte[] Content { get; set; }
[Display(Name = "Manuscript",ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public int ManuscriptId { get; set; }
[ForeignKey("ManuscriptId")]
public Manuscript Manuscript { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/DescriptionManuscriptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class DescriptionManuscriptsController : BaseController
{
// GET: BackOffice/DescriptionManuscripts
public ActionResult Index()
{
return View(db.DescriptionManuscripts.ToList());
}
// GET: BackOffice/DescriptionManuscripts/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/DescriptionManuscripts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DescriptionEn,DescriptionFr,DescriptionZh")] DescriptionManuscript descriptionManuscript)
{
if (ModelState.IsValid)
{
db.DescriptionManuscripts.Add(descriptionManuscript);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(descriptionManuscript);
}
// GET: BackOffice/DescriptionManuscripts/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DescriptionManuscript descriptionManuscript = db.DescriptionManuscripts.Find(id);
if (descriptionManuscript == null)
{
return HttpNotFound();
}
return View(descriptionManuscript);
}
// POST: BackOffice/DescriptionManuscripts/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DescriptionEn,DescriptionFr,DescriptionZh")] DescriptionManuscript descriptionManuscript)
{
if (ModelState.IsValid)
{
db.Entry(descriptionManuscript).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(descriptionManuscript);
}
// GET: BackOffice/DescriptionManuscripts/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DescriptionManuscript descriptionManuscript = db.DescriptionManuscripts.Find(id);
if (descriptionManuscript == null)
{
return HttpNotFound();
}
return View(descriptionManuscript);
}
// POST: BackOffice/DescriptionManuscripts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
DescriptionManuscript descriptionManuscript = db.DescriptionManuscripts.Find(id);
db.DescriptionManuscripts.Remove(descriptionManuscript);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/TochStoriesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class TochStoriesController : BaseController
{
// GET: BackOffice/TochStories
public ActionResult Index()
{
var tochStorys = db.TochStorys.Include(t => t.SourceStory).Include(t => t.ThemeStory);
return View(tochStorys.ToList());
}
// GET: BackOffice/TochStories/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochStory tochStory = db.TochStorys.Include("SourceStory").Include("ThemeStory").SingleOrDefault(x => x.Id == id);
if (tochStory == null)
{
return HttpNotFound();
}
return View(tochStory);
}
// GET: BackOffice/TochStories/Create
public ActionResult Create()
{
ViewBag.SourceStoryId = new SelectList(db.SourceStorys, "Id", "SourceEn");
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeEn), "Id", "ThemeEn");
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeFr), "Id", "ThemeFr");
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeZn), "Id", "ThemeZn");
}
return View();
}
// POST: BackOffice/TochStories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,SourceStoryId,ThemeStoryId,PlasticRepresentation,MainFindSpot,Content,English,Francaise,Chinese,Description,Visible")] TochStory tochStory )
{
if (ModelState.IsValid)
{
db.TochStorys.Add(tochStory);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SourceStoryId = new SelectList(db.SourceStorys, "Id", "SourceEn", tochStory.SourceStoryId);
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeEn), "Id", "ThemeEn", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeFr), "Id", "ThemeFr", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeZn), "Id", "ThemeZn", tochStory.ThemeStoryId);
}
return View(tochStory);
}
// GET: BackOffice/TochStories/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochStory tochStory = db.TochStorys.Include("SourceStory").Include("ThemeStory").SingleOrDefault(x => x.Id == id); ;
if (tochStory == null)
{
return HttpNotFound();
}
ViewBag.SourceStoryId = new SelectList(db.SourceStorys, "Id", "SourceEn", tochStory.SourceStoryId);
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeEn), "Id", "ThemeEn", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeFr), "Id", "ThemeFr", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeZn), "Id", "ThemeZn", tochStory.ThemeStoryId);
}
return View(tochStory);
}
// POST: BackOffice/TochStories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name,SourceStoryId,ThemeStoryId,PlasticRepresentation,MainFindSpot,Content,English,Francaise,Chinese,Description,Visible")] TochStory tochStory)
{
db.Entry(tochStory).State = EntityState.Modified;
db.TochStorys.SingleOrDefault(x => x.Id == tochStory.Id);
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SourceStoryId = new SelectList(db.SourceStorys, "Id", "SourceEn", tochStory.SourceStoryId);
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeEn), "Id", "ThemeEn", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeFr), "Id", "ThemeFr", tochStory.ThemeStoryId);
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
ViewBag.ThemeStoryId = new SelectList(db.ThemeStorys.OrderBy(x => x.ThemeZn), "Id", "ThemeZn", tochStory.ThemeStoryId);
}
return View(tochStory);
}
// GET: BackOffice/TochStories/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochStory tochStory = db.TochStorys.Find(id);
if (tochStory == null)
{
return HttpNotFound();
}
return View(tochStory);
}
// POST: BackOffice/TochStories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
TochStory tochStory = db.TochStorys.Find(id);
db.TochStorys.Remove(tochStory);
db.SaveChanges();
return RedirectToAction("Index");
}
// Search
public ActionResult SearchStory(string search)
{
IEnumerable<TochStory> tochStories = db.TochStorys.Include("SourceStory").Include("ThemeStory");
if (!string.IsNullOrWhiteSpace(search))
{
tochStories = tochStories.Where(x => (x.Content != null && x.Content.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))
|| (x.SourceStory.SourceEn != null && x.SourceStory.SourceEn.Contains(search))
|| (x.SourceStory.SourceFr != null && x.SourceStory.SourceFr.Contains(search))
|| (x.SourceStory.SourceZh != null && x.SourceStory.SourceZh.Contains(search))
|| (x.Name != null && x.Name.Contains(search))
|| (x.SourceStory.SourceEn != null && x.Description.Contains(search))
|| (x.ThemeStory.ThemeEn != null && x.ThemeStory.ThemeEn.Contains(search))
|| (x.ThemeStory.ThemeFr != null && x.ThemeStory.ThemeFr.Contains(search))
|| (x.ThemeStory.ThemeZn != null && x.ThemeStory.ThemeZn.Contains(search)));
}
if (tochStories.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchStory", tochStories.OrderBy(x => x.Name).ToList());
}
}
}
<file_sep>/Horizone/Models/GenderManuscript.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class GenderManuscript
{
public int Id { get; set; }
[Display(Name = "GenderEn", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderEn { get; set; }
[Display(Name = "GenderFr", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderFr { get; set; }
[Display(Name = "GenderZh", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderZh { get; set; }
}
}<file_sep>/Horizone/Models/Gender.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Gender
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string NameGender { get; set; }
[Display(Name = "GenderEn", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderEn { get; set; }
[Display(Name = "GenderFr", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderFr { get; set; }
[Display(Name = "GenderZh", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderZh { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<DictionaryTocharian> DictionaryTocharians { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<NounAdjective> NounAdjectives { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Pronoun> Pronouns { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/MapsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class MapsController : BaseController
{
// GET: BackOffice/Maps
public ActionResult Index()
{
return View(db.Maps.ToList());
}
// GET: BackOffice/Maps/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Map map = db.Maps.Find(id);
if (map == null)
{
return HttpNotFound();
}
return View(map);
}
// GET: BackOffice/Maps/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/Maps/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,NamePicture")] Map map)
{
if (ModelState.IsValid)
{
db.Maps.Add(map);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(map);
}
// GET: BackOffice/Maps/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Map map = db.Maps.Include("ImageMaps").SingleOrDefault(x => x.Id == id);
if (map == null)
{
return HttpNotFound();
}
return View(map);
}
// POST: BackOffice/Maps/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,NamePicture")] Map map)
{
db.Entry(map).State = EntityState.Modified;
db.Maps.Include("ImageMaps").SingleOrDefault(x => x.Id == map.Id);
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(map);
}
// GET: BackOffice/Maps/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Map map = db.Maps.Include("ImageMaps").SingleOrDefault(x => x.Id == id);
if (map == null)
{
return HttpNotFound();
}
return View(map);
}
// POST: BackOffice/Maps/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Map map = db.Maps.Include("ImageMaps").SingleOrDefault(x => x.Id == id);
db.Maps.Remove(map);
db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
public ActionResult AddPicture(HttpPostedFileBase picture, int id)
{
if (picture?.ContentLength > 0)
{
var tp = new ImageMap();
tp.ContentType = picture.ContentType;
tp.Name = picture.FileName;
tp.MapId = id;
using (var reader = new BinaryReader(picture.InputStream))
{
tp.Content = reader.ReadBytes(picture.ContentLength);
}
db.ImageMaps.Add(tp);
db.SaveChanges();
return RedirectToAction("edit", "Maps", new { id = id });
}
Display("une image doit être séléctionnée");
// return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return RedirectToAction("edit", "Maps", new { id = id });
}
public ActionResult DeletePicture(int id, int idmap)
{
ImageMap image = db.ImageMaps.Find(id);
db.ImageMaps.Remove(image);
db.Entry(image).State = EntityState.Deleted;
db.SaveChanges();
// return Json(image);
return RedirectToAction("Edit", "Maps", new { id = idmap });
}
}
}
<file_sep>/Horizone/Models/Script.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Script
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "ScriptEn", ResourceType = typeof(StaticResource.Resources))]
public string ScriptEn { get; set; }
[AllowHtml]
[Display(Name = "ScriptFr", ResourceType = typeof(StaticResource.Resources))]
public string ScriptFr { get; set; }
[AllowHtml]
[Display(Name = "ScriptZh", ResourceType = typeof(StaticResource.Resources))]
public string ScriptZh { get; set; }
[Display(Name = "ScriptType", ResourceType = typeof(StaticResource.Resources))]
public int ScriptTypeId { get; set; }
[ForeignKey("ScriptTypeId")]
public ScriptType ScriptType { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/ClientsController.cs
using Horizone.Controllers;
using Horizone.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ClientsController : BaseController
{
// GET: BackOffice/Clients
public ActionResult Index()
{
List<Client> clients = db.Clients.ToList();
return View(clients);
}
// GET: BackOffice/Topics/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Client client = db.Clients.Find(id);
if (client == null)
{
return HttpNotFound();
}
return View(client);
}
// POST: BackOffice/Topics/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Client client = db.Clients.Find(id);
db.Clients.Remove(client);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/WritingTool.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class WritingTool
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "WritingToolEn", ResourceType = typeof(StaticResource.Resources))]
public string WritingToolEn { get; set; }
[AllowHtml]
[Display(Name = "WritingToolFr", ResourceType = typeof(StaticResource.Resources))]
public string WritingToolFr { get; set; }
[AllowHtml]
[Display(Name = "WritingToolZh", ResourceType = typeof(StaticResource.Resources))]
public string WritingToolZh { get; set; }
}
}<file_sep>/Horizone/Models/TochPhrase.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class TochPhrase
{
public int Id { get; set; }
[AllowHtml]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[Display(Name = "Phrase", ResourceType = typeof(StaticResource.Resources))]
public string Phrase { get; set; }
[AllowHtml]
[Display(Name = "English", ResourceType = typeof(StaticResource.Resources))]
public string English { get; set; }
[AllowHtml]
[Display(Name = "French", ResourceType = typeof(StaticResource.Resources))]
public string Francaise { get; set; }
[AllowHtml]
[Display(Name = "Chinese", ResourceType = typeof(StaticResource.Resources))]
public string Chinese { get; set; }
[Display(Name = "TochLanguage", ResourceType = typeof(StaticResource.Resources))]
public int TochLanguageId { get; set; }
[ForeignKey("TochLanguageId")]
public TochLanguage TochLanguage { get; set; }
[Display(Name = "DerivedFrom", ResourceType = typeof(StaticResource.Resources))]
public string DerivedFrom { get; set; }
[AllowHtml]
[Display(Name = "RelatedLexemes", ResourceType = typeof(StaticResource.Resources))]
public string RelatedLexemes { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Bibliography> Bibliographys { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
}
}<file_sep>/Horizone/Models/Metric.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Metric
{
public int Id { get; set; }
[Display(Name = "MetricEn", ResourceType = typeof(StaticResource.Resources))]
public string MetricEn { get; set; }
[Display(Name = "MetricFr", ResourceType = typeof(StaticResource.Resources))]
public string MetricFr { get; set; }
[Display(Name = "MetricZh", ResourceType = typeof(StaticResource.Resources))]
public string MetricZh { get; set; }
}
}<file_sep>/Horizone/Models/SieveMark.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class SieveMark
{
public int Id { get; set; }
[Display(Name = "SieveMark", ResourceType = typeof(StaticResource.Resources))]
public string SieveMarkEn { get; set; }
[Display(Name = "SieveMark", ResourceType = typeof(StaticResource.Resources))]
public string SieveMarkFr { get; set; }
[Display(Name = "SieveMark", ResourceType = typeof(StaticResource.Resources))]
public string SieveMarkZh { get; set; }
}
}<file_sep>/Horizone/Models/PaperColor.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class PaperColor
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "PaperColorEn", ResourceType = typeof(StaticResource.Resources))]
public string PaperColorEn { get; set; }
[AllowHtml]
[Display(Name = "PaperColorFr", ResourceType = typeof(StaticResource.Resources))]
public string PaperColorFr { get; set; }
[AllowHtml]
[Display(Name = "PaperColorZh", ResourceType = typeof(StaticResource.Resources))]
public string PaperColorZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/StatesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class StatesController : BaseController
{
// GET: BackOffice/States
public ActionResult Index()
{
return View(db.States.ToList());
}
// GET: BackOffice/States/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/States/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,StateEn,StateFr,StateZh")] State state)
{
if (ModelState.IsValid)
{
db.States.Add(state);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(state);
}
// GET: BackOffice/States/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
State state = db.States.Find(id);
if (state == null)
{
return HttpNotFound();
}
return View(state);
}
// POST: BackOffice/States/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,StateEn,StateFr,StateZh")] State state)
{
if (ModelState.IsValid)
{
db.Entry(state).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(state);
}
// GET: BackOffice/States/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
State state = db.States.Find(id);
if (state == null)
{
return HttpNotFound();
}
return View(state);
}
// POST: BackOffice/States/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
State state = db.States.Find(id);
db.States.Remove(state);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/PronounsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class PronounsController : BaseController
{
// GET: BackOffice/Pronouns
public ActionResult Index()
{
var pronouns = db.Pronouns.Include(p => p.DictionaryTocharian)
.Include(p=>p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Genders").Include("Persons").Include("Cases").OrderBy(x => x.DictionaryTocharian.Word);
return View(pronouns.ToList());
}
// GET: BackOffice/Pronouns/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pronoun pronoun = db.Pronouns.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Genders").Include("Persons").Include("Cases")
.SingleOrDefault(p=>p.Id == id);
if (pronoun.Cases.Count() == 0)
pronoun.Cases = db.Cases.Where(x => x.NameCaseEn == "No Case").ToList();
if (pronoun.Genders.Count() == 0)
pronoun.Genders = db.Genders.Where(x => x.NameGenderEn == "No Gender").ToList();
if (pronoun.Persons.Count() == 0)
pronoun.Persons = db.Persons.Where(x => x.ConjugatedPersonEn == "No Person").ToList();
if (pronoun == null)
{
return HttpNotFound();
}
return View(pronoun);
}
// GET: BackOffice/Pronouns/Create
public ActionResult Create()
{
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 3 || x.WordSubClassId == 80).OrderBy(x => x.Word), "Id", "Word");
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View();
}
// POST: BackOffice/Pronouns/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DictionaryId")] Pronoun pronoun, int[] CaseId, int[] GenderId, int[] PersonId)
{
if (ModelState.IsValid)
{
if (CaseId.Count() == 0)
{ pronoun.Cases = db.Cases.Where(x => x.Id == 1).ToList(); }
else
{
pronoun.Cases = db.Cases.Where(x => CaseId.Contains(x.Id)).ToList();
}
if (GenderId.Count() == 0)
{
pronoun.Genders = db.Genders.Where(x => x.Id == 1).ToList();
}
else
{
pronoun.Genders = db.Genders.Where(x => GenderId.Contains(x.Id)).ToList();
}
if (PersonId.Count() == 0)
{
pronoun.Persons = db.Persons.Where(x => x.Id == 1).ToList();
}
else
{
pronoun.Persons = db.Persons.Where(x => PersonId.Contains(x.Id)).ToList();
}
db.Pronouns.Add(pronoun);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 3 || x.WordSubClassId == 80).OrderBy(x => x.Word), "Id", "Word", pronoun.DictionaryId);
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(pronoun);
}
// GET: BackOffice/Pronouns/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pronoun pronoun = db.Pronouns.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Genders").Include("Persons").Include("Cases")
.SingleOrDefault(p => p.Id == id);
if (pronoun == null)
{
return HttpNotFound();
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 3 || x.WordSubClassId == 80).OrderBy(x => x.Word), "Id", "Word", pronoun.DictionaryId);
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(pronoun);
}
// POST: BackOffice/Pronouns/Edit/5
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DictionaryId")] Pronoun pronoun, int[] CaseId, int[] GenderId, int[] PersonId)
{
if (ModelState.IsValid)
{
db.Entry(pronoun).State = EntityState.Modified;
if (CaseId != null)
pronoun.Cases = db.Cases.Where(x => CaseId.Contains(x.Id)).ToList();
if (GenderId != null)
pronoun.Genders = db.Genders.Where(x => GenderId.Contains(x.Id)).ToList();
if (PersonId != null)
pronoun.Persons = db.Persons.Where(x => PersonId.Contains(x.Id)).ToList();
if (pronoun.Cases.Count() == 0)
pronoun.Cases = db.Cases.Where(x => x.NameCaseEn == "No Case").ToList();
if (pronoun.Genders.Count() == 0)
pronoun.Genders = db.Genders.Where(x => x.NameGenderEn == "No Gender").ToList();
if (pronoun.Persons.Count() == 0)
pronoun.Persons = db.Persons.Where(x => x.ConjugatedPersonEn == "No Person").ToList();
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 3 || x.WordSubClassId == 80).OrderBy(x => x.Word), "Id", "Word", pronoun.DictionaryId);
ViewBag.CasesEn = new SelectList(db.Cases.OrderBy(x => x.NameCaseEn), "Id", "NameCaseEn");
ViewBag.CasesFr = new SelectList(db.Cases.OrderBy(x => x.NameCaseFr), "Id", "NameCaseFr");
ViewBag.CasesZh = new SelectList(db.Cases.OrderBy(x => x.NameCaseZh), "Id", "NameCaseZh");
ViewBag.GendersFr = new SelectList(db.Genders.OrderBy(x => x.NameGenderEn), "Id", "NameGenderFr");
ViewBag.GendersEn = new SelectList(db.Genders.OrderBy(x => x.NameGenderFr), "Id", "NameGenderEn");
ViewBag.GendersZh = new SelectList(db.Genders.OrderBy(x => x.NameGenderZh), "Id", "NameGenderZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(pronoun);
}
// GET: BackOffice/Pronouns/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Pronoun pronoun = db.Pronouns.Include(p => p.DictionaryTocharian).Include(p => p.DictionaryTocharian.TochLanguage).Include("Genders").Include("Persons").Include("Cases").SingleOrDefault(p => p.Id == id);
if (pronoun == null)
{
return HttpNotFound();
}
return View(pronoun);
}
// POST: BackOffice/Pronouns/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Pronoun pronoun = db.Pronouns.Include(p => p.DictionaryTocharian).Include(p => p.DictionaryTocharian.TochLanguage).Include("Genders").Include("Persons").Include("Cases").SingleOrDefault(p => p.Id == id);
db.Pronouns.Remove(pronoun);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchDictionary(string search)
{
IEnumerable<Pronoun> pronouns = db.Pronouns.Include(d => d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
pronouns = pronouns.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (pronouns.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = pronouns.Count();
ViewBag.Search = search;
return View("SearchDictionary", pronouns.ToList());
}
}
}
<file_sep>/Horizone/Areas/BackOffice/Controllers/DictionaryTochariansController.cs
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class DictionaryTochariansController : BaseController
{
// GET: BackOffice/DictionaryTocharians
public ActionResult Index(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers");
return View(dictionaryTocharians.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
// GET: BackOffice/DictionaryTocharians/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers").SingleOrDefault(x => x.Id == id);
if (dictionaryTocharian.Numbers.Count() == 0)
dictionaryTocharian.Numbers = db.Numbers.Where(x => x.WordNumberEn == "No Number").ToList();
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
return View(dictionaryTocharian);
}
// GET: BackOffice/DictionaryTocharians/Create
public ActionResult Create()
{
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language");
ViewBag.WordClassEnId = new SelectList(db.WordClasses.OrderBy(x => x.ClassEn), "ClassEn");
ViewBag.WordClassFrId = new SelectList(db.WordClasses.OrderBy(x => x.ClassFr), "Id", "ClassFr");
ViewBag.WordClassZhId = new SelectList(db.WordClasses.OrderBy(x => x.ClassZh), "Id", "ClassZh");
ViewBag.WordSubClassEnId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassEn), "Id", "SubClassEn");
ViewBag.WordSubClassFrId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassFr), "Id", "SubClassFr");
ViewBag.WordSubClassZhId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassZh), "Id", "SubClassZh");
ViewBag.NumbersEn = new SelectList(db.Numbers.OrderBy(x => x.WordNumberEn), "Id", "WordNumberEn");
ViewBag.NumbersFr = new SelectList(db.Numbers.OrderBy(x => x.WordNumberFr), "Id", "WordNumberFr");
ViewBag.NumbersZh = new SelectList(db.Numbers.OrderBy(x => x.WordNumberZh), "Id", "WordNumberZh");
return View();
}
// POST: BackOffice/DictionaryTocharians/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Word,Sanskrit,English,Francaise,German,Latin,Chinese,WordClassId,WordSubClassId,TochLanguageId,EquivalentTA,EquivalentTB,TochCommon,TochCorrespondence,EquivalentInOther,DerivedFrom,RelatedLexemes,RootCharacter,InternalRootVowel,Stem,StemClass,Visible")] DictionaryTocharian dictionaryTocharian, int[] NumberId)
{
if (ModelState.IsValid)
{
if (NumberId.Count() > 0)
{
dictionaryTocharian.Numbers = db.Numbers.Where(x => NumberId.Contains(x.Id)).ToList();
}
else
{
dictionaryTocharian.Numbers = db.Numbers.Where(x => x.Id == 1).ToList();
}
db.DictionaryTocharians.Add(dictionaryTocharian);
db.SaveChanges();
if (dictionaryTocharian.WordClassId == 10)
{
AddVerb(dictionaryTocharian.Id);
return RedirectToAction("Details", "Verbs", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId == 2 || dictionaryTocharian.WordClassId == 4)
{
AddNounAdjective(dictionaryTocharian.Id);
return RedirectToAction("Details", "NounAdjectives", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId == 3)
{
AddPronoun(dictionaryTocharian.Id);
return RedirectToAction("Details", "Pronouns", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId != 10 && dictionaryTocharian.WordClassId != 2 && dictionaryTocharian.WordClassId != 3 && dictionaryTocharian.WordClassId != 4)
{
AddOtherWord(dictionaryTocharian.Id);
return RedirectToAction("Details", "OtherWords", new { id = ViewBag.Id });
}
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", dictionaryTocharian.TochLanguageId);
ViewBag.WordClassEnId = new SelectList(db.WordClasses.OrderBy(x => x.ClassEn), "ClassEn");
ViewBag.WordClassFrId = new SelectList(db.WordClasses.OrderBy(x => x.ClassFr), "Id", "ClassFr");
ViewBag.WordClassZhId = new SelectList(db.WordClasses.OrderBy(x => x.ClassZh), "Id", "ClassZh");
ViewBag.WordSubClassEnId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassEn), "Id", "SubClassEn");
ViewBag.WordSubClassFrId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassFr), "Id", "SubClassFr");
ViewBag.WordSubClassZhId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassZh), "Id", "SubClassZh");
ViewBag.NumbersEn = new SelectList(db.Numbers.OrderBy(x => x.WordNumberEn), "Id", "WordNumberEn");
ViewBag.NumbersFr = new SelectList(db.Numbers.OrderBy(x => x.WordNumberFr), "Id", "WordNumberFr");
ViewBag.NumbersZh = new SelectList(db.Numbers.OrderBy(x => x.WordNumberZh), "Id", "WordNumberZh");
return View();
}
// GET: BackOffice/DictionaryTocharians/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers").SingleOrDefault(x => x.Id == id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", dictionaryTocharian.TochLanguageId);
ViewBag.WordClassEnId = new SelectList(db.WordClasses.OrderBy(x => x.ClassEn), "ClassEn");
ViewBag.WordClassFrId = new SelectList(db.WordClasses.OrderBy(x => x.ClassFr), "Id", "ClassFr");
ViewBag.WordClassZhId = new SelectList(db.WordClasses.OrderBy(x => x.ClassZh), "Id", "ClassZh");
ViewBag.WordSubClassEnId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassEn), "Id", "SubClassEn");
ViewBag.WordSubClassFrId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassFr), "Id", "SubClassFr");
ViewBag.WordSubClassZhId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassZh), "Id", "SubClassZh");
ViewBag.NumbersEn = new SelectList(db.Numbers.OrderBy(x => x.WordNumberEn), "Id", "WordNumberEn");
ViewBag.NumbersFr = new SelectList(db.Numbers.OrderBy(x => x.WordNumberFr), "Id", "WordNumberFr");
ViewBag.NumbersZh = new SelectList(db.Numbers.OrderBy(x => x.WordNumberZh), "Id", "WordNumberZh");
return View(dictionaryTocharian);
}
// POST: BackOffice/DictionaryTocharians/Edit/5
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Word,Sanskrit,English,Francaise,German,Latin,Chinese,WordClassId,WordSubClassId,TochLanguageId,EquivalentTA,EquivalentTB,TochCommon,TochCorrespondence,EquivalentInOther,DerivedFrom,RelatedLexemes,RootCharacter,InternalRootVowel,Stem,StemClass,Visible")] DictionaryTocharian dictionaryTocharian, int[] NumberId)
{
db.Entry(dictionaryTocharian).State = EntityState.Modified;
if (ModelState.IsValid)
{
if (NumberId != null)
dictionaryTocharian.Numbers = db.Numbers.Where(x => NumberId.Contains(x.Id)).ToList();
db.SaveChanges();
if (dictionaryTocharian.WordClassId == 10)
{
IEnumerable<Verb> verbs = db.Verbs.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (verbs.Count() == 0)
{
AddVerb(dictionaryTocharian.Id);
}
else
{
ViewBag.Id = verbs.First().Id;
}
return RedirectToAction("Details", "Verbs", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId == 2 || dictionaryTocharian.WordClassId == 4)
{
IEnumerable<NounAdjective> nounAdjectives = db.NounAdjectives.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (nounAdjectives.Count() == 0)
{
AddNounAdjective(dictionaryTocharian.Id);
}
else
{
ViewBag.Id = nounAdjectives.First().Id;
}
return RedirectToAction("Details", "NounAdjectives", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId == 3)
{
IEnumerable<Pronoun> pronouns = db.Pronouns.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (pronouns.Count() == 0)
{
AddPronoun(dictionaryTocharian.Id);
}
else
{
ViewBag.Id = pronouns.First().Id;
}
return RedirectToAction("Details", "Pronouns", new { id = ViewBag.Id });
}
if (dictionaryTocharian.WordClassId != 10 && dictionaryTocharian.WordClassId != 2 && dictionaryTocharian.WordClassId == 3 && dictionaryTocharian.WordClassId == 4)
{
IEnumerable<OtherWord> otherWords = db.OtherWords.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (otherWords.Count() == 0)
{
AddOtherWord(dictionaryTocharian.Id);
}
else
{
ViewBag.Id = otherWords.First().Id;
}
return RedirectToAction("Details", "OtherWords", new { id = ViewBag.Id });
}
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", dictionaryTocharian.TochLanguageId);
ViewBag.WordClassEnId = new SelectList(db.WordClasses.OrderBy(x => x.ClassEn), "ClassEn");
ViewBag.WordClassFrId = new SelectList(db.WordClasses.OrderBy(x => x.ClassFr), "Id", "ClassFr");
ViewBag.WordClassZhId = new SelectList(db.WordClasses.OrderBy(x => x.ClassZh), "Id", "ClassZh");
ViewBag.WordSubClassEnId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassEn), "Id", "SubClassEn");
ViewBag.WordSubClassFrId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassFr), "Id", "SubClassFr");
ViewBag.WordSubClassZhId = new SelectList(db.WordSubClasses.OrderBy(x => x.SubClassZh), "Id", "SubClassZh");
ViewBag.NumbersEn = new SelectList(db.Numbers.OrderBy(x => x.WordNumberEn), "Id", "WordNumberEn");
ViewBag.NumbersFr = new SelectList(db.Numbers.OrderBy(x => x.WordNumberFr), "Id", "WordNumberFr");
ViewBag.NumbersZh = new SelectList(db.Numbers.OrderBy(x => x.WordNumberZh), "Id", "WordNumberZh");
return View(dictionaryTocharian);
}
// POST: BackOffice/Verbs/AddVerb/5
public ActionResult AddVerb(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Find(id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
IEnumerable<Verb> verbs = db.Verbs.Where(x => x.DictionaryId == dictionaryTocharian.Id);
Verb verb = new Verb();
if (verbs.Count() == 0)
{
verb.DictionaryId = dictionaryTocharian.Id;
verb.MoodId = 1;
verb.TenseAndAspectId = 1;
verb.ValencyId = 1;
verb.VoiceId = 1;
}
else
{
Display("Verb existe");
}
db.Verbs.Add(verb);
db.SaveChanges();
ViewBag.Id = verb.Id;
return RedirectToAction("Details", "Verbs", new { id = verb.Id });
}
// POST: BackOffice/DictionaryTocharians/AddNounAdjective/5
public ActionResult AddNounAdjective(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Find(id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
IEnumerable<NounAdjective> nounAdjectives = db.NounAdjectives.Where(x => x.DictionaryId == dictionaryTocharian.Id);
NounAdjective nounAdjective = new NounAdjective();
if (nounAdjectives.Count() == 0)
{
nounAdjective.DictionaryId = dictionaryTocharian.Id;
}
else
{
Display("NounAdjective existe");
}
db.NounAdjectives.Add(nounAdjective);
db.SaveChanges();
ViewBag.Id = nounAdjective.Id;
return RedirectToAction("Details", "NounAdjectives", new { id = nounAdjective.Id });
}
// POST: BackOffice/DictionaryTocharians/Pronoun/5
public ActionResult AddPronoun(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Find(id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
IEnumerable<Pronoun> pronouns = db.Pronouns.Where(x => x.DictionaryId == dictionaryTocharian.Id);
Pronoun pronoun = new Pronoun();
if (pronouns.Count() == 0)
{
pronoun.DictionaryId = dictionaryTocharian.Id;
}
else
{
Display("Pronoun existe");
}
db.Pronouns.Add(pronoun);
db.SaveChanges();
ViewBag.Id = pronoun.Id;
return RedirectToAction("Details", "Pronouns", new { id = pronoun.Id });
}
// POST: BackOffice/DictionaryTocharians/AddOtherWord/5
public ActionResult AddOtherWord(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Find(id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
IEnumerable<OtherWord> otherWords = db.OtherWords.Where(x => x.DictionaryId == dictionaryTocharian.Id);
OtherWord otherWord = new OtherWord();
if (otherWords.Count() == 0)
{
otherWord.DictionaryId = dictionaryTocharian.Id;
}
else
{
Display("OtherWord existe");
}
db.OtherWords.Add(otherWord);
db.SaveChanges();
ViewBag.Id = otherWord.Id;
return RedirectToAction("Details", "OtherWords", new { id = otherWord.Id });
}
// GET: BackOffice/DictionaryTocharians/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Find(id);
if (dictionaryTocharian == null)
{
return HttpNotFound();
}
return View(dictionaryTocharian);
}
// POST: BackOffice/DictionaryTocharians/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
DictionaryTocharian dictionaryTocharian = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass).Include("Numbers").SingleOrDefault(x => x.Id == id);
if (dictionaryTocharian.WordClassId == 10)
{
IEnumerable<Verb> verbs = db.Verbs.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (verbs.Count() != 0)
{
foreach (var item in verbs)
{
db.Verbs.Remove(item);
}
}
}
if (dictionaryTocharian.WordClassId == 2 || dictionaryTocharian.WordClassId == 4)
{
IEnumerable<NounAdjective> nounAdjectives = db.NounAdjectives.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (nounAdjectives.Count() != 0)
{
foreach (var item in nounAdjectives)
{
db.NounAdjectives.Remove(item);
}
}
}
if (dictionaryTocharian.WordClassId == 3)
{
IEnumerable<Pronoun> pronouns = db.Pronouns.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (pronouns.Count() != 0)
{
foreach (var item in pronouns)
{
db.Pronouns.Remove(item);
}
}
}
if (dictionaryTocharian.WordClassId != 10 && dictionaryTocharian.WordClassId != 2 && dictionaryTocharian.WordClassId != 3 && dictionaryTocharian.WordClassId != 4)
{
IEnumerable<OtherWord> otherWords = db.OtherWords.Where(x => x.DictionaryId == dictionaryTocharian.Id);
if (otherWords.Count() != 0)
{
foreach (var item in otherWords)
{
db.OtherWords.Remove(item);
}
}
}
db.DictionaryTocharians.Remove(dictionaryTocharian);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult Parallel(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.Word).ToPagedList(page, pageSize));
}
public ActionResult TocharianA(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Where(x => x.TochLanguage.Language.Contains("TA")).Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.EquivalentTA).ToPagedList(page, pageSize));
}
public ActionResult TocharianB(int page = 1, int pageSize = 200)
{
var dictionaryTocharians = db.DictionaryTocharians.Where(x => x.TochLanguage.Language.Contains("TB")).Include(d => d.TochLanguage).Include(d => d.WordClass).Include(d => d.WordSubClass);
return View(dictionaryTocharians.OrderBy(x => x.EquivalentTB).ToPagedList(page, pageSize));
}
public ActionResult SearchParallel(string search)
{
IEnumerable<DictionaryTocharian> dictionaryTocharians = db.DictionaryTocharians.Include("WordClass").Include("WordSubClass").Include("TochLanguage").Where(x => x.Word.Contains(search)
|| (x.EquivalentTA != null && x.EquivalentTA.Contains(search))
|| (x.EquivalentTB != null && x.EquivalentTB.Contains(search))
|| (x.EquivalentTB != null && x.TochCommon.Contains(search))
|| (x.EquivalentTB != null && x.TochCorrespondence.Contains(search))
|| (x.Sanskrit != null && x.Sanskrit.Contains(search))
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.German != null && x.German.Contains(search))
|| (x.Latin != null && x.Latin.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search))); ;
if (dictionaryTocharians.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View("SearchParallel", dictionaryTocharians.ToList());
}
/*
public ActionResult AddEquivalentDictionary(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
NounAdjective nounAdjective = db.NounAdjectives.Include(n => n.DictionaryTocharian.TochLanguage).Include(n => n.DictionaryTocharian.WordClass).Include(n => n.DictionaryTocharian.WordSubClass).Include("Cases").Include("Genders").SingleOrDefault(y => y.Id == id);
NounAdjective equivalent = new NounAdjective();
if (nounAdjective.DictionaryTocharian.TochLanguageId == 1 && nounAdjective.DictionaryTocharian.EquivalentTB != null)
{
IEnumerable<NounAdjective> equivalentTB = db.NounAdjectives.Include(n => n.DictionaryTocharian.TochLanguage).Include(n => n.DictionaryTocharian.WordClass).Include(n => n.DictionaryTocharian.WordSubClass).Include("Cases").Include("Numbers").Include("Genders").Where(y => y.DictionaryTocharian.Word == nounAdjective.DictionaryTocharian.EquivalentTB);
if (equivalentTB.Count() == 0)
{
equivalent.TochWord = nounAdjective.EquivalentTB;
equivalent.EquivalentTA = nounAdjective.TochWord;
equivalent.EquivalentTB = nounAdjective.EquivalentTB;
equivalent.TochLanguageId = 2;
equivalent.Sanskrit = nounAdjective.Sanskrit;
equivalent.English = nounAdjective.English;
equivalent.Francaise = nounAdjective.Francaise;
equivalent.German = nounAdjective.German;
equivalent.Latin = nounAdjective.Latin;
equivalent.Chinese = nounAdjective.Chinese;
equivalent.Visible = true;
equivalent.TochCommon = nounAdjective.TochCommon;
equivalent.TochCorrespondence = nounAdjective.TochCorrespondence;
equivalent.EquivalentInOther = nounAdjective.EquivalentInOther;
equivalent.WordClassId = nounAdjective.WordClassId;
equivalent.WordSubClassId = nounAdjective.WordSubClassId;
db.NounAdjectives.Add(equivalent);
}
else
{
Display("Mots existé");
}
}
if (nounAdjective.TochLanguageId == 2 && nounAdjective.EquivalentTA != null)
{
IEnumerable<NounAdjective> equivalentTA = db.NounAdjectives.Include(n => n.TochLanguage).Include(n => n.WordClass).Include(n => n.WordSubClass).Include("Cases").Include("Numbers").Include("Genders").Where(y => y.TochWord == nounAdjective.EquivalentTA);
if (equivalentTA.Count() == 0)
{
equivalent.TochWord = nounAdjective.EquivalentTA;
equivalent.EquivalentTB = nounAdjective.TochWord;
equivalent.EquivalentTA = nounAdjective.EquivalentTA;
equivalent.TochLanguageId = 1;
equivalent.Sanskrit = nounAdjective.Sanskrit;
equivalent.English = nounAdjective.English;
equivalent.Francaise = nounAdjective.Francaise;
equivalent.German = nounAdjective.German;
equivalent.Latin = nounAdjective.Latin;
equivalent.Chinese = nounAdjective.Chinese;
equivalent.Visible = true;
equivalent.TochCommon = nounAdjective.TochCommon;
equivalent.TochCorrespondence = nounAdjective.TochCorrespondence;
equivalent.EquivalentInOther = nounAdjective.EquivalentInOther;
equivalent.WordClassId = nounAdjective.WordClassId;
equivalent.WordSubClassId = nounAdjective.WordSubClassId;
db.NounAdjectives.Add(equivalent);
}
else
{
Display("Mots existé");
}
}
db.SaveChanges();
return RedirectToAction("index");
}
return View();*/
}
}
<file_sep>/Horizone/Migrations/201912180824559_changeOtherWord.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class changeOtherWord : DbMigration
{
public override void Up()
{
RenameTable(name: "dbo.NounAdjectiveCases", newName: "CaseNounAdjectives");
RenameTable(name: "dbo.NumberNounAdjectives", newName: "NounAdjectiveNumbers");
RenameTable(name: "dbo.PronounGenders", newName: "GenderPronouns");
RenameTable(name: "dbo.NumberPronouns", newName: "PronounNumbers");
RenameTable(name: "dbo.PersonVerbs", newName: "VerbPersons");
DropForeignKey("dbo.DictionaryTocharians", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.Bibliographies", "OtherWord_Id", "dbo.OtherWords");
DropForeignKey("dbo.OtherWordNumbers", "OtherWord_Id", "dbo.OtherWords");
DropForeignKey("dbo.OtherWordNumbers", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.OtherWords", "TochLanguageId", "dbo.TochLanguages");
DropForeignKey("dbo.OtherWords", "WordClassId", "dbo.WordClasses");
DropForeignKey("dbo.OtherWords", "WordSubClassId", "dbo.WordSubClasses");
DropIndex("dbo.Bibliographies", new[] { "OtherWord_Id" });
DropIndex("dbo.DictionaryTocharians", new[] { "Number_Id" });
DropIndex("dbo.OtherWords", new[] { "TochLanguageId" });
DropIndex("dbo.OtherWords", new[] { "WordClassId" });
DropIndex("dbo.OtherWords", new[] { "WordSubClassId" });
DropIndex("dbo.OtherWordNumbers", new[] { "OtherWord_Id" });
DropIndex("dbo.OtherWordNumbers", new[] { "Number_Id" });
DropPrimaryKey("dbo.CaseNounAdjectives");
DropPrimaryKey("dbo.NounAdjectiveNumbers");
DropPrimaryKey("dbo.GenderPronouns");
DropPrimaryKey("dbo.PronounNumbers");
DropPrimaryKey("dbo.VerbPersons");
CreateTable(
"dbo.NumberDictionaryTocharians",
c => new
{
Number_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Number_Id, t.DictionaryTocharian_Id })
.ForeignKey("dbo.Numbers", t => t.Number_Id, cascadeDelete: false)
.ForeignKey("dbo.DictionaryTocharians", t => t.DictionaryTocharian_Id, cascadeDelete: false)
.Index(t => t.Number_Id)
.Index(t => t.DictionaryTocharian_Id);
AddColumn("dbo.DictionaryTocharians", "DerivedFrom", c => c.String());
AddColumn("dbo.DictionaryTocharians", "RelatedLexemes", c => c.String());
AddColumn("dbo.DictionaryTocharians", "RootCharacter", c => c.String());
AddColumn("dbo.DictionaryTocharians", "InternalRootVowel", c => c.String());
AddColumn("dbo.DictionaryTocharians", "Stem", c => c.String());
AddColumn("dbo.DictionaryTocharians", "StemClass", c => c.String());
AddColumn("dbo.OtherWords", "DictionaryId", c => c.Int(nullable: false));
AddColumn("dbo.OtherWords", "Number_Id", c => c.Int());
AddPrimaryKey("dbo.CaseNounAdjectives", new[] { "Case_Id", "NounAdjective_Id" });
AddPrimaryKey("dbo.NounAdjectiveNumbers", new[] { "NounAdjective_Id", "Number_Id" });
AddPrimaryKey("dbo.GenderPronouns", new[] { "Gender_Id", "Pronoun_Id" });
AddPrimaryKey("dbo.PronounNumbers", new[] { "Pronoun_Id", "Number_Id" });
AddPrimaryKey("dbo.VerbPersons", new[] { "Verb_Id", "Person_Id" });
CreateIndex("dbo.OtherWords", "DictionaryId");
CreateIndex("dbo.OtherWords", "Number_Id");
AddForeignKey("dbo.OtherWords", "DictionaryId", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.OtherWords", "Number_Id", "dbo.Numbers", "Id");
DropColumn("dbo.Bibliographies", "OtherWord_Id");
DropColumn("dbo.DictionaryTocharians", "IdClassSource");
DropColumn("dbo.DictionaryTocharians", "Number_Id");
DropColumn("dbo.OtherWords", "TochWord");
DropColumn("dbo.OtherWords", "Sanskrit");
DropColumn("dbo.OtherWords", "English");
DropColumn("dbo.OtherWords", "Francaise");
DropColumn("dbo.OtherWords", "German");
DropColumn("dbo.OtherWords", "Latin");
DropColumn("dbo.OtherWords", "Chinese");
DropColumn("dbo.OtherWords", "TochLanguageId");
DropColumn("dbo.OtherWords", "WordClassId");
DropColumn("dbo.OtherWords", "WordSubClassId");
DropColumn("dbo.OtherWords", "EquivalentTA");
DropColumn("dbo.OtherWords", "EquivalentTB");
DropColumn("dbo.OtherWords", "TochCommon");
DropColumn("dbo.OtherWords", "TochCorrespondence");
DropColumn("dbo.OtherWords", "EquivalentInOther");
DropColumn("dbo.OtherWords", "DerivedFrom");
DropColumn("dbo.OtherWords", "RelatedLexemes");
DropColumn("dbo.OtherWords", "RootCharacter");
DropColumn("dbo.OtherWords", "InternalRootVowel");
DropColumn("dbo.OtherWords", "Stem");
DropColumn("dbo.OtherWords", "StemClass");
DropColumn("dbo.OtherWords", "Visible");
DropTable("dbo.OtherWordNumbers");
}
public override void Down()
{
CreateTable(
"dbo.OtherWordNumbers",
c => new
{
OtherWord_Id = c.Int(nullable: false),
Number_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.OtherWord_Id, t.Number_Id });
AddColumn("dbo.OtherWords", "Visible", c => c.Boolean(nullable: false));
AddColumn("dbo.OtherWords", "StemClass", c => c.String());
AddColumn("dbo.OtherWords", "Stem", c => c.String());
AddColumn("dbo.OtherWords", "InternalRootVowel", c => c.String());
AddColumn("dbo.OtherWords", "RootCharacter", c => c.String());
AddColumn("dbo.OtherWords", "RelatedLexemes", c => c.String());
AddColumn("dbo.OtherWords", "DerivedFrom", c => c.String());
AddColumn("dbo.OtherWords", "EquivalentInOther", c => c.String());
AddColumn("dbo.OtherWords", "TochCorrespondence", c => c.String());
AddColumn("dbo.OtherWords", "TochCommon", c => c.String());
AddColumn("dbo.OtherWords", "EquivalentTB", c => c.String());
AddColumn("dbo.OtherWords", "EquivalentTA", c => c.String());
AddColumn("dbo.OtherWords", "WordSubClassId", c => c.Int(nullable: false));
AddColumn("dbo.OtherWords", "WordClassId", c => c.Int(nullable: false));
AddColumn("dbo.OtherWords", "TochLanguageId", c => c.Int(nullable: false));
AddColumn("dbo.OtherWords", "Chinese", c => c.String());
AddColumn("dbo.OtherWords", "Latin", c => c.String());
AddColumn("dbo.OtherWords", "German", c => c.String());
AddColumn("dbo.OtherWords", "Francaise", c => c.String());
AddColumn("dbo.OtherWords", "English", c => c.String());
AddColumn("dbo.OtherWords", "Sanskrit", c => c.String());
AddColumn("dbo.OtherWords", "TochWord", c => c.String(nullable: false));
AddColumn("dbo.DictionaryTocharians", "Number_Id", c => c.Int());
AddColumn("dbo.DictionaryTocharians", "IdClassSource", c => c.Int(nullable: false));
AddColumn("dbo.Bibliographies", "OtherWord_Id", c => c.Int());
DropForeignKey("dbo.OtherWords", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.OtherWords", "DictionaryId", "dbo.DictionaryTocharians");
DropForeignKey("dbo.NumberDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.NumberDictionaryTocharians", "Number_Id", "dbo.Numbers");
DropIndex("dbo.NumberDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.NumberDictionaryTocharians", new[] { "Number_Id" });
DropIndex("dbo.OtherWords", new[] { "Number_Id" });
DropIndex("dbo.OtherWords", new[] { "DictionaryId" });
DropPrimaryKey("dbo.VerbPersons");
DropPrimaryKey("dbo.PronounNumbers");
DropPrimaryKey("dbo.GenderPronouns");
DropPrimaryKey("dbo.NounAdjectiveNumbers");
DropPrimaryKey("dbo.CaseNounAdjectives");
DropColumn("dbo.OtherWords", "Number_Id");
DropColumn("dbo.OtherWords", "DictionaryId");
DropColumn("dbo.DictionaryTocharians", "StemClass");
DropColumn("dbo.DictionaryTocharians", "Stem");
DropColumn("dbo.DictionaryTocharians", "InternalRootVowel");
DropColumn("dbo.DictionaryTocharians", "RootCharacter");
DropColumn("dbo.DictionaryTocharians", "RelatedLexemes");
DropColumn("dbo.DictionaryTocharians", "DerivedFrom");
DropTable("dbo.NumberDictionaryTocharians");
AddPrimaryKey("dbo.VerbPersons", new[] { "Person_Id", "Verb_Id" });
AddPrimaryKey("dbo.PronounNumbers", new[] { "Number_Id", "Pronoun_Id" });
AddPrimaryKey("dbo.GenderPronouns", new[] { "Pronoun_Id", "Gender_Id" });
AddPrimaryKey("dbo.NounAdjectiveNumbers", new[] { "Number_Id", "NounAdjective_Id" });
AddPrimaryKey("dbo.CaseNounAdjectives", new[] { "NounAdjective_Id", "Case_Id" });
CreateIndex("dbo.OtherWordNumbers", "Number_Id");
CreateIndex("dbo.OtherWordNumbers", "OtherWord_Id");
CreateIndex("dbo.OtherWords", "WordSubClassId");
CreateIndex("dbo.OtherWords", "WordClassId");
CreateIndex("dbo.OtherWords", "TochLanguageId");
CreateIndex("dbo.DictionaryTocharians", "Number_Id");
CreateIndex("dbo.Bibliographies", "OtherWord_Id");
AddForeignKey("dbo.OtherWords", "WordSubClassId", "dbo.WordSubClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.OtherWords", "WordClassId", "dbo.WordClasses", "Id", cascadeDelete: false);
AddForeignKey("dbo.OtherWords", "TochLanguageId", "dbo.TochLanguages", "Id", cascadeDelete: false);
AddForeignKey("dbo.OtherWordNumbers", "Number_Id", "dbo.Numbers", "Id", cascadeDelete: true);
AddForeignKey("dbo.OtherWordNumbers", "OtherWord_Id", "dbo.OtherWords", "Id", cascadeDelete: true);
AddForeignKey("dbo.Bibliographies", "OtherWord_Id", "dbo.OtherWords", "Id");
AddForeignKey("dbo.DictionaryTocharians", "Number_Id", "dbo.Numbers", "Id");
RenameTable(name: "dbo.VerbPersons", newName: "PersonVerbs");
RenameTable(name: "dbo.PronounNumbers", newName: "NumberPronouns");
RenameTable(name: "dbo.GenderPronouns", newName: "PronounGenders");
RenameTable(name: "dbo.NounAdjectiveNumbers", newName: "NumberNounAdjectives");
RenameTable(name: "dbo.CaseNounAdjectives", newName: "NounAdjectiveCases");
}
}
}
<file_sep>/Horizone/Models/WordClass .cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class WordClass
{
public int Id { get; set; }
[Display(Name = "WordClass", ResourceType = typeof(StaticResource.Resources))]
public string Class { get; set; }
[Display(Name = "WordClassEn", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string ClassEn { get; set; }
[Display(Name = "WordClassFr", ResourceType = typeof(StaticResource.Resources))]
public string ClassFr { get; set; }
[Display(Name = "WordClassZh", ResourceType = typeof(StaticResource.Resources))]
public string ClassZh { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/TochPhrasesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class TochPhrasesController : BaseController
{
// GET: BackOffice/TochPhrases
public ActionResult Index()
{
var tochPhrases = db.TochPhrases.Include(t => t.TochLanguage);
return View(tochPhrases.ToList());
}
// GET: BackOffice/TochPhrases/Create
public ActionResult Create()
{
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language");
return View();
}
// POST: BackOffice/TochPhrases/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Phrase,English,Francaise,Chinese,TochLanguageId,DerivedFrom,RelatedLexemes,Description,Visible")] TochPhrase tochPhrase)
{
if (ModelState.IsValid)
{
db.TochPhrases.Add(tochPhrase);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", tochPhrase.TochLanguageId);
return View(tochPhrase);
}
// GET: BackOffice/TochPhrases/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochPhrase tochPhrase = db.TochPhrases.Find(id);
if (tochPhrase == null)
{
return HttpNotFound();
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", tochPhrase.TochLanguageId);
return View(tochPhrase);
}
// POST: BackOffice/TochPhrases/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Phrase,English,Francaise,Chinese,TochLanguageId,DerivedFrom,RelatedLexemes,Description,Visible")] TochPhrase tochPhrase)
{
if (ModelState.IsValid)
{
db.Entry(tochPhrase).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TochLanguageId = new SelectList(db.TochLanguages, "Id", "Language", tochPhrase.TochLanguageId);
return View(tochPhrase);
}
// GET: BackOffice/TochPhrases/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
TochPhrase tochPhrase = db.TochPhrases.Find(id);
if (tochPhrase == null)
{
return HttpNotFound();
}
return View(tochPhrase);
}
// POST: BackOffice/TochPhrases/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
TochPhrase tochPhrase = db.TochPhrases.Find(id);
db.TochPhrases.Remove(tochPhrase);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchPhrase(string search)
{
IEnumerable<TochPhrase> tochPhrases = db.TochPhrases;
if (!string.IsNullOrWhiteSpace(search))
{
tochPhrases = db.TochPhrases.Include("TochLanguage").Where(x => x.Phrase.Contains(search)
|| (x.English != null && x.English.Contains(search))
|| (x.Francaise != null && x.Francaise.Contains(search))
|| (x.Chinese != null && x.Chinese.Contains(search)));
}
if (tochPhrases.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
return View(tochPhrases.ToList());
}
}
}
<file_sep>/Horizone/Models/Manuscript.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Manuscript
{
public int Id { get; set; }
[Display(Name = "Catalogue", ResourceType = typeof(StaticResource.Resources))]
public int CatalogieId { get; set; }
[ForeignKey("CatalogieId")]
public Catalogie Catalogie { get; set; }
[Display(Name = "Index")]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Index { get; set; }
//OverallDescription
[Display(Name = "Collection", ResourceType = typeof(StaticResource.Resources))]
public string Collection { get; set; }
[Display(Name = "Siglum", ResourceType = typeof(StaticResource.Resources))]
public string Siglum { get; set; }
[Display(Name = "Joint", ResourceType = typeof(StaticResource.Resources))]
public string Joint { get; set; }
[Display(Name = "OtherSiglum", ResourceType = typeof(StaticResource.Resources))]
public string OtherSiglum { get; set; }
[Display(Name = "ExpeditionCode", ResourceType = typeof(StaticResource.Resources))]
public string ExpeditionCode { get; set; }
[Display(Name = "MainFindSpot", ResourceType = typeof(StaticResource.Resources))]
public int MapId { get; set; }
[ForeignKey("MapId")]
public Map Map { get; set; }
[Display(Name = "SpecificFindSpot", ResourceType = typeof(StaticResource.Resources))]
public string SpecificFindSpot { get; set; }
[Display(Name = "GeneralState", ResourceType = typeof(StaticResource.Resources))]
public int StateId { get; set; }
[ForeignKey("StateId")]
public State State { get; set; }
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public int DescriptionManuscriptId { get; set; }
[ForeignKey("DescriptionManuscriptId")]
public DescriptionManuscript DescriptionManuscript{ get; set; }
[Display(Name = "Remark", ResourceType = typeof(StaticResource.Resources))]
public int RemarkAddId { get; set; }
[ForeignKey("RemarkAddId")]
public RemarkAdd RemarkAdd { get; set; }
[Display(Name = "LeafNumber", ResourceType = typeof(StaticResource.Resources))]
public string LeafNumber { get; set; }
//LayoutManuscript
[Display(Name = "SizeHeight", ResourceType = typeof(StaticResource.Resources))]
public string SizeHeight { get; set; }
[Display(Name = "Completeness", ResourceType = typeof(StaticResource.Resources))]
public string Completeness { get; set; }
[Display(Name = "SizeWidth", ResourceType = typeof(StaticResource.Resources))]
public string SizeWidth { get; set; }
[Display(Name = "NumberOfLine", ResourceType = typeof(StaticResource.Resources))]
public int NumberOfLine { get; set; }
[Display(Name = "LineDistance", ResourceType = typeof(StaticResource.Resources))]
public string LineDistance { get; set; }
[Display(Name = "Format", ResourceType = typeof(StaticResource.Resources))]
public int FormatId { get; set; }
[ForeignKey("FormatId")]
public Format Format { get; set; }
[Display(Name = "Ruling", ResourceType = typeof(StaticResource.Resources))]
public int RulingId { get; set; }
[ForeignKey("RulingId")]
public Ruling Ruling { get; set; }
[Display(Name = "RulingColor", ResourceType = typeof(StaticResource.Resources))]
public int RulingColorId { get; set; }
[ForeignKey("RulingColorId")]
public RulingColor RulingColor { get; set; }
[Display(Name = "RulingDetail", ResourceType = typeof(StaticResource.Resources))]
public int RulingDetailId { get; set; }
[ForeignKey("RulingDetailId")]
public RulingDetail RulingDetail { get; set; }
[Display(Name = "StringholeHeight", ResourceType = typeof(StaticResource.Resources))]
public string StringholeHeight { get; set; }
[Display(Name = "StringholeWidth", ResourceType = typeof(StaticResource.Resources))]
public string StringholeWidth { get; set; }
[Display(Name = "DistanceStringholeRight", ResourceType = typeof(StaticResource.Resources))]
public string DistanceStringholeRight { get; set; }
[Display(Name = "DistanceStringholeLeft", ResourceType = typeof(StaticResource.Resources))]
public string DistanceStringholeLeft { get; set; }
[Display(Name = "InterruptedLine", ResourceType = typeof(StaticResource.Resources))]
public string InterruptedLine { get; set; }
//Linguistique
[AllowHtml]
[Display(Name = "Transliteration", ResourceType = typeof(StaticResource.Resources))]
public string Transliteration { get; set; }
[AllowHtml]
[Display(Name = "Transcription", ResourceType = typeof(StaticResource.Resources))]
public string Transcription { get; set; }
[AllowHtml]
[Display(Name = "English", ResourceType = typeof(StaticResource.Resources))]
public string English { get; set; }
[AllowHtml]
[Display(Name = "French", ResourceType = typeof(StaticResource.Resources))]
public string Francaise { get; set; }
[AllowHtml]
[Display(Name = "Chinese", ResourceType = typeof(StaticResource.Resources))]
public string Chinese { get; set; }
[Display(Name = "Editor", ResourceType = typeof(StaticResource.Resources))]
public string Editor { get; set; }
[AllowHtml]
[Display(Name = "References", ResourceType = typeof(StaticResource.Resources))]
public string References { get; set; }
[AllowHtml]
[Display(Name = "PhilologicalCommentary", ResourceType = typeof(StaticResource.Resources))]
public string PhilologicalCommentary { get; set; }
//Material
[Display(Name = "Material", ResourceType = typeof(StaticResource.Resources))]
public int MaterialId { get; set; }
[ForeignKey("MaterialId")]
public Material Material { get; set; }
[Display(Name = "PaperColor", ResourceType = typeof(StaticResource.Resources))]
public int PaperColorId { get; set; }
[ForeignKey("PaperColorId")]
public PaperColor PaperColor { get; set; }
[Display(Name = "PaperThickness", ResourceType = typeof(StaticResource.Resources))]
public string PaperThickness { get; set; }
[Display(Name = "WritingTool", ResourceType = typeof(StaticResource.Resources))]
public int WritingToolId { get; set; }
[ForeignKey("WritingToolId")]
public WritingTool WritingTool { get; set; }
//Script
[Display(Name = "AlignmentType", ResourceType = typeof(StaticResource.Resources))]
public int AlignmentTypeId { get; set; }
[ForeignKey("AlignmentTypeId")]
public AlignmentType AlignmentType { get; set; }
[Display(Name = "ModuleWidth", ResourceType = typeof(StaticResource.Resources))]
public string ModuleWidth { get; set; }
[Display(Name = "ModuleHeight", ResourceType = typeof(StaticResource.Resources))]
public string ModuleHeight { get; set; }
[Display(Name = "AvCharPerLigne", ResourceType = typeof(StaticResource.Resources))]
public string AvCharPerLigne { get; set; }
[Display(Name = "NibThickness", ResourceType = typeof(StaticResource.Resources))]
public string NibThickness { get; set; }
[Display(Name = "Script", ResourceType = typeof(StaticResource.Resources))]
public int ScriptId { get; set; }
[ForeignKey("ScriptId")]
public Script Script { get; set; }
[Display(Name = "ScriptAdd", ResourceType = typeof(StaticResource.Resources))]
public int ScriptAddId { get; set; }
[ForeignKey("ScriptAddId")]
public ScriptAdd ScriptAdd { get; set; }
//Text language
[Display(Name = "TochLanguage", ResourceType = typeof(StaticResource.Resources))]
public int TochLanguageId { get; set; }
[ForeignKey("TochLanguageId")]
public TochLanguage TochLanguage { get; set; }
[Display(Name = "LanguageStage", ResourceType = typeof(StaticResource.Resources))]
public int LanguageStageId { get; set; }
[ForeignKey("LanguageStageId")]
public LanguageStage LanguageStage { get; set; }
[Display(Name = "LanguageAdd", ResourceType = typeof(StaticResource.Resources))]
public int LanguageDetailId { get; set; }
[ForeignKey("LanguageDetailId")]
public LanguageDetail LanguageDetail { get; set; }
//Text Content
[Display(Name = "TextGenre", ResourceType = typeof(StaticResource.Resources))]
public int GenderManuscriptId { get; set; }
[ForeignKey("GenderManuscriptId")]
public GenderManuscript GenderManuscript { get; set; }
[Display(Name = "TextSubgenre", ResourceType = typeof(StaticResource.Resources))]
public int SubGenderManuscriptId { get; set; }
[ForeignKey("SubGenderManuscriptId")]
public SubGenderManuscript SubGenderManuscript { get; set; }
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[Display(Name = "Passage", ResourceType = typeof(StaticResource.Resources))]
public string Passage { get; set; }
[Display(Name = "Parallel", ResourceType = typeof(StaticResource.Resources))]
public string Parallel { get; set; }
[Display(Name = "MetricForm", ResourceType = typeof(StaticResource.Resources))]
public int MetricId { get; set; }
[ForeignKey("MetricId")]
public Metric Metric { get; set; }
[Display(Name = "Tune", ResourceType = typeof(StaticResource.Resources))]
public string Tune { get; set; }
public ICollection<ImageManuscript> ImageManuscripts { get; set; }
[AllowHtml]
[Display(Name = "CEToM")]
public string Cetom { get; set; }
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Bibliography> Bibliographys { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
}
}<file_sep>/Horizone/Models/Ruling.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Ruling
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "RulingEn", ResourceType = typeof(StaticResource.Resources))]
public string RulingEn { get; set; }
[AllowHtml]
[Display(Name = "RulingFr", ResourceType = typeof(StaticResource.Resources))]
public string RulingFr { get; set; }
[AllowHtml]
[Display(Name = "RulingZh", ResourceType = typeof(StaticResource.Resources))]
public string RulingZh { get; set; }
}
}<file_sep>/Horizone/Models/TenseAndAspect.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class TenseAndAspect
{
public int Id { get; set; }
[Display(Name = "Abbreviations", ResourceType = typeof(StaticResource.Resources))]
public string Tense { get; set; }
[Display(Name = "Tense", ResourceType = typeof(StaticResource.Resources))]
public string TenseEn { get; set; }
[Display(Name = "Tense", ResourceType = typeof(StaticResource.Resources))]
public string TenseFr { get; set; }
[Display(Name = "Tense", ResourceType = typeof(StaticResource.Resources))]
public string TenseZh { get; set; }
}
}<file_sep>/Horizone/Models/SubGenderManuscript.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class SubGenderManuscript
{
public int Id { get; set; }
[Display(Name = "SubGenderEn", ResourceType = typeof(StaticResource.Resources))]
public string SubGenderEn { get; set; }
[Display(Name = "SubGenderFr", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderFr { get; set; }
[Display(Name = "SubGenderZh", ResourceType = typeof(StaticResource.Resources))]
public string NameGenderZh { get; set; }
}
}<file_sep>/Horizone/Models/Client.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Client : Personne
{
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(500, MinimumLength = 1, ErrorMessageResourceName = "MinLength", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }
[Display(Name = "Email", ResourceType = typeof(StaticResource.Resources))]
[NotMapped]
public string EmailDisplay { get; set; }
}
}<file_sep>/Horizone/Models/Verb.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Verb
{
public int Id { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public int DictionaryId { get; set; }
[ForeignKey("DictionaryId")]
public DictionaryTocharian DictionaryTocharian { get; set; }
[Display(Name = "Person", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Person> Persons { get; set; }
[Display(Name = "Voice", ResourceType = typeof(StaticResource.Resources))]
public int VoiceId { get; set; }
[ForeignKey("VoiceId")]
public Voice Voice { get; set; }
[Display(Name = "Valency", ResourceType = typeof(StaticResource.Resources))]
public int ValencyId { get; set; }
[ForeignKey("ValencyId")]
public Valency Valency { get; set; }
[Display(Name = "TenseAndAspect", ResourceType = typeof(StaticResource.Resources))]
public int TenseAndAspectId { get; set; }
[ForeignKey("TenseAndAspectId")]
public TenseAndAspect TenseAndAspect { get; set; }
[Display(Name = "Mood", ResourceType = typeof(StaticResource.Resources))]
public int MoodId { get; set; }
[ForeignKey("MoodId")]
public Mood Mood { get; set; }
[AllowHtml]
[Display(Name = "PronounSuffix", ResourceType = typeof(StaticResource.Resources))]
public string PronounSuffix { get; set; }
}
}<file_sep>/Horizone/Models/Restore.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Restore
{
public int Id { get; set; }
[Display(Name = "Restore", ResourceType = typeof(StaticResource.Resources))]
public string RestoreEn { get; set; }
[Display(Name = "Restore", ResourceType = typeof(StaticResource.Resources))]
public string RestoreFr { get; set; }
[Display(Name = "Restore", ResourceType = typeof(StaticResource.Resources))]
public string RestoreZh { get; set; }
}
}<file_sep>/Horizone/Models/ThemeStory.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.AccessControl;
using System.Web;
namespace Horizone.Models
{
public class ThemeStory
{
public int Id { get; set; }
[Display(Name = "ThemeStoryEn", ResourceType = typeof(StaticResource.Resources))]
public string ThemeEn { get; set; }
[Display(Name = "ThemeStoryFr", ResourceType = typeof(StaticResource.Resources))]
public string ThemeFr { get; set; }
[Display(Name = "ThemeStoryZh", ResourceType = typeof(StaticResource.Resources))]
public string ThemeZn { get; set; }
}
}<file_sep>/Horizone/Models/Activity.cs
using Horizone.Validators;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Activity
{
public int Id { get; set; }
[Display(Name = "DateActivity", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string DateofActivity { get; set; }
[AllowHtml]
[Display(Name = "Place", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Place { get; set; }
[Display(Name = "NameActivity", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string NameActivity { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
public string UlrActivity { get;set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public string Picture { get; set; }
[Display(Name = "Topic", ResourceType = typeof(StaticResource.Resources))]
public int TopicId { get; set; }
[ForeignKey("TopicId")]
public Topic Topic { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
}
}<file_sep>/Horizone/Models/RemarkAdd.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class RemarkAdd
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "RemarkEn", ResourceType = typeof(StaticResource.Resources))]
public string RemarkEn { get; set; }
[AllowHtml]
[Display(Name = "RemarkFr", ResourceType = typeof(StaticResource.Resources))]
public string RemarkFr { get; set; }
[AllowHtml]
[Display(Name = "RemarkZh", ResourceType = typeof(StaticResource.Resources))]
public string RemarkZh { get; set; }
}
}<file_sep>/Horizone/Migrations/201912022031279_somechange.cs
namespace Horizone.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class somechange : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.CaseDictionaryTocharians", "Case_Id", "dbo.Cases");
DropForeignKey("dbo.CaseDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.GenderDictionaryTocharians", "Gender_Id", "dbo.Genders");
DropForeignKey("dbo.GenderDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.NumberDictionaryTocharians", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.NumberDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.PersonDictionaryTocharians", "Person_Id", "dbo.People");
DropForeignKey("dbo.PersonDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians");
DropForeignKey("dbo.DictionaryTocharians", "MoodId", "dbo.Moods");
DropForeignKey("dbo.DictionaryTocharians", "TenseAndAspectId", "dbo.TenseAndAspects");
DropForeignKey("dbo.DictionaryTocharians", "ValencyId", "dbo.Valencies");
DropForeignKey("dbo.DictionaryTocharians", "VoiceId", "dbo.Voices");
DropForeignKey("dbo.Comments", "UserId", "dbo.Users");
DropIndex("dbo.DictionaryTocharians", new[] { "VoiceId" });
DropIndex("dbo.DictionaryTocharians", new[] { "ValencyId" });
DropIndex("dbo.DictionaryTocharians", new[] { "TenseAndAspectId" });
DropIndex("dbo.DictionaryTocharians", new[] { "MoodId" });
DropIndex("dbo.Comments", new[] { "UserId" });
DropIndex("dbo.CaseDictionaryTocharians", new[] { "Case_Id" });
DropIndex("dbo.CaseDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.GenderDictionaryTocharians", new[] { "Gender_Id" });
DropIndex("dbo.GenderDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.NumberDictionaryTocharians", new[] { "Number_Id" });
DropIndex("dbo.NumberDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
DropIndex("dbo.PersonDictionaryTocharians", new[] { "Person_Id" });
DropIndex("dbo.PersonDictionaryTocharians", new[] { "DictionaryTocharian_Id" });
CreateTable(
"dbo.SearchResults",
c => new
{
Id = c.Int(nullable: false, identity: true),
NameTable = c.String(),
IdResult = c.Int(nullable: false),
Summary = c.String(),
})
.PrimaryKey(t => t.Id);
AddColumn("dbo.DictionaryTocharians", "IdClassSource", c => c.Int(nullable: false));
AddColumn("dbo.DictionaryTocharians", "Case_Id", c => c.Int());
AddColumn("dbo.DictionaryTocharians", "Gender_Id", c => c.Int());
AddColumn("dbo.DictionaryTocharians", "Number_Id", c => c.Int());
AddColumn("dbo.DictionaryTocharians", "Person_Id", c => c.Int());
AddColumn("dbo.Comments", "Date", c => c.DateTime(nullable: false));
AddColumn("dbo.Comments", "ClientId", c => c.Int(nullable: false));
AddColumn("dbo.NamePlaces", "InStory", c => c.Boolean(nullable: false));
AddColumn("dbo.ProperNouns", "DescriptionEn", c => c.String());
AddColumn("dbo.ProperNouns", "DescriptionFr", c => c.String());
AddColumn("dbo.ProperNouns", "DescriptionZh", c => c.String());
AddColumn("dbo.ProperNouns", "InStory", c => c.Boolean(nullable: false));
CreateIndex("dbo.DictionaryTocharians", "Case_Id");
CreateIndex("dbo.DictionaryTocharians", "Gender_Id");
CreateIndex("dbo.DictionaryTocharians", "Number_Id");
CreateIndex("dbo.DictionaryTocharians", "Person_Id");
CreateIndex("dbo.Comments", "ClientId");
AddForeignKey("dbo.DictionaryTocharians", "Case_Id", "dbo.Cases", "Id");
AddForeignKey("dbo.DictionaryTocharians", "Gender_Id", "dbo.Genders", "Id");
AddForeignKey("dbo.DictionaryTocharians", "Number_Id", "dbo.Numbers", "Id");
AddForeignKey("dbo.DictionaryTocharians", "Person_Id", "dbo.People", "Id");
AddForeignKey("dbo.Comments", "ClientId", "dbo.Clients", "Id", cascadeDelete: false);
DropColumn("dbo.DictionaryTocharians", "DerivedFrom");
DropColumn("dbo.DictionaryTocharians", "RelatedLexemes");
DropColumn("dbo.DictionaryTocharians", "RootCharacter");
DropColumn("dbo.DictionaryTocharians", "InternalRootVowel");
DropColumn("dbo.DictionaryTocharians", "Stem");
DropColumn("dbo.DictionaryTocharians", "StemClass");
DropColumn("dbo.DictionaryTocharians", "VoiceId");
DropColumn("dbo.DictionaryTocharians", "ValencyId");
DropColumn("dbo.DictionaryTocharians", "TenseAndAspectId");
DropColumn("dbo.DictionaryTocharians", "MoodId");
DropColumn("dbo.DictionaryTocharians", "PronounSuffix");
DropColumn("dbo.Comments", "UserId");
DropTable("dbo.CaseDictionaryTocharians");
DropTable("dbo.GenderDictionaryTocharians");
DropTable("dbo.NumberDictionaryTocharians");
DropTable("dbo.PersonDictionaryTocharians");
}
public override void Down()
{
CreateTable(
"dbo.PersonDictionaryTocharians",
c => new
{
Person_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Person_Id, t.DictionaryTocharian_Id });
CreateTable(
"dbo.NumberDictionaryTocharians",
c => new
{
Number_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Number_Id, t.DictionaryTocharian_Id });
CreateTable(
"dbo.GenderDictionaryTocharians",
c => new
{
Gender_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Gender_Id, t.DictionaryTocharian_Id });
CreateTable(
"dbo.CaseDictionaryTocharians",
c => new
{
Case_Id = c.Int(nullable: false),
DictionaryTocharian_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Case_Id, t.DictionaryTocharian_Id });
AddColumn("dbo.Comments", "UserId", c => c.String(maxLength: 128));
AddColumn("dbo.DictionaryTocharians", "PronounSuffix", c => c.String());
AddColumn("dbo.DictionaryTocharians", "MoodId", c => c.Int(nullable: false));
AddColumn("dbo.DictionaryTocharians", "TenseAndAspectId", c => c.Int(nullable: false));
AddColumn("dbo.DictionaryTocharians", "ValencyId", c => c.Int(nullable: false));
AddColumn("dbo.DictionaryTocharians", "VoiceId", c => c.Int(nullable: false));
AddColumn("dbo.DictionaryTocharians", "StemClass", c => c.String());
AddColumn("dbo.DictionaryTocharians", "Stem", c => c.String());
AddColumn("dbo.DictionaryTocharians", "InternalRootVowel", c => c.String());
AddColumn("dbo.DictionaryTocharians", "RootCharacter", c => c.String());
AddColumn("dbo.DictionaryTocharians", "RelatedLexemes", c => c.String());
AddColumn("dbo.DictionaryTocharians", "DerivedFrom", c => c.String());
DropForeignKey("dbo.Comments", "ClientId", "dbo.Clients");
DropForeignKey("dbo.DictionaryTocharians", "Person_Id", "dbo.People");
DropForeignKey("dbo.DictionaryTocharians", "Number_Id", "dbo.Numbers");
DropForeignKey("dbo.DictionaryTocharians", "Gender_Id", "dbo.Genders");
DropForeignKey("dbo.DictionaryTocharians", "Case_Id", "dbo.Cases");
DropIndex("dbo.Comments", new[] { "ClientId" });
DropIndex("dbo.DictionaryTocharians", new[] { "Person_Id" });
DropIndex("dbo.DictionaryTocharians", new[] { "Number_Id" });
DropIndex("dbo.DictionaryTocharians", new[] { "Gender_Id" });
DropIndex("dbo.DictionaryTocharians", new[] { "Case_Id" });
DropColumn("dbo.ProperNouns", "InStory");
DropColumn("dbo.ProperNouns", "DescriptionZh");
DropColumn("dbo.ProperNouns", "DescriptionFr");
DropColumn("dbo.ProperNouns", "DescriptionEn");
DropColumn("dbo.NamePlaces", "InStory");
DropColumn("dbo.Comments", "ClientId");
DropColumn("dbo.Comments", "Date");
DropColumn("dbo.DictionaryTocharians", "Person_Id");
DropColumn("dbo.DictionaryTocharians", "Number_Id");
DropColumn("dbo.DictionaryTocharians", "Gender_Id");
DropColumn("dbo.DictionaryTocharians", "Case_Id");
DropColumn("dbo.DictionaryTocharians", "IdClassSource");
DropTable("dbo.SearchResults");
CreateIndex("dbo.PersonDictionaryTocharians", "DictionaryTocharian_Id");
CreateIndex("dbo.PersonDictionaryTocharians", "Person_Id");
CreateIndex("dbo.NumberDictionaryTocharians", "DictionaryTocharian_Id");
CreateIndex("dbo.NumberDictionaryTocharians", "Number_Id");
CreateIndex("dbo.GenderDictionaryTocharians", "DictionaryTocharian_Id");
CreateIndex("dbo.GenderDictionaryTocharians", "Gender_Id");
CreateIndex("dbo.CaseDictionaryTocharians", "DictionaryTocharian_Id");
CreateIndex("dbo.CaseDictionaryTocharians", "Case_Id");
CreateIndex("dbo.Comments", "UserId");
CreateIndex("dbo.DictionaryTocharians", "MoodId");
CreateIndex("dbo.DictionaryTocharians", "TenseAndAspectId");
CreateIndex("dbo.DictionaryTocharians", "ValencyId");
CreateIndex("dbo.DictionaryTocharians", "VoiceId");
AddForeignKey("dbo.Comments", "UserId", "dbo.Users", "Id");
AddForeignKey("dbo.DictionaryTocharians", "VoiceId", "dbo.Voices", "Id", cascadeDelete: false);
AddForeignKey("dbo.DictionaryTocharians", "ValencyId", "dbo.Valencies", "Id", cascadeDelete: false);
AddForeignKey("dbo.DictionaryTocharians", "TenseAndAspectId", "dbo.TenseAndAspects", "Id", cascadeDelete: false);
AddForeignKey("dbo.DictionaryTocharians", "MoodId", "dbo.Moods", "Id", cascadeDelete: false);
AddForeignKey("dbo.PersonDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.PersonDictionaryTocharians", "Person_Id", "dbo.People", "Id", cascadeDelete: false);
AddForeignKey("dbo.NumberDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.NumberDictionaryTocharians", "Number_Id", "dbo.Numbers", "Id", cascadeDelete: false);
AddForeignKey("dbo.GenderDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.GenderDictionaryTocharians", "Gender_Id", "dbo.Genders", "Id", cascadeDelete: false);
AddForeignKey("dbo.CaseDictionaryTocharians", "DictionaryTocharian_Id", "dbo.DictionaryTocharians", "Id", cascadeDelete: false);
AddForeignKey("dbo.CaseDictionaryTocharians", "Case_Id", "dbo.Cases", "Id", cascadeDelete: false);
}
}
}
<file_sep>/Horizone/Models/Drying.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Drying
{
public int Id { get; set; }
[Display(Name = "Drying", ResourceType = typeof(StaticResource.Resources))]
public string DryingEn { get; set; }
[Display(Name = "Drying", ResourceType = typeof(StaticResource.Resources))]
public string DryingFr { get; set; }
[Display(Name = "Drying", ResourceType = typeof(StaticResource.Resources))]
public string DryingZh { get; set; }
}
}<file_sep>/Horizone/Models/Map.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Map
{
public int Id { get; set; }
[Display(Name = "NamePicture", ResourceType = typeof(StaticResource.Resources))]
public string NamePicture { get; set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImageMap> ImageMaps { get; set; }
}
}<file_sep>/Horizone/Models/IdentityModels.cs
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Horizone.Models
{
// Vous pouvez ajouter des données de profil pour l'utilisateur en ajoutant d'autres propriétés à votre classe ApplicationUser. Pour en savoir plus, consultez https://go.microsoft.com/fwlink/?LinkID=317594.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Notez qu'authenticationType doit correspondre à l'élément défini dans CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Ajouter les revendications personnalisées de l’utilisateur ici
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("Horizone", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>().ToTable("Users");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
}
//pour tous
public DbSet<Language> Languages { get; set; }
public DbSet<LinkAndPress> LinkAndPresses { get; set; }
public DbSet<AboutProject> AboutProjets { get; set; }
public DbSet<ImageProject> ImageProjets { get; set; }
public DbSet<Presentation> Presentations { get; set; }
public DbSet<ImageMap> ImageMaps { get; set; }
public DbSet<Map> Maps { get; set; }
public DbSet<SearchResult> SearchResults { get; set; }
//Gestion Utilisateur et équipe
public DbSet<Client> Clients { get; set; }
public DbSet<Collaborator> Collaborators { get; set; }
public DbSet<Collaboration> Collaborations { get; set; }
public DbSet<Publication> Publications { get; set; }
public DbSet<PartnerAndRelation> PartnerAndRelations { get; set; }
public DbSet<ImagePartner> ImagePartners { get; set; }
public DbSet<ImageCollaboration> ImageCollaborations { get; set; }
//Visual Aid
public DbSet<VisualAid> VisualAids { get; set; }
//News and Activity
public DbSet<Comment> Comments { get; set; }
public DbSet<News> Newses { get; set; }
public DbSet<Topic> Topics { get; set; }
public DbSet<ImageNews> ImageNews { get; set; }
public DbSet<Activity> Activitys { get; set; }
//Dictionaire
public DbSet<TochLanguage> TochLanguages { get; set; }
public DbSet<DictionaryTocharian> DictionaryTocharians { get; set; }
public DbSet<Case> Cases { get; set; }
public DbSet<Gender> Genders { get; set; }
public DbSet<Number>Numbers { get; set; }
public DbSet<Person> Persons { get; set; }
public DbSet<TenseAndAspect> TenseAndAspects { get; set; }
public DbSet<Valency> Valencies { get; set; }
public DbSet<Voice> Voices { get; set; }
public DbSet<Mood> Moods { get; set; }
public DbSet<WordClass> WordClasses { get; set; }
public DbSet<WordSubClass> WordSubClasses { get; set; }
public DbSet<AbbreviationDictionary> AbbreviationDictionaries { get; set; }
public DbSet<ReverseDictionary> ReverseDictionaries { get; set; }
public DbSet<Verb> Verbs { get; set; }
public DbSet<NounAdjective> NounAdjectives { get; set; }
public DbSet<Pronoun> Pronouns { get; set; }
public DbSet<OtherWord> OtherWords { get; set; }
//Manuscript
public DbSet<Catalogie> Catalogies { get; set; }
public DbSet<ImageManuscript> ImageManuscripts { get; set; }
public DbSet<Manuscript> Manuscripts { get; set; }
public DbSet<State> States { get; set; }
public DbSet<DescriptionManuscript> DescriptionManuscripts { get; set; }
public DbSet<RemarkAdd> RemarkAdds { get; set; }
public DbSet<Format> Formats { get; set; }
public DbSet<Ruling> Rulings { get; set; }
public DbSet<RulingColor> RulingColors { get; set; }
public DbSet<RulingDetail> RulingDetails { get; set; }
public DbSet<PaperColor> PaperColors { get; set; }
public DbSet<Material> Materials { get; set; }
public DbSet<WritingTool> WritingTools { get; set; }
public DbSet<AlignmentType> AlignmentTypes { get; set; }
public DbSet<Script> Scripts { get; set; }
public DbSet<ScriptType> ScriptTypes { get; set; }
public DbSet<ScriptAdd> ScriptAdds { get; set; }
public DbSet<LanguageStage> LanguageStages { get; set; }
public DbSet<LanguageDetail> LanguageDetails { get; set; }
public DbSet<GenderManuscript> GenderManuscripts { get; set; }
public DbSet<SubGenderManuscript> SubGenderManuscripts { get; set; }
public DbSet<Metric> Metrics { get; set; }
public DbSet<AnalyseMaterial> AnalyseMaterials { get; set; }
public DbSet<ImageUV> ImageUVs { get; set; }
public DbSet<ImageAnalyse> ImageAnalyses { get; set; }
//Analyse Macroscopic
public DbSet<AnalyseMacroscopic> AnalyseMacroscopics { get; set; }
public DbSet<TransmittedLight> TransmittedLights { get; set; }
public DbSet<Restore> Restores { get; set; }
public DbSet<ManufaturingDefect> ManufaturingDefects { get; set; }
public DbSet<PreparationPaperBeforeUsing> PreparationPaperBeforeUsings { get; set; }
public DbSet<Drying> Dryings { get; set; }
public DbSet<ChainLinesVisibility> ChainLinesVisibilitys { get; set; }
public DbSet<LaidLinesRegularity> LaidLinesRegularitys { get; set; }
public DbSet<FiberDirection> FiberDirections { get; set; }
public DbSet<SieveMark> SieveMarks { get; set; }
public DbSet<FiberDistribution> FiberDistributions { get; set; }
//TochPhrase and TochStory
public DbSet<TochPhrase> TochPhrases { get; set; }
public DbSet<TochStory> TochStorys { get; set; }
public DbSet<NamePlace> NamePlaces { get; set; }
public DbSet<ThemeStory> ThemeStorys { get; set; }
public DbSet<SourceStory> SourceStorys { get; set; }
public DbSet<ProperNoun> ProperNouns { get; set; }
//Reference
public DbSet<Bibliography> Bibliographys { get; set; }
public DbSet<Abreviation> Abreviations { get; set; }
public DbSet<ImageBook> ImageBooks { get; set; }
}
}<file_sep>/Horizone/Models/ScriptAdd.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class ScriptAdd
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "ScriptAddEn", ResourceType = typeof(StaticResource.Resources))]
public string ScriptAddEn { get; set; }
[AllowHtml]
[Display(Name = "ScriptAddFr", ResourceType = typeof(StaticResource.Resources))]
public string ScriptAddFr { get; set; }
[AllowHtml]
[Display(Name = "ScriptAddZh", ResourceType = typeof(StaticResource.Resources))]
public string ScriptAddZh { get; set; }
}
}<file_sep>/Horizone/Models/AnalyseMacroscopic.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class AnalyseMacroscopic
{
public int Id { get; set; }
//General Information
[Display(Name = "Catalogue", ResourceType = typeof(StaticResource.Resources))]
public int CatalogieId { get; set; }
[ForeignKey("CatalogieId")]
public Catalogie Catalogie { get; set; }
[Display(Name = "Index")]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string Index { get; set; }
[Display(Name = "FindingPlace", ResourceType = typeof(StaticResource.Resources))]
public int MapId { get; set; }
[ForeignKey("MapId")]
public Map Map { get; set; }
[Display(Name = "EstimatedDateProduction", ResourceType = typeof(StaticResource.Resources))]
public string EstimatedDateProduction { get; set; }
[Display(Name = "PlaceProduction", ResourceType = typeof(StaticResource.Resources))]
public string PlaceProduction{ get; set; }
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[Display(Name = "Theme", ResourceType = typeof(StaticResource.Resources))]
public int GenderManuscriptId { get; set; }
[ForeignKey("GenderManuscriptId")]
public GenderManuscript GenderManuscript { get; set; }
[Display(Name = "GeneralState", ResourceType = typeof(StaticResource.Resources))]
public int StateId { get; set; }
[ForeignKey("StateId")]
public State State { get; set; }
[Display(Name = "TochLanguage", ResourceType = typeof(StaticResource.Resources))]
public int TochLanguageId { get; set; }
[ForeignKey("TochLanguageId")]
public TochLanguage TochLanguage { get; set; }
//Sheet Description
[Display(Name = "Format", ResourceType = typeof(StaticResource.Resources))]
public int FormatId { get; set; }
[ForeignKey("FormatId")]
public Format Format { get; set; }
[Display(Name = "NumberOfHoles", ResourceType = typeof(StaticResource.Resources))]
public int NumberOfHoles { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[Display(Name = "AverageThickness", ResourceType = typeof(StaticResource.Resources))]
public string AverageThickness { get; set; }
[Display(Name = "Correction", ResourceType = typeof(StaticResource.Resources))]
public Boolean Correction { get; set; }
[Display(Name = "SheetCondition", ResourceType = typeof(StaticResource.Resources))]
public string SheetCondition { get; set; }
[Display(Name = "NeedForConservation", ResourceType = typeof(StaticResource.Resources))]
public string NeedForConservation { get; set; }
[AllowHtml]
[Display(Name = "Observation", ResourceType = typeof(StaticResource.Resources))]
public string Observation { get; set; }
[Display(Name = "Restore", ResourceType = typeof(StaticResource.Resources))]
public int RestoreId { get; set; }
[ForeignKey("RestoreId")]
public Restore Restore { get; set; }
//Layout
[Display(Name = "Ruling", ResourceType = typeof(StaticResource.Resources))]
public int RulingId { get; set; }
[ForeignKey("RulingId")]
public Ruling Ruling { get; set; }
[Display(Name = "NumberOfLine", ResourceType = typeof(StaticResource.Resources))]
public int NumberOfLine { get; set; }
[Display(Name = "Script", ResourceType = typeof(StaticResource.Resources))]
public int ScriptId { get; set; }
[ForeignKey("ScriptId")]
public Script Script { get; set; }
[Display(Name = "PageFrame", ResourceType = typeof(StaticResource.Resources))]
public string PageFrame { get; set; }
//Macroscopic Analysic
[Display(Name = "PaperColor", ResourceType = typeof(StaticResource.Resources))]
public int PaperColorId { get; set; }
[ForeignKey("PaperColorId")]
public PaperColor PaperColor { get; set; }
[Display(Name = "WritingTool", ResourceType = typeof(StaticResource.Resources))]
public int WritingToolId { get; set; }
[ForeignKey("WritingToolId")]
public WritingTool WritingTool { get; set; }
[Display(Name = "SoftQuality", ResourceType = typeof(StaticResource.Resources))]
public Boolean SoftQuality { get; set; }
[Display(Name = "RattleQuality", ResourceType = typeof(StaticResource.Resources))]
public Boolean RattleQuality { get; set; }
[Display(Name = "Transparency", ResourceType = typeof(StaticResource.Resources))]
public Boolean Transparency { get; set; }
[Display(Name = "SurfaceAspect", ResourceType = typeof(StaticResource.Resources))]
public string SurfaceAspect { get; set; }
[Display(Name = "CoatingColor", ResourceType = typeof(StaticResource.Resources))]
public int RulingColorId { get; set; }
[ForeignKey("RulingColorId")]
public RulingColor RulingColor { get; set; }
[Display(Name = "CoatingDecayingCondition", ResourceType = typeof(StaticResource.Resources))]
public string CoatingDecayingCondition { get; set; }
[Display(Name = "ClayOrSandParticules", ResourceType = typeof(StaticResource.Resources))]
public Boolean ClayOrSandParticules { get; set; }
[Display(Name = "SurfaceOnBothSides", ResourceType = typeof(StaticResource.Resources))]
public Boolean SurfaceOnBothSides { get; set; }
[Display(Name = "TransmittedLight", ResourceType = typeof(StaticResource.Resources))]
public ICollection<TransmittedLight> TransmittedLights { get; set; }
[Display(Name = "FiberDistribution", ResourceType = typeof(StaticResource.Resources))]
public int FiberDistributionId { get; set; }
[ForeignKey("FiberDistributionId")]
public FiberDistribution FiberDistribution { get; set; }
[Display(Name = "NumberLayer", ResourceType = typeof(StaticResource.Resources))]
public string NumberLayer { get; set; }
[Display(Name = "SieveMark", ResourceType = typeof(StaticResource.Resources))]
public int SieveMarkId { get; set; }
[ForeignKey("SieveMarkId")]
public SieveMark SieveMark { get; set; }
[Display(Name = "FiberDirection", ResourceType = typeof(StaticResource.Resources))]
public int FiberDirectionId { get; set; }
[ForeignKey("FiberDirectionId")]
public FiberDirection FiberDirection { get; set; }
[Display(Name = "LaidLinesRegularity", ResourceType = typeof(StaticResource.Resources))]
public int LaidLinesRegularityId { get; set; }
[ForeignKey("LaidLinesRegularityId")]
public LaidLinesRegularity LaidLinesRegularity { get; set; }
[Display(Name = "NumberChainLinePerCm", ResourceType = typeof(StaticResource.Resources))]
public int NumberChainLinePerCm { get; set; }
[Display(Name = "ChainLinesVisibility", ResourceType = typeof(StaticResource.Resources))]
public int ChainLinesVisibilityId { get; set; }
[ForeignKey("ChainLinesVisibilityId")]
public ChainLinesVisibility ChainLinesVisibility { get; set; }
[Display(Name = "SpaceBetweenLines", ResourceType = typeof(StaticResource.Resources))]
public string SpaceBetweenLines { get; set; }
[Display(Name = "Drying", ResourceType = typeof(StaticResource.Resources))]
public int DryingId { get; set; }
[ForeignKey("DryingId")]
public Drying Drying { get; set; }
[Display(Name = "PreparationPaperBeforeUsing", ResourceType = typeof(StaticResource.Resources))]
public int PreparationPaperBeforeUsingId { get; set; }
[ForeignKey("PreparationPaperBeforeUsingId")]
public PreparationPaperBeforeUsing PreparationPaperBeforeUsing { get; set; }
[Display(Name = "ManufaturingDefect", ResourceType = typeof(StaticResource.Resources))]
public int ManufaturingDefectId { get; set; }
[ForeignKey("ManufaturingDefectId")]
public ManufaturingDefect ManufaturingDefect { get; set; }
[Display(Name = "Bibliography", ResourceType = typeof(StaticResource.Resources))]
public ICollection<Bibliography> Bibliographys { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/ManufaturingDefectsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ManufaturingDefectsController : BaseController
{
// GET: BackOffice/ManufaturingDefects
public ActionResult Index()
{
return View(db.ManufaturingDefects.ToList());
}
// GET: BackOffice/ManufaturingDefects/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/ManufaturingDefects/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,ManufaturingDefectEn,ManufaturingDefectFr,ManufaturingDefectZh")] ManufaturingDefect manufaturingDefect)
{
if (ModelState.IsValid)
{
db.ManufaturingDefects.Add(manufaturingDefect);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(manufaturingDefect);
}
// GET: BackOffice/ManufaturingDefects/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ManufaturingDefect manufaturingDefect = db.ManufaturingDefects.Find(id);
if (manufaturingDefect == null)
{
return HttpNotFound();
}
return View(manufaturingDefect);
}
// POST: BackOffice/ManufaturingDefects/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,ManufaturingDefectEn,ManufaturingDefectFr,ManufaturingDefectZh")] ManufaturingDefect manufaturingDefect)
{
if (ModelState.IsValid)
{
db.Entry(manufaturingDefect).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(manufaturingDefect);
}
// GET: BackOffice/ManufaturingDefects/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ManufaturingDefect manufaturingDefect = db.ManufaturingDefects.Find(id);
if (manufaturingDefect == null)
{
return HttpNotFound();
}
return View(manufaturingDefect);
}
// POST: BackOffice/ManufaturingDefects/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ManufaturingDefect manufaturingDefect = db.ManufaturingDefects.Find(id);
db.ManufaturingDefects.Remove(manufaturingDefect);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Controllers/FontNewsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Common;
using Horizone.Models;
using Microsoft.AspNet.Identity;
namespace Horizone.Controllers
{
public class FontNewsController : BaseController
{
// GET: FontNews
public ActionResult Index()
{
var newses = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic);
return View(newses.ToList());
}
public ActionResult ConferencesAndSymposia()
{
var newses = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic).Where(x => x.Topic.Id == 9 || x.Topic.Id == 14);
return View(newses.ToList());
}
public ActionResult ExpositionsAndMuseums()
{
var newses = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic).Where(x => x.Topic.Id == 11 || x.Topic.Id == 16);
return View(newses.ToList());
}
public ActionResult Media()
{
var newses = db.Newses.Include(n => n.Collaborator).Include(n => n.Language).Include(n => n.Topic).Where(x=>x.Topic.Id == 12);
return View(newses.ToList());
}
[ChildActionOnly]
public ActionResult ListNews()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses");
return PartialView(news.OrderByDescending(x => x.View).Take(3).ToList());
}
[ChildActionOnly]
public ActionResult LatestNewsFr()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x=>x.LanguageId == 1);
if (news.Count() != 0)
{
ViewBag.NewsIdFr = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
[ChildActionOnly]
public ActionResult LatestNewsEn()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x => x.LanguageId == 2);
if (news.Count() != 0)
{
ViewBag.NewsIdEn = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
[ChildActionOnly]
public ActionResult LatestNewsZh()
{
var news = db.Newses.Include("Language").Include("Collaborator").Include("Topic").Include("ImageNewses").Where(x => x.LanguageId == 3);
if(news.Count()!=0)
{ ViewBag.NewsIdZh = news.OrderByDescending(x => x.Id).First().Id;
}
return PartialView(news.OrderByDescending(x => x.Id).ToList());
}
// GET: FontNews/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
News news = db.Newses.Include("Collaborator").Include("Language").Include("Topic").Include("ImageNewses").SingleOrDefault(x=>x.Id ==id);
news.View += 1;
if (news == null)
{
return HttpNotFound();
}
return View(news);
}
[ChildActionOnly]
public ActionResult ListComment(int? id)
{
var comments = db.Comments.Include("News").Include("Client").Where(x=>x.NewsId==id);
ViewBag.NewsId = id;
return PartialView(comments.OrderByDescending(x => x.Id).ToList());
}
public ActionResult NewComment(string search,int id)
{ string userId = User.Identity.GetUserId();
var comment = new Comment();
Client client = db.Clients.Include("ApplicationUser").SingleOrDefault(x => x.UserId == userId);
if (id != 0)
{
comment.Content = search;
comment.Date = DateTime.Now;
comment.NewsId = id;
comment.ClientId = client.Id;
}
if (ModelState.IsValid)
{
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Index","Home");
}
return View(comment);
}
}
}
<file_sep>/Horizone/Models/Topic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Topic
{
public int Id { get; set; }
[Display(Name = "TopicEn", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(40, MinimumLength = 1, ErrorMessageResourceName = "MaxLength40", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string TopicEn { get; set; }
[Display(Name = "TopicFr", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(40, MinimumLength = 1, ErrorMessageResourceName = "MaxLength40", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string TopicFr { get; set; }
[Display(Name = "TopicZh", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(40, MinimumLength = 1, ErrorMessageResourceName = "MaxLength40", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string TopicZh { get; set; }
[Display(Name = "Activity", ResourceType = typeof(StaticResource.Resources))]
public bool Activity { get; set; }
[Display(Name = "News", ResourceType = typeof(StaticResource.Resources))]
public bool News { get; set; }
}
}<file_sep>/Horizone/Models/ImageUV.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class ImageUV
{
public int Id { get; set; }
[Display(Name = "Name", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
[StringLength(150)]
public string Name { get; set; }
[Required]
[StringLength(20)]
public string ContentType { get; set; }
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public byte[] Content { get; set; }
[Display(Name = "AnalyseMaterial", ResourceType = typeof(StaticResource.Resources))]
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public int AnalyseMaterialId { get; set; }
[ForeignKey("AnalyseMaterialId")]
public AnalyseMaterial AnalyseMaterial { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/ThemeStoriesController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class ThemeStoriesController : BaseController
{
// GET: BackOffice/ThemeStories
public ActionResult Index()
{
return View(db.ThemeStorys.OrderBy(x => x.ThemeEn).ToList());
}
// GET: BackOffice/ThemeStories/Create
public ActionResult Create()
{
return View();
}
// POST: BackOffice/ThemeStories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,ThemeEn,ThemeFr,ThemeZn")] ThemeStory themeStory)
{
if (ModelState.IsValid)
{
db.ThemeStorys.Add(themeStory);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(themeStory);
}
// GET: BackOffice/ThemeStories/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ThemeStory themeStory = db.ThemeStorys.Find(id);
if (themeStory == null)
{
return HttpNotFound();
}
return View(themeStory);
}
// POST: BackOffice/ThemeStories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,ThemeEn,ThemeFr,ThemeZn")] ThemeStory themeStory)
{
if (ModelState.IsValid)
{
db.Entry(themeStory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(themeStory);
}
// GET: BackOffice/ThemeStories/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ThemeStory themeStory = db.ThemeStorys.Find(id);
if (themeStory == null)
{
return HttpNotFound();
}
return View(themeStory);
}
// POST: BackOffice/ThemeStories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
ThemeStory themeStory = db.ThemeStorys.Find(id);
db.ThemeStorys.Remove(themeStory);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchTheme(string search)
{
IEnumerable<ThemeStory> themeStorys = db.ThemeStorys;
if (!string.IsNullOrWhiteSpace(search))
{
themeStorys = themeStorys.Where(x => x.ThemeEn.Contains(search) || x.ThemeFr.Contains(search) || x.ThemeZn.Contains(search));
}
if (themeStorys.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Search = search;
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "en")
{
themeStorys.OrderBy(x => x.ThemeEn).ToList();
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "fr")
{
themeStorys.OrderBy(x => x.ThemeFr).ToList();
}
if (Session[Horizone.Common.CommonConstants.CurrentCulture].ToString() == "zh")
{
themeStorys.OrderBy(x => x.ThemeZn).ToList();
}
return View("SearchTheme", themeStorys);
}
}
}
<file_sep>/Horizone/Models/OtherWord.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class OtherWord
{
public int Id { get; set; }
[Display(Name = "DictionaryTocharian", ResourceType = typeof(StaticResource.Resources))]
public int DictionaryId { get; set; }
[ForeignKey("DictionaryId")]
public DictionaryTocharian DictionaryTocharian { get; set; }
}
}<file_sep>/Horizone/Models/Voice.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Voice
{
public int Id { get; set; }
[Display(Name = "Voice", ResourceType = typeof(StaticResource.Resources))]
public string AbbreviationVoice { get; set; }
[Display(Name = "VoiceFr", ResourceType = typeof(StaticResource.Resources))]
public string VoiceEn { get; set; }
[Display(Name = "VoiceFr", ResourceType = typeof(StaticResource.Resources))]
public string VoiceFr { get; set; }
[Display(Name = "VoiceZh", ResourceType = typeof(StaticResource.Resources))]
public string VoiceZh { get; set; }
}
}<file_sep>/Horizone/Models/Comment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Comment
{
public int Id { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Date ")]
public DateTime Date { get; set; }
[AllowHtml]
[Display(Name = "Content", ResourceType = typeof(StaticResource.Resources))]
public string Content { get; set; }
[Display(Name = "News", ResourceType = typeof(StaticResource.Resources))]
public int NewsId { get; set; }
[ForeignKey("NewsId")]
public News News { get; set; }
[Display(Name = "Client", ResourceType = typeof(StaticResource.Resources))]
public int ClientId { get; set; }
[ForeignKey("ClientId")]
public Client Client { get; set; }
}
}<file_sep>/Horizone/Models/FiberDirection.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class FiberDirection
{
public int Id { get; set; }
[Display(Name = "FiberDirection", ResourceType = typeof(StaticResource.Resources))]
public string DirectionEn { get; set; }
[Display(Name = "FiberDirection", ResourceType = typeof(StaticResource.Resources))]
public string DirectionFr { get; set; }
[Display(Name = "FiberDirection", ResourceType = typeof(StaticResource.Resources))]
public string DirectionZh { get; set; }
}
}<file_sep>/Horizone/Controllers/BaseController.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Horizone.Common;
using Horizone.Models;
using Microsoft.AspNet.Identity;
namespace Horizone.Controllers
{
public class BaseController : Controller
{
protected ApplicationDbContext db = new ApplicationDbContext();
/// <summary>
/// Affiche un message dans le layout success ou erreur avec ou sans redirection
/// </summary>
/// <param name="text">le text a afficher</param>
/// <param name="type">le type de message</param>
protected void Display(string text, MessageType type = MessageType.SUCCES)
{
var m = new Message(type, text);
TempData["MESSAGE"] = m;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
this.db.Dispose();
}
protected int GetCurrentClientId()
{
var userId = User.Identity.GetUserId();
var client = db.Clients.SingleOrDefault(x => x.UserId == userId);
if (client != null)
{
return client.Id;
}
else
{
return 0;
}
}
protected string GetCurrentClientName()
{
var userId = User.Identity.GetUserId();
var client = db.Clients.SingleOrDefault(x => x.UserId == userId);
if (client != null)
{
return client.FirstName;
}
else
{
return "";
}
}
protected string GetCurrentCollaboratorName()
{
var userId = User.Identity.GetUserId();
var collaborator = db.Collaborators.SingleOrDefault(x => x.UserId == userId);
if (collaborator != null)
{
return collaborator.FirstName;
}
else
{
return "";
}
}
protected string GetCurrentUserRoles()
{
var userId = User.Identity.GetUserId();
var client = db.Clients.SingleOrDefault(x => x.UserId == userId);
if (client != null)
{
return client.FirstName;
}
else
{
return "";
}
}
//initilizing culture on controller initialization
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
if (Session[CommonConstants.CurrentCulture] != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(Session[CommonConstants.CurrentCulture].ToString());
Thread.CurrentThread.CurrentUICulture = new CultureInfo(Session[CommonConstants.CurrentCulture].ToString());
}
else
{
Session[CommonConstants.CurrentCulture] = "fr";
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr");
}
}
// changing culture
public ActionResult ChangeCulture(string ddlCulture, string returnUrl)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlCulture);
Session[CommonConstants.CurrentCulture] = ddlCulture;
return Redirect(returnUrl);
}
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/OtherWordsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
[Authorize(Roles = "Collaborator,Admin")]
public class OtherWordsController : BaseController
{
// GET: BackOffice/OtherWords
public ActionResult Index(int page = 1, int pageSize = 200)
{
var otherWords = db.OtherWords.Include(o => o.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers);
return View(otherWords.OrderBy(x => x.DictionaryTocharian.Word).ToPagedList(page, pageSize));
}
public ActionResult Adverb()
{
var otherWords = db.OtherWords.Include(d => d.DictionaryTocharian).Include(d => d.DictionaryTocharian.WordClass).Include(d => d.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.Numbers)
.Where(x => x.DictionaryTocharian.WordClass.ClassEn == "Adverb" || x.DictionaryTocharian.WordSubClass.SubClassEn == "Adverb");
return View(otherWords.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
// GET: BackOffice/OtherWords/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
OtherWord otherWord = db.OtherWords
.Include(x=>x.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.SingleOrDefault(x=>x.Id==id);
if (otherWord == null)
{
return HttpNotFound();
}
return View(otherWord);
}
// GET: BackOffice/OtherWords/Create
public ActionResult Create()
{
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId != 10 && x.WordClassId != 2 && x.WordClassId != 3 && x.WordClassId != 4).OrderBy(x => x.Word), "Id", "Word");
return View();
}
// POST: BackOffice/OtherWords/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DictionaryId")] OtherWord otherWord)
{
if (ModelState.IsValid)
{
db.OtherWords.Add(otherWord);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId != 10 && x.WordClassId != 2 && x.WordClassId != 3 && x.WordClassId != 4).OrderBy(x => x.Word), "Id", "Word", otherWord.DictionaryId);
return View(otherWord);
}
// GET: BackOffice/OtherWords/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
OtherWord otherWord = db.OtherWords
.Include(x => x.DictionaryTocharian).SingleOrDefault(x=>x.Id==id);
if (otherWord == null)
{
return HttpNotFound();
}
return View(otherWord);
}
// POST: BackOffice/OtherWords/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
OtherWord otherWord = db.OtherWords
.Include(x => x.DictionaryTocharian).SingleOrDefault(x => x.Id == id);
db.OtherWords.Remove(otherWord);
db.SaveChanges();
return RedirectToAction("Index");
}
}
}
<file_sep>/Horizone/Models/PartnerAndRelation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class PartnerAndRelation
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "Name", ResourceType = typeof(StaticResource.Resources))]
public string Name { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[AllowHtml]
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
public string Link { get; set; }
[Display(Name = "Partner", ResourceType = typeof(StaticResource.Resources))]
public Boolean Partner { get; set; }
[Display(Name = "RelationInternational", ResourceType = typeof(StaticResource.Resources))]
public Boolean Relation { get; set; }
[Display(Name = "Order", ResourceType = typeof(StaticResource.Resources))]
public int Order { get; set; }
[Display(Name = "Visible", ResourceType = typeof(StaticResource.Resources))]
public Boolean Visible { get; set; }
[Display(Name = "Picture", ResourceType = typeof(StaticResource.Resources))]
public ICollection<ImagePartner> ImagePartners { get; set; }
}
}<file_sep>/Horizone/Areas/BackOffice/Controllers/VerbsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Horizone.Controllers;
using Horizone.Models;
using PagedList;
namespace Horizone.Areas.BackOffice.Controllers
{
public class VerbsController : BaseController
{
// GET: BackOffice/Verbs
public ActionResult Index()
{
var verbs = db.Verbs.Include(v => v.DictionaryTocharian)
.Include(v => v.DictionaryTocharian.TochLanguage)
.Include(v => v.DictionaryTocharian.WordClass)
.Include(v => v.DictionaryTocharian.WordSubClass)
.Include(v => v.DictionaryTocharian.Numbers)
.Include(v => v.Mood).Include(v => v.TenseAndAspect)
.Include(v => v.Valency).Include(v => v.Voice)
.Include("Persons");
return View(verbs.OrderBy(x => x.DictionaryTocharian.Word).ToList());
}
// GET: BackOffice/Verbs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Verb verb = db.Verbs.Include(v => v.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include(v => v.Mood).Include(v => v.TenseAndAspect)
.Include(v => v.Valency).Include(v => v.Voice)
.Include("Persons").SingleOrDefault(p => p.Id == id);
if (verb == null)
{
return HttpNotFound();
}
return View(verb);
}
// GET: BackOffice/Verbs/Create
public ActionResult Create()
{
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 10).OrderBy(x=>x.Word), "Id", "Word");
ViewBag.MoodEnId = new SelectList(db.Moods.OrderBy(x=>x.MoodEn), "Id", "MoodEn");
ViewBag.MoodFrId = new SelectList(db.Moods.OrderBy(x => x.MoodFr), "Id", "MoodFr");
ViewBag.MoodZhId = new SelectList(db.Moods.OrderBy(x => x.MoodZh), "Id", "MoodZh");
ViewBag.TenseAndAspectEnId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseEn), "Id", "TenseEn");
ViewBag.TenseAndAspectFrId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseFr), "Id", "TenseFr");
ViewBag.TenseAndAspectZhId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseZh), "Id", "TenseZh");
ViewBag.ValencyEnId = new SelectList(db.Valencies.OrderBy(x => x.ValencyEn), "Id", "ValencyEn");
ViewBag.ValencyFrId = new SelectList(db.Valencies.OrderBy(x => x.ValencyFr), "Id", "ValencyFr");
ViewBag.ValencyZhId = new SelectList(db.Valencies.OrderBy(x => x.ValencyZh), "Id", "ValencyZh");
ViewBag.VoiceEnId = new SelectList(db.Voices.OrderBy(x => x.VoiceEn), "Id", "VoiceEn");
ViewBag.VoiceFrId = new SelectList(db.Voices.OrderBy(x => x.VoiceFr), "Id", "VoiceFr");
ViewBag.VoiceZhId = new SelectList(db.Voices.OrderBy(x => x.VoiceZh), "Id", "VoiceZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View();
}
// POST: BackOffice/Verbs/Create
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DictionaryId,VoiceId,ValencyId,TenseAndAspectId,MoodId,PronounSuffix")] Verb verb, int[] PersonId)
{
if (ModelState.IsValid)
{
if (PersonId.Count() == 0)
{
verb.Persons = db.Persons.Where(x => x.Id == 1).ToList();
}
else
{
verb.Persons = db.Persons.Where(x => PersonId.Contains(x.Id)).ToList();
}
db.Verbs.Add(verb);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 10).OrderBy(x => x.Word), "Id", "Word");
ViewBag.MoodEnId = new SelectList(db.Moods.OrderBy(x => x.MoodEn), "Id", "MoodEn");
ViewBag.MoodFrId = new SelectList(db.Moods.OrderBy(x => x.MoodFr), "Id", "MoodFr");
ViewBag.MoodZhId = new SelectList(db.Moods.OrderBy(x => x.MoodZh), "Id", "MoodZh");
ViewBag.TenseAndAspectEnId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseEn), "Id", "TenseEn");
ViewBag.TenseAndAspectFrId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseFr), "Id", "TenseFr");
ViewBag.TenseAndAspectZhId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseZh), "Id", "TenseZh");
ViewBag.ValencyEnId = new SelectList(db.Valencies.OrderBy(x => x.ValencyEn), "Id", "ValencyEn");
ViewBag.ValencyFrId = new SelectList(db.Valencies.OrderBy(x => x.ValencyFr), "Id", "ValencyFr");
ViewBag.ValencyZhId = new SelectList(db.Valencies.OrderBy(x => x.ValencyZh), "Id", "ValencyZh");
ViewBag.VoiceEnId = new SelectList(db.Voices.OrderBy(x => x.VoiceEn), "Id", "VoiceEn");
ViewBag.VoiceFrId = new SelectList(db.Voices.OrderBy(x => x.VoiceFr), "Id", "VoiceFr");
ViewBag.VoiceZhId = new SelectList(db.Voices.OrderBy(x => x.VoiceZh), "Id", "VoiceZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(verb);
}
// GET: BackOffice/Verbs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Verb verb = db.Verbs.Include(p => p.DictionaryTocharian)
.Include(p => p.DictionaryTocharian.TochLanguage)
.Include(n => n.DictionaryTocharian.WordClass)
.Include(n => n.DictionaryTocharian.WordSubClass)
.Include(d => d.DictionaryTocharian.Numbers)
.Include("Persons").SingleOrDefault(p => p.Id == id);
if (verb == null)
{
return HttpNotFound();
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 10).OrderBy(x => x.Word), "Id", "Word",verb.DictionaryId);
ViewBag.MoodEnId = new SelectList(db.Moods.OrderBy(x => x.MoodEn), "Id", "MoodEn");
ViewBag.MoodFrId = new SelectList(db.Moods.OrderBy(x => x.MoodFr), "Id", "MoodFr");
ViewBag.MoodZhId = new SelectList(db.Moods.OrderBy(x => x.MoodZh), "Id", "MoodZh");
ViewBag.TenseAndAspectEnId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseEn), "Id", "TenseEn");
ViewBag.TenseAndAspectFrId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseFr), "Id", "TenseFr");
ViewBag.TenseAndAspectZhId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseZh), "Id", "TenseZh");
ViewBag.ValencyEnId = new SelectList(db.Valencies.OrderBy(x => x.ValencyEn), "Id", "ValencyEn");
ViewBag.ValencyFrId = new SelectList(db.Valencies.OrderBy(x => x.ValencyFr), "Id", "ValencyFr");
ViewBag.ValencyZhId = new SelectList(db.Valencies.OrderBy(x => x.ValencyZh), "Id", "ValencyZh");
ViewBag.VoiceEnId = new SelectList(db.Voices.OrderBy(x => x.VoiceEn), "Id", "VoiceEn");
ViewBag.VoiceFrId = new SelectList(db.Voices.OrderBy(x => x.VoiceFr), "Id", "VoiceFr");
ViewBag.VoiceZhId = new SelectList(db.Voices.OrderBy(x => x.VoiceZh), "Id", "VoiceZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(verb);
}
// POST: BackOffice/Verbs/Edit/5
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DictionaryId,VoiceId,ValencyId,TenseAndAspectId,MoodId,PronounSuffix")] Verb verb, int[] PersonId)
{
if (ModelState.IsValid)
{
db.Entry(verb).State = EntityState.Modified;
if (PersonId != null)
verb.Persons = db.Persons.Where(x => PersonId.Contains(x.Id)).ToList();
if (verb.Persons.Count() == 0)
verb.Persons = db.Persons.Where(x => x.ConjugatedPersonEn == "No Person").ToList();
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DictionaryId = new SelectList(db.DictionaryTocharians.Where(x => x.WordClassId == 10).OrderBy(x => x.Word), "Id", "Word",verb.DictionaryId);
ViewBag.MoodEnId = new SelectList(db.Moods.OrderBy(x => x.MoodEn), "Id", "MoodEn");
ViewBag.MoodFrId = new SelectList(db.Moods.OrderBy(x => x.MoodFr), "Id", "MoodFr");
ViewBag.MoodZhId = new SelectList(db.Moods.OrderBy(x => x.MoodZh), "Id", "MoodZh");
ViewBag.TenseAndAspectEnId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseEn), "Id", "TenseEn");
ViewBag.TenseAndAspectFrId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseFr), "Id", "TenseFr");
ViewBag.TenseAndAspectZhId = new SelectList(db.TenseAndAspects.OrderBy(x => x.TenseZh), "Id", "TenseZh");
ViewBag.ValencyEnId = new SelectList(db.Valencies.OrderBy(x => x.ValencyEn), "Id", "ValencyEn");
ViewBag.ValencyFrId = new SelectList(db.Valencies.OrderBy(x => x.ValencyFr), "Id", "ValencyFr");
ViewBag.ValencyZhId = new SelectList(db.Valencies.OrderBy(x => x.ValencyZh), "Id", "ValencyZh");
ViewBag.VoiceEnId = new SelectList(db.Voices.OrderBy(x => x.VoiceEn), "Id", "VoiceEn");
ViewBag.VoiceFrId = new SelectList(db.Voices.OrderBy(x => x.VoiceFr), "Id", "VoiceFr");
ViewBag.VoiceZhId = new SelectList(db.Voices.OrderBy(x => x.VoiceZh), "Id", "VoiceZh");
ViewBag.PersonsEn = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonEn");
ViewBag.PersonsFr = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonFr");
ViewBag.PersonsZh = new SelectList(db.Persons.OrderBy(x => x.ConjugatedPersonEn), "Id", "ConjugatedPersonZh");
return View(verb);
}
// GET: BackOffice/Verbs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Verb verb = db.Verbs.Include(p => p.DictionaryTocharian).Include(p => p.DictionaryTocharian.TochLanguage).Include("Persons").SingleOrDefault(p => p.Id == id);
if (verb == null)
{
return HttpNotFound();
}
return View(verb);
}
// POST: BackOffice/Verbs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Verb verb = db.Verbs.Include(p => p.DictionaryTocharian).Include(p => p.DictionaryTocharian.TochLanguage).Include("Persons").SingleOrDefault(p => p.Id == id);
db.Verbs.Remove(verb);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchDictionary(string search)
{
IEnumerable<Verb> verbs = db.Verbs.Include(d => d.DictionaryTocharian)
.Include(d => d.DictionaryTocharian.TochLanguage)
.Include(d => d.DictionaryTocharian.WordClass)
.Include(d => d.DictionaryTocharian.WordSubClass)
;
if (!string.IsNullOrWhiteSpace(search))
{
verbs = verbs.Where(x => x.DictionaryTocharian.Word.Contains(search));
}
if (verbs.Count() == 0)
{
Display("Aucun résultat");
}
ViewBag.Count = verbs.Count();
ViewBag.Search = search;
return View("SearchDictionary", verbs.ToList());
}
}
}
<file_sep>/Horizone/Models/Abreviation.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Horizone.Models
{
public class Abreviation
{
public int Id { get; set; }
[AllowHtml]
[Display(Name = "Symbol", ResourceType = typeof(StaticResource.Resources))]
public string Symbol { get; set; }
[AllowHtml]
[Display(Name = "Description", ResourceType = typeof(StaticResource.Resources))]
public string Description { get; set; }
[AllowHtml]
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
public string Link { get; set; }
}
}<file_sep>/Horizone/Models/LaidLinesRegularity.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class LaidLinesRegularity
{
public int Id { get; set; }
[Display(Name = "LaidLinesRegularity", ResourceType = typeof(StaticResource.Resources))]
public string LaidLinesRegularityEn { get; set; }
[Display(Name = "LaidLinesRegularity", ResourceType = typeof(StaticResource.Resources))]
public string LaidLinesRegularityFr { get; set; }
[Display(Name = "LaidLinesRegularity", ResourceType = typeof(StaticResource.Resources))]
public string LaidLinesRegularityZh { get; set; }
}
}<file_sep>/Horizone/Models/Collaborator.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class Collaborator : Personne
{
[Required(ErrorMessageResourceName = "FieldRequired", ErrorMessageResourceType = typeof(StaticResource.Resources))]
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser ApplicationUser { get; set; }
public ICollection<News> Newses { get; set; }
}
}<file_sep>/Horizone/Models/LinkAndPress.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Horizone.Models
{
public class LinkAndPress
{
public int Id { get; set; }
[Display(Name = "TitleArticle", ResourceType = typeof(StaticResource.Resources))]
public string Title { get; set; }
[Display(Name = "Link", ResourceType = typeof(StaticResource.Resources))]
public string Link { get; set; }
[Display(Name = "OrderOfLink", ResourceType = typeof(StaticResource.Resources))]
public int Order { get; set; }
[Display(Name = "Press", ResourceType = typeof(StaticResource.Resources))]
public Boolean Press { get; set; }
public Byte Status { get; set; }
[Display(Name = "ListedPosition", ResourceType = typeof(StaticResource.Resources))]
public string Target { get; set; }
[Display(Name = "Language", ResourceType = typeof(StaticResource.Resources))]
public int LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
}
}
|
cf78d6ab385ab1c6351e092e9d906aad33d09b13
|
[
"C#"
] | 120
|
C#
|
My-Particularities-techniques/Horizone
|
52e23ebcf06ef73ed3bd4aa242e3b7bc7b6d326f
|
6580af3ffa0a5532588a7d50dd0117f69d1e92fa
|
refs/heads/master
|
<file_sep><?php
class Login_model extends CI_Model
{
function can_login($userName,$password)
{
$this->db->where('Username',$userName );
$this->db->where('Password',$password);
$query=$this->db->get('register');
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
function user_role($userName,$password)
{
$this->db->where('Username',$userName );
$this->db->where('Password',$<PASSWORD>);
$query=$this->db->get('register');
$res=$query->result();
foreach ($res as $object1)
{
return $object1->role;
}
}
}<file_sep> <br>
<br>
<h2><?= $title ?></h2>
<?php foreach ($posts as $post) : ?>
<h3><?php echo $post['title']; ?></h3>
<small class="post-date"> Posted on: <?php echo $post['time']; ?></small><br>
<?php echo $post['comment']; ?>
<hr>
<a class="btn btn-default pull-left" href="<?php echo base_url('index.php/Posts/Edit/'.$post['slug']) ?>">Edit</a>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
<input type="submit" value="Delete" class="btn btn-danger">
</form>
<?php endforeach; ?>
<a style="background-color:#005c99;color:#FFF" class="btn btn-default pull-left" href="<?php echo base_url('index.php/Posts/create/'.$Rid) ?>">New comment </a>
<br>
<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Lists extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('listsModel');
}
function user_reservation_list()
{
$username=$this->session->userdata('username');
$data['dat']=$this->listsModel->user_view_list($username);
$this->load->view('user_reservation_list',$data);
// print_r($res);
}
function cancel_reservation($Did){
// echo $Did;
$res=$this->listsModel->delete_by_user($Did);
if ($res) {
redirect(base_url('/index.php/Lists/user_reservation_list'));
}
}
function Update_reservation($Did){
$data['updateDetail']=$this->listsModel->update_by_user($Did);
$this->load->view('UpdateRes',$data);
}
function Update_reservation_savedata(){
//edit this
$Did = $this->input->post('name');
$data=array(
'CheckIn'=>$this->input->post('txtIn'),
'CheckOut'=>$this->input->post('txtOut'),
'TeleNo'=>$this->input->post('teleNo')
);
//edit this to Did
$this->db->where('Did', $Did);
//edit to res table
$res=$this->db->update('res', $data);
if($res){
redirect(base_url('/index.php/Lists/user_reservation_list'));
}
else{
return false;
}
}
public function view_user_details(){
$res=$this->listsModel->view_reserved_user_details();
if($res){
return $res;
}
else{
return "No data";
}
}
}<file_sep><?php
class fileupload extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('uploadModel');
}
//upload picture
public function uploadPicture(){
$id = "file";
$path="img1br1com";
if($_FILES[$id]["name"]==""){
return;
}
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES[$id]["name"]);
$file_extension = end($temporary);
if ($_FILES[$id]["error"] > 0)
{
$alert = "Return Code: " . $_FILES[$id]["error"] . "<br/><br/>";
echo $alert;
return;
}
else
{
$sourcePath = $_FILES[$id]['tmp_name']; // Storing source path of the file in a variable
$targetPath = str_replace("1br1", "/", $path)."/".$_FILES['file']['name'];
move_uploaded_file($sourcePath,$targetPath);
//set path in the database
if($this->uploadModel->setPicturePath($targetPath)){
echo "uploaded";
}else{
echo "uploading error occured";
}
}
}
public function updatePicture(){
$id = "file";
$path="img1br1com";
if($_FILES[$id]["name"]==""){
return;
}
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES[$id]["name"]);
$file_extension = end($temporary);
if ($_FILES[$id]["error"] > 0)
{
$alert = "Return Code: " . $_FILES[$id]["error"] . "<br/><br/>";
echo $alert;
return;
}
else
{
$sourcePath = $_FILES[$id]['tmp_name']; // Storing source path of the file in a variable
$targetPath = str_replace("1br1", "/", $path)."/".$_FILES['file']['name'];
move_uploaded_file($sourcePath,$targetPath);
//set path in the database
if($this->uploadModel->updatePicturePath($targetPath)){
echo "uploaded";
}else{
echo "uploading error occured";
}
}
}
}<file_sep><?php
class uploadModel extends CI_Model{
function __construct(){
parent::__construct();
}
function setPicturePath($targetPath){
echo $targetPath;
$query=$this->db->query("SELECT Rid FROM reservation");
$Rid="";
foreach ($query->result() as $row1) {
$Rid=$row1->Rid;
}
$data=array(
'ImagePath'=>$targetPath
);
$this->db->where('Rid', $Rid);
$res=$this->db->update('reservation', $data);
// $data=array(
// 'complaint_id'=>$this->session->userdata('complaint_no'),
// 'path'=>$targetPath
// );
// $res=$this->db->insert('images',$data);
if($res){
return true;
}
else{
return false;
}
}
function updatePicturePath($targetPath){
echo $targetPath;
$Rid=$this->session->userdata('Rid');
$data=array(
'ImagePath'=>$targetPath
);
$this->db->where('Rid', $Rid);
$res=$this->db->update('reservation', $data);
if($res){
return true;
}
else{
return false;
}
}
}<file_sep><?php
class Posts extends CI_Controller{
public function index( ){
$this->load->model("Post_model");
$data['title'] = 'Rates and Reviews';
$data['posts'] = $this->Post_model->get_posts();
$this-> load->view('templates/header');
$this-> load->view('post/index',$data);
$this-> load->view('templates/footer');
}
public function create($Rid){
$this->load->model("Post_model");
$data['Rid']=$Rid;
$data['title'] = 'Create Post';
// $this-> form_validation-> set_rules('name', 'Name', 'required');
// $this->form_validation->set_rules('title', 'Title', 'required');
// $this->form_validation->set_rules('body', 'Body', 'required');
$this->load->view('post/create',$data);
// if($this->form_validation->run()=== FALSE){
// $this->load->view('post/create',$data);
// }
// else{
// $this->Post_model->create_post();
// redirect(posts);
// }
}
public function add(){
$this->load->model("Post_model");
$data['title'] = 'Create Post';
$Rid=$this->input->post('Rid');
// $this-> form_validation-> set_rules('name', 'Name', 'required');
// $this->form_validation->set_rules('title', 'Title', 'required');
// $this->form_validation->set_rules('body', 'Body', 'required');
$this->Post_model->create_post();
redirect(base_url('/index.php/Book/viewAll/'.$Rid));
// if($this->form_validation->run()=== FALSE){
// $this->load->view('post/create',$data);
// }
// else{
// $this->Post_model->create_post();
// redirect(posts);
// }
}
public function delete($id){
$this->load->model("Post_model");
$this->Post_model->delete_post($id);
redirect(posts);
}
public function Edit($slug){
$this->load->model("Post_model");
$data['post'] = $this->Post_model->get_posts($slug);
if(empty($data['post'])){
show_404();
}
$data['title'] ='Edit Post';
$this->load->view('post/edit', $data);
}
public function update(){
$this->load->model("Post_model");
$this->Post_model->update_post();
redirect('posts');
}
}<file_sep><html >
<head>
<title>Edit your Review</title>
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
</head>
<body style="font-family:'Times New Roman', Times, serif;
font-weight:900;
font-size:15px;
color:#006;
background-color:#e6e6ff">
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div class="container">
<h2><?= $title ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php echo $post['id']; ?>">
<div class="form-group">
<label>Rate Your Stay </label>
</div>
<!--<div class="form-group">
<label>Full name </label>
<input type="text" class="form-control" name="name" placeholder="Type your name" />
</div>
<div class="form-group">
<label>Date of arrival </label>
<input type="text" class="form-control" name="date" />
</div> -->
<div class="form-group">
<label>Title your review </label>
<input type="text" class="form-control" name="title" placeholder="Add Title" value="<?php echo $post['title']; ?>" />
</div>
<div class="form-group">
<label>Your Review </label>
<textarea class="form-control" name="body" placeholder="Add Your Comment"><?php echo $post['comment']; ?></textarea>
</div>
<button type="submit" class="btn btn-default">ADD Comment</button>
</form>
</div>
<br><br><br><br><br><br><br><br><br><br><br>
<div class="container" id="footer" style="max-width:100%;height:54px;margin-bottom:none">
<p style="margin-top:17px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html><file_sep><?php
/**
*
*/
class RegisterModel extends CI_Model
{
public function __construct(){
parent::__construct();
}
public function make_rent(){
$availabilty='yes';
// print_r($url);
// echo "hey";
$url="ada";
$status="pending";
$username=$this->session->userdata('username');
$data = array(
//'name' => $this -> input->post('name'),
//'renterName'=>$this-> input-> post('name'),
'Destination'=>$this->input->post('city'),
'Availability'=> $availabilty,
'ImagePath'=> $url,
'LodgeName'=>$this->input->post('lname'),
'address1'=>$this->input->post('address1'),
'address2'=>$this->input->post('address2'),
'NumRooms'=>$this->input->post('select'),
'price'=>$this->input->post('price'),
'description'=>$this->input->post('des'),
'status'=>$status,
'username'=>$username
);
$res=$this-> db-> insert('reservation' , $data);
return($res);
}
}
?><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Make Rent out</title>
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<link rel="stylesheet" href="<?php echo base_url('assets/reg.css');?>">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body style="background-color:#e6e6ff">
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1 style="float:left">
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="<?php echo base_url('index.php/Mylogin/login');?>">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div style="margin-top:30px"class="container">
<h2 style="font-size:16px;font-weight:bold;font-family:Verdana;text-align:center;margin-bottom:1px"><?= $title ?></h2>
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('RegisterCntrol/create'); ?>
<!--<div class="form-group">
<label>Renter Name :</label>
<input type="text" class="form-control" name="name"/>
</div>-->
<div class="form-group" >
<label style="margin-top:15px">Address Line 1:</label>
<input style="width:300px;height:35px"type="text" class="form-control" name="address1"/>
</div>
<div class="form-group">
<label>Address Line 2:</label>
<input style="width:300px;height:35px" type="text" class="form-control" name="address2"/>
</div>
<div class="form-group">
<label>City:</label>
<input style="width:300px;height:35px" type="text" class="form-control" name="city"/>
</div>
<div class="form-group">
<label>Price:</label>
<input style="width:300px;height:35px"type="text" class="form-control" name="price"/>
</div>
<div class="form-group">
<label>Lodge Name :</label>
<input style="width:300px;height:35px"type="text" class="form-control" name="lname"/>
</div>
<div class="form-group">
<label>Number Of Rooms</label>
<select style="width:300px;height:40px" class="form-control" name="select">
<option>Number Of Rooms</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<p> </p>
<div class="form-group">
<label>Description :</label>
<textarea rows="4" colums ="30" type="text" class="form-control" name="des"/></textarea>
</div>
<!-- <label>Images :</label>
<br> -->
<p> </p>
<button style="width:110px;float:left;background-color: #005c99" type="submit" class="btn btn-default" name="btnAdd">Next</button>
<button style="width:110px;float:right;background-color: #005c99" type="submit" class="btn btn-default" name="btnAdd" onClick="window.location.href = '<?php echo base_url();?>index.php/Renterlists/lists';return false;" >View All</button>
</div>
<br><br><br><br><br><br>
<div class="container" id="footer" style="max-width:100%;height:43px;margin-bottom:none;">
<p>CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
<script>
function uploadfile(){
// Function to preview image after validation
$.ajax({
url: "<?php echo base_url('index.php/fileupload/uploadPicture'); ?>", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(document.getElementById("uploadimage")), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
},error:function(xhr, textStatus, errorThrown){
alert("error");
}
});
}
</script>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div id="me">
<?php
foreach ($dat as $object) {
echo $object->Destination.'<br/>';
$a=$object->ImagePath;
?>
<img src="<?php echo base_url($a);?>">
<?php
}
echo '<br/><br/><br/>';
foreach ($ava as $object1) {
echo $object1->Availability.'<br/>';
echo $object1->Destination.'<br/>';
$a=$object1->ImagePath;
?>
<img src="<?php echo base_url($a);?>">
<?php
}
?>
</div>
</body>
</html><file_sep><?php
class listsModel extends CI_Model
{
function user_view_list($username)
{
// echo $username;
$query=$this->db->query("SELECT * FROM reservation as r INNER JOIN res as re on r.Rid= re.Rid WHERE re.username= ? ",array($username));
// get the reservation details and the hotel details reserved by a pirticular user
if($query->num_rows()>0)
{
return $query->result();
// return array of object
}
else
{
return $query->result();
}
}
function delete_by_user($Did){
$x="yes";
$Rid="";
$query1=$this->db->query("SELECT * FROM res WHERE Did= ? ",array($Did));
foreach ($query1->result() as $row1) {
$Rid=$row1->Rid;
}
$data=array(
'Availability'=>$x
);
$this->db->where('Rid', $Rid);
$res=$this->db->update('reservation', $data);
if($res){
$query=$this->db->query("DELETE FROM res WHERE Did= ? ",array($Did));
return $query;
}
else{
return false;
}
}
function Update_by_user($Did){
$query=$this->db->query("SELECT * FROM res WHERE Did= ? ",array($Did));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function view_reserved_user_details(){
$name=$this->input->post('cpno');
$query=$this->db->query("SELECT * FROM register WHERE Username= ? ",array($name));
echo "<div class='box-body'><dl class='dl-horizontal'>" ;
foreach ($query->result() as $row) {
echo "<h6>User Details</h6><br/>";
echo "<dt>User id</dt>";
echo "<dd>".$row->Rid."</dd>";
echo "<dt>First name</dt>";
echo "<dd>".$row->firstName."</dd>";
echo "<dt>Last name</dt>";
echo "<dd>".$row->lastName."</dd>";
echo "<dt>Email</dt>";
echo "<dd>".$row->Email."</dd>";
echo "<dt>Telephone</dt>";
echo "<dd>".$row->Telephone."</dd>";
echo "<dt>Address 1</dt>";
echo "<dd>".$row->Add1."</dd>";
echo "<dt>Address 2</dt>";
echo "<dd>".$row->Add2."</dd>";
echo "<dt>City</dt>";
echo "<dd>".$row->City."</dd>";
echo "<dt>Username</dt>";
echo "<dd>".$row->Username."</dd>";
}
echo "</dl></div>";
}
}<file_sep><?php
class managerlistModel extends CI_Model
{
function new_rentout()
{
$status="pending";
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? ",array($status));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function accept_rentout()
{
$status="accept";
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? ",array($status));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function reject_rentout()
{
$status="reject";
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? ",array($status));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function view_reserved_user_details(){
$name=$this->input->post('cpno');
$query=$this->db->query("SELECT * FROM register WHERE Username= ? ",array($name));
echo "<div class='box-body'><dl class='dl-horizontal'>" ;
foreach ($query->result() as $row) {
echo "<h6>Renter Details</h6><br/>";
echo "<dt>Renter id</dt>";
echo "<dd>".$row->Rid."</dd>";
echo "<dt>First name</dt>";
echo "<dd>".$row->firstName."</dd>";
echo "<dt>Last name</dt>";
echo "<dd>".$row->lastName."</dd>";
echo "<dt>Email</dt>";
echo "<dd>".$row->Email."</dd>";
echo "<dt>Telephone</dt>";
echo "<dd>".$row->Telephone."</dd>";
echo "<dt>Address 1</dt>";
echo "<dd>".$row->Add1."</dd>";
echo "<dt>Address 2</dt>";
echo "<dd>".$row->Add2."</dd>";
echo "<dt>City</dt>";
echo "<dd>".$row->City."</dd>";
echo "<dt>Username</dt>";
echo "<dd>".$row->Username."</dd>";
}
echo "</dl></div>";
}
}<file_sep><?php
class renterReservationModel extends CI_Model
{
function user_view_list($username)
{
$query=$this->db->query("SELECT * FROM reservation as r INNER JOIN res as re on r.Rid= re.Rid WHERE r.username= ?",array($username));
// get the reservation details and the hotel details reserved by a every user
if($query->num_rows()>0)
{
return $query->result();
// return array of object
}
else
{
return $query->result();
}
}
}<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Book extends CI_Controller
{
function index($des)
{
$data['des']=$des;
$query1=$this->db->query("SELECT * FROM reservation WHERE Rid= ? ",array($des));
$data['res']=$query1->result();
if($this->session->userdata('username')!='')
{
$name=$this->session->userdata('username');
$query2=$this->db->query("SELECT * FROM register WHERE Username= ? ",array($name));
$data['user']=$query2->result();
$this->load->view('AB',$data);
}
else
{
redirect(base_url('/index.php/Book_login/login'));
}
}
function viewall($des)
{
$this->load->model("Dat_Model");
$data['res']=$this->Dat_Model->viewAll($des);
$data['title'] = 'Rates and Reviews';
$this->load->view('viewall',$data);
$this->load->model("Post_model");
$Rid=$des;
$slug = FALSE;
$data['posts'] = $this->Post_model->get_posts($slug,$Rid);
$this->load->view('templates/header');
$data['Rid']=$Rid;
$this->load->view('post/index',$data);
// add review
$blog_id = $des;
$this->load->model('blogmodel');
$vote_results = $this->blogmodel->get_blog_rating($blog_id);
$data['blog_vote_overall_rows'] = $vote_results['vote_rows'];
$data['blog_vote_overall_rate'] = $vote_results['vote_rate'];
$data['blog_vote_overall_dec_rate'] = $vote_results['vote_dec_rate'];
$vote_results = $this->blogmodel->get_blog_rating_from_ip($blog_id);
$data['blog_vote_ip_rate'] = $vote_results['vote_rate'];
// $this->load->view('blog', $data);
$this->load->view('rating/x/index',$data);
}
// function cancel_reservation($Did){
// echo $Did;
// }
}
<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">
<title>MyLogin | <?php echo $title; ?></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
body
{
font-family:Verdana;
font-size:15px;
height: 100px;
}
@media(min-width:340px)
{
.container{max-width:340px};
}
div#back_glob
{
background-color:white;
border:1px solid #25b2d5;
vertical-align: middle;
width: 300px;
height: 250px;
margin-left: 360px;
box-shadow:1px 0px 15px #25b2d5;
}
input
{
display:block;
margin:10px;
}
div#back_header
{
background-color:#25b2d5;
text-align:center;
font-size:22px;
font-weight:bold;
color:white;
padding:20px;
}
input[type=text],input[type=password],
{
padding:20px;
border-radius:3px;
font-size:14px;
border:1px solid #ddd;
}
input[type=submit]
{
/*;*/
/*margin:48px;*/
/*margin-left:10px; */
margin-top:10px;
background-color:25b2d5;
padding:5px 10px 5px 10 px;
border-radius:3px;
border:1px solid #319db8;
color:white;
font-weight:bold;
}
button
{
/*;*/
/*margin:48px;*/
/*margin-left:10px; */
margin-top:10px;
background-color:25b2d5;
padding:5px 10px 5px 10 px;
border-radius:3px;
border:1px solid #319db8;
color:white;
font-weight:bold;
}
div#back_form
{
display:flex;
vertical-align: middle;
margin-top: auto;
justify-content:center;
}
</style>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<script type="text/javascript"></script>
</head>
<body>
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div class="container">
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<div id="back_glob">
<div id="back_header">
LOGIN
</div>
<div id="back_form" >
<form method="post" action="<?php echo base_url('index.php/Book_login/login_validation');?>">
<input style="margin-top:50px; height:25px;-moz-border-radius:5px;
-webkit-border-radius:5px" type="text" name="username" placeholder="Username"/>
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input style="height:25px; -moz-border-radius:6px;
-webkit-border-radius:5px" type="<PASSWORD>" name="pass" placeholder="<PASSWORD>"/>
<span class="text-danger"><?php echo form_error('pass'); ?></span>
<div class="row" >
<div class="col-sm-6">
<input style="float:left" type="submit" name="valid" vlaue="Login" />
<?php
echo '<label class="text-danger">'.$this->session->flashdata('error');
?>
</div>
<div class="col-sm-6" >
<button style="float:right" onClick="window.location.href = '<?php echo base_url();?>index.php/RegisterC';return false;">Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
<br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br>
<br>
<br>
<div class="container" id="footer" style="max-width:100%">
<p>CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class CheckD extends CI_Controller
{
function myDate()
{
$this->load->model('getcitiesModel');
$res=$this->getcitiesModel->city();
$data['cities']=$res;
$this->load->view('Home',$data);
$this->load->library('form_validation');
$this->form_validation->set_rules('txtDate','CHECKIN','callback_compareDate');
$this->form_validation->set_rules('txtCheckOut','CHECKOUT','callback_compareDate');
$this->form_validation->set_rules('opt','OPT','required');
}
}<file_sep><html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
<link href='http://fonts.googleapis.com/css?family=Marcellus' rel='stylesheet' type='text/css'/>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<link rel="stylesheet" href="<?php echo base_url('assets/style.css');?>">
</head>
<body style=" background-color:#e6e6ff">
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1 style="float:left">
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div id="container">
<?php echo form_open('RegisterC') ; ?>
<h1 style="color: #009">REGISTER</h1><hr/>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER><br>
<?php } ?>
<?php echo form_label('First Name :'); ?> <?php echo form_error('fname'); ?><br />
<?php echo form_input(array('id' => 'fname', 'name' => 'fname')); ?><br />
<?php echo form_label('Last Name :'); ?> <?php echo form_error('lname'); ?><br />
<?php echo form_input(array('id' => 'lname', 'name' => 'lname')); ?><br />
<?php echo form_label('Email :'); ?> <?php echo form_error('demail'); ?><br />
<?php echo form_input(array('id' => 'demail', 'name' => 'demail')); ?><br />
<?php echo form_label('Mobile No. :'); ?> <?php echo form_error('dmobile'); ?><br />
<?php echo form_input(array('id' => 'dmobile', 'name' => 'dmobile', 'placeholder' => '10 Digit Mobile No.')); ?><br />
<?php echo form_label('Address 1 :'); ?> <?php echo form_error('Faddress'); ?><br />
<?php echo form_input(array('id' => 'Faddress', 'name' => 'Faddress')); ?><br />
<?php echo form_label('Address 2 :'); ?> <?php echo form_error('Saddress'); ?><br />
<?php echo form_input(array('id' => 'Saddress', 'name' => 'Saddress')); ?><br />
<?php echo form_label('City:'); ?> <?php echo form_error('city'); ?><br />
<?php echo form_input(array('id' => 'city', 'name' => 'city')); ?><br />
<?php echo form_label('User name:'); ?> <?php echo form_error('Uname'); ?><br />
<?php echo form_input(array('id' => 'Uname', 'name' => 'Uname')); ?><br />
<?php echo form_label('Password:'); ?> <?php echo form_error('pass'); ?><br />
<?php echo form_input(array( 'id' => 'pass', 'name' => 'pass','type'=>'password')); ?><br />
<?php echo form_label('Confirm Password:'); ?> <?php echo form_error('conf'); ?><br />
<?php echo form_input(array( 'id' => 'conf', 'name' => 'conf','type'=>'password' )); ?><br />
<select style="-moz-border-radius:5px;
-webkit-border-radius:5px ; "name="selection1" id="selection1">
<option value="Renter">Renter</option>
<option value="Tourist">Tourist</option>
</select>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
<?php echo form_close(); ?><br/>
<div id="fugo">
</div>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div class="container" id="footer" style="max-width:100%;height:40px;margin-bottom:none;float:left">
<p style="padding-top:5px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html><file_sep><?php
class Dat_Model extends CI_Model
{
// function datee($startDate,$des)
// {
// $No="No";
// $query=$this->db->query("SELECT * FROM reservation as r INNER JOIN res as re on r.Rid= re.Rid WHERE r.Availability= ? and r.Destination= ? and re.CheckOut<? ",array($No,$des,$startDate));
// if($query->num_rows()>0)
// {
// return $query->result();
// }
// else
// {
// return $query->result();
// }
// }
function compare($startDate,$endDate,$des)
{
$No="No";
//$query=$this->db->query("SELECT * FROM reservation as r INNER JOIN res as re on r.Rid= re.Rid WHERE r.Availability= ? and r.Destination= ? and re.CheckOut<? ",array($No,$des,$startDate));
$query=$this->db->query("SELECT * FROM reservation WHERE Availability= ? and Destination= ? ",array($No,$des));
foreach ($query->result() as $row) {
$Rid=$row->Rid;
$row->flag="YES";
$query1=$this->db->query("SELECT * FROM res WHERE Rid= ? ",array($Rid));
foreach($query1->result() as $row1) {
$cin=$row1->CheckIn;
$cout=$row1->CheckOut;
if (($cout >= $startDate) && ($cin <= $startDate)) {
$row->flag="NO";
}
if (($cout >= $endDate) && ($cin <= $endDate)) {
$row->flag="NO";
}
}
}
return $query->result();
}
function Avail($valuee)
{
$yes="yes";
// $this->db->select('*');
// $this->db->from('reservation');
// $this->db->where('Availability',$yes AND 'Destination',$valuee);
$query=$this->db->query("SELECT * FROM reservation WHERE Availability='".$yes."' AND Destination='".$valuee."' ");
foreach ($query->result() as $row2 ) {
$row2->flag="YES";
}
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function viewAll($des)
{
// echo $des;
$query=$this->db->query("SELECT * FROM reservation WHERE Rid='".$des."' ");
// $query=$this->db->get();
if($query->num_rows()>0)
{
// echo "yes";
return $query->result();
}
else
{
return $query->result();
}
}
}<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Cbook extends CI_Controller
{
function mybook()
{
$username=$this->session->userdata('username');
$data = array(
'CheckIn' => $this->input->post('txtIn'),
'CheckOut' => $this->input->post('txtOut'),
'Rid' => $this->input->post('name'),
'TeleNo' => $this->input->post('teleNo'),
'username'=>$username
);
//Transfering data to Model
$this->db->insert('res', $data);
$no=$this->input->post('name');
$x="No";
$data1=array(
'Availability'=>$x,
);
$this->db->where('Rid', $no);
$res=$this->db->update('reservation', $data1);
$this->load->view('thankyou');
}
}<file_sep>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title></title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
</head>
<body style="font-family:'Times New Roman', Times, serif;
font-weight:900;
font-size:15px;
color:#006;
background-color:#e6e6ff">
<header style="margin-top:-20px;margin-left:-20px"id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br><br><br>
<?php
function db_connect(){
$server_name = "localhost";
$user_name = "root";
$password = "";
$db_name = "ci_b";
$db = new mysqli($server_name, $user_name, $password, $db_name);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
return $db;
}
$db = db_connect();
mysqli_query($db,"set character_set_results='utf8'");
foreach ($res as $object1) {
$des= $object1->Destination;
$a=$object1->ImagePath;
$id=$object1->Rid;
$name=$object1->LodgeName;
$add1=$object1->Address1;
$add2=$object1->Address2;
$rooms=$object1->NumRooms;
$price=$object1->Price;
$description=$object1->description;
?>
<div id="picA"><img style="margin-left:-20px" src="<?php echo base_url($a);?>" width="103%" height="500px"></div>
<div class="row">
<div class="col-md-8">
<div id="desA"><h3 ><?php echo $name.' '.$des; ?></h3>
<?php
$id=$object1->Rid;
$sql = 'SELECT COUNT(DISTINCT(vote_id)) total_rows,IFNULL(SUM(blog_vote),0) total_rating, blog_id
FROM blog_vote
WHERE blog_id='.$id.' LIMIT 1';
$result3 = $db->query($sql);
$row =$result3->fetch_assoc();
$total_rows = $row['total_rows'];
$total_rating = $row['total_rating'];
$results['vote_rows'] = $total_rows;
$rating = 0;
if ($total_rows > 0) {
$rating = $total_rating / $total_rows;
}
$dec_rating = round($rating, 1);
//echo $dec_rating;
$starNumber=$dec_rating;
for($x=1;$x<=$starNumber;$x++) {
echo '<img src="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678064-star-128.png" style="width:35px" />';
}
if (strpos($starNumber,'.')) {
echo '<img src="https://cdn4.iconfinder.com/data/icons/pretty_office_3/256/Star-Half-Full.png" style="width:35px"/>';
$x++;
}
while ($x<=5) {
echo '<img src="http://time-static-shared.s3-website-us-east-1.amazonaws.com/interactives/how_american_are_you/images/white-star-md.png" style="width:35px" />';
$x++;
}
?>
</div>
</div>
</div>
<p><?php echo $add1; ?></p>
<p><?php echo $add2; ?></p>
<p><?php echo $rooms; ?></p>
<p><?php echo $price; ?></p>
<p><?php echo $description; ?></p>
<div id= "priceA">
<p>
<a style="background-color:#005c99;color:#FFF" class="btn btn-default pull-left" href="<?php echo base_url('index.php/Book/index/'.$id) ?>">Book Now </a>
</p>
</div>
<?php
}
?>
</body>
</html><file_sep><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Make Rent out</title>
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css">
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<link rel="stylesheet" href="<?php echo base_url('assets/reg.css');?>">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body style="background-color:#e6e6ff">
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1 style="float:left">
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div style="margin-top:30px"class="container">
<h2 style="font-size:16px;font-weight:bold;font-family:Verdana;text-align:center;margin-bottom:1px">One more step ad you are finished</h2>
<form id="uploadimage" enctype='multipart/form-data'>
<div class="form-group">
<input type="file" name="file" id="file">
</div>
<div class="form-group">
<input style="width:110px;float:left;background-color: #005c99" type="button" name="" class="btn btn-default" onclick="uploadfile()" value="upload">
<button style="width:110px;float:right;background-color: #005c99" type="submit" class="btn btn-default" name="btnAdd" onClick="window.location.href = '<?php echo base_url();?>index.php/Renterlists/lists';return false;" >View All</button>
</div>
</form>
</div>
<br><br><br><br><br><br>
<div class="container" id="footer" style="max-width:100%;height:45px;margin-top:280px;">
<p>CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
<script>
function uploadfile(){
// Function to preview image after validation
$.ajax({
url: "<?php echo base_url('index.php/fileupload/uploadPicture'); ?>", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(document.getElementById("uploadimage")), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
},error:function(xhr, textStatus, errorThrown){
alert("error");
}
});
}
</script>
</html>
<file_sep><?php
class RegisterC extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('RegModel');
}
function index() {
//Including validation library
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('fname', 'Username', 'required');
$this->form_validation->set_rules('lname', 'LastName', 'required');
//Validating Email Field
$this->form_validation->set_rules('demail', 'Email', 'required|valid_email');
//Validating Mobile no. Field
$this->form_validation->set_rules('dmobile', 'Mobile No.', 'required|regex_match[/^[0-9]{10}$/]');
//Validating Address Field
$this->form_validation->set_rules('Faddress', 'Address', 'required');
$this->form_validation->set_rules('Saddress', 'Last_address', 'required');
$this->form_validation->set_rules('city', 'City', 'required');
$this->form_validation->set_rules('Uname', 'UserName', 'required');
$this->form_validation->set_rules('pass', '<PASSWORD>', '<PASSWORD>');
//Validate Confirm Password field
$this->form_validation->set_rules('conf', 'ConfPass', 'required|matches[pass]');
$this->form_validation->set_rules('selection1','Menu','required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('Register');
}
else
{
//Setting values for tabel columns
$data = array(
'firstName' => $this->input->post('fname'),
'lastName' => $this->input->post('lname'),
'Email' => $this->input->post('demail'),
'Telephone' => $this->input->post('dmobile'),
'Add1' => $this->input->post('Faddress'),
'Add2' => $this->input->post('Saddress'),
'City' => $this->input->post('city'),
'Username' => $this->input->post('Uname'),
'Password' => $<PASSWORD>('<PASSWORD>'),
'role'=>$this->input->post('selection1'),
);
//Transfering data to Model
$this->RegModel->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('Register', $data);
}
}
}
?><file_sep><html>
<head>
<title>B&B</title>
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>/assets/css/style.css">
</head>
<body>
<div class="container"><file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class ManagerReservation extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('managerReservationModel');
}
function user_reservation_list()
{
// $username=$this->session->userdata('username');
$data['dat']=$this->managerReservationModel->user_view_list();
$this->load->view('manager_reservation_list',$data);
// print_r($res);
}
public function view_user_details(){
$res=$this->managerReservationModel->view_reserved_user_details();
if($res){
return $res;
}
else{
return "No data";
}
}
}<file_sep><?php
class Me extends CI_Controller{
public function index1()
{
echo "This is my index function";
}
public function one()
{
echo "This is two";
}
}
<file_sep><?php
class renterlistsModel extends CI_Model
{
function pending_rentout()
{
$status="pending";
$username=$this->session->userdata('username');
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? AND username= ? ",array($status,$username));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function accept_rentout()
{
$status="accept";
$username=$this->session->userdata('username');
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? AND username= ? ",array($status,$username));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function reject_rentout()
{
$status="reject";
$username=$this->session->userdata('username');
$query=$this->db->query("SELECT * FROM reservation WHERE status= ? AND username= ? ",array($status,$username));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function UpdateRentOuts($id){
$session_data= array('Rid' =>$id);
$this->session->set_userdata($session_data);
$query=$this->db->query("SELECT * FROM reservation WHERE Rid= ? ",array($id));
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return $query->result();
}
}
function deleteRent($id){
$query=$this->db->query("DELETE FROM reservation WHERE Rid= ? ",array($id));
return $query;
}
}<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<style>
input[type="Date"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
input[type="Text"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
</style>
</head>
<body style="font-family:Verdana;
font-size:15px;
background-color:#e6e6ff;
">
<header style="height:68px"id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<?php echo validation_errors(); ?>
<form
style="margin-top:120px;border:1px solid #ccc;
box-shadow:0 1px 25px;width:450px;margin-left:400px;background-color:#FFF"
id="form1" name="form1" method="post" action="<?php echo base_url('index.php/PaymentsCon/cardnumber_validation');?>">
<table width="281" border="0" align="center">
<tr>
<p style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">Reservation</p>
<h2 style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">User name: <?php echo $user[0]->firstName." ".$user[0]->lastName?></h2>
<p style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">Email: <?php echo $user[0]->Email?></p>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Name of Card</p></td>
<td width="170"><label for="LisName"></label>
<select class="form-control select2" style="width: 100%;" name="name">
<option value="Master Card">MasterCard</option>
<option value="Visa Card">Visa Card</option>
<option value="American Express">Discover</option>
</select>
<!-- <input style="margin-top:8px" value="" type="text" name="name" id="txtName" /></td> -->
</tr>
<tr>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Card Number</p></td>
<td width="170"><label for="LisNo"></label>
<input style="margin-top:8px" value="" type="text" name="cardnumber" id="txtNo" /></td>
</tr>
<tr>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">CSC</p></td>
<td width="170"><label for="LisNo"></label>
<input style="margin-top:8px" value="" type="text" name="CSC" id="txtNo" /></td>
</tr>
<tr>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Exp Date</p></td>
<td width="170"><label for="LisNo"></label>
<input style="margin-top:8px" value="" type="month" name="exp" id="txtNo" /></td>
</tr>
<tr>
<td></td>
<td>
<input style="width:120px;float:left;-webkit-border-radius:3px;height:35px;margin-bottom:20px;background-color: #005c99;color:#FFF"
type="submit" name="btnRes" id="btnRes" value="Book"/>
</tr>
</table>
</form>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div class="container" id="footer" style="max-width:100%;height:54px;margin-bottom:none">
<p style="padding-top:20px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><h2><?= $title ?></h2>
<body>
<form>
<div class="form-group">
<label>Rate Your Stay </label>
</div>
<div class="form-group">
<label>Full name </label>
<input type="text" class="form-control" name="name" placeholder="Type your name" />
</div>
<div class="form-group">
<label>Date of arrival </label>
<input type="text" class="form-control" name="date" />
</div>
<div class="form-group">
<label>Title your review </label>
<input type="text" class="form-control" name="title" placeholder="Add Title" />
</div>
<div class="form-group">
<label>Your Review </label>
<textarea class="form-control" name="body" placeholder="Add Your Comment"></textarea>
</div>
<button type="submit" class="btn btn-default">ADD Comment</button>
</form>
</body><file_sep><!DOCTYPE html>
<html class="ng-scope" ng-app=""><head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>Simple Rating System in JQuery, CSS, PHP, MySQL :devzone.co.in</title>
<style type="text/css">.main {
width: auto;
}
#dv1, #dv0{
width: 408px;
/*border: 1px #ccc solid;*/
padding: 0px;
}
/*downloaded from http://devzone.co.in*/
</style>
<style>
/****** Rating Starts *****/
@import url(http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css);
fieldset, label { margin: 0; padding: 0; }
body{ margin: 20px; }
h1 { font-size: 1.5em; }
.rating {
border: none;
float: left;
}
.rating > input { display: none; }
.rating > label:before {
margin: 0px;
font-size: 1.25em;
font-family: FontAwesome;
display: inline-block;
content: "\f005";
}
.rating > .half:before {
content: "\f089";
/*/position: absolute;*/
}
.rating > label {
color: #ddd;
float: right;
}
.rating > input:checked ~ label,
.rating:not(:checked) > label:hover,
.rating:not(:checked) > label:hover ~ label { color: #FFD700; }
.rating > input:checked + label:hover,
.rating > input:checked ~ label:hover,
.rating > label:hover ~ input:checked ~ label,
.rating > input:checked ~ label:hover ~ label { color: #FFED85; }
/* Downloaded from http://devzone.co.in/ */
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="<?php echo base_url('assets/views/rating/x/index_files/ca-pub-2074772727795809.js');?>" type="text/javascript" async=""></script><script src="index_files/analytics.js" async=""></script>
</head>
<body>
<!-- ad1 start -->
<div style="width:170px;margin:0 auto;float: left;position:fixed;">
<script async="" src="index_files/adsbygoogle.js"></script>
<!-- 160x600_verticle -->
<ins data-adsbygoogle-status="done" class="adsbygoogle" style="display:inline-block;width:160px;height:600px" data-ad-client="ca-pub-2074772727795809" data-ad-slot="3439042376"><ins id="aswift_0_expand" style="display:inline-table;border:none;height:600px;margin:0;padding:0;position:relative;visibility:visible;width:160px;background-color:transparent"><ins id="aswift_0_anchor" style="display:block;border:none;height:600px;margin:0;padding:0;position:relative;visibility:visible;width:160px;background-color:transparent"></ins></ins></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<!-- ad1 end http://DevZone.co.in-->
<div class="main">
<div class="content">
<div id="dv0"></div>
<div id="dv1" style="folat: left;">
<!-- Demo 1 start -->
<h1>Add your rate</h1>
<script>
$(document).ready(function () {
$("#demo1 .stars").click(function () {
<?php
$id=0;
foreach ($res as $object1) {
$a=$object1->ImagePath;
$id=$object1->Rid;
}
$des=$id; ?>
$.post( "<?php echo base_url('index.php/BlogController/rate_s/'.$des); ?>",{rate:$(this).val()},function(d){
if(d>0)
{
alert('You already rated');
}else{
alert('Thanks For Rating');
}
});
$(this).attr("checked");
});
});
</script>
<fieldset id='demo1' class="rating">
<input class="stars" type="radio" id="star5" name="rating" value="5" />
<label class = "full" for="star5" title="Awesome - 5 stars"></label>
<input class="stars" type="radio" id="star4" name="rating" value="4" />
<label class = "full" for="star4" title="Pretty good - 4 stars"></label>
<input class="stars" type="radio" id="star3" name="rating" value="3" />
<label class = "full" for="star3" title="Meh - 3 stars"></label>
<input class="stars" type="radio" id="star2" name="rating" value="2" />
<label class = "full" for="star2" title="Kinda bad - 2 stars"></label>
<input class="stars" type="radio" id="star1" name="rating" value="1" />
<label class = "full" for="star1" title="Sucks big time - 1 star"></label>
</fieldset>
<!-- Demo 3 start -->
<div style='clear:both;'></div>
</div>
<div class="cfmonitor" style="width:700px;margin-top:50px;">
<div style="width:340px;float:left;">
<script async="" src="index_files/adsbygoogle.js"></script>
<!-- 336x280 -->
<ins data-adsbygoogle-status="done" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-2074772727795809" data-ad-slot="3475973578"><ins id="aswift_1_expand" style="display:inline-table;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent"><ins id="aswift_1_anchor" style="display:block;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent"></ins></ins></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div style="width:340px;float:left;">
<script async="" src="index_files/adsbygoogle.js"></script>
<!-- 336x280 -->
<ins data-adsbygoogle-status="done" class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-2074772727795809" data-ad-slot="3475973578"><ins id="aswift_2_expand" style="display:inline-table;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent"><ins id="aswift_2_anchor" style="display:block;border:none;height:280px;margin:0;padding:0;position:relative;visibility:visible;width:336px;background-color:transparent"></ins></ins></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</div>
</div>
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-43091346-1', 'devzone.co.in');
ga('send', 'pageview');
</script></div>
</body></html><file_sep># 3rd-year-ITPDM-me
sample for B&B hotel reservation system
use CodeIgniter Web Framework, ajax, sql and php
<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">
<title>MyLogin | <?php echo $title; ?></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
body
{
font-family:Verdana;
font-size:15px;
background-color:#e6e6ff;
}
@media(min-width:340px)
{
.container{max-width:340px};
}
div#back_glob
{
background-color:white;
border:1px solid #FFF;
vertical-align: middle;
width: 320px;
height: 288px;
margin-left: 360px;
box-shadow:1px 0px 15px #00134d;
}
input
{
display:block;
margin:10px;
}
div#back_header
{
background-color:#00134d;
text-align:center;
border-radius:3px;
font-size:22px;
font-weight:bold;
color:white;
padding:20px;
}
input[type=text],input[type=password],
{
padding:35px;
border-radius:3px;
font-size:14px;
}
input[type=submit]
{
/*;*/
/*margin:48px;*/
/*margin-left:10px; */
margin-top:20px;
background-color:25b2d5;
padding:5px 10px 5px 10 px;
border-radius:3px;
color:white;
font-weight:bold;
}
button
{
/*;*/
/*margin:48px;*/
/*margin-left:10px; */
margin-top:10px;
background-color:25b2d5;
padding:5px 10px 5px 10 px;
border-radius:3px;
border:1px solid #319db8;
color:white;
font-weight:bold;
height: 25px;
}
div#back_form
{
display:flex;
vertical-align: middle;
margin-top: auto;
justify-content:center;
}
</style>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<script type="text/javascript"></script>
</head>
<body>
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div class="container">
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<div id="back_glob">
<div id="back_header">
LOGIN
</div>
<div id="back_form" >
<form method="post" action="<?php echo base_url('index.php/Mylogin/login_validation');?>">
<input style="margin-top:50px; height:25px;-moz-border-radius:5px;
-webkit-border-radius:5px ; background-color:#b3c6ff;margin-left: 63px"
type="text" name="username" placeholder="Username"/>
<span class="text-danger"><?php echo form_error('username'); ?></span>
<input style="height:25px;margin-top:30px; -moz-border-radius:6px;
-webkit-border-radius:5px;margin-left: 63px; background-color:#b3c6ff"
type="password" name="pass" placeholder="<PASSWORD>"/>
<span class="text-danger"><?php echo form_error('pass'); ?></span>
<div class="row" >
<div class="col-sm-4">
<button style="float:left;border-radius:3px;border:1px solid #319db8;background-color:#005c99;height: 25px;
width:70px;font-size: 11px; "
type="submit" name="valid" vlaue="Login">Login</button>
<span class="text-danger" style=" clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;margin-top:20px"> <?php echo $this->session->flashdata('error');?></span>
</div>
<div class="col-sm-4">
<button style="float:left;border-radius:3px;border:1px solid #319db8;background-color:#005c99;height: 25px;
width:70px;font-size: 11px; "
type="submit" name="valid" vlaue="Logout" onClick="window.location.href = '<?php echo base_url();?>index.php/Mylogin/logout';return false;">Logout</button>
</div>
<div class="col-sm-4" >
<button style="float:right; background-color: #005c99; width:70px;font-size: 11px;"
onClick="window.location.href = '<?php echo base_url();?>index.php/RegisterC';return false;">Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
<br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br> <br>
<br>
<br>
<br>
<br>
<div class="container" id="footer" style="max-width:100%;height:40px;margin-bottom:none">
<p>CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class PaymentsCon extends CI_Controller
{
function Pay()
{
$name=$this->session->userdata('username');
$query2=$this->db->query("SELECT * FROM register WHERE Username= ? ",array($name));
$data['user']=$query2->result();
// $this->load->library('form_validation');
$this->load->view('PaymentsV',$data);
}
function cardnumber_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('cardnumber','CardNumber','required|regex_match[/^[0-9]{16}$/]');
$this->form_validation->set_rules('CSC','CSC','required|regex_match[/^[0-9]{3}$/]');
if($this->form_validation->run()){
$this->load->view('paymentthank');
}else{
$this->Pay();
}
}
}<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="../../../../../../../Users/adm/Downloads/Dw B&B/Dw B&B/Booking.css" rel="stylesheet" type="text/css"/>
<title>Place a Booking</title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
</head>
<body style="font-family:'Times New Roman', Times, serif;
font-weight:900;
font-size:15px;
color:#006;
background-color:#e6e6ff">
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<?php
function db_connect(){
$server_name = "localhost";
$user_name = "root";
$password = "";
$db_name = "ci_b";
$db = new mysqli($server_name, $user_name, $password, $db_name);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
return $db;
}
$db = db_connect();
mysqli_query($db,"set character_set_results='utf8'");
?>
<!-- <div id="container">
<div id="body">
<p></p>
<p><em> Hotels near Kandy , Srilanka</em></p>
<div id="A">
//
<div id="desA"><h3>Kandalama </h3>
</div>
<div id= "priceA">
LKR 10 800
<p></p>
<p>
<input type="button" id="BtnA" value=" Book Now " >
</p>
</div>
</div>
-->
<table class="table">
<!-- <thead>
<tr>
<th></th>
<th></th>
<th>Email</th>
</tr>
</thead> -->
<tbody>
<?php
foreach ($dat as $object) {
$des= $object->Destination.'<br/>';
$a=$object->ImagePath;
$name=$object->LodgeName;
$ad1=$object->Address1;
$ad2=$object->Address2;
$id=$object->Rid;
$price=$object->Price;
$c_in=$object->CheckIn;
$c_out=$object->CheckOut;
$Did=$object->Did;
$user_name=$object->username;
?>
<tr>
<td><div id="picA"><img src="<?php echo base_url($a);?>" width="260" height="125"></div></td>
<td><div id="desA"><h3><?php echo $des; ?></h3>
<?php
$id=$object->Rid;
$sql = 'SELECT COUNT(DISTINCT(vote_id)) total_rows,IFNULL(SUM(blog_vote),0) total_rating, blog_id
FROM blog_vote
WHERE blog_id='.$id.' LIMIT 1';
$result3 = $db->query($sql);
$row =$result3->fetch_assoc();
$total_rows = $row['total_rows'];
$total_rating = $row['total_rating'];
$results['vote_rows'] = $total_rows;
$rating = 0;
if ($total_rows > 0) {
$rating = $total_rating / $total_rows;
}
$dec_rating = round($rating, 1);
//echo $dec_rating;
$starNumber=$dec_rating;
for($x=1;$x<=$starNumber;$x++) {
echo '<img src="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678064-star-128.png" style="width:35px" />';
}
if (strpos($starNumber,'.')) {
echo '<img src="https://cdn4.iconfinder.com/data/icons/pretty_office_3/256/Star-Half-Full.png" style="width:35px"/>';
$x++;
}
while ($x<=5) {
echo '<img src="http://time-static-shared.s3-website-us-east-1.amazonaws.com/interactives/how_american_are_you/images/white-star-md.png" style="width:35px" />';
$x++;
}
?>
</div></td>
<td><div id="desA"><h3><?php echo $name; ?></h3></div>
<p><?php echo $ad1;?></p>
<p><?php echo $ad2;?></p>
</td>
<td><div id="desA"><h3>Dates</h3></div>
<p><?php echo "CheckIn : ".$c_in;?></p>
<p><?php echo "CheckOut : ".$c_out;?></p>
</td>
<td>
<div id= "priceA">
<?php echo $price; ?>
<p></p>
<p>
<a style="background-color:#005c99;color:#FFF" class="btn btn-default pull-left" href="<?php echo base_url('index.php/Book/viewAll/'.$id) ?>">View all </a>
</p>
<ul>
<li onclick="view_user_details('<?php echo $user_name; ?>')"><a href="#">Reserved by</a></li>
</ul>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</div> <!-- Accomodation Catalogue-->
<!-- <footer>End of the page</footer> -->
<!--view all modal-->
<div id="view_all" 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>
<h4 class="modal-title">All details</h4>
</div>
<!--modal body-->
<div class="modal-body" id="view_all_body">
</div>
<!--end of modal body-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
function view_user_details(cp){
$compno=cp;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/Lists/view_user_details'); ?>",
data: "cpno="+cp,
success: function(data) {
//alert("added to database");
$('#view_all_body').html(data);
$('#view_all').modal('show');
},
error: function() {
alert("something went wrong");
}
});
}
</script>
</html>
<file_sep><?php
$overall_vote_rows = $blog_vote_overall_rows;
$overall_vote_rate = $blog_vote_overall_rate;
$overall_vote_dec_rate = $blog_vote_overall_dec_rate;
$ip_vote_rate = $blog_vote_ip_rate;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Voting System</title>
<!--[if IE]> <script> (function() { var html5 = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video").split(','); for (var i = 0; i < html5.length; i++) { document.createElement(html5[i]); } try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} })(); </script> <![endif]-->
<link type="text/css" rel="stylesheet" href="http://localhost:8090/ci_intro/assets/css/blog_rating.css"/>
<script type= 'text/javascript' src="http://localhost:8090/ci_intro/assets/js/jquery-1.9.1.min.js"></script>
<script type= 'text/javascript' src="http://localhost:8090/ci_intro/assets/js/blog_rating.js"></script>
</head>
<body>
<div class='singlepost'>
<div class='fullpost clearfix'>
<div class='entry'>
<h1 class='post-title'>
Ratings
</h1>
<input type="hidden" name="blog_content_id" id="blog_content_id" value="1"/>
<?php
$stars = '';
echo '<div id="ajax_vote">';
for ($i = 0; $i <= floor($overall_vote_rate); $i++) {
$stars .= '<div class="star" id="' . $i . '"></div>';
}
//THE OVERALL RATING (THE OPAQUE STAR
echo $blog_vote_overall_dec_rate;
echo '<div class="r"><div class="rating">' . $stars . '</div>';
//THE TRANSPARENT STARS (OPAQUE STARS WILL COVER AS MANY STARS AS THE RATING REPRESENTS)
echo '<div class="transparent">
<div class="star" id="1"></div>
<div class="star" id="2"></div>
<div class="star" id="3"></div>
<div class="star" id="4"></div>
<div class="star" id="5"></div>
<div class="votes">(' . $blog_vote_overall_dec_rate . '/5, ' . $overall_vote_rows . ' ' . ($overall_vote_rows > 1 ? ' votes' : ' vote') . ') ' . ($blog_vote_ip_rate > 0 ? '<strong>You rated this: <span style="color:#39C;">' . $blog_vote_ip_rate . '</span></strong>' : '') . '</div>
</div>
</div>';
echo '</div>';
?>
<!-- view rating as stars -->
<?php
$starNumber=$blog_vote_overall_dec_rate;
for($x=1;$x<=$starNumber;$x++) {
echo '<img src="https://cdn0.iconfinder.com/data/icons/small-n-flat/24/678064-star-128.png" style="width:35px" />';
}
if (strpos($starNumber,'.')) {
echo '<img src="https://cdn4.iconfinder.com/data/icons/pretty_office_3/256/Star-Half-Full.png" style="width:35px"/>';
$x++;
}
while ($x<=5) {
echo '<img src="http://time-static-shared.s3-website-us-east-1.amazonaws.com/interactives/how_american_are_you/images/white-star-md.png" style="width:35px" />';
$x++;
}
?>
</div>
</body>
</html><file_sep> <?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Book_login extends CI_Controller{
function login()
{
//http://localhost:81/ci_intro/Login/login
$data['title']='LOGIN';
$this->load->view("Booklogin",$data);
}
function login_validation()
{
echo "hey";
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('pass','Password','required');
if($this->form_validation->run())
{
$username= $this->input->post('username');
$password= $this->input->post('pass');
$this->load->model('Login_model');
// echo "in forvalidation";
if($this->Login_model->can_login($username,$password))
{
$session_data= $arrayName = array('username' =>$username);
$this->session->set_userdata($session_data);
echo "sesson created";
//echo $this->session->userdata('username');
redirect(base_url('index.php/Book_login/enter'));
}
else
{
$this->session->set_flashdata('error','Invalid username and password');
redirect(base_url('/index.php/Book_login/login'));
}
}
else
{
$this->login();
}
}
function enter()
{
if($this->session->userdata('username')!='')
{
redirect(base_url('/index.php/CheckD/myDate'));
}
else
{
redirect(base_url('/index.php/Book_login/logout'));
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect(base_url('/index.php/Book_login/login'));
}
}
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<style>
input[type="Date"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
input[type="Text"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
</style>
</head>
<body style="font-family:Verdana;
font-size:15px;
background-color:#e6e6ff;
">
<header style="height:68px"id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div style="text-align:center;">
</div>
<form
style="margin-top:120px;border:1px solid #ccc;
box-shadow:0 1px 25px;width:450px;margin-left:400px;background-color:#FFF"
id="form1" name="form1" method="post" action="<?php echo base_url('index.php/Cbook/mybook');?>">
<?php
// echo $des;?>
<table width="281" border="0" align="center">
<tr>
<p style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">Reservation</p>
<h2 style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">User name: <?php echo $user[0]->firstName." ".$user[0]->lastName?></h2>
<p style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">Email: <?php echo $user[0]->Email?></p>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Name of Lodge</p></td>
<td width="170"><label for="LisName"></label>
<input style="margin-top:8px" value="<?php echo $res[0]->LodgeName;?>" type="text" name="name1" id="txtNo" /></td>
<input style="margin-top:8px" value="<?php echo $des;?>" type="hidden" name="name" id="txtNo" /></td>
</tr>
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Check In</p></td>
<td><label for="txtIn"></label>
<input
type="Date" name="txtIn" id="txtIn" /></td>
</tr>
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Check Out</p></td>
<td><label for="txtOut"></label>
<input type="Date" name="txtOut" id="txtOut" /></td>
</tr>
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Telephone</p></td>
<td><label for="txtNo"></label>
<input style="margin-top:8px" type="text" name="teleNo" id="txtNo" /></td>
</tr>
<tr>
<td></td>
<td>
<input style="width:120px;float:left;-webkit-border-radius:3px;height:35px;margin-bottom:20px;background-color: #005c99;color:#FFF"
type="submit" name="btnRes" id="btnRes" value="Reserve"/>
<input style="width:120px;float:right;-webkit-border-radius:3px;height:35px;margin-bottom:20px;background-color: #005c99;color:#FFF"
type="submit" name="btnRes" id="btnRes" value="View All"
onClick="window.location.href = '<?php echo base_url();?>index.php/Lists/user_reservation_list';return false;"/></td>
</tr>
</table>
</form>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div class="container" id="footer" style="max-width:100%;height:54px;margin-bottom:none">
<p style="padding-top:20px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
</style>
</head>
<body style="font-family:Verdana;
font-size:15px;
background-color:#e6e6ff;
">
<header style="height:68px"id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<form
style="margin-top:120px;border:1px solid #ccc;
box-shadow:0 1px 25px;width:450px;margin-left:400px;background-color:#FFF"
id="form1" name="form1" method="post" action="<?php echo base_url('index.php/PaymentsCon/Pay');?>">
<h3 >RESERVATION SUCCESFULLY COMPLETED</h3>
<h2>THANK YOU FOR USING B&B</h2>
<input style="width:120px;float:left;-webkit-border-radius:3px;height:35px;margin-bottom:20px; text-align:center;background-color: #005c99;color:#FFF"
type="submit" name="btnRes" id="btnRes" value="ADD PAYMENT"/>
</form>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<div class="container" id="footer" style="max-width:100%;height:54px;margin-bottom:none">
<p style="padding-top:20px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class compereChechkinCheckout extends CI_Controller
{
function compareDate()
{
$this->load->model("Dat_Model");
$startDate= $_POST['txtDate'];
$endDate= $_POST['txtCheckout'];
$valuee=$_POST['opt'];
$data['dat']=$this->Dat_Model->compare($startDate,$endDate,$valuee);
$data['ava']=$this->Dat_Model->Avail($valuee);
// $data2=$this->Dat_Model->datee($startDate,$valuee);
// print_r($res);
// print_r($data['ava']);
$this->load->view('Booking',$data);
}
}<file_sep>
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Managerlists extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('managerlistModel');
}
function rentout_status()
{
$data['dat']=$this->managerlistModel->new_rentout();
$data['accept']=$this->managerlistModel->accept_rentout();
$data['reject']=$this->managerlistModel->reject_rentout();
$this->load->view('managerPendinglist',$data);
}
function accept($Rid){
$no=$this->input->post('c_no');
$status="accept";
$data=array(
'status'=>$status
);
$this->db->where('Rid', $Rid);
$res=$this->db->update('reservation', $data);
if($res){
redirect(base_url('/index.php/managerlists/rentout_status'));
}
else{
return false;
}
}
function reject($Rid){
$no=$this->input->post('c_no');
$status="reject";
$data=array(
'status'=>$status
);
$this->db->where('Rid', $Rid);
$res=$this->db->update('reservation', $data);
if($res){
redirect(base_url('/index.php/managerlists/rentout_status'));
}
else{
return false;
}
}
}<file_sep><!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>
Responsive Header Demo
</title>
<link rel="stylesheet" href="<?php echo base_url('assets/styleNew.css');?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
.mySlides {display:none;}
</style>
</head>
<body>
<div>
<header id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="<?php echo base_url('index.php/Mylogin/login');?>">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<div class="w3-content w3-section" style="max-width:100%;max-height:-5%">
<img class="mySlides" src="<?php echo base_url('Image/img1.jpg');?>" style="width:100%">
<img class="mySlides" src="<?php echo base_url('Image/img2.jpg');?>" style="width:100%">
<img class="mySlides" src="<?php echo base_url('Image/img3.jpg');?>" style="width:100%">
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script>
<br>
<form name="form1" method="post" action="<?php echo base_url('index.php/compereChechkinCheckout/compareDate');?>">
<div class="container" id="divmaintab">
<div class="row" >
<div class="col-md-3" align="center" >
<label>Check In</label>
<br>
<input type="Date" name="txtDate" id="txtDate">
</div>
<div class="col-md-3" align="center">
<label>Check Out</label>
<br>
<input type="Date" name="txtCheckout" id="txtCheckout">
</div>
<div class="col-md-3" align="center">
<label>Destination</label>
<br>
<label for="opt"></label>
<select name="opt" id="opt" style="width:200px; -moz-border-radius:7px;
-webkit-border-radius:5px;height:25px">
<?php
foreach ($cities as $row) {
$city=$row->Destination;
?>
<option value="<?php echo $city; ?>"><?php echo $city; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-3" align="center">
<input type="submit" class="btn btn-primary btn-sm" name="btnSearch" id="btnSearch" value="Submit" />
</div>
</div>
</div>
</form>
<br>
<br>
<br>
<br>
<div class="container ">
<div id="imageHeader" style="background:white">
<div class="row"> <!-- Begining of the first row -->
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/galle_face.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;-webkit-border-radius:8px">
<div id="desc">
<p>Colombo</p>
</div>
</div>
</div>
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/sri-lanka-kandy-buddha-temple-sri-dalada-maligawa-temple-of-the-tooth-2.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p>Kandy</p>
</div>
</div>
</div>
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/lake.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p>Nuwara Eliya</p>
</div>
</div>
</div>
</div> <!-- End of the first row -->
<div class="row"> <!-- Beigining of the second row -->
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/1109-1062.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p>Mirissa</p>
</div>
</div>
</div>
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/sigiriya-sri-lanka.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p>Sigiriya</p>
</div>
</div>
</div>
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/negambo-beach.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p>Negombo</p>
</div>
</div>
</div>
</div> <!-- End of the second row -->
<div class="row"><!-- Beigining of the third row -->
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/image-slider-3.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p style="margin-bottom:70px">Galle</p>
</div>
</div>
</div> <!-- end of the column1-->
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/yala-national-park-sri-lanka-022.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p style="margin-bottom:70px">Yala</p>
</div>
</div>
</div><!-- end of the column2-->
<div class="col-md-4" align="center">
<div id="image">
<img src="<?php echo base_url('Image/slider9.jpg');?>" width="200" height="200" style="-moz-border-radius:8px;
-webkit-border-radius:8px">
<div id="desc">
<p style="margin-bottom:70px">Unawatuna</p>
</div>
</div>
</div><!-- end of the column3-->
</div><!-- End of the third row -->
</div>
</div>
<br>
<br>
<div class="container" id="footer" style="max-width:100%">
<p>CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</div>
</body>
</html>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="<?php echo base_url('assets/log.css');?>">
<style>
input[type="Date"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
input[type="Text"]
{
width:300px;
height:35px;
margin-top:5px;
border-radius:5px;
-moz-border-radius:7px;
-webkit-border-radius:7px;
}
</style>
</head>
<body style="font-family:Verdana;
font-size:15px;
background-color:#e6e6ff;
">
<header style="height:68px"id="header">
<div class="container">
<div id="logo"> <img src="<?php echo base_url('Image/PicsArt_03-21-08.30.27.jpg');?>" width="60" height="60"></div>
<h1>
BED AND BREAKFAST
</h1>
<nav id="nav">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Contact</a>
</li>
<li>
<a href="#">Facilities</a>
</li>
<li>
<a href="#">Login</a>
</li>
</ul>
</nav>
</div>
</header>
<br>
<br>
<br>
<br>
<form
style="margin-top:120px;border:1px solid #ccc;
box-shadow:0 1px 25px;width:450px;margin-left:400px;background-color:#FFF"
id="form1" name="form1" method="post" action=" <?php echo base_url('index.php/Lists/Update_reservation_savedata') ?>">
<?php
print_r($updateDetail);?>
<table width="281" border="0" align="center">
<tr>
<p style="text-align:center;font-family:'Lucida Calligraphy';font-size:18px;font-weight:bold;color:#009">Reservation</p>
<td width="105"><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Name of Lodge</p></td>
<td width="170"><label for="LisName"></label>
<input style="margin-top:8px" value="<?php echo $updateDetail[0]->Did; ?>" type="text" name="name" id="txtNo" /></td>
</tr>
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Check In</p></td>
<td><label for="txtIn"></label>
<input
type="Date" value="<?php echo $updateDetail[0]->CheckIn; ?>" name="txtIn" id="txtIn" /></td>
</tr>
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Check Out</p></td>
<td><label for="txtOut"></label>
<input type="Date" value="<?php echo $updateDetail[0]->CheckOut; ?>" name="txtOut" id="txtOut" /></td>
</tr>
<!-- <tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">City</p></td>
</tr> -->
<tr>
<td><p style="font-family:'Times New Roman', Times, serif;font-size:14px;font-weight:bold;color:#009">Telephone</p></td>
<td><label for="txtNo"></label>
<input style="margin-top:8px" type="text" value="<?php echo $updateDetail[0]->TeleNo; ?>" name="teleNo" id="txtNo" /></td>
</tr>
<tr>
<td> </td>
<td>
<input style="width:300px;-webkit-border-radius:3px;height:35px;margin-bottom:20px;background-color: #005c99;color:#FFF" type="submit" name="btnRes" id="btnRes" value="Reserve" /></td>
</tr>
</table>
</form>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div class="container" id="footer" style="max-width:100%;height:54px;margin-bottom:none">
<p style="padding-top:20px">CopyRight2017 Bed and Breakfast private limited.</p>
</div>
</body>
</html>
<file_sep><?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Mylogin extends CI_Controller{
function login()
{
//http://localhost:81/ci_intro/Login/login
$data['title']='LOGIN';
$this->load->view("Login",$data);
}
function login_validation()
{
// Add validation rules to the username and password
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('pass','Password','required');
if($this->form_validation->run())
{
$username= $this->input->post('username'); //get username & password from the user
$password= $this->input->post('pass');
$this->load->model('Login_model');// load login model
if($this->Login_model->can_login($username,$password))// If username & password valid create a session
{
$session_data= $arrayName = array('username' =>$username);// Add session details using associative array
$this->session->set_userdata($session_data);// create session
$role=$this->Login_model->user_role($username,$password);// access to user_role method in login_model
//check user roles and redirect to relevent pages
if ($role=="renter")
{
$data['title'] = 'Make Rent Outs';
$this->load->view('RegisterRent',$data);
}
else if ($role=="Manager")
{
redirect(base_url('/index.php/Managerlists/rentout_status'));
}
else
{
redirect(base_url('/index.php/CheckD/myDate'));
}
}
else
{
$this->session->set_flashdata('error','Invalid username and password');
redirect(base_url('/index.php/Mylogin/login'));
}
}
else
{
$this->login();
}
}
function enter()
{
if($this->session->userdata('username')!='')
{
echo '<h2> Welcome -'.$this->session->userdata('username').'</h2>';
}
else
{
redirect(base_url('/index.php/Mylogin/logout'));
}
}
function logout()
{
$this->session->sess_destroy();
redirect(base_url('/index.php/CheckD/mydate'));
}
}
<file_sep><?php
class RegisterCntrol extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->library(array('form_validation'));
$this->load->model('RegisterModel');
}
public function create(){
$data['title'] = 'Make Rent Outs';
$this->form_validation->set_rules('address1' , 'First Address','required');
$this->form_validation->set_rules('address2' , 'Second Address','required');
$this->form_validation->set_rules('city' , 'City','required');
$this->form_validation->set_rules('price' , 'Price','required');
$this->form_validation->set_rules('lname' , 'Lodge Name','required');
if ($this->form_validation->run()===FALSE) {
$this->load->view('RegisterRent',$data);
}
else{
$res=$this->RegisterModel->make_rent();
if ($res){
$this->load->view('uploadimage.php');
}
}
}
}
?>
<file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php echo base_url('index.php/CheckD/compareDate');?>">
<p>
<label for="CheckIn"></label>
<input type="Date" name="CheckIn" id="CheckIn" />
<label for="opt"></label>
<select name="opt" id="opt">
<option value="Nuwaraeliya">Nuwaraeliya</option>
<option value="Colombo">Colombo</option>
</select>
</p>
<p>
<label for="CheckOut"></label>
<input type="Date" name="CheckOut" id="CheckOut" />
</p>
<p>
<input type="submit" name="Check" id="Check" value="CDates" />
</p>
</form>
</body>
</html><file_sep><?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class BlogController extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('blogmodel');
}
function index() {
//the hard-coded blog id value 1 should come from UI
$blog_id = 1;
$vote_results = $this->blogmodel->get_blog_rating($blog_id);
$data['blog_vote_overall_rows'] = $vote_results['vote_rows'];
$data['blog_vote_overall_rate'] = $vote_results['vote_rate'];
$data['blog_vote_overall_dec_rate'] = $vote_results['vote_dec_rate'];
$vote_results = $this->blogmodel->get_blog_rating_from_ip($blog_id);
$data['blog_vote_ip_rate'] = $vote_results['vote_rate'];
$this->load->view('blog', $data);
$this->load->view('rating/x/index');
}
function rate_s($des) {
$a=$_POST['rate'];
// $des=$_POST['desti']
//echo $des;
$ip=0;
$blogid=$des;
$data = array(
//'name' => $this -> input->post('name'),
'blog_vote'=>$a,
'blog_id' => $blogid,
'ip_address'=>$ip
);
$this-> db-> insert('blog_vote' , $data);
}
function rate_blog() {
if (isset($_POST)) {
$blog_id = $_POST['blog_id'];
$rating = $_POST['rating'];
$vote_results = $this->blogmodel->rate_blog($blog_id, $rating);
$blog_vote_overall_rows = $vote_results['vote_rows'];
$blog_vote_overall_rate = $vote_results['vote_rate'];
$blog_vote_overall_dec_rate = $vote_results['vote_dec_rate'];
$blog_vote_ip_rate = $vote_results['vote_curr_rate'];
$stars = '';
for ($i = 1; $i <= floor($blog_vote_overall_rate); $i++) {
$stars .= '<div class="star" id="' . $i . '"></div>';
}
//THE OVERALL RATING (THE OPAQUE STARS)
echo '<div class="r"><div class="rating">' . $stars . '</div>' .
'<div class="transparent">
<div class="star" id="1"></div>
<div class="star" id="2"></div>
<div class="star" id="3"></div>
<div class="star" id="4"></div>
<div class="star" id="5"></div>
<div class="votes">(' . $blog_vote_overall_dec_rate . '/5, ' . $blog_vote_overall_rows . ' ' . ($blog_vote_overall_rows > 1 ? ' votes' : ' vote') . ') ' . ($blog_vote_ip_rate > 0 ? '<strong>You rated this: <span style="color:#39C;">' . $blog_vote_ip_rate . '</span></strong>' : '') . '</div>
</div>
</div>';
}
}
}<file_sep>
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Renterlists extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('renterlistsModel');
}
function lists(){
$data['dat']=$this->renterlistsModel->pending_rentout();
$data['accept']=$this->renterlistsModel->accept_rentout();
$data['reject']=$this->renterlistsModel->reject_rentout();
$this->load->view('renterlists',$data);
}
function cancelRent($id){
echo $id;
$res=$this->renterlistsModel->deleteRent($id);
if ($res) {
redirect(base_url('/index.php/Renterlists/lists'));
}
}
function UpdateRentouts($id){
$res['title']='Update Rent Outs';
// echo $id;
$res['UpdatedData']=$this->renterlistsModel->UpdateRentOuts($id);
// print_r($res) ;
$this->load->view('UpdateRent',$res);
}
function UpdateRen_savedata(){
//edit this
$data=array(
'Address1'=>$this->input->post('address1'),
'Address2'=>$this->input->post('address2'),
'Destination'=>$this->input->post('city'),
'Price'=>$this->input->post('price'),
'LodgeName'=>$this->input->post('lname'),
'NumRooms'=>$this->input->post('select')
);
$id=$this->input->post('name');
print_r($data);
echo $id;
$this->db->where('Rid', $id);
$res=$this->db->update('reservation', $data);
if($res){
$this->load->view('UpdateImages');
// redirect(base_url('/index.php/Renterlists/lists'));
}
else{
return false;
}
}
}
|
f4d3427155b1437faf515527bae7dda786ce20f0
|
[
"Markdown",
"PHP"
] | 46
|
PHP
|
LaknaGammedda/3rd-year-ITPDM-me
|
4ce00f98670b99c7d625f45dadf6ac0e6d82a3fe
|
3cc087a626489e0624ebaa538eb9956801d5792e
|
refs/heads/main
|
<file_sep>const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
const ejs = require("ejs");
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/public"));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
let city = req.body.cityname;
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=a3e9f654d8503bc06810b44ed628d7af`;
https.get(url, (response) => {
console.log(response.statusCode);
response.on("data", function(data) {
const weatherReport = JSON.parse(data);
const temp = weatherReport.main.temp;
res.render("weather-in-city", { city: city, temp: temp });
});
});
});
app.listen(process.env.PORT || 3000, function() {
console.log(`server is running on port 3000`);
});
|
592c548a3da312f89afe02e63d5b72e6396c28df
|
[
"JavaScript"
] | 1
|
JavaScript
|
01naveen10/weather-app
|
286237d77ed7233d747070331e6f4516016c99f6
|
13932149a0b1357bbe61a786561975674c0c8985
|
refs/heads/master
|
<repo_name>dyelax/dqn-question-6-17-16<file_sep>/dqn_model.py
import tensorflow as tf
import numpy as np
from dqn_constants import *
from dqn_utils import *
class DQN_Model:
def __init__(self, action_space):
self.num_actions = action_space.n
self.define_graph()
def define_graph(self):
"""
Sets up the DQN graph in TensorFlow.
"""
##
# Utilities
##
def w(shape, stddev=0.1):
"""
Returns a weight layer with the given shape and standard deviation.
"""
return tf.Variable(tf.truncated_normal(shape, stddev=stddev))
def b(shape):
"""
Returns a bias layer initialized with 1s with the given shape.
"""
return tf.Variable(tf.constant(1.0, shape=shape))
def qloss(results, pred_Qs):
"""
Q-function loss with target freezing - the difference between the observed
Q value, taking into account the recently received r (while holding future
Qs at target) and the predicted Q value the agent had for (s, a) at the time
of the update.
Params:
results - A BATCH_SIZE x 4 Tensor containing a, r, s' and target_Q for
each experience
pred_Qs - The Q values predicted by the model network
Returns:
A Tensor with the Q-function loss for each experience.
"""
losses = []
for i in xrange(BATCH_SIZE):
a = results[i, 0]
r = results[i, 1]
s_ = results[i, 2]
target_Q = results[i, 3]
pred_Q = tf.gather(pred_Qs[i, :], tf.to_int32(a))
y = r
if s_ is not None: #if the episode doesn't terminate after s
y += DISCOUNT * target_Q
losses.append(float(clip(y - pred_Q)**2))
return losses
##
# Input data
##
#holds s from each experience in the minibatch
self.train_states = tf.placeholder(tf.float32,
shape=(BATCH_SIZE, FRAME_HEIGHT, FRAME_WIDTH, HIST_LEN))
#holds a, r, s_ and target_Q from each experience in the minibatch
self.train_results = tf.placeholder(tf.float32,
shape=(BATCH_SIZE, 4))
#holds one state to make a prediction
self.test_state = tf.placeholder(tf.float32,
shape=(1, FRAME_HEIGHT, FRAME_WIDTH, HIST_LEN))
##
# Layers
##
#layer params TODO: make these caps
PAD_CONV1 = 'SAME'
KSIZE_CONV1 = 8
STRIDE_CONV1 = 4
OSIZE_CONV1 = 21
ODEPTH_CONV1 = 32
PAD_CONV2 = 'SAME'
KSIZE_CONV2 = 4
STRIDE_CONV2 = 2
OSIZE_CONV2 = 11
ODEPTH_CONV2 = 64
PAD_CONV3 = 'SAME'
KSIZE_CONV3 = 3
STRIDE_CONV3 = 1
OSIZE_CONV3 = 11
ODEPTH_CONV3 = 64
I_DENSE1 = OSIZE_CONV3**2 * ODEPTH_CONV3
O_DENSE1 = 512
I_DENSE2 = O_DENSE1
O_DENSE2 = self.num_actions
#layer setup
self.w_conv1 = w([KSIZE_CONV1, KSIZE_CONV1, HIST_LEN, ODEPTH_CONV1])
self.b_conv1 = b([ODEPTH_CONV1])
self.w_conv2 = w([KSIZE_CONV2, KSIZE_CONV2, ODEPTH_CONV1, ODEPTH_CONV2])
self.b_conv2 = b([ODEPTH_CONV2])
self.w_conv3 = w([KSIZE_CONV3, KSIZE_CONV3, ODEPTH_CONV2, ODEPTH_CONV3])
self.b_conv3 = b([ODEPTH_CONV3])
self.w_dense1 = w([I_DENSE1, O_DENSE1])
self.b_dense1 = b([O_DENSE1])
self.w_dense2 = w([I_DENSE2, O_DENSE2])
self.b_dense2 = b([O_DENSE2])
##
# Calculation
##
def predict(states):
"""
Runs states through the network to get predictions.
"""
with tf.name_scope('conv1') as scope:
preds = tf.nn.conv2d(
states, self.w_conv1, [1, STRIDE_CONV1, STRIDE_CONV1, 1], padding=PAD_CONV1)
preds = tf.nn.relu(preds + self.b_conv1)
with tf.name_scope('conv2') as scope:
preds = tf.nn.conv2d(
preds, self.w_conv2, [1, STRIDE_CONV2, STRIDE_CONV2, 1], padding=PAD_CONV2)
preds = tf.nn.relu(preds + self.b_conv2)
with tf.name_scope('conv3') as scope:
preds = tf.nn.conv2d(
preds, self.w_conv3, [1, STRIDE_CONV3, STRIDE_CONV3, 1], padding=PAD_CONV3)
preds = tf.nn.relu(preds + self.b_conv3)
#flatten preds for dense layers
shape = preds.get_shape().as_list()
preds = tf.reshape(preds, [shape[0], shape[1] * shape[2] * shape[3]])
with tf.name_scope('dense1') as scope:
preds = tf.nn.relu(tf.matmul(preds, self.w_dense1) + self.b_dense1)
with tf.name_scope('dense2') as scope:
preds = tf.nn.relu(tf.matmul(preds, self.w_dense2) + self.b_dense2)
return preds
##
# Training computation
##
self.train_preds = predict(self.train_states)
self.loss = tf.reduce_mean(qloss(self.train_results, self.train_preds))
self.optimizer = tf.train.RMSPropOptimizer(
LEARN_RATE, momentum=MOMENTUM).minimize(self.loss)
##
# Test computation
##
self.test_pred = predict(test_state)[0]<file_sep>/dqn.py
import gym
import tensorflow as tf
import numpy as np
from skimage.transform import resize
from copy import deepcopy
from collections import deque
from dqn_constants import *
from dqn_model import *
from dqn_utils import *
##
# Setup environment
##
# env = gym.make('SpaceInvaders-v0')
env = gym.make('Pong-v0')
env.monitor.start(MONITOR_PATH, force=True)
#init session
sess = tf.Session()
#init models
model = DQN_Model(env.action_space)
target = DQN_Model(env.action_space)
sess.run(tf.initialize_all_variables())
update_target(model, target)#start target with same weights as model
#experience replay vars
frames = []
frame_index = 0 #index at which to add the next frame
experiences = deque()
#start for epsilon annealing
eps = EPS_START
##
# Run training
##
num_episodes = 0
episode_done = True
for frame_num in xrange(TRAIN_FRAMES):
if episode_done:
#reset for new episode
raw_frame = env.reset()
new_frame = process_frame(raw_frame)
hist = deque([None, None, None, add_frame(frame)])
num_episodes += 1
episode_done = False
#anneal epsilon
if frame_num < EPS_ANNEAL_PERIOD:
eps -= EPS_DIFF
else:
eps = EPS_END
#choose a new action every SKIP_FRAMES
if frame_num % SKIP_FRAMES == 0:
#If we shouldn't start learning yet or with epsilon probability, act randomly
#Otherwise, select the max predicted Q action
if frame_num < REPLAY_START_SIZE or np.random.choice([True, False], p=[eps, 1 - eps]):
a = env.action_space.sample()#random action
else:
s = get_state(hist)
a = np.argmax(model.get_pred(model, s))
#execute aciton
assert a is not None, 'a should never be None.'
raw_frame, r, done, info = env.step(a)
new_frame = process_frame(raw_frame, frames[frame_index-1])
#store the indeces of frames for s and s', and update hist
i_s = list(hist)#list() makes a copy, so not affected by subsequent pop/append
hist.popleft()#pop off oldest frame
hist.append(add_frame(new_frame))#add new frame
i_s_ = list(hist)
#save experience - tuple of s frame indeces, action, reward, s' frame indeces.
experiences.append((i_s, a, r, i_s_))
#update the model
if len(experiences) >= REPLAY_START_SIZE and frame_num % (SKIP_FRAMES * UPDATE_FREQ) == 0:
train_step(model, frame_num)
# if frame_num % SAVE_FREQ == 0:
# save()
if frame_num % TARGET_UPDATE_FREQ == 0:
update_target()
##
# Upload results
##
env.monitor.close()
# gym.upload(MONITOR_PATH, API_KEY=API_KEY)
<file_sep>/dqn_utils.py
import tensorflow as tf
import numpy as np
from skimage.transform import resize
from copy import deepcopy
from collections import deque
from dqn_constants import *
from dqn import *
##
# Preprocessing
##
def process_frame(raw_frame, prev_frame=np.zeros((FRAME_HEIGHT, FRAME_WIDTH))):
"""
Preprocesses a frame for learning.
Params:
raw_frame - A 210x160x3 array representing an RGB image
prev_frame - The previously-observed frame
(already processed as an 84x84 luminance array)
Returns:
The processed version of raw_frame - an 84x84 array representing a luminance
image, taking the max luminance for each pixel of raw_frame and prev_frame
"""
#rgb -> luminance
new_frame = rgb_to_luminance(raw_frame)
#resize
new_frame = resize(new_frame, (FRAME_HEIGHT, FRAME_WIDTH))
#take max luminance from either frame
paired = np.dstack((new_frame, prev_frame))#pair pixels to max on an array dimension
new_frame = np.amax(paired, axis=2)#takes max of each pixel
return new_frame
def rgb_to_luminance(rgb_frame):
"""
Extracts luminance from every pixel's rgb values and
returns an equivalent frame with luminance pixels.
Params:
rgb_frame - A 3D array representing a 2D RGB image
Returns:
A 2D array representing rgb_frame with luminance pixels
"""
#axis=2 sums along the innermost axis (each pixel's rgb values)
return np.sum(rgb_frame, axis=2)/3.
def clip(x):
"""
Clips reward or error x to stay between bounds [-1, 1].
"""
if x >= 1:
return 1
if x <= -1:
return -1
return x
##
# Model functions
##
def update_target(model, target):
"""
Updates target with the values of model.
"""
cp_ops = [
target.w_conv1.assign(model.w_conv1), target.b_conv1.assign(model.b_conv1),
target.w_conv2.assign(model.w_conv2), target.b_conv2.assign(model.b_conv2),
target.w_conv3.assign(model.w_conv3), target.b_conv3.assign(model.b_conv3),
target.w_dense1.assign(model.w_dense1), target.b_dense1.assign(model.b_dense1),
target.w_dense2.assign(model.w_dense2), target.b_dense2.assign(model.b_dense2)]
sess.run(cp_ops)
def get_pred(network, s):
"""
Uses network to predict the Q values for each action from a state.
Params:
network - The model to use to predict the Q values for s
s - The state for which to predict Q values
Returns:
A list representing the Q values for each action from s
"""
return sess.run(network.test_pred, feed_dict={test_data: [s]})
def train_step(model, frame_num):
"""
Trains model for one step.
"""
#create minibatch
experiences = np.random.choice(REPLAY_SIZE, BATCH_SIZE)
states = []
results = []
for i_s, a, r, i_s_ in experiences:
states.append(get_state(i_s))
#get target q value
if s_ is not None:
target_Q = np.amax(get_pred(target, s_))
else:
target_Q = None
results.append([a, r, get_state(i_s_), target_Q])
#update
feed_dict = {train_states : states, train_results : results}
_, l, preds = sess.run([optimizer, loss, train_preds], feed_dict=feed_dict)
#print loss
if frame_num % (100 * UPDATE_FREQ * SKIP_FRAMES) == 0:
print 'loss at frame %d: %f' % (frame_num, l)
##
# Misc
##
def get_state(s_indeces):
"""
Creates a state from a list of frames.
Params:
s_indeces - The indeces (in frames array) of the frames from which to
create the state. None => empty frame. len = HIST_LEN.
Returns:
A single state image array with the frames in hist as channels
"""
assert len(s_indeces) == HIST_LEN, 's_indeces must have %i elements' % HIST_LEN
frames = []
for i in s_indeces:
if i is None:
frames.append(np.zeros(FRAME_HEIGHT, FRAME_WIDTH))
else:
frames.append(frames[i])
return np.dstack(frames)
def add_frame(frame):
"""
Adds frame to frames and returns the index at which it was added.
"""
frames[frame_index] = frame
added_index = frame_index
frame_index = (frame_index + 1) % REPLAY_SIZE
return added_index
<file_sep>/dqn_constants.py
#Saving/OpenAI Gym settings
MODEL_SAVE_DIR = 'save/model/'
MONITOR_PATH = 'save/monitor/dqn0'
API_KEY = '<KEY>'
#Data
FRAME_HEIGHT = FRAME_WIDTH = 84
#Implementation constants
SKIP_FRAMES = 4 #Num frames to skip (and repeat action) between each observation
UPDATE_FREQ = 4 #Num actions to take between each SGD update
REPLAY_SIZE = 1e5 #Number of elements in experience replay data (Paper uses 1e6)
REPLAY_START_SIZE = 5e4 #Don't learn (use random policy) until this many iters
DISCOUNT = 0.99 #Discount factor for q learning
NOOP_MAX = 30 #Max num "do nothing" actions performed by agent at start of episode
TRAIN_FRAMES = 1e7 #The total number of frames to train on (Paper uses 5e7)
SAVE_FREQ = 1e6 #Num frames between each save of the model
TARGET_UPDATE_FREQ = 1e4 #Num frames between each update of the target network
#Epsilon annealing
EPS_START = 1
EPS_END = 0.1
EPS_ANNEAL_PERIOD = 1e6
EPS_DIFF = (EPS_START - EPS_END) / EPS_ANNEAL_PERIOD
#Hyperparameters
BATCH_SIZE = 32
HIST_LEN = 4 #Num most recent frames used as input
LEARN_RATE = 2.5e-4
MOMENTUM = 0.95<file_sep>/README.md
# dqn-question-6-17-16
|
5c41daaa03e786e780845423003ef5aa1400d196
|
[
"Markdown",
"Python"
] | 5
|
Python
|
dyelax/dqn-question-6-17-16
|
19d61afc72793ee1e9f647e49a56cf16ce06a561
|
378a6de2a9438bb8f9ae4a4c553556117b5dc939
|
refs/heads/main
|
<repo_name>fsdarif/advance-javascript<file_sep>/map-filter-object-property.js
const students = [
{id: 20, name: "Arif"},
{id: 21, name: "Sharif"},
{id: 22, name: "Shanto"}
];
const names = students.map(s => s.name);
const ids = students.map(s => s.id);
// filter
const idNumber = students.filter(s => s.id > 21);
const idnumberForFind = students.find(s => s.id>20);
console.log(idnumberForFind)<file_sep>/map-filter.js
const numbers = [2, 4, 9, 10]
const output = [];
for (let i=0; i<numbers.length; i ++) {
const elements = numbers[i];
const result = elements * elements;
output.push(result);
console.log (output)
}
const numbers = [2, 4, 9, 10];
numbers.map(function (element, index, array) {
console.log(element, index, array );
}
)
function squre (element){
return element * element;
}
const squre = element => element * element;
const squre = x => x * x;
const number = [2, 4, 6];
// const result = number.map(function(element){
// return element * element
// })
const result = number.map(x => x * x);
console.log(result)
filter
const number = [2, 3, 4, 5, 9, 11, 52];
const bigger = number.filter(x => x > 5);
console.log(bigger);<file_sep>/null-undesined.js
//undefined
let name;
function add (num1, num2) {
console.log(num1 + num2);
return // return undefined
}
function add (num1, num2) {
return num1 + num2
}
console.log(add(num1)) // num2 undefined
const person = {name: "Hosen", age: 25, job: "student" };
console.log(person.friend); // friend undefined
let fun = undefined;
console.log(fun);
//nul
|
92dddb99ccd5f8388fa3627a7835ea975968cd7f
|
[
"JavaScript"
] | 3
|
JavaScript
|
fsdarif/advance-javascript
|
e02d1db1b37827db6dc696d4cd69bf86c467e9d3
|
daf43dc6a0e05575db274995dfbdecbf074570d9
|
refs/heads/master
|
<repo_name>nikhilrayaprolu/duplicate-elimination<file_sep>/code/hash.py
from SqlException import SqlException
import itertools
import sys, time
hashmap = {}
INT_SIZE = sys.getsizeof(int())
def getNext(line, records_per_block, output_buffer):
if line:
sum = hash(line)
try:
if sum:
val = hashmap[sum]
except:
if sum:
hashmap[sum] = line
if line:
output_buffer.append(line)
return output_buffer
def printmessage(message):
#print message
pass
def openfile(filename, num_attrs, num_buffers, block_size):
input_buffer = []
output_buffer = []
block_size = int(block_size)
printmessage(block_size)
num_attrs = int(num_attrs)
printmessage(num_attrs)
num_buffers = int(num_buffers)
printmessage(num_buffers)
if num_buffers <= 1:
raise SqlException("Number of buffers should be greater than or equal to 2")
printmessage(num_buffers)
records_per_block = block_size//(INT_SIZE*num_attrs)
N = 0
if records_per_block:
N = (num_buffers - 1) * records_per_block
out = open('output_hash.txt', 'wa');
start = 0
with open(filename, 'r') as f:
if f:
for input_buffer in iter(lambda: list(itertools.islice(f, N)), []):
if input_buffer:
for line in input_buffer:
if line:
line = line.strip()
line = line.strip('\n')
if len(line.split(',')) != num_attrs:
raise SqlException("All rows do not contain same number of attributes")
printmessage("raised sqlexception")
output_buffer = getNext(line, records_per_block, output_buffer)
if output_buffer:
if len(output_buffer) == records_per_block:
a = '\n'.join(output_buffer)
if a:
out.write(a + '\n')
output_buffer = []
if len(output_buffer):
a = '\n'.join(output_buffer)
if a:
out.write(a + '\n')
output_buffer = []
out.close()
def distinct(args):
start_time = time.time()
if args:
openfile(args[0], args[1], args[2], args[3])
print("%s sec" % (time.time() - start_time))
<file_sep>/code/SqlException.py
class SqlException(Exception):
def __init__(self, arg):
self.message = arg
<file_sep>/code/btree.py
from SqlException import SqlException
import itertools
import sys, time
INT_SIZE = sys.getsizeof(int())
def errorcheck(message):
#print message
pass
class BNode(object):
def __init__(self, min_degree, leaf):
errorcheck(min_degree)
self.min_degree = min_degree # 't'
self.children = [None] * (2 * self.min_degree) # array of BNodes
errorcheck(self.children)
self.keys = [None] * (2 * self.min_degree - 1) # array of keys (int)
self.leaf = leaf
errorcheck(leaf)
self.present = 0
def insertNode(self, val):
i = self.present-1
if self.leaf:
while i >= 0 and self.keys[i] > val:
errorcheck(self.keys[i])
self.keys[i+1] = self.keys[i]
i -= 1
errorcheck(i)
self.keys[i+1] = val
errorcheck(val)
self.present += 1
else:
while i >= 0 and self.keys[i] > val:
i -= 1
errorcheck(i)
if (self.children[i+1]).present == 2*self.min_degree - 1:
self.addKeyAndSplit(i+1, self.children[i+1])
if self.keys[i+1] < val:
i += 1
errorcheck(i)
self.children[i+1].insertNode(val)
def searchNode(self, val):
i = 0
while i < self.present and val > self.keys[i]:
i += 1
errorcheck(i)
if i < len(self.keys) and self.keys[i] == val:
return self
if self.leaf:
return None
errorcheck(self.children[i])
return (self.children[i]).searchNode(val)
def addKeyAndSplit(self, i, childNode):
B = BNode(childNode.min_degree, childNode.leaf)
if B:
B.present = self.min_degree - 1
j = 0
if j == 0:
while j < self.min_degree - 1:
B.keys[j] = childNode.keys[j+self.min_degree]
j += 1
if not childNode.leaf:
j = 0
if j == 0:
while j < self.min_degree:
errorcheck(j)
B.children[j] = childNode.children[j+self.min_degree]
if j:
j += 1
childNode.present = self.min_degree - 1
j = self.present
if j:
while j >= i + 1:
errorcheck(j)
self.children[j+1] = self.children[j]
j -= 1
self.children[i+1] = B
errorcheck(self.children[i+1])
j = self.present - 1
if j:
while j >= i:
errorcheck(j)
self.keys[j+1] = self.keys[j]
j -= 1
self.keys[i] = childNode.keys[self.min_degree - 1]
self.present += 1
class BTree(object):
def __init__(self, min_degree):
self.min_degree = min_degree
self.root = None
def insert(self, val):
if self.root is None:
B = BNode(self.min_degree, True)
if B:
B.keys.insert(0, val)
B.present = 1
self.root = B
errorcheck(self.root)
else:
if self.root.present == 2*self.min_degree - 1:
B = BNode(self.min_degree, False)
if B:
B.children.insert(0, self.root)
errorcheck(self.root)
B.addKeyAndSplit(0, self.root)
i = 0
if B.keys[0] < val:
i += 1
errorcheck(i)
(B.children[i]).insertNode(val)
self.root = B
else:
(self.root).insertNode(val)
def search(self, val):
if self.root is None:
return None
return (self.root).searchNode(val)
def getNext(btree, line, records_per_block, output_buffer):
val = hash(line)
if btree.search(val) is None:
if val:
output_buffer.append(line)
btree.insert(val)
return output_buffer
def openfile(filename, num_attrs, num_buffers, block_size):
input_buffer = []
output_buffer = []
block_size = int(block_size)
errorcheck(block_size)
num_attrs = int(num_attrs)
errorcheck(num_attrs)
num_buffers = int(num_buffers)
errorcheck(num_buffers)
mindegree = block_size//INT_SIZE - 1
btree = BTree(mindegree)
if num_buffers <= 1:
raise SqlException("Number of buffers should be greater than or equal to 2")
errorcheck("raised an sql exception")
records_per_block = block_size//(INT_SIZE*num_attrs)
N = 0
if N==0:
N = (num_buffers - 1) * records_per_block
errorcheck(N)
start = 0
out = open('output_btree.txt', 'wa');
with open(filename, 'r') as f:
if f:
for input_buffer in iter(lambda: list(itertools.islice(f, N)), []):
if input_buffer:
for line in input_buffer:
if line:
line = line.strip()
line = line.strip('\n')
if len(line.split(',')) != num_attrs:
raise SqlException("All rows do not contain same number of attributes")
errorcheck("raised an sql exception")
output_buffer = getNext(btree, line, records_per_block, output_buffer)
errorcheck(output_buffer)
if len(output_buffer) == records_per_block:
a = '\n'.join(output_buffer)
if a:
out.write(a + '\n')
output_buffer = []
if len(output_buffer):
a = '\n'.join(output_buffer)
if a:
out.write(a + '\n')
output_buffer = []
out.close()
def distinct(args):
start_time = time.time()
errorcheck(start_time)
openfile(args[0], args[1], args[2], args[3])
print("%s sec" % (time.time() - start_time))
return
<file_sep>/code/main.py
from SqlException import SqlException
import sys
import btree
import hash
def printmessage(message):
# print message
pass
def main():
try:
if len(sys.argv) < 6:
raise SqlException("Usage: python main.py filename numAttributes~3 numBuffers~10 blockSize~144 typeOfIndex")
printmessage("raised sql error")
elif sys.argv[4] == 0 or sys.argv[5] == "btree":
btree.distinct(sys.argv[1:-1])
printmessage("btree selected")
elif sys.argv[4] == 1 or sys.argv[5] == "hash":
hash.distinct(sys.argv[1:-1])
printmessage("btee selected")
except SqlException, e:
print e.message
if __name__ == '__main__':
main()
<file_sep>/201501090.sh
python code/main.py input/1MB_50Percent 10 10 104857 btree
|
eb3dd72a1745eaa0fd16fc6a399755508725e0d0
|
[
"Python",
"Shell"
] | 5
|
Python
|
nikhilrayaprolu/duplicate-elimination
|
408acc71f64593608654160f85b497c0281d41f7
|
c2fcf6deae7ece986dfbe5d00b64f3c96f51873c
|
refs/heads/master
|
<file_sep># bucky-react-creator
Create buck-react webpages.
<file_sep>#include <iostream>
#include <experimental/filesystem>
#include <string>
#include <cstdlib>
using namespace std;
class CreateProject{
private:
string ex_no;
string files_dest;
string files_origin;
public:
CreateProject(string &ex){
ex_no=ex;
files_origin="~/bucky-react-boilerplate/React-Boilerplate";
files_dest="~/htdocs/buck-react/"+ex_no;
}
void transfer_files(){
experimental::filesystem::path p=files_dest.c_str();
if(experimental::filesystem::exists(p)){
cout<<"File directory already exists,"
<<"remove it please. and try again"<<endl;
}else{
cout<<"Starting to move files...."<<endl;
string cmd="cp -R ";//copy command
cmd=cmd+files_origin+"*";//files to copy
cmd=cmd+" "+files_dest;
system(cmd.c_str());
cout<<"Done moving files."<<endl;
}
}
};
int main(){
cout<<"Enter the project name to create a Bucky React project"<<endl;
string no;
getline(cin,no);
if(no.length()<1){
cout<<"Please enter something more reasonable."<<endl;
}else{
CreateProject proj(no);
proj.transfer_files();
}
return 0;
}
|
ceb71ba3bacfd3b7d36270a20839b73b3ecce32b
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
Borwe/bucky-react-creator
|
e4fbd91cfeed83fb4bf135d7b80e1f0529fb0944
|
76a1dc13f61453cad0f755f80eb0c3ef90754a6e
|
refs/heads/master
|
<repo_name>ff-uva/Consulting-Cases-Presentation<file_sep>/Project3.R
#***************************************************************
#
# Project 3: Simulation & Bootstrapping
# A Case Study: Transplant Center
#
#***************************************************************
#***************************************************************
#
# Read in the data
#
#***************************************************************
#Set working directory
#Read data
r11xplant <- read.table("C:/Users/Think/Documents/Transplant/R11xplant.csv", sep = ",", header = T)
r11donor<-read.table("C:/Users/Think/Documents/Transplant/R11donor.csv", sep = ",", header = T)
uva <- read.table("C:/Users/Think/Documents/Transplant/UVAxplant.csv", sep = ",", header = T)
duke <- read.table("C:/Users/Think/Documents/Transplant/Dukexplant.csv", sep = ",", header = T)
mcv <- read.table("C:/Users/Think/Documents/Transplant/MCVxplant.csv", sep = ",", header = T)
unc <- read.table("C:/Users/Think/Documents/Transplant/UNCxplant.csv", sep = ",", header = T)
# Source the bootstrapping functions
library(boot) #If you don't have this library, install it by: install.packages('boot')
source("C:/Users/Think/Downloads/TSbootfunctions.R")
source("C:/Users/Think/Downloads/SPM_Panel.R")
source("C:/Users/Think/Downloads/Transplant.plots.R")
#***************************************************************
#
# Part 1: Basic Statistics
#
#***************************************************************
#Step 1.1 Compare the performance of UVa with MCV kidney transplants
#Get the distribution of uva$Kidney, mcv$Kidney, r11donor$Kidney. What do you observe?
kidney<-data.frame(uva$Kidney[-30],mcv$Kidney[-30],r11donor$Kidney[-30])
uva.pairs(as.matrix(kidney))
#We observed that the distribution for the uva center is much more symmetric than the other two
#The distribution for the mcv center is very asymmetric, with higher density on the extremes
#The mcv center has the highest correlation with region 11 kidney donors
#On average, how many kidney transplants are performed at UVa per year? MCV?
mean(uva$Kidney[-30])
mean(mcv$Kidney[-30])
#Excluding year 2017 data, 67.31 kidney transplants are performed at UVA per year
#and 84.69 kidney transplants are performed at MCV per year, on average
#Perform a paired t-test between uva and mcv kidney transplants
#What is the result?
t.test(uva$Kidney[-30],mcv$Kidney[-30],paired=T)
#the paired t-test resulted in a p-value of about .006
#we reject the null hypothesis, indicating that there is a significant difference in the means of UVA and MCV kidney transplants
#Step 1.2 Compare the performance of UVa with Duke kidney transplants
#Get the distribution of uva$Kidney, Duke$Kidney, r11xplant$Kidney. What do you observe?
kidney1<-data.frame(uva$Kidney[-30],duke$Kidney[-30],r11xplant$Kidney[-30])
uva.pairs(as.matrix(kidney1))
#we observed that the dist. for the UVA center is much more symmetric than the other two
#The dist. for the Duke center is roughly uniform, with a peak on the lower end of the range
#The Duke center has the higher correlation with region 11 kidney explants
#On average, how many kidney transplants are performed at UVa per year? Duke?
mean(uva$Kidney[-30])
mean(duke$Kidney[-30])
#Excluding year 2017 data, 67.31 kidney transplants are peformed at UVA per year
#and 87.79 kidney transplants are performed at Duke per year
#Perform a paired t-test between uva and duke kidney transplants
#What is the result?
t.test(uva$Kidney[-30],duke$Kidney[-30],paired=T)
#the paired t-test resulted in a p-value of about .000065
#we reject the null hypothesis, indicating that there is a significant difference in the means of UVA and Duke kidney transplants
#Step 1.3 Use bootstrapping to test the hypothesis: there is not a significant difference between UVa and MCV kidney transplants.
#What are the standard errors of the mean? What're the 95% confidence intervals? Do you accept or reject the null hypothesis?
bs.mean<-function(x,i)
{
return(mean(x[i]))
}
uvamcv.diff<-ts(uva$Kidney-mcv$Kidney,1988,2016)
bs.uvamcv.diff<-boot(uvamcv.diff,bs.mean,R=10000)
bs.uvamcv.diff
boot.ci(bs.uvamcv.diff,0.95,type=c('bca','perc'))
#The standard errors of the mean is about 5.76
#The 95% confidence intervals are (-28.93, -6.41) [Percentile]; (-29.21, -6.72) [BCa]
#We reject the null hypothesis because the confidence intervals don't include zero
#Step 1.4 Use bootstrapping to test the hypothesis: There is not a significant difference between UVa and Duke kidney transplants.
#What are the standard errors of the mean? What're the 95% confidence intervals? Do you accept or reject the null hypothesis?
bs.mean<-function(x,i)
{
return(mean(x[i]))
}
uvaduke.diff<-ts(uva$Kidney-duke$Kidney,1988,2016)
bs.uvaduke.diff<-boot(uvaduke.diff,bs.mean,R=10000)
bs.uvaduke.diff
boot.ci(bs.uvaduke.diff,0.95,type=c('bca','perc'))
#The standard error of the mean is about 4.29
#The 95% confidence intervals are (-29.07,-12.21) [Percentile]; (-29.38,-12.59) [BCa]
#We reject the null hypothesis because the confidence intervals don't include zero
#Step 1.5 Get the scatter plot matrix with the above 4 variables (UVA kidney, Duke kidney, R11 trnasplants, R11 donors). Describe what you observe. You can use either uva.pairs() {source("SPM_Panel.R")} or pairs().
uva.pairs(as.matrix(data.frame(uva$Kidney[-30],duke$Kidney[-30],r11xplant$Kidney[-30],r11donor$Kidney[-30])))
#we observe that the Duke center is more correlated with both Region 11 kidney transplants, as well as Region 11 kidney donors, than UVA
#The dist. for kidney transplants at UVA is somewhat symmetric with extreme modes in the center
#The dist. for kidney transplants at Duke is much less symmetric, closer to being uniform
#The UVA and Duke centers are almost equally correlated with Region 11 Donors
#The R11 Transplants and R11 donors for kidney transplants are extremely correlated (almost 1)
#***************************************************************
#
# Part 2: Linear Regression Models
#
#***************************************************************
# Test the hypothesis: There is no difference between the forecasted numbers of kidney
# transplants that will performed at UVA and at MCV in 2017.
# Step 2.1 Build a linear model:
# uva$Kidney-mcv$Kidney = b0+b1*r11donor$Kidney+e. Call it uva.kidney.lm.
# Analyze the result: R^2, model utility test, t-tests, etc.
uva.mcv.diff<-(uva$Kidney[-30]-mcv$Kidney[-30])
uva.kidney.lm<-lm(uva.mcv.diff~r11donor$Kidney[-30])
summary(uva.kidney.lm)
#We obtained an Adjusted R^2 value of .4122 and a Multiple R^2 value of .4332, indicating somewhat good fit
#The model utility test resulted in a p-value of .0001042, indicating that the model is highly significant, even at the .01 level
#The t-test for the r11donor variable results in a p-value of .000104, indicating that the paramater is different from zero
#These results indicate that the r11 donor variable is very useful in predicting the difference between the mean of uva and mcv kidney transplants
#For every increase in r11donor$kidney, uva kidney transplants decreases relative to mcv by -.072
#Step 2.2 Generate the diagnostic plots. Interpret the results of the diagnostic plots. Do you see any problem?
par(mfrow=c(2,2))
plot(uva.kidney.lm)
par(mfrow=c(1,1))
#The Residuals vs Fitted plot shows a lack of fit and heteroscendasticity
#The QQ plot shows that the tails of the distribution are not Gaussian
#The Residuals vs Leverage plot shows there are multiple outliers, none of which are influential
# Step 2.3 Estimate the model with bootstrapping (by residuals). Is b1 significant?
# Get the fitted values from the regression model
uvamcv.fit<-fitted(uva.kidney.lm)
# Get the residuals from the regression model
uvamcv.res<-residuals(uva.kidney.lm)
# Get the regression model
uvamcv.mod<-model.matrix(uva.kidney.lm)
# Bootstrapping LM
uvamcv.boot<-RTSB(uva.mcv.diff,r11donor$Kidney[-30],uvamcv.fit,uvamcv.res,uvamcv.mod,5000)
uvamcv.boot
sqrt(abs(var(uvamcv.boot$t)))
# 95% CI of r11donor
boot.ci(uvamcv.boot, .95, index=2)
#none of the confidence intervals include zero as a value
# Distribution of b1
par(mfrow = c(1,2))
hist(uvamcv.boot$t[,2], main = "Region 11 Donors",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvamcv.boot $t[,2])
qqline(uvamcv.boot $t[,2])
par(mfrow = c(1,1))
# Is b1 significant?
#b1 is significant because all four of the 95% confidence intervals for b1 estimate do not include zero, implying that b1 is not equal to zero
#the histogram for region 11 donor coefficient values forms almost a normal distribution, centered around -.07, implying that b1 is significant
#Step 2.4* (bonus) What about Duke? Repeat the above steps and compare the results.
# Test the hypothesis: There is no difference between the forecasted numbers of kidney
# transplants that will be performed at UVA and at Duke in 2017.
# Build a linear model and analyze the results
uva.duke.diff<-uva$Kidney[-30]-duke$Kidney[-30]
uva.duke.lm<-lm(uva.duke.diff~r11donor$Kidney[-30])
summary(uva.duke.lm)
#We obtained an Adjusted R^2 value of .04548 and a Multiple R^2 value of .079, indicating a worse fit than the previous model
#The model utility test resulted in a p-value of .1382, indicating that the model is not significant, contrasted to the previous model comparing UVA and MCV
#The t-test for the r11donor variable results in a p-value of .138, indicating that the paramater is not different from zero
#These results indicate that the r11 donor variable is not useful in predicting the difference between the mean of uva and duke kidney transplants
#the r11donor variable is much worse at predicting the difference between UVA and Duke than it is at predicting UVA and MCV kidney transplants
#Generate the diagnostic plots. Interpret the results of the diagnostic plots. Do you see any problem?
par(mfrow=c(2,2))
plot(uva.duke.lm)
par(mfrow=c(1,1))
#The Residuals vs Fitted plot also shows a lack of fit and heteroscendasticity
#The QQ plot shows that the distrbution is Gausian, even at the tails, different from the previous model
#The Residuals vs Leverage plot again shows there are multiple outliers, none of which are influential
#Estimate the model with bootstrapping (by residuals). Is b1 significant?
# Get the fitted values from the regression model
uvaduke.fit<-fitted(uva.duke.lm)
#Get the residuals from the regression model
uvaduke.resid<-residuals(uva.duke.lm)
#Get the regression model
uvaduke.mod<-model.matrix(uva.duke.lm)
#Bootstrapping LM [UVA and Duke]
uvaduke.boot<-RTSB(uva.duke.diff,r11donor$Kidney[-30],uvaduke.fit,uvaduke.resid,uvaduke.mod,5000)
uvaduke.boot
sqrt(abs(var(uvaduke.boot$t)))
#95% CI of r11donor
boot.ci(uvaduke.boot, .95, index=2)
#All 4 confidence intervals include zero as a value, in contrast to the confidence interavals for the previous model
# Distribution of b1
par(mfrow = c(1,2))
hist(uvaduke.boot$t[,2], main = "Region 11 Donors",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvaduke.boot $t[,2])
qqline(uvaduke.boot $t[,2])
par(mfrow = c(1,1))
# Is b1 significant?
#b1 is not significant for the model predicting the differences between UVA and Duke, in contrast to the previous model predicting the differences between UVA and MCV (which was significant)
#this is because all four of the confidence intervals for b1 included zero as a value
#in addition, the histogram for b1 has a much greater frequency for a coefficeint value of zero than for the previous model
#and the normal QQ plot has a sample quantile of zero that is much closer to a zero theoretical quantile than the previous model
#***************************************************************
#
# Part 3: Time Series Models
#
#***************************************************************
#Step 3.1 Generate the ACF and PACF plots of the residuals from your part 2 linear model for UVA and MCV kidney transplants. Interpret the results of the ACF and PACF plots. Do you recommend modeling the residuals? If so, what kind of model should you try based on these plots?
acf(uvamcv.res)
pacf(uvamcv.res)
#The acf and pacf plots indicate that the the residuals are stationary - exponential decay in the ACF plot
#However, the plots show that there are correlated residuals, indicating that there is still structure to be modeled
#I would recommend modeling the residuals with an AR(1) model because the PACF plot cuts off after lag 1, but the ACF shows sinusoidal decay
#Step 3.2 Based on the above ACF and PACF plots, fit an ar model to the residuals
# Add the AR model of the residuals to regression linear model based on the acf/pacf plots.
# Call this model uvamcv.kidney.lm2. Analyze the regression results.
uva.mcv.diff2<-(uva$Kidney[2:29]-mcv$Kidney[2:29])
uvamcv.kidney.lm2<- lm(uva.mcv.diff2~r11donor$Kidney[2:29]+uva.kidney.lm$residuals[1:28])
summary(uvamcv.kidney.lm2)
#The new model has an Adjusted R^2 of .787, indicating a great fit
#A model utility test resulted in a extremely significant p-value (very close to zero), indicating that the model is very significant
#Lastly, the p-values for both the r11donor variable and the residuals variable are significant, implying that the added residuals model is useful in predicting the difference in UVA and MCV kidney transplants
#Generate diagnostic plots for uvamcv.kidney.lm2. What are your observations?
par(mfrow=c(2,2))
plot(uvamcv.kidney.lm2)
par(mfrow=c(1,1))
#the residuals vs fitted plot indicates that while there is some heteroscendasticity, there is much less than in the previous model
#the normal QQ plot shows that the distribution is relatively normal
#there are also a few outliers, with one having a Leverage of close to .5
#overall, this model is a better fit than the previous model without the added residuals
#Step 3.3 Bootstrap the above time series model. Are the coefficients significant?
# Get the fitted values from the regression model
uvamcv.lm2.fit<-fitted(uvamcv.kidney.lm2)
# Get the residuals from the regression model
uvamcv.lm2.resid<-residuals(uvamcv.kidney.lm2)
# Get the regression model
uvamcv.lm2.mod<-model.matrix(uvamcv.kidney.lm2)
# Use the RTSB function to obtain the bootstrap
uvamcv.lm2.boot<-RTSB(uva.mcv.diff2,r11donor$Kidney[2:29],uvamcv.lm2.fit,uvamcv.lm2.resid,uvamcv.lm2.mod,5000)
# The estimates
uvamcv.lm2.boot
summary(uvamcv.kidney.lm2)
uvamcv.lm2.boot$t
sqrt(abs(var(uvamcv.lm2.boot$t)))
boot.ci(uvamcv.lm2.boot, .95, index=2) #for r11donor variable
boot.ci(uvamcv.lm2.boot, .95, index=3) #for residual variable
# Plot the results for the coeffiecient for region 11 donors
par(mfrow = c(1,2))
hist(uvamcv.lm2.boot$t[,2], main = "Region 11 Donors",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvamcv.lm2.boot$t[,2])
par(mfrow = c(1,1))
# Plot the results for the coeffiecient for time series components
par(mfrow = c(1,2))
hist(uvamcv.lm2.boot$t[,3], main = "Time Series Component",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvamcv.lm2.boot$t[,3])
par(mfrow = c(1,1))
# Are the coefficients significant?
#The coefficient for region 11 donors is very significant, due to the histogram of its coefficient values; there is a frequency of about zero for a coefficient value of 0
#The confidence intervals for the region 11 donors coefficient also do not contain zero in them
#The coefficient for the time series components is also very significant due to the histogram being centered around a coefficient value of .8
#The confidence intervals for the time sereies component coefficeint also do not contain zero in them.
#Step 3.5* (bonus) What about Duke? Repeat the above steps and compare the results.
# Generate the ACF and PACF plots of the residuals from your part 2 linear model for UVA and Duke kidney transplants. Interpret the results of the ACF and PACF plots. Do you recommend modeling the residuals? If so, what kind of model should you try based on these plots?
acf(uva.duke.lm$residuals)
pacf(uva.duke.lm$residuals)
#The plots show that there are correlated residuals, indicating that there is still structure to be modeled
#I would recommend modeling the residuals with an AR(2) model because the PACF plot cuts off after lag 2
#This is in contrast to UVA vs MCV in which we modeled the residuals with an AR(1) model
uva.duke.diff2<-(uva$Kidney[3:29]-duke$Kidney[3:29])
uvaduke.kidney.lm2<- lm(uva.duke.diff2~r11donor$Kidney[3:29]+uva.duke.lm$residuals[1:27]+uva.duke.lm$residuals[2:28])
summary(uvaduke.kidney.lm2)
#The new model has an Adjusted R^2 of .41, indicating a great fit
#A model utility test resulted in a extremely significant p-value (very close to zero), indicating that the model is very significant
#Lastly, the p-values for both the r11donor variable and the residuals variable are significant, implying that the added residuals model is useful in predicting the difference in UVA and MCV kidney transplants
#Generate diagnostic plots for uvamcv.kidney.lm2. What are your observations?
par(mfrow=c(2,2))
plot(uvaduke.kidney.lm2)
par(mfrow=c(1,1))
#the residuals vs fitted plot indicates that while there is some heteroscendasticity, there is much less than in the previous model
#the normal QQ plot shows that the distribution is relatively normal
#there are also a few outliers, with one having a Leverage of close to .5
#overall, this model is a better fit than the previous model without the added residuals
# Get the fitted values from the regression model
uvaduke.lm2.fit<-fitted(uvaduke.kidney.lm2)
# Get the residuals from the regression model
uvaduke.lm2.resid<-residuals(uvaduke.kidney.lm2)
# Get the regression model
uvaduke.lm2.mod<-model.matrix(uvaduke.kidney.lm2)
# Use the RTSB function to obtain the bootstrap
uvaduke.lm2.boot<-RTSB(uva.duke.diff2,r11donor$Kidney[3:29],uvaduke.lm2.fit,uvaduke.lm2.resid,uvaduke.lm2.mod,5000)
# The estimates
uvaduke.lm2.boot
summary(uvaduke.kidney.lm2)
boot.ci(uvaduke.lm2.boot, .95, index=2) #for r11donor variable
#According to the confidence intervals, the r11donor variable is significant because Percentile and BCa don't bracket zero
# Plot the results for the coeffiecient for region 11 donors
par(mfrow = c(1,2))
hist(uvaduke.lm2.boot$t[,2], main = "Region 11 Donors",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvaduke.lm2.boot$t[,2])
par(mfrow = c(1,1))
# Plot the results for the coeffiecient for time series components
par(mfrow = c(1,2))
hist(uvaduke.lm2.boot$t[,3], main = "Time Series Component",xlab ="Coefficient Values", col = "steelblue", breaks = 50)
qqnorm(uvaduke.lm2.boot$t[,3])
par(mfrow = c(1,1))
# Are the coefficients significant?
#The coefficient for region 11 donors is significant, due to the histogram of its coefficient values; there is a frequency of about zero for a coefficient value of 0
#The confidence intervals for the region 11 donors coefficient also do not contain zero in them
#The coefficient for the time series components is also significant due to the histogram being centered around a coefficient value of .8
#The confidence intervals for the time sereies component coefficeint also do not contain zero in them.
#***************************************************************
#
# Part 4: Predicting Differences in Kidney Transplants Part 1
#
#***************************************************************
#Step 4.1 Build an AR model to predict the difference in 2017
uvamcv.diff<-ts(uva$Kidney-mcv$Kidney,1988,2017)
uvamcv.ar<-ar(uvamcv.diff,method="yule-walker")
#Step 4.2 Use the predict function with ar model to forecast 2017 differences between UVA and MCV
uvamcv.pred<-predict(uvamcv.ar,newdata=uvamcv.diff)
uvamcv.pred<-predict(uvamcv.ar,se.fit=T,interval="predict")
uvamcv.pred
# Calculate the CI and plot the time series and prediction and CIs on a graph
# Plot the historical time series, the new prediction, and CIs on a graph
uvamcv.pred$pred+1.96*uvamcv.pred$se #upper CI
uvamcv.pred$pred-1.96*uvamcv.pred$se #lower CI
#The CI is (-45, 21)
plot(uvamcv.diff,ylim=c(-90,30),type='o') #historical time series
segments(2016,uvamcv.pred$pred,col = "red",2017) # prediction
segments(2016,uvamcv.pred$pred+1.96*uvamcv.pred$se,col = "red",2017,lty = "dashed") # upper CI
segments(2016,uvamcv.pred$pred-1.96*uvamcv.pred$se,col = "red",2017,lty = "dashed") # lower CI
# What do you observe?
#Observe that the predicting for 2017 is very close to the actual 2017 value, which is much greater than for 2016.
#The confidence interval is also very wide, with the lower bound being much around -45 and the upper bound being around 21
#Step 4.3 Bootstrapping the difference of UVa and MCV in 2017
# To obtain a bootstrap estimate of the prediction for 2017
# use the TSB function in the source file.
# It takes three arguments:
# tsint - the time series
# oth.arg - the data for the new estimate
# boot.number- number of replications (default=1000)
uvamcv.boot<-TSB(uvamcv.diff,uvamcv.pred$pred,5000)
uvamcv.boot
tsboot.ci(uvamcv.boot)
# Interpret the results. Is there a significant difference between UVA and MCV in 2017?
#There is a significant difference between UVA and MCV in 2017
#the mean difference was estimated as -13, and the 95% CI was (-17.14,-9.3) which doesn't include zero
#The actual 2017 difference falls with in the bootstrapping interval
#Step 4.4* (bonus) What about Duke? Repeat the above steps and compare for Duke.
uvaduke.kid.diff<-ts(uva$Kidney-duke$Kidney,1988,2017)
uvaduke.ar.kid<-ar(uvaduke.kid.diff, method = "yule-walker")
uvaduke.kidney.pred<-predict(uvaduke.ar.kid,newdata=uvaduke.kid.diff)
plot(uvaduke.kid.diff,type='o')
segments(2016,uvaduke.kidney.pred$pred,col = "red",2017) # Prediction
segments(2016,uvaduke.kidney.pred$pred+1.96*uvaduke.kidney.pred$se,col = "red",2017,lty = "dashed") # upper CI
segments(2016,uvaduke.kidney.pred$pred-1.96*uvaduke.kidney.pred$se,col = "red",2017,lty = "dashed") # lower CI
#The prediction is very close to the actual 2017 difference.
#The 95% CI is very wide and contains the actual 2017 difference
diff.boot<-TSB(uvaduke.kid.diff,uvaduke.kidney.pred$pred,5000)
diff.boot
tsboot.ci(diff.boot)
#There is a significant difference between UVA and Duke in 2017
#the mean difference was estimated as -20.96, and the 95% CI was (-24.22,-17.65) which doesn't bracket zero
#***************************************************************
#
# Part 5: Predicting Differences in Kidney Transplants Part 2
#
#***************************************************************
#Step 5.1 Develop an AR model of region 11 kidney donors
#Plot an acf/pacf to estimate the model order for region 11 kidney donors - what model order do you suggest?
acf(r11donor$Kidney[-30])
pacf(r11donor$Kidney[-30])
#an AR(1) model is recommended because the pacf cuts off after lag 1
#Use ar() to fit an ar model to region 11 kidney donors from 1988-2016
r11donor.ar<-ar(r11donor$Kidney[-30],method="yule-walker")
r11donor.ar
#Step 5.2 Forecast the R11 donors and standard errors for 2017 using your ar model from step 5.1. Use forecast from the library(forecast).
library(forecast)
r11donor.pred <- forecast(r11donor.ar,h=1)
r11donor.pred
#Step 5.3 Use the linear model from part 3.2 combined with the forecast of region 11 kidney donors
#to forecast the differences in number of kidney transplants between UVa and MCV for 2017.
#Use the predict() function
# Creating the new data frame
uvamcv.nd<-data.frame(r11k=r11donor.pred$mean,uvamcv.lm.e1=uva.kidney.lm$residuals[29])
# Predict the linear model with the time series
uvamcv.new<-predict(uvamcv.kidney.lm2,newdata=uvamcv.nd,num=5000)
#Step 5.4 Bootstrap the Forecast from the linear model combined with the forecast of region 11 kidney donors to forecast the differences in number of kidney transplants between UVa and MCV for 2017.
# Bootstrap prediction
r11donor.kidney<-r11donor$Kidney[-30]
r11k <- r11donor.kidney[2:29]
uvamcv.dm <- data.frame(uvamcv.diff[2:29], r11k, uva.kidney.lm$residuals[1:28])
r11donor.boot <- RFB(uvamcv.dm, model = uvamcv.kidney.lm2, ndata = uvamcv.nd, num=2000)
# Bootstrap plot
plot(r11donor.boot, index = 1)
# Bootstrap confidence intervals
r11donor.boot.ci<-boot.ci(r11donor.boot, index=1)
r11donor.boot.ci
# Interpret the results
#The bootstrapping the r11donor$Kidney is not significant because the confidence intervals include zero
#Step 5.5 Plot the current and predictions for each value along with the confidence intervals. Describe your observations.
uvamcv<-uva$Kidney-mcv$Kidney
ticks<-c(1988:2017)
plot(uvamcv~uva$Year,xlim=c(1988,2017), type="o",xlab="Years",ylab="No. of kidney")
segments(2017,r11donor.boot$t0[1],2017, r11donor.boot.ci$percent[4],lty="dashed")
segments(2017,r11donor.boot$t0[1],2017, r11donor.boot.ci$percent[5],lty="dashed")
#Observations?
#The actual difference for 2017 falls in the bootstrapping confidence interval
#Step 5.6* (bonus) What about Duke? Repeat the above steps for Duke.
#Plot an acf/pacf to estimate the model order for region 11 kidney donors - what model order do you suggest?
acf(r11donor$Kidney[-30])
pacf(r11donor$Kidney[-30])
#an AR(1) model is recommended because the pacf cuts off after lag 1
#Use ar() to fit an ar model to region 11 kidney donors from 1988-2016
r11donor.ar<-ar(r11donor$Kidney[-30],method="yule-walker")
r11donor.ar
#Step 5.2 Forecast the R11 donors and standard errors for 2017 using your ar model from step 5.1. Use forecast from the library(forecast).
library(forecast)
r11donor.pred <- forecast(r11donor.ar,h=1)
r11donor.pred
#Step 5.3 Use the linear model from part 3.2 combined with the forecast of region 11 kidney donors
#to forecast the differences in number of kidney transplants between UVa and MCV for 2017.
#Use the predict() function
# Creating the new data frame
uvamcv.nd<-data.frame(r11k=r11donor.pred$mean,uvamcv.lm.e1=uva.kidney.lm$residuals[29])
# Predict the linear model with the time series
uvamcv.new<-predict(uvamcv.kidney.lm2,newdata=uvamcv.nd,num=5000)
#Step 5.4 Bootstrap the Forecast from the linear model combined with the forecast of region 11 kidney donors to forecast the differences in number of kidney transplants between UVa and MCV for 2017.
uvaduke.diff<-ts(uva$Kidney-duke$Kidney,1988,2017)
uvaduke.dm <- data.frame(uvaduke.diff[2:29], r11k[1:28], uva.duke.lm$residuals[1:28])
r11donor.boot <- RFB(uvaduke.dm, model = uvaduke.kidney.lm2, ndata = uvaduke.nd, num=2000)
# Bootstrap plot
plot(r11donor.boot, index = 1)
# Bootstrap confidence intervals
r11donor.boot.ci<-boot.ci(r11donor.boot, index=1)
r11donor.boot.ci
# Interpret the results
#The bootstrapping the r11donor$Kidney is not significant because the confidence intervals include zero
#Step 5.5 Plot the current and predictions for each value along with the confidence intervals. Describe your observations.
uvamcv<-uva$Kidney-mcv$Kidney
ticks<-c(1988:2017)
plot(uvamcv~uva$Year,xlim=c(1988,2017), type="o",xlab="Years",ylab="No. of kidney")
segments(2017,r11donor.boot$t0[1],2017, r11donor.boot.ci$percent[4],lty="dashed")
segments(2017,r11donor.boot$t0[1],2017, r11donor.boot.ci$percent[5],lty="dashed")
#Observations?
#The actual difference for 2017 falls in the bootstrapping confidence interval<file_sep>/README.md
# Consulting-Cases-Presentation
|
8398c10e287ab43220aa89d0761bc6265d73390c
|
[
"Markdown",
"R"
] | 2
|
R
|
ff-uva/Consulting-Cases-Presentation
|
c523ae13d954d15c72cfb4bca455a13ceedec7d8
|
463616f44b86e2325ed7fa33eff9b91230837924
|
refs/heads/master
|
<file_sep>#include "omp.h"
#include "iostream"
#include <stdio.h>
using namespace std;
const int NMAX = 50;
const int LIMIT = 1;
void main()
{
setlocale(LC_ALL, "Russian");
int i, j;
float sum;
//Переменные для расчета времени
double start;
double end;
//<NAME>ский, потому что иначе будет Stack Overflow
int** a = new int* [NMAX];
for (i = 0; i < NMAX; i++)
a[i] = new int[NMAX];
start = omp_get_wtime();
/*Начало параллельного фрагмента*/
#pragma omp parallel shared(a) if (NMAX>LIMIT)
{
#pragma omp for private(i,j)
for (i = 0; i < NMAX; i++)
for (j = 0; j < NMAX; j++)
a[i][j] = i + j;
#pragma omp for private(i,j,sum)
for (i = 0; i < NMAX; i++)
{
sum = 0;
for (j = 0; j < NMAX; j++)
sum += a[i][j];
//printf("Сумма элементов строки %d равна %f\n", i, sum);
}
}
/* Завершение параллельного фрагмента */
end = omp_get_wtime();
//cout << endl << sum << endl;
for (i = 0; i < NMAX; i++)
delete[]a[i];
cout << "Время " << end - start << endl;
}
|
b863ddb411ccfbb3e07e2fbb7bc84830b1beda9d
|
[
"C++"
] | 1
|
C++
|
Stuthemp/openMP_labs
|
e7fbd019a3273206f2d0b3b959799bfca1028d7c
|
5c183cb9ff08e7e54df2a7cad531d57ebb07b8ef
|
refs/heads/master
|
<file_sep>import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
backlog: null,
todo: null,
doing: null,
done: null
},
mutations: {
setBackLog (state, payload) {
state.backlog = payload
},
setTodo (state, payload) {
state.todo = payload
},
setDoing (state, payload) {
state.doing = payload
},
setDone (state, payload) {
state.done = payload
}
},
actions: {
},
getters: {
getBacklogs: state => {
return state.backlog
},
getTodos: state => {
return state.todo
},
getDoing: state => {
return state.doing
},
getDone: state => {
return state.done
}
}
})
<file_sep># Kandang
Kandang apps is a simple kanban application by <NAME>
### Database
Using firebase database with 4 parent :
-backlog
-todo
-doing
-done
### Installation and Usage
Kandang Apps requires [Node.js](https://nodejs.org/) v4+ to run.
Install the dependencies and devDependencies and start the client.
```sh
$ cd kandang
$ npm install
$ npm run serve
```
|
096c4da72800eb4a2c52f3c7b9b45fb74007c7fe
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
fuadinaqi/kandang
|
f9ac281189d9c5c2f80aa89f10c890378050ecf1
|
b76a343cf401d46b8472c8b12a8124c8598d22c5
|
refs/heads/master
|
<file_sep>// when sampling, how wide/long is a single sample? note: splat is centered
// around a randomly drawn coordinate
// 0 -> 1 pixel, 1-> 3 pixels, etc...
var SPLAT_SIZE=1;
// colors
var MODEL_COLORS = ['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999'];
// maximum height of a gaussian in the model plot
var P_HEIGHT = 40;
// to speed up sampling, we create a map from a uniform probability distribution to
// the gaussin mix distribution. MAP_SIZE determines the resolution of this map
// (higher resolution=less aliasing)
var MAP_SIZE = 100;
// activate callbacks on model update
var UPDATE_CALLBACK = true;
function gauss(x, p) {
var mue = p[0]
var delta = p[1];
var scaler = (p[2] === undefined || p[2] === null) ? 1 : p[2];
var k = delta * Math.sqrt(2*Math.PI);
return scaler * (1/k)*Math.exp(-0.5 * Math.pow((x-mue)/delta, 2) );
}
function GaussMix(w, h, svg)
{
this.w = w;
this.h = h;
this.svg = svg;
this.models = [];
this.modelMaxX = 0;
this.modelMaxY = 0;
this.cdfX = null;
this.mapX = null;
this.cdfY = null;
this.mapY = null;
this.callbacks = [];
}
GaussMix.prototype.copyTo = function(newModel, dontUpdate)
{
if (!newModel) {
newModel = new GaussMix(this.w, this.h, null);
}
else {
newModel.w = this.w;
newModel.h = this.h;
}
newModel.models = [];
for (var i=0; i<this.models.length; i++) {
var m = this.models[i];
newModel.models.push({
t: m.t,
param: m.param.slice(),
axis: m.axis
});
}
if (!dontUpdate) {
newModel.updateModel();
}
return newModel;
}
GaussMix.prototype.addCallback = function(_callback) {
var _id = Math.random();
this.callbacks.push({
callback: _callback,
id: _id
});
return _id;
}
GaussMix.prototype.unregisterCallback = function(callbackID) {
for (var i=0; i<this.callbacks.length; i++) {
if (this.callbacks[i].id == callbackID) {
this.callbacks.splice(i, 1);
return true;
}
}
return false;
}
GaussMix.prototype.fireCallbacks = function() {
if (!UPDATE_CALLBACK) {
return;
}
for (var i=0; i<this.callbacks.length; i++) {
this.callbacks[i].callback(this);
}
}
GaussMix.prototype.init = function()
{
this.models = [];
// add a few random gausses
for (var i=0, count=1+Math.floor(.499 + Math.random()*3); i<count; i++ ) {
this.add('x');
}
for (var i=0, count=1+Math.floor(.499 + Math.random()*3); i<count; i++ ) {
this.add('y');
}
this.updateModel();
}
GaussMix.prototype.computeCDFs = function()
{
var w = this.w;
var h = this.h;
var X=d3.range(0, w);
var Y=d3.range(0, h);
var cdfX, cdfY;
for (var x=0; x<w; x++) {
X[x]=0;
}
for (var y=0; y<h; y++) {
Y[y]=0;
}
// compute PDFs
for (var m=0; m < this.models.length; m++)
{
var model = this.models[m];
var outs = model.outputs;
var len = model.axis == 'x' ? w : h;
var P = model.axis == 'x' ? X : Y;
for (var i=0; i<len; i++)
{
P[i] += outs[i].y;
}
}
// compute CDFs and normalize
cdfX=d3.range(0, w);
cdfY=d3.range(0, h);
var cummX=0;
for (var i=0, len=X.length; i<len; i++) {
cummX += X[i];
cdfX[i] = 0;
}
for (var i=0, cdf=0, len=X.length; i<len; i++) {
X[i] /= cummX;
cdf += X[i];
cdfX[i] = cdf;
}
var cummY=0;
for (var i=0, len=Y.length; i<len; i++) {
cummY += Y[i];
}
for (var i=0, cdf=0, len=Y.length; i<len; i++) {
Y[i] /= cummY;
cdf += Y[i];
cdfY[i] = cdf;
}
this.pdfX = X;
this.pdfY = Y;
this.cdfX = cdfX;
this.cdfY = cdfY;
/*
// old way of computing CDFs; slightly more accurate but slower
cdfX=d3.range(0, w);
cdfY=d3.range(0, h);
var cumm=0;
for (var x=0; x<w; x++) {
cumm+=X[x];
cdfX[x]=cumm;
}
for (var x=0; x<w; x++) {
cdfX[x] /= cumm;
}
var cumm=0;
for (var y=0; y<h; y++) {
cumm+=Y[y];
cdfY[y]=cumm;
}
for (var y=0; y<h; y++) {
cdfY[y] /= cumm;
}
this.cdfX = cdfX;
this.cdfY = cdfY;
*/
// compute a descrete p map: this allows us to map from discrete
// uniform p distribution to the distribution characterized by the above CDFs
// larger MAP_SIZE=less aliasing (at the cost of memory and initial compute time)
mapX=d3.range(w*MAP_SIZE);
mapY=d3.range(h*MAP_SIZE);
for (var x=0, last=0, p=0, len=w*MAP_SIZE, step=1/(w*MAP_SIZE); x<len; x++, p+=step)
{
while (cdfX[last] <= p)
{
last++;
}
mapX[x]=last;
}
for (var y=0, last=0, p=0, len=h*MAP_SIZE, step=1/(h*MAP_SIZE); y<len; y++, p+=step)
{
while (cdfY[last] < p)
{
last++;
}
mapY[y]=last;
}
this.mapX = mapX;
this.mapY = mapY;
}
GaussMix.prototype.sampleModel = function(_iterations, _field, rotate)
{
var SPLAT_AREA=(SPLAT_SIZE*2+1)*(SPLAT_SIZE*2+1);
var splat = [];
for (var j=0;j<SPLAT_AREA; j++) {
splat.push(0);
}
if (!this.mapX) {
this.computeCDFs();
}
var mapX = this.mapX;
var mapY = this.mapY;
var pdfX = this.pdfX;
var pdfY = this.pdfY;
var w = this.w;
var h = this.h;
var w_1 = w-1;
var h_1 = h-1;
var w_2 = Math.floor(w/2);
var h_2 = Math.floor(h/2);
// reset scalar field with zeros
_field.zero();
var view = _field.view;
var iterations = _iterations;
/*
rotation stuff
var theta, cosTheta, sinTheta; rotate=ROTATE;
if (rotate) {
theta = (Math.random()*2-1) * Math.PI;
cosTheta = Math.cos(theta);
sinTheta = Math.sin(theta);
}
*/
for (var i=0; i<iterations; i++)
{
var x = Math.min(mapX.length-1, Math.floor(Math.random()*mapX.length));
var y = Math.min(mapY.length-1, Math.floor(Math.random()*mapY.length));
var R=mapY[y];
var C=mapX[x];
/*
// rotation stuff
if (rotate)
{
var tY = R-h_2, tX = C-w_2;
var x_ = Math.floor(.5 + tX*cosTheta - tY*sinTheta + w_2);
var y_ = Math.floor(.5 + tX*sinTheta + tY*cosTheta + h_2);
// test if within range
if (x_ >= 0 && x_ < w && y_ >=0 && y_ < h) {
R = y_;
C = x_;
}
}
*/
// create a splat
var I=0;
var R0 = Math.max(0, R-SPLAT_SIZE), R1 = Math.min(h_1, R+SPLAT_SIZE);
var C0 = Math.max(0, C-SPLAT_SIZE), C1 = Math.min(w_1, C+SPLAT_SIZE);
var P=0;
// compute total density at this splat
for (var r=R0; r<=R1; r++)
{
for (var c=C0; c<=C1; c++, I++)
{
var p = pdfX[c]*pdfY[r];
splat[I] = p;
P += p;
}
}
var iP = 1/P;
I = 0;
// distribute density throughout the splat according to the PDF
for (var r=R0; r<=R1; r++)
{
for (var c=C0; c<=C1; c++, I++)
{
view[ r*w + c ] += splat[I] * iP;
}
}
//view[ R*w + C ] += 1.0;
}
_field.normalize();
_field.updated();
}
GaussMix.prototype.add = function(axis)
{
var L = axis == 'x' ? this.w : this.h;
this.models.push({
t: gauss,
param: [
L * ( 0.5 + (Math.random()*2 - 1) * 0.5 ), // center
L * ( 0.1 + (Math.random()*2 - 1) * (.1/2)), // std
0.7 + (Math.random()*2 - 1)*0.3
],
axis: axis
});
this.updateModel();
}
GaussMix.prototype.remove = function(axis)
{
var m=null, mCount=0;
for (i=0; i<this.models.length; i++) {
if (this.models[i].axis==axis) {
mCount++;
m=i;
}
}
if (mCount > 1) {
this.models.splice(m, 1);
this.updateModel();
}
}
GaussMix.prototype.klDivergence = function()
{
// too lazy to implement (also, probably unneeded for now)
return 0;
}
// randomly perturbs the model a bit
GaussMix.prototype.randomPerturb = function()
{
var CENTER_PERTURB = .1/2;
var DENSITY_PERTURB = 4; // of maxiumum weight
var maxXDensity = this.modelMaxX;
var maxYDensity = this.modelMaxY;
for (var i=0; i<this.models.length; i++) {
var m = this.models[i];
var c = m.axis=='x' ? WIDTH : HEIGHT;
c *= (Math.random()*2-1) * CENTER_PERTURB;
var d = m.axis=='x' ? maxXDensity : maxYDensity;
d *= (Math.random()*2-1) * DENSITY_PERTURB;
m.param[0] += c;
m.param[2] += d;
// don't bother perturbing the SD for now
}
this.updateModel();
}
GaussMix.prototype.updateModel = function()
{
var modelMaxX = 0;
var modelMaxY = 0;
var models = this.models;
// compute probability density
var modelOutputs = [];
for (var m=0; m<models.length; m++)
{
var model = models[m];
var points = [];
if (model.axis == 'x') {
points = d3.range(0, this.w);
}
else if (model.axis == 'y') {
points = d3.range(0, this.h);
}
var maxVal = 0;
for (var i=0; i<points.length; i++) {
var p = points[i];
var out = {
x: p,
y: model.t(p, model.param)
}
maxVal = Math.max(maxVal, out.y) ;
points[i] = out;
}
model.outputs = points;
modelOutputs.push(points);
if (model.axis == 'x')
{
modelMaxX = Math.max(modelMaxX, maxVal);
}
else {
modelMaxY = Math.max(modelMaxY, maxVal);
}
}
this.modelMaxX = modelMaxX;
this.modelMaxY = modelMaxY;
// compute CDFs and maps
this.computeCDFs();
// plot to svg
this.plotModelCurves();
}
GaussMix.prototype.plotModelCurves = function()
{
if (!this.svg) {
return;
}
// plot distribution
var lineGeneratorX = (function(models) {
return d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return -P_HEIGHT * (d.y/models.modelMaxX); });
})(this);
var lineGeneratorY = (function(models) {
return d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return -P_HEIGHT * (d.y/models.modelMaxY); });
})(this);
var paths = this.svg.selectAll('path').data(this.models)
paths.exit().remove();
var enter = paths.enter().append('path');
paths = paths.merge(enter);
(function(models, paths) {
paths
.attr('d', function(d) {
return d.axis=='x' ? lineGeneratorX(d.outputs) : lineGeneratorY(d.outputs)
})
.attr('class', 'modelPath')
.attr('stroke', function(d, i) {
return MODEL_COLORS[Math.min(i, MODEL_COLORS.length-1)];
})
.attr('transform', function(d)
{
if (d.axis == 'y') {
return 'translate(' + models.w + ',0) ,rotate(90)';
}
else {
return null;
}
})
.on('mouseover', function() { d3.select(this).style('stroke', '#333333'); })
.on('mouseout', function(d, j) {
d3.select(this).style('stroke', MODEL_COLORS[Math.min(j, MODEL_COLORS.length-1)]);
});
paths.on('mousedown', function(d) {
var mouseCoord = d3.mouse(models.svg.node());
(function(model, oldDelta, oldScaler, mouseCoord) {
d3.select(document).on('mousemove.moveDist', function() {
var dMove, dScaler, mouse = d3.mouse(models.svg.node());
if (model.axis=='x')
{
dMove = mouse[0] - mouseCoord[0];
dScaler = -(mouse[1] - mouseCoord[1]);
}
else {
dMove = mouse[1] - mouseCoord[1];
dScaler = mouse[0] - mouseCoord[0];
}
var newDelta = oldDelta + dMove;
newDelta = Math.max(1, newDelta);
newDelta = Math.min(model.axis=='x' ? models.w-1 : models.h-1, newDelta);
newScaler = oldScaler + dScaler/P_HEIGHT;
model.param[1] = newDelta;
model.param[2] = Math.max(0.05, newScaler);
models.updateModel();
});
d3.select(document).on('mouseup.moveDist', function()
{
models.fireCallbacks();
d3.select(document).on('mousemove.moveDist', null)
d3.select(document).on('mouseup.moveDist', null)
})
})(d, d.param[1], d.param[2], mouseCoord);
});
})(this, paths);
// plot model center
var lines = this.svg.selectAll('line').data(this.models);
(function(lines, models) {
lines.exit().remove();
enter = lines.enter().append('line');
lines = lines.merge(enter);
lines
.attr('x1', function(d) {
return d.axis=='x' ? d.param[0] : -1 * (-P_HEIGHT * d.t(d.param[0], d.param)/models.modelMaxY);
})
.attr('x2', function(d) { return d.axis=='x' ? d.param[0] : 0; })
.attr('y1', function(d) { return d.axis=='x' ? (-P_HEIGHT * d.t(d.param[0], d.param)/models.modelMaxX) : d.param[0]})
.attr('y2', function(d) { return d.axis=='x' ? 0 : d.param[0] })
.attr('transform', function(d)
{
if (d.axis == 'y') {
return 'translate(' + models.w + ',0)';
}
else {
return null;
}
})
.attr('stroke', function(d, i) {
return MODEL_COLORS[Math.min(i, MODEL_COLORS.length-1)];
})
.style('stroke-width', '3px')
.on('mouseover', function() { d3.select(this).style('stroke', '#333333'); })
.on('mouseout', function(d, j)
{
d3.select(this).style('stroke', MODEL_COLORS[Math.min(j, MODEL_COLORS.length-1)]);
})
.on('mousedown', function(d) {
var mouseCoord = d3.mouse(models.svg.node());
(function(model, oldMue, oldScaler, mouseCoord) {
d3.select(document).on('mousemove.moveLine', function() {
var dMove=0, dScaler=0, mouse = d3.mouse(models.svg.node());
if (model.axis=='x')
{
dMove = mouse[0] - mouseCoord[0];
//dScaler = -(mouse[1] - mouseCoord[1]);
}
else {
dMove = mouse[1] - mouseCoord[1];
//dScaler = mouse[0] - mouseCoord[0];
}
var newMue = oldMue + dMove;
newMue = Math.max(0, newMue);
newMue = Math.min(model.axis=='x' ? models.w-1 : models.h-1, newMue);
newScaler = oldScaler + dScaler/P_HEIGHT;
model.param[0] = newMue;
model.param[2] = Math.max(0.05, newScaler);
models.updateModel();
});
d3.select(document).on('mouseup.moveLine', function() {
// notify there's been a model update
models.fireCallbacks();
d3.select(document).on('mousemove.moveLine', null)
d3.select(document).on('mouseup.moveLine', null)
})
})(d, d.param[0], d.param[2], mouseCoord)
})
})(lines, this);
}
<file_sep>function LineupExperiment(w, h, _lineupN, gMain, gDecoy, nullOption, table)
{
// width / height of the model
this.w = w;
this.h = h;
// whether to randomly perturb decoy (subjec to perturbation parameters)
this.perturb = true;
// create model
var modelType = GaussMixBivariate;
if (typeof MODEL_TYPE !== 'undefined') {
modelType = MODEL_TYPE;
}
this.main = new modelType(w, h, gMain);
this.decoy = new modelType(w, h, gDecoy);
this.randomModel();
// lineup
this.lineupN = _lineupN;
if (table) {
this.lineup = new LineupFixed(w, h, _lineupN, this.main, this.decoy, nullOption, table);
}
else {
this.lineup = new Lineup(w, h, _lineupN, this.main, this.decoy, nullOption);
}
this.canMakeSelection = false;
this.nullOption = nullOption;
}
LineupExperiment.prototype.dispose = function() {
this.lineup.dispose();
this.main.dispose();
this.decoy.dispose();
this.main = null;
this.decoy = null;
this.w = null;
this.h = null;
}
LineupExperiment.prototype.enableSelection = function(t) {
this.canMakeSelection = t;
}
LineupExperiment.prototype.getMain = function() {
return this.main;
}
LineupExperiment.prototype.getDecoy = function() {
return this.decoy;
}
LineupExperiment.prototype.copyToDecoy = function()
{
this.main.copyTo(this.decoy);
if (this.perturb)
{
this.decoy.randomPerturb();
}
this.decoy.fireCallbacks();
}
LineupExperiment.prototype.setClickFeedback = function(correct, incorrect)
{
this.correct = correct;
this.incorrect = incorrect;
}
LineupExperiment.prototype.randomModel = function()
{
this.curDistance = null;
this.main.init();
this.copyToDecoy();
}
LineupExperiment.prototype.modelDecoyDistance = function()
{
this.curDistance = this.main.pdfDistance(this.decoy);
return this.curDistance;
}
LineupExperiment.prototype.getAnswer = function() {
return this.answer;
}
LineupExperiment.prototype.highlightCorrect = function(show)
{
this.domSelection.selectAll('td').style('background-color', null);
d3.select('div.nullOption').style('border', 'solid 1px black');
var correctID = '#sample' + this.lineup.getCorrectAnswer();
var td = d3.select(correctID).node().parentNode;
if (this.trialHasDecoy) {
d3.select(td)
.style('background-color', show ? '#aaaaaa' : null);
}
else
{
d3.select('div.nullOption')
.style('border', show ? 'solid 10px #aaaaaa' : 'solid 1px black');
}
// 00cc66
}
LineupExperiment.prototype.randomLineup = function(fidelity, domSelection, noDecoy)
{
var SEL_BORDER = "#ff623b"//"solid 4px #fcbd00";
// new lineup
this.trialHasDecoy = noDecoy ? false : true;
this.lineup.layoutCanvases(domSelection);
this.lineup.sample(fidelity, noDecoy);
this.domSelection = domSelection;
this.correctAnswer = this.lineup.getCorrectAnswer();
// clear out old selection / answer
this.answer = null;
if (!this.tdSelection) {
this.tdSelection = domSelection.selectAll('td')
}
var canvasType = 'canvas';
if (typeof CANVAS_TYPE === 'string') {
canvasType = CANVAS_TYPE
}
if (!this.canvasSelection) {
this.canvasSelection = domSelection.selectAll(canvasType)
}
if (!this.nullSelection) {
this.nullSelection = domSelection.selectAll('div.nullOption');
}
this.tdSelection.style('background-color', null);
// setup callbacks
(function(lineup, dom, noDecoy, correctAnswer)
{
var canvasType = 'canvas';
if (typeof CANVAS_TYPE === 'string') {
canvasType = CANVAS_TYPE
}
dom.selectAll(canvasType).on('click', function()
{
console.log('click');
if (lineup.incorrect) lineup.incorrect();
if (lineup.canMakeSelection)
{
lineup.tdSelection.style('background-color', null);
lineup.nullSelection.style('border', 'solid 1px black');
d3.select(this.parentNode).style('background-color', SEL_BORDER);
}
lineup.answer = "0";
lineup.canvasIndex = d3.select(this).attr('class').substr(5);
});
dom.selectAll('div.nullOption').on('click', function()
{
if (noDecoy && lineup.correct) lineup.correct();
else if (!noDecoy && lineup.incorrect) lineup.incorrect();
lineup.answer = noDecoy ? '1' : '0';
lineup.tdSelection.style('background-color', null);
d3.select(this).style('border', 'solid 10px ' + SEL_BORDER)
lineup.canvasIndex = '98';
});
})(this, domSelection, noDecoy, this.correctAnswer);
(function(lineup, dom, noDecoy, correctAnswer)
{
d3.select('#sample' + correctAnswer).on('click', function()
{
if (lineup.correct) lineup.correct();
if (lineup.canMakeSelection)
{
lineup.tdSelection.style('background-color', null);
lineup.nullSelection.style('border', 'solid 1px black');
d3.select(this.parentNode).style('background-color', SEL_BORDER);
}
lineup.answer = noDecoy ? '0' : '1';
lineup.canvasIndex = d3.select(this).attr('class').substr(5);
})
})(this, domSelection, noDecoy, this.correctAnswer);
}
// generates a lineup with an expected distance between the main and the decoy
// ideally, set tolerance level to STD (from simulations)
var LINEUP_TOLERANCE = 0.01;
var LINEUP_MAX_TRIAL = 60;
var LINEUP_MAX_ROUNDS = 3;
LineupExperiment.prototype.modelWithExpectation = function(expectation)
{
var range = expectation && typeof(expectation) == 'object';
var tolerance = LINEUP_TOLERANCE;
var converged = false;
var distance = null;
var iterations = 0;
this.answer = null;
for (var round=0; !converged && round<LINEUP_MAX_ROUNDS; round++)
{
for (var trial=0; !converged && trial<LINEUP_MAX_TRIAL; trial++, iterations++)
{
this.randomModel();
distance = this.modelDecoyDistance();
if (!expectation)
{
console.log("no expectaiton. Converged");
converged = true;
}
else
{
if (range && distance >= expectation[0] && distance <= expectation[1])
{
converged = true;
}
if (Math.abs(distance-expectation) <= tolerance)
{
converged = true;
}
}
}
if (!converged)
{
tolerance *= 2;
}
}
//console.log("[" + iterations + "]: requested: " + expectation + ", got: " + distance);
this.curDistance = distance;
this.curExpectation = expectation;
this.converged = converged;
this.iterations = iterations;
return distance;
}
LineupExperiment.prototype.getCurDistance = function() {
return this.curDistance;
}
LineupExperiment.prototype.getCurExpectation = function() {
return this.curExpectation;
}
<file_sep>var RAMP_W = 230;
var RAMP_H = 30;
var RAMP_OFF_X = 80;
var RAMP_OFF_Y = 100;
var PATCH_W = 15;
var PATCH_H = 15;
var PATCH_GAP = 4;
var PATCH_OFF_X = -60
var PATCH_OFF_Y = 30;
var PLOT_H = 40;
var PLOT_OFFSET = 5;
var CONTROL_R = 4;
// number of samples to take in the computinglor ramp
// when computing difference
var DIFF_SAMPLES = 50;
// size of local speed window and number of samples
var LOCAL_SPEED_W = .1;
var LOCAL_SPEED_S = 20*2;
// allow more leeway in tuning lightning
var PERMISSIVE_L_TUNING = false;
function ColorRamp(_colors, _svg, _colorPicker)
{
this.colors = _colors ||
[
// default is black / white ramp interpolated in LAB space
{
value: 0.0,
lab: [15, 0, 0]
},
{
value: 1.0,
lab: [80, 0, 0]
}
];
this.colormap = null;
this.svg = _svg;
// create structure for the SVG
var g = this.svg.append('g');
g.attr('transform', 'translate(' + RAMP_OFF_X + ',' + RAMP_OFF_Y + ')');
this.g = g;
// create an image to be used to render the colormap onto
(function(ramp) {
ramp.colorRampImage = g.append('image')
.attr('width', RAMP_W + "px").attr('height', RAMP_H + 'px')
.on('mousemove', function()
{
var m = d3.mouse(this);
var t = m[0]/RAMP_W;
var color = ramp.colormap.mapValue(t, true);
if (color) {
ramp.colorPicker.brushColor(color);
}
// callbacks
for (var i=0, len=ramp.callbacks.length; i<len; i++) {
var c = ramp.callbacks[i];
if (c.type == 'brushRamp') {
c.callback(t, color);
}
}
})
.on('mouseout', function() {
ramp.colorPicker.brushColor(null);
for (var i=0, len=ramp.callbacks.length; i<len; i++) {
var c = ramp.callbacks[i];
if (c.type == 'brushRamp') {
c.callback(-1);
}
}
})
})(this)
this.connectionLines = g.append('g');
var controlPoints = g.append('g')
.attr('transform', 'translate(0,' + RAMP_H + ')');
// store a reference to the color picker tool
this.colorPicker = _colorPicker;
// luminance plot
this.lPlot = g.append('g');
this.lPlot.attr('transform', 'translate(0,' + (-PLOT_H-PLOT_OFFSET) + ')');
this.lRect = this.lPlot.append('rect')
.attr('width', RAMP_W).attr('height', PLOT_H)
.style('fill', 'white').style('stroke', 'black')
this.lPlot.append('path')
.attr('class', 'luminancePlot');
// color difference plot
this.diffPlot = g.append('g');
this.diffPlot.attr('transform', 'translate(0,' + 2*(-PLOT_H-PLOT_OFFSET) + ')');
this.diffRect = this.diffPlot.append('rect')
.attr('width', RAMP_W).attr('height', PLOT_H)
.style('fill', 'white').style('stroke', 'black')
this.diffPlot.append('path')
.attr('class', 'diffPlot');
this.gButtons = g.append('g');
// keep track of history
this.history = [];
// create UI elements for the ramp (to add/remove colors)
this.addUI();
// initialize
this.selectedControlPoint = null;
this.controlPoints = controlPoints;
this.updateRamp();
// keep track of callbacks
this.callbacks = [];
}
ColorRamp.prototype.changeLuminanceProfile = function(profile)
{
var MAX_L = MAX_LUMINANCE;
var MIN_L = MIN_LUMINANCE;
switch (profile)
{
case 'linear':
for (var i=0, len=this.colors.length; i<len; i++)
{
var color = this.colors[i];
// look at the value of the color
var v = color.value;
var c = d3.lab(color.lab[0], color.lab[1], color.lab[2]);
var L = v*(MAX_L-MIN_L) + MIN_L;
// adjust luminacne accordingly
if (picker.getColorSpace()==COLORSPACE_CAM02) {
c = d3.jab(c);
c = d3.lab(d3.jab(L, c.a, c.b));
}
else
{
c = d3.lab(L, c.a, c.b);
}
color.lab = [c.l, c.a, c.b];
}
break;
case 'divergent':
// see if there's a 0.5 point
var hasMiddle = false;
for (var i=0, len=this.colors.length; i<len; i++) {
if (Math.abs(this.colors[i].v - 0.5) <= 0.01) {
hasMiddle = true;
break;
}
}
if (!hasMiddle) {
// insert a middle
this.insertColor(d3.lab(100, 0, 0), 0.5);
}
for (var i=0, len=this.colors.length; i<len; i++)
{
var color = this.colors[i];
// look at the value of the color
var v = color.value;
var c = d3.lab(color.lab[0], color.lab[1], color.lab[2]);
var L;
if (v < 0.5) {
L = MIN_L + 2*v*(MAX_L-MIN_L)
}
else if (v > 0.5)
{
L = MIN_L + 2*(1-v)*(MAX_L-MIN_L);
}
else {
L = MAX_L;
}
if (picker.getColorSpace() == COLORSPACE_CAM02) {
c = d3.jab(c);
c = d3.lab(d3.jab(L, c.a, c.b));
}
else
{
c = d3.lab(L, c.a, c.b);
}
color.lab = [c.l, c.a, c.b];
}
break;
}
this.updateRamp();
}
ColorRamp.prototype.registerCallback = function(_type, callback) {
this.callbacks.push({
type: _type,
callback: callback
});
}
ColorRamp.prototype.fireUpdate = function()
{
if (this.callbacks)
{
for (var i=0; i<this.callbacks.length; i++)
{
var c = this.callbacks[i];
if (c.type == 'update') {
c.callback(this);
}
}
}
}
ColorRamp.prototype.getColorMap = function() {
return this.colormap;
}
ColorRamp.prototype.addUI = function()
{
var g = this.svg.append('g');
var add = g.append('image')
.attr('xlink:href', 'img/plus.png')
.attr('width', '20px').attr('height', '20px')
.attr('x', 10).attr('y', RAMP_OFF_Y+7)
var remove = g.append('image')
.attr('xlink:href', 'img/minus.png')
.attr('width', '20px').attr('height', '20px')
.attr('x', 35).attr('y', RAMP_OFF_Y+7)
g.selectAll('image')
.on('mouseover', function() {
d3.select(this).style('background-color', 'red');
})
.on('mouseout', function() {
d3.select(this).style('background-color', null);
});
(function(add, remove, ramp, svg) {
add.on('click', function() {
ramp.insertColor({r: 255, g: 255, b: 255});
});
remove.on('click', function() {
ramp.removeColor();
})
svg.on('dblclick', function() {
if (!isNaN(ramp.selectedControlPoint)) {
ramp.unselectControlPoint();
}
})
ramp.colorPicker.registerCallback('pick', function(c) {
ramp.pickColor(c);
});
ramp.colorPicker.registerCallback('instantiateColormap', function(colormap, controlPoints) {
ramp.setColorMap(colormap, controlPoints);
})
// ramp image double click adds a new colors
ramp.lRect.on('dblclick', function()
{
var m = d3.mouse(this);
m[0] = m[0]/RAMP_W;
m[1] = 1-m[1]/PLOT_H;
// find an index where to insert the new control point
var cs = ramp.colors;
for (var i=0; i<cs.length-1; i++) {
var j1=i, j2=i+1;
if (cs[j1].value+0.03 < m[0] && cs[j2].value-0.03 > m[0])
{
// this is where we should be inserting (i.e., between i and i+1)
var c = [m[1] * 100, 0, 0];
ramp.colors.splice(i+1, 0, {
value: m[0],
lab: c
});
ramp.updateRamp();
ramp.selectControlPoint(i+1);
ramp.colorPicker.switchToColor(d3.lab(c[0], c[1], c[2]));
break;
}
}
});
// create radio buttons to chooise mode of selection plot
var g = ramp.g.append('g')
g.attr('transform', 'translate(-30,' + 2*(-PLOT_H-PLOT_OFFSET) + ')');
ramp.plotSelection = new SmallRadio(g, [
{ choice: 'de2000', text: 'dE \'00', },
{ choice: 'dejab', text: 'dE Jab'},
{ choice: 'localspeed', text: 'speed'},
{ choice: 'curve' , text: 'dCurve' }
], function(choice) {
ramp.colormapDiffMode = choice;
ramp.createDiffPlot();
});
// defaults to plotting CIE 2000 dE
ramp.colormapDiffMode = 'de2000';
})(add, remove, this, this.svg);
}
ColorRamp.prototype.unselectControlPoint = function() {
this.g.selectAll('rect.selectedColorPatch')
.attr('class', 'colorPatch');
this.selectedControlPoint = null;
}
ColorRamp.prototype.selectControlPoint = function(i)
{
this.unselectControlPoint();
this.selectedControlPoint=i;
this.g.selectAll('.colorPatch').each(function(d, _i)
{
if (i==_i) {
d3.select(this)
.attr('class', 'colorPatch selectedColorPatch');
}
});
// get the color
var theColor = this.colors[i].lab;
var c = d3.lab(theColor[0], theColor[1], theColor[2]);
}
ColorRamp.prototype.undo = function()
{
fireUpdate();
}
ColorRamp.prototype.pickColor = function(color)
{
if (this.selectedControlPoint !== null)
{
// create a copy of the old color map
var older = [];
for (i=0; i<this.colors.length; i++)
{
var oldControl = this.colors[i];
older.push({
value: oldControl.value,
lab: oldControl.lab
});
}
this.history.push(older);
var control = this.colors[ this.selectedControlPoint ];
control.lab = [ color.l, color.a, color.b ];
this.updateRamp();
}
}
ColorRamp.prototype.updateSVG = function()
{
// create control points onto the ramp
var controlPoints = this.controlPoints;
var u = controlPoints.selectAll('circle').data(this.colors);
u.exit().remove();
u = u.enter().append('circle')
.attr('r', 0/*CONTROL_R*/)
.attr('class', 'controlPoint')
.merge(u);
u
.attr('cx', function(d)
{
//console.log("d.value" + d.value);
return d.value * RAMP_W;
})
.attr('cy', 0)
// create color patches and connect them to control points on the ramp
this.patches = (function(ramp)
{
var uPatches = ramp.g.selectAll('rect.colorPatch').data(ramp.colors);
uPatches.exit().remove();
uPatches = uPatches.enter().append('rect')
.attr('width', PATCH_W)
.attr('height', PATCH_H)
.attr('class', 'colorPatch')
.merge(uPatches);
uPatches
.attr('x', PATCH_OFF_X)
.attr('y', function(d, i) {
return RAMP_H + PATCH_OFF_Y + i * (PATCH_H + PATCH_GAP);
})
.style('fill', function(d) {
var c = d3.lab(d.lab[0], d.lab[1], d.lab[2]);
var rgb = d3.rgb(c);
return rgb.toString()
})
.each(function(d, i) {
if (i===ramp.selectedControlPoint) {
d3.select(this)
.attr('class', 'colorPatch selectedColorPatch');
}
});
uPatches.on('click', function(d, i)
{
ramp.selectControlPoint(i);
var c = ramp.colors[i].lab;
ramp.colorPicker.switchToColor( d3.lab( c[0], c[1], c[2]) );
d3.event.stopPropagation();
});
if (ramp.selectedControlPoint >= ramp.colors.length) {
ramp.selectedControlPoint = null;
}
return uPatches;
})(this);
// create connections between the control points and the patches
this.connectionLines.selectAll('g.controlPointConnection').remove();
var uConnect = this.connectionLines.selectAll('g.controlPointConnection').data(this.colors)
uConnect = uConnect.enter().append('g')
.attr('class', 'controlPointConnection')
.merge(uConnect);
uConnect
.each(function(d, i) {
var l1 = d3.select(this).append('line');
var l2 = d3.select(this).append('line');
var y1 = RAMP_H + PATCH_OFF_Y + i * (PATCH_H + PATCH_GAP) + PATCH_H/2;
l1
.attr('x1', PATCH_OFF_X+PATCH_W).attr('x2', RAMP_W * d.value)
.attr('y1', y1).attr('y2', y1);
l2
.attr('x1', RAMP_W * d.value).attr('x2', RAMP_W * d.value)
.attr('y1', y1).attr('y2', RAMP_H);
});
uConnect.exit().remove();
// create luminance plot
this.createLPlot();
// create diff plot
this.createDiffPlot();
}
ColorRamp.prototype.computeLocalDirection = function() {
}
ColorRamp.prototype.computeDivergence = function(t)
{
// size of window (in t coordinates) to compute
// local speed within
var WINDOW = LOCAL_SPEED_W;
var SAMPLES = LOCAL_SPEED_S/2;
var STEP = WINDOW/SAMPLES;
var d = 0.0, count = 0;
for (var i=0; i<SAMPLES; i++)
{
var t1 = t-i*STEP;
var t2 = t+i*STEP;
if (t1 < 0 || t2 > 1) {
break;
}
else
{
var rgb1 = this.colormap.mapValue(t1);
var c1 = d3.jab(rgb1);
var rgb2 = this.colormap.mapValue(t2);
var c2 = d3.jab(rgb2);
d += Math.sqrt(
Math.pow(c1.J-c2.J, 2) +
Math.pow(c1.a-c2.a, 2) +
Math.pow(c1.b-c2.b, 2)
);
count++;
}
}
return count == 0 ? 0.0 : d/count;
}
ColorRamp.prototype.computeLocalSpeed = function(t)
{
// size of window (in t coordinates) to compute
// local speed within
var WINDOW = LOCAL_SPEED_W;
var SAMPLES = LOCAL_SPEED_S;
var STEP = WINDOW/SAMPLES;
var d = 0.0;
var rgb0 = this.colormap.mapValue(t);
var c0 = d3.jab(rgb0);
for (var pass=0; pass<2; pass++)
{
var dir = pass == 0 ? -1 : +1;
var cur = t;
var endReached = false;
for (var i=0; i<SAMPLES/2 && !endReached; i++)
{
var next = cur + dir * STEP;
var next = Math.min(1, Math.max(0, next));
if (next == cur) {
// can't move anymore
break;
}
else if ( Math.abs(next-cur) < STEP-0.0001 ) {
endReached = true;
}
var rgb = this.colormap.mapValue(next);
var c1 = d3.jab(rgb);
d += Math.sqrt(
Math.pow(c1.J-c0.J, 2) +
Math.pow(c1.a-c0.a, 2) +
Math.pow(c1.b-c0.b, 2)
) // / Math.abs(next-t);
cur = next;
}
}
return d;
}
ColorRamp.prototype.createDiffPlot = function()
{
var SAMPLES = DIFF_SAMPLES;
var lastColor = null;
var diffValues = [], diffVectors = [];
var maxDiff = -Number.MAX_VALUE;
var avgDiff = 0, N=0;
var colormap = this.colormap;
function normalize(a) {
var L = a[0]*a[0] + a[1]*a[1] + a[2]*a[2];
if (L > 0) {
L = 1.0 / Math.sqrt(L)
return [L*a[0], L*a[1], L*a[2]];
}
else
{
return a;
}
}
function dot(a, b)
{
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
}
function angle(a, b)
{
nA = normalize(a);
nB = normalize(b);
return dot(nA, nB);
}
for (var i=0, len=SAMPLES; i<len; i++)
{
var v = i/(len-1);
var vv = colormap.mapValue(v);
var currColor = d3.lab( d3.rgb(vv.r, vv.g, vv.b) );
if (lastColor)
{
var d, diffV = [0,0,0];
switch (this.colormapDiffMode)
{
case 'de2000':
d = ciede2000(
currColor.l, currColor.a, currColor.b,
lastColor.l, lastColor.a, lastColor.b
);
break;
case 'dejab':
var x = d3.jab(currColor);
var y = d3.jab(lastColor);
d = Math.sqrt(
Math.pow(x.J-y.J, 2) +
Math.pow(x.a-y.a, 2) +
Math.pow(x.b-y.b, 2)
);
break;
case 'localspeed':
d = this.computeDivergence(v); //this.computeLocalSpeed(v);
break;
case 'curve':
currColor = d3.jab(currColor);
diffV = [
currColor.J-lastColor.J,
currColor.a-lastColor.a,
currColor.b-lastColor.b,
];
d = Math.sqrt(
Math.pow(diffV[0], 2) +
Math.pow(diffV[1], 2) +
Math.pow(diffV[2], 2)
);
break;
}
diffValues.push(d);
diffVectors.push(diffV);
maxDiff = Math.max(d, maxDiff);
avgDiff += d;
N++;
}
else {
diffValues.push(0);
diffVectors.push([0,0,0]);
}
lastColor = currColor;
if (this.colormapDiffMode=='curve') {
lastColor = d3.jab(lastColor);
}
}
avgDiff /= N;
if (this.colormapDiffMode == 'curve')
{
// do another pass
var secondOrder = [0];
maxDiff = 0.0;
avgDiff = 0.0;
for (var i=1, len=diffVectors.length; i<len-1; i++)
{
//var d = Math.abs(diffValues[i]-diffValues[i+1]);
var d = angle(diffVectors[i], diffVectors[i+1]);
d = d == 0 ? 0 : 1-d;
secondOrder.push(d);
maxDiff = Math.max(d, maxDiff);
avgDiff += d;
}
avgDiff /= diffVectors.length-1;
diffValues = secondOrder;
}
// round D to the next multiple of 10
var TICKS = this.colormapDiffMode == 'curve' ? 2 : 5
var scaleMax = Math.ceil(maxDiff / TICKS) * TICKS;
// plot
var points = [];
for (var i=0, len=diffValues.length; i<len; i++)
{
points.push({
value: i/(len-1)*RAMP_W,
diff: PLOT_H * (1.0 - diffValues[i] / scaleMax)
});
}
var lineGen = d3.line()
.x(function(d) { return d.value;})
.y(function(d) { return d.diff;});
var diffPath = this.diffPlot.select('path');
diffPath.attr('d', lineGen(points));
var diffText = this.diffPlot.select('text');
if (diffText.size() == 0) {
diffText = this.diffPlot.append('text');
}
diffText.html(scaleMax);
diffText
.style('font-size', '10px')
.attr('text-anchor', 'end');
}
ColorRamp.prototype.createLPlot = function(skipControls)
{
// sample the color map
var SAMPLES = 30, luminanceSamples = [];;
for (var i=0; i<SAMPLES; i++)
{
var t = i/(SAMPLES-1);
var rgb = this.colormap.mapValue(t), L=0;
if (rgb)
{
switch (picker.getColorSpace())
{
case COLORSPACE_CAM02:
L = d3.jab(rgb).J;
break;
case COLORSPACE_LAB:
L = d3.lab(rgb).l;
break;
}
}
else
{
L = 0;
}
luminanceSamples.push({value: t, L: L});
}
var lPath = this.lPlot.select('path');
var lineGen = d3.line()
.x(function(d) { return RAMP_W * d.value; })
.y(function(d) { return PLOT_H * (1-d.L/100); });
var pathD = lineGen(luminanceSamples);
lPath.attr('d', pathD);
if (skipControls) {
return;
}
// add points to control luminance
var lControls = this.lPlot.selectAll('circle.controlPoint').data(this.colors);
lControls.exit().remove();
lControls = lControls.enter()
.append('circle')
.attr('class', 'controlPoint')
.merge(lControls);
lControls
.attr('r', CONTROL_R)
.attr('cx', function(d, i) { return d.value * RAMP_W})
.attr('cy', function(d, i) { return PLOT_H * (1-d.lab[0]/100); });
(function(controls, ramp)
{
controls
.on('dblclick', function(d, i) {
//if (i!=0 && i<ramp.colors.length-1) {
ramp.removeColor(i);
//}
//else if (i==0 && ramp.colors.length >= 3) {
//}
d3.event.stopPropagation();
})
.on('mousedown', function(d, i)
{
d3.select(this).style('stroke-width', '2px');
var c = d.lab;
ramp.selectControlPoint(i);
ramp.colorPicker.switchToColor( d3.lab(c[0], c[1], c[2]) );
ramp.lControl = { index: i, control: d, circle: d3.select(this), lastL: c[0] };
// change interpolation type and luminance profile to 'manual'
ramp.colorPicker.setInterpolationType('nonuniformLinear');
setLuminanceProfile('manual');
d3.select(document)
.on('mousemove.lControl', function()
{
var m = d3.mouse(ramp.lRect.node());
m[1] = Math.min(Math.max(0, m[1]), PLOT_H)/PLOT_H;
m[0] = Math.min(Math.max(0, m[0]), RAMP_W)/RAMP_W;
var c = ramp.lControl.control.lab;
var newL = 100*(1-m[1]);
//console.log("newL: " + newL);
// see if new L leads to a displayble color
var redraw = false;
var newLab = d3.lab(newL, c[1], c[2]);
if (newLab.displayable() || PERMISSIVE_L_TUNING)
{
if (!newLab.displayable()) {
// convert to RGB and back to lab
newLab = d3.lab(d3.rgb(newLab));
newL = newLab.l;
}
// update
ramp.lControl.control.lab[0] = newL;
ramp.lControl.circle.attr('cy', m[1] * PLOT_H);
var newC = ramp.lControl.control.lab;
// redraw
redraw = true;
ramp.colorPicker.switchToColor( d3.lab(c[0], c[1], c[2]) );
}
// change horizontal position
// don't allow this since we don't handle that with interpolation right now
/*
if (ramp.lControl.index > 0 && ramp.lControl.index < ramp.colors.length-1) {
// allow horizontal movement
var minV = ramp.colors[0].value+.03;
var maxV = ramp.colors[ramp.colors.length-1].value-.03;
var newV = Math.max(Math.min(maxV, m[0]), minV);
ramp.colors[ramp.lControl.index].value = newV;
ramp.lControl.circle.attr('cx', newV * RAMP_W);
redraw = true;
}
*/
if (redraw) {
ramp.updateRamp();
}
})
.on('mouseup.lControl', function() {
ramp.lControl.circle.style('stroke-width', null);
ramp.lControl = undefined;
d3.select(document)
.on('mousemove.lControl', null)
.on('mouseup.lControl', null);
//d3.event.stopPropagation();
});
d3.event.stopPropagation();
})
})(lControls, this);
}
ColorRamp.prototype.setColorMap = function(_colormap, controlPoints)
{
// remove existing color map
if (this.colormap) {
this.colormap.dispose();
this.colormap = null;
}
if (!this.lControl)
{
// essentally update controlPoints only if user is not manipulating
// the ramp
this.colors = controlPoints;
}
this.updateColormap(_colormap, true);
this.updateSVG();
}
ColorRamp.prototype.updateColormap = function(colormap, noUpdate)
{
var interpType;
switch(picker.getColorSpace())
{
case COLORSPACE_CAM02:
interpType = 'jab';
break;
case COLORSPACE_LAB:
interpType = 'lab';
break;
default:
interpType = undefined;
}
this.colormap = colormap || new ColorMap(this.colors, interpType);
// render color ramp
var colorScale = document.createElement('canvas');
colorScale.width = RAMP_W; colorScale.height=RAMP_H;
this.colormap.drawColorScale(RAMP_W, RAMP_H, Math.floor(RAMP_W/1), 'horizontal', colorScale);
// update the color ramp image
this.colorRampImage.attr('xlink:href', colorScale.toDataURL());
// update the picker
var SAMPLES = 50;
var points = [];
for (var i=0; i<SAMPLES; i++)
{
var v = i/(SAMPLES-1);
var c = this.colormap.mapValue(v);
points.push({
value: v,
color: d3.lab(d3.rgb(c.r, c.g, c.b))
});
}
// notify
if (!noUpdate) {
this.colorPicker.plotColormap(points);
}
this.fireUpdate();
}
ColorRamp.prototype.updateRamp = function()
{
picker.setControlPoints(this.colors);
// don't update colormap from here; picker will call us back
//this.updateColormap();
this.updateSVG();
}
ColorRamp.prototype.removeColor = function(index) {
if (this.colors.length == 2) {
return;
}
else if (index !== null && index !== undefined)
{
this.colors.splice(index, 1);
if (index == 0) {
this.colors[0].value = 0;
}
else if (index == this.colors.length) {
this.colors[index-1].value = 1;
}
this.updateRamp()
if (this.selectedControlPoint === index) {
this.unselectControlPoint();
}
}
else
{
this.colors.pop();
// move the last control point to the end of the ramp
this.colors[ this.colors.length-1 ].value = 1;
this.updateRamp();
if (!isNaN(this.selectedControlPoint) && this.selectedControlPoint > this.colors.length-1) {
this.unselectControlPoint();
}
}
}
ColorRamp.prototype.insertColor = function(newColor, value)
{
var labNewColor = null;
if (newColor.r !== undefined && newColor.g !== undefined && newColor.b !== undefined) {
labNewColor = d3.lab(d3.rgb(newColor.r, newColor.g, newColor.b));
}
else if (newColor.l !== undefined && newColor.a !== undefined && newColor.b !== undefined) {
labNewColor = d3.lab(newColor.l, newColor.a, newColor.b);
}
// create a new entry
var cPoint = {
value: value,
lab: [labNewColor.l, labNewColor.a, labNewColor.b]
}
// if a value is given, insert the color in the right space
if (value !== undefined && value !== null)
{
if (this.colors[0].value > value)
{
this.colors.splice(0, 0, cPoint);
}
else if (this.colors[this.colors.length-1].value < value)
{
this.colors.push(cPoint);
}
else
{
// find the correct place
for (var i=0; i<this.colors.length-1; i++)
{
var c1 = this.colors[i];
var c2 = this.colors[i+1];
if (c1.value == value) {
this.colors[i] = cPoint;
}
else if (c2.value == value) {
this.colors[i+1] = cPoint;
}
else if (c1.value < value && c2.value > value)
{
this.colors.splice(i+1, 0, cPoint);
break;
}
}
}
}
else
{
// append to the end of the colormap, but rescale the rest of the colors
cPoint.value = 1;
this.colors.push(cPoint);
var oldRange = d3.scaleLinear()
.domain([0, this.colors.length-1])
.range([ 0, 1 ]);
for (var i=0; i<this.colors.length-1; i++)
{
var c = this.colors[i];
c.value = oldRange(i);
}
}
this.updateRamp();
}
<file_sep>
var HEATMAP_BIN_SIZE = [5, 5];
var MODEL_TYPE, DISCRETE_TYPE, SAMPLER_TYPE, CANVAS_TYPE;
function setRepresentationType(_vis_type)
{
switch (_vis_type) {
case 'mapSmooth':
MODEL_TYPE = GaussMixBiDiscrete;
SAMPLER_TYPE = ScalarSample;
DISCRETE_TYPE = DiscreteMap;
CANVAS_TYPE = 'canvas';
break;
case 'mapDiscrete':
MODEL_TYPE = GaussMixBiDiscrete;
SAMPLER_TYPE = DiscreteSampler;
DISCRETE_TYPE = DiscreteMap;
CANVAS_TYPE = 'svg';
break;
case 'fieldSmooth':
MODEL_TYPE = GaussMixBivariate;
SAMPLER_TYPE = ScalarSample;
DISCRETE_TYPE = undefined;
CANVAS_TYPE = 'canvas';
break;
case 'fieldDiscrete':
MODEL_TYPE = GaussMixBiDiscrete;
SAMPLER_TYPE = DiscreteSampler;
DISCRETE_TYPE = HeatMap;
CANVAS_TYPE = 'svg';
break;
}
}
function createLineupElements(table, n, elementType, w, h)
{
if (!elementType) {
elementType = CANVAS_TYPE;
}
// how many rows
var rows = 2;
var rs = d3.range(rows);
table.selectAll('tr').data(rs)
.enter().append('tr')
.each(function(rowNum)
{
var cols = Math.ceil(n/2);
d3.select(this).selectAll('td').data(d3.range(cols))
.enter().append('td').each(function(d, i) {
var index = i + rowNum*cols;
if (index < n)
{
d3.select(this).append(elementType)
.attr('width', w)
.attr('height', h)
.attr('id', "sample" + index);
}
})
});
table
.attr('cellspacing', 10)
.attr('cellpadding', 10);
}
var US_COUNTY_PATHS = 'lineup/maps/us_county_paths.json';
var US_COUNTY_PIXEL_MAP = 'lineup/maps/us_countymap.json';
var US_COUNTY_DATA = null;
function drawPaths(paths, svg)
{
// create a white background
svg.append('rect')
.attr('width', +svg.attr('width'))
.attr('height', +svg.attr('height'))
.style('fill', 'white')
.style('stroke', 'none');
// plot paths
svg.selectAll('.county')
.data(paths)
.enter()
.append('path')
.attr('class', 'county choroplethBin')
.attr('d', function(d) { return d.path })
.attr('id', function(d) { return d.id; });
}
function qLoadJSON(url, callback)
{
d3.json(url).then(function(data) {
callback(null, data)
});
}
var LOAD_ALL_REGARDLESS = false;
function setBasicMapData(width, height) {
loadGlobalMapData({
width: width,
height: height,
binSize: HEATMAP_BIN_SIZE
});
}
function loadExperimentData(callback)
{
var q = d3.queue();
if (LOAD_ALL_REGARDLESS || VIS_TYPE.substr(0,3) == 'map')
{
console.log("load: " + US_COUNTY_PIXEL_MAP);
q.defer(qLoadJSON, US_COUNTY_PIXEL_MAP)
}
if (LOAD_ALL_REGARDLESS || VIS_TYPE == 'mapDiscrete') {
console.log("load: " + US_COUNTY_PATHS);
q.defer(qLoadJSON, US_COUNTY_PATHS);
}
q.awaitAll(function(error, results)
{
var start = new Date();
if (LOAD_ALL_REGARDLESS || VIS_TYPE == 'mapDiscrete')
{
var countyPaths = results[1];
US_COUNTY_DATA = countyPaths;
//drawPaths(countyPaths, svgTarget)
//drawPaths(countyPaths, svgDecoy)
if (!LOAD_ALL_REGARDLESS) {
d3.select('#lineupTable').selectAll('svg')
.each(function() {
drawPaths(countyPaths, d3.select(this));
});
}
console.log('map draw time: ' + ((new Date()-start)/1000).toFixed(2) + ' seconds');
}
// load pixel map data
var dMapData;
if (LOAD_ALL_REGARDLESS || VIS_TYPE.substr(0, 3) == 'map')
{
dMapData = results[0];
dMapData.binSize = HEATMAP_BIN_SIZE;
}
else
{
dMapData = {
width: WIDTH,
height: HEIGHT,
binSize: HEATMAP_BIN_SIZE
}
}
// load global discrete map data
loadGlobalMapData(dMapData);
// initialize the lineup
if (callback) {
callback();
}
var e = ((new Date()) - start)/1000;
console.log("Total setup time: " + e.toFixed(2) + ' sec');
});
}
<file_sep>
var dashboardHeight = 6000;
var dashboardWidth = 700;
c3.load("c3_data.json");
init();
// Display a ramp
var svg = d3.select("body").append("svg")
.attr("height", dashboardHeight+25)
.attr("width", dashboardWidth+40);
var OPTIONS = ["L Length", "L Variance", "C Length", "C Variance", "H Length", "H Variance", "LAB Length", "LAB Variance", "Name Length", "Name Variance"];
for (var i = 0; i < OPTIONS.length; ++i) {
var option = document.createElement("option");
option.value = OPTIONS[i];
option.text = OPTIONS[i];
$("#mode-select").append(option);
}
// Open the document
d3.csv("./interpolated_hex_ramps.csv", function(data) {
data.forEach(function(d, i){
d.colors = [d3.rgb(d.C1), d3.rgb(d.C2), d3.rgb(d.C3), d3.rgb(d.C4), d3.rgb(d.C5), d3.rgb(d.C6), d3.rgb(d.C7), d3.rgb(d.C8), d3.rgb(d.C9)];
});
$("#mode-select").change(function(){
console.log("get here");
//console.log("Displaying " + $("#mode-select").prop('selectedIndex'))
//displayRamp(data[$("#mode-select").prop('selectedIndex')]);
// Sort the data
var property =$("#mode-select option:selected").text();
console.log(property)
sortData(property, data);
svg.selectAll("text").remove();
// Display the data
for (var i = 0; i < data.length; i++)
displayRamp(property, data, i);
});
// Display the data
svg.selectAll("text").remove();
sortData("L Length", data)
for (var i = 0; i < data.length; i++)
displayRamp("L Length", data, i);
})
function sortData(property, data){
switch(property) {
case "L Length":
data.sort(function(a, b) {
console.log(getLLength(a));
return getLLength(a) - getLLength(b);
});
break;
case "L Variance":
data = data.sort(function(a, b) {
return getLVariance(a) - getLVariance(b);
});
break;
case "C Length":
data = data.sort(function(a, b) {
return getCLength(a) - getCLength(b);
});
break;
case "C Variance":
data = data.sort(function(a, b) {
return getCVariance(a) - getCVariance(b);
});
break;
case "H Length":
data = data.sort(function(a, b) {
return getHLength(a) - getHLength(b);
});
break;
case "H Variance":
data = data.sort(function(a, b) {
return getHVariance(a) - getHVariance(b);
});
break;
case "LAB Length":
data = data.sort(function(a, b) {
return getLABLength(a) - getLABLength(b);
});
break;
case "LAB Variance":
data = data.sort(function(a, b) {
return getLABVariance(a) - getLABVariance(b);
});
break;
case "Name Length":
data = data.sort(function(a, b) {
return getNameLength(a) - getNameLength(b);
});
break;
case "Name Variance":
data = data.sort(function(a, b) {
return getNameVariance(a) - getNameVariance(b);
});
break;
default:
break;
}
}
function getText(property, a){
switch(property) {
case "L Length":
return getLLength(a);
break;
case "L Variance":
return getLVariance(a);
break;
case "C Length":
return getCLength(a);
break;
case "C Variance":
return getCVariance(a);
break;
case "H Length":
return getHLength(a);
break;
case "H Variance":
return getHVariance(a);
break;
case "LAB Length":
return getLABLength(a);
break;
case "LAB Variance":
return getLABVariance(a);
break;
case "Name Length":
return getNameLength(a);
break;
case "Name Variance":
return getNameVariance(a);
break;
default:
break;
}
}
function displayRamp(prop, ramps, order) {
var rampWidth = dashboardWidth;
var boxWidth = 20;
var rampX = d3.scaleLinear()
.domain([0,9])
.range([0, 300]);
var ramp = ramps[order];
var rampY = d3.scaleLinear()
.domain([0,ramps.length])
.range([0, dashboardHeight]);
svg.selectAll(".swatch").remove();
svg.selectAll(".swatch")
.data(ramp.colors)
.enter()
.append("rect")
.attr("x", function(d, i) {
return rampX(i);
})
.attr("y", rampY(order -1))
.attr("height", 20)
.attr("width", 20)
.attr("fill", function(d) {
return d;
})
svg.append("text")
.attr("x", 300)
.attr("y", rampY(order)-12)
.text(getText(prop, ramp).toFixed(2));
//svg.append("text")
//.attr("x", 0)
//.attr("y", dashboardHeight+10)
//.text("LAB Length: " + getLABLength(ramp).toFixed(2) + " Name Length: " + getNameLength(ramp).toFixed(2) + " LAB Variance: " + getLABVariance(ramp).toFixed(2) + " Name Variance: " + getNameVariance(ramp).toFixed(2))
//renderLabDistance(ramp);
//renderNameDistance(ramp);
}
// Compute the LAB distance--MOVED TO UTILS
/*
function computeLabDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.lab(ramp.colors[i]);
var c2 = d3.lab(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.l - c2.l)*(c1.l - c2.l) + (c1.a - c2.a)*(c1.a - c2.a) + (c1.b - c2.b)*(c1.b - c2.b)));
}
return distances;
}
function computeLDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.lab(ramp.colors[i]);
var c2 = d3.lab(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.l - c2.l)*(c1.l - c2.l)));
}
return distances;
}
function computeCDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.hcl(ramp.colors[i]);
var c2 = d3.hcl(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.c - c2.c)*(c1.c - c2.c)));
}
return distances;
}
function computeHDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.hcl(ramp.colors[i]);
var c2 = d3.hcl(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.h - c2.h)*(c1.h - c2.h)));
}
return distances;
}*/
function renderLabDistance(ramp) {
// set the dimensions and margins of the graph
var margin = {top: 60, right: 20, bottom: 50, left: 50},
width = dashboardWidth/2.0 - margin.left - margin.right,
height = dashboardHeight - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Scale the range of the data
var data = computeLabDistances(ramp);
//console.log(data)
x.domain([0, data.length]);
y.domain([0, Math.max.apply(null, data)]);
// define the line
var valueline = d3.line()
.x(function(d, i) { return x(i) + margin.left; })
.y(function(d) { return y(d) + margin.top; });
d3.selectAll("path").remove();
d3.selectAll("g").remove();
svg.selectAll("circle").remove();
// Add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
svg.selectAll(".labPoint")
.data(data)
.enter()
.append("circle")
.attr("stroke-width", 1)
.attr("stroke", "steelblue")
.attr("fill", function(d, i) {
return ramp.colors[i];
})
.attr("r", 10)
.attr("cx", function(d, i) {
return x(i) + margin.left;
})
.attr("cy", function(d) {
return y(d) + margin.top;
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
.call(d3.axisBottom(x));
svg.append("text")
.attr("transform",
"translate(" + (width/2 + margin.left) + " ," +
(height + margin.top + 40) + ")")
.style("text-anchor", "middle")
.text("CIELAB Distance");
// Add the Y Axis
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(y));
}
// Compute the Name distance
function computeNameDistances(ramp) {
var distances = [0];
var colorSet = ramp.colors.map(color);
for (var i = 0; i < colorSet.length - 1; i++) {
var c1 = colorSet[i];
var c2 = colorSet[i+1];
distances.push(1 - c3.color.cosine(c1.c, c2.c));
}
return distances;
}
function renderNameDistance(ramp) {
// set the dimensions and margins of the graph
var margin = {top: 60, right: 20, bottom: 50, left: dashboardWidth/2.0+50},
width = dashboardWidth/2.0 - margin.right,
height = dashboardHeight - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Scale the range of the data
var data = computeNameDistances(ramp);
//console.log(data)
x.domain([0, data.length]);
y.domain([0, 1.0]);
// define the line
var valueline = d3.line()
.x(function(d, i) { return x(i) + margin.left; })
.y(function(d) { return y(d) + margin.top; });
// Add the valueline path.
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
svg.selectAll(".namePoint")
.data(data)
.enter()
.append("circle")
.attr("stroke-width", 1)
.attr("stroke", "steelblue")
.attr("fill", function(d, i) {
return ramp.colors[i];
})
.attr("r", 10)
.attr("cx", function(d, i) {
return x(i) + margin.left;
})
.attr("cy", function(d) {
return y(d) + margin.top;
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
.call(d3.axisBottom(x));
svg.append("text")
.attr("transform",
"translate(" + (width/2 + margin.left) + " ," +
(height + margin.top + 40) + ")")
.style("text-anchor", "middle")
.text("Color Name Distance");
// Add the Y Axis
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(y));
}
/*
function getLABLength(ramp) {
var dists = computeLabDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getLLength(ramp) {
var dists = computeLDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getCLength(ramp) {
var dists = computeCDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getHLength(ramp) {
var dists = computeHDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getNameLength(ramp) {
var dists = computeNameDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getLABVariance(ramp) {
var dists = computeLabDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getLVariance(ramp) {
var dists = computeLDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getCVariance(ramp) {
var dists = computeCDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getHVariance(ramp) {
var dists = computeHDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getNameVariance(ramp){
var dists = computeNameDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}*/
// Compute the Structural distance
// Visualize the distances
<file_sep>/* -------------------------------------
* GLSL color analysis pipeline
* -------------------------------------
*/
function gLoadShader(object, shaderPath, shaderName, callback)
{
(function(_path, _name, _object, _callback)
{
d3.text(_path).then(function(text, error)
{
if (error) {
if (_callback) _callback(error); else throw error;
} else
{
_object.shaders[_name] = text;
if (_callback) _callback(null);
}
})
})(shaderPath, shaderName, object, callback);
}
ColorAnalysis = function(field, glCanvas, _readyCallback, _shaderList)
{
this.glCanvas = glCanvas;
this.field = field;
this.shaders = {};
this.pipelines = null;
// list of canvases to copy results to at the end of analysis (optional)
this.copyList = [];
// load shaders
(function(object, readyCallback, shaderList) {
var q = d3.queue();
if (shaderList)
{
for (var i=0; i<shaderList.length; i++)
{
var shaderPath = shaderList[i].path;
var shaderName = shaderList[i].name;
q.defer( gLoadShader, object, shaderPath, shaderName )
}
}
else
{
q
.defer( gLoadShader, object, 'design/src/shaders/vertex.vert', 'vertex' )
.defer( gLoadShader, object, 'design/src/shaders/cie2000.frag', 'cie2000')
.defer( gLoadShader, object, 'design/src/shaders/speed.frag', 'speed')
.defer( gLoadShader, object, 'design/src/shaders/vis.frag', 'vis')
.defer( gLoadShader, object, 'design/src/shaders/cam022rgb.frag', 'cam02slice')
.defer( loadExternalColorPresets )
}
q.awaitAll(function(error, results)
{
if (error) {
throw error;
}
else if (!shaderList)
{
object.createDefaultPipelines();
object.isReady = true;
if (readyCallback) {
readyCallback();
}
}
else
{
object.isReady = true;
if (readyCallback) {
readyCallback();
}
}
});
})(this, _readyCallback, _shaderList)
}
ColorAnalysis.prototype.clearCanvas = function() {
var gl = this.glCanvas.getContext('webgl');
gl.clear(gl.COLOR_BUFFER_BIT);
}
ColorAnalysis.prototype.ready = function() {
return this.isReady === true;
}
ColorAnalysis.prototype.createVisPipeline = function()
{
var visPipeline = new GLPipeline(this.glCanvas);
visPipeline.addStage({
uniforms: {
scalarField: {},
colormap: {},
contour: {value: -1.0}
},
inTexture: 'scalarField',
fragment: this.shaders['vis'],
vertex: this.shaders['vertex']
});
this.visPipeline = visPipeline;
if (!this.pipelines) this.pipelines = {};
this.pipelines['vis'] = visPipeline;
}
ColorAnalysis.prototype.createDefaultPipelines = function()
{
// create a color scale from extendedBlackBody to be used
// to visualzie cie2000de or speed
var c = getColorPreset('extendedBlackBody');
this.gpuDiffColormapTexture = c.createGPUColormap()
var visPipeline = new GLPipeline(this.glCanvas);
visPipeline.addStage({
uniforms: {
scalarField: {},
colormap: {},
contour: {value: -1.0}
},
inTexture: 'scalarField',
fragment: this.shaders['vis'],
vertex: this.shaders['vertex']
});
this.visPipeline = visPipeline;
var diffPipeline = new GLPipeline(this.glCanvas);
diffPipeline.addStage({
uniforms: {
hPitch: {value: 1.0 / this.field.getMaskedW()},
vPitch: {value: 1.0 / this.field.getMaskedH()},
scalarField: {},
colormap: {},
colorDiffScale: {value: this.gpuDiffColormapTexture},
outputColor: {value: true}
},
inTexture: 'scalarField',
fragment: this.shaders['cie2000'],
vertex: this.shaders['vertex']
});
this.diffPipeline = diffPipeline;
var speedPipeline = new GLPipeline(this.glCanvas);
// add first stage to perform a cie2000 color-diff
speedPipeline.addStage({
uniforms: {
hPitch: {value: 1.0 / this.field.getMaskedW()},
vPitch: {value: 1.0 / this.field.getMaskedH()},
scalarField: {},
colormap: {},
colorDiffScale: {value: this.gpuDiffColormapTexture},
outputColor: {value: false}
},
inTexture: 'scalarField',
fragment: this.shaders['cie2000'],
vertex: this.shaders['vertex']
});
// add a second stage
speedPipeline.addStage({
uniforms: {
colorDiff: {},
hPitch: {value: 1.0 / this.field.getMaskedW()},
vPitch: {value: 1.0 / this.field.getMaskedH()},
colorDiffScale: {value: this.gpuDiffColormapTexture},
outputColor: {value: false}
},
inTexture: 'colorDiff',
fragment: this.shaders['speed'],
vertex: this.shaders['vertex']
});
this.speedPipeline = speedPipeline;
var cam02slice = new GLPipeline(this.glCanvas);
cam02slice.addStage({
uniforms: { J: {value: 50.0} },
fragment: this.shaders['cam02slice'],
vertex: this.shaders['vertex']
});
// create a list of pipelines currently loaded
this.pipelines = {
vis: visPipeline,
diff: diffPipeline,
speed: speedPipeline,
cam02slice: cam02slice
};
}
ColorAnalysis.prototype.getUniforms = function(pipelineName, stageIndex, uniformName)
{
var pipeline = this.pipelines[pipelineName];
if (!pipeline)
{
console.error("Can not find pipeline: " + pipelineName);
return;
}
else
{
var stage = pipeline.getStage(stageIndex);
var uniforms = stage.getUniforms();
if (uniformName) {
return uniforms[uniformName];
}
else
{
return uniforms;
}
}
}
ColorAnalysis.prototype.run = function(analysis)
{
if (!this.pipelines) {
console.error("Attempting to run ColorAnalysis pipeline before loading");
}
// deal with GPU texture
if (!this.field.gpuTexture) {
this.field.createGPUTexture();
}
// deal with color map
if (!this.field.gpuColormapTexture) {
this.field.setColorMap();
}
var pipeline = this.pipelines[analysis];
if (!pipeline) {
console.error("Can not find pipeline: " + analysis);
return;
}
// initialize stage0 to take scalarField as inTexture
var stage0 = pipeline.getStage(0);
var uniforms = stage0.getUniforms();
if (stage0.inTexture)
{
uniforms[stage0.inTexture].value = this.field.gpuTexture;
}
for (var i=0; i<pipeline.getStageCount(); i++)
{
var s = pipeline.getStage(i);
var u = s.getUniforms();
// does this stage require a colormap?
if (u.colormap) {
// if so, give it the current colormap associated with the scalar field
u.colormap.value = this.field.gpuColormapTexture;
}
}
pipeline.run();
// deal with copy list
for (var i=0; i<this.copyList.length; i++)
{
var copyTarget = this.copyList[i];
glCanvasToCanvas(this.glCanvas, copyTarget);
}
}
ColorAnalysis.prototype.copyToCanvas = function(copyTarget, dontFlip) {
glCanvasToCanvas(this.glCanvas, copyTarget, dontFlip);
}
ColorAnalysis.prototype.addCopyCanvas = function(canvas)
{
// render color diff
this.copyList.push(canvas);
}
<file_sep>c3.load("c3_data.json");
init();
function getLABLength(ramp) {
var dists = computeLabDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getLLength(ramp) {
var dists = computeLDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getCLength(ramp) {
var dists = computeCDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getHLength(ramp) {
var dists = computeHDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getNameLength(ramp) {
var dists = computeNameDistances(ramp);
return dists.slice(1, dists.length).reduce(function(a, b){
return a + b;
}, 0);
}
function getLABVariance(ramp) {
var dists = computeLabDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getLVariance(ramp) {
var dists = computeLDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getCVariance(ramp) {
var dists = computeCDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getHVariance(ramp) {
var dists = computeHDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
function getNameVariance(ramp){
var dists = computeNameDistances(ramp);
return d3.variance(dists.slice(1, dists.length));
}
// Compute the Name distance
// Compute the LAB distance
function computeLabDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.lab(ramp.colors[i]);
var c2 = d3.lab(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.l - c2.l)*(c1.l - c2.l) + (c1.a - c2.a)*(c1.a - c2.a) + (c1.b - c2.b)*(c1.b - c2.b)));
}
return distances;
}
function computeLDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.lab(ramp.colors[i]);
var c2 = d3.lab(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.l - c2.l)*(c1.l - c2.l)));
}
return distances;
}
function computeCDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.hcl(ramp.colors[i]);
var c2 = d3.hcl(ramp.colors[i+1]);
distances.push(Math.sqrt((c1.c - c2.c)*(c1.c - c2.c)));
}
return distances;
}
function computeHDistances(ramp) {
var distances = [0];
for (var i = 0; i < ramp.colors.length - 1; i++) {
var c1 = d3.hcl(ramp.colors[i]);
var c2 = d3.hcl(ramp.colors[i+1]);
var d1 = Math.sqrt((c1.h - c2.h)*(c1.h - c2.h));
if (d1 > 180) {
d1 = 360.0 - d1;
}
distances.push(d1);
}
return distances;
}
function computeNameDistances(ramp) {
var distances = [0];
var colorSet = ramp.colors.map(color);
for (var i = 0; i < colorSet.length - 1; i++) {
var c1 = colorSet[i];
var c2 = colorSet[i+1];
distances.push(1 - c3.color.cosine(c1.c, c2.c));
}
return distances;
}
<file_sep>var BLUR=false;
// disable renderer caching, forcing new canvases each time
ALL_SAMPLERS = [];
var CALLBACK_SAMPLE = true;
var shaderList = [
{name: 'vis', path: 'design/src/shaders/vis.frag'},
{name: 'vertex', path: 'design/src/shaders/vertex.vert'},
{name: 'blur', path: 'design/src/shaders/blur.frag'}
];
function ScalarSample(w, h, canvas, model, colormap)
{
console.log('scalar sample constructor');
this.w = w;
this.h = h;
this.field = new ScalarField(w, h);
this.model = model;
this.canvas = canvas;
// add myself to the model
if (model) {
this.setModel(model);
}
// if we're passed a d3 selection, convert to a standard canvas
if (this.canvas.selectAll) {
this.canvas = this.canvas.node();
}
if (this.canvas)
{
(function(me) {
me.visualizer = new ColorAnalysis(
me.field, me.canvas,
function()
{
console.log('initVisPipeline');
me.initVisPipeline();
}, shaderList
);
})(this);
}
if (!colormap) {
this.field.setColorMap(getColorPreset('viridis'));
}
else {
this.field.setColorMap(colormap);
}
ALL_SAMPLERS.push(this);
}
ScalarSample.prototype.dispose = function()
{
for (var i=0; i<ALL_SAMPLERS.length; i++) {
var s = ALL_SAMPLERS[i];
if (s == this) {
ALL_SAMPLERS.splice(i, 1);
break;
}
}
if (this.canvas) {
var c = this.canvas
if (!c.attr) {
c = d3.select(this.canvas);
}
removeRenderCache(c.attr('id'));
}
this.field = null;
this.model = null;
this.canvas = null;
this.w = null;
this.h = null;
}
ScalarSample.prototype.setColorMap = function(colormap)
{
this.field.setColorMap(colormap);
}
ScalarSample.setUniversalColormap = function(colormap, dontVis) {
for (var i=0; i<ALL_SAMPLERS.length; i++)
{
ALL_SAMPLERS[i].setColorMap(colormap);
// render?
if (!dontVis) {
ALL_SAMPLERS[i].vis();
}
}
}
ScalarSample.prototype.setModel = function(_model, dontVis)
{
if (this.model) {
this.model.unregisterCallback(this.callbackID);
this.model = null;
}
this.model = _model;
(function(me) {
me.callbackID = me.model.addCallback(function()
{
if (CALLBACK_SAMPLE || me.callbackSample)
{
console.log('callback sampling');
me.sampleModel();
if (me.canvas || me.svg) {
me.vis();
}
}
});
})(this);
if (this.canvas && !dontVis)
{
this.sampleModel();
this.vis();
}
}
ScalarSample.prototype.setSamplingFidelity = function(fidelity)
{
this.localN = fidelity;
}
ScalarSample.prototype.sampleModel = function(_fidelity, model)
{
var fidelity = !isNaN(_fidelity) ? _fidelity : this.localN;
if (!fidelity || isNaN(fidelity)) {
if (typeof N === 'undefined') {
fidelity = 0;
}
else {
fidelity = N;
}
}
if (!model) {
model = this.model;
}
model.sampleModel(fidelity, this.field);
}
ScalarSample.prototype.sampleAndVis = function(_fidelity)
{
this.sampleModel(_fidelity);
this.vis();
}
ScalarSample.prototype.vis = function()
{
if (!this.canvas)
{
console.log("Error: ScalarSample doesn't have a canvas.");
}
else if (!this.visualizer || !this.visualizer.ready())
{
// pipeline not yet ready. Set flag to callVis when it's ready
this.callVisFlag = true;
}
else {
this.visualizer.run(BLUR ? 'blur' : 'vis');
}
}
ScalarSample.prototype.initVisPipeline = function()
{
if (!this.canvas) {
console.log("Error: ScalarSample doesn't have a canvas.");
return;
}
// standard vis
var vis = new GLPipeline(this.visualizer.glCanvas);
vis.addStage({
uniforms: {
scalarField: {},
colormap: {},
contour: {value: -1.0},
},
inTexture: 'scalarField',
fragment: this.visualizer.shaders['vis'],
vertex: this.visualizer.shaders['vertex']
});
// blur + vis
var blur = new GLPipeline(this.visualizer.glCanvas);
blur.addStage({
uniforms: {
scalarField: {},
colormap: {},
pitch: {value: [1/this.field.w, 1/this.field.h]}
},
inTexture: 'scalarField',
fragment: this.visualizer.shaders['blur'],
vertex: this.visualizer.shaders['vertex']
});
this.visualizer.pipelines = {
vis: vis,
blur: blur
};
//this.visualizer.createVisPipeline();
if (this.callVisFlag) {
this.callVisFlag = false;
this.vis();
}
}
<file_sep>function Lineup(w, h, n, realModel, decoyModel, nullOption, table)
{
// total number of exposures (n-1 actual + 1 decoy)
this.w = w;
this.h = h;
this.n = n;
this.realModel = realModel;
this.decoyModel = decoyModel;
// create canvases and samplers
this.canvases = [];
this.samplers = [];
this.nullOption = nullOption;
var canvasType = 'canvas'
if (typeof CANVAS_TYPE === 'string') {
canvasType = CANVAS_TYPE
}
var samplerType = ScalarSample;
if (typeof SAMPLER_TYPE !== 'undefined') {
samplerType = SAMPLER_TYPE;
}
// initialize random canvases
for (var i=0; i<n; i++)
{
this.canvases.push(null);
}
if (table) {
this.layoutCanvases(table)
}
for (var i=0; i<n; i++)
{
var canvas = this.canvases[i];
if (!canvas) {
canvas = document.createElement(canvasType);
if (canvasType == 'svg')
{
d3.select(canvas)
.attr('width', w)
.attr('height', h);
}
else
{
canvas.width = w;
canvas.height = h;
}
canvas.id="sample" + i;
this.canvases[i] = ( canvas );
}
// sampler
var sampler = new samplerType(w, h, canvas, i==n-1 ? this.decoyModel : this.realModel);
this.samplers.push(sampler);
}
this.correctSample = n-1;
}
Lineup.prototype.dispose = function() {
for (var i=0; i<this.samplers.length; i++) {
this.samplers[i].dispose();
}
this.samplers = null;
this.canvases = null;
}
Lineup.prototype.getCorrectAnswer = function() {
return this.correctSample;
}
Lineup.prototype.sample = function(samplingRate, noDecoy)
{
if (noDecoy) {
console.log('sampling no decoy (fidelity: ' + samplingRate + ')');
}
for (var i=0; i<this.samplers.length; i++)
{
this.samplers[i].sampleModel(samplingRate, noDecoy ? this.realModel : undefined);
this.samplers[i].vis();
}
}
var LINEUP_PADDING = 6;
var LINEUP_SPACING = 10;
Lineup.prototype.layoutCanvases = function(table)
{
if (!table) {
table = this.table;
}
var randomCanvases = this.canvases.slice();
var decoyCanvas = randomCanvases.pop();
// reinsert
var insertPos = Math.floor( Math.random() * (randomCanvases.length+1) );
randomCanvases.splice(insertPos, 0, decoyCanvas);
var canvasType = 'canvas';
if (typeof CANVAS_TYPE === 'string') {
canvasType = CANVAS_TYPE;
}
// remove everything in the table
table.selectAll('*').remove();
table.attr('cellpadding', LINEUP_PADDING).attr("cellspacing", LINEUP_SPACING);
// how many rows
var rows = 2;
var cols = Math.ceil(this.n/2);
(function(width, height, table, rows, cols, n, randomCanvases, nullOption)
{
var rs = d3.range(rows);
table.selectAll('tr').data(rs)
.enter().append('tr')
.each(function(d, thisRow)
{
(function(rowNum, thisRow)
{
d3.select(thisRow).selectAll('td').data(d3.range(cols))
.enter().append('td').each(function(d, i) {
var index = i + rowNum*cols;
if (index < n)
{
var canvas = randomCanvases[index];
if (!canvas) {
var c = d3.select(this).append(canvasType);
c
.attr('width', width)
.attr('height', height)
.attr('id', "sample" + index);
randomCanvases[canvas] = c;
}
this.appendChild( randomCanvases[index] );
d3.select(randomCanvases[index])
.attr('class', 'index' + index);
}
});
if (rowNum==0 && nullOption)
{
var w_div = +d3.select(randomCanvases[0]).attr('width')
var w = 25 + w_div;
var h = +d3.select(randomCanvases[0]).attr('height');
var tdNull = d3.select(thisRow).append('td')
.attr('rowSpan', rows)
.attr('width', w);
var div = tdNull.append('div')
.style('margin', '0 auto')
.style('width', w + 'px');
div.append('div')
.style('margin-top', ((rows*h)/2-h/1) + 'px')
.style('margin-left', 'auto')
.style('margin-right', 'auto')
.attr('class', 'nullOption')
.style('text-align', 'center')
.style('vertical-align', 'middle')
.style('width', w_div + 'px')
.style('height', h + 'px')
.style('border', 'solid 1px black')
.style('font-size', '35px')
.style('color', "#bbbbbb")
.style('font-weight', 'bold')
.html('no discernible difference between images');
}
})(d, this);
});
})(this.w, this.h, table, rows, cols, this.n, randomCanvases, this.nullOption);
this.table = table;
}
function LineupFixed(w, h, n, realModel, decoyModel, nullOption, table)
{
this.w = w;
this.h = h;
this.n = n;
this.realModel = realModel;
this.decoyModel = decoyModel;
// create canvases and samplers
this.canvases = [];
this.samplers = [];
this.nullOption = nullOption;
this.canvasType = 'canvas';
if (typeof CANVAS_TYPE === 'string') {
this.canvasType = CANVAS_TYPE;
}
var samplerType = ScalarSample;
if (typeof SAMPLER_TYPE !== 'undefined')
{
samplerType = SAMPLER_TYPE;
}
(function(_table, canvases, canvasType)
{
var selectionSize = table.selectAll(canvasType).size();
if (selectionSize != n) {
console.error("LineupFixed: number of canvases (" + selectionSize + ") + doesn't match number of requested lineup samples (" + n + ")");
}
table.selectAll(canvasType).each(function() {
canvases.push(d3.select(this));
d3.select(this)
.attr('id', 'sample' + (canvases.length-1))
.classed('index' + (canvases.length-1), true);
});
table
.attr('cellpadding', LINEUP_PADDING).attr("cellspacing", LINEUP_SPACING);
})(table, this.canvases, this.canvasType);
this.table = table;
// create samplers
for (var i=0; i<n; i++) {
var canvas = this.canvases[i];
var sampler = new samplerType(w, h, canvas, i==n-1 ? this.decoyModel : this.realModel);
this.samplers.push(sampler);
}
// randomly assign the real model
this.randomAssignCorrect()
}
LineupFixed.prototype = Object.create(Lineup.prototype);
LineupFixed.prototype.randomAssignCorrect = function()
{
// generate random number
var correctIndex = Math.floor(Math.random() * this.canvases.length);
for (var i=0; i<this.n; i++)
{
var dontVis = true;
if (i == correctIndex) {
this.samplers[i].setModel(this.decoyModel, dontVis);
}
else
{
this.samplers[i].setModel(this.realModel, dontVis);
}
}
this.correctSample = correctIndex;
}
LineupFixed.prototype.layoutCanvases = function()
{
this.randomAssignCorrect();
}
<file_sep>// somewhere between 2 and 5 seems (visually) like a reasonable tradeoff
var BI_MAP_SIZE=2;
var DOUBLE_PRECISION=true;
function GaussMixBivariate(w, h, svg)
{
GaussMix.call(this, w, h, svg);
if (this.svg) {
this.svg = this.svg.append('g');
}
// double precision for pdf
this.pdf = new ScalarField(w, h, DOUBLE_PRECISION);
this.cdf = new ScalarField(w, h);
var cdfMapSize = Float32Array.BYTES_PER_ELEMENT * w * h * (BI_MAP_SIZE * BI_MAP_SIZE);
this.cdfMap = new Float32Array(new ArrayBuffer(cdfMapSize));
}
function biGauss(mX, mY, sX, sY, rho, scaler)
{
this.mX = mX;
this.mY = mY;
this.sX = sX;
this.sY = sY;
this.updateRho(rho);
this.scaler = (scaler ? scaler : 1);
}
biGauss.prototype.updateRho = function(_rho)
{
// rescale row so that it's between -.7 and .7
this.rho = _rho;
this.rho2 = this.rho * this.rho;
this.rhoExpConst = -1/(2 * (1-this.rho2));
this.rhoSqrConst = 1/(2 * Math.PI * Math.sqrt(1-this.rho2));
}
biGauss.prototype.eval = function(x, y)
{
var stX = (x-this.mX)/this.sX;
var stY = (y-this.mY)/this.sY;
var stXY = stX * stY;
var e = this.rhoExpConst * (stX*stX -2 * this.rho * stXY + stY*stY);
var a = this.rhoSqrConst * (1/(this.sX * this.sY))
return 10.0 * a * Math.exp( e );
}
GaussMixBivariate.prototype = new GaussMix();
GaussMixBivariate.prototype.constructor = GaussMixBivariate;
GaussMixBivariate.prototype.dispose = function()
{
this.pdf = null;
this.cdf = null;
this.cdfMap = null;
}
GaussMixBivariate.prototype.init = function()
{
var MIN_GAUSS = 3;
var MAX_GAUSS = 6;
var count = Math.floor(.5 + Math.random() * (MAX_GAUSS-MIN_GAUSS)) + MIN_GAUSS;
this.models = [];
// add a few random gausses
var dontUpdate = true;
for (var i=0; i<count; i++ ) {
this.add(dontUpdate);
}
this.updateModel();
}
GaussMixBivariate.prototype.copyTo = function(newModel, dontUpdate)
{
if (!newModel) {
newModel = new GaussMixBivariate(this.w, this.h, null);
}
else {
newModel.w = this.w;
newModel.h = this.h;
}
newModel.models = [];
for (var i=0; i<this.models.length; i++)
{
var m = this.models[i];
newModel.models.push(
new biGauss(m.mX, m.mY, m.sX, m.sY, m.rho, m.scaler)
);
}
if (!dontUpdate) {
newModel.updateModel();
}
return newModel;
}
var MIN_SIGMA = 10;
GaussMixBivariate.prototype.add = function(dontUpdate)
{
// center
var mX = this.w/2 + (Math.random()*2-1) * (this.w*0.35);
var mY = this.h/2 + (Math.random()*2-1) * (this.h*0.35);
// standard deviation
var sigmaX = (Math.random()*.5 + .2) * this.w * .32;
var sigmaY = (Math.random()*.5 + .2) * this.h * .32;
// correlation (limit to -0.7 to 0.7)
var rho = (Math.random()*2-1) *.7;
// scaler
var scaler = 1.0; //0.7 + (Math.random()*2 - 1)*0.3;
this.models.push(new biGauss(mX, mY, sigmaX, sigmaY, rho, scaler));
if (!dontUpdate) {
this.updateModel();
}
}
GaussMixBivariate.prototype.remove = function() {
if (this.models.length < 1) {
return;
}
else {
this.models.splice(this.models.length-1, 1);
this.updateModel();
}
}
var MIN_M_PERTURB = 0.01;
var MAX_M_PERTURB = 0.20;
var MIN_R_PERTURB = 0.0;
var MAX_R_PERTURB = 0.3;
var M_PERTURB = .015;
var S_PERTURB = 0;
var R_PERTURB = 0.07;
GaussMixBivariate.prototype.randomPerturb = function()
{
var MAX_M_PERTURB = Math.min(this.w * .1, this.h *.1);
var MIN_M_PERTURB = Math.min(this.w * .05, this.h *.05);
var MIN_RHO = 0.05;
var MAX_RHO = 0.2;
for (var i=0; i<this.models.length; i++)
{
var l = 0;
var r = [0, 0];
do {
r = [Math.random()*2-1, Math.random()*2-1];
l = r[0]*r[0]+r[1]*r[1];
} while (l==0);
//var p = Math.random() * (MAX_M_PERTURB-MIN_M_PERTURB) + MIN_M_PERTURB;
l = (M_PERTURB * Math.min(this.w, this.h)) / Math.sqrt(l);
var m = this.models[i];
m.mX += r[0] * l;
m.mY += r[1] * l;
var rhoP = (Math.random() > .5 ? 1 : -1) * (Math.random() * R_PERTURB);
var newRho = m.rho + rhoP;
if (newRho > 1 || newRho < -1) {
rhoP*=-1;
newRho = m.rho + rhoP;
}
m.updateRho(newRho);
}
this.updateModel();
}
GaussMixBivariate.prototype.deldensity = function(nonZeroOK)
{
var RESOLUTION=30;
var HIST_ROW = RESOLUTION*2+1;
var w = this.w;
var h = this.h;
var histSize = HIST_ROW * HIST_ROW;
var histogram = DOUBLE_PRECISION ?
new Float64Array(histSize) :
new Float32Array(histSize);
/*
var histogram = w*h < 65000 ?
new Uint16Array(histSize) :
new Uint32Array(histSize);
*/
var histMax = 0;
// get the pdf and its range
var pdf = this.pdf.view;
var minDensity = this.minDensity;
var maxDensity = this.maxDensity;
var densityRange_1 = RESOLUTION / (maxDensity-minDensity);
var totalDensity=0;
var R0=1, R1=h-1, C0=1, C1=w-1;
for (var r=R0, R=w; r<R1; r++, R+=w)
{
for (var c=C0; c<C1; c++)
{
var RC = R+c;
var P = pdf[RC];
var fx = (P-pdf[RC-1]) * densityRange_1;
var fy = (P-pdf[RC-w]) * densityRange_1;
//console.log("num: " + fx + ',' + fy);
var fj = Math.floor(.49999999 + Math.abs(fx));
var fi = Math.floor(.49999999 + Math.abs(fy));
if (fx<0) fj = RESOLUTION-fj; else fj += RESOLUTION;
if (fy<0) fi = RESOLUTION-fi; else fi += RESOLUTION;
var hI = fi*HIST_ROW + fj;
var hV = histogram[ hI ] + 1;
if (hV > histMax) {
histMax = hV;
}
histogram[ hI ] = hV;
}
}
// scan histogram again, and ensuring no non-zero elements within
var cummDeldensity = (R1-R0) * (C1-C0);
if (!nonZeroOK) {
for (var i=0; i<histSize; i++)
{
if (histogram[i] == 0.0) {
histogram[i] = 1e-40;
cummDeldensity += 1e-40;
}
}
}
this.deldensityResult = {
deldensity: histogram,
maxDeldensity: histMax,
cummDeldensity: cummDeldensity,
histW: HIST_ROW,
histH: HIST_ROW
};
return this.deldensityResult;
}
// for debugging
GaussMixBivariate.prototype.plotDeldensity = function()
{
var results = this.deldensityResult;
if (!results) {
results = this.deldensity();
}
var histogram = results.deldensity;
var w=results.histW, h=results.histH;
var scalar = new ScalarField(w, h);
var view = scalar.view;
for (var i=0, len=w*h; i<len; i++)
{
var t = histogram[i]
view[i] = t;
}
scalar.normalize();
scalar.setColorMap(getColorPreset('spectral'));
var canvas = scalar.generatePicture();
d3.selectAll('#plotDeldensity').remove();
d3.select(canvas).attr('id', 'plotDeldensity');
d3.select('body').node().appendChild(canvas);
}
GaussMixBivariate.prototype.plotModelCurves = function()
{
if (!this.svg) {
return;
}
var ellipses = this.svg.selectAll('ellipse').data(this.models)
ellipses.exit().remove();
var enter = ellipses.enter().append('ellipse')
.attr('class', 'modelEllipse');
ellipses = ellipses.merge(enter);
ellipses
//.attr('cx', function(d) { return d.mX; })
//.attr('cy', function(d) { return d.mY; })
.attr('transform', function(d) {
var rotation = 'rotate(' + -Math.PI*.25*d.rho * 180.0/Math.PI + ')';
var translation = 'translate(' + d.mX + ',' + d.mY + ')';
return translation + ' ' + rotation;
})
.attr('rx', function(d) { return d.sX; })
.attr('ry', function(d) { return d.sY; })
.style('stroke-width', '3px')
.attr('stroke', function(d, i) {
return MODEL_COLORS[Math.min(i, MODEL_COLORS.length-1)];
})
.attr('fill', 'none');
var lines = this.svg.selectAll('line').data(this.models)
lines.exit().remove();
enter = lines.enter().append('line');
lines = lines.merge(enter);
lines
.attr('stroke', function(d, i) {
return MODEL_COLORS[Math.min(i, MODEL_COLORS.length-1)];
})
.style('stroke-width', '3px')
.attr('x1', function(d) { return d.mX+3*Math.cos( Math.PI*.25*d.rho ); })
.attr('y1', function(d) { return d.mY-3*Math.sin( Math.PI*.25*d.rho ); })
.each(function(d) {
// slop based on rho
var len = d.sX;
var x2 = d.mX + len * Math.cos( Math.PI*.25*d.rho );
var y2 = d.mY - len * Math.sin( Math.PI*.25*d.rho );
d3.select(this)
.attr('x2', x2).attr('y2', y2)
});
// plots centers
var centers = this.svg.selectAll('circle.center').data(this.models)
centers.exit().remove();
enter = centers.enter().append('circle')
.attr('class', 'center');
centers = centers.merge(enter);
centers
.attr('cx', function(d) { return d.mX; })
.attr('cy', function(d) { return d.mY; })
.attr('fill', function(d, i) {
return MODEL_COLORS[Math.min(i, MODEL_COLORS.length-1)];
})
.attr('r', 3);
// event handlers
(function(me, centers, ellipses) {
centers.on('mousedown', function(biG)
{
me.mouseCoord = d3.mouse(me.svg.node());
me.oldMX = biG.mX;
me.oldMY = biG.mY;
d3.select(document)
.on('mousemove.moveCenter', function()
{
var mouse = d3.mouse(me.svg.node());
var dMouse = [
mouse[0]-me.mouseCoord[0],
mouse[1]-me.mouseCoord[1]
];
biG.mX = me.oldMX + dMouse[0];
biG.mY = me.oldMY + dMouse[1];
me.plotModelCurves();
})
.on('mouseup.moveCenter', function() {
me.updateModel();
me.fireCallbacks();
d3.select(document)
.on('mousemove.moveCenter', null)
.on('mouseup.moveCenter', null);
me.putOnTop();
});
});
ellipses.on('mousedown', function(biG)
{
me.mouseCoord = d3.mouse(me.svg.node());
me.oldSX = biG.sX;
me.oldSY = biG.sY;
d3.select(document)
.on('mousemove.moveCenter', function()
{
var mouse = d3.mouse(me.svg.node());
var dMouse = [
mouse[0]-me.mouseCoord[0],
mouse[1]-me.mouseCoord[1]
];
biG.sX = Math.max(MIN_SIGMA, me.oldSX + dMouse[0]);
biG.sY = Math.max(MIN_SIGMA, me.oldSY + dMouse[1]);
me.plotModelCurves();
})
.on('mouseup.moveCenter', function() {
me.updateModel();
me.fireCallbacks();
d3.select(document)
.on('mousemove.moveCenter', null)
.on('mouseup.moveCenter', null);
me.putOnTop();
});
});
lines.on('mousedown', function(BiG)
{
me.mouseCoord = d3.mouse(me.svg.node());
d3.select(document)
.on('mousemove.moveCenter', function()
{
// compute new rho based on slope created by line
// passing through model center and new mouse coordinates
var mouse = d3.mouse(me.svg.node());
var slope = (mouse[1]-BiG.mY)/(mouse[0]-BiG.mX);
if (slope > 1) {
slope=1;
}
else if (slope < -1) {
slope=-1;
}
BiG.updateRho(slope*-1);
me.plotModelCurves();
})
.on('mouseup.moveCenter', function() {
me.updateModel();
me.fireCallbacks();
d3.select(document)
.on('mousemove.moveCenter', null)
.on('mouseup.moveCenter', null);
me.putOnTop();
});
});
})(this, centers, ellipses);
}
GaussMixBivariate.prototype.updateModel = function()
{
// compute CDFs and maps
this.computeCDFs();
this.plotModelCurves();
}
GaussMixBivariate.prototype.computeCDFs = function()
{
var w = this.w;
var h = this.h;
var models = this.models;
var mCount = models.length;
// compute PDF / CDF
var cummDensity = 0, maxDensity = 0, minDensity=Number.MAX_VALUE;
// clear out
this.pdf.zero();
this.cdf.zero();
var pdf = this.pdf.view;
var cdf = this.cdf.view;
// loop through all rows / columns
for (var r=0, I=0; r<h; r++)
{
for (var c=0; c<w; c++, I++)
{
// evaluate density of all models
var P=0;
for (var m=0; m<mCount; m++)
{
var model = models[m];
P += model.eval(c, r);
}
// To force a uniform distribution (for testing):
//P = Math.random();//1/(w*h);
if (P > maxDensity) {
maxDensity = P;
}
if (P < minDensity) {
minDensity = P;
}
cummDensity += P;
pdf[I] = P;
cdf[I] = cummDensity;
}
}
this.maxDensity = maxDensity;
this.minDensity = minDensity;
this.cummDensity = cummDensity;
// construct map
this.updateCDFMap = true;
}
// construct map
GaussMixBivariate.prototype.computeCDFMap = function(pixelMap)
{
var cdf = this.cdf.view;
var cummDensity = this.cummDensity;
var cdfMap = this.cdfMap;
var cdfMapLen = this.cdfMap.length;
for (var i=0, last=0, p=0, step=cummDensity/cdfMapLen; i<cdfMapLen; i++, p+=step)
{
while (cdf[last] < p)
{
last++;
}
cdfMap[i] = last;
//cdfMap[i]= pixelMap ? pixelMap(last) : last;
}
this.updateCDFMap = false;
}
GaussMixBivariate.prototype.normalizedDivergence = function(other)
{
var kld = this.klDivergence(other);
return kld;
//return kld / (.5 * (this.entropy + other.entropy));
}
GaussMixBivariate.prototype.pdfDistance = function(other)
{
var P = this.pdf.view;
var Q = other.pdf.view;
var maxP_1 = 1.0/this.cummDensity;
var maxQ_1 = 1.0/other.cummDensity;
var distance = 0;
// amplitude distance
// ==================
for (var i=0, len=P.length; i<len; i++)
{
var p = P[i];
p *= maxP_1;
var q = Q[i];
q *= maxQ_1;
distance += Math.abs(p-q);
}
// distance is between 0..2, so multiply between 0.5
var distDistance = logDTransform(distance*.5)
// frequency-based distance
// ==========================
var delP = this.deldensity(true /* don't bother zeroing out empty bins */);
var delQ = other.deldensity(true);
var fP = delP.deldensity;
var fQ = delQ.deldensity;
var maxfP = delP.cummDeldensity;
var maxfQ = delQ.cummDeldensity;
distance = 0;
for (var i=0, len=fP.length; i<len; i++) {
distance += Math.abs(fP[i]-fQ[i]);
}
var freqDistance = logDTransform(distance/maxfP) *.5;
// return weighted average of the two distances
var ALPHA = 0.5;
return ALPHA * distDistance + (1-ALPHA) * freqDistance;
}
function logDTransform(x)
{
var k =0.7;
var expK = Math.pow(10, -k);
return (Math.log10(x+expK) + k) / (Math.log10(1+expK)+k);
}
function expDTransform(x)
{
var b = 3; // base
return (Math.pow(b, x-1) - 1/b) / (1-1/b);
}
GaussMixBivariate.prototype.klDivergence = function(other)
{
var DELENTROPY = false;
var delMe = null, delOt = null;
var LOG_C_1 = 1.0 / (Math.log10(1.01) + 2.0);
if (DELENTROPY)
{
delMe = this.deldensity();
delOt = other.deldensity();
}
// implements a KL divergence of other from this KL(me||other)
var P = DELENTROPY ? delMe.deldensity : this.pdf.view;
var Q = DELENTROPY ? delOt.deldensity : other.pdf.view;
if (P.length != Q.length) {
console.error("Can't compute divergence: probability distributions of different sizes");
return null;
}
var maxP = DELENTROPY ? delMe.cummDeldensity : this.cummDensity;
var maxQ = DELENTROPY ? delOt.cummDeldensity : other.cummDensity;
var maxP_1 = 1.0/maxP;
var maxQ_1 = 1.0/maxQ;
var divergence = 0, divergence2 = 0;
var entropyMe = 0, entropyOther = 0;
var distDistance = 0;
//console.log('max densities: ' + maxP + ', ' + maxQ);
for (var i=0, len=P.length; i<len; i++)
{
var p = P[i];
p *= maxP_1;
var q = Q[i];
q *= maxQ_1;
var logP = Math.log2(p);
var logQ = Math.log2(q)
entropyMe += logP * p;
entropyOther += logQ * q;
// divergence = p * log(p/q) = p * (log(p) - log(q))
divergence += p * (logP - logQ);
divergence2 += q * (logQ - logP);
/*
var d = Math.abs(p-q);
var d1 = (Math.log10(d+0.01) + 2) * LOG_C_1;
*/
distDistance += Math.abs(p-q);
//console.log("d: " + d + ", d1: " + d1 + ', ' + distDistance);
}
this.entropy = -entropyMe;
other.entropy = -entropyOther;
this.divergence = divergence;
other.divergence = divergence2;
return logDTransform(distDistance / 2);
/*
if (divergence > divergence2) {
return divergence / this.entropy;
} else {
return divergence2 / other.entropy;
}
//return Math.max(divergence, divergence2);
*/
}
var BI_SPLAT = [];
var splatGauss = new biGauss(0, 0, SPLAT_SIZE/4, SPLAT_SIZE/4, 0);
var cummSplat=0.0;
for (var I=0,r=-SPLAT_SIZE; r<=SPLAT_SIZE; r++)
{
for (var c=-SPLAT_SIZE; c<=SPLAT_SIZE; c++, I++)
{
var s = splatGauss.eval(c, r);
BI_SPLAT.push(s);
cummSplat += s;
}
}
for (var i=0; i<BI_SPLAT.length; i++) {
BI_SPLAT[i] /= cummSplat;
}
GaussMixBivariate.prototype.putOnTop = function()
{
function putNodeOnTop(node)
{
var n = jQuery(node);
n.parent().append(n.detach());
}
if (!this.svg) {
return;
}
else
{
putNodeOnTop(this.svg.node());
}
}
GaussMixBivariate.prototype.sampleModel = function(iterations, _field)
{
if (this.updateCDFMap) {
this.computeCDFMap();
}
var SPLAT_AREA=(SPLAT_SIZE*2+1)*(SPLAT_SIZE*2+1);
var splat = [];
for (var j=0;j<SPLAT_AREA; j++) {
splat.push(0);
}
var w = this.w;
var h = this.h;
var w_1 = w-1;
var h_1 = h-1;
var cdf = this.cdf.view;
var cdfMap = this.cdfMap;
var cdfLen = cdfMap.length;
// reset scalar field with zeros
_field.zero();
var view = _field.view;
// iterate
for (var i=0; i<iterations; i++)
{
// find center of splat
var I = cdfMap[ Math.floor(Math.random() * cdfLen) ];
// convert to row, column coordinate
var C = I % w;
var R = Math.floor(I/w);
// find splat boundary
var R0 = Math.max(0, R-SPLAT_SIZE), R1 = Math.min(h_1, R+SPLAT_SIZE);
var C0 = Math.max(0, C-SPLAT_SIZE), C1 = Math.min(w_1, C+SPLAT_SIZE);
var cummP=0;
// compute total density at this splat
for (var k=0, r=R0; r<=R1; r++)
{
for (var c=C0; c<=C1; c++, k++)
{
var p = cdf[r*w + c];
splat[k] = p;
cummP += p;
}
}
cummP = 1/cummP;
// distribute density throughout the splat according to the PDF
for (var k=0, r=R0; r<=R1; r++)
{
for (var c=C0; c<=C1; c++, k++)
{
view[ r*w + c ] += splat[k] * cummP;
}
}
/*
for (var S=0, r=-SPLAT_SIZE; r<=SPLAT_SIZE; r++)
{
var _R = R+r;
if (_R<0 && _R>=h) {
S+=SPLAT_SIZE*2+1;
continue;
}
else
{
_R*=w;
for (var c=-SPLAT_SIZE; c<=SPLAT_SIZE; c++, S++)
{
var _C = C+c;
if (_C>=0 && _C<w) {
view[ _R + _C ] += BI_SPLAT[S];
}
}
}
}
*/
//view[ R*w + C ] += 1.0;
}
_field.normalize();
_field.updated();
}
<file_sep>
var ATTEMPTS = 8;
var TRIALS0 = 15;
var TRIALS = 15;
var TOLERANCE = .07;
var TOLERANCE_INTERCEPT = 0.035;
var HIST_BIN = 10;
// different types of noise functions to choose from
var NOISE_TYPE_PERLIN = 1;
var NOISE_TYPE_SIMPLEX = 2;
var NOISE_TYPE_TERRAIN = 3;
var NOISE_TYPE_SIGMOID = 4;
var NOISE_TYPE_DISPLACEMENT = 5;
var LOW_GRADIENT = 1.5;
var MED_GRADIENT = 2.5;
var HI_GRADIENT = 5.0;
var DIFF = [0.1, 14.0];
var noiseType = NOISE_TYPE_SIMPLEX;
// terrain noise generator
var terrain = null;
function printTimeDiff(timeStart, timeEnd, label)
{
var elapsed = timeEnd - timeStart;
var sec=0, milli=0;
if (elapsed > 1000) {
sec = Math.floor(elapsed / 1000);
milli = elapsed % 1000;
} else {
sec = 0;
milli = elapsed;
}
console.log( (label ? label+": " : "time: ") + sec + " sec, " + milli + " milli");
}
function genericNoiseFunction(_scalarField, targetScale)
{
switch (noiseType)
{
case NOISE_TYPE_SIMPLEX:
makeNoise(_scalarField, targetScale);
break;
case NOISE_TYPE_TERRAIN:
terrain = new Terrain(Math.log2(_scalarField.w-1), _scalarField.view);
terrain.generate(targetScale*100);
_scalarField.normalize();
break;
case NOISE_TYPE_DISPLACEMENT:
}
}
function TAFC(width, height)
{
this.width = width;
this.height = height;
this.stim1 = new ScalarField(width, height);
this.stim2 = new ScalarField(width, height);
this.stim1.setMask([width, height]);
this.stim2.setMask([width, height]);
// shuffle image position?
this.shuffle = false;
this.swaped = false;
}
TAFC.prototype.shuffleImagePosition = function() {
this.shuffle = true;
}
TAFC.prototype.isSwaped = function() {
return this.swaped;
}
TAFC.prototype.randomStimulusThreaded = function(targetScale, diff, ksThreshold, callback)
{
(function(tafc, _targetScale, _diff, _ksThreshold, _callback)
{
var w = tafc.stim1.w;
var h = tafc.stim1.h;
tafc.swaped = false;
var worker = new Worker('src/threaded_noisegen.js');
worker.onmessage = function(msg)
{
var results = msg.data;
if (tafc.shuffle && Math.random() > .5)
{
tafc.stim1.buffer = results.stim2Buffer;
tafc.stim1.view = new Float32Array(results.stim2Buffer);
tafc.stim2.buffer = results.stim1Buffer;
tafc.stim2.view = new Float32Array(results.stim1Buffer);
tafc.swaped = true;
}
else
{
tafc.stim1.buffer = results.stim1Buffer;
tafc.stim1.view = new Float32Array(results.stim1Buffer);
tafc.stim2.buffer = results.stim2Buffer;
tafc.stim2.view = new Float32Array(results.stim2Buffer);
}
tafc.stim1.generated = true;
tafc.stim2.generated = true;
tafc.stim1.updated();
tafc.stim2.updated();
// clear out references to buffers (not needed)
results.stim1Buffer = undefined;
results.stim2Buffer = undefined;
callback(results);
}
worker.postMessage({
w: w,
h: h,
exponentWeight: getExponentWeight(),
targetScale: _targetScale,
diff: _diff,
ksThreshold: _ksThreshold,
// iteration parameters
TRIALS: TRIALS,
TRIALS0: TRIALS0,
TOLERANCE: TOLERANCE,
TOLERANCE_INTERCEPT: TOLERANCE_INTERCEPT,
ATTEMPTS: ATTEMPTS
});
})(this, targetScale, diff, ksThreshold, callback);
}
TAFC.prototype.randomStimulus = function(targetScale, diff, ksThreshold)
{
var timeStart = Date.now();
function sign(x) { if (x >= 0) return 1; else return -1; }
this.swaped = false;
var done = false;
var minDiff = Number.MAX_VALUE;
var maxDiff = Number.MIN_VALUE;
var actualDiff;
var tolerance = Math.abs(diff * TOLERANCE) + TOLERANCE_INTERCEPT;
var g1, g2;
// TODO: randomize the position of the target
var iterations = 0;
for (var longIt=0; longIt<TRIALS0 && !done; longIt++)
{
seedNoise();
setNoiseOffset(Math.random() * 10000, Math.random() * 10000);
genericNoiseFunction(this.stim1, targetScale);
g1 = calcAvgGradient(this.stim1);
for (var shortIt=0; shortIt<TRIALS && !done; shortIt++, iterations++)
{
seedNoise();
setNoiseOffset(Math.random() * 10000, Math.random() * 10000);
var K_RANGE = [.1,.1];
var k = Math.random() * (K_RANGE[1]-K_RANGE[0]) + K_RANGE[1];
genericNoiseFunction(this.stim2, targetScale+diff*k);
// compute difference between the two stimuli
g2 = calcAvgGradient(this.stim2);
actualDiff = g2-g1;
minDiff = Math.min(actualDiff, minDiff);
maxDiff = Math.max(actualDiff, maxDiff);
var delta = actualDiff-diff
if (Math.abs(delta) <= tolerance && sign(actualDiff) == sign(diff))
{
done = true;
/*
if (sign(actualDiff) != sign(diff))
{
// flip
console.log("flip!!!!!");
var temp = this.stim1;
this.stim1 = this.stim2;
this.stim2 = temp;
temp = g1;
g1 = g2;
g2 = temp;
}
*/
}
if (done && ksThreshold !== undefined && ksThreshold != 0.0)
{
// copy views
var view1 = this.stim1.copyView();
var view2 = this.stim2.copyView();
var ksRes = KS_test(view1, view2);
if (ksRes.maxD > ksThreshold) {
done = false;
}
}
}
}
//printTimeDiff(timeStart, Date.now(), "gen time");
// calculate amplitudes
timeStart = Date.now();
this.stim1Dist = this.stim1.calcAmplitudeFrequency(HIST_BIN);
this.stim2Dist = this.stim2.calcAmplitudeFrequency(HIST_BIN);
//chiSqured(this.stim1Dist, this.stim2Dist, this.width * this.height);
if (done)
{
console.log('** base: ' + g1.toFixed(2) + ', actualDiff: ' + actualDiff.toFixed(3) + ", req: " + diff.toFixed(3) + ", converged: " + iterations);
return {
actualDiff: actualDiff,
requestedDiff: diff,
iterations: iterations,
success: true
};
}
else
{
console.warn("could not converge. min Diff rached: " + minDiff);
return {
requestedDiff: diff,
minDiff: diff,
iterations: iterations,
success: false
};
}
}
TAFC.prototype.getFirst = function() {
return this.stim1;
};
TAFC.prototype.getSecond = function() {
return this.stim2;
};
TAFC.prototype.getFirstDist = function() {
return this.stim1Dist;
}
TAFC.prototype.getSecondDist = function() {
return this.stim2Dist;
}
var KS_lookup_i = 0;
var KS_field = null;
function KS_test(field1, field2)
{
var o1 = field1.sort();
var o2 = field2.sort();
if (o1.length != o2.length) {
console.error("can't compute KS test. Datasets not identical in length")
return null;
}
else
{
KS_lookup_i = 0;
KS_field = o2;
function lookup(x)
{
var len = KS_field.length;
var first = KS_field[0];
var last = KS_field[len-1];
if (x < first) {
return 0;
}
else if (x >= last) {
return 1;
}
else
{
// find next X
while (!(KS_field[KS_lookup_i] <= x && x <= KS_field[KS_lookup_i+1]))
{
KS_lookup_i++;
}
return (KS_lookup_i+1) / len;
}
}
var maxD = 0;
var maxIndex = 0;
var maxValue = 0;
for (var i=0, len=o1.length; i<len; i++)
{
var l = lookup(o1[i]);
var p = Math.abs((i+1)/len - l);
if (p > maxD)
{
maxD = p;
maxIndex = i;
maxValue = o1[i];
}
}
var critical = 1.627 * Math.sqrt( (o1.length + o2.length) / (o2.length * o1.length) );
console.log("maxD: " + maxD + ", critical: " + critical);
return {
maxD: maxD, valueAtMax: maxValue,
field1: o1, field2: o2
};
}
}
var cummP = 0;
function plotQQ(svg, w, h, field1, field2, index)
{
var W = w;
var H = h;
var lineGenerator = d3.line()
.x(function(d, i) { return d*W; })
.y(function(d, i) {
var out = cummP;
cummP += 1/field1.length;
return (1-out)*H;
});
svg.selectAll('path').remove();
var xScale = d3.scaleLinear().domain([0,1]).range([0, W]);
var yScale = d3.scaleLinear().domain([0, 100]).range([H, 0]);
var xAxis = d3.axisBottom(xScale); svg.append('g')
.style('font-size', 8)
.attr('transform', 'translate(0,' + H + ')').call(xAxis);
var yAxis = d3.axisLeft(yScale); svg.append('g')
.style('font-size', 8)
.call(yAxis);
cummP = 0;
svg.append('path')
.attr('d', lineGenerator(field1))
.attr('class', 'red')
.style('fill', 'none').style('stroke', 'red')
.style('stroke-width', '1px')
cummP = 0;
svg.append('path')
.attr('d', lineGenerator(field2))
.attr('class', 'blue')
.style('fill', 'none').style('stroke', 'blue')
.style('stroke-width', '1px')
if (index)
{
svg.append('line')
.style('stroke-width', '0.5px').style('stroke', '#888888')
.attr('y1', 0).attr('y2', H)
.attr('x1', index*W).attr('x2', index*W);
}
}
function chiSqured(d1, d2, stimSize)
{
var CHI_CRITICAL_95 = [3.841, 5.991, 7.815, 9.488, 1.070, 12.592, 14.067, 15.507, 16.919, 18.307, 19.675, 21.026, 22.362, 23.685, 24.996, 26.296, 27.587, 28.869, 30.144, 31.410, 32.671, 33.924, 35.172, 36.415, 37.652, 38.885, 40.113, 41.337, 42.557, 43.773, 44.985, 46.194, 47.400, 48.602, 49.802, 50.998, 52.192, 53.384, 54.572, 55.758, 56.942, 58.124, 59.304, 60.481, 61.656, 62.830, 64.001, 65.171, 66.339, 67.505, 68.669, 69.832, 70.993, 72.153, 73.311, 74.468, 75.624, 76.778, 77.931, 79.082, 80.232, 81.381, 82.529, 83.675, 84.821, 85.965, 87.108, 88.250, 89.391, 90.531, 91.670, 92.808, 93.945, 95.081, 96.217, 97.351, 98.484, 99.617, 100.749, 101.879, 103.010, 104.139, 105.267, 106.395, 107.522, 108.648, 109.773, 110.898, 112.022, 113.145, 114.268, 115.390, 116.511, 117.632, 118.752, 119.871, 120.990, 122.108, 123.225, 124.342, 124.342
];
var dTotal = [], pTable = [];
var bins = d1.length;
for (var i=0; i<bins; i++)
{
dTotal.push(d1[i] + d2[i]);
//pTable.push(dTotal[i] / (stimSize*2));
pTable.push(d1[i] / stimSize)
}
var table = [ d1, d2 ];
var chiStat = 0;
for (var i=0; i < bins; i++)
{
var p = pTable[i];
for (var s=1; s<2; s++)
{
var observed = table[s][i];
var e = stimSize * p;
var k = Math.pow(observed - e, 2) / e;
chiStat += k;
}
}
var dof = bins-1;
//console.log("$ chiStat: " + chiStat + ", critical[" + dof + "]: CHI_CRITICAL_95[dof-1]");
if (CHI_CRITICAL_95[dof-1] < chiStat) {
console.log("chiStat: " + chiStat + ", critical[" + dof + "]: " + CHI_CRITICAL_95[dof-1]);
return true;
}
else {
return false;
}
}
function calcAvgGradient(field)
{
var stats = field.getSubregionStats(0, 0, STIM_W, STIM_H);
return stats.steepness;
}
<file_sep>/* -------------------------------------
* Color Picker tool
* -------------------------------------
*/
var BACKGROUND = [200, 200, 200];
var MAX_B_CONTROLS = 12;
var MIN_LUMINANCE = 15;
var MAX_LUMINANCE = 90;
// color spaces
var COLORSPACE_LAB = 1;
var COLORSPACE_CAM02 = 2;
// ranges for color spaces
var A_RANGE=[-112, 112];
var B_RANGE=[-112, 112];
var JAB_A_RANGE = [-45, 45];
var JAB_B_RANGE = [-45, 45];
var CHANNEL_RAMP_OFFSET = 10;
var PICKER_RENDER_GL = true;
function isArray (value) {
return value && typeof value === 'object' && value.constructor === Array;
}
function ColorPicker(svg, mainCanvas, channelCanvas, threeDCanvas)
{
this.svg = svg;
this.mainCanvas = mainCanvas;
this.channelCanvas = channelCanvas;
this.threeDCanvas = threeDCanvas;
// default to using CIE LAB color space
this.colorSpace = COLORSPACE_LAB;
// location of current selection on the channel
// this should be a normalized number between 0 and 1
this.channelPos = 0.5;
this.makeUI();
// currently selected color
this.currentColor = null;
// callbacks, initially empty
this.callbacks = [];
// shows color curve
this.colorCurve = null;
// create a 'path' to visualize the map's curve in the color space
this.controlGroup = svg.append('g');
this.colormapCurve = this.controlGroup.append('path').attr('class', 'colormapCurve');
// control points to specify a color ramp within the picker
this.bControls = [];
this.luminanceProfile = 'linear';
if (PICKER_RENDER_GL)
{
this.glCanvas = document.createElement('canvas');
this.glCanvas.width = +mainCanvas.width;
this.glCanvas.height = +mainCanvas.height;
this.glCanvas.id = 'canvasPickerGL';
// object to store shaders
this.shaders = {};
var q = d3.queue();
q
.defer( gLoadShader, this, 'design/src/shaders/vertex.vert', 'vertex' )
.defer( gLoadShader, this, 'design/src/shaders/lab2rgb.frag', 'labslice')
.defer( gLoadShader, this, 'design/src/shaders/cam022rgb.frag', 'cam02slice');
(function(picker, _q) {
_q.awaitAll(function(error)
{
if (error) {
throw error;
}
else {
var bg = BACKGROUND;
picker.jabPipeline = new GLPipeline(picker.glCanvas);
picker.jabPipeline.addStage({
uniforms: {
J: {value: picker.getL()},
background: {value: [bg[0]/255, bg[1]/255, bg[2]/255]},
width: {value: +picker.glCanvas.width},
height: {value: +picker.glCanvas.height}
},
fragment: picker.shaders['cam02slice'],
vertex: picker.shaders['vertex']
});
picker.labPipeline = new GLPipeline(picker.glCanvas);
picker.labPipeline.addStage({
uniforms: {
L: {value: picker.getL()},
background: {value: [bg[0]/255, bg[1]/255, bg[2]/255]},
},
fragment: picker.shaders['labslice'],
vertex: picker.shaders['vertex']
});
// render initial view
picker.renderChannel();
picker.renderPerceptual();
}
});
})(this, q);
}
}
ColorPicker.prototype.L = function() {
return (1-this.channelPos) * 100;
}
ColorPicker.prototype.setL = function(_L)
{
this.channelPos = 1 - _L/100
this.drawChannelSelection();
this.renderPerceptual();
}
ColorPicker.prototype.getL = function() {
return 100 * (1-this.channelPos);
}
ColorPicker.prototype.getColorSpace = function() {
return this.colorSpace;
}
ColorPicker.prototype.addBControl = function(color)
{
if (this.bControls.length < MAX_B_CONTROLS) {
this.bControls.push(color);
}
this.updateBControl();
}
ColorPicker.prototype.hasCurve = function() {
return this.bControls.length >= 2;
}
ColorPicker.prototype.changeLuminanceProfile = function(profile)
{
this.luminanceProfile = profile;
if (this.bControls.length >= 2) {
this.instantiateColorMap();
}
}
ColorPicker.prototype.getLuminanceGivenProfile = function(t)
{
var MAX_L = MAX_LUMINANCE;
var MIN_L = MIN_LUMINANCE;
// color map properties
if (this.luminanceProfile == 'linear') {
return MIN_L + t*(MAX_L-MIN_L);
}
else if (this.luminanceProfile == 'divergent')
{
if (t < 0.5) {
return MIN_L + 2*t*(MAX_L-MIN_L)
}
else if (t > 0.5)
{
return MIN_L + 2*(1-t)*(MAX_L-MIN_L);
}
else {
return MAX_L;
}
}
else
{
return null;
}
}
ColorPicker.prototype.instantiateColorMap = function()
{
var SAMPLES = 100;
if (this.bControls.length >= 2)
{
// convert control group to an Array format
var controls = [], colors = [];
for (var i=0; i < this.bControls.length; i++)
{
var control = this.bControls[i];
// translate to L, A, B
var L = control.L;
var AB = this.xy2ab([control.x, control.y]);
var A = AB[0], B = AB[1];
var color = [L, A, B];
var colorLab = d3.lab(this.getColorFromAB(color));
controls.push(
{
lab: [colorLab.l, colorLab.a, colorLab.b],
value: control.value
});
colors.push(color)
}
// interpolate the curve
this.colormapCoordinates = [];
var colorset = [];
var interpolation = null;
switch (this.interpolationType) {
case 'spline':
interpolation = new CatmulRom(colors, true);
break;
case 'linear':
interpolation = new LinearInterpolation(colors, LINEAR_UNIFORM);
break;
case 'nonuniformLinear':
interpolation = new LinearInterpolation(colors, LINEAR_NON_UNIFORM);
break;
}
for (var i=0; i<SAMPLES; i++)
{
var t = i/(SAMPLES-1);
var c = interpolation.interpolate(t);
// make sure we have a valid color
if (isNaN(c[0]) || isNaN(c[1]) || isNaN(c[2])) {
console.error('NaN in interpolation');
}
// adjust control point luminance according to profile
var luminanceProfiled = this.getLuminanceGivenProfile(t)
if (luminanceProfiled !== null) {
c[0] = luminanceProfiled;
}
else
{
//console.log("non luminanceProfile")
}
var color;
switch (this.colorSpace)
{
case COLORSPACE_LAB:
color = d3.lab(c[0], c[1], c[2]);
break;
case COLORSPACE_CAM02:
color = d3.jab(c[0], c[1], c[2]);
break;
}
// add to the color map
var cLab = d3.lab(color);
colorset.push({
value: t,
lab: [cLab.l, cLab.a, cLab.b]
});
// now take that color and convert it coordinates
var coord = this.coordFromColor(color);
// add to coordinates
this.colormapCoordinates.push(coord);
}
this.plotColormapCurve2D();
this.plotColormapCurve3D();
// instantiate a new color map
var theColormap = new ColorMap(colorset, COLORSPACE_LAB ? 'lab' : 'jab');
// re-distribute the value in original control points based on interpolation
for (var i=0; i < controls.length; i++)
{
var t = interpolation.getTFromIndex(i);
controls[i].value = t;
// re-adjust the color based on the interpolation
var newColor = interpolation.interpolate(t);
var luminanceProfiled = this.getLuminanceGivenProfile(t)
if (luminanceProfiled !== null) {
newColor[0] = luminanceProfiled;
}
var newColorLab = d3.lab(this.getColorFromAB(newColor));
controls[i].lab = [
newColorLab.l, newColorLab.a, newColorLab.b
];
}
// sort controls
controls.sort(function(a, b) { return a.value-b.value});
for (var i=0; i<this.callbacks.length; i++)
{
var callback = this.callbacks[i];
if (callback.event == 'instantiateColormap') {
callback.callback(theColormap, controls);
}
}
return theColormap;
}
else
{
return null;
}
}
ColorPicker.prototype.setInterpolationType = function(interpType)
{
this.interpolationType = interpType;
this.interpolationSelector.makeActive(interpType);
}
ColorPicker.prototype.setControlPoints = function(colors)
{
var controls = [];
for (var i=0; i<colors.length; i++)
{
var c = colors[i];
var lab = d3.lab(c.lab[0], c.lab[1], c.lab[2]);
var xy, L;
switch (this.colorSpace) {
case COLORSPACE_LAB:
xy = this.ab2xy([lab.a, lab.b], COLORSPACE_LAB);
L = lab.l;
break;
case COLORSPACE_CAM02:
var jab = d3.jab(lab);
xy = this.ab2xy([jab.a, jab.b], COLORSPACE_CAM02);
L = jab.J;
break;
}
controls.push({
x: xy[0],
y: xy[1],
L: L,
colorSpace: this.colorSpace,
value: c.value,
});
}
this.bControls = controls;
this.updateBControl();
}
ColorPicker.prototype.updateBControl = function()
{
var B_CONTROL_R = 5;
this.colormapCurve.attr('d', null);
//console.log("bCongtrols[1]: " + this.bControls[1].L);
// show the curves
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var u = this.controlGroup.selectAll('g.bControlPoint').data(this.bControls);
u.exit().remove();
u = u.enter().append('g')
.attr('class', 'bControlPoint')
.each(function() {
var g = d3.select(this)
g.append('circle')
.attr('r', B_CONTROL_R).attr('cx', 1).attr('cy', 1)
.style('stroke', 'white');
g.append('circle')
.attr('r', B_CONTROL_R).attr('cx', 0).attr('cy', 0)
.style('stroke', 'black');
})
.merge(u);
// add circles
(function(u, picker)
{
u.each(function(d, i)
{
d3.select(this)
.attr('transform', 'translate(' + d.x + ',' + d.y + ')');
})
.on('mousedown', function(d, i)
{
d3.select(this).style('stroke-width', '3px');
picker.selectedBControl = i;
picker.selectedCircle = d3.select(this);
// mouse move
d3.select(document).on('mousemove.bControl', function()
{
var m = d3.mouse(picker.svg.node());
var selected = picker.bControls[ picker.selectedBControl ];
selected.x = m[0];
selected.y = m[1];
// update (which also updates on screen)
picker.updateBControl();
});
// mouse up
d3.select(document).on('mouseup.bControl', function()
{
d3.select(document)
.on('mousemove.bControl', null)
.on('mouseup.bControl', null);
picker.selectedCircle.style('stroke-width', null);
picker.selectedBControl = undefined;
picker.selectedCircle = undefined;
})
d3.event.stopPropagation();
})
.on('dblclick', function(d, i)
{
if (!event.shiftKey) {
// remove control point
picker.bControls.splice(i, 1);
picker.updateBControl();
d3.event.stopPropagation();
}
})
})(u, this);
return this.instantiateColorMap();
}
ColorPicker.prototype.changeColorSpace = function(newSpace)
{
this.colorSpace = newSpace;
this.renderChannel();
this.renderPerceptual();
// remap position of contorl points
var updateControls = false;
for (var i=0, len=this.bControls.length; i<len; i++)
{
var c = this.bControls[i];
if (c.colorSpace != newSpace)
{
// remap from XY to AB in original color space
var AB = this.xy2ab([c.x, c.y], c.colorSpace);
// remap from AB in original to new color space
var color = c.colorSpace == COLORSPACE_CAM02 ? d3.jab(c.L, AB[0], AB[1]) : d3.lab(c.L, AB[0], AB[1]);
var newColor = newSpace == COLORSPACE_CAM02 ? d3.jab(color) : d3.lab(color);
var LL = newSpace == COLORSPACE_CAM02 ? newColor.J : newColor.l;
if (isNaN(newColor.a) || isNaN(newColor.b)) {
console.error("Error in convering color")
}
// remap from AB in new color space to new XY
var xy = this.ab2xy([newColor.a, newColor.b], newSpace);
c.x = xy[0];
c.y = xy[1];
c.L = LL;
c.colorSpace = newSpace;
updateControls = true;
}
}
if (updateControls) {
this.updateBControl();
}
}
ColorPicker.prototype.registerCallback = function(event, callback, id)
{
// two events are supported: preview and pick
this.callbacks.push({ event: event, callback: callback, id: id });
}
ColorPicker.prototype.unregisterCallback = function(id)
{
}
ColorPicker.prototype.renderChannel = function() {
var canvas = this.channelCanvas;
var context = canvas.getContext("2d");
var width = canvas.width;
var height = canvas.height;
var image = context.createImageData(width, height);
// what should the aux canvas be?
switch (this.colorSpace)
{
case COLORSPACE_CAM02:
case COLORSPACE_LAB:
// luminance interpolation
for (var i=0; i<height; i++)
{
var cLAB = this.colorSpace == COLORSPACE_LAB
? d3.lab(100-100*i/(height-1), 0.0, 0.0)
: d3.jab(100-100*i/(height-1), 0.0, 0.0);
var cRGB = d3.rgb(cLAB);
var I = i * width * 4;
for (var j=0; j < width-CHANNEL_RAMP_OFFSET; j++)
{
image.data[I+j*4 ] = cRGB.r;
image.data[I+j*4+1] = cRGB.g;
image.data[I+j*4+2] = cRGB.b;
image.data[I+j*4+3] = 255;
}
}
break;
default:
for (var i=0; i<height; i++)
{
var cCAM = d3.jab(100-100*i/(height-1), 0.0, 0.0);
}
break;
}
// store the image data
this.channelImage = image;
// display it
context.putImageData(image, 0, 0);
// create a thing rectangle to indicate currently selected position along with channel
this.drawChannelSelection();
}
ColorPicker.prototype.drawChannelSelection = function()
{
var context = this.channelCanvas.getContext("2d");
var height = this.channelCanvas.height;
var width = this.channelCanvas.width;
context.fillStyle="#222222";
context.strokeStyle="";
context.putImageData(this.channelImage, 0, 0);
var y = (height-1) * this.channelPos;
var path=new Path2D();
path.moveTo(width - CHANNEL_RAMP_OFFSET, y);
path.lineTo(width-1, y-6);
path.lineTo(width-1, y+6);
context.fill(path);
// draw two markers to show MIN/MAX_LUMINANCE
//context.fillStyle="";
context.strokeStyle="#ffff00";
context.beginPath();
context.moveTo(0, (height-1) * (1-MAX_LUMINANCE/100));
context.lineTo(width-CHANNEL_RAMP_OFFSET, (height-1) * (1-MAX_LUMINANCE/100));
context.stroke();
context.strokeStyle="#ffff00";
context.beginPath();
context.moveTo(0, (height-1) * (1-MIN_LUMINANCE/100));
context.lineTo(width-CHANNEL_RAMP_OFFSET, (height-1) * (1-MIN_LUMINANCE/100));
context.stroke();
}
ColorPicker.prototype.plotColormap = function(colorPoints)
{
var coordinates = [];
for (var i=0; i<colorPoints.length; i++)
{
var p = colorPoints[i];
var c = this.coordFromColor(p.color);
coordinates.push(c)
}
this.colormapCoordinates = coordinates;
// plot the 2D color map curve
this.plotColormapCurve2D();
// plot the 3D color map curve
if (this.threeDCanvas) {
this.plotColormapCurve3D();
}
}
ColorPicker.prototype.plotColormapCurve2D = function()
{
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var lineGen = d3.line()
.x(function(d) { return d.x * (w-1);})
.y(function(d) { return d.y * (w-1);});
var pathD = lineGen(this.colormapCoordinates);
if (pathD.indexOf('NaN') != -1) {
console.log("ERROR!");
}
this.colormapCurve.attr('d', pathD);
}
ColorPicker.prototype.plotColormapCurve3D = function()
{
if (!this.renderer)
{
// renderer
var canvas = this.threeDCanvas;
this.renderer = new THREE.WebGLRenderer({
canvas: canvas
});
this.renderer.setClearColor(0xcccccc, 1);
// camera
var camera = new THREE.PerspectiveCamera( 45, +canvas.width / +canvas.height, 1, 1000 );
camera.position.set( 0, 0, 400 );
camera.lookAt( new THREE.Vector3( 0, 0, 0 ) );
// add 'Orbit' controls to camera
controls = new THREE.OrbitControls( camera, this.renderer.domElement );
(function(_controls, picker) {
_controls.addUpdateCallback(function() {
picker.renderer.render(picker.scene, picker.camera);
});
})(controls, this)
this.camera = camera;
// scene
this.scene = new THREE.Scene();
// plane
var planeGeom = new THREE.PlaneBufferGeometry( 100, 100, 8, 8 )
var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 1 } );
var wireframe = new THREE.LineSegments( planeGeom, mat );
this.plane = wireframe;
this.plane.rotateX( Math.PI / 2 );
// add plane to scene
this.scene.add(this.plane);
// add sphere to be used for brushing
var sphereGeom = new THREE.SphereGeometry( 2.5, 32, 32 );
var sphereMaterials = new THREE.MeshBasicMaterial( {color: 0xff0000, wireframe: true} );
var sphere = new THREE.Mesh( sphereGeom, sphereMaterials );
this.scene.add( sphere );
this.sphere = sphere;
this.sphere.visible = false;
}
// if there is an old scene, dispose of it
if (this.lineObject) {
this.scene.remove(this.lineObject);
doDispose(this.lineObject);
this.lineObject = undefined;
}
// create line
var material = new THREE.LineBasicMaterial( { color: 0x01188e, linewidth: 4.0 } );
var geometry = new THREE.Geometry();
// insert vertices
var coordinates = this.colormapCoordinates;
var a_range = this.colorSpace == COLORSPACE_LAB ? A_RANGE : JAB_A_RANGE;
var b_range = this.colorSpace == COLORSPACE_LAB ? B_RANGE : JAB_B_RANGE;
for (var i=0, len=coordinates.length; i<len; i++)
{
var p = coordinates[i];
geometry.vertices.push(new THREE.Vector3( 100*(p.x-.5), 100*p.z, 100*(p.y-.5) ));
}
this.lineObject = new THREE.Line( geometry, material );
this.scene.add(this.lineObject);
this.renderer.render( this.scene, this.camera );
}
ColorPicker.prototype.makeUI = function() {
(function(picker) {
d3.select(picker.channelCanvas).on("mousedown", function()
{
// test if we're manipulating MIN/MAX_Luminance
var m = d3.mouse(this);
var y = m[1];
var MAX_Y = +this.height * (1-MAX_LUMINANCE/100);
var MIN_Y = +this.height * (1-MIN_LUMINANCE/100);
var withinMax = Math.abs(y-MAX_Y) < 5;
var withinMin = Math.abs(y-MIN_Y) < 5;
if ( withinMax ) {
picker.pick = 'max';
}
else if ( withinMin ) {
picker.pick = 'min';
}
else {
picker.pick = undefined;
}
d3.select(document)
.on("mousemove.channelPicker", function()
{
var m = d3.mouse(picker.channelCanvas);
var h = +picker.channelCanvas.height;
if (picker.pick == 'max')
{
m[1] = Math.max(0, m[1]);
m[1] = Math.min(m[1], h*(1-MIN_LUMINANCE/100)-5);
MAX_LUMINANCE = (1-m[1]/h)*100;
picker.drawChannelSelection();
picker.instantiateColorMap();
}
else if (picker.pick == 'min')
{
m[1] = Math.min(h, m[1]);
m[1] = Math.max(m[1], h*(1-MAX_LUMINANCE/100)+5)
MIN_LUMINANCE = (1-m[1]/h)*100;
picker.drawChannelSelection();
picker.instantiateColorMap();
}
else
{
m[1] = Math.min(h, Math.max(0, m[1]));
// set Luminance for color picker
var L = (1 - m[1] / h) * 100;
picker.setL(L);
// callbacks
for (var i=0, len=picker.callbacks.length; i<len; i++) {
var c = picker.callbacks[i];
if (c.event == 'changeLuminance') {
c.callback(L);
}
}
}
})
.on("mouseup.channelPicker", function() {
d3.select(document)
.on("mousemove.channelPicker", null)
.on("mouseup.channelPicker", null);
})
})
picker.svg
.on('mousemove', function() {
var c = picker.colorFromMouse(d3.mouse(this));
if (picker.mouseDown) {
picker.pickColor(c);
}
else {
picker.previewColor(c);
}
})
.on('mouseout', function() {
picker.previewColor();
})
.on('mousedown', function()
{
var m = d3.mouse(this);
if (d3.event.shiftKey)
{
// add a control ppoint
picker.addBControl({
x: m[0], y: m[1],
L: picker.L(),
colorSpace: picker.getColorSpace()
});
}
else
{
var c = picker.colorFromMouse(d3.mouse(this));
picker.pickColor(c);
picker.mouseDown = true;
}
})
.on('dblclick', function() {
if (d3.event.shiftKey) {
picker.bControls = [];
picker.updateBControl();
}
})
.on('mouseup', function() {
picker.mouseDown = false;
});
var g = picker.svg.append('g')
g.attr('transform', 'translate(50,5)');
picker.interpolationSelector = new SmallRadio(g, [
{text: 'spline', choice: 'spline'},
{text: 'linear', choice: 'linear'},
{text: '! uniform', choice: 'nonuniformLinear'}
], function(choice) {
picker.interpolationType = choice;
picker.instantiateColorMap();
})
// defaults to spline interpolation
picker.interpolationType = 'spline';
})(this);
}
ColorPicker.prototype.coordFromColor = function(color)
{
if (isArray(color)) {
// assume this is a lab color
color = d3.lab(color[0], color[1], color[2])
}
var w = +this.mainCanvas.width, h = +this.mainCanvas.height;
var xScale = d3.scaleLinear(), yScale = d3.scaleLinear(), x, y, L, c;
switch (this.colorSpace)
{
case COLORSPACE_LAB:
xScale.range([0, 1]).domain(A_RANGE);
yScale.range([1, 0]).domain(B_RANGE);
c = d3.lab(color);
L = c.l;
break;
case COLORSPACE_CAM02:
xScale.range([0, 1]).domain(JAB_A_RANGE);
yScale.range([1, 0]).domain(JAB_B_RANGE);
c = d3.jab(color);
L = c.J;
break;
}
x = xScale(c.a);
y = yScale(c.b);
z = L/100;
return {x: x, y: y, z: z};
}
ColorPicker.prototype.colorFromMouse = function(mouse)
{
var canvas = this.mainCanvas;
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var xScale, yScale, A, B;
switch (this.colorSpace)
{
case COLORSPACE_LAB:
xScale = d3.scaleLinear().domain([0, w-1]).range(A_RANGE);
yScale = d3.scaleLinear().domain([h-1, 0]).range(B_RANGE);
B = yScale(mouse[1]);
A = xScale(mouse[0]);
return d3.lab((1-this.channelPos)*100, A, B);
break;
case COLORSPACE_CAM02:
xScale = d3.scaleLinear().domain([0, w-1]).range(JAB_A_RANGE);
yScale = d3.scaleLinear().domain([h-1, 0]).range(JAB_B_RANGE);
B = yScale(mouse[1]);
A = xScale(mouse[0]);
return d3.lab(d3.jab((1-this.channelPos)*100, A, B));
}
}
ColorPicker.prototype.switchToColor = function(c)
{
var color, L;
switch (this.colorSpace)
{
case COLORSPACE_CAM02:
color = d3.jab(c);
L = color.J;
break;
case COLORSPACE_LAB:
color = d3.lab(c);
L = color.l;
break;
}
if (!color.displayable()) {
// color not displyable in RGB gamut
//console.log("\tNon-displayable");
}
else
{
// adjust the channel position to match luminance of given color
this.setL(L);
// change the color div to reflect selection
d3.select('#pickedColor')
.style('background-color', c.toString());
this.markColor(color);
}
}
ColorPicker.prototype.markColor = function(c)
{
/*
var a_range, b_range;
switch (this.colorSpace)
{
case COLORSPACE_CAM02:
c = d3.jab(c);
a_range = JAB_A_RANGE;
b_range = JAB_B_RANGE;
break;
case COLORSPACE_LAB:
c = d3.lab(c);
a_range = A_RANGE;
b_range = B_RANGE;
break;
}
// draw a simple cross sign
var aS = d3.scaleLinear().domain(a_range).range([0, +this.mainCanvas.width]);
var bS = d3.scaleLinear().domain(b_range).range([+this.mainCanvas.height, 0]);
var x = aS(c.a);
var y = bS(c.b);
var ctx = this.mainCanvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(x-5, y);
ctx.lineTo(x+5, y);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x, y-5);
ctx.lineTo(x, y+5);
ctx.stroke();
*/
}
ColorPicker.prototype.pickColor = function(c, skipCallback)
{
switch (this.colorSpace)
{
case COLORSPACE_CAM02:
case COLORSPACE_LAB:
var cLab = d3.lab(c);
if (!cLab.displayable()) {
//console.log("\tNon-displayable");
}
else
{
// adjust the channel position to match luminance of given color
//this.channelPos = 1 - cLab.l / 100;
//this.drawChannelSelection();
// change the color div to reflect selection
d3.select('#pickedColor')
.style('background-color', c.toString());
// notify
if (!skipCallback) {
for (var i=0; i<this.callbacks.length; i++) {
var callback = this.callbacks[i];
if (callback.event == 'pick') {
callback.callback(c);
}
}
}
this.renderPerceptual();
this.markColor(c);
}
//this.renderLAB();
break;
}
}
ColorPicker.prototype.previewColor = function(c)
{
if (!c) {
d3.select("#previewColor").style('background-color', null);
for (var i=0; i<this.callbacks.length; i++) {
var callback = this.callbacks[i];
if (callback.event == 'preview') {
callback.callback(null);
}
}
}
else
{
var cLab = d3.lab(c);
if (cLab.displayable())
{
d3.select("#previewColor").style('background-color', cLab.toString());
for (var i=0; i<this.callbacks.length; i++)
{
var callback = this.callbacks[i];
if (callback.event == 'preview') {
callback.callback(cLab);
}
}
}
else
{
d3.select("#previewColor").style('background-color', null);
}
}
}
ColorPicker.prototype.brushColor = function(color)
{
if (color)
{
if (isArray(color)) {
color = d3.lab(color[0], color[1], color[2]);
}
switch(this.colorSpace)
{
case COLORSPACE_LAB:
color = d3.lab(color);
break;
case COLORSPACE_CAM02:
color = d3.jab(color);
break;
}
// highlight location in SVG
var circle = this.svg.selectAll('circle.brushBall');
if (circle.size() == 0) {
this.svg.append('circle')
.attr('class', 'brushBall')
.attr('r', '5');
}
var coord = this.coordFromColor(color);
var w = +this.mainCanvas.width, h = +this.mainCanvas.height;
circle
.attr('visibility', 'visible')
.attr('cx', coord.x * w)
.attr('cy', coord.y * h);
// switch to color
this.switchToColor(color);
if (this.renderer && this.sphere) {
this.sphere.position.x = 100*(coord.x-.5);
this.sphere.position.y = 100*(coord.z);
this.sphere.position.z = 100*(coord.y-.5);
this.sphere.visible = true;
this.renderer.render( this.scene, this.camera );
}
}
else
{
this.svg.selectAll('circle.brushBall')
.attr('visibility', 'hidden');
if (this.renderer && this.sphere) {
this.sphere.visible = false;
this.renderer.render( this.scene, this.camera );
}
}
}
ColorPicker.prototype.renderPerceptual = function()
{
// color ranges (actual LAB ranges are -128, 127)
var a = this.colorSpace == COLORSPACE_LAB ? A_RANGE : JAB_A_RANGE;
var b = this.colorSpace == COLORSPACE_LAB ? B_RANGE : JAB_B_RANGE;
var canvas = this.mainCanvas;
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var context = canvas.getContext("2d");
var image = context.createImageData(w, h);
var xScale = d3.scaleLinear().domain([0, w-1]).range(a);
var yScale = d3.scaleLinear().domain([h-1, 0]).range(b);
var L = 100 - this.channelPos * 100;
if (this.colorSpace == COLORSPACE_CAM02 && PICKER_RENDER_GL)
{
var uniforms = this.jabPipeline.getStage(0).getUniforms();
uniforms.J.value = L;
this.jabPipeline.run();
glCanvasToCanvas(this.glCanvas, this.mainCanvas, true);
}
else if (this.colorSpace == COLORSPACE_LAB && PICKER_RENDER_GL)
{
var uniforms = this.labPipeline.getStage(0).getUniforms();
uniforms.L.value = L;
this.labPipeline.run();
glCanvasToCanvas(this.glCanvas, this.mainCanvas, true);
}
else
{
var I=0, displayables = 0, imageData = image.data;
for (var r=0; r<h; r++)
{
var B = yScale(r);
for (var c=0; c<w; c++, I+=4)
{
var A = xScale(c);
// deal with off-gamut d3-cam02 issue
var offgamut = false;
if (this.colorSpace == COLORSPACE_CAM02 && L < 40) {
var limit = h*(20/250)+h*((160-20)/250)*(L/40);
var offLimitC = [w/2-limit, w/2+limit];
var offLimitR = [h/2+h*(20/250)-limit, h/2+h*(20/250)+limit];
if (!(c >= offLimitC[0] && c <= offLimitC[1] &&
r >= offLimitR[0] && r <= offLimitR[1]))
{
imageData[I] = BACKGROUND[0];
imageData[I+1] = BACKGROUND[1];
imageData[I+2] = BACKGROUND[2];
imageData[I+3] = 255;
offgamut = true;
continue;
}
}
var cLAB = this.colorSpace == COLORSPACE_LAB ? d3.lab(L, A, B) : d3.jab(L, A, B);
if (cLAB.displayable())
{
var cRGB = d3.rgb(cLAB);
imageData[I] = cRGB.r;
imageData[I+1] = cRGB.g;
imageData[I+2] = cRGB.b;
imageData[I+3] = 255;
//displayables++;
}
else if (!offgamut)
{
imageData[I] = BACKGROUND[0];
imageData[I+1] = BACKGROUND[1];
imageData[I+2] = BACKGROUND[2];
imageData[I+3] = 255;
}
}
}
context.putImageData(image, 0, 0);
}
}
ColorPicker.prototype.xy2ab = function(xy, colorSpace)
{
if (!colorSpace) {
colorSpace = this.colorSpace;
}
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var a_range, b_range;
switch (colorSpace)
{
case COLORSPACE_LAB:
a_range = A_RANGE;
b_range = B_RANGE;
break;
case COLORSPACE_CAM02:
a_range = JAB_A_RANGE;
b_range = JAB_B_RANGE;
break;
}
// create scales
var aScale = d3.scaleLinear().range(a_range).domain([0, w-1]);
var bScale = d3.scaleLinear().range(b_range).domain([h-1, 0]);
return [
aScale(xy[0]),
bScale(xy[1])
];
}
ColorPicker.prototype.ab2xy = function(ab, colorSpace)
{
if (!colorSpace) {
colorSpace = this.colorSpace;
}
var w = +this.mainCanvas.width;
var h = +this.mainCanvas.height;
var a_range, b_range;
switch (colorSpace)
{
case COLORSPACE_LAB:
a_range = A_RANGE;
b_range = B_RANGE;
break;
case COLORSPACE_CAM02:
a_range = JAB_A_RANGE;
b_range = JAB_B_RANGE;
break;
}
// create scales
var xScale = d3.scaleLinear().domain(a_range).range([0, w-1]);
var yScale = d3.scaleLinear().domain(b_range).range([h-1, 0]);
return [
xScale(ab[0]),
yScale(ab[1])
];
}
// expects an array of L, A, B. Returns a color D3 color object
// based in the current color space
ColorPicker.prototype.getColorFromAB = function(c)
{
switch (this.colorSpace)
{
case COLORSPACE_LAB:
return d3.lab(c[0], c[1], c[2]);
break;
case COLORSPACE_CAM02:
return d3.jab(c[0], c[1], c[2]);
break;
}
}
function getLab(c)
{
if (!isNaN(c.l) && !isNaN(c.a) && !isNaN(c.b)) {
return c;
}
else
{
if (!isNaN(c.r) && !isNaN(c.g) && !isNaN(c.b)) {
// we have an RGB. Convert it to LAB and return
return d3.lab(d3.rgb(c.r, c.g, c.b));
}
}
}
// dispose of three js object and its children
function doDispose(obj)
{
if (obj !== null)
{
for (var i = 0; i < obj.children.length; i++)
{
doDispose(obj.children[i]);
}
if (obj.geometry)
{
obj.geometry.dispose();
obj.geometry = undefined;
}
if (obj.material)
{
if (obj.material.map)
{
obj.material.map.dispose();
obj.material.map = undefined;
}
obj.material.dispose();
obj.material = undefined;
}
}
obj = undefined;
}
<file_sep>// ===========================================
// Douglas Peucker shape simplification
// ===========================================
var PROFILE_SHAPE_TOLERANCE = 1.5;
function Segment(p1, p2)
{
this.dy = p2.y - p1.y;
this.dx = p2.x - p1.x;
this.nominator = p2.x*p1.y-p2.y*p1.x;
this.denominator = Math.sqrt(this.dy * this.dy + this.dx * this.dx);
}
Segment.prototype.distanceToPoint = function(p)
{
return Math.abs( this.dy*p.x - this.dx*p.y + this.nominator) / this.denominator;
}
function DouglasPeucker(points, r0, r1, tolerance)
{
var index = r0;
var dmax = 0;
var segment = r0+1 <= r1-1 ? new Segment( points[r0], points[r1] ) : undefined;
for (var i = r0+1, len=r1-1; i <= len; i++)
{
var d = segment.distanceToPoint( points[i] );
if (d > dmax)
{
index = i;
dmax = d;
}
}
segment = undefined;
if ( dmax > tolerance )
{
var recResults1 = DouglasPeucker(points, r0, index, tolerance);
var recResults2 = DouglasPeucker(points, index, r1, tolerance);
recResults1.pop();
return recResults1.concat(recResults2);
}
else
{
return [ points[r0], points[r1] ];
}
}
function Profile(scalar_or_profile, p1, p2)
{
if ((p1 === null || p1 === undefined) || (p2 === null || p2 === undefined))
{
this.profile = scalar_or_profile;
}
else
{
var distance = Math.sqrt( Math.pow(p1.x-p2.x, 2) + Math.pow(p1.y-p2.y, 2) );
this.profile = scalar_or_profile.sampleProfile(p1, p2, distance/3);
}
}
Profile.prototype.similarity = function(profile2)
{
function sample(profile, u)
{
var i=u*(profile.length-1);
if (i%1 == 0) {
return profile[i];
}
else
{
// linear interpolation
var i0 = Math.floor(i);
var i1 = Math.ceil(i);
var p0 = profile[i0];
var p1 = profile[i1];
return (i-i0) * (p1-p0) + p0;
}
}
var p1 = this.profile;
var p2 = profile2.profile;
var N = 100;
/*
var totalDiff = 0;
for (var i=0; i<N; i++)
{
pp1 = sample(p1, i/(N-1));
pp2 = sample(p2, i/(N-1));
totalDiff += Math.abs(pp2-pp1);
}
return 1 - (totalDiff / N);
*/
var ts1 = [], ts2 = [];
for (var i=0; i<N; i++) {
ts1.push(sample(p1, i/(N-1)));
ts2.push(sample(p2, i/(N-1)));
}
ts1 = new Timeseries(ts1);
ts2 = new Timeseries(ts2);
var d = ts1.distance(ts2);
return 1 - d/N;
}
Profile.prototype.visualize = function(svg, w, h)
{
if (this.g) {
this.remove();
}
var profile = this.profile;
var profileShape = [];
for (var i=0, samples=profile.length; i<samples; i++) {
var p = {
x: i/(samples-1) * w,
y: (1-profile[i]) * h
};
profileShape.push(p);
/*
if (isNaN(p.x) || isNaN(p.y)) {
console.error("NaN in profile!");
}
*/
}
var pathGenerator = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
var g = svg.append('g')
.attr('class', 'profileShape');
g.append('rect')
.attr('width', w).attr('height', h)
.style('stroke', 'black').style('fill', 'none');
g.append('path')
.attr('d', pathGenerator(profileShape))
.style('stroke', 'black').style('fill', 'none')
.style('stroke-width', '2px');
this.g = g;
return this.g;
}
function incrementProfileShapeTolerance(delta) {
PROFILE_SHAPE_TOLERANCE += delta;
if (PROFILE_SHAPE_TOLERANCE < 0) {
PROFILE_SHAPE_TOLERANCE = 0;
}
return PROFILE_SHAPE_TOLERANCE;
}
Profile.prototype.visualizeToCanvas = function(canvas)
{
var canvasNode = canvas.node();
var w = canvasNode.width;
var h = canvasNode.height;
var ctx = canvasNode.getContext('2d');
ctx.clearRect(0, 0, w, h);
var profileShape = this.getProfileShape(w, h);
// simplify shape
profileShape = DouglasPeucker(profileShape, 0, profileShape.length-1, PROFILE_SHAPE_TOLERANCE)
ctx.strokeStyle="#000000";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(profileShape[0].x, profileShape[0].y);
for (var i=1, len=profileShape.length; i<len; i++)
{
var p = profileShape[i];
ctx.lineTo(p.x, p.y);
ctx.stroke();
}
}
Profile.prototype.reverse = function() {
this.doReverse = true;
}
Profile.prototype.getProfileShape = function(w, h)
{
var profile = this.profile;
var profileShape = [];
for (var i=0, samples=profile.length; i<samples; i++) {
profileShape.push({
x: ((this.doReverse ? samples-1-i : i) / (samples-1)) * w,
y: (1-profile[i]) * h
});
}
return profileShape;
}
Profile.prototype.getProfile = function()
{
return this.profile;
}
Profile.prototype.remove = function()
{
if (this.g) {
this.g.remove();
this.g = undefined;
}
}
<file_sep>// empty cell
var SCALAR_EMPTY = -99.0;
if (!ArrayBuffer.prototype.slice)
ArrayBuffer.prototype.slice = function (start, end) {
var that = new Uint8Array(this);
if (end == undefined) end = that.length;
var result = new ArrayBuffer(end - start);
var resultArray = new Uint8Array(result);
for (var i = 0; i < resultArray.length; i++) {
resultArray[i] = that[i + start];
}
return result;
}
function checkWebGL()
{
var canvas;
var ctx;
var exts;
try {
canvas = document.createElement('canvas');
ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
exts = ctx.getSupportedExtensions();
}
catch (e) {
return false;
}
return exts;
}
function checkFLoatingTexture(ext)
{
if (!ext) {
ext = checkWebGL();
}
if (!ext) {
return false;
}
else {
for (var i=0, len=ext.length; i<len; i++) {
var e = ext[i];
if (e.search('texture_float') >= 0) {
return true;
}
}
return false;
}
}
function ScalarField(width, height, doublePrecision)
{
if (width && height)
{
this.w = width;
this.h = height;
}
else {
this.w = 0;
this.h = 0;
}
var bytesPerPixel = doublePrecision ? 8 : 4;
if (this.w && this.h)
{
// create a buffer
this.buffer = new ArrayBuffer(bytesPerPixel * this.w * this.h);
this.view = doublePrecision ? new Float64Array(this.buffer) : new Float32Array(this.buffer);
}
this.bytesPerPixel = bytesPerPixel;
this.doublePrecision = (doublePrecision ? true : false);
this.contour = -1;
}
ScalarField.prototype.copyView = function()
{
var newBuffer = this.buffer.slice(0);
return this.doublePrecision ?
new Float64Array(newBuffer) : new Float32Array(newBuffer);
}
ScalarField.prototype.setMask = function(theMask)
{
this.mask = theMask;
}
ScalarField.prototype.getMaskedW = function() {
if (this.mask) {
return Math.min(this.w, this.mask[0]);
}
else
{
return this.w;
}
}
ScalarField.prototype.getMaskedH = function()
{
if (this.mask) {
return Math.min(this.h, this.mask[1]);
}
else
{
return this.h;
}
}
ScalarField.prototype.duplicate = function()
{
var field = this.view;
var newScalar = new ScalarField(this.w, this.h);
var newField = newScalar.view;
for (var i=0, len=field.length; i<len; i++)
{
newField[i] = field[i];
}
if (this.minmax) {
newScalar.minmax = [
this.minmax[0], this.minmax[1]
];
}
if (this.colorMap) {
newScalar.setColorMap(this.colorMap);
}
return newScalar;
}
ScalarField.prototype.zero = function()
{
for (var i=0, len=this.w*this.h; i<len; i++) {
this.view[i] = 0;
}
}
ScalarField.prototype.zeroLeaveEmpty = function()
{
var view = this.view;
var empty = SCALAR_EMPTY
for (var i=0, len=this.w*this.h; i<len; i++)
{
if (view[i] != empty) {
view[i] = 0;
}
}
}
function lerp(s, e, t) {return s+(e-s)*t;}
function blerp(c00, c10, c01, c11, tx, ty)
{
return lerp(lerp(c00, c10, tx), lerp(c01, c11, tx), ty);
}
ScalarField.prototype.crop = function(x, y, w, h)
{
x0 = Math.max(0, x);
y0 = Math.max(0, y);
x1 = Math.min(this.w, x0+w);
y1 = Math.min(this.h, y0+h);
var newBuffer = new ArrayBuffer(this.bytesPerPixel * (x1-x0) * (y1-y0));
var newView = this.doublePrecision ?
new Float64Array(newBuffer) : new Float32Array(newBuffer);
var view = this.view;
for (var y=y0, I=0; y<y1; y++)
{
for (var x=x0; x<x1; x++)
{
newView[I++] = view[ y*this.w + x ]
}
}
this.w = x1-x0;
this.h = y1-y0;
this.view = newView;
this.buffer = newBuffer;
}
ScalarField.prototype.guassian = function(kernelSize, proceduralFunc)
{
console.log("guassian, kernelSize: " + kernelSize);
var w = this.w, h = this.h;
// create kernel
var kernel = [], kernelLen = kernelSize * 2 + 1;
kernel.length = kernelLen * kernelLen;
// set guassian parameter so that the middle
// 3 delta = kernelSize -> delta = kernelSize / 3
var delta = kernelSize / 3;
var deltaSq = 2 * delta * delta;
var totalDensity = 0;
for (var r=0; r<kernelLen; r++)
{
for (var c=0; c<kernelLen; c++)
{
var e = Math.exp( -(Math.pow(c-kernelSize, 2)/deltaSq + Math.pow(r-kernelSize, 2)/deltaSq) );
kernel[ r*kernelLen + c ] = e;
totalDensity += e;
}
}
// noramlize so that the kernel's density is a total of 1.0
for (var i=0; i<kernel.length; i++) {
kernel[i] /= totalDensity;
}
var field = this.view;
var newScalar = new ScalarField(w, h);
var newField = newScalar.view;
var maxP = -Number.MAX_VALUE, minP = Number.MAX_VALUE;
var originalMinMax = this.originalMinMax;
// apply the kernel
for (var r=0; r < h; r++)
{
for (var c=0; c < w; c++)
{
var p = 0.0;
if ((!proceduralFunc) && (r < kernelSize || r >= (h - kernelSize) || c < kernelSize || c >= (w - kernelSize)))
{
p = field[r*w + c];
newField[r*w + c] = p;
maxP = Math.max(p, maxP);
minP = Math.min(p, minP)
}
else
{
var k = 0;
for (var kr=-kernelSize; kr<= kernelSize; kr++)
{
for (var kc=-kernelSize; kc<=kernelSize; kc++)
{
var y = r+kr, x = c+kc;
var f = null;
if (x < 0 || x >= w || y < 0 || y >= h) {
f = proceduralFunc(x, y, w, h);
if (originalMinMax)
{
f = (f - originalMinMax[0]) / (originalMinMax[1] - originalMinMax[0]);
}
}
else
{
f = field[ y*w + x ];
}
p += kernel[k++] * f;
}
}
newField[r*w + c] = p;
maxP = Math.max(p, maxP);
minP = Math.min(p, minP);
}
}
}
newScalar.minmax = [minP, maxP];
newScalar.normalize();
return newScalar;
}
ScalarField.prototype.scale = function(newW, newH, cropW, cropH)
{
// bi-linear interpolation:
// https://rosettacode.org/wiki/Bilinear_interpolation
// create a new image
var stopH = cropH ? cropH : newH;
var w = this.w, h=this.h, view = this.view;
var newBuffer = new ArrayBuffer(this.bytesPerPixel * newW * stopH);
var newView = this.doublePrecision ?
new Float64Array(newBuffer) : new Float32Array(newBuffer);
for (var i=0, r=0; r<stopH; r++) {
for (var c=0; c<newW; c++, i++) {
var gx = (c / newW) * (w-1);
var gy = (r / newH) * (h-1);
var gxi = Math.floor(gx);
var gyi = Math.floor(gy);
var c00 = view[ gyi*w + gxi ];
var c10 = view[ gyi*w + gxi+1];
var c01 = view[ (gyi+1)*w + gxi ];
var c11 = view[ (gyi+1)*w + gxi+1];
var result = blerp(c00, c10, c01, c11, gx-gxi, gy-gyi);
newView[i] = result;
}
}
// replace
this.buffer = newBuffer;
this.view = newView;
this.w = newW;
this.h = stopH;
this.minmax = undefined;
}
ScalarField.prototype.getMinMax = function()
{
if (!this.minax)
{
var m0 = Number.MAX_VALUE;
var m1 = Number.MIN_VALUE;
var view = this.view;
for (var r=0, rLen = this.getMaskedH(); r<rLen; r++)
{
var R = r * this.w;
for (var c=0, cLen=this.getMaskedW(); c<cLen; c++) {
var v = view[R + c];
if (v != SCALAR_EMPTY) {
m0 = Math.min(m0, v);
m1 = Math.max(m1, v);
}
}
}
this.minmax = [m0, m1]
}
return this.minmax;
}
ScalarField.prototype.getSubregionStats = function(x, y, w, h)
{
var view = this.view;
var minmax = [Number.MAX_VALUE, Number.MIN_VALUE];
var sW = this.w;
var mean = 0;
var count = 0;
var w_1 = this.w-1;
var h_1 = this.h-1;
// min/max and mean
for (var r=y, rr=y+h; r<rr; r++)
{
for (var c=x, cc=x+w; c<cc; c++, count++)
{
var v = view[ r*sW + c ];
minmax[0] = Math.min(minmax[0], v);
minmax[1] = Math.max(minmax[1], v);
mean += v;
}
}
mean /= count;
// standard deviation
var std = 0;
var steepness = 0;
var steepnessCount = 0, maxSteepness = 0;
for (var r=y, rr=y+h; r<rr; r++)
{
for (var c=x, cc=x+w; c<cc; c++)
{
std += Math.pow(view[ r*sW + c ]-mean, 2);
if (c > 0 && c < w_1 && r > 0 && r < h_1)
{
// kernel components
var aaa = view[r *sW+c-1];
var ddd = view[r *sW+c+1];
var www = view[(r-1)*sW+c ];
var xxx = view[(r+1)*sW+c ];
var eee = view[(r-1)*sW+c+1];
var ccc = view[(r+1)*sW+c+1];
var qqq = view[(r-1)*sW+c-1];
var zzz = view[(r+1)*sW+c-1];
// sobel kernels
var gx = -qqq - 2*aaa -zzz +eee +2*ddd +ccc;
var gy = qqq + 2*www +eee -zzz -2*xxx -ccc;
var g = Math.abs(gx) + Math.abs(gy);
steepness += 100 * g;
steepnessCount++;
maxSteepness = Math.max(g, maxSteepness);
}
}
}
std = Math.sqrt( std / count );
return {
minmax: minmax,
mean: mean,
std: std,
steepness: steepness / steepnessCount,
steepnessCount: steepnessCount,
maxSteepness: maxSteepness,
};
}
ScalarField.prototype.flipV = function()
{
var view = this.view;
var h1=0, h2=this.h-1, w=this.w;
while (h1 < h2)
{
var h1o = h1*w;
var h2o = h2*w;
for (var c=0; c<w; c++)
{
var temp = view[h1o+c];
view[h1o+c] = view[h2o+c];
view[h2o+c] = temp;
}
h1++;
h2--;
}
}
ScalarField.prototype.flipH = function()
{
var view = this.view;
var w=this.w, h=this.h;
for (var r=0; r<h; r++)
{
var c1=0, c2=w-1;
var rOffset = r*w;
while (c1 < c2)
{
var temp = view[rOffset+c1];
view[rOffset+c1] = view[rOffset+c2];
view[rOffset+c2] = temp;
c1++;
c2--;
}
}
}
ScalarField.prototype.normalize = function()
{
if (this.w > 0 && this.h > 0)
{
var minmax = this.getMinMax();
var len = minmax[1] - minmax[0];
if (len > 0 && !(minmax[0] == 0 && minmax[1] == 1))
{
var view = this.view;
var m0 = minmax[0];
var m1 = minmax[1];
var _len = 1.0 / len;
for (var i=0, len=this.w*this.h; i < len; i++)
{
var v = view[i];
if (v != SCALAR_EMPTY) {
view[i] = (v-m0) * _len;
}
}
this.originalMinMax = [m0, m1];
this.minmax = [0, 1];
this.updated();
}
}
}
ScalarField.prototype.setGreyscale = function()
{
var minmax = this.getMinMax();
var colorset = [
{
value: minmax[0],
rgb: [0, 0, 0]
},
{
value: minmax[1],
rgb: [255, 255, 255]
}
];
this.colorMap = new ColorMap(colorset)
}
ScalarField.prototype.setColorMap = function(colorMap)
{
if (colorMap) {
this.colorMap = colorMap;
}
if (this.gpuTexture)
{
if (!this.gpuColormapTexture || colorMap)
{
if (this.gpuColormapTexture) {
this.gpuColormapTexture.dispose();
this.gpuColormapTexture = undefined;
}
var theColorMap = colorMap || this.colorMap;
this.gpuColormapTexture = theColorMap.createGPUColormap();
}
}
}
ScalarField.prototype.getColorMap = function() {
return this.colorMap;
}
ScalarField.prototype.drawFFT = function()
{
var w = this.w;
var h = this.h;
var internalCanvas = document.createElement('canvas');
internalCanvas.width = w;
internalCanvas.height = h;
var context = internalCanvas.getContext('2d');
var imgData = context.createImageData(this.w, this.h);
var data = imgData.data;
// draw magnitude data
if (!this.fftMagnitude) {
this.fft();
}
var magnitude = this.fftMagnitude;
// create a new Float32Array for the log, normalized FFT magnitude
var LOG_RANGE = 1000000;
var LOG_MAX = Math.log(LOG_RANGE);
var minmaxrange = this.fftMaxMag-this.fftMinMag;
var minval = this.fftMinMag;
for (var r=0, i=0, j=0; r<h; r++)
{
for (var c=0; c<w; c++, i++, j+=4)
{
var nval = (magnitude[i] - minval) / minmaxrange;
var lval = (LOG_RANGE-1) * nval + 1;
var l = Math.log(lval) / LOG_MAX;
/*
var c = this.colorMap.mapValue(l);
data[j] = c.r;
data[j+1] = c.g;
data[j+2] = c.b;
data[j+3] = 255;
*/
var nC = Math.floor(l*255);
data[j] = nC;
data[j+1] = nC;
data[j+2] = nC;
data[j+3] = 255;
}
}
var center = 4*((h/2)*w + w/2);
data[center]=255;
data[center+1]=0;
data[center+2]=0;
return imgData;
}
/* =========================================================
* Visualization Code
* =========================================================
*/
ScalarField.prototype.generatePicture = function()
{
var internalCanvas = document.createElement('canvas');
internalCanvas.width = this.w;
internalCanvas.height = this.h;
var context = internalCanvas.getContext('2d');
var imgData = context.createImageData(this.w, this.h);
var data = imgData.data;
var colorMap = this.colorMap;
var view = this.view;
for (var i=0, j=0, len=this.w * this.h; i<len; i++, j+=4)
{
var c = colorMap.mapValue(view[i]);
if (typeof(c) == 'string') {
c = d3.color(c);
}
data[j] = c.r;
data[j+1] = c.g;
data[j+2] = c.b;
data[j+3] = 255;
}
context.putImageData(imgData, 0, 0);
return internalCanvas;
}
ScalarField.prototype.createGPUTexture = function(colorDif)
{
if (this.doublePrecision || this.bytesPerPixel!=4)
{
console.warn("ScalarField.createGPUTexture: double precision detected, which generally can't be GL texturized.")
}
var texture = new THREE.DataTexture(
this.view,
this.w, this.h,
THREE.LuminanceFormat, //THREE.RGBAFormat,
THREE.FloatType,
THREE.UVMapping,
THREE.ClampToEdgeWrapping, // wrapS
THREE.ClampToEdgeWrapping, // wrapT
THREE.NearestFilter, // mag filter
THREE.NearestFilter, // min filter
1
);
texture.needsUpdate = true;
this.gpuTexture = texture;
}
ScalarField.prototype.showContour = function(contour)
{
this.contour = contour;
if (this.contour < 0) {
this.contour = -1;
}
}
ScalarField.prototype.updated = function()
{
if (this.gpuTexture) {
this.gpuTexture.dispose();
this.gpuTexture = undefined;
}
}
ScalarField.prototype.generatePictureGL = function(canvas, COLOR_DIFF)
{
// upload the source scalar field data
if (!this.gpuTexture)
{
this.createGPUTexture();
}
// upload / update colormap
if (!this.gpuColormapTexture) {
this.setColorMap();
}
if (!this.colormapShader)
{
// load uniforms
this.colormapUniforms =
{
scalarField: { type: "t", value: this.gpuTexture},
colormap: { type: "t", value: this.gpuColormapTexture},
contour: { value: this.contour }
};
this.colormapShader = new THREE.ShaderMaterial({
uniforms: this.colormapUniforms,
fragmentShader: document.getElementById('colormapFragment').textContent,
vertexShader: document.getElementById('colormapVertex').textContent,
side: THREE.DoubleSide
});
}
else
{
this.colormapUniforms.scalarField.value = this.gpuTexture;
this.colormapUniforms.colormap.value = this.gpuColormapTexture;
this.colormapUniforms.contour.value = this.contour;
}
if (!this.quadScene)
{
var squareMesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), this.colormapShader);
this.quadScene = new THREE.Scene();
this.quadScene.add(squareMesh);
this.orthoCamera = new THREE.OrthographicCamera(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
if (!this.renderer)
{
if (typeof getRenderer == 'undefined' || typeof getRenderer == 'null' )
{
this.renderer = new THREE.WebGLRenderer({
canvas: canvas
});
this.renderer.setClearColor(0x000000, 1)
}
else
{
this.renderer = getRenderer(canvas);
}
}
this.renderer.render(this.quadScene, this.orthoCamera);
}
ScalarField.prototype.generateColorDiffGL = function(canvas)
{
// upload the source scalar field data
if (!this.gpuTexture)
{
this.createGPUTexture();
}
// upload / update colormap
if (!this.gpuColormapTexture) {
this.setColorMap();
}
// create a colormap to visualize color diff
if (!this.gpuDiffColormapTexture) {
var c = getColorPreset('extendedBlackBody');
this.gpuDiffColormapTexture = c.createGPUColormap();
}
if (!this.colorDiffShader)
{
this.colorDiffUniforms =
{
scalarField: { type: "t", value: this.gpuTexture},
colormap: { type: "t", value: this.gpuColormapTexture},
colorDiffScale: { type: 't', value: this.gpuDiffColormapTexture},
hPitch: { value: 1.0 / this.w },
vPitch: { value: 1.0 / this.h }
};
this.colorDiffShader = new THREE.ShaderMaterial({
uniforms: this.colorDiffUniforms,
fragmentShader: document.getElementById('colorDiffFragment').textContent,
vertexShader: document.getElementById('colormapVertex').textContent,
side: THREE.DoubleSide
});
}
else
{
this.colorDiffUniforms.scalarField.value = this.gpuTexture;
this.colorDiffUniforms.colormap.value = this.gpuColormapTexture;
}
if (!this.quadSceneDiff)
{
var squareMesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(2, 2), this.colorDiffShader);
this.quadSceneDiff = new THREE.Scene();
this.quadSceneDiff.add(squareMesh);
this.diffOrthoCamera = new THREE.OrthographicCamera(-1.0, 1.0, 1.0, -1.0, -1.0, 1.0);
}
if (!this.renderer)
{
if (typeof getRenderer == 'undefined' || typeof getRenderer == 'null' )
{
this.renderer = new THREE.WebGLRenderer({
canvas: canvas
});
this.renderer.setClearColor(0x000000, 1)
}
else
{
this.renderer = getRenderer(canvas);
}
}
this.renderer.render(this.quadSceneDiff, this.diffOrthoCamera);
}
ScalarField.prototype.fft = function()
{
var w = this.w;
var h = this.h;
var mW = w;
var mH = h;
var n = h * (mW);
// get FFT spectrum
var spectrum = this.spectrum;
if (!spectrum)
{
// calculate FFT
// measure time
start = performance.now();
console.log("calculating FFT...");
// FFT
spectrum = rfft2d(this.view, this.w, this.h);
this.sepctrum = spectrum;
// measure stop time
stop = performance.now();
console.log("FFT: " + (stop-start).toFixed(2) + " milliseconds");
}
// calculate FFT magnitude components
var maxmag = Number.MIN_VALUE, minmag = Number.MAX_VALUE;
var magnitude = new Float32Array(n);
for (var cH = 0, cW = 0, j=0, i=0, len=n*2; i<len; cW++, j++, i += 2)
{
if (cW >= w/2+1) {
cW = 0;
cH++;
}
var mag = Math.sqrt( Math.pow(spectrum[i], 2) + Math.pow(spectrum[i+1], 2) );
magnitude[cH*mW + cW] = mag;
maxmag = Math.max(maxmag, mag);
minmag = Math.min(minmag, mag);
}
// mirror and shift the magnitude
mirror_n_fftshift(magnitude, mW, mH);
this.fftMagnitude = magnitude;
this.fftMinMag = minmag;
this.fftMaxMag = maxmag;
this.mW = mW;
this.mH = mH;
}
ScalarField.prototype.calcAmplitudeFrequency = function(_bins)
{
var BINS = _bins || 30;
var histogram = [], curve = [];
for (var b=0; b<BINS; b++) {
histogram.push(0);
}
var view = this.view;
for (var r=0, rLen=this.getMaskedH(); r<rLen; r++)
{
var R = this.w * r;
for (var c=0, cLen=this.getMaskedW(); c<cLen; c++)
{
var b = Math.min(BINS-1, Math.floor(view[R+c] * BINS));
histogram[b]++;
}
}
for (var i=0, len=histogram.length; i<len; i++) {
curve.push({x: i, y: histogram[b]});
}
return histogram;
}
ScalarField.prototype.calcSpatialFrequency = function()
{
if (!this.spectrum) {
this.fft();
}
var magnitude = this.fftMagnitude;
var mW = this.mW;
var mH = this.mH;
var center = [Math.floor(this.w/2), Math.floor(this.h/2)];
// keep track of min/max frequency
var frequencies = [];
var minFreq = Number.MAX_VALUE;
var maxFreq = Number.MIN_VALUE;
for (var r=0; r<mH; r++)
{
for (var c=0; c<mW; c++)
{
//if (c == center[0] && r == center[1])
if (c == center[0] && r == center[1])
{
// DC point, ignore
continue;
}
else
{
var f = Math.sqrt( Math.pow(center[0]-c, 2), Math.pow(center[1]-r, 2) );
var v = magnitude[r*mW +c];
minFreq = Math.min(f, minFreq);
maxFreq = Math.max(f, maxFreq);
frequencies.push({f: f, contrast: v});
}
}
}
minFreq = 0;
// create a frequency histogram
var FREQ_BIN = 30;
var freqHistogram = []; freqHistogram.length = FREQ_BIN;
var freqCount = []; freqCount.length = FREQ_BIN;
for (var i=0; i<FREQ_BIN; i++) {
freqHistogram[i] = 0;
freqCount[i] = 0;
}
for (var i=0, len=frequencies.length; i<len; i++)
{
var freq = frequencies[i];
var f = freq.f;
var bin = Math.min( FREQ_BIN-1, Math.floor(((f - minFreq) / (maxFreq-minFreq)) * FREQ_BIN) );
freqHistogram[bin] += freq.contrast;
freqCount[bin]++;
}
// normalize the bins
for (var i=0; i<FREQ_BIN; i++) {
if (freqCount[i] > 1) {
freqHistogram[i] /= freqCount[i];
}
}
// sort frequencies
var powerSpectraH = {};
var powerSpectra = [];
var spectraIndex = [];
for (var i=0, len=frequencies.length; i<len; i++)
{
var freq = frequencies[i];
var f = freq.f;
var c = freq.contrast;
var a = powerSpectraH[f];
if (!a) {
powerSpectraH[f] = [c];
spectraIndex.push(f);
}
else
{
a.push(c);
}
}
var maxPower = 0;
for (var i=0, len=spectraIndex.length; i<len; i++) {
f = spectraIndex[i];
var a=powerSpectraH[f];
var avg=0;
for (var j=0; j<a.length; j++) {
avg += a[j];
}
avg /= a.length;
powerSpectra.push({x: f, y: avg, f: f});
maxPower = Math.max(maxPower, avg)
}
powerSpectra.sort(function(a, b) {
return a.x-b.x;
});
return {
histogram: freqHistogram,
counts: freqCount,
minFreq: minFreq,
maxFreq: maxFreq,
frequencies: frequencies,
powerSpectra: powerSpectra,
maxPower: maxPower
};
}
ScalarField.prototype.sampleProfile = function(p1, p2, samples)
{
var values = [];
var diff = {
x: p2.x-p1.x,
y: p2.y-p1.y
};
var w = this.w;
var view = this.view;
for (var i=0; i<samples; i++)
{
var alpha = i/(samples-1);
var gx = p1.x + alpha * diff.x;
var gy = p1.y + alpha * diff.y;
var gxi = Math.floor(gx);
var gyi = Math.floor(gy);
var c00 = view[ gyi*w + gxi ];
var c10 = view[ gyi*w + gxi+1];
var c01 = view[ (gyi+1)*w + gxi ];
var c11 = view[ (gyi+1)*w + gxi+1];
var r = blerp(c00, c10, c01, c11, gx-gxi, gy-gyi);
if (isNaN(r)) {
console.error("NaN in profile sample!");
}
values.push(r);
}
return values;
}
ScalarField.prototype.blur = function(kernelSize)
{
kernelSize = 7;
var hks = Math.floor(kernelSize / 2);
var kernel = [
[0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067],
[0.00002292, 0.00078634, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292],
[0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117],
[0.00038771, 0.01330373, 0.11098164, 0.22508352, 0.11098164, 0.01330373, 0.00038771],
[0.00019117, 0.00655965, 0.05472157, 0.11098164, 0.05472157, 0.00655965, 0.00019117],
[0.00002292, 0.00078633, 0.00655965, 0.01330373, 0.00655965, 0.00078633, 0.00002292],
[0.00000067, 0.00002292, 0.00019117, 0.00038771, 0.00019117, 0.00002292, 0.00000067]
];
var w = this.w;
var h = this.h;
var field = this.view;
var newBuffer = new ArrayBuffer(this.bytesPerPixel * this.w * this.h);
var newField = this.doublePrecision ?
new Float64Array : new Float32Array(newBuffer);
var maxP = -Number.MAX_VALUE, minP = Number.MAX_VALUE;
for (var r=hks, R=this.h-hks; r < R; r++)
{
for (var c=hks, W=this.w-hks; c < W; c++)
{
var p = 0.0;
for (var rr=0; rr<kernelSize; rr++)
{
for (var cc=0; cc<kernelSize; cc++)
{
p += kernel[rr][cc] * field[ (r+rr-hks) * w + c+cc-hks ];
}
}
newField[r * w + c] = p;
maxP = Math.max(p, maxP);
minP = Math.min(p, minP);
}
}
for (var i=0; i<2; i++ )
{
for (var r=(i==0 ? 0 : this.h-hks), j=0; j<hks; j++, r++)
{
for (var c = 0; c<this.w; c++)
{
var p = field[r * this.w + c];
maxP = Math.max(p, maxP);
minP = Math.min(p, minP);
newField[r*this.w + c] = p;
}
}
}
for (var i=0; i<2; i++ )
{
for (var c=(i==0 ? 0 : this.w-hks), j=0; j<hks; j++, c++)
{
for (var r = 0; r<this.h; r++)
{
var p = field[r * this.w + c];
maxP = Math.max(p, maxP);
minP = Math.min(p, minP);
newField[r*this.w + c] = p;
}
}
}
this.buffer = newBuffer;
this.view = newField;
this.minmax = [minP, maxP];
this.normalize();
}
function scalarFromImageData(imgData, cropW, cropH)
{
var w = imgData.width;
var h = imgData.height;
var data = imgData.data;
var sW = w;
var sH = h;
// crop, if desired
if (cropW) sW = Math.min(sW, cropW);
if (cropH) sH = Math.min(sH, cropH);
var scalar = new ScalarField(sW, sH);
// convert image to scalar
for (var r=0, j=0; r<h; r++)
{
if (r >= sH) {
continue;
}
for (var c=0; c<w; c++)
{
if (c >= sW) {
continue;
}
else
{
var i = 4*(r*w+c);
var rr = data[i];
var gg = data[i+1];
var bb = data[i+2];
var l;
if (rr == gg && gg == bb)
{
l = rr;
}
else
{
l = Math.min(255, Math.floor(.5 + 0.21*rr + 0.72*gg + 0.07*bb));
}
scalar.view[j++] = l;
}
}
}
return scalar;
}
function mirror_n_fftshift(input, m, n)
{
var m2 = m/2;
var n2 = n/2;
for (var r=1, rMirror=n-1; r<n; r++, rMirror--)
{
for (var c=0, cMirror=m-1; c<m2; c++, cMirror--)
{
input[rMirror*m + cMirror] = input[ r*m + c ];
}
}
for (var r=0; r<n2; r++)
{
for (var c=0; c<m; c++)
{
var rr = (r + n2) % n;
var cc = (c + m2) % m;
var temp = input[ r*m + c ];
input[ r*m + c ] = input[rr * m + cc];
input[rr * m + cc] = temp;
}
}
// copy center column
var rC = n/2
for (var c=m-1, cc=1; cc<m2; c--, cc++) {
input[ rC*m+cc ] = input[ rC*m+c ];
}
return input;
}
<file_sep>var STEP_START = 0.1/4;
var STEP_SAMPLES = 6;
var STEP_S = 0.1/12;
var STEP = 0.1/1.0;
var STEP_P = 0.1/6;
// function to sample a continuous colormap returning a discrete color sequence
function sampleRamp(colormap, n)
{
if (!n) n=9;
var ramp = {
name: "nothing",
colors: []
};
for (var i=0; i<n; i++)
{
var c = colormap.mapValue(i/(n-1));
ramp.colors.push(c);
}
return ramp;
}
function getLocalNameVariation(colormap, n)
{
var localNVar = 0, samples = 0, localLabDiff = 0;
for (var k=0, s=STEP_START; k<STEP_SAMPLES; s+= STEP_S, samples++, k++)
{
var l = (STEP - STEP_START) * (k/(STEP_SAMPLES-1)) + STEP_START;
s = l;
var c0=colormap.mapValue(n);
var c_1 = colormap.mapValue(n-s);
var c_2 = colormap.mapValue(n+s);
// compute local LAB differences
/*
var l0 = d3.lab(c0);
var l1 = d3.lab(c_1);
var l2 = d3.lab(c_2);
var labDiff =
Math.sqrt(Math.pow(l0.b-l1.b, 2) +
Math.pow(l0.a-l1.a, 2) +
Math.pow(l0.l-l1.l, 2));
labDiff += Math.sqrt(Math.pow(l0.b-l2.b, 2) +
Math.pow(l0.a-l2.a, 2) +
Math.pow(l0.l-l2.l, 2))
localLabDiff += labDiff;
*/
// compute local name variation
localNVar = Math.max(localNVar, getNameLength({colors: [c_1, c0, c_2]}));
}
return localNVar;
}
<file_sep><?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: php/user.php");
exit(0);
}
else if ($_SESSION['status'] == 'failed') {
header("Location: php/exit.php");
exit(0);
}
include 'php/connect.php';
$timeToStimulus = time() - $_SESSION['time'];
$userid = $_SESSION['user'];
$sql = "UPDATE user SET timeToStimulus=" . $timeToStimulus . " WHERE userid=" . $userid;
mysqli_query($conn, $sql);
mysqli_close($conn);
?><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
<script src="jnd/lib/d3.min.js"></script>
<script src="https://d3js.org/d3-axis.v1.min.js"></script>
<script src="jnd/lib/three.min.js"></script>
<script src="src/scalar.js"></script>
<script src="src/perlin.js"></script>
<script src="src/noisegen.js"></script>
<script src="src/terrain.js"></script>
<script src="design/src/colormap.js"></script>
<script src="design/src/gl_pipeline.js"></script>
<script src="design/src/coloranalysis.js"></script>
<script src="jnd/src/2afc.js"></script>
<script src="jnd/src/experiment.js"></script>
<style>
body {
background-color: #eeeeee;
font-family: Helvetica;
font-size: 17px;
/* disable selection */
-webkit-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
.uiParentDiv {
margin-bottom: 10px;
vertical-align: middle;
}
.uiDiv {
width: 80px;
display: inline-block;
}
.sliderDiv {
width: 80px;
height: 5px;
font-size: 10px;
}
.distRect {
fill: #cccccc;
stroke: #333333;
stroke-width: 1px;
}
#stimLeft {
margin: 5px 5px;
}
#stimRight {
margin: 5px 5px;
}
#divLeft {
border: solid 4px #eeeeee;
}
#divRight {
border: solid 4px #eeeeee;
}
#confirmButton
{
font-size: 14px;
height: 60px;
width: 110px;
}
#divColorScale {
text-align: center;
}
/* ========================================
* Modal stuff
* ========================================
*/
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 200px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<div style="width: 650px; margin:0 auto;">
<div style="margin-bottom: 20px">
<!--
<div class="uiParentDiv">
<div class="uiDiv">Gradient<br>magnitude</div>
<div class="uiDiv sliderDiv" id="sliderMagnitude"></div>
<div class="uiDiv" id="sliderMagnitudeValue"></div>
</div>
<div class="uiParentDiv">
<div class="uiDiv">Diff</div>
<div class="uiDiv sliderDiv" id="sliderDiff"></div>
<div class="uiDiv" id="sliderDiffValue"></div>
</div>
<div class="uiParentDiv">
<div class="uiDiv">Exponent</div>
<div class="uiDiv sliderDiv" id="sliderExponent"></div>
<div class="uiDiv" id="sliderExponentValue"></div>
</div>
-->
<div class="uiParentDiv">
<p>
<p>Terrain is steeper when there is larger CHANGE in elevation between adjacent locations in the map.<!-- That is, elevation changes more quickly as you move across the map. -->
<p>Click on the map that shows STEEPER terrain on average. Press the <u>Confirm</u> button to submit choice and get a new pair of maps.
<p>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content" style="font-size: 22px">
<span class="close">×</span>
<p><span id="modalText1">Doing great! Feel free to take a moment to rest your eyes if you wish.</span> </p>
<p id="modalText2">There are <span>Num</span> sets left.</p>
</div>
</div>
</div>
</div>
<div style="height: 230px">
<div id="divLeft" style="width: 210px; height: 210px; float: left">
<canvas id="stimLeft" width="200" height="200"></canvas>
</div>
<div id="divColorScale" style="width: 90; height: 210px; float: right;">
<div style="color: #666666; margin-left: 15px; margin-top: 35px; font-size: 13px">
high<br>elevation<br><canvas id="colorScaleCanvas" width="25" height="100"></canvas><br>low<br>elevation
</div>
</div>
<div id="divRight" style="width: 210px; height: 210px; float: right;">
<canvas id="stimRight" width="200" height="200"></canvas>
</div>
</div>
<div style="text-align: center; margin-top: 0px; margin-right: 60px">
<div>
<span id="alert" style="font-weight: bold; color: #db0000; font-size: 14px; visibility: hidden">Select one of the two maps!</span><br>
<button id="confirmButton">Confirm</button>
<br><img id="loadingImage" width="80" src="img/loading2.gif">
</div>
<div style="text-align: center; font-size: 14px">
Study progress:
<br>
<svg id="svgProgress" width="150" height="12" style="margtin-top: 5px; background-color: #cccccc">
<rect id="rectProgress" height="12" width="15" style="fill: #46a1fc"></rect>
</svg>
<span id="labelProgress">10%</span>
</div>
</div>
</div>
<script type="text/javascript">
var modal = document.getElementById("myModal");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
function displayModal() {
modal.style.display = "block";
}
var _modalCallback = null;
function setModalCallback(_callback) {
_modalCallback = _callback;
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
var originalDisplay = modal.style.display;
modal.style.display = "none";
if (originalDisplay == 'block') {
console.log("close modal");
if (_modalCallback) {
_modalCallback();
}
}
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event)
{
if (event.target == modal)
{
var originalDisplay = modal.style.display;
modal.style.display = "none";
if (originalDisplay == 'block') {
console.log("close modal");
if (_modalCallback) {
_modalCallback();
}
}
}
}
</script>
<script type="text/javascript">
// trial config
var COLORMAP = <?php echo "'" . $_SESSION['condition'] . "';\n"; ?>
//var MAGNITUDES = [2.0, 3.5, 5.0];
var MAGNITUDES = [3.0, 5.0];
var COLORMAPS = [ 'rainbowjet', 'coolwarm', 'viridis' ];
var START_DIFF = 3.0;
var TRIAL_COUNT = 40;
var MAG_ORDER = <?php echo "'" . (isset($_SESSION['magOrder']) ? $_SESSION['magOrder'] : 'R') . "';\n"; ?>
var COL_ORDER = <?php echo "'" . (isset($_SESSION['colOrder']) ? $_SESSION['colOrder'] : 'R') . "';\n"; ?>
if (MAG_ORDER === 'r' || MAG_ORDER === 'R') {
shuffleArray(MAGNITUDES);
}
else if (typeof MAG_ORDER === 'string' && MAG_ORDER.length > 0) {
MAGNITUDES = reorderArray(MAGNITUDES, MAG_ORDER);
}
if (COL_ORDER === 'r' || COL_ORDER === 'R') {
shuffleArray(COLORMAPS);
}
else if (typeof COL_ORDER === 'string' && COL_ORDER.length > 0) {
COLORMAPS = reorderArray(COLORMAPS, COL_ORDER);
}
// engagements
var ENGAGEMENT_CHECKS = 3;
var ENGAGEMENT_DIFF = 13.0;
// stepping
var STEP = 0.5/1.75;
var BACKWARD = 3.0*STEP;
var FORWARD = STEP;
// border style
var BORDER_STYLE = '4px solid blue';
var selectedImage = null;
function unselect()
{
d3.select("#divLeft")
.style("border", null);
d3.select("#divRight")
.style("border", null);
selectedImage = null;
}
d3.select("#divLeft").on("mousedown", function() {
d3.select("#divRight").style("border", null);
d3.select(this).style("border", BORDER_STYLE);
selectedImage = 'left';
d3.event.stopPropagation();
});
d3.select("#divRight").on("mousedown", function() {
d3.select("#divLeft").style("border", null);
d3.select(this).style("border", BORDER_STYLE);
selectedImage = 'right';
d3.event.stopPropagation();
});
d3.select("#confirmButton")
.on('click', function() {
if (!selectedImage) {
d3.select("#alert").style('visibility', 'visible');
//alert("Please answer by clicking one of the two maps.");
}
else
{
d3.select("#alert").style('visibility', 'hidden');
var result = experiment.answer(selectedImage);
}
d3.event.stopPropagation();
})
.on('mousedown', function() {
d3.event.stopPropagation();
})
d3.select("body").on('mousedown', function() { unselect(); });
var experiment = null;
// set periodic timeout to poll heartbeat
function heartbeat()
{
setTimeout(function() {
if (experiment) {
$.post('php/heartbeat.php', {
totalComplete: experiment.totalCount,
totalAll: TRIAL_COUNT * MAGNITUDES.length
}, function(data, status) {
console.log("heartbeat: " + data + ", status: " + status);
});
}
heartbeat();
}, 15*1000);
}
var lastColormapNotification = -2;
$(document).ready(function()
{
experiment = new Experiment(false, COLORMAP);
window.onbeforeunload = function() { return "Your work will be lost."; };
setModalCallback(function() {
experiment.resumeBlock();
});
experiment.setBlockPause(function(magnitudeIndex, colormapIndex)
{
console.log("mag: " + magnitudeIndex + ', col: ' + colormapIndex);
var left = experiment.cycleColormaps ? COLORMAPS.length-colormapIndex : MAGNITUDES.length-magnitudeIndex;
if (colormapIndex === 0 || lastColormapNotification == colormapIndex) {
experiment.resumeBlock();
return;
}
if (experiment.cycleColormaps)
{
lastColormapNotification = colormapIndex;
}
var text2 = null;
if (left == 1) {
text2 = "Only 1 set remaining.";
}
else
{
text2 = "There are " + left + " sets remaining.";
}
d3.select("#modalText2").html(text2);
if (colormapIndex < 0 && (magnitudeIndex == 2) || colormapIndex == 2)
{
d3.select("#modalText1").html("Almost finished. You may rest for a moment if you wish.");
}
displayModal();
});
heartbeat();
});
</script>
</body>
</html><file_sep>// Implementation of CatmulRom splines
// based on:
// https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline
var SAMPLES_PER_CURVE_SEGMENT = 40;
function vmult(scalar, v) {
return [
scalar * v[0],
scalar * v[1],
scalar * v[2]
];
}
function vadd(x, y) {
return [
x[0]+y[0],
x[1]+y[1],
x[2]+y[2]
];
}
function vsub(x, y)
{
return [
x[0]-y[0],
x[1]-y[1],
x[2]-y[2]
];
}
function normalize(a)
{
var L = a[0]*a[0] + a[1]*a[1] + a[2]*a[2];
if (L > 0) {
L = 1.0 / Math.sqrt(L)
return [L*a[0], L*a[1], L*a[2]];
}
else
{
return a;
}
}
function vlen(a) {
return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
}
function CatmulRom4(p0, p1, p2, p3, _t)
{
var ALPHA = 0.5;
function GetT(t, _p0, _p1)
{
var a =
Math.pow((_p1[0]-_p0[0]), 2) +
Math.pow((_p1[1]-_p0[1]), 2) +
Math.pow((_p1[2]-_p0[2]), 2);
var b = Math.pow(a, 0.5);
var c = Math.pow(b, ALPHA);
return (c + t);
}
var t0 = 0.0;
var t1 = GetT(t0, p0, p1);
var t2 = GetT(t1, p1, p2);
var t3 = GetT(t2, p2, p3);
var t = _t * (t2-t1) + t1;
var A1 = vadd( vmult( (t1-t)/(t1-t0), p0 ) , vmult( (t-t0)/(t1-t0), p1 ) );
var A2 = vadd( vmult( (t2-t)/(t2-t1), p1 ) , vmult( (t-t1)/(t2-t1), p2 ) );
var A3 = vadd( vmult( (t3-t)/(t3-t2), p2 ) , vmult( (t-t2)/(t3-t2), p3 ) );
var B1 = vadd( vmult( (t2-t)/(t2-t0), A1 ) , vmult( (t-t0)/(t2-t0), A2 ) );
var B2 = vadd( vmult( (t3-t)/(t3-t1), A2 ) , vmult( (t-t1)/(t3-t1), A3 ) );
var C = vadd( vmult( (t2-t)/(t2-t1), B1 ) , vmult( (t-t1)/(t2-t1), B2 ) );
return C;
}
function vpad(a, b, c)
{
var v1 = (vsub(b, a));
var v2 = c ? (vsub(c, b)) : [0, 0, 0];
var d1 = vlen(v1);
var d2 = vlen(v2);
var v = vadd( normalize(v1), normalize(v2) );
return vmult( c ? (d1+d2)/2 : 1, normalize(v) );
}
// uniformly sampled CatmulRom curve
function CatmulRom(controls, pad)
{
if (pad)
{
var l = controls.length;
var v0 = vpad(controls[0], controls[1], controls[2]);
var p0 = vsub(controls[0], v0);
var v1 = vpad(controls[l-1], controls[l-2]);
var p1 = vadd(controls[l-1], v1);
var newControls = ([p0]).concat(controls);
newControls.push(p1);
controls = newControls;
}
var out = [];
for (var i=1; i<controls.length-2; i++)
{
for (var j=0; j<SAMPLES_PER_CURVE_SEGMENT; j++)
{
var t = j/(SAMPLES_PER_CURVE_SEGMENT-1);
var p = CatmulRom4
(
controls[i-1],
controls[i ],
controls[i+1],
controls[i+2],
t
);
out.push(p);
}
}
this.controls = controls;
this.curve = out;
// add up distances
var totalD = 0;
var distances = [];
for (var i=0; i<out.length-1; i++)
{
var p0 = out[i];
var p1 = out[i+1];
var d = Math.sqrt(
Math.pow(p0[0]-p1[0], 2) +
Math.pow(p0[1]-p1[1], 2) +
Math.pow(p0[2]-p1[2], 2)
);
distances.push(d);
totalD += d;
}
// normalize d by total distances
for (var i=0; i<distances.length; i++)
{
distances[i] /= totalD;
}
this.distances = distances;
}
CatmulRom.prototype.sumDistanceTo = function(index)
{
var running = 0;
var distances = this.distances;
for (var i=0, len=Math.min(index, distances.length-1); i<len; i++) {
running += distances[i];
}
return running;
}
CatmulRom.prototype.getTFromIndex = function(index)
{
if (index == 0) {
return 0;
}
else if (index >= this.controls.length-2-1) {
return 1;
}
else {
return this.sumDistanceTo(index * SAMPLES_PER_CURVE_SEGMENT -1);
}
}
CatmulRom.prototype.interpolate = function(t)
{
// figure out we're we are in total distance
var distances = this.distances;
var curve = this.curve;
var running = 0;
var index = distances.length-1;
for (var i=0; i<distances.length; i++)
{
var d = distances[i];
running += d;
if (t <= running) {
index = i;
break;
}
}
if (index >= 0)
{
var s = 1-((running - t) / distances[index]);
var c0 = curve[index];
var c1 = curve[index+1];
return [
s * (c1[0]-c0[0]) + c0[0],
s * (c1[1]-c0[1]) + c0[1],
s * (c1[2]-c0[2]) + c0[2],
];
}
else
{
return null;
}
}
<file_sep>function SmallRadio(g, choices, _callback)
{
this.g = g;
// clear if anything
this.g.selectAll('g').remove();
// create groups for buttons
this.buttons = this.g.selectAll('g').data(choices);
this.buttons = this.buttons.enter().append('g')
.attr('transform', function(d, i) {
return 'translate(' + 0 + ',' + (i*14) + ')';
})
.merge(this.buttons);
(function(all, buttons, radio) {
buttons.each(function(d, i)
{
var thisG = d3.select(this);
thisG.append('rect')
.attr('x', 0).attr('y', 0).attr('class', 'smallButton' + (i==0 ? ' smallButtonClicked' : ''))
.attr('width', '10').attr('height', '10');
thisG.append('text')
.attr('x', -5).attr('y', 9).attr('class', 'smallText')
.attr('text-anchor', 'end').html(d.text);
thisG.on('click', function(_d)
{
all.selectAll('rect.smallButton').attr('class', 'smallButton');
d3.select(this).select('rect').attr('class', 'smallButton smallButtonClicked');
radio.fireCallback(_d.choice);
});
});
})(this.g, this.buttons, this);
if (_callback) {
this.callback = _callback;
}
}
SmallRadio.prototype.makeActive = function(_choice)
{
this.buttons.each(function(d)
{
d3.select(this).select('rect')
.attr('class', 'smallButton' + (d.choice===_choice ? ' smallButtonClicked' : ''));
});
}
SmallRadio.prototype.addCallback = function() {
this.callback = callback;
}
SmallRadio.prototype.fireCallback = function(choice) {
this.callback(choice)
}<file_sep>//BI_MAP_SIZE=1;
//CALLBACK_SAMPLE = false;
function DiscreteSampler(w, h, svg, model, colormap)
{
this.svg = svg;
this.colormap = colormap;
this.w = w;
this.h = h;
this.field = null;
this.model = model;
// add myself to the model
if (model) {
this.setModel(model);
}
ALL_SAMPLERS.push(this);
}
DiscreteSampler.prototype = Object.create(ScalarSample.prototype);
DiscreteSampler.prototype.vis = function()
{
if (!this.model) {
console.error("DiscreteSampler: No model!")
}
else if (!this.model.discreteMap)
{
console.error("DiscreteSampler: model has no discrete map!")
}
var discreteMap = this.model.discreteMap
this.selectionCache = discreteMap.visTheMap(this.svg, this.colormap, this.selectionCache);
}
DiscreteSampler.prototype.setColorMap = function(colormap)
{
this.colormap = colormap;
}
<file_sep>var shaderList = [
{name: 'vis', path: 'design/src/shaders/vis.frag'},
{name: 'vertex', path: 'design/src/shaders/vertex.vert'},
];
ALL_SCALAR_VIS = [];
function ScalarVis(field, canvas, colormap)
{
this.field = field;
this.w = field.w;
this.h = field.h;
this.canvas = canvas;
this.colormap = colormap;
if (this.canvas)
{
(function(me) {
me.visualizer = new ColorAnalysis(
me.field, me.canvas,
function() {
me.initVisPipeline();
}, shaderList
);
})(this);
}
if (!this.colormap) {
this.colormap = getColorPreset('viridis');
}
this.field.setColorMap(this.colormap);
ALL_SCALAR_VIS.push(this);
}
ScalarVis.prototype.setContour = function(contour)
{
var visUniforms = this.visualizer.getUniforms('vis', 0);
visUniforms.contour.value = contour;
this.vis();
}
ScalarVis.setUniversalColormap = function(colormap) {
for (var i=0; i<ALL_SCALAR_VIS.length; i++)
{
ALL_SCALAR_VIS[i].field.setColorMap(colormap);
ALL_SCALAR_VIS[i].colormap = colormap;
// render?
ALL_SCALAR_VIS[i].vis();
}
}
ScalarVis.prototype.vis = function()
{
if (!this.canvas)
{
console.log("Error: ScalarVis doesn't have a canvas.");
}
else if (!this.visualizer || !this.visualizer.ready())
{
// pipeline not yet ready. Set flag to callVis when it's ready
this.callVisFlag = true;
}
else {
this.visualizer.run('vis');
}
}
ScalarVis.prototype.initVisPipeline = function()
{
if (!this.canvas) {
console.log("Error: ScalarVis doesn't have a canvas.");
return;
}
// standard vis
var vis = new GLPipeline(this.visualizer.glCanvas);
vis.addStage({
uniforms: {
scalarField: {},
colormap: {},
contour: {value: -1.0},
},
inTexture: 'scalarField',
fragment: this.visualizer.shaders['vis'],
vertex: this.visualizer.shaders['vertex']
});
this.visualizer.pipelines = {
vis: vis,
};
//this.visualizer.createVisPipeline();
if (this.callVisFlag) {
this.callVisFlag = false;
this.vis();
}
}
<file_sep><?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: php/user.php");
exit(0);
}
else if ($_SESSION['status'] == 'failed') {
header("Location: php/exit.php");
exit(0);
}
include 'php/connect.php';
$timeToPractice = time() - $_SESSION['time'];
$userid = $_SESSION['user'];
$sql = "UPDATE user SET timeToPractice=" . $timeToPractice . " WHERE userid=" . $userid;
mysqli_query($conn, $sql);
mysqli_close($conn);
?><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://d3js.org/d3-queue.v3.min.js"></script>
<script src="jnd/lib/d3.min.js"></script>
<script src="https://d3js.org/d3-axis.v1.min.js"></script>
<script src="jnd/lib/three.min.js"></script>
<script src="src/scalar.js"></script>
<script src="src/perlin.js"></script>
<script src="src/noisegen.js"></script>
<script src="src/terrain.js"></script>
<script src="design/src/colormap.js"></script>
<script src="design/src/gl_pipeline.js"></script>
<script src="design/src/coloranalysis.js"></script>
<script src="jnd/src/2afc.js"></script>
<script src="jnd/src/experiment.js"></script>
<style>
body {
background-color: #ffffff;
font-family: Helvetica;
font-size: 17px;
/* disable selection */
-webkit-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
.uiParentDiv {
margin-bottom: 10px;
vertical-align: middle;
}
.uiDiv {
width: 80px;
display: inline-block;
}
.sliderDiv {
width: 80px;
height: 5px;
font-size: 10px;
}
.distRect {
fill: #cccccc;
stroke: #333333;
stroke-width: 1px;
}
#stimLeft {
margin: 5px 5px;
}
#stimRight {
margin: 5px 5px;
}
#divLeft {
border: solid 4px #ffffff;
}
#divRight {
border: solid 4px #ffffff;
}
#confirmButton
{
font-size: 14px;
height: 60px;
width: 110px;
}
#divColorScale {
text-align: center;
}
</style>
</head>
<body>
<div style="width: 650px; margin:0 auto;">
<div style="margin-bottom: 20px">
<!--
<div class="uiParentDiv">
<div class="uiDiv">Gradient<br>magnitude</div>
<div class="uiDiv sliderDiv" id="sliderMagnitude"></div>
<div class="uiDiv" id="sliderMagnitudeValue"></div>
</div>
<div class="uiParentDiv">
<div class="uiDiv">Diff</div>
<div class="uiDiv sliderDiv" id="sliderDiff"></div>
<div class="uiDiv" id="sliderDiffValue"></div>
</div>
<div class="uiParentDiv">
<div class="uiDiv">Exponent</div>
<div class="uiDiv sliderDiv" id="sliderExponent"></div>
<div class="uiDiv" id="sliderExponentValue"></div>
</div>
-->
<div class="uiParentDiv">
<div style="font-weight: bold; font-size: 20px; background-color: #eeeeee; border: solid 1px black; width: 100%; height: 40px; padding-top: 20px; padding-bottom: 5px; padding: 5px 5px">
<span id="practiceLabel">Practice</span>
</div>
<p>Terrain is steeper when there is larger CHANGE in elevation between adjacent locations in the map.<!-- That is, elevation changes more quickly as you move across the map. -->
<p>Click on the map that shows STEEPER terrain on average. Press the <u>Confirm</u> button to submit choice and get a new pair of maps.
<p>
</div>
</div>
<div style="height: 230px">
<div id="divLeft" style="width: 210px; height: 210px; float: left">
<canvas id="stimLeft" width="200" height="200"></canvas>
</div>
<div id="divColorScale" style="width: 90; height: 210px; float: right;">
<div style="margin-top: 35px; font-size: 13px">
high<br>elevation<br><canvas id="colorScaleCanvas" width="25" height="100"></canvas><br>low<br>elevation
</div>
</div>
<div id="divRight" style="width: 210px; height: 210px; float: right;">
<canvas id="stimRight" width="200" height="200"></canvas>
</div>
</div>
<div style="text-align: center; margin-top: 0px; margin-right: 50px">
<div>
<span id="alert" style="font-weight: bold; color: #db0000; font-size: 17px; visibility: hidden">Select one of the two maps!</span><br>
<button id="confirmButton">Confirm</button>
<br><img id="loadingImage1" width="80" src="img/loading2.gif" style="visibility: hidden">
</div>
<div style="text-align: center; font-size: 14px">
Practice progress:
<br>
<svg id="svgProgress" width="150" height="12" style="margtin-top: 5px; background-color: #cccccc">
<rect id="rectProgress" height="12" width="15" style="fill: #46a1fc"></rect>
</svg>
<span id="labelProgress">10%</span>
</div>
</div>
</div>
<script type="text/javascript">
// trial config
var COLORMAP = <?php echo "'" . $_SESSION['condition'] . "';\n"; ?>
var MAGNITUDES = [2.0, 4.0, 3];
var COLORMAPS = shuffleArray([ 'rainbowjet', 'viridis', 'coolwarm' ]);
var START_DIFF = 4.0;
var TRIAL_COUNT = 5;
var lastBlock = [];
// engagements
var ENGAGEMENT_CHECKS = 0;
var ENGAGEMENT_DIFF = 14.0;
// stepping
var STEP = .70 * (0.5/1.75);
var BACKWARD = 3.0*STEP;
var FORWARD = STEP;
var selectedImage = null;
var PRACTICE = true;
var FLASH_RATE = 80;
var BORDER_STYLE = '4px solid blue';
var BORDER_STYLE_ERROR = '4px solid red';
var overallAccuracy = 0.0;
var lastBlockAccuracy = 0.0;
if (DIFF) {
DIFF[0] = 0.5;
}
for (var i=0; i<TRIAL_COUNT; i++) {
lastBlock.push(true);
}
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var R = getUrlParameter('r');
if (R == '1')
{
d3.select("#practiceLabel").html("Practice (2 / 2)");
}
function flash() {
if (!selectedImage) {
return;
}
var theDiv = selectedImage == 'left' ? d3.select('#divLeft') : d3.select('#divRight');
(function(_theDiv) {
theDiv.style('border', null)
setTimeout(function() {
theDiv.style('border', BORDER_STYLE_ERROR);
setTimeout(function() {
theDiv.style('border', null);
setTimeout(function() {
theDiv.style('border', BORDER_STYLE_ERROR);
setTimeout(function() {
theDiv.style('border', null);
setTimeout(function() {
theDiv.style('border', BORDER_STYLE_ERROR);
setTimeout(function() {
theDiv.style('border', null);
setTimeout(function() {
theDiv.style('border', BORDER_STYLE);
});
}, FLASH_RATE);
}, FLASH_RATE);
}, FLASH_RATE);
}, FLASH_RATE);
}, FLASH_RATE);
}, FLASH_RATE);
})(theDiv);
}
function unselect()
{
d3.select("#divLeft")
.style("border", null);
d3.select("#divRight")
.style("border", null);
selectedImage = null;
}
d3.select("#divLeft").on("mousedown", function() {
d3.select("#divRight").style("border", null);
d3.select(this).style("border", BORDER_STYLE);
selectedImage = 'left';
d3.event.stopPropagation();
});
d3.select("#divRight").on("mousedown", function() {
d3.select("#divLeft").style("border", null);
d3.select(this).style("border", BORDER_STYLE);
selectedImage = 'right';
d3.event.stopPropagation();
});
var newStimulus = true;
d3.select("#confirmButton")
.on('click', function()
{
if (!selectedImage) {
d3.select("#alert")
.style('visibility', 'visible')
.style("color", '#db0000')
.html("Select one of the two maps!");
}
else
{
var currentTrial = experiment.getCurrentTrial();
var currentBlock = experiment.getCurrentBlock();
//console.log("currentBlock: " + currentBlock + ', currentTrial: ' + currentTrial);
d3.select("#alert").style('visibility', 'hidden');
var result = experiment.answer(selectedImage);
var LAST_BLOCK = ((currentBlock+1) % MAGNITUDES.length == 0);
if ( LAST_BLOCK )
{
if (lastBlock[currentTrial])
{
lastBlock[currentTrial] = result;
}
}
if (newStimulus && result) {
overallAccuracy += 1.0 /
(MAGNITUDES.length * TRIAL_COUNT * (COLORMAPS.length> 0 ? COLORMAPS.length : 1));
}
if (!result && PRACTICE) {
d3.select("#alert")
.style("visibility", 'visible')
.style("color", '#db0000')
.html("Incorrect choice");
newStimulus = false;
flash();
}
else {
newStimulus = true;
d3.select("#alert")
.style('visibility', 'visible')
.style('color', '#009933')
.html("Correct!");
setTimeout(function() {
d3.select("#alert").style('visibility', 'hidden');
}, 1000);
}
if (result && LAST_BLOCK && (currentTrial == TRIAL_COUNT-1))
{
//console.log("** lastBlock: " + lastBlock)
// sum up accuracy of last block and reset
var acc = 0.0;
for (var j=0; j<lastBlock.length; j++) {
if (lastBlock[j]) {
acc += 1/TRIAL_COUNT;
}
lastBlock[j] = true;
}
lastBlockAccuracy += acc / (COLORMAPS.length> 0 ? COLORMAPS.length : 1);
}
}
// see if the practice is over
if (experiment.isFinished()) {
// compute accuracy in the last block
var correct = 0;
for (var i=0; i<lastBlock.length; i++) {
if (lastBlock[i]) {
correct++;
}
}
// check whether the last block has at least
// a miniumum level of accuracy
if (lastBlockAccuracy >= .66 || overallAccuracy >= .66)
{
window.location.replace('debrief.html')
}
else if (!R)
{
window.location.replace('jnd-practice.php?r=1');
}
else
{
// failed 2x in a row
window.location.replace('php/exit_practice.php');
}
}
d3.event.stopPropagation();
})
.on('mousedown', function() {
d3.event.stopPropagation();
})
d3.select("body").on('mousedown', function() { unselect(); });
var experiment = null;
$(document).ready(function() {
experiment = new Experiment(PRACTICE, COLORMAP);
})
</script>
</body>
</html>
|
764da945bc243ef20fdd8f1aa3f48fe562c496a3
|
[
"JavaScript",
"PHP"
] | 21
|
JavaScript
|
liok889/ScalarVisTools
|
b18cfe38a291317d8cf43017e68b5555b0a5d114
|
af3de98a46988bdd1741e31d13108613a0963489
|
refs/heads/master
|
<repo_name>lprabha/Instagram<file_sep>/src/main/java/com/prabha/instagram/LoginApi.java
package com.prabha.instagram;
import com.prabha.instagram.models.UserModel;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface LoginApi {
//for Register
@POST("instagram/users/register")
Call<Void> register(@Body UserModel user);
//for Login
@POST("instagram/users/login")
Call<Void> login(@Body UserModel user);
}
|
e2b0829e2d5c7dd78927183b073d20068f477ba0
|
[
"Java"
] | 1
|
Java
|
lprabha/Instagram
|
b46dcea3b730ce668a1dede54e907a23184d4ea2
|
36bdff9fc991f92a10097917336aae80d4af6866
|
refs/heads/master
|
<repo_name>kchenery/nagios<file_sep>/README.md
Nagios
======
This is just a repository of nagios checks, plugins etc that I have created and use.
<file_sep>/pnp4nagios/templates/check_slingshot_usage.php
<?php
#
# Copyright (c) 2006-2010 <NAME> (http://www.pnp4nagios.org)
# Plugin: check_load
#
$opt[1] = "--vertical-label \"Usage (GB)\" -l0 --title \"Data usage for $hostname / $servicedesc\" ";
#
#
#
$def[1] = rrd::def("var1", $RRDFILE[1], $DS[1], "AVERAGE");
if ($WARN[1] != "") {
$def[1] .= "HRULE:$WARN[1]#FFFF00 ";
}
if ($CRIT[1] != "") {
$def[1] .= "HRULE:$CRIT[1]#FF0000 ";
}
$def[1] .= rrd::area("var1", "#4792FC30") ;
$def[1] .= rrd::line2("var1", "#4792FC", "Usage (GB)");
$def[1] .= rrd::gprint("var1", array("LAST", "AVERAGE", "MAX"), "%6.2lf");
$opt[2] = "--vertical-label \"Usage (GB)\" -l0 ";
$def[2] = rrd::def("var1", $RRDFILE[1], $DS[2], "MAX");
$def[2] .= rrd::area("var1", "#D7000060", "Uploaded", "STACK");
#$def[2] .= rrd::line2("var1", "#d00000", "Uploaded", "STACK");
$def[2] .= rrd::gprint("var1", "LAST", "%6.2lf");
$def[2] .= rrd::def("var2", $RRDFILE[1], $DS[3], "MAX");
$def[2] .= rrd::area("var2", "#0ACD2860", "Downloaded", "STACK");
#$def[2] .= rrd::line2("var2", "#00d000", "Downloaded", "STACK");
$def[2] .= rrd::gprint("var2", "LAST", "%6.2lf");
?>
<file_sep>/checks/check_slingshot_usage.sh
#!/bin/bash
usage_warn="$1"
usage_error="$2"
username="$3"
password="$4"
if [ "${usage_warn}" == "" ]; then
usage_warn=90
fi
if [ "${usage_error}" == "" ]; then
usage_error=100
fi
if [ "${username}" == "" ]; then
username=YourUsername
fi
if [ "${password}" == "" ]; then
password=<PASSWORD>
fi
#Get the usage from slingshot into a variable
usage_url="https://myaccount.slingshot.co.nz/api/?username=${username}&pwd=${password}"
rawusage=$( wget "${usage_url}" -q -O - )
# Convert the file to a pipe delimited list with each item on a single line
usage=$( echo "$rawusage" | sed 's/,/\
/g' | sed 's/=/\|/g' | grep DataUsedGB | sed 's/DataUsedGB|//')
todaysent=$( echo "$rawusage" | sed 's/,/\
/g' | sed 's/=/\|/g' | grep TodayDataSentTotalGB | sed 's/TodayDataSentTotalGB|//')
todayreceived=$( echo "$rawusage" | sed 's/,/\
/g' | sed 's/=/\|/g' | grep TodayDataRcvdTotalGB | sed 's/TodayDataRcvdTotalGB|//')
usage_int=$( printf "%.0f" $usage )
# Work out the return values
if [ ${usage_error} -lt ${usage_int} ]; then
status=2
statustxt=CRITICAL
elif [ "${usage_warn}" -lt "${usage_int}" ]; then
status=1
statustxt=WARNING
else
status=0
statustxt=OK
fi
echo "Data usage $statustxt - used = ${usage}GB | Monthly=${usage}GB;${usage_warn};${usage_error}; DailyUpload=${todaysent}GB; DailyDownload=${todayreceived}GB;"
|
00bc49d73023be732c4ca1ef9ae7427d597dcbfa
|
[
"Markdown",
"PHP",
"Shell"
] | 3
|
Markdown
|
kchenery/nagios
|
0d826d551e5e008f02a772c8fb4eb8bd9d9caf2f
|
f3cf49605ce73297c9b1024b8ea93ff1868a036b
|
refs/heads/master
|
<repo_name>sungmin-park/WTForms.java<file_sep>/src/main/java/kr/redo/wtforms/utils/ObjectUtils.java
package kr.redo.wtforms.utils;
import java.util.Optional;
public class ObjectUtils {
public static <T> T get(Optional<T> optional) {
if (optional.isPresent()) {
return optional.get();
}
return null;
}
}
<file_sep>/src/test/java/kr/redo/wtforms/fields/TextIntegerFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class TextIntegerFieldTest {
@Test
public void testProcessData() throws InstantiationException, IllegalAccessException {
final IntegerFieldTestForm form = Form.bind(IntegerFieldTestForm.class);
final TextIntegerField field = form.getTextIntegerField();
// should return empty if there are no values
final MockHttpServletRequest request = new MockHttpServletRequest();
field.processData(request);
assertEquals(Optional.<Integer>empty(), field.getValue());
// should return empty if value is not integer
request.addParameter("wtf-text-integer-field", "this is not a integer");
field.processData(request);
assertEquals(Optional.<Integer>empty(), field.getValue());
// should return 1
request.setParameter("wtf-text-integer-field", "1");
field.processData(request);
assertEquals(Optional.of(1), field.getValue());
}
public static class IntegerFieldTestForm extends Form {
private TextIntegerField textIntegerField = new TextIntegerField();
public TextIntegerField getTextIntegerField() {
return textIntegerField;
}
}
}<file_sep>/src/main/java/kr/redo/wtforms/validators/AbstractValidator.java
package kr.redo.wtforms.validators;
public abstract class AbstractValidator<T> {
public static class StopValidationException extends Exception {
}
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/CheckBoxField.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.transformers.Transformer;
import kr.redo.wtforms.validators.MultipleValueOptionsValidator;
public class CheckBoxField<T> extends MultipleValueOptionsField<T> {
public CheckBoxField(Transformer<T> transformer) {
super(transformer);
}
@SafeVarargs
public CheckBoxField(Transformer<T> transformer, MultipleValueOptionsValidator<T>... validators) {
super(transformer, validators);
}
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/TextStringField.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.transformers.StringTransformer;
import kr.redo.wtforms.transformers.Transformer;
import kr.redo.wtforms.validators.Validator;
import static kr.redo.wtforms.transformers.StringTransformer.STRING_TRANSFORMER;
public class TextStringField extends TextField<String> {
public TextStringField(Validator<String> validator) {
super(STRING_TRANSFORMER, validator);
}
public TextStringField() {
super(STRING_TRANSFORMER);
}
}
<file_sep>/src/test/java/kr/redo/wtforms/widgets/SelectWidgetTest.java
package kr.redo.wtforms.widgets;
import junit.framework.Assert;
import kr.redo.wtforms.fields.SelectStringField;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
public class SelectWidgetTest {
@Test
public void testRender() throws Exception {
final TestForm form = Form.bind(TestForm.class);
final SelectStringField selectStringField = form.getSelectStringField();
Assert.assertEquals(
"<select id=\"wtf-select-string-field\" name=\"wtf-select-string-field\"></select>", selectStringField.render()
);
selectStringField.setOptions(new String[]{"one", "two"});
Assert.assertEquals(
"<select id=\"wtf-select-string-field\" name=\"wtf-select-string-field\">" +
"<option value=\"one\">one</option>" +
"<option value=\"two\">two</option>" +
"</select>",
selectStringField.render()
);
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("wtf-select-string-field", "two");
selectStringField.processData(request);
Assert.assertEquals(
"<select id=\"wtf-select-string-field\" name=\"wtf-select-string-field\">" +
"<option value=\"one\">one</option>" +
"<option value=\"two\" selected=\"selected\">two</option>" +
"</select>",
selectStringField.render()
);
}
public static class TestForm extends Form {
private SelectStringField selectStringField = new SelectStringField();
public SelectStringField getSelectStringField() {
return selectStringField;
}
}
}<file_sep>/src/main/java/kr/redo/wtforms/widgets/AbstractWidget.java
package kr.redo.wtforms.widgets;
import kr.redo.wtforms.fields.AbstractField;
import org.rendersnake.HtmlAttributes;
import org.rendersnake.HtmlAttributesFactory;
abstract public class AbstractWidget {
HtmlAttributes makeDefaultAttributes(AbstractField field) {
return HtmlAttributesFactory.id(field.getParameterName()).name(field.getParameterName());
}
}
<file_sep>/README.md
WTForms.java
============
WTForms in Java
<file_sep>/src/main/java/kr/redo/wtforms/fields/SelectStringField.java
package kr.redo.wtforms.fields;
import static kr.redo.wtforms.transformers.StringTransformer.STRING_TRANSFORMER;
public class SelectStringField extends SelectField<String> {
public SelectStringField() {
super(STRING_TRANSFORMER);
}
}
<file_sep>/src/test/java/kr/redo/wtforms/fields/DateFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import org.joda.time.DateMidnight;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class DateFieldTest {
@Test
public void testProcessData() throws InstantiationException, IllegalAccessException {
final DateFieldTestForm form = Form.bind(DateFieldTestForm.class);
final DateField dateField = form.getDateField();
final MockHttpServletRequest request = new MockHttpServletRequest();
dateField.processData(request);
assertEquals(Optional.<DateMidnight>empty(), dateField.getValue());
// test default date process
final DateMidnight today = new DateMidnight();
request.addParameter("wtf-date-field", today.toString("yyyy-MM-dd"));
dateField.processData(request);
assertEquals(Optional.of(today), dateField.getValue());
}
public static class DateFieldTestForm extends Form {
private DateField dateField = new DateField();
public DateField getDateField() {
return dateField;
}
}
}<file_sep>/src/test/java/kr/redo/wtforms/fields/AbstractFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class AbstractFieldTest {
@Test
public void testGetTag() throws Exception {
final TestForm form = Form.bind(TestForm.class);
assertEquals(
"<input id=\"wtf-text-string-field\" name=\"wtf-text-string-field\" type=\"text\"/>",
form.getTextStringField().getTag()
);
}
public static class TestForm extends Form {
TextStringField textStringField = new TextStringField();
public TextStringField getTextStringField() {
return textStringField;
}
}
}<file_sep>/src/main/java/kr/redo/wtforms/validators/MultipleValueOptionsValidator.java
package kr.redo.wtforms.validators;
import kr.redo.wtforms.fields.MultipleValueOptionsField;
@FunctionalInterface
public interface MultipleValueOptionsValidator<T> {
public void validate(MultipleValueOptionsField<T> field) throws Exception;
}
<file_sep>/src/test/java/kr/redo/wtforms/validators/RequiredTest.java
package kr.redo.wtforms.validators;
import junit.framework.Assert;
import kr.redo.wtforms.fields.TextStringField;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
import static kr.redo.wtforms.validators.Required.REQUIRED;
public class RequiredTest {
@Test
public void testValidate() throws Exception {
TestForm form = Form.bind(TestForm.class);
Assert.assertFalse("Required should be false on null", form.validate());
final MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter("wtf-field", "");
form = Form.bind(TestForm.class);
form.processData(request);
Assert.assertFalse("Required should be false on empty", form.validate());
request.setParameter("wtf-field", " ");
form = Form.bind(TestForm.class);
form.processData(request);
final boolean validate = form.validate();
Assert.assertEquals(Optional.of(""), form.getField().getValue());
Assert.assertFalse("Required should be false on trimmed", validate);
request.setParameter("wtf-field", "value");
form = Form.bind(TestForm.class);
form.processData(request);
Assert.assertTrue("Required should be true on correct value", form.validate());
}
public static class TestForm extends Form {
private TextStringField field = new TextStringField(REQUIRED);
public TextStringField getField() {
return field;
}
}
}<file_sep>/src/main/java/kr/redo/wtforms/widgets/SelectWidget.java
package kr.redo.wtforms.widgets;
import kr.redo.wtforms.fields.OptionsField;
import kr.redo.wtforms.fields.ParameterOption;
import kr.redo.wtforms.utils.ObjectUtils;
import org.rendersnake.HtmlAttributes;
import org.rendersnake.HtmlCanvas;
import static org.rendersnake.HtmlAttributesFactory.value;
public class SelectWidget extends AbstractWidget implements OptionsWidget {
@Override
public String render(OptionsField<?> field) throws Exception {
String parameterValue = ObjectUtils.get(field.getParameterValue());
HtmlCanvas select = new HtmlCanvas().select(makeDefaultAttributes(field));
for (ParameterOption parameterOption : field.getParameterOptions()) {
final String value = parameterOption.getValue();
final HtmlAttributes attrs = value(value).selected_if(value.equals(parameterValue));
select = select.option(attrs).content(parameterOption.getLabel());
}
return select._select().toHtml();
}
public static final SelectWidget SELECT_WIDGET = new SelectWidget();
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/DateField.java
package kr.redo.wtforms.fields;
import org.joda.time.DateMidnight;
import static kr.redo.wtforms.transformers.DateTransformer.DATE_TRANSFORMER;
public class DateField extends Field<DateMidnight> {
public DateField() {
super(DATE_TRANSFORMER);
}
}
<file_sep>/src/test/java/kr/redo/wtforms/Test.java
package kr.redo.wtforms;
import org.springframework.mock.web.MockHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.function.Consumer;
public class Test {
public static void main(String[] args) {
final MockHttpServletRequest request = new MockHttpServletRequest();
Form form = new Form(request, (f) -> f.id.setData(10));
if (form.validate()) {
System.err.println("failed");
}
}
public static class Form {
public final IntegerField id = new IntegerField();
public Form(HttpServletRequest request, Consumer<Form> initializer) {
if (request.getAttributeNames().hasMoreElements()) {
final String[] values = request.getParameterValues("id");
if (values.length > 0) {
id.setData(Integer.parseInt(values[0]));
}
} else {
initializer.accept(this);
}
}
public boolean validate() {
return false;
}
}
public static class IntegerField {
private int data;
public void setData(int data) {
this.data = data;
}
}
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/TextField.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.transformers.ValueTransformer;
import kr.redo.wtforms.validators.Validator;
import static kr.redo.wtforms.widgets.TextWidget.TEXT_WIDGET;
public class TextField<T> extends Field<T> {
public TextField(ValueTransformer<T> transformer) {
super(transformer, TEXT_WIDGET);
}
public TextField(ValueTransformer<T> transformer, Validator<T> validator) {
super(transformer, TEXT_WIDGET, validator);
}
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/RadioField.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.transformers.Transformer;
import kr.redo.wtforms.widgets.RadioWidget;
public class RadioField<T> extends OptionsField<T> {
public RadioField(Transformer<T> transformer) {
super(transformer, RadioWidget.RADIO_WIDGET);
}
}
<file_sep>/src/main/java/kr/redo/wtforms/validators/OptionsValidator.java
package kr.redo.wtforms.validators;
import kr.redo.wtforms.fields.OptionsField;
@FunctionalInterface
public interface OptionsValidator<T> {
public void validate(OptionsField<T> field) throws Exception;
}<file_sep>/src/main/java/kr/redo/wtforms/fields/MultipleValuesField.java
package kr.redo.wtforms.fields;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
public class MultipleValuesField extends AbstractField {
private String[] values = {};
@Override
public void processData(HttpServletRequest request) {
final String[] parameterValues = request.getParameterValues(getParameterName());
if (parameterValues == null) {
return;
}
values = Arrays.copyOf(parameterValues, parameterValues.length);
}
@Override
public String render() throws Exception {
return null;
}
@Override
public void validate() throws Exception {
throw new NotImplementedException();
}
public String[] getValues() {
return values;
}
}
<file_sep>/src/test/java/kr/redo/wtforms/fields/FieldTest.java
package kr.redo.wtforms.fields;
import junit.framework.Assert;
import kr.redo.wtforms.forms.Form;
import kr.redo.wtforms.transformers.StringTransformer;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
public class FieldTest {
@Test
public void testValue() throws InstantiationException, IllegalAccessException {
final FieldTestForm form = Form.bind(FieldTestForm.class);
final Field valueField = form.getField();
final MockHttpServletRequest request = new MockHttpServletRequest();
// if there is no value return null option
valueField.processData(request);
Assert.assertEquals(Optional.<String>empty(), valueField.getValue());
request.addParameter("wtf-field", "value");
valueField.processData(request);
Assert.assertEquals(Optional.of("value"), valueField.getValue());
}
public static class FieldTestForm extends Form {
private Field<String> field = new Field<>(StringTransformer.STRING_TRANSFORMER);
public Field<String> getField() {
return field;
}
}
}<file_sep>/pom.xml
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>kr.redo</groupId>
<artifactId>wtforms</artifactId>
<version>0.0.1</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.5.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0.1</version>
</dependency>
<dependency>
<groupId>com.intellij</groupId>
<artifactId>annotations</artifactId>
<version>12.0</version>
</dependency>
<dependency>
<groupId>com.esotericsoftware</groupId>
<artifactId>reflectasm</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.rendersnake</groupId>
<artifactId>rendersnake</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.javatuples</groupId>
<artifactId>javatuples</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>
<file_sep>/src/main/java/kr/redo/wtforms/transformers/Transformer.java
package kr.redo.wtforms.transformers;
import kr.redo.wtforms.fields.ParameterOption;
import java.util.Optional;
abstract public class Transformer<T> {
public String toParameterValue(T t) {
return t.toString();
}
public String toParameterLabel(T t) {
return toParameterValue(t);
}
public ParameterOption toParameterOption(T t) {
return new ParameterOption(toParameterValue(t), toParameterValue(t));
}
}
<file_sep>/src/main/java/kr/redo/wtforms/fields/CheckBoxStringField.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.validators.MultipleValueOptionsValidator;
import static kr.redo.wtforms.transformers.StringTransformer.STRING_TRANSFORMER;
public class CheckBoxStringField extends CheckBoxField<String> {
public CheckBoxStringField() {
super(STRING_TRANSFORMER);
}
@SafeVarargs
public CheckBoxStringField(MultipleValueOptionsValidator<String>... validators) {
super(STRING_TRANSFORMER, validators);
}
}
<file_sep>/src/test/java/kr/redo/wtforms/fields/SelectStringFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
import static org.junit.Assert.*;
public class SelectStringFieldTest {
@Test
public void testProcessData() throws InstantiationException, IllegalAccessException {
final SelectFieldTestForm form = Form.bind(SelectFieldTestForm.class);
final SelectStringField selectStringField = form.getSelectStringField();
final MockHttpServletRequest request = new MockHttpServletRequest();
// return empty
selectStringField.processData(request);
assertEquals(Optional.<String>empty(), selectStringField.getValue());
// parameter not in options, will be ignored.
request.addParameter("wtf-select-string-field", "value");
selectStringField.processData(request);
assertEquals(Optional.<String>empty(), selectStringField.getValue());
// parameter in options, will be accepted.
selectStringField.setOptions(new String[]{"value"});
selectStringField.processData(request);
assertEquals(Optional.of("value"), selectStringField.getValue());
}
public static class SelectFieldTestForm extends Form {
private SelectStringField selectStringField = new SelectStringField();
public SelectStringField getSelectStringField() {
return selectStringField;
}
}
}<file_sep>/src/test/java/kr/redo/wtforms/fields/TextStringFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
public class TextStringFieldTest {
@Test
public void testProcessData() throws InstantiationException, IllegalAccessException {
final TextFieldTestForm form = Form.bind(TextFieldTestForm.class);
final TextStringField textStringField = form.getTextStringField();
final MockHttpServletRequest request = new MockHttpServletRequest();
request.addParameter("wtf-text-string-field", "textValue");
textStringField.processData(request);
assertEquals(Optional.of("textValue"), textStringField.getValue());
}
public static class TextFieldTestForm extends Form {
private TextStringField textStringField = new TextStringField();
public TextStringField getTextStringField() {
return textStringField;
}
}
}<file_sep>/src/test/java/kr/redo/wtforms/fields/MultipleValueOptionsFieldTest.java
package kr.redo.wtforms.fields;
import kr.redo.wtforms.forms.Form;
import kr.redo.wtforms.transformers.StringTransformer;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.ArrayList;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class MultipleValueOptionsFieldTest {
@Test
public void testProcessData() throws Exception {
final MultipleValueOptionsFieldTestForm form = Form.bind(MultipleValueOptionsFieldTestForm.class);
final MultipleValueOptionsField<String> field = form.getMultipleValueOptionsField();
final MockHttpServletRequest request = new MockHttpServletRequest();
// should return empty array when no values
field.processData(request);
assertEquals(new ArrayList<String>(), field.getValues());
// should not take value when value is not in options
request.addParameter("wtf-multiple-value-options-field", "one");
field.processData(request);
assertEquals(new ArrayList<String>(), field.getValues());
// take value when it in options
field.setOptions(asList("one"));
field.processData(request);
assertEquals(asList("one"), field.getValues());
// take value if and only if in options
request.addParameter("wtf-multiple-value-options-field", "two");
field.processData(request);
assertEquals(asList("one"), field.getValues());
// take more then one value
request.addParameter("wtf-multiple-value-options-field", "three");
field.setOptions(asList("one", "three"));
field.processData(request);
assertEquals(asList("one", "three"), field.getValues());
}
public static class MultipleValueOptionsFieldTestForm extends Form {
private MultipleValueOptionsField<String> multipleValueOptionsField =
new MultipleValueOptionsField<>(StringTransformer.STRING_TRANSFORMER);
public MultipleValueOptionsField<String> getMultipleValueOptionsField() {
return multipleValueOptionsField;
}
}
}<file_sep>/src/main/java/kr/redo/wtforms/transformers/IntegerTransformer.java
package kr.redo.wtforms.transformers;
import java.util.Optional;
public class IntegerTransformer extends ValueTransformer<Integer> {
@Override
public java.util.Optional<Integer> fromParameterValue(String value) {
try {
return Optional.of(Integer.parseInt(value));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
public static final IntegerTransformer INTEGER_TRANSFORMER = new IntegerTransformer();
}
<file_sep>/src/main/java/kr/redo/wtforms/forms/Form.java
package kr.redo.wtforms.forms;
import com.esotericsoftware.reflectasm.MethodAccess;
import com.google.common.base.CaseFormat;
import kr.redo.wtforms.fields.AbstractField;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Form {
private List<AbstractField> wtfFields = new ArrayList<>();
public static <F extends Form> F bind(Class<F> formClass) throws IllegalAccessException, InstantiationException {
final F form = formClass.newInstance();
final MethodAccess methodAccess = MethodAccess.get(formClass);
final String[] methodNames = methodAccess.getMethodNames();
final Class[][] parameterTypes = methodAccess.getParameterTypes();
final Class[] returnTypes = methodAccess.getReturnTypes();
final List<AbstractField> wtfFields = form.getWtfFields();
for (int i = 0; i < methodNames.length; i++) {
// check is this a simple getter
if (parameterTypes[i].length > 0) {
continue;
}
// check getter from method name
final String methodName = methodNames[i];
if (!methodName.startsWith("get")) {
continue;
}
// check return type is field
if (!AbstractField.class.isAssignableFrom(returnTypes[i])) {
continue;
}
final AbstractField abstractField = ((AbstractField) methodAccess.invoke(form, i));
abstractField.bind(form, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, methodName.substring(3)));
wtfFields.add(abstractField);
}
return form;
}
public String prefix() {
return "wtf-";
}
public void processData(HttpServletRequest request) {
for (AbstractField field : getWtfFields()) {
field.processData(request);
}
}
public boolean validate() throws Exception {
for (AbstractField field : wtfFields) {
field.validate();
}
return !hasErrors();
}
public boolean hasErrors() {
return wtfFields.stream().filter(AbstractField::hasErrors).findAny().isPresent();
}
public Map<String, List<String>> getErrors() {
return wtfFields.stream()
.filter(AbstractField::hasErrors)
.collect(Collectors.toMap(AbstractField::getParameterName, AbstractField::getErrors));
}
public List<AbstractField> getWtfFields() {
return wtfFields;
}
public void clearErrors() {
getWtfFields().forEach(AbstractField::clearErrors);
}
}
|
1e87714a520e2816f047317a97db05eea8f9c98f
|
[
"Markdown",
"Java",
"Maven POM"
] | 29
|
Java
|
sungmin-park/WTForms.java
|
4100e11f7f7b45790baf0e16f71d76e77e8abfc0
|
738644719f4c0c8278fba84638b37e0920f102b0
|
refs/heads/master
|
<file_sep>virtualenv==15.1.0
<file_sep>/*+------------------------------------------------------------------+*/
/*| Random Password Generator |*/
/*+------------------------------------------------------------------+*/
/*| Developed by C.Lawshea. |*/
/*+------------------------------------------------------------------+*/
var alpha_numeric = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%";
function getValue(){
/*Process values from the html radio buttons.*/
var assess = document.getElementsByName("pwlength");
var size = assess.length;
for(i=0; i < size; i++){
if(assess[i].checked == true){
return assess[i].value;
}
}
}
function passwordGen() {
/*Generates a random password.*/
var val = getValue();
var new_password = ''
for (i = 0; i != val; i++){
new_password += alpha_numeric.charAt(Math.floor(Math.random() * alpha_numeric.length));
}
document.getElementById("newpw").innerHTML = new_password;
}
<file_sep><!DOCTYPE html>
{% load staticfiles %}
<!--two-column, fixed-width design with dark color scheme.-->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>C.O.Lawshea</title>
<meta name="keywords" content="Portfolio, Resume, Programming, Self, taught, Programmer, Web, design, Lawshea"/>
<meta name="description" content="Portfolio and curriculum vitae website." />
{% block script %}
<script type="text/javascript" src="#"></script>
{% endblock %}
<script type="text/javascript" src="{% static 'js/quotegen.js' %}"></script>
<script type="text/javascript" src="{% static 'js/pwGen.js' %}"></script>
<script type="text/javascript" src="{% static 'js/macro.js' %}"></script>
<script>
function notice(){
window.alert("Under construction.");
}
</script>
<link href="http://fonts.googleapis.com/css?family=Share+Tech" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="{% static 'css/styling.css' %}" media="all" />
<!--[if IE 6]><link href="styling_ie6.css" rel="stylesheet" type="text/css" /><![endif]-->
</head>
<body>
<div id="page" class="container">
<div id="header">
<div id="my-avatar">
<img src="{% static 'images/me.png'%}" alt="<NAME>" />
<h1><a>My Portfolio</a></h1>
<span>
Design by <a href="https://www.linkedin.com/in/clearthur-oscar-lawshea-01680a105">
C.O.Lawshea</a>
</span>
</div>
<div id="sidebarmenu">
<ul>
<li><a id="home" href="{% url 'home' %}">Home</a></li>
<li><a id="skills" href="{% url 'genskills' %}">Skills</a></li>
<li><a id="education" href="{% url 'education' %}">Education</a></li>
<li><a id="exp" href="{% url 'medicalexp' %}" >Experience</a></li>
<li><a id="samplepro" href="{% url 'programmingexp' %}">Program Samples</a></li>
<li><a id="contact" href="{% url 'contact' %}" >Contact Me</a></li>
</ul>
</div>
</div>
<div id="main">
{% block div %}
<div id="banner">
<img src="" alt="" class="image-full"/>
</div>
{% endblock %}
{% block welcome %}
<div id="welcome">
<div class="title">
<h2>Welcome to my website!</h2>
</div>
<p>
Hello, this is my first personal website. Here, I get to display
my skills and talents acquired over the years. As a matter of fact
you are looking at and using the product of one of my skills now...this very website.
Yes, I designed and programmed this site myself!
I hope you enjoy taking a small peek into my career interests and pursuits.
</p>
</div>
{% endblock %}
<span>
<div class='generator' id='main-generator'>
<div class='generator-wrapper'>
<p alt='First' class='quote'>"Your work is going to fill a large part of your life, and the only way to be truly satisfied is to do what you believe is great work. And the only way to do great work is to love what you do. If you haven't found it yet, keep looking. Don't settle. As with all matters of the heart, you'll know when you find it." -<NAME></p>
<p alt='Second' class='quote'>"Formal education will make you a living; self-education will make you a fortune." -<NAME>
</p>
<p alt='Third' class='quote'>"Education is what remains after one has forgotten what one has learned in school." -<NAME></p>
<p alt='Fourth' class='quote'>"Ninety-nine percent of the failures come from people who have the habit of making excuses." -<NAME></p>
<p alt='Fifth' class='quote'>"Every living being is an engine geared to the wheel-work of the universe. Though seemingly affected only by its immediate surrounding, the sphere of external influence extends to infinite distance." -<NAME></p>
<p alt='Sixth' class='quote'>"No individual has any right to come into the world and go out of it without leaving behind him distinct and legitimate reasons for having passed through it." -<NAME></p>
<p alt='Seventh' class='quote'>"It's fine to celebrate success but it is more important to heed the lessons of failure." -<NAME></p>
<p alt='Eighth' class='quote'>"If your culture doesn't like geeks, you are in real trouble." -<NAME></p>
<p alt='Ninth' class='quote'>"Don't worry that you can't seem to come up with sure billion dollar winners at first. Just do projects for yourself for fun. You'll get better and better." -<NAME></p>
<p alt='Tenth' class='quote'>"It's the great tragedy - people employed in ways that don't fully tap everything they do best in life." -<NAME></p>
<p alt='Eleventh' class='quote'>"Success is no accident. It is hard work, perseverance, learning, studying, sacrifice and most of all, love of what you are doing or learning to do." -Pele</p>
<p alt='Twelfth' class='quote'>"There are no secrets to success. It is the result of preparation, hard work, and learning from failure." -<NAME></p>
<p alt='Thirteenth' class='quote'>"The two most powerful warriors are patience and time." -<NAME></p>
<p alt='Fourteenth' class='quote'>"If your actions inspire others to dream more, learn more, do more and become more, you are a leader." -<NAME></p>
<p alt='Fifteenth' class='quote'>"Leadership is practiced not so much in words as in attitude and in actions." -<NAME></p>
<p alt='Sixteenth' class='quote'>"The quality of a leader is reflected in the standards they set for themselves." -<NAME></p>
<p alt='Seventeenth' class='quote'>"Self-education is, I firmly believe, the only kind of education there is." -<NAME>,</p>
</div><!--End Quote Generator-->
</span>
</div>
{% block featured %}
<div id="main-content">
{% block content %}
<ul class="lst">
<li class="first">
<p class="numbering"><b>.I</b></p>
<h3>Medical Administration</h3>
<h4>Clinical Support(Radiology) / Medical Records:</h4>
<p id="content1">
<ul class="list">
<li>Professional phone etiquette</li>
<li>Excellent communication skills</li>
<li>Customer Service</li>
<li>Accurate and detailed</li>
<li>Trained in HIPPA compliance</li>
<li>Medical Terminology</li>
<li>CPR certification</li>
<li>Knowledge of electronic medical record systems</li>
<li>Time Management</li>
<li>Professionalism</li>
<li>Scheduling</li>
<li>Computer and Electronics skills </li>
<li>Radiology operations</li>
<li>(Epic, e-Clinical Works, Excel, Word, Outlook, PowerPoint)</li>
<li>Problem Solving</li>
<li>Accurate Information Recall</li>
</ul>
</p>
</li>
<li>
<p class="numbering"><b>.II</b></p>
<h3>Military(United States Navy)</h3>
<h4>Naval Security:</h4>
<p id="content2">
<ul id="" class="list">
<li>Operational Risk Management</li>
<li>Combat First Aid</li>
<li>Sterilization</li>
<li>Small Arms Safety</li>
<li>Pistol Fundamentals</li>
<li>Pistol Marksmanship</li>
<li>Pistol Combat Shooting</li>
<li>Rifle Safety</li>
<li>Rifle Fundamentals</li>
<li>Rifle Marksmanship</li>
<li>Rifle Combat Shooting</li>
<li>Vehicle Bailout</li>
<li>Basic Military Comms</li>
<li>Counter-IED Recognition</li>
<li>Combat Psychology</li>
<li>Rules of Engagement</li>
<li>Nautical Navigation</li>
<li>Land Navigation</li>
</ul>
</p>
</li>
<li>
<p class="numbering"><b>.III</b></p>
<h3>Surgical Procedure</h3>
<h4><a href="">Surgical Technology(click here for education):</a></h4>
<p id="content3">
<ul class="list">
<li>Aseptic Techniques</li>
<li>Wound Dressing</li>
<li>Sterilization</li>
<li>Cautery Safety</li>
<li>Supplies Inventory</li>
<li>Specimen Labeling/Disposal</li>
<li>Surgical Procedural Support</li>
<li>Maintain and re-stock supplies</li>
<li>Prepare patients </li>
<li>Medical instrumentation</li>
<li>Medical Terminology</li>
<li>Total knee arthroplasty</li>
<li>ORIF of Mandible</li>
<li>Tibia plateau ORIF</li>
<li>Hernia Repair</li>
<li>Cholecystectomy</li>
<li>Percutaneous Endoscopic Gastrostomy</li>
<li>Appendectomy</li>
<li>Cesarean Section</li>
<li>Ectopic Pregnancy</li>
<li>Tonsillectomy/Adenoidectomy</li>
<li>Partial Mastectomy</li>
<li>Excision of Axillary Mass</li>
<li> Irrigation & Drainage</li>
</ul>
</p>
</li>
<li>
<p class="numbering"><b>.IV</b></p>
<h3>Software Engineering</h3>
<h4>Programming / Web Development:</h4>
<p id="content4">
<ul class="list">
<li>Visual Basic 6</li>
<li>Python</li>
<li>SQL</li>
<li>HTML 5</li>
<li>CSS 3</li>
<li>JavaScript</li>
<li>Windows PowerShell</li>
<li>GIT</li>
<li>Data Structures</li>
<li>Object Oriented Programming</li>
<li>Anaconda</li>
<li><a href="https://docs.djangoproject.com/en/1.11/">Django</a></li>
<li>Debugging</li>
<li>Abstraction</li>
<li>Decomposition</li>
<li>Modeling</li>
<li>Basic Database Design</li>
<li>Event-Driven Programming</li>
<li>Pip</li>
<li>Full-Stack Web Development</li>
<li>Command Line Interface</li>
</ul>
</p>
</li>
</ul>
{% endblock %}
</div><!--End Featured div-->
{% endblock %}
<div id="poweredby">
<span>
Powered by<a href="https://docs.djangoproject.com/en/1.11/" rel="">DJANGO</a>.
</span>
<span>
<a id="sitemap"><img src="{% static 'icons/sitemap.png'%}" width="30" height="30" alt="Site map image" onclick="notice();"/></a>
</span>
</div>
</div>
</div>
</body>
</html>
<file_sep>from django.shortcuts import render_to_response
from django.template.context import RequestContext
# Create your views here.
def index(request):
return render_to_response('index.html', context_instance=RequestContext(request))<file_sep>var AppID = "2ccd31780465f06ed2dce6a1c4c5f3d0"; /*Put Api Key in different file before launch!*/
var temp;
var loc;
var humidity;
var wind;
var direction;
var icon;
function updateByZip(zip){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"zip=" + zip +
"&AppID=" + AppID;
sendRequest(url);
}
function update_by_geo(lat, lon){
var url = "http://api.openweathermap.org/data/2.5/weather?" +
"lat=" + lat +
"&lon=" + lon +
"&AppID=" + AppID;
sendRequest(url);
}
function degrees_to_direction(degrees){
var range = 360/16;
var low = 360 - range/2;
var high = (low + range) % 360;
var angles =["N", "NNE", "ENE", "E", "ESE", "SE",
"SSE", "S", "SSW", "SW", "WSW", "W","WNW", "NW",
"NNW"
];
for(i in angles){
if (degrees >= low && degrees < high)
return angles[i];
low = (low + range) % 360;
high = (high + range)% 360;
}
return "N";
}
function kel_to_cel(kel){
return Math.round(kel - 273.15);
}
function kel_to_fah(kel){
return Math.round(kel*(9/5) - 459.67);
}
function sendRequest(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var data = JSON.parse(xmlhttp.responseText);
var weather = {};
icon = ("<img src='http://openweathermap.org/img/w/"+ data.weather[0].icon + ".png'>");
//weather.iconcode = data.weather[0].icon;//
weather.humidity = data.main.humidity;
weather.wind = data.wind.speed;
weather.direction = degrees_to_direction(data.wind.deg);
weather.loc = data.name;
weather.temp = kel_to_fah(data.main.temp);
update(weather);
console.log(weather.iconcode);
console.log(icon);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function update(weather){
temp.innerHTML = weather.temp;
loc.innerHTML = weather.loc;
humidity.innerHTML = weather.humidity;
wind.innerHTML = weather.wind;
direction.innerHTML = weather.direction;
icon.src = "img/w/" + icon + ".png";//
console.log(icon.src);
}
function show_position(position){
update_by_geo(position.coords.latitude, positon.coords.longitude);
}
window.onload = function(){
temp = document.getElementById("temperature");
loc = document.getElementById("location");
humidity = document.getElementById("humidity");
wind = document.getElementById("wind");
direction = document.getElementById("direction");
icon = document.getElementById("icon");
if(!navigator.geolocation){
navigator.geolocation.getCurrentPosition(show_position);
}else{
var zip = window.prompt("If you would like to get the current weather in your location, please enter your zip code>>");
updateByZip(zip);
}
}<file_sep>var bodyweight;
var fats;
var proteins;
var cal;
var carbs;
var bmr;
var choicepool;
var genderchoice;
var heightcm;
var heightft;
var userage;
var bodyweightkg;
function find_selection(field){
/*Process values from the html physical activity radio buttons.*/
choicepool = document.getElementsByName(field);
var size = choicepool.length;
for(i=0; i < size; i++){
if(choicepool[i].checked == true){
return choicepool[i].value;
}
}
}
function gender_selection(field){
/*Process values from the html gender choice radio buttons.*/
genderchoice = document.getElementsByName(field);
var size = genderchoice.length;
for(i=0; i < size; i++){
if(genderchoice[i].checked == true){
return genderchoice[i].value;
}
}
}
function get_weight(){
bodyweight = document.querySelector('#weightlbs').value;
bodyweightkg = ((1 / 2.2) * (bodyweight));
return bodyweightkg;
}
function get_height(){
heightft = document.querySelector('#height').value;
heightcm = ((1 / 0.0323) *(heightft));
return heightcm;
}
function get_age(){
userage = document.querySelector('#age').value;
return userage;
}
function BMR(){
/*Mifflin formula:*/
bmr = ((10 * get_weight() ) + (6.25 * get_height()) - (5 * get_age()) + (gender_selection("gender")));
return bmr;
}
function macro_cal(){
fats = (get_weight() * 0.6);
proteins = (get_weight() * 0.8);
cal = (BMR() * find_selection("activity"));
carbo = (( cal - proteins) / (4));
document.getElementById("fats").innerHTML = fats;
document.getElementById("protein").innerHTML = proteins;
document.getElementById("calories").innerHTML = cal;
document.getElementById("carbs").innerHTML = carbo;
}<file_sep>//Education content(Biology)//
var h3bio146 = "Biology Major: California Baptist University (1 year 10 months):";
var h4bio146 = "Biology 146:";
var bio146 = "Topics covered include cell structure and function, genetics, reproduction and development of animal systems.";
var roman5 = ".V";
var h3bio148 = "";
var h4bio148 = "Biology 148:";
var bio148 = "Topics includes organismal biology of animals and plants, their behavior, ecology, evolution and adaptations.";
var roman6 = ".VI";
var h3genbio1 = "";
var h4genbio1 = "General Biology 1:";
var genbio1 = "Fundamental concepts of biochemistry, cell biology, genetics. Concepts include important organic molecules, cell structure and function, metabolism and enzyme activity, cellular respiration and photosynthesis, DNA structure, meiosis and mitosis, Mendelian genetics.";
var roman7 = ".VII"
var h3bio114 = "";
var h4bio114 = "Biology 114:";
var bio114 = "A study of the physiology, morphology, reproduction, and a survey of the plant kingdom, including fungi, algae, liverworts, mosses, ferns, gymnosperms and angiosperms. Emphasis will be placed on the development, reproduction and the relevance of plants to humans.";
var roman8 = ".VIII";
var h3genchem115 ="";
var h4genchem115 = "General Chemistry 115:";
var genchem115 = "Structure and behavior of inorganic matter and a mathematical treatment of chemical systems.";
var h3genchem125 = "";
var h4genchem125 = "General Chemistry";
var genchem125 = "A continuation of Chemistry 115, including qualitative inorganic analysis."
var h3genpsych ="";
var h4genpsych = "General Psychology:";
var genpsych = "introductory survey of the processes of adjustment, growth, learning, remembering, perception, sensation, socialization, and emotions.";
var h3algebra = "";
var h4algebra = "College Algebra 1 & 2:";
var algebra = "Instruction in the following areas; roots and radicals, quadratic equations and inequalities, graphing relations and functions, systems of equations and inequalities, and matrices and determinants, evaluate logarithmic and exponential expressions; calculate the probability of events with given sets of parameters, Evaluate and apply arithmetic and geometric sequences.";
function changecontent(){
document.getElementById("contenttitle1").innerHTML = h3bio146;
document.getElementById("subtitle1").innerHTML = h4bio146;
document.getElementById("list1").innerHTML = bio146;
document.getElementById("roman5").innerHTML = roman5;
document.getElementById("contenttitle2").innerHTML = h3bio148;
document.getElementById("subtitle2").innerHTML = h4bio148;
document.getElementById("list2").innerHTML = bio148;
document.getElementById("roman6").innerHTML = roman6;
document.getElementById("contenttitle3").innerHTML = h3genbio1;
document.getElementById("subtitle3").innerHTML = h4genbio1;
document.getElementById("list3").innerHTML = genbio1;
document.getElementById("roman7").innerHTML = roman7;
document.getElementById("contenttitle4").innerHTML = h3bio114;
document.getElementById("subtitle4").innerHTML = h4bio114;
document.getElementById("list4").innerHTML = bio114;
document.getElementById("roman8").innerHTML = roman8;
document.getElementById("contenttitle5").innerHTML = h3genchem115;
document.getElementById("subtitle5").innerHTML = h4genchem115;
document.getElementById("list5").innerHTML = genchem115;
document.getElementById("contenttitle6").innerHTML = h3genchem125;
document.getElementById("subtitle6").innerHTML = h4genchem125;
document.getElementById("list6").innerHTML = genchem125;
document.getElementById("contenttitle7").innerHTML = h3genpsych;
document.getElementById("subtitle7").innerHTML = h4genpsych;
document.getElementById("list7").innerHTML = genpsych;
document.getElementById("contenttitle8").innerHTML = h3algebra;
document.getElementById("subtitle8").innerHTML = h4algebra;
document.getElementById("list8").innerHTML = algebra;
return false
}
|
071024307e25349e00378d54d97ad49e7ced3c07
|
[
"JavaScript",
"Python",
"Text",
"HTML"
] | 7
|
Text
|
law35/final-design
|
bc71759c85832fb409cb3e758f801920326fac8d
|
9f1331402f4e50f5c0ce6faef50b4616fd901e97
|
refs/heads/master
|
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "MessageBuilder.h"
#include "MessageConstants.h"
using namespace std;
enum Command
{
NULL1 = 0,
LOGO = 0x11,
VAT = 0x12,
DEPARTMENT = 0x13,
PLU = 0x14,
CREDIT = 0x15,
MAIN_CAT = 0x16,
SUB_CAT = 0x17,
CASHIER = 0x18,
PRG_OPTIONS = 0x19,
FCURRENCY = 0x1A,
TSM_IP_PORT = 0x1B,
GRAPHIC_LOGO = 0x1C,
NETWORK = 0x1D,
START_RCPT = 0x21,
SALE_ITEM = 0x22,
ADJUSTMENT = 0x23,
CORRECTION = 0x24,
VOID_ITEM = 0x25,
SUBTOTAL = 0x26,
PAYMENT = 0x27,
CLOSE_RCPT = 0x28,
VOID_RCPT = 0x29,
CUSTOMER_NOTE = 0x2A,
RCPT_BARCODE = 0x2B,
VOID_PAYMENT = 0x2C,
SALE_DEPT = 0x2D,
SALE_DOC = 0x2E,
X_DAILY = 0x31,
X_PLU = 0x32,
SYSTEM_INFO_REP = 0x33,
RECEIPT_TOTAL = 0x34,
Z_DAILY = 0x41,
Z_FM_ZZ = 0x42,
Z_FM_ZZ_DETAIL = 0x43,
Z_FM_DATE = 0x44,
Z_FM_DATE_DETAIL = 0x45,
Z_ENDDAY = 0x46, //Endday bank
CMD_Z_OLD_DAILY = 0x47,
EJ_DETAIL = 0x51,
EJ_RCPTCOPY_ZR = 0x52,//both single and periodic
EJ_RCPTCOPY_DATE = 0x53,//both single and periodic. either daily
SRV_CLEAR_DAILY = 0x61,
SRV_SET_DATETIME = 0x62,
SRV_FACTORY_SETTINGS = 0x63,
SRV_STOP_FM = 0x64,
SRV_EXTERNAL_DEV_SETTINGS = 0x65,
SRV_UPDATE_FIRMWARE = 0x66,
SRV_PRINT_LOGS = 0x67,
SRV_CREATE_DB = 0x68,
SRV_EXIT_SERVICE = 0x6F,
INFO_LAST_Z = 0x71,
INFO_LAST_RCPT = 0x72,
INFO_DRAWER = 0x73,
INFO_RECEIPT = 0x74,
STATUS = 0x81,
LAST_RESPONSE = 0x82,
BREAK = 0x83,
START_FM = 0x84,
FISCALIZE = 0x85,
INIT_EJ = 0x86,
CASHIER_LOGIN = 0x87,
CASHIER_LOGOUT = 0x88,
CASH_IN = 0x89,
CASH_OUT = 0x8A,
START_NF_RCPT = 0x8B,
ADD_NF_LINE = 0x8C,
END_NF_RCPT = 0x8D,
EJ_LIMIT = 0x8E,
START_SERVICE = 0x8F,
ENTER_SERVICE = 0x90,
FILE_TRANSFER = 0x91,
OPEN_DRAWER = 0x92,
EFT_PAYMENT = 0xA0,
EFT_CARD_INFO = 0xA7,
EFT_CARD_INFO_LIST = 0xA8,
EFT_VOID = 0xA9,
EFT_REFUND = 0xAA,
EFT_BANK_LIST = 0xAB,
EFT_END_DAY = 0xA6,
EFT_SLIPCOPY = 0xAC
};
class FPURequest
{
public:
static int REQUEST_MSG_ID;
static int MAX_PRCSS_SEC_NUM;
static string FiscalId;
static int SequenceNum;
Command command;
vector<unsigned char> data;
vector<unsigned char> Request;
int sequence;
FPURequest(Command command, vector<unsigned char> data);
~FPURequest(void);
vector<unsigned char> CreateRequest(string terminalNo, int messageType);
static wstring GetCommand(Command command);
};
<file_sep># restgmp3
RESTful web server for GMP3 library
<file_sep>#pragma once
#include <string>
#include <vector>
#include "MessageBuilder.h"
using namespace std;
enum SFResponseLabel
{
ERROR_CODE,
STATUS1,
PARAM,
NULL2
};
class SFResponseObject
{
public:
int errorCode;
int statusCode;
vector<string> paramList;
SFResponseObject();
};
class SFResponse
{
private:
static char SPEC_CHAR;
SFResponseObject respObj;
public:
SFResponse(void);
~SFResponse(void);
void AddParam(string value);
void AddErrorCode(int value );
void AddStatus(int value );
string GetString();
void AddNull(int count);
static SFResponseObject GetObjectByString(string str);
};
<file_sep>#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include "HSMessageContext.h"
#include "GMPMessage.h"
#include "MessageConstants.h"
#include "MessageBuilder.h"
using namespace std;
namespace ExDevice
{
class HSState
{
static map<string, int> desktopVerTable;
static map<double, int> vxVerTable;
public :
virtual GMPMessage* GetMessage() = 0;
virtual int Process(vector<byte> &buffer) = 0;
virtual HSState* NextState() = 0;
virtual const char *StateName() = 0;
static const int MAX_BUFFER_LEN = 2048;
static DeviceInfo DevInfo;
static int VERSION;
public :
HSState(void);
virtual ~HSState(void);
void AddExDevInfo(GMPMessage &msg);
void AddEcrDevInfo(GMPMessage &msg);
static void SetVersion(DeviceInfo devInfo);
};
class Start : public HSState
{
public:
Start(DeviceInfo devInfo);
virtual int Process(vector<byte> &buffer);
virtual HSState* NextState();
virtual GMPMessage* GetMessage();
virtual const char *StateName();
};
class KeyExchange : public HSState
{
public :
static const string PRM_GMP3_PRF_LABEL;
static const string COMPUTE_KEYS_LABEL;
static const string CER_KAMU_SM_PRODUCER;
public :
virtual int Process(vector<byte> &buffer);
virtual HSState* NextState();
virtual GMPMessage* GetMessage();
virtual const char *StateName();
};
class Close : public HSState
{
public :
virtual int Process(vector<byte>& buffer);
virtual HSState* NextState();
virtual GMPMessage* GetMessage();
virtual const char *StateName();
};
}
<file_sep>#pragma once
#ifdef WIN32
#include <Windows.h>
#else
typedef unsigned char byte;
#endif
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include "DevInfo.h"
#include "openssl/dh.h"
#include "openssl/x509v3.h"
#include <openssl/hmac.h>
using namespace std;
namespace ExDevice
{
enum PaddingMode
{
None = 1,
PKCS7 = 2,
Zeros = 3,
ANSIX923 = 4,
ISO10126 = 5,
};
enum CipherMode
{
CBC = 1,
ECB = 2,
OFB = 3,
CFB = 4,
CTS = 5,
};
class ICryptoTransform
{
public :
EVP_CIPHER_CTX *ctx;
const EVP_CIPHER * chiper;
vector<byte> IV;
vector<byte> Key;
CipherMode Mode;
PaddingMode Padding;
bool fEncrypt;
ICryptoTransform();
virtual ~ICryptoTransform();
virtual vector<byte> TransformFinalBlock(vector<byte>inputBuffer, int inputOffset, int inputCount);
};
class SymmetricAlgorithm
{
public :
virtual ICryptoTransform *CreateEncryptor() = 0;
virtual ICryptoTransform *CreateDecryptor() = 0;
};
class Rijndael : public SymmetricAlgorithm
{
public:
virtual ICryptoTransform *CreateEncryptor();
virtual ICryptoTransform *CreateDecryptor();
};
class HashAlgorithm
{
//EVP_MD * evp_md;
protected:
HMAC_CTX ctx;
EVP_MD_CTX *evpMdCtx;
EVP_MD *evpMd;
public:
virtual ~HashAlgorithm();
vector<byte> ComputeHash(vector<byte> buffer);
virtual vector<byte> ComputeHash(vector<byte> buffer, int offset, int count);
virtual void Initialize() = 0;
virtual vector<byte> TransformFinalBlock(vector<byte> inputBuffer, int inputOffset, int inputCount);
vector<byte> Hash;
unsigned int HashSize;
};
class KeyedHashAlgorithm : public HashAlgorithm
{
public :
vector<byte> Key;
};
class HMAC : public KeyedHashAlgorithm
{
public:
virtual vector<byte> TransformFinalBlock(vector<byte> inputBuffer, int inputOffset, int inputCount);
};
class HMACSHA256 : public HMAC
{
bool fInit;
public :
HMACSHA256(vector<byte> &key);
virtual ~HMACSHA256();
virtual void Initialize();
virtual vector<byte> ComputeHash(vector<byte> buffer, int offset, int count);
};
class SHA256 : public HashAlgorithm
{
public:
SHA256();
virtual ~SHA256();
void Initialize();
};
class DiffieHellman
{
public:
DiffieHellman();
DiffieHellman(int bits);
~DiffieHellman();
bool GeneratePubKey();
static vector<byte> Bignum2Vector(const BIGNUM *big_num);
int bits;
BIGNUM *GivenPubKey;
vector<byte> secretKey;
int secretKeyLength;
DH *dh1;
};
class X509Certificate2
{
X509 *x;
public:
X509Certificate2(const vector<byte> &data);
EVP_PKEY* PublicKey();
};
class RSA
{
::RSA *r;
public:
RSA(const vector<byte> &publicKey);
RSA(EVP_PKEY *pKey);
virtual ~RSA();
bool Verify(vector<byte> signedBytes, vector<byte> sign);
};
class HSMessageContext
{
public:
static const int MASTER_SECRET_LEN = 32;
static const int IV_LEN = 16;
static const int HMAC_LEN = 32;
static const int HMAC_CHECK_VALUE_LEN = 32;
static const int KEY_LEN_AES256 = 32;
DeviceInfo ExDevInfo;
DeviceInfo EcrDevInfo;
DiffieHellman ExDH;
DiffieHellman EcrDH;
vector<byte> ExRandom;
vector<byte> EcrRandom;
vector<byte> keyEnc;
vector<byte> keyIV;
vector<byte> keyHMAC;
X509Certificate2 *EcrCertificate;
int ErrorCode;
int PosIndex;
private:
KeyedHashAlgorithm *keyHMACAlg;
SymmetricAlgorithm *symAlg;
ICryptoTransform *encryptor;
ICryptoTransform *decryptor;
public :
HSMessageContext ();
virtual ~HSMessageContext(void);
vector<byte> TransformData(vector<byte> buffer, int offset, int len);
vector<byte> ComputeRecordMAC(vector<byte> buffer, int len);
vector<byte> EncryptRecord(vector<byte> fragment, int fragmentLen, vector<byte> mac);
void DecryptRecord(vector<byte> fragment, vector<byte>& dcrFragment, vector<byte>& dcrMAC);
void CreateCryptoTransformer();
static vector<byte> PRFForTLS1_2(vector<byte> secret, string label, vector<byte> data, int length);
private:
static vector<byte> Expand(int HashSize, HMAC* hmac, vector<byte> seed, int length);
};
bool CreateSecretKeys(DiffieHellman &DH);
}
<file_sep>#pragma once
#include <string>
using namespace std;
#if defined(HUGINAPI_DLL_BUILD) // inside DLL
# define HUGINAPI __declspec(dllexport)
#elif defined __MINGW32__
# define HUGINAPI
#elif defined(WIN32) // outside DLL
# define HUGINAPI __declspec(dllimport)
#else
# define HUGINAPI
#endif // _WINDLL
class HUGINAPI DevInfo
{
public:
DevInfo(void) { }
~DevInfo(void) { }
string IP;
int Port;
string TerminalNo;
string SerialNum;
string Model;
string Brand;
string Version;
};
typedef DevInfo DeviceInfo;
<file_sep>#pragma once
#include "Connection.h"
#ifdef WIN32
#pragma comment (lib, "ws2_32.lib")
class TcpConnection : public Connection
{
private:
string ip;
int port;
SOCKET _socket;
public:
TcpConnection(string ip, int port);
~TcpConnection();
bool Open();
void Close();
void RecvProc();
bool Write(unsigned char* buffer, unsigned long writeBytes, unsigned long& writtenBytes);
};
#else
class TcpConnection : public Connection
{
private:
string ip;
int port;
int _socket;
pthread_t threadRecv;
public:
TcpConnection(string ip, int port);
~TcpConnection();
bool Open();
void Close();
void RecvProc();
bool Write(unsigned char* buffer, unsigned long writeBytes, unsigned long& writtenBytes);
};
#endif
<file_sep>cmake_minimum_required(VERSION 2.6)
project (ws_vfxbridger CXX)
set(WS_VFXBRIDGER_HEADERS ws_vfxbridger.hpp)
set(PROJECT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
set(WS_VFXBRIDGER_CODEGEN_DIR "${PROJECT_BINARY_DIR}/codegen")
PREPEND(WS_VFXBRIDGER_HEADERS_PATHS ${PROJECT_SOURCE_DIR} ${WS_VFXBRIDGER_HEADERS})
CODEGEN_FILES(WS_VFXBRIDGER_CODEGEN_SOURCES ${WS_VFXBRIDGER_CODEGEN_DIR} ${WS_VFXBRIDGER_HEADERS})
add_custom_command(OUTPUT ${WS_VFXBRIDGER_CODEGEN_SOURCES}
COMMAND ${NGREST_BIN_PATH}ngrestcg -i "${PROJECT_SOURCE_DIR}" -o ${WS_VFXBRIDGER_CODEGEN_DIR} -t service ${WS_VFXBRIDGER_HEADERS}
DEPENDS ${WS_VFXBRIDGER_HEADERS_PATHS}
)
file(GLOB WS_VFXBRIDGER_SOURCES ${PROJECT_SOURCE_DIR}/*.cpp ${PROJECT_SOURCE_DIR}/*.hpp)
list(APPEND WS_VFXBRIDGER_SOURCES ${WS_VFXBRIDGER_CODEGEN_SOURCES})
include_directories(${PROJECT_SOURCE_DIR})
add_library(ws_vfxbridger MODULE ${WS_VFXBRIDGER_SOURCES})
set_target_properties(ws_vfxbridger PROPERTIES PREFIX "")
set_target_properties(ws_vfxbridger PROPERTIES
LIBRARY_OUTPUT_DIRECTORY "${PROJECT_SERVICES_DIR}"
)
# link_directories("${FP300SERVICE_DIR}/FP300Java/lib")
target_link_libraries(ws_vfxbridger ngrestutils ngrestcommon ngrestjson ngrestengine ${FP300SERVICE_DIR}/FP300Java/lib/libprinterlib.so -pthread ${FP300SERVICE_DIR}/etc/raspbian/libssl.so)
<file_sep>#pragma once
#include "Connection.h"
#include "Logger.h"
#ifdef WIN32
class SerialConnection : public Connection
{
private:
string portName;
int baudRate;
HANDLE hFile;
OVERLAPPED osRead;
OVERLAPPED osWrite;
HANDLE threadRecv;
public:
// Logger serialLogger;
SerialConnection(string portName, int baudRate);
~SerialConnection();
void SerialConnection::Set( string portName, int baudRate );
bool Open();
void Close();
void RecvProc();
bool Write(BYTE* buffer, DWORD writeBytes, DWORD& writtenBytes);
};
#else
class SerialConnection : public Connection
{
private:
string portName;
int baudRate;
int tty_fd;
pthread_t threadRecv;
public:
// Logger serialLogger;
SerialConnection( string portName, int baudRate );
~SerialConnection();
void Set( string portName, int baudRate );
bool Open();
void Close();
void RecvProc();
bool Write(unsigned char* buffer, unsigned long writeBytes, unsigned long& writtenBytes);
};
#endif
<file_sep>#pragma once
#ifdef WIN32
#include <windows.h>
#if defined(HUGINAPI_DLL_BUILD) // inside DLL
# define HUGINAPI __declspec(dllexport)
#elif defined __MINGW32__
# define HUGINAPI
#else // outside DLL
# define HUGINAPI __declspec(dllimport)
#endif // _WINDLL
#else
#define HUGINAPI
#include <unistd.h>
typedef unsigned char byte;
#endif
using namespace std;
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
namespace Hugin
{
namespace GMPCommon
{
class Logger
{
public:
enum LogLevel
{
FATAL = 1,
_ERROR = 2,
WARN = 3,
INFO = 4,
Debug = 5,
HIDE_BUG = 6
};
private:
static bool fInit;
static string logFileName;
static bool isLoggingStart;
static LogLevel Level;
static string LogFileDirectory;
static int logDay;
static bool Initialize();
static void CreateLogFile();
public:
static void AddLog(string log);
static void DebugLine(string strClass, string strFunc, int line);
static void Enter(string strClass, string strFunc);
static void Exit(string strClass, string strFunc);
static void Log(LogLevel level, string log);
static void Log(LogLevel level, const vector<byte> &buffer);
static void Log(LogLevel level, const vector<byte> &buffer, string note);
static void Log(LogLevel level, const char *fmt, ...);
static void Log(exception *ex);
static void SetLogLevel(LogLevel level);
static void SetDebugFolder( string folderPath );
};
}
}
<file_sep>#pragma once
#include <string>
#include <map>
using namespace std;
class ProgramConfig
{
public:
static int LOGO_LINE_LENGTH;
static int PRODUCT_NAME_LENGTH;
static int PLU_NAME_FIXLENGTH;
static int CREDIT_NAME_LENGTH;
static int FCURRENCY_NAME_LENGTH;
static int DEP_NAME_LENGTH;
static int LENGTH_OF_LOGO_LINES;
static int MAX_CREDIT_COUNT;
static int MAX_FCURRENCY_COUNT;
static int MAX_VAT_RATE_COUNT;
static int MAX_DEPARTMENT_COUNT;
static int MAX_SUB_CAT_COUNT;
static int MAX_MAIN_CATEGORY_COUNT;
static int MAX_CASHIER_COUNT;
static int AMOUNT_LENGTH;
static int STX;
static int ETX;
static int FPU_CMD_TIMEOUT;
static int FPU_RPRT_TIMEOUT;
static int FPU_SRV_TIMEOUT;
static int FPU_START_FM_TIMEOUT;
static int FPU_EFT_PAYMENT_TIMEOUT;
};
class GMPConstants
{
public:
static int LEN_SERIAL;
static int LEN_EX_SERIAL;
static int LEN_SEQUENCE;
static int LEN_DATE;
static int LEN_TIME;
static int LEN_RESP_CODE;
static int LEN_DATA_TAG;
static int LEN_GRUP_TAG;
static int LEN_FISCAL_COMMAND;
static int LEN_LENGTH;
static int LEN_RANDOM_NUMBER;
static int LEN_VERSION;
};
class FPUCommonTags
{
public:
static int FPU_FISCAL_COMMAND;
};
class GMPCommonTags
{
public:
static int TAG_SEQUNCE;
static int TAG_OP_DATE;
static int TAG_OP_TIME;
static int TAG_RESP_CODE;
};
class GMPGrupTags
{
public:
static int DG_HEADER;
static int DG_BLOCK;
static int DG_MATCH;
};
class GMPDataTags
{
public:
static int DT_HOSTLOCALIP;
static int DT_IP;
static int DT_BRAND;
static int DT_MODEL;
static int DT_SERIAL;
static int DT_ECR_BRAND;
static int DT_ECR_MODEL;
static int DT_ECR_SERIAL;
static int DT_RANDOM_NUMBER;
static int DT_ECR_RANDOM_NUMBER;
static int DT_MOD_KEY;
static int DT_EXP_KEY;
static int DT_ENC_KEY;
static int DT_CHK_VAL;
static int DT_ECR_CERT;
static int DT_EXT_DH_PUB_KEY;
static int DT_ERROR_CODE;
static int DT_ECR_POS_INDEX;
static int DT_SIGNATURE_OF_A;
static int DT_DRIVER_VERSION;
static int DT_DH_P;
static int DT_DH_G;
static int DT_DH_CHECK_HASH;
};
class FPUGroupTags
{
public:
static int DETAIL;
static int SALE;
static int VOID1;
static int TOTALS;
static int PAYMENT;
static int END;
static int FILE;
static int DISCOUNT;
static int NOTES;
static int PARAMS;
static int EFT;
};
class FPUDataTags
{
public:
static int DEPT; // Departman numarası
static int PLU; // Plu Numarası
static int QUANTITY; // Miktar/Count
static int AMOUNT; // Fiyat/Price
static int PAYMENT_TYPE; // Ödeme Tipi
static int PART_NUM; // Blok no(büyük mesajlar için)
static int TOTAL_PART; // Toplam blok sayısı
static int FILE_NAME; // Dosya adı
static int DOC_TYPE; // Belge Tipi (Fiş, Fatura,...)
static int REG_ID; // Kasaya özel numara
static int CASHIER_ID; // Kasiyer numarası
static int BARCODE; // Barkod bilgisi (Ürün barkodu...)
static int DOCUMENT_NUM; // Fiş numarası
static int DOC_SERIAL; // Seri no (Örn: Fatura seri no)
static int INSTALL_NUM; // Taksit
static int INDEX; // İndeks (Kredi no,logo no)
static int PERCENTAGE; // Yüzde (indirim, kdv)
static int ENDOFMSG; // Paket sonu
static int PAY_REFCODE; // Ödeme referans kodu
static int VATGROUP_NO; // Kdv grubu numarası
static int CATEGORY_NO; // Ana ürün grubu numarası
static int SUBCATEGORY_NO; // Alt ürün grubu numarası
static int LAST_PART; // Son paket olduğunu gösterir
static int NOTE; // Metin alanı (ürün adı, satır vs)
static int SALE_REFCODE; // Satış kalemine varsa harici ref kodu.
static int PASSWORD; // Şifre
static int ZNO; // Z Numarası
static int EJNO; // Ekü Numarası
static int PROPNAME; // Özellik Adı
static int PROPVALUE; // Özellik Değeri
static int ITEMOPTIONS; // Tartılabilirlik, Fiyatlı Satış gibi departman ve ürün opsiyonları
static int CMD; // Komut numarası/kodu
static int ERROR1; // Mali uygulamadan dönen hata kodu
static int STATE; // Mali uygulamanın durumu
static int PORT; // Port Numarası
static int EJ_LIMIT_LINE; // Ekü limit satır sayısı
static int CASHIER_AUTH; // Kasiyer yetki seviyesi
static int GRAPHIC_LOGO; // Grafik Logo
static int TCKN_VKN_LOGO; // Müşteri tc no veya vergi no
static int PLATE_NUM; // Araç plaka
static int EFT_PAY_STATE;// Kredi ödeme durum
static int CARD_HOLDER; // Kredi kartı müşteri adı
static int CARD_NUMBER; // Kart Numarası
static int EFT_DISC_ACTIVE; // Ödeme indirim artırım yapılabilir?
static int HGNCCID; // Hugin card id
static int HGNCCNAME; // Hugin card name
static int CHECK_NO; // Çek Numarası
static int PROVISION_ID; // Provision id
static int ACQUIER_ID;// Bank Info
static int ISSUER_ID;// Issuer
static int BATCH_NO; // Batch
static int STAN_NO; // Standing
static int BANK_INFO; // Bank info
static int SPEC_DOC_DATE; // Invoice date or parking entrance date
static int PARKING_TIME; // parking doc entrance time
static int INVOICE_SERIAL;// Invoice serial no (just for invoices)
static int SPEC_DOC_NAME; // Customer name or Instution name (just for advance and collection doc)
static int SUBSCRIBER_NO; // Subscriber or customer no (just for collection doc)
static int DOC_OPTION_FLAG; // Special documnets option flags
static int COMISSION_AMOUNT; // comission amount for colleciton documents with comission
};
class HSMessageTags
{
public:
static int INIT_REQ;
static int INIT_RESP;
static int KEY_EX_REQ;
static int KEY_EX_RESP;
static int CLOSE_REQ;
static int CLOSE_RESP;
static int ECHO_REQ;
static int ECHO_RESP;
};
class POSMessageTags
{
public:
static int BANK_LIST;
};
class POSDataTags
{
public:
static int APP_LIST;
static int APP_BKM_ID;
static int APP_STATUS;
static int APP_PRIORITY;
};
class GMPResCodes
{
public:
static string SUCCESS;// Operation successful
static string UNREG_SERIAL;//03 Unregistered terminal serial
static string INV_OPERATION;//12 Invalid Operation
static string SEQNUM_NOT_UNIQUE;//80 Sequence number not unique
static string SYSTEM_BUSY;//91 System busy
static string SYSTEM_ERROR;//96 System error
static string TIMEOUT; //99 Timeout
static string CONNECTION_ERROR; // 100 Connection error
};
enum State
{
ST_IDLE = 1,
ST_SELLING,
ST_SUBTOTAL,
ST_PAYMENT,
ST_OPEN_SALE,
ST_INFO_RCPT,
ST_CUSTOM_RCPT,
ST_IN_SERVICE,
ST_SRV_REQUIRED,
ST_LOGIN,
ST_NONFISCAL,
ST_ON_PWR_RCOVR,
ST_INVOICE,
ST_CONFIRM_REQUIRED
};
class Utililty
{
private:
static wstring stateMessages[];
public:
static wstring GetErrorMessage(int errorCode);
static wstring GetStateMessage(State state);
};
<file_sep>#pragma once
#include <iostream>
#include "MessageConstants.h"
#include "MessageBuilder.h"
#include "GMPMessage.h"
using namespace std;
class FPUResponse
{
public:
static int RESPONSE_MSG_ID;
string fiscalId;
int SequenceNum;
int ErrorCode;
State FPUState;
vector<unsigned char> Data;
vector<GMPField*> Detail;
FPUResponse();
FPUResponse(vector<unsigned char> bytesRead);
~FPUResponse(void);
};
<file_sep>#pragma once
#include <string>
#include <vector>
#include <map>
using namespace std;
class GMPItem
{
public:
virtual int Tag();
virtual int Length();
virtual vector<unsigned char> Value();
virtual bool IsField();
};
class GMPField : public GMPItem
{
private:
int tag;
int length;
vector<unsigned char> value;
public:
int Tag();
int Length();
vector<unsigned char> Value();
bool IsField();
GMPField(int tag, vector<unsigned char> value);
GMPField(int tag, int length, vector<unsigned char> value);
GMPField(int tag, string value);
static vector<GMPField> Parse(vector<unsigned char> bytesRead);
};
class GMPGroup : public GMPItem
{
private:
int groupTag;
map<int, GMPField*> tags;
public:
int Tag();
int Length();
vector<unsigned char> Value();
bool IsField();
map<int, GMPField*>& Tags();
GMPGroup(int groupTag);
~GMPGroup();
void Add(GMPField* tlv);
GMPField* FindTag(int tag);
};
class GMPMessage
{
private:
int msgType;
string terminalNo;
map<int, GMPItem*> items;
vector<int> itemsOrder;
public:
int MsgType();
string GetTerminalNo();
void SetTerminalNo(string value);
GMPMessage();
GMPMessage(int msgType);
~GMPMessage();
void AddItem(GMPItem* item);
void InsertItem(int index, GMPItem* item);
GMPGroup* FindGroup(int groupTag);
GMPField* FindTag(int tag);
static GMPMessage* Parse(vector<unsigned char> bytesRead);
vector<unsigned char> ToByte();
};
<file_sep>
#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include "SFResponse.h"
#include "DevInfo.h"
#include "SerialConnection.h"
#include "TcpConnection.h"
#include "GMPMessage.h"
#include "FPURequest.h"
#include "FPUResponse.h"
#include "JSONDocument.h"
#include "Logger.h"
using namespace Hugin::GMPCommon;
#ifdef WIN32
#include <windows.h>
#if defined(HUGINAPI_DLL_BUILD) // inside DLL
# define HUGINAPI __declspec(dllexport)
#elif defined __MINGW32__
# define HUGINAPI
#else // outside DLL
# define HUGINAPI __declspec(dllimport)
#endif // _WINDLL
#else
#define HUGINAPI
#include <unistd.h>
typedef unsigned char byte;
#endif
using namespace std;
enum MatchingState
{
NoMatchedDevice,
Matched
};
enum Settings
{
CUTTER,
PAY_WITH_EFT,
RECEIPT_LIMIT,
GRAPHIC_LOGO1,
RECEIPT_BARCODE
};
enum PaymentType
{
CASH,
CREDIT1,
CHECK,
FCURRENCY1
};
enum AdjustmentType
{
Fee,
PercentFee,
Discount,
PercentDiscount
};
class ProgramOption
{
public:
int No;
string Value;
ProgramOption()
{
No = 0;
Value = "";
}
};
#ifdef HUGINAPI
class HUGINAPI HuginPrinter
#else
class HuginPrinter
#endif
{
private:
DevInfo devInfo;
string licanceKey;
Connection* connection;
MatchingState matchState;
wstring currentLog;
string FiscalRegisterNo;
vector<unsigned char> EncapsulateMessage(int msgType, vector<unsigned char> reqPacket);
void SendMessage(GMPMessage* msg);
vector<unsigned char> FormatFPUMessage(GMPMessage* msg);
vector<unsigned char> Read();
vector<unsigned char> read();
int Send( vector<unsigned char> buffer );
public:
HuginPrinter(void);
~HuginPrinter(void);
string LibraryVersion();
void SetDebugLevel(Logger::LogLevel level);
void SetDebugFolder(string folderPath);
bool SerialConnect(string portName, int baudRate);
bool TcpConnect(string ip, int port);
bool MatchExDevice(DevInfo devInfo, string fiscalNo);
int GetTimeout();
void SetTimeout(int timeout);
bool IsConnected();
void Disconnect();
bool Connect(DevInfo devInfo, string fiscalRegNo, string licanceKey);
string SetDepartment(int id, vector<unsigned char> name, int vatId, double price, int weighable);
string GetDepartment(int deptId);
string SetCreditInfo(int id, vector<unsigned char> name);
string GetCreditInfo(int id);
string SetCurrencyInfo(int id, vector<unsigned char> name, double exchangeRate);
string GetCurrencyInfo(int index);
string SetMainCategory(int id, vector<unsigned char> name);
string GetMainCategory(int mainCatId);
string SetSubCategory(int id, vector<unsigned char> name, int mainCatId);
string GetSubCategory(int subCatId);
string SaveCashier(int id, vector<unsigned char> name, vector<unsigned char> password);
string GetCashier(int cashierId);
string SignInCashier(int id, vector<unsigned char> password);
string CheckCashierIsValid(int id, vector<unsigned char> password);
string GetLogo(int index);
string SetLogo(int index, vector<unsigned char> line);
tm GetDateTime();
string SetDateTime(tm date, tm time);
string GetVATRate(int index);
string SetVATRate(int index, double taxRate);
string SaveProduct(int productId, vector<unsigned char> productName, int deptId, double price, int weighable, vector<unsigned char> barcode, int subCatId);
string GetProduct(int pluNo);
string GetProgramOptions(int progEnum);
string SaveProgramOptions(int progEnum, vector<unsigned char> progValue);
string SaveGMPConnectionInfo(vector<unsigned char> ip, int port);
string PrintDocumentHeader();
string PrintDocumentHeader(vector<unsigned char> tckn_vkn, double amount, int docType);
string PrintDocumentHeader(int docType, string tckn_vkn, string docSerial, tm docDateTime);
string PrintParkDocument(vector<unsigned char> plate, tm entrenceDate);
string PrintAdvanceDocumentHeader(string tckn, string name, double amount);
string PrintCollectionDocumentHeader(string invoiceSerial, tm invoiceDate, double amount, string subscriberNo, string institutionName, double comissionAmount);
string PrintFoodDocumentHeader();
string PrintItem(int PLUNo, double quantity, double amount, vector<unsigned char> name, vector<unsigned char> barcode, int deptId, int weighable);
string PrintItems(vector<JSONItem3> itemList);
string PrintDeptItems(vector<JSONItem3> itemList);
string PrintDepartment(int deptId, double quantity, double amount, string name, int weighable);
string VoidDepartment(int deptId, string deptName, double quantity);
string PrintAdjustment(int adjustmentType, double amount, int percentage);
string Correct();
string Void(int PLUNo, double quantity);
string PrintSubtotal(bool isQuery);
string PrintPayment(int paymentType, int index, double paidTotal);
string VoidPayment(int paymentSequenceNo);
string CloseReceipt(bool slipCopy);
string VoidReceipt();
string PrintRemarkLine(vector<string> line);
string PrintRemarkLine( vector<vector<byte> > lines );
string PrintReceiptBarcode(vector<unsigned char> barcode);
string PrintJSONDocument(JSONDocument3 jsonDoc);
string PrintJSONDocument(string json);
string PrintJSONDocumentDeptOnly(const JSONDocument3& jsonDoc);
string PrintJSONDocumentDeptOnly(string jsonStr);
string PrintSalesDocument(string jsonStr);
string PrintXReport(int copy);
string PrintXPluReport(int firstPlu, int lastPlu, int copy);
string PrintZReport();
string PrintPeriodicZZReport(int firstZ, int lastZ, int copy, bool detail);
string PrintPeriodicDateReport(tm firstDay, tm lastDay, int copy, bool detail);
string PrintEJPeriodic(tm day, int copy);
string PrintEJPeriodic(tm startTime, tm endTime, int copy);
string PrintEJPeriodic(int ZStartId, int docStartId, int ZEndId, int docEndId, int copy);
string PrintEJDetail(int copy);
string PrintEndDayReport();
string PrintEJReport(int firstZNo, int firstDocId, int lastZNo, int lastDocId, int copy);
string PrintSystemInfoReport(int copy);
string PrintReceiptTotalReport(int copy);
string EnterServiceMode(vector<unsigned char> password);
string ExitServiceMode(vector<unsigned char> password);
string ClearDailyMemory();
string FactorySettings();
string CloseFM();
string SetExternalDevAddress(vector<unsigned char> ip, int port);
string UpdateFirmware(vector<unsigned char> ip, int port);
string PrintLogs(tm date);
string CreateDB();
string CheckPrinterStatus();
string GetLastResponse();
string CashIn(double amount);
string CashOut(double amount);
string CloseNFReceipt();
string Fiscalize(vector<unsigned char> password);
string StartFMTest();
string GetDrawerInfo();
string GetLastDocumentInfo(bool lastZ);
string GetServiceCode();
string ClearError();
string InterruptReport();
string OpenDrawer();
string SaveNetworkSettings(vector<unsigned char> ip, vector<unsigned char> subnet, vector<unsigned char> gateway);
string SetEJLimit(int index);
string StartEJ();
string StartFM(int fiscalNo);
string StartNFReceipt();
string StartNFDocument(int documentType);
string TransferFile(string fileName);
string WriteNFLine(vector<string> lines);
string GetPrinterDate();
ProgramOption ParsePrmOption(vector<unsigned char> data);
string SendReport(Command command, vector<unsigned char> buffer);
string SendCommand(Command command, vector<unsigned char> data);
vector<unsigned char> ConvertAddIp(vector<unsigned char> ipAddr);
FPUResponse Send(FPURequest request);
void SetLog(FPURequest request, FPUResponse response);
wstring GetLastLog();
string LoadGraphicLogo(const vector<byte>& monoChromeBitmapData);
string GetEFTAuthorisation(double amount, int installment, vector<unsigned char> cardNumber);
string GetEFTCardInfo(double amount);
string VoidEFTPayment(int acquierID, int batchNo, int stanNo);
string RefundEFTPayment(int acquierID);
string GetEFTSlipCopy(int acquierID, int batchNo, int stanNo, int zNo, int receiptNo);
string GetBankListOnEFT();
string GetSalesInfo();
};
<file_sep>#pragma once
#ifdef WIN32
#include <windows.h>
#else
#include <stdlib.h>
typedef unsigned char byte;
typedef char *LPCWSTR;
int WideCharToMultiByte(int CodePage,int dwFlags,char* lpWideCharStr,size_t cchWideChar,char* lpMultiByteStr,size_t cbMultiByte,char* lpDefaultChar,int* lpUsedDefaultChar);
#endif
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <map>
#include <stdarg.h>
using namespace std;
#ifdef WIN32
#define _GLIBCXX_USE_NOEXCEPT
#endif
class Exception : public exception
{
string message;
public:
Exception(const char *fmt, ...)
{
char buffer[1024] = {0};
va_list arg;
va_start(arg, fmt);
vsnprintf(buffer, sizeof (buffer) - 1, fmt, arg);
va_end(arg);
this->message = buffer;
}
//Exception(const char *message)
//{
// this->message = message;
//}
Exception(const string& message)
{
this->message = message;
}
~Exception() _GLIBCXX_USE_NOEXCEPT
{
}
const char *what() const _GLIBCXX_USE_NOEXCEPT
{
return message.c_str();
}
};
class Buffer : public vector<byte>
{
public:
static void BlockCopy(vector<byte>& src, int srcOffset, vector<byte>& dst, int dstOffset, int count);
};
template <class T>
class List : public vector<T>
{
public:
void AddRange(const vector<T>& collection)
{
for (int i = 0; i < collection.size(); ++i)
{
vector<T>::push_back(collection[i]);
}
}
void Clear()
{
vector<T>::clear();
}
vector<T> ToArray()
{
return *this;
}
void InsertRange(int index, const vector<T>& collection )
{
for (int i = 0; i < collection.size(); ++i)
{
vector<T>::insert(this->begin() + index + i, collection[i]);
}
}
void Add(const T& t)
{
vector<T>::push_back(t);
}
};
class _Math
{
public:
static double Round(double d);
static double Round(double d, int digits);
static int Min(int t1, int t2);
};
extern _Math Math;
vector<unsigned char> ToVector(string s);
vector<unsigned char> ToVector(const void *buffer, int size);
std::string ToString( vector<unsigned char> v );
bool GetMACaddress(string &mac);
string HexDump(const vector<byte> &buffer, int);
string HexDump(const void *buffer, int size);
string ToString(const wstring &str);
<file_sep>#pragma once
#include <ctime>
#include <cmath>
#include <string>
#include <sstream>
#include <vector>
#include <cstdlib>
#include "MessageConstants.h"
using namespace std;
#ifdef WIN32
#include <windows.h>
#if defined(HUGINAPI_DLL_BUILD) // inside DLL
# define HUGINAPI __declspec(dllexport)
#elif defined __MINGW32__
# define HUGINAPI
#else // outside DLL
# define HUGINAPI __declspec(dllimport)
#endif // _WINDLL
#else
#define HUGINAPI
#endif
class HUGINAPI MessageBuilder
{
public:
static vector<unsigned char> GetDateTimeInBytes(tm date);
static vector<unsigned char> GetDateInBytes(tm date);
static vector<unsigned char> Date2Bytes(tm date);
static vector<unsigned char> GetTimeInBytes(tm time);
static vector<unsigned char> Time2Bytes(tm time);
static tm GetDateFromBcd(vector<unsigned char> blockData, int index, int& outIndex);
static tm AddTimeFromBcd(vector<unsigned char> blockData, int index, int& outIndex, tm dtToAdd);
static vector<unsigned char> AddLength(int len);
static vector<unsigned char> HexToByteArray(int hexNum);
static int ByteArrayToHex(vector<unsigned char> bytesArray, int offset, int len);
static int GetTag(vector<unsigned char> bytesArray, int offset, int& outOffset);
static tm ConvertBytesToDate(vector<unsigned char> bytesBCD, int offset);
static tm ConvertBytesToTime(vector<unsigned char> bytesBCD, int offset);
static int ConvertBcdToInt(vector<unsigned char> bytesBCD, int offset, int len);
static vector<unsigned char> ByteArrayToString(vector<unsigned char> bytesArray, int offset, int len);
static vector<unsigned char> GetString(vector<unsigned char> bytesArray, int index, int& outIndex);
static vector<unsigned char> GetBytesFromOffset(vector<unsigned char> bytesArray, int offset, int len);
static unsigned char CalculateLRC(vector<unsigned char> reqPacket);
static short CalculateCRC(vector<unsigned char> buffer, int offset, int length);
static vector<unsigned char> ConvertIntToBCD(int value, int bcdLen);
static vector<unsigned char> ConvertDecimalToBCD(double value, int decimalCnt);
static int GetLength(vector<unsigned char> msgBytes, int offset, int& outIndex);
static string BytesToHexString(vector<unsigned char> bytesArr);
static string ByteToHexString(unsigned char byte);
static vector<unsigned char> HexStringToBytes(string strBytes);
static string FixTurkish(string str);
static string IntToString(int val, int len = 0);
static string DoubleToString(double val, int decimal = 2);
static string ToString(vector<unsigned char> v);
static vector<unsigned char> ToVector(string str);
static int ToInt32(vector<unsigned char> v);
static int ToInt32(vector<string> s, int offset, int count);
static string PadLeft(string s, int len, unsigned char ch);
static vector<unsigned char> PadRight(vector<unsigned char> v, int len, unsigned char ch);
static vector<string> Split(string str, char ch);
static string PadRight(string s, int len, unsigned char ch);
static string DateToString(tm date);
static string TimeToHHMM(tm date);
static double RoundToDouble(double val);
static vector<unsigned char> GetSecureRandomBytes(int count);
};
class Crc16
{
private:
static unsigned short polynomial;
static unsigned short table[];
public:
// CRC16_BYTE(crc, data) (crc16_table[ ((crc >> 8) ^ data) ] ^ (crc << 8));
static unsigned short ComputeChecksum(vector<unsigned char> bytes, int offset, int length);
static vector<unsigned char> ComputeChecksumBytes(vector<unsigned char> bytes);
};
<file_sep>#pragma once
#ifndef WIN32
#include <unistd.h>
#include <libudev.h> // sudo apt-get install libudev-dev
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <string>
#include <vector>
using namespace std;
typedef unsigned char byte;
class DevInfo;
class IDevice
{
public:
virtual void DeviceAdded(DevInfo& dev) = 0;
virtual void DeviceRemoved(const string& DevNode) = 0;
};
class DeviceNotifier
{
IDevice &pid;
static bool _running;
public:
DeviceNotifier(IDevice &id);
~DeviceNotifier(void);
void ThreadFunction() ;
void Start();
void Stop();
};
class DevInfo
{
public:
string vendor ;
string product ;
string description ;
string manufacturer;
string serial;
string Devtype;
string DevNode;
string Subsystem;
DevInfo(struct udev_device *dev);
static vector<DevInfo> GetDevices();
string Print();
};
string RunCommand(const char* cmd);
void RunCommand(const char* cmd, vector<string> & output);
#endif<file_sep>#pragma once
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
typedef unsigned char byte;
#define Sleep(X) usleep(X * 1000)
#endif
#define MAX_TRY_COUNT 2
#define TIMEOUT 8000
#define STX 0x02
#define ETX 0x03
#define ACK 0x06
#define NACK 0x15
#define _min(a,b) ((a<b)?(a):(b))
#define BLOCK_SIZE 4096
using namespace std;
class Connection
{
public:
enum
{
NOT_INIT,
INITED,
OPENED,
CLOSING,
CLOSED
};
int opened;
long recvTimeout;
vector<char> _queue;
char _recvbuf[BLOCK_SIZE];
char ConnectionString[128];
Connection(void);
virtual ~Connection(void);
virtual bool Open();
virtual bool Write(unsigned char* buffer, unsigned long writeBytes, unsigned long& writtenBytes);
virtual void Close();
bool IsOpen();
int GetTimeout();
void SetTimeout(int timeout);
void Enqueue(char* buffer, int len);
int Dequeue(char* buffer, int len);
bool Read(unsigned char* buffer, unsigned long receiveBytes, unsigned long& receivedBytes); // without timeout
void ReadExisting();
vector<unsigned char> Read(unsigned long bytesToRead);
bool ReadByte(byte &data);
int Write(vector<unsigned char> v);
#ifdef WIN32
HANDLE _mutex;
#else
pthread_mutex_t _mutex;
#endif
};
<file_sep>// This file generated by ngrestcg
// For more information, please visit: https://github.com/loentar/ngrest
#ifndef WS_VFXBRIDGER_H
#define WS_VFXBRIDGER_H
#include <ngrest/common/Service.h>
#include <ngrest/common/HttpException.h>
#include <PrinterLib/HuginPrinter.h>
#include <PrinterLib/Utilities.h>
#include <PrinterLib/Logger.h>
class HP
{
public:
static HuginPrinter* inst()
{
static HuginPrinter* instance = NULL;
if (instance == NULL)
{
instance = new HuginPrinter();
}
return instance;
}
static bool lock(int fLock = -1)
{
static bool s_fLock = false;
if (fLock == -1) return s_fLock;
s_fLock = ((fLock == 0) ? false: true);
return s_fLock;
}
};
//! Dummy description for the service
/*! Some detailed description of the service */
// '*location' comment sets resource path for this service
// *location: ws_vfxbridger
class ws_vfxbridger: public ngrest::Service
{
public:
// Here is an example of service operation
//! Dummy description for the operation
/*! Some detailed description of the operation */
// To invoke this operation from browser open: http://localhost:9098/ws_vfxbridger/World!
//
// '*location' metacomment sets path to operation relative to service operation.
// Default value is operation name.
// This will bind "echo" method to resource path: http://host:port/ws_vfxbridger/{text}
// *location: /{text}
//
// '*method' metacomment sets HTTP method for the operation. GET is default method.
// *method: GET
//
std::string echo(const std::string& text)
{
std::string rv;
//NGREST_ASSERT_HTTP(!HP::lock(), ngrest::HTTP_STATUS_423_LOCKED, "Service busy");
//HP::lock(1);
Logger::SetLogLevel(Logger::HIDE_BUG);
if (text == "9")
{
rv = HP::inst()->SerialConnect("/dev/ttyACM0", 115200) ? "1" : "0";
}
else if (text == "0")
{
DevInfo di;
di.IP = "127.0.0.1";
di.TerminalNo = "FO00007005";
di.Brand = "HUGIN";
di.Model = "HUGIN COMPACT";
di.Version = "1.0.4";
di.SerialNum = "12345678";
rv = HP::inst()->Connect(di, di.TerminalNo, "") ? "1" : "0";
}
else if (text == "1")
{
rv = HP::inst()->CheckPrinterStatus();
}
else if (text == "2")
{
rv = HP::inst()->PrintDocumentHeader();
}
else if (text == "3")
{
rv = HP::inst()->PrintItem(1, 15, 3.00, ToVector("SAMPLE PRODUCT"), ToVector(""), 1, 1);
}
else if (text == "4")
{
rv = HP::inst()->PrintPayment(0, -1, 45.0);
}
else if (text == "5")
{
rv = HP::inst()->CloseReceipt(false);
}
HP::lock(0);
return text + " " + rv;// " b1(" + b1 + ") b2(" + b2 + ")";
}
};
#endif // WS_VFXBRIDGER_H
<file_sep>#pragma once
#include <string>
#include <vector>
using namespace std;
enum AdjustmentType3
{
FEE3 = 0,
PERCENT_FEE3 = 1,
DISCOUNT3 = 2,
PERCENT_DISCOUNT3 = 3
};
enum PaymentType3
{
CASH3,
CREDIT3,
CHECK3,
FCURRENCY3
};
class PaymentInfo3
{
public:
PaymentType3 Type;
int Index;
double PaidTotal;
bool isNull;
bool ViaByEFT;
};
class Adjustment3
{
public:
int AdjType;
double Amount;
int Percentage;
bool isNull;
string NoteLine1;
string NoteLine2;
Adjustment3();
};
class JSONItem3
{
public:
int Id;
double Quantity;
double Price;
string Name;
string Barcode;
int DeptId;
int Status;
Adjustment3 Adj;
bool isNull;
int Weighable;
string NoteLine1;
string NoteLine2;
};
class EndOfReceipt
{
public:
bool CloseReceiptFlag;
bool BarcodeFlag;
string Barcode;
EndOfReceipt();
};
class JSONDocument3
{
public:
vector<JSONItem3> FiscalItems;
vector<Adjustment3> Adjustments;
vector<PaymentInfo3> Payments;
vector<string> FooterNotes;
EndOfReceipt EndOfReceiptInfo;
JSONDocument3();
JSONDocument3(string &json);
};
|
90857e2d74a3200ed0a22e023f27b46a2a0e5005
|
[
"Markdown",
"CMake",
"C++"
] | 20
|
C++
|
mhunesi/restgmp3
|
63d68f15ea697f788aca79081aa507dc28277a1c
|
10e1998b623dde4a60f556c2c28d08939b9f7c72
|
refs/heads/master
|
<file_sep>package com.example.scheduleapp
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.CalendarView
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class AddActivity : AppCompatActivity(),
TimePickerDialogFragment.OnSelectedTimeListener {
//DBヘルパー
private val helper = DatabaseHelper(this@AddActivity)
private var selectedDate = "";
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
//選択されている日付の初期値を設定
val calendar = findViewById<CalendarView>(R.id.calendarView)
val sdf = SimpleDateFormat("yyyy/MM/dd")
selectedDate = sdf.format(calendar.date)
calendar.setOnDateChangeListener(DateChangeListener())
//時間入力欄の取得
val etTime = findViewById<EditText>(R.id.etTime)
//選択時にダイアログを表示するためのリスナ設定
etTime.setOnClickListener{
showTimePickerDialog()
}
}
private fun showTimePickerDialog() {
val timePickerDialogFragment = TimePickerDialogFragment()
timePickerDialogFragment.show(supportFragmentManager, null)
}
override fun selectedTime(hour: Int, minute: Int) {
val text = String.format("%02d", hour) + ":" + String.format("%02d", minute)
val etTime = findViewById<EditText>(R.id.etTime)
etTime.setText(text)
}
/**
* 作成ボタン押下時のリスナ
*/
fun onMakeButtonClick(view: View){
//入力内容をDBに登録する処理
val etTime = findViewById<EditText>(R.id.etTime)
val etTimeText = etTime.text.toString()
val etDesc = findViewById<EditText>(R.id.etDesc)
val etDescText = etDesc.text.toString()
var checkTimeText = true
checkTimeText = validationCheck(etTime)
if(checkTimeText){
//ヘルパーからDB接続オブジェクトを取得
val db = helper.writableDatabase
//INSERT用SQLの用意
val sqlInsert = "INSERT INTO schedule (date,time,description,update_time) VALUES (?,?,?,?)"
//プリペアドステートメントの取得
val stmt = db.compileStatement(sqlInsert)
//変数のバインド
stmt.bindString(1, selectedDate)
stmt.bindString(2, etTimeText)
stmt.bindString(3, etDescText)
//現在時刻をupdate_timeに入れる
val now = Date()
val sdf = SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
stmt.bindString(4,sdf.format(now).toString())
//実行
stmt.executeInsert()
db.close()
//今追加したスケジュールの通知をセットする
createScheduledNotification()
Toast.makeText(applicationContext, R.string.toast_add, Toast.LENGTH_SHORT).show()
finish()
}
}
override fun onDestroy() {
//ヘルパーオブジェクトの開放
helper.close()
super.onDestroy()
}
/**
* カレンダーの日付を変えたときのリスナ
*/
private inner class DateChangeListener : CalendarView.OnDateChangeListener{
override fun onSelectedDayChange(
calendarView: CalendarView,
year: Int,
month: Int,
dayOfMonth: Int
) {
// monthは0起算のため+1します。
val displayMonth = month + 1
selectedDate = "$year/$displayMonth/$dayOfMonth"
}
}
/**
* 指定した時間にintentを飛ばす処理
*/
private fun scheduleNotification(id: String,content: String, calendar: Calendar) {
val notificationIntent = Intent(this@AddActivity, AlarmReceiver::class.java)
//NOTIFICATION_ID = 通知固有のID
notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, id)
//NOTIFICATION_CONTENT = 通知の表示メッセージ
notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_CONTENT, content)
val pendingIntent = PendingIntent.getBroadcast(
this@AddActivity,
id.toInt(), //アラームごとの固有ID
notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT
)
val alarmManager = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
//指定した時間になったらpendingIntentを飛ばす
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
}
/**
* 今登録したスケジュールで通知を送るように設定する処理
*/
private fun createScheduledNotification(){
//ヘルパーからDB接続オブジェクトを取得
val db = helper.writableDatabase
//全取得してupdate_timeが最新の行のデータ = 今登録したデータ
val sql = "SELECT * FROM schedule ORDER BY update_time DESC;"
//SQL実行
val cursor = db.rawQuery(sql,null)
cursor.moveToNext()
//通知作成に必要な情報を取得
val idIdx = cursor.getColumnIndex("_id")
val dateIdx = cursor.getColumnIndex("date")
val timeIdx = cursor.getColumnIndex("time")
val descIdx = cursor.getColumnIndex("description")
val id = cursor.getString(idIdx).toString()
val date = cursor.getString(dateIdx).toString()
val time = cursor.getString(timeIdx).toString()
val desc = cursor.getString(descIdx).toString()
//dateとtimeからcalendarを生成
val calendar = Calendar.getInstance()
//calendarにセットするためにsplitで分割した値を使う
val splitDate = date.split("/")
val splitTime = time.split(":")
//月は-1する
calendar.set(splitDate[0].toInt(), splitDate[1].toInt() - 1, splitDate[2].toInt(),
splitTime[0].toInt(), splitTime[1].toInt())
db.close()
//通知作成に必要なデータを渡す
scheduleNotification(id,desc,calendar)
}
private fun validationCheck(etTime:EditText) : Boolean{
if(etTime.text.toString().isEmpty()){
etTime.requestFocus()
//画面の下にToastエラーメッセージを表示
Toast.makeText(applicationContext, R.string.validation_error, Toast.LENGTH_SHORT).show()
return false
}
return true
}
}<file_sep>package com.example.scheduleapp
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
class AlarmReceiver : BroadcastReceiver() {
companion object{
const val NOTIFICATION_ID = "notificationId"
const val NOTIFICATION_CONTENT = "content"
}
/**
* アラーム受信時の処理
*/
override fun onReceive(context: Context, intent: Intent) {
val id = intent.getStringExtra(NOTIFICATION_ID)
val content = intent.getStringExtra(NOTIFICATION_CONTENT)
//通知チャネルの取得
createNotificationChannel(context)
createNotification(context,id,content)
}
/**
* 通知チャネルの設定
*/
private fun createNotificationChannel(context: Context){
//通知チャネルのIDの文字列
val id = "scheduleapp_notification_channel"
//通知チャネル名
val name = context.getString(R.string.notification_channel_name)
//通知チャネルの重要度:中(音は鳴らない)
val importance = NotificationManager.IMPORTANCE_LOW
//通知チャネル生成
val channel = NotificationChannel(id, name, importance)
//NotificationManagerオブジェクトを取得
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//通知チャネルを設定
manager.createNotificationChannel(channel)
}
/**
* 通知の呼び出し
*/
private fun createNotification(context: Context, id: String?, text: String?){
//builderクラスの作成
val builder = NotificationCompat.Builder(context, "scheduleapp_notification_channel")
//通知エリアに表示されるアイコン
builder.setSmallIcon(android.R.drawable.ic_dialog_info)
//表示メッセージ
builder.setContentText(text)
//Notificationオブジェクトの作成
val notification = builder.build()
//NotificationManagerオブジェクトの取得
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//通知を送る
if (id != null) {
manager.notify(id.toInt(), notification)
}
}
}<file_sep>package com.example.scheduleapp
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.CalendarView
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.text.SimpleDateFormat
import java.util.*
class DetailActivity : AppCompatActivity(),
TimePickerDialogFragment.OnSelectedTimeListener {
//DBヘルパー
private val helper = DatabaseHelper(this@DetailActivity)
private var selectedDate = ""
private val sdf = SimpleDateFormat("yyyy/MM/dd")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
//インテントからメイン画面で選択されたIDを取得
val selectedId = intent.getStringExtra("selectedId")
//IDで検索して結果をEditTextに入力しておく
//ヘルパーからDB接続オブジェクトを取得
val db = helper.writableDatabase
//INSERT用SQLの用意
val sql = "SELECT * FROM schedule WHERE _id = $selectedId"
//sql実行
val cursor = db.rawQuery(sql, null)
cursor.moveToFirst()
//実行結果を取り出す
val idxDate = cursor.getColumnIndex("date")
val date = cursor.getString(idxDate)
val idxTime = cursor.getColumnIndex("time")
val time = cursor.getString(idxTime)
val idxDesc = cursor.getColumnIndex("description")
val desc = cursor.getString(idxDesc)
//フィールドに日付をセット
selectedDate = date
//日付をcalendarViewにセット
//Calendar型の変数を用意
val tmpCalendar:Calendar = Calendar.getInstance()
//Calendarの日付を検索結果に合わせる
tmpCalendar.time = sdf.parse(date)
//画面部品を取得
val calendar = findViewById<CalendarView>(R.id.calendarView)
//画面部品に日付をセット
calendar.date = tmpCalendar.timeInMillis
//画面部品にリスナをセット
calendar.setOnDateChangeListener(DateChangeListener())
//EditTextにセット
val etTime = findViewById<EditText>(R.id.etTime)
etTime.setText(time.toString())
val etDesc = findViewById<EditText>(R.id.etDesc)
etDesc.setText(desc.toString())
db.close()
//時間入力用のダイアログをセット
etTime.setOnClickListener{
showTimePickerDialog()
}
}
/**
* 更新ボタンが押されたときの処理
*/
fun onUpdateButtonClick(view: View) {
//前画面で選択された行のプライマリIDをインテントから取得
val selectedId = intent.getStringExtra("selectedId")
val etTime = findViewById<EditText>(R.id.etTime)
val etDesc = findViewById<EditText>(R.id.etDesc)
var checkTimeText = true
checkTimeText = validationCheck(etTime)
if(checkTimeText){
//ヘルパーからDB接続オブジェクトを取得
val db = helper.writableDatabase
//INSERT用SQLの用意
val sqlUpdate =
"UPDATE schedule SET date = ?,time = ?,description = ? WHERE _id = $selectedId"
//プリペアドステートメントの取得
val stmt = db.compileStatement(sqlUpdate)
//変数のバインド
stmt.bindString(1, selectedDate)
stmt.bindString(2, etTime.text.toString())
stmt.bindString(3, etDesc.text.toString())
//実行
stmt.executeUpdateDelete()
db.close()
//通知の更新(通知を削除し、登録し直す)
deleteScheduledNotification(selectedId)
updateScheduledNotification(
selectedId,
selectedDate,
etTime.text.toString(),
etDesc.text.toString()
)
Toast.makeText(applicationContext, R.string.toast_update, Toast.LENGTH_SHORT).show()
//アクティビティを閉じる
finish()
}
}
/**
* 削除ボタンが押されたときの処理
*/
fun onDeleteButtonClick(view: View) {
//入力内容をDBから削除する処理
val selectedId = intent.getStringExtra("selectedId")
//ヘルパーからDB接続オブジェクトを取得
val db = helper.writableDatabase
//INSERT用SQLの用意
val sqlDelete = "DELETE FROM schedule WHERE _id = ?"
//プリペアドステートメントの取得
val stmt = db.compileStatement(sqlDelete)
//変数のバインド
stmt.bindString(1, selectedId)
//実行
stmt.executeUpdateDelete()
db.close()
//設定されていたアラームを削除する
deleteScheduledNotification(selectedId)
Toast.makeText(applicationContext, R.string.toast_delete, Toast.LENGTH_SHORT).show()
finish()
}
/**
* カレンダーの日付を変えたときのリスナ
*/
private inner class DateChangeListener : CalendarView.OnDateChangeListener{
override fun onSelectedDayChange(calendarView: CalendarView, year: Int, month: Int, dayOfMonth: Int) {
// monthは0起算のため+1します。
val displayMonth = month + 1
selectedDate = "$year/$displayMonth/$dayOfMonth"
}
}
private fun showTimePickerDialog() {
val timePickerDialogFragment = TimePickerDialogFragment()
timePickerDialogFragment.show(supportFragmentManager, null)
}
override fun selectedTime(hour: Int, minute: Int) {
val text = String.format("%02d", hour) + ":" + String.format("%02d", minute)
val etTime = findViewById<EditText>(R.id.etTime)
etTime.setText(text)
}
override fun onDestroy() {
//ヘルパーオブジェクトの開放
helper.close()
super.onDestroy()
}
/**
* 設定されていた通知を削除する処理
*/
private fun deleteScheduledNotification(id :String?){
val notificationIntent = Intent(this@DetailActivity, AlarmReceiver::class.java)
//NOTIFICATION_ID = 通知固有のID
notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, id)
val pendingIntent = id?.let {
PendingIntent.getBroadcast(
this@DetailActivity,
id.toInt(), //アラームごとの固有ID
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
//アラームの削除
val alarmManager = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
alarmManager.cancel(pendingIntent)
}
/**
* 指定した時間にintentを飛ばす処理
*/
private fun scheduleNotification(id: String,content: String, calendar: Calendar) {
val notificationIntent = Intent(this@DetailActivity, AlarmReceiver::class.java)
//NOTIFICATION_ID = 通知固有のID
notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_ID, id)
//NOTIFICATION_CONTENT = 通知の表示メッセージ
notificationIntent.putExtra(AlarmReceiver.NOTIFICATION_CONTENT, content)
val pendingIntent = PendingIntent.getBroadcast(
this@DetailActivity,
id.toInt(), //アラームごとの固有ID
notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT
)
val alarmManager = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
//指定した時間になったらpendingIntentを飛ばす
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
}
/**
* 更新したスケジュールで通知を送るように設定する処理
*/
private fun updateScheduledNotification(id: String?,date: String,time: String,desc: String){
//dateとtimeからcalendarを生成
val calendar = Calendar.getInstance()
//calendarにセットするためにsplitで分割した値を使う
val splitDate = date.split("/")
val splitTime = time.split(":")
//月は-1する
calendar.set(splitDate[0].toInt(), splitDate[1].toInt() - 1, splitDate[2].toInt(),
splitTime[0].toInt(), splitTime[1].toInt())
//通知作成に必要なデータを渡す
if (id != null) {
scheduleNotification(id,desc,calendar)
}
}
private fun validationCheck(etTime:EditText) : Boolean{
if(etTime.text.toString().isEmpty()){
etTime.requestFocus()
//画面の下にToastエラーメッセージを表示
Toast.makeText(applicationContext, R.string.validation_error, Toast.LENGTH_SHORT).show()
return false
}
return true
}
}<file_sep>package com.example.scheduleapp
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
//DBヘルパー
private val helper = DatabaseHelper(this@MainActivity)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val lvMain = findViewById<ListView>(R.id.lvMain)
//リストにリスナを設定
lvMain.onItemClickListener = ListItemClickListener()
//リストの取得
reloadListView(lvMain)
}
override fun onResume() {
super.onResume()
val lvMain = findViewById<ListView>(R.id.lvMain)
//リストの更新
reloadListView(lvMain)
}
/**
* リストタップ時のリスナ
*/
private inner class ListItemClickListener : AdapterView.OnItemClickListener{
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
//タップされた項目のidを取得
//隠しTextViewからプライマリキーの値を取得
val idPrimary = view?.findViewById<TextView>(R.id.idPrimary)
val selectedId = idPrimary?.text.toString()
//idを更新画面に渡して起動
val intent = Intent(applicationContext, DetailActivity::class.java)
intent.putExtra("selectedId",selectedId)
startActivity(intent)
}
}
/**
* DBから取得したデータをListViewに詰めて表示する処理
*/
private fun reloadListView(lv: ListView){
//DBから取ってきた値をリスト表示
val db = helper.writableDatabase
val sql = "SELECT * FROM schedule ORDER BY date ASC , time ASC;"
//SQL実行
val cursor = db.rawQuery(sql,null)
//cursorに格納された結果をListViewに詰め替えて表示する処理
val from = arrayOf("date","time","description","_id")
val to = intArrayOf(R.id.tvDateRow,R.id.tvTimeRow,R.id.tvDescRow,R.id.idPrimary)
val adapter = SimpleCursorAdapter(applicationContext,R.layout.row,cursor,from,to,0)
lv.adapter = adapter
db.close()
}
/**
* フローティングアクションボタンをタップしたときのリスナ
*/
fun onFABClick(view: View){
val intent = Intent(applicationContext, AddActivity::class.java)
startActivity(intent)
}
}
|
28ec63594ceba39dbb9a064efc10d90ab570c990
|
[
"Kotlin"
] | 4
|
Kotlin
|
sss-szk/ScheduleApp
|
efe48cac9a9184728fc1d75d3825b2076d300c78
|
e302c66677ea12600026cb54edc1ccba3c1a0e9a
|
refs/heads/master
|
<file_sep># beerReview
## Table Breakdown
* User
* Beer
* Brewery
* Post (User <> Beer)
* Created (Brewery <> Beer)
* Likes (Brewery <> User)
* Friend (User <> User)
This describes the tables in the database. Intend to scrape internet for all known breweries and beer.
<file_sep>/**
* Objects:
* Beer: Name, Type
* Brewery: Name, Established
* User: Name, Created
*
* Relations:
* Beer <> Brewery: First brewed
* User <> Beer: Description, Rating
*/
const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/beers';
var client = new pg.Client(connectionString);
client.on("drain", client.end.bind(client));
client.connect();
console.log("Starting creating tables...");
client.query("CREATE TABLE beer(id SERIAL PRIMARY KEY, name VARCHAR(30) NOT NULL, type VARCHAR(30))");
client.query("CREATE TABLE brewery(id SERIAL PRIMARY KEY, name VARCHAR(30) NOT NULL, established INTERVAL YEAR, location VARCHAR(30))");
client.query("CREATE TABLE users(id SERIAL PRIMARY KEY, name VARCHAR(30) NOT NULL, created TIMESTAMP)");
client.query("CREATE TABLE brewed(beer_id INTEGER REFERENCES beer (id), brewery_id INTEGER REFERENCES brewery (id), first_brewed DATE, PRIMARY KEY (beer_id, brewery_id))");
client.query("CREATE TABLE post(id SERIAL PRIMARY KEY, description TEXT NOT NULL, rating INTEGER, user_id INTEGER REFERENCES users (id), beer_id INTEGER REFERENCES beer (id))");
console.log("Finished creating tables");<file_sep>var express = require('express');
var router = express.Router();
const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/beers';
var config = {
user: 'Doko', //env var: PGUSER
database: 'beers', //env var: PGDATABASE
host: 'localhost', // Server hosting the postgres database
port: 5432, //env var: PGPORT
max: 10, // max number of clients in the pool
idleTimeoutMillis: 30000, // how long a client is allowed to remain idle before being closed
};
var pool = new pg.Pool(config);
var queryMap = {};
queryMap["beer"] = {
"GET": "SELECT * FROM beer where id=$1",
"POST": "INSERT INTO beer (name, type) VALUES ($1, $2) returning id"
};
queryMap["brewery"] = {
"GET": "SELECT * FROM brewery where id=$1",
"POST": "INSERT INTO brewery (name, established) VALUES ($1, $2) returning id"
};
function getResult(query, res, id) {
pool.connect(function(err, client, done) {
if (err) throw err;
client.query(query, [id], function(error, result) {
if (error) throw error;
res.send(result["rows"]);
});
})
};
function postResult(query, arr, res) {
client.connect(function (err, client, done) {
if (err) throw err;
client.query(query, arr, function(error, result) {
if (error) throw error;
console.log(result);
});
res.send("POST Okay");
});
}
router.get('/', function(req, res, next) {
res.send("Default entry to API");
});
router.get('/beers', function(req, res, next) {
res.send("Get entry to Beers");
});
router.post('/beers', function(req, res, next) {
const data = {name: req.body.name, type: req.body.type};
postResult(queryMap["beer"]["POST"], [data.name, data.type], res);
});
router.get("/beers/:id", function(req, res) {
getResult(queryMap["beer"]["GET"], res, req.params.id);
});
router.get('/brewery', function(req, res, next) {
getResult(queryMap["brewery"]["GET"], res, req.params.id);
});
router.post('/brewery', function(req, res, next) {
const data = {name: req.body.name, established: req.body.established};
postResult(queryMap["brewery"]["POST"], [data.name, data.established], res);
});
module.exports = router;
|
197af0171f314a3d1ac19631d502a67e8ee144c3
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
Dokopuffs/beerReview
|
a843b14451e3c4d5909468738fe549f5caa8f257
|
ca8343b1238991c11f6fd3b2da3773328b143a2b
|
refs/heads/master
|
<repo_name>yonekurayuki/blockchain-work<file_sep>/Fabric/sdktest/secure_token_manager/lib/table/tables.go
/*
* tables.go
* secure_token_manager(table)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
//構造体定義のためのパッケージ
package table
const (
USERTABLE_PREFIX = "userTable"
GROUPTABLE_PREFIX = "groupTable"
WALLETTABLE_PREFIX = "walletTable"
HISTORYTABLE_PREFIX = "historyTable"
)
/*
アカウント管理系 テーブル
*/
//ユーザーテーブル
type AccountInfo struct {
UserID string `json:"userID"` //ユーザID(任意の文字列)
UserName string `json:"userName"` //ユーザ名
GroupID string `json:"groupID"` //グループID(任意の文字列)
GroupName string `json:"groupName"` //グループ名
Property string `json:"property"` //プロパティ
}
//グループ管理テーブル
//user, wallet, transactionそれぞれが参照。グループ内のユーザを検索する際に利用。
type GroupInfo struct {
GroupID_UserID string //グループID_ユーザID(ユーザを一意に指定)
}
//アカウント情報返却用構造体
type AccountInfoArray struct {
Results []AccountInfo `json:"results"`
}
/*
ウォレット管理テーブル
*/
//ウォレットテーブル
type WalletInfo struct {
GroupID string `json:"groupID"` //グループID(任意の文字列)
UserID string `json:"userID"` //ユーザID(任意の文字列)
TokenID string `json:"tokenID"` //トークンID(任意の文字列)
Quantity string `json:"quantity"` //トークン残高
Property string `json:"property"` //プロパティ
LastUpdated string `json:"lastUpdated"` //最終更新日時
}
//単一ユーザのウォレット情報
type WalletInfoArray struct {
GroupID string `json:"groupID"`
UserID string `json:"userID"`
Wallets []Wallets `json:"wallets"`
}
//単一ウォレット情報
type Wallets struct{
TokenID string `json:"tokenID"`
Quantity string `json:"quantity"`
Property string `json:"property"`
LastUpdated string `json:"lastUpdated"`
}
//複数ユーザのウォレット情報
type GroupWalletInfoArray struct{
Results []WalletInfoArray `json:"results"`
}
/*
トークン取引履歴管理テーブル
*/
type FromID struct {
GroupID string `json:"groupID"`
UserID string `json:"userID"`
}
type ToID struct {
GroupID string `json:"groupID"`
UserID string `json:"userID"`
}
type TxHistory struct{
GroupID string `json:"groupID"`
UserID string `json:"userID"`
TxType string `json:"txType"`
From FromID `json:"from"`
To ToID `json:"to"`
TokenID string `json:"tokenID"`
QuantityDelta string `json:"quantityDelta"`
QuantitySnapshot string `json:"quantitySnapshot"`
Action string `json:"action"`
Timestamp string `json:"timestamp"`
TxID string `json:"txID"`
}
type TxHistories struct{
Results []TxHistory `json:"results"`
}
<file_sep>/Fabric/sdktest/registerSWAdmin.js
/*
* registerSWAdmin.js
* COPYRIGHT FUJITSU LIMITED 2018
*/
/* 概要:
* SmartWalletの管理者ユーザを登録する
*/
const config = require("./config/default.json");
const CA_SDK = require("./registerUser.js");
const fabric = require('./lib/fabricaccess.js');
const smartWalletAPIUtil = require('./lib/smartWalletAPIUtil.js');
CA_SDK.RegisterUser(config.smartwallet.SWAdmin.name,
config.smartwallet.SWAdmin.secret,
config.smartwallet.SWAdmin.groupID,
config.smartwallet.SWAdmin.userID,
true)
.then(() =>{
console.log("successfully registered Smartwallet admin");
//管理者ユーザをSmartWalletに登録
var arg0 = JSON.stringify({
groupID:config.smartwallet.SWAdmin.groupID,
groupName:config.smartwallet.SWAdmin.groupName,
userID:config.smartwallet.SWAdmin.userID,
userName:config.smartwallet.SWAdmin.userName});
var reqparam = {fcn:"createUser", args:[arg0]};
console.log(reqparam);
return fabric.Invoke(reqparam, true, config.smartwallet.SWAdmin.name, config.smartwallet.SWAdmin.secret)
}).then((returnvalue) => {
console.log("successfully registered Smartwallet admin to chaincode");
console.log(returnvalue);
//デフォルトウォレットの作成
var timestamp = new Date();
var arg0 = JSON.stringify({
groupID:config.smartwallet.SWAdmin.groupID,
userID:config.smartwallet.SWAdmin.userID,
tokenID:config.smartwallet.defaultWallet.tokenID,
quantity:config.smartwallet.defaultWallet.quantity,
timestamp:smartWalletAPIUtil.FormatISO8601(timestamp)
});
var reqparam = {fcn:"createWallet", args:[arg0]};
return fabric.Invoke(reqparam, true, config.smartwallet.SWAdmin.name, config.smartwallet.SWAdmin.secret)
}).then((res) =>{
console.log("successfully created default wallet for admin");
console.log(res);
}).catch(err => {
console.error(err);
});
<file_sep>/Ethereum-collabo/connector/src/app.js
/*
* app.js
* COPYRIGHT Fujitsu Limited 2018 and FUJITSU LABORATORIES LTD. 2018
*/
/* 概要: ethereum, fabric呼び出しRESTサーバー
*
*/
const conf = require('config');
var express = require('express');
//var path = require('path');
//var favicon = require('serve-favicon');
//var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const sampleAPIError = require('./lib/sampleAPIError.js');
//各パスにリクエストを受けたときに呼び出すライブラリ
var getBalance = require('./routes/getBalance');
var createAccount = require('./routes/createAccount');
var addInstance = require('./routes/addInstance');
var deleteInstance = require('./routes/deleteInstance');
var transfer = require('./routes/transfer');
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use('/getBalance', getBalance); //残高確認
app.use('/createAccount', createAccount); //アカウント作成
app.use('/addInstance', addInstance); //アセット登録
app.use('/deleteInstance', deleteInstance); //アセット消却
app.use('/transfer', transfer); //アセット移転
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new sampleAPIError(404, 1000);
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.statusCode || 500);
res.send(err.errorBody);
});
module.exports = app;
<file_sep>/Fabric/blocklistener_v1.0/MonitorManager.js
/*
* MonitorManager.js
* COPYRIGHT Fujitsu Limited 2017 and FUJITSU LABORATORIES LTD. 2017
*/
/* 概要:
* ブロック生成イベント監視クラスの管理用ライブラリ
*/
var EventMonitor = require('./EventMonitor.js');
var config = require('config');
var utils = require('../node_modules/fabric-client/lib/utils.js');// ログ出力用に1.0のライブラリ利用
// ログの設定
var logger = utils.getLogger('MonitorManager[' + process.pid + ']');
var allStarted = false;
/**
* startAllMonitor: 全てのブロック生成イベント(CC、EC)監視を開始する
**/
function startAllMonitor() {
// サーバ起動時に1回だけ実施
if (allStarted) return;
// EventMonitor開始
var em = new EventMonitor(config.chainId, config.fabric);
em.start();
allStarted = true;
}
exports.startAllMonitor = function() {
return startAllMonitor();
}
<file_sep>/Fabric/sdktest/lib/smartWalletAPIUtil.js
/*
* smartWalletAPIUtil.js
* COPYRIGHT FUJITSU LIMITED 2018
*/
/* 概要:
* APIのユーティリティクラス
*/
var smartWalletAPIUtil = class {
/**
* コンテンツタイプのチェック
* @param {Obj} req: リクエスト
* @return{bool} true:有効/false:無効
**/
static isValidContentType(req) {
var cType = req.header('Content-type');
if (cType != undefined) {
// JSON形式かどうか
if (cType.toLowerCase().indexOf('application/json') != -1) {
return true;
}
}
return false;
}
/**
* Authorizationヘッダの形式チェック
* @param {string} authorization header
* @return{bool} true:有効/false:無効
**/
static isValidAuthorizationHeader(auth) {
//var credentials = new Buffer(auth.split(" ").pop(), "base64").toString().split(":");
if(auth.split(" ")[1] == undefined){
return false
} else if(new Buffer(auth.split(" ").pop(), "base64").toString().split(":")[1] == undefined){
return false
}
return true;
}
/**
* 日時をISO8601拡張形式に変換する
* @param {date} dateオブジェクト
* @return{string} ISO8601拡張形式の日付文字列
* 例:2016-06-11T18:00:00+09:00
**/
static FormatISO8601(date) {
var offset = (function (d) {
var o = d.getTimezoneOffset() / -60;
return ((0 < o) ? '+' : '-') + ('00' + Math.abs(o)).substr(-2) + ':00';
})(date);
var iso = date.toISOString().substr(0, 19);
return (iso + offset); //+09:00を取得して後ろに連結
}
/**
* REST実行結果解析処理
* @param {object}} data: Fabric-RESTからのレスポンスボディ
* httpStatus: httpステータスコード
* res: レスポンスコールバック関数
* @return{object} result 正常時は返却値、異常時はNULL
**/
/*
static parseResultData(data, httpStatus, res) {
var result = null;
if (httpStatus === 200) {
// ステータスコード200の場合
if (data.results != null) {
// 正常終了
result = data.result.message;
} else if (data.error != null) {
// チェーンコードの実行で問題発生
var code = data.error.code;
var message = data.error.message;
var errorData = data.error.data;
console.log(code + " " + message + " " + errorData);
//エラーを返却
res.header('Content-Type', 'application/json; charset=UTF-8');
res.status(500).send(data);
return null;
}
} else {
// ステータスコード200以外の場合
// チェーンコードの実行前にK5サービス内で問題発生
var code = data.code;
var message = data.message;
console.log(code + " " + message);
//エラーを返却
res.header('Content-Type', 'application/json; charset=UTF-8');
res.status(500).send(data);
return null;
}
return result;
}
*/
}
module.exports = smartWalletAPIUtil;
<file_sep>/Fabric/FabricRestServer1.0/src/main/java/com/fujitsu/blockchain/rest/ChaincodeHandler.java
package com.fujitsu.blockchain.rest;
import java.io.IOException;
import java.security.cert.CertificateException;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.hyperledger.fabric.sdk.Channel;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.exception.ChaincodeException;
import org.hyperledger.fabric.sdk.exception.CryptoException;
import org.hyperledger.fabric.sdk.exception.NoAvailableTCertException;
import org.hyperledger.fabric_ca.sdk.exception.EnrollmentException;
import com.fujitsu.blockchain.rest.json.JacksonUtil;
import com.fujitsu.blockchain.rest.json.chaincode.JsonRpcRequest;
import com.fujitsu.blockchain.rest.json.chaincode.JsonRpcResponse;
import com.fujitsu.blockchain.rest.json.chaincode.JsonRpcResponseError;
import com.fujitsu.blockchain.rest.json.chaincode.JsonRpcResponseResult;
import com.fujitsu.blockchain.rest.util.LoggerUtil;
import com.fujitsu.blockchain.sdk.ChaincodeInvoker;
import com.fujitsu.blockchain.sdk.ChaincodeQuery;
import com.fujitsu.blockchain.sdk.FabricUser;
@Path("/chaincode")
public class ChaincodeHandler {
private LoggerUtil logger = LoggerUtil.getLogger();
/*
* チェーンコードを呼び出します。
* 現状はinvoke/queryを実施可能です。
*
* @params req jsonrpcのデータ構造。チェーンコードを呼び出す際の情報を設定しておく必要あり
* @params reqHeader RESTサーバ呼び出し時に設定されているリクエストヘッダ
* @return jsonrpcのデータ構造。チェーンコードの実行結果、エラーが設定されています。
*/
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JsonRpcResponse callChaincode(JsonRpcRequest req) {
String chaincodeResult = null;
String errMsg = null;
String mode = null;
try {
logger.debug("req=" + JacksonUtil.obj2Str(req));
// メソッド名を判定することでチェーンコードへの処理を切り分ける
String method = req.getMethod();
switch (method) {
// チェーンコードのDEPLOY処理
case "install":
// TODO
// 未サポート
break;
case "instantiate":
// TODO
// 未サポート
break;
// チェーンコードのINVOKE処理
case "invoke":
mode = "invoke";
chaincodeResult = invoke(req);
break;
// チェーンコードのQUERY処理
case "query":
mode = "query";
chaincodeResult = query(req);
break;
default:
break;
}
} catch (CertificateException | EnrollmentException
| ChaincodeException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
errMsg = e.getMessage();
} catch (NoAvailableTCertException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
errMsg = e.getMessage();
} catch (CryptoException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
errMsg = e.getMessage();
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
errMsg = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
errMsg = e.getMessage();
}
JsonRpcResponse response = new JsonRpcResponse();
response.setJsonrpc("2.0");
response.setId(req.getId());
if( null != chaincodeResult ){
// チェーンコードの呼び出しに成功した場合
// TODO invokeの際にsetMessageの内容がおかしい。SDKのバグと思われる
// 期待:トランザクションID
// 結果:チェーンコードID
JsonRpcResponseResult result = new JsonRpcResponseResult();
if(mode.equals("invoke")){
String[] output = chaincodeResult.split("\\+");
result.setStatus("OK");
result.setMessage(output[0]);
if(!output[1].equals("empty")){
result.setPayload(output[1]);
}
response.setResult(result);
}else{
result.setStatus("OK");
result.setMessage(chaincodeResult);
response.setResult(result);
}
} else {
// チェーンコードの呼び出しに失敗した場合の処理
// TODO エラーメッセージの考慮
JsonRpcResponseError error = new JsonRpcResponseError();
error.setCode(0);
error.setData(0);
error.setMessage(errMsg);
response.setError(error);
}
return response;
}
/*
* チェーンコードにinvokeします。
*
* @params req jsonrpcのデータ構造。チェーンコードを呼び出す際の情報を設定しておく必要あり
* @return 呼び出し結果をStringで返します。
*/
private String invoke(JsonRpcRequest req) throws Exception, CertificateException, EnrollmentException, ChaincodeException, NoAvailableTCertException, CryptoException, IOException {
logger.debug(req);
// HFClient client = HFClient.createNewInstance();
// client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
HFClient client = FabricUser.getClient(req.getParams().getSecureContext(),req.getParams().getOrgName());
//client.setUserContext(user);
Channel chain = FabricUser.getChain(req.getParams().getChannelName(), req.getParams().getOrgName(), client);
ChaincodeInvoker invoker = new ChaincodeInvoker(chain, client);
String result = invoker.invoke(req.getParams());
return result;
}
/*
* チェーンコードにqueryします。
*
* @params req jsonrpcのデータ構造。チェーンコードを呼び出す際の情報を設定しておく必要あり
* @return 呼び出し結果をStringで返します。
*/
private String query(JsonRpcRequest req) throws Exception, CertificateException, EnrollmentException, ChaincodeException, NoAvailableTCertException, CryptoException, IOException {
logger.debug(req);
// HFClient client = HFClient.createNewInstance();
//client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
HFClient client = FabricUser.getClient(req.getParams().getSecureContext(),req.getParams().getOrgName());
// client.setUserContext(user);
Channel chain = FabricUser.getChain(req.getParams().getChannelName(), req.getParams().getOrgName(), client);
ChaincodeQuery query = new ChaincodeQuery(chain, client);
String result = query.query(req.getParams());
return result;
}
}
<file_sep>/Ethereum-collabo/geth-docker/README.md
# geth
JCB用Ethereumプライベートチェーン環境の構築を行います.
## 使い方
dockerのimageを作成します。環境変数として`http_proxy`に有効なproxy情報を設定してからbuildします。
build1ディレクトリ内で実施してください。
```
$ export http_proxy=http://name:passwd@proxy:port
$ cd build1
$ chmod +x docker_build
$ ./docker_build -t dev/eth1 .
$ cd ..
```
dockerコンテナを作成します。
```
$ docker-compose up -d
-> これで、Ethereumのdockerコンテナが起動する。
CONTAINER ID IMAGE COMMAND PORTS NAMES
230eaf4c5f06 dev/eth1 "geth" 0.0.0.0:8545->8545/tcp, 8546/tcp, 0.0.0.0:30300->30300/tcp, 30303/tcp, 30303/udp geth1
```
以上でコンテナ環境までの作成は完了です.
## Dockerコンテナのディレクトリ構成
```
/root/work
|- geth
|- DATA
|- start_geth2.sh
|- attachconsole.sh
```
`geth`にはプライベートチェーン用のDATAディレクトリ及びgethの起動スクリプトがそれぞれ格納されています。
## gethの使い方
以降、上記のgeth1コンテナに乗り込んで実施します。
```
$ docker exec -it geth1 sh
```
gethを起動します。
```
$ cd geth
$ ./start_geth2.sh
⇒3つのアカウントは作成済み(DATA/keystoreに格納)。初期残高設定済みのファイル(DATA/customGenesis.json)を読み込んで起動
```
バックグラウンドで起動するので、以下のコマンドを打ってコンソールに接続する。
コンソール内にてマイニングを実行しておく。
```
$ ./attachconsole.sh
> miner.start()
```
※adminアカウントの秘密鍵は各Ethereumコンテナにマウントされている.
ETHがたまり,ブロックが生成されるまでしばらく待つ必要がある.
## coinbaseアカウントのアンロック方法
```
$ ./attachconsole.sh
> personal.unlockAccount(eth.accounts[0], "pass0", 0)
```
<file_sep>/Fabric/FabricRestServer1.0/src/main/java/com/fujitsu/blockchain/rest/util/LoggerUtil.java
package com.fujitsu.blockchain.rest.util;
public class LoggerUtil {
private final String LOG_LEVEL = "com.fujitsu.blockchain.LOG_LEVEL";
private static LoggerUtil logger;
private LogLevel level = LogLevel.INFO;
LoggerUtil(){
// ログレベルの設定
// ログレベルをDEBUGにする場合は、システムプロパティに設定する
String propLevel = System.getProperty(LOG_LEVEL);
if( LogLevel.DEBUG.toString().equals(propLevel) ) {
level = LogLevel.DEBUG;
}
}
/*
* LoggerUtilのインスタンスを取得する
* @return LoggerUtilインスタンス。シングルトン
*/
public static synchronized LoggerUtil getLogger(){
// Singletonとして利用
if( logger == null ) {
logger = new LoggerUtil();
}
return logger;
}
/*
* INFOとしてログを出力
* [DEBUG]がメッセージ本文にプレフィックス設定
* @param args メッセージ可変情報
*/
public void debug(Object... args){
if(level == LogLevel.DEBUG) {
StringBuilder sb = new StringBuilder();
sb.append("[DEBUG] ");
sb.append(getCallerMethod());
sb.append(": ");
for( Object o : args ){
sb.append(o);
sb.append(", ");
}
publish( LogLevel.DEBUG, sb.toString() );
}
}
/*
* SEVEREとしてログを出力
* @param id メッセージID
* @param args メッセージ可変情報
*/
public void error(Object... args){
StringBuilder sb = new StringBuilder();
for( Object o : args ){
sb.append(o);
sb.append(", ");
}
publish( LogLevel.SEVERE, sb.toString() );
}
/*
* INFOとしてログを出力
* @param id メッセージID
* @param args メッセージ可変情報
*/
public void info(Object... args){
StringBuilder sb = new StringBuilder();
for( Object o : args ){
sb.append(o);
sb.append(", ");
}
publish( LogLevel.INFO, sb.toString() );
}
/*
* 呼び出し元のメソッド名を取得する
* スタックトレースの4番目の要素がログ呼び出し元のメソッド情報
* [0] java.lang.Thread.getStackTrace(Thread.java:lineno)
* [1] LoggerUtil.getCallerMethod(LoggerUtil.java:lineno)
* [2] LoggerUtil.traceIn(LoggerUtil.java:lineno)
* [3] caller className.methodName(source:lineno)
*/
private String getCallerMethod(){
StackTraceElement element = Thread.currentThread().getStackTrace()[3];
StringBuilder sb = new StringBuilder();
sb.append(element.getClassName());
sb.append("#");
sb.append(element.getMethodName());
return sb.toString();
}
/*
* メッセージを標準出力、標準エラー出力にログ出力します。
* @param msg ログに出力するメッセージ
*/
private void publish(LogLevel level, String msg){
if( level == LogLevel.SEVERE ){
System.err.println( msg );
}
else{
System.out.println( msg );
}
}
}
/*
* ログのレベルを表す列挙型
* ログのレベル値と、それを表す文字列で構成
*/
enum LogLevel {
SEVERE("SEVERE"),
WARNING("WARNING"),
INFO("INFO"),
DEBUG("DEBUG"),
TRACE("TRACE"),
TRACEHIGH("TRACEHIGH");
private final String name;
LogLevel(String name){
this.name = name;
}
@Override
public String toString() {
return this.name;
}
/*
* ログのレベルを返します。ordinalを利用し、順番に応じたレベルを返す
* @return ログレベル
*/
public int level() {
return ordinal();
}
}
<file_sep>/Fabric/sdktest/secure_token_manager/lib/constants/constants.go
/*
* constants.go
* secure_token_manager(constants definitions)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package constants
const(
//ID_prefix
USERID_PREFIX = "user"
GROUPID_PREFIX = "group"
TOKENID_PREFIX = "token"
//key_name
USERID = "userID"
USERNAME = "userName"
GROUPID = "groupID"
GROUPNAME = "groupName"
TOKENID = "tokenID"
PROPERTY = "property"
QUANTITY = "quantity"
TIMESTAMP = "timestamp"
PUBKEY = "pubkey"
ACTION = "action"
QUANTITYDELTA = "quantityDelta"
QUANTITYSNAPSHOT = "quantitySnapshot"
TXTYPE = "txType"
FROMGROUPID = "fromGroupID"
FROMUSERID = "fromUserID"
TOGROUPID = "toGroupID"
TOUSERID = "toUserID"
//txType
TXTYPE_DEPOSIT = "deposit"
TXTYPE_WITHDRAW = "withdraw"
TXTYPE_TRANSFER = "transfer"
//key partition(groupIDとuserIDの連結に使用)
KEYPARTITION = "_"
DATETIME_FORMAT = "2006-01-02T15:04:05+09:00"
BIT_SIZE = 64
//error_prefix
ERR_INTERNAL = "[InternalError]"
ERR_INVALID_PARAM = "[Invalid Parameter]"
ERR_INCORRECT_JSON = "[Incorrect JSON string format]"
ERR_CHARLIMIT = "[Character Limit Error]"
ERR_INCORRECTFORMAT = "[Incorrect Format]"
ERR_NOT_AUTHORIZED ="[Authorization Error]"
/*
error codes
*/
//未登録情報
ERRCODE_ACCOUNT_NOT_EXISTS = 1001
ERRCODE_WALLET_NOT_EXISTS = 1002
ERRCODE_TXINFO_NOT_EXISTS = 1003
//重複登録・権限がない
ERRCODE_NOT_AUTHORIZED = 4000
ERRCODE_ACCOUNT_EXISTS = 4001
ERRCODE_WALLET_EXISTS = 4002
ERRCODE_INTERNAL = 3000
)
<file_sep>/Ethereum-collabo/connector/src/lib/fabricaccess.js
/* fabricaccess.js
* COPYRIGHT Fujitsu Limited 2018
*/
/* 概要:
* fabric v1.2.0へのリクエスト処理ライブラリ
*/
//依存ライブラリ
var path = require('path');
var util = require('util');
var os = require('os');
//fabric client系依存ライブラリ
var Fabric_Client = require('fabric-client');
var Peer = require('fabric-client/lib/Peer.js');
var Orderer = require('fabric-client/lib/Orderer.js');
var User = require('fabric-client/lib/User.js');
var EventHub = require('fabric-client/lib/EventHub.js');
var copService = require('fabric-ca-client/lib/FabricCAClientImpl.js');
//設定情報
var config = require("../config/default.json");
const chaincodeId = config.fabric.chaincodeId; //チェーンコードID
// fabric-clientオブジェクトのリスト
var clients = {}
//Invoke用関数
exports.Invoke = function(reqBody, isWait){
var tx_id = null;
var the_user = null;
var eventhubs = [];
var invokeResponse; //チェーンコードからの返却値
return new Promise(function(resolve, reject){
var channel = null;
var client = null;
getClientAndChannel(config.fabric.channelName, config)
.then((retObj) => {
channel = retObj.channel;
client = retObj.client;
return getSubmitter(client, config);
})
.then((admin) => {
// Enrollに成功したUserオブジェクトを設定する
the_user = admin; // 使用していない?→client内でUserContextとして吸収している模様
// EPへのEventHubコネクションを張る
for (var i = 0; i < config.fabric.peers.length; i++) {
var eh = client.newEventHub();
eh.setPeerAddr(config.fabric.peers[i].events);
eh.connect();
eventhubs.push(eh);
}
return channel.initialize();
}).then((nothing) => {
// get a transaction id object based on the current user assigned to fabric client
tx_id = client.newTransactionID();
var request = {
//targets: let default to the peer assigned to the client
chaincodeId: chaincodeId, //チェーンコードID
fcn: reqBody.fcn, //チェーンコード関数名
args: reqBody.args, //チェーンコード引数
chainId: config.fabric.channelName, //チャネル名
txId: tx_id
};
// send the transaction proposal to the peers
return channel.sendTransactionProposal(request);
}).then((results) => {
// EPから返されたProposal応答が成功しているかチェック
var proposalResponses = results[0];
var proposal = results[1];
var header = results[2];
var all_good = true;
var resStr = ''; // 戻り値ありのinvoke関数結果格納用
for(var i in proposalResponses) {
let one_good = false;
if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) {
if (proposalResponses[i].response.payload) {
resStr = new String(proposalResponses[i].response.payload);
invokeResponse = resStr;
}
one_good = true;
console.log('transaction proposal was good');
} else {
console.log('transaction proposal was bad');
}
all_good = all_good & one_good;
}
if (all_good) {
// EventHubからのトランザクションイベントを待機する
var invokeId = tx_id.getTransactionID();
var cnt = 0;
eventhubs.forEach((eh) => {
eh.registerTxEvent(invokeId.toString(), (tx, code) => {
eh.unregisterTxEvent(invokeId);
if (code !== 'VALID') {
console.log('Transaction Commited Failure, code = ' + code + ', ' + eh.getPeerAddr() + ', tx_id=' + invokeId);
} else {
console.log('Transaction Commited, ' + eh.getPeerAddr() + ', tx_id=' + invokeId);
}
// EventHubサーバから切断
if (eh.isconnected()) {
console.log('Disconnecting the event hub');
eh.disconnect();
}
// ブロック生成を待つ場合、EventHubからのトランザクションイベントが全て揃ったらresolve
cnt++;
if (cnt == eventhubs.length && isWait) {
if(invokeResponse != ""){ //invokeの返却値が""の場合、TxIDを返すよう変更
return resolve(invokeResponse);
} else {
return resolve(invokeId);
}
}
});
});
// Ordering ServiceにsendTransactionする
var request = {
proposalResponses: proposalResponses,
proposal: proposal,
header: header
};
console.log('sendTransaction(to Orderer) start');
return channel.sendTransaction(request)
.then((response) => {
if (response.status === 'SUCCESS') {
console.log('sendTransaction(to Orderer) end');
if (!isWait) {
// ブロック生成を待たない場合はここでresolve
if(invokeResponse != ""){ //invokeの返却値が""の場合、TxIDを返すよう変更
return resolve(invokeResponse);
} else {
return resolve(invokeId);
}
}
} else {
throw new Error('Failed to order the transaction. Error code: ' + response.status);
}
});
} else {
// チェーンコード自体がエラーを返した場合はここに来る
// queryと違い、チェーンコードからのエラーメッセージは取得できない模様。要ログ参照
throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
}
})
.catch((err) => {
eventhubs.forEach((eh) => {
// EventHubサーバから切断
if (eh.isconnected()) {
console.log('Disconnecting the event hub');
eh.disconnect();
}
});
return reject(err);
});
}).catch((err) => {
console.error('Failed to invoke successfully :: ' + err);
});
}
//Query用関数
exports.Query = function(reqbody) {
var tx_id = null;
var nonce = null;
var the_user = null;
return new Promise((resolve, reject) => {
var channel = null;
var client = null;
getClientAndChannel(config.fabric.channelName, config)
.then((retObj) => {
channel = retObj.channel;
client = retObj.client
return getSubmitter(client, config);
})
.then((admin) => {
// Enrollに成功したUserオブジェクトを設定する
the_user = admin;
return channel.initialize();
}).then((nothing) => {
// Query実行用の要求オブジェクトを生成する
tx_id = client.newTransactionID();
var request = {
chaincodeId : chaincodeId,
fcn: reqbody.fcn,
args: reqbody.args,
txId: tx_id
};
// Query実行
console.log('queryByChaincode start, txid=' + tx_id.getTransactionID());
return channel.queryByChaincode(request);
})
.then((response_payloads) => {
console.log('queryByChaincode end');
if (response_payloads) {
var resStr = '';
var errMsg = '';
var valid = false;
for(let i = 0; i < response_payloads.length; i++) {
resStr = new String(response_payloads[i]);
// チェーンコード自体がエラーを返した場合はエラーメッセージが格納されている
// 接続失敗等もSDKからのエラーメッセージ(Error: Connect Failed)
if (resStr.indexOf('Error:') == 0){
errMsg = resStr;
} else {
valid = true;
break;
}
}
if (valid) {
// 1つでも正常な結果が得られていればそれを返す
return resolve(resStr);
} else {
// 全EPからのレスポンスがエラーの場合
throw new Error(errMsg);
}
} else {
throw new Error('response_payloads is null');
}
})
.catch((err) => {
return reject(err);
});
});
}
// EPへのProposal送信を行うユーザオブジェクトを取得する
// ※setUserContextで設定したものをclient内部で使用するので
// 返却するユーザオブジェクト自体は特に使用しなくなった。
function getSubmitter(cli,config) {
var caUrl = config.fabric.ca.url;
var caName = config.fabric.ca.name;
return cli.getUserContext(config.fabric.submitter.name, true)
.then((user) => {
return new Promise((resolve, reject) => {
if (user && user.isEnrolled()) {
return resolve(user);
}
var member = new User(config.fabric.submitter.name);
var cryptoSuite = cli.getCryptoSuite();
if (!cryptoSuite) {
var storePath = '/tmp/kvs-' + caName;
cryptoSuite = Fabric_Client.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(
Fabric_Client.newCryptoKeyStore({
path: storePath
})
);
cli.setCryptoSuite(cryptoSuite);
}
member.setCryptoSuite(cryptoSuite);
var tlsOptions = {
trustedRoots: [],
verify: false
};
var cop = new copService(caUrl,tlsOptions, caName, cryptoSuite);
return cop.enroll({
enrollmentID: config.fabric.submitter.name,
enrollmentSecret: config.fabric.submitter.secret
}).then((enrollment) => {
return member.setEnrollment(enrollment.key, enrollment.certificate, config.fabric.mspid);
}).then(() => {
return cli.setUserContext(member, false);
}).then(() => {
return resolve(member);
}).catch((err) => {
return reject(err);
});
});
});
}
// fabric-clientオブジェクトとChannelオブジェクト生成
function getClientAndChannel(channelName, config) {
var retObj = {client:null, channel:null};
// clientに1つしかKVSを設定できないので、KVSのパスと同様にCA単位での管理
var isNewClient = false;
var client = clients[config.fabric.ca.name];
if (!client) {
console.log('create new fabric-client');
client = new Fabric_Client();
clients[config.fabric.ca.name] = client;
isNewClient = true;
}
var channel = null;
// ※v1.0SDKのgetChannelは存在しない場合にnullではなく例外を返してくるのでtry~catch
// そのため初回は必ずClient.jsからのエラーがログ出力されてしまうが実害はない
try {
channel = client.getChannel(channelName);
// channelに設定してある現在のpeer、ordererが今回指定された接続先情報と異なる場合は差分反映
// TODO: おそらくこれでいけるとは思うが変更時の動作未確認
var oldPeers = channel.getPeers();
var oldPeerUrls = [];
for (var i = 0; i < oldPeers.length; i++) {
oldPeerUrls[i] = oldPeers[i].getUrl();
}
var newPeerUrls = [];
for (var i = 0; i < config.fabric.peers.length; i++) {
newPeerUrls[i] = config.fabric.peers[i].requests;
}
// old, newの順で結合配列を作成
var allPeerUrls = [...oldPeerUrls, ...newPeerUrls];
for (var [i, e] of allPeerUrls.entries()) {
if(!oldPeerUrls.includes(e)) {
// 現在のpeersに含まれていないので追加
var newPeer = client.newPeer(e);
channel.addPeer(newPeer);
}
if(!newPeerUrls.includes(e)) {
// 今回指定されたpeersに含まれていないので削除
channel.removePeer(oldPeers[i]);
}
}
// ordererは現状1件だけの指定にしているので、異なる場合は置き換え
var oldOrderer = channel.getOrderers();
var newOrderer = config.fabric.orderer;
if (oldOrderer[0].getUrl() != newOrderer) {
channel.removeOrderer(oldOrderer[0]);
channel.addOrderer(client.newOrderer(newOrderer));
}
}catch(e) {
if(channel == null) {
console.log('create new channel, name=' + channelName);
channel = client.newChannel(channelName);
// ordererの設定
channel.addOrderer(client.newOrderer(config.fabric.orderer));
// EPの設定
for (var i = 0; i < config.fabric.peers.length; i++) {
var peer = client.newPeer(config.fabric.peers[i].requests);
channel.addPeer(peer);
}
} else {
// 接続先情報差分反映時の例外
console.error(e);
}
}
retObj.channel = channel;
return new Promise((resolve, reject) => {
if (isNewClient) {
var storePath = '/tmp/kvs-' + config.fabric.ca.name;
var cryptoSuite = Fabric_Client.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(
Fabric_Client.newCryptoKeyStore({
path: storePath
})
);
client.setCryptoSuite(cryptoSuite);
// Enrollment情報の格納先を生成する
return Fabric_Client.newDefaultKeyValueStore({
path: storePath
})
.then((store) => {
// KeyValueストアを設定
client.setStateStore(store);
retObj.client = client;
resolve(retObj);
})
} else {
retObj.client = client;
resolve(retObj);
}
});
}
<file_sep>/Fabric/sdktest/secure_token_manager/lib/util/util.go
/*
* util.go
* secure_token_manager(util)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package util
import (
"github.com/secure_token_manager/lib/constants"
"fmt"
"errors"
"encoding/json"
"strconv"
"time"
"math"
"github.com/hyperledger/fabric/core/chaincode/shim"
"github.com/hyperledger/fabric/core/chaincode/lib/cid"
)
// ========================================================================
// VerifyUser- 実行ユーザの認証を行う。
// 証明書の属性に設定されているグループID,ユーザIDと一致することを検証する。
// @param {stub} shim.ChaincodeStubInterface
// {string} groupID
// {string} userID
// @return {bool} 検証成功の場合、true
// ========================================================================
func VerifyUser (stub shim.ChaincodeStubInterface, groupID string, userID string) bool {
groupid, _,_ := cid.GetAttributeValue(stub, "groupID")
userid, _,_ := cid.GetAttributeValue(stub, "userID")
if(userid == userID && groupid == groupID){
return true
}
return false
}
// ============================================================
// IsAdmin- 実行ユーザが管理者かどうか判定する。
// 証明書の属性値(以下を設定)から判断する。
// "admin":"true" or "false"
// "groupID":"グループID"
// "userID":"ユーザID"
// @param {stub} shim.ChaincodeStubInterface
// @return {bool} 管理者である場合、true
// {error} エラー
// ============================================================
func IsAdmin (stub shim.ChaincodeStubInterface ) bool {
err := cid.AssertAttributeValue(stub, "admin", "true")
if(err != nil){
return false
} else{
return true
}
return false
}
// =================================================================
// GetOperator - 実行ユーザを証明書の属性情報から取得する。
// @param {stub} shim.ChaincodeStubInterface
// @return {string} groupID
// {string} userID
// =================================================================
/*
func GetOperator(stub shim.ChaincodeStubInterface ) (string, string){
groupid, _,_ := cid.GetAttributeValue(stub, "groupID")
userid, _,_ := cid.GetAttributeValue(stub, "userID")
return groupid, userid
}
*/
// =============================================================================
// SameGroupUser- 実行ユーザが操作対象ユーザと同グループに属しているかどうか判定する。
// 証明書の属性値から判断する。
// @param {stub} shim.ChaincodeStubInterface
// @return {bool} 管理者である場合、true
// {error} エラー
// =============================================================================
func SameGroupUser (stub shim.ChaincodeStubInterface, groupID string) bool {
//属性値から取得したグループID(実行ユーザ)と、引数groupID(操作対象ユーザ)
//が一致した場合、同グループと判断
err := cid.AssertAttributeValue(stub, "groupID", groupID)
if(err != nil){
return false
} else{
return true
}
return false
}
// ============================================================
// AddValue- 2つの値(string)を足し算(引き算)する。
// @param {string} val1 足される(引かれる)値
// {string} val2 足す(引く)値
// {bool} isAdd 足すか引くか
// @return {string} 計算結果
// ============================================================
func AddValue (val1 string, val2 string, isAdd bool) (string, error) {
//val1,2のフォーマットが異常ならここでエラー
val1float,err := strconv.ParseFloat(val1, constants.BIT_SIZE)
if(err != nil){
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return "", errors.New(errorstr)
}
val2float, err := strconv.ParseFloat(val2, constants.BIT_SIZE)
if(err != nil){
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return "", errors.New(errorstr)
}
var newval float64
if(isAdd){
newval = val1float + val2float
} else{
newval = val1float - val2float
}
resultVal := fmt.Sprint(newval)
return resultVal, nil
}
// ============================================================
// IsPlusVal - 文字列数値の正負判定
// @param {string} value
// @return {bool} +の場合、true
// {error} エラー(引数が数値の形式でない場合)
// ============================================================
func IsPlusVal(value string) (bool, error) {
floatval, err := strconv.ParseFloat(value, constants.BIT_SIZE)
if(err != nil){
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return false, errors.New(errorstr)
}
if(floatval < 0){
return false, nil
}
return true, nil
}
// ==================================================================
// InverseLexicalOrder - タイムスタンプを辞書順に逆になるように変換する
// @param {string} timestamp:日付。"yyyy.mm.dd hh.mm.ss"の形式とする
// @return string 逆変換後のタイムスタンプ
// err 日付の形式が異なる場合のエラー
// ==================================================================
func InverseLexicalOrder(timestamp string) (string, error) {
// 指定されたタイムスタンプを数値変換する
tm, err := time.Parse(constants.DATETIME_FORMAT, timestamp)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return "invalid datetime format", errors.New(errorstr)
}
//-------------------------------------------------------------------------
// 変換ルール
// 1.int64のMAX値から、ナノ秒のタイムスタンプ値を減算(未来のほうが小さい値)
// 2.1の数値を0パディングし、int64のMAX値の桁数に揃える
//
// [辞書順] 10, 101, 11, 215, 22
// [小さい順] 10, 11, 22, 101, 215
// [パディング+辞書順] 010, 011, 022, 101, 215
//-------------------------------------------------------------------------
// int64の最大値からtimestampをナノ秒変換した数値を減算
return fmt.Sprintf("%019d", math.MaxInt64 - tm.UnixNano()), nil
}
// ==================================================================
// MakeErrorFormat - エラーメッセージにエラーコードを付加して返却
// @param {int} errcode エラーコード
// {string} errrmessage エラーメッセージ
// @return string フォーマット変換後のエラー
// ==================================================================
func MakeErrorFormat(errcode int, errmessage string) string{
type ErrorFormat struct{
Code int `json:"code"`
Message string `json:"message"`
}
error := ErrorFormat{
Code: errcode,
Message: errmessage }
returnvalJSONBytes, _ := json.Marshal(error)
return string(returnvalJSONBytes)
}
<file_sep>/Ethereum-collabo/geth-docker/build/docker_build
#!/bin/sh
echo "$@"
docker build --build-arg HTTP_PROXY=$http_proxy --build-arg http_proxy=$http_proxy --build-arg HTTPS_PROXY=$http_proxy --build-arg https_proxy=$https_proxy $@
<file_sep>/Fabric/sdktest/secure_token_manager/README.md
# secure_token_manager
secure_token_manager
<file_sep>/Fabric/sdktest/test_invoke.js
const fabric = require('./lib/fabricaccess2.js');
const config = require("./config/default.json");
const smartWalletAPIUtil = require('./lib/smartWalletAPIUtil.js');
var timestamp = new Date();
var arg0 = JSON.stringify({
groupID:config.smartwallet.SWAdmin.groupID,
userID:config.smartwallet.SWAdmin.userID,
tokenID:"t0",
quantity:config.smartwallet.defaultWallet.quantity,
timestamp: smartWalletAPIUtil.FormatISO8601(timestamp)
});
var reqparam = {fcn:"createWallet", args:[arg0]};
fabric.Invoke(reqparam, true, config.smartwallet.SWAdmin.name, config.smartwallet.SWAdmin.secret)
.then((res) =>{
console.log(res);
}).catch(err => {
console.error(err);
});
<file_sep>/Ethereum-collabo/connector/build/Dockerfile
FROM hyperledger/fabric-ccenv:x86_64-1.0.4
ENV http_proxy $HTTP_PROXY
ENV https_proxy $HTTP_PROXY
ENV HTTP_PROXY $HTTP_PROXY
ENV HTTPS_PROXY $HTTP_PROXY
RUN echo $HTTP_PROXY
RUN apt-get update
RUN apt-get install -y npm
RUN npm -g config set proxy $HTTP_PROXY
RUN npm -g config set http-proxy $HTTP_PROXY
RUN npm -g config set https-proxy $HTTP_PROXY
RUN npm -g config set registry http://registry.npmjs.org/
RUN npm config list
RUN npm -g install n
RUN n 8.9.0<file_sep>/Ethereum-collabo/README.md
# as-bcAbstractControl
NS本委託向けのアセットサービス用のBC抽象操作機能の開発ディレクトリ
```
・geth-dockerフォルダ ⇒環境構築資材が格納されています。構築方法はtxtファイルを参照ください。
※cc-demo3(VM)上に起動済みのため、cc-demo3上でのテストの際は本作業は必要なしです。
VM上の資材は、/opt配下にあります。
・connecterフォルダ ⇒ lib/eth_smartwallet.js 今回作成したコントラクト(ライブラリ)
bin/www.js socket通信のサーバー側が起動できます。
lib/ethaccess.js socket通信のクライアント側実行ライブラリ
※ethereumの環境を作り直した場合、config/default.jsonを書き換えてください。
(接続先アドレス、管理者アカウントのアドレス・パスワード)
※VM上(/home/yone配下)に配備済みです。Nodeコマンドでサーバー起動⇒クライアント実行のみで動作確認できるはずです。
```
# 環境構築
* 前提
Fabric v1.2の環境(basic-network, couchDB無しver)でsmartwalletが動作していること
1.ethereum環境構築
geth-dockerフォルダをVMの任意のディレクトリに配備。
あとは、geth-docker/Ethereumメモ.txtを参照。
2.RESTサーバー構築
RESTサーバーは、5000番ポートでリクエストを待ち受け、Fabric/Ethereumにリクエストを送信する。
connecterフォルダをVMの任意のディレクトリに配備して実施。
1. dockerイメージの作成
connector/build配下で以下のコマンドを打つ
$ export http_proxy="host:<EMAIL>:8080"
$ export https_proxy="host:<EMAIL>:8080"
$ ./docker_build -t rest .
2-2. サーバーの起動
connecterフォルダに戻って、docker-composeで起動
$ docker-compose -f docker-compose-rest.yaml up -d
dockerコンテナに乗り込み、サーバーを起動する。
$ docker exec -it restserver bash
(restserverコンテナ内)
~~~/work/$ nohup npm start &
~~~/work/$ exit
# REST IF仕様
## アカウント作成(createaccount)
* メソッド
POST
* パス
/createAccount
* リクエストパラメータ
~~~
{
"name": <名前(Fabricの場合必須)>,
"pass": <アカウントのパスワード(Ethereumの場合必須)>
"ChainType": <"Fabric" or "Ethereum">
}
~~~
* レスポンス(正常時)
~~~
{
"status": 200(固定),
"accountID": <アカウントID(Fabricの場合、name)>
}
~~~
## アセット登録(addInstance)
* メソッド
POST
* パス
/addInstance
* リクエストパラメータ
~~~
{
"accountID": <登録先アドレス(Fabricの場合、name)>,
"value": <金額(eth)>, //現状、Fabricの場合小数はエラーになる
"ChainType": <"Fabric" or "Ethereum">
}
~~~
* レスポンス(正常時)
~~~
{
"status": 200(固定),
"txid": <トランザクションID>
}
~~~
## アセット消却(deleteInstance)
* メソッド
POST
* パス
/deleteInstance
* リクエストパラメータ
~~~
{
"accountID": <登録先アドレス(Fabricの場合、name)>,
"unlockpass": <アンロックパスワード>,
"value": <金額(eth)>, //現状、Fabricの場合小数はエラーになる
"ChainType": <"Fabric" or "Ethereum">
}
~~~
* レスポンス(正常時)
~~~
{
"status": 200(固定),
"txid": <トランザクションID>
}
~~~
## 残高確認(getBalance)
* メソッド
POST
* パス
/getBalance
* リクエストパラメータ
~~~
{
"accountID": <アカウントID(Fabricの場合、name)>,
"ChainType": <"Fabric" or "Ethereum">
}
~~~
* レスポンス(正常時)
~~~
{
"status": 200(固定),
"amount": <残高(Ether)>
}
~~~
## 送金(transfer)
* メソッド
POST
* パス
/transfer
* リクエストパラメータ
~~~
{
"from": <送金元アドレス(Fabricの場合、name)>,
"unlockpass": <アンロックパスワード(Ethereumの場合必須)>,
"to": <送金先アドレス(Fabricの場合、name)>,
"value": <送金額(Ether)>, //現状、Fabricの場合小数はエラーになる
"ChainType": <"Fabric" or "Ethereum">
}
~~~
* レスポンス(正常時)
~~~
{
"status": 200(固定),
"TXID": <トランザクションID>
}
~~~
<file_sep>/Fabric/blocklistener_v1.2/MonitorManager.js
/* 概要:
* ブロック生成イベント監視クラスの管理用ライブラリ
*/
var EventMonitor = require('./EventMonitor.js');
var config = require('./config/default.json');
var utils = require('fabric-client/lib/utils.js');// ログ出力用に1.0のライブラリ利用
// ログの設定
var logger = utils.getLogger('MonitorManager[' + process.pid + ']');
var allStarted = false;
/**
* startAllMonitor: 全てのブロック生成イベント(CC、EC)監視を開始する
**/
function startAllMonitor() {
// サーバ起動時に1回だけ実施
if (allStarted) return;
// EventMonitor開始
var em = new EventMonitor(config.chainId, config.fabric);
em.start();
allStarted = true;
}
//実行
startAllMonitor();
<file_sep>/Fabric/sdktest/secure_token_manager/lib/transaction/transaction_query.go
/*
* transaction_query.go
* secure_token_manager(transaction management)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package transaction
import (
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/secure_token_manager/lib/constants"
"errors"
"github.com/secure_token_manager/lib/util"
"github.com/secure_token_manager/lib/table"
)
// ====================================================================================================
// GetSingleUserTxHistoryWithCheckOperator - 特定のトークンについて、単一アカウントのトークン取引履歴を取得する。
// 実行ユーザの検証をする。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID",
// "userID":"ユーザID",
// "tokenID":"トークンID",
// "txType":"トランザクションタイプ"
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "results":[{
// "txType":"トランザクションタイプ",
// "from":{
// "groupID":"移転元グループID",
// "userID":"移転元ユーザID"
// },
// "to":{
// "groupID":"移転先グループID",
// "userID":"移転先ユーザID"
// },
// "tokenID":"トークンID",
// "quantityDelta":"トークン移転量",
// "quantitySnapshot":"トークン累積値",
// "action":"アクション",
// "timestamp":"タイムスタンプ",
// "txID":"トランザクションID"
// },・・]
// }
// ===================================================================================================
func GetSingleUserTxHistoryWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetSingleUserTxHistoryWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数から各引数の取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
tokenID, argserr := argsmap[constants.TOKENID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOKENID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
txType, _ := argsmap[constants.TXTYPE].(string)
if(txType != ""){
if(txType != constants.TXTYPE_WITHDRAW && txType != constants.TXTYPE_TRANSFER && txType != constants.TXTYPE_DEPOSIT){
errormessage := constants.ERR_INVALID_PARAM + constants.TXTYPE + " must be " + constants.TXTYPE_TRANSFER + " or " + constants.TXTYPE_WITHDRAW + " or " + constants.TXTYPE_DEPOSIT
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
}
//証明書の属性検証(管理者もしくは同グループのユーザでない場合、エラー)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
トークン取引履歴取得(単一アカウント)
*/
logger.Infof("getTxHistory")
txhistories, err := getTxHistory(stub, groupID, userID, tokenID, txType)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(len(txhistories.Results) == 0){
errormessage := constants.ERR_INTERNAL + " TxHistory of wallet " + "(" +constants.GROUPID + ": " + groupID + " , " + constants.USERID +": " + userID + " , " + constants.TOKENID +": " + tokenID + ")" + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_TXINFO_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
txHistoryInfoJSONBytes, err := json.Marshal(txhistories)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
return shim.Success(txHistoryInfoJSONBytes)
}
// ==================================================================================================================
// GetGroupUsersTxHistoryWithCheckOperator - 特定のトークンについて、特定のグループに属する全アカウントのトークン取引履歴を、
// userIDの昇順ごとの新着順で取得する。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID" (必須指定)
// "tokenID":"トークンID", (必須指定)
// "txType":"トランザクションタイプ"
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "results":[{
// "txType":"トランザクションタイプ",
// "from":{
// "groupID":"移転元グループID",
// "userID":"移転元ユーザID"
// },
// "to":{
// "groupID":"移転先グループID",
// "userID":"移転先ユーザID"
// },
// "tokenID":"トークンID",
// "quantityDelta":"トークン移転量",
// "quantitySnapshot":"トークン累積値",
// "action":"アクション",
// "timestamp":"タイムスタンプ",
// "txID":"トランザクションID"
// },・・]
// }
// =================================================================================================================
func GetGroupUsersTxHistoryWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetGroupUsersTxHistoryWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数からgroupIDの取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
tokenID, argserr := argsmap[constants.TOKENID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOKENID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
txType, _ := argsmap[constants.TXTYPE].(string)
if(txType != ""){
if(txType != constants.TXTYPE_WITHDRAW && txType != constants.TXTYPE_TRANSFER && txType != constants.TXTYPE_DEPOSIT){
errormessage := constants.ERR_INVALID_PARAM + constants.TXTYPE + " must be " + constants.TXTYPE_TRANSFER + " or " + constants.TXTYPE_WITHDRAW + " or " + constants.TXTYPE_DEPOSIT
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
}
//証明書の属性検証(管理者もしくは同グループのユーザでない場合、エラー)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
グループ内トークン取引情報取得
*/
logger.Infof("getTxHistory")
txhistories, err := getTxHistory(stub, groupID, "", tokenID, txType)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(len(txhistories.Results) == 0){
errormessage := constants.ERR_INTERNAL + " TxHistory of wallet " + "(" +constants.GROUPID + ": " + groupID + " , " + constants.TOKENID +": " + tokenID + ")" + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_TXINFO_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
txHistoryInfoJSONBytes, err := json.Marshal(txhistories)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
return shim.Success(txHistoryInfoJSONBytes)
}
// ================================================================================
// getTxHistory- トークン取引履歴情報を取得する。(内部関数。WSにアクセス)
// @param {string} groupID
// {string} userID (省略時、グループ全体のトークン取引履歴情報を返却)
// {string} tokenID
// {string} txType
// @return {table.TxHistories}
// {
// "results":[{
// "txType":"トランザクションタイプ",
// "from":{
// "groupID":"移転元グループID",
// "userID":"移転元ユーザID"
// },
// "to":{
// "groupID":"移転先グループID",
// "userID":"移転先ユーザID"
// },
// "tokenID":"トークンID",
// "quantityDelta":"トークン移転量",
// "quantitySnapshot":"トークン累積値",
// "action":"アクション",
// "timestamp":"タイムスタンプ",
// "txID":"トランザクションID"
// },・・]
// }
// {error} エラー
// ================================================================================
func getTxHistory(stub shim.ChaincodeStubInterface, groupID string, userID string, tokenID string, txType string) (table.TxHistories, error){
results := table.TxHistories{}
//ウォレット情報の取得(存在確認)
groupwalletinfoarray, err := util.GetWallet(stub, groupID, userID, tokenID)
if(err != nil){
return results, err
} else if(len(groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallets in " + constants.GROUPID + ": " + groupID + " , " + constants.TOKENID +": " + tokenID + " not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return results, errors.New(errorstr)
}
var userlist []string
if(userID == ""){
//groupIDからgroupID_userIDのリストを取得
userlist, err = util.GetUserList(stub, groupID)
if(err != nil){
return results, err
} else if(len(userlist) == 0 ){
errormessage := constants.ERR_INTERNAL + " Users in " +constants.GROUPID + ": " + groupID +" not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return results, errors.New(errorstr)
}
} else {
//単一アカウント情報取得(存在確認)
accountInfoJSONBytes, err := util.GetUser(stub, groupID, userID)
if (err != nil) {
return results, err
} else if (accountInfoJSONBytes == nil) {
errormessage := constants.ERR_INTERNAL + " User " + "(" + constants.GROUPID + ": " + groupID + " and " + constants.USERID + ": " + userID + ")" + " not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return results, errors.New(errorstr)
}
groupuserkey := constants.GROUPID_PREFIX + groupID + constants.KEYPARTITION + constants.USERID_PREFIX + userID
userlist = append(userlist, groupuserkey)
}
//グループ内のユーザの数だけトークン取引履歴情報取得
for _, groupuserkey := range userlist{
partialkey := []string{groupuserkey, constants.TOKENID_PREFIX + tokenID}
if(txType != ""){
partialkey = append(partialkey, txType)
}
resultsiterator, err := stub.GetStateByPartialCompositeKey(table.HISTORYTABLE_PREFIX, partialkey)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
defer resultsiterator.Close()
var i int
for i = 0; resultsiterator.HasNext(); i++ {
data := table.TxHistory{}
response, err := resultsiterator.Next()
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
err = json.Unmarshal(response.Value, &data)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
results.Results = append(results.Results, data)
}
}
return results, nil
}
<file_sep>/Ethereum-collabo/geth-docker/eth_private_net/start_geth.sh
geth --datadir ./DATA init ./DATA/myGenesis.json
geth --datadir ./DATA --networkid 12345 --port 8545 --nodiscover --maxpeers 0 console 2>> ./DATA/gethLog.log
<file_sep>/Fabric/sdktest/secure_token_manager/lib/user/user.go
/*
* user.go
* secure_token_manager(user management)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package user
import (
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"errors"
"github.com/secure_token_manager/lib/util"
"github.com/secure_token_manager/lib/constants"
"github.com/secure_token_manager/lib/table"
)
const (
LOGGER_NAME = "secure_token_manager_user"
)
// ==============================================================================================
// CreateUserWithCheckOperator - 一般ユーザアカウントの作成
// 実行ユーザの認証を行う。(管理者でない場合エラー)
// IF詳細はCreateUser関数参照
// ==============================================================================================
func CreateUserWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("CreateUserWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//証明書の属性を検証 ⇒管理者でなければエラー
if(!util.IsAdmin(stub)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin can createUser"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
//上記の2パラメータ以外はCreateAdminUserと同じなので、引数チェックはcreateUserでおこなう。
logger.Infof("createUser")
resvalBytes, err := createUser(stub, args[0])
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
// ==============================================================================================
// CreateAdminUser - 管理者アカウントの作成
// チェーンコードの初期化時に呼び出す。実行ユーザの認証なし。
// IF詳細はCreateUser関数参照
// ==============================================================================================
/*
func CreateAdminUser(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("CreateAdminUser")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
return shim.Error(errormessage)
}
logger.Infof("createUser")
resvalBytes, err := createUser(stub, args[0])
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
*/
// =================================================================
// createUser- アカウントを新規に作成する。(内部関数)
// @param {string} args: 以下のJSON文字列
// {
// "groupID":"グループID", (必須指定)
// "groupName":"グループ名",
// "userID":"ユーザID", (必須指定)
// "userName":"ユーザ名",
// "property":"プロパティ"
// }
// @return {[]byte}
// {
// "groupID":"グループID",
// "groupName":"グループ名",
// "userID":"ユーザID",
// "userName":"ユーザ名",
// "property":"プロパティ",
// "txID":"トランザクションID"
// }
// {error} エラー
// =================================================================
func createUser(stub shim.ChaincodeStubInterface, args string) ([]byte, error) {
//返却値用構造体定義
type CreateUser_Return struct{
UserID string `json:"userID"` //ユーザID(任意の文字列)
UserName string `json:"userName"` //ユーザ名
GroupID string `json:"groupID"` //グループID(任意の文字列)
GroupName string `json:"groupName"` //グループ名
Property string `json:"property"` //プロパティ
TxID string `json:"txID"` //トランザクションID
}
//引数をmap型変数にparse
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//map型変数から各引数の取得
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
userName, _ := argsmap[constants.USERNAME].(string)
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
groupName, _ := argsmap[constants.GROUPNAME].(string)
property, _ := argsmap[constants.PROPERTY].(string)
/*
アカウント情報登録
*/
//ユーザーテーブル(※)用複合キー生成
//(※)グループID、ユーザIDでアカウント情報を検索するためのテーブル
usertablekey, err := stub.CreateCompositeKey(table.USERTABLE_PREFIX, []string{constants.GROUPID_PREFIX + groupID, constants.USERID_PREFIX + userID})
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//アカウント情報構造体
accountInfo := &table.AccountInfo{
UserID: userID, //ユーザID
UserName: userName, //ユーザ名
GroupID: groupID, //グループID
GroupName: groupName, //グループ名
Property: property } //プロパティ
accountInfoJSONBytes, err := json.Marshal(accountInfo)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//ユーザーテーブルへ登録
//アカウントの存在確認
tmp, err := stub.GetState(usertablekey)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
} else if(tmp != nil){
errormessage := constants.ERR_INTERNAL + " User " + " ( " +constants.GROUPID + ": " + groupID + " and " + constants.USERID +": " + userID + " ) " + " already exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_EXISTS, errormessage)
return nil, errors.New(errorstr)
}
err = stub.PutState(usertablekey, []byte(accountInfoJSONBytes))
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
/*
グループ管理情報登録
*/
//グループ管理テーブル(※)用複合キー生成
//(※)グループ全体のウォレット、トークン移転履歴情報を取得する際、このテーブルからグループID_ユーザIDのリストを取得し、各々についてウォレット、トークン移転履歴テーブルを参照する。
grouptablekey, err := stub.CreateCompositeKey(table.GROUPTABLE_PREFIX, []string{constants.GROUPID_PREFIX + groupID, constants.USERID_PREFIX + userID})
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//ユーザを一意に指定するため、userIDとgroupIDを内部で連結
groupID_userID := constants.GROUPID_PREFIX + groupID + constants.KEYPARTITION + constants.USERID_PREFIX + userID
//グループ情報構造体
groupInfo := &table.GroupInfo{GroupID_UserID: groupID_userID}
groupInfoJSONBytes, err := json.Marshal(groupInfo)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//グループ管理テーブルへ登録
//ユーザテーブル登録時にアカウントの存在確認をしているためここではしない
err = stub.PutState(grouptablekey, []byte(groupInfoJSONBytes))
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//txIDを取得
txID:= stub.GetTxID()
//返却値の設定
returnval := &CreateUser_Return{
UserID: userID, //ユーザID
UserName: userName, //ユーザ名
GroupID: groupID, //グループID
GroupName: groupName, //グループ名
Property: property, //プロパティ
TxID: txID}
returnvalJSONBytes, err := json.Marshal(returnval)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
return returnvalJSONBytes, nil
}
// ==============================================================================================
// GetSingleUserWithCheckOperator - 単一アカウントのアカウント情報を取得する。実行ユーザの検証をする。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID",
// "userID":"ユーザID"
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "groupID":"グループID",
// "groupName":"グループ名",
// "userID":"ユーザID",
// "userName":"ユーザ名",
// "property":"プロパティ"
// }
// ===============================================================================================
func GetSingleUserWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetSingleUserWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数から各引数の取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//管理者でない、かつ同グループのユーザでない場合エラー
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
単一アカウント情報取得
*/
logger.Infof("GetUser")
accountInfoJSONBytes, err := util.GetUser(stub, groupID, userID)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(accountInfoJSONBytes == nil){
errormessage := constants.ERR_INTERNAL + " User " + "(" +constants.GROUPID + ": " + groupID + " and " + constants.USERID +": " + userID + ")" + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
return shim.Success(accountInfoJSONBytes)
}
// ============================================================================================================
// GetGroupUsersWithCheckOperator - //特定のグループに属する全アカウントのアカウント情報を、userIDの昇順で取得する。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID" (必須指定)
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "results":[
// {
// "groupID":"グループID",
// "groupName":"グループ名",
// "userID":"ユーザID",
// "userName":"ユーザ名",
// "property":"プロパティ"
// },
// ・・
// ]
// }
// ============================================================================================================
func GetGroupUsersWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetGroupUsersWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数からgroupIDの取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//証明書の属性検証処理(管理者or同一グループ内のアカウントでないと実行できない)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
グループ内アカウント情報取得
*/
logger.Infof("GetUser")
accountInfoJSONBytes, err := util.GetUser(stub, groupID, "")
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(accountInfoJSONBytes == nil){
errormessage := constants.ERR_INTERNAL + " Users in " +constants.GROUPID + ": " + groupID +" not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
return shim.Success(accountInfoJSONBytes)
}
<file_sep>/Fabric/blocklistener_v1.0/sdk_if.js
/*
* sdk_if.js
* COPYRIGHT Fujitsu Limited 2017 and FUJITSU LABORATORIES LTD. 2017
*/
/* 概要:
* fabric v1.0のinvoke,queryリクエスト用のライブラリ
*
* エントリポイント:
* 無し(libのため)
*/
//var CoreAPIUtil = require('../CoreAPIUtil.js');
// 基本パッケージの依存宣言
var path = require('path');
var fs = require('fs');
var util = require('util');
var process = require('process');
// fabric-clientの依存宣言
var fclient = require('fabric-client');
var utils = require('fabric-client/lib/utils.js');
var Peer = require('fabric-client/lib/Peer.js');
var Orderer = require('fabric-client/lib/Orderer.js');
var User = require('fabric-client/lib/User.js');
var EventHub = require('fabric-client/lib/EventHub.js');
// fabric-ca-clientの依存宣言
var copService = require('fabric-ca-client/lib/FabricCAClientImpl.js');
// ログの設定
var logger = utils.getLogger('sdk_if[' + process.pid + ']');
// fabric-clientオブジェクトのリスト
var clients = {}
/**
* invokeRequest: fabric v1.0のチェーンコードにinvoke命令
* @param {string} chainId: チェーンID(例: "ConnectionChain")※不要になった
* @param {JSON} network: チェーンネットワーク情報(以下の形式)
* JSON: {
* "orderer": (string)ordererのURL, // 例: "grpc://localhost:7050"
* "ca" {
* "url": (string)caのURL, // 例: "http://localhost:7054",
* "name": (string)caの名前(yamlファイルのFABRIC_CA_SERVER_CA_NAMEで指定した値)
* },
* "mspid": (string)peersが属する組織のMSPID, // 例: "Org1MSP"
* "peers": []{
* "requests": (string)リクエスト用のURL, // 例: "grpc://localhost:7051"
* "events": (string)イベント待受用のURL, // 例: "grpc://localhost:7053"
* },
* "submitter": {
* "name": (string)操作ユーザの名前, // 例: "admin"
* "secret": (string)操作ユーザのパスワード // 例: "<PASSWORD>"
* }
* }
* @param {string} channelName: チャンネル名(例: "mychannel")
* @param {string} chaincodeID: チェーンコード名(例: "transfer_informations")
* @param {string} func: invoke関数名(例: "deleteECInfo")
* @param {[]string} args: invoke引数(例: "['Chain1']")
* @param {bool} isWait: ブロック生成まで待つかどうか
**/
function invokeRequest(chainId, network, channelName, chaincodeID, func, args, isWait) {
var tx_id = null;
var nonce = null;
var the_user = null;
var eventhubs = [];
var invokeResponse = {uuid:null, data:null};
return new Promise((resolve, reject) => {
var channel = null;
var client = null;
getClientAndChannel(channelName, network)
.then((retObj) => {
channel = retObj.channel;
client = retObj.client;
return getSubmitter(network.submitter, client, network.mspid, network.ca);
})
.then((admin) => {
// Enrollに成功したUserオブジェクトを設定する
the_user = admin; // 使用していない?→client内でUserContextとして吸収している模様
// EPへのEventHubコネクションを張る
for (var i = 0; i < network.peers.length; i++) {
var eh = client.newEventHub();
eh.setPeerAddr(network.peers[i].events);
eh.connect();
eventhubs.push(eh);
}
return channel.initialize();
}).then((nothing) => {
// Invoke実行用の要求オブジェクトを生成する
tx_id = client.newTransactionID();
invokeResponse.uuid = tx_id.getTransactionID();
var request = {
chaincodeId : chaincodeID,
fcn: func,
args: args,
txId: tx_id
};
// Proposal実行
logger.info('sendTransactionProposal start, txid=' + tx_id.getTransactionID());
return channel.sendTransactionProposal(request);
})
.then((results) => {
logger.info('sendTransactionProposal end');
// EPから返されたProposal応答が成功しているかチェック
var proposalResponses = results[0];
var proposal = results[1];
var header = results[2];
var all_good = true;
var resStr = ''; // 戻り値ありのinvoke関数結果格納用
for(var i in proposalResponses) {
let one_good = false;
if (proposalResponses && proposalResponses[i].response && proposalResponses[i].response.status === 200) {
if (proposalResponses[i].response.payload) {
resStr = new String(proposalResponses[i].response.payload);
invokeResponse.data = resStr;
}
one_good = true;
logger.info('transaction proposal was good');
} else {
logger.error('transaction proposal was bad');
}
all_good = all_good & one_good;
}
if (all_good) {
// EventHubからのトランザクションイベントを待機する
var invokeId = tx_id.getTransactionID();
var cnt = 0;
eventhubs.forEach((eh) => {
eh.registerTxEvent(invokeId.toString(), (tx, code) => {
eh.unregisterTxEvent(invokeId);
if (code !== 'VALID') {
logger.error('Transaction Commited Failure, code = ' + code + ', ' + eh.getPeerAddr() + ', tx_id=' + invokeId);
} else {
logger.info('Transaction Commited, ' + eh.getPeerAddr() + ', tx_id=' + invokeId);
}
// EventHubサーバから切断
if (eh.isconnected()) {
logger.info('Disconnecting the event hub');
eh.disconnect();
}
// ブロック生成を待つ場合、EventHubからのトランザクションイベントが全て揃ったらresolve
cnt++;
if (cnt == eventhubs.length && isWait) {
return resolve(invokeResponse);
}
});
});
// Ordering ServiceにsendTransactionする
var request = {
proposalResponses: proposalResponses,
proposal: proposal,
header: header
};
logger.info('sendTransaction(to Orderer) start');
return channel.sendTransaction(request)
.then((response) => {
if (response.status === 'SUCCESS') {
logger.info('sendTransaction(to Orderer) end');
if (!isWait) {
// ブロック生成を待たない場合はここでresolve
return resolve(invokeResponse);
}
} else {
throw new Error('Failed to order the transaction. Error code: ' + response.status);
}
});
} else {
// チェーンコード自体がエラーを返した場合はここに来る
// queryと違い、チェーンコードからのエラーメッセージは取得できない模様。要ログ参照
throw new Error('Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...');
}
})
.catch((err) => {
eventhubs.forEach((eh) => {
// EventHubサーバから切断
if (eh.isconnected()) {
logger.info('Disconnecting the event hub');
eh.disconnect();
}
});
return reject(err);
});
});
}
/**
* queryRequest: fabric v1.0のチェーンコードにquery命令
* @param {string} chainId: チェーンID(例: "ConnectionChain")※不要になった
* @param {JSON} network: チェーンネットワーク情報(以下の形式)
* JSON: {
* "orderer": (string)ordererのURL, // 例: "grpc://localhost:7050"
* "ca" {
* "url": (string)caのURL, // 例: "http://localhost:7054",
* "name": (string)caの名前(yamlファイルのFABRIC_CA_SERVER_CA_NAMEで指定した値)
* },
* "mspid": (string)peersが属する組織のMSPID, // 例: "Org1MSP"
* "peers": []{
* "requests": (string)リクエスト用のURL, // 例: "grpc://localhost:7051"
* "events": (string)イベント待受用のURL, // 例: "grpc://localhost:7053" ※queryでは使用しない
* },
* "submitter": {
* "name": (string)操作ユーザの名前, // 例: "admin"
* "secret": (string)操作ユーザのパスワード // 例: "<PASSWORD>"
* }
* }
* @param {string} channelName: チャンネル名(例: "mychannel")
* @param {string} chaincodeID: チェーンコード名(例: "transfer_informations")
* @param {string} func: query関数名(例: "getRuleInfoList")
* @param {[]string} args: query引数(例: "['', '']")
**/
function queryRequest(chainId, network, channelName, chaincodeID, func, args) {
var tx_id = null;
var nonce = null;
var the_user = null;
return new Promise((resolve, reject) => {
var channel = null;
var client = null;
getClientAndChannel(channelName, network)
.then((retObj) => {
channel = retObj.channel;
client = retObj.client
return getSubmitter(network.submitter, client, network.mspid, network.ca);
})
.then((admin) => {
// Enrollに成功したUserオブジェクトを設定する
the_user = admin;
return channel.initialize();
}).then((nothing) => {
// Query実行用の要求オブジェクトを生成する
tx_id = client.newTransactionID();
var request = {
chaincodeId : chaincodeID,
fcn: func,
args: args,
txId: tx_id
};
// Query実行
logger.info('queryByChaincode start, txid=' + tx_id.getTransactionID());
return channel.queryByChaincode(request);
})
.then((response_payloads) => {
logger.info('queryByChaincode end');
if (response_payloads) {
var resStr = '';
var errMsg = '';
var valid = false;
for(let i = 0; i < response_payloads.length; i++) {
resStr = new String(response_payloads[i]);
// チェーンコード自体がエラーを返した場合はエラーメッセージが格納されている
// 接続失敗等もSDKからのエラーメッセージ(Error: Connect Failed)
if (resStr.indexOf('Error:') == 0){
errMsg = resStr;
} else {
valid = true;
break;
}
}
if (valid) {
// 1つでも正常な結果が得られていればそれを返す
return resolve(resStr);
} else {
// 全EPからのレスポンスがエラーの場合
throw new Error(errMsg);
}
} else {
throw new Error('response_payloads is null');
}
})
.catch((err) => {
return reject(err);
});
});
}
// 上記関数をexportsする(外部ライブラリとして,他の関数が参照可能とする)
exports.invokeRequest = function(chainId, network, channelName, chaincodeID, func, args) {
// CCでは常にブロック生成を待たない
return invokeRequest(chainId, network, channelName, chaincodeID, func, args, false);
}
exports.queryRequest = function(chainId, network, channelName, chaincodeID, func, args) {
return queryRequest(chainId, network, channelName, chaincodeID, func, args);
}
// fabric-clientオブジェクトとChannelオブジェクト生成
function getClientAndChannel(channelName, network) {
var retObj = {client:null, channel:null};
// clientに1つしかKVSを設定できないので、KVSのパスと同様にCA単位での管理
var isNewClient = false;
var client = clients[network.ca.name];
if (!client) {
logger.info('create new fabric-client');
client = new fclient();
clients[network.ca.name] = client;
isNewClient = true;
}
var channel = null;
// ※v1.0SDKのgetChannelは存在しない場合にnullではなく例外を返してくるのでtry~catch
// そのため初回は必ずClient.jsからのエラーがログ出力されてしまうが実害はない
try {
channel = client.getChannel(channelName);
// channelに設定してある現在のpeer、ordererが今回指定された接続先情報と異なる場合は差分反映
// TODO: おそらくこれでいけるとは思うが変更時の動作未確認
var oldPeers = channel.getPeers();
var oldPeerUrls = [];
for (var i = 0; i < oldPeers.length; i++) {
oldPeerUrls[i] = oldPeers[i].getUrl();
}
var newPeerUrls = [];
for (var i = 0; i < network.peers.length; i++) {
newPeerUrls[i] = network.peers[i].requests;
}
// old, newの順で結合配列を作成
var allPeerUrls = [...oldPeerUrls, ...newPeerUrls];
for (var [i, e] of allPeerUrls.entries()) {
if(!oldPeerUrls.includes(e)) {
// 現在のpeersに含まれていないので追加
var newPeer = client.newPeer(e);
channel.addPeer(newPeer);
}
if(!newPeerUrls.includes(e)) {
// 今回指定されたpeersに含まれていないので削除
channel.removePeer(oldPeers[i]);
}
}
// ordererは現状1件だけの指定にしているので、異なる場合は置き換え
var oldOrderer = channel.getOrderers();
var newOrderer = network.orderer;
if (oldOrderer[0].getUrl() != newOrderer) {
channel.removeOrderer(oldOrderer[0]);
channel.addOrderer(client.newOrderer(newOrderer));
}
}catch(e) {
if(channel == null) {
logger.info('create new channel, name=' + channelName);
channel = client.newChannel(channelName);
// ordererの設定
channel.addOrderer(client.newOrderer(network.orderer));
// EPの設定
for (var i = 0; i < network.peers.length; i++) {
var peer = client.newPeer(network.peers[i].requests);
channel.addPeer(peer);
}
} else {
// 接続先情報差分反映時の例外
logger.error(e);
}
}
retObj.channel = channel;
return new Promise((resolve, reject) => {
if (isNewClient) {
var storePath = '/tmp/kvs-' + network.ca.name;
var cryptoSuite = fclient.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(
fclient.newCryptoKeyStore({
path: storePath
})
);
client.setCryptoSuite(cryptoSuite);
// Enrollment情報の格納先を生成する
return fclient.newDefaultKeyValueStore({
path: storePath
})
.then((store) => {
// KeyValueストアを設定
client.setStateStore(store);
retObj.client = client;
resolve(retObj);
})
} else {
retObj.client = client;
resolve(retObj);
}
});
}
// fabric-clientオブジェクト生成
function getClient(network) {
// clientに1つしかKVSを設定できないので、KVSのパスと同様にCA単位での管理
var isNewClient = false;
var client = clients[network.ca.name];
if (!client) {
logger.info('create new fabric-client');
client = new fclient();
clients[network.ca.name] = client;
isNewClient = true;
}
return new Promise((resolve, reject) => {
if (isNewClient) {
var storePath = '/tmp/kvs-' + network.ca.name;
var cryptoSuite = fclient.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(
fclient.newCryptoKeyStore({
path: storePath
})
);
client.setCryptoSuite(cryptoSuite);
// Enrollment情報の格納先を生成する
return fclient.newDefaultKeyValueStore({
path: storePath
})
.then((store) => {
// KeyValueストアを設定
client.setStateStore(store);
resolve(client);
})
} else {
resolve(client);
}
});
}
// EPへのProposal送信を行うユーザオブジェクトを取得する
// ※setUserContextで設定したものをclient内部で使用するので
// 返却するユーザオブジェクト自体は特に使用しなくなった。
function getSubmitter(submitter, cli, mspID, ca) {
var caUrl = ca.url;
var caName = ca.name;
return cli.getUserContext(submitter.name, true)
.then((user) => {
return new Promise((resolve, reject) => {
if (user && user.isEnrolled()) {
return resolve(user);
}
var member = new User(submitter.name);
var cryptoSuite = cli.getCryptoSuite();
if (!cryptoSuite) {
var storePath = '/tmp/kvs-' + caName;
cryptoSuite = fclient.newCryptoSuite();
cryptoSuite.setCryptoKeyStore(
fclient.newCryptoKeyStore({
path: storePath
})
);
cli.setCryptoSuite(cryptoSuite);
}
member.setCryptoSuite(cryptoSuite);
var tlsOptions = {
trustedRoots: [],
verify: false
};
var cop = new copService(caUrl,tlsOptions, caName, cryptoSuite);
return cop.enroll({
enrollmentID: submitter.name,
enrollmentSecret: submitter.secret
}).then((enrollment) => {
return member.setEnrollment(enrollment.key, enrollment.certificate, mspID);
}).then(() => {
return cli.setUserContext(member, false);
}).then(() => {
return resolve(member);
}).catch((err) => {
return reject(err);
});
});
});
}
// 1.0用Monitorクラスから使用するためにexports
exports.getClient = function(network) {
return getClient(network);
}
exports.getSubmitter = function(submitter, cli, mspID, ca) {
return getSubmitter(submitter, cli, mspID, ca);
}
<file_sep>/Fabric/sdktest/registerUser.js
/*
* registerUser.js
* COPYRIGHT FUJITSU LIMITED 2018
*/
/* 概要:
* Fabric-CAにユーザを登録する。
*/
var Fabric_Client = require('fabric-client');
var Fabric_CA_Client = require('fabric-ca-client');
const config = require("./config/default.json");
var path = require('path');
/*
RegisterUser
@param {string} enrollmentID
{string} secret
{string} groupID
{string} userID
{bool} adminの場合、true
@return Promise
*/
exports.RegisterUser = function(enrollmentID, secret, groupID, userID, isAdmin){
var fabric_client = new Fabric_Client();
var fabric_ca_client = null;
var admin_user = null;
//var member_user = null;
var store_path = path.join(__dirname, config.fabric.keystore);
console.log(' Store path:'+store_path);
return new Promise((resolve, reject) => {
// create the key value store as defined in the fabric-client/config/default.json 'key-value-store' setting
Fabric_Client.newDefaultKeyValueStore({ path: store_path
}).then((state_store) => {
// assign the store to the fabric client
fabric_client.setStateStore(state_store);
var crypto_suite = Fabric_Client.newCryptoSuite();
// use the same location for the state store (where the users' certificate are kept)
// and the crypto store (where the users' keys are kept)
var crypto_store = Fabric_Client.newCryptoKeyStore({path: store_path});
crypto_suite.setCryptoKeyStore(crypto_store);
fabric_client.setCryptoSuite(crypto_suite);
var tlsOptions = {
trustedRoots: [],
verify: false
};
// be sure to change the http to https when the CA is running TLS enabled
fabric_ca_client = new Fabric_CA_Client(config.fabric.ca.url, tlsOptions , config.fabric.ca.name, crypto_suite);
// first check to see if the admin is already enrolled
return fabric_client.getUserContext(config.fabric.submitter.name, true);
}).then((user_from_store) => {
if (user_from_store && user_from_store.isEnrolled()) {
console.log('Successfully loaded admin from persistence');
admin_user = user_from_store;
} else {
throw new Error('Failed to get admin.... run enrollAdmin.js');
}
// at this point we should have the admin user
// first need to register the user with the CA server
var admin;
if(isAdmin){
admin = "true";
} else{
admin = "false";
}
return fabric_ca_client.register(
{
enrollmentID: enrollmentID + secret,
enrollmentSecret:secret,
affiliation: 'org1.department1',
role: 'client',
attrs:[{name:"groupID", value:groupID, ecert:true},{name:"userID", value:userID, ecert:true}, {name:"admin", value:admin, ecert:true}]
}, admin_user);
}).then((secret) => {
console.log('Successfully registered user - secret:'+ secret);
resolve();
}).catch((err) => {
console.error('Failed to register: ' + err);
if(err.toString().indexOf('Authorization') > -1) {
console.error('Authorization failures may be caused by having admin credentials from a previous CA instance.\n' +
'Try again after deleting the contents of the store directory '+store_path);
}
reject(err);
});
});
};
<file_sep>/Ethereum-collabo/geth-docker/docker-compose.yml
version: "2"
networks:
chainnet:
external: true
services:
geth1:
image: dev/eth1
ports:
- "8545:8545"
- "30300:30300"
container_name: "geth1"
networks:
- chainnet
volumes:
- ./DATA/:/root/work/geth/DATA
- ./eth_private_net/:/root/work/geth
<file_sep>/Fabric/FabricRestServer1.0/build.gradle
/*
* This build file was auto generated by running the Gradle 'init' task
* by 'li.hangyu' at '17/07/20 18:05' with Gradle 2.13
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/2.13/userguide/tutorial_java_projects.html
*/
// Apply the java plugin to add support for Java
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'maven'
// In this section you declare where to find the dependencies of your project
repositories {
// Use 'jcenter' for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
maven { url "http://repo.maven.apache.org/maven2" }
}
// In this section you declare the dependencies for your production and test code
dependencies {
// The production code uses the SLF4J logging API at compile time
compile 'org.slf4j:slf4j-api:1.7.21'
// https://mvnrepository.com/artifact/org.glassfish.jersey.containers/jersey-container-servlet
compile group: 'org.glassfish.jersey.containers', name: 'jersey-container-servlet', version: '2.25'
// https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-client
compile group: 'org.glassfish.jersey.core', name: 'jersey-client', version: '2.25'
// https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-json-jackson
compile group: 'org.glassfish.jersey.media', name: 'jersey-media-json-jackson', version: '2.25'
// https://mvnrepository.com/artifact/org.projectlombok/lombok
compile group: 'org.projectlombok', name: 'lombok', version: '1.16.12'
// https://mvnrepository.com/artifact/org.hyperledger.fabric-sdk-java/fabric-sdk-java
compile group: 'org.hyperledger.fabric-sdk-java', name: 'fabric-sdk-java', version: '1.2.2'
compile files('libs/RestJsonObjectFabric1.0.jar')
providedCompile 'javax:javaee-api:7.0'
// https://mvnrepository.com/artifact/io.grpc/grpc-netty
compile group: 'io.grpc', name: 'grpc-netty', version: '1.13.2'
// https://mvnrepository.com/artifact/io.grpc/grpc-protobuf
compile group: 'io.grpc', name: 'grpc-protobuf', version: '1.13.2'
// https://mvnrepository.com/artifact/io.grpc/grpc-stub
compile group: 'io.grpc', name: 'grpc-stub', version: '1.13.2'
// https://mvnrepository.com/artifact/io.netty/netty-codec-http2
compile group: 'io.netty', name: 'netty-codec-http2', version: '4.1.26.Final'
// compile group: 'io.netty', name: 'netty-codec-http2', version: '4.1.13.Final'
// https://mvnrepository.com/artifact/io.netty/netty-tcnative-boringssl-static
compile group: 'io.netty', name: 'netty-tcnative-boringssl-static', version: '2.0.10.Final'
//compile group: 'io.netty', name: 'netty-tcnative-boringssl-static', version: '2.0.5.Final'
// https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java
compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.6.0'
compile group: 'com.google.protobuf', name: 'protobuf-java-util', version: '3.6.0'
// https://mvnrepository.com/artifact/org.bouncycastle/bcpkix-jdk15on
compile group: 'org.bouncycastle', name: 'bcpkix-jdk15on', version: '1.60'
// https://mvnrepository.com/artifact/commons-logging/commons-logging
compile group: 'commons-logging', name: 'commons-logging', version: '1.2'
// https://mvnrepository.com/artifact/commons-cli/commons-cli
compile group: 'commons-cli', name: 'commons-cli', version: '1.4'
// https://mvnrepository.com/artifact/org.apache.commons/commons-compress
compile group: 'org.apache.commons', name: 'commons-compress', version: '1.17'
// https://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.6'
// https://mvnrepository.com/artifact/log4j/log4j
compile group: 'log4j', name: 'log4j', version: '1.2.17'
compile group: 'log4j', name: 'apache-log4j-extras', version: '1.2.17'
// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.2'
// https://mvnrepository.com/artifact/org.glassfish/javax.json
compile group: 'org.glassfish', name: 'javax.json', version: '1.1.2'
// https://mvnrepository.com/artifact/org.yaml/snakeyaml
compile group: 'org.yaml', name: 'snakeyaml', version: '1.21'
compile group: 'org.jacoco', name: 'jacoco-maven-plugin', version:'0.7.9'
// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
// testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
// 'test.useTestNG()' to your build script.
testCompile 'junit:junit:4.12'
}
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}<file_sep>/Ethereum-collabo/geth-docker/sample_web3/send_transaction.js
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
var fromaccount = web3.eth.accounts[1];
var toaccount = web3.eth.accounts[2];
var amount = 10;
web3.personal.unlockAccount(fromaccount, "test");
var result = web3.eth.sendTransaction({from:fromaccount, to:toaccount, value:amount},(error, result) => {
console.log(result);
});
<file_sep>/Ethereum-collabo/geth-docker/eth_private_net/attachconsole.sh
geth --datadir ./DATA attach ipc:./DATA/geth.ipc
<file_sep>/Fabric/blocklistener_v1.2/EventMonitor.js
/* 概要:
* fabric v1.2のブロック生成イベント監視
*/
// 基本パッケージの依存宣言
var process = require('process');
// fabric-clientの依存宣言
var sdk = require('./sdk_if.js');
var utils = require('fabric-client/lib/utils.js');
//var Peer = require('fabric-client/lib/Peer.js');
//var ChannelEventHub = require('fabric-client/lib/ChannelEventHub.js');
// ログの設定
var logger = utils.getLogger('EventMonitor[' + process.pid + ']');
var EventMonitor = class {
constructor(chainId, network) {
this._id = chainId;
this._network = network;
this._eh = null;
}
start() {
var network = this._network;
var cli = null;
var channel = null;
sdk.getClientAndChannel(network.channelName, network) //getClientAndChannelに置き換え
.then((retobj) => {
channel = retobj.channel; //返却されたchannelをset
cli = retobj.client;
return sdk.getSubmitter(network.submitter, retobj.client, network.mspid, network.ca)
})
.then((submitter) => {
var peer = cli.newPeer(network.peers[0].requests); //下と一緒
//var peer = new Peer(network.peers[0].requests); //eventポートは使用しない
this._eh = channel.newChannelEventHub(peer); //下と一緒
//this._eh = new ChannelEventHub(channel, peer);
this._eh.registerBlockEvent(
(block) => {
logger.info('*** Block Event ***');
logger.info('chain id :' + this._id);
logger.info("blocknumber : " + block.header.number);
var len = block.data.data.length;
logger.info('data.data.length :' + len);
for (var i = 0; i < len; i++) {
//デコード不要。直接参照できるようになった
var payload = block.data.data[i].payload;
var channel_header = payload.header.channel_header;
if (channel_header.type == 3) { //'ENDORSER_TRANSACTION'はtype 3に対応するtypeStringとなった。
var txid = channel_header.tx_id;
logger.info('transaction id :' + txid);
var transaction = payload.data;
var actionPayload = transaction.actions[0].payload;
var proposalPayload = actionPayload.chaincode_proposal_payload;
var invocationSpec = proposalPayload.input;
// チェーンコード名と引数リスト(先頭が関数名)をinvocationSpecから取得できる
var ccid = invocationSpec.chaincode_spec.chaincode_id.name;
logger.info('chaincode id :' + ccid);
var args = invocationSpec.chaincode_spec.input.args;
logger.info('args.length :' + args.length);
for (var j = 0; j < args.length; j++) {
// toStringはコード指定必須
args[j] = args[j].toString('utf8');
logger.info('args[' + j + '] :' + args[j]);
}
// 応答の解釈
var resp = actionPayload.action.proposal_response_payload.extension.response.payload;
logger.info('resp :' + resp);
// 後続処理の実行要求
}
}
},
(err) => {
console.log('error: ' + err);
},
{ //参照するブロック番号の範囲を指定
startBlock: network.fetchblock.start,
endBlock: network.fetchblock.end
}
);
this._eh.connect(true); //fullBlock = true
})
.catch((err) => {
logger.error(err);
});
}
end() {
if (this._eh == null) {
logger.error('EventHub does not exist');
return;
}
if (this._eh.isconnected()) {
logger.info('Disconnecting the event hub');
this._eh.disconnect();
}
}
};
module.exports = EventMonitor;
<file_sep>/Fabric/blocklistener_v1.0/README.md
# Fabric v1.0.x blocklistener
EventHubを利用してトランザクションを監視するためのモジュール。
## 使い方
* 前提
Fabric v1.0.x、node.js(v6.9.x)がインストールされていること。
1. npm install
blocklistener_v1.0ファイルをVM上の任意のパスに配備し、依存パッケージをインストールする。
~~~
$ npm install fabric-client
$ npm install fabric-ca-client
~~~
2. 起動
configファイルの設定を環境に合わせて変更する。設定値は以下参照。
~~~
{
"fabric":{
"mspid": <MSPのID 例:"Org1MSP">,
"peers":[
{
"requests": <peerのアドレス 例:"grpc://localhost:7051">,
"events": <指定の必要なし。 例:"grpc://localhost:7053">
}
],
"orderer":<ordererのアドレス 例:"grpc://localhost:7050">,
"channelName":<チャネル名 例:"mychannel">,
"ca":{
"name":<fabric-caの名前 例:"ca.example.com">,
"url":"<fabric-caのURL 例:http://localhost:7054">
},
"submitter":{
"name":<エンロールユーザー名 例:"admin">,
"secret":<エンロールユーザーのパス 例:"adminpw">
},
"chaincodeId":<チェーンコードID。指定の必要なし。 例:"smartwallet">
},
"chainId":<チェーンID 例:"test">
}
~~~
起動は以下コマンド
~~~
$ node MonitorManager.js
~~~<file_sep>/Ethereum-collabo/connector/src/bin/www.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
//var debug = require('debug')('ethereum_collabo_server:server');
var http = require('http');
//var fs = require('fs');
//var https = require('https');
var server = http.createServer(app);
var io = require('socket.io')(server);
//var Web3 = require('web3');
var conf = require('../config/default.json');
// Ethereumへの実行要求ライブラリ
var EthereumSplug = require('../lib/eth_smartwallet.js');
/**
* Get port from environment and store in Express.
*/
/*
var sslport = normalizePort(process.env.PORT || config.sslport);
app.set('port', sslport);
*/
// �閧���Əؖ����̎w��
/*
var sslParam = {
key: fs.readFileSync(config.sslParam.key),
cert: fs.readFileSync(config.sslParam.cert)
};
*/
/**
* Create HTTPS server.
*/
/*
var httpsserver = https.createServer(sslParam, app); // https�T�[�o�Ƃ��ċN������B
*/
/**
* Listen on provided port, on all network interfaces.
*/
/*
httpsserver.listen(sslport);
httpsserver.on('error', onError);
httpsserver.on('listening', onListening);
*/
/**
* Normalize a port into a number, string, or false.
*/
/*
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
*/
/**
* Event listener for HTTPS server "error" event.
*/
/*
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof sslport === 'string'
? 'Pipe ' + sslport
: 'Port ' + sslport;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
*/
/**
* Event listener for HTTPS server "listening" event.
*/
/*
function onListening() {
var addr = httpsserver.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
*/
/*
socket.io サーバー
*/
var ioPort = conf.socket.port;
var filterTable = {};
io.on('connection', function(client) {
console.log('Client ' + client.id + ' connected.');
/**
* request: web3.ethの関数実行要求待ち受け
* @param {JSON} data: リクエストボディ(以下の形式)
* JSON: {
* "func": (string)関数名, // 例: "transferNumericAsset"
* "args": ([]Object)引数 // 例: [{"from":"xxx", "to":"yyy", "value":"10000"}]
* }
* @param cb: レスポンス用コールバック関数
**/
// client.on('request', function(data) {
client.on('request', function(data, cb) {
var url = conf.nodeaddress;
var supplied = conf.adminaccount.address;
var pass = conf.adminaccount.pass;
var gasconsume = conf.gasconsume;
var gasprice = conf.gasprice;
var func = data.func;
var args = data.args;
console.log('*** REQUEST ***');
console.log('Client ID :' + client.id);
console.log('Data :' + JSON.stringify(data));
var ret_obj = {};
var Splug = new EthereumSplug(url, supplied, pass, gasconsume, gasprice);
if (Splug.isExistFunction(func)) {
ret_obj = Splug[func](args);
console.log('*** RESPONSE ***');
console.log('Client ID :' + client.id);
console.log('Response :' + JSON.stringify(ret_obj));
} else {
var emsg = "Function " + func + " not found!";
console.log(emsg);
ret_obj = {
"status" : 504,
"errorDetail" : emsg
};
}
/*
var emit_type = "";
if(ret_obj.status == 200) {
emit_type = "response";
} else {
emit_type = "error";
}
io.to(client.id).emit(emit_type, ret_obj);
*/
cb(ret_obj);
});
client.on('disconnect', function(reason) {
console.log('Client ' + client.id + ' disconnected.');
console.log('Reason :' + reason);
var filter = filterTable[client.id];
if (filter) {
console.log('stop watching and remove filter.');
filter.stopWatching();
delete filterTable[client.id];
}
});
});
server.listen(ioPort, function(){
console.log('listening on *:' + ioPort);
});
/*
REST サーバー
*/
//サーバーのポート番号
const PORT = conf.api.port;
// サーバをlisten
var server = app.listen(PORT, function(){
console.log("Node.js is listening to PORT:" + server.address().port);
});
<file_sep>/Ethereum-collabo/geth-docker/build/Dockerfile
FROM ethereum/client-go:latest
RUN mkdir -p /root/work/geth/DATA
#COPY eth_private_net1/customGenesis.json /root/work/geth/DATA
#COPY eth_private_net1/start_geth.sh /root/work/geth
#COPY eth_private_net1/attachconsole.sh /root/work/geth
#RUN chmod +x /root/work/geth/start_geth.sh
#RUN chmod +x /root/work/geth/attachconsole.sh
WORKDIR /root/work
<file_sep>/Fabric/sdktest/secure_token_manager/lib/wallet/wallet.go
/*
* wallet.go
* secure_token_manager(wallet management)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package wallet
import (
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/secure_token_manager/lib/constants"
"errors"
"time"
"strconv"
"github.com/secure_token_manager/lib/util"
)
const (
LOGGER_NAME = "secure_token_manager_wallet"
)
// ==============================================================================================
// CreateWalletWithCheckOperator - デフォルトウォレット以外の作成
// 実行ユーザの認証とアカウントの存在確認を行う。
// IF詳細はcreateWallet関数参照
// ==============================================================================================
func CreateWalletWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("CreateWalletWithChackOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args[0]) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//証明書の属性を検証 ⇒管理者または実行ユーザでなければエラー
if(!util.IsAdmin(stub)){
if(!util.VerifyUser(stub, groupID, userID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin can create other account wallet"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
//引数チェックはcreateWalletでおこなう。
logger.Infof("createWallet")
resvalBytes, err := createWallet(stub, args[0])
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
// ==============================================================================================
// CreateDefaultWallet - デフォルトウォレットの作成(内部関数)
// CreateAccountの内部で呼び出す。実行ユーザの認証(CreateAccountの最初に実施)とアカウントの存在確認を飛ばす。
// IF詳細はcreateWallet関数参照
// ==============================================================================================
/*
func CreateDefaultWallet(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("CreateDefaultWallet")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
return nil, errors.New(errormessage)
}
isDefault := true
logger.Infof("createWallet")
resvalBytes, err := createWallet(stub, args[0],isDefault)
if(err != nil){
return nil, err
}
return resvalBytes, nil
}
*/
// ===================================================================================================
// createWallet- ウォレットを新規に作成する。(内部関数)
// @param {string} args :以下のJSON文字列
// {
// "groupID":"グループID", (必須指定)
// "userID":"ユーザID", (必須指定)
// "tokenID":"トークンID", (必須指定)
// "quantity":"トークン初期値",
// "property":"プロパティ",
// "timestamp":"タイムスタンプ"
// }
//
// @return pb.Response 以下のJSON文字列を含む
// {
// "groupID":"グループID", (必須指定)
// "userID":"ユーザID", (必須指定)
// "tokenID":"トークンID", (必須指定)
// "quantity":"トークン初期値",
// "property":"プロパティ",
// "lastUpdated":"最終更新日時",
// "txID":"トランザクションID"
// }
// ====================================================================================================
func createWallet(stub shim.ChaincodeStubInterface, args string) ([]byte, error) {
//ウォレット作成返却値
type CreateWallet_Return struct{
GroupID string `json:"groupID"` //グループID(任意の文字列)
UserID string `json:"userID"` //ユーザID(任意の文字列)
TokenID string `json:"tokenID"` //トークンID(任意の文字列)
Quantity string `json:"quantity"` //トークン残高
Property string `json:"property"` //プロパティ
LastUpdated string `json:"lastUpdated"` //最終更新日時
TxID string `json:"txID"` //トランザクションID
}
//引数をmap型変数にparse
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//map型変数から各引数の取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
tokenID, argserr := argsmap[constants.TOKENID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOKENID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
quantity, _ := argsmap[constants.QUANTITY].(string)
if(quantity == ""){
quantity = "0"
} else{
_, err := strconv.ParseFloat(quantity, constants.BIT_SIZE)
if(err != nil){
errormessage := constants.ERR_INCORRECTFORMAT + constants.QUANTITY + " format is invalid."
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
}
property, _ := argsmap[constants.PROPERTY].(string)
timestamp, _ := argsmap[constants.TIMESTAMP].(string)
if(timestamp != ""){
_, err := time.Parse(constants.DATETIME_FORMAT, timestamp)
if(err != nil){
errormessage := constants.ERR_INCORRECTFORMAT + constants.TIMESTAMP + " format is invalid."
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
}
//アカウントの存在チェック
accountInfoJSONBytes, err := util.GetUser(stub, groupID, userID)
if(err != nil){
return nil, err
} else if(accountInfoJSONBytes == nil){
errormessage := constants.ERR_INTERNAL + " User " + "(" +constants.GROUPID + ": " + groupID + " and " + constants.USERID +": " + userID + ")" + " not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return nil, errors.New(errorstr)
}
/*
ウォレット情報登録
*/
params := []string{groupID, userID, tokenID, quantity, property, timestamp}
err = util.UpdateWallet(stub, params)
if(err != nil){
return nil, err
}
//txIDを取得
txID:= stub.GetTxID()
//返却値の設定
returnval := &CreateWallet_Return{
UserID: userID, //ユーザID
GroupID: groupID, //グループID
TokenID: tokenID, //トークンID
Quantity: quantity, //トークン初期値
Property: property, //プロパティ
LastUpdated:timestamp, //最終更新日時
TxID: txID}
returnvalJSONBytes, err := json.Marshal(returnval)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
return returnvalJSONBytes, nil
}
// ====================================================================================================
// GetSingleUserWalletWithCheckOperator - 単一アカウントのウォレット情報を取得する。実行ユーザの検証をする。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID",
// "userID":"ユーザID",
// "tokenID":"トークンID",
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "results":[{
// "groupID":"グループID",
// "userID":"ユーザID",
// "wallets":[{
// "tokenID":"トークンID",
// "quantity":"トークン残高",
// "property":"プロパティ",
// "lastUpdated":"最終更新日時"
// },・・
// ]
// }]
// }
// ===================================================================================================
func GetSingleUserWalletWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetSingleUserWalletWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数から各引数の取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
tokenID, _ := argsmap[constants.TOKENID].(string)
//証明書の属性検証処理(管理者or同一グループ内のアカウントでないと実行できない)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
//ウォレット情報の取得(単一アカウント)
logger.Infof("GetWallet")
groupwalletinfoarray, err := util.GetWallet(stub, groupID, userID, tokenID)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(len(groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallet " + "(" +constants.GROUPID + ": " + groupID + " , " + constants.USERID +": " + userID + " , " + constants.TOKENID +": " + tokenID + ")" + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
walletInfoJSONBytes, err := json.Marshal(groupwalletinfoarray)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
return shim.Success(walletInfoJSONBytes)
}
// ==================================================================================================================
// GetGroupUsersWalletWithCheckOperator - 特定のグループに属する全アカウントのウォレット情報を、userIDの昇順で取得する。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID" (必須指定)
// "tokenID":"トークンID"
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "results":[{
// "groupID":"グループID",
// "userID":"ユーザID",
// "wallets":[{
// "tokenID":"トークンID",
// "quantity":"トークン残高",
// "property":"プロパティ",
// "lastUpdated":"最終更新日時"
// },・・
// ]
// },・・
// ]
// }
// =================================================================================================================
func GetGroupUsersWalletWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetGroupUsersWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数からgroupIDの取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
tokenID, _ := argsmap[constants.TOKENID].(string)
//証明書の属性検証処理(管理者or同一グループ内のアカウントでないと実行できない)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
グループ内ウォレット情報取得
*/
logger.Infof("GetWallet")
groupwalletinfoarray, err := util.GetWallet(stub, groupID, "", tokenID)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(len(groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallets in " + constants.GROUPID + ": " + groupID + " , " + constants.TOKENID +": " + tokenID + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
walletInfoJSONBytes, err := json.Marshal(groupwalletinfoarray)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
return shim.Success(walletInfoJSONBytes)
}
// ===================================================================================================================
// GetGroupWalletWithCheckOperator - 特定のグループのウォレット情報(グループ内全アカウントのトークン残高総和)を取得する。
// @param {[]string} args :query実行時引数
// args[0]: 以下のJSON文字列
// {
// "groupID":"グループID" (必須指定)
// "tokenID":"トークンID"
// }
// @return pb.Response 以下のJSON文字列を含む
// {
// "groupID":"グループID",
// "wallets":[{
// "tokenID":"トークンID",
// "quantity":"トークン残高"
// },・・
// ]
// }
// ===================================================================================================================
func GetGroupWalletWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response{
//ウォレット情報(返却用)
type Wallets struct{
TokenID string `json:"tokenID"`
Quantity string `json:"quantity"`
}
//グループウォレット情報(返却用)
type WalletInfoArray struct {
GroupID string `json:"groupID"`
Wallets []Wallets `json:"wallets"`
}
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("GetGroupWalletWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse
argsJSON := args[0]
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(argsJSON) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//map型変数からgroupIDの取得
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
tokenID, _ := argsmap[constants.TOKENID].(string)
//証明書の属性検証処理(管理者or同一グループ内のアカウントでないと実行できない)
if(!util.IsAdmin(stub)){
if(!util.SameGroupUser(stub, groupID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin and Same Group Users can see other Account Info"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
/*
グループ内ウォレット情報(ユーザ単位)取得
*/
logger.Infof("GetWallet")
groupwalletinfoarray, err := util.GetWallet(stub, groupID, "", tokenID)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
} else if(len(groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallets in " + constants.GROUPID + ": " + groupID + " , " + constants.TOKENID +": " + tokenID + " not exists."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return shim.Error(errorstr)
}
//グループ内のトークン残高足しあげ
walletInfoArray := WalletInfoArray{}
walletInfoArray.GroupID = groupID
tmp := []Wallets{} //グループ全体の残高管理用ウォレット
for _, userwallets := range groupwalletinfoarray.Results { //ユーザーの数だけループ
//単一ユーザの各トークンについて、残高を足しあげる
for _, wallet := range userwallets.Wallets {
//フラグを初期化
flag := false
for i, tmpwallet := range tmp{
//tmpwalletにtokenIDが同じものがあればquantityを足す
if(wallet.TokenID == tmpwallet.TokenID){
//見つかったフラグを立てる
flag = true
//tmpwallet.Quantityにwallet.Quantityを足す
addedval, err := util.AddValue(tmpwallet.Quantity, wallet.Quantity, true)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
tmp[i].Quantity = addedval
}
}
//見つかったフラグがfalseならtmpに新規追加
if(!flag){
tmp = append(tmp, Wallets{TokenID:wallet.TokenID, Quantity: wallet.Quantity})
}
}
}
//最後にtmpをgroupwalletInfoArray.Walletsに代入
walletInfoArray.Wallets = tmp
walletInfoJSONBytes, err := json.Marshal(walletInfoArray)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
return shim.Success(walletInfoJSONBytes)
}
<file_sep>/Ethereum-collabo/connector/src/routes/addInstance.js
//依存ライブラリ
const express = require('express');
const sampleAPIUtil = require('../lib/sampleAPIUtil.js');
const sampleAPIError = require('../lib/sampleAPIError.js');
var Web3 = require('web3');
const eth = require('../lib/ethaccess.js');
const fabric = require('../lib/fabricaccess.js');
const conf = require('../config/default.json');
var router = express.Router();
//
// アセット登録
// req:{
// "accountID":<登録先アドレス(Fabricの場合、name)>,
// "value":<金額(eth)>,
// "ChainType":<"Fabric" or "Ethereum">
// }
// res : {
// "status": <HTTPステータス>,
// "txid":<トランザクションID>
// }
//
router.post('/', function(req, res, next){
if (!sampleAPIUtil.isValidContentType(req)) {
next(new sampleAPIError(400, 2000));
return;
}
//パラメータチェック
var accountID = req.body.accountID;
if ( accountID == undefined ) {
next(new sampleAPIError(422, 2101));
return;
}
var value = req.body.value;
if ( value == undefined ) {
next(new sampleAPIError(422, 2003));
return;
} else if( Number(value) == "NaN" ){
next(new sampleAPIError(422, 3002));
return;
} else if( Number(value) < 0 ){ //depositは負の値もいけるが、deleteInstanceがあるのでここではじく。
next(new sampleAPIError(422, 3003));
return;
}
var ChainType = req.body.ChainType;
if ( ChainType != "Fabric" && ChainType != "Ethereum" ) {
next(new sampleAPIError(422, 3001));
return;
}
if(ChainType == "Ethereum"){ //Ethreumの場合
console.log("***addInstance start on Ethereum***");
eth.send(conf.socket.address + conf.socket.port ,
"addInstance",
{"to": accountID, "value": value}
).then((returnvalue) => {
res.header('Content-Type', 'application/json; charset=UTF-8');
res.status(200).send(returnvalue);
}).catch(err => {
next(new sampleAPIError(500, 9000));
});
} else if(ChainType == "Fabric"){ //Fabricの場合
console.log("***addInstance start on Fabric***");
var reqparam = {fcn:"deposit", args:["fujitsu", accountID,"0", value]}; //暫定的にGroupを"fujitsu"固定、AssetID:0をetherに対応づけている。
fabric.Invoke(reqparam, true)
.then((returnvalue) => {
var resval = {status:200, txid: returnvalue}
res.header('Content-Type', 'application/json; charset=UTF-8');
//invoke時returnした値を返却する。
res.status(200).send(resval);
}).catch(err => {
next(new sampleAPIError(500, 9000));
});
}
});
module.exports = router;
<file_sep>/Fabric/sdktest/secure_token_manager/lib/transaction/transaction_invoke.go
/*
* transaction_invoke.go
* secure_token_manager(transaction management)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package transaction
import (
"encoding/json"
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/secure_token_manager/lib/constants"
"errors"
"github.com/secure_token_manager/lib/util"
"github.com/secure_token_manager/lib/table"
)
const (
LOGGER_NAME = "secure_token_manager_transaction"
)
// ==============================================================================================
// DepositTokenWithCheckOperator - トークンの払い出しを行う
// 実行ユーザの認証を行う。(管理者アカウントでない場合、エラー)
// IF詳細はdeposit関数参照
// ==============================================================================================
func DepositTokenWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("DepositTokenWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//管理者でない場合、エラー
if(!util.IsAdmin(stub)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin can deposit"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
logger.Infof("deposit")
txType := constants.TXTYPE_DEPOSIT
resvalBytes, err := deposit(stub, args[0], txType)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
// ==============================================================================================
// WithdrawTokenWithCheckOperator - トークンの消却を行う
// 実行ユーザの認証を行う。(管理者アカウントでない場合、エラー)
// IF詳細はdeposit関数参照
// ==============================================================================================
func WithdrawTokenWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("WithdrawTokenWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//管理者でない場合、エラー
if(!util.IsAdmin(stub)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin can withdraw"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
logger.Infof("deposit")
txType := constants.TXTYPE_WITHDRAW
resvalBytes, err := deposit(stub, args[0], txType)
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
// ==============================================================================================
// TransferTokenWithCheckOperator - トークンの移転を行う
// 実行ユーザの認証を行う。(管理者アカウントまたは、移転元ユーザでない場合、エラー)
// IF詳細はtransfer関数参照
// ==============================================================================================
func TransferTokenWithCheckOperator(stub shim.ChaincodeStubInterface, args []string) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("TransferTokenWithCheckOperator")
//引数の数チェック
if len(args) != 1 {
errormessage := constants.ERR_INVALID_PARAM + " Incorrect number of arguments. Expecting 1"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//引数をmap型変数にparse(実行ユーザ検証のためにここでチェック)
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args[0]) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
fromgroupID, argserr := argsmap[constants.FROMGROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.FROMGROUPID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
fromuserID, argserr := argsmap[constants.FROMUSERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.FROMUSERID + " must be specified"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
//管理者または実行ユーザが移転元でなければエラー
if(!util.IsAdmin(stub)){
if(!util.VerifyUser(stub, fromgroupID, fromuserID)){
errormessage := constants.ERR_NOT_AUTHORIZED + " Only Admin can transfer other account wallet token."
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_NOT_AUTHORIZED, errormessage)
return shim.Error(errorstr)
}
}
logger.Infof("transfer")
resvalBytes, err := transfer(stub, args[0])
if(err != nil){
logger.Error(err.Error())
return shim.Error(err.Error())
}
return shim.Success(resvalBytes)
}
// ===================================================================================================
// deposit - トークンの払出/消却を行う(内部関数)
// @param {string} args: 以下のJSON文字列
// {
// "groupID":"グループID", (必須指定)
// "userID":"ユーザID", (必須指定)
// "tokenID":"トークンID", (必須指定)
// "quantityDelta":"トークン払出/消却値",
// "action":"アクション",
// "timestamp":"タイムスタンプ" (必須指定)
// }
// {string} txType: "deposit" or "withdraw"
//
// @return {[]byte}
// {
// "groupID":"グループID",
// "userID":"ユーザID",
// "tokenID":"トークンID",
// "quantityDelta":"トークン消却/払出値",
// "quantitySnapshot":"トークン累積値",
// "action":"アクション",
// "timestamp":"タイムスタンプ",
// "txID":"トランザクションID"
// }
// {error} エラー
// ====================================================================================================
func deposit(stub shim.ChaincodeStubInterface, args string, txType string) ([]byte, error) {
//返却値用構造体
type Deposit_Return struct{
GroupID string `json:"groupID"` //グループID
UserID string `json:"userID"` //ユーザID
TokenID string `json:"tokenID"` //トークンID
QuantityDelta string `json:"quantityDelta"` //トークン払出/消却量
QuantitySnapshot string `json:"quantitySnapshot"` //トークン累積値
Action string `json:"action"` //プロパティ
Timestamp string `json:"timestamp"` //タイムスタンプ
TxID string `json:"txID"` //トランザクションID
}
//引数をmap型変数にparse
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
groupID, argserr := argsmap[constants.GROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.GROUPID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
userID, argserr := argsmap[constants.USERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.USERID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
tokenID, argserr := argsmap[constants.TOKENID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOKENID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
quantityDelta, argserr := argsmap[constants.QUANTITYDELTA].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.QUANTITYDELTA + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//quantitydeltaが非数値、負の値の場合エラー
isplus, err := util.IsPlusVal(quantityDelta)
if(err != nil){
return nil, err
} else if(!isplus){
errormessage := constants.ERR_INVALID_PARAM + constants.QUANTITYDELTA + " must be larger than 0"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
action, _ := argsmap[constants.ACTION].(string)
timestamp, argserr := argsmap[constants.TIMESTAMP].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TIMESTAMP + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
params := []string{txType, "", "", groupID, userID, tokenID, quantityDelta, action, timestamp}
_, quantitysnapshot, err := move(stub, params)
if(err != nil){
return nil, err
}
//withdrawの場合、"-"を付加
if(txType == constants.TXTYPE_WITHDRAW){
quantityDelta = "-" + quantityDelta
}
//返却値の設定
txID := stub.GetTxID()
returnval := &Deposit_Return{
GroupID: groupID,
UserID: userID,
TokenID: tokenID,
QuantityDelta: quantityDelta,
QuantitySnapshot: quantitysnapshot,
Action: action,
Timestamp:timestamp,
TxID: txID }
returnvalJSONBytes, err := json.Marshal(returnval)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
return returnvalJSONBytes, nil
}
// ===================================================================================================
// transfer - トークンの移転を行う(内部関数)
// @param {string} args: 以下のJSON文字列
// {
// "fromGroupID":"移転元グループID",(必須指定)
// "fromUserID":"移転元ユーザID", (必須指定)
// "toGroupID":"移転先グループID", (必須指定)
// "toUserID":"移転先ユーザID", (必須指定)
// "tokenID":"トークンID", (必須指定)
// "quantityDelta":"トークン移転値",(必須指定)
// "action":"アクション",
// "timestamp":"タイムスタンプ" (必須指定)
// }
// @return {[]byte} 以下のJSON文字列バイト型
// {
// "from":{
// "groupID":"グループID",
// "userID":"ユーザID"
// }
// "to":{
// "groupID":"グループID",
// "userID":"ユーザID"
// }
// "tokenID":"トークンID",
// "quantityDelta":"トークン消却/払出値",
// "quantitySnapshot":"トークン累積値",
// "action":"アクション",
// "timestamp":"タイムスタンプ",
// "txID":"トランザクションID"
// }
// ====================================================================================================
func transfer(stub shim.ChaincodeStubInterface, args string) ([]byte, error) {
//返却値用構造体
type Transfer_Return struct{
From table.FromID `json:"from"`
To table.ToID `json:"to"`
TokenID string `json:"tokenID"`
QuantityDelta string `json:"quantityDelta"`
QuantitySnapshot string `json:"quantitySnapshot"`
Action string `json:"action"`
Timestamp string `json:"timestamp"`
TxID string `json:"txID"`
}
//引数をmap型変数にparse
var argsmap map[string]interface{}
if err := json.Unmarshal([]byte(args) , &argsmap); err != nil {
errormessage := constants.ERR_INCORRECT_JSON + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
fromgroupID,_ := argsmap[constants.FROMGROUPID].(string)
fromuserID,_ := argsmap[constants.FROMUSERID].(string)
togroupID, argserr := argsmap[constants.TOGROUPID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOGROUPID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
touserID, argserr := argsmap[constants.TOUSERID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOUSERID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
tokenID, argserr := argsmap[constants.TOKENID].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TOKENID + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
quantityDelta, argserr := argsmap[constants.QUANTITYDELTA].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.QUANTITYDELTA + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//quantitydeltaが非数値、負の値の場合エラー
isplus, err := util.IsPlusVal(quantityDelta)
if(err != nil){
return nil, err
} else if(!isplus){
errormessage := constants.ERR_INVALID_PARAM + constants.QUANTITYDELTA + " must be larger than 0"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
action, _ := argsmap[constants.ACTION].(string)
timestamp, argserr := argsmap[constants.TIMESTAMP].(string)
if (!argserr) {
errormessage := constants.ERR_INVALID_PARAM + constants.TIMESTAMP + " must be specified"
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
//①ウォレット参照、②取引計算、③取引後ウォレット情報登録、④取引履歴情報登録
txType := constants.TXTYPE_TRANSFER
params := []string{txType, fromgroupID, fromuserID, togroupID, touserID, tokenID, quantityDelta, action, timestamp}
from_quantitysnapshot, _, err := move(stub, params)
if(err != nil){
return nil, err
}
//返却値の設定
txID := stub.GetTxID()
from := table.FromID{GroupID: fromgroupID, UserID: fromuserID}
to := table.ToID{GroupID: togroupID, UserID: touserID}
returnval := &Transfer_Return{
From: from,
To: to,
TokenID: tokenID,
QuantityDelta: "-" + quantityDelta,
QuantitySnapshot: from_quantitysnapshot,
Action: action,
Timestamp:timestamp,
TxID: txID }
returnvalJSONBytes, err := json.Marshal(returnval)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
return returnvalJSONBytes, nil
}
// ===================================================================================================
// move - ①ウォレット参照、②取引計算、③取引後ウォレット情報登録、④取引履歴情報登録 を行う(内部関数)
// @param {[]string} args
// args[0]: txType "deposit" or "withdraw" or "transfer"
// args[1]: fromGroupID
// args[2]: fromUserID
// args[3]: toGroupID
// args[4]: toUserID
// args[5]: tokenID
// args[6]: quantityDelta
// args[7]: action
// args[8]: timestamp
// @return {string} from_quantitysnapshot トークン移転結果(移転元)
// {string} to_quantitysnapshot トークン移転結果(移転先)
// {error} エラー
// ====================================================================================================
func move(stub shim.ChaincodeStubInterface, args []string) (string, string, error) {
var err error
//移転元系のパラメータ(transferの場合に利用)
var from_groupwalletinfoarray table.GroupWalletInfoArray
var from_quantitysnapshot string //返却値
var from_property string
var to_quantityDelta string
isDeposit := true
//パラメータチェックは呼び出し側
txType := args[0]
fromGroupID := args[1]
fromUserID := args[2]
toGroupID := args[3]
toUserID := args[4]
tokenID := args[5]
quantityDelta := args[6]
action := args[7]
timestamp := args[8]
//ウォレット情報取得(移転元と移転先)
if(txType == constants.TXTYPE_TRANSFER){
from_groupwalletinfoarray, err = util.GetWallet(stub, fromGroupID, fromUserID, tokenID)
if(err != nil){
return "", "", err
} else if(len(from_groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallet " + "(" +constants.GROUPID + ": " + fromGroupID + " , " + constants.USERID +": " + fromUserID + " , " + constants.TOKENID +": " + tokenID + " )" + " not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return "", "", errors.New(errorstr)
}
}
to_groupwalletinfoarray, err := util.GetWallet(stub, toGroupID, toUserID, tokenID)
if(err != nil){
return "", "", err
} else if(len(to_groupwalletinfoarray.Results) == 0){
errormessage := constants.ERR_INTERNAL + " Wallet " + "(" +constants.GROUPID + ": " + toGroupID + " , " + constants.USERID +": " + toUserID + " , " + constants.TOKENID +": " + tokenID + " )" + " not exists."
errorstr := util.MakeErrorFormat(constants.ERRCODE_WALLET_NOT_EXISTS, errormessage)
return "", "", errors.New(errorstr)
}
// userID, tokenIDを指定したGetWalletの場合
// groupwalletinfoarray.Results[0]に単一ユーザのウォレット情報、
// groupwalletinfoarray.Results[0].Wallets[0]に単一のウォレット情報が格納される。
if(txType == constants.TXTYPE_TRANSFER){
//移転元の残高を減らし、移転先の残高を増やす。
from_quantitysnapshot, err = util.AddValue(from_groupwalletinfoarray.Results[0].Wallets[0].Quantity, quantityDelta, false)
if(err != nil){
return "", "", err
}
//移転元について、計算結果の正負を判定
isplus, _ := util.IsPlusVal(from_quantitysnapshot)
if(!isplus){
errormessage := constants.ERR_INTERNAL + " Transfer Error: " + constants.QUANTITYDELTA + " must be less than " + constants.QUANTITY
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return "", "", errors.New(errorstr)
}
from_property = from_groupwalletinfoarray.Results[0].Wallets[0].Property
}
if(txType == constants.TXTYPE_WITHDRAW){
isDeposit = false
}
to_quantitysnapshot, err := util.AddValue(to_groupwalletinfoarray.Results[0].Wallets[0].Quantity, quantityDelta, isDeposit)
if(err != nil){
return "", "", err
}
//消却の場合、計算結果の正負を判定
isplus, _ := util.IsPlusVal(to_quantitysnapshot)
if(!isplus){
errormessage := constants.ERR_INTERNAL + " Withdraw Error: " + constants.QUANTITYDELTA + " must be less than " + constants.QUANTITY
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return "", "", errors.New(errorstr)
}
to_property := to_groupwalletinfoarray.Results[0].Wallets[0].Property
/*
ウォレットに登録(移転元、移転先)
*/
if(txType == constants.TXTYPE_TRANSFER){
params := []string{fromGroupID, fromUserID, tokenID, from_quantitysnapshot, from_property, timestamp}
err = util.UpdateWallet(stub, params)
if(err != nil){
return "", "", err
}
}
params := []string{toGroupID, toUserID, tokenID, to_quantitysnapshot, to_property, timestamp}
err = util.UpdateWallet(stub, params)
if(err != nil){
return "", "", err
}
/*
取引履歴に登録(移転元、移転・払出・消却先)
*/
to_quantityDelta = quantityDelta
if(txType == constants.TXTYPE_TRANSFER){
from_quantityDelta := "-" + quantityDelta
params := []string{txType, fromGroupID, fromUserID, toGroupID, toUserID, tokenID, from_quantityDelta, from_quantitysnapshot, action, timestamp}
err = addToHistory(stub, params, true) //移転元
if(err != nil){
return "", "", err
}
} else if(txType == constants.TXTYPE_WITHDRAW){
to_quantityDelta = "-" + quantityDelta
}
params = []string{txType, fromGroupID, fromUserID, toGroupID, toUserID, tokenID, to_quantityDelta ,to_quantitysnapshot, action, timestamp}
err = addToHistory(stub, params, false) //移転・払出・消却先
if(err != nil){
return "", "", err
}
return from_quantitysnapshot, to_quantitysnapshot, nil
}
// ===================================================================================================
// addToHistory - トークン取引履歴情報の登録(内部関数)
// @param {[]string} args
// args[0]: txType "deposit" or "withdraw" or "transfer"
// args[1]: fromGroupID
// args[2]: fromUserID
// args[3]: toGroupID
// args[4]: toUserID
// args[5]: tokenID
// args[6]: quantityDelta
// args[7]: quantitySnapshot
// args[8]: action
// args[9]: timestamp
// {bool} keyIsFrom fromGroupID, fromUserIDがKeyの場合、true
// @return {error} エラー
// ====================================================================================================
func addToHistory(stub shim.ChaincodeStubInterface, args []string, keyIsFrom bool) error {
var groupID string
var userID string
//パラメータチェックは呼び出し側
txType := args[0]
fromGroupID := args[1]
fromUserID := args[2]
toGroupID := args[3]
toUserID := args[4]
tokenID := args[5]
quantityDelta := args[6]
quantitySnapshot := args[7]
action := args[8]
timestamp := args[9]
txID := stub.GetTxID()
inversetime, err := util.InverseLexicalOrder(timestamp)
if(err != nil){
return err
}
//取引履歴テーブル用複合キー生成
var groupuserkey string
if(keyIsFrom){
groupuserkey = constants.GROUPID_PREFIX + fromGroupID + constants.KEYPARTITION + constants.USERID_PREFIX + fromUserID
groupID = fromGroupID
userID = fromUserID
} else{
groupuserkey = constants.GROUPID_PREFIX + toGroupID + constants.KEYPARTITION + constants.USERID_PREFIX + toUserID
groupID = toGroupID
userID = toUserID
}
historytablekey, err := stub.CreateCompositeKey(table.HISTORYTABLE_PREFIX, []string{groupuserkey, constants.TOKENID_PREFIX + tokenID, txType, inversetime , txID })
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
//取引履歴情報構造体
from := table.FromID{GroupID: fromGroupID, UserID: fromUserID}
to := table.ToID{GroupID: toGroupID, UserID: toUserID}
historyInfo := &table.TxHistory{
GroupID:groupID, //グループID(誰の履歴か特定するため)
UserID:userID, //ユーザID(誰の履歴か特定するため)
TxType: txType, //トランザクションタイプ
From: from, //移転元
To: to, //移転先
TokenID: tokenID, //トークンID
QuantityDelta: quantityDelta, //トークン移転/払出/消却値
QuantitySnapshot: quantitySnapshot, //トークン累積値
Action:action, //アクション
Timestamp:timestamp, //タイムスタンプ
TxID:txID} //トランザクションID
historyInfoJSONBytes, err := json.Marshal(historyInfo)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
//取引履歴テーブルへ登録
err = stub.PutState(historytablekey, []byte(historyInfoJSONBytes))
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
return nil
}
<file_sep>/Ethereum-collabo/connector/src/lib/ethaccess.js
// 基本パッケージの依存宣言
var io = require('socket.io-client');
//var HttpProxyAgent = require('http-proxy-agent');
//var proxy = process.env.http_proxy;
//var agent = new HttpProxyAgent(proxy);
//socketクライアント テスト実行
//事前にsocketのサーバー側を起動しておく
/*
各機能におけるfunc、argsの形式は次の通り。
・アカウント作成
func: "createaccount"
args: {"password":<パスワード>}
・残高参照
func: "getBalance"
args: {"referedAddress":<アドレス>}
・アセット登録
func: "addInstance"
args: {"to":<送金先アドレス>,"value":<送金額(eth)>}
・アセット消却
func: "deleteInstance"
args: {"from":<消却対象アドレス>,"unlockpass":<アンロックパス>, value":<消却額(eth)>}
・アセット移転
func: "transfer"
args: {"from":<送金元アドレス>,"unlockpass":<アンロックパス>,"to":<送金先アドレス>,"value":<送金額(eth)>}
*/
//テスト実行
/*
//アカウント作成
send("http://localhost:4030","createaccount", {"password":"<PASSWORD>"})
.then((data) => {
console.log("アカウント作成");
console.log(data);
})
//残高参照
send("http://localhost:4030","getBalance", {"referedAddress":"9de80f3654690e2cf4daeb845a7c7c34b144a97d"})
.then((data) => {
console.log("残高参照");
console.log(data);
})
//アセット登録
send("http://localhost:4030","addInstance", {"to":"ac90231ca44d9c6ed70c7e7917bd6d0a6b600d1f","value":"0.001"})
.then((data) => {
console.log("アセット登録");
console.log(data);
})
//アセット消却
send("http://localhost:4030","deleteInstance", {"from":"09e62111de368ca9d5f2164d2ba274033e0fdb27","unlockpass":"<PASSWORD>","value":"0.0001"})
.then((data) => {
console.log("アセット消却");
console.log(data);
})
//アセット移転
send("http://localhost:4030","transfer", {"from":"09e62111de368ca9d5f2164d2ba274033e0fdb27","unlockpass":"<PASSWORD>","to":"<PASSWORD>","value":"0.0001"})
.then((data) => {
console.log("アセット移転");
console.log(data);
})
*/
/**
* send: ethereumに要求送信
* @param {string} csUrl: 連携サーバのURL(例: "http://192.168.3.11:4030")
* @param {string} func: 関数名(例: "xxx")
* @param {JSON} args: 引数(例: {fromAddress:"aaa", toAddress:"bbb", amount:100, endChainFee:0})
**/
exports.send = function(csUrl, func, args) {
return new Promise((resolve, reject) => {
// https://socket.io/docs/client-api/
// reconnection を切っておかないと、繋がるまでリトライを繰り返す。
// timeoutはデフォルト値だが、編集しやすいよう記述しておく。
var socket = io(csUrl, {
reconnection : false,
timeout : 20000
// agent: agent
});
var requestData = {
func : func,
args : args
};
// socket.emit('request', requestData);
socket.emit('request', requestData, function (responseData) {
if(!socket.disconnected) {
socket.disconnect();
}
if (responseData.status == 200) {
return resolve(responseData);
} else {
return reject(responseData);
}
});
function tmout(err) {
// 接続失敗 or TIMEOUT。
console.log(err.toString());
var emsg = "Cooperation node down?";
var ret_obj = {
"status" : 404,
"errorDetail" : emsg
};
if(!socket.disconnected) {
socket.disconnect();
}
return reject(ret_obj);
}
// どちらを検出しても同じエラーとして返却する。
socket.on('connect_error', function(err){
return tmout(err);
});
socket.on('connect_timeout', function(err){
return tmout(err);
});
/*
* socket.on('response', function (res) {
* if(!socket.disconnected) {
* socket.disconnect();
* }
* return resolve(res);
* });
*
* socket.on('error', function (e) {
* if(!socket.disconnected) {
* socket.disconnect();
* }
* return reject(e);
* });
*/
});
}<file_sep>/Ethereum-collabo/connector/src/lib/sampleAPIUtil.js
/*
* sampleAPIUtil.js
* COPYRIGHT FUJITSU LIMITED 2018
*/
/* 概要:
* APIのユーティリティクラス
*/
var crypto = require("crypto");
var sampleAPIUtil = class {
/**
* コンテンツタイプのチェック
* @param {Obj} req: リクエスト
* @return{bool} true:有効/false:無効
**/
static isValidContentType(req) {
var cType = req.header('Content-type');
if (cType != undefined) {
// JSON形式かどうか
if (cType.toLowerCase().indexOf('application/json') != -1) {
return true;
}
}
return false;
}
/**
* タイムスタンプ文字列作成
* @return{string} 現在時刻の文字列(YYYYMMDDThhmmss形式)
**/
static getTimestampString() {
var dateObj = new Date();
var y = dateObj.getFullYear();
var m = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var d = ('0' + dateObj.getDate()).slice(-2);
var h = ('0' + dateObj.getHours()).slice(-2);
var min = ('0' + dateObj.getMinutes()).slice(-2);
var s = ('0' + dateObj.getSeconds()).slice(-2);
return ''+ y + m + d + 'T' + h + min + s;
}
/**
* ハッシュ生成
* @param {string} input: 入力文字
* @return{string} sha256によるハッシュの16進ダイジェスト
**/
static getHash(input) {
var sha256 = crypto.createHash('sha256');
sha256.update(input);
var hash = sha256.digest('hex');
return hash;
}
}
module.exports = sampleAPIUtil;
<file_sep>/Ethereum-collabo/connector/src/routes/createAccount.js
//依存ライブラリ
const express = require('express');
const sampleAPIUtil = require('../lib/sampleAPIUtil.js');
const sampleAPIError = require('../lib/sampleAPIError.js');
var Web3 = require('web3');
const eth = require('../lib/ethaccess.js');
const fabric = require('../lib/fabricaccess.js');
const conf = require('../config/default.json');
var router = express.Router();
//
// アカウント作成
// req: {
// "name":<アカウント名(Fabricの場合必須)>,
// "pass":<パスワード(Ethereumの場合必須)>,
// "ChainType": <"Fabric" or "Ethereum">
// }
// res: {
// "status":<HTTPステータスコード>,
// "accountID"":<アカウントID(Fabricの場合、name)>
// }
//
router.post('/', function(req, res, next){
if (!sampleAPIUtil.isValidContentType(req)) {
next(new sampleAPIError(400, 2000));
return;
}
//パラメータチェック
var ChainType = req.body.ChainType;
if ( ChainType != "Fabric" && ChainType != "Ethereum" ) {
next(new sampleAPIError(422, 3001));
return;
}
var pass = req.body.pass;
if(ChainType == "Ethereum"){
if( pass == undefined ) {
next(new sampleAPIError(422, 2001));
return;
}
}
var name = req.body.name;
if(ChainType == "Fabric"){
if ( name == undefined ) {
next(new sampleAPIError(422, 2005));
return;
}
}
if(ChainType == "Ethereum"){ //Ethreumの場合
console.log("***createAccount start on Ethereum***");
eth.send(conf.socket.address + conf.socket.port ,
"createaccount",
{"password": <PASSWORD>}
).then((returnvalue) => {
res.header('Content-Type', 'application/json; charset=UTF-8');
res.status(200).send(returnvalue);
}).catch(err => {
next(new sampleAPIError(500, 9000));
});
} else if(ChainType == "Fabric"){ //Fabricの場合
console.log("***createAccount start on Fabric***");
var reqparam = {fcn:"createuser", args:["fujitsu", name]}; //暫定的にGroupを"fujitsu"固定としている。
fabric.Invoke(reqparam, true)
.then((returnvalue) => {
var resval = {status:200, accountID:name} //TXIDはreturnvalueから取得できるが、Ethereumでは取得できないっぽいのでIFを合わせるために返却しない。
res.header('Content-Type', 'application/json; charset=UTF-8');
//invoke時returnした値を返却する。
res.status(200).send(resval);
}).catch(err => {
next(new sampleAPIError(500, 9000));
});
}
});
module.exports = router;
<file_sep>/Fabric/sdktest/secure_token_manager/lib/util/walletutil.go
/*
* walletutil.go
* secure_token_manager(util)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
//ウォレット管理系のutil
//アカウント管理系、トランザクション管理系のパッケージが参照する。
package util
import (
"errors"
"github.com/hyperledger/fabric/core/chaincode/shim"
"encoding/json"
"github.com/secure_token_manager/lib/table"
"github.com/secure_token_manager/lib/constants"
)
// =========================================================================
// GetWallet- ウォレット情報を取得する。(内部関数。WSにアクセス)
// @param {string} groupID
// {string} userID (省略時、グループ全体のアカウント情報を返却)
// {string} tokenID (省略時、全ウォレット情報を返却)
// @return {table.GroupWalletInfoArray}
// results:[{
// "groupID":"グループID",
// "groupName":"グループ名",
// "userID":"ユーザID",
// "userName":"ユーザ名",
// "property":"プロパティ"
// },・・・
// ]
// {error} エラー
// =========================================================================
func GetWallet(stub shim.ChaincodeStubInterface, groupID string, userID string, tokenID string) (table.GroupWalletInfoArray, error){
results := table.GroupWalletInfoArray{}
/*
ウォレット情報の取得
*/
var userlist []string
var err error
//ユーザを一意に指定する
if(userID == ""){
//groupIDからgroupID_userIDのリストを取得
userlist, err = GetUserList(stub, groupID)
if(err != nil){
return results, err
} else if(len(userlist) == 0 ){
errormessage := constants.ERR_INTERNAL + " Users in " +constants.GROUPID + ": " + groupID +" not exists."
errorstr := MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return results, errors.New(errorstr)
}
} else {
//単一アカウント情報取得(存在確認)
accountInfoJSONBytes, err := GetUser(stub, groupID, userID)
if (err != nil) {
return results, err
} else if (accountInfoJSONBytes == nil) {
errormessage := constants.ERR_INTERNAL + " User " + "(" + constants.GROUPID + ": " + groupID + " and " + constants.USERID + ": " + userID + ")" + " not exists."
errorstr := MakeErrorFormat(constants.ERRCODE_ACCOUNT_NOT_EXISTS, errormessage)
return results, errors.New(errorstr)
}
groupuserkey := constants.GROUPID_PREFIX + groupID + constants.KEYPARTITION + constants.USERID_PREFIX + userID
userlist = append(userlist, groupuserkey)
}
//グループ内のユーザの数だけウォレット情報取得
for _, groupuserkey := range userlist{
partialkey := []string{groupuserkey}
if(tokenID != ""){
partialkey = append(partialkey, constants.TOKENID_PREFIX + tokenID)
}
resultsiterator, err := stub.GetStateByPartialCompositeKey(table.WALLETTABLE_PREFIX, partialkey)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
defer resultsiterator.Close()
datalist := table.WalletInfoArray{}
datalist.GroupID = groupID
var i int
for i = 0; resultsiterator.HasNext(); i++ {
data := table.WalletInfo{}
response, err := resultsiterator.Next()
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
err = json.Unmarshal(response.Value, &data)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return results, errors.New(errorstr)
}
//問題
datalist.UserID = data.UserID
wallets := table.Wallets{
TokenID: data.TokenID,
Quantity: data.Quantity,
Property: data.Property,
LastUpdated: data.LastUpdated }
datalist.Wallets = append(datalist.Wallets, wallets)
}
//Walletsの中身がない場合、GroupWalletInfoArrayには追加しない。
if(len(datalist.Wallets) != 0){
results.Results = append(results.Results, datalist)
}
}
return results, nil
}
// ===================================================================================================
// UpdateWallet - ウォレット情報の登録、更新(内部関数)
// @param {[]string} args
// args[0]: groupID
// args[1]: userID
// args[2]: tokenID
// args[3]: quantity
// args[4]: property
// args[5]: timestamp
// @return {error} 登録エラー
// ====================================================================================================
func UpdateWallet(stub shim.ChaincodeStubInterface, args []string) error {
//パラメータチェックは呼び出し側
groupID := args[0]
userID := args[1]
tokenID := args[2]
quantity := args[3]
property := args[4]
timestamp := args[5]
//ウォレットテーブル用複合キー生成
groupuserkey := constants.GROUPID_PREFIX + groupID + constants.KEYPARTITION + constants.USERID_PREFIX + userID
wallettablekey, err := stub.CreateCompositeKey(table.WALLETTABLE_PREFIX, []string{groupuserkey, constants.TOKENID_PREFIX + tokenID})
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
//ウォレット情報構造体
walletInfo := &table.WalletInfo{
UserID: userID, //ユーザID
GroupID: groupID, //グループID
TokenID: tokenID, //トークンID
Quantity: quantity, //トークン初期値
Property: property, //プロパティ
LastUpdated:timestamp} //最終更新日時
walletInfoJSONBytes, err := json.Marshal(walletInfo)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
//ウォレットテーブルへ登録
err = stub.PutState(wallettablekey, []byte(walletInfoJSONBytes))
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return errors.New(errorstr)
}
return nil
}
<file_sep>/Ethereum-collabo/connector/src/lib/HttpRequestPromise.js
/*
* HttpRequestPromise.js
* COPYRIGHT Fujitsu Limited 2017-2018 and FUJITSU LABORATORIES LTD. 2017-2018
* 作成者:FJH)田中 大策
*/
/* 概要:
* HTTPリクエストをPromise形式で扱うためのライブラリ
*
* エントリポイント:
* 無し(libのため)
*/
// 基本パッケージの依存宣言
var request = require('request');
// Httpリクエスト送信
function send(options) {
return new Promise((resolve, reject) => {
request(options, function (err, response, body) {
if (err) {
return reject(err);
}
// header情報が必要となるため、resolveに渡す変数をbodyからresponseに変更。
// return resolve(body);
return resolve(response);
})
});
}
exports.send = function(options) {
return send(options);
}
<file_sep>/Fabric/sdktest/secure_token_manager/main.go
/*
* main.go
* secure_token_manager main
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
package main
import (
"github.com/hyperledger/fabric/core/chaincode/shim"
pb "github.com/hyperledger/fabric/protos/peer"
"github.com/secure_token_manager/lib/user"
"github.com/secure_token_manager/lib/wallet"
"github.com/secure_token_manager/lib/constants"
"github.com/secure_token_manager/lib/transaction"
"github.com/secure_token_manager/lib/util"
)
// チェーンコード構造体の定義
type Chaincode struct {
}
const LOGGER_NAME = "Smartwallet_main"
// チェーンコードの初期化関数
// ===========================
func (t *Chaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Info("Smartwallet initialized")
return shim.Success(nil)
}
// Invoke関数
// ========================================
func (t *Chaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {
logger := shim.NewLogger(LOGGER_NAME)
logger.Infof("Invoke called: Tx ID = %s", stub.GetTxID())
args := stub.GetStringArgs()
params := []string{}
var function string
if args[0] == "invoke" { //nodeのバージョンが古い場合、args[0]="invoke"となるので調整
function = args[1]
params = args[2:]
}
if args[0] != "invoke" {
function = args[0]
params = args[1:]
}
logger.Infof("function name = %s", function)
//アカウント管理
if function == "createUser" { //アカウントを新規に作成する。
return user.CreateUserWithCheckOperator(stub, params)
} else if function == "getSingleUser" { //単一アカウントのアカウント情報を取得する。
return user.GetSingleUserWithCheckOperator(stub, params)
} else if function == "getGroupUsers" { //特定のグループに属する全アカウントのアカウント情報を、userIDの昇順で取得する。
return user.GetGroupUsersWithCheckOperator(stub, params)
}
//ウォレット管理
if function == "createWallet" { //ウォレットを新規に作成する。
return wallet.CreateWalletWithCheckOperator(stub, params)
} else if function == "getSingleUserWallet" { //単一アカウントのアカウント情報を取得する。
return wallet.GetSingleUserWalletWithCheckOperator(stub, params)
} else if function == "getGroupUsersWallet" { //特定のグループに属する全アカウントのアカウント情報を、userIDの昇順で取得する。
return wallet.GetGroupUsersWalletWithCheckOperator(stub, params)
} else if function == "getGroupWallet" { //特定のグループに属する全アカウントのアカウント情報を、userIDの昇順で取得する。
return wallet.GetGroupWalletWithCheckOperator(stub, params)
}
//トランザクション管理
if function == "deposit" { //トークンを払い出す
return transaction.DepositTokenWithCheckOperator(stub, params)
} else if function == "withdraw" { //トークンを消却する
return transaction.WithdrawTokenWithCheckOperator(stub, params)
} else if function == "transfer" { //トークンを移転する
return transaction.TransferTokenWithCheckOperator(stub, params)
} else if function == "getSingleUserTxHistory" { //単一アカウントの特定のトークンに関するトークン取引履歴情報を、userIDの昇順で新着順で取得する。
return transaction.GetSingleUserTxHistoryWithCheckOperator(stub, params)
} else if function == "getGroupUsersTxHistory" { //特定のグループに属する全アカウントの特定のトークンに関するトークン取引履歴情報を、userIDの昇順で新着順で取得する。
return transaction.GetGroupUsersTxHistoryWithCheckOperator(stub, params)
}
//関数名が存在しない場合エラー
errormessage := constants.ERR_INTERNAL + " function:" + function + " does not exist"
logger.Error(errormessage)
errorstr := util.MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return shim.Error(errorstr)
}
// ===================================================================================
// Main
// ===================================================================================
func main() {
err := shim.Start(new(Chaincode))
if err != nil {
logger := shim.NewLogger(LOGGER_NAME)
errormessage := constants.ERR_INTERNAL + " Error starting chaincode:" + err.Error()
logger.Error(errormessage)
}
}
<file_sep>/Ethereum-collabo/geth-docker/sample_web3/invoke.js
var Web3 = require('web3');
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
//コントラクトのアドレス
var address = "0xc64e68e73c00cc27cd45f5e11f0dde0e181a8583"; //Ballot
//abi情報 solidityページからコピー
var abi = [{"constant": false,"inputs": [{"name": "to","type": "address"}],"name": "delegate","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"},{"constant": false,"inputs": [{"name": "toVoter","type": "address"}],"name": "giveRightToVote","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"},{"constant": false,"inputs": [{"name": "toProposal","type": "uint8"}],"name": "vote","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"},{"inputs": [{"name": "_numProposals","type": "uint8"}],"payable": false,"stateMutability": "nonpayable","type": "constructor"},{"constant": true,"inputs": [],"name": "winningProposal","outputs": [{"name": "_winningProposal","type": "uint8"}],"payable": false,"stateMutability": "view","type": "function"}];
//コントラクトの取得
var contract = web3.eth.contract(abi).at(address);
//console.log(contract);
//query実行
var response = contract.winningProposal.call();
//invoke実行
//var response = contract.vote.sendTransaction(2, {from: web3.eth.accounts[1]});
console.log("response:",response);
<file_sep>/Fabric/sdktest/secure_token_manager/lib/util/userutil.go
/*
* userutil.go
* secure_token_manager(util)
*
* COPYRIGHT 2018 Fujitsu Laboratries Limited
*/
//アカウント管理系のutil
//ウォレット管理系、トランザクション管理系のパッケージが参照する。
package util
import (
"errors"
"github.com/hyperledger/fabric/core/chaincode/shim"
"encoding/json"
"github.com/secure_token_manager/lib/table"
"github.com/secure_token_manager/lib/constants"
)
// =============================================================================
// GetUser- アカウント情報を取得する。(内部関数。WSにアクセス)
// @param {string} groupID
// {string} userID (空文字の場合、グループ全体のアカウント情報を返却)
// @return []byte 以下のバイト型JSON文字列
// results:[{
// "groupID":"グループID",
// "groupName":"グループ名",
// "userID":"ユーザID",
// "userName":"ユーザ名",
// "property":"プロパティ"
// },・・・
// ]
// ==============================================================================
func GetUser(stub shim.ChaincodeStubInterface, groupID string, userID string) ([]byte, error){
//userIDが指定されていない場合、group全体のアカウント情報を取得
partialkey := []string{constants.GROUPID_PREFIX + groupID}
if(userID != ""){
partialkey = append(partialkey, constants.USERID_PREFIX + userID)
}
resultsiterator, err := stub.GetStateByPartialCompositeKey(table.USERTABLE_PREFIX, partialkey)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
defer resultsiterator.Close()
datalist := table.AccountInfoArray{}
var i int
for i = 0; resultsiterator.HasNext(); i++ {
data := table.AccountInfo{}
response, err := resultsiterator.Next()
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
err = json.Unmarshal(response.Value, &data)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
datalist.Results = append(datalist.Results, data)
}
var accountInfoJSONBytes []byte
if(len(datalist.Results) != 0 ){
accountInfoJSONBytes, err = json.Marshal(datalist)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
}
return accountInfoJSONBytes, nil
}
// ==============================================================================================
// GetUserList- groupID_userIDで一意に指定されるアカウントのIDリストを返す。(内部関数。WSにアクセス)
// @param {string} groupID
// @return []string ユーザを一意に指定するIDのリスト(辞書順)
// ==============================================================================================
func GetUserList(stub shim.ChaincodeStubInterface, groupID string) ([]string, error){
resultsiterator, err := stub.GetStateByPartialCompositeKey(table.GROUPTABLE_PREFIX, []string{constants.GROUPID_PREFIX + groupID})
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
defer resultsiterator.Close()
var IDList []string //groupID_userIDのリスト
var i int
for i = 0; resultsiterator.HasNext(); i++ {
data := &table.GroupInfo{}
response, err := resultsiterator.Next()
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
err = json.Unmarshal(response.Value, &data)
if err != nil {
errormessage := constants.ERR_INTERNAL + err.Error()
errorstr := MakeErrorFormat(constants.ERRCODE_INTERNAL, errormessage)
return nil, errors.New(errorstr)
}
IDList = append(IDList, data.GroupID_UserID)
}
//何も取得できなかった場合は呼び出し元で判定する。
return IDList, nil
}
|
5ed14f5eedc6d67fa5ebe884dc9a36b176ec3d4a
|
[
"YAML",
"JavaScript",
"Markdown",
"Gradle",
"Java",
"Go",
"Dockerfile",
"Shell"
] | 41
|
Go
|
yonekurayuki/blockchain-work
|
b247fd0c71b7876696b8afdce980dec8ad042c6c
|
07ea208e6c336b587a5fed65f224cf65e61f68fa
|
refs/heads/master
|
<repo_name>amirnd51/277project<file_sep>/src/router/index.js
import Vue from "vue";
import Router from "vue-router";
// Containers
const DefaultContainer = () => import("@/containers/DefaultContainer");
// Views
const Dashboard = () => import("@/views/Dashboard");
const Scientist = () => import("@/components/Scientists");
const Projects = () => import("@/components/Projects");
const Resources = () => import("@/components/Resources");
const Executives = () => import("@/components/Executives");
const Departments = () => import("@/components/Departments");
const Welcome = () => import("@/components/Welcome");
const Mypage = () => import("@/components/Mypage");
// const Typography = () => import('@/views/theme/Typography')
// const Charts = () => import('@/views/Charts')
// const Widgets = () => import('@/views/Widgets')
// // Views - Components
// const Cards = () => import('@/views/base/Cards')
// const Forms = () => import('@/views/base/Forms')
// const Switches = () => import('@/views/base/Switches')
const Tables = () => import("@/views/base/Tables");
// const Tabs = () => import('@/views/base/Tabs')
// const Breadcrumbs = () => import('@/views/base/Breadcrumbs')
// const Carousels = () => import('@/views/base/Carousels')
// const Collapses = () => import('@/views/base/Collapses')
// const Jumbotrons = () => import('@/views/base/Jumbotrons')
// const ListGroups = () => import('@/views/base/ListGroups')
// const Navs = () => import('@/views/base/Navs')
// const Navbars = () => import('@/views/base/Navbars')
// const Paginations = () => import('@/views/base/Paginations')
// const Popovers = () => import('@/views/base/Popovers')
// const ProgressBars = () => import('@/views/base/ProgressBars')
// const Tooltips = () => import('@/views/base/Tooltips')
// // Views - Buttons
// const StandardButtons = () => import('@/views/buttons/StandardButtons')
// const ButtonGroups = () => import('@/views/buttons/ButtonGroups')
// const Dropdowns = () => import('@/views/buttons/Dropdowns')
// const BrandButtons = () => import('@/views/buttons/BrandButtons')
// // Views - Icons
// const Flags = () => import('@/views/icons/Flags')
// const FontAwesome = () => import('@/views/icons/FontAwesome')
// const SimpleLineIcons = () => import('@/views/icons/SimpleLineIcons')
// const CoreUIIcons = () => import('@/views/icons/CoreUIIcons')
// // Views - Notifications
// const Alerts = () => import('@/views/notifications/Alerts')
// const Badges = () => import('@/views/notifications/Badges')
// const Modals = () => import('@/views/notifications/Modals')
// // Views - Pages
// const Page404 = () => import('@/views/pages/Page404')
// const Page500 = () => import('@/views/pages/Page500')
const Login = () => import("@/views/pages/Login");
const Register = () => import("@/views/pages/Register");
// // Users
// const Users = () => import('@/views/users/Users')
// const User = () => import('@/views/users/User')
Vue.use(Router);
export default new Router({
mode: "hash", // https://router.vuejs.org/api/#mode
linkActiveClass: "open active",
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: "/",
name: "login",
component: Login
},
{
path: "/login",
name: "login",
component: Login
},
{
path: "/register",
name: "register",
component: Register
},
{
path: "/home",
name: "Home",
component: DefaultContainer,
children: [
{
path: "/",
name: "welcome",
component: Welcome
},
{
name: "department",
path: "/department",
component: Departments
},
{
name: "Executives Board",
path: "/executivesBoard",
component: Executives
},
{
name: "Projects",
path: "/projects",
component: Projects
},
{
name: "Scientist",
path: "/scientist",
component: Scientist
},
{
name: "Resources",
path: "/resources",
component: Resources
}
]
},
{
path: "/Mypage",
name: "Mypage",
component: DefaultContainer,
children: [
{
path: "/",
name: "mypage",
component: Mypage
}
]
}
]
});
<file_sep>/src/_nav.js
export default {
items: [
{
name: "Tables",
url: "/Tables",
icon: "icon-list",
badge: {
variant: "primary"
},
children: [
{
name: "Department",
url: "/Department",
icon: "icon-list"
},
{
name: "Executives Board",
url: "/ExecutivesBoard",
icon: "icon-list"
},
{
name: "Projects",
url: "/Projects",
icon: "icon-list"
},
{
name: "Scientist",
url: "/Scientist",
icon: "icon-list"
},
{
name: "Resources",
url: "/Resources",
icon: "icon-list"
}
]
},
{
name: "Mypage",
url: "/Mypage",
icon: "icon-layers",
badge: {
variant: "primary"
}
}
]
};
|
90f8b36e07016d099c72fd046e48f3947f826df7
|
[
"JavaScript"
] | 2
|
JavaScript
|
amirnd51/277project
|
52e6a12a6294e42165a16aec133426314b68f410
|
7e9b90c3b73dab0ec7c6bd986a0ed2645827833f
|
refs/heads/master
|
<repo_name>Streamote-extension/Front-end<file_sep>/emote/drop physics/animation.js
import pogchamp from './pogchamp.png';
import BabyRage from './Babyrage.png';
import React,{Component} from 'react';
import Matter from 'matter-js';
let images = {
'BabyRage': BabyRage,
'PogChamp' : pogchamp
}
class Animations extends Component{
constructor(props){
super(props);
this.state = {
emotion: 'happy',
img: 'PogChamp'
}
let animate = () => {
let image = this.state.img;
let emote = images.image;
let choice
switch(image){
case 'PogChamp':
choice = pogchamp
break;
case 'BabyRage':
choice = BabyRage
break;
}
console.log(image)
// var Engine = Matter.Engine,
// Render = Matter.Render,
// World = Matter.World,
// Bodies = Matter.Bodies,
// Body = Matter.Body;
// var engine = Engine.create();
// var render = Render.create({
// element: document.body,
// engine: engine,
// options: {
// width: 800,
// height: 400,
// wireframes: false,
// wireFrameBackground : 'transparent',
// background: 'transparent'
// }
// });
let {Engine,Render,World,Bodies, engine, render} = this.props
var bottomWall = Bodies.rectangle(500, 400, 1100, 20, { isStatic: true,render: {opacity : .01}});
var leftWall = Bodies.rectangle(.1, 210, 20, 600, { isStatic: true, render: {opacity : .01}});
var rightWall = Bodies.rectangle(800, 210, 20, 600, { isStatic: true,render: {opacity : .01}});
bottomWall.render.opacity = .01
var boxA = Bodies.circle(100, 10, 30,{
render:{
sprite: {
texture: choice,
xScale: .3,
yScale: .3
}
},
restitution: .8
});
var boxB = Bodies.circle(250, 10, 30,{
render:{
sprite: {
texture: choice,
xScale: .3,
yScale: .3
}
},
restitution: .8
});
var boxC = Bodies.circle(300, 10, 30,{
render:{
sprite: {
texture: choice,
xScale: .3,
yScale: .3
}
},
restitution: .8
});
var boxD = Bodies.circle(150, 10, 30,{
render:{
sprite: {
texture: choice,
xScale: .3,
yScale: .3
}
},
restitution: .8
});
var boxE = Bodies.circle(350, 10, 30,{
render:{
sprite: {
texture: choice,
xScale: .3,
yScale: .3
}
},
restitution: .8
});
World.add(engine.world, [rightWall,leftWall,bottomWall,boxA,boxB,boxC,boxD,boxE]);
Engine.run(engine);
Render.run(render);
let run = (callback) => {
console.log('runing')
Render.run(render);
callback();
}
let stop = () => {
setTimeout(() => {render.canvas.remove()},5000)
}
run(stop);
}
animate()
}
// socker.on(emotion)
render(){
return(
<div>
</div>
)
}
}
export default Animations;<file_sep>/emote/vote overylay/layout.js
import React,{Component} from 'react'
import './style.css';
import pogchamp from '../../pogchamp.png';
import openSocket from 'socket.io-client';
class Layout extends Component {
constructor(props){
super(props);
this.state = {
emotion: 'surprised',
image1: 'monkaS',
image2: 'Jebaited',
image3: 'PogChamp',
image1Click: true,
image2Click: true,
image3Click: true,
}
}
vote(image) {
if(this.state.image1Click && this.state.image2Click && this.state.image3Click){
this.setState({image1Click: false,image2Click: false,image3Click: false})
const socket = openSocket('http://0.0.0.0:8080');
socket.emit('vote','hello');
}
}
render(){
return(
<div className="outer">
<div className="container">
<img onClick = {() => this.vote('monkaS')} src={pogchamp} />
<img src={pogchamp} />
<img src={pogchamp} />
</div>
<h1>{this.state.emotion}</h1>
</div>
)
}
}
export default Layout;
|
3bb6d77c02aba07db99d5d99e2426287cb863435
|
[
"JavaScript"
] | 2
|
JavaScript
|
Streamote-extension/Front-end
|
419bf5d28fa3fd08eb8024b86c7f6fe0313e978b
|
7a76f8d36e0d6f90d82d7638b6371f68604b7342
|
refs/heads/master
|
<file_sep>const express = require('express')
const mongoose = require('mongoose')
const router = express.Router()
const Story = mongoose.model('stories')
const {
isAuthenticated,
isGuest
} = require('../helper/auth')
router.get('/', isGuest, (req, res) => {
res.render('index/welcome')
})
router.get('/dashbord', isAuthenticated, (req, res) => {
Story.find({
user: req.user.id
})
.then(stories => {
res.render('index/dashbord', {
stories
})
})
})
module.exports = router<file_sep>const express = require('express')
const mongoose = require('mongoose')
const router = express.Router()
const Story = mongoose.model('stories')
const {
isAuthenticated,
isGuest
} = require('../helper/auth')
router.get('/', (req, res) => {
Story.find({
status: "public"
})
.populate('user')
.sort({
date: 'desc'
})
.then(stories => {
res.render('stories/index', {
stories
})
})
})
// Add Story form
router.get('/add', isAuthenticated, (req, res) => {
res.render('stories/add')
})
// Edit Story Form
router.get('/edit/:id', isAuthenticated, (req, res) => {
Story.findById(req.params.id)
.then(story => {
if (!story) {
return res.status(400).send()
}
if (story.user != req.user.id) {
return res.redirect('/stories')
}
res.render('stories/edit', {
story
})
}).catch(err => res.status(400).send(err))
})
// Update the story// PUT stories/:id
router.put('/:id', isAuthenticated, (req, res) => {
let allowComments;
if (req.body.allowComments) {
allowComments = true
} else {
allowComments: false
}
Story.findByIdAndUpdate(req.params.id, {
$set: {
title: req.body.title,
body: req.body.body,
status: req.body.status,
allowComments
}
}, {
new: true
})
.then(story => {
res.redirect(`/dashbord`)
})
})
router.post('/', isAuthenticated, (req, res) => {
let allowComments;
if (req.body.allowComments) {
allowComments = true
} else {
allowComments = false
}
const newStory = {
title: req.body.title,
status: req.body.status,
body: req.body.body,
user: req.user.id,
allowComments
}
new Story(newStory)
.save()
.then(story => {
res.redirect(`/stories/show/${story._id}`)
})
.catch(err => console.log(err))
})
// show single story
router.get('/show/:id', (req, res) => {
Story.findById(req.params.id)
.populate('user')
.populate('comments.commentUser')
.then(story => {
if (story.status === 'public') {
res.render('stories/show', {
story
})
} else {
if (req.user) {
if (req.user.id == story.user._id) {
res.render('stories/show', {
story
})
} else {
res.redirect('/stories')
}
} else {
res.redirect('/stories')
}
}
}).catch(err => res.status(400).send(err))
})
router.delete('/:id', (req, res) => {
Story.findByIdAndRemove(req.params.id)
.then(() => {
res.redirect('/dashbord')
})
})
// List Stories from a loggedin user
router.get('/my', isAuthenticated, (req, res) => {
Story.find({
user: req.user.id
})
.populate('user')
.then(stories => {
res.render('stories/index', {
stories
})
})
})
// List Stories from a user
router.get('/user/:userId', (req, res) => {
Story.find({
user: req.params.userId,
status: 'public'
})
.populate('user')
.then(stories => {
res.render('stories/index', {
stories
})
})
})
// Story Comment router
router.post('/comments/:id', (req, res) => {
Story.findById(req.params.id)
.then(story => {
const newComment = {
commentBody: req.body.commentBody,
commentUser: req.user.id
}
// Add to comments array
story.comments.unshift(newComment)
story.save()
.then(story => {
res.redirect(`/stories/show/${story.id}`)
})
})
})
module.exports = router
|
e4c7896f9fe44ddd071ebb752c4759029171a700
|
[
"JavaScript"
] | 2
|
JavaScript
|
sureshn04/story_body
|
746370163e0bff61ed159a20f5192103af8651d4
|
376bee0f948df3a04b393680e68e6c222c3fb18d
|
refs/heads/master
|
<file_sep>const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const morgan = require('morgan')
const cors = require('cors')
morgan.token("body", (req, res) => {return JSON.stringify(req.body)})
app.use(cors())
app.use(bodyParser.json())
app.use(morgan(":method :url :status :response-time ms - :body"))
let persons = [
{
"name": "<NAME>",
"number": "040-123456",
"id": 1
},
{
"name": "<NAME>",
"number": "39-44-5323523",
"id": 2
},
{
"name": "<NAME>",
"number": "12-43-234345",
"id": 3
},
{
"name": "<NAME>",
"number": "39-23-6423122",
"id": 4
},
{
"name": "Jombe",
"number": "666",
"id": 5
}
]
const generateId = (maxId) => {
return Math.floor(Math.random() * Math.floor(maxId))
}
// localhost root
app.get('/', (req, res) => {
res.send('<h1>Hello World!</h1>')
})
app.get('/info', (req, res) => {
const notesCount = () => persons.length
const getTimeInfo = () => {
const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
const today = new Date()
const weekday = days[today.getDay()]
const date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate()
const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()
const datetime = date+' '+time
return (weekday + ' ' + datetime)
}
res.send( '<h2>Phonebook has info for ' + notesCount() + ' people</h2><h2>Today is: ' + getTimeInfo() + '</h2>' )
})
// GET ALL
app.get('/api/persons', (req, res) => {
res.json(persons)
})
// GET person
app.get('/api/persons/:id', (req, res) => {
const id = Number(req.params.id)
const person = persons.find(person => person.id === id)
if (person) {
res.json(person)
}
else {
res.status(404).end()
}
})
// DELETE person
app.delete('/api/persons/:id', (req, res) => {
const id = Number(req.params.id)
persons = persons.filter(person => person.id !== id)
res.status(204).end()
})
// POST person
app.post('/api/persons', (req, res) => {
const body = req.body
if (!body.name) {
return res.status(400).json({
error: 'Name missing!'
})
}
else if (!body.number) {
return res.status(400).json({
error: 'Number missing!'
})
}
const nameexists = persons.find(person => person.name === body.name)
if (!nameexists) {
const person= {
name: body.name,
number: body.number,
id: generateId(1000000000),
}
persons = persons.concat(person)
res.json(person)
}
else {
return res.status(400).json({
error: 'Name must be unique!'
})
}
})
const PORT = process.env.PORT || 3001
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
|
23aaea73de43458bc78c3c7b97c872e6be989766
|
[
"JavaScript"
] | 1
|
JavaScript
|
Murzum/FullStackOpen2019_Osa3
|
cb9e6551fcb066cf2f064326ef0d74fe28dc60b6
|
1935bf595efcaad573264af28117d2a0f047c309
|
refs/heads/master
|
<repo_name>YoungGyuLee/inno_seminar7th<file_sep>/app/src/main/java/com/yg/a3rdseminar/ChatActivity.kt
package com.yg.a3rdseminar
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_chat.*
class ChatActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
chat_friend_image.setImageResource(intent.getIntExtra("profile", 0))
chat_friend_name.text = intent.getStringExtra("name")
}
}
<file_sep>/app/src/main/java/com/yg/a3rdseminar/MainActivity.kt
package com.yg.a3rdseminar
import android.content.Intent
import android.graphics.Canvas
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.View
import android.view.animation.AnimationUtils
import android.widget.RelativeLayout
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), View.OnClickListener{
private lateinit var kakaoItems : ArrayList<KaKaoItem>
private lateinit var kaKaoAdapter: KaKaoAdapter
lateinit var swipeController: SwipeController
lateinit var itemTouchListener: ItemTouchHelper
var isDisplayButtons : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//swipeController = SwipeController()
kakaoItems = ArrayList()
kakaoItems.add(KaKaoItem(R.drawable.pika1, "09의 바나나안드로이드", "낰낰", "오후 4:07"))
kakaoItems.add(KaKaoItem(R.drawable.pika2, "이돌이의 차근차근기획", ":D ><", "오후 6:05"))
kakaoItems.add(KaKaoItem(R.drawable.pika3, "트카의 트카TV", "브이로그 찍었당~~", "오후 3:07"))
kakaoItems.add(KaKaoItem(R.drawable.pika4, "사과의 고속사과", "이상하다 혜진아,, 내심장은 너한테만 반응하나봐,,", "오후 8:24"))
kakaoItems.add(KaKaoItem(R.drawable.pika5, "섭이의 섭섭한칼퇴", "옆모습 정승환(섭피셜)", "오후 11:07"))
kakaoItems.add(KaKaoItem(R.drawable.pika6, "인누강의 웹마이웨이", "호에에에에에엥", "오후 12:16"))
kakaoItems.add(KaKaoItem(R.drawable.pika7, "신선이의 힐링캠프", "얘들아 그.. 딱 5분만 말할게요^^", "오후 8:02"))
kakaoItems.add(KaKaoItem(R.drawable.pika8, "할머니의 당찬하루", "야!", "오후 4:21"))
kakaoItems.add(KaKaoItem(R.drawable.pika9, "이모님의 회계원리", "뒤풀이 어디가지...★", "오후 11:07"))
kakaoItems.add(KaKaoItem(R.drawable.pika10, "대장의 생방송", "따봉따봉미 bb", "오후 10:10"))
kaKaoAdapter = KaKaoAdapter(kakaoItems, this)
kaKaoAdapter.setOnItemClickListener(this)
main_rv.layoutManager = LinearLayoutManager(this)
main_rv.adapter = kaKaoAdapter
swipeController = SwipeController(object : SwipeControllerActions() {
override fun onRightClicked(position: Int) {
//kaKaoAdapter..remove(position)
kaKaoAdapter.notifyItemRemoved(position)
kaKaoAdapter.notifyItemRangeChanged(position, kaKaoAdapter.itemCount)
}
})
itemTouchListener = ItemTouchHelper(swipeController)
itemTouchListener.attachToRecyclerView(main_rv)
main_rv.addItemDecoration(object : RecyclerView.ItemDecoration(){
override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
swipeController.onDraw(c!!)
}
})
main_float_add.setOnClickListener {
clickFloat()
}
main_float_c1.setOnClickListener {
Toast.makeText(this, "1번 버튼", Toast.LENGTH_SHORT).show()
}
main_float_c2.setOnClickListener {
Toast.makeText(this, "2번 버튼", Toast.LENGTH_SHORT).show()
}
}
override fun onClick(v: View?) {
val idx : Int = main_rv.getChildAdapterPosition(v)
val name : String = kakaoItems[idx].name
val profile : Int = kakaoItems[idx].profile
val intent = Intent(applicationContext, ChatActivity::class.java)
intent.putExtra("name", name)
intent.putExtra("profile", profile)
startActivity(intent)
}
fun clickFloat(){
if (!isDisplayButtons) {
isDisplayButtons = true
main_wrapper_layout.visibility = View.VISIBLE
main_wrapper_layout.setOnClickListener{ clickFloat() }
val animation = AnimationUtils.loadAnimation(this, R.anim.float_main_show)
main_float_add.setBackgroundResource(R.drawable.monster2)
main_float_add.startAnimation(animation)
val layoutParams1 = main_float_c1.layoutParams as RelativeLayout.LayoutParams
layoutParams1.bottomMargin += (main_float_c1.height * 1.2).toInt()
val showC1 = AnimationUtils.loadAnimation(this, R.anim.float_button1_show)
main_float_c1.layoutParams = layoutParams1
main_float_c1.startAnimation(showC1)
main_float_c1.isClickable = true
val layoutParam2 = main_float_c2.layoutParams as RelativeLayout.LayoutParams
layoutParam2.bottomMargin += (main_float_c2.height * 2.4).toInt()
val showC2 = AnimationUtils.loadAnimation(this, R.anim.float_button2_show)
main_float_c2.layoutParams = layoutParam2
main_float_c2.startAnimation(showC2)
main_float_c2.isClickable = true
} else {
isDisplayButtons = false
main_wrapper_layout.visibility = View.INVISIBLE
val animation = AnimationUtils.loadAnimation(this, R.anim.float_main_hide)
main_float_add.setBackgroundResource(R.drawable.monster)
main_float_add.startAnimation(animation)
val layoutParams1 = main_float_c1.layoutParams as RelativeLayout.LayoutParams
layoutParams1.bottomMargin -= (main_float_c1.height * 1.2).toInt()
val hideC1 = AnimationUtils.loadAnimation(this, R.anim.float_button1_hide)
main_float_c1.layoutParams = layoutParams1
main_float_c1.startAnimation(hideC1)
main_float_c1.isClickable = false
val layoutParams2 = main_float_c2.layoutParams as RelativeLayout.LayoutParams
layoutParams2.bottomMargin -= (main_float_c2.height * 2.4).toInt()
val hideC2 = AnimationUtils.loadAnimation(this, R.anim.float_button2_hide)
main_float_c2.layoutParams = layoutParams2
main_float_c2.startAnimation(hideC2)
main_float_c2.isClickable = false
}
}
}
<file_sep>/app/src/main/java/com/yg/a3rdseminar/ProfileActivity.kt
package com.yg.a3rdseminar
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_profile.*
class ProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
profile_friend_image.setImageResource(intent.getIntExtra("profile", 0))
profile_friend_name.text = intent.getStringExtra("name")
}
}
<file_sep>/app/src/main/java/com/yg/a3rdseminar/KaKaoHead.kt
package com.yg.a3rdseminar
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.EditText
class KaKaoHead(itemView: View?) : RecyclerView.ViewHolder(itemView) {
var kakaoPreView : EditText = itemView!!.findViewById(R.id.head_search_edit) as EditText
}
|
49fefc34cfd989bdd6be09bb251528ea62f58b8e
|
[
"Kotlin"
] | 4
|
Kotlin
|
YoungGyuLee/inno_seminar7th
|
731324b93610f5cfc956e7b1a4cbf75dc40b67ef
|
e9725741e358b03d60ad4f0784573a00418d4e5a
|
refs/heads/master
|
<file_sep>import math
import dieletric
class FDTD():
def __init__(self, dieletrico, showGraphic, KE, NSTEPS):
self.dieletrico = dieletrico
self.showGraphic = showGraphic
self.KE = KE
self.NSTEPS = NSTEPS
self.ex = []
self.hy = []
self.dic = dict()
def init(self):
self.ex = [0. for i in range(self.KE)]
self.hy = [0. for i in range(self.KE)]
self.dic['ddx'] = .0
self.dic['dt'] = .0
self.dic['t0'] = 40.
self.dic['spread'] = 12.
self.dic['pulse'] = .0
self.dic['T'] = 0
self.dic['ex_low_m1'] = .0
self.dic['ex_low_m2'] = .0
self.dic['ex_high_m1'] = .0
self.dic['ex_high_m2'] = .0
def loopFDTD(self):
while(self.NSTEPS < 10):
for i in range(1,self.NSTEPS+1,1):
self.dic['T'] += 1
for j in range(1,self.KE,1):
self.ex[j] = self.ex[j] + self.dieletrico.cb[j]*(self.hy[j-1] - self.hy[j])
self.dic['pulse'] = math.exp(-.5*(math.pow((self.dic['t0'] - self.dic['T'])/self.dic['spread'],2.0)))
self.ex[5] = self.ex[5] + self.dic['pulse']
self.ex[0] = self.dic['ex_low_m2']
self.dic['ex_low_m2'] = self.dic['ex_low_m1']
self.dic['ex_low_m1'] = self.ex[1]
self.ex[self.KE - 1] = self.dic['ex_high_m2']
self.dic['ex_high_m2'] = self.dic['ex_high_m1']
self.dic['ex_high_m1'] = self.ex[self.KE - 2]
for j in range(0,self.KE-1,1):
self.hy[j] = self.hy[j] + .5*(self.ex[j] - self.ex[j+1])
self.showGraphic.saveFig(self.NSTEPS, self.ex, self.hy, self.dieletrico.cb)
#self.showGraphic.saveFig(self.ex, self.hy, self.dieletrico.cb)
self.NSTEPS += 1<file_sep>import math
class dieletrico():
def __init__(self, start, epsilon, KE):
self.start = start
self.epsilon = epsilon
self.KE = KE
self.cb = []
def init(self):
self.cb = [.5 for i in range(self.KE)]
for i in range(self.start,self.KE):
self.cb[i] = self.cb[i]/self.epsilon
class DielCond():
def __init__(self, start, epsilon, KE, sigma):
self.start = start
self.epsilon = epsilon
self.sigma = sigma
self.KE = KE
self.ga = []
self.gb = []
self.dt = .01/6e8
self.epsz = 8.8e-12
def init(self):
self.ga = [1. for i in range(self.KE)]
self.gb = [.0 for i in range(self.KE)]
print(self.KE)
for i in range(self.start,self.KE):
self.ga[i] = 1/(self.epsilon + self.sigma*(self.dt/self.epsz))
self.gb[i] = self.sigma*(self.dt/self.epsz)
class Cilinder():
def __init__(self, radius, sigma, epsilon, start, end, size):
self.radius = radius
self.sigma = sigma
self.epsilon = epsilon
self.start = start
self.end = end
self.size = size
self.ga = []
self.gb = []
self.dt = 0.01/6e8
self.epsz = 8.8e-12
def init(self):
self.ga = [ [1.0 for j in range(self.size)] for i in range(self.size)]
self.gb = [ [.0 for j in range(self.size)] for i in range(self.size)]
for j in range(self.size):
for i in range(self.size):
xdist = self.start - i
ydist = self.end - j
dist = math.sqrt(pow(xdist, 2.) + pow(ydist, 2.))
if (dist <= self.radius):
self.ga[i][j] = 1. / (self.epsilon + ((self.sigma * self.dt) / self.epsz))
self.gb[i][j] = (self.sigma * (self.dt / self.epsz))
<file_sep>from dieletric import dieletrico
import FDTD
import showPlt
d = dieletrico(100, 0.2, 200)
sh = showPlt.showPlt(1,-1)
d.init()
method = FDTD.FDTD(d, sh, 200, 1)
method.init()
method.loopFDTD()<file_sep>import matplotlib.pyplot as plt
class showPlt():
def __init__(self, max_Y, min_Y):
self.max_Y = max_Y
self.min_Y = min_Y
def saveFig(self, NSTEPS, ex, hy, cb):
plt.plot([self.max_Y])
plt.plot([self.min_Y])
plt.plot(ex)
plt.plot(hy)
plt.plot(cb)
plt.title("Ex - Green | Hy - Red | Dieletric Blue | Step = "+str(NSTEPS))
fig = plt.gcf()
fig.savefig(str("img"+str(NSTEPS)+".png"))
plt.close()
def showFig(self, ex, hy, cb):
plt.plot([self.max_Y])
plt.plot([self.min_Y])
plt.plot(ex)
plt.plot(hy)
plt.plot(cb)
plt.show()
plt.close()<file_sep>import math
import Materiais
import tkinter
from tkinter import ttk
class FDTD():
def __init__(self, showGraphic, KE, NSTEPS, material):
self.material = material
self.showGraphic = showGraphic
self.KE = KE
self.NSTEPS = NSTEPS
self.ex = []
self.hy = []
self.dx = []
self.ix = []
self.mag = []
self.freq = []
self.arg = []
self.real_in = []
self.imag_in = []
self.amp_in = []
self.phase_in = []
self.real_pt = []
self.imag_pt = []
self.ampn = []
self.phasen = []
self.dic = dict()
self.dic['ddx'] = .0
self.dic['dt'] = .0
self.dic['t0'] = 0.
self.dic['spread'] = 0.
self.dic['pulse'] = .0
self.dic['T'] = 0
self.dic['ex_low_m1'] = .0
self.dic['ex_low_m2'] = .0
self.dic['ex_high_m1'] = .0
self.dic['ex_high_m2'] = .0
self.dic['kc'] = 0
self.progress = None
def init(self):
self.ex = [0. for i in range(self.KE)]
self.hy = [0. for i in range(self.KE)]
self.dx = [0. for i in range(self.KE)]
self.ix = [0. for i in range(self.KE)]
self.mag = [0. for i in range(0,self.KE,1)]
self.freq = [0. for i in range(0,5,1)]
self.arg = [.0 for i in range(0,5,1)]
self.real_in = [0. for i in range(0,5,1)]
self.imag_in = [0. for i in range(0,5,1)]
self.amp_in = [0. for i in range(0,5,1)]
self.phase_in = [0. for i in range(0,5,1)]
self.real_pt = [[.0 for j in range (0,self.KE,1)] for i in range(0,5,1)]
self.imag_pt = [[.0 for j in range (0,self.KE,1)] for i in range(0,5,1)]
self.ampn = [[.0 for j in range (0,self.KE,1)] for i in range(0,5,1)]
self.phasen = [[.0 for j in range (0,self.KE,1)] for i in range(0,5,1)]
self.dic['ddx'] = .0
self.dic['dt'] = .0
self.dic['t0'] = 50.
self.dic['spread'] = 20.
self.dic['pulse'] = .0
self.dic['T'] = 0
self.dic['ex_low_m1'] = .0
self.dic['ex_low_m2'] = .0
self.dic['ex_high_m1'] = .0
self.dic['ex_high_m2'] = .0
self.dic['kc'] = 5
for m in range(0, 3, 1):
self.real_in[m] = self.real_in[m] + math.cos(self.arg[m] * self.dic['T']) * self.ex[10]
self.imag_in[m] = self.imag_in[m] - math.sin(self.arg[m] * self.dic['T']) * self.ex[10]
def loopFDTD(self):
tk = tkinter.Tk()
tk.title("Saving Images")
label = tkinter.Label(tk)
label.pack()
p = ttk.Progressbar(tk,orient=tkinter.HORIZONTAL,length=200,mode="determinate",takefocus=True,maximum=self.NSTEPS)
p.pack()
for i in range(1,self.NSTEPS+1,1):
self.dic['T'] += 1
for j in range(1,self.KE,1):
self.dx[j] = self.dx[j] + 0.5*(self.hy[j-1] - self.hy[j])
self.dic['pulse'] = math.exp(-.5*(math.pow((self.dic['t0'] - (self.dic['T'] - self.dic['t0']))/self.dic['spread'],2.0)))
# self.dic['pulse'] = math.sin(2*math.pi*500*self.dic['T']);
self.dx[self.dic['kc']] = self.dx[self.dic['kc']] + self.dic['pulse']
for k in range(1,self.KE-1):
self.ex[k] = self.material.ga[k]*(self.dx[k] - self.ix[k])
# self.ix[k] = self.ix[k] + self.material.gb[k]*self.ex[k]
self.ex[0] = self.dic['ex_low_m2']
self.dic['ex_low_m2'] = self.dic['ex_low_m1']
self.dic['ex_low_m1'] = self.ex[1]
self.ex[self.KE - 1] = self.dic['ex_high_m2']
self.dic['ex_high_m2'] = self.dic['ex_high_m1']
self.dic['ex_high_m1'] = self.ex[self.KE - 2]
for j in range(0,self.KE-1,1):
self.hy[j] = self.hy[j] + .5*(self.ex[j] - self.ex[j+1])
self.showGraphic.saveFig(i, self.ex, self.hy, self.material)
p.step()
label["text"] = "image-"+str(i)
tk.update()
#self.showGraphic.saveFig(self.ex, self.hy, self.material.cb)
tk.destroy()
def loopFDTDFourier(self):
tk = tkinter.Tk()
tk.title("Saving Images")
label = tkinter.Label(tk)
label.pack()
p = ttk.Progressbar(tk,orient=tkinter.HORIZONTAL,length=200,mode="determinate",takefocus=True,maximum=self.NSTEPS)
p.pack()
for i in range(1,self.NSTEPS+1,1):
self.dic['T'] += 1
for j in range(1,self.KE,1):
self.dx[j] = self.dx[j] + 0.5*(self.hy[j-1] - self.hy[j])
self.dic['pulse'] = math.exp(-.5*(math.pow((self.dic['t0'] - (self.dic['T'] - self.dic['t0']))/self.dic['spread'],2.0)))
self.dx[25] = self.dx[25] + self.dic['pulse']
for k in range(1,self.KE-1):
self.ex[k] = (self.dx[k] - self.ix[k])
for m in self.material:
if(m.ga[k] != 1):
self.ex[k] = m.ga[k]*(self.dx[k] - self.ix[k])
self.ix[k] = self.ix[k] + m.gb[k]*self.ex[k]
break
for k in range(self.KE):
self.mag[k] = self.mag[k] + math.pow(self.ex[k],2.)
for m in range(0,5,1):
self.real_pt[m][k] = self.real_pt[m][k] + math.cos(self.arg[m]*self.dic['T'])*self.ex[k]
self.imag_pt[m][k] = self.imag_pt[m][k] - math.sin(self.arg[m]*self.dic['T'])*self.ex[k]
if(self.dic['T'] < 100):
for m in range(0, 3, 1):
self.real_in[m] = self.real_in[m] + math.cos(self.arg[m] * self.dic['T']) * self.ex[10]
self.imag_in[m] = self.imag_in[m] - math.sin(self.arg[m] * self.dic['T']) * self.ex[10]
self.ex[0] = self.dic['ex_low_m2']
self.dic['ex_low_m2'] = self.dic['ex_low_m1']
self.dic['ex_low_m1'] = self.ex[1]
self.ex[self.KE - 1] = self.dic['ex_high_m2']
self.dic['ex_high_m2'] = self.dic['ex_high_m1']
self.dic['ex_high_m1'] = self.ex[self.KE - 2]
for j in range(0,self.KE-1,1):
self.hy[j] = self.hy[j] + .5*(self.ex[j] - self.ex[j+1])
self.showGraphic.saveFig(i, self.ex, self.hy, self.material)
p.step()
label["text"] = "image-"+str(i)
tk.update()
tk.destroy()
class FDTD2D(FDTD):
def __init__(self, material, showGraphic, NSTEPS, kc, IE, JE):
super().__init__(showGraphic, JE, NSTEPS, material)
self.IE = IE
self.JE = JE
self.ez = []
self.iz = []
self.hx = []
self.ihx = []
self.ihy = []
self.gi2 = []
self.gi3 = []
self.gj2 = []
self.gj3 = []
self.fi1 = []
self.fi2 = []
self.fi3 = []
self.fj1 = []
self.fj2 = []
self.fj3 = []
self.dic['ez_inc_low_m1'] = 0
self.dic['ez_inc_low_m2'] = 0
self.dic['ez_inc_high_m1'] = 0
self.dic['ez_inc_high_m2'] = 0
self.dic['ic'] = 0
self.dic['jc'] = 0
self.dic['ia'] = 0
self.dic['ib'] = 0
self.dic['ja'] = 0
self.dic['jb'] = 0
self.dic['kc'] = kc
def init(self, npml):
self.dz = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.ez = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.iz = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.hx = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.hy = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.ihx = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.ihy = [ [0.0 for j in range(self.JE)] for i in range(self.IE)]
self.gi2 = [ 1.0 for i in range(self.IE)]
self.gi3 = [ 1.0 for i in range(self.IE)]
self.gj2 = [ 1.0 for i in range(self.JE)]
self.gj3 = [ 1.0 for i in range(self.JE)]
self.fi1 = [ 0.0 for i in range(self.IE)]
self.fi2 = [ 1.0 for i in range(self.IE)]
self.fi3 = [ 1.0 for i in range(self.IE)]
self.fj1 = [ 0.0 for i in range(self.JE)]
self.fj2 = [ 1.0 for i in range(self.JE)]
self.fj3 = [ 1.0 for i in range(self.JE)]
self.ez_inc = [ 0.0 for i in range(self.JE)]
self.hx_inc = [ 0.0 for i in range(self.JE)]
self.dic['t0'] = 20.
self.dic['T'] = 0
self.dic['spread'] = 8.
self.dic['ic'] = self.IE//2
self.dic['jc'] = self.JE//2
self.dic['ia'] = 6
self.dic['ib'] = self.IE - self.dic['ia'] - 1
self.dic['ja'] = 6
self.dic['jb'] = self.JE - self.dic['ja'] - 1
for i in range(npml+1):
xnum = npml - i
xd = npml
xxn = xnum / xd
xn = 0.25 * pow(xxn, 3.0)
self.gi2[i] = 1.0 / (1.0 + xn)
self.gi2[self.IE - 1 - i] = 1.0 / (1.0 + xn)
self.gi3[i] = (1.0 - xn) / (1.0 + xn)
self.gi3[self.IE - i - 1] = (1.0 - xn) / (1.0 + xn)
xxn = (xnum - .5) / xd
xn = 0.25 * pow(xxn, 3.0)
self.fi1[i] = xn
self.fi1[self.IE - 2 - i] = xn
self.fi2[i] = 1.0 / (1.0 + xn)
self.fi2[self.IE - 2 - i] = 1.0 / (1.0 + xn)
self.fi3[i] = (1.0 - xn) / (1.0 + xn)
self.fi3[self.IE - 2 - i] = (1.0 - xn) / (1.0 + xn)
for j in range(npml+1):
xnum = npml - j
xd = npml
xxn = xnum / xd
xn = 0.25 * pow(xxn, 3.0)
self.gj2[j] = 1.0 / (1.0 + xn)
self.gj2[self.JE - 1 - j] = 1.0 / (1.0 + xn)
self.gj3[j] = (1.0 - xn) / (1.0 + xn)
self.gj3[self.JE - j - 1] = (1.0 - xn) / (1.0 + xn)
xxn = (xnum - .5) / xd
xn = 0.25 * pow(xxn, 3.0)
self.fj1[j] = xn
self.fj1[self.JE - 2 - j] = xn
self.fj2[j] = 1.0 / (1.0 + xn)
self.fj2[self.JE - 2 - j] = 1.0 / (1.0 + xn)
self.fj3[j] = (1.0 - xn) / (1.0 + xn)
self.fj3[self.JE - 2 - j] = (1.0 - xn) / (1.0 + xn)
def loopFDTD(self):
loop = True
tk = tkinter.Tk()
tk.title("Saving Images")
label = tkinter.Label(tk)
label.pack()
p = ttk.Progressbar(tk,orient=tkinter.HORIZONTAL,length=200,mode="determinate",takefocus=True,maximum=self.NSTEPS)
p.pack()
while(loop):
for n in range(1,self.NSTEPS+1):
self.dic['T'] += 1
for j in range(1,self.JE):
self.ez_inc[j] = self.ez_inc[j] + .5 * (self.hx_inc[j - 1] - self.hx_inc[j])
self.ez_inc[0] = self.dic['ez_inc_low_m2']
self.dic['ez_inc_low_m2'] = self.dic['ez_inc_low_m1']
self.dic['ez_inc_low_m1'] = self.ez_inc[1]
self.ez_inc[self.JE - 1] = self.dic['ez_inc_high_m2']
self.dic['ez_inc_high_m2'] = self.dic['ez_inc_high_m1']
self.dic['ez_inc_high_m1'] = self.ez_inc[self.JE - 2]
for j in range(1,self.IE):
for i in range(1,self.IE):
self.dz[i][j] = self.gi3[i] * self.gj3[j] * self.dz[i][j] + self.gi2[i] * self.gj2[j] * .5 * (self.hy[i][j] - self.hy[i - 1][j] - self.hx[i][j] + self.hx[i][j - 1])
self.dic['pulse'] = math.exp(-.5 * pow((self.dic['T'] - self.dic['t0']) / self.dic['spread'], 2.))
self.ez_inc[self.dic['kc']] = self.dic['pulse']
for i in range(self.dic['ia'],self.dic['ib']+1):
self.dz[i][self.dic['ja']] = self.dz[i][self.dic['ja']] + 0.5 * self.hx_inc[self.dic['ja'] - 1]
self.dz[i][self.dic['jb']] = self.dz[i][self.dic['jb']] - 0.5 * self.hx_inc[self.dic['jb']]
for j in range(1,self.IE):
for i in range(1,self.IE):
self.ez[i][j] = self.material.ga[i][j] * (self.dz[i][j] - self.iz[i][j])
self.iz[i][j] = self.iz[i][j] + (self.material.gb[i][j] * self.ez[i][j])
#for j in range(1,self.IE):
# for i in range(1,self.JE):
# self.ez[i][j] = float(self.material.ga[i][j] * self.dz[i][j])
for j in range(self.JE-1):
self.hx_inc[j] = self.hx_inc[j] + .5 * (self.ez_inc[j] - self.ez_inc[j + 1])
for j in range(self.JE-1):
for i in range(self.IE):
curl_e = self.ez[i][j] - self.ez[i][j + 1]
self.ihx[i][j] = self.ihx[i][j] + self.fi1[i] * curl_e
self.hx[i][j] = self.fj3[j] * self.hx[i][j] + self.fj2[j] * .5 * (curl_e + self.ihx[i][j])
for i in range(self.dic['ia'],self.dic['ib']+1):
self.hx[i][self.dic['ja'] - 1] = self.hx[i][self.dic['ja'] - 1] + (.5 * self.ez_inc[self.dic['ja']])
self.hx[i][self.dic['jb']] = self.hx[i][self.dic['jb']] - (.5 * self.ez_inc[self.dic['jb']])
for j in range(self.JE-1):
for i in range(self.IE-1):
curl_e = self.ez[i + 1][j] - self.ez[i][j]
self.ihy[i][j] = self.ihy[i][j] + self.fj1[j] * curl_e
self.hy[i][j] = self.fi3[i] * self.hy[i][j] + self.fi2[i] * .5 * (curl_e + self.ihy[i][j])
for j in range(self.dic['ja'],self.dic['jb']+1):
self.hy[self.dic['ia'] - 1][j] = self.hy[self.dic['ia'] - 1][j] - (.5 * self.ez_inc[j])
self.hy[self.dic['ib']][j] = self.hy[self.dic['ib']][j] + (.5 * self.ez_inc[j])
self.showGraphic.saveFigColor(self.dic['T'],self.ez)
p.step()
label["text"] = "image-"+str(self.dic['T'])
tk.update()
loop = False
tk.destroy()
def loopFDTD2(self, materiais):
tk = tkinter.Tk()
tk.title("Saving Images")
label = tkinter.Label(tk)
label.pack()
p = ttk.Progressbar(tk,orient=tkinter.HORIZONTAL,length=200,mode="determinate",takefocus=True,maximum=self.NSTEPS)
p.pack()
for n in range(self.NSTEPS+1):
self.dic['T'] += 1
for j in range(1,self.JE):
self.ez_inc[j] = self.ez_inc[j] + .5 * (self.hx_inc[j - 1] - self.hx_inc[j])
self.ez_inc[0] = self.dic['ez_inc_low_m2']
self.dic['ez_inc_low_m2'] = self.dic['ez_inc_low_m1']
self.dic['ez_inc_low_m1'] = self.ez_inc[1]
self.ez_inc[self.JE - 1] = self.dic['ez_inc_high_m2']
self.dic['ez_inc_high_m2'] = self.dic['ez_inc_high_m1']
self.dic['ez_inc_high_m1'] = self.ez_inc[self.JE - 2]
for j in range(1,self.IE):
for i in range(1,self.IE):
self.dz[i][j] = self.gi3[i] * self.gj3[j] * self.dz[i][j] + self.gi2[i] * self.gj2[j] * .5 * (self.hy[i][j] - self.hy[i - 1][j] - self.hx[i][j] + self.hx[i][j - 1])
self.dic['pulse'] = math.exp(-.5 * pow((self.dic['T'] - self.dic['t0']) / self.dic['spread'], 2.))
self.ez_inc[self.dic['kc']] = self.dic['pulse']
for i in range(self.dic['ia'],self.dic['ib']+1):
self.dz[i][self.dic['ja']] = self.dz[i][self.dic['ja']] + 0.5 * self.hx_inc[self.dic['ja'] - 1]
self.dz[i][self.dic['jb']] = self.dz[i][self.dic['jb']] - 0.5 * self.hx_inc[self.dic['jb']]
for i in range(1,self.IE):
for j in range(1,self.JE):
for k in materiais:
if(k.ga[i][j] != 1):
self.ez[i][j] = float(k.ga[i][j] * self.dz[i][j])
for j in range(self.JE - 1):
self.hx_inc[j] = self.hx_inc[j] + .5 * (self.ez_inc[j] - self.ez_inc[j + 1])
for j in range(self.JE-1):
for i in range(self.IE):
curl_e = self.ez[i][j] - self.ez[i][j + 1]
self.ihx[i][j] = self.ihx[i][j] + self.fi1[i] * curl_e
self.hx[i][j] = self.fj3[j] * self.hx[i][j] + self.fj2[j] * .5 * (curl_e + self.ihx[i][j])
for i in range(self.dic['ia'],self.dic['ib']+1):
self.hx[i][self.dic['ja'] - 1] = self.hx[i][self.dic['ja'] - 1] + .5 * self.ez_inc[self.dic['ja']]
self.hx[i][self.dic['jb']] = self.hx[i][self.dic['jb']] - .5 * self.ez_inc[self.dic['jb']]
for j in range(self.JE-1):
for i in range(self.IE-1):
curl_e = self.ez[i + 1][j] - self.ez[i][j]
self.ihy[i][j] = self.ihy[i][j] + self.fj1[j] * curl_e
self.hy[i][j] = self.fi3[i] * self.hy[i][j] + self.fi2[i] * .5 * (curl_e + self.ihy[i][j])
for j in range(self.dic['ja'],self.dic['jb']+1):
self.hy[self.dic['ia'] - 1][j] = self.hy[self.dic['ia'] - 1][j] - .5 * self.ez_inc[j]
self.hy[self.dic['ib']][j] = self.hy[self.dic['ib']][j] + .5 * self.ez_inc[j]
self.showGraphic.saveFigColor(self.dic['T'],self.ez)
p.step()
label["text"] = "image-"+str(self.dic['T'])
tk.update()
tk.destroy()
<file_sep>import tkinter
from tkinter import messagebox
from tkinter import ttk
import FDTD
import ShowPlt
import Materiais
import time
tk = tkinter.Tk()
tk.wm_maxsize(width=500,height=500)
tk.wm_minsize(width=450,height=450)
tk.title("FDTD Program")
value = tkinter.IntVar()
def selection():
global raioE
if(value.get() == 2):
raioE.config(state='normal')
else:
raioE.config(state='disabled')
FDTD1 = tkinter.Radiobutton(tk,text="FDTD 1-Dimension", variable = value, value = 1, command = selection)
FDTD2 = tkinter.Radiobutton(tk,text="FDTD 2-Dimension", variable = value, value = 2, command = selection)
FDTD3 = tkinter.Radiobutton(tk,text="FDTD 3-Dimension", variable = value, value = 3, command = selection)
FDTD1.pack()
FDTD2.pack()
FDTD3.pack()
L1 = tkinter.Label(tk, text="Cells: ")
L1.pack()
E1 = tkinter.Entry(tk, width=10)
E1.pack()
L4 = tkinter.Label(tk, text="Steps: ")
L4.pack()
E4 = tkinter.Entry(tk, width=10)
E4.pack()
L2 = tkinter.Label(tk, text="ε: ", font=10)
L2.pack()
E2 = tkinter.Entry(tk, width=10)
E2.pack()
L3 = tkinter.Label(tk, text="σ: ", font=10)
L3.pack()
E3 = tkinter.Entry(tk, width=10)
E3.pack()
raio = tkinter.Label(tk, text="Radius: ", font=10)
raio.pack()
raioE = tkinter.Entry(tk, width=10, state='disabled')
raioE.pack()
def funcao():
graph = ShowPlt.showPlt(1,-1)
global value, E1, E2, E3, raioE
if(value.get() == 1):
if(E1.get() != "" and E4.get() != "" and E1.getint(E1.get()) > 0 and E4.getint(E4.get())):
if(E2.get() != "" and E3.get() != "" and E2.getdouble(E2.get()) >= 0 and E3.getdouble(E3.get()) >= 0):
material = Materiais.DielCond(E1.getint(E1.get())//2, E2.getdouble(E2.get()), E1.getint(E1.get()), E3.getdouble(E3.get()))
material.init()
fdtd = FDTD.FDTD(graph, E1.getint(E1.get()), E4.getint(E4.get()) , material)
fdtd.init()
fdtd.loopFDTD()
else:
messagebox.showinfo("Error","Fill all parameters")
else:
messagebox.showinfo("Error","Fill all parameters")
elif(value.get() == 2):
if(E1.get() != "" and E1.getint(E1.get()) > 0):
if(E2.get() != "" and E3.get() != "" and E2.getdouble(E2.get()) > 0 and E3.getdouble(E3.get()) > 0):
cilindro = Materiais.Cilinder(raioE.getint(raioE.get()), E4.getint(E4.get()),E3.getdouble(E3.get()) , E1.getint(E1.get())//2,E1.getint(E1.get())//2, E1.getint(E1.get()))
cilindro.init()
fdtd = FDTD.FDTD2D(cilindro, graph, E4.getint(E4.get()) , 0, E1.getint(E1.get()), E1.getint(E1.get()))
fdtd.init(20)
fdtd.loopFDTD()
else:
messagebox.showinfo("Error","Fill all parameters")
elif(value.get() == 3):
messagebox.showinfo("FDTD 3-D","FDTD 3-dimensions is coming ")
else:
messagebox.showinfo("Error","Fill all parameters")
button = tkinter.Button(tk,text = "start", command = funcao)
button.pack()
label = tkinter.Label(tk)
label.pack()
tk.mainloop()
'''
from Materiais import DielCond
import FDTD
import ShowPlt
d = DielCond(100, 3, 500,1)
sh = ShowPlt.showPlt(1,-1)
d.init()
method = FDTD.FDTD(sh, 500, 200,d)
method.init()
method.loopFDTDFourier()
'''
'''
from Materiais import Cilinder
from FDTD import FDTD2D
import ShowPlt
cilindro = Cilinder(20, 0.1,50 , 15, 150, 150)
sh = ShowPlt.showPlt(1,-1)
cilindro.init()
method = FDTD2D(cilindro,sh,200,300,150,150)
method.init(20)
method.loopFDTD()
'''
'''
from Materiais import Cilinder
from FDTD import FDTD2D
import ShowPlt
cilindro = Cilinder(1, 0.1,50 , 25,25 , 50)
#cilindro2 = Cilinder(4,0.1,50, 20,20,50)
sh = ShowPlt.showPlt(1,-1)
cilindro.init()
#cilindro2.init()
method = FDTD2D(cilindro,sh,150,0,50,50)
method.init(20)
method.loopFDTD()
'''<file_sep>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import numpy as np
class showPlt():
def __init__(self, max_Y, min_Y):
self.max_Y = max_Y
self.min_Y = min_Y
def saveFig(self, NSTEPS, ex, hy, args):
plt.plot([self.max_Y])
plt.plot([self.min_Y])
'''for i in range(len(ex)):
if(ex[i] > 1.):
ex[i] = 1
if(hy[i] > 1.):
hy[i] = 1
'''
plt.plot(ex)
plt.plot(hy)
plt.plot(args.ga)
plt.title("Ex - Green | Hy - Red | Step = "+str(NSTEPS))
fig = plt.gcf()
fig.savefig(str("img"+str(NSTEPS)+".png"))
plt.close()
def showFig(self, ex, hy, *args):
plt.plot([self.max_Y])
plt.plot([self.min_Y])
plt.plot(ex)
plt.plot(hy)
for i in args:
plt.plot(i)
plt.show()
plt.close()
def saveFigImageDemo(self, NSTEPS, value, *args):
fig = plt.gcf()
ax = Axes3D(fig)
X = np.arange(0, len(value), 1)
Z = np.array(value)
Y = np.arange(0, len(value), 1)
X, Y = np.meshgrid(X, Y)
ax.plot_surface(X,Y,Z)
ax.view_init(10, 300)
#ax.view_init(70, 290)
#plt.show()
plt.close()
ax.set_zbound(-1, 1)
fig.savefig(str("img" + str(NSTEPS) + ".png"))
def saveFigColor(self, NSTEPS, value):
fig = plt.gcf()
ax = Axes3D(fig)
X = np.arange(0, len(value), 1)
Z = np.array(value)
Y = np.arange(0, len(value), 1)
X, Y = np.meshgrid(X, Y)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis)
ax.view_init(90, 0)
#ax.view_init(45,45)
ax.set_axis_off()
#plt.show()
plt.close()
ax.set_zbound(-1, 1)
fig.savefig(str("img" + str(NSTEPS) + ".png"),dpi=150)
<file_sep>class dieletrico():
def __init__(self, start, epsilon, KE):
self.start = start
self.epsilon = epsilon
self.KE = KE
self.cb = []
def init(self):
self.cb = [.5 for i in range(self.KE)]
for i in range(self.start,self.KE):
self.cb[i] = self.cb[i]/self.epsilon
|
76930ba42be5113a5fbae685ec281a7a5b0f0437
|
[
"Python"
] | 8
|
Python
|
UFC-PyFDTD/Sullivan-Programs
|
90c06d96c176b8235dd6d9cf4a429d14ddd2e70e
|
6cb674a2ae2170ac34d2bc93e8d6d7125c0b0e3b
|
refs/heads/master
|
<repo_name>andreealupu/LinkedList<file_sep>/LinkedList.py
class Node():
def __init__(self, data):
self.data = data
self.next = None
class LinkedList():
def __init__(self, data) :
node = Node(data)
self.head = node
self.tail = self.head
self.length = 1
def append(self, data):
node = Node(data)
self.tail.next = node
self.tail = node
self.length += 1
def prepend(self, data):
node = Node(data)
temp = self.head
node.next = temp
self.head = node
self.length += 1
def printList(self):
array = []
currentNode = self.head
while currentNode :
array.append(currentNode.data)
currentNode = currentNode.next
print(array)
def insert(self, index, data):
#check prams if
newNode = Node(data)
currNode = self.head
prevNode = None
if index == 0:
self.prepend(data)
return
if index >= self.length:
self.append(data)
return
for i in range(index):
prevNode = currNode
currNode = currNode.next
prevNode.next = newNode
newNode.next = currNode
self.length += 1
return
#remove by data course did remove by index
#what about duplicates? not addressed here
def remove(self, data):
currNode = self.head
prevNode = None
while currNode:
if currNode.data == data:
temp = currNode.next
if not prevNode:
self.head = currNode.next
else:
prevNode.next = temp
del currNode
self.length -= 1
return
prevNode = currNode
currNode = currNode.next
#reverse
def reverse(self):
current_node = self.head
if current_node == None:
return current_node
self.tail = self.head
first = self.head
second = current_node.next
while(second):
temp = second.next
second.next = first
first = second
second = temp
self.head.next = None
self.head = first
myLinkedList = LinkedList(3)
myLinkedList.append(5)
myLinkedList.append(6)
myLinkedList.prepend(2)
myLinkedList.insert(2,4)
myLinkedList.insert(0,1)
myLinkedList.insert(8,7)
myLinkedList.remove(1)
print(myLinkedList.head.data)
myLinkedList.printList()
myLinkedList.reverse()
myLinkedList.printList()
<file_sep>/DoubleLinkedList.py
#Doubly linked List
class Node():
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoubleLinkedList():
def __init__(self, data) :
node = Node(data)
self.head = node
self.tail = self.head
self.length = 1
def append(self, data):
node = Node(data)
self.tail.next = node
node.prev = self.tail
self.tail = node
self.length += 1
def prepend(self, data):
node = Node(data)
temp = self.head
temp.prev = node
node.next = temp
self.head = node
self.length += 1
def printList(self):
array = []
currentNode = self.head
while currentNode :
array.append(currentNode.data)
currentNode = currentNode.next
print(array)
def printRevList(self):
array = []
currentNode = self.tail
while currentNode:
array.append(currentNode.data)
currentNode = currentNode.prev
print(array)
def insert(self, index, data):
#check prams if
newNode = Node(data)
currNode = self.head
prevNode = None
if index == 0:
self.prepend(data)
return
if index >= self.length:
self.append(data)
return
for i in range(index):
prevNode = currNode
currNode = currNode.next
prevNode.next = newNode
currNode.prev = newNode
newNode.next = currNode
newNode.prev = prevNode
self.length += 1
return
#remove by data course did remove by index
#what about duplicates? not addressed here
def remove(self, data):
currNode = self.head
prevNode = None
while currNode:
if currNode.data == data:
temp = currNode.next
if not prevNode:
self.head = currNode.next
self.head.prev = None
else:
prevNode.next = temp
temp.prev = prevNode
del currNode
self.length -= 1
return
prevNode = currNode
currNode = currNode.next
|
76eaf2d95db47c42264f4a3303d4d62e630d6568
|
[
"Python"
] | 2
|
Python
|
andreealupu/LinkedList
|
dc7c6e690a3eafe8487856671fcd79e50de7dc4f
|
4d0150617229d2b4a2dabb6ecfcc4df189746482
|
refs/heads/master
|
<repo_name>LuffyGitHub/regCenter<file_sep>/regCenter/src/main/java/com/sigis/entity/ServiceInfo.java
package com.sigis.entity;
import java.util.List;
/**
* 获取各个信息返回值对象
* @Title
* @ClassName:PortType
* @author Luffy
* @Description:TODO(用一句话描述这个类作用)
* @date 2018年1月4日 上午9:30:46
*/
public class ServiceInfo {
/**
* 服务类名,也就是标签portType中name属性值
*/
private String portType;
/**
* 服务wsdl地址
*/
private String url;
/**
* 服务里面所有方法的信息集合
*/
private List<MethodContentInfo> Operations;
public String getPortType() {
return portType;
}
public void setPortType(String portType) {
this.portType = portType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<MethodContentInfo> getOperations() {
return Operations;
}
public void setOperations(List<MethodContentInfo> operations) {
Operations = operations;
}
}
<file_sep>/regCenter/src/main/java/com/sigis/entity/ContainerInfo.java
package com.sigis.entity;
import java.util.List;
/**
* 容器实体类
* @Title
* @ClassName:ContainerInfo
* @author Luffy
* @Description:TODO(用一句话描述这个类作用)
* @date 2018年1月12日 下午1:57:00
*/
public class ContainerInfo {
/**
* 容器名称
*/
private String containerName;
/**
* 容器里面所有服务结果集
*/
private List<ServiceInfo> serviceInfos;
public List<ServiceInfo> getServiceInfos() {
return serviceInfos;
}
public void setServiceInfos(List<ServiceInfo> serviceInfos) {
this.serviceInfos = serviceInfos;
}
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
}
<file_sep>/regCenter/src/test/java/com/sigis/action/TestCxfUseWsdl.java
package com.sigis.action;
import javax.xml.namespace.QName;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class TestCxfUseWsdl {
public static void main(String[] args) {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
// url为调用webService的wsdl地址
Client client = dcf.createClient("http://localhost:8080/regCenter/ws?wsdl");
QName name = new QName("http://action.sigis.com/", "getConstantsList");
// namespace是命名空间,methodName是方法名
// paramvalue为参数值
Object[] objects;
try {
objects = client.invoke(name);
for(Object o : objects) {
System.out.println(o.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/regCenter/src/main/java/com/sigis/entity/MethodContentInfo.java
/**
*
*/
/**
* @Title
* @ClassName:package-info
* @author Luffy
* @Description:TODO(用一句话描述这个类作用)
* @date 2018年1月4日 上午9:23:02
*/
package com.sigis.entity;
import java.util.List;
import java.util.Map;
/**
* 返回的json对象封装
* @Title
* @ClassName:JsonObject
* @author Luffy
* @Description:TODO(用一句话描述这个类作用)
* @date 2018年1月4日 上午9:24:00
*/
public class MethodContentInfo{
/**
* 方法名称
*/
private String methodName;
/**
* 方法响回名称
*/
private String response;
/**
* 方法形参参数
*/
private Map<String,String> params;
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public Map<String, String> getParams() {
return params;
}
public void setParams(Map<String, String> params) {
this.params = params;
}
}<file_sep>/regCenter/src/main/java/com/sigis/service/ListenService.java
package com.sigis.service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import com.sigis.utils.GlobalConstants;
/**
* 监听zookeeper节点变化
* @Title
* @ClassName:ListenService
* @author Luffy
* @Description:TODO(用一句话描述这个类作用)
* @date 2017年12月29日 上午10:03:31
*/
@Service
public class ListenService implements ApplicationListener<ContextRefreshedEvent>{
private ZooKeeper zookeeper;
/**
* 封装成结果集返回
*/
private StringBuffer result = new StringBuffer();
private int i = 0 ;
/**
* @Title: getConstantsList
* @Description: TODO(获取所有容器节点的列表)key:代表容器节点目录,values:容器节点里面的值
* @param @return
* @param @throws KeeperException
* @param @throws InterruptedException
* @param @throws UnsupportedEncodingException 设定文件
* @return Map<String,String> 返回类型
* @throws
*/
public Map<String,String> getConstantsList(){
Map<String,String> mapServer = new HashMap<String,String>();
List<String> subList;
try {
subList = zookeeper.getChildren(GlobalConstants.SERVERS, true);
for (String subNode : subList) {
//获取节点数据
byte[] data = zookeeper.getData(GlobalConstants.SERVERS + "/" + subNode, false, null);
mapServer.put(GlobalConstants.SERVERS + "/" + subNode, new String(data,"utf-8"));
}
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapServer;
}
/**
* spring容器启动的时候执行监听,实时返回容器的状态
* @Title: onApplicationEvent
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param @param event 设定文件
* @return void 返回类型
* @throws
*/
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){
try {
// 注册全局默认watcher
zookeeper = new ZooKeeper(GlobalConstants.ZKHOSTS, 1000, new Watcher(){
public void process(WatchedEvent event) {
if (event.getType() == EventType.NodeChildrenChanged && (GlobalConstants.SERVERS).equals(event.getPath())) {
/**
* 每次节点有变化就刷新列表
*/
getConstantsList();
}
}
});
// watcher注册后,只能监听事件一次,参数true表示继续使用默认watcher监听事件
zookeeper.getChildren(GlobalConstants.SERVERS, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("开启zookeeper服务注册中心监听.......");
}
}
}
|
cd3062db3a910975b23e41d78e7e01f63fcb82d7
|
[
"Java"
] | 5
|
Java
|
LuffyGitHub/regCenter
|
a271cfa8eebeab058669a4ca29e3948ea83faa0e
|
e5ea281c53f0dd88735d178a9ebb5abd7b8cb35c
|
refs/heads/main
|
<repo_name>weiinblack/COU_21_5_MoveableCameraInUnity<file_sep>/README.md
# COU_21_5_MoveableCameraInUnity
FPS般的基礎攝影機控制for Unity3D <br>

<file_sep>/MoveableCamera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveableCamera : MonoBehaviour
{
private float _personRotationY = 0;
private Vector3 _persionVeciloty;
[Range(1, 10)]
public float walkingSpeed = 2;
[Range(1, 10)]
public float mouseSensitivity = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
this._persionVeciloty = new Vector3(0, this.transform.parent.GetComponent<Rigidbody>().velocity.y, 0);
if (Input.GetKey(KeyCode.W))
{
this._persionVeciloty += this.transform.parent.forward * walkingSpeed;
}
if (Input.GetKey(KeyCode.S))
{
this._persionVeciloty -= this.transform.parent.forward * walkingSpeed;
}
if (Input.GetKey(KeyCode.D))
{
this._persionVeciloty += this.transform.parent.right * walkingSpeed;
}
if (Input.GetKey(KeyCode.A))
{
this._persionVeciloty -= this.transform.parent.right * walkingSpeed;
}
this.transform.parent.GetComponent<Rigidbody>().velocity = this._persionVeciloty;
this._personRotationY += Input.GetAxis("Mouse X") * mouseSensitivity ;
this.transform.localEulerAngles = new Vector3(Mathf.Clamp(Input.mousePosition.y / Screen.height * -180f + 90f, -90f, 90f),0, 0);
this.transform.parent.localEulerAngles = new Vector3(0, this._personRotationY, 0);
}
}
|
c99320c16f09453aef482b5b2120de383ad98b6f
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
weiinblack/COU_21_5_MoveableCameraInUnity
|
ec309ae73ce713c7e0e547c4bb068ab82f31e2ae
|
0bd929021eecdd2aac6df36eebd6b6976bf86714
|
refs/heads/master
|
<file_sep>(function() {
'use strict';
var DIR = '../',
cl = require('./cl'),
place = require('place'),
rendy = require('rendy'),
shortdate = require('shortdate'),
Info = require(DIR + 'package');
module.exports = function(callback) {
var history = 'Version history\n---------------\n',
link = '//github.com/cloudcmd/archive/raw/master/cloudcmd',
template = '- *{{ date }}*, ' +
'**[v{{ version }}]' +
'(' + link + '-v{{ version }}.tar.gz)**\n',
version = Info.version;
cl(function(error, versionNew) {
if (error) {
callback(error);
} else {
replaceVersion('README.md', version, versionNew, callback);
replaceVersion('HELP.md', version, versionNew, function() {
var historyNew = history + rendy(template, {
date : shortdate(),
version : versionNew
});
replaceVersion('HELP.md', history, historyNew, callback);
});
}
});
};
function replaceVersion(name, version, versionNew, callback) {
place(name, version, versionNew, function(error) {
var msg;
if (!error)
msg = 'done: ' + name;
callback(error, msg);
});
}
})();
<file_sep>(function() {
'use strict';
var gulp = require('gulp'),
jshint = require('gulp-jshint'),
recess = require('gulp-recess'),
mocha = require('gulp-mocha'),
jscs = require('gulp-jscs'),
docs = require('./gulp/docs'),
cloudfunc = require('./test/lib/cloudfunc.js'),
LIB = 'lib/',
LIB_CLIENT = LIB + 'client/',
LIB_SERVER = LIB + 'server/',
Src = [
'*.js',
'test/**/*.js',
'gulp/**/*.js',
LIB + '*.js',
LIB_CLIENT + '/*.js',
LIB_CLIENT + 'storage/*.js',
LIB_SERVER + '/**/*.js'
];
gulp.task('release', function() {
docs(function(e, msg) {
error(e) || console.log(msg);
});
});
gulp.task('jshint', function() {
gulp.src(Src)
.pipe(jshint())
.pipe(jshint.reporter())
.on('error', error);
});
gulp.task('jscs', function () {
return gulp.src(Src)
.pipe(jscs());
});
gulp.task('css', function () {
gulp.src('css/*.css')
.pipe(recess())
.pipe(recess.reporter())
.on('error', error);
});
gulp.task('test', function() {
cloudfunc.check();
gulp.src('test/lib/util.js')
.pipe(mocha({reporter: 'min'}))
.on('error', error);
});
gulp.task('default', ['jshint', 'jscs', 'css', 'test']);
function error(e) {
e && console.error(e.message);
return e;
}
})();
|
08bda73c5c2469af38ef971f0e67456be7b96feb
|
[
"JavaScript"
] | 2
|
JavaScript
|
circleride/cloudcmd
|
7d2f6c5ab0a6fd3660bb6a8c2f408c3d853b2b76
|
be46387b7815bc1b3bd70d7f8f4fee46e77ca794
|
refs/heads/master
|
<file_sep>#! /bin/bash
set -e
# A script to configure openNetVM
# Expected to be run as scripts/install.sh
# CONFIGURATION (via environment variable):
# - Make sure $RTE_TARGET and $RTE_SDK are correct (see install docs)
# - Set $ONVM_NUM_HUGEPAGES to control the number of pages created
# - Set $ONVM_SKIP_FSTAB to not add huge fs to /etc/fstab
if [ -z "$RTE_TARGET" ]; then
echo "Please export \$RTE_TARGET"
exit 1
fi
if [ -z "$RTE_SDK" ]; then
echo "Please export \$RTE_SDK"
exit 1
fi
# Validate sudo access
sudo -v
# Ensure we're working relative to the onvm root directory
if [ $(basename $(pwd)) == "scripts" ]; then
cd ..
fi
# Set state variables
start_dir=$(pwd)
# Compile dpdk
cd $RTE_SDK
echo "Compiling and installing dpdk in $RTE_SDK"
sleep 1
make config T=$RTE_TARGET
make T=$RTE_TARGET -j 8
make install T=$RTE_TARGET -j 8
# Refresh sudo
sudo -v
cd $start_dir
# Configure HugePages
hp_size=$(cat /proc/meminfo | grep Hugepagesize | awk '{print $2}')
hp_count="${ONVM_NUM_HUGEPAGES:-1024}"
echo "Configuring $hp_count hugepages with size $hp_size"
sleep 1
sudo mkdir -p /mnt/huge
# Only add to /etc/fstab if user wants it
if [ -z "$ONVM_SKIP_FSTAB" ]; then
echo "Adding huge fs to /etc/fstab"
sleep 1
sudo sh -c "echo \"huge /mnt/huge hugetlbfs defaults 0 0\" >> /etc/fstab"
fi
echo "Mounting hugepages"
sleep 1
sudo mount -t hugetlbfs nodev /mnt/huge
echo "Creating $hp_count hugepages"
sleep 1
sudo sh -c "echo $hp_count > /sys/devices/system/node/node0/hugepages/hugepages-${hp_size}kB/nr_hugepages"
# Configure local environment
echo "Configuring environment"
sleep 1
scripts/setup_environment.sh
<file_sep>[Branch Details][Branches]
==
Master: < Original fork of OpenNetVM; only for git pull and push to main OpenNetVM-dev >
--
clean_nfvnice: < Fork of clean_sched: for release of NFVNICE code as of SIGCOMM Paper >
--
clean_sched: < Most actively developed code for NF Scheduling, Backpressure, CGROUP features. >
--
diff_ipc_mode: < Earlier code; used to instrument differnt IPC mechanisms and choose best fit of NF/NF_MGR communication >
--
earlier_code_merges: < Do Not Remember; Mostly first working merge of WEIs CoNEXT code >
--
new_merges: < Do Not Remember; Mostly release candidate of merge of WEIs CoNEXT code >
--
nfv_res: < Likely forked of clean_sched or sc_backpressure; for NF Resiliency work>
--
proactive_nf: < Do Not Remember; Discard this >
--
sc_backpressure: < Earliest working code version for chain mode Backpressure >
--
sc0: < Do Not Remember; Discard this >
--
<file_sep>#!/bin/bash
cpu=$1
service=$2
print=$3
if [ -z $service ]
then
echo "$0 [cpu-list] [Service ID] [PRINT]"
echo "$0 3 0 --> core 3, Service ID 0"
echo "$0 3,7,9 1 --> cores 3,7, and 9 with Service ID 1"
echo "$0 3,7,9 1 1000 --> cores 3,7, and 9 with Service ID 1 and Print Rate of 1000"
exit 1
fi
if [ -z $print ]
then
sudo ./build/monitor -l $cpu -n 3 --proc-type=secondary -- -r $service
else
sudo ./build/monitor -l $cpu -n 3 --proc-type=secondary -- -r $service -- -p $print
fi
<file_sep>#!/bin/bash
cpu=$1
service=$2
dst=$3
print=$4
if [ -z $dst ]
then
echo "$0 [cpu-list] [Service ID] [DST] [PRINT]"
echo "$0 3,7,9 1 2 --> cores 3,7, and 9, with Service ID 1, and forwards to service ID 2"
echo "$0 3,7,9 1 2 1000 --> cores 3,7, and 9, with Service ID 1, forwards to service ID 2, and Print Rate of 1000"
exit 1
fi
if [ -z $print ]
then
sudo ./build/speed_tester -l $cpu -n 3 --proc-type=secondary -- -r $service -- -d $dst
else
sudo ./build/speed_tester -l $cpu -n 3 --proc-type=secondary -- -r $service -- -d $dst -p $print
fi
<file_sep>Running openNetVM in Docker
==
Running openNetVM NFs inside Docker containers becomes using the
included [Docker Script][docker]. This script does the following:
- Creates a Docker container with a custom name
- Maps NIC devices from the host into the container
- Maps the shared hugepage region into the container
- Maps the openNetVM directory into the container
- Maps any other directories you want into the container
- Configures the container to use all of the shared memory and data
structures
Usage
--
To use the script, simply run it from the command line with the
following arguments:
```
sudo ./docker.sh DEVICES HUGEPAGES ONVM NAME [DIRECTORY]
```
- `DEVICES - A comma deliniated list of NIC devices to map to the
container`
- `HUGEPAGES - A path to where the hugepage filesystem is on the host`
- `ONVM - A path to the openNetVM directory on the host filesystem`
- `NAME - A name to give the container`
- `DIRECTORY - An optional directory to be mapped into the container`
```
sudo ./docker.sh /dev/uio0,/dev/uio1 /mnt/huge /root/openNetVM
Basic_Monitor_NF
```
- This will start a container with two NIC devices mapped in, /dev/uio0
and /dev/uio1, the hugepage directory at `/mnt/huge` mapped in, and the
openNetVM source directory at `/root/openNetVM` mapped into the
container with the name of Basic_Monitor_NF.
Running NFs Inside Containers
--
To run an NF inside of a container, use the provided script which creates a new container and presents you with its shell. From there, if you run `ls`, you'll see that inside the root directory, there is an `openNetVM` directory. This is the same openNetVM directory that is on your host - it is mapped from your local host into the container. Now enter that directory and go to the example NFs or enter the other directory that you mapped into the container located in the root of the filesystem. From there, you can run the `go.sh` script to run your NF.
Some prerequisites are:
- Compile all applications from your local host. The Docker container is not configured to compile NFs.
- Make sure that the openNetVM manager is running first on your local host.
Here is an example of starting a container and then running an NF inside of it:
```
root@nimbnode /root/openNetVM # ./scripts/docker.sh
sudo ./docker.sh DEVICES HUGEPAGES ONVM NAME [DIRECTORY]
e.g. sudo ./docker.sh /dev/uio0,/dev/uio1 /hugepages /root/openNetVM Basic_Monitor_NF
This will create a container with two NIC devices, uio0 and uio1,
hugepages mapped from the host's /hugepage directory and openNetVM
mapped from /root/openNetVM and it will name it Basic_Monitor_NF
root@nimbnode /root/openNetVM # ./scripts/docker.sh /dev/uio0,/dev/uio1 /hugepages /home/neel/openNetVM ExampleNF
root@2f20c33f9d69:/# ls
bin boot dev etc home hugepages lib lib64 media mnt openNetVM opt proc root run sbin srv sys tmp usr var
root@2f20c33f9d69:/# cd openNetVM/
root@2f20c33f9d69:/openNetVM# ls
CPPLINT.cfg LICENSE Makefile README.md docs dpdk examples onvm scripts style tags
root@2f20c33f9d69:/openNetVM# cd examples/
root@2f20c33f9d69:/openNetVM/examples# ls
Makefile basic_monitor bridge flow_table simple_forward speed_tester test_flow_dir
root@2f20c33f9d69:/openNetVM/examples# cd basic_monitor/
root@2f20c33f9d69:/openNetVM/examples/basic_monitor# ls
Makefile README.md basic_monitor build go.sh monitor.c
root@2<PASSWORD>:/openNetVM/examples/basic_monitor# ./go.sh
./go.sh [cpu-list] [Service ID] [PRINT]
./go.sh 3 0 --> core 3, Service ID 0
./go.sh 3,7,9 1 --> cores 3,7, and 9 with Service ID 1
./go.sh 3,7,9 1 1000 --> cores 3,7, and 9 with Service ID 1 and Print Rate of 1000
root@2<PASSWORD>:/openNetVM/examples/basic_monitor# ./go.sh 3 1
...
```
[docker]: ../scripts/docker.sh
<file_sep>/*********************************************************************
* openNetVM
* https://sdnfv.github.io
*
* BSD LICENSE
*
* Copyright(c)
* 2015-2016 George Washington University
* 2015-2016 University of California Riverside
* 2010-2014 Intel Corporation. All rights reserved.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
********************************************************************/
/******************************************************************************
onvm_stats.c
This file contain the implementation of all functions related to
statistics display in the manager.
******************************************************************************/
#include "onvm_mgr.h"
#include "onvm_stats.h"
#include "onvm_nf.h"
/****************************Interfaces***************************************/
void
onvm_stats_display_all(unsigned difftime) {
onvm_stats_clear_terminal();
onvm_stats_display_ports(difftime);
onvm_stats_display_clients(difftime);
}
void
onvm_stats_clear_all_clients(void) {
unsigned i;
for (i = 0; i < MAX_CLIENTS; i++) {
clients[i].stats.rx = clients[i].stats.rx_drop = 0;
clients[i].stats.act_drop = clients[i].stats.act_tonf = 0;
clients[i].stats.act_next = clients[i].stats.act_out = 0;
}
}
void
onvm_stats_clear_client(uint16_t id) {
clients[id].stats.rx = clients[id].stats.rx_drop = 0;
clients[id].stats.act_drop = clients[id].stats.act_tonf = 0;
clients[id].stats.act_next = clients[id].stats.act_out = 0;
}
/****************************Internal functions*******************************/
void
onvm_stats_display_ports(unsigned difftime) {
unsigned i;
/* Arrays to store last TX/RX count to calculate rate */
static uint64_t tx_last[RTE_MAX_ETHPORTS];
static uint64_t rx_last[RTE_MAX_ETHPORTS];
printf("PORTS\n");
printf("-----\n");
for (i = 0; i < ports->num_ports; i++)
printf("Port %u: '%s'\t", (unsigned)ports->id[i],
onvm_stats_print_MAC(ports->id[i]));
printf("\n\n");
for (i = 0; i < ports->num_ports; i++) {
printf("Port %u - rx: %9"PRIu64" (%9"PRIu64" pps)\t"
"tx: %9"PRIu64" (%9"PRIu64" pps)\n",
(unsigned)ports->id[i],
ports->rx_stats.rx[ports->id[i]],
(ports->rx_stats.rx[ports->id[i]] - rx_last[i])
/difftime,
ports->tx_stats.tx[ports->id[i]],
(ports->tx_stats.tx[ports->id[i]] - tx_last[i])
/difftime);
rx_last[i] = ports->rx_stats.rx[ports->id[i]];
tx_last[i] = ports->tx_stats.tx[ports->id[i]];
}
}
void
onvm_stats_display_clients(unsigned difftime) {
unsigned i;
#ifdef INTERRUPT_SEM
uint64_t vol_rate;
uint64_t rx_drop_rate;
uint64_t serv_rate;
uint64_t serv_drop_rate;
uint64_t rx_qlen;
uint64_t tx_qlen;
uint64_t comp_cost;
uint64_t num_wakeups = 0;
uint64_t prev_num_wakeups = 0;
uint64_t wakeup_rate;
/* unsigned sleep_time = 1; // This info is not availble anymore:
// must move entire wakeup to separate new function onvm_stats_display_client_wakeup_info(difftime)
*/
#else
printf ("diff_time= 0x%4x", difftime);
#endif
#ifdef INTERRUPT_SEM
for (i = 0; i < ONVM_NUM_WAKEUP_THREADS; i++) {
num_wakeups += wakeup_infos[i].num_wakeups;
prev_num_wakeups += wakeup_infos[i].prev_num_wakeups;
wakeup_infos[i].prev_num_wakeups = wakeup_infos[i].num_wakeups;
}
wakeup_rate = (num_wakeups - prev_num_wakeups) / difftime;
printf("num_wakeups=%"PRIu64", wakeup_rate=%"PRIu64"\n", num_wakeups, wakeup_rate);
#endif
printf("\nCLIENTS\n");
printf("-------\n");
for (i = 0; i < MAX_CLIENTS; i++) {
if (!onvm_nf_is_valid(&clients[i]))
continue;
const uint64_t rx = clients[i].stats.rx;
const uint64_t rx_drop = clients[i].stats.rx_drop;
const uint64_t tx = clients_stats->tx[i];
const uint64_t tx_drop = clients_stats->tx_drop[i];
const uint64_t act_drop = clients[i].stats.act_drop;
const uint64_t act_next = clients[i].stats.act_next;
const uint64_t act_out = clients[i].stats.act_out;
const uint64_t act_tonf = clients[i].stats.act_tonf;
const uint64_t act_buffer = clients_stats->tx_buffer[i];
const uint64_t act_returned = clients_stats->tx_returned[i];
printf("Client %2u - rx: %9"PRIu64" rx_drop: %9"PRIu64" next: %9"PRIu64" drop: %9"PRIu64" ret: %9"PRIu64"\n"
"tx: %9"PRIu64" tx_drop: %9"PRIu64" out: %9"PRIu64" tonf: %9"PRIu64" buf: %9"PRIu64"\n",
clients[i].info->instance_id,
rx, rx_drop, act_next, act_drop, act_returned,
tx, tx_drop, act_out, act_tonf, act_buffer);
#ifdef INTERRUPT_SEM
/* periodic/rate specific statistics of NF instance */
const uint64_t prev_rx = clients[i].stats.prev_rx;
const uint64_t prev_rx_drop = clients[i].stats.prev_rx_drop;
const uint64_t prev_tx = clients_stats->prev_tx[i];
const uint64_t prev_tx_drop = clients_stats->prev_tx_drop[i];
vol_rate = (rx - prev_rx) / difftime;
rx_drop_rate = (rx_drop - prev_rx_drop) / difftime;
serv_rate = (tx - prev_tx) / difftime;
serv_drop_rate = (tx_drop - prev_tx_drop) / difftime;
rx_qlen = rte_ring_count(clients[i].rx_q);
tx_qlen = rte_ring_count(clients[i].tx_q);
comp_cost = clients_stats->comp_cost[i];
printf("instance_id=%d, vol_rate=%"PRIu64", rx_drop_rate=%"PRIu64","
" comp_cost=%"PRIu64", serv_rate=%"PRIu64","
"serv_drop_rate=%"PRIu64", rx_qlen=%"PRIu64", tx_qlen=%"PRIu64", msg_flag=%d\n",
clients[i].info->instance_id, vol_rate, rx_drop_rate, comp_cost,
serv_rate, serv_drop_rate, rx_qlen, tx_qlen, rte_atomic16_read(clients[i].shm_server));
//clients[i].stats.prev_rx = clients[i].stats.rx;
//clients[i].stats.prev_rx_drop = clients[i].stats.rx_drop;
//clients_stats->prev_tx[i] = clients_stats->tx[i];
//clients_stats->prev_tx_drop[i] = clients_stats->tx_drop[i];
#endif
}
printf("\n");
}
/***************************Helper functions**********************************/
void
onvm_stats_clear_terminal(void) {
const char clr[] = { 27, '[', '2', 'J', '\0' };
const char topLeft[] = { 27, '[', '1', ';', '1', 'H', '\0' };
printf("%s%s", clr, topLeft);
}
const char *
onvm_stats_print_MAC(uint8_t port) {
static const char err_address[] = "00:00:00:00:00:00";
static char addresses[RTE_MAX_ETHPORTS][sizeof(err_address)];
if (unlikely(port >= RTE_MAX_ETHPORTS))
return err_address;
if (unlikely(addresses[port][0] == '\0')) {
struct ether_addr mac;
rte_eth_macaddr_get(port, &mac);
snprintf(addresses[port], sizeof(addresses[port]),
"%02x:%02x:%02x:%02x:%02x:%02x\n",
mac.addr_bytes[0], mac.addr_bytes[1],
mac.addr_bytes[2], mac.addr_bytes[3],
mac.addr_bytes[4], mac.addr_bytes[5]);
}
return addresses[port];
}
<file_sep>#!/bin/bash
cpu=$1
service=$2
print=$3
if [ -z $service ]
then
echo "$0 [cpu-list] [Service ID] [PRINT]"
echo "$0 3,4 1 --> cores 3,4 with Service ID of 1"
echo "$0 3,4 1 10000 --> cores 3,4 with Service ID of 1 and print rate of 10000 packets"
exit 1
fi
if [ -z $print ]
then
sudo ./flow_table/$RTE_TARGET/flow_table -l $cpu -n 3 --proc-type=secondary -- -r $service
else
sudo ./flow_table/$RTE_TARGET/flow_table -l $cpu -n 3 --proc-type=secondary -- -r $service -- $print
fi
<file_sep>/*********************************************************************
* openNetVM
* https://sdnfv.github.io
*
* BSD LICENSE
*
* Copyright(c)
* 2015-2016 George Washington University
* 2015-2016 University of California Riverside
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
********************************************************************/
/******************************************************************************
onvm_nflib_internal.h
Header file for all internal functions used within the API
******************************************************************************/
#ifndef _ONVM_NFLIB_INTERNAL_H_
#define _ONVM_NFLIB_INTERNAL_H_
/***************************Standard C library********************************/
#include <getopt.h>
#include <signal.h>
//#ifdef INTERRUPT_SEM //move maro to makefile, otherwise uncomemnt or need to include these after including common.h
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <semaphore.h>
#include <fcntl.h>
//#endif //INTERRUPT_SEM
/*****************************Internal headers********************************/
#include "onvm_includes.h"
#include "onvm_sc_common.h"
/**********************************Macros*************************************/
// Number of packets to attempt to read from queue
#define PKT_READ_SIZE ((uint16_t)32)
/******************************Global Variables*******************************/
// ring used to place new nf_info struct
static struct rte_ring *nf_info_ring;
// rings used to pass packets between NFlib and NFmgr
static struct rte_ring *tx_ring, *rx_ring;
// shared data from server. We update statistics here
static volatile struct client_tx_stats *tx_stats;
// Shared data for client info
extern struct onvm_nf_info *nf_info;
// Shared pool for all clients info
static struct rte_mempool *nf_info_mp;
// User-given NF Client ID (defaults to manager assigned)
static uint16_t initial_instance_id = NF_NO_ID;
// User supplied service ID
static uint16_t service_id = -1;
// True as long as the NF should keep processing packets
static uint8_t keep_running = 1;
// Shared data for default service chain
static struct onvm_service_chain *default_chain;
#ifdef INTERRUPT_SEM
// to track packets per NF <used for sampling computation cost>
uint64_t counter = 0;
// flag (shared mem variable) to track state of NF and trigger wakeups
// flag_p=1 => NF sleeping (waiting on semaphore)
// flag_p=0 => NF is running and processing (not waiting on semaphore)
static rte_atomic16_t *flag_p;
// Mutex for sem_wait
static sem_t *mutex;
#endif //INTERRUPT_SEM
/******************************Internal functions*****************************/
/*
* Function that initialize a nf info data structure.
*
* Input : the tag to name the NF
* Output : the data structure initialized
*
*/
static struct onvm_nf_info *
onvm_nflib_info_init(const char *tag);
/*
* Function printing an explanation of command line instruction for a NF.
*
* Input : name of the executable containing the NF
*
*/
static void
onvm_nflib_usage(const char *progname);
/*
* Function that parses the global arguments common to all NFs.
*
* Input : the number of arguments (following C standard library convention)
* an array of strings representing these arguments
* Output : an error code
*
*/
static int
onvm_nflib_parse_args(int argc, char *argv[]);
/*
* Signal handler to catch SIGINT.
*
* Input : int corresponding to the signal catched
*
*/
static void
onvm_nflib_handle_signal(int sig);
#ifdef INTERRUPT_SEM
/*
* Function to initalize the shared cpu support
*
* Input : Number of NF instances
*/
static void
init_shared_cpu_info(uint16_t instance_id);
#endif //INTERRUPT_SEM
#endif // _ONVM_NFLIB_INTERNAL_H_
<file_sep>#!/bin/bash
# openNetVM
# https://sdnfv.github.io
#
# OpenNetVM is distributed under the following BSD LICENSE:
#
# Copyright(c)
# 2015-2016 George Washington University
# 2015-2016 University of California Riverside
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Intel Corporation nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
RAW_DEVICES=$1
HUGE=$2
ONVM=$3
NAME=$4
DIR=$5
DEVICES=()
if [ -z $NAME ]
then
echo -e "sudo ./docker.sh DEVICES HUGEPAGES ONVM NAME [DIRECTORY]\n"
echo -e "\te.g. sudo ./docker.sh /dev/uio0,/dev/uio1 /hugepages /root/openNetVM Basic_Monitor_NF"
echo -e "\t\tThis will create a container with two NIC devices, uio0 and uio1,"
echo -e "\t\thugepages mapped from the host's /hugepage directory and openNetVM"
echo -e "\t\tmapped from /root/openNetVM and it will name it Basic_Monitor_NF"
exit 1
fi
IFS=','
for DEV in $RAW_DEVICES
do
DEVICES+=("--device=$DEV:$DEV")
done
if [ -z $DIR ]
then
sudo docker run -it --privileged ${DEVICES[@]} -v /var/run:/var/run -v $HUGE:$HUGE -v $ONVM:/openNetVM --name=$NAME ubuntu /bin/bash
else
sudo docker run -it --privileged ${DEVICES[@]} -v /var/run:/var/run -v $HUGE:$HUGE -v $ONVM:/openNetVM -v $DIR:/$(basename $DIR) --name=$NAME ubuntu /bin/bash
fi
<file_sep>#! /bin/bash
set -e
# A script to configure your environment each boot
# Loads the uio kernel modules, shows NIC status
# CONFIGURATION (via environment variable):
# - Ensure that $RTE_SDK and $RTE_TARGET are set (see install docs)
# - Set ONVM_NIC to the name of the interface you want to bind (default p2p1)
# - Can set ONVM_NIC_PCI to the PCI address of the interface (default 07:00.0)
# Confirm environment variables
if [ -z "$RTE_TARGET" ]; then
echo "Please export \$RTE_TARGET"
exit 1
fi
if [ -z "$RTE_SDK" ]; then
echo "Please export \$RTE_SDK"
exit 1
fi
# Ensure we're working relative to the onvm root directory
if [ $(basename $(pwd)) == "scripts" ]; then
cd ..
fi
start_dir=$(pwd)
# Disable ASLR
sudo sh -c "echo 0 > /proc/sys/kernel/randomize_va_space"
# Setup/Check for free HugePages
hp_size=$(cat /proc/meminfo | grep Hugepagesize | awk '{print $2}')
hp_count="${ONVM_NUM_HUGEPAGES:-1024}"
sudo sh -c "echo $hp_count > /sys/devices/system/node/node0/hugepages/hugepages-${hp_size}kB/nr_hugepages"
hp_free=$(cat /proc/meminfo | grep HugePages_Free | awk '{print $2}')
if [ $hp_free == "0" ]; then
echo "No free huge pages. Did you try turning it off and on again?"
exit 1
fi
# Verify sudo access
sudo -v
# Load uio kernel modules
grep -m 1 "igb_uio" /proc/modules | cat
if [ ${PIPESTATUS[0]} != 0 ]; then
echo "Loading uio kernel modules"
sleep 1
cd $RTE_SDK/$RTE_TARGET/kmod
sudo modprobe uio
sudo insmod igb_uio.ko
else
echo "IGB UIO module already loaded."
fi
echo "Checking NIC status"
sleep 1
$RTE_SDK/tools/dpdk_nic_bind.py --status
echo "Binding NIC status"
if [ -z "$ONVM_NIC_PCI" ];then
for id in $($RTE_SDK/tools/dpdk_nic_bind.py --status | grep -v Active | grep -e "10G" -e "10-Gigabit" | grep unused=igb_uio | cut -f 1 -d " ")
do
read -r -p "Bind interface $id to DPDK? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]];then
echo "Binding $id to dpdk"
sudo $RTE_SDK/tools/dpdk_nic_bind.py -b igb_uio $id
fi
done
else
# Auto binding example format: export ONVM_NIC_PCI=" 07:00.0 07:00.1 "
for nic_id in $ONVM_NIC_PCI
do
echo "Binding $nic_id to DPDK"
sudo $RTE_SDK/tools/dpdk_nic_bind.py -b igb_uio $id
done
fi
echo "Finished Binding"
$RTE_SDK/tools/dpdk_nic_bind.py --status
<file_sep>#! /bin/bash
# A script to configure dpdk environment variables on the cloudlab server
DPDK_PATH=/local/onvm/openNetVM/dpdk
if [ -z "$RTE_TARGET" ]; then
export RTE_TARGET=x86_64-native-linuxapp-gcc
fi
if [ -z "$RTE_SDK" ]; then
export RTE_SDK=$DPDK_PATH
fi
|
8dc46578a2206c8b20af191e7c21819471dfc34b
|
[
"Markdown",
"C",
"Shell"
] | 11
|
Shell
|
sameergk/REINFORCE_SOURCE
|
4665ff935d60afd463c2afbb7cf6f16b9fef3836
|
4e8c8e0f05d6dda37f6467c9748e4b43417f502a
|
refs/heads/master
|
<repo_name>sammazhao/CSharpLearning<file_sep>/StartNow/StartNow/ClassDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class ClassDemo
{
}
abstract class Animal //抽象类,只能继承,不能实例化,没有构造函数
{
public void Running()
{
Console.WriteLine($"I can run!!");
}
public int age;
public Sex sex;
}
class Dog : Animal
{
}
}
<file_sep>/README.md
# cSharpLearning
包含c#基础知识和对应的demo
<file_sep>/StartNow/StartNow/OverrideDemoSub1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
public class OverrideDemoSub1 : OverrideDemo
{
/// <summary>
/// override 发生在父类和子类之间的, 是纵向的关系
/// </summary>
/// <param name="s"></param>
public override void Show(string s)
{
s = $"{s}+++++++++++++++++++++++++{s}";
base.Show(s);
}
/// <summary>
/// overload 发生在同一个类, 是平行关系
/// </summary>
public void Show1()
{
Console.WriteLine("this is function of show1.");
}
public string Show1(string s)
{
Console.WriteLine("this is function of show1 with parameter s.");
return s;
}
}
}
<file_sep>/StartNow/StartNow/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class Program
{
static void Main(string[] args)
{
//Cat babyCat = new Cat();
//babyCat.Name = "xiaominhg";
//babyCat.Age = 2;
//babyCat.Sex = "female";
////$是string.format中的新特性
//string msg = $"I'm a new born baby cat, " +
// $"my name is {babyCat.Name}, my age is {babyCat.Age}, " +
// $"my sex is {babyCat.Sex}";
//Console.WriteLine(msg);
//Console.ReadKey();
//Console.WriteLine("Please input a number:");
//Sanyuan sanyuan = new Sanyuan();
//var input = int.Parse(Console.ReadLine());
//sanyuan.PanDuan(input);
//const string myName = "Mona";
//const string SBName = "Dennis";
//const string goodName = "Samma";
//string name;
//Console.WriteLine ("What is your name?");
//name = Console.ReadLine();
//switch (name.ToLower())
//{
// case myName:
// Console.WriteLine("{0}, Your name is same as mine", myName);
// break;
// case SBName:
// Console.WriteLine("{0}, this name is too stupid", SBName);
// break;
// case goodName:
// Console.WriteLine("{0}, this name is good", goodName);
// break;
// default:
// Console.WriteLine("Hi {0}", name);
// break;
//}
//LoopTest looptest = new LoopTest();
////looptest.DoWhile();
//int returnResult=looptest.TestWhile(1);
//Console.WriteLine("return result is: {0}", returnResult);
//testPractice testpractice = new testPractice();
//while (testpractice.TestNumInput())
//{
//}
//LunchType lunchToday = LunchType.hamburger;
//Console.WriteLine("I want to eat {0} today", lunchToday);
//string[] myStringArray=new string[3];
//myStringArray[0] = "Hi";
//myStringArray[1] = "xiongda";
//myStringArray[2] = "xionger";
//int[] myArray=new int[5];
//myArray[0] = 22;
////myArray[1] = 33;
//Console.WriteLine($"the resule is {myArray[0]},{myArray[4]}, totally there are {myArray.Length} items in the array");
//string[] friendsArray = new string[6] { "samma", "mona", "ruby", "dennis", "izzie", "tina" };
//foreach (string friend in friendsArray)
//{
// Console.WriteLine( $"Here is my friend {friend}");
//}
//string myStr = "This is a string!";
//char[] myChar = myStr.ToCharArray();
//foreach (char s in myStr)
//{
// Console.WriteLine($"the result is {s}");
//}
//Console.WriteLine($"{myStr.Length}");
//foreach (char s in myChar)
//{
// Console.WriteLine($"the result is: {s}");
//}
//ManipulateStringTest manitest = new ManipulateStringTest();
//manitest.ManiTestLoopString();
////Login login = new Login();
////login.UserLogin();
//Console.WriteLine("Please input a number: ");
//string testStr = Console.ReadLine();
//var result=Convert.ToInt32(testStr);
//Console.WriteLine(result);
////Console.WriteLine("i want to eat: " + Enum.GetName(typeof(LunchType), 2));
////string[] array1 = Enum.GetNames(typeof(LunchType));
////Console.WriteLine("tomorrow i want to eat: " + array1[3]);
////string[] array2 = Enum.GetNames(typeof(LunchType));
////Console.WriteLine("yesterday i ate: " + array2.GetValue(4));
///// 2019/06/08
//OrderStatus actualStatus = OrderStatus.ordercomplete;
//Console.WriteLine("the order status is: " + actualStatus + "status code is: " + (int)actualStatus);
//Console.ReadKey();
///// 2019/06/09
//ArrayDemo arrayDemo = new ArrayDemo();
//arrayDemo.TestArrayFuntion();
//arrayDemo.TestArrayFunction2();
//arrayDemo.TestArrayFunction3();
//CaseSwitchDemo caseSwitchDemo = new CaseSwitchDemo();
//caseSwitchDemo.CaseSwitchFunction();
//ArrayDemo arrayDemo = new ArrayDemo();
////arrayDemo.MultiArray();
////arrayDemo.MultiArray2();
////arrayDemo.ManipulateStringTest();
//arrayDemo.ToupperTest();
//arrayDemo.ToTrimTest();
////2019/06/11
//int result=hanshuDemo.StaticFunction();
//Console.WriteLine("return value is: {0}", result);
//int[] testArray = new int[5] { 3, 6, 1, 20, 5 };
//int result=hanshuDemo.MaxValue(testArray);
//Console.WriteLine("The max value is: {0}", result);
//int result=hanshuDemo.SumValues(1, 10, 3);
//Console.WriteLine("The sum value is: {0}", result);
//int myValue = 5;
//Console.WriteLine("my value is {0}", myValue);
//hanshuDemo.showDouble(ref myValue);
//Console.WriteLine("my value is {0}", myValue);
//2019/06/12
//hanshuDemo.testFun();
//hanshuDemo.testFun2();
//int myNum = 5;
//Console.WriteLine($"number in main is {myNum}");
//hanshuDemo.testFun3(myNum);
//Console.ReadKey();
//2019/06/21 类练习
Dog aDog = new Dog();
aDog.Running();
Console.ReadKey();
}
}
}
<file_sep>/StartNow/StartNow/EnumDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
enum LunchType:byte
{
pizza = 1,
hamburger = 2,
beef = 3,
noodle = 4,
salad = 5,
sushi = 6
}
//public class testPractice
//{
// public enum LunchType
// {
// pizza=1,
// hamburger=2,
// beef=3,
// noodle=4,
// salad=5,
// sushi=6
// }
//public bool TestNumInput()
//{
// Console.WriteLine("Please input number1");
// int num1 = Convert.ToInt32(Console.ReadLine());
// Console.WriteLine("Please input number2");
// int num2 = Convert.ToInt32(Console.ReadLine());
// while(num1 <= 10)
// if (num1 > 10)
// {
// if (num2 <= 10)
// {
// Console.WriteLine("The numbers you input are {0}, {1}", num1, num2);
// return true;
// break;
// }
// else
// {
// return false;
// }
// }
// else
// {
// Console.WriteLine("The numbers you input are {0}, {1}", num1, num2);
// }
// while ()
//}
public enum OrderStatus
{
invalid=0,
askprice=1,
placeorder=2,
payment=3,
ordercancal=101,
ordercomplete=102,
}
public enum Sex
{
Male=0,
Female=1
}
}
<file_sep>/StartNow/StartNow/ArrayDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
public class ArrayDemo
{
/// <summary>
/// Use initialize and define the length of array.
/// </summary>
public void TestArrayFuntion()
{
int[] numArray = new int[6];
for (int i=0; i < numArray.Count(); i++)
{
Console.WriteLine("The number is {0}", numArray[i]);
}
}
/// <summary>
/// directly assign values for each element in array.
/// </summary>
public void TestArrayFunction2()
{
string[] strArray = { "this", "is", "demo", "for", "array", "" };
for (int i = 0; i < strArray.Count(); i++)
{
Console.WriteLine("Index is: {0}, value is {1}.", i, strArray[i]);
}
}
/// <summary>
/// Initialize new array object and same time define the length and each elements of this array.
/// </summary>
/// <returns></returns>
public int[] TestArrayFunction3()
{
int[] numArrayNew = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("The array length is: {0}", numArrayNew.Count());
return numArrayNew;
}
///////////////多维数组////////////////////
/// <summary>
/// 1. 矩形数组
/// </summary>
public void MultiArray()
{
//声明多维数组法1
int[,] hillHight = { {3,2 }, {1,2 }, {6,7 } };
//声明多维数组法2
int[,] hillHight2 = new int[3, 2];
foreach (int height in hillHight)
{
Console.WriteLine("Hill value: {0}", height);
}
}
/// <summary>
/// 2. 锯齿数组,声明并初始化
/// </summary>
public void MultiArray2()
{
int[][] tableContentArray = { new int[] { 8, 2, 3 }, new int[] { 999 }, new int[] { 3, 4 } };
////需要先循环数组中子数组个数,再循环每个子数组中的元素
for (int i = 0; i < tableContentArray.Count(); i++)
{
Console.WriteLine("Start to traversal Sub array {0}", i + 1);
foreach (int j in tableContentArray[i])
{
Console.WriteLine("Elements in sub array {0}: {1}", i+1, j);
}
}
}
/////////字符串处理//////////////////
//string类型变量可以看做Char变量的只读数组
public void ManipulateStringTest()
{
string testStr = "This is a test string.";
char[] testChars = testStr.ToCharArray();
foreach (char i in testChars)
{
Console.WriteLine(i);
}
Console.WriteLine("char array length is: {0}", testChars.Length);
}
/// <summary>
/// 同理还有ToLower
/// </summary>
public void ToupperTest()
{
Console.WriteLine("Please input yes");
string userInput = Console.ReadLine();
if (userInput.ToUpper() == "YES")
{
userInput = userInput.ToUpper();
Console.WriteLine(userInput);
}
}
/// <summary>
/// trim去除字符串首尾的空格
/// </summary>
public void ToTrimTest()
{
Console.WriteLine("Please input a string: ");
string userInput = Console.ReadLine();
userInput = userInput.Trim();
Console.WriteLine("what you input is:{0} ", userInput);
}
}
}
<file_sep>/StartNow/StartNow/Login.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace StartNow
{
class Login
{
public void UserLogin()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://www.jd.com/");
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
driver.Close();
}
}
}
<file_sep>/StartNow/StartNow/InterfaceDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class InterfaceDemo
{
//
}
}
<file_sep>/Util/DelegateDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SammaTestApp
{
class DelegateDemo
{
}
}
<file_sep>/Util/ArrayListDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SammaTestApp
{
class ArrayListDemo
{
//private int[] testArray = new int[5] { 2, 4, 7, 6, 8 };
public static int GetArrayLength(Object[] obj)
{
int res = obj.Length;
return res;
}
public static int GetIndexObject(Object[] obj, Object obj2)
{
int ret2 = Array.IndexOf(obj, obj2);
return ret2;
}
public static string[] ReturnStringArray(Object[] obj)
{
string[] res = new string[obj.Length];
for (int i = 0; i < obj.Length; i++)
{
res[i] = obj[i].ToString();
}
return res;
}
}
}
<file_sep>/StartNow/StartNow/OverrideDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
/// <summary>
/// abstract
/// </summary>
public abstract class OverrideDemo
{
public virtual void Show(string s)
{
Console.WriteLine($"i am show in father method.{s}");
}
}
}
<file_sep>/StartNow/StartNow/Cat.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class CatOld
{
private string name;
private int age;
private string sex;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int Age //get访问器get到并返回该字段age的值。set访问器给这个字段赋值
{
get { return this.age; }
set { this.age = value; }
}
public string Sex
{
get { return this.sex; }
set { this.sex = value; }
}
}
}
<file_sep>/StartNow/StartNow/OOPDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class OOPDemo
{
//理解对象:对象时OOP应用程序的一个构件,这个构件封装了部分应用程序,可以是一个过程,一些数据或一些更抽象的实体
//类和对象:对象的类型是类。可以使用类的定义来实例化对象。类的实例=对象
//属性和字段:属性不能直接访问 private。通常将字段设为私有,通过公共属性访问他。公共属性禁止外部用户访问这些数据
//构造函数:每个类定义都至少有一个构造函数,默认的构造函数没有参数,与类名相同。也可以类定义包含参数的构造函数
//静态构造函数:一个类只有一个,不能有访问修饰符,不带任何参数,不能直接调用。
//只有在1.创建包含静态构造函数的类实例时。2. 访问白喊静态构造函数的类的静态成员时。会先调用静态构造
//析构函数:清理对象。
//静态成员:静态属性,方法---全局对象,使用静态成员时,不需要实例化对象。 如 Console.writeline()
///////////////////////////面向对象技术包含内容////////////////////////////////////////
//1. 接口
//2. 继承 派生类可以访问基类的public, protected,不能访问private。 外部类只能访问public。
// sealed类:不能用作基类,没有派生类。
//3. 多态性
//引用类型和值类型区别: 值类型总是包含一个值,引用类型可以为null。创建的每个类都是引用类型
//class修饰符:
//默认: internal - 只能当前项目中代码访问。public - 其他项目中代码也可以访问。abstract - 不能实例化,只能继承,可以有抽象成员
// sealed - 不能继承
//类中定义指定继承:
//1. 继承基类: public class MyClass : MyBase。 类定义中只能有一个基类。派生类的可访问性不能高于基类。所以下述代码错误:
// internal class ClassFather
// public class ClassChild : ClassFather
//2. 继承接口 eg: public class MyClass : IMyInterface
// 支持该接口的类必须实现所有接口成员,如果不想使用给定的接口成员,可以提供空的方式即代码为空来实现。
// 顺序:冒号后先基类,后接口,可以有多个接口
// public class MyClass : MyBase, IMyInterface1, IMyInterface2
}
public abstract class MyBase { } // 抽象类,只能继承,不能实例化
public interface IMyBaseInterface { }
internal interface IMyBaseInterface2 { }
internal interface IMyInterface : IMyBaseInterface, IMyBaseInterface2 { }
internal sealed class MyComplexClass : MyBase, IMyBaseInterface { } // sealed类,不能继承
//构造函数
internal class Cat
{
//默认构造函数
public Cat()
{
}
//非默认构造函数
public Cat(string type)
{
Console.WriteLine($"Cat of type: {type}");
}
}
//析构函数。 当进行垃圾回收时,执行析构函数中的代码,释放资源
class MyClassNew
{
~MyClassNew()
{
}
}
// 实例化派生类时,先实例化基类。
//构造函数执行顺序。 发生构造函数调用错误通常是因为类继承结构中某个基类没有正确实例化,或没有正确的给基类构造函数提供信息。
public class MyBaseClass
{
public MyBaseClass()
{ }
public MyBaseClass(int i) { }
}
}
<file_sep>/TestStringJoin.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SammaTestApp
{
class TestStringJoin
{
public string TestFunction()
{
string[] sammaarry = { "hello", "1", "am", "34" };
string newarray = String.Join(" ", sammaarry);
return newarray;
}
public string Tsfunction2()
{
DateTime waiting = new DateTime(2018, 11, 21, 12, 15, 32);
string chat = String.Format("message sent at {0:t} on {0:D}", waiting);
Console.WriteLine("message:{0}", chat);
Console.ReadKey();
}
}
}
<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SammaTestApp
{
class Program
{
static void Main(string[] args)
{
try
{
//ArrayListDemo testArray = new ArrayListDemo();
//string final = testArray.GetArrayString();
//int final2 = testArray.GetIndexObject();
//Console.WriteLine("result is: {0}, index of array is {1}", final, final2);
//Console.ReadKey();
TestStringJoin teststringjoin = new TestStringJoin();
//string a =teststringjoin.TestFunction();
//Console.WriteLine("result is: {0}", a);
//Console.ReadKey();
string b = teststringjoin.Tsfunction2();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}<file_sep>/StartNow/StartNow/ManipulateStringTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class ManipulateStringTest
{
public void ManiTestLoopString()//遍历循环字符串(字符数组)中的每个字符
{
string mystr1 = "This is to test foreach function in string";
//char[] mychar = mystr1.ToCharArray();
foreach (char s in mystr1)
{
Console.WriteLine($"{s}");
}
//输出字符串中字符个数
Console.WriteLine($"{mystr1.Length}");
//将字符串中所有字符都小写,并未改变原来字符串
Console.WriteLine($"{mystr1.ToLower()}");
//删除字符串前后的空格
string strWithSpace = " Ha Ha ";
Console.WriteLine($"{strWithSpace.Trim()}");
//删除字符串前后的指定字符
string inpputStr = ",MY name is Mona,-";
char[] trimChars = {' ', ',', '-'};
string result = inpputStr.ToLower().Trim(trimChars);
Console.WriteLine($"String after manipulation: {result}");
//左右对齐
List<string> numList = new List<string> {"23","23453244", "1", "234"};
foreach (string s in numList)
{
Console.WriteLine($"{s.PadLeft(10)}");
}
Console.ReadKey();
}
}
}
<file_sep>/StartNow/StartNow/hanshuDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class hanshuDemo
{
public static string myStr = "this is global string";
public static int StaticFunction() //静态方法可以不用初始化。
{
int para1 = 33;
Console.WriteLine("This is a static function. No mwwd to initialize a object of this function");
//当执行到return语句时。程序立即返回嗲用代码,该语句后面的代码都不会再执行。return必须在方法结束}之前加上。
return para1;
}
/// <summary>
/// 返回一个数组中的最大值
/// </summary>
/// <param name="intArray"></param>
/// <returns></returns>
public static int MaxValue(int[] intArray)
{
int max = intArray[0];
for (int i = 0; i < intArray.Count(); i++)
{
if (intArray[i] > max)
{
max = intArray[i];
}
}
return max;
}
/// <summary>
/// 使用参数数组,关键字params, 可以传入任意个该类型的参数
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public static int SumValues(params int[] values)
{
int sum = 0;
foreach (int val in values)
{
sum += val;
}
return sum;
}
public static void showDouble(ref int val)
{
val *= 2;
Console.WriteLine("result is: {0}", val);
}
public static void testRef()
{
//ref作为局部变量使用
int val1 = 3;
ref int val2 = ref val1;
val2 = 88;
Console.WriteLine("{0}, {1}", val1, val2);
Console.ReadKey();
}
/// <summary>
/// ref作为返回值使用
/// </summary>
/// <param name="val">parameter</param>
/// <returns>value</returns>
public static ref int testRef2(ref int val)
{
val *= 2;
return ref val;
}
///////////////////////////变量作用域/////////////////////////
//定义静态全局变量.
//Q: 当全局和局部重名,如何使用全局?
public static void testFun()
{
string myStr = "this is defined in testFun";
Console.WriteLine("Now in testFun string: {0}", myStr);
Console.WriteLine($"Now in global string: {myStr}");
}
//在分支和循环中的变量作用域
public static void testFun2()
{
string text = string.Empty; //使用变量前需要对变量进行声明和初始化,该局部变量可以在循环内外部使用。
for (int i = 0; i < 5; i++)
{
text = $"Line {Convert.ToString(i)}";
}
Console.WriteLine($"last output line is: {text}");
}
public static void testFun3(int val)
{
val *= 2;
Console.WriteLine($"local -val={val}");
}
///////////////////////////函数重载////////////////////////////////
//同名函数,每个函数使用不同的参数类型,只有返回值类型不同的不行
}
}
<file_sep>/StartNow/EncapsulateInheritMultipleshapeProject/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EncapsulateInheritMultipleshapeProject
{
abstract public class Pet
{
//在基类中初始化
public Pet(string name)
{
_name = name;
}
protected string _name;
public void PrintName()
{
Console.WriteLine("Pet name is" + _name);
}
abstract public void Speak();
}
// 定义一个派生类,其中包含静态方法,静态成员,普通方法
public class Dog : Pet
{
//定义静态成员
static int Num;
//定义一个静态方法
static public void ShowNum()
{
Console.WriteLine("Dog count is: " + Num);
}
//定义静态构造函数对静态成员进行初始化
static Dog()
{
Num = 0;
}
public Dog(string name) : base(name)
{
//普通方法可以访问静态成员
++Num;
}
sealed public override void Speak()
{
Console.WriteLine(_name + " is speaking" + " Wang!!");
}
}
public class Cat : Pet, ICatchMouse, IClimbTree
{
public Cat(string name) : base(name)
{
}
//实现接口的类,在其中声明继承的接口,并在类中实现接口中定义的方法
public void CatchMouse()
{
Console.WriteLine("I can catch mouse");
}
public void ClimbTree()
{
Console.WriteLine("I can climb tree");
}
//通过new关键字,隐藏父类方法
new public void PrintName()
{
Console.WriteLine("Cat name is" + _name);
}
public override void Speak()
{
Console.WriteLine(_name + " is speaking" + " Miao!!");
}
}
//定义一个静态类,用来扩展方法
static class PetGuide
{
static public void HowToFeedDog(this Dog dog)
{
Console.WriteLine("play a vedio about how to feed a dog");
}
}
//定义一个结构
struct fish
{
int weight;
int size;
string type;
}
//定义一个接口,其中包含一个方法,这个方法是public的但不能声明public
interface ICatchMouse
{
void CatchMouse();
}
interface IClimbTree
{
void ClimbTree();
}
class Program
{
static void Main(string[] args)
{
Pet[] pets = new Pet[] { new Dog("Wangcai"), new Cat("Xiaoming"), new Dog("xiaoPeng")};
//也可以使用基类的引用,只能调用基类中的方法
//Pet dog2 = new Dog("xxx");
for (int i = 0; i < pets.Length; i++)
{
pets[i].Speak();
}
Console.ReadKey();
Cat xiaoming = new Cat("xiaoming");
ICatchMouse icatchmouse = (ICatchMouse)xiaoming;
IClimbTree iclimbtree = (IClimbTree)xiaoming;
//通过对象调用
xiaoming.CatchMouse();
xiaoming.ClimbTree();
//通过接口调用
icatchmouse.CatchMouse();
iclimbtree.ClimbTree();
Console.ReadKey();
//调用静态方法
Dog.ShowNum();
Console.ReadKey();
//使用静态类扩展的方法
Dog dog = new Dog("ergouzi");
dog.HowToFeedDog();
Console.ReadKey();
}
}
}<file_sep>/StartNow/StartNow/LoopTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class LoopTest
{
public int DoWhile(int input=1)// do while循环至少会执行一次,因为循环中的布尔测试是在do之后进行的
{
do
{
Console.WriteLine("{0}", input++);
}
while (input <= 10);
return input;
}
public int TestWhile(int input)//while循环的布尔测试时在循环开始时进行的,如果为false,则不会执行循环
{
while (input <= 5)
{
Console.WriteLine("{0}", input++);
}
return input;
}
public void TestFor(int input)
{
for (input = 1; input <= 10; ++input)
{
Console.WriteLine("{0}", input);
}
}
}
}
<file_sep>/Util/GetSetDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SammaTestApp
{
public class GetSetDemo
{
private double width;
public double Width
{
get { return width; }
set { width = value; }
}
private double length;
public double Length { get; set; }
public double GetArea()
{
return length * width;
}
public void Display()
{
try
{
Guid id = new Guid();
Console.WriteLine("length is: {0}", length);
Console.WriteLine("width is: {0}", width);
Console.WriteLine("Area is: {0}", GetArea());
}
catch (Exception e)
{
}
}
}
}
<file_sep>/StartNow/StartNow/sanyuan.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
class Sanyuan
{
public void PanDuan(int number)
{
string result = (number > 10) ? number.ToString() : "Less than or equal to 10";
Console.WriteLine("Result is : {0}", result);
}
}
}
<file_sep>/StartNow/StartNow/CaseSwitchDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StartNow
{
public class CaseSwitchDemo
{
public void CaseSwitchFunction()
{
string[] dayName = { "Mon.", "Tue.", "Sun." };
foreach (var name in dayName)
{
switch (name)
{
case "Mon.":
Console.WriteLine("It is {0} today, we should work", name);
break;
case "Tue.":
Console.WriteLine("It is {0} today, we should work", name);
break;
case "Sun.":
Console.WriteLine("It is {0}, we should play and be happy. ", name);
break;
}
}
}
}
}
|
917398661033da5ac8e563b45fafe21fd21736e5
|
[
"Markdown",
"C#"
] | 22
|
C#
|
sammazhao/CSharpLearning
|
32e68283a5a954913a4b6b54540f6040d0ffa5d5
|
731d79e669bd471d1a802c7f45413905900591c5
|
refs/heads/main
|
<repo_name>amitbdj14/shorten_URL<file_sep>/src/main/java/com/shortner/controller/URLShortenController.java
package com.shortner.controller;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.shortner.model.ShortURLBean;
@RestController
public class URLShortenController {
@PostMapping(path ="/shortenurl")
public ResponseEntity<String> getShortenURL(@RequestBody ShortURLBean shortenURL){
return null;
}
@GetMapping(path ="/s/{randomString}")
public ResponseEntity<String> getFullURL(HttpServletResponse response, @PathVariable String randomString){
return null;
}
}
|
1fd16664d534fa07d192fdcf4c9b67247e1a399a
|
[
"Java"
] | 1
|
Java
|
amitbdj14/shorten_URL
|
8813887975c4a675bd7fea854509ccac273d8850
|
75885a2ed174d09188c44a4821dcc92dd1961f00
|
refs/heads/master
|
<repo_name>Muqiu7890/node-demo<file_sep>/new/readdir.js
// var fs = require('fs');
//
// fs.readdir('./www',function (err,files) {
// if(err) {
// return console.log('not exist')
// }
// console.log(files)
// })
var http = require('http')
var fs = require('fs')
var template = require('art-template')
var wwwDir = './www'
http.createServer(function (req, res) {
var url = req.url
//1.获得响应页面内容
fs.readFile('./temple.html', function (err, data) {
if (err) {
return res.end('404 not found')
}
//2.得到目录列表
fs.readdir(wwwDir, function (err, files) {
if (err) {
return console.log('not exist')
}
// var content = ''
// files.forEach(function (item) {
// content += `<tr>
// <td data-value="apple/"><a class="icon dir" href="">${item}</a></td>
// <td class="detailsColumn" data-value="0"></td>
// <td class="detailsColumn" data-value="1536750277">9/12/18, 7:04:37 PM</td>
// `
// })
//3.目录中的内容替换页面中需要替换的内容
data = template.render(data.toString(),{
files: files
}) //错误: var data
//将替换后的结果响应给浏览器
res.end(data)
})
})
}).listen(3000,function () {
console.log('run at http://127.0.0.1:3000')
})
<file_sep>/old-ej/super.js
// class Polygon {
// constructor(height, width) {
// this.name = 'Polygon';
// this.height = height;
// this.width = width;
// }
// sayName() {
// console.log('Hi, I am a ', this.name + '.');
// }
// }
//
// class Square extends Polygon {
// constructor(length) {
// //this.height; //this不允許使用在super前
// super(length, length);
// this.name = 'Square';
// }
//
// get area() {
// return this.height * this.width;
// }
//
// set area(value) {
// //this.area = value;
// console.log(value);
// }
// }
// var res = new Square(2);
// console.log(res,res.area); //Square { name: 'Square', height: 2, width: 2 } 4
// res.sayName(); //Hi, I am a Square.
// class Human {
// constructor() {}
// static ping() {
// return 'ping';
// }
// }
//
// class Computer extends Human {
// constructor() {}
// static pingpong() {
// return super.ping() + ' pong';
// }
// }
// console.log(Computer.pingpong()); //ping pong
//继承
const EventEmitter = require('events');
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`接收的数据:"${data}"`);
});
stream.write('使用 ES6');
<file_sep>/mongoose-demo/index.js
const mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://localhost/test');
// 创建一个模型
// 就是在设计数据库
// MongoDB 是动态的,非常灵活,只需要在代码中设计你的数据库就可以了
// mongoose 这个包就可以让你的设计编写过程变的非常的简单
const Cat = mongoose.model('Cat', { name: String });
//实例化一个Cat
const kitty = new Cat({ name: 'Zildjian' });
//持久化保存kiity实例
kitty.save().then(() => console.log('meow'));<file_sep>/old-ej/modulepath.js
//console.log(module.paths);
//console.log(__filename); //绝对路径
//console.log(__dirname); //目录名
//文件读写
var fs = require('fs');
//同步
//读文件
// var readMe = fs.readFileSync("read.txt","utf-8");
//console.log(readMe);
//写文件
// fs.writeFileSync("wirte.txt",readMe);
//异步
//读写文件
// var readMe = fs.readFile("read.txt","utf-8",function (err,data) {
// //console.log(data);
// fs.writeFile("write1.txt",data,function () {
// console.log('write has finished');
// })
// });
//模块
// var events = require('events');
// var util = require('util');
//
// var Person = function (name) {
// this.name = name;
// };
//
// util.inherits(Person,events.EventEmitter);
//
// var xiaoming = new Person('xiaoming');
// var lili = new Person('lili');
// var lucy = new Person('lucy');
//
// var person = [xiaoming,lili,lucy];
//
// person.forEach(function (person) {
// person.on('speak',function(message) {
// console.log(person.name + " say: " + message);
// })
// })
//
// xiaoming.emit('speak','hi');
// lucy.emit('speak','nihao');
// var myEmitter = new events.EventEmitter();
//
// myEmitter.on('someEvent',function (message) {
// console.log(message);
// });
//
// myEmitter.emit('someEvent','fdfds sddsds fddfdfsdsfs');
//读流
var myReadStream = fs.createReadStream(__dirname + '/read.txt');
// var data = "";
//
// myReadStream.on('data',function (chunk) {
// data += chunk;
// //console.log(data);
// })
//
// myReadStream.on('end',function (chunk) {
// console.log(data);
// })
//用流写入文件
// var myWriteStream = fs.createWriteStream(__dirname + '/wirte3.txt');
//
// var writeData = "kkkkkkkkkkkkkkk";
// myWriteStream.write(writeData);
// myWriteStream.end();
// myWriteStream.on('finish',function () {
// console.log('finished');
// })
//console.log(__dirname);
console.log(window)
console.log(document)<file_sep>/new/os.js
//node没有全局作用域 只有模块
//用户自己编写的文件模块 相对路径过必须加 ./ 不能省略 省略会被当作核心模块
// var os = require('os')
//获取机器信息
console.log(os.cpus()) // 获取cpu信息
console.log(os.totalmem()) // 获取内存大小 mem-> memory
// var http = require('http')
//
// var server = http.createServer()
//
// server.on('request',function (req, res) {
// res.setHeader('Content-Type','text/plain; charset=utf-8') ///plain 普通文本
// res.end('nihao 中国\n')
// })
//
// server.listen(3000,function () {
// console.log('Server running at http://127.0.0.1:3000/')
// })
//若使用无分号的代码风格 需要加分号的情况 以 ( [ ` 开头的代码
<file_sep>/middleware/index.js
var express = require('express')
const app = express()
app.use(function (req,res,next) {
console.log('time ' + Date.now())
next()
})
app.use(function (req,res,next) {
console.log("Q")
next()
})
app.use('/',function (req,res) {
console.log(req.method)
res.send('index.js')
})
app.listen(3000,function () {
console.log('running at ...')
})<file_sep>/express-demo/message-board/README.md
##### 留言版
node留言版--express实现<file_sep>/express-demo/crud-express/student-fs.js
/*
数据操作文件模块
只处理数据
*/
const fs = require('fs')
const dbPath = './db.json'
/*
* 获取学生列表
*/
exports.find = function (callback) {
fs.readFile(dbPath,'utf8',function (err,data) {
if(err) {
return callback(err)
}
callback(null,JSON.parse(data).students)
})
}
/*
* 根据学生id获取学生信息
*/
exports.findById = function (id,callback) {
fs.readFile(dbPath,'utf8',function (err,data) {
if(err) {
return callback(err)
}
var students = JSON.parse(data).students
var result = students.find(function (item) {
return item.id === id
})
callback(null,result)
})
}
/*
* 添加学生
*/
exports.save = function (student,callback) {
fs.readFile(dbPath,'utf8',function (err,data) {
if(err) {
return callback(err)
}
var students = JSON.parse(data).students
student.id = students[students.length - 1].id + 1
students.push(student)
var result = JSON.stringify({
students: students
})
fs.writeFile(dbPath,result,function () {
if(err) {
return callback(err)
}
callback(null)
})
})
}
/*
* 更新学生
*/
exports.updateById = function (student,callback) {
fs.readFile(dbPath, 'utf8', function (err, data) {
if (err) {
return callback(err)
}
var students = JSON.parse(data).students
student.id = parseInt(student.id)
//要被操作的学生
var stu = students.find(function (item) {
return item.id === student.id
})
//遍历更新内容
for(let key in student) {
stu[key] = student[key]
}
var result = JSON.stringify({
students: students
})
fs.writeFile(dbPath,result,function () {
if(err) {
return callback(err)
}
callback(null)
})
})
}
/*
* 删除学生
*/
exports.deleteById = function (id,callback) {
fs.readFile(dbPath,'utf8',function (err,data) {
var students = JSON.parse(data).students
var deteleId = students.findIndex(function (item) {
return item.id === parseInt(id)
})
students.splice(deteleId,1)
var result = JSON.stringify({
students: students
})
fs.writeFile(dbPath,result,function () {
if(err) {
return callback(err)
}
callback(null)
})
})
}<file_sep>/express-demo/message-board/index.js
const express = require('express')
var bodyParser = require('body-parser')
const app = new express()
var comments = [{
name: '张三',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三2',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三3',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三4',
message: '今天天气不错!',
dateTime: '2015-10-16'
},
{
name: '张三5',
message: '今天天气不错!',
dateTime: '2015-10-16'
}
]
// 配置使用art-template 模版引擎
// 第一个参数表示,当渲染以 .art 结尾的文件的时候,使用 art-template 模板引擎
// express-art-template 是专门用来在 Express 中把 art-template 整合到 Express 中
// 虽然外面这里不需要记载 art-template 但是也必须安装
// 原因就在于 express-art-template 依赖了 art-template
app.engine('html', require('express-art-template'));
app.use('/public/',express.static('./public/'))
app.use('/views/',express.static('./views/'))
// Express 为 Response 相应对象提供了一个方法:render
// render 方法默认是不可以使用,但是如果配置了模板引擎就可以使用了
// res.render('html模板名', {模板数据})
// 第一个参数不能写路径,默认会去项目中的 views 目录查找该模板文件
// 也就是说 Express 有一个约定:开发人员把所有的视图文件都放到 views 目录中
// 如果想要修改默认的 views 目录,则可以
// app.set('views', render函数的默认路径)
//配置 bodyParser 用来解析 post 提交请求体
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.get('/',(req,res) => {
res.render('index.html',{
comments: comments
});
})
app.get('/post',(req,res) => {
res.render('post.html')
})
// app.get('/pinglun',(req,res) => {
// // console.log(req.query);
// var comment = req.query
// comment.dateTime = '2017-9-15'
// comments.unshift(comment)
// res.redirect('/')
// // res.statusCode = 302
// // res.setHeader('Location','/')
// })
// 当以 POST 请求 /post 的时候,执行指定的处理函数
app.post('/post',function (req,res) {
//1. 获取post请求体数据
//2. 处理
//3. 发送响应
var comment = req.body //类似与 get 请求的 query 属性
comment.dateTime = '2017-9-15'
comments.unshift(comment)
res.redirect('/')
})
app.listen(3000,function () {
console.log('running at 3000')
})<file_sep>/express-demo/crud-express/router.js
/*
* router.js 路由模块
* 职责:
* 处理路由
* 根据不同的请求方法+请求路径设置具体的请求处理函数
* 模块职责要单一,不要乱写
* 我们划分模块的目的就是为了增强项目代码的可维护性
* 提升开发效率
*/
const express = require('express')
const fs = require('fs')
const Student = require('./student')
//Express提供了一种更好的方式 专门由来包装路由
//1.创建一个路由容器
const router = express.Router()
//2.把路由都挂载到 router 路由容器中
/*
* 渲染学生列表页面
*/
router.get('/students',function (req,res) {
// fs.readFile('./db.json','utf8',function (err,data) {
// if(err) {
// return res.status(500).send('server error')
// } else {
// res.render('index.html',{
// star: [
// '白','龙','冠','天'
// ],
// students: JSON.parse(data).students
// })
// }
// })
Student.find(function (err,students) {
if(err) {
return res.status(500).send('server error')
} else {
res.render('index.html',{
star: [
'白','龙','冠','天'
],
students: students
})
}
}) //该函数即为callback
})
/*
* 渲染添加学生页面
*/
router.get('/students/new',function (req,res) {
res.render('update.html')
})
/*
* 处理添加学生页面
*/
router.post('/students/new',function (req,res) {
//获取表单数据
const student = req.body
new Student(student).save(function (err) {
if(err) {
return res.status(500).send('server error')
}
res.redirect('/students')
})
})
/*
* 渲染编辑学生页面
*/
router.get('/students/edit',function (req,res) {
//console.log(req.query.id)
//1。根据 id 拿到对应学生信息
//2.将拿到的数据渲染到页面中
Student.findById((req.query.id).replace(/"/g,''),function (err,student) {
if(err) {
return res.status(500).send('server error')
}
res.render('edit.html',{
student: student
})
})
})
/*
* 更新学生信息
*/
router.post('/students/edit',function (req,res) {
//1.获取表单数据
//2.将获取到的数据进行处理
//3.定向到首页
// console.log(req.body);
//console.log(req.body.id)
var id = (req.body.id).replace(/"/g,'')
Student.findByIdAndUpdate(id,req.body,function (err) {
if(err) {
return res.status(500).send('server error')
}
res.redirect('/students')
})
})
/*
* 删除学生
*/
router.get('/students/delete',function (req,res) {
Student.findByIdAndRemove((req.query.id).replace(/"/g,''),function (err) {
if(err) {
return res.status(500).send('server error')
}
res.redirect('/students')
})
})
module.exports = router<file_sep>/express-demo/first-demo/index.js
const express = require('express')
//1.创建httpServer服务器
const app = express()
//2。当服务器受到get请求时执行回调函数
app.get('/',function (req,res) {
//获取查询字符串参数
//console.log(res.query)
res.send("hell world")
})
//设置公共目录
//当以/pubilc/开头(标识)的时候 去./public/ 目录中找对应资源
app.use('/public/',express.static('./public/'))
// app.use(express.static('./public/')) 第一个参数默认为 ‘/’ 127.0.0.1:3000/main.js
// app.use('/a/',express.static('./public/')) 127.0.0.1:3000/a/main.js
app.get('/about',function (req,res) {
res.send(`<p>hello experss</p>`)
})
//3.监听端口
app.listen(3000,function () {
console.log('app running at port 3000')
})<file_sep>/old-ej/circle.js
var pi = Math.PI;
exports.area = function (r) {
return pi * r * r;
};
exports.zhouchang = function (r) {
return pi * r * 2;
};
exports.val = 65;
<file_sep>/blog-node/router.js
const express = require('express')
const User = require('./models/user')
const md5 = require('blueimp-md5')
const router = express.Router()
router.get('/',function (req,res) {
res.render('index.html',{
user: req.session.user
})
})
router.get('/login',function (req,res) {
res.render('login.html')
})
router.post('/login',function (req,res) {
//1.拿到请求数据
//console.log(req.body)
var body = req.body
body.password = md5(md5(body.password))
//console.log(body.password)
User.findOne({
email: body.email,
password: body.<PASSWORD>
},function (err,user) {
if(err) {
return res.status(500).json({
err_code: 500,
message: 'server error'
})
}
if(!user) {
return res.status(200).json({
err_code: 1,
message: 'email or password error'
})
}
req.session.user = user
res.status(200).json({
err_code: 0,
message: 'login success'
})
})
})
router.get('/register',function (req,res) {
res.render('register.html')
})
router.post('/register',function (req,res) {
//1.拿到请求数据
//console.log(req.body)
const body = req.body
//2.数据处理 若用户已存在 不允许注册 若不存在 允许注册
User.findOne({
$or: [
{
email:body.email
},
{
nickname: body.nickname
}
]
},function (err,data) {
if(err) {
return res.status(500).json({
success: false,
message: '服务端错误'
})
}
if(data) {
return res.status(200).json({
err_code: 1,
message: 'email or nickname already exist.'
})
}
body.password = md5(md5(body.password))
//不存在 注册
new User(body).save(function (err,user) {
if(err) {
return res.status(500).json({
err_code: 500,
message: 'server error.'
})
}
//注册成功 使用session记录用户登陆状态
req.session.user = user
res.status(200).json({
err_code: 0,
message: 'register success'
})
})
})
})
router.get('/logout',function (req,res) {
//清除登陆状态
req.session.user = null
//重定向
res.redirect('/')
})
module.exports = router<file_sep>/new/comment-panel/app.js
var http = require('http')
var fs = require('fs')
var url = require('url')
var template = require('art-template')
var content = [
{
name: '张三',
message: '米纳桑',
dataTime: '2015-9-10'
},
{
name: '张三1',
message: '米纳桑',
dataTime: '2015-9-10'
},
{
name: '张三2',
message: '米纳桑',
dataTime: '2015-9-10'
},
{
name: '张三3',
message: '米纳桑',
dataTime: '2015-9-10'
}
]
http.createServer(function (req, res) {
var parseObj = url.parse(req.url, true)
pathname = parseObj.pathname
console.log(parseObj);
if (pathname === '/') {
fs.readFile('./views/index.html', function (err, data) {
if (err) {
return console.log('404 not exist')
}
var htmlRes = template.render(data.toString(), {
content: content,
})
res.end(htmlRes)
})
} else if (pathname === '/post') {
fs.readFile('./views/post.html', function (err, data) {
if (err) {
return console.log('404 not exist')
}
res.end(data)
})
}
else if (pathname.indexOf('/public/') === 0) {
fs.readFile('.' + pathname, function (err, data) {
if (err) {
return console.log('404 not exist')
}
res.end(data)
})
} else if (pathname === '/pinglun') {
//1.获取表单提交的数据 parseObj.query
//2.获取当前时间添加到数组对象中,并存储在数组中
//3.重定向到首页
var comment = parseObj.query
comment.dataTime = '2019-2-12'
content.push(comment)
// 如何重定向?
// 1. 状态码设置为302临时重定向 statusCode 301永久重定向
// 2. 在响应头中通过 Location 告诉客户端往哪重定向 setHeader
res.statusCode = 302
res.setHeader('Location','/')
res.end()
}
else {
fs.readFile('./views/false.html', function (err, data) {
if (err) {
return console.log('404 not exist')
}
res.end(data)
})
}
}).listen(3000, function () {
console.log('run at ...')
})
<file_sep>/new/http.js
var http = require('http')
var server = http.createServer()
//客户端发请求 服务器 接受请求 处理请求 发送响应
//注册request请求事件 当客户端发起请求时 自动触发该事件 执行回调函数
//接受两个参数 request 请求对象用来获取客户端的一些请求信息 eg:请求路径
// response 用来给客户端发送响应消息
server.on('request',function (req,res) {
// console.log('收到客户端请求, 请求路径为' + req.url)
var url = req.url;
if(url === '/index') {
res.end('index')
} else if(url === '/login') {
res.end('login')
} else {
res.end('hello world')
//手动end 否着浏览器会一直等待
})
//绑定端口号 启动服务器
server.listen(3000,function () {
console.log('Server running at http://127.0.0.1:3000/')
})
|
a7f9897d2d9715d65841fa9af5a5c50467295ada
|
[
"JavaScript",
"Markdown"
] | 15
|
JavaScript
|
Muqiu7890/node-demo
|
058e098e5f57ef0e6d5ff768ace508351c9d4252
|
789148f51eb3dfa4652e00d02ab9d8026d15375c
|
refs/heads/master
|
<repo_name>vilenhakobyan4444/ISTC-JS-Fundamentals<file_sep>/homeworks.js
console.log("Hello World !!!");
//output 5,10,15
function numberInc(num) {
var n1 = num;
var res = num+=num;
console.log(n1,res,num+n1);
}
numberInc(5);
//averageSumm
function averageSumm(x,y,z,h,l) {
var summ = x+y+z+h+l;
var res = summ/5;
return res;
}
console.log(averageSumm(12,43,7,54,7));
//week days
var day;
switch(new Date().getDay()){
case 0:
day="Today is: Sunday";
break;
case 1:
day="Today is: Monday";
break;
case 2:
day="Today is: Tuesday";
break;
case 3:
day="Today is: Wednesday";
break;
case 4:
day="Today is: Thursday";
break;
case 5:
day="Today is: Friday";
break;
case 6:
day="Today is: Saturday";
}
console.log(day);
//chek pm or am (Dates)
var hour = new Date();
var result;
switch (hour.getHours()){
case hour.getHours(12-23):
result = "pm";
break;
default:
result = "am"
}
console.log(result);
//get time
function getSecMinHr() {
var h;
var m = new Date().getMinutes();
var s = new Date().getSeconds();
var ampm;
if (h = new Date().getHours(0-11)) {
ampm = "PM";
}
else{
ampm = "AM"
}
console.log("Current time is:",h,ampm+":",m+":",s);
}
getSecMinHr();
//DateTask
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12)? " PM ":" AM ";
hour = (hour >= 12)? hour - 12: hour;
if (hour===0 && prepand===' PM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Noon';
}
else
{
hour=12;
prepand=' PM';
}
}
if (hour===0 && prepand===' AM ')
{
if (minute===0 && second===0)
{
hour=12;
prepand=' Midnight';
}
else
{
hour=12;
prepand=' AM';
}
}
console.log("Current Time : "+hour + prepand + " : " + minute + " : " + second);
//sort numbers
function sort(x,y,z){
if(x<y&&x<z&&z<y){
console.log(x,z,y)
}
else if(y<x&&y<z&&x<z){
console.log(y,x,z)
}
else if(y<x&&y<z&&x>z){
console.log(y,z,x)
}
else if(z<x&&z<y&&x<y){
console.log(z,x,y)
}
else if(z<x&&z<y&&x>y){
console.log(z,y,x)
}
else{
console.log(x,y,z)
}
}
sort(7,5,3);
//reverse numbers
function reverse(numbers) {
var str = numbers.toString();
var array = str.split("");
var rev = array.reverse();
var res = rev.join("")
return res;
}
console.log(reverse(12345));
//toUpperCase
function toUpCase(str) {
var empS="";
for (var i = 0; i < str.length; i++) {
empS += str[i].toUpperCase();
}
console.log(empS);
}
toUpCase("string");
//Calendar.day.
function cal(x) {
var d = new Date().getDate();
for (var i = 1; i <= x; i++) {
if (i==d) {
console.log(i+"+");
}
else
console.log(i);
}
}
cal(30);
//daysInMonth
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
console.log(daysInMonth(6, 2019));
console.log(daysInMonth(7, 2019));
console.log(daysInMonth(8, 2019));
//arraySortWhile
function sort(arr) {
var i = 0;
var j;
while(i<arr.length){
j=i+1;
while(j<arr.length){
if (arr[i]>arr[j]) {
var m = arr[i];
arr[i]=arr[j];
arr[j]=m
}
j++;
}
i++;
}
console.log(arr)
}
sort([1,3,6,3,4,10,5]);
//forSort
var arr = [1,5,1,7,3,2];
for (var i = 0; i < arr.length; i++) {
for (var j = i+1; j < arr.length; j++) {
if (arr[i]>arr[j]) {
var p = arr[i];
arr[i]=arr[j];
arr[j]=p
}
}}
console.log(arr);
//maxArray
function max(x) {
var max = x[0];
for (var i = 0; i < x.length; i++) {
if (x[i]>max) {
max=x[i];
}
}
console.log(max)
}
max([1,5,2,18,59,100,128]);
//count of reapet string
function fu(str){
var score = 1;
for(var i = 0; i< str.length; i++){
if(str[i] === str[i+1]){
score++;
} else{
console.log(score + str[i]);
score = 1;
}
}
}
fu("wwwaaagsdfsdss");
//toUpperCase
function func(str){
var newStr = "";
for(var i = 0; i < str.length; i++){
if(i === 0){
newStr = str[i].toUpperCase();
} else if(str[i] === " "){
j = newStr.length;
newStr += (str.slice(j,i) + " " + str[i+1].toUpperCase());
}
}
console.log(newStr + "ion");
}
func("the king is lion")
<file_sep>/objects/objTasks.js
//checkLetter
var obj = {
1:"a",
2:"b",
3:"c"
}
function check(xy) {
for(var x in obj)
if (obj[x]==xy) {
console.log(true);
}
}
check("c");
//checkName
var object = {
name: "Vilen",
srname: "Hakobyan",
age:"25"
}
function check2(x) {
for(var i in object)
if (object[i]==x) {
alert("objecty uni "+object.name+" parametry")
}
}
f("Vilen");
//deleteObj
var obj = {
1: "Hello",
2: "My",
3: "Dear",
4: "Freind"
}
function deleteObj() {
for(var i in obj)
if (i==3) {
delete obj[i];
}
}
deleteObj()
console.log(obj);
//checkObjLength 1
var objects = {
1: "Mek",
2: "Erku",
3: "Ereq",
4: "Chors",
5: "Hing"
}
function Objlength(x) {
for(var i in objects){
x++;
}
console.log("Objects length is "+x)
}
Objlength(0);
//checkObjLength 2
var objects = {
1: "Mek",
2: "Erku",
3: "Ereq",
4: "Chors",
5: "Hing"
}
var arr = Object.keys(objects);
console.log(arr.length);
//objKeys
var objects = {
1: "Mek",
2: "Erku",
3: "Ereq",
4: "Chors",
5: "Hing"
}
var objArr = Object.keys(objects);
console.log(parseInt(objArr[1])+parseInt(objArr[3]));
<file_sep>/loops.js
//forExample
function myFunction() {
var text = "";
for (var i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.write(text);
}
myFunction();
//whileExample
function myFunction() {
var text = "";
var i = 0;
while (i < 5) {
text += "<br>The number is " + i;
i++;
}
document.write(text);
}
myFunction();
//doWhileExample
function myFunction() {
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 5);
document.write(text);
}
myFunction();
//foreach
var numbers = [1,2,3,4,5];
numbers.forEach(fu);
function fu(value,index) {
console.log(value * 2);
}
//arrayMap
var numbers = [1,2,3,4,5];
numbers.map(fu);
function myFunction(value,index) {
console.log(value * 2);
}
//forin
function check(xy) {
for(var x in obj)
if (obj[x]==xy) {
console.log(true);
}
}
check("c");
|
e37c8af0422855a4e2b56ee0712b91b04eaa79a4
|
[
"JavaScript"
] | 3
|
JavaScript
|
vilenhakobyan4444/ISTC-JS-Fundamentals
|
3ea3b1298b5114451008525e6866a07581ccfcb6
|
aae09f6662334895c9016b41667cca90f98df265
|
refs/heads/master
|
<repo_name>mapic/docker-mapic-xenial<file_sep>/install-nodejs.sh
#!/bin/bash
# # NodeJS version
# NODE_VERSION=6.10.3
# # install
# gpg --keyserver pool.sks-keyservers.net --recv-keys <KEY> <KEY>
# curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
# && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
# && rm "node-v$NODE_VERSION-linux-x64.tar.gz" \
# && npm install -g npm \
# && npm cache clear
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
sudo apt-get install -y build-essential nodejs<file_sep>/README.md
# mapic/xenial [](https://travis-ci.org/mapic/docker-mapic-xenial) [](https://hub.docker.com/r/mapic/xenial/builds/) [](https://hub.docker.com/r/mapic/xenial/)
Dockerfiles for `mapic/xenial:latest` Docker image.
Based on [`ubuntu:xenial`](https://hub.docker.com/_/ubuntu/).
<file_sep>/build.sh
#!/bin/bash
docker build -t mapic/xenial:latest .
|
bd65a5f7ae07dfbe8adbb9c8ab044a9770da73b4
|
[
"Markdown",
"Shell"
] | 3
|
Shell
|
mapic/docker-mapic-xenial
|
873c0f66142649cca15c1a4e97e08e58f7d3100b
|
aec28677a874d69413529ebb50185622bc715259
|
refs/heads/master
|
<file_sep>sudo apt install vim
sudo apt install git
sudo apt install tmux
sudo apt install make
sudo apt install cmake
sudo apt install build-essential
sudo apt install vlc
sudo apt install curl
sudo apt install mupdf
sudo apt install texlive-full
sudo apt install nodejs
|
4380e3b2dc666bb9db18288ed6698854ca3dda75
|
[
"Shell"
] | 1
|
Shell
|
tewidis/dotfiles
|
a145023734a09a078a7d34c5227caf8498cc3305
|
f137becc65befcaa934794ee258219d95dda0f51
|
refs/heads/main
|
<repo_name>kuplevich-max/TestTask<file_sep>/README.md
# Proxy Parser
# Using scrapy and scrapy-splash.
## To run project you need run splash server in docker.
### Than you need to open project in terminal and use:
### <i>scrapy crawl proxyhttp</i>
## The result will be saved in <i>proxyhttp.json<i> file.
<file_sep>/task/task/spiders/proxy_http_spider.py
import scrapy
from scrapy_splash import SplashRequest
class ProxyHttpSpider(scrapy.Spider):
name = 'proxyhttp'
allowed_domains = ['proxyhttp.net']
start_urls = ['https://proxyhttp.net/free-list/anonymous-server-hide-ip-address#proxylist']
custom_settings = {'FEED_URI': "proxy_http.json",
'FEED_FORMAT': 'json'}
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url)
def parse(self, response, **kwargs):
ip = response.css('table.proxytbl tr td.t_ip::text').getall()
ports = [item.split('\n')[0] for item in response.css('table.proxytbl tr td.t_port::text').getall() if item[0] != '\n']
rows = [(ip[i], ports[i]) for i in range(len(ip))]
for row in rows:
scraped_info = {
'ip' : row[0],
'port': row[1]
}
yield scraped_info
|
432bd226bab2dc01656d549ed660efd444eab16c
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
kuplevich-max/TestTask
|
159023ab9f1d72c2b7cff5f2fa3ae24d04b88d87
|
4d71c606cf4ccf1be44977de345ea5188c4d74e4
|
refs/heads/master
|
<file_sep>import express from "express";
import transfer from "../domains/transfer/ApiRoute";
const router = express.Router();
router.use('/transfer', transfer);
export default router;
<file_sep>import express from 'express';
import Auth from './ApiController';
let router = express.Router();
router.post('/', Auth.login);
router.post('/create-account', Auth.createAccount);
export default router;
<file_sep>import express from 'express';
import Transfer from './ApiController';
let router = express.Router();
router.post('/create', Transfer.create);
router.get('/:id', Transfer.list)
export default router;
<file_sep>import controller from '../../helpers/compose-controller';
import Transfer from '../../models/Transfer';
import Users from '../../models/Users';
import knex from 'knex';
class TransferApiController {
static async list(req, res) {
let data = await Transfer.query()
.select(
'transfer.*',
'users.name as name_user_receive'
)
.join("users", "transfer.user_receive_id", "users.id")
.where(knex.raw(`user_send_id = ${req.params.id} or user_receive_id = ${req.params.id}`))
if (!data) {
return res.status(404).json({
message: 'Nenhum registro cadastrado.',
});
}
return res.status(200).responseComposer({ data });
}
static async create(req, res){
let user_send = await Users.query()
.select()
.first()
.where('id', req.body.user_send_id)
let user_receive = await Users.query()
.select()
.first()
.where('id', req.body.user_receive_id)
if (!user_send) {
return res.status(404).json({
message: 'Nenhum usuario cadastrado.',
});
}
if (user_send.sale < req.body.value_transfer) {
return res.status(404).json({
message: 'Saldo insuficiente!',
});
}
let send = await Users.query()
.findById(user_send.id)
.patch({
sale: user_send.sale - req.body.value_transfer
});
let receive = await Users.query()
.findById(user_receive.id)
.patch({
sale: user_receive.sale + req.body.value_transfer
});
let transfer = await Transfer.query()
.insert({
sale: req.body.value_transfer,
name: req.body.name_transfer,
type: req.body.type,
user_send_id: req.body.user_send_id,
user_receive_id: req.body.user_receive_id,
created_at: new Date()
})
return res.status(200).responseComposer(transfer);
}
}
export default controller(TransferApiController);
<file_sep># BLC
Sistema para transferência de valores entre contas, utilizado o framework bootstrap, axios, reactjs, yup, nodejs para este desenvolvimento, o sistema
acompanha um database contruido em Mysql utilizando a ferramente DBeaver para gerenciamento do banco.
# Quem está por trás disso ?
Um desenvolvedor apaixonado por tecnologias, <NAME>
<file_sep><h1 align="center">
<br>
<img src="https://cdn.iconscout.com/icon/free/png-512/node-js-1174925.png" alt="node" width="120">
<br>
<br>
BLC Api
</h1>
<br>
## Sobre
O BLC api é uma aplicação responsável por acrescentar informações solicitadas pelo front-end do BLC dentro do banco de dados.
Quais tecnologias foram utilizadas ?
- **[NodeJS](https://nodejs.org/en/)**
- **[Express](https://expressjs.com/)**
- **[Nodemon](https://nodemon.io/)**
## Instalação
Você precisa [Node.js](https://nodejs.org) instalado em seu computador e rodar
os seguintes comandos.
```bash
git clone
$ cd Api
$ yarn install
$ yarn dev
```
<file_sep>import React,{ useEffect, useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Table, Navbar } from 'react-bootstrap';
import axios from 'axios';
import {history} from '../../history';
import moment from 'moment'
const Home = () => {
const [listTable, setListTable] = useState([])
const [user, setUser] = useState('')
useEffect(() => {
axios.get('http://localhost:3307/api/transfer/2') //passa
.then(resp => {
const { data } = resp.data
if (data) {
setListTable(data.data);
}
})
}, []);
useEffect(() => {
setUser(JSON.parse(localStorage.getItem('app-token')))
}, [listTable]);
return (
<>
<Navbar bg="dark" variant="dark">
<Navbar.Brand href="#home">{user ? user.user.name : ''}</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Navbar.Text>
{user ? '$' + user.user.sale : 0}
</Navbar.Text>
</Navbar.Collapse>
</Navbar>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>Codigo</th>
<th>Nome da transferencia</th>
<th>Valor</th>
<th>Tipo</th>
<th>Destinatario</th>
<th>Data da transferencia</th>
</tr>
</thead>
<tbody>
{listTable.map((item) => {
return (
<tr style={{backgroundColor: item.name_user_receive == user.user.name ? 'green' : 'transpartent' }}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.sale}</td>
<td>{item.type}</td>
<td>{item.name_user_receive}</td>
<td>{moment(item.created_at, 'YYYY-MM-DD').format('DD/MM/YYYY')}</td>
</tr>
)
})}
</tbody>
</Table>
<button className="Login-btn" type="submit" onClick={() => history.push('/transfer')}>Transferir</button>
</>
)}
export default Home;<file_sep>export { default as Users } from './Users';
export { default as Transfer } from './Transfer';
export { default as Model } from './Model';
<file_sep>import React, {useState, useEffect} from 'react'
import 'bootstrap/dist/css/bootstrap.min.css';
import { Dropdown,ButtonGroup,Button } from 'react-bootstrap';
import { ErrorMessage, Formik, Form, Field } from 'formik'
import * as yup from 'yup'
import axios from 'axios'
import { history } from '../../history'
const Transfer = () => {
const [type, setType] = useState(null);
const [user, setUser] = useState('')
useEffect(() => {
setUser(JSON.parse(localStorage.getItem('app-token'))) // Retorna o registro para formato array-objeto
}, [!user]);
const handleSubmit = values => {
let body = {
user_send_id: user ? user.user.id : 0,
user_receive_id: values ? values.user_receive_id : '',
value_transfer: values ? values.value_transfer : '', // Testando valores para transferir preencher a variavel body conforme o banco;
name_transfer: values ? values.name_transfer : '',
type: type || ''
}
axios.post('http://localhost:3307/api/transfer/create', body)
.then(resp => {
const { data } = resp //cadastro para retornar o valor "data" para que possa conter os valores do user e direcionar para login.
if (data) {
history.push('/')
}
})
}
const validations = yup.object().shape({
})
return (
<>
<image className="logo2" href="./images/logo2.png" alt="logo2"/>
<h1>Transferência</h1>
<h4>Faça sua transferência preenchendo todos os campos.</h4>
<Formik
initialValues={{}}
onSubmit={handleSubmit}
validationSchema={validations}
>
<Form className="Login">
<div className="Login-Group">
<h3>Valor</h3>
<Field
name="value_transfer"
className="Login-Field"
/>
<ErrorMessage
component="span"
name="value_transfer"
className="Login-Error"
/>
</div>
<div className="Login-Group">
<h3>Nome da transferência</h3>
<Field
name="name_transfer"
className="Login-Field"
/>
<ErrorMessage
component="span"
name="name_transfer"
className="Login-Error"
/>
</div>
<div className="Login-Group">
<h3>Tipo</h3>
<Dropdown as={ButtonGroup} onSelect={(value) => setType(value)}>
<Button variant="success">{type || 'Selecione'}</Button>
<Dropdown.Toggle split variant="success" id="dropdown-split-basic" />
<Dropdown.Menu>
<Dropdown.Item eventKey='receita'>Receita</Dropdown.Item>
<Dropdown.Item eventKey='resultado'>Resultado</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</div>
<div className="Login-Group">
<h3>Conta (ID)</h3>
<Field
name="user_receive_id"
className="Login-Field"
/>
<ErrorMessage
component="span"
name="user_receive_id"
className="Login-Error"
/>
</div>
<button className="Login-btn" type="submit" onClick={() => handleSubmit()}>Register</button>
</Form>
</Formik>
</>
)
}
export default Transfer<file_sep>
exports.up = function(knex, Promise) {
return knex.schema.createTable('transfer',function(table){
table.increments('id').primary();
table.decimal('sale',14,2);
table.string('name');
table.string('type');
table.string('user_receive_id');
table.string('user_send_id');
table.timestamps();
})
};
exports.down = function(knex, Promise) {
return knex.schema.dropTable('transfer');
};
<file_sep>import React, {useState} from 'react';
import { ErrorMessage, Formik, Form, Field } from 'formik';
import * as yup from 'yup';
import { Toast } from 'react-bootstrap';
import axios from 'axios';
import { IoIosEyeOff, IoIosEye } from "react-icons/io";
import {history} from '../../history';
import './styles.css';
import logo from '../Images/LC.png';
const Login = () => {
const [viewPassword, setViewPassword] = useState(false) // setViewPassword altera o estado
const [show, setShow] = useState(false);
function funcViewPassword(password){ //função para ver o password ou não
setViewPassword(!password)
}
function ToastView() { //mensagem de erro
return (
<Toast onClose={() => setShow(false)} show={show} delay={3000} autohide>
<Toast.Body>Autenticação invalida, verifique os campos e tente novamente!</Toast.Body>
</Toast>
);
}
const handleSubmit = values => {
axios.post('http://localhost:3307/api/auth/', values)
.then(resp => {
const { data } = resp
if (data) {
localStorage.setItem('app-token', JSON.stringify(data)) // seta o registro em formato de String
history.push('/')
}
}).catch((error)=>{
setShow(true)
})
}
const validations = yup.object().shape({ //Valida os inputs com limitações e requisições se acaso nao for Clicado;
email:yup.string().email().required(),
password: yup.string().min(8).required()
})
return(
<>
<img src={logo} style={{ display: 'block', marginLeft: 'auto', marginRight: 'auto', width: '50%' }} />
<h1 color="#FFF">Login</h1>
<Formik initialValues={{}}
validationSchema={validations}
onSubmit={handleSubmit}>
<Form className="Login">
<div className="Login-Group">
<h3>Email</h3>
<Field
name="email"
className="Login-Field"
/>
<ErrorMessage
component="span"
name="email"
className="Login-Error"
/>
</div>
<div className="Login-Group">
<h3>Senha { viewPassword
? <a onClick={()=>funcViewPassword(viewPassword)} ><IoIosEye/></a>
: <a onClick={()=>funcViewPassword(viewPassword)}><IoIosEyeOff/></a>}
</h3>
<Field
name="password"
type= {viewPassword === false && 'password'}
className="Login-Field"
/>
<ErrorMessage
component="span"
name="password"
className="Login-Error"
/>
</div>
<div>
</div>
<button className="Login-btn" type="submit" onClick={handleSubmit()}>Entrar</button>
<ToastView/>
</Form>
</Formik>
</>
)
}
export default Login;<file_sep>import React from 'react';
import Login from '../pages/Login';
import Register from '../pages/Register';
import Transfer from '../pages/Transfer';
import Home from '../pages/Home';
import NotFound from './Notfound';
import {history} from '../history';
import PrivateRoute from '../components/PrivateRoute/index';
const { Router, Switch, Route } = require("react-router");
const Routes = () => (
<Router history={history}>
<Switch>
<Route component={Login} exact path="/login"/>
<Route component={Transfer} exact path="/transfer"/>
<Route component={Register} exact path="/register"/>
<PrivateRoute component={Home} exact path="/"/>
{/* <Route component={NotFound}/> */}
</Switch>
</Router>
)
export default Routes;
|
381bed6751ac52e79088522849a7d23a0671b5ae
|
[
"JavaScript",
"Markdown"
] | 12
|
JavaScript
|
Iagocarvalholima/BLC
|
2a451678edc0d6d995e76ca871fc6407cd13d96b
|
4136a85a13a205213d66c6301a9af0206eee2d4b
|
refs/heads/master
|
<file_sep># Final Project-Alsarraf: Adjustable Sound FX
## Project Goal/Description
This project is aimed at people with recorded audio that is facing various normal issues such as loudness or consistent background noise. My original motivation for such a project was that during a gaming or podcast session, the audio that was recorded in the session is often affected by some type of audio issue. Audio issues can be fixable before the recording even happens, but in certain situations when moving setups or rooms, audio quality tends to fall behind. Therefore, I created this project to have a quick and accessible program that can modify audio and preserve old, working settings.
## Usage
From the directory of this project, do the following command:
$ python3 main.py
Any audio files generated by the program will be put into its own respective sub-directory within the main project directory. A history of all the audio processes that was done through this program is accessible via the main menu of the program.
## Unit Testing
I tried to make my project as modular as it possibly can be. I would pick singular files and test their functionality as a stand-alone, dependent file. When testing is done, I would integrate the functionality of the tested file with the rest of the project, and then test the entire project altogether.
## Project Progress and Analysis
I faced various challenges during the development of this project. I have more than double the lines of code that is present in this repository sitting on my local machine, but unfourtantly, the written code does not work as intended. I didn't have a clear vision of what to focus on at the start; and most importantly, I did not have a good estimate of the difficulty of the effects that I wanted to implement. For example, noise gating keyboard sounds from an audio clip was extremely difficult to implement. The difficulty in itself was not a problem as much as me shifting gears towards something else when my first initial plan fails. I usually never encounter such issues when developing projects, but due to the fact that I'm new to audio, I kept changing plans whenever something failed to work out as intended.
With that being said, I believe that I learned a lot about audio in general while developing this project. Despite not being able to implement all of my goals for this project, I believe that I gained very valuable insight into how audio work in my study field. I deeply wish that I had more time for this project, as I think developing audio-related projects is somethinng that I found to be way more interesting than what I initially had in mind.
## Future Vision
My ultimate goal for this project is to be able to automate my sound processing process. I will be taking a Machine Learning class next fall, and it would be interesting to see how I can integrate parts of Machine Learning concepts into this project. I want to be able to give this project to few friends of mine, and they would be able to generate improved audio clips from their recordings without tinkering with audio settings (or even have an understanding of what is going on).
<file_sep>#!/usr/bin/python3
from pydub import AudioSegment
import sys
import wave as wav
import math
import struct
import numpy as np
import matplotlib.pyplot as plt
import soundfile as sf
import os
import csvLogger
def getFileInfo(filename):
audiofile = wav.open(filename, 'rb')
channels = audiofile.getnchannels()
width = audiofile.getsampwidth()
rate = audiofile.getframerate()
frames = audiofile.getnframes()
frame_width = width * channels
audiofile.close()
info = [channels, width, rate, frames, frame_width]
return info
def getAudioSamples(filename):
wavfile = wav.open(filename, 'rb')
channels = wavfile.getnchannels()
width = wavfile.getsampwidth()
rate = wavfile.getframerate()
frames = wavfile.getnframes()
frame_width = width * channels
wave_bytes = wavfile.readframes(frames)
samples = []
# Iterate over frames.
for f in range(0, len(wave_bytes), frame_width):
frame = wave_bytes[f : f + frame_width]
# Iterate over channels.
for c in range(0, len(frame), width):
sample_bytes = frame[c : c + width]
sample = int.from_bytes(sample_bytes,
byteorder='little',
signed=(width>1))
samples.append(sample)
wavfile.close()
return samples
def amplify(filename, amount):
folder = filename[:len(filename)-4]
#print(folder)
if os.path.isdir(folder) == False:
print('Error: cannot amplify the file without having a directory for the new samples.')
return
samples = getAudioSamples(filename)
rate = getFileInfo(filename)
rate = rate[2]
'''
plt.figure(1)
plt.title('OG Signal Wave...')
#plt.plot(Time,signal)
plt.plot(samples)
plt.show()
plt.close()
#print(samples[0:160])
'''
number = csvLogger.getNum(filename)
if number == None:
number = 0
newFN = filename[:len(filename)-4]+'/'+filename[:len(filename)-4]+'-version'+str(number)+'.wav'
obj = wav.open(newFN, 'w')
obj.setnchannels(1)
obj.setsampwidth(2)
obj.setframerate(rate)
for i in range(len(samples)):
#print(samples[i])
#if (samples[i] < 0):
# value = samples[i]
#else:
# value = samples[i] * -1
#value = value + samples[i] + 100 # This needs adjusments
value = samples[i] * amount
if value > 32766:
value = 32767
elif value < -32766:
value = -32766
#print(value)
data = struct.pack('<h', value)
obj.writeframesraw(data)
obj.close()
spf = wav.open(newFN,'rb')
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')
#fs = spf.getframerate()
if spf.getnchannels() == 2:
sys.exit(0)
#Time=np.linspace(0, len(signal)/fs, num=len(signal))
'''
plt.figure(num=2)
plt.title('After Editing Signal Wave...')
#plt.plot(Time,signal)
plt.plot(signal)
plt.show()
plt.close()
'''
def filterNoise(filename, low, high):
audiofile = wav.open(filename, 'r')
info = list(audiofile.getparams())
number = csvLogger.getNum(filename)
if number == None:
number = 0
newFN = filename[:len(filename)-4]+'/'+filename[:len(filename)-4]+'-version'+str(number)+'.wav'
output = wav.open(newFN, 'w')
output.setparams(tuple(info))
LP = low
HP = high
cframe = audiofile.getframerate()
wholeFileFrames = int(audiofile.getnframes()/cframe)
#print(audiofile.getnframes())
#print(wholeFileFrames)
for frame in range(0, wholeFileFrames):
no = np.fromstring(audiofile.readframes(cframe), dtype = np.int16)
LC = no[0::2]
RC = no[1::2]
lf = np.fft.rfft(LC)
rf = np.fft.rfft(RC)
lf[55:66] = 0
rf[55:66] = 0
lf[:LP] = 0
lf[HP:] = 0
rf[:LP] = 0
rf[HP:] = 0
normalizeLeft = np.fft.irfft(lf)
normalizeRight = np.fft.irfft(rf)
ns = np.column_stack((normalizeLeft, normalizeRight)).ravel().astype(np.int16)
output.writeframes(ns.tostring())
#print(frame)
audiofile.close()
output.close()
def getAmp(fileInfo, targetdB):
delta = targetdB - fileInfo.dBFS
result = fileInfo.apply_gain(delta)
return result
def normalize(filename, targetAmp):
audioFormat = filename[len(filename)-3:]
audio = AudioSegment.from_file(filename, audioFormat)
normalizedResult = getAmp(audio, targetAmp)
number = csvLogger.getNum(filename)
if number == None:
number = 0
newFN = filename[:len(filename)-4]+'/'+filename[:len(filename)-4]+'-version'+str(number)+'.wav'
normalizedResult.export(newFN, audioFormat)
#normalize('spkr0.wav', -20)
#amplify('test.wav', 4)
#f = sf.SoundFile('test.wav')
#print('samples = {}'.format(len(f)))
#print(f)
#print(len(f))
#print('sample rate = {}'.format(f.samplerate))
#print('seconds = {}'.format(len(f) / f.samplerate))
<file_sep>#!/usr/bin/python3
import csvLogger
import audiomin
import datetime
import os
def helloworld():
print('helloworld')
def mainMenuPrint():
print('\n\n===============================')
print('0: quit the program')
print('1: Print log')
print('2: Amplify a sound clip')
print('3: Remove background noise of a sound clip')
print('4: Normalize a sound clip')
print('===============================\n\n')
menuOptions = {0 : quit,
1 : csvLogger.printGeneral,
2 : None}
def main():
amplifyDef = 4
lowDef = 21
highDef = 9000
normDef = -20
csvLogger.createGeneralLog()
csvLogger.createVersionLog()
while True:
while True:
mainMenuPrint()
try:
choice = int(input('please enter an option: '))
if choice > 4:
raise LookupError
break;
except ValueError as error:
print('Error: please enter a valid option(number)..\n')
except LookupError as error:
print('Error: please enter a valid option..\n')
if choice < 2:
menuOptions[choice]()
else:
while True:
filename = input('Please enter the file name that you want to modify (has to be in the same directory): ')
if filename == 'm':
break;
try:
if os.path.isfile(filename) == False or len(filename) < 5 or filename[-4:] != '.wav':
raise LookupError
break;
except LookupError as error:
print('\n\nError: please enter a valid file name in the same directory..')
print('Example: example.wav')
print('Enter m if you want to return to the main menu\n\n')
#print('we are here after file addition')
if filename != 'm':
info = audiomin.getFileInfo(filename)
csvLogger.createSpecificLog(filename, info)
if choice == 2:
while True:
amplifySet = int(input('Please enter by how much you would want to amplify the audio clip(1-5), or 0 for the default value: '))
if amplifySet > 5 or amplifySet < 0:
print('error, please enter a valid value')
else:
break;
if amplifySet == 0:
audiomin.amplify(filename, amplifyDef)
setting = amplifyDef
else:
audiomin.amplify(filename, amplifySet)
setting = amplifySet
csvLogger.increFile(filename)
csvLogger.addNewEntry(filename, 'Yes', amplifySet, 'No', '(0, 0)', 'No', 0)
elif choice == 3:
low = int(input('Please enter the number of the low frequency to filter out, or -1 for the default value: '))
if low == -1:
low = lowDef
high = int(input('Please enter the number of the high frequency to filter out, or -1 for the default value: '))
if high == -1:
high = highDef
audiomin.filterNoise(filename, 21, 9000)
csvLogger.increFile(filename)
csvLogger.addNewEntry(filename, 'No', 0, 'Yes', '('+str(low)+', '+str(high)+')', 'No', 0)
elif choice == 4:
target = int(input('Please enter the the decibel, or -1 for the default value: '))
if target == -1:
target = normDef
audiomin.normalize(filename, target)
csvLogger.increFile(filename)
csvLogger.addNewEntry(filename, 'No', 0, 'No', '(0, 0)', 'Yes', target)
if __name__ == '__main__':
main()
<file_sep>import csv
import os
import pandas as pd
import datetime
generalLog = 'generalLog.csv'
versionCounterLog = 'versionLog.csv'
tempVersionCounterLog = 'tempVersionLog.csv'
def createGeneralLog():
if os.path.isfile(generalLog) == False:
with open(generalLog, 'w') as cfile:
write = csv.writer(cfile)
write.writerow(['filename', 'date', 'amplify', 'setting', 'noise filter', 'setting', 'normalize', 'setting'])
def createVersionLog():
if os.path.isfile(versionCounterLog) == False:
with open(versionCounterLog, 'w') as cfile:
write = csv.writer(cfile)
write.writerow(['filename', 'current # of files created'])
def createSpecificLog(filename, info):
path = filename[:len(filename)-4]
if os.path.isdir(path) == False:
os.mkdir(path)
csvpath = path+'/'+path+'-log.csv'
#print("first: "+csvpath)
#print(csvpath)
with open(csvpath, 'w') as cfile:
write = csv.writer(cfile)
rate = info[2]
length = info[3]/rate
write.writerow(['filename', 'date', 'amplify', 'setting', 'noise filter', 'setting', 'normalize', 'setting'])
print('\n\n===========ATTENTION===========')
print('since this is the first time file {} have been used in the program'.format(filename))
print('a directory for file {} has been created by the name of {}.'.format(filename, path))
print('it will contain all the info/created samples/modfied versions of the file {}.'.format(filename))
print('===============================\n\n')
addNewToVersionLog(filename)
else:
csvpath = path+'/'+path+'-log.csv'
if os.path.isfile(path) == False:
csvpath = path+'/'+path+'-log.csv'
with open(csvpath, 'w') as cfile:
write = csv.writer(cfile)
rate = info[2]
length = info[3]/rate
#write.writerow(['filename: '+filename, 'rate: '+str(rate), 'length: '+str(length)+' seconds'])
write.writerow(['filename', 'date', 'amplify', 'setting', 'noise filter', 'setting', 'normalize', 'setting'])
def addNewToVersionLog(filename):
fields = [filename, 0]
with open(versionCounterLog, 'a') as cfile:
write = csv.writer(cfile)
write.writerow(fields)
#cfile.write(filename+',0\n')
def addNewEntry(filename, amplify, setting1, bf, setting2, normalize, setting3):
date = datetime.datetime.now()
dateS = str(date.year)+'/'+str(date.month)+'/'+str(date.day)
fields = [filename, dateS, amplify, setting1, bf, setting2, normalize, setting3]
with open(generalLog, 'a') as cfile:
write = csv.writer(cfile)
write.writerow(fields)
#cfile.write(filename+',0\n')
def increFile(filename):
"""
with open(versionCounterLog) as f_in, open ('test.csv', 'w') as f_out:
header = f_in.readline()
f_out.write(header)
for line in f_in:
print(line)
f_out.write(line)
"""
with open(versionCounterLog, 'r') as cfile:
reader = csv.reader(cfile.readlines())
with open(tempVersionCounterLog, 'w+') as cfile:
write = csv.writer(cfile)
for line in reader:
#print(line)
if line[0] == filename:
incre = int(line[1])
incre+=1
line[1] = str(incre)
write.writerow(line)
else:
write.writerow(line)
os.remove(versionCounterLog)
os.rename(tempVersionCounterLog, versionCounterLog)
def getNum(filename):
with open(versionCounterLog, 'r') as cfile:
reader = csv.reader(cfile.readlines())
for line in reader:
if line[0] == filename:
return line[1]
def printGeneral():
file = 'generalLog.csv'
df = pd.read_csv(file)
pd.options.display.max_columns = len(df.columns)
print(df)
#if os.path.isfile(generalLog) == False:
# createGeneralLog()
#printGeneral()
|
f5642e384118d6d85cebd1d43a4637abb9b41803
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
SulimanCS/cs410-final-project-soundFX-suite
|
e1bb25a58cb1f95bbb57b084a0fadf468491cdaa
|
6f94fa3823fe7705b2e171d0be260357ba66cdfc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.