branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># TicTacToe A simple Android Tic Tac Toe app built for CIS195 - concepts include recylcler views and shared preferences <file_sep>package cis195.tictactoe; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class TicTacToe extends AppCompatActivity { private boolean playerOne = true; private int numTurns; private String turn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tic_tac_toe); TextView text = (TextView) findViewById(R.id.textView); turn = getString(R.string.append_turn); text.setText(getIntent().getStringExtra("playerOne") + turn); } public void clickListen(View view) { TextView text = (TextView) findViewById(R.id.textView); Button btn = (Button) findViewById(view.getId()); if(playerOne && btn.getText().toString().isEmpty()) { playerOne = false; btn.setText("X"); numTurns++; } else if (!playerOne && btn.getText().toString().isEmpty()) { playerOne = true; btn.setText("O"); numTurns++; } if(!((Button) findViewById(R.id.one)).getText().toString().isEmpty()) { if(((Button) findViewById(R.id.one)).getText().toString().equals(((Button) findViewById(R.id.two)).getText().toString()) && ((Button) findViewById(R.id.one)).getText().toString().equals(((Button) findViewById(R.id.three)).getText().toString()) || ((Button) findViewById(R.id.one)).getText().toString().equals(((Button) findViewById(R.id.four)).getText().toString()) && ((Button) findViewById(R.id.one)).getText().toString().equals(((Button) findViewById(R.id.seven)).getText().toString())) { winCondition(); } } else if(!((Button) findViewById(R.id.five)).getText().toString().isEmpty()) { if (((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.two)).getText().toString()) && ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.eight)).getText().toString()) || ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.four)).getText().toString()) && ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.six)).getText().toString()) || ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.one)).getText().toString()) && ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.nine)).getText().toString()) || ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.three)).getText().toString()) && ((Button) findViewById(R.id.five)).getText().toString().equals(((Button) findViewById(R.id.seven)).getText().toString())) { winCondition(); } } else if (!((Button) findViewById(R.id.nine)).getText().toString().isEmpty()) { if (((Button) findViewById(R.id.nine)).getText().toString().equals(((Button) findViewById(R.id.eight)).getText().toString()) && ((Button) findViewById(R.id.nine)).getText().toString().equals(((Button) findViewById(R.id.seven)).getText().toString()) || ((Button) findViewById(R.id.nine)).getText().toString().equals(((Button) findViewById(R.id.six)).getText().toString()) && ((Button) findViewById(R.id.nine)).getText().toString().equals(((Button) findViewById(R.id.three)).getText().toString())) { winCondition(); } } else if(numTurns == 9) { drawCondition(); } if(playerOne) { text.setText(getIntent().getStringExtra("playerOne") + turn); } else { text.setText(getIntent().getStringExtra("playerTwo") + turn); } } public void winCondition() { String result = playerOne ? getIntent().getStringExtra("playerTwo") : getIntent().getStringExtra("playerOne"); String loser = playerOne ? getIntent().getStringExtra("playerOne") : getIntent().getStringExtra("playerTwo"); createDialog(result + getString(R.string.won)); SharedPreferences sharedPref = getSharedPreferences("LevelScores", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(result, sharedPref.getInt(result, 0) + 1); editor.putInt(loser, sharedPref.getInt(loser, 0)); editor.commit(); } public void drawCondition() { createDialog(getString(R.string.draw)); SharedPreferences sharedPref = getSharedPreferences("LevelScores", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getIntent().getStringExtra("playerOne"), sharedPref.getInt(getIntent().getStringExtra("playerOne"), 0)); editor.putInt(getIntent().getStringExtra("playerTwo"), sharedPref.getInt(getIntent().getStringExtra("playerTwo"), 0)); editor.commit(); } public void createDialog(String condition) { new AlertDialog.Builder(this) .setTitle(condition) .setItems(R.array.end_options, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if(which == 0) { startActivity(new Intent(getBaseContext(), NameEntry.class)); } else if (which == 1) { startActivity(new Intent(getBaseContext(), Leaderboard.class)); } else { startActivity(new Intent(getBaseContext(), MainActivity.class)); } } }) .setIcon(android.R.drawable.ic_menu_view) .show(); } } <file_sep>package cis195.tictactoe; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class NameEntry extends AppCompatActivity { EditText firstPlayer; EditText secondPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_name_entry); firstPlayer = (EditText)findViewById(R.id.editText); secondPlayer = (EditText) findViewById(R.id.editText2); } public void sendNames(View view) { if(firstPlayer.getText().toString().isEmpty() || secondPlayer.getText().toString().isEmpty()) { Toast.makeText(this, "Must enter names for both players", Toast.LENGTH_SHORT).show(); } else if(firstPlayer.getText().toString().equals(secondPlayer.getText().toString())) { Toast.makeText(this, "Must enter different names", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(getBaseContext(), TicTacToe.class); intent.putExtra("playerOne", firstPlayer.getText().toString()); intent.putExtra("playerTwo", secondPlayer.getText().toString()); startActivity(intent); } } }
9709a953203f5704ca45b6f72a5536898a7c65e9
[ "Markdown", "Java" ]
3
Markdown
relisher/TicTacToe
5b081d1ff8c87b50060e3cd998482d9541797bd8
3861d610669a707d05e1b913123802ad333980be
refs/heads/master
<file_sep># Práctica 5 Pruebas(Mocha , Tai, Sinon, Blanket) Con Karma y Travis Este repositorio aloja la práctica de conversión de tipos, realizada con html, css y javascript, usando POO y haciendo uso de la herencia en javascript. **_Travis:_** [![Build Status](https://travis-ci.org/alu0100783612/eliminacion-del-switch-smell-josemena-yerayperez-1516.svg?branch=master)](https://travis-ci.org/alu0100783612/eliminacion-del-switch-smell-josemena-yerayperez-1516) **Enlace a la descripción de la práctica** * [_Descripción en GitBook_](https://casianorodriguezleon.gitbooks.io/pl1516/content/practicas/travis.html) **Enlace Campus Virtual de la asignatura** * [_Campus Virtual_](https://campusvirtual.ull.es/1516/course/view.php?id=144) **Repositorio GitHuB** * [_Repositorio del fork_](https://github.com/alu0100783612/eliminacion-del-switch-smell-josemena-yerayperez-1516/tree/master) * [_Repositorio Git Organización_](https://github.com/ULL-ESIT-GRADOII-DSI/karma-y-travis-mena-yeray) **Página de lo autores** * [_Web de <NAME>_](http://alu0100768893.github.io/) * [_Web de <NAME>_](http://alu0100783612.github.io/) <file_sep>(function(exports) { "use strict"; //---Cadenas para las expresiones regulares--- var reg1 = '^(\\s*) '+ '(?<val> ([-+]?\\d+(?:\\.\\d+)?)\\s*(e[-+]?\\d+(?:\\.\\d+)?)?) '+ '(\\s*) '+ '(?<tipo> [a-z]+[0-9]*) '+ '(\\s*) '; var reg2 = '(a?) '+ '(\\s*) '+ '(?<destino> [a-z]+[0-9]*) '+ '(\\s*)$ '; function Medida(valor,tipo) { //---Si me introducen las dos variables--- if (tipo) { console.log("Se pasaron dos parametros"); this.valor_ = valor; this.tipo_ = tipo; //---Si introducen toda la temperatura como un sólo argumento--- }else { var med = XRegExp.exec(valor,XRegExp( reg1 ,'xi')); if (med) { var val = med.val; val = parseFloat(val); var tip = med.tipo; this.valor_ = val; this.tipo_ = tip; } } }; Medida.prototype.constructor = Medida; //---Tabla hash donde se almacenarán las parejas identificador de la medida y la clase de la medida--- Medida.measures = {} || 0; Medida.prototype.toS = function (){ return this.valor_; }; Medida.prototype.type = function(){ return this.tipo_; }; //Medida.protoype.convertir = function(valor) { Medida.prototype.convertir = function(valor) { var match = XRegExp.exec(valor,XRegExp( reg1+reg2 ,'xi')); if (match) { //console.log("entre al if"); var numero = match.val; var tipo = match.tipo; tipo = tipo.toLowerCase(); var to = match.destino; to = to.toLowerCase(); numero = parseFloat(numero); //console.log("numero "+numero+" tipo "+tipo+" destino "+ to); try{ var measures = Medida.measures; //---Creamos un objeto de la medida tipo a través de la tabla measures--- var source = new measures[tipo](numero); //---Obtenemos mediante la tabla measures la medida destino de la conversión--- var target = "to"+measures[to].name; //---Ordenamos al objeto convertirse, lo que nos devuelve un objeto del tipo destino--- var resultado = source[target](); return resultado.toS() + " " + to; } catch(err){ return 'Desconozco como convertir desde "'+tipo+'" hasta "'+to+'"'; } } else{ return "Introduzca algo como 32c a F"; } }; exports.Medida = Medida; })(this); <file_sep>(function(exports) { "use strict"; function Temperatura(valor,tipo) { Medida.call(this, valor, tipo); }; Temperatura.prototype = new Medida(); Temperatura.prototype.constructor = Temperatura; Temperatura.toS = function(){ return this.valor; }; exports.Temperatura = Temperatura; //---Hash de medidas--- var measures= Medida.measures; //---Celsius--- function Celsius(valor) { Temperatura.call(this, valor, 'c'); }; Celsius.prototype = new Temperatura(); Celsius.prototype.constructor = Celsius; measures.c = Celsius; Celsius.prototype.toFarenheit = function(){ var resultado = (this.valor_ * (9/5))+32; var objetoResultado = new Farenheit(resultado); return objetoResultado; }; Celsius.prototype.toKelvin = function(){ var resultado = this.valor_ + 273; var objetoResultado = new Kelvin(resultado); return objetoResultado; }; Celsius.prototype.toS = function(){ return this.valor_; }; exports.Celsius = Celsius; //---Farenheit--- function Farenheit(valor) { Temperatura.call(this, valor, 'f'); }; Farenheit.prototype = new Temperatura(); Farenheit.prototype.constructor = Farenheit; measures.f = Farenheit; Farenheit.prototype.toCelsius = function(){ var resultado = (this.valor_ - 32)*(5/9); var objetoResultado = new Celsius(resultado); return objetoResultado; }; Farenheit.prototype.toKelvin = function(){ var resultado = ((this.valor_ - 32)*(5/9)) + 273; var objetoResultado = new Kelvin(resultado); return objetoResultado; }; Farenheit.prototype.toS = function(){ return this.valor_; }; exports.Farenheit = Farenheit; //---Kelvin--- function Kelvin(valor) { Temperatura.call(this, valor, 'k'); }; Kelvin.prototype = new Temperatura(); Kelvin.prototype.constructor = Kelvin; measures.k = Kelvin; Kelvin.prototype.toCelsius = function(){ var resultado = this.valor_ - 273; var objetoResultado = new Celsius(resultado); return objetoResultado; }; Kelvin.prototype.toFarenheit = function(){ var resultado = ((this.valor_ - 273) * (9/5))+32 var objetoResultado = new Farenheit(resultado); return objetoResultado; }; Kelvin.prototype.toS = function(){ return this.valor_; }; exports.Kelvin = Kelvin; })(this);
64e9851d4b8fcaf99b550ecb46beab4ce6a2c2aa
[ "Markdown", "JavaScript" ]
3
Markdown
ULL-ESIT-GRADOII-DSI/karma-y-travis-josemena-yerayperez-1516
ef24e06c96f2766ff806812be154ccb086c73c44
5aa6ce93c7c695055c3b84fd24ca83fa0a80f9cd
refs/heads/master
<file_sep>import React, { useEffect } from "react"; import { useSelector, useDispatch } from "react-redux"; import { fetchRepos } from "./store/repos"; const App = () => { const dispatch = useDispatch(); const { repos, isFetching, error } = useSelector((state) => state.repos); useEffect(() => { dispatch(fetchRepos()); }, [dispatch]); return ( <> {isFetching && <div>Loading...</div>} {error && <div>Error: {error.message}</div>} <div> {repos.map((repo) => ( <p key={repo.id}>{repo.name}</p> ))} </div> </> ); }; export default App; <file_sep>import { ofType } from "redux-observable"; import { of } from "rxjs"; import { map, mergeMap, delay, catchError } from "rxjs/operators"; import { ajax } from "rxjs/ajax"; import api from "../services/api"; const TYPES = { FETCH_REPOS_REQUEST: "FETCH_REPOS_REQUEST", FETCH_REPOS_SUCCESS: "FETCH_REPOS_SUCCESS", FETCH_REPOS_FAILURE: "FETCH_REPOS_FAILURE", }; const initialState = { isFetching: false, status: null, error: "", repos: [], }; const reducer = (state = initialState, action) => { switch (action.type) { case TYPES.FETCH_REPOS_REQUEST: return { ...state, isFetching: true, status: null, error: null }; case TYPES.FETCH_REPOS_FAILURE: return { ...state, isFetching: false, status: "error", error: action.error, repos: [], }; case TYPES.FETCH_REPOS_SUCCESS: return { ...state, isFetching: false, status: "success", error: null, repos: action.repos, }; default: return state; } }; const fetchRepos = () => ({ type: TYPES.FETCH_REPOS_REQUEST, }); const fetchFailure = (error) => ({ type: TYPES.FETCH_REPOS_FAILURE, error, }); const fetchSuccess = (repos) => ({ type: TYPES.FETCH_REPOS_SUCCESS, repos, }); const fetchRepoEpic = (action$) => action$.pipe( ofType(TYPES.FETCH_REPOS_REQUEST), mergeMap((action) => ajax.getJSON(`${api.github}/repositories`).pipe( delay(5000), map((repos) => fetchSuccess(repos)), catchError((error) => of(fetchFailure(error.xhr.response))) ) ) ); export { fetchRepos, fetchRepoEpic }; export default reducer; <file_sep>const Api = { github: "https://api.github.com", }; export default Api; <file_sep>import { createStore, combineReducers, applyMiddleware, compose } from "redux"; import { createEpicMiddleware, combineEpics } from "redux-observable"; import reposReducer, { fetchRepoEpic } from "./repos"; import usersReducer from "./users"; const epicMiddleware = createEpicMiddleware(); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const combinedEpics = combineEpics(fetchRepoEpic); const combinedReducers = combineReducers({ users: usersReducer, repos: reposReducer, }); const store = createStore( combinedReducers, composeEnhancers(applyMiddleware(epicMiddleware)) ); epicMiddleware.run(combinedEpics); export default store; <file_sep>const TYPES = { FETCH_USERS_REQUEST: "FETCH_USERS_REQUEST", FETCH_USERS_SUCCESS: "FETCH_USERS_SUCCESS", FETCH_USERS_FAILURE: "FETCH_USERS_FAILURE", }; const initialState = { isFetching: false, status: null, error: "", users: [], }; const reducer = (state = initialState, action) => { switch (action.type) { case TYPES.FETCH_USERS_REQUEST: return { ...state, isFecthing: true, status: null, error: null }; case TYPES.FETCH_USERS_FAILURE: return { ...state, isFetching: false, status: "error", error: action.error, users: [] }; case TYPES.FETCH_USERS_SUCCESS: return { ...state, isFetching: false, status: "success", error: null, users: action.USERS }; default: return state; } }; const fetchRepo = (name) => ({ type: TYPES.FETCH_USERS_REQUEST, name, }); const fetchFailure = () => ({ type: TYPES.FETCH_USERS_FAILURE, }); const fetchSuccess = () => ({ type: TYPES.FETCH_USERS_SUCCESS, }); export { fetchRepo }; export default reducer;
321b5e13180e97068a3fce70265ea1d58a8b4554
[ "JavaScript" ]
5
JavaScript
brunorcajo/boilerplate-observable-rxjs
a0d819686ce85cdda861c6c9bfdb41044e9b7e7a
cb0abbd5ac4cd50f50ae2984a73054e0f79c93cd
refs/heads/master
<file_sep>'use strict'; /** * Module dependencies. */ process.env.NODE_ENV = 'development'; var init = require('./config/init')(), config = require('./config/config'), mongoose = require('mongoose'), chalk = require('chalk'); //console.log(config); //process.exit(); /** * Main application entry file. * Please note that the order of loading is important. */ // Bootstrap db connection //@todo http://stackoverflow.com/questions/13980236/does-mongodb-have-reconnect-issues-or-am-i-doing-it-wrong // ORIG CODE var db = mongoose.connect(config.db, {server: {auto_reconnect: true}}, function(err) { if (err) { console.error(chalk.red('Could not connect to MongoDB!')); console.log(chalk.red(err)); } }); //createConnection instead of connect //var db = mongoose.connect(config.db, {server: {auto_reconnect: true, socketOptions: {keepAlive: 1}}}, function(err) { // if (err) { // console.error(chalk.red('Could not connect to MongoDB!')); // console.log(chalk.red(err)); // } //}); // Init the express application var app = require('./config/express')(db); // Bootstrap passport config require('./config/passport')(); // Start the app by listening on <port> app.listen(config.port); // Expose app exports = module.exports = app; // Logging initialization // console.log('===================server.js======================='); var now = new Date(); //var tStart = new Date(1461945100 * 1000); //var tEnd = new Date(1462031500 * 1000); console.log(''); console.log('################################################################################'); console.log('# LogMyAssets application started on port ' + config.port + ' #'); console.log('# Current Directory ' + process.cwd() + ' #'); console.log('# Current process id ' + process.pid + ' #'); console.log('# Current process env ' + process.env.NODE_ENV + ' #');//JSON.stringify(process.env) console.log('# Current time ' + now + ' #'); //console.log('# Current tStart ' + tStart + ' #'); //console.log('# Current tEnd ' + tEnd + ' #'); console.log('################################################################################'); console.log('');<file_sep>'use strict'; module.exports = function (grunt) { grunt.initConfig({ //pkg: grunt.file.readJson('package.json'), dist: { options: {}, files: { 'dist': ['dist/application.js', 'dist/application.min.1.30.css', 'dist/application.min.1.30.js'], }, }, copy: { dist: { cwd: 'modules', src: ['**/**'], dest: 'dist', expand: true } }, jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'modules/application.js' ] }, concat: { plugin: { src: ['modules/**/**/*.js'], dest: 'dist/application.js' }, css: { src: ['modules/**/**/*.css'], dest: 'dist/application.min.1.30.css' } }, uglify: { plugin: { src: ['dist/application.js'], dest: 'dist/application.min.1.30.js' } } }); grunt.loadNpmTasks('grunt-dist'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); // grunt.registerTask('travis', ['jshint']); grunt.registerTask('default', [ 'dist', 'copy', 'jshint', 'concat', 'uglify' ]); };<file_sep>LogMyAssets =========== This system uses [npm](https://www.npmjs.com/) to create a working environment. To use the system you will need to install both [nodeJS](https://nodejs.org/en/) and [MongoDB](https://www.mongodb.com/download-center#community) first. Requirements -------------- 1. Clone this git respository. 2. Install [Grunt](http://gruntjs.com/) npm install -g grunt-cli. 3. Install [Bower](https://bower.io/) npm install -g bower 4. Install server dependencies with npm install. 5. Install client application dependencies with bower install. 6. Once complete run the application with grunt 7. Browse to http://localhost:3000/ Install database ------------------------------- binary files located externally no current migrations
f923f7adfc7d4924de4bc4e0355dc323b7402e70
[ "JavaScript", "Markdown" ]
3
JavaScript
kavitsoni/LogMyAsset
f00e36ccee8bbe9862279eb351d8bfa59925d37a
2581a35b04ad54e2744baa4f64f3fe88aed975f4
refs/heads/master
<file_sep># # This script is the server-side of the XML-RPC defined for gef # It must be run from inside IDA # # If you edit HOST/PORT, use `gef config` command to edit them # # Ref: # - https://docs.python.org/2/library/simplexmlrpcserver.html # - https://pymotw.com/2/SimpleXMLRPCServer/ # # @_hugsy_ # from __future__ import print_function from threading import Thread from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer, list_public_methods from idautils import * from idc import * import string import inspect HOST = "0.0.0.0" PORT = 1337 def expose(f): "Decorator to set exposed flag on a function." f.exposed = True return f def is_exposed(f): "Test whether another function should be publicly exposed." return getattr(f, 'exposed', False) def ishex(s): if s.startswith("0x") or s.startswith("0X"): s = s[2:] return all(c in set(string.hexdigits) for c in s) class Ida: """ Top level class where exposed methods are declared. """ PREFIX = "ida" def __init__(self, server, *args, **kwargs): self.server = server return def _dispatch(self, method, params): """ Plugin dispatcher """ if not method.startswith(self.PREFIX + '.'): raise NotImplementedError('Method "%s" is not supported' % method) method_name = method.partition('.')[2] func = getattr(self, method_name) if not is_exposed(func): raise NotImplementedError('Method "%s" is not exposed' % method) return func(*params) def _listMethods(self): """ Class method listing (required for introspection API). """ m = [] for x in list_public_methods(self): if x.startswith("_"): continue if not is_exposed( getattr(self, x) ): continue m.append(x) return m def _methodHelp(self, method): """ Method help (required for introspection API). """ f = getattr(self, method) return inspect.getdoc(f) @expose def shutdown(self): """ ida.shutdown() => None Cleanly shutdown the XML-RPC service. Example: ida.shutdown """ self.server.server_close() print("XMLRPC server stopped") return 0 @expose def add_comment(self, address, comment): """ ida.add_comment(int addr, string comment) => None Add a comment to the current IDB at the location `address`. Example: ida.add_comment 0x40000 "Important call here!" """ addr = long(address, 16) if ishex(address) else long(address) return MakeComm(addr, comment) @expose def set_color(self, address, color="0x005500"): """ ida.set_color(int addr [, int color]) => None Set the location pointed by `address` in the IDB colored with `color`. Example: ida.set_color 0x40000 """ addr = long(address, 16) if ishex(address) else long(address) color = long(color, 16) if ishex(color) else long(color) return SetColor(addr, CIC_ITEM, color) @expose def set_name(self, address, name): """ ida.set_name(int addr, string name]) => None Set the location pointed by `address` with the name specified as argument. Example: ida.set_name 0x00000000004049de __entry_point """ addr = long(address, 16) if ishex(address) else long(address) return MakeName(addr, name) @expose def jump_to(self, address): """ ida.jump_to(int addr) => None Move the IDA EA pointer to the address pointed by `addr`. Example: ida.jump_to 0x00000000004049de """ addr = long(address, 16) if ishex(address) else long(address) return Jump(addr) # ideas for commands: # - rebase program based on gdb runtime value # - run ida plugin remotely # - edit gdb/capstone disassembly view to integrate comments from idb # - generic command about idb : path/dir/hash etc. # - details of xref to a given address class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = ("/RPC2",) def start_xmlrpc_server(): """ Initialize the XMLRPC thread """ print("[+] Starting XMLRPC server: {}:{}".format(HOST, PORT)) server = SimpleXMLRPCServer((HOST, PORT), requestHandler=RequestHandler, logRequests=True) server.register_introspection_functions() server.register_instance( Ida(server) ) print("[+] Registered {} functions.".format( len(server.system_listMethods()) )) server.serve_forever() return if __name__ == "__main__": t = Thread(target=start_xmlrpc_server, args=()) t.daemon = True print("[+] Creating new thread for XMLRPC server: {}".format(t.name)) t.start()
2bcf72e37755bf721c22eaeafa8f31211351c2fe
[ "Python" ]
1
Python
wambiri/stuff
1acf0cf527f8541d288263c9e65e9676263bd36b
c8cd4f1593b4c8e6b6571203ffcfdc480d5ca370
refs/heads/master
<repo_name>skydive-project/dede<file_sep>/dede/asciinema.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "encoding/json" "fmt" "io/ioutil" "sync" "time" ) type asciinemaRecorderEntry struct { delay float64 data string } type asciinemaRecorder struct { Version int `json:"version"` Width int `json:"width"` Height int `json:"height"` Duration float64 `json:"duration"` Command string `json:"command"` Title string `json:"title"` Env map[string]string `json:"env"` Stdout []asciinemaRecorderEntry `json:"stdout"` lastEntry time.Time lock sync.RWMutex filename string } func (a *asciinemaRecorderEntry) MarshalJSON() ([]byte, error) { return json.MarshalIndent([]interface{}{a.delay, a.data}, "", " ") } func (a *asciinemaRecorder) addEntry(data string) { a.lock.Lock() defer a.lock.Unlock() now := time.Now() delay := float64(now.Sub(a.lastEntry).Nanoseconds()) / float64(time.Second) a.Stdout = append(a.Stdout, asciinemaRecorderEntry{ delay: delay, data: data, }) a.lastEntry = now a.Duration += delay } func (a *asciinemaRecorder) addInputEntry(data string) { a.addEntry(data) } func (a *asciinemaRecorder) addOutputEntry(data string) { a.addEntry(data) } func (a *asciinemaRecorder) write() error { a.lock.RLock() defer a.lock.RUnlock() data, err := json.MarshalIndent(a, "", " ") if err != nil { return fmt.Errorf("Unable to serialize asciinema file: %s", err) } if err := ioutil.WriteFile(a.filename, data, 0644); err != nil { return fmt.Errorf("Unable to write asciinema file: %s", err) } return nil } func newAsciinemaRecorder(filemane string) *asciinemaRecorder { return &asciinemaRecorder{ Env: make(map[string]string), lastEntry: time.Now(), filename: filemane, } } <file_sep>/cmd/server.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package cmd import ( "github.com/skydive-project/dede/dede" "github.com/spf13/cobra" ) var ( port int dataDir string ) var server = &cobra.Command{ Use: "server", Short: "dede server", Long: "dede server", SilenceUsage: true, Run: func(cmd *cobra.Command, args []string) { dede.InitServer(dataDir, port) dede.ListenAndServe() }, } func init() { server.Flags().StringVarP(&dataDir, "data-dir", "", "/tmp", "data dir path, place where the files will go") server.Flags().IntVarP(&port, "port", "", 11664, "port used by the DeDe server, default: 11664") } <file_sep>/dede/text_handler.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "encoding/json" "io/ioutil" "net/http" "github.com/gorilla/mux" ) type textHandler struct { } func (v *textHandler) addText(w http.ResponseWriter, r *http.Request) { tp, err := createPathFromForm(r, "text.json") if err != nil { w.WriteHeader(http.StatusBadRequest) return } text := struct { Type string Text string }{} decoder := json.NewDecoder(r.Body) if err = decoder.Decode(&text); err != nil { w.WriteHeader(http.StatusBadRequest) return } data, err := json.MarshalIndent(text, "", " ") if err != nil { w.WriteHeader(http.StatusInternalServerError) return } if err := ioutil.WriteFile(tp, data, 0644); err != nil { w.WriteHeader(http.StatusInternalServerError) return } Log.Infof("Text recorded %s", tp) w.WriteHeader(http.StatusOK) } func registerTextHandler(prefix string, router *mux.Router) error { t := &textHandler{} router.HandleFunc(prefix+"/text", t.addText) return nil } func init() { addHandler("text", registerTextHandler) } <file_sep>/cmd/cmd.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package cmd import "github.com/spf13/cobra" var RootCmd = &cobra.Command{ Use: "dede [sub]", Short: "DeDe", SilenceUsage: true, PersistentPreRun: func(cmd *cobra.Command, args []string) { }, } func init() { RootCmd.AddCommand(versionCmd) RootCmd.AddCommand(server) } <file_sep>/dede/assets.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "mime" "net/http" "path/filepath" "strings" "github.com/skydive-project/dede/statics" ) func asset(prefix string, w http.ResponseWriter, r *http.Request) { upath := strings.TrimPrefix(r.URL.Path, prefix) if strings.HasPrefix(upath, "/") { upath = strings.TrimPrefix(upath, "/") } content, err := statics.Asset(upath) if err != nil { Log.Errorf("unable to find the asset: %s", upath) w.WriteHeader(http.StatusNotFound) return } ext := filepath.Ext(upath) ct := mime.TypeByExtension(ext) w.Header().Set("Content-Type", ct+"; charset=UTF-8") w.WriteHeader(http.StatusOK) w.Write(content) } <file_sep>/dede/history.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "encoding/json" "fmt" "io/ioutil" "strings" "sync" ) type historyRecorderEntry struct { Input string Output string } type historyRecorder struct { Entries []historyRecorderEntry lock sync.RWMutex filename string current historyRecorderEntry prevData string prevDirection string } func (h *historyRecorder) addInputEntry(data string) { h.lock.Lock() defer h.lock.Unlock() if h.prevDirection == "output" { h.Entries = append(h.Entries, h.current) // generate a new entry h.current = historyRecorderEntry{} } t := strings.TrimSuffix(data, "\r") if t != "" { h.current.Input += t } h.prevData = data h.prevDirection = "input" } func (h *historyRecorder) addOutputEntry(data string) { h.lock.Lock() defer h.lock.Unlock() // do not register echo if data == h.prevData { return } h.current.Output += data h.prevDirection = "output" } func (h *historyRecorder) write() error { h.lock.RLock() defer h.lock.RUnlock() if h.current.Input != "" { h.Entries = append(h.Entries, h.current) } data, err := json.MarshalIndent(h, "", " ") if err != nil { return fmt.Errorf("Unable to serialize history file: %s", err) } if err := ioutil.WriteFile(h.filename, data, 0644); err != nil { return fmt.Errorf("Unable to write asciinema file: %s", err) } return nil } func newHistoryRecorder(filename string) *historyRecorder { return &historyRecorder{ filename: filename, } } <file_sep>/contrib/python/dede.py import urllib2 import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class DedeChapterManager: def __init__(self, dede, chapterID): self.dede = dede self.chapterID = chapterID def __enter__(self): self.prevChapterID = self.dede.chapterID self.dede.chapterID = self.chapterID def __exit__(self, type, value, traceback): self.dede.chapterID = self.prevChapterID class DedeSectionManager: def __init__(self, dede, sectionID): self.dede = dede self.sectionID = sectionID def __enter__(self): self.prevSectionID = self.dede.sectionID self.dede.sectionID = self.sectionID def __exit__(self, type, value, traceback): self.dede.sectionID = self.prevSectionID class Dede: def __init__(self, endpoint, driver, sessionID): self.endpoint = endpoint self.driver = driver self.sessionID = sessionID self.chapterID = '' self.sectionID = '' def fake_mouse(self): return DedeFakeMouse(self) def terminal_manager(self): return DedeTerminalManager(self) def video_recorder(self): return DedeVideoRecorder(self) def chapter(self, chapterID): return DedeChapterManager(self, chapterID) def section(self, sectionID): return DedeSectionManager(self, sectionID) class DedeFakeMouse: def __init__(self, dede): self.dede = dede def install(self): # TODO catch error print("%s/fake-mouse/install" % self.dede.endpoint) script = urllib2.urlopen( "%s/fake-mouse/install" % self.dede.endpoint).read() self.dede.driver.execute_script(script) def _fake_mouse_click_on(self, el): self.dede.driver.execute_async_script( "DedeFakeMouse.clickOn(arguments[0], arguments[1])", el) def _fake_mouse_move_on(self, el): self.dede.driver.execute_async_script( "DedeFakeMouse.moveOn(arguments[0], arguments[1])", el) def click_on(self, el): self._fake_mouse_click_on(el) el.click() def move_on(self, el): self._fake_mouse_move_on(el) class DedeTerminalManagerTab: def __init__(self, dede, window_handle): self.dede = dede self.window_handle = window_handle def focus(self): self.dede.driver.switch_to_window(self.window_handle) def start_record(self): self.dede.driver.execute_script( "DedeTerminal.startRecord(%d, %d, %d)" % (self.dede.sessionID, self.dede.chapterID, self.dede.sectionID)) def stop_record(self): self.dede.driver.execute_script("DedeTerminal.stopRecord()") def type(self, str): self.dede.driver.execute_async_script( "DedeTerminal.type(arguments[0], arguments[1])", str) def type_cmd(self, str): self.dede.driver.execute_async_script( "DedeTerminal.typeCmd(arguments[0], arguments[1])", str) def type_cmd_wait(self, str, regex): self.dede.driver.execute_async_script( "DedeTerminal.typeCmdWait(" "arguments[0], arguments[1], arguments[2])", str, regex) class DedeTerminalManager: def __init__(self, dede): self.dede = dede self.termIndex = 1 def open_terminal_tab( self, title, width=1400, cols=2000, rows=40, delay=70): self.dede.driver.execute_script( "window.open('%s/terminal/%s?" "title=%s&width=%d&cols=%d&rows=%d&delay=%d')" % (self.dede.endpoint, self.termIndex, title, width, cols, rows, delay)) self.termIndex += 1 window_handle = self.dede.driver.window_handles[-1] tab = DedeTerminalManagerTab(self.dede, window_handle) self.dede.driver.switch_to_window(window_handle) return tab class DedeVideoRecord: def __init__(self, dede): self.dede = dede def stop(self): # TODO catch error urllib2.urlopen( "%s/video/stop-record?sessionID=%s&chapterID=%s&sectionID=%s" % (self.dede.endpoint, self.dede.sessionID, self.dede.chapterID, self.dede.sectionID)) class DedeVideoRecorder: def __init__(self, dede): self.dede = dede def start_record(self): # TODO catch error urllib2.urlopen( "%s/video/start-record?sessionID=%s&chapterID=%s&sectionID=%s" % (self.dede.endpoint, self.dede.sessionID, self.dede.chapterID, self.dede.sectionID)) return DedeVideoRecord(self.dede) if __name__ == '__main__': driver = webdriver.Remote( command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities={"browserName": "chrome"}) driver.maximize_window() driver.get("https://github.com/skydive-project/dede") driver.set_script_timeout(20) time.sleep(2) dede = Dede("http://192.168.1.21:55555", driver, 1) fake_mouse = dede.fake_mouse() fake_mouse.install() with dede.chapter(1): record = dede.video_recorder().start_record() time.sleep(2) # start the demo clone = driver.find_element_by_xpath( "//details[contains(@class, 'get-repo-select-menu')]") fake_mouse.click_on(clone) copy = driver.find_element_by_xpath( "//button[@aria-label='Copy to clipboard']") fake_mouse.click_on(copy) input = driver.find_element_by_xpath( "//input[contains(@aria-label, 'Clone this repository at')]") url = input.get_property("value") time.sleep(1) tab1 = dede.terminal_manager().open_terminal_tab('clone') tab2 = dede.terminal_manager().open_terminal_tab('list') time.sleep(1) with dede.section(1): tab1.focus() tab1.start_record() tab1.type_cmd_wait("cd /tmp", "safchain") tab1.type_cmd_wait("git clone %s" % url, "safchain") tab1.type_cmd_wait("cd dede", "safchain") tab1.stop_record() with dede.section(2): tab2.focus() tab2.start_record() tab2.type_cmd_wait("ls -al", "safchain") tab2.stop_record() record.stop() time.sleep(10) driver.close() <file_sep>/dede/terminal_handler.go // +build !windows /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "html/template" "net/http" "strconv" "sync" "github.com/gobwas/ws" "github.com/gobwas/ws/wsutil" "github.com/gorilla/mux" "github.com/skydive-project/dede/statics" ) type terminalSession struct { sync.RWMutex id string recorders []terminalRecorder recording bool } type terminalHandler struct { sync.RWMutex prefix string sessions map[string]*terminalSession } func (t *terminalHandler) terminalStartRecord(w http.ResponseWriter, r *http.Request) { tp, err := createPathFromForm(r, "history.json") if err != nil { w.WriteHeader(http.StatusBadRequest) return } ap, err := createPathFromForm(r, "asciinema.json") if err != nil { w.WriteHeader(http.StatusBadRequest) return } vars := mux.Vars(r) id := vars["id"] t.RLock() s, ok := t.sessions[id] t.RUnlock() if !ok { w.WriteHeader(http.StatusNotFound) return } if s.recording { w.WriteHeader(http.StatusConflict) return } s.Lock() s.recorders = append(s.recorders, newAsciinemaRecorder(ap)) s.recorders = append(s.recorders, newHistoryRecorder(tp)) s.recording = true s.Unlock() Log.Infof("start recording terminal session %s", tp) w.WriteHeader(http.StatusOK) } func (t *terminalHandler) terminalStopRecord(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] t.RLock() s, ok := t.sessions[id] t.RUnlock() if !ok { w.WriteHeader(http.StatusNotFound) return } t.RLock() recorders := s.recorders t.RUnlock() if !ok { w.WriteHeader(http.StatusPreconditionFailed) return } for _, recorder := range recorders { if err := recorder.write(); err != nil { w.WriteHeader(http.StatusInternalServerError) w.Write([]byte(err.Error())) return } } s.Lock() s.recorders = s.recorders[:0] s.recording = false s.Unlock() Log.Infof("stop recording terminal session %s", id) w.WriteHeader(http.StatusOK) } func (t *terminalHandler) terminalIndex(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] asset := statics.MustAsset("statics/terminal.html") w.Header().Set("Content-Type", "text/html; charset=UTF-8") w.WriteHeader(http.StatusOK) width := r.FormValue("width") if width == "" { width = "1200" } height := r.FormValue("height") if height == "" { height = "600" } data := struct { Prefix string ID string Title string Cols string Rows string Width string Height string Delay string Controls string InitCmd string }{ Prefix: t.prefix, ID: id, Title: r.FormValue("title"), Cols: r.FormValue("cols"), Rows: r.FormValue("rows"), Width: width, Height: height, Delay: r.FormValue("delay"), Controls: r.FormValue("controls"), InitCmd: r.FormValue("cmd"), } tmpl := template.Must(template.New("terminal").Parse(string(asset))) if err := tmpl.Execute(w, data); err != nil { Log.Errorf("Unable to execute terminal template: %s", err) } t.Lock() t.sessions[id] = &terminalSession{} t.Unlock() } func (t *terminalHandler) terminalWebsocket(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] t.RLock() s, ok := t.sessions[id] t.RUnlock() if !ok { w.WriteHeader(http.StatusNotFound) return } conn, _, _, err := ws.UpgradeHTTP(r, w, nil) if err != nil { Log.Errorf("websocket upgrade error: %s", err) return } Log.Infof("websocket new client from: %s", r.RemoteAddr) in := make(chan []byte, 50) out := make(chan []byte, 50) var cols int if value := r.FormValue("cols"); value != "" { cols, err = strconv.Atoi(value) if err != nil { Log.Errorf("unable to parse cols value %s: %s", value, err) } } // start a new terminal for this connection term := newTerminal("/bin/bash", terminalOpts{cols: cols}) term.start(in, out, nil) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() defer conn.Close() for msg := range out { s.RLock() for _, recorder := range s.recorders { recorder.addOutputEntry(string(msg)) } s.RUnlock() err = wsutil.WriteServerMessage(conn, ws.OpText, msg) if err != nil { Log.Errorf("websocket error while writing message: %s", err) break } } }() wg.Add(1) go func() { defer wg.Done() for { msg, _, err := wsutil.ReadClientData(conn) if err != nil { Log.Errorf("websocket error while reading message: %s", err) break } s.RLock() for _, recorder := range s.recorders { recorder.addInputEntry(string(msg)) } s.RUnlock() in <- msg } term.close() close(out) }() go func() { wg.Wait() Log.Infof("websocket client left: %s", r.RemoteAddr) }() } func registerTerminalHandler(prefix string, router *mux.Router) error { t := &terminalHandler{ sessions: make(map[string]*terminalSession), prefix: prefix, } assetFnc := func(w http.ResponseWriter, r *http.Request) { asset(prefix, w, r) } router.PathPrefix(prefix + "/statics").HandlerFunc(assetFnc) router.HandleFunc(prefix+"/terminal/{id}/ws", t.terminalWebsocket) router.HandleFunc(prefix+"/terminal/{id}/start-record", t.terminalStartRecord) router.HandleFunc(prefix+"/terminal/{id}/stop-record", t.terminalStopRecord) router.HandleFunc(prefix+"/terminal/{id}", t.terminalIndex) return nil } func init() { addHandler("terminal", registerTerminalHandler) } <file_sep>/contrib/go/dede.go package main import ( "time" "github.com/tebeka/selenium" ) func main() { caps := selenium.Capabilities{"browserName": "chrome"} webdriver, err := selenium.NewRemote(caps, "http://localhost:4444/wd/hub") if err != nil { panic(err) } webdriver.MaximizeWindow("") webdriver.SetAsyncScriptTimeout(5 * time.Second) } <file_sep>/dede/video_recorder.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "context" "fmt" "os" "os/exec" ) type videoRecorder struct { filename string frameRate int width int height int cancel context.CancelFunc } func (v *videoRecorder) start() error { cmd := "ffmpeg" args := []string{ "-f", "x11grab", "-framerate", fmt.Sprintf("%d", v.frameRate), "-video_size", fmt.Sprintf("%dx%d", v.width, v.height), "-i", ":1.0+0,0", "-draw_mouse", "0", "-segment_format_options", "movflags=+faststart", "-crf", "0", "-preset", "ultrafast", "-qp", "0", "-y", "-an", v.filename} Log.Infof("start video recording: %s %v", cmd, args) command := exec.Command(cmd, args...) if err := command.Start(); err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) v.cancel = cancel go func() { <-ctx.Done() err := command.Process.Signal(os.Interrupt) if err != nil { Log.Errorf("cannot kill video recorder process: %s %v", cmd, args) return } command.Wait() }() return nil } func (v *videoRecorder) stop() { v.cancel() } func newVideoRecorder(filename string, width int, height int, frameRate int) *videoRecorder { return &videoRecorder{ filename: filename, width: width, height: height, frameRate: frameRate, } } <file_sep>/Makefile bindata: go-bindata ${BINDATA_FLAGS} -nometadata -o statics/bindata.go -pkg=statics -ignore=bindata.go statics/* statics/js/vendor/* statics/css/vendor/* gofmt -w -s statics/bindata.go install: bindata go install -v ./... <file_sep>/dede/terminal.go // +build !windows /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "fmt" "os" "os/exec" "sync" "syscall" "unsafe" "github.com/kr/pty" ) type terminalOpts struct { cols int } type terminal struct { sync.RWMutex cmd string opts terminalOpts pty *os.File } func newTerminal(cmd string, opts ...terminalOpts) *terminal { t := &terminal{ cmd: cmd, } if len(opts) > 0 { t.opts = opts[0] } return t } type termsize struct { Rows uint16 Cols uint16 X uint16 Y uint16 } func setsize(f *os.File, ts *termsize) error { _, _, errno := syscall.Syscall( syscall.SYS_IOCTL, f.Fd(), syscall.TIOCSWINSZ, uintptr(unsafe.Pointer(ts)), ) if errno != 0 { return syscall.Errno(errno) } return nil } func (t *terminal) start(in chan []byte, out chan []byte, err chan error) { sz := &termsize{ Cols: 80, } if t.opts.cols != 0 { sz.Cols = uint16(t.opts.cols) } p, e := pty.Start(exec.Command(t.cmd)) if e != nil { err <- fmt.Errorf("failed to start: %s", e) return } setsize(p, sz) t.Lock() t.pty = p t.Unlock() // pty reading go func() { for { buf := make([]byte, 1024) n, e := p.Read(buf) data := buf[:n] if e != nil { err <- fmt.Errorf("failed to start: %s", e) return } out <- data } }() // pty writing go func() { for b := range in { if _, e := p.Write(b); e != nil { err <- fmt.Errorf("failed to start: %s", e) return } } }() } func (t *terminal) close() { if err := t.pty.Close(); err != nil { Log.Errorf("failed to stop: %s", err) } } <file_sep>/dede/server.go /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package dede import ( "fmt" "html/template" "net/http" "os" "path/filepath" "sync" "github.com/gorilla/mux" logging "github.com/op/go-logging" "github.com/skydive-project/dede/statics" ) type Handler func(prefix string, router *mux.Router) error var ( Log = logging.MustGetLogger("default") format = logging.MustStringFormatter(`%{color}%{time:15:04:05.000} ▶ %{level:.6s}%{color:reset} %{message}`) handlers = make(map[string]Handler) router *mux.Router lock sync.RWMutex dataDir = "/tmp" port int ) func createPathFromForm(r *http.Request, filename string) (string, error) { path := fmt.Sprintf("%s/%s/%s/%s", dataDir, r.FormValue("sessionID"), r.FormValue("chapterID"), r.FormValue("sectionID")) if err := os.MkdirAll(path, 0755); err != nil { Log.Errorf("unable to create data dir %s: %s", path, err) return "", err } return filepath.Join(dataDir, r.FormValue("sessionID"), r.FormValue("chapterID"), r.FormValue("sectionID"), filename), nil } func idFromForm(r *http.Request, filename string) string { return fmt.Sprintf("%s-%s-%s-%s", r.FormValue("sessionID"), r.FormValue("chapterID"), r.FormValue("sectionID"), filename) } func index(w http.ResponseWriter, r *http.Request) { asset := statics.MustAsset("statics/index.html") w.Header().Set("Content-Type", "text/html; charset=UTF-8") w.WriteHeader(http.StatusOK) tmpl := template.Must(template.New("index").Parse(string(asset))) tmpl.Execute(w, nil) } func ListenAndServe() { addr := fmt.Sprintf(":%d", port) Log.Info("DeDe server started on " + addr) Log.Fatal(http.ListenAndServe(addr, router)) } func addHandler(name string, handler Handler) { handlers[name] = handler } func HasHandler(name string) bool { _, found := handlers[name] return found } func RegisterHandler(name, prefix string, router *mux.Router) error { if handler, found := handlers[name]; found { return handler(prefix, router) } return fmt.Errorf("unknown handler '%s'", name) } func InitServer(dd string, pp int) { logging.SetFormatter(format) dataDir = dd port = pp router = mux.NewRouter() router.HandleFunc("/", index) assetFnc := func(w http.ResponseWriter, r *http.Request) { asset("", w, r) } router.PathPrefix("/statics").HandlerFunc(assetFnc) for name := range handlers { RegisterHandler(name, "", router) } } <file_sep>/statics/js/terminal.js /* * Copyright (C) 2017 Red Hat, Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ $('#dede-terminal-record').change(function() { DedeTerminal.toggleRecord(); }); _DedeTerminal = function(endpoint, id, cols, rows, delay, initCmd) { var self = this; this.endpoint = endpoint; this.id = id; this.cols = parseInt(cols) || 80; this.rows = parseInt(rows) || 40; this.delay = parseInt(delay) || 100; this.recording = false; var container = document.getElementById('dede-terminal'); var term = new Terminal({ geometry: [this.cols, this.rows], //debug: true }); term.open(container); term.fit(); this.term = term; this.onMessageCallback = null; var websocket; function wsConnect() { var protocol = "ws://"; if (location.protocol === "https:") { protocol = "wss://"; } websocket = new WebSocket(protocol + endpoint + "/terminal/" + id + "/ws?cols=" + cols); websocket.onopen = function(evt) { term.attach(websocket); if (initCmd) { self.typeCmd(initCmd); } }; websocket.addEventListener('message', function(msg) { if (self.onMessageCallback) self.onMessageCallback(msg); }); websocket.onclose = wsDisconnected; websocket.onerror = wsOnError; } wsConnect(); function wsOnError() { $.notify("Writing error", "error"); } function wsDisconnected(evt) { $.notify("Connection error", "error"); setTimeout(wsConnect, 5000); } }; _DedeTerminal.prototype.type = function(str, callback) { var self = this; var el = str.split(''); var i = 0; var fnc = function() { self.term.send(el[i]); if (++i < el.length) { setTimeout(fnc, self.delay); } else if (callback) callback(); }; fnc(); }; _DedeTerminal.prototype.typeCmd = function(str, callback) { var self = this; this.type(str, function() { self.term.send("\n"); if (callback) callback(); }); }; _DedeTerminal.prototype.typeCmdWait = function(str, regex, callback) { var self = this; var re = new RegExp(regex, "m"); this.onMessageCallback = function(msg) { if (re.test(msg.data)) { self.onMessageCallback = null; if (callback) callback(); } }; this.typeCmd(str); }; _DedeTerminal.prototype.startRecord = function(sessionID, chapterID, sectionID) { $.ajax({ url : location.protocol + '//' + this.endpoint + '/terminal/' + this.id + '/start-record?sessionID=' + sessionID + "&chapterID=" + chapterID + "&sectionID=" + sectionID }); this.recording = true; }; _DedeTerminal.prototype.stopRecord = function() { $.ajax({ url : location.protocol + '//' + this.endpoint + '/terminal/' + this.id + '/stop-record' }); this.recording = false; }; _DedeTerminal.prototype.toggleRecord = function() { if (this.recording) this.stopRecord(); else this.startRecord(); };
391ce52c19c9c9f43e4c63118bbcde4930c21ad9
[ "Makefile", "Python", "Go", "JavaScript" ]
14
Go
skydive-project/dede
b1b74a5bb85696105128e95454a32cd82e6d3937
2e3ac2b1c0039e124415fd759a199c8d1cd74dbf
refs/heads/master
<repo_name>markisus/ssbm-labeler<file_sep>/video_seeker_image_provider.h // VideoSeekerImageProvider wraps a VideoSeeker as a QImageProvider #include <video_seeker.h> #include <QQuickImageProvider> #include <QDebug> class VideoSeekerImageProvider : public QQuickImageProvider { public: VideoSeekerImageProvider(const std::string& file_path) : QQuickImageProvider{QQuickImageProvider::Image}, video_seeker_{file_path} {} int maxMsec() const { return (int)(video_seeker_.duration()*1000); } QImage requestImage(const QString& id, QSize* size, const QSize& requestedSize) override { const int msecs = id.toInt(); const double secs = msecs/(double)1000; video_seeker_.Seek(secs); QImage result { video_seeker_.data(), video_seeker_.width(), video_seeker_.height(), QImage::Format_RGB32}; return result; } private: lius_tools::VideoSeeker video_seeker_; }; <file_sep>/video_loader.cpp #include <QCryptographicHash> #include <QDebug> #include <QProcess> #include <QSqlQuery> #include <QSqlError> #include <QStringList> #include <QVariant> #include "video_loader.h" VideoLoader::VideoLoader(const std::string& target_directory, const QSqlDatabase& db) : target_directory_(target_directory), db_(db) { db_.open(); InstallTableIfNotExists(); } std::string VideoLoader::DownloadVideo(const std::string& url) { QCryptographicHash hash_function(QCryptographicHash::Md4); hash_function.addData(url.c_str(), url.size()); const std::string hashed_url = hash_function.result().toHex().toStdString(); const std::string target_path = target_directory_ + "/" + hashed_url + ".mp4"; QProcess youtube_dl_process; QString program { "youtube-dl"}; QStringList arguments; arguments << "-o" << target_path.c_str() << "-f" << "mp4" << url.c_str(); youtube_dl_process.start(program, arguments); youtube_dl_process.waitForFinished(); qDebug() << "Processed finished"; qDebug() << youtube_dl_process.readAllStandardOutput(); if (youtube_dl_process.exitCode() != QProcess::NormalExit) { qDebug() << "Abnormal exit"; qDebug() << youtube_dl_process.readAllStandardError(); exit(-1); } return target_path; } void VideoLoader::InstallTableIfNotExists() { QSqlQuery query(db_); if(!query.exec("create table if not exists local_videos " "(url text primary key, local_file_path text)")) { qDebug() << "Could not create local_videos table"; qDebug() << query.lastError(); }; } std::string VideoLoader::GetLocalPath(const std::string& url) { QSqlQuery query(db_); query.prepare("select local_file_path from local_videos where url = :url"); query.bindValue(":url", url.c_str()); if(!query.exec()) { qDebug() << "Local path query failed " << query.lastError(); exit(-1); }; while (query.next()) { QString local_file_path = query.value(0).toString(); return local_file_path.toStdString(); } // If we didn't early return... std::string local_file_path = DownloadVideo(url); QSqlQuery insert_query(db_); insert_query.prepare( "insert into local_videos (url, local_file_path) " "values (:url, :local_file_path)"); insert_query.bindValue(":url", url.c_str()); insert_query.bindValue(":local_file_path", local_file_path.c_str()); if(!insert_query.exec()) { qDebug() << "Local path insert failed " << insert_query.lastError(); qDebug() << insert_query.lastError(); }; return local_file_path; }; <file_sep>/video_loader.h #ifndef VIDEO_LOADER_H #define VIDEO_LOADER_H #include <QSqlDatabase> #include <string> #include <vector> class VideoLoader { public: VideoLoader(const std::string& target_directory, const QSqlDatabase& db); std::string GetLocalPath(const std::string& url); private: void InstallTableIfNotExists(); std::string DownloadVideo(const std::string& url); QSqlDatabase db_; std::string target_directory_; }; #endif // VIDEO_LOADER_H <file_sep>/main.cpp #include <QDebug> #include <QGuiApplication> #include <QImage> #include <QQmlApplicationEngine> #include <QQmlContext> #include "video_loader.h" #include "video_seeker_image_provider.h" const char* SSBM_DB_FILENAME = "ssbm-labler.db"; void write_test_image(const std::string& video_path) { lius_tools::VideoSeeker seeker{video_path}; QImage result { seeker.data(), seeker.width(), seeker.height(), QImage::Format_RGB32}; result.save("result.png"); } int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); const std::string video_path = "C:/Users/marki/Videos/smash0.mp4"; { // Need to intialize the app db with the correct tables QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(SSBM_DB_FILENAME); VideoLoader video_loader { app.applicationDirPath().toStdString(), db }; std::string local_path = video_loader.GetLocalPath("https://www.youtube.com/watch?v=-OMZm1wyCVQ"); qDebug() << "Local path to video " << local_path.c_str(); } VideoSeekerImageProvider* video_seeker_image_provider = new VideoSeekerImageProvider { video_path }; const double max_msec = video_seeker_image_provider->maxMsec(); QQmlApplicationEngine engine; engine.addImageProvider("ssbm_video", video_seeker_image_provider); engine.rootContext()->setContextProperty("max_msec", max_msec); engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) { return -1; } return app.exec(); }
4488a5a09c873d765b31bcc3ded3a492e99abe49
[ "C++" ]
4
C++
markisus/ssbm-labeler
d2a99c7c95a10e668da36e615d81421b46649570
782b4f55505c3b53f8a4a84fb1be49b84ba081f2
refs/heads/main
<file_sep>import React from "react"; import firebase from "../fire"; import {BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' //De importerer behövs för att Routing ska fungera import manne from '../profileicons/manne.svg'; import sonny from '../profileicons/sonny.svg'; import rocky from '../profileicons/rocky.svg'; import removecalendar from '../profileicons/removecalendar.svg'; export default function Event({ event }) { const deleteEvent = () => { const eventRef = firebase.database().ref("Event").child(event.id); eventRef.remove(); }; console.log(event); return ( <div className="eventcard"> <h1>{event.title} - {event.date}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{event.time}</h1> <h3>{event.textarea}</h3> <h2>Värd</h2> <figure className="deltagare"> <Link to="/Profile"> <img width="41" height="41" src={manne} alt="Manne" /> </Link> </figure> <h2>Deltagare</h2> <figure className="deltagare"> <Link to="/Sonny"> <img width="41" height="41" src={sonny} alt="Sonny" /> </Link> &nbsp; &nbsp; <Link to="/Rocky"> <img width="41" height="41" src={rocky} alt="Rocky" /> </Link> </figure> <br/> <button className="deleteButton" onClick={deleteEvent}> <img src={removecalendar} width="48" height="34" alt="Add as a contact" /> </button> </div> ); } <file_sep>import React from "react"; import { Button, Card } from "react-bootstrap"; import { BrowserRouter as Router, Link, Switch, Route } from "react-router-dom"; //De importerer behövs för att Routing ska fungera import manne from "../profileicons/manne.svg"; import johnny from "../profileicons/johnny.svg"; import ronny from "../profileicons/ronny.svg"; export default function Profile({ handleLogout }) { return ( <> <br/> <Card.Title className="title">Profil</Card.Title> <div className="profilecard"> <Card> <Card.Body> <Card.Img className="img" variant="top" src={manne} alt="Manne profile icon" /> <Card.Text className="name"><NAME></Card.Text> <Card.Subtitle className="bio"> Tja! Manne här! Jag gillar att käka god mat och gamear gärna när jag får tid över. Sugen på en bärs eller ska vi ba käka lunch? Hör av dig! </Card.Subtitle> <Card.Text className="buddies">Hänger ofta med</Card.Text> <figure className="nameforbuddies"> <Link to="/Johnny"> <img src={johnny} alt="Johnny" /> </Link> <span className="buddyname"><NAME></span> </figure> <figure className="nameforbuddies"> <Link to="/Ronny"> <img src={ronny} alt="Ronny" /> </Link> <span className="buddyname"><NAME></span> </figure> </Card.Body> </Card> </div> <div> <Button onClick={handleLogout}>Logga ut</Button> </div> </> ); } <file_sep>import React from 'react' import { Card, Button, Modal } from "react-bootstrap"; import {BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' //De importerer behövs för att Routing ska fungera import ronny from '../profileicons/ronny.svg'; import johnny from '../profileicons/johnny.svg'; import rocky from '../profileicons/rocky.svg'; import kenny from '../profileicons/kenny.svg'; import addcontact from '../profileicons/addcontact.svg'; import pew from '../profileicons/pew.svg'; import Module from "../components/SendFriendRequest"; export default function Johnny() { return ( <> <br/> <Card.Title className="title">Profil</Card.Title> <div className="profilecard"> <Card> <Card.Body> <Card.Img className="img" variant="top" width="103" height="103" src={ronny} alt="Ronny profile icon" /> <Card.Text className="name"><NAME></Card.Text> <Card.Subtitle className="bio"> Hello! Jag gillar djur och natur. Tycker även om dator- och brädspel. Ses gärna för typ grill i skogen eller spelkväll :-) </Card.Subtitle> <div className="othercontacticons" > <Module /> </div> <Card.Text className="buddies">Kontakter</Card.Text> <figure className="nameforbuddies"> <Link to="/Rocky"> <img src={rocky} alt="Rocky" /> </Link> <span className="buddyname"><NAME></span> </figure> <figure className="nameforbuddies"> <Link to="/Kenny"> <img src={kenny} alt="Kenny" /> </Link> <span className="buddyname">Kenny</span> </figure> <figure className="nameforbuddies"> <Link to="/Johnny"> <img src={johnny} alt="Johnny" /> </Link> <span className="buddyname"><NAME></span> </figure> </Card.Body> </Card> </div> </> ); } <file_sep>import React from 'react'; import Popup from 'reactjs-popup'; import { Modal, Button } from "react-bootstrap"; import 'reactjs-popup/dist/index.css'; import addcontact from "../profileicons/addcontact.svg"; export default () => ( <Popup trigger={<button> <img src={addcontact} width="45" alt="Add as a contact" /> </button>} position="top"> <div> <Button>Add friend</Button> <hr></hr> <Button>Close</Button> </div> </Popup> );<file_sep>import { useState } from "react"; import fire from "../fire"; import Login from "./Login"; const LoginSystem = ({ hasAccount, showLoginForm }) => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [emailError, setEmailError] = useState(""); const [passwordError, setPasswordError] = useState(""); const clearInputs = () => { setEmail(""); setPassword(""); }; const clearErrors = () => { setEmailError(""); setPasswordError(""); }; const handleLogin = () => { clearErrors(); console.log(password, email); fire .auth() .signInWithEmailAndPassword(email, password).then((token)=>{ localStorage.setItem('user', "true"); showLoginForm(); }) .catch((err) => { switch (err.code) { case "auth/invalid-email": case "auth/user-disabled": case "auth/user-not-found": setEmailError(err.message); break; case "auth/wrong-password": setPasswordError(err.message); break; } }); }; const handleSignUp = () => { clearErrors(); fire .auth() .createUserWithEmailAndPassword(email, password).then((token)=>{ localStorage.setItem("user", "true"); showLoginForm(); }) .catch((err) => { switch (err.code) { case "auth/email-already-in-use": case "auth/invalid-email": setEmailError(err.message); break; case "auth/weak-password": setPasswordError(err.message); break; } }); }; return ( <div className="App"> <Login email={email} setEmail={setEmail} password={password} setPassword={setPassword} handleLogin={handleLogin} handleSignUp={handleSignUp} hasAccount={hasAccount} emailError={emailError} passwordError={passwordError} /> </div> ); }; export default LoginSystem; <file_sep>import React, { useState, useEffect } from "react"; import {BrowserRouter as Router, Link, Switch, Route, useHistory } from 'react-router-dom' //De importerer behövs för att Routing ska fungera import firebase from "../fire"; import Event from "./Event"; import Container from "react-bootstrap/Container"; import johnny from '../profileicons/johnny.svg'; import manne from '../profileicons/manne.svg'; import sonny from '../profileicons/sonny.svg'; import rocky from '../profileicons/rocky.svg'; import jeff from '../profileicons/jeff.svg'; import addtocalendar from '../profileicons/addtocalendar.svg'; import { Card} from "react-bootstrap"; export default function EventList() { const [eventList, setEventList] = useState([]); const history = useHistory(); useEffect(() => { const eventRef = firebase.database().ref("Event"); eventRef.on("value", (snapshot) => { const events = snapshot.val(); const eventList = []; for (let id in events) { eventList.push({ id, ...events[id] }); } console.log(eventList); setEventList(eventList); }); }, []); return ( <> <div className="webcontext"> <Container> <Card.Text className="title">Aktiviteter</Card.Text> <Link to="/addevent" id="addButton"> Skapa aktivitet + </Link> </Container> {eventList.length !== 0 ? ( eventList.map((event, index)=> <Event event={event} key={index} />) ) : ( //Om aktivitetskalender är tom, visa följande på sidan: <div className="emptyCalendar"> </div> )} <div className="eventcard"> <h1>Brädspelskväll - 24/4 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 16:00</h1> <h3>Schack och Backgammon hemma hos mig! Står för chips och några bärs ;)</h3> <h2>Värd</h2> <figure className="deltagare"> <Link to="/Johnny"> <img width="41" height="41" src={johnny} alt="Johnny" /> </Link> </figure> <h2>Deltagare</h2> <figure className="deltagare"> <Link to="/Sonny"> <img width="41" height="41" src={sonny} alt="Sonny" /> </Link> &nbsp; &nbsp; <Link to="/Rocky"> <img width="41" height="41" src={rocky} alt="Rocky" /> </Link> </figure> <br/> <br/> <button className="addtocalendar" onClick> <img src={addtocalendar} alt="Add event to your calender" /> </button> </div> <div className="eventcard"> <h1>Grillkväll - 10/5 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 18:00</h1> <h3>Ta med dig egen dryck och kött så bjuder jag på potatissallad! Vi sitter på min altan, tänder grillen och har det gött helt enkelt! Väl mött</h3> <h2>Värd</h2> <figure className="deltagare"> <Link to="/Rocky"> <img width="41" height="41" src={rocky} alt="Rocky" /> </Link> </figure> <h2>Deltagare</h2> <figure className="deltagare"> <Link to="/Profile"> <img width="41" height="41" src={manne} alt="Manne" /> </Link> &nbsp; &nbsp; <Link to="/Sonny"> <img width="41" height="41" src={sonny} alt="Sonny" /> </Link> </figure> <br/> <button className="addtocalendar" onClick={ () => { history.push("/calender/3"); } }> <img src={addtocalendar} alt="Add event to your calender" /> </button> </div> <div className="eventcard"> <h1>Kräftskriva - 6/8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 20:00</h1> <h3>Kidsen är hos svärföräldrarna så vi kör en kräftskiva! Jag bjuder på dryck och västerbottenostpaj, så ta med er så mycket kräftor ni orkar! Tjoho!</h3> <h2>Värd</h2> <figure className="deltagare"> <Link to="/Jeff"> <img width="41" height="41" src={jeff} alt="Jeff" /> </Link> </figure> <h2>Deltagare</h2> <figure className="deltagare"> <Link to="/Sonny"> <img width="41" height="41" src={sonny} alt="Sonny" /> </Link> &nbsp; &nbsp; <Link to="/Johnny"> <img width="41" height="41" src={johnny} alt="Johnny" /> </Link> &nbsp; &nbsp; <Link to="/Rocky"> <img width="41" height="41" src={rocky} alt="Rocky" /> </Link> </figure> <br/> <button className="addtocalendar" onClick> <img src={addtocalendar} alt="Add event to your calender" /> </button> </div> </div> </> ); } <file_sep>import React from "react"; import { useMobile } from "./useMobile"; import Navbar from "../navbar/navbar"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import EventList from "./EventList"; import EventForm from "./EventForm"; import Profile from "./Profile"; import Friends from "./Friends"; import Calendar from "./Calendar"; import Johnny from "../profiles/Johnny"; import Ronny from "../profiles/Ronny"; import Rocky from "../profiles/Rocky"; import Lenny from "../profiles/Lenny"; import Sonny from "../profiles/Sonny"; import Kenny from "../profiles/Kenny"; import Jeff from "../profiles/Jeff"; const Hero = ({ handleLogout }) => { const isMobile = useMobile(); return ( <Router> {!isMobile && <Navbar />} {isMobile && ( <div style={{ position: "fixed", bottom: "0px", width: "100%" }} > <Navbar />{" "} </div> )} {/*Här finns Routes till de olika komponenter*/} <Switch> <Route exact path="/"> <EventList/> </Route> <Route path="/activities"> <EventList /> </Route> <Route path="/calender/:user?"> <Calendar /> </Route> <Route path="/addevent"> <EventForm /> </Route> <Route path="/profile"> <Profile handleLogout={handleLogout}/> </Route> <Route path="/friends"> <Friends /> </Route> <Route path="/Johnny"> <Johnny /> </Route> <Route path="/Ronny"> <Ronny /> </Route> <Route path="/Rocky"> <Rocky /> </Route> <Route path="/Lenny"> <Lenny /> </Route> <Route path="/Sonny"> <Sonny /> </Route> <Route path="/Kenny"> <Kenny /> </Route> <Route path="/Jeff"> <Jeff /> </Route> </Switch> </Router> ); }; export default Hero; <file_sep>import React from 'react' import { Card, Button, Modal } from "react-bootstrap"; import {BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' //De importerer behövs för att Routing ska fungera import sonny from '../profileicons/sonny.svg'; import rocky from '../profileicons/rocky.svg'; import ronny from '../profileicons/ronny.svg'; import johnny from '../profileicons/johnny.svg'; import addcontact from '../profileicons/addcontact.svg'; import pew from '../profileicons/pew.svg'; import Module from "../components/SendFriendRequest"; export default function Johnny() { return ( <> <br/> <Card.Title className="title">Profil</Card.Title> <div className="profilecard"> <Card> <Card.Body> <Card.Img className="img" variant="top" width="103" height="103" src={rocky} alt="Rocky profile icon" /> <Card.Text className="name">Rocky 38</Card.Text> <Card.Subtitle className="bio"> Hej! Anders, 38 bor i Solna med sambo. Supernörd när det kommer till gamla noir-filmer. Hörs! </Card.Subtitle> <div className="othercontacticons" > <Module /> </div> <Card.Text className="buddies">Kontakter</Card.Text> <figure className="nameforbuddies"> <Link to="/Sonny"> <img src={sonny} alt="Sonny" /> </Link> <span className="buddyname"><NAME></span> </figure> <figure className="nameforbuddies"> <Link to="/Ronny"> <img src={ronny} alt="Ronny" /> </Link> <span className="buddyname"><NAME></span> </figure> <figure className="nameforbuddies"> <Link to="/Johnny"> <img src={johnny} alt="Johnny" /> </Link> <span className="buddyname"><NAME></span> </figure> </Card.Body> </Card> </div> </> ); } <file_sep>import React, { useState } from "react"; import fire from "../fire"; import firebase from "../fire"; export default function EventForm() { const [title, setTitle] = useState(""); const [date, setDate] = useState(""); const [time, setTime] = useState(""); const [textarea, setTextarea] = useState(""); const handleTitle = (e) => { setTitle(e.target.value); }; const handleDate = (e) => { setDate(e.target.value); }; const handleTime = (e) => { setTime(e.target.value); }; const handleTextarea = (e) => { setTextarea(e.target.value); }; const createEvent = () => { const eventRef = firebase.database().ref("Event"); const event = { title, date, time, textarea, }; setTitle(""); setDate(""); setTime(""); setTextarea(""); eventRef.push(event); }; return ( <div className="addForm"> <br /> &nbsp; &nbsp; &nbsp; Skriv in aktivitetens namn <br /> <input className="formtext" type="text" onChange={handleTitle} value={title} /> <br /> <br /> &nbsp; &nbsp; &nbsp; Välj datum <br /> <input className="formtext" type="date" onChange={handleDate} value={date} /> <br /> <br /> &nbsp; &nbsp; &nbsp; Välj tid <br /> <input className="formtext" type="time" onChange={handleTime} value={time} /> <br /> <br /> &nbsp; &nbsp; &nbsp; Beskriv aktiviteten <br /> <input className="formtextarea" type="textarea" maxLength="500" placeholder="max 500 tecken" onChange={handleTextarea} value={textarea} /> <br /> <br /> <button className="addInForm" onClick={createEvent}> &nbsp; &nbsp; &nbsp; Skapa &nbsp; &nbsp; &nbsp; </button> </div> ); } <file_sep>import React, { useState } from "react"; import { Button, Container } from "react-bootstrap"; import fire from "../fire"; import Hero from "./Hero"; import LoginSystem from "./LoginSystem"; export const OnBoarding = () => { const [hasAccount, setHasAccount] = useState(false); const [showLoginForm, setShowLoginForm] = useState(false); const [showOnBoarding, setOnBoarding] = useState(true); const [showHero, setShowHero] = useState(window.localStorage.getItem("user")); const handleLogin = () => { setOnBoarding(false); setHasAccount(true); setShowLoginForm(true); }; const handleLogout = () => { fire.auth().signOut(); window.localStorage.removeItem("user"); window.location.href="/"; //testtest }; const handleRegisterLogin = () => { setHasAccount(false); setShowLoginForm(true); setOnBoarding(false); }; const hideLoginForm = () => { setShowLoginForm(false); setOnBoarding(false); setShowHero(true); }; const isLogin = window.localStorage.getItem("user"); return ( <> {showOnBoarding && isLogin != "true" && ( <section className="login"> <Container className="loginContainer"> <Container className="btnContainer"> <div className="heyo">HEYO!</div> <Button onClick={handleLogin}>&nbsp;&nbsp;&nbsp;LOGGA IN&nbsp;&nbsp;&nbsp;</Button> <p> Har du inget konto? <br/> <span onClick={handleRegisterLogin}> Registrera dig här! </span> </p> </Container> </Container> </section> )} {showLoginForm && ( <LoginSystem hasAccount={hasAccount} showLoginForm={hideLoginForm} /> )} {showHero && <Hero handleLogout={handleLogout} />} </> ); }; <file_sep>import { useMediaQuery } from "./useMediaQuery"; export const useMobile = () => { return useMediaQuery("(max-width:600px)"); }; <file_sep>import React, { useState, useEffect } from "react"; import {BrowserRouter as Router, Link, Switch, Route, useParams } from 'react-router-dom' //De importerer behövs för att Routing ska fungera import firebase from "../fire"; import Event from "./Event"; import Container from "react-bootstrap/Container"; import activities from '../navbar/activities.svg'; import { Card} from "react-bootstrap"; export default function Calendar() { const [eventList, setEventList] = useState([]); const {user} = useParams(); useEffect(() => { const eventRef = firebase.database().ref("Event"); eventRef.on("value", (snapshot) => { const events = snapshot.val(); const eventList = []; if (user === "3"){ eventList.push({id: 1000, title:"Grillkväll", date: "10/5", time: "18:00", textarea: "Ta med dig egen dryck och kött så bjuder jag på potatissallad! Vi sitter på min altan, tänder grillen och har det gött helt enkelt! Väl mött"}); } for (let id in events) { eventList.push({ id, ...events[id] }); } console.log(eventList); setEventList(eventList); }); }, []); return ( <div className="webcontext"> <Container> <Card.Text className="title">Min kalender</Card.Text> <Link to="/addevent" id="addButton"> Skapa aktivitet + </Link> {eventList.length !== 0 ? ( eventList.map((event, index)=> <Event event={event} key={index} />) ) : ( //Om aktivitetskalender är tom, visa följande på sidan: <div className="emptyCalendar"> <Container> <h2> Du har inga kommande aktiviteter än. Kolla vad dina vänner pysslar med för att se om det finns något att haka på! </h2> <br /> <img src={activities} id="callogo" alt="Calendar SVG" /> <br /> <br /> <br /> <h2> Eller varför inte själv skapa en aktivitet att bjuda in dina polers till! </h2> </Container> </div> )} </Container> </div> ); } <file_sep>import React from 'react' import {BrowserRouter as Router, Link, Switch, Route } from 'react-router-dom' import calendar from './calendar.svg'; import face from './face.svg'; import activities from './activities.svg'; import profile from './profile.svg' import heyo from './heyo.svg' import {useMobile} from '../components/useMobile'; const styles = { margin: "-10px", background: "#FFF0E2", padding: "10px", width: "101%", borderRadius: "15px", display: "flex", justifyContent: "space-around", }; const Navbar = () => { const isMobile = useMobile(); return ( <section> <div style={styles}> <div><Link to="/friends"><img src={face} alt="friends" id="navbaricons" /></Link></div> <div><Link to="/activities"><img src={activities} alt="activities" id="navbaricons" /></Link></div> {!isMobile && <div><img src={heyo} style={{marginTop:"0px"}} alt="logo" id="navbaricons" /></div> } <div><Link to="/calender"><img src={calendar} alt="calender" id="navbaricons" /></Link></div> <div><Link to="/profile"><img src={profile} alt="profile" id="navbaricons" /> </Link></div> </div> </section> ) } export default Navbar
53a208c80d6a01ec2e66a64d544c50b0ece0b6e2
[ "JavaScript" ]
13
JavaScript
JavaJonte/HeYov3
6e64d3041ae554e97d7663e818032f9e6cd1326a
f5b4402509a1d12d8fa68b006fae351981149503
refs/heads/master
<repo_name>markuspalme/cropimage-xamarin<file_sep>/README.md cropimage ========= Easy to use library for image cropping on Android apps built with Xamarin. Android does not offer a built-in activity for image cropping (there is no guarantee that "com.android.camera.action.CROP" is present) so you have to build your own. This library is a simplified port of the project found at https://github.com/MMP-forTour/cropimage. ![](https://raw.github.com/markuspalme/cropimage-xamarin/master/Screenshot.png) <file_sep>/MainActivity.cs /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.App; using Android.Content; using Android.OS; using Android.Provider; using Android.Widget; namespace CropImage { [Activity(Label = "CropImage", MainLauncher = true)] public class MainActivity : Activity { private const int PICK_FROM_CAMERA = 1; private Android.Net.Uri mImageCaptureUri; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.button); button.Click += (s, e) => doTakePhotoAction(); } private Java.IO.File createDirectoryForPictures() { //var dir = new Java.IO.File(global::Android.OS.Environment.GetExternalStoragePublicDirectory(global::Android.OS.Environment.DirectoryPictures), "Boruto"); var dir = new Java.IO.File(GetExternalFilesDir(null), ".pics"); //private dir in app folder if (!dir.Exists()) { dir.Mkdirs(); } return dir; } private void doTakePhotoAction() { Intent intent = new Intent(MediaStore.ActionImageCapture); var file = new Java.IO.File(createDirectoryForPictures(), string.Format("myPhoto_{0}.jpg", System.Guid.NewGuid())); mImageCaptureUri = Android.Support.V4.Content.FileProvider.GetUriForFile(this, PackageName + ".fileprovider", file); intent.PutExtra(MediaStore.ExtraOutput, mImageCaptureUri); try { intent.PutExtra("return-data", false); StartActivityForResult(intent, PICK_FROM_CAMERA); } catch (ActivityNotFoundException e) { e.PrintStackTrace(); } } protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (resultCode != Result.Ok) { return; } switch (requestCode) { case PICK_FROM_CAMERA: Intent intent = new Intent(this, typeof(CropImage)); intent.PutExtra("image-path", mImageCaptureUri.ToString()); intent.PutExtra("scale", true); StartActivity(intent); break; } } } }
f82f9f421960312f239725326e7a0afec5872e29
[ "Markdown", "C#" ]
2
Markdown
markuspalme/cropimage-xamarin
389106a24a5b9a5148cba14e3a5d2888f08b69ef
76c3ccea1d1fe3541446eee42c40e48897011566
refs/heads/master
<repo_name>aliToha/QRScaner<file_sep>/app/src/main/java/com/gagalcoding/qrscaner/ApiInterface.java package com.gagalcoding.qrscaner; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; /** * Created by Ali on 3/11/2018. */ public interface ApiInterface { @FormUrlEncoded @POST("addBarcode.php") Call<Value> addBarcode (@Field("nilai_barcode") String nilai_barcode); }
602f7ca014d649838a7ae25620c1ebaed57368f1
[ "Java" ]
1
Java
aliToha/QRScaner
1febe43eae509a1002898757f8ea7d542cccda45
09b1150e57c9c4d1959ed2dd0d8b1a037b5955f5
refs/heads/master
<repo_name>redhog/numjs<file_sep>/test.py import bitstring, random, numpy def float2bits(x): F = numpy.float32 x = F(x) sign = F(0.0) exp = F(0.0) frac = [F(0.0), F(0.0), F(0.0)] if x < F(0.0): sign = F(1.0) x = -x if numpy.isnan(x): exp = F(255.0) frac = [F(64.0), F(0.0), F(0.0)] elif numpy.isinf(x): exp = F(255.0) frac = [F(0.0), F(0.0), F(0.0)] elif x == F(0.0): exp = F(0.0) frac = [F(0.0), F(0.0), F(0.0)] else: exp = numpy.floor(numpy.log2(x)) + 127 while x < F(2**23): x = x * F(2) x = x - F(2**23) # print "NNNNN1", bitstring.pack("uint:23", x).bin frac[0] = numpy.floor(x / F(2**16)) x = x - frac[0] * F(2**16) frac[1] = numpy.floor(x / F(2**8)) x = x - frac[1] * F(2**8) frac[2] = x return [sign * 128.0 + numpy.floor(exp / 2.0), (exp % 2.0) * 128.0 + frac[0], frac[1], frac[2] ] def bits2float(bits): F = numpy.float32 sign = numpy.floor(bits[0] / 128.0) if sign == 1.0: sign = -1.0 else: sign = 1.0 exp = (bits[0] % 128.0) * 2.0 + numpy.floor(bits[1] / 128.0) frac = (bits[1] % 128.0) * F(2**16) + bits[2] * F(2**8) + bits[3] if exp == 255.0 and frac > 0.0: return numpy.NaN elif exp == 255.0 and frac == 0.0: return sign * numpy.Inf elif exp == 0.0 and frac == 0.0: return 0.0 else: exp = exp - 127.0 - 23.0 frac = frac + F(2**23) return frac * 2**exp def float2bitstring(x): return bitstring.pack("uint:8,uint:8,uint:8,uint:8", *float2bits(x)) def disp(x): x = x.bin return "%s, %s, %s" % (x[0:1], x[1:9], x[9:]) #unpack("uint:1, uint:8, uint:23") def printdiff(x): print "%s: %s != %s" % (x, disp(bitstring.pack("float:32", x)), disp(float2bitstring(x))) print " %s != %s" % (bitstring.pack("float:32", x).unpack("float:32"), float2bitstring(x).unpack("float:32")) if __name__ == "__main__": if False: x = 1.64740653118 printdiff(x) elif False: for a in xrange(0, 100): x = random.random() * 2**(23*random.random()) x = bitstring.pack("float:32", x).unpack("float:32")[0] # Cast to float32 if bitstring.pack("float:32", x) != float2bitstring(x): printdiff(x) for x in ['NaN', "Inf", "-Inf"]: x = float(x) if bitstring.pack("float:32", x) != float2bitstring(x): printdiff(x) else: for a in xrange(0, 100): x = random.random() * 2**(23*random.random()) x = bitstring.pack("float:32", x).unpack("float:32")[0] # Cast to float32 res = bits2float(float2bits(x)) if res != x: print "%s != %s" % (res, x) for x in ['NaN', "Inf", "-Inf"]: x = float(x) res = bits2float(float2bits(x)) if res != x and not (numpy.isnan(x) and numpy.isnan(res)): print "%s != %s" % (res, x)
f5c86c64a6f11423a24cd0f1436454c1f171e3fd
[ "Python" ]
1
Python
redhog/numjs
90de3502bd3ba2531b1355431dbba277e8d132cb
ec78fbc715b729ba57165279b351ed1f99ca80e1
refs/heads/master
<file_sep>/// <reference path="../global_js/phantomjs.d.ts" /> /// <reference path="../global_js/require.d.ts" /> module printer { var phantom; export class Server { public static start() { var system = require('system') var address, output, size, ms var page = require('webpage').create() //phantom.addCookie({ // 'CurrentDeviceTypeCookie':'DeviceTypeModel={"DeviceType":"Responsive","DeviceModel":"All","OperatingSystem":"All","OperatingSystemVersion":null,"BrowserName":null,"SupportsFlash":false}' //}) //page.addCookie({ // login:false //}) //console.log('The default user agent is ' + page.settings.userAgent); //CurrentDeviceTypeCookie=DeviceTypeModel={"DeviceType":"Responsive","DeviceModel":"All","OperatingSystem":"All","OperatingSystemVersion":null,"BrowserName":null,"SupportsFlash":false}; page.settings.userAgent = 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25'; page.customHeaders = {'Referer': 'localhost'}; if (system.args.length < 3 || system.args.length > 5) { console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); phantom.exit(1); } address = system.args[1]; output = system.args[2]; if (output && output.substr(-4) === ".pdf") { page.paperSize = { orientation: 'portrait', margin: '2cm', //format: 'pdf', size: "A4" } } else { page.viewportSize = { width: 1024, height: 2048, margin: "50" } } ms = system.args[4] || 30000; console.log("ms=" + ms) console.log(" > Fetching " + address + ' >>> ' + output) page.open(address, function (status) { if (status !== 'success') { console.log('Unable to load the address!'); phantom.exit(1); } else { window.setTimeout(()=> { console.log(' > Rendering'); page.render(output); console.log(' > Done'); phantom.exit(0); }, ms); } }); } } } printer.Server.start(); //var page = require('webpage').create(), // system = require('system'), // address, output, size; //if (system.args.length < 3 || system.args.length > 5) { // console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]'); // console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"'); // phantom.exit(1); //} else { // address = system.args[1]; // output = system.args[2]; // page.viewportSize = { width: 600, height: 600 }; // if (system.args.length > 3 && system.args[2].substr(-4) === ".pdf") { // size = system.args[3].split('*'); // page.paperSize = size.length === 2 ? { width: size[0], height: size[1], margin: '0px' } // : { format: system.args[3], orientation: 'portrait', margin: '1cm' }; // } // if (system.args.length > 4) { // page.zoomFactor = system.args[4]; // } // page.open(address, function (status) { // if (status !== 'success') { // console.log('Unable to load the address!'); // phantom.exit(); // } else { // window.setTimeout(function () { // page.render(output); // phantom.exit(); // }, 10000); // } // }); //} <file_sep># <NAME> ##### Bristol UK - phone: 077958 16065 - email: <EMAIL> > Tenacious and hard working with a strong and varied technical background, commercial awareness, good communication and interpersonal skills. Comprehensive knowledge and experience developing websites and HTTP API's using Microsoft .Net C#, JavaScript and Databases. Demonstrated ability to develop and support business systems by working directly with colleagues to turn requirements into robust solutions. Proactive. Strong commitment to quality and recognised for having a pragmatic approach to problem solving. ## Work History ### Senior Developer (contract) - Iress > **February 2015 - Current** - Developing and supporting features for Nationwide mortgage system using web and .net technologies. ### Senior e-Commerce Developer (contract extended 7x) - Clarks International, UK/European Website and Microsoft Dev Team > **December 2011 - December 2014** - www.clarks.co.uk - Coded full stack e-commerce website features, fixes, infrastructure API's and services using the following technologies: MVC, WebApi, ASP.Net, WCF, C#, Ninject Dependency injection, Moq, MS SQL Server, CSS3, HTML5, Less, Typescript, JavaScript, Ajax, JQuery, Entity Framework, Stored Procs, SQL, JSON, EpiServer CMS, NUnit, NCrunch, ReSharper on TFS source control system. Wrote TDD unit and integration tests where appropriate. Required to target desktop, tablet and mobile devices using responsive techniques and internationalised content, hosted on a server farm for applications to maintain throughput capacity up to 1.6 million page views per hour. - Designed, coded and delivered new client side dynamic front end global header and menu implementation using C# MVC and TypeScript/JavaScript. Designed and coded fully tested Payment Notification service to spec for processing WorldPay XML API messages using C# WebApi, SQL Server. This service is now part of the live e-commerce checkout pipeline. - Designed and coded appointment booking system interfacing with third party Timetrade XML service via custom C# client consumed by website. Produced a fully tested JSON/XML API for third parties own e-commerce stores available for UK and French sites. Helped and influenced with design and set-up of continuous build and delivery system using TFS source control, MSbuild / Jenkins. - Implemented (SEO) Search Engine Optimisations to improve Google search engine rankings using schema.org definitions. - Designed image processing solution using Azure. - Designed and coded shoe size calculator javascript front end and JSON api for the French and UK sites. - Added features, optimised and repaired to MS Access/Excel based Shoe Modelling and Rangetracker Software. - Conceived, promoted, designed and coded usability enhancements that increased checkout conversion by 3.6% verified by Coremetrics, and Maximiser user data. - Trouble shot and fixed issues using fiddler proxy, chrome developer tools, profiling and C# debugging techniques. > November 2014 - Created and coded a new open source Nuget Project "Synology.NET" ### Software Engineer (contract) - Star Internet, Microsoft Dev Team > **March 2011 - December 2011** - www.star.co.uk - Wrote Ticketing service using WCF, C#. - Developed front-end SharePoint ASP.Net web parts for customer portal using C#, JQuery, JavaScript, XML, XSLT, CSS, HTML. - Re-wrote product management service for worklife products, interfacing with Oracle and Parallels (digital assets manager) XML-rpc platform. This resulted in a complex and error prone manual five day process reducing to a couple of service calls taking less than a minute. Fully Unit/Integration tested via a Jenkins continuous delivery pipeline which I installed and configured to provide build artifacts and status. - Incorporated real-time usage charts sourcing data from Oracle, router APIs and SQL Server. - Wrote automated single sign-on within ASP.Net web site facility. - Employed and encouraged Agile Scrum methods and TDD where possible. ### Senior Engineer (perm) - NOKIA, Music Services Platform Agile Team > **December 2008 - March 2011** - music.ovi.com - Coded tasks for stories within agile team within large, continuously integrated C# Rest service architecture using TDD based Object Oriented Programming techniques. - Developed Unit tested MVC controllers and views for mobile and PC devices. - Involved in re-writing Commerce and Membership services from .Net to Java. - Contributed to the improvement of deployment pipeline influencing productivity improvements for the customised infrastructure deployment tool. - Championed the standardisation of Java project structure using archetypes. - Delivered presentations to the team as part of learning and knowledge sharing sessions. - Devised tool to provide real-time information on REST service availability used on display panels throughout the building. - Technologies used: C#, .Net, ASP.Net MVC, WCF Services within a Java/Microsoft SOA Environment, REST, JQuery/JavaScript, HTML, CSS, nHibernate, MySQL, Unit testing, Dependency Injection, Mocking, Visual Studio, Fiddler, Wireshark, TCP SVN, Hudson Continuous Integration Server, Java / Eclipse, Build Automation, JSON, XML ### Systems Developer (contract) - AIRBUS / CIMPA, Research and Development Team > **November 2007 - October 2008** - Designed and developed database, processing server and web service for occasionally connected devices to send/receive blood tracking information within an RFID (Radio Frequency Identification) based tracking system. The architecture supported a dynamic web site, Windows forms and mobile devices, using secure, transactional, text-based message formats for maximum client compatibility. - Secured first contract with customer using the above system architecture Presented improvement ideas to the business and executed successful implementation of a ticketing system for managing team workflow information - Technologies Used: C#, .Net, Web Services, ASP.Net, Windows Forms, SQL Server, Web Services, OOP, JQuery, JavaScript/Ajax, CSS, HTML, Vault Source Control, Build Automation ### Technical Analyst - MMTeleperfomance, Development Team > **November 2005 - November 2007** - Provided Visual Basic software development and support for Sony’s European PlayStation Customer Data System containing nine million customer records and related data. - Ensured that four servers, 80Gb of Data, 51 scheduled jobs all processing up to 7000 customers daily using 1m+ queries weekly, deliver print, data cleaning and reporting services as expected. - Smoothly transferred system to upgraded servers with minimum downtime, created Intranet graphical reporting tool and web services providing statistics on PlayStation 3 data flows for monitoring purposes. - Ensured reliable delivery of critical fulfilment data for the entire range of PlayStation products up to 200,000 customers a month. > December 2004 - October 2005 - Round the world trip ### Analyst Developer (temp to permanent) - NHS Northwest London, Customer Information Services Team > **June 2002 - December 2004** - Provided ‘end to end’ electronic information collection and reporting solutions to meet the individual needs of PCT staff and local hospitals, from administration to director level. - Worked towards implementing a central data centre based on the government’s National Program for IT specifications. - Managed extra resource required to assist in the development of any solutions liaising with other departments as necessary. - Built data importers capable of processing large volumes of monthly health data. - Designed and implemented Intranet Stop Smoking web application for Call Centre. - Automated parts of the CIS system significantly improving support service efficiency. - Technologies used: ASP, ASP.Net, SQL Server, VB6, JavaScript, CSS, HTML ### Software Products Developer (contract) - Verdandi, London > **January 2001 - May 2002** - Developed Project Management related software products. - Improved or wrote databases / spread sheets for the Project Managers to assist their work. - Integrated the web based reporting interface using Crystal Reports. - Technologies used: Access, SQL Server and ASP, VB6, Crystal Reports, Excel VBA ### Technical Analyst (contract), IMS Health, i-squared Internet Portal Team > **June 1999 – January 2001** - Within the flagship I-squared Internet Portal Team, developed and maintained intranet requirements management system Launchpad using ASP and Access for handling the ideas and feedback. - Worked closely with Program Manager assisting with administration a distribution of work for the development teams. - Developed optical scanning and search system for the research department that digitised paper assets, reducing manual search times significantly (OCR Scanning, Word, Access VBA)Built manpower planning tool for the research department (MS Access). > 1997 - 1999 (London UK) - Various Temporary Administrative Positions > <br>1992 - 1997 Reese Plastics (Wellington NZ) Team Leader / Assembly Technician ##Education and Subscriptions - Certified Scrum Master – Agile Alliance 2010. - Completed 78 video course by pluralsite on Developing AngularJs Line of Business Applications 2014 - Subscribe to .Net magazine covering Web and internet technologies. - Follow blogs by <NAME>, <NAME> and sites like Code project. - Devote much time outside of work investigating an trying out new technologies on top of personal proejcts, such as the Agile scrumboard application I use for workflow management. - Paid-for Tekpub.com subscriber since 2009 - to keep up to date on cutting edge technologies. - NHS Training Centre, London 2004 Project Management. - Learning Tree International IT Training, Euston, London 2002-2003 Professional Building Ecommerce Web Sites, Enterprise Web Development using ASP, Internet & Intranet Security, Crystal Reports for the Enterprise - City & Guilds, London 1998 PC Maintenance & Repair, Building NT Networks. - Rongotai Boys College, Wellington 1989 Five Subjects passed for University Entrance Exams. - Rongotai Boys College, Wellington 1988 Six Passes Math, Science, Physics, Statistics, Art, Music. - Rongotai Boys College, Wellington 1987 Six Passes, A's in Math, Physics Science Sixth Form Cert. Passes. - Rongotai Boys College, Wellington 1986 Certificate of Distinction in Australian Mathematics Competition. ## Interests and Hobbies Interests include playing piano, guitar and mandolin. I play football badly, enjoy watching rugby/cricket and socialising. Also, I have interests in Hi-fi, various electronic DIY projects such as my self-assembled chain driven electric bike (which has done close to 3500 miles and still going strong). To help out and improve my local community I do occasional charity work eg data migration work for Woodlands group of Churches where 5000 users were exported, transformed from a spreadsheet into MySQL Db behind the open source Drupal / CiviCRM. Having a natural enthusiasm for computer technology and the internet, leads me to explore, study and try out new developments by making software for personal use at home. This has also proved useful for work. <file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; /// <reference path="../../global_js/domo.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/routie.d.ts" /> var App; (function (App) { var Linkr = (function () { function Linkr() { this.hasSetEvents = false; this.registerEvents(); this.registerRoutes(); //this.parseAllTemplatesToWindow("templates.htm"); } Linkr.prototype.registerRoutes = function () { window.routie({ '/link/:id': function (id) { return new App.ViewLinkDetail({ id: id }); }, '/link/new': function (id) { return new App.ViewLinkNew({}); }, '/links': function () { return new App.ViewLinks(); }, // '/': () => new App.ViewLinks(), '': function () { return new App.ViewLinks(); } }); }; Linkr.prototype.registerEvents = function () { if (this.hasSetEvents === false) { this.hasSetEvents = true; } }; return Linkr; })(); App.Linkr = Linkr; var ViewBase = (function () { function ViewBase(template) { this.template = template; } ViewBase.prototype.events = function (data) { }; ViewBase.prototype.render = function (data, parts) { App.ViewEngine.renderview(this.template, data, parts); }; ViewBase.prototype.getHtml = function (data) { }; ViewBase.prototype.getTemplate = function (data) { }; return ViewBase; })(); App.ViewBase = ViewBase; var ViewLinks = (function (_super) { __extends(ViewLinks, _super); function ViewLinks() { var _this = this; var frame = { top_content: TemplateProvider.logo() + TemplateProvider.addButton() + TemplateProvider.filters(), middle_content: TemplateProvider.links, bottom_content: "<hr><hr>" }; var all = App.ViewEngine.getHtml(TemplateProvider.linksPageFrame(), frame); _super.call(this, all); //var data = { // header : "popular", // footer : "the footer", // links: [{textof:"link1"},{textof:"link2"},{textof:"link3"}] //} var client = new LinkrServerClient(); var parts = { link: TemplateProvider.link }; var act = client.CallMethod("GetLinks", {}); $.when(act).then(function (resp) { var future = moment.utc().add('days', 3); $.each(resp.links, function (idx, item) { item.fuzzyCreated = "made " + moment.utc(item.date_created).fromNow(); item.fuzzyAccessed = "used " + moment.utc(item.date_accessed).fromNow(); item.daysOld = future.diff(moment.utc(item.date_created), 'days'); item.score = item.hits / item.daysOld; }); _this.render(resp, parts); $(".data-items").isotope({ itemSelector: '.link', getSortData: { hits: function ($elem) { return parseInt($elem.find(".hits").text(), 10); }, date_accessed: function ($elem) { return $elem.find(".date_accessed").text(); }, date_created: function ($elem) { return $elem.find(".date_created").text(); }, score: function ($elem) { return parseInt($elem.find(".score").text(), 10); } }, sortBy: "score", sortAscending: false }); $(".logo").on("click", function (e) { location.href = "/linkr"; }); $(".title a").on("click", function (e) { var target = $(e.currentTarget); var href = target.attr("href"); var id = target.attr("data-id"); var client = new LinkrServerClient(); client.CallMethod("Increment", { id: id }); }); $(".filter").on("click", function (e) { e.preventDefault(); var selected = $(e.currentTarget).text(); var sortFunction = FilterOptions[selected]; $('.data-items').isotope(sortFunction); $("#selectedfilter").text("by " + $(e.currentTarget).text()); }); }); } return ViewLinks; })(ViewBase); App.ViewLinks = ViewLinks; var ViewLinkDetail = (function (_super) { __extends(ViewLinkDetail, _super); function ViewLinkDetail(data) { var _this = this; _super.call(this, TemplateProvider.linkDetail()); var client = new LinkrServerClient(); var parts = { link: TemplateProvider.link }; var act = client.CallMethod("GetLink", { id: data.id }); $.when(act).then(function (resp) { _this.render(resp); $("#btnSubmit").on("click", function (e) { return _this.submit(e); }); }); } ViewLinkDetail.prototype.submit = function (e) { e.preventDefault(); var client = new LinkrServerClient(); var form = App.GlobalCommon.getFormInputs($("#form1")); var act = client.CallMethod("UpdateLinkDetail", form); // $.when(act).then(resp => }; return ViewLinkDetail; })(ViewBase); App.ViewLinkDetail = ViewLinkDetail; var ViewLinkNew = (function (_super) { __extends(ViewLinkNew, _super); function ViewLinkNew(data) { var _this = this; _super.call(this, TemplateProvider.linkNew()); $("#btnSubmit").on("click", function (e) { return _this.submit(e); }); } ViewLinkNew.prototype.submit = function (e) { e.preventDefault(); var client = new LinkrServerClient(); var form = App.GlobalCommon.getFormInputs($("#form1")); var act = client.CallMethod("AddLink", form); }; return ViewLinkNew; })(ViewBase); App.ViewLinkNew = ViewLinkNew; var FilterOptions = (function () { function FilterOptions() { } FilterOptions.oldest = function () { return { sortBy: "date_created", sortAscending: true }; }; FilterOptions.newest = function () { return { sortBy: "date_created", sortAscending: false }; }; FilterOptions.popular = function () { return { sortBy: "score", sortAscending: false }; }; FilterOptions.stale = function () { return { sortBy: "last_accessed", sortAscending: true }; }; FilterOptions.recent = function () { return { sortBy: "last_accessed", sortAscending: false }; }; FilterOptions.hits = function () { return { sortBy: "hits", sortAscending: false }; }; return FilterOptions; })(); App.FilterOptions = FilterOptions; var ViewHome = (function (_super) { __extends(ViewHome, _super); function ViewHome() { _super.call(this, window.templates.homeFrame); } return ViewHome; })(ViewBase); App.ViewHome = ViewHome; var LinkrServerClient = (function (_super) { __extends(LinkrServerClient, _super); function LinkrServerClient() { _super.call(this, "linkr_server.ashx"); } return LinkrServerClient; })(App.ServerClientBase); App.LinkrServerClient = LinkrServerClient; var TemplateProvider = (function () { function TemplateProvider() { } TemplateProvider.test = function () { var tmp; if (!tmp) { } return tmp; }; TemplateProvider.linksPageFrame = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"frame\">"; tmp += " <div class=\"top_content\">{{&top_content}}<\/div>"; tmp += " <div class=\"middle_content\">{{&middle_content}}<\/div>"; tmp += " <div class=\"bottom_content\">{{&bottom_content}}<\/div>"; tmp += " <\/div>"; } return tmp; }; TemplateProvider.linkDetail = function () { var tmp; if (!tmp) { tmp = ""; var id = App.GlobalCommon.inputstring("link_id", "link_id", "{{link.id}}", "", "hidden"); var href = App.GlobalCommon.inputstring("href", "href", "{{link.href}}", "The Url", "text"); var textof = App.GlobalCommon.inputstring("textof", "textof", "{{link.textof}}", "The Link Title", "text"); var descof = App.GlobalCommon.textarea("descof", "descof", "{{link.descof}}", "The Description", "10"); tmp += App.GlobalCommon.form("Edit Link", id + href + textof + descof, "btnSubmit", "form1"); } return tmp; }; TemplateProvider.linkNew = function () { var tmp; if (!tmp) { tmp = ""; var id = App.GlobalCommon.inputstring("link_id", "link_id", "0", "", "hidden"); var textof = App.GlobalCommon.inputstring("textof", "textof", "{{link.textof}}", "The Link Title", "text"); var href = App.GlobalCommon.inputstring("href", "href", "{{link.href}}", "The Url", "text"); var descof = App.GlobalCommon.textarea("descof", "descof", "{{link.descof}}", "The Description", "10"); tmp += App.GlobalCommon.form("Add Link", id + href + textof + descof, "btnSubmit", "form1"); } return tmp; }; TemplateProvider.logo = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"logo\">"; tmp += " <div class=\"textof\">Linkly<\/div>"; tmp += " <div class=\"catch\">witty catch<\/div>"; tmp += " <\/div>"; } return tmp; }; TemplateProvider.displayData = function (field) { return DIV({ id: field, "class": field }, "{{" + field + "}}"); }; TemplateProvider.link = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"link\">"; //tmp += " <div class=\"edit icon-pen\"><a data-id=\"{{id}}\" href=\"#/link{{edit}}/{{id}}\">edit<\/a><\/div>" tmp += " <div class=\"title\"> <span class=\"icon-export-outline\"><\/span> <a data-id=\"{{id}}\" href=\"{{href}}\" target=\"blank\">{{textof}}<\/a>"; tmp += " <a data-id=\"{{id}}\" href=\"#/link{{edit}}/{{id}}\"><div class=\"edit icon-pen\"\/><\/a>"; tmp += " <\/div>"; tmp += " <div class=\"hits\">{{hits}}<\/div>"; tmp += " <div class=\"score\">{{score}}<\/div>"; tmp += " <div class=\"fuzzyAccessed\">{{fuzzyAccessed}}<\/div>"; tmp += " <div class=\"fuzzyCreated\">{{fuzzyCreated}}<\/div>"; tmp += " <div class=\"date date_accessed\">{{date_accessed}}<\/div>"; tmp += " <div class=\"date date_created\">{{date_created}}<\/div>"; tmp += " <div class=\"movement\">^<\/div>"; tmp += " <\/div>"; //var a = A({"data-id":"{{id}}", href:"{{href}}", target:"blank", },"{{textof}}") //var title = DIV({"class":"title"},a.outerHTML) //var hits = this.displayData("hits") //var score = this.displayData("score") //var fuzzyAccessed = this.displayData("fuzzyAccessed") //var fuzzyCreated = this.displayData("fuzzyCreated") //var movement = this.displayData("movement") } return tmp; }; TemplateProvider.filters = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"filters\">"; tmp += " <div class=\"title\"><span id=\"selectedfilter\"><br><\/><\/div>"; tmp += " <div class=\"filter\">popular<\/div>"; tmp += " <div class=\"filter\">newest<\/div>"; tmp += " <div class=\"filter\">recent<\/div>"; tmp += " <div class=\"filter\">hits<\/div>"; tmp += " <div class=\"filter\">oldest<\/div>"; tmp += " <div class=\"filter\">hidden<\/div>"; tmp += " <\/div>"; } return tmp; }; TemplateProvider.addButton = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"addbutton\">"; tmp += " <a href=\"#\/link\/new\">NEW<\/div>"; tmp += " <\/div>"; } return tmp; }; TemplateProvider.links = function () { var tmp; if (!tmp) { tmp = ""; tmp += " <div id=\"links\">"; tmp += " <div class=\"data-items\">"; tmp += " {{#links}}"; tmp += " {{>link}}"; tmp += " {{\/links}}"; tmp += " <\/div>"; tmp += " <div class=\"footer\">{{footer}}<\/div> "; tmp += " <\/div>"; } return tmp; }; return TemplateProvider; })(); App.TemplateProvider = TemplateProvider; })(App || (App = {})); <file_sep>using System; using System.Web; using System.Web.UI; using Tekphoria.Web.Server.Account; using Tekphoria.Web.Server.Linkr; namespace Tekphoria.Web.linkr { public class LinkrPage : Page { public AccountServer accountServer = new AccountServer(); public LinkrServer svr = new LinkrServer(); //private readonly IDbConnection _scrumboDbConnection; //private IDbConnection GetOpenConnection(string connectionString) //{ // IDbConnection dbConnection = new MySqlConnection(connectionString); // dbConnection.Open(); // return dbConnection; //} //private void CloseConnection(IDbConnection con) //{ // if (con != null) { // con.Close(); // con.Dispose(); // } //} //public void CloseConnections() //{ // CloseConnection(_scrumboDbConnection); //} //public IDbConnection GetScrumboConnection() //{ // if (_scrumboDbConnection == null || _scrumboDbConnection.State != ConnectionState.Open) // CloseConnection(_scrumboDbConnection); // return GetOpenConnection(Config.GetScrumboConnectionString.Value); //} public string GetNonEmptyCookie(string name) { HttpCookie ck = HttpContext.Current.Request.Cookies[name]; if (ck == null || string.IsNullOrWhiteSpace(ck.Value)) { accountServer.LogOut(); Response.Redirect("/login?LastUrl=" + Uri.EscapeDataString(Context.Request.RawUrl)); } return ck.Value; } } } <file_sep>using System; using System.Data; using FluentValidation; using Newtonsoft.Json.Linq; namespace Tekphoria.Web.Server.Scrumbo { public class Processor { public Processor(ActionEnum actionEnum, Func<IDbConnection, dynamic, object> logic, IValidator<JObject> jValidator) { ActionEnum = actionEnum; Run = logic; JValidator = jValidator; } public ActionEnum ActionEnum { get; set; } public Func<IDbConnection, dynamic, object> Run { get; set; } public IValidator<JObject> JValidator { get; set; } } }<file_sep>using System.Data; using System.Linq; using System.Web; using FluentValidation; using Newtonsoft.Json.Linq; using Tekphoria.Server.Common; namespace Tekphoria.Server.Scrumbo { public class Validators { #region Nested type: BoardConfigValidator public class BoardConfigValidator : AbstractValidator<JObject> { public BoardConfigValidator() { RuleFor(x => x.GetValue("nameof").ToString()) .Length(3, 100) .WithMessage("Board name should be at least 2 characters long and no more than 100.") .WithName("nameof"); RuleFor(x => x.GetValue("extra_status_1").ToString()) .Length(0, 15) .WithMessage("Status Columns should be between 3 and 20 Characters in length.") .WithName("extra_status_1"); RuleFor(x => x.GetValue("extra_status_2").ToString()) .Length(0, 15) .WithMessage("Status Columns should be between 3 and 20 Characters in length.") .WithName("extra_status_2"); RuleFor(x => x.GetValue("more_info").ToString()) .Length(0, 500) .WithMessage("The extra information field is too long. Try entering less text.") .WithName("more_info"); } } #endregion #region Nested type: BoardValidator public class BoardValidator : AbstractValidator<JObject> { public BoardValidator() { RuleFor(x => x.GetValue("nameof").ToString()) .Length(3, 100) .WithMessage("Board name should be at least 2 characters long and no more than 100.") .WithName("nameof"); } } #endregion #region Nested type: EmptyValidator public class EmptyValidator : AbstractValidator<JObject> { } #endregion #region Nested type: SignInValidator public class SignInValidator : AbstractValidator<JObject> { public SignInValidator() { RuleFor(x => x.GetValue("email").ToString()) .EmailAddress() .WithMessage("Email is not valid.") .Must(HaveEmailInDB) .WithMessage("Email not recognised.") .WithName("email"); When(data => HaveEmailInDB((string) data.GetValue("email")), () => RuleFor(data => data) .Must(HaveValidPassword) .WithName("password") .WithMessage("Password is not valid.")); } protected bool HaveValidPassword(JObject data) { var con = HttpContext.Current.Items["con"] as IDbConnection; string email = data.GetValue("email").ToString(); string password = data.GetValue("password").ToString(); dynamic res = con.Query<dynamic>("select email,password from users where email=@email;", new {email}).FirstOrDefault(); dynamic dbpass = res.password.ToString(); return dbpass == password; } protected bool HaveEmailInDB(string email) { var con = HttpContext.Current.Items["con"] as IDbConnection; dynamic res = con.Query<dynamic>("select count(id) as user_count from users where email=@email;", new {email}) .Single(); return res.user_count > 0; } } #endregion #region Nested type: StoryValidator public class StoryValidator : AbstractValidator<JObject> { public StoryValidator() { RuleFor(x => x.GetValue("textof").ToString()) .Length(5, 300) .WithMessage("Story text should be at least 10 characters long.") .WithName("textof"); } } #endregion #region Nested type: TaskValidator public class TaskValidator : AbstractValidator<JObject> { public TaskValidator() { RuleFor(x => x.GetValue("textof").ToString()) .Length(2, 500) .WithMessage("Task text name should be at least 3 characters long and no more than 500.") .WithName("textof"); } } #endregion #region Nested type: UserAddSharedBoardValidator public class UserAddSharedBoardValidator : AbstractValidator<JObject> { public UserAddSharedBoardValidator() { RuleFor(x => x.GetValue("hash").ToString()) .Length(5, 50) .WithMessage("The hash should be 5 or more characters.") .Must(HaveExistingBoard) .WithName("hash") .WithMessage("The board has was not recognised.") .Must(NotHaveExistingLink) .WithMessage("This board is already in your list."); } protected bool HaveExistingBoard(string hash) { var con = HttpContext.Current.Items["con"] as IDbConnection; dynamic res = con.Query<dynamic>("select count(id) as board_count from boards where hash=@hash;", new {hash}) .Single(); return res.board_count == 1; } protected bool NotHaveExistingLink(string hash) { var con = HttpContext.Current.Items["con"] as IDbConnection; dynamic res = con.Query<dynamic>( "select count(id) as link_count from user_boards where board_hash=@hash and user_id=@user_id;", new {hash, user_id = HttpContext.Current.Items["UserId"]}) .Single(); return res.link_count == 0; } } #endregion #region Nested type: UserAddValidator public class UserAddValidator : AbstractValidator<JObject> { public UserAddValidator() { RuleFor(x => x.GetValue("email").ToString()) .EmailAddress() .WithMessage("Email is not valid.") .Must(HaveNoEmailInDB) .WithMessage("Email already exists.") .WithName("email"); RuleFor(x => x.GetValue("password").ToString()) .Length(5, 100) .WithMessage("The password is to short.") .WithName("password"); RuleFor(x => x.GetValue("display_name").ToString()) .Length(3, 100) .WithMessage("A display name must be entered and be at least 3 characters long.") .WithName("display_name"); } protected bool HaveNoEmailInDB(string email) { var con = HttpContext.Current.Items["con"] as IDbConnection; dynamic res = con.Query<dynamic>("select count(id) as user_count from users where email=@email;", new {email}) .Single(); return res.user_count == 0; } } #endregion #region Nested type: UserUpdateValidator public class UserUpdateValidator : AbstractValidator<JObject> { public UserUpdateValidator() { RuleFor(x => x.GetValue("password").ToString()) .Length(5, 100) .WithMessage("The password is to short.") .WithName("password"); RuleFor(x => x.GetValue("display_name").ToString()) .Length(3, 100) .WithMessage("A display name must be entered and be at least 3 characters long.") .WithName("display_name"); } } #endregion } }<file_sep>/// <reference path="Account.ts" /> /// <reference path="../global_js/amplify.d.ts" /> /// <reference path="../global_js/linq-2.2.d.ts" /> /// <reference path="../global_js/routie.d.ts" /> /// <reference path="../global_js/App.GlobalCommon.ts" /> module App { export class AccountClient extends ServerClientBase { constructor() { super("account_server.ashx") } } export class Starter { private window: Window; private static hasSetEvents: boolean = false; public static start() { this.registerEvents(); this.registerRoutes(); } static registerRoutes() { window["routie"]({ '/create': (id) => Account.CreateAccountView.init(), '/signin': (id) => Account.LoginView.init(), '/signout': (id) => Account.LoginView.signout(), '/': (id) => Account.LoginView.init(), '': () => Account.LoginView.init() }); } private static registerEvents() { if (this.hasSetEvents === false) { this.hasSetEvents = true; } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Security.Cryptography; using System.Text; using System.Web.UI.WebControls; using Dapper; using MySql.Data.MySqlClient; namespace Tekphoria.Web.Server.Common { public class DbMeta { private readonly string _constring; private readonly IDbConnection _connection; public DbMeta(string constring) { _constring = constring; } public IDbConnection GetOpenConnection() { var con = new MySqlConnection(_constring); con.Open(); return con; } public List<DbField> GetMySqlStructure() { IDbConnection con = null; var dbFields = new List<DbField>(); try { con = GetOpenConnection(); var tables = SqlMapper.Query<string>(con, "show tables;").ToList(); var currentFields = new List<DbField>(); foreach (var table in tables) { currentFields = SqlMapper.Query<DbField>(con, "describe " + table).ToList(); foreach (var field in currentFields) { field.table = table; var hashable = new[] { field.table, field.@field, field.type, field.@null, field.key, field.@default, field.extra, }; field.hash = string.Join("^", hashable).ToUpperInvariant(); // Debug.Print(field.hash); dbFields.Add(field); } } } finally { if (con != null && con.State != ConnectionState.Closed) con.Close(); } return dbFields; } } public class DbField { public string hash { get; set; } public string table { get; set; } public string field { get; set; } public string @type { get; set; } public string @null { get; set; } public string key { get; set; } public string @default { get; set; } public string @extra { get; set; } } }<file_sep>var App; (function (App) { var ViewPart = (function () { function ViewPart() { } ViewPart.info = function (title, message) { var info = App.GlobalCommon.div("info__", "alert alert-success", "<strong>" + title + "</strong>" + "<br>" + message); $("#info__").fadeOut().remove(); $("#app").prepend(info).hide().fadeIn(); return info; }; ViewPart.info_hide = function () { $("#info__").remove(); }; return ViewPart; })(); App.ViewPart = ViewPart; })(App || (App = {})); <file_sep>using System; using System.Web; using System.Web.UI; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.account { public partial class RequiresLogin : UserControl { protected void Page_Init(object sender, EventArgs e) { try { var a = new AccountServer(); a.Authorise(HttpContext.Current); } catch (Exception) { Response.Redirect("/login"); } } } } <file_sep>var WB; (function (WB) { var Board = (function () { function Board(id, nameof, columns, stories, tasks) { this.id = id; this.nameof = nameof; this.columns = columns; this.stories = stories; this.tasks = tasks; } return Board; })(); WB.Board = Board; var BoardSummary = (function () { function BoardSummary(id, nameof) { this.id = id; this.nameof = nameof; } return BoardSummary; })(); WB.BoardSummary = BoardSummary; var BoardController = (function () { function BoardController() { } BoardController.BOARDS_LIST = function () { var boards = []; var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardsList", {}); $.when(action).then(function (resp) { return BoardsView.render(resp); }); }; BoardController.BOARD_ADD = function () { BoardAddView.render(); }; BoardController.BOARD_DELETE = function (hash) { DeleteBoardView.render(hash); }; BoardController.BOARD_GET = function (hash) { var _this = this; var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetByHash", { hash: hash }); $.when(action).then(function (resp) { return _this.HandleBoardResponse(resp); }); }; BoardController.HandleBoardResponse = function (resp) { if (resp.board) { BoardView2.render(resp); } else { window.routie("boards"); } }; BoardController.BOARD_DELETE_REPLY = function () { }; BoardController.BOARD_GET_CONFIGURATION = function (hash) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetConfiguration", { hash: hash }); $.when(action).then(function (resp) { return BoardConfigView.render(resp); }); }; BoardController.BOARD_GET_ARCHIVE = function (hash) { var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardGetArchiveByHash", { hash: hash }); $.when(act).then(function (resp) { return BoardArchiveView.render(resp); }); }; BoardController.USER_ADD_SHARED_BOARD = function (data) { AddSharedBoardView.render(); }; return BoardController; })(); WB.BoardController = BoardController; var BoardView2 = (function () { function BoardView2() { } BoardView2.render = function (data) { amplify.store("last_board_hash", data.board.hash); if (data.board.extra_status_2) data.columns.splice(2, 0, data.board.extra_status_2); if (data.board.extra_status_1) data.columns.splice(2, 0, data.board.extra_status_1); var rows = ""; Enumerable.From(data.stories).OrderBy(function (s) { return s.sort_order; }).ForEach(function (story) { rows += "<tr data-storyid=" + story.id + ">"; rows += "<td valign=top align=center>" + WB.StoryView.munged(story, data.board.hash) + "</td>"; Enumerable.From(data.columns).ForEach(function (col, idx) { rows += "<td valign=middle align=center><div class='tasks' data-storyid='" + story.id + "' data-status='" + col + "'>"; Enumerable.From(data.tasks).OrderBy(function (t) { return t.sort_order; }).ForEach(function (t) { if (t.story_id === story.id && t.status === col) { t.display_name = Enumerable.From(data.users).FirstOrDefault(function (u) { return t.user_id === u.id; }).display_name; rows += WB.TaskView.getHtml(t); } }); rows += "</div></td>"; }); rows += "</tr>"; }); if (data.stories.length < 6) { Enumerable.RangeTo(data.stories.length, 5).ForEach(function (i) { rows += "<tr>"; Enumerable.RangeTo(0, data.columns.length).ForEach(function (i) { rows += "<td></td>"; }); rows += "</tr>"; }); } data.rowsHtml = rows; var toolbar = App.ViewEngine.getHtml(this.getToolBarTemplate(), data); var takmoreView = WB.TaskMoreBarView.getHtml({ id: 0 }); WB.TaskMoreBarView.setEvents(); App.ViewEngine.renderview(this.getTemplate(), data); $("#board").append(toolbar); $("#board").before(takmoreView); this.makeTasksSortable(); this.makeStoriesSortable(); }; BoardView2.makeTasksSortable = function () { var tasklists = $(".tasks"); tasklists.sortable({ connectWith: ".tasks", cursor: "move", placeholder: 'hover', distance: 1, tolerance: "pointer", start: function (event, ui) { var id = $(ui.item).attr("data-id"); var tasks = $(ui.item).parent(); var story_id = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var start_index = ui.item.index(); var start_data = '' + story_id + status + start_index; tasks.attr('data-start_data', start_data); }, stop: function (event, ui) { var tasks = $(ui.item).parent(); var board_id = $("#board_id").val(); var tasks_all = tasks.find(".task"); var story_id = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var id = $(ui.item).attr("data-id"); var new_index = ui.item.index(); var start_data = tasks.attr('data-start_data'); var new_data = '' + story_id + status + new_index; if (new_data === start_data) { return; } else { if (status === 'archive') { WB.TaskController.TASK_UPDATE_STATUS({ id: id, status: 'archive' }); return; } var task_ordering = Enumerable.From(tasks_all).Select(function (t) { return +$(t).attr("data-id"); }).ToArray(); WB.TaskController.TASK_MOVE({ board_id: board_id, story_id: story_id, id: id, status: status, task_ordering: task_ordering }); } } }).disableSelection(); }; BoardView2.makeStoriesSortable = function () { var touch = 'ontouchend' in document; if (!('ontouchend' in document)) { $("#board tbody").sortable({ placeholder: 'hover', cursor: "move", stop: function (event, ui) { var stories = $(ui.item).parent(); var stories_all = stories.find(".story"); var id = $(ui.item).attr("data-storyid"); var story_order = Enumerable.From(stories_all).Select(function (s) { return +$(s).attr("data-id"); }).ToArray(); var data = { id: id, story_order: story_order }; var client = new WB.ScrumboServerClient(); client.CallMethod("BoardSortStory", data); } }); } }; BoardView2.getTemplate = function () { return "" + "<table width=100%>" + "<tr>" + "<td>" + "<div class='board-name pagination-left'>{{board.nameof}}</div>" + "<div class='board-moreinfo'>{{&board.more_info}}</div>" + "</td>" + "<td align=right>" + "<div class=''>" + "<a href='#boards'>All Boards</a>" + " <a href='#board/{{board.hash}}/config'>Configure</a> " + " <a href='#board/{{board.hash}}/archive'>Archive</a> " + " <a href='#board/{{board.slug}}/{{board.hash}}'>Link</a>" + "</div>" + "</td>" + "</tr>" + "</table>" + "<table id='board' class='table' align=center data-id={{board.hash}}>" + "<thead>" + "<th>Story <a class='btn btn-mini info' href='#board/{{board.hash}}/addstory'>add</a></th>" + "{{#columns}}<th>{{.}}</th>{{/columns}}" + "</tr>" + "</thead>" + "<tbody>" + "{{&rowsHtml}}" + "</tbody>" + "</table>" + "{{&board.taskMoreBarViewHtml}}" + "<input type=hidden id=board_id value='{{board.hash}}'></input>"; }; BoardView2.getToolBarTemplate = function () { return "<div>" + "</div>"; }; return BoardView2; })(); WB.BoardView2 = BoardView2; var BoardConfigView = (function () { function BoardConfigView() { } BoardConfigView.render = function (boardConfigData) { App.ViewEngine.renderview(this.getTemplate(), boardConfigData); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var formdata = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardSetConfiguration", formdata); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1)); }); }); }; BoardConfigView.getTemplate = function () { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '{{board.nameof}}', 'The name of the board', 'text'); var info = App.GlobalCommon.textarea('more_info', 'more_info', '{{board.more_info}}', 'Extra infomation to be displayed.', '5'); var status1 = App.GlobalCommon.inputstring('extra_status_1', 'extra_status_1', '{{board.extra_status_1}}', 'Status Column 1 after between inprogress and done.', 'text'); var status2 = App.GlobalCommon.inputstring('extra_status_2', 'extra_status_2', '{{board.extra_status_2}}', 'Status Column 2 after between inprogress and done.', 'text'); var hash = App.GlobalCommon.inputstring('hash', 'hash', '{{board.hash}}', '', 'hidden'); return App.GlobalCommon.form('Configure board', nameof + info + status1 + status2 + hash); }; return BoardConfigView; })(); WB.BoardConfigView = BoardConfigView; var BoardTrashView = (function () { function BoardTrashView() { } BoardTrashView.render = function () { this.registerEvents(); App.ViewEngine.renderview(this.getTemplate(), {}); }; BoardTrashView.getHtml = function () { return this.getTemplate(); }; BoardTrashView.registerEvents = function () { }; BoardTrashView.getTemplate = function () { this.registerEvents(); return "<div class='trash'><img src='/img/trash.png'/></div>"; }; return BoardTrashView; })(); WB.BoardTrashView = BoardTrashView; var BoardAddView = (function () { function BoardAddView() { } BoardAddView.getFormInputsAsObject = function () { var form = $("#form1"); return App.GlobalCommon.getFormInputs(form); }; BoardAddView.render = function () { App.ViewEngine.renderview(this.getTemplate(), {}); var submitbtn = $("#btnsubmit"); var hash = $("#hash"); submitbtn.on("click", function (e) { e.preventDefault(); hash.val(App.GlobalCommon.createUUID(12, 36)); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardAdd", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(1); }); }); }); }; BoardAddView.getTemplate = function () { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '', 'The name of the board', 'text'); var hash = App.GlobalCommon.inputstring('hash', 'hash', App.GlobalCommon.createUUID(12, 36), '', 'hidden'); return App.GlobalCommon.form('Add a board', nameof + hash); }; return BoardAddView; })(); WB.BoardAddView = BoardAddView; var BoardsView = (function () { function BoardsView() { } BoardsView.render = function (boards) { App.ViewEngine.renderview(this.getTemplate(), boards); }; BoardsView.getTemplate = function () { return "<div class=container><strong>Boards</strong><br>" + "<div class='pull-right'><a class='' href='#boards/addshared'>Add Shared Board</a> <a class='btn' href='#boards/add'>New Board</a></div>" + "<table class='table'><br><br>{{#BoardSummaries}}<tr><td><a class='' href='#board/{{hash}}'><strong>{{nameof}}</strong></a> </td>" + "<td><a class='' href='#board/{{hash}}/addstory'>+story</a></td><td><span class=muted>key: {{hash}}</span></td>" + "</tr>{{/BoardSummaries}}</table></div>"; }; return BoardsView; })(); WB.BoardsView = BoardsView; var DeleteBoardView = (function () { function DeleteBoardView() { } DeleteBoardView.render = function (hash) { App.ViewEngine.renderview(this.getViewTemplate(), { "hash": hash }); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardDelete", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window["routie"]("boards"); }); }); }); }; DeleteBoardView.getViewTemplate = function () { return App.GlobalCommon.form('<div class="alert alert-danger">DANGER ZONE! Actions taken will delete a board</div>', 'To Cancel use the back button or press submit to delete the board' + App.GlobalCommon.inputstring('hash', 'hash', '{{hash}}', '', 'hidden')); }; return DeleteBoardView; })(); WB.DeleteBoardView = DeleteBoardView; var BoardArchiveView = (function () { function BoardArchiveView() { } BoardArchiveView.render = function (data) { var tasksHtml = ''; Enumerable.From(data.tasks).ForEach(function (t) { tasksHtml += WB.TaskView.getHtml(t); }); data.tasksHtml = tasksHtml; var taskMoreBarViewHtml = WB.TaskMoreBarView.render(data); App.ViewEngine.renderview(this.getViewTemplate() + taskMoreBarViewHtml, data); $('#archivedtasks').masonry({ itemSelector: '.task' }); }; BoardArchiveView.getViewTemplate = function () { return '<div class="well clearfix board_archive"><strong>Board Archive</strong><hr><div id="archivedtasks" >{{&tasksHtml}}</div></div>'; }; return BoardArchiveView; })(); WB.BoardArchiveView = BoardArchiveView; var AddSharedBoardView = (function () { function AddSharedBoardView() { } AddSharedBoardView.render = function () { App.ViewEngine.renderview(this.getTemplate(), {}); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("UserAddSharedBoard", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window["routie"]("boards"); }); }); }); }; AddSharedBoardView.getTemplate = function () { var hash = App.GlobalCommon.inputstring('hash', 'hash', '', 'The shared boards hash', 'text'); return App.GlobalCommon.form('Link shared board', hash); }; return AddSharedBoardView; })(); WB.AddSharedBoardView = AddSharedBoardView; })(WB || (WB = {})); <file_sep>using System; using System.Web.UI; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.account { public partial class LogOut : Page { protected void Page_Load(object sender, EventArgs e) { var a = new AccountServer(); a.LogOut(); } } } <file_sep>/// <reference path="WB.BoardClasses.ts" /> /// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="wb.storage.ts" /> module WB { /* ========================================================================================= */ export class TaskController { public static TASK_ADD_TO_STORY(id, hash) { TaskAddView.render( { id: id, hash: hash } ); $("#btnsubmit").on("click", (e) => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); this.submitForm() }) } static submitForm() { var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskAddToStory", form) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(-1)); }) } //public static TASK_ADD_TO_STORY_REPLY(data) { // validate(data); //} public static TASK_MOVE(data: any): void { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskMove", data) } public static TASK_UPDATE_STATUS(data: any): void { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data) } public static TASK_DELETE(deleteData: any) { TaskDeleteView.render(deleteData); } public static TASK_GET(id: string) { var client = new WB.ScrumboServerClient(); var serverData = client.CallMethod("TaskGet", {id:id}) $.when(serverData).then(resp => TaskEditView.render(resp)); } //public static TASK_UPDATE_TEXT_REPLY(data) { // this.validate(data); //} public static validate(data) { if (data.IsValid !== 'undefined' && data.IsValid === false) { App.GlobalCommon.apply_validation(data, $("#form1")); } else { window.history.back(-1); } } public static TASK_DELETE_REPLY(data) { window.history.back(-1); } } export class TaskMenuView { public static getHtml(task: Task): string { return App.ViewEngine.getHtml(this.getTemplate(), task) } static getTemplate(): string { return "<div class='taskmenu' data-id={{id}}>" + "<a href='#' class='act'>Edit</a>" + "<a href='#' class='act'>Add Log</a>" + "<a href='#' class='act'>Add File</a>" + "<a href='#' class='act'>Archive</a>" + "<a href='#' class='act'>Delete</a>" +"</div>" } static render(task) { App.ViewEngine.renderview(this.getTemplate(), task) } } export class TaskView { static adjustModel(task: Task): Task { if (!task.css_class) task.css_class = 'task'; task.isEditable = task.status === "TODO"; task.showUser = (task.user_id > 0); // task.fuzzyModified = Common.prettyDate(task.date_modified); task.fuzzyModified = moment.utc(task.date_modified).fromNow() task.textof = App.GlobalCommon.uiify(task.textof); return task; } public static render(task: Task) { this.adjustModel(task) App.ViewEngine.renderview(this.getTemplate(task), task) } public static getHtml(task: Task): string { this.adjustModel(task); return App.ViewEngine.getHtml(this.getTemplate(task), task) } static getTemplate(task: Task): string { var done = task.status !== 'DONE' ? "" : " <a class='btntaskarchive' alt='archive' href='#' data-id='{{id}}'>archive</a>" var archive = task.status !== 'ARCHIVE' ? "":" <a class='btntaskdone' alt='archive' href='#' data-id='{{id}}'>set done</a>" return "<div class='task {{css_class}} clearfix' data-id='{{id}}' data-status='{{status}}'>" + "<div class=ttext> {{&textof}}" + "<div class='task-foot clearfix'>" + "<span class=''>#{{id}}</span> changed <span>{{fuzzyModified}} by {{display_name}}</span>" + " <a data-id={{id}} class='taskmore' alt='view taskbar' href='#task/{{id}}'>edit</a>" + done + archive + " </div>" + "</div>" + "</div>" // + "</div>" //<img class='profileimage img-rounded pull-left' width=30px height=30px src='/userfiles/user/{{user_id}}.jpg'/> } } export class TaskDeleteView { public static render(id: any) { App.ViewEngine.renderview(this.getTemplate(), { id: id }) $("#btnsubmit").on("click", (e) => { e.preventDefault(); var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskDelete", form) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(-1)); }) }) } static getTemplate() { var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') return App.GlobalCommon.form('Delete Task ?', id + "Pressing Submit will delete the task and any associated objects permenantly.") } } export class TaskAddLogView { public static render(data) { return App.ViewEngine.renderview(this.getTemplate(), data); } static getData(data) { data.board_hash = amplify.store("last_board_hash") return data; } public static getHtml(data) { return App.ViewEngine.getHtml(this.getTemplate(), data); } static getTemplate() { var log = App.GlobalCommon.textarea('textof', 'textof', '', 'Enter the log text.', '') var id = App.GlobalCommon.inputstring('task_id', 'task_id', "{{id}}", '', 'hidden') var form = App.GlobalCommon.form('Add Log item', log, 'btnaddlog', "formAddLog"); return form; } } export class TaskAddView { public static render(taskViewData: any): void { App.ViewEngine.renderview(this.getTemplate(), taskViewData) } static getTemplate() { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{textof}}', '', "7") var id = App.GlobalCommon.inputstring('story_id', 'story_id', "{{id}}", '', 'hidden') var css = "" css += App.GlobalCommon.radio('css_class', 'task', 'Yellow', 'taskmini yellow', true) css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'taskmini green', false) css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'taskmini orange', false) css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'taskmini pink', false) css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'taskmini blue', false) css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'taskmini purple', false) var shortcut = "<div class='label'>shift + n to save</div>" var hash = App.GlobalCommon.inputstring('hash', 'hash', "{{hash}}", '', 'hidden') return App.GlobalCommon.form('New Task ' + shortcut, textof + id + css + hash) } } export interface IView { render(data: any); registerEvents(): void; getHtml(): string; } export class TaskEditView implements IView { render(data: any) { } registerEvents() { } getHtml() : string { return ""; } public static render(taskViewData: any) { var html = App.ViewEngine.renderview(this.getTemplate(taskViewData), taskViewData); $("input:radio[value=" + taskViewData.css_class + "]").first().attr('checked', "checked"); $("#btnsubmit").on("click", e => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskUpdateText", data) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(-1)); }) }) $("#btnaddlog").on("click", e => { e.preventDefault(); }) return html; } static getTemplate(data) { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{&textof}}', '', "7") var css = "" css += App.GlobalCommon.radio('css_class', 'task', 'Yellow', 'taskmini yellow', true) css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'taskmini green', false) css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'taskmini orange', false) css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'taskmini pink', false) css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'taskmini blue', false) css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'taskmini purple', false) var id = "<input class='form-editing' type='hidden' id='id' name='id' value='{{id}}' maxlength='50'>" var form = App.GlobalCommon.form('Edit Task #{{id}}', textof + css + TaskSetStatusView.getHtml(data) + id) return form; } } export class TaskSetStatusView{ public static getHtml(data) { this.init(data); return App.ViewEngine.getHtml(this.getTemplate(), data); } public static init(data) { $("body").on("click", ".btn_status", e => { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data) window.history.back(-1); }) } public static render(data) { this.init(data); return App.ViewEngine.renderview(this.getTemplate(), data); } public static getTemplate() { var tmp = "<br><div class=''>Status</div><div class='btn-group'>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='INPROGRESS'>In progress</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='TODO'>To do</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='DONE'>Done</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='ARCHIVE'>Archive</a>" + "</div>"; return tmp; } } export class TaskMoreBarView { public static setData(data: any) { data.trashview = WB.BoardTrashView.getHtml(); return data; } public static render(data: any) { this.setData(data); this.setEvents(); return App.ViewEngine.renderview(this.getTemplate(), this.setData(data)) } public static getHtml(data) { this.setData(data); this.setEvents(); return this.render(data); } public static setEvents() { //$("body").on("click", ".taskmore", (e) => { // e.preventDefault(); // var id = $(e.currentTarget).attr("data-id"); // var taskmoreview = $('#TaskMoreBarView'); // taskmoreview // .show() // .css('position', 'absolute') // .css('left', e.pageX - 90 + 'px') // .css('top', e.pageY + 20 + 'px') // .attr('data-id', id); // taskmoreview // .find(".btntaskedit") // .first() // .attr("href", '#task/' + id) // taskmoreview // .find(".btntaskdelete") // .first() // .attr("href", '#task/delete/' + id) // taskmoreview // .find(".btntaskarchive") // .first() // .attr("data-id", id) // setTimeout(()=> $('#TaskMoreBarView').hide(), 10000); //}); //$("body").on("click", ".btntaskclose", (e) => { // e.preventDefault(); // $('#TaskMoreBarView').hide(); //}); //$("body").on("click", ".btntaskarchive", (e) => { // e.preventDefault(); // var id = $(e.target).attr("data-id"); // TaskController.TASK_UPDATE_STATUS({ id: id, status: 'archive' }); // var task = $(".task[data-id=" + id + "]") // task.remove(); // $('#TaskMoreBarView').hide(); //}); } static getTemplate() { return "<div data-id=0 id='TaskMoreBarView' class='taskmoreviewbar'><strong>Task Bar</strong>" + " <a class = 'btntaskedit' alt='view and edit details' href='#'><i class='icon-edit'></i> edit</a>" + " <a class = 'btntaskaddlog' alt='add log' href='#'><i class='icon-th-list'></i> add log</a>" + " <a class = 'btntaskarchive' alt='archive of the board' href='#'><i class='icon-folder-close'></i> archive</a>" + " <a class = 'btntaskclose' alt='close this' href='#' ><i class='icon-remove'></i> close </a>" + " <a class = 'btntaskdelete' alt='delete' href='#'><i class='icon-trash'></i> delete</a>" + " </div >" } } export class Task { constructor( public id: number, public nameof: string, public textof: string, public story_id: number, public status: string, public sort_order: string, public isEditable: boolean, public css_class: string, public user_id: number, public showUser: boolean, public fuzzyModified: string, public display_name: string, public date_modified: string ) { } } }<file_sep>/// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/domo.d.ts" /> module App { export class days { public static init() { // alert(html.outerHtml) } static getDaysContent() : string { var html = ""; var now = moment(); for (var i; i <= now.daysInMonth(); i++ ) { DIV({class:"day"}) } now.daysInMonth(); return ""; } } export class Header { static init() { } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Tekphoria.Web.global_pages { public partial class Centered : System.Web.UI.MasterPage { private int _offset; public int BoxWidth { get; set; } public int Offset{ get { _offset = (12 - BoxWidth) / 2; return _offset; } set { _offset = value; } } public Centered() { BoxWidth = 4; Offset = 4; } protected void Page_Load(object sender, EventArgs e) { } } }<file_sep>/// <reference path="WB.Storage.ts" /> /// <reference path="WB.BoardClasses.ts" /> /// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> module WB { /* ========================================================================================= */ export class TaskController { public static TASK_ADD_TO_STORY(id, hash) { TaskAddView.render( { id: id, hash: hash } ); $("#btnsubmit").on("click", (e) => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); this.submitForm() }) } static submitForm() { var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskAddToStory", form) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(-1)); }) } public static TASK_MOVE(data: any): void { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskMove", data) } public static TASK_UPDATE_STATUS(data: any): void { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data) } public static TASK_DELETE(deleteData: any) { TaskDeleteView.render(deleteData); } public static TASK_GET(id: string) { var client = new WB.ScrumboServerClient(); var serverData = client.CallMethod("TaskGet", {id:id}) $.when(serverData).then(resp => TaskEditView.render(resp)); } public static TASK_ADD_LOG() { } public static validate(data) { if (data.IsValid !== 'undefined' && data.IsValid === false) { App.GlobalCommon.apply_validation(data, $("#form1")); } else { window.history.back(-1); } } public static TASK_DELETE_REPLY(data) { window.history.back(-1); } } export class TaskMenuView { public static getHtml(task: Task): string { return App.ViewEngine.getHtml(this.getTemplate(), task) } static getTemplate(): string { return "<div class='taskmenu' data-id={{id}}>" + "<a href='#' class='act'>Edit</a>" + "<a href='#' class='act'>Add Log</a>" + "<a href='#' class='act'>Add File</a>" + "<a href='#' class='act'>Archive</a>" + "<a href='#' class='act'>Delete</a>" +"</div>" } static render(task) { App.ViewEngine.renderview(this.getTemplate(), task) } } export class LogNote { constructor( public textof: string ) {} } export class LogNoteRowView { public static render(note: LogNote) { return App.ViewEngine.renderview(LogNoteRowView.getTemplate(), note) } public static getHtml(note: LogNote) { return App.ViewEngine.getHtml(LogNoteRowView.getTemplate(), note) } public static getTemplate(): string { return "<div class='lognoterow'><span class='glyphicon glyphicon-pencil'>&nbsp;</span><span class='lognote'>{{textof}}</span></div>" } } export class TaskView { static adjustModel(task: Task): Task { if (!task.css_class) task.css_class = 'task'; task.isEditable = task.status === "TODO"; task.showUser = (task.user_id > 0); task.fuzzyModified = moment.utc(task.date_modified).fromNow() task.textof = App.GlobalCommon.uiify(task.textof); return task; } public static render(task: Task) { this.adjustModel(task) App.ViewEngine.renderview(this.getTemplate(task), task) } public static getHtml(task: Task): string { this.adjustModel(task); //task["archivelink"] = task.status === 'DONE' ? "<br><a class='btn btn_status btn-xs' alt='Archive this task' href='#' data-status='ARCHIVE' data-id='{{id}}'>archive</a>" : "" return App.ViewEngine.getHtml(this.getTemplate(task), task) } // static tmpl : string; static getTemplate(task: Task): string { var tmpl = "" var logNoteRow = LogNoteRowView.getTemplate() var archive = task.status === 'DONE' ? "<br><a class='btn btn_status btn-xs' alt='Archive this task' href='#' data-status='ARCHIVE' data-id='{{id}}'>archive >></a>" : "" var tmpl = "<div class='task {{css_class}} clearfix' data-id='{{id}}' data-status='{{status}}'>" + "<div class='ttext'> {{&textof}} " + "<span class='more'>[more...]</span>" + archive //+ "<br><a class='btn btn_status btn-xs' alt='Archive this task' href='#' data-status='ARCHIVE' data-id='{{id}}'>archive</a>" + "<div class=lognotes>{{#log_notes}}" + logNoteRow + "{{/log_notes}}</div>" + "<div class='task-foot clearfix'>" + "---<br><span class=''>#{{id}}</span> changed <span>{{fuzzyModified}} by {{display_name}}</span><span class='usercss_{{user_id}}'></span>" + " <a data-id={{id}} class='taskmore' alt='View taskbar' href='#task/{{id}}'>[edit]</a>" + " <a data-id={{id}} class='addlog' alt='Add a task comment' href='#'>[add notelog]</a> " + " <a data-id={{id}} class='' alt='View Task Log' href='#task/{{id}}/log'>[see {{note_count}} in note log]</a>" + " </div>" + "</div>" + "</div>" return tmpl; } } export class TaskDeleteView { public static render(id: any) { App.ViewEngine.renderview(this.getTemplate(), { id: id }) $("#btnsubmit").on("click", (e) => { e.preventDefault(); var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskDelete", form) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.routie("board/" + amplify.store('last_board_hash'))); }) }) } static getTemplate() { var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-trash'></span> Delete Task</h2>", id + " <span class='label label-danger'>Warning</span> <span>Pressing Submit will delete the task and any associated objects permenantly.</span><br><br>") return App.GlobalCommon.container(form) } } export class TaskAddLogView { public static render(data) { App.ViewEngine.renderview(this.getTemplate(), data); } public static getHtml(data) { return App.ViewEngine.getHtml(this.getTemplate(), data); } static getTemplate() { $("#addlogid").remove() var lines = [] lines.push('<div class="addlogview">') lines.push('<form role="form" class="form-vertical" id="formAddLog">') lines.push('<input class="form-editing" type="text" id="textof" name="addlogid" value="" maxlength="50"/>') lines.push('<input class="form-editing" type="hidden" id="addlogid" name="addlogid" value="{{id}}" maxlength="50"/>') lines.push(' <button id="btnaddlog" data-id="0" class="btn btn-primary btn-xs clearfix">add</button>') lines.push('<div id="errors"></div>') lines.push('</form>') lines.push('</div>') return lines.join('') } } export class TaskAddView { public static render(taskViewData: any): void { App.ViewEngine.renderview(this.getTemplate(), taskViewData) } static getTemplate() { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{textof}}', '', "4") var id = App.GlobalCommon.inputstring('story_id', 'story_id', "{{id}}", '', 'hidden') var css = "" css += App.GlobalCommon.radio('css_class', 'taskyellow', 'Yellow', 'yellow taskmini', true) css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', ' green taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'orange taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'pink taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'blue taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'purple taskmini', false) var hash = App.GlobalCommon.inputstring('hash', 'hash', "{{hash}}", '', 'hidden') var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-leaf'></span> New Task</h2>", textof + id + css + hash +"<br><br>") return App.GlobalCommon.container(form) } } export interface IView { render(data: any); registerEvents(): void; getHtml(): string; } export class TaskEditView implements IView { render(data: any) { } registerEvents() { } getHtml() : string { return ""; } public static render(taskViewData: any) { var html = App.ViewEngine.renderview(this.getTemplate(taskViewData), taskViewData); $("input:radio[value=" + taskViewData.css_class + "]").first().attr('checked', "checked"); $("#btnsubmit").on("click", e => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskUpdateText", data) $.when(servertask).then(resp => { App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(-1)); }) }) return html; } static getTemplate(data) { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{&textof}}', '', "4") var css = "<br>" css += App.GlobalCommon.radio('css_class', 'taskyellow', 'Yellow', 'yellow taskmini', true) css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'green taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'orange taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'pink taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'blue taskmini', false) css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'purple taskmini', false) var id = "<input class='form-editing' type='hidden' id='id' name='id' value='{{id}}' maxlength='50'>" var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-edit'></span> Edit Task #{{id}}</h2>", textof + css + TaskSetStatusView.getHtml(data) + id) return App.GlobalCommon.container(form); } } export class TaskSetStatusView{ public static getHtml(data) { this.init(data); return App.ViewEngine.getHtml(this.getTemplate(), data); } public static init(data) { $("body").on("click", ".btn_status", e => { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); client.CallMethod( status === 'DELETE' ? "TaskDelete" : "TaskUpdateStatus", data) window.history.back(-1); }) } public static render(data) { this.init(data); return App.ViewEngine.renderview(this.getTemplate(), data); } public static getTemplate() { var tmp = "<div class='clearfix'></div><div class='clearfix btn-group'>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='INPROGRESS'>In progress</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='TODO'>To do</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='DONE'>Done</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='ARCHIVE'>Archive</a>" + "<a class='btn btn-default btn_status btn-warning' href='#' data-id='{{id}}' data-status='DELETE'>Delete</a>" + "</div><br><br>"; return tmp; } } export class TaskMoreBarView { public static setData(data: any) { data.trashview = WB.BoardTrashView.getHtml(); return data; } public static render(data: any) { this.setData(data); return App.ViewEngine.renderview(this.getTemplate(), this.setData(data)) } public static setEvents() {} public static getHtml(data) { this.setData(data); return this.render(data); } static getTemplate() { return "<div data-id=0 id='TaskMoreBarView' class='taskmoreviewbar'><strong>Task Bar</strong>" + " <a class = 'btntaskedit' alt='view and edit details' href='#'><i class='icon-edit'></i> edit</a>" + " <a class = 'btntaskaddlog' alt='add log' href='#'><i class='icon-th-list'></i> add log</a>" + " <a class = 'btntaskarchive' alt='archive of the board' href='#'><i class='icon-folder-close'></i> archive</a>" + " <a class = 'btntaskclose' alt='close this' href='#' ><i class='icon-remove'></i> close </a>" + " <a class = 'btntaskdelete' alt='delete' href='#'><i class='icon-trash'></i> delete</a>" + " </div >" } } export class Task { constructor( public id: number, public nameof: string, public textof: string, public story_id: number, public status: string, public sort_order: string, public isEditable: boolean, public css_class: string, public user_id: number, public showUser: boolean, public fuzzyModified: string, public display_name: string, public date_modified: string, public note_count: number, public log_notes: any[] ) { } } }<file_sep>var views; (function (views) { var menu = (function () { function menu() { } menu.getHtml = function () { var h = templates.menu; this.events(); return h; }; menu.events = function () { var _this = this; $("body").on("click", "#allgames", function (e) { return _this.allgames_fired(e); }); $("body").on("click", "#newgame", function (e) { return _this.newgame_fired(e); }); }; menu.allgames_fired = function (e) { e.preventDefault(); $(".main").first().html(games.getHtml()); }; menu.newgame_fired = function (e) { e.preventDefault(); $(".main").first().html(newgame.getHtml()); }; return menu; })(); views.menu = menu; var board = (function () { function board() { } board.getHtml = function () { var html = App.ViewEngine.getHtml(templates.frame(), {}); return html; }; return board; })(); views.board = board; var games = (function () { function games() { } games.getHtml = function () { var client = new chess.ChessServerClient(); var act = client.CallMethod("Games", {}); $.when(act).then(function (resp) { return App.ViewEngine.getHtml(templates.games(), resp); }); }; return games; })(); views.games = games; var newgame = (function () { function newgame() { } newgame.getHtml = function () { this.events(); return App.ViewEngine.getHtml(templates.setupgame(), {}); }; newgame.events = function () { var _this = this; $("body").on("click", "#btnsubmit", function (e) { e.preventDefault(); var client = new chess.ChessServerClient(); var form = App.GlobalCommon.getFormInputs($("#form1")); var resp = client.CallMethod("NewGame", form); $.when(resp).then(function (resp) { return _this.handleSetupResponse(resp); }); }); }; newgame.handleSetupResponse = function (resp) { if (resp.result.IsValid === undefined) { var html = views.board.getHtml(); $(".main").first().html(html); } else { App.GlobalCommon.apply_validation(resp.result, $("#form1")); } }; return newgame; })(); views.newgame = newgame; var home = (function () { function home() { } home.prototype.render = function (data) { var html = App.ViewEngine.renderview(templates.frame(), { menu: menu.getHtml(), main: templates.main }); return html; }; return home; })(); views.home = home; var templates = (function () { function templates() { } templates.frame = function () { return "" + "<div" + " <div class='top'><h1>TS Chess</h1>by <NAME></div>" + "</div>" + "<div>" + " <div class='menu cell'>{{&menu}}</div>" + " <div class='main cell'>{{&main}}</div>" + "</div>"; }; templates.menu = function () { return "" + "<h3>Menu</h3>" + "<input type='button' name=allgames id=allgames value='All Games' />" + "<br><br><br><input type='button' name=newgame id=newgame value='New Game' />"; }; templates.main = function () { return "" + "<h3>Main Game</h3>"; }; templates.board = function () { var tmp = ""; tmp += "<div class=board>"; var rownum = 0; var color = "white"; Enumerable.Range(0, 8).ForEach(function (r) { tmp += " <div class=boardrow>"; if (r === 0 || r % 2 === 0) { color = "white"; } else { color = "black"; } Enumerable.Range(0, 8).ForEach(function (s) { tmp += "<div id=square class='cell " + color + "'>row" + r + " cell" + s + "</div>"; if (color === "black") { color = "white"; } else { color = "black"; } }); tmp += " </div>"; }); return tmp; }; templates.messages = function () { return "" + "<div>" + "<h3>Messages</div>" + "{{#messages}}{{>message}}{{/messages}}" + "</div>"; }; templates.message = function () { return "" + "<br>at {{time}}, {{name}} said '{{message}}'"; }; templates.setupgame = function () { var title = "<h3>New Game</h3>"; var black = App.GlobalCommon.inputstring("blackplayer", "blackplayer", "", "The black players name", "text", "200"); var white = App.GlobalCommon.inputstring("whiteplayer", "whiteplayer", "", "The white players name", "text", "200"); return title + App.GlobalCommon.form("Enter the player names", black + white, "btnsubmit", "form1"); }; templates.game = function () { var tmp = ""; tmp += "<div class=game>Game {{id}} between {{blackplayer}} and {{whiteplayer}}</div>"; return tmp; }; templates.games = function () { var tmp = ""; tmp += "<h3>All Games<h3>"; tmp += "{{#games}}"; tmp += "{{>game}}"; tmp += "{{/games}}"; return tmp; }; return templates; })(); views.templates = templates; })(views || (views = {})); <file_sep>using FluentValidation; using FluentValidation.Internal; namespace Tekphoria.Web.Server.Account { public class UserValidator : AbstractValidator<User> { public UserValidator() { RuleSet("displayname", () => RuleFor(x => x.display_name) .Length(3, 50) .Matches("[a-zA-Z0-9_-]") .WithName("Display Name") .WithMessage("'Display Name' must only contain the characters 'a-z A-Z 0-9 _-'.")); RuleSet("emailandpwd", () => { RuleFor(x => x.email).EmailAddress().WithName("Email"); RuleFor(x => x.password) .Length(7, 256) .Matches("[a-zA-Z0-9_-]") .WithName("Password") .WithMessage("'Password' must only contain the characters 'a-z A-Z 0-9 _-'."); }); RuleSet("validid", () => { RuleFor(x => x.id).GreaterThan(0).WithMessage("The User is invalid"); }); } } }<file_sep>namespace Tekphoria.Web.Server.Common { public class Payload { public string Action { get; set; } public dynamic Data { get; set; } } public class Payload2 { public string MethodName { get; set; } public dynamic Data { get; set; } } }<file_sep>/// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="wb.storage.ts" /> module WB { /* ========================================================================================= */ export class UserController { public static USER_GET(id: string) { if (+id === +amplify.store(EventNames.LOCAL_USERID)) { WebStorage.USER_GET({ id: id }) } } public static USER_GET_REPLY(data) { UserUpdateView.render(data) } public static USER_UPDATE(data) { } public static USER_UPDATE_REPLY(data) { if (data.IsValid !== 'undefined' && data.IsValid === false) { App.GlobalCommon.apply_validation(data, $("#form1")) } else { window["routie"]("boards"); } } public static USER_LOGIN_REQUIRED(data) { this.SIGN_IN(data); } public static SIGN_IN(data) { Account.Common.SignIn(window.location.href); } public static USER_ADD_SHARED_BOARD(data) { AddSharedBoardView.render(); } } export class UserUpdateView { public static render(data) { var form = App.ViewEngine.getHtml(this.getTemplate(),data); var upload = UserUploadPhotoView.getHtml({}); App.ViewEngine.setAppHtml(form + upload) $("#btnsubmit").on("click", (e: any) => { e.preventDefault(); var form = App.GlobalCommon.getFormInputs($("#form1")); WebStorage.USER_UPDATE_ASYNC(form); }); } static getTemplate() { var displayname = App.GlobalCommon.inputstring('display_name', 'display_name', "{{display_name}}", 'Your display name', 'text') var password = App.GlobalCommon.inputstring('password', 'password', '{{password}}', 'Your password', 'password') // var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') return App.GlobalCommon.form('Update profile details', displayname + password) } } export class UserAddView { public static render(data) { App.ViewEngine.renderview(this.getTemplate(), {}) } static getTemplate(): string { var email = App.GlobalCommon.inputstring('email', 'email', "{{&email}}", 'Your email', 'text') var displayname = App.GlobalCommon.inputstring('display_name', 'display_name', "", 'The display name', 'text') var password = App.GlobalCommon.inputstring('password', '<PASSWORD>', "", 'Your password', '<PASSWORD>') var count = App.GlobalCommon.inputstring('count', 'count', "{{count}}", '', 'hidden') return App.GlobalCommon.form('Register', email + displayname + password + count) } } export class UserSummariesView { public static render(users : any) { App.ViewEngine.renderview(this.getTemplate(), users); } public static getHtml(users: any) { return App.ViewEngine.getHtml(this.getTemplate(), users); } static getTemplate() { return "<div class='users clearfix'><strong>Users</strong><br>{{#Users}}<div class=user><img src='userfiles/{{id}}.jpg'/> {{display_name}}</div>{{/Users}} </div>"; } } export class UserUploadPhotoView { public static render(data) { data.id = amplify.store(WB.EventNames.LOCAL_USERID); App.ViewEngine.renderview(this.getTemplate(), data); $("#btnuploadsubmit").on("click", (e: any) => { e.preventDefault(); // startUpload(); }); } public static getHtml(data) { data.id = amplify.store(WB.EventNames.LOCAL_USERID); return App.ViewEngine.getHtml(this.getTemplate(), data ); } static getTemplate() { return "<div class='well span4'><strong>Profile Image</strong><br><br><p style='display: none;' id='f1_upload_process'>Loading...<br/><img src='img/ajax-loader.gif' target='upload_target' /></p>" + "<form action='upload.ashx' method='post' enctype='multipart/form-data' target='upload_target'>" + "Select Photo <input name='clientfile' type='file' />" + "<br><br><input type='submit' name='btnuploadsubmit' id='btnuploadsubmit' value='Upload' />" + App.GlobalCommon.inputstring('id', 'id', '{{id}}', '', 'hidden') //+ "</form></div>" + "<iframe id='upload_target' name='upload_target' src='/empty.html' style='width:0;height:0;border:0px solid #fff;'></iframe>" + "</form></div>" + "<div class='well span3'><strong>Image Upload Status</strong><br><iframe id='upload_target' name='upload_target' src='upload.ashx' style='width:200px;height:50px;border:0px solid #fff;' ></iframe></div>" } } export class DefaultView { public static render(data) { App.ViewEngine.renderview(this.getTemplate(), data); } public static getHtml(data) { return App.ViewEngine.getHtml(this.getTemplate(), data); } static getTemplate() { var tmp = "default view"; return tmp; } } export class UserSummaryItemView { public static render(data) { App.ViewEngine.renderview(this.getTemplate(), data); } public static getHtml(data) { return App.ViewEngine.getHtml(this.getTemplate(), data); } static getTemplate() { var tmp = "<div class='user'>UserSummaryView</div>"; return tmp; } } }<file_sep>/// <reference path="../../global_js/require.d.ts" /> /// <reference path="./hyperlink.ts" /> //module app { module app { interface widget { render(tmpl, data); getHtml(tmpl, data); } class widgetbase implements widget { render(tmpl, data) {} getHtml(tmpl, data) { } } export class linklistwidget extends widgetbase { } }<file_sep>using System; using System.Diagnostics; using System.Web.UI; using Newtonsoft.Json; using Tekphoria.Web.global_pages; using Tekphoria.Web.Server.Account; using Tekphoria.Web.Server.Common; using Tekphoria.Web.Server.Handlers; namespace Tekphoria.Web.account { public partial class Verify : Page { protected void Page_Load(object sender, EventArgs e) { SuccessPanel.Visible = ErrorPanel.Visible = false; try { var instr = Request["k"] ?? ""; if (!string.IsNullOrWhiteSpace(instr)) { var json = Crypto.DecryptStringAES(instr, Config.ID); dynamic data = JsonConvert.DeserializeObject(json); var accountServer = new AccountServer(); accountServer.VerifyAccount(data); SuccessPanel.Msg = "Account Verified. <a href='/login'>Log in</a>."; } else { ErrorPanel.Msg = "Nothing to verify."; } } catch (Exception ex) { Debug.Write(ex); ErrorPanel.Msg = "Error verifying account."; } } } } <file_sep>using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.Caching; using FluentValidation; using FluentValidation.Results; using FluentValidation.Validators; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.Server.Printer { public class PrinterServer : JsonServer, IHttpHandler { private static readonly string Phantom = HttpContext.Current.Server.MapPath("~/components/phantom/phantomjs.exe"); private static readonly string Js = HttpContext.Current.Server.MapPath(".") + @"\printer-svr.js"; private static readonly string UserFiles = HttpContext.Current.Server.MapPath("~/userfiles/print"); public new void ProcessRequest(HttpContext context) { try { // http://localhost:1001/printer/printer_server.ashx?method=print&url=http%3A%2F%2Flocalhost%3A1001%2Ftekphoria%2Fallan-brunskill-cv.html2&format=jpg var method = context.Request["method"]; if (method == "print") { var url = context.Request["url"]; var format = context.Request["format"]; var filename = Print(url, format); context.Response.Write(JsonConvert.SerializeObject(new {filename})); } if (method == "status") { } if (method == "stop") { } //throw new HttpException("Method not recognised"); } catch (Exception ex) { HandleError(ex); } finally { } } public string Print(string url, string format) { string fulltempfilename = Path.Combine(UserFiles, ToUrlSlug(url)) + "." + format; var clearedDate = (DateTime?)HttpContext.Current.Application["printcleared"]; if (clearedDate == null) HttpContext.Current.Application["printcleared"] = DateTime.Now; if (DateTime.Now.AddSeconds(-60) > clearedDate.Value) { foreach (var file in Directory.GetFiles(UserFiles)) if (new FileInfo(file).CreationTime < DateTime.Now.AddSeconds(-60)) try { File.Delete(file); } catch {} HttpContext.Current.Application["printcleared"] = DateTime.Now; } //try { File.Delete(fulltempfilename); } catch { } //var validator = new PrintServerValidator(); //ValidationResult validationResult = validator.Validate(data); //if (!validationResult.IsValid) //{ // return new // { // validationResult // }; //} const string empty = "XXXXXX"; string command = string.Format("\"{0}\" \"{1}\" \"{2}\" \"{3}\" \"{4}\" \"{5}\" \"{6}\"", Phantom, Js, url, fulltempfilename, "A4", "30000", empty) .Replace("\"" + empty + "\"", string.Empty) .Trim(); //HttpContext.Current.Response.Write(command); //HttpContext.Current.Response.Flush(); // "C:\Program Files\iisnode\www\app2\website\components\phantom\phantomjs.exe" "C:\Program Files\iisnode\www\app2\website\printer\printer-svr.js" "http://www.clarks.co.uk/" "C:\Program Files\iisnode\www\app2\website\userfiles\httpwwwclarkscouk.png" "A4" "20000" // "C:\Program Files\iisnode\www\app2\website\components\phantom\phantomjs.exe" --proxy=127.0.0.1:8888 "C:\Program Files\iisnode\www\app2\website\printer\printer-svr.js" "http://localhost:1001/tekphoria/allan-brunskill-cv.html" "C:\Program Files\iisnode\www\app2\website\userfiles\httplocalhost1001tekphoriaallan-brunskill-cvhtml.pdf" "A4" "20000" // "C:\Users\allan2\Documents\GitHub\Tekphoria-Web\website\components\phantom\phantomjs.exe" "C:\Users\allan2\Documents\GitHub\Tekphoria-Web\website\printer\printer-svr.js" "http://www.tekphoria.co.uk/tekphoria/allan-brunskill-cv.html" "C:\Users\allan2\Documents\GitHub\Tekphoria-Web\website\userfiles\print\httplocalhost1001tekphoriaallan-brunskill-cvhtml.pdf" "A4" "60000"; try { var proc = new Process { StartInfo = new ProcessStartInfo(command) { RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false, CreateNoWindow = true } }; //proc.Start(); //proc.WaitForExit(60000); } catch (Exception) { throw; } // Cache.Insert(Guid.NewGuid().ToString(), status.Doing, null, DateTime.MaxValue, new TimeSpan(0, 0,40)); //Cache.Insert(key, status.Done, null, DateTime.MaxValue, new TimeSpan(0, 0, 40)); // Response.Redirect(tempfilename); // HttpContext.Current.Response.Write(tempfilename); return fulltempfilename; } public static string Base64Encode(string plainText) { byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText); return Convert.ToBase64String(plainTextBytes); } public static string Base64Decode(string base64EncodedData) { byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedData); return Encoding.UTF8.GetString(base64EncodedBytes); } //public object GetStatus(dynamic data) //{ // var file = GetName(data); // string filename = null; // if (file != null) // { // filename = file.name; // } // var exists = File.Exists(filename); // if (exists) // { // var name = new FileInfo(filename).Name; // return new { res = true, file = name }; // } // return new { res = false, file = "" }; //} public static string ToUrlSlug(string value) { //First to lower case value = value.ToLowerInvariant(); //Remove all accents byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(value); value = Encoding.ASCII.GetString(bytes); //Replace spaces value = Regex.Replace(value, @"\s", "-", RegexOptions.Compiled); //Remove invalid chars value = Regex.Replace(value, @"[^a-z0-9\s-_]", "", RegexOptions.Compiled); //Trim dashes from end value = value.Trim('-', '_'); //Replace double occurences of - or _ value = Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled); return value; } } public class PrintServerValidator : AbstractValidator<JObject> { public PrintServerValidator() { RuleFor(x => x.GetValue("format").ToString()) .Must(x => new[] { "png", "jpg", "pdf" }.Contains(x)) .WithMessage("The file format is invalid.") .WithName("format"); RuleFor(x => x.GetValue("url").ToString()) .Must(BeValidUri) .WithMessage("The url must be valid.") .WithName("url"); RuleFor(x => x.GetValue("url").ToString()) .Must(BeAvailable) .WithMessage("The endpoint must be available.") .WithName("url"); RuleFor(x => (int)x.GetValue("renderTime")) .InclusiveBetween(10000,60000) .WithName("Render Time"); } private bool BeAvailable(JObject data, string arg2, PropertyValidatorContext ctx) { try { string url = data.GetValue("url").ToString(); using (var wc = new WebClient()) wc.DownloadString(url); return true; } catch (Exception ex) { ex.ToString(); } return false; } private bool BeValidUri(JObject data, string arg2, PropertyValidatorContext ctx) { { try { string url = data.GetValue("url").ToString(); var uri = new Uri(url); return true; } catch (Exception ex) { ex.ToString(); } return false; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; namespace Tests.SchemaOrg { [TestFixture] public class tests { [Test] public void CanGenerateScema() { string result = testbase.GetEmbeddedText("schema-org-json"); var strongobj = JsonConvert.DeserializeObject(result); string.IsNullOrWhiteSpace(result).Should().BeFalse("the resource should have content"); } } } <file_sep>using System; using FluentValidation.Results; using Newtonsoft.Json.Linq; namespace Tekphoria.Web.linkr { public partial class NewLink : LinkrPage { protected void Page_Load(object sender, EventArgs e) { try { if (IsPostBack) { ErrorPanel.Visible = InfoPanel.Visible = SuccessPanel.Visible = false; string href2 = href.Value.Trim().Replace("http://", ""); href2 = string.Concat("http://", href2); var data = new JObject(); data.Add("href", href2); data.Add("textof", textof.Value.Trim()); data.Add("descof", descof.Value.Trim()); data.Add("ishidden", isHidden.Checked ? 1 : 0); data.Add("user_id", GetNonEmptyCookie("UserId")); dynamic callresult = svr.InsertLink(data); ValidationResult vr = callresult.result; if (vr.Errors.Count == 0) SuccessPanel.Msg = "The link has been added successfully"; else { foreach (ValidationFailure error in vr.Errors) ErrorPanel.Msg += "<li>" + error.ErrorMessage; } } } catch (Exception ex) { ErrorPanel.Msg += "<li>" + ex.Message; } finally { svr.CloseConnections(); } } } } <file_sep>/// <reference path="../global_js/App.ServiceClient.ts" /> /// <reference path="../global_js/App.GlobalCommon.ts" /> module printer { export class PrinterServerClient extends App.ServerClientBase { constructor() { super("printer_server.ashx") } } }<file_sep>/// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="wb.userclasses.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> module WB { /* ========================================================================================= */ export class Log_Item { constructor( public id: number, public board_id: string, public story_id: number, public task_id: string, public user_id: string, public textof: boolean, public display_text: string, public date_created: string, public action: number ) { } } export class LogController { public static SHOW_TASK_LOG(id: number) { LogView.render({ task_id: id }); } } export class LogView { constructor() { } public static render(args: any) { var client = new WB.ScrumboServerClient() var act = client.CallMethod("GetTaskLogItems", args); $.when(act).then(data => { data.log_items.forEach(t=> { t.fuzzy_date = moment.utc(t.date_created).fromNow() t.action_name = data.actions[t.action]; App.ViewEngine.renderview(this.getTemplate(), data) } ) }); } static getTemplate(): string { var tmp = "<div class='logitems clearfix'>" + "<h1>Task Activity</h1>" + "{{#log_items}}<div class=logitem>" + "<span class='text'>{{action_name}} {{&textof}}</span>" + "<span class='date'>{{fuzzy_date}}</span>" + "</div>{{/log_items}}</div>" return tmp; } static getHtml(data) { //Enumerable.From(data.log_items).ForEach((logitem: Log_Item) => { // var actionname = this.getActionName(logitem.action, data.actions); // var user = this.getUserName(logitem.user_id, data.users) // var fuzzytime = App.GlobalCommon.prettyDate(logitem.date_created); // logitem.display_text = user + " " + " <br> " + fuzzytime + " <br> " + actionname + " [" + logitem.task_id + "] " + logitem.textof //}) return App.ViewEngine.getHtml(this.getTemplate(), data); } } }<file_sep>var WB; (function (WB) { var MiscController = (function () { function MiscController() { } MiscController.show404 = function () { alert("not found"); }; return MiscController; })(); WB.MiscController = MiscController; })(WB || (WB = {})); <file_sep>var App; (function (App) { var CustomViewEngine = (function () { function CustomViewEngine() { } CustomViewEngine.renderview = function (viewname, data, partials) { var html = Mustache.render(viewname, data, partials); this.setAppHtml(html); return html; }; CustomViewEngine.getHtml = function (viewname, data, partials) { return Mustache.render(viewname, data, partials); }; CustomViewEngine.setAppHtml = function (html) { amplify.store("last_page", window.location.toString()); this.getAppEl().html(html); }; CustomViewEngine.getAppEl = function () { return $("#app"); }; CustomViewEngine.ClearScreen = function () { this.getAppEl().html(""); }; CustomViewEngine.ReloadPage = function () { }; return CustomViewEngine; })(); App.CustomViewEngine = CustomViewEngine; })(App || (App = {})); <file_sep>using System; using System.Text.RegularExpressions; namespace Tekphoria.Web.Server.Common.Routing { public static class RouterExtentions { public static string CleanUrl(this string incoming) { var check = incoming ?? string.Empty; return check.Trim(new[] { '/', '\\' }).ToLowerInvariant(); } public static string GenerateSlug(this string phrase) { string str = RemoveAccent(phrase).ToLower(); str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); str = Regex.Replace(str, @"\s+", " ").Trim(); str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); str = Regex.Replace(str, @"\s", "-"); // hyphens return str; } public static string RemoveAccent(this string txt) { byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt); return System.Text.Encoding.ASCII.GetString(bytes); } public static bool IsNumber(this string input) { int n; return int.TryParse(input, out n); } public static bool IsToken(this string input) { if (string.IsNullOrWhiteSpace(input)) return false; return input.StartsWith("{") && input.EndsWith("}"); } public static bool IsOptionalToken(this string input) { if (string.IsNullOrWhiteSpace(input)) return false; return input.StartsWith("{?") && input.EndsWith("}"); } public static string CleanToken(this string input) { if (string.IsNullOrWhiteSpace(input)) return input; return input.Replace("{", "") .Replace("{", "") .Replace("?","") .Replace("}", ""); } public static bool Matches(this IRouteInfo r1, IRouteInfo r2) { string[] r1Segments = new string[Math.Max(r1.UriSegments.Length,r2.UriSegments.Length)]; // populate tmp list for (int i = 0; i < r1.UriSegments.Length; i++) r1Segments[i] = r1.UriSegments[i]; // wipe tokens and from r1 for (int i = 0; i < r2.UriSegments.Length; i++) if (r2.UriSegments[i].IsToken()) r1Segments[i] = null; var sig = string.Join("", r1Segments); return string.Equals(sig, r2.Comparator, StringComparison.OrdinalIgnoreCase); } public static string CleanForComparision(this string input) { var p = input; p = input.Replace("/", string.Empty); if (string.IsNullOrWhiteSpace(input)) return string.Empty; var res = new string(input.ToCharArray()); res = res.Replace(@"/", string.Empty); res = Regex.Replace(res, @"\{([^}]+)}", string.Empty); return res; } } } <file_sep>/// <reference path="../../global_js/App.ServiceClient.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="ScrumboServerClient.ts" /> /// <reference path="WB.Storage.ts" /> /// <reference path="WB.Common.ts" /> module WB { /* ========================================================================================= */ export class StoryController { public static STORY_GET(id: string) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("StoryGet", { id: id }) $.when(action).then(resp => StoryEditView.render(resp)) } public static STORY_ADD_TO_BOARD(boardid: string) { WB.StoryAddView.render(boardid); } public static STORY_DELETE(storyId) { StoryDeleteView.render({ id: storyId }); } } /* ========================================================================================= */ export class StoryView { public static render(data) { this.setStatus(data) App.ViewEngine.renderview(this.getTemplate(), data); } public static munged(data, boardhash): string { data.board_hash = boardhash data.textof = App.GlobalCommon.uiify(data.textof); this.setStatus(data) return App.ViewEngine.getHtml(this.getTemplate(), data); } static setStatus(data) { if (data && !data.status) { data.status = "TODO"; } } static getTemplate(): string { if (!this.hasOwnProperty("val")) { var lines = [] lines.push("<div class='story clearfix' data-id={{id}}>") lines.push("{{&textof}}") lines.push("<div class='storybar clearfix'>") lines.push("<div class=''>") lines.push("<a alt='view and edit details' class='btn btn-link btn-xs' href='#story/{{id}}'>edit</a> ") lines.push("<a alt='delete story' class='btn btn-link btn-xs' href='#story/{{id}}/delete'>delete</a> ") lines.push("<a class='btn btn-default btn-xs' alt='add task' href='#task/addtostory/{{id}}/{{board_hash}}'>+task</a> ") lines.push("<a class='btn btn-default btn-xs' alt='add task' href='#story/{{id}}/addfile/{{board_hash}}'>+file</a> ") lines.push("</div>") lines.push("</div>") lines.push("</div>") this["val"]=lines.join("") } return this["val"] } } /* ========================================================================================= */ export class StoryDeleteView { public static render(data) { App.ViewEngine.renderview(this.getTemplate(), data); $("#btnsubmit").on("click", (e) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("StoryDelete", data) $.when(act).then(resp => window.history.back(1)); }) } static getTemplate() { var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') var hash = App.GlobalCommon.inputstring('hash', 'hash', "{{hash}}", '', 'hidden') var form = App.GlobalCommon.form('Delete Story?', hash + id) return form; } } /* ========================================================================================= */ export class StoryChangeStatusView { private static render(data: any) { $("body").off("click").on("click", ".btn_status", (e) => { e.preventDefault(); var id = $(e.target).attr("data-id"); var status = $(e.target).attr("data-status"); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("StorySetStatus", { id: id, status: status }) $.when(act).then((resp) => { $("#BoardChangeStatusView").prepend("<div id=changeOk class='alert alert-success'>Done, going back to board...</div>") .fadeOut() .fadeIn() setTimeout(() => window.history.back(1), 3000); } ); }); return App.ViewEngine.renderview(this.getTemplate(), data) } public static getHtml(data) { return this.render(data); } static getTemplate() { var form = "<div id='BoardChangeStatusView'><h3>Story Status</h3>" + " <div class=''>CURRENT: {{status}}</div>" + "<br><br>Change to : <br>" + " <a class='btn btn-primary btn_status' data-id='{{id}}' data-status='TODO' href='#'>To Do</a>" + " <a class='btn btn-primary btn_status' data-id='{{id}}' data-status='INPROGRESS' href='#'>In Progress</a>" + " <a class='btn btn-primary btn_status' data-id='{{id}}' data-status='DONE' href='#'>Done</a>" + " <a class='btn btn-primary btn_status' data-id='{{id}}' data-status='ARCHIVE' href='#'>Archive</a>" + "</div>" return App.GlobalCommon.container(form); } } /* ========================================================================================= */ export class StoryEditView { public static render(data) { var setstatus = StoryChangeStatusView.getHtml(data); var wrapper = "<div class=form-wrap>" + this.getTemplate() + setstatus + "</div>" App.ViewEngine.renderview(wrapper, data); $("#btnsubmit").off("click").on("click", (e) => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("StoryUpdateText", form) $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1))) }) } static getTemplate() { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{textof}}', '', "4") var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-edit'></span> Story Details</h2>", textof + id) return App.GlobalCommon.container(form); } } /* ========================================================================================= */ export class StoryAddView { public static render(hash: string) { App.ViewEngine.renderview(this.getTemplate(hash), {}); $("#btnsubmit").off("click").on("click", (e) => { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("StoryAddToBoard", data) $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1))); }) } static getTemplate(hash: string) { var nameof = App.GlobalCommon.textarea('textof', 'textof', '', '', "4") var hash = App.GlobalCommon.inputstring('hash', 'hash', hash, '', 'hidden') var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-leaf'></span> Add Story to board</h2>", nameof + hash) return App.GlobalCommon.container(form); } } /* ========================================================================================= */ export class Story { constructor( public id: number, public priority: number, public textof: string, public sort_order: number, public status: string ) { } } } <file_sep>/// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="wb.storage.ts" /> /// <reference path="wb.logclasses.ts" /> /// <reference path="wb.taskclasses.ts" /> /// <reference path="wb.interfaces.ts" /> /// <reference path="wb.errorclasses.ts" /> /// <reference path="WB.StoryClasses.ts" /> /// <reference path="ScrumboServerClient.ts" /> var WB; (function (WB) { var Board = (function () { function Board(id, sort_order, nameof, columns, stories, tasks) { this.id = id; this.sort_order = sort_order; this.nameof = nameof; this.columns = columns; this.stories = stories; this.tasks = tasks; } return Board; })(); WB.Board = Board; var BoardSummary = (function () { function BoardSummary(id, nameof) { this.id = id; this.nameof = nameof; } return BoardSummary; })(); WB.BoardSummary = BoardSummary; var BoardController = (function () { function BoardController() { } BoardController.BOARDS_LIST = function () { var boards = []; var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardsList", {}); $.when(action).then(function (resp) { return BoardsView.render(resp); }); }; BoardController.BOARD_ADD = function () { BoardAddView.render(); }; BoardController.BOARD_DELETE = function (hash) { DeleteBoardView.render(hash); }; BoardController.BOARD_GET = function (hash) { var _this = this; var client = new WB.ScrumboServerClient(); var req1 = client.CallMethod("BoardGetByHash", { hash: hash }); $.when(req1).then(function (resp1) { var accountClient = new Account.AccountClient(); var req2 = accountClient.CallMethod("GetUsersById", { id_list: Enumerable.From(resp1.tasks).Select(function (t) { return t.user_id; }).Distinct().ToArray().join(',') }); $.when(req2).then(function (resp2) { return _this.HandleBoardResponse(resp1, resp2); }); }); }; BoardController.BOARD_GET_SIMPLE = function (hash) { var _this = this; var client = new WB.ScrumboServerClient(); var req1 = client.CallMethod("BoardGetByHash", { hash: hash }); //var getUsers = () => $.when(req1).then(function (resp1) { var accountClient = new Account.AccountClient(); var req2 = accountClient.CallMethod("GetUsersById", { id_list: Enumerable.From(resp1.tasks).Select(function (t) { return t.user_id; }).Distinct().ToArray().join(',') }); $.when(req2).then(function (resp2) { return _this.HandleBoardResponse(resp1, resp2, "simple"); }); }); }; BoardController.HandleBoardResponse = function (boardresp, usersresp, viewtype) { var vdata = boardresp; vdata.users = usersresp.user_list; if (vdata.board) { if (viewtype) { BoardViewSimple.render(vdata); } else { BoardView2.render(vdata); } } else { window.routie("boards"); } }; BoardController.BOARD_DELETE_REPLY = function () { }; BoardController.BOARD_GET_CONFIGURATION = function (hash) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetConfiguration", { hash: hash }); $.when(action).then(function (resp) { return BoardConfigView.render(resp); }); }; BoardController.BOARD_GET_ARCHIVE = function (hash) { var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardGetArchiveByHash", { hash: hash }); $.when(act).then(function (resp) { return BoardArchiveView.render(resp); }); }; BoardController.USER_ADD_SHARED_BOARD = function (data) { AddSharedBoardView.render(); }; return BoardController; })(); WB.BoardController = BoardController; /* ========================================================================================= */ var BoardViewSimple = (function () { function BoardViewSimple() { } BoardViewSimple.render = function (data) { App.ViewEngine.renderview(this.getTemplate(data), data); }; BoardViewSimple.getTemplate = function (data) { var lines = []; lines.push("<div class='container'>"); lines.push("<h2>{{board.nameof}}</h2>"); lines.push("<h3>{{&board.more_info}}</h3>"); lines.push("<ul>"); Enumerable.From(data.columns).ForEach(function (col) { lines.push('<h4>' + col + '</h4>'); }); Enumerable.From(data.stories).OrderBy(function (s) { return s.sort_order; }).ForEach(function (story) { lines.push("<li><h4>#" + story.id + " " + story.textof + "</h4></li>"); lines.push("<ul>"); Enumerable.From(data.tasks).Where(function (t) { return t.story_id === story.id; }).OrderBy(function (t) { return t.sort_order; }).ForEach(function (t) { var user = BoardView2.findUser(t.user_id, data.users); t.display_name = user.display_name; lines.push("<li>" + t.status.toLocaleUpperCase() + " " + t.textof + " by " + user.display_name + "</li>"); }); lines.push("</ul>"); }); lines.push("</ul>"); lines.push("</div>"); return lines.join(""); }; return BoardViewSimple; })(); WB.BoardViewSimple = BoardViewSimple; var BoardView2 = (function () { function BoardView2() { } BoardView2.findUser = function (id, users) { for (var i = 0; i < users.length; i++) { if (users[i].id === id) { return users[i]; } } return { display_name: 'unknown' }; }; BoardView2.render = function (data) { var _this = this; amplify.store("last_board_hash", data.board.hash); $("#custom_css").remove(); if (data.board.custom_css) { $("link").last().after("<style id=custom_css>" + data.board.custom_css + "</style>"); } ; if (data.board.extra_status_2) data.columns.splice(2, 0, data.board.extra_status_2); if (data.board.extra_status_1) data.columns.splice(2, 0, data.board.extra_status_1); var rows = ""; Enumerable.From(data.stories).OrderBy(function (s) { return s.sort_order; }).ForEach(function (story) { rows += "<tr data-storyid=" + story.id + ">"; rows += "<td valign=top align=center>" + WB.StoryView.munged(story, data.board.hash) + "</td>"; Enumerable.From(data.columns).ForEach(function (col, idx) { rows += "<td valign=middle align=center><div class='tasks' data-storyid='" + story.id + "' data-status='" + col + "'>"; Enumerable.From(data.tasks).OrderBy(function (t) { return t.sort_order; }).ForEach(function (t) { if (t.story_id === story.id && t.status === col) { var user = _this.findUser(t.user_id, data.users); t.display_name = user.display_name; t.log_notes = Enumerable.From(data.log_notes).Where(function (ln) { return ln.task_id == t.id; }).ToArray(); rows += WB.TaskView.getHtml(t); } }); rows += "</div></td>"; }); rows += "</tr>"; }); if (data.stories.length < 6) { Enumerable.RangeTo(data.stories.length, 5).ForEach(function (i) { rows += "<tr>"; Enumerable.RangeTo(0, data.columns.length).ForEach(function (i) { rows += "<td></td>"; }); rows += "</tr>"; }); } data.rowsHtml = rows; var toolbar = App.ViewEngine.getHtml(this.getToolBarTemplate(), data); var takmoreView = WB.TaskMoreBarView.getHtml({ id: 0 }); WB.TaskMoreBarView.setEvents(); App.ViewEngine.renderview(this.getTemplate(), data); $("#board").append(toolbar); $("#board").before(takmoreView); this.makeTasksSortable(); this.makeStoriesSortable(); this.makeTaskArchivable(true); this.addtaskloglistener(); this.addtaskExpandListener(); this.resizetasks(); }; BoardView2.addLog = function (e) { e.preventDefault(); var taskId = $("#addlogid").val(); var textof = $(".addlogview #textof").val(); var storyId = $(e.currentTarget).first().closest(".tasks").attr("data-storyid"); var boardId = $("#board").attr("data-id"); var client = new WB.ScrumboServerClient(); client.CallMethod("InsertLogItem", { board_id: boardId, story_id: storyId, id: taskId, textof: textof, action: "NOTE" }); }; BoardView2.addtaskloglistener = function () { $(".addlog").off("click").on("click", function (e) { e.preventDefault(); $(".addlogview").remove(); $(".addlog").show(); var id = $(e.currentTarget).attr("data-id"); var view = WB.TaskAddLogView.getHtml({ id: id }); var target = $(e.currentTarget); var task = target.closest(".task"); var lognotes = task.find(".lognotes").first(); task.after(view); $("#textof").focus(); $("#btnaddlog").off("click").on("click", function (e) { e.preventDefault(); var taskId = $("#addlogid").val(); var textof = $(".addlogview #textof").val(); var storyId = $(e.currentTarget).first().closest(".tasks").attr("data-storyid"); var boardId = $("#board").attr("data-id"); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("InsertLogItem", { board_id: boardId, story_id: storyId, id: taskId, textof: textof, action: "29" }); $.when(act).then(function () { var logNoteRow = WB.LogNoteRowView.getHtml(new WB.LogNote(textof)); lognotes.prepend(logNoteRow); $(".addlogview").fadeOut(); }); }); App.GlobalCommon.clearTimers(); var timerid = setTimeout(function () { return $(".addlogview").remove(); }, 60000); App.GlobalCommon.timers.push(timerid); }); }; BoardView2.addtaskExpandListener = function () { $(".task .more").off("click").on("click", function (e) { e.preventDefault(); var task = $(e.currentTarget).closest(".task"); var foot = task.find(".task-foot").first(); var height = task.height(); foot.slideDown(); var timedfunc = function (task) { task.css({ height: height }); $(".task-foot").slideUp(); }; setTimeout(function () { return timedfunc(task); }, 60000); }); }; BoardView2.resizetasks = function () { var tasks = $(".task"); var width = tasks.first().width(); var larger = width * 1.6; Enumerable.From(tasks).ForEach(function (t) { var ttext = $(t).find(".ttext"); var length = ttext.text().length; if (length > 200) { $(t).width(larger); } }); }; BoardView2.makeTasksSortable = function () { var tasklists = $(".tasks"); tasklists.sortable({ connectWith: ".tasks", cursor: "move", placeholder: 'hover', distance: 1, tolerance: "pointer", start: function (event, ui) { var id = $(ui.item).attr("data-id"); var tasks = $(ui.item).parent(); var storyId = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var startIndex = ui.item.index(); var startData = '' + storyId + status + startIndex; // create a key to determin current state so as not to update unecessarily tasks.attr('data-start_data', startData); }, stop: function (event, ui) { var tasks = $(ui.item).parent(); var boardId = $("#board_id").val(); var tasksAll = tasks.find(".task"); var storyId = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var id = $(ui.item).attr("data-id"); var newIndex = ui.item.index(); // read start data to determin id a server method needs to be sent var startData = tasks.attr('data-start_data'); var newData = '' + storyId + status + newIndex; if (newData === startData) { return; } else { if (status === 'archive') { WB.TaskController.TASK_UPDATE_STATUS({ id: id, status: 'archive' }); return; } var taskOrdering = Enumerable.From(tasksAll).Select(function (t) { return +$(t).attr("data-id"); }).ToArray(); WB.TaskController.TASK_MOVE({ board_id: boardId, story_id: storyId, id: id, status: status, task_ordering: taskOrdering }); } } }).disableSelection(); }; BoardView2.makeStoriesSortable = function () { if (!document.hasOwnProperty("ontouchend")) { $("#board tbody").sortable({ placeholder: 'hover', cursor: "move", stop: function (event, ui) { var stories = $(ui.item).parent(); var stories_all = stories.find(".story"); var id = $(ui.item).attr("data-storyid"); var story_order = Enumerable.From(stories_all).Select(function (s) { return +$(s).attr("data-id"); }).ToArray(); var data = { id: id, story_order: story_order }; var client = new WB.ScrumboServerClient(); client.CallMethod("BoardSortStory", data); } }); } }; BoardView2.makeTaskArchivable = function (removeAfter) { $("body").off("click", ".btn_status").on("click", ".btn_status", function (e) { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); var act = client.CallMethod("TaskUpdateStatus", data); $.when(act).then(function (resp) { if (removeAfter) { var selector = $(".task[data-id='" + id + "']"); // $(selector).fadeOut() selector.css({ position: 'absolute', 'z-order': 1000 }).animate({ 'margin-left': '3000px' }, 2000, function () { return selector.remove(); }); } else { window.location.reload(); } }); }); }; BoardView2.getTemplate = function () { if (this.hasOwnProperty("tmpl")) { } else { var lines = []; lines.push("<table width=100%>"); lines.push("<tr>"); lines.push("<td>"); lines.push("<div class='board-header'><h2 class='board-name'><span class='board-title'>{{board.nameof}}</span></h2>"); lines.push("<div class='board-moreinfo'>{{&board.more_info}}</div>"); lines.push("</div></td>"); lines.push("<td align=right>"); lines.push("<div class='pagination-right'>"); lines.push("<a href='#boards' class='btn btn-default btn-xs'>All Boards</a>"); lines.push(" <a href='#board/{{board.hash}}/simple' class='btn btn-default btn-xs'>List View</a> "); lines.push(" <a href='#board/{{board.hash}}/config' class='btn btn-default btn-xs'>Configure</a> "); lines.push(" <a href='#board/{{board.hash}}/archive' class='btn btn-default btn-xs'>Archive</a> "); lines.push("</div>"); lines.push("</td>"); lines.push("</tr>"); lines.push("</table>"); lines.push("<table id='board' class='table' align=center data-id={{board.hash}}>"); lines.push("<thead>"); lines.push("<th>Story <a class='btn btn-default btn-xs' href='#board/{{board.hash}}/addstory'>Add</a></th>"); lines.push("{{#columns}}<th>{{.}}</th>{{/columns}}"); lines.push("</tr>"); lines.push("</thead>"); lines.push("<tbody>"); lines.push("{{&rowsHtml}}"); lines.push("</tbody>"); lines.push("</table>"); lines.push("{{&board.taskMoreBarViewHtml}}"); lines.push("<input type=hidden id=board_id value='{{board.hash}}'></input>"); this["tmpl"] = lines.join(""); } return this["tmpl"]; }; BoardView2.getToolBarTemplate = function () { return "<div>" + "</div>"; }; BoardView2.timerids = []; return BoardView2; })(); WB.BoardView2 = BoardView2; /* ========================================================================================= */ var BoardConfigView = (function () { function BoardConfigView() { } BoardConfigView.render = function (boardConfigData) { App.ViewEngine.renderview(this.getTemplate(), boardConfigData); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var formdata = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardSetConfiguration", formdata); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1)); }); }); }; BoardConfigView.getTemplate = function () { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '{{board.nameof}}', 'The name of the board', 'text'); // var top = App.GlobalCommon.inputstring('top_status', 'top_status', '{{board.top_status}}', 'Status for the top section', 'text') var info = App.GlobalCommon.textarea('more_info', 'more_info', '{{board.more_info}}', 'Extra infomation to be displayed.', '5'); var custom_css = App.GlobalCommon.textarea('custom_css', 'custom_css', '{{board.custom_css}}', 'The Custom css values.', '5'); var status1 = App.GlobalCommon.inputstring('extra_status_1', 'extra_status_1', '{{board.extra_status_1}}', 'Status Column 1 after between inprogress and done.', 'text'); var status2 = App.GlobalCommon.inputstring('extra_status_2', 'extra_status_2', '{{board.extra_status_2}}', 'Status Column 2 after between inprogress and done.', 'text'); var hash = App.GlobalCommon.inputstring('hash', 'hash', '{{board.hash}}', '', 'hidden'); return App.GlobalCommon.container("<h2><span class='glyphicon glyphicon-cog'></span> Board Configuration</h2><a class-'btn btn-link' href='#board/{{board.hash}}/delete'>Delete board</a><hr>" + App.GlobalCommon.form('Board Details', nameof + info + status1 + status2 + custom_css + hash)); }; return BoardConfigView; })(); WB.BoardConfigView = BoardConfigView; /* ========================================================================================= */ var BoardTrashView = (function () { function BoardTrashView() { } BoardTrashView.render = function () { this.registerEvents(); App.ViewEngine.renderview(this.getTemplate(), {}); }; BoardTrashView.getHtml = function () { return this.getTemplate(); }; BoardTrashView.registerEvents = function () { }; BoardTrashView.getTemplate = function () { this.registerEvents(); return "<div class='trash'><img src='/img/trash.png'/></div>"; }; return BoardTrashView; })(); WB.BoardTrashView = BoardTrashView; /* ========================================================================================= */ var BoardAddView = (function () { function BoardAddView() { } BoardAddView.getFormInputsAsObject = function () { var form = $("#form1"); return App.GlobalCommon.getFormInputs(form); }; BoardAddView.render = function () { App.ViewEngine.renderview(this.getTemplate(), {}); //events var submitbtn = $("#btnsubmit"); var hash = $("#hash"); submitbtn.on("click", function (e) { e.preventDefault(); hash.val(App.GlobalCommon.createUUID(12, 36)); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardAdd", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(1); }); }); }); }; BoardAddView.getTemplate = function () { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '', 'The name of the board', 'text'); var hash = App.GlobalCommon.inputstring('hash', 'hash', App.GlobalCommon.createUUID(12, 36), '', 'hidden'); var form = App.GlobalCommon.form('<h2>Add a board</h2><hr>', nameof + hash); return App.GlobalCommon.container(form); }; return BoardAddView; })(); WB.BoardAddView = BoardAddView; /* ========================================================================================= */ var BoardsView = (function () { function BoardsView() { } BoardsView.render = function (data) { App.ViewEngine.renderview(this.getTemplate(), data); this.registerEvents(); }; BoardsView.registerEvents = function () { if (!document.hasOwnProperty("ontouchend")) { var boardrows = $("#boards tbody"); boardrows.sortable({ placeholder: 'hover', cursor: "move", stop: function (event, ui) { //var stories = $(ui.item).parent(); var boardsummaries = $(".boardsummary"); var id = $(ui.item).attr("data-boardid"); var boards_order = Enumerable.From(boardsummaries).Select(function (summary) { return $(summary).attr("data-boardid"); }).ToArray(); var data = { id: id, boards_order: boards_order }; var client = new WB.ScrumboServerClient(); client.CallMethod("BoardsSort", data); } }); } }; BoardsView.getTemplate = function () { return "<div class=container><h2><span class='glyphicon glyphicon-list'></span> Boards</h2>" + "<div class='pull-right'><a class='btn btn-success btn-xs' href='#boards/add'>New Board</a> <a class='btn btn-primary btn-xs' href='#boards/addshared'>Add Shared Board</a> </div><br><br>" + "<table id='boards' class='table table-hover'><tbody>" + "{{#BoardSummaries}}" + "<tr data-boardid='{{hash}}' class='boardsummary'><td><a class='' href='#board/{{hash}}'><strong>{{nameof}}</strong></a> </td>" + "<td></td><td><span class=muted>key: {{hash}}</span></td>" + "</tr>{{/BoardSummaries}}" + "</tbody></table></div>"; }; return BoardsView; })(); WB.BoardsView = BoardsView; /* ========================================================================================= */ var DeleteBoardView = (function () { function DeleteBoardView() { } DeleteBoardView.render = function (hash) { App.ViewEngine.renderview(this.getViewTemplate(), { "hash": hash }); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardDelete", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window["routie"]("boards"); }); }); }); }; DeleteBoardView.getViewTemplate = function () { var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-warning-sign'></span> Delete Board and Contents</h2><div class='alert alert-danger'>DANGER ZONE! Actions taken will delete a board</div>", 'To Cancel use the back button or press submit to delete the board' + App.GlobalCommon.inputstring('hash', 'hash', '{{hash}}', '', 'hidden')); return App.GlobalCommon.container(form); }; return DeleteBoardView; })(); WB.DeleteBoardView = DeleteBoardView; /* ========================================================================================= */ var BoardArchiveView = (function () { function BoardArchiveView() { } BoardArchiveView.render = function (data) { var tasksHtml = ''; Enumerable.From(data.tasks).ForEach(function (t) { tasksHtml += WB.TaskView.getHtml(t); }); data.tasksHtml = tasksHtml; var taskMoreBarViewHtml = WB.TaskMoreBarView.render(data); App.ViewEngine.renderview(this.getViewTemplate() + taskMoreBarViewHtml, data); BoardView2.makeTaskArchivable(false); $(".task-foot").show(); $('#archivedtasks').masonry({ itemSelector: '.task' }); }; BoardArchiveView.getViewTemplate = function () { var page = '<div class="clearfix board_archive"><h2>Board Archive</h2><hr><div id="archivedtasks" >{{&tasksHtml}}</div></div>'; return App.GlobalCommon.container(page); }; return BoardArchiveView; })(); WB.BoardArchiveView = BoardArchiveView; var AddSharedBoardView = (function () { function AddSharedBoardView() { } AddSharedBoardView.render = function () { App.ViewEngine.renderview(this.getTemplate(), {}); $("#btnsubmit").off("click").on("click", function (e) { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("UserAddSharedBoard", data); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window["routie"]("boards"); }); }); }); }; AddSharedBoardView.getTemplate = function () { var hash = App.GlobalCommon.inputstring('hash', 'hash', '', 'The shared boards hash', 'text'); // var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') var form = App.GlobalCommon.form('<h2>Link shared board</h2><hr>', hash); return App.GlobalCommon.container(form); }; return AddSharedBoardView; })(); WB.AddSharedBoardView = AddSharedBoardView; })(WB || (WB = {})); <file_sep>module things { export class person { constructor( public fullname: string = "", public image: string = "", public imagealt: string = "", public jobtitle: string = "", public telephone: string = "", public email: string = "", public emailhref: string = "", public emailtitle: string = "", public url: string = "", public urltitle: string = "" ) {} } export class address { constructor( public streetAddress: string = "", public addressLocality: string = "", public addressRegion: string = "", public postalCode: string = "", public addressCountry: string = "" ) {} } export class review { constructor( public reviewname: string = "", public author: string = "", public dateyymmdd: string = "", public datepublished: string = "", public description: string = "", public reviewRating : reviewRating = null ) {} } export class reviewRating { constructor( public worstrating: string = "", public ratingvalue: string = "", public bestrating: string = "" ) {} } export class product { constructor( public name: string = "", public image: string = "", public imagealt: string = "", public reviews : review[] = [] ) {} } export class article { constructor( public title: string = "", public heading: string = "", public content: string = "", public date: string = "" ) {} } export class htmlPageModel { constructor( public title: string = "Tekphoria Hompage", public description: string = "Tekphoria Hompage Description", public content: string = "Tekphoria Limited Software development - fast efficient industrial strength web applications." ) {} } export class logomain { constructor( public src: string = "/global_img/tekphoria.logo.01.jpg", public alt: string = "Tekphoria Main Logo" ) {} } }<file_sep>using System.Data; using MySql.Data.MySqlClient; namespace Tekphoria.Server.Common { public class DatabaseStructureTest { private readonly IDbConnection _connection; public DatabaseStructureTest(IDbConnection connection) { } public IDbConnection GetOpenConnection() { var con = new MySqlConnection(Config.GetProspectsConnectionString.Value); con.Open(); return con; } } }<file_sep>var App; (function (App) { var View_EditProspect = (function () { function View_EditProspect() { } View_EditProspect.init = function (data) { var _this = this; var client = new App.ProspectorServerClient(); var prospectdata = client.CallMethod("EditProspect", data); $.when(prospectdata).then(function (data) { return _this.render(data); }, null); }; View_EditProspect.render = function (data) { data.user_id = amplify.store('UserId'); var images = []; Enumerable.From(data.files).Where(function (f) { return f.file_type === 'IMAGE'; }).ForEach(function (f) { var image = {}; image.thumb = f.filename.replace("]_", "]_t_"); image.filename = f.filename; images.push(image); }); data.files = Enumerable.From(data.files).Where(function (f) { return f.file_type !== 'IMAGE'; }).ToArray(); data.images = images; App.ViewEngine.renderview(this.getTemplate(data), data); $("#location-map").append(View_ProspectsMap.getHtml(data)); View_ProspectsMap.setEvents(data); $("#sale_type_id option[value=" + data.prospect.sale_type_id + "]").first().prop("selected", true); $("#source_type_id option[value=" + data.prospect.source_type_id + "]").first().prop("selected", true); $("#status_id option[value=" + data.prospect.status_id + "]").first().prop("selected", true); $("#detailed_planning_permission").attr('checked', data.prospect.detailed_planning_permission === 1); $("#outline_planning").attr('checked', data.prospect.outline_planning === 1); var touch = 'ontouchend' in document; if (touch) { $("#uploadtouch").show(); $("#uploadnontouch").hide(); } else { $("#uploadtouch").hide(); $("#uploadnontouch").show(); $('#file_upload').uploadify({ 'swf': '/components/uploadify/uploadify.swf', 'uploader': '/components/uploadify/uploadify.ashx', 'buttonText': 'select and upload', 'buttonClass': 'btn btn-small', 'formData': { prospect_id: data.prospect.id }, 'multi': true }); } $("#btn_save_prospect").on("click", function (e) { e.preventDefault(); App.ViewPart.info_hide(); var form = App.GlobalCommon.getFormInputs($("#prospect_form")); var client = new App.ProspectorServerClient(); var resp = client.CallMethod("UpdateProspect", form); $.when(resp).then(function (data) { if (data.validationResult.IsValid) { App.ViewPart.info("Success", "The prospect has been updated."); } else { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } }, null); }); }; View_EditProspect.getTemplate = function (data) { var tab_panel = "<div id='tab-panel'></div>"; var tabs = '<ul id=sections class=" nav nav-tabs">' + '<li class="active"><a id="location-link">Location</a></li>' + '<li class="active"><a id="finance-link">Finance</a></li>' + '<li class="active"><a id="attachments-link">Attachments</a></li>' + '<li class="active"><a id="images-link">Images</a></li>' + '<li class="active"><a id="planning-link">Planning</a></li>' + '<li class="active"><a id="other-link">Other</a></li>' + '</ul> '; var address1 = App.GlobalCommon.textarea('address1', 'address1', '{{prospect.address1}}', 'The Address1', 'text'); var prefix = "prospect"; var postcode = App.GlobalCommon.input_data_string('postcode', 'The Postcode', "prospect"); var price_low = App.GlobalCommon.input_data_string('price_low', 'The Low Price', "prospect"); var price_high = App.GlobalCommon.input_data_string('price_high', 'The High Price', "prospect"); var price_sell = App.GlobalCommon.input_data_string('price_sell', 'The Estimated Sale Price', "prospect"); var source_types = App.GlobalCommon.dropdown('The source type', 'source_type_id', 'source_type_id', data.source_types, ''); var sale_types = App.GlobalCommon.dropdown('The sale type', 'sale_type_id', 'sale_type_id', data.sale_types, ''); var status = App.GlobalCommon.dropdown('The Status type', 'status_id', 'status_id', data.statuses, ''); var detailed_planning_permission = App.GlobalCommon.checkbox('detailed_planning_permission', 'detailed_planning_permission', 'Detailed planning permission', '0'); var outline_planning = App.GlobalCommon.checkbox('outline_planning', 'outline_planning', 'Outline planning', '0'); var upload = App.GlobalCommon.uploadify("Select file[s]"); upload = '<div id="queue"></div><input id="file_upload" name="file_upload" type="file" multiple="true">'; var id = App.GlobalCommon.inputstring("prospect_id", "prospect_id", "{{prospect.id}}", "", "hidden"); var location_info = address1 + postcode; var location_map = "<div id='control-group'><div id='location-map'/></div>"; var location = App.GlobalCommon.div("location-content", "tab-content", "<h5 id=location>Location</h5>" + location_info + location_map); var other = App.GlobalCommon.div("other-content", "tab-content", "<h5 id=other>Other</h5>" + sale_types + source_types + status); var finance = App.GlobalCommon.div("finance-content", "tab-content", "<h5 id=finance>Financial</h5>" + price_low + price_high + price_sell); var planning = App.GlobalCommon.div("planning-content", "tab-content", "<h5 id=planning>Planning</h5>" + detailed_planning_permission + outline_planning); var attachments = App.GlobalCommon.div("attachments-content", "tab-content", "<h5 id=attachments>Attachments</h5> " + upload + "<div class='attachments row row-fluid well offset2'>" + "<ul class='files'>{{#files}}<li><div class='file'><a href='/uskerfiles/files/{{filename}}'>{{filename}}</a></div></li>{{/files}}</ul>" + "</div>"); var images = App.GlobalCommon.div("images-content", "tab-content", "<h5 id=images>Images</h5><div class='images row row-fluid well offset2'>{{#images}} <a href='/userfiles/files/{{filename}}'><img src='/userfiles/files/{{thumb}}'/></a>{{/images}}</div>"); var fields = tab_panel + location + images + attachments + other + finance + planning + id; var form = App.GlobalCommon.form('<h3>{{prospect.address1}} {{prospect.postcode}}</h3>' + tabs, fields, 'btn_save_prospect', 'prospect_form'); return form; }; return View_EditProspect; })(); App.View_EditProspect = View_EditProspect; var View_Prospects = (function () { function View_Prospects() { } View_Prospects.frame = function () { var tmp = ""; tmp += "<div class='row-fluid'>"; tmp += "<div class='sidebar well-small span2'>"; tmp += "<a class='' href='#/newprospect'>New Prospect</a><hr>"; tmp += "<div>Filter</div>"; tmp += "<ul class='nav nav-list'>"; tmp += "<li><a class='filter latest' href='#/prospects'>All / Latest</a></li>"; tmp += "<li><a class='filter open' href='#/prospects/status/open'>Open</a></li>"; tmp += "<li><a class='filter closed' href='#/prospects/status/closed'>Closed</a></li>"; tmp += "</ul>"; tmp += "</div>"; tmp += "<div class='prospect_list span9'>{content}</div>"; tmp += "</div>"; return tmp; }; View_Prospects.getTemplate = function () { var rows = "{{#prospects}}" + "<tr data-id='{{id}}'>" + "<td>#{{id}}</td>" + "<td class='status-{{status}}'>&bull; {{status}}</td>" + "<td class=address1>{{address1}}<br></td><td><small>{{postcode}}</small></td><td>created {{fuzzyCreated}}</td>" + "</tr>{{/prospects}}"; var tmp = ""; tmp += "<ul class='nav nav-tabs'><li class='active'><a href='#/prospects'>Prospects</a></li></ul>"; tmp += "<table id=prospects class='table table-condensed table-hover'>"; tmp += rows; tmp += "</table>"; return this.frame().replace("{content}", tmp); }; View_Prospects.init = function (data) { var _this = this; var client = new App.ProspectorServerClient(); var viewdata = client.CallMethod("GetProspects", data); var cardTemplate = $.get("tmpl/ProspectCardView.html"); $.when(viewdata, cardTemplate).then(function (data, tmpl) { return _this.render(data[0], tmpl[0]); }, null); }; View_Prospects.setData = function (data) { Enumerable.From(data.prospects).ForEach(function (item) { item.fuzzyCreated = moment.utc(item.date_created).fromNow(); }); return data; }; View_Prospects.render = function (data, tmpl) { this.setData(data); if (!tmpl) { tmpl = this.getTemplate(); } var html = App.ViewEngine.renderview(this.frame().replace("{content}", tmpl), data); $(".prospect-card").click(function (e) { e.preventDefault(); var id = $(e.currentTarget).attr("data-id"); window.location.href = "#/prospect/" + id + "/edit"; }); return html; }; return View_Prospects; })(); App.View_Prospects = View_Prospects; var View_DeleteProspect = (function () { function View_DeleteProspect() { } View_DeleteProspect.init = function (data) { this.render(data); }; View_DeleteProspect.render = function (data) { var html = App.ViewEngine.renderview(this.getTemplate(), { id: data.id }); $("#deleteok").click(function (e) { e.preventDefault(); var client = new App.ProspectorServerClient(); var serverdelete = client.CallMethod("DeleteProspect", data); $.when(serverdelete).then(function (data) { App.ViewEngine.ClearScreen(); App.ViewPart.info("Success", "The prospect has been deleted"); }, null); }); $("#deletecancel").click(function (e) { e.preventDefault(); window.history.go(-1); }); return html; }; View_DeleteProspect.getTemplate = function () { var tmp = "<div class='well span3'>"; tmp += "Delete Prospect {{prospect}} <br><br><a class='btn' id='deleteok' href='#/prospect/4/deleteok'>Yes</a> <a class='btn' id='deletecancel' href='#/prospect/4/deleteok'>No</a> "; tmp += "</div>"; return tmp; }; return View_DeleteProspect; })(); App.View_DeleteProspect = View_DeleteProspect; var View_ProspectsMap = (function () { function View_ProspectsMap() { } View_ProspectsMap.getTemplate = function () { var title = ''; var help = '<div class="control-label" for="map-canvas">You can move the pin here to acurately set the location of the property. Enter address and click search to view map.</div>'; var searchbuton = '<div class="controls"><div><input class="input span3" id="query" type="text" placeholder="Enter a search eg postcode" value=""/><button id="btn_map_search" class="btn" type="button">Search</button></div><br>'; var tmp = "<div id='latitude' style='display:none'></div>"; tmp += "<div id='longitude' style='display:none'></div>"; tmp += "<div id='prospect_id' style='display:none'></div>"; tmp += "<div id='map-canvas' style='height: 400px;width: 400px;'>Waiting for search term</div></div>"; return App.GlobalCommon.control(title + help + searchbuton + tmp); }; View_ProspectsMap.getHtml = function (data) { this.setData(data); var html = App.ViewEngine.getHtml(this.getTemplate(), data); return html; }; View_ProspectsMap.setData = function (data) { data.hasLocation = !(!data.prospect.latitude || !data.prospect.longitude); return data; }; View_ProspectsMap.setEvents = function (data) { $("#prospect_id").text(data.prospect.id); if (data.hasLocation) { Component.GoogleMaps.show_location({ latitude: data.prospect.latitude, longitude: data.prospect.longitude }); } $("#btn_map_search").on("click", function (e) { e.preventDefault(); var query = $("#query").val(); if (query && query.length > 2) { Component.GoogleMaps.search_address_2(query); } }); amplify.subscribe("SearchAddress_reply", function (data) { Component.GoogleMaps.show_location({ latitude: data[0].geometry.location.lat(), longitude: data[0].geometry.location.lng() }); }); }; View_ProspectsMap.render = function (data) { this.setData(data); var html = App.ViewEngine.getHtml(this.getTemplate(), data); App.ViewEngine.setAppHtml(html); this.setEvents(data); return html; }; View_ProspectsMap.render_map = function (data) { var google = window["google"]; var mapOptions = { center: data[0].geometry.location, zoom: 18, mapTypeId: google.maps.MapTypeId.SATELLITE }; Component.GoogleMaps.show_map(mapOptions, data); }; View_ProspectsMap.search_address = function (address) { Component.GoogleMaps.search_address_2(address); }; return View_ProspectsMap; })(); App.View_ProspectsMap = View_ProspectsMap; var View_NewProspect = (function () { function View_NewProspect() { } View_NewProspect.init = function (data) { var _this = this; var client = new App.ProspectorServerClient(); var newserverdata = client.CallMethod("NewProspect", data); $.when(newserverdata).then(function (respData) { _this.render(respData); }, null); }; View_NewProspect.render = function (data) { if (data.validationResult && data.validationResult.IsValid === false) { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } else { App.ViewEngine.renderview(this.getTemplate(data), {}); $("#price_low").val("0"); $("#price_high").val("0"); $("#btn_save_prospect").on("click", function (e) { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#prospect_form")); var client = new App.ProspectorServerClient(); var addprospect = client.CallMethod("AddProspect", data); $.when(addprospect).then(function (data) { if (data.validationResult.IsValid) { App.ViewPart.info("Success", "The prospect has added."); } else { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } }, null); }); } }; View_NewProspect.div = function (id, cssclass, content) { var tmp = "<div id='{id}' class='{class}'>{content}</div>"; if (!cssclass) { cssclass = ''; } if (!id) { id = ''; } return tmp.replace('{id}', id).replace('{class}', cssclass).replace('{content}', content); }; View_NewProspect.getTemplate = function (data) { var address1 = App.GlobalCommon.textarea('address1', 'address1', '', 'The Address1', 'text'); var postcode = App.GlobalCommon.inputstring('postcode', 'postcode', '', 'The Postcode', 'text'); var price_low = App.GlobalCommon.inputstring('price_low', 'price_low', '', 'The Low Price', 'text'); var price_high = App.GlobalCommon.inputstring('price_high', 'price_high', '', 'The High Price', 'text'); var sale_types = App.GlobalCommon.dropdown('The sale type', 'sale_type_id', 'sale_type_id', data.sale_types, ''); var source_types = App.GlobalCommon.dropdown('The source type', 'source_type_id', 'source_type_id', data.source_types, ''); var detailed_planning_permission = App.GlobalCommon.checkbox('detailed_planning_permission', 'detailed_planning_permission', 'Detailed planning permission', '0'); var outline_planning = App.GlobalCommon.checkbox('outline_planning', 'outline_planning', 'Outline planning', '0'); var upload = App.GlobalCommon.upload('Please enter a file to upload'); var fields = address1 + postcode + price_low + price_high + sale_types + source_types + detailed_planning_permission + outline_planning; var form = App.GlobalCommon.form('<h4>Add prospect</h4>', fields, 'btn_save_prospect', 'prospect_form'); return form; }; return View_NewProspect; })(); App.View_NewProspect = View_NewProspect; })(App || (App = {})); <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.account { public partial class ChangePassword : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { error_panel.Controls.Clear(); error_panel.Visible = false; success_panel.Visible = false; if (!IsPostBack) { new_password.Text = ""; } else { var ob = new JObject(); new_password.Text = new_password.Text.Trim(); var user_cookie = Request.Cookies.Get("UserId") ?? new HttpCookie("UserId"); var user_id = string.IsNullOrWhiteSpace(user_cookie.Value) ? "0" : user_cookie.Value; ob.Add("user_id", new JValue(user_id)); ob.Add("password", new JValue(new_password.Text)); var accountserver = new AccountServer(); dynamic result = accountserver.UserChangePassword(ob); var validationResult = (ValidationResult)result.validationResult; if (validationResult.Errors.Count > 0) { error_panel.Visible = true; success_panel.Visible = false; foreach (ValidationFailure er in validationResult.Errors) { error_panel.Controls.Add(new Literal { Text = string.Concat("<p>", er.ErrorMessage, "</p>") }); } } else { error_panel.Visible = false; success_panel.Visible = true; input_panel.Visible = false; } } } } }<file_sep>using System; using FluentValidation; using FluentValidation.Validators; namespace Tekphoria.Web.locate { public class LocationArgsValidatior : AbstractValidator<LocationArgs> { public LocationArgsValidatior() { RuleFor(a => a.lat).Must(BeDecimal).Length(3,20).WithMessage("Latitude is invalid"); RuleFor(a => a.lng).Must(BeDecimal).Length(3, 20).WithMessage("Longitude is invalid"); RuleFor(a => a.user_id).Must(BeNumberInRange).WithMessage("User Id is not a number"); } private bool BeDecimal(LocationArgs arg1, string arg2, PropertyValidatorContext arg3) { try { decimal n; decimal.TryParse(arg2, out n); return true; } catch (Exception) { return false; } } private bool BeNumberInRange(LocationArgs arg1, string arg2, PropertyValidatorContext arg3) { try { int n; int.TryParse(arg2, out n); return n > 0 && n < 100000; } catch (Exception) { return false; } } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Web; using Dapper; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.Server.Scrumbo { public class ScrumboServerSetup : ScrumboServer, IHttpHandler { private const string email = "<EMAIL>"; private string board_hash = "6SZUZNVQ786S"; private int user_id; public new void ProcessRequest(HttpContext context) { try { Run(); context.Response.Write("OK"); } catch (Exception ex) { HandleError(ex); } finally { CloseConnection(ScrumboCon); } } public bool IsReusable { get; private set; } public void Run() { CheckMode(); var accountServer = new AccountServer(); user_id = GetUserId(accountServer); // delete the board int id = GetBoardIdFromHash(board_hash); if (id > 0) { JObject data = GetUserObject(); data.Add("hash", new JValue(board_hash)); BoardDelete(data); } var board_id = (int) BoardAdd(GetDemoBoard()).id; int story1_id = StoryAddToBoard(GetDemoStory1(board_id)); var tasks = new[] { "1. White side up. Pre-fold diagonals. Valley-fold the top corner to the center and unfold.", "2. Fold the corner down to the crease from step 1.", "3. Fold the bottom corner up to the edge.", "4. Fold behind.", "5. Unfold step 3." }; for (int i = 0; i < tasks.Count(); i++) TaskAddToStory(GetTask(board_id, story1_id, tasks[i])); var userfiles = AppDomain.CurrentDomain.BaseDirectory + "\\userfiles"; if (!Directory.Exists(userfiles)) Directory.CreateDirectory(userfiles); } private void CheckMode() {} private JObject GetUserObject() { var data = new JObject(); data.Add("user_id", user_id); return data; } private JObject GetTask(int board_id, long story1Id, string text) { // data.textof, data.story_id, board_id, data.css_class JObject data = GetUserObject(); data.Add("board_id", new JValue(board_id)); data.Add("story_id", new JValue(story1Id)); data.Add("textof", new JValue(text)); data.Add("css_class", new JValue(GetColour())); data.Add("hash", new JValue(board_hash)); return data; } private JObject GetDemoStory1(int board_id) { // data.textof, board_id = id, sort_order = 100, status = "TODO" JObject data = GetUserObject(); data.Add("textof", new JValue("User needs to make a traditional origami dragon")); data.Add("board_id", new JValue(board_id.ToString())); data.Add("hash", new JValue(board_hash)); return data; } private object GetDemoBoard() { JObject data = GetUserObject(); data.Add("nameof", new JValue("Paperworx (Demo Board)")); data.Add("hash", new JValue("6SZUZNVQ786S")); return data; } private int GetUserId(AccountServer accountServer) { int id = 0; var data = new JObject(); data.Add("email", new JValue(email)); dynamic query = accountServer.GetUserByEmail(data); List<dynamic> users = query.user_list as List<dynamic> ?? new List<dynamic>(); if (users.Count == 0) id = accountServer.UserAdd(GetDemoUser()); else id = users.First().id; return id; } private JObject GetDemoUser() { var userData = new JObject(); userData.Add("email", new JValue(email)); userData.Add("display_name", new JValue("demo")); userData.Add("password", new JValue("<PASSWORD>")); return userData; } public static string GetColour() { var list = new[] { "taskyellow", "taskgreen", "taskorange", "taskpink", "taskblue", "taskpurple" }; Shuffle(list); return list[GetRandom(list.Length)]; } public static void Shuffle<T>(IList<T> list) { var provider = new RNGCryptoServiceProvider(); int n = list.Count; while (n > 1) { var box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < n * (Byte.MaxValue / n))); int k = (box[0] % n); n--; T value = list[k]; list[k] = list[n]; list[n] = value; } } public static int GetRandom(int max) { var provider = new RNGCryptoServiceProvider(); int n = max; var box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < n * (Byte.MaxValue / n))); int k = (box[0] % n); return k; } public static void CheckDb() {} public void Add_note_count() { string sql = "ALTER TABLE tasks ADD note_count SMALLINT NOT NULL"; GetScrumboConnection().Execute(sql); GetScrumboConnection().Close(); } } } <file_sep>/// <reference path="../../global_js/jquery-1.9.1.d.ts" /> module app { export class starter { public static init() { $(".logo, .nav a").on("click", e=> this.onNavClick(e)); this.show("home") } public static onNavClick(e) { e.preventDefault() var selector = $(e.currentTarget).attr("data-show-content"); this.show(selector) } public static show(contentid) { var content = $("#" + contentid + "-content").html() $("#right-panel").hide().html(content).fadeIn() } } }<file_sep>/// <reference path="../../global_js/jquery-1.9.1.d.ts" /> var app; (function (app) { var starter = (function () { function starter() { } starter.init = function () { //$("[id$=content]").css("height", 1024); //$("[id$=content]").css("height", 1024); // $(".logo, .nav a").on("click", e=> this.onNavClick(e)); this.show("home"); }; starter.onNavClick = function (e) { e.preventDefault(); var selector = $(e.currentTarget).attr("data-show-content"); this.show(selector); }; starter.show = function (contentid) { //$("[id$=content]").hide() var content = $("#" + contentid + "-content").html(); $("#right-panel").hide().html(content).fadeIn("slow"); }; return starter; })(); app.starter = starter; })(app || (app = {})); <file_sep>using System; using System.Linq; namespace Tekphoria.Web.Server.Common.Routing { public class RouteInfo : IRouteInfo { public RouteInfo(string template, Action act) : this(template, null, null, act) { } public RouteInfo(string template, Func<dynamic, dynamic> func = null, dynamic defaultArgs = null, Action act = null) { if (template == null) throw new ArgumentNullException("template"); Template = template.CleanUrl(); Fn = func; Act = act; DefaultArgs = defaultArgs; UriSegments = template.Split(new[] {'/'}, StringSplitOptions.RemoveEmptyEntries); RouteParams = UriSegments.Where(s => s.IsToken()).ToArray(); OptionalParams = UriSegments.Where(s => s.IsOptionalToken()).ToArray(); NoOptionalParams = UriSegments.Where(s => !s.IsToken()).ToArray(); RawSegments = UriSegments.Where(s => !s.IsOptionalToken() && !s.IsToken()).ToArray(); Comparator = string.Join("", NoOptionalParams); } public Action Act { get; private set; } public string[] NoOptionalParams { get; private set; } public string[] RawSegments { get; private set; } public dynamic DefaultArgs { get; private set; } public string Template { get; private set; } public Func<dynamic, dynamic> Fn { get; private set; } public string[] UriSegments { get; private set; } public string[] RouteParams { get; private set; } public string[] OptionalParams { get; private set; } public string Comparator { get; private set; } public dynamic RouteArgs { get; set; } public dynamic Execute() { if (Fn != null) return Fn.Invoke(RouteArgs); if (Act != null) Act.Invoke(); return "void"; } } }<file_sep>module App { export class Common{ public static filesize (fileSizeInBytes) { var i = -1; var byteUnits = [' kB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB']; do { fileSizeInBytes = fileSizeInBytes / 1024; i++; } while (fileSizeInBytes > 1024); return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i]; } } }<file_sep>///// <reference path="../../global_js/jquery-1.9.1.d.ts" /> ///// <reference path="../../global_js/linq-2.2.d.ts" /> ///// <reference path="../../global_js/amplify.d.ts" /> ///// <reference path="../../global_js/jqueryui-1.9.d.ts" /> ///// <reference path="wb.userclasses.ts" /> ///// <reference path="../../global_js/App.ViewEngine.ts" /> //module WB { ///* //========================================================================================= //*/ // export class Log_Item { // constructor( // public id: number, // public board_id: string, // public story_id: number, // public task_id: string, // public user_id: string, // public textof: boolean, // public display_text: string, // public date_created: string, // public action: number // ) { } // } // export class LogView { // public static render(data) { // App.ViewEngine.renderview(this.getTemplate(), data); // } // static getTemplate() : string { // var tmp = ""; // tmp += "<div class='logitems clearfix'><strong>Activity</strong><br>{{#log_items}}<div class=logitem>{{&display_text}}</div>{{/log_items}}</div>" // return tmp; // } // static getActionName(action, actionList) { // return actionList[action].replace("_", " "); // } // static getUserName(id, users) { // var user = Enumerable.From(users).Where((u) => u.id === id).First(); // return user.display_name; // } // public static getHtml(data) { // Enumerable.From(data.log_items).ForEach((logitem: Log_Item) => { // var actionname = this.getActionName(logitem.action, data.actions); // var user = this.getUserName(logitem.user_id, data.users) // var fuzzytime = App.GlobalCommon.prettyDate(logitem.date_created); // logitem.display_text = user + " " + " <br> " + fuzzytime + " <br> " + actionname + " [" + logitem.task_id + "] " + logitem.textof // }) // return App.ViewEngine.getHtml(this.getTemplate(), data); // } // } //}<file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; /// <reference path="../../global_js/App.GlobalCommon.ts" /> var WB; (function (WB) { var ScrumboServerClient = (function (_super) { __extends(ScrumboServerClient, _super); function ScrumboServerClient() { _super.call(this, "scrumbo_server.ashx"); } return ScrumboServerClient; })(App.ServerClientBase); WB.ScrumboServerClient = ScrumboServerClient; })(WB || (WB = {})); <file_sep>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Security.Cryptography; using System.Text; using System.Web; using System.Web.Configuration; using Yahoo.Yui.Compressor; namespace Tekphoria.Web.Server.Handlers { public class AssetHandler : IHttpHandler { private static readonly string basedir = AppDomain.CurrentDomain.BaseDirectory; private static CompilationSection configSection = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation"); public static ConcurrentDictionary<string, StringBuilder> Assets = new ConcurrentDictionary<string, StringBuilder>(); public void ProcessRequest(HttpContext context) { try { string type = context.Request["type"] ?? string.Empty; string load = context.Request["load"] ?? string.Empty; string[] virtualPaths = load.Split(",".ToCharArray()); var etag = GetHashString(load); context.Response.Cache.SetETag(etag); //StringBuilder content = Assets.GetOrAdd(etag, e => GetContent(context, virtualPaths, type, new StringBuilder())); StringBuilder content = GetContent(context, virtualPaths, type, new StringBuilder()); if (configSection.Debug) context.Response.Expires = 1; else { context.Response.Cache.SetProxyMaxAge(new TimeSpan(100, 0, 0, 0)); context.Response.Cache.SetExpires(DateTime.Now.Add(new TimeSpan(100, 0, 0, 0))); context.Response.Cache.SetMaxAge(new TimeSpan(0, 100, 0, 0)); context.Response.CacheControl = HttpCacheability.Public.ToString(); context.Response.Cache.SetCacheability(HttpCacheability.Server); context.Response.Cache.SetAllowResponseInBrowserHistory(true); context.Response.Cache.SetValidUntilExpires(true); } context.Response.Expires = 60 * 24 * 30; if (type == "js") context.Response.ContentType = "application/javascript"; else if (type == "css") context.Response.ContentType = "text/css"; context.Response.Write(content); } catch (Exception ex) { throw; } } private StringBuilder GetContent(HttpContext context, IEnumerable<string> paths, string type, StringBuilder buffer) { if (type == "js") { var scriptCompressor = new JavaScriptCompressor(); CreateCompressedContent(scriptCompressor, paths, buffer); } else if (type == "css") { var cssCompressor = new CssCompressor(); context.Response.ContentType = "text/css"; CreateCompressedContent(cssCompressor, paths, buffer); } return buffer; } public static byte[] GetHash(string inputString) { HashAlgorithm algorithm = MD5.Create(); // SHA1.Create() return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)); } public static string GetHashString(string inputString) { StringBuilder sb = new StringBuilder(); foreach (byte b in GetHash(inputString)) sb.Append(b.ToString("X2")); return sb.ToString(); } private void CreateCompressedContent(Compressor compressor, IEnumerable<string> virtualPaths, StringBuilder buffer) { foreach (string virtualPath in virtualPaths) { var fullname = basedir + virtualPath.Replace("//", "\\"); var contents = File.ReadAllText(fullname, Encoding.UTF8); if (string.IsNullOrWhiteSpace(contents)) continue; if (configSection.Debug || virtualPath.Contains(".min.")) buffer.AppendFormat("\r\n\r\n /*{0}*/ \r\n\r\n{1}", virtualPath, contents); else buffer.AppendFormat("\r\n\r\n /* {0} */ \r\n\r\n {1}", virtualPath, compressor.Compress(contents)); } } public bool IsReusable { get; private set; } } }<file_sep>// Type definitions for PlantomJS v1.8.0 API // Project: https://github.com/ariya/phantomjs/wiki/API-Reference // Definitions by: <NAME> <https://github.com/jedhunsaker> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface Phantom { // Properties args: string[]; // DEPRECATED cookies: Cookie[]; cookiesEnabled: boolean; libraryPath: string; scriptName: string; // DEPRECATED version: any; // Functions addCookie(cookie: Cookie): boolean; clearCookies(); deleteCookie(cookieName: string): boolean; exit(returnValue: any): boolean; injectJs(filename: string): boolean; // Callbacks onError: Function; } interface System { pid: number; platform: string; os: OS; env: any; args: string[]; } interface OS { architecture: string; name: string; version: string; } interface WebPage { // Properties canGoBack: boolean; canGoForward: boolean; clipRect: ClipRect; content: string; cookies: Cookie[]; customHeaders: any; event; focusedFrameName: string; frameContent: string; frameName: string; framePlainText: string; frameTitle: string; frameUrl: string; framesCount: number; framesName; libraryPath: string; navigationLocked: boolean; offlineStoragePath: string; offlineStorageQuota: number; ownsPages: boolean; pages; pagesWindowName: string; paperSize: PaperSize; plainText: string; scrollPosition: TopLeft; settings: WebPageSettings; title: string; url: string; viewportSize: Size; windowName: string; zoomFactor: number; // Functions addCookie(cookie: Cookie): boolean; childFramesCount(): number; // DEPRECATED childFramesName(): string; // DEPRECATED clearCookies(); close(); currentFrameName(): string; // DEPRECATED deleteCookie(cookieName: string): boolean; evaluate(fn: Function, ...args: any[]): any; evaluateAsync(fn: Function); evaluateJavascript(str: string); getPage(windowName: string); go(index: number); goBack(); goForward(); includeJs(url: string, callback: Function); injectJs(filename: string): boolean; open(url: string, callback: (status: string) => void); openUrl(url: string, httpConf: any, settings: any); release(); // DEPRECATED reload(); render(filename: string); renderBase64(format: any): string; sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string); sendEvent(keyboardEventType: string, keyOrKeys, aNull?, bNull?, modifier?); setContent(content: string, url: string); stop(); switchToFocusedFrame(); switchToFrame(frameName: string); switchToFrame(framePosition); switchToChildFrame(frameName: string); switchToChildFrame(framePosition); switchToMainFrame(); // DEPRECATED switchToParentFrame(); // DEPRECATED uploadFile(selector: string, filename: string); // Callbacks onAlert: Function; onCallback: Function; // EXPERIMENTAL onClosing: Function; onConfirm: Function; onConsoleMessage: Function; onError: Function; onFilePicker: Function; onInitialized: Function; onLoadFinished: Function; onLoadStarted: Function; onNavigationRequested: Function; onPageCreated: Function; onPrompt: Function; onResourceRequested: Function; onResourceReceived: Function; onUrlChanged: Function; // Callback triggers closing(page); initialized(); javaScriptAlertSent(message: string); javaScriptConsoleMessageSent(message: string); loadFinished(status); loadStarted(); navigationRequested(url: string, navigationType, navigationLocked, isMainFrame: boolean); rawPageCreated(page); resourceReceived(request); resourceRequested(resource); urlChanged(url: string); } interface PaperSize { width: string; height: string; border: string; format: string; orientation: string; } interface WebPageSettings { javascriptEnabled: boolean; loadImages: boolean; localToRemoteUrlAccessEnabled: boolean; userAgent: string; password: string; XSSAuditingEnabled: boolean; webSecurityEnabled: boolean; } interface FileSystem { // Properties separator: string; workingDirectory: string; // Functions // Query Functions list(path: string): string[]; absolute(path: string): string; exists(path: string): boolean; isDirectory(path: string): boolean; isFile(path: string): boolean; isAbsolute(path: string): boolean; isExecutable(path: string): boolean; isReadable(path: string): boolean; isWritable(path: string): boolean; isLink(path: string): boolean; readLink(path: string): string; // Directory Functions changeWorkingDirectory(path: string); makeDirectory(path: string); makeTree(path: string); removeDirectory(path: string); removeTree(path: string); copyTree(source: string, destination: string); // File Functions open(path: string, mode: string): Stream; read(path: string): string; write(path: string, content: string, mode: string); size(path: string): number; remove(path: string); copy(source: string, destination: string); move(source: string, destination: string); touch(path: string); } interface Stream { read(): string; readLine(): string; write(data: string); writeLine(data: string); flush(); close(); } interface WebServer { port: number; listen(port: number, cb?: (request, response) => void): boolean; listen(ipAddressPort: string, cb?: (request, response) => void): boolean; close(); } interface Request { method: string; url: string; httpVersion: number; headers: any; post: string; postRaw: string; } interface Response { headers: any; setHeader(name: string, value: string); header(name: string): string; statusCode: number; setEncoding(encoding: string); write(data: string); writeHead(statusCode: number, headers?: any); close(); closeGracefully(); } interface TopLeft { top: number; left: number; } interface Size { width: number; height: number; } interface ClipRect extends TopLeft, Size { width: number; height: number; } interface Cookie { name: string; value: string; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using FluentAssertions; using NUnit.Framework; using Tekphoria.Web.Server.Common; namespace Tests { [TestFixture] public class CompareDb { public void HasSameStructure(string dev_constr, string live_constr) { var dev = new DbMeta(dev_constr); var dev_fields = dev.GetMySqlStructure(); var live = new DbMeta(live_constr); var live_fields = live.GetMySqlStructure(); // check for a in b for (int i = 0; i < dev_fields.Count; i++) { var search = dev_fields[i].hash; bool match = false; for (int j = 0; j < live_fields.Count; j++) { var candidate = live_fields[j].hash; if (string.CompareOrdinal(search, candidate) == 0) { match = true; } } if(!match) Assert.Fail("Dev not found in Live " + search); } // check for b in a for (int i = 0; i < live_fields.Count; i++) { var search = live_fields[i].hash; bool match = false; for (int j = 0; j < dev_fields.Count; j++) { var candidate = dev_fields[j].hash; if (string.CompareOrdinal(search, candidate) == 0) match = true; } if (!match) Assert.Fail("Live not found in Dev " + search); } dev_fields.Count.Should().Be(live_fields.Count); } [Test] public void CompareDbs() { var devConstrings = new[] { Config.GetScrumboConnectionString.Value, Config.GetCommonDbConnectionString.Value }; var liveConstrings = new[] { Config.GetDecryptedConstr("ScrumboDbConnectionString-live"), Config.GetDecryptedConstr("GetCommonDbConnectionString-live") }; for (int i = 0; i < devConstrings.Count(); i++) HasSameStructure(devConstrings[i], liveConstrings[i]); Assert.Pass(); } [Test] public void GetPropertyNames() { } } } <file_sep>var App; (function (App) { var File = (function () { function File(Name, Size, Created, Modified, Extension) { } return File; })(); App.File = File; })(App || (App = {})); <file_sep>using System.Web; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.Server.Handlers { public class ImageHandler : IHttpHandler { private static readonly string basedir = HttpContext.Current.Server.MapPath(".") + "\\js"; public void ProcessRequest(HttpContext context) { string path = context.Request["path"] ?? ""; context.Response.WriteFile(Image.GetImageServerFullPath(path)); } public bool IsReusable { get; private set; } } } <file_sep>var WB; (function (WB) { var Error = (function () { function Error(title, message, exception) { this.title = title; this.message = message; this.exception = exception; } return Error; })(); WB.Error = Error; var ErrorController = (function () { function ErrorController() { } ErrorController.Show = function (error) { ErrorView.render(error); }; return ErrorController; })(); WB.ErrorController = ErrorController; var ErrorView = (function () { function ErrorView() { } ErrorView.render = function (error) { var munge = this.getErrorView(error.title, error.message); $("#errors").html(munge); }; ErrorView.getErrorView = function (title, message) { var tmp = this.getTemplate(); return tmp.replace('{0}', title).replace('{1}', message); }; ErrorView.getTemplate = function () { return "<div class=row><div class='span4 alert alert-error'><strong>{0}</strong> {1}</div></div>"; }; return ErrorView; })(); WB.ErrorView = ErrorView; })(WB || (WB = {})); <file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var App; (function (App) { var account_server_client = (function (_super) { __extends(account_server_client, _super); function account_server_client() { _super.call(this, "account_server.ashx"); } return account_server_client; })(App.ServerClientBase); App.account_server_client = account_server_client; var ledger = (function () { function ledger() { this.Accounting = window["accounting"]; } ledger.prototype.init = function () { var _this = this; var client = new account_server_client(); var act = client.CallMethod("GetAccountsList", {}); $.when(act).then(function (resp) { return _this.render(resp); }); }; ledger.prototype.render = function (resp) { var _this = this; App.ViewEngine.renderview(this.getTemplate(resp), {}); $("#amount").css({ "text-align": "right" }); $("#btnsubmit").off("click").on("click", function (e) { return _this.onFormSubmit(e); }); $("body").on("keypress", function (e) { return _this.handleAmountKey(e); }); }; ledger.prototype.handleAmountKey = function (e) { var _this = this; var n = String.fromCharCode(e.charCode); if (App.GlobalCommon.isNumber(n) && e.target.id === "amount") { setTimeout(function () { var curr = $("#amount").val(); var formatted = _this.Accounting.toFixed(+curr, 2); $("#amount").val(formatted); }, 3000); } }; ledger.prototype.getTemplate = function (resp) { var items = [{ id: 1, valueof: "CAT" }, { id: 2, valueof: "DOG" }]; var account = App.GlobalCommon.input_data_string("amount", "Amount", ""); var amount = App.GlobalCommon.dropdown("Account", "account", "", resp.accounts, "One"); var descof = App.GlobalCommon.input_data_string("Description", "descof", ""); var form = App.GlobalCommon.form("New Account Record", account + amount + descof, "btnsubmit", "form1"); return form; }; ledger.prototype.onFormSubmit = function (e) { e.preventDefault(); var formdata = App.GlobalCommon.getFormInputs($("#form1")); var client = new account_server_client(); var act = client.CallMethod("SaveNewLedger", formdata); $.when(act).then(function (resp) { return App.GlobalCommon.processPostBack(resp, $("#form1"), function () { }); }); }; return ledger; })(); App.ledger = ledger; })(App || (App = {})); <file_sep>using System; using FluentValidation; namespace Tekphoria.Web.Server.Common { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] sealed class ValidationAttribute : Attribute { // This is a positional argument public ValidationAttribute(IValidator validatorType) { } } }<file_sep>using System; using System.Data; using FluentValidation.Results; using Newtonsoft.Json.Linq; namespace Tekphoria.Web.linkr { public partial class EditLink : LinkrPage { protected void Page_Load(object sender, EventArgs e) { string id = Context.Request.QueryString["id"] ?? ""; if (string.IsNullOrWhiteSpace(id)) throw new DataException("Data is missing."); ErrorPanel.Visible = InfoPanel.Visible = SuccessPanel.Visible = false; try { if (!IsPostBack) { var data = new JObject(); data.Add("id", id); data.Add("user_id", GetNonEmptyCookie("UserId")); dynamic callresult = svr.GetLink(data); try { textof.Value = callresult.link.textof; href.Value = callresult.link.href; //descof.Value = svr.Translate(callresult.link.descof); descof.Value = callresult.link.descof; isHidden.Checked = callresult.link.ishidden; hits.Value = callresult.link.hits.ToString(); } catch (Exception ex) { ErrorPanel.Msg = "Could not retreive record."; } } else { var data = new JObject(); data.Add("href", href.Value); data.Add("link_id", id); data.Add("textof", textof.Value); data.Add("descof", descof.Value); data.Add("ishidden", isHidden.Checked); data.Add("hits", hits.Value); data.Add("user_id", GetNonEmptyCookie("UserId")); dynamic callresult = svr.UpdateLinkDetail(data); ValidationResult vr = callresult.result; if (vr.Errors.Count == 0) SuccessPanel.Msg = "Link updated successfully"; else { foreach (ValidationFailure err in vr.Errors) ErrorPanel.Msg += err.ErrorMessage; } } } finally { svr.CloseConnections(); } } } } <file_sep>/// <reference path="../../global_js/domo.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/routie.d.ts" /> module App { export class Linkr { private window: Window; private hasSetEvents: boolean = false; constructor() { this.registerEvents(); this.registerRoutes(); //this.parseAllTemplatesToWindow("templates.htm"); } private registerRoutes() { window.routie({ '/link/:id': (id) => new App.ViewLinkDetail({ id: id }), '/link/new': (id) => new App.ViewLinkNew({}), '/links': () => new App.ViewLinks(), // '/': () => new App.ViewLinks(), '': () => new App.ViewLinks() }); } private registerEvents() { if (this.hasSetEvents === false) { this.hasSetEvents = true; } } } export class ViewBase { constructor(public template: string) { } public events(data?: any) {} public render(data?: any, parts?: any) { App.ViewEngine.renderview(this.template, data, parts); } public getHtml(data?: any) {} public getTemplate(data: any) {} } export class ViewLinks extends ViewBase { constructor() { var frame = { top_content: TemplateProvider.logo() + TemplateProvider.addButton() + TemplateProvider.filters(), middle_content: TemplateProvider.links, bottom_content: "<hr><hr>" }; var all = ViewEngine.getHtml(TemplateProvider.linksPageFrame(), frame); super(all); //var data = { // header : "popular", // footer : "the footer", // links: [{textof:"link1"},{textof:"link2"},{textof:"link3"}] //} var client = new LinkrServerClient(); var parts = { link: TemplateProvider.link }; var act = client.CallMethod("GetLinks", {}); $.when(act).then(resp => { var future = moment.utc().add('days', 3); $.each(resp.links, (idx, item) => { item.fuzzyCreated = "made " + moment.utc(item.date_created).fromNow(); item.fuzzyAccessed = "used " + moment.utc(item.date_accessed).fromNow(); item.daysOld = future.diff(moment.utc(item.date_created), 'days'); item.score = item.hits / item.daysOld; }); this.render(resp, parts); $(".data-items").isotope({ itemSelector: '.link', getSortData: { hits: $elem => { return parseInt($elem.find(".hits").text(), 10); }, date_accessed: $elem => { return $elem.find(".date_accessed").text(); }, date_created: $elem => { return $elem.find(".date_created").text(); }, score: $elem => { return parseInt($elem.find(".score").text(), 10); } }, sortBy: "score", sortAscending: false }); $(".logo").on("click", e => { location.href = "/linkr"; }); $(".title a").on("click", e => { var target = $(e.currentTarget); var href = target.attr("href"); var id = target.attr("data-id"); var client = new LinkrServerClient(); client.CallMethod("Increment", { id: id }); }); $(".filter").on("click", e => { e.preventDefault(); var selected = $(e.currentTarget).text(); var sortFunction = FilterOptions[selected]; $('.data-items').isotope(sortFunction); $("#selectedfilter").text("by " + $(e.currentTarget).text()); }); }); } } export class ViewLinkDetail extends ViewBase { constructor(data) { super(TemplateProvider.linkDetail()); var client = new LinkrServerClient(); var parts = { link: TemplateProvider.link }; var act = client.CallMethod("GetLink", { id: data.id }); $.when(act).then(resp => { this.render(resp); $("#btnSubmit").on("click", e => this.submit(e)); }); } submit(e) { e.preventDefault(); var client = new LinkrServerClient(); var form = App.GlobalCommon.getFormInputs($("#form1")); var act = client.CallMethod("UpdateLinkDetail", form); // $.when(act).then(resp => } } export class ViewLinkNew extends ViewBase { constructor(data) { super(TemplateProvider.linkNew()); $("#btnSubmit").on("click", e => this.submit(e)); } submit(e) { e.preventDefault(); var client = new LinkrServerClient(); var form = App.GlobalCommon.getFormInputs($("#form1")); var act = client.CallMethod("AddLink", form); } } export class FilterOptions { static oldest(): any { return { sortBy: "date_created", sortAscending: true }; } static newest(): any { return { sortBy: "date_created", sortAscending: false }; } static popular(): any { return { sortBy: "score", sortAscending: false }; } static stale(): any { return { sortBy: "last_accessed", sortAscending: true }; } static recent(): any { return { sortBy: "last_accessed", sortAscending: false }; } static hits(): any { return { sortBy: "hits", sortAscending: false }; } } export class ViewHome extends ViewBase { constructor() { super(window.templates.homeFrame); } } export class LinkrServerClient extends ServerClientBase { constructor() { super("linkr_server.ashx"); } } export class TemplateProvider { public static test(): string { var tmp; if (!tmp) { } return tmp; } public static linksPageFrame(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"frame\">"; tmp += " <div class=\"top_content\">{{&top_content}}<\/div>"; tmp += " <div class=\"middle_content\">{{&middle_content}}<\/div>"; tmp += " <div class=\"bottom_content\">{{&bottom_content}}<\/div>"; tmp += " <\/div>"; } return tmp; } public static linkDetail(): string { var tmp; if (!tmp) { tmp = ""; var id = App.GlobalCommon.inputstring("link_id", "link_id", "{{link.id}}", "", "hidden"); var href = App.GlobalCommon.inputstring("href", "href", "{{link.href}}", "The Url", "text"); var textof = App.GlobalCommon.inputstring("textof", "textof", "{{link.textof}}", "The Link Title", "text"); var descof = App.GlobalCommon.textarea("descof", "descof", "{{link.descof}}", "The Description", "10"); tmp += App.GlobalCommon.form("Edit Link", id + href + textof + descof, "btnSubmit", "form1"); } return tmp; } public static linkNew(): string { var tmp; if (!tmp) { tmp = ""; var id = App.GlobalCommon.inputstring("link_id", "link_id", "0", "", "hidden"); var textof = App.GlobalCommon.inputstring("textof", "textof", "{{link.textof}}", "The Link Title", "text"); var href = App.GlobalCommon.inputstring("href", "href", "{{link.href}}", "The Url", "text"); var descof = App.GlobalCommon.textarea("descof", "descof", "{{link.descof}}", "The Description", "10"); tmp += App.GlobalCommon.form("Add Link", id + href + textof + descof, "btnSubmit", "form1"); } return tmp; } public static logo(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"logo\">"; tmp += " <div class=\"textof\">Linkly<\/div>"; tmp += " <div class=\"catch\">witty catch<\/div>"; tmp += " <\/div>"; } return tmp; } public static displayData(field: string) { return DIV({ id: field, "class": field }, "{{" + field + "}}"); } public static link(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"link\">"; //tmp += " <div class=\"edit icon-pen\"><a data-id=\"{{id}}\" href=\"#/link{{edit}}/{{id}}\">edit<\/a><\/div>" tmp += " <div class=\"title\"> <span class=\"icon-export-outline\"><\/span> <a data-id=\"{{id}}\" href=\"{{href}}\" target=\"blank\">{{textof}}<\/a>"; tmp += " <a data-id=\"{{id}}\" href=\"#/link{{edit}}/{{id}}\"><div class=\"edit icon-pen\"\/><\/a>"; tmp += " <\/div>"; tmp += " <div class=\"hits\">{{hits}}<\/div>"; tmp += " <div class=\"score\">{{score}}<\/div>"; tmp += " <div class=\"fuzzyAccessed\">{{fuzzyAccessed}}<\/div>"; tmp += " <div class=\"fuzzyCreated\">{{fuzzyCreated}}<\/div>"; tmp += " <div class=\"date date_accessed\">{{date_accessed}}<\/div>"; tmp += " <div class=\"date date_created\">{{date_created}}<\/div>"; tmp += " <div class=\"movement\">^<\/div>"; tmp += " <\/div>"; //var a = A({"data-id":"{{id}}", href:"{{href}}", target:"blank", },"{{textof}}") //var title = DIV({"class":"title"},a.outerHTML) //var hits = this.displayData("hits") //var score = this.displayData("score") //var fuzzyAccessed = this.displayData("fuzzyAccessed") //var fuzzyCreated = this.displayData("fuzzyCreated") //var movement = this.displayData("movement") } return tmp; } public static filters(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"filters\">"; tmp += " <div class=\"title\"><span id=\"selectedfilter\"><br><\/><\/div>"; tmp += " <div class=\"filter\">popular<\/div>"; tmp += " <div class=\"filter\">newest<\/div>"; tmp += " <div class=\"filter\">recent<\/div>"; tmp += " <div class=\"filter\">hits<\/div>"; tmp += " <div class=\"filter\">oldest<\/div>"; tmp += " <div class=\"filter\">hidden<\/div>"; tmp += " <\/div>"; } return tmp; } public static addButton(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div class=\"addbutton\">"; tmp += " <a href=\"#\/link\/new\">NEW<\/div>"; tmp += " <\/div>"; } return tmp; } public static links(): string { var tmp; if (!tmp) { tmp = ""; tmp += " <div id=\"links\">"; tmp += " <div class=\"data-items\">"; tmp += " {{#links}}"; tmp += " {{>link}}"; tmp += " {{\/links}}"; tmp += " <\/div>"; tmp += " <div class=\"footer\">{{footer}}<\/div> "; tmp += " <\/div>"; } return tmp; } } }<file_sep>namespace Tekphoria.Server.Scrumbo { public enum ActionEnum { UNKNOWN = 0, BOARD_ADD, BOARD_GET_BY_HASH, BOARD_GET, BOARD_DELETE, BOARD_GET_CONFIGURATION, BOARDS_LIST, STORY_DELETE, STORY_ADD_TO_BOARD, STORY_UPDATE, TASK_MOVE, TASK_GET, TASK_DELETE, TASK_ADD_TO_STORY, TASK_UPDATE_TEXT, STORY_GET, STORY_UPDATE_TEXT, BOARD_SET_CONFIGURATION, BOARD_SORT_STORY, TASK_UPDATE_STATUS, USER_SIGN_IN_TRY, USER_ADD, USER_ADD_SHARED_BOARD, USER_GET, USER_UPDATE, BOARD_GET_ARCHIVE, BOARD_SET_STATUS, STORY_SET_STATUS, USER_GET_RECENT_TASKS } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Xml.Serialization; using Clarks.MCR.WebSite.Sitemaps; using Tekphoria.Web.Server.Sitemap; namespace Tekphoria.Web.Server.Handlers { public class SitemapXmlHandler : IHttpHandler { private const tChangeFreq CHANGE_FREQUENCY = tChangeFreq.weekly; private readonly string _lastMod; public SitemapXmlHandler() { _lastMod = DateTime.UtcNow.ToString("yyyy-MM-dd"); } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/xml"; context.Response.ContentEncoding = new UTF8Encoding(); context.Response.Write(GetContent()); } private string GetContent() { var sitemap = new urlset { url = SitemapData.Items.Select(u => new tUrl { loc = u, changefreqSpecified = true, changefreq = CHANGE_FREQUENCY, lastmod = _lastMod }).ToArray() }; using (var writer = new Utf8StringWriter()) { new XmlSerializer(typeof(urlset)).Serialize(writer, sitemap); return writer.ToString(); } } public bool IsReusable { get; private set; } } public class Utf8StringWriter : StringWriter { public override Encoding Encoding { get { return Encoding.UTF8; } } } }<file_sep>/// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> module Component { export class GoogleMaps { static api_key: string = "<KEY>"; static maps_direct_lat_log_url = "https://maps.google.com/maps?ll={latitude},{longitude}&z=20"; private static map: any; public static search_address_2(address: string) : any { var google: any = window["google"]; var geocoder: any = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { amplify.publish("SearchAddress_reply", results); } else { alert("Geocode was not successful for the following reason: " + status); } }); } //public static calculateDistances() { // var google = window["google"]; // var service = new google.maps.DistanceMatrixService(); // service.getDistanceMatrix( // { // origins: [origin1, origin2], // destinations: [destinationA, destinationB], // travelMode: google.maps.TravelMode.DRIVING, // unitSystem: google.maps.UnitSystem.METRIC, // avoidHighways: false, // avoidTolls: false // }, callback); //} public static getDistanceFromBase(lat: string, lng: string): number { var google = window["google"]; var base = new google.maps.LatLng(51.4920292996691, 2.64677873809819); var dest = new google.maps.LatLng(+lat, +lng); var distanceMeters: number = 0; return distanceMeters; } public static get_default_options() { var google = window["google"]; return { zoom: 18, mapTypeId: google.maps.MapTypeId.SATELLITE, center: {} }; } public static show_location(data) { var google = window["google"]; var options = this.get_default_options(); options.center = new google.maps.LatLng(data.latitude, data.longitude); this.map = new google.maps.Map(document.getElementById("map-canvas"), options); var marker = new google.maps.Marker({ map: this.map, draggable: true, raiseOnDrag: false, position: options.center }); google.maps.event.addListener(marker, 'dragend', function () { var position = marker.getPosition(); this.map.setCenter(position); // set the map center to it's new position amplify.publish("location_change", { latitude: position.lat(), longitude: position.lng() }) $("#latitude").text(position.lng()); $("#longitude").text(position.lat()); var data = { latitude: position.lat(), longitude: position.lng(), query: $("#query").text(), id: $("#prospect_id").text() } amplify.publish("UpdateProspectLocation", data); }); } public static show_map(options: any, results) { var google = window["google"]; this.map = new google.maps.Map(document.getElementById("map-canvas"), options); var marker = new google.maps.Marker({ map: this.map, draggable: true, raiseOnDrag: false, position: results[0].geometry.location }); $("#query").val(results[0].address_components[0].short_name + ' ' + results[0].address_components[1].short_name + ' ' + results[0].address_components[2].short_name + ' UK'); google.maps.event.addListener(marker, 'dragend', function () { var position = marker.getPosition(); this.map.setCenter(position); // set the map center to it's new position amplify.publish("location_change", { latitude: position.lat(), longitude: position.lng() }) $("#latitude").text(position.lng()); $("#longitude").text(position.lat()); var data = { latitude: position.lat(), longitude: position.lng(), query: $("#query").text(), id: $("#prospect_id").text() } amplify.publish("UpdateProspectLocation", data); }); return this.map; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Tekphoria.Web.linkr { public partial class Links : LinkrPage { protected void Page_Load(object sender, EventArgs e) { try { string userid = GetNonEmptyCookie("UserId"); int h; Int32.TryParse(Request["h"], out h); IEnumerable<LinkDB> links = svr.GetLinks(userid, h == 1).ToArray(); PostProcess(links); NewLinkList.Links = links.OrderByDescending(l => l.date_created).ToArray(); PopularLinkList.Links = links.OrderByDescending(l => l.average_hits).ToArray(); RecentlyUsedLinkList.Links = links.OrderByDescending(l => l.date_accessed).ToArray(); StaleLinks.Links = links.OrderBy(l => l.date_stale).ToArray(); RandomLinkList.Links = links.OrderBy(l => Guid.NewGuid()).ToArray(); } finally { svr.CloseConnections(); } } private void PostProcess(IEnumerable<LinkDB> links) { foreach (LinkDB link in links.Where(l => l.textof.Length > 27)) link.textof = link.textof.Substring(0, 27) + "..."; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Tekphoria.Web.global_pages { public partial class InfoPanel : System.Web.UI.UserControl { public string Msg { get { return TextOf.Text; } set { Visible = true; TextOf.Text = value; } } protected void Page_Load(object sender, EventArgs e) { } } }<file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var App; (function (App) { var MailServerClient = (function (_super) { __extends(MailServerClient, _super); function MailServerClient() { _super.call(this, "/global_svr/email.ashx"); } return MailServerClient; })(App.ServerClientBase); App.MailServerClient = MailServerClient; var Mail = (function () { function Mail() { } Mail.init = function () { $("#to").val("<EMAIL>"); $("#subject").val("test-subject"); $("#body").text("test-subject"); $("#btnSend").on("click", function (e) { e.preventDefault(); var data = { to: $("#to").val(), subject: $("#subject").val(), body: $("#testcontent").html(), ishtml: true }; var client = new App.MailServerClient(); var m = client.CallMethod("SendMailTest", data); $.when(m).then(function (resp) { alert(resp); }); }); }; return Mail; })(); App.Mail = Mail; })(App || (App = {})); <file_sep>using System.Data; using System.Linq; using Dapper; using FluentValidation; namespace Tekphoria.Web.Server.Account { public class UserAddValidator : AbstractValidator<User> { private readonly IDbConnection _accountDbConnection; public UserAddValidator(IDbConnection accountDbConnection) { _accountDbConnection = accountDbConnection; RuleFor(x => x.email) .Must(PassEmailInDbCheck) .WithMessage("'Email' already exists.") .WithName("Email"); RuleFor(x => x.display_name) .Must(PassDisplayNameDbCheck) .WithMessage("'Display Name' already exists.") .WithName("Display Name"); } private bool PassDisplayNameDbCheck(string display_name) { dynamic res = _accountDbConnection.Query<dynamic>( "select count(id) as user_count from users where display_name=@display_name;", new { display_name }).Single(); return res.user_count == 0; } protected bool PassEmailInDbCheck(string email) { dynamic res = _accountDbConnection.Query<dynamic>("select count(id) as user_count from users where email=@email;", new { email }).Single(); return res.user_count == 0; } } }<file_sep>var Tests; (function (Tests) { var SomeView = (function () { function SomeView() { } SomeView.prototype.render = function () { return "rendered!"; }; return SomeView; })(); Tests.SomeView = SomeView; var ViewTests = (function () { function ViewTests() { } ViewTests.Run = function () { QUnit.test("IView Test", function () { var obj = { render: function (data) { return data.name; } }; QUnit.equal(obj.render({ name: "test" }), "test"); }); }; return ViewTests; })(); Tests.ViewTests = ViewTests; })(Tests || (Tests = {})); Tests.ViewTests.Run(); <file_sep>/// <reference path="./d/node.d.ts" /> /// <reference path="./d/express.d.ts" /> var express = require("express"); var app = new express(); var svr; (function (svr) { var app = (function () { function app() { } app.main = function () { console.log("hello"); }; return app; })(); svr.app = app; })(svr || (svr = {})); svr.app.main(); <file_sep>/// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="wb.storage.ts" /> /// <reference path="wb.logclasses.ts" /> /// <reference path="wb.taskclasses.ts" /> /// <reference path="wb.interfaces.ts" /> /// <reference path="wb.errorclasses.ts" /> /// <reference path="WB.StoryClasses.ts" /> /// <reference path="ScrumboServerClient.ts" /> module WB { export class Board { constructor( public id: string, public sort_order: number, public nameof: string, public columns?: string[], public stories?: Story[], public tasks?: Task[] ) { } } export class BoardSummary { constructor( public id: number, public nameof: string ) { } } export class BoardController { public static BOARDS_LIST() { var boards: Board[] = []; var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardsList", {}) $.when(action).then(resp => BoardsView.render(resp)); } public static BOARD_ADD() { BoardAddView.render(); } public static BOARD_DELETE(hash: string) { DeleteBoardView.render(hash); } public static BOARD_GET(hash: string) { var client = new WB.ScrumboServerClient(); var req1 = client.CallMethod("BoardGetByHash", { hash: hash }) $.when(req1).then(resp1 => { var accountClient = new Account.AccountClient(); var req2 = accountClient.CallMethod("GetUsersById", { id_list: Enumerable.From(resp1.tasks).Select(t => t.user_id).Distinct().ToArray().join(',') }) $.when(req2).then(resp2 => this.HandleBoardResponse(resp1, resp2)); }) } public static BOARD_GET_SIMPLE(hash: string) { var client = new WB.ScrumboServerClient(); var req1 = client.CallMethod("BoardGetByHash", { hash: hash }) //var getUsers = () => $.when(req1).then(resp1 => { var accountClient = new Account.AccountClient(); var req2 = accountClient.CallMethod("GetUsersById", { id_list: Enumerable.From(resp1.tasks).Select(t => t.user_id).Distinct().ToArray().join(',') }) $.when(req2) .then( resp2 => this.HandleBoardResponse(resp1, resp2, "simple")); }) } public static HandleBoardResponse(boardresp, usersresp, viewtype?: string) { var vdata = boardresp vdata.users = usersresp.user_list if (vdata.board) { if (viewtype) { BoardViewSimple.render(vdata); } else { BoardView2.render(vdata); } } else { window.routie("boards"); } } public static BOARD_DELETE_REPLY() { } public static BOARD_GET_CONFIGURATION(hash) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetConfiguration", { hash: hash }) $.when(action).then(resp => BoardConfigView.render(resp)) } public static BOARD_GET_ARCHIVE(hash) { var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardGetArchiveByHash", { hash: hash }) $.when(act).then(resp => BoardArchiveView.render(resp)) } public static USER_ADD_SHARED_BOARD(data) { AddSharedBoardView.render() } } /* ========================================================================================= */ export class BoardViewSimple { public static render(data) { App.ViewEngine.renderview(this.getTemplate(data), data) } static getTemplate(data) { var lines = []; lines.push("<div class='container'>") lines.push("<h2>{{board.nameof}}</h2>") lines.push("<h3>{{&board.more_info}}</h3>") lines.push("<ul>") Enumerable.From(data.columns).ForEach(col=> { lines.push('<h4>' + col + '</h4>') }) Enumerable.From(data.stories).OrderBy((s: Story) => s.sort_order).ForEach((story: Story) => { lines.push("<li><h4>#" + story.id + " " + story.textof + "</h4></li>") lines.push("<ul>") Enumerable.From(data.tasks).Where((t: Task) => t.story_id === story.id).OrderBy((t: Task) => t.sort_order).ForEach((t: Task) => { var user = BoardView2.findUser(t.user_id, data.users); t.display_name = user.display_name lines.push("<li>" + t.status.toLocaleUpperCase() + " " + t.textof + " by " + user.display_name + "</li>") }); lines.push("</ul>") }); lines.push("</ul>") lines.push("</div>") return lines.join("") } } export class BoardView2 { public static findUser(id, users) { for (var i = 0; i < users.length; i++) { if (users[i].id === id) { return users[i] } } return { display_name: 'unknown' }; } public static render(data: any): void { amplify.store("last_board_hash", data.board.hash) $("#custom_css").remove() if (data.board.custom_css) { $("link").last().after("<style id=custom_css>" + data.board.custom_css + "</style>") }; if (data.board.extra_status_2) data.columns.splice(2, 0, data.board.extra_status_2); if (data.board.extra_status_1) data.columns.splice(2, 0, data.board.extra_status_1); var rows: string = ""; Enumerable.From(data.stories).OrderBy((s: Story) => s.sort_order).ForEach((story: Story) => { rows += "<tr data-storyid=" + story.id + ">" rows += "<td valign=top align=center>" + StoryView.munged(story, data.board.hash) + "</td>" Enumerable.From(data.columns).ForEach((col, idx) => { rows += "<td valign=middle align=center><div class='tasks' data-storyid='" + story.id + "' data-status='" + col + "'>" Enumerable.From(data.tasks).OrderBy((t: Task) => t.sort_order).ForEach((t: Task) => { if (t.story_id === story.id && t.status === col) { var user = this.findUser(t.user_id, data.users); t.display_name = user.display_name t.log_notes = Enumerable.From(data.log_notes).Where(ln => ln.task_id == t.id).ToArray(); rows += WB.TaskView.getHtml(t); } }); rows += "</div></td>"; }) rows += "</tr>" }); if (data.stories.length < 6) { Enumerable.RangeTo(data.stories.length, 5).ForEach(i => { rows += "<tr>" Enumerable.RangeTo(0, data.columns.length).ForEach(i => { rows += "<td></td>" }) rows += "</tr>" }) } data.rowsHtml = rows; var toolbar = App.ViewEngine.getHtml(this.getToolBarTemplate(), data); var takmoreView = WB.TaskMoreBarView.getHtml({ id: 0 }) WB.TaskMoreBarView.setEvents() App.ViewEngine.renderview(this.getTemplate(), data); $("#board").append(toolbar) $("#board").before(takmoreView) this.makeTasksSortable() this.makeStoriesSortable() this.makeTaskArchivable(true) this.addtaskloglistener() this.addtaskExpandListener() this.resizetasks() } static addLog(e) { e.preventDefault() var taskId = $("#addlogid").val() var textof = $(".addlogview #textof").val() var storyId = $(e.currentTarget).first().closest(".tasks").attr("data-storyid") var boardId = $("#board").attr("data-id") var client = new WB.ScrumboServerClient(); client.CallMethod("InsertLogItem", { board_id: boardId, story_id: storyId, id: taskId, textof: textof, action: "NOTE" }) } static timerids = [] static addtaskloglistener() { $(".addlog").off("click").on("click", e=> { e.preventDefault() $(".addlogview").remove() $(".addlog").show() var id = $(e.currentTarget).attr("data-id") var view: string = TaskAddLogView.getHtml({ id: id }); var target: JQuery = $(e.currentTarget) var task = target.closest(".task") var lognotes = task.find(".lognotes").first() task.after(view) $("#textof").focus(); $("#btnaddlog").off("click").on("click", e=> { e.preventDefault() var taskId = $("#addlogid").val() var textof = $(".addlogview #textof").val() var storyId = $(e.currentTarget).first().closest(".tasks").attr("data-storyid") var boardId = $("#board").attr("data-id") var client = new WB.ScrumboServerClient(); var act = client.CallMethod("InsertLogItem", { board_id: boardId, story_id: storyId, id: taskId, textof: textof, action: "29" }) $.when(act).then(() => { var logNoteRow = LogNoteRowView.getHtml(new LogNote(textof)) lognotes.prepend(logNoteRow) $(".addlogview").fadeOut() }) }) App.GlobalCommon.clearTimers() var timerid = setTimeout(() => $(".addlogview").remove(), 60000) App.GlobalCommon.timers.push(timerid) }) } static addtaskExpandListener() { $(".task .more").off("click").on("click", e=> { e.preventDefault() var task = $(e.currentTarget).closest(".task"); var foot = task.find(".task-foot").first(); var height = task.height() foot.slideDown() var timedfunc = (task) => { task.css({ height: height }) $(".task-foot").slideUp(); } setTimeout(() => timedfunc(task), 60000) }) } static resizetasks() { var tasks = $(".task") var width = tasks.first().width() var larger = width * 1.6; Enumerable.From(tasks).ForEach((t: Task) => { var ttext = $(t).find(".ttext"); var length = ttext.text().length if (length > 200) { $(t).width(larger) } }); } static makeTasksSortable() { var tasklists = $(".tasks"); tasklists.sortable({ connectWith: ".tasks", cursor: "move", placeholder: 'hover', distance: 1, tolerance: "pointer", start: (event, ui) => { var id = $(ui.item).attr("data-id"); var tasks = $(ui.item).parent(); var storyId = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var startIndex = ui.item.index(); var startData = '' + storyId + status + startIndex; // create a key to determin current state so as not to update unecessarily tasks.attr('data-start_data', startData); }, stop: (event, ui) => { var tasks = $(ui.item).parent(); var boardId = $("#board_id").val(); var tasksAll = tasks.find(".task"); var storyId = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var id = $(ui.item).attr("data-id"); var newIndex = ui.item.index(); // read start data to determin id a server method needs to be sent var startData = tasks.attr('data-start_data'); var newData = '' + storyId + status + newIndex; if (newData === startData) { return; } else { if (status === 'archive') { TaskController.TASK_UPDATE_STATUS({ id: id, status: 'archive' }); return; } var taskOrdering = Enumerable.From(tasksAll).Select((t: Task) => { return +$(t).attr("data-id"); }).ToArray(); TaskController.TASK_MOVE({ board_id: boardId, story_id: storyId, id: id, status: status, task_ordering: taskOrdering }); } } }).disableSelection(); } static makeStoriesSortable() { if (!document.hasOwnProperty("ontouchend")) { $("#board tbody").sortable({ placeholder: 'hover', cursor: "move", stop: (event, ui) => { var stories = $(ui.item).parent(); var stories_all = stories.find(".story"); var id = $(ui.item).attr("data-storyid"); var story_order = Enumerable.From(stories_all).Select((s: Story) => { return +$(s).attr("data-id"); }) .ToArray(); var data = { id: id, story_order: story_order } var client = new WB.ScrumboServerClient(); client.CallMethod("BoardSortStory", data) } }); } } static makeTaskArchivable(removeAfter: boolean) { $("body").off("click", ".btn_status").on("click", ".btn_status", e=> { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); var act = client.CallMethod("TaskUpdateStatus", data) $.when(act).then(resp => { if (removeAfter) { var selector = $(".task[data-id='" + id + "']") // $(selector).fadeOut() selector.css({ position: 'absolute', 'z-order': 1000 }) .animate( { 'margin-left': '3000px' }, 2000, () => selector.remove()); } else { window.location.reload() } }); }) } public static getTemplate() { if (this.hasOwnProperty("tmpl")) { } else { var lines = []; lines.push("<table width=100%>") lines.push("<tr>") lines.push("<td>") lines.push("<div class='board-header'><h2 class='board-name'><span class='board-title'>{{board.nameof}}</span></h2>") lines.push("<div class='board-moreinfo'>{{&board.more_info}}</div>") lines.push("</div></td>") lines.push("<td align=right>") lines.push("<div class='pagination-right'>") lines.push("<a href='#boards' class='btn btn-default btn-xs'>All Boards</a>") lines.push(" <a href='#board/{{board.hash}}/simple' class='btn btn-default btn-xs'>List View</a> ") lines.push(" <a href='#board/{{board.hash}}/config' class='btn btn-default btn-xs'>Configure</a> ") lines.push(" <a href='#board/{{board.hash}}/archive' class='btn btn-default btn-xs'>Archive</a> ") lines.push("</div>") lines.push("</td>") lines.push("</tr>") lines.push("</table>") lines.push("<table id='board' class='table' align=center data-id={{board.hash}}>") lines.push("<thead>") lines.push("<th>Story <a class='btn btn-default btn-xs' href='#board/{{board.hash}}/addstory'>Add</a></th>") lines.push("{{#columns}}<th>{{.}}</th>{{/columns}}") lines.push("</tr>") lines.push("</thead>") lines.push("<tbody>") lines.push("{{&rowsHtml}}") lines.push("</tbody>") lines.push("</table>") lines.push("{{&board.taskMoreBarViewHtml}}") lines.push("<input type=hidden id=board_id value='{{board.hash}}'></input>") this["tmpl"] = lines.join(""); } return this["tmpl"]; } static getToolBarTemplate() { return "<div>" //+ " <a href='#board/{{board.hash}}/config'>Configure</a> " //+ " <a href='#board/{{board.hash}}/archive'>Archive</a> " //+ " <a href='#board/{{board.slug}}/{{board.hash}}'>Link</a>" + "</div>"; } } /* ========================================================================================= */ export class BoardConfigView { public static render(boardConfigData: any) { App.ViewEngine.renderview(this.getTemplate(), boardConfigData); $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var formdata = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardSetConfiguration", formdata); $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1))) }); } static getTemplate(): string { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '{{board.nameof}}', 'The name of the board', 'text') // var top = App.GlobalCommon.inputstring('top_status', 'top_status', '{{board.top_status}}', 'Status for the top section', 'text') var info = App.GlobalCommon.textarea('more_info', 'more_info', '{{board.more_info}}', 'Extra infomation to be displayed.', '5') var custom_css = App.GlobalCommon.textarea('custom_css', 'custom_css', '{{board.custom_css}}', 'The Custom css values.', '5') var status1 = App.GlobalCommon.inputstring('extra_status_1', 'extra_status_1', '{{board.extra_status_1}}', 'Status Column 1 after between inprogress and done.', 'text') var status2 = App.GlobalCommon.inputstring('extra_status_2', 'extra_status_2', '{{board.extra_status_2}}', 'Status Column 2 after between inprogress and done.', 'text') var hash = App.GlobalCommon.inputstring('hash', 'hash', '{{board.hash}}', '', 'hidden') return App.GlobalCommon.container("<h2><span class='glyphicon glyphicon-cog'></span> Board Configuration</h2><a class-'btn btn-link' href='#board/{{board.hash}}/delete'>Delete board</a><hr>" + App.GlobalCommon.form('Board Details', nameof + info + status1 + status2 + custom_css + hash)); } } /* ========================================================================================= */ export class BoardTrashView { public static render() { this.registerEvents(); App.ViewEngine.renderview(this.getTemplate(), {}) } public static getHtml() { return this.getTemplate(); } static registerEvents() { } static getTemplate() { this.registerEvents(); return "<div class='trash'><img src='/img/trash.png'/></div>"; } } /* ========================================================================================= */ export class BoardAddView { private static getFormInputsAsObject(): any { var form: JQuery = $("#form1"); return App.GlobalCommon.getFormInputs(form); } public static render(): void { App.ViewEngine.renderview(this.getTemplate(), {}) //events var submitbtn = $("#btnsubmit"); var hash = $("#hash"); submitbtn.on("click", (e: any) => { e.preventDefault(); hash.val(App.GlobalCommon.createUUID(12, 36)); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardAdd", data) $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(1))) }); } public static getTemplate(): string { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '', 'The name of the board', 'text') var hash = App.GlobalCommon.inputstring('hash', 'hash', App.GlobalCommon.createUUID(12, 36), '', 'hidden') var form = App.GlobalCommon.form('<h2>Add a board</h2><hr>', nameof + hash) return App.GlobalCommon.container(form) } } /* ========================================================================================= */ export class BoardsView { public static render(data: any): void { App.ViewEngine.renderview(this.getTemplate(), data) this.registerEvents() } public static registerEvents() { if (!document.hasOwnProperty("ontouchend")) { var boardrows = $("#boards tbody"); boardrows.sortable({ placeholder: 'hover', cursor: "move", stop: (event, ui) => { //var stories = $(ui.item).parent(); var boardsummaries = $(".boardsummary"); var id = $(ui.item).attr("data-boardid"); var boards_order = Enumerable.From(boardsummaries).Select(summary => { return $(summary).attr("data-boardid"); }) .ToArray(); var data = { id: id, boards_order: boards_order } var client = new WB.ScrumboServerClient(); client.CallMethod("BoardsSort", data) } }); } } static getTemplate(): string { return "<div class=container><h2><span class='glyphicon glyphicon-list'></span> Boards</h2>" + "<div class='pull-right'><a class='btn btn-success btn-xs' href='#boards/add'>New Board</a> <a class='btn btn-primary btn-xs' href='#boards/addshared'>Add Shared Board</a> </div><br><br>" + "<table id='boards' class='table table-hover'><tbody>" + "{{#BoardSummaries}}" + "<tr data-boardid='{{hash}}' class='boardsummary'><td><a class='' href='#board/{{hash}}'><strong>{{nameof}}</strong></a> </td>" + "<td></td><td><span class=muted>key: {{hash}}</span></td>" //+ "<td></td>" + "</tr>{{/BoardSummaries}}" + "</tbody></table></div>" } } /* ========================================================================================= */ export class DeleteBoardView { public static render(hash): void { App.ViewEngine.renderview(this.getViewTemplate(), { "hash": hash }); $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardDelete", data); $.when(act) .then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window["routie"]("boards"))) }); } static getViewTemplate(): string { var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-warning-sign'></span> Delete Board and Contents</h2><div class='alert alert-danger'>DANGER ZONE! Actions taken will delete a board</div>", 'To Cancel use the back button or press submit to delete the board' + App.GlobalCommon.inputstring('hash', 'hash', '{{hash}}', '', 'hidden') ) return App.GlobalCommon.container(form) } } /* ========================================================================================= */ export class BoardArchiveView { public static render(data): void { var tasksHtml = ''; Enumerable.From(data.tasks).ForEach((t: Task) => { tasksHtml += TaskView.getHtml(t); }); data.tasksHtml = tasksHtml; var taskMoreBarViewHtml = TaskMoreBarView.render(data); App.ViewEngine.renderview(this.getViewTemplate() + taskMoreBarViewHtml, data); BoardView2.makeTaskArchivable(false); $(".task-foot").show() $('#archivedtasks').masonry({ itemSelector: '.task', }); } static getViewTemplate(): string { var page = '<div class="clearfix board_archive"><h2>Board Archive</h2><hr><div id="archivedtasks" >{{&tasksHtml}}</div></div>'; return App.GlobalCommon.container(page) } } export class AddSharedBoardView { public static render() { App.ViewEngine.renderview(this.getTemplate(), {}) $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("UserAddSharedBoard", data); $.when(act) .then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window["routie"]("boards"))) }); } static getTemplate(): string { var hash = App.GlobalCommon.inputstring('hash', 'hash', '', 'The shared boards hash', 'text') // var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') var form = App.GlobalCommon.form('<h2>Link shared board</h2><hr>', hash) return App.GlobalCommon.container(form) } } } <file_sep>/// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/mustache-0.7.d.ts" /> module App { export class CustomViewEngine { public static renderview(viewname: string, data: any, partials? : any) { var html = Mustache.render(viewname, data, partials); this.setAppHtml(html); return html; } public static getHtml(viewname: string, data: any, partials? : any): string { return Mustache.render(viewname, data, partials); } public static setAppHtml(html: string) { //getAppEl().hide().html(html).fadeIn(); amplify.store("last_page", window.location.toString()); this.getAppEl().html(html); } public static getAppEl() : JQuery { return $("#app"); } public static ClearScreen() { this.getAppEl().html(""); } public static ReloadPage() { //window.location.reload(); } } }<file_sep>/// <reference path="./d/node.d.ts" /> /// <reference path="./d/express.d.ts" /> var express = require("express") var app = new express(); module svr { export class app { public static main() { console.log("hello") } } } svr.app.main();<file_sep>/// <reference path="../global_js/qunit.d.ts" /> QUnit.test("hello test",() => { QUnit.ok('1' == '1', "Passed!"); }) <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Security.Cryptography.Pkcs; using System.Web; using Dapper; using FluentValidation; using FluentValidation.Results; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Common; using Tekphoria.Web.Server.Handlers; namespace Tekphoria.Web.Server.Account { public class AccountServer : JsonServer, IHttpHandler { private IDbConnection _accountsDbConnection; public new void ProcessRequest(HttpContext context) { try { base.ProcessRequest(context); } catch (Exception ex) { HandleError(ex); } finally { CloseConnection(GetAccountsDbConnection()); } } public IDbConnection GetAccountsDbConnection() { if (_accountsDbConnection == null || _accountsDbConnection.State != ConnectionState.Open) _accountsDbConnection = GetOpenConnection(Config.GetCommonDbConnectionString.Value); return _accountsDbConnection; } public void LogOut() { foreach (string cookieName in HttpContext.Current.Request.Cookies.AllKeys) { HttpCookie ck = HttpContext.Current.Request.Cookies[cookieName]; ck.Value = null; ck.Expires = DateTime.Now.AddYears(-1); HttpContext.Current.Response.Cookies.Add(ck); } } public dynamic UserChangePassword(dynamic data) { var user = new User { id = data.user_id, password = <PASSWORD>, email = "<EMAIL>" // always validates }; var val = new UserValidator(); ValidationResult validationResult = val.Validate(user, ruleSet: "emailandpwd"); if (validationResult.IsValid) { string pwd = Crypto.EncryptStringAes(user.password, Config.ID); dynamic res = GetAccountsDbConnection() .Execute( "update users set password='v2',pwd=@pwd where id=@id", new { user.id, pwd }); } return new { validationResult }; } public dynamic UserSignInTry(dynamic data) { try { var anon_user = new User { email = data.email.ToString(), password = data.password.ToString() }; var val = new UserValidator(); ValidationResult validationResult = val.Validate(anon_user, ruleSet: "emailandpwd"); if (!validationResult.IsValid) return new { validationResult }; var validator = new SignInValidator(GetAccountsDbConnection()); validationResult = validator.Validate(anon_user); if (validationResult.IsValid) { dynamic account = GetAccountsDbConnection() .Query<dynamic>("select id,display_name,pwd from users where email=@email;", new { data.email }).Single(); // add ticket string ticket = Guid.NewGuid() .ToString() .Replace("{", string.Empty) .Replace("}", string.Empty) .Replace("-", string.Empty) .ToUpperInvariant() .Substring(0, 16); string clearTicket = "delete from tickets where user_id = @user_id;"; string addticket = "insert into tickets (user_id, date_expires, access_id) values (@user_id, @date_expires, @access_id);"; dynamic user_id = account.id; GetAccountsDbConnection().Execute(clearTicket + addticket, new { user_id, date_expires = DateTime.UtcNow.AddDays(30), access_id = ticket }); SetCookie("IsLoggedIn", "1"); SetCookie("UserName", account.display_name.ToString()); SetCookie("Auth", ticket); SetCookie("UserId", account.id.ToString()); // http://www.codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form bool signed_in = true; return new { validationResult, account, signed_in }; } return new { validationResult }; } catch (Exception ex) { Debug.Print(ex.ToString()); throw ex; } } public dynamic UserAdd(dynamic data) { var anon_user = new User { display_name = data.display_name.ToString(), email = data.email.ToString(), password = data.password.ToString() }; try { var val = new UserValidator(); ValidationResult validationResult = val.Validate(anon_user, ruleSet: "emailandpwd,displayname"); if (!validationResult.IsValid) return new { validationResult }; var validator = new UserAddValidator(GetAccountsDbConnection()); validationResult = validator.Validate(anon_user); if (validationResult.IsValid) { string pwd = Crypto.EncryptStringAes(anon_user.password, Config.ID); data.password = "v2"; dynamic res = GetAccountsDbConnection() .Query<dynamic>( "insert into users (email,display_name,date_created,pwd,password) values (@email,@display_name,UTC_TIMESTAMP(),@pwd,'v2');select last_insert_id() as newid;", new { anon_user.email, anon_user.display_name, pwd }).Single(); string stringToEncrypt = JsonConvert.SerializeObject(new { user_id = res.newid }); string encrypted = Crypto.EncryptStringAes(stringToEncrypt, Config.ID); string domain = "www.tekphoria.co.uk"; if (Config.IsDevMachine) { data.email = "<EMAIL>"; domain = "localhost:1001"; } var handler = new EmailHandler(); handler.SendMailTest(new EmailArgs { To = data.email, Subject = string.Format("Account Verification for {0}", domain), Body = string.Format("Click <a href='http://{0}/account/verify?k={1}'>here</a> to verify account.", domain, encrypted), IsHtml = true }); return new { validationResult, id = res.newid }; } return new { validationResult }; } catch (Exception ex) { Debug.Write(ex); throw; } } public dynamic VerifyAccount(dynamic data) { var user_id = (int)data.user_id; dynamic user = GetVerifiedUserById(data); if (user != null) throw new DataException("User already verified."); string sql = "update users set status='VERIFIED' where id=@user_id"; dynamic res = GetAccountsDbConnection().Execute(sql, new { user_id }); string confimSql = "select status from users where status='VERIFIED' and id=@user_id"; List<dynamic> confirmResult = GetAccountsDbConnection().Query(confimSql, new { user_id }).ToList(); if (confirmResult.Any()) { return new { result = "confirmed" }; } return new { result = "error" }; } public dynamic GetVerifiedUserById(dynamic data) { string sql = "select display_name from users where status='VERIFIED' and id = @user_id;"; dynamic user = GetAccountsDbConnection().Query<dynamic>(sql, new { data.user_id }).ToList().FirstOrDefault(); return user; } public dynamic GetUsersById(dynamic data) { var id_list = (string)data.id_list; if (string.IsNullOrWhiteSpace(id_list)) id_list = "0"; string sql = "select id, display_name from users where id in(" + id_list + ");"; dynamic user_list = GetAccountsDbConnection().Query<dynamic>(sql, new { id_list }).ToList(); return new { user_list }; } public dynamic GetUserByEmail(dynamic data) { var validator = new UserExistsByEmailValidator(); ValidationResult validationResult = validator.Validate(new JObject(data)); if (validationResult.IsValid) { string sql = "select id, display_name from users where email=@email;"; dynamic user_list = GetAccountsDbConnection().Query<dynamic>(sql, new { data.email }).ToList(); return new { validationResult, user_list }; } return new { validationResult, user_list = new List<dynamic>() }; } public class UserExistsByEmailValidator : AbstractValidator<JObject> { public UserExistsByEmailValidator() { RuleFor(x => x.GetValue("email").ToString()) .EmailAddress() .WithMessage("Email is not valid") .WithName("email"); } } } }<file_sep>/// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="wb.userclasses.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> var WB; (function (WB) { /* ========================================================================================= */ var Log_Item = (function () { function Log_Item(id, board_id, story_id, task_id, user_id, textof, display_text, date_created, action) { this.id = id; this.board_id = board_id; this.story_id = story_id; this.task_id = task_id; this.user_id = user_id; this.textof = textof; this.display_text = display_text; this.date_created = date_created; this.action = action; } return Log_Item; })(); WB.Log_Item = Log_Item; var LogController = (function () { function LogController() { } LogController.SHOW_TASK_LOG = function (id) { LogView.render({ task_id: id }); }; return LogController; })(); WB.LogController = LogController; var LogView = (function () { function LogView() { } LogView.render = function (args) { var _this = this; var client = new WB.ScrumboServerClient(); var act = client.CallMethod("GetTaskLogItems", args); $.when(act).then(function (data) { data.log_items.forEach(function (t) { t.fuzzy_date = moment.utc(t.date_created).fromNow(); t.action_name = data.actions[t.action]; App.ViewEngine.renderview(_this.getTemplate(), data); }); }); }; LogView.getTemplate = function () { var tmp = "<div class='logitems clearfix'>" + "<h1>Task Activity</h1>" + "{{#log_items}}<div class=logitem>" + "<span class='text'>{{action_name}} {{&textof}}</span>" + "<span class='date'>{{fuzzy_date}}</span>" + "</div>{{/log_items}}</div>"; return tmp; }; LogView.getHtml = function (data) { //Enumerable.From(data.log_items).ForEach((logitem: Log_Item) => { // var actionname = this.getActionName(logitem.action, data.actions); // var user = this.getUserName(logitem.user_id, data.users) // var fuzzytime = App.GlobalCommon.prettyDate(logitem.date_created); // logitem.display_text = user + " " + " <br> " + fuzzytime + " <br> " + actionname + " [" + logitem.task_id + "] " + logitem.textof //}) return App.ViewEngine.getHtml(this.getTemplate(), data); }; return LogView; })(); WB.LogView = LogView; })(WB || (WB = {})); <file_sep>/// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/keyboardjs.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> module App { export class invoice { static accounting = window["accounting"]; public static init() { var inputs = amplify.store("invoice_inputs"); inputs = $.extend(inputs, App.GlobalCommon.getUrlParams()) App.GlobalCommon.getUrlParams() // http://www.tekphoria.co.uk/tekphoria/invoice.html?inputcompanycode=PSOURCE&inputcounter=01&inputdayrate=415&inputdaysworked=22&inputvatrate=20&print=1 if (inputs) { for(var propertyName in inputs) { $("[name="+ propertyName +"]").first().val(inputs[propertyName]); } } $("#invoicedate").val(moment().format("dd MMM YYYY")) $("#generate-button").off("click").on("click", e => { e.preventDefault(); this.processInputs(); }); KeyboardJS.on('ctrl > s', e=> { e.preventDefault(); this.processInputs(); }); KeyboardJS.on('ctrl > f', e=> { e.preventDefault(); var form = $("#input-form"); if (form.is(':visible')) { form.hide(); } else { form.show(); } }); var switchprint = () => { $("#input-form").hide(); $("#email").hide(); } KeyboardJS.on('ctrl > p', e => { e.preventDefault(); switchprint() window.print(); }) if (inputs.print) { switchprint() } this.processInputs(); } public static getLastMonthDate() { var date = moment().subtract('months', 1).calendar() return moment(date).format("MMM YYYY") } public static getReference(companycode:string, counter: string) { //Invoice-WESTEK1108-01.odt return "Invoice-" + companycode + moment().format("YYMM") + "-" + counter; } public static processInputs() { var inputs = App.GlobalCommon.getFormInputs($("body")) amplify.store("invoice_inputs", inputs); // calculate var results : any = {}; results.days = inputs.inputdaysworked; results.net = inputs.inputdayrate * inputs.inputdaysworked; results.dayrate = inputs.inputdayrate; results.nettotal = results.net; results.vat = (inputs.inputvatrate / 100) * results.net; results.payable = results.net + results.vat; results.reference = this.getReference(inputs.inputcompanycode, inputs.inputcounter); results.invoicedate = moment().format("D MMMM YYYY"); var lastmonth = moment().subtract('month', 1).calendar(); results.lastmonth = moment(lastmonth).format("MMMM YYYY"); results.emaildatesubject = results.lastmonth; results.emaildatebody = results.lastmonth; // format var accounting = window["accounting"] results.net = results.nettotal = accounting.formatMoney(results.net, "£"); results.vat = accounting.formatMoney(results.vat, "£"); results.payable = accounting.formatMoney(results.payable, "£"); results.dayrate = accounting.formatMoney(results.dayrate, "£"); for(var propertyName in results) { $("#" + propertyName).text(results[propertyName]); } // make sure it has stuff in it var required = $("body").find("[data-required=true]") $.each(required, (x, item) => { var frag = $(item) var text = frag.text(); if (!text.length) { alert("Error: " + frag.attr("id")) } }) $("title").text(results.reference); $("body").fadeIn().fadeOut().fadeIn(); } } }<file_sep>using System; using System.Web.UI; using System.Web.UI.WebControls; namespace Tekphoria.Web.linkr { public partial class LinkRow : UserControl { public LinkRow(HyperLink link, Image editImage) { _editImage = editImage; _link = link; } protected void Page_Load(object sender, EventArgs e) {} } } <file_sep>using System; using System.Web; namespace Tekphoria.Server { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { HttpContext ctx = HttpContext.Current; var error = Server.GetLastError(); var code = (error is HttpException) ? (error as HttpException).GetHttpCode() : 500; if (code != 404) { //send mail? } if (code == 500){ Response.Clear(); Server.ClearError(); ctx.Response.StatusCode = 500; Context.Response.TrySkipIisCustomErrors = true; Context.Response.Write(error.Message); Context.Response.End(); } } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Tekphoria.Web.global_pages { public partial class ErrorPanel : InfoPanel { } }<file_sep>using System; namespace Tekphoria.Web.linkr { public partial class Default : LinkrPage { protected void Page_Load(object sender, EventArgs e) { Response.Redirect("/linkr/links"); } } } <file_sep>/// <reference path="../global_js/App.GlobalCommon.ts" /> /// <reference path="views.ts" /> module chess { export class program { public run() { this.registerEvents(); var controller :IGameController = new gamecontroller(); controller.home() } registerEvents() { amplify.subscribe("new_game_fired", (data) => { }) } } export enum gamestate { playing, waiting, settingup, none } export interface IGameController { home(); addwhiteplayer(player: player) addblackplayer(player: player) } export class gamecontroller implements IGameController { home() { var view = new views.home(); var board = new chess.board(); var game = new chess.game(); game.board = board; view.render({data:game}) } addwhiteplayer(player:player) { var client = new ChessServerClient(); client.CallMethod("AddPlayer", {player:player}) } addblackplayer(player: player) { var client = new ChessServerClient(); client.CallMethod("AddPlayer", { player: player }) } } export class game { public blackplayer: player; public whiteplayer: player; public board: board; public gamestate: gamestate = gamestate.none; } export class player { constructor(public name: string) { } } export class ChessServerClient extends App.ServerClientBase { constructor(){ super("chess_server.ashx") } } export class board { private _squares : any = []; private _graveyard : any = []; squares(): any { return this._squares; } graveyard(): any { return this._graveyard; } constructor() { this.init() } public init() { this._squares = [ ['br1', 'bk1', 'bb1', 'bkg1', 'bq', 'bb2', 'bk2', 'br2'], ['bp1', 'bp2', 'bp3', 'bp4', 'bp5', 'bp6', 'bp7', 'bp8'], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['wp1', 'wp2', 'wp3', 'wp4', 'wp5', 'wp6', 'wp7', 'wp8'], ['wr1', 'wk1', 'wb1', 'wkg1', 'wq', 'wb2', 'wk2', 'wr2'] ]; this._graveyard = [] } } }<file_sep>using System; using System.IO; namespace Tekphoria.Web.Server.Common { public static class Image { public static string GetImageServerFullPath(string path) { string webpath = path.Replace(@"/", "\\"); string fullpath = AppDomain.CurrentDomain.BaseDirectory + webpath; if (File.Exists(fullpath)) return fullpath; return AppDomain.CurrentDomain.BaseDirectory + "\\global_img\\ajax-loader.gif"; ; } } }<file_sep>/// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/keyboardjs.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> module App { export class invoice { static accounting = window["accounting"]; public static init() { var inputs = amplify.store("invoice_inputs"); var items = amplify.store("invoice_items"); if (inputs) { for (var propertyName in inputs) { $("[name="+ propertyName +"]").first().val(inputs[propertyName]); } } if (items) { $(".invoiceitems").first().html(items); } $("#inputitemqty").off("keydown").on("keydown", e => { if (this.isDeleteOrBackSpace(e)) { return true; } if ((e.keyCode < 48 || e.keyCode > 57)) { return false; } }); $("#inputincvat").off("keyup").on("keyup", () => { var inc = $("#inputincvat").val() var rate = $("#inputvatrate").val() var divder = 1 + (+rate / 100); var excl = +inc / divder $("#inputexcvat").val(accounting.formatNumber(excl, 2)) }) $("#inputitemprice").off("keydown").on("keydown", e => { if (this.isDeleteOrBackSpace(e)) { return true; } var val = "" + $(e.target).val() if (this.isFullStop(e)) { if (this.hasFullStop(val)) { return false; } else { return true; } } var chars = val.split("."); if (chars.length <= 1) { } else { if (chars.length === 2 && chars[1].length < 2) { } else { return false; } } if (this.isNotNumberKey(e)) { return false; } }); $("body").on("click", ".removeItem", e => { e.preventDefault() var row = $(e.target).closest("tr").remove() this.recalculate(); }) $("#additem").off("click").on("click", e => this.addInvoiceItem()); $("#generate-button").off("click").on("click", e => { e.preventDefault(); this.recalculate(); }); KeyboardJS.on('ctrl > s', e=> { e.preventDefault(); this.recalculate(); this.processInputs(); }); KeyboardJS.on('ctrl > f', e=> { e.preventDefault(); var form = $("#input-form"); if (form.is(':visible')) { form.hide(); } else { form.show(); } }); KeyboardJS.on('ctrl > p', e => { e.preventDefault(); $("#input-form").hide(); $("#input-items").hide(); $("#email").hide(); $(".removeItem").hide(); window.print(); }) $("#invoicedate").text(moment().format("DD MMMM YYYY")) this.processInputs(); } static isNotNumberKey(e) { if ((e.keyCode < 48 || e.keyCode > 57)) { return true; } } static hasFullStop(val) { return val.indexOf(".") !== -1 } static isFullStop(e) { return e.keyCode === 190 } static isDeleteOrBackSpace(e) { return e.keyCode === 8 || e.keyCode === 46 } static addInvoiceItem() { var inputs = App.GlobalCommon.getFormInputs($("body")) var tmpl = $("#itemrowtemplate") if ($(".invoiceitems .invoiceitem").length === 0) { $(".invoiceitems tr").first().before(tmpl.html()) } else { $(".invoiceitems .invoiceitem").last().after(tmpl.html()) } $(".itemdesc").last().text(inputs.inputitemdesc.toLocaleUpperCase()); $(".itemqty").last().text(inputs.inputitemqty); $(".itemprice").last().text(accounting.formatNumber(inputs.inputitemprice, 2)); this.recalculate(); } public static recalculate() { var inputs = App.GlobalCommon.getFormInputs($("body")) var invoiceItems = $(".invoiceitem"); var summary = { net: 0, vatrate: inputs.inputvatrate / 100, }; Enumerable.From(invoiceItems).ForEach(row => { var row = $(row) var qty = row.find(".itemqty").text(); var price = row.find(".itemprice").text(); var total = +qty * +price; row.find(".itemtotal").text(accounting.formatNumber(total, 2)); summary.net += total; }) $("#nettotal").text(accounting.formatNumber(summary.net, 2)) $("#vat").text(accounting.formatNumber(summary.net * summary.vatrate, 2)) $("#payable").text(accounting.formatMoney(summary.net + (summary.net * summary.vatrate), "£")) } public static getLastMonthDate() { var date = moment().subtract('months', 1).calendar() return moment(date).format("MMM YYYY") } public static getReference(companycode: string, counter: string) { //Invoice-WESTEK1108-01.odt return "Invoice-" + companycode + moment().format("YYMM") + "-" + counter; } public static processInputs() { var inputs = App.GlobalCommon.getFormInputs($("body")) amplify.store("invoice_inputs", inputs); amplify.store("invoice_items", $(".invoiceitems").html()); // calculate var results: any = {}; // format results.address = inputs.inputaddress; results.reference = this.getReference(inputs.inputcompanycode, inputs.inputcounter); for (var propertyName in results) { var txt = results[propertyName]; $("#" + propertyName).text(txt); $("#address").html(App.GlobalCommon.uiify(results.address).toLocaleUpperCase()) } // make sure it has stuff in it var required = $("body").find("[data-required=true]") $.each(required, (x, item) => { var frag = $(item) var text = frag.text(); if (!text.length) { alert("Error: " + frag.attr("id")) } }) $("title").text(results.reference); $("body").fadeIn().fadeOut().fadeIn(); } } }<file_sep>/// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/Things.ts" /> interface widget { toHtml(): string; } module App2 { export module widgets { export class defaultWidget implements widget { constructor(public somemodel) { } public toHtml() { return App.ViewEngine.getHtml(App.ViewEngine.tmpl["person"], this.somemodel); } } export class personWidget { constructor(public person: things.person) { } public toHtml() { return App.ViewEngine.getHtml(App.ViewEngine.tmpl["person"], this.person); } } export class addressWidget implements widget { constructor(public address: things.address) { } public toHtml() { return App.ViewEngine.getHtml(App.ViewEngine.tmpl["address"], this.address); } } export class articleWidget implements widget { constructor(public article: things.article) { } public toHtml() { return App.ViewEngine.getHtml(App.ViewEngine.tmpl["article"], this.article); } } export class logoMainWidget implements widget { constructor() { } public toHtml() { var model = new things.logomain() return App.ViewEngine.getHtml(App.ViewEngine.tmpl["logomain"], model); } } export class headerWidget implements widget { constructor() { } public toHtml() { var model = { title: "Tekphoria Main Header", phrase: "Building great stuff" }; return App.ViewEngine.getHtml(App.ViewEngine.tmpl["header"], model); } } export class footerWidget implements widget { constructor() { } public toHtml() { return App.ViewEngine.getHtml(App.ViewEngine.tmpl["footer"], {}); } } } } <file_sep>/// <reference path="../global_js/qunit.d.ts" /> module Tests { export interface IView { render(): string; render(data: any): string; } export class SomeView implements IView { public render() : string { return "rendered!" } } export class ViewTests { public static Run() { QUnit.test("IView Test",() => { var obj = { render: <string> (data: any) => { return data.name } } QUnit.equal(obj.render({name:"test"}), "test") }) } } } Tests.ViewTests.Run() <file_sep>using System; using System.CodeDom; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Text; using FluentAssertions; using NUnit.Framework; namespace Tests { [TestFixture] public class History { [TestCase("1", "1", "1")] [TestCase("1,2", "1,2", "1,2")] [TestCase("1,1,2", "1*2,2", "1,1,2")] [TestCase("1,1,2,2,2", "1*2,2*3", "1,1,2,2,2")] [TestCase("1,1,2,2,2,3", "1*2,2*3,3", "1,1,2,2,2,3")] [TestCase("10,11,11,12,11,10,9", "10*2,11*3,12,9", "10,10,11,11,11,12,9")] [TestCase("100,110,110,120,110,100,90", "100*2,110*3,120,90", "100,100,110,110,110,120,90")] [TestCase("100,100,110,110,110,120,90", "100*2,110*3,120,90", "100,100,110,110,110,120,90")] public void CompressHistory(string inputlist, string serialised, string reserialized) { int[] inputs = inputlist.Split(new[] { ',' }).Select(n => Convert.ToInt32(n)).ToArray(); var ch = new CompressHistory(); foreach (var number in inputs) { ch.Increment(number); } string res = ch.Deserialise(); string res2 = ch.DeserialiseBucket(); string res3 = ch.DeserialiseBucketGrouping(); res.Should().Be(serialised); res2.Should().Be(serialised); res3.Should().Be(serialised); List<int> list1 = ch.Serialise(serialised); var ser1 = string.Join(",", list1); ser1.Should().Be(reserialized); } [TestCase(1, 100, 100000)] public void SpeedTest(int id, int range, int totalCount) { var inputlist = new int[totalCount]; var fillTotal = 0; var rangeList = Enumerable.Range(0, 100).ToArray(); while (fillTotal < totalCount) { Shuffle(rangeList); foreach (var rdm in rangeList) { inputlist[fillTotal] = rdm; fillTotal++; } } var compressHistory = new CompressHistory(); foreach (var i in inputlist) { compressHistory.Increment(i); } var sw1 = new Stopwatch(); sw1.Start(); var res1 = compressHistory.Deserialise(); sw1.Stop(); Console.WriteLine("Deserialise took {0}", sw1.Elapsed.ToString("g")); var sw2 = new Stopwatch(); sw2.Start(); var res2 = compressHistory.DeserialiseBucket(); sw2.Stop(); Console.WriteLine("DeserialiseBucket took {0}", sw2.Elapsed.ToString("g")); var sw3 = new Stopwatch(); sw3.Start(); var res3 = compressHistory.DeserialiseBucketGrouping(); sw3.Stop(); Console.WriteLine("DeserialiseBucketGrouping took {0}", sw3.Elapsed.ToString("g")); Assert.Pass(); } public static void Shuffle<T>(IList<T> list) { var provider = new RNGCryptoServiceProvider(); int n = list.Count; while (n > 1) { var box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < n * (Byte.MaxValue / n))); int k = (box[0] % n); n--; T value = list[k]; list[k] = list[n]; list[n] = value; } } public static int GetRandom(int max) { var provider = new RNGCryptoServiceProvider(); int n = max; var box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < n * (Byte.MaxValue / n))); int k = (box[0] % n); return k; } } public class Tally { public int Number { get; set; } public int Total { get; set; } } public class CompressHistory { private List<int> _items = new List<int>(); public void Increment(int number) { _items.Add(number); } public List<int> Serialise(string input) { _items = new List<int>(); try { string[] itemsarray = input.Split(new[] { ',' }); foreach (var item in itemsarray) { var splat = item.Split(new[] { '*' }); var key = Convert.ToInt32(splat[0]); if (splat.Length == 1) _items.Add(key); else { var total = Convert.ToInt32(splat[1]); for (int i = 0; i < total; i++) _items.Add(key); } } } catch (Exception) { _items.Clear(); throw; } return _items; } public string Deserialise() { return string.Join(",", _items.Distinct() .Select(dist => new Tally { Number = dist, Total = _items.Count(i => i == dist) }) .Select(t => t.Total > 1 ? string.Format("{0}*{1}", t.Number, t.Total) : t.Number.ToString()) ); } public string DeserialiseBucket() { var countList = new Dictionary<int, int>(); foreach (var item in _items) { if (countList.ContainsKey(item)) countList[item] = countList[item] + 1; else countList[item] = 1; } return string.Join(",", countList.Select(t => t.Value > 1 ? string.Format("{0}*{1}", t.Key, t.Value) : t.Key.ToString())); } public string DeserialiseBucketGrouping() { return string.Join(",", _items.GroupBy(i => i).Select(group => new { item = group.Key,total = group.Count() }).Select(t => t.total > 1 ? string.Format("{0}*{1}", t.item, t.total) : t.item.ToString())); } } } <file_sep>namespace Tekphoria.Web.Server.Prospect { public class ProcessorActions { } }<file_sep>/// <reference path="wb.common.ts" /> interface IStorage { saveboard(boardData: any) : void; get_boards(): any; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace Tests { class Program { static void Main(string[] args) { IWebDriver driver = new ChromeDriver(); try { driver.Navigate().GoToUrl("http://devsvr-019156"); //var links = driver.FindElements(By.TagName("link")); //var canonical = links.Where(l => l.GetAttribute("rel") == "canonical"); //var source = driver.PageSource; //var mens = driver.FindElement(By.Id("mens-nav-link")); //mens.Click(); //Thread.Sleep(2000); //var boots = driver.FindElement(By.LinkText("Boots")); //boots.Click(); //Thread.Sleep(2000); //var items = driver.FindElements(By.ClassName("product-list-item")); //items.Last().Click(); } finally { driver.Quit(); } } } } <file_sep>/// <reference path="WB.Storage.ts" /> /// <reference path="WB.BoardClasses.ts" /> /// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> var WB; (function (WB) { /* ========================================================================================= */ var TaskController = (function () { function TaskController() { } TaskController.TASK_ADD_TO_STORY = function (id, hash) { var _this = this; TaskAddView.render({ id: id, hash: hash }); $("#btnsubmit").on("click", function (e) { e.preventDefault(); $(e.target).attr("disabled", "disabled"); _this.submitForm(); }); }; TaskController.submitForm = function () { var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskAddToStory", form); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(-1); }); }); }; TaskController.TASK_MOVE = function (data) { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskMove", data); }; TaskController.TASK_UPDATE_STATUS = function (data) { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data); }; TaskController.TASK_DELETE = function (deleteData) { TaskDeleteView.render(deleteData); }; TaskController.TASK_GET = function (id) { var client = new WB.ScrumboServerClient(); var serverData = client.CallMethod("TaskGet", { id: id }); $.when(serverData).then(function (resp) { return TaskEditView.render(resp); }); }; TaskController.TASK_ADD_LOG = function () { }; TaskController.validate = function (data) { if (data.IsValid !== 'undefined' && data.IsValid === false) { App.GlobalCommon.apply_validation(data, $("#form1")); } else { window.history.back(-1); } }; TaskController.TASK_DELETE_REPLY = function (data) { window.history.back(-1); }; return TaskController; })(); WB.TaskController = TaskController; var TaskMenuView = (function () { function TaskMenuView() { } TaskMenuView.getHtml = function (task) { return App.ViewEngine.getHtml(this.getTemplate(), task); }; TaskMenuView.getTemplate = function () { return "<div class='taskmenu' data-id={{id}}>" + "<a href='#' class='act'>Edit</a>" + "<a href='#' class='act'>Add Log</a>" + "<a href='#' class='act'>Add File</a>" + "<a href='#' class='act'>Archive</a>" + "<a href='#' class='act'>Delete</a>" + "</div>"; }; TaskMenuView.render = function (task) { App.ViewEngine.renderview(this.getTemplate(), task); }; return TaskMenuView; })(); WB.TaskMenuView = TaskMenuView; var LogNote = (function () { function LogNote(textof) { this.textof = textof; } return LogNote; })(); WB.LogNote = LogNote; var LogNoteRowView = (function () { function LogNoteRowView() { } LogNoteRowView.render = function (note) { return App.ViewEngine.renderview(LogNoteRowView.getTemplate(), note); }; LogNoteRowView.getHtml = function (note) { return App.ViewEngine.getHtml(LogNoteRowView.getTemplate(), note); }; LogNoteRowView.getTemplate = function () { return "<div class='lognoterow'><span class='glyphicon glyphicon-pencil'>&nbsp;</span><span class='lognote'>{{textof}}</span></div>"; }; return LogNoteRowView; })(); WB.LogNoteRowView = LogNoteRowView; var TaskView = (function () { function TaskView() { } TaskView.adjustModel = function (task) { if (!task.css_class) task.css_class = 'task'; task.isEditable = task.status === "TODO"; task.showUser = (task.user_id > 0); task.fuzzyModified = moment.utc(task.date_modified).fromNow(); task.textof = App.GlobalCommon.uiify(task.textof); return task; }; TaskView.render = function (task) { this.adjustModel(task); App.ViewEngine.renderview(this.getTemplate(task), task); }; TaskView.getHtml = function (task) { this.adjustModel(task); //task["archivelink"] = task.status === 'DONE' ? "<br><a class='btn btn_status btn-xs' alt='Archive this task' href='#' data-status='ARCHIVE' data-id='{{id}}'>archive</a>" : "" return App.ViewEngine.getHtml(this.getTemplate(task), task); }; // static tmpl : string; TaskView.getTemplate = function (task) { var tmpl = ""; var logNoteRow = LogNoteRowView.getTemplate(); var archive = task.status === 'DONE' ? "<br><a class='btn btn_status btn-xs' alt='Archive this task' href='#' data-status='ARCHIVE' data-id='{{id}}'>archive >></a>" : ""; var tmpl = "<div class='task {{css_class}} clearfix' data-id='{{id}}' data-status='{{status}}'>" + "<div class='ttext'> {{&textof}} " + "<span class='more'>[more...]</span>" + archive + "<div class=lognotes>{{#log_notes}}" + logNoteRow + "{{/log_notes}}</div>" + "<div class='task-foot clearfix'>" + "---<br><span class=''>#{{id}}</span> changed <span>{{fuzzyModified}} by {{display_name}}</span><span class='usercss_{{user_id}}'></span>" + " <a data-id={{id}} class='taskmore' alt='View taskbar' href='#task/{{id}}'>[edit]</a>" + " <a data-id={{id}} class='addlog' alt='Add a task comment' href='#'>[add notelog]</a> " + " <a data-id={{id}} class='' alt='View Task Log' href='#task/{{id}}/log'>[see {{note_count}} in note log]</a>" + " </div>" + "</div>" + "</div>"; return tmpl; }; return TaskView; })(); WB.TaskView = TaskView; var TaskDeleteView = (function () { function TaskDeleteView() { } TaskDeleteView.render = function (id) { App.ViewEngine.renderview(this.getTemplate(), { id: id }); $("#btnsubmit").on("click", function (e) { e.preventDefault(); var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskDelete", form); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.routie("board/" + amplify.store('last_board_hash')); }); }); }); }; TaskDeleteView.getTemplate = function () { var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden'); var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-trash'></span> Delete Task</h2>", id + " <span class='label label-danger'>Warning</span> <span>Pressing Submit will delete the task and any associated objects permenantly.</span><br><br>"); return App.GlobalCommon.container(form); }; return TaskDeleteView; })(); WB.TaskDeleteView = TaskDeleteView; var TaskAddLogView = (function () { function TaskAddLogView() { } TaskAddLogView.render = function (data) { App.ViewEngine.renderview(this.getTemplate(), data); }; TaskAddLogView.getHtml = function (data) { return App.ViewEngine.getHtml(this.getTemplate(), data); }; TaskAddLogView.getTemplate = function () { $("#addlogid").remove(); var lines = []; lines.push('<div class="addlogview">'); lines.push('<form role="form" class="form-vertical" id="formAddLog">'); lines.push('<input class="form-editing" type="text" id="textof" name="addlogid" value="" maxlength="50"/>'); lines.push('<input class="form-editing" type="hidden" id="addlogid" name="addlogid" value="{{id}}" maxlength="50"/>'); lines.push(' <button id="btnaddlog" data-id="0" class="btn btn-primary btn-xs clearfix">add</button>'); lines.push('<div id="errors"></div>'); lines.push('</form>'); lines.push('</div>'); return lines.join(''); }; return TaskAddLogView; })(); WB.TaskAddLogView = TaskAddLogView; var TaskAddView = (function () { function TaskAddView() { } TaskAddView.render = function (taskViewData) { App.ViewEngine.renderview(this.getTemplate(), taskViewData); }; TaskAddView.getTemplate = function () { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{textof}}', '', "4"); var id = App.GlobalCommon.inputstring('story_id', 'story_id', "{{id}}", '', 'hidden'); var css = ""; css += App.GlobalCommon.radio('css_class', 'taskyellow', 'Yellow', 'yellow taskmini', true); css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', ' green taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'orange taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'pink taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'blue taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'purple taskmini', false); var hash = App.GlobalCommon.inputstring('hash', 'hash', "{{hash}}", '', 'hidden'); var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-leaf'></span> New Task</h2>", textof + id + css + hash + "<br><br>"); return App.GlobalCommon.container(form); }; return TaskAddView; })(); WB.TaskAddView = TaskAddView; var TaskEditView = (function () { function TaskEditView() { } TaskEditView.prototype.render = function (data) { }; TaskEditView.prototype.registerEvents = function () { }; TaskEditView.prototype.getHtml = function () { return ""; }; TaskEditView.render = function (taskViewData) { var html = App.ViewEngine.renderview(this.getTemplate(taskViewData), taskViewData); $("input:radio[value=" + taskViewData.css_class + "]").first().attr('checked', "checked"); $("#btnsubmit").on("click", function (e) { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskUpdateText", data); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(-1); }); }); }); return html; }; TaskEditView.getTemplate = function (data) { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{&textof}}', '', "4"); var css = "<br>"; css += App.GlobalCommon.radio('css_class', 'taskyellow', 'Yellow', 'yellow taskmini', true); css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'green taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'orange taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'pink taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'blue taskmini', false); css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'purple taskmini', false); var id = "<input class='form-editing' type='hidden' id='id' name='id' value='{{id}}' maxlength='50'>"; var form = App.GlobalCommon.form("<h2><span class='glyphicon glyphicon-edit'></span> Edit Task #{{id}}</h2>", textof + css + TaskSetStatusView.getHtml(data) + id); return App.GlobalCommon.container(form); }; return TaskEditView; })(); WB.TaskEditView = TaskEditView; var TaskSetStatusView = (function () { function TaskSetStatusView() { } TaskSetStatusView.getHtml = function (data) { this.init(data); return App.ViewEngine.getHtml(this.getTemplate(), data); }; TaskSetStatusView.init = function (data) { $("body").on("click", ".btn_status", function (e) { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); client.CallMethod(status === 'DELETE' ? "TaskDelete" : "TaskUpdateStatus", data); window.history.back(-1); }); }; TaskSetStatusView.render = function (data) { this.init(data); return App.ViewEngine.renderview(this.getTemplate(), data); }; TaskSetStatusView.getTemplate = function () { var tmp = "<div class='clearfix'></div><div class='clearfix btn-group'>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='INPROGRESS'>In progress</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='TODO'>To do</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='DONE'>Done</a>" + "<a class='btn btn-default btn_status' href='#' data-id='{{id}}' data-status='ARCHIVE'>Archive</a>" + "<a class='btn btn-default btn_status btn-warning' href='#' data-id='{{id}}' data-status='DELETE'>Delete</a>" + "</div><br><br>"; return tmp; }; return TaskSetStatusView; })(); WB.TaskSetStatusView = TaskSetStatusView; var TaskMoreBarView = (function () { function TaskMoreBarView() { } TaskMoreBarView.setData = function (data) { data.trashview = WB.BoardTrashView.getHtml(); return data; }; TaskMoreBarView.render = function (data) { this.setData(data); return App.ViewEngine.renderview(this.getTemplate(), this.setData(data)); }; TaskMoreBarView.setEvents = function () { }; TaskMoreBarView.getHtml = function (data) { this.setData(data); return this.render(data); }; TaskMoreBarView.getTemplate = function () { return "<div data-id=0 id='TaskMoreBarView' class='taskmoreviewbar'><strong>Task Bar</strong>" + " <a class = 'btntaskedit' alt='view and edit details' href='#'><i class='icon-edit'></i> edit</a>" + " <a class = 'btntaskaddlog' alt='add log' href='#'><i class='icon-th-list'></i> add log</a>" + " <a class = 'btntaskarchive' alt='archive of the board' href='#'><i class='icon-folder-close'></i> archive</a>" + " <a class = 'btntaskclose' alt='close this' href='#' ><i class='icon-remove'></i> close </a>" + " <a class = 'btntaskdelete' alt='delete' href='#'><i class='icon-trash'></i> delete</a>" + " </div >"; }; return TaskMoreBarView; })(); WB.TaskMoreBarView = TaskMoreBarView; var Task = (function () { function Task(id, nameof, textof, story_id, status, sort_order, isEditable, css_class, user_id, showUser, fuzzyModified, display_name, date_modified, note_count, log_notes) { this.id = id; this.nameof = nameof; this.textof = textof; this.story_id = story_id; this.status = status; this.sort_order = sort_order; this.isEditable = isEditable; this.css_class = css_class; this.user_id = user_id; this.showUser = showUser; this.fuzzyModified = fuzzyModified; this.display_name = display_name; this.date_modified = date_modified; this.note_count = note_count; this.log_notes = log_notes; } return Task; })(); WB.Task = Task; })(WB || (WB = {})); <file_sep>module linkr { export class app { public static start() { } } }<file_sep>using System; using System.Drawing; using System.IO; using System.Web; using ImageResizer; namespace Tekphoria.Web.Server.Handlers { public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; if (context.Request.Files.Count == 0) { context.Response.Write("Waiting for file."); } else { try { HttpPostedFile file = context.Request.Files["clientfile"]; string userid = context.Request.Form["id"]; var path = InitPath(context, userid, file); File.Delete(path); Bitmap b = ImageBuilder.Current.Build( file.InputStream, new ResizeSettings { MaxHeight = 30, MaxWidth = 30 }); b.Save(path); } catch (Exception ex) { context.Response.Write("Error " + ex.Message); } context.Response.Write("OK"); } context.Response.End(); } private string InitPath(HttpContext ctx, string userId, HttpPostedFile file) { return ctx.Server.MapPath(".") + "\\userfiles\\" + userId + ".jpg"; } public bool IsReusable { get { return false; } } } }<file_sep>using System; using System.Data; using System.Linq; using System.Web; using FluentValidation; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Server.Common; namespace Tekphoria.Server.Scrumbo { public class ScrumboServer : JsonServer, IHttpHandler { private readonly Lazy<IDbConnection> _scrumboDb = new Lazy<IDbConnection>(() => GetOpenConnection(Config.GetScrumboConnectionString.Value)); public new void ProcessRequest(HttpContext context) { try { base.ProcessRequest(context); } catch (Exception ex) { HandleError(ex); } finally { CloseConnection(_scrumboDb); } } private readonly string[] _columns = new[] { "TODO", "INPROGRESS", "DONE" }; public object StorySetStatus(dynamic data) { string status = ((string)data.status).ToUpperInvariant().Trim(); _scrumboDb.Value.Execute("update stories set status=@status where id=@id", new { data.id, status }); if (status == "DONE" || status == "ARCHIVE") _scrumboDb.Value.Execute("update tasks set status=@status where story_id=@story_id", new { story_id = data.id, status = "ARCHIVE" }); return true; } public object BoardGetArchiveByHash(dynamic data) { int board_id = GetBoardIdFromHash((string)data.hash); dynamic tasksAll = _scrumboDb.Value.Query( "select * from tasks where board_id=@board_id AND user_id=@user_id and status in('DONE','ARCHIVE') order by date_done desc limit 200;", new { data.user_id, board_id }).ToList(); return new { tasks = tasksAll }; } public object UserUpdate(IDbConnection conn, dynamic data) { conn.Execute("update users set display_name=@display_name,password=<PASSWORD> where id=@id;", new { data.id, data.password, data.display_name }); return true; } public object UserGet(dynamic data) { return _scrumboDb.Value.Query("select * from users where id=@id;", new { data.id }).Single(); } public object UserAddSharedBoard(dynamic data) { _scrumboDb.Value.Execute("insert into user_boards (user_id, board_hash) values (@user_id, @hash);", new { data.user_id, data.hash }); return true; } public object UserAdd(dynamic data) { dynamic res = _scrumboDb.Value.Query<dynamic>( "insert into users (email,display_name,password) values (@email,@display_name,@password);select last_insert_id() as newid;", new { data.email, data.password, data.display_name }).Single(); return new { id = res.newid }; } public object BoardSortStory(dynamic data) { JToken[] jTokens = ((JArray)data.story_order).ToArray(); for (int i = 0; i < jTokens.Length; i++) { string valueof = (jTokens[i]).ToString(); _scrumboDb.Value.Execute("update stories set sort_order=@i where id=@valueof", new { i, valueof }); } return true; } public ValidationResult Validate(IValidator validator, dynamic data) { ValidationResult result = validator.Validate(data); return result; } public object BoardSetConfiguration(dynamic data) { var validator = new Validators.BoardConfigValidator(); ValidationResult result = validator.Validate(data); if (!result.IsValid) return new { result }; int id = GetBoardIdFromHash((string)data.hash); string extra_status_1 = ((string)data.extra_status_1).ToUpperInvariant(); string extra_status_2 = ((string)data.extra_status_2).ToUpperInvariant(); return _scrumboDb.Value.Execute( "update boards set nameof=@nameof,extra_status_1=@extra_status_1,extra_status_2=@extra_status_2,more_info=@more_info where id=@id;", new { data.nameof, extra_status_1, extra_status_2, data.more_info, id } ); } public object BoardGetConfiguration(dynamic data) { var board = _scrumboDb.Value.Query("select id,nameod,hash,extra_status_1,extra_status_2,more_info,row_header_name from boards where hash=@hash;", new { data.hash }).FirstOrDefault(); return new { board }; } public object StoryUpdateText(dynamic data) { _scrumboDb.Value.Execute("update stories set textof=@textof where id=@id;", new { data.textof, data.id }); return true; } public object StoryGet(dynamic data) { dynamic story = _scrumboDb.Value.Query("select * from stories where id=@id;", new { data.id }).FirstOrDefault(); return story; } public object TaskUpdateText(dynamic data) { var textof = (string)data.textof; textof = textof.Replace("•", "&bull;"); return _scrumboDb.Value.Execute( "update tasks set textof=@textof,css_class=@css_class,user_id=@user_id,date_modified=@date_modified where id=@id;", new { data.id, textof, data.css_class, data.user_id, date_modified = DateTime.UtcNow }); } public object TaskGet(dynamic data) { dynamic task = _scrumboDb.Value.Query("select * from tasks where id=@id", new { data.id }).FirstOrDefault(); return task; } public object TaskAddToStory(dynamic data) { int board_id = GetBoardIdFromHash((string)data.hash); return _scrumboDb.Value.Execute( "insert into tasks (textof,story_id,board_id,sort_order,status,css_class) values (@textof, @story_id, @board_id, 100,'TODO',@css_class); SELECT last_insert_id() as Last_ID;" , new { data.textof, data.story_id, board_id, data.css_class } ); } public object TaskDelete(dynamic data) { _scrumboDb.Value.Execute("delete from tasks where id=@id", new { data.id }); return true; } public object TaskUpdateStatus(dynamic data) { string status = ((string)data.status).ToUpperInvariant(); _scrumboDb.Value.Execute("update tasks set status=@status,user_id=@user_id,date_modified=@date_modified where id=@id", new { data.id, status, data.user_id, date_modified = DateTime.UtcNow } ); return true; } public object TaskMove(dynamic data) { JToken[] arry = ((JArray)data.task_ordering).ToArray(); for (int i = 0; i < arry.Length; i++) { string valueof = (arry[i]).ToString(); _scrumboDb.Value.Execute("update tasks set sort_order=@i where id=@valueof", new { i, valueof }); } string status = ((string)data.status).ToUpperInvariant(); _scrumboDb.Value.Execute( "update tasks set story_id=@story_id, status=@status,story_id=@story_id, user_id=@user_id, date_modified=@date_modified where id=@id", new { data.story_id, data.sort_order, data.id, status, data.user_id, date_modified = DateTime.UtcNow } ); if (status == "DONE" || status == "ARCHIVE") _scrumboDb.Value.Execute( "update tasks set date_done=@date_done where id=@id", new { date_done = DateTime.UtcNow, data.id }); data.textof = " to " + status; data.action = (int)ActionEnum.TASK_MOVE; data.board_id = GetBoardIdFromHash((string)data.board_id); InsertLogItem(data); return true; } public void InsertLogItem(dynamic data) { _scrumboDb.Value.Execute( "insert into log_items (board_id,story_id,task_id,user_id,action,textof) values (@board_id,@story_id,@task_id,@user_id,@action,@textof)", new { data.board_id, data.story_id, task_id = data.id, data.user_id, data.action, data.textof } ); } public object StoryAddToBoard(dynamic data) { int id = GetBoardIdFromHash((string)data.hash); int newid = _scrumboDb.Value.Execute( "insert into stories (textof, board_id, sort_order, status) values (@textof, @board_id, @sort_order, @status); SELECT last_insert_id() as Last_ID;", new { data.textof, board_id = id, sort_order = 100, status = "TODO" } ); return newid; } public object StoryAddToBoardByid(dynamic data) { int newid = _scrumboDb.Value.Execute( "insert into stories (textof, board_id, sort_order, status) values (@textof, @board_id, @sort_order, @status); SELECT last_insert_id() as Last_ID;", new { data.textof, data.board_id, sort_order = 100, status = "TODO" } ); return true; } public object StoryDelete(dynamic data) { _scrumboDb.Value.Execute("delete from stories where id=@id;delete from tasks where story_id=@id;", new { data.id } ); return true; } public object BoardDelete(dynamic data) { int id = GetBoardIdFromHash((string)data.hash); _scrumboDb.Value.Execute( "delete from boards where id=@id;delete from stories where board_id=@id;delete from tasks where board_id=@id;", new { id }); return true; } public int GetBoardIdFromHash(string hash) { dynamic boardrow = _scrumboDb.Value.Query("select id from boards where hash=@hash", new { hash }).Single(); return (int)boardrow.id; } public object BoardGetByHash(dynamic data) { dynamic board = _scrumboDb.Value.Query<dynamic>( "select id,nameof,hash,group_hash,extra_status_1,extra_status_2,more_info from boards where hash=@hash", new { data.hash }).FirstOrDefault(); if (board == null) return new { board }; // and status in(@StoryDisplayStatuses); dynamic stories = _scrumboDb.Value.Query( "select id,textof,board_id,sort_order,status,date_created from stories where board_id=@id and status <> 'DONE';", new { board.id }).ToList(); dynamic tasks = _scrumboDb.Value.Query( "select id,textof,story_id,board_id,sort_order,status,css_class,user_id,date_created,date_modified from tasks where board_id=@id and status not in ('ARCHIVE');", new { board.id }).ToList(); // dynamic log_items = _scrumboDb.Value.Query("select * from log_items where board_id=@id order by id desc limit 10;", new { board.id }).ToList(); string board_users = "select * from users where id in(select user_id from user_boards where board_hash=@hash);"; dynamic users = _scrumboDb.Value.Query(board_users, new { data.hash }).ToList(); dynamic actions = Enum.GetNames(typeof(ActionEnum)); return new { board, stories, tasks, columns = _columns, users, actions }; } public object BoardsList(dynamic data) { return new { BoardSummaries = _scrumboDb.Value.Query( "select * from boards where hash in (select board_hash from user_boards where user_id=@user_id)", new { data.user_id }).ToList() }; } public dynamic BoardAdd(dynamic data) { var validator =new Validators.BoardValidator(); ValidationResult validationResult = validator.Validate(data); if (!validationResult.IsValid) return validationResult; dynamic result = _scrumboDb.Value.Query<dynamic>( "insert into boards (nameof, hash, more_info) values (@nameof, @hash, ''); SELECT last_insert_id() as newid;", new { data.nameof, data.hash }) .Single(); UserAddSharedBoard(data); StoryAddToBoardByid(new { textof = "General Work", board_id = result.newid }); return true; } public object UserRecentTasks(dynamic data) { dynamic tasks = _scrumboDb.Value.Query("select * from tasks where user_id=@user_id", new { data.user_id }).ToArray(); return new { tasks }; } } }<file_sep>/// <reference path="../global_js/amplify.d.ts" /> /// <reference path="../global_js/jquery-1.9.1.d.ts" /> module App { export class File { constructor( Name: string, Size: number, Created: string, Modified: string, Extension: string ) { } } }<file_sep>using System; using System.Drawing; using System.IO; using System.Web; using ImageResizer; namespace Tekphoria.Web.Server.Handlers { public class Upload2Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; if (context.Request.Files.Count == 0) { context.Response.Write("Waiting for file."); } else { try { HttpPostedFile file = context.Request.Files[0]; var path = AppDomain.CurrentDomain.BaseDirectory + "\\userfiles\\shared\\" + file.FileName; if(File.Exists(path)) File.Delete(path); Bitmap b = ImageBuilder.Current.Build(file.InputStream,new ResizeSettings(1024, 1024, FitMode.Max, "jpg")); // Bitmap b1 = ImageBuilder.Current.Build(new ImageJob(file,path, new Instructions("jpg",false,true)); b.Save(path); context.Response.Write("OK"); } catch (Exception ex) { context.Response.Write(ex.ToString()); } } context.Response.End(); } public bool IsReusable { get { return false; } } } }<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Net; using System.Net.Mail; namespace Tekphoria.Web.Server.Common { public static class Config { public static string GoogleApiKey = ConfigurationManager.AppSettings["mail_admin_email"]; private static readonly Dictionary<string, string> EncyptedConnectionStrings = new Dictionary<string, string> { { "ProspectsDbConnectionString-live" , "<KEY> } , { "GetCommonDbConnectionString-live" , "<KEY> } , { "ScrumboDbConnectionString-live" , "<KEY> } }; public static readonly Lazy<string> GetProspectsConnectionString = new Lazy<string>(() => { if (IsDevMachine) return "Server=localhost;Database=prospector;Uid=dev;Password=<PASSWORD>"; return GetDecryptedConstr ( "ProspectsDbConnectionString-live"); }); public static readonly Lazy<string> GetScrumboConnectionString = new Lazy<string>(() => { if (IsDevMachine) return "Server=localhost;Database=scrumbo;Uid=dev;Password=<PASSWORD>"; return GetDecryptedConstr ( "ScrumboDbConnectionString-live"); }); public static readonly Lazy<string> GetCommonDbConnectionString = new Lazy<string>(() => { if (IsDevMachine) return "Server=localhost;Database=common;Uid=dev;Password=<PASSWORD>"; return GetDecryptedConstr ( "GetCommonDbConnectionString-live"); }); public static readonly string ID = "d866f9e8"; public static bool IsDevMachine { get { return Environment.MachineName == "DEVSVR-019156" || Environment.MachineName == "TUI" || Environment.MachineName == "MOKO" || Environment.MachineName == "WETA"; } } public static string FilesPath { get { return AppDomain.CurrentDomain.BaseDirectory + "userfiles\\files"; } } public static NetworkCredential EmailCredentials { get { return new NetworkCredential { UserName = ConfigurationManager.AppSettings.Get("mail_username"), Password = Crypto.DecryptStringAES(ConfigurationManager.AppSettings.Get("mail_password"), ID) }; } } public static string EmailServer { get { return ConfigurationManager.AppSettings["mail_server"]; } } public static MailAddress EmailAddress { get { return new MailAddress(ConfigurationManager.AppSettings["mail_username"]); } } public static string GetDecryptedConstr(string key) { // dbo535009992 return Crypto.DecryptStringAES(EncyptedConnectionStrings[key], ID); } } }<file_sep>/// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="wb.errorclasses.ts" /> /// <reference path="wb.common.ts" /> /// <reference path="wb.interfaces.ts" /> /// <reference path="wb.errorclasses.ts" /> module WB { /* ========================================================================================= */ export class EventNames { public static BOARDS_LIST: string = "BOARDS_LIST"; public static BOARD_ADD: string = "BOARD_ADD"; public static BOARD_DELETE: string = "BOARD_DELETE"; public static BOARD_GET: string = "BOARD_GET"; public static BOARD_GET_BY_HASH: string = "BOARD_GET_BY_HASH"; public static STORY_ADD_TO_BOARD: string = "STORY_ADD_TO_BOARD"; public static STORY_DELETE: string = "STORY_DELETE"; public static TASK_ADD_TO_STORY: string = "TASK_ADD_TO_STORY"; public static TASK_MOVE: string = "TASK_MOVE"; public static TASK_GET: string = "TASK_GET"; public static TASK_UPDATE_TEXT: string = "TASK_UPDATE_TEXT"; public static TASK_UPDATE_STATUS: string = "TASK_UPDATE_STATUS"; public static STORY_GET: string = "STORY_GET"; public static TASK_DELETE: string = "TASK_DELETE"; public static STORY_UPDATE_TEXT: string = "STORY_UPDATE_TEXT"; public static BOARD_GET_CONFIGURATION: string = "BOARD_GET_CONFIGURATION"; public static BOARD_SET_CONFIGURATION: string = "BOARD_SET_CONFIGURATION"; public static BOARD_SORT_STORY: string = "BOARD_SORT_STORY"; public static USER_SIGN_IN_REQUIRED: string = "USER_SIGN_IN_REQUIRED"; public static USER_SIGN_IN_TRY: string = "USER_SIGN_IN_TRY"; public static USER_ADD: string = "USER_ADD"; public static LOCAL_ISLOGGEDIN: string = "IsLoggedIn"; public static LOCAL_EMAIL: string = "Email"; public static LOCAL_USERID: string = "UserId"; public static USER_ADD_SHARED_BOARD: string = "USER_ADD_SHARED_BOARD"; public static USER_GET: string = "USER_GET"; public static USER_UPDATE: string = "USER_UPDATE"; public static BOARD_GET_ARCHIVE: string = "BOARD_GET_ARCHIVE"; public static STORY_SET_STATUS: string = "STORY_SET_STATUS"; } /* ========================================================================================= */ export class Payload { constructor(public action: string, public data: any) { } } export class WebStorage { public static sendPayload(payload: Payload, next: Function) { if (amplify.store(EventNames.LOCAL_ISLOGGEDIN) === "1") { } else if (payload.action !== WB.EventNames.USER_SIGN_IN_TRY && payload.action !== WB.EventNames.USER_ADD) { amplify.publish(WB.EventNames.USER_SIGN_IN_REQUIRED) return; } $.ajax({ type: "POST", url: '/scrumbo/scrumbo_server.ashx', headers: { "UserId": amplify.store(EventNames.LOCAL_USERID) }, dataType: 'JSON', cache: false, contentType: "application/json; charset=utf-8", data: JSON.stringify(payload), success: function (data, b, c) { next(data); }, error: function () { }, statusCode: { 404: (data, two, three) => ErrorController.Show(new WB.Error("404 Not Found","The method was not found.", "")), 403: (data, two, three) => ErrorController.Show(new WB.Error("403 Access denied","Access is not permitted to this service.", "")), 500: (data, two, three) => ErrorController.Show(new WB.Error("500 Server Error", data.responseText, "")) } }) } public static BOARD_GET_CONFIGURATION_ASYNC(hash): any { var payload = new Payload(WB.EventNames.BOARD_GET_CONFIGURATION, {hash:hash}); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_GET_CONFIGURATION + "_REPLY", data); }); } public static BOARD_SET_CONFIGURATION_ASYNC(setConfigData): any { var payload = new Payload(WB.EventNames.BOARD_SET_CONFIGURATION, setConfigData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_SET_CONFIGURATION + "_REPLY", data); }); } public static BOARDS_LIST_ASYNC(): any { var payload = new Payload(WB.EventNames.BOARDS_LIST, {}); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARDS_LIST + "_REPLY", data); }); } public static BOARD_ADD_ASYNC(boardData: any): void { var payload = new Payload(WB.EventNames.BOARD_ADD, boardData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_ADD + "_REPLY", data); }); } public static BOARD_DELETE_ASYNC(hash: string): void { var payload = new Payload(WB.EventNames.BOARD_DELETE, { hash: hash }); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_DELETE + '_REPLY', data); }); } public static BOARD_GET_BY_HASH_ASYNC(hash: string): void { var payload = new Payload(WB.EventNames.BOARD_GET_BY_HASH, { hash: hash }); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_GET_BY_HASH + "_REPLY", data); }); } public static STORY_DELETE_ASYNC(storyDeleteData: any): void { var payload = new Payload(WB.EventNames.STORY_DELETE,storyDeleteData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.STORY_DELETE + "_REPLY", data); }); } public static TASK_ADD_TO_STORY_ASYNC(addTaskToStoryData: any): void { var payload = new Payload(WB.EventNames.TASK_ADD_TO_STORY, addTaskToStoryData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_ADD_TO_STORY + "_REPLY", data); }); } public static TASK_MOVE_ASYNC(taskMoveData: any): void { var payload = new Payload(WB.EventNames.TASK_MOVE, taskMoveData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_MOVE + "_REPLY", data); }); } public static TASK_GET_ASYNC(taskGetData: any): void { var payload = new Payload(WB.EventNames.TASK_GET, taskGetData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_GET + "_REPLY", data); }); } public static TASK_UPDATE_TEXT_ASYNC(updateTextData: any): void { var payload = new Payload(WB.EventNames.TASK_UPDATE_TEXT, updateTextData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_UPDATE_TEXT + "_REPLY", data); }); } public static TASK_DELETE_ASYNC(deleteData: any): void { var payload = new Payload(WB.EventNames.TASK_DELETE, deleteData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_DELETE + "_REPLY", data); }); } public static STORY_GET_ASYNC(storyGetData: any): void { var payload = new Payload(WB.EventNames.STORY_GET, storyGetData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.STORY_GET + "_REPLY", data); }); } public static STORY_UPDATE_TEXT_ASYNC(storyGetData: any): void { var payload = new Payload(WB.EventNames.STORY_UPDATE_TEXT, storyGetData); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.STORY_UPDATE_TEXT + "_REPLY", data); }); } public static BOARD_SORT_STORY_ASYNC(data) { var payload = new Payload(WB.EventNames.BOARD_SORT_STORY, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_SORT_STORY + "_REPLY", data); }); } public static TASK_UPDATE_STATUS_ASYNC(data) { var payload = new Payload(WB.EventNames.TASK_UPDATE_STATUS, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.TASK_UPDATE_STATUS + "_REPLY", data); }); } public static USER_SIGN_IN_ASYNC(data) { var payload = new Payload(WB.EventNames.USER_SIGN_IN_TRY, data); this.sendPayload(payload, (data) => { amplify.store("user", data); amplify.publish(WB.EventNames.USER_SIGN_IN_TRY + "_REPLY", data); }); } public static USER_ADD_ASYNC(data) { var payload = new Payload(WB.EventNames.USER_ADD, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.USER_ADD + "_REPLY", data); }); } public static USER_ADD_SHARED_BOARD_ASYNC(data) { var payload = new Payload(WB.EventNames.USER_ADD_SHARED_BOARD, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.USER_ADD_SHARED_BOARD + "_REPLY", data); }); } public static USER_GET(data) { var payload = new Payload(WB.EventNames.USER_GET, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.USER_GET + "_REPLY", data); }); } public static USER_UPDATE_ASYNC(data) { var payload = new Payload(WB.EventNames.USER_UPDATE, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.USER_UPDATE + "_REPLY", data); }); } public static BOARD_GET_ARCHIVE_ASYNC(data) { var payload = new Payload(WB.EventNames.BOARD_GET_ARCHIVE, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.BOARD_GET_ARCHIVE + "_REPLY", data); }); } public static STORY_SET_STATUS_ASYNC(data) { var payload = new Payload(WB.EventNames.STORY_SET_STATUS, data); this.sendPayload(payload, (data) => { amplify.publish(WB.EventNames.STORY_SET_STATUS + "_REPLY", data); }); } } }<file_sep>namespace Tekphoria.Web.Server.Common { public static class Extensions { public static string RemoveTrailingSlash(this string input) { if (string.IsNullOrWhiteSpace(input)) return input; return input.Trim(new[]{'\\','/'}); } } }<file_sep>using System; namespace Tekphoria.Web.Server.Common.Routing { public interface IRouteInfo { string[] NoOptionalParams { get; } string[] RawSegments { get; } dynamic DefaultArgs { get; } string Template { get; } Func<dynamic, dynamic> Fn { get; } string[] UriSegments { get; } string[] RouteParams { get; } string[] OptionalParams { get; } string Comparator { get; } dynamic RouteArgs { get; set; } dynamic Execute(); } }<file_sep>/// <reference path="../../../global_js/jquery-1.9.1.d.ts" /> interface Array<T> { prln(p1?: string); } Array.prototype.prln = (val? : string) => { this.push('<br>' + val) } module app { export class board { public static sidelength: number = 3; public static tilecount: number = board.sidelength * board.sidelength; public static ary: number[][]; public static rnd: number; public static row: number; public static col: number; static init() { this.ary = new Array(this.sidelength) for (var i = 0; i < this.ary.length; i++) { var row = new Array(this.sidelength) for (var j = 0; j < row.length; j++) { row[j] = 0 } this.ary[i] = row; } } static clear() { if (!this.ary) { this.init() } for (var i = 0; i < this.ary.length; i++) { var row = this.ary[i] for (var j = 0; j < row.length; j++) { row[j] = 0 } } } public static refresh() { this.clear() this.rnd = Math.floor(Math.random() * this.tilecount); //var r = Math.floor(7 / 3); this.row = Math.floor(this.rnd / this.sidelength); this.col = this.rnd % this.sidelength; this.ary[this.row][this.col] = 1; } } export class piece { public symbol: string = ''; } enum state { UNKNOWN, RUNNING, STOPPED } export class random { // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c private m: number = 4294967296 // a - 1 should be divisible by m's prime factors private a: number = 1664525 // c and m should be co-prime private c = 1013904223 private seed private z public setSeed(val) { this.z = this.seed = val || Math.round(Math.random() * this.m); } getSeed() { return this.seed; } public generate() { // define the recurrence relationship this.z = (this.a * this.z + this.c) % this.m; // return a float in [0, 1) // if z = m then z / m = 0 therefore (z % m) / m < 1 always return this.z / this.m; } } export class textRenderer { static line: string = '--------------------' static dbline: string = '====================' static empty: string = '' public static render() { var lines = []; lines.prln(textRenderer.line); lines.prln(game.nameof + ' ' + game.version); //lines.prln('by ' + ' ' + game.auther); lines.prln(textRenderer.dbline); lines.prln(textRenderer.getBoard()); lines.prln(this.empty); lines.prln(textRenderer.line); lines.prln('score ' + game.score); lines.prln('level ' + game.level); lines.prln('frame ' + game.currentFrame); //lines.prln('rnd ' + game.rnd); //lines.prln('row ' + board.row); //lines.prln('col ' + board.col); return lines.join(''); } public static getBoard1() { var cellId = 0; var lines = []; var row = []; for (var r = 0; r < board.ary.length; r++) { row = board.ary[r]; lines.push('<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;') for (var c = 0; c < row.length; c++) { cellId += 1; lines.push(textRenderer.renderCell({ val: row[c] })); } } return lines.join(''); } public static getBoard() { var cellId = 0; var lines = []; lines.push('<table>') var row = []; for (var r = 0; r < board.ary.length; r++) { lines.push('<tr>') row = board.ary[r]; for (var c = 0; c < row.length; c++) { cellId += 1; lines.push(textRenderer.renderCell({ val: row[c] })); } lines.push('<tr>') } lines.push('</table>') return lines.join(''); } public static renderCell(data) { if (data.val === 1) return '<td class=hit>&nbsp;</td>'; return '<td>&nbsp;</td>'; } } export class game { public static nameof: string = 'Tappit'; public static version: string = '0.1'; public static auther: string = 'Eloise'; public static levelframes: number = 100; public static score: number = 0; public static level: number = 1; public static state: number = state.STOPPED; public static framerate: number = 1; public static board_data: board = board.ary public static rnd : number = 0; public static currentFrame : number = 0; static el : JQuery = $("#app") static random : app.random; static timerId : number; public static handleGridClick() { } public static start() { game.random = new app.random(); this.timerId = setInterval(game.loopFunction, 600) game.loopFunction() $('body').on('click touch', 'td', (e) => { var el = $(e.target) if (el.hasClass('hit')) { game.score += 1; el.css('background-color','greenyellow') } else { } }); } static loopFunction = () => { game.currentFrame += 1 app.board.refresh() game.rnd = app.board.rnd; var html = textRenderer.render(); game.el.html(html) if (game.currentFrame === game.levelframes) { clearTimeout(game.timerId); } } } }<file_sep>var App; (function (App) { var ViewEngine = (function () { function ViewEngine() { } ViewEngine.renderview = function (viewname, data, partials) { var html = Mustache.render(viewname, data, partials); this.setAppHtml(html); return html; }; ViewEngine.getHtml = function (viewname, data, partials) { return Mustache.render(viewname, data, partials); }; ViewEngine.setAppHtml = function (html) { amplify.store("last_page", window.location.toString()); this.getAppEl().html(html); }; ViewEngine.getAppEl = function () { return $("#app"); }; ViewEngine.setElHtml = function (selector, html) { var el = $(selector); el.html(html); return el; }; ViewEngine.ClearScreen = function () { this.getAppEl().html(""); }; ViewEngine.ReloadPage = function () { }; return ViewEngine; })(); App.ViewEngine = ViewEngine; })(App || (App = {})); <file_sep>using System.Net.Mail; namespace Tekphoria.Server.Common { public static class Email { public static void Send(string email, string title, string message) { var mm = new MailMessage(); mm.From = Config.EmailAddress; mm.Subject = "Hello"; mm.Body = "<p>Body</p>"; mm.IsBodyHtml = true; var smtp = new SmtpClient(Config.EmailServer, 587); smtp.EnableSsl = false; smtp.UseDefaultCredentials = true; smtp.Credentials = Config.EmailCredentials; smtp.Port = 587; smtp.Send(mm); } } }<file_sep>using System; using FluentValidation; namespace Tekphoria.Server.Common { [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] sealed class ValidationAttribute : Attribute { // This is a positional argument public ValidationAttribute(IValidator validatorType) { // TODO: Implement code here throw new NotImplementedException(); } } }<file_sep>using System; namespace Tekphoria.Web.Server.Account { public class User { public int id { get; set; } public DateTime date_created { get; set; } public string email { get; set; } public string password { get; set; } public string pwd { get; set; } public string more_info { get; set; } public string display_name { get; set; } public string picture { get; set; } public string status { get; set; } public string dec_pwd { get; set; } } }<file_sep>/// <reference path="../../global_js/App.GlobalCommon.ts" /> module WB { export class ScrumboServerClient extends App.ServerClientBase { constructor() { super("scrumbo_server.ashx") } } } <file_sep>using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; namespace Tekphoria.Web.Server.Common.Routing { public class Router { public List<IRouteInfo> Routes = new List<IRouteInfo>(); public void Add(RouteInfo routeinfo) { Routes.Add(routeinfo); } public IRouteInfo FindRoute(string realUrl) { var dataRoute = new RouteInfo(realUrl); IEnumerable<IRouteInfo> matches = new List<IRouteInfo>(); IRouteInfo bestMatch = new RouteInfo(""); foreach (IRouteInfo routeInfo in Routes) { if (dataRoute.Matches(routeInfo)) bestMatch = routeInfo; } if (bestMatch.UriSegments.Length > 0) { /* Invalid */ bestMatch.RouteArgs = MakeArgs(dataRoute, bestMatch); return bestMatch; } return null; } private static IDictionary<string, object> MakeArgs(RouteInfo dataRoute, IRouteInfo templateRoute) { var args = new ExpandoObject() as IDictionary<string, object>; foreach (string param in templateRoute.RouteParams) { var name = param.CleanToken(); int indx = GetIndexOf(param, templateRoute.UriSegments); if (indx > -1) { string val; if (indx > dataRoute.UriSegments.Length - 1) val = GetObjectProperty(name, templateRoute.DefaultArgs); else val = dataRoute.UriSegments[indx]; if (val != null) args.Add(name, val.IsNumber() ? Int32.Parse(val) as object : val); } } return args; } private static string GetObjectProperty(string name, dynamic defaultArgs) { var allprops = ((PropertyInfo[]) defaultArgs.GetType().GetProperties()); Func<PropertyInfo, bool> func = p => p.Name == name; return allprops.Any(func) ? allprops.First(func).GetValue(defaultArgs, null).ToString() : null; } private static int GetIndexOf(string s, string[] array) { for (int i = 0; i < array.Length; i++) if (string.CompareOrdinal(array[i], s) == 0) return i; return -1; } } } <file_sep>/// <reference path="../../global_js/App.GlobalCommon.ts" /> module App { export class MailServerClient extends ServerClientBase { constructor() { super("/global_svr/email.ashx") } } export class Mail { public static init() { $("#to").val("<EMAIL>") $("#subject").val("test-subject") $("#body").text("test-subject") $("#btnSend").on("click", (e) => { e.preventDefault(); //var form = $("form").first(); //var data = GlobalCommon.getFormInputs(form) var data = { to: $("#to").val(), subject : $("#subject").val(), body : $("#testcontent").html(), ishtml : true } var client = new App.MailServerClient() var m = client.CallMethod("SendMailTest", data); $.when(m).then(resp => { alert(resp); }); }) } } } <file_sep>using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.account { public partial class Login : Page { protected void Page_Load(object sender, EventArgs e) { error_panel.Visible = false; if (IsPostBack) { var ob = new JObject(); ob.Add("email", new JValue(email.Text)); ob.Add("password", new JValue(password.Text)); var accountserver = new AccountServer(); dynamic result = accountserver.UserSignInTry(ob); var validationResult = (ValidationResult) result.validationResult; error_panel.Controls.Clear(); if (validationResult.Errors.Count > 0) { error_panel.Visible = true; foreach (ValidationFailure er in validationResult.Errors) { var label = new Literal { Text = string.Concat("<p>", er.ErrorMessage, "</p>") }; error_panel.Controls.Add(label); } } else { string next = Request["LastUrl"]; if (!string.IsNullOrWhiteSpace(next)) Response.Redirect(next); HttpCookie re = Context.Request.Cookies["LastUrl"]; if (re != null && !string.IsNullOrEmpty(re.Value)) Response.Redirect(re.Value); Response.Redirect("/account"); } } } } } <file_sep>function translate(input) { var res = ''; for (var i = 0; i < input.length; i++) { res += String.fromCharCode(1083756 ^ input.charCodeAt(i)); } return res; } var submitclicks = 0; //function doSubmit() { // submitclicks += 1; // alert(submitclicks); // el.value = translate(el.value); // if (submitclicks % 2 === 0) { // if (confirm('Submit now?')) { // document.getElementById("submit").click(); // return true; // } else { // el.value = translate(el.value); // return false; // } // } // return false; //} //el: HTMLTextAreaElement = document.getElementById("xxxxx") as HTMLTextAreaElement; //el.value = translate(el.value)<file_sep>/// <reference path="../global_js/App.ServiceClient.ts" /> /// <reference path="../global_js/App.GlobalCommon.ts" /> /// <reference path="../global_js/moment.d.ts" /> /// <reference path="../global_js/linq-2.2.d.ts" /> /// <reference path="Common.ts" /> /// <reference path="../global_js/routie.d.ts" /> /// <reference path="../global_js/amplify.d.ts" /> /// <reference path="Server.ts" /> module App { export class NavServerClient extends ServerClientBase { constructor() { super("filenav_server") } } //export class Starter { // private window: Window; // private static hasSetEvents: boolean = false; // public static start() { // this.registerEvents(); // this.registerRoutes(); // } // static registerRoutes() { // window.routie({ // '/browse': () => FilesView.init({}), // '/': () => FilesView.init({}), // '': () => FilesView.init({}) // }); // } // private static registerEvents() { // if (!this.hasSetEvents) { // this.hasSetEvents = true; // } // } //} export class Controller { public static FILES_LIST() { } } export class FilesView { public static init(data) { $.when(this.getViewData({})).then((resp) => { this.render(resp); } , null) } public static getViewData(data) { var client = new NavServerClient() return client.CallMethod("FileList", data); } public static render(data) { Enumerable.From(data.files).ForEach((f) => { f.filesize = App.Common.filesize(f.Length) f.created = "created " + moment(f.CreationTimeUtc).fromNow(); f.accessed = "accessed " + moment(f.LastAccessTimeUtc).fromNow(); f.written = "written " + moment(f.LastWriteTimeUtc).fromNow(); f.href = "/" + data.path ? data.path + "/" + f.Name : f.Name }); Enumerable.From(data.folders).ForEach((f) => { f.Name = f.Path.split("\\").pop(); }); amplify.store("currentpath", data.path); App.ViewEngine.renderview(this.getTemplate(), data) this.events(); } public static events() { $(".delete").on("click", (e) => { e.preventDefault(); var name = $(e.currentTarget).attr("data-name"); var path = amplify.store("currentpath"); var browsingpath = ""; if (confirm("Delete " + name + "?")) { var client = new NavServerClient() var deleter = client.CallMethod("DeleteFile", { name: name, path: path }); $.when(deleter).then((resp) => { alert("Deleted OK"); this.render(resp); }, (resp) => alert(resp.responseText) ); } }); $(".rename").on("click", (e) => { var name = $(e.currentTarget).attr("data-name"); var newname = prompt("Enter new filename", name) if (newname) { var path = amplify.store("currentpath"); var client = new NavServerClient() var renamer = client.CallMethod("RenameFile", { newname: newname, name: name, path: path }); $.when(renamer).then((resp) => { alert("Renamed OK"); this.render(resp); }, (resp) => alert(resp.responseText) ); } }) $(".path").on("click", (e) => { e.preventDefault(); var path = $(e.currentTarget).attr("data-path"); $.when(this.getViewData({ path: path })).then((resp) => this.render(resp), null) }) } public static getTemplate() { //<a href="#/browse/?path=App_Code" class ="path" data-path="App_Code">App_Code</a> var tmp = "" tmp += " <a href='#/browse/?path={{parent}}' class='path' data-path='{{parent}}'>[back]</a> " tmp += "<strong>\\\\{{path}}</strong>" tmp += "<table class='table table-hover table-condensed'>" tmp += "{{#folders}}<tr class='folder'><td><input type=checkbox></input></td><td><a href='#/browse/?path={{Path}}' class='path' data-path='{{Path}}'><strong>{{Name}}</strong></a></td><td>{{filesize}}</td><td><a data-name='{Path}' class='delete' href='#'>del</a></td><td><a data-name='{Path}' href='#'>ren</a></td><td>{{created}}</td><td>{{written}}</td><tr>{{/folders}}" tmp += "{{#files}}<tr class=files><td><input type=checkbox></input></td><td class='file'><a href={{href}}>{{Name}}</a></td><td>{{filesize}}</td><td><a data-name='{{Name}}' class='delete' href='#'>del</a></td><td><a data-name='{{Name}}' class='rename' href='#'>ren</a></td><td>{{created}}</td><td>{{written}}</td><tr>{{/files}}" tmp += "</table></hr>" return tmp; } public static upload() { } } }<file_sep>using System; using System.Web; namespace Tekphoria.Web.Server.Modules { public class WebApplicationErrorModule : IHttpModule { /// <summary> /// You will need to configure this module in the Web.config file of your /// web and register it with IIS before being able to use it. For more information /// see the following link: http://go.microsoft.com/?linkid=8101007 /// </summary> public void Dispose() { //clean-up code here. } public void Init(HttpApplication context) { context.Error += OnError; } void OnError(object sender, EventArgs e) { Exception ex = HttpContext.Current.Server.GetLastError(); ExceptionOccurred(ex); } private static void ExceptionOccurred(Exception ex) { HttpRequest request = HttpContext.Current.Request; HttpResponse response = HttpContext.Current.Response; if (HttpContext.Current.Cache != null) HttpContext.Current.Cache["Error"] = ex; // SendEmail(report, path); // Write the crash report to the browser // if there is no replacement defined for the HTTP response HttpContext.Current.Server.ClearError(); try { response.Clear(); response.StatusCode = 500; response.StatusDescription = "Server Error"; response.TrySkipIisCustomErrors = true; response.Write(ex.ToString()); response.End(); } catch { } } } } <file_sep>using System; namespace Tekphoria.Web.locate { public class LocationArgs { public LocationArgs() { date_created = DateTime.UtcNow; } public string user_id { get; set; } public string lat { get; set; } public string lng { get; set; } public DateTime date_created { get; private set; } } }<file_sep>using System; using System.Collections.Generic; using System.Security.Principal; namespace Tekphoria.Web.account { public class Principle : IPrincipal { public bool IsInRole(string role) { throw new NotImplementedException(); } public IIdentity Identity { get; private set; } } public class Identity : IIdentity { public string Name { get; private set; } public string AuthenticationType { get; private set; } public bool IsAuthenticated { get; private set; } } public class UsersCookie { public int Id { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string TimeZone { get; set; } public List<string> Roles { get; set; } public bool DisplayName { get; set; } } } <file_sep>using System; using System.Data; namespace Tekphoria.Server.Prospect { public class Processor { public Processor(Func<IDbConnection, dynamic, object> logic) { Run = logic; } public Func<IDbConnection, dynamic, object> Run { get; set; } } }<file_sep>var WB; (function (WB) { var EventNames = (function () { function EventNames() { } EventNames.BOARDS_LIST = "BOARDS_LIST"; EventNames.BOARD_ADD = "BOARD_ADD"; EventNames.BOARD_DELETE = "BOARD_DELETE"; EventNames.BOARD_GET = "BOARD_GET"; EventNames.BOARD_GET_BY_HASH = "BOARD_GET_BY_HASH"; EventNames.STORY_ADD_TO_BOARD = "STORY_ADD_TO_BOARD"; EventNames.STORY_DELETE = "STORY_DELETE"; EventNames.TASK_ADD_TO_STORY = "TASK_ADD_TO_STORY"; EventNames.TASK_MOVE = "TASK_MOVE"; EventNames.TASK_GET = "TASK_GET"; EventNames.TASK_UPDATE_TEXT = "TASK_UPDATE_TEXT"; EventNames.TASK_UPDATE_STATUS = "TASK_UPDATE_STATUS"; EventNames.STORY_GET = "STORY_GET"; EventNames.TASK_DELETE = "TASK_DELETE"; EventNames.STORY_UPDATE_TEXT = "STORY_UPDATE_TEXT"; EventNames.BOARD_GET_CONFIGURATION = "BOARD_GET_CONFIGURATION"; EventNames.BOARD_SET_CONFIGURATION = "BOARD_SET_CONFIGURATION"; EventNames.BOARD_SORT_STORY = "BOARD_SORT_STORY"; EventNames.USER_SIGN_IN_REQUIRED = "USER_SIGN_IN_REQUIRED"; EventNames.USER_SIGN_IN_TRY = "USER_SIGN_IN_TRY"; EventNames.USER_ADD = "USER_ADD"; EventNames.LOCAL_ISLOGGEDIN = "IsLoggedIn"; EventNames.LOCAL_EMAIL = "Email"; EventNames.LOCAL_USERID = "UserId"; EventNames.USER_ADD_SHARED_BOARD = "USER_ADD_SHARED_BOARD"; EventNames.USER_GET = "USER_GET"; EventNames.USER_UPDATE = "USER_UPDATE"; EventNames.BOARD_GET_ARCHIVE = "BOARD_GET_ARCHIVE"; EventNames.STORY_SET_STATUS = "STORY_SET_STATUS"; return EventNames; })(); WB.EventNames = EventNames; var Payload = (function () { function Payload(action, data) { this.action = action; this.data = data; } return Payload; })(); WB.Payload = Payload; var WebStorage = (function () { function WebStorage() { } WebStorage.sendPayload = function (payload, next) { if (amplify.store(EventNames.LOCAL_ISLOGGEDIN) === "1") { } else if (payload.action !== WB.EventNames.USER_SIGN_IN_TRY && payload.action !== WB.EventNames.USER_ADD) { amplify.publish(WB.EventNames.USER_SIGN_IN_REQUIRED); return; } $.ajax({ type: "POST", url: '/scrumbo/scrumbo_server.ashx', headers: { "UserId": amplify.store(EventNames.LOCAL_USERID) }, dataType: 'JSON', cache: false, contentType: "application/json; charset=utf-8", data: JSON.stringify(payload), success: function (data, b, c) { next(data); }, error: function () { }, statusCode: { 404: function (data, two, three) { return WB.ErrorController.Show(new WB.Error("404 Not Found", "The method was not found.", "")); }, 403: function (data, two, three) { return WB.ErrorController.Show(new WB.Error("403 Access denied", "Access is not permitted to this service.", "")); }, 500: function (data, two, three) { return WB.ErrorController.Show(new WB.Error("500 Server Error", data.responseText, "")); } } }); }; WebStorage.BOARD_GET_CONFIGURATION_ASYNC = function (hash) { var payload = new Payload(WB.EventNames.BOARD_GET_CONFIGURATION, { hash: hash }); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_GET_CONFIGURATION + "_REPLY", data); }); }; WebStorage.BOARD_SET_CONFIGURATION_ASYNC = function (setConfigData) { var payload = new Payload(WB.EventNames.BOARD_SET_CONFIGURATION, setConfigData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_SET_CONFIGURATION + "_REPLY", data); }); }; WebStorage.BOARDS_LIST_ASYNC = function () { var payload = new Payload(WB.EventNames.BOARDS_LIST, {}); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARDS_LIST + "_REPLY", data); }); }; WebStorage.BOARD_ADD_ASYNC = function (boardData) { var payload = new Payload(WB.EventNames.BOARD_ADD, boardData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_ADD + "_REPLY", data); }); }; WebStorage.BOARD_DELETE_ASYNC = function (hash) { var payload = new Payload(WB.EventNames.BOARD_DELETE, { hash: hash }); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_DELETE + '_REPLY', data); }); }; WebStorage.BOARD_GET_BY_HASH_ASYNC = function (hash) { var payload = new Payload(WB.EventNames.BOARD_GET_BY_HASH, { hash: hash }); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_GET_BY_HASH + "_REPLY", data); }); }; WebStorage.STORY_DELETE_ASYNC = function (storyDeleteData) { var payload = new Payload(WB.EventNames.STORY_DELETE, storyDeleteData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.STORY_DELETE + "_REPLY", data); }); }; WebStorage.TASK_ADD_TO_STORY_ASYNC = function (addTaskToStoryData) { var payload = new Payload(WB.EventNames.TASK_ADD_TO_STORY, addTaskToStoryData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_ADD_TO_STORY + "_REPLY", data); }); }; WebStorage.TASK_MOVE_ASYNC = function (taskMoveData) { var payload = new Payload(WB.EventNames.TASK_MOVE, taskMoveData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_MOVE + "_REPLY", data); }); }; WebStorage.TASK_GET_ASYNC = function (taskGetData) { var payload = new Payload(WB.EventNames.TASK_GET, taskGetData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_GET + "_REPLY", data); }); }; WebStorage.TASK_UPDATE_TEXT_ASYNC = function (updateTextData) { var payload = new Payload(WB.EventNames.TASK_UPDATE_TEXT, updateTextData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_UPDATE_TEXT + "_REPLY", data); }); }; WebStorage.TASK_DELETE_ASYNC = function (deleteData) { var payload = new Payload(WB.EventNames.TASK_DELETE, deleteData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_DELETE + "_REPLY", data); }); }; WebStorage.STORY_GET_ASYNC = function (storyGetData) { var payload = new Payload(WB.EventNames.STORY_GET, storyGetData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.STORY_GET + "_REPLY", data); }); }; WebStorage.STORY_UPDATE_TEXT_ASYNC = function (storyGetData) { var payload = new Payload(WB.EventNames.STORY_UPDATE_TEXT, storyGetData); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.STORY_UPDATE_TEXT + "_REPLY", data); }); }; WebStorage.BOARD_SORT_STORY_ASYNC = function (data) { var payload = new Payload(WB.EventNames.BOARD_SORT_STORY, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_SORT_STORY + "_REPLY", data); }); }; WebStorage.TASK_UPDATE_STATUS_ASYNC = function (data) { var payload = new Payload(WB.EventNames.TASK_UPDATE_STATUS, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.TASK_UPDATE_STATUS + "_REPLY", data); }); }; WebStorage.USER_SIGN_IN_ASYNC = function (data) { var payload = new Payload(WB.EventNames.USER_SIGN_IN_TRY, data); this.sendPayload(payload, function (data) { amplify.store("user", data); amplify.publish(WB.EventNames.USER_SIGN_IN_TRY + "_REPLY", data); }); }; WebStorage.USER_ADD_ASYNC = function (data) { var payload = new Payload(WB.EventNames.USER_ADD, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.USER_ADD + "_REPLY", data); }); }; WebStorage.USER_ADD_SHARED_BOARD_ASYNC = function (data) { var payload = new Payload(WB.EventNames.USER_ADD_SHARED_BOARD, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.USER_ADD_SHARED_BOARD + "_REPLY", data); }); }; WebStorage.USER_GET = function (data) { var payload = new Payload(WB.EventNames.USER_GET, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.USER_GET + "_REPLY", data); }); }; WebStorage.USER_UPDATE_ASYNC = function (data) { var payload = new Payload(WB.EventNames.USER_UPDATE, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.USER_UPDATE + "_REPLY", data); }); }; WebStorage.BOARD_GET_ARCHIVE_ASYNC = function (data) { var payload = new Payload(WB.EventNames.BOARD_GET_ARCHIVE, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.BOARD_GET_ARCHIVE + "_REPLY", data); }); }; WebStorage.STORY_SET_STATUS_ASYNC = function (data) { var payload = new Payload(WB.EventNames.STORY_SET_STATUS, data); this.sendPayload(payload, function (data) { amplify.publish(WB.EventNames.STORY_SET_STATUS + "_REPLY", data); }); }; return WebStorage; })(); WB.WebStorage = WebStorage; })(WB || (WB = {})); <file_sep>using System; using System.Data; using System.Linq; using Newtonsoft.Json.Linq; using Tekphoria.Server.Common; namespace Tekphoria.Server.Scrumbo { public class ProcessorActions { private static readonly string[] Columns = new[] { "TODO", "INPROGRESS", "DONE" }; public static object StorySetStatus(IDbConnection con, dynamic data) { string status = ((string)data.status).ToUpperInvariant().Trim(); con.Execute("update stories set status=@status where id=@id", new { data.id, status }); if (status == "DONE" || status == "ARCHIVE") con.Execute("update tasks set status=@status where story_id=@story_id", new { story_id = data.id, status }); return true; } public static object UserUpdate(IDbConnection conn, dynamic data) { conn.Execute("update users set display_name=@display_name,password=<PASSWORD> where id=@id;", new { data.id, data.password, data.display_name }); return true; } public static object UserGet(IDbConnection con, dynamic data) { return con.Query("select * from users where id=@id;", new { data.id }).Single(); } public static object UserAddSharedBoard(IDbConnection con, dynamic data) { con.Execute("insert into user_boards (user_id, board_hash) values (@user_id, @hash);", new { data.user_id, data.hash }); return true; } public static object UserAdd(IDbConnection con, dynamic data) { dynamic res = con.Query<dynamic>( "insert into users (email,display_name,password) values (@email,@display_name,@password);select last_insert_id() as newid;", new { data.email, data.password, data.display_name }).Single(); return new { id = res.newid }; } [Obsolete("Should use account service")] public static object UserSignInTry(IDbConnection con, dynamic data) { dynamic res = con.Query<dynamic>("select id, display_name from users where email=@email;", new { data.email }).Single(); return new { res.id, res.display_name, data.email }; } public static void InsertLogItem(IDbConnection con, dynamic data) { con.Execute( "insert into log_items (board_id,story_id,task_id,user_id,action,textof) values (@board_id,@story_id,@task_id,@user_id,@action,@textof)", new { data.board_id, data.story_id, task_id = data.id, data.user_id, data.action, data.textof } ); } public static object StoryAddToBoardByid(IDbConnection con, dynamic data) { int newid = con.Execute( "insert into stories (textof, board_id, sort_order, status) values (@textof, @board_id, @sort_order, @status); SELECT last_insert_id() as Last_ID;", new { data.textof, data.board_id, sort_order = 100, status = "TODO" } ); return true; } public static object BoardDelete(IDbConnection con, dynamic data) { int id = GetBoardIdFromHash(con, (string)data.hash); con.Execute( "delete from boards where id=@id;delete from stories where board_id=@id;delete from tasks where board_id=@id;", new { id }); return true; } public static int GetBoardIdFromHash(IDbConnection con, string hash) { dynamic boardrow = con.Query("select id from boards where hash=@hash", new { hash }).Single(); return (int)boardrow.id; } public static object BoardGetByHash(IDbConnection con, dynamic data) { dynamic board = con.Query<dynamic>( "select id,nameof,hash,group_hash,extra_status_1,extra_status_2,more_info from boards where hash=@hash", new { data.hash }).Single(); // and status in(@StoryDisplayStatuses); dynamic stories = con.Query( "select id,textof,board_id,sort_order,status,date_created from stories where board_id=@id and status in ('','INPROGRESS','TODO');", new { board.id }).ToList(); dynamic tasks = con.Query( "select id,textof,story_id,board_id,sort_order,status,css_class,user_id,date_created,date_modified from tasks where board_id=@id and status in ('','INPROGRESS','TODO');", new { board.id }).ToList(); // dynamic log_items = con.Query("select * from log_items where board_id=@id order by id desc limit 10;", new { board.id }).ToList(); string board_users = "select * from users where id in(select user_id from user_boards where board_hash=@hash);"; dynamic users = con.Query(board_users, new { data.hash }).ToList(); dynamic actions = Enum.GetNames(typeof(ActionEnum)); return new { board, stories, tasks, columns = Columns, users, actions }; } public static object BoardAdd(IDbConnection con, dynamic data) { dynamic result = con.Query<dynamic>( "insert into boards (nameof, hash, more_info) values (@nameof, @hash, ''); SELECT last_insert_id() as newid;", new { data.nameof, data.hash }) .Single(); UserAddSharedBoard(con, data); StoryAddToBoardByid(con, new { textof = "General Work", board_id = result.newid }); return true; } public static object UserRecentTasks(IDbConnection con, dynamic data) { dynamic tasks = con.Query("select * from tasks where user_id=@user_id", new { data.user_id }).ToArray(); return new {tasks}; } } }<file_sep>var Component; (function (Component) { var GoogleMaps = (function () { function GoogleMaps() { } GoogleMaps.search_address_2 = function (address) { var google = window["google"]; var geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { amplify.publish("SearchAddress_reply", results); } else { alert("Geocode was not successful for the following reason: " + status); } }); }; GoogleMaps.getDistanceFromBase = function (lat, lng) { var google = window["google"]; var base = new google.maps.LatLng(51.4920292996691, 2.64677873809819); var dest = new google.maps.LatLng(+lat, +lng); var distanceMeters = 0; return distanceMeters; }; GoogleMaps.get_default_options = function () { var google = window["google"]; return { zoom: 18, mapTypeId: google.maps.MapTypeId.SATELLITE, center: {} }; }; GoogleMaps.show_location = function (data) { var google = window["google"]; var options = this.get_default_options(); options.center = new google.maps.LatLng(data.latitude, data.longitude); this.map = new google.maps.Map(document.getElementById("map-canvas"), options); var marker = new google.maps.Marker({ map: this.map, draggable: true, raiseOnDrag: false, position: options.center }); google.maps.event.addListener(marker, 'dragend', function () { var position = marker.getPosition(); this.map.setCenter(position); amplify.publish("location_change", { latitude: position.lat(), longitude: position.lng() }); $("#latitude").text(position.lng()); $("#longitude").text(position.lat()); var data = { latitude: position.lat(), longitude: position.lng(), query: $("#query").text(), id: $("#prospect_id").text() }; amplify.publish("UpdateProspectLocation", data); }); }; GoogleMaps.show_map = function (options, results) { var google = window["google"]; this.map = new google.maps.Map(document.getElementById("map-canvas"), options); var marker = new google.maps.Marker({ map: this.map, draggable: true, raiseOnDrag: false, position: results[0].geometry.location }); $("#query").val(results[0].address_components[0].short_name + ' ' + results[0].address_components[1].short_name + ' ' + results[0].address_components[2].short_name + ' UK'); google.maps.event.addListener(marker, 'dragend', function () { var position = marker.getPosition(); this.map.setCenter(position); amplify.publish("location_change", { latitude: position.lat(), longitude: position.lng() }); $("#latitude").text(position.lng()); $("#longitude").text(position.lat()); var data = { latitude: position.lat(), longitude: position.lng(), query: $("#query").text(), id: $("#prospect_id").text() }; amplify.publish("UpdateProspectLocation", data); }); return this.map; }; GoogleMaps.api_key = "<KEY>"; GoogleMaps.maps_direct_lat_log_url = "https://maps.google.com/maps?ll={latitude},{longitude}&z=20"; return GoogleMaps; })(); Component.GoogleMaps = GoogleMaps; })(Component || (Component = {})); <file_sep>/// <reference path="jquery-1.9.1.d.ts" /> /// <reference path="amplify.d.ts" /> /// <reference path="mustache-0.7.d.ts" /> module App { export class ViewEngine { public static renderview(viewname: string, data: any, partials?: any) { var html = Mustache.render(viewname, data, partials); this.setAppHtml(html); return html; } public static getHtml(viewname: string, data: any, partials?: any): string { return Mustache.render(viewname, data, partials); } public static setAppHtml(html: string) { //getAppEl().hide().html(html).fadeIn(); amplify.store("last_page", window.location.toString()); this.getAppEl().html(html); } public static getAppEl(): JQuery { return $("#app"); } public static setElHtml(selector: string, html: string): JQuery { var el = $(selector); el.html(html); return el; } public static ClearScreen() { this.getAppEl().html(""); } public static ReloadPage() { //window.location.reload(); } public static tmpl:any = {}; public static parseTemplateHtml(html: string) { var h = $(html); var alldivs = h.filter("div"); $.each(alldivs, (idx, div)=> { var d = $(div); App.ViewEngine.tmpl[d.attr("data-tmpl")] = d.html().trim().replace(/\s+/g, ' '); }); } } }<file_sep>using System.IO; using System.Reflection; namespace Tests.SchemaOrg { public class testbase { public static string GetEmbeddedText(string filename) { Assembly assembly = Assembly.GetExecutingAssembly(); string resourceName = string.Format("Tests.Resources.{0}.txt", filename); string result; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (var reader = new StreamReader(stream)) { result = reader.ReadToEnd(); } return result; } } }<file_sep>/// <reference path="../global_js/App.GlobalCommon.ts" /> module app { export class LocateServerClient extends App.ServerClientBase { constructor() { super("locate.ashx") } } var google; export class main { static UserId: string; static mapCanvas = $("#map-canvas") static timeoutVal: number = 10 * 1000 * 1000; static uriTmpl: string = "/locate/locate.ashx?u={u}&l={l}&n={n}" static map static cookies; static GetUser public static start() { if (navigator.geolocation) { app.main.getLocFunction() // setInterval(app.main.getLocFunction, 15000) } else { alert("Nav not supported") } } public static getLocFunction() { navigator.geolocation.getCurrentPosition(app.main.displayPosition, app.main.displayError, { enableHighAccuracy: true, timeout: this.timeoutVal, maximumAge: 0 }); } public static displayPosition(position) { $("#app").contents().remove().append('Locations at ' + new Date() + ' : Latitude: ' + position.coords.latitude + ', Longitude: ' + position.coords.longitude); var url = app.main.uriTmpl.replace("{u}", App.GlobalCommon.readCookie("UserId")) .replace("{l}", position.coords.latitude.toFixed(5)) .replace("{n}", position.coords.longitude.toFixed(5)) $.get(url); var client = new LocateServerClient() var act = () => client.CallMethod("GetLocations", {}) $.when(act()).then(resp => { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude) app.main.map = app.main.map || new google.maps.Map(document.getElementById("map-canvas"), { center: pos, zoom: 12 }); var bounds = new google.maps.LatLngBounds(); for (var i = 0; i < resp.locs.length; i++) { var pos = new google.maps.LatLng(resp.locs[i].lat, resp.locs[i].lng) var marker = new google.maps.Marker({ position: pos, map: app.main.map, title: resp.locs[i].display_name }); //marker.infowindow = new google.maps.InfoWindow({ // content: resp.locs[i].display_name //}); //google.maps.event.addListener(marker, 'click', () => { // marker.infowindow.open(); // }); bounds.extend(pos); } app.main.map.fitBounds(bounds); }); } public static displayError(error) { var errors = { 1: 'Permission denied', 2: 'Position unavailable', 3: 'Request timeout' }; alert("Error: " + errors[error.code]); } static readCookie(name, c, C, i) { //var cookies = app.main.cookies; // if (cookies) { return cookies[name]; } c = document.cookie.split('; '); var cookies = {}; for (i = c.length - 1; i >= 0; i--) { C = c[i].split('='); cookies[C[0]] = C[1]; } return cookies[name]; } } }<file_sep>/// <reference path="../global_js/amplify.d.ts" /> /// <reference path="../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../global_js/App.GlobalCommon.ts" /> /// <reference path="../global_js/App.ServiceClient.ts" /> /// <reference path="../global_js/App.ViewEngine.ts" /> module Account { export class AccountClient extends App.ServerClientBase { constructor() { super("/account/account_server.ashx"); } } export class Common { public static getStoredAccountDetails() { return { display_name: App.GlobalCommon.readCookie("UserName"), IsLoggedIn: App.GlobalCommon.readCookie("IsLoggedIn"), Auth: App.GlobalCommon.readCookie("Auth"), UserId: App.GlobalCommon.readCookie("UserId"), }; } public static SignInUrl = "/login"; public static SignOutUrl = "/logout"; public static SignIn(from: string) { window.location.href = this.SignInUrl; amplify.store("LastUrl", from); Account.LoginView.init(); } } export class LoginBarView { public static getHtml() { return this.render(); } public static render() { var tmpl = ""; var account = Common.getStoredAccountDetails(); if (account && account.display_name && account.display_name.length > 0) { tmpl = this.getLoggedinTemplate(); } else { tmpl = this.getLoggedoutTemplate(); } var html = App.ViewEngine.getHtml(tmpl, account); amplify.publish("getLoginView", html); return html; } public static getLoggedinTemplate() { var frag = "<span id='logged_in_part' class='logged_in_part'>" + "Hello, <span id='display_name'><b>{{display_name}}</b></span>" + "&nbsp;&nbsp;&nbsp;&nbsp;<span id='sign_out'><a href='/logout'>Log Out</a></span>" + "</span>"; return frag; } public static getLoggedoutTemplate() { var frag = "<span id='not_logged_in_part'>" + "<div id='sign_in'><a href='/login'>Log in</a></div>" + "</span>"; return frag; } } export class LoginView { public static init() { var tmpl = $.get("Login.html"); $.when(tmpl).then(data => this.render(data)); } public static signout() { this.setStoredAccountDetails(null); amplify.store("LastUrl", null); amplify.store("IsLoggedIn", null); amplify.store("last_board_hash", null); amplify.publish("UserLoggedOut"); window.location.href = "/account"; } public static setStoredAccountDetails(account) { // ms to expiry amplify.store("account", null); if (account) { var options = { expires: 1000 * 60 * 60 * 24 * 14 }; return amplify.store("account", account, options); } } public static login(form: JQuery) { var client = new Account.AccountClient(); var inputs = App.GlobalCommon.getFormInputs(form); var act = client.CallMethod("UserSignInTry", inputs); $.when(act) .then(resp => { if (resp.validationResult.IsValid === false) { App.GlobalCommon.apply_validation(resp.validationResult, form); } else { this.setStoredAccountDetails(resp.account); amplify.store("IsLoggedIn", "1"); var last_url = amplify.store("LastUrl"); if (last_url) { window.location.href = last_url; } else { $("#not_logged_in").remove(); $("#logged_in").show(); } } }); } public static handleSubmit(e) { e.preventDefault(); this.login($("#login-form")); } public static render(data) { $("#app").html($(data)); $("#logged_in").hide(); var account = Account.Common.getStoredAccountDetails(); if (account) { $("#not_logged_in").hide(); var part = $.get("LoginPart.html"); $.when(part).then(tmpl => this.handleLoggedIn(tmpl, account)); } $("#login-form").submit(e => this.handleSubmit(e)); // $("#submit-btn").off("click").on("click", (e) => this.handleSubmit(e)) } public static handleLoggedIn(tmpl, data) { var loggedinpart = App.ViewEngine.getHtml(tmpl, data); $("#logged_in").show(); $("#logged_in_part").html(loggedinpart); $("#not_logged_in_part").hide(); } } export class CreateAccountView { public static init() { var tmpl = $.get("CreateAccount.html"); $.when(tmpl).then((resp) => this.render(resp)); } public static render(resp) { App.ViewEngine.renderview(resp, null); $("#submit-btn").off("click").on("click", (e) => this.handleSubmit(e)); } public static handleSubmit(e) { e.preventDefault(); var form = $("#create-account-form"); var inputs = App.GlobalCommon.getFormInputs(form); var client = new Account.AccountClient(); $.when( client.CallMethod("UserAdd", inputs)) .then((resp) => { if (resp.validationResult.IsValid === false) { App.GlobalCommon.apply_validation(resp.validationResult, form); } else { // Login after creation LoginView.login($("#create-account-form")); } }); } } }<file_sep>using System; using System.Web; using System.Web.UI; namespace Tekphoria.Web.account { public partial class UserLoginDisplayStatus : UserControl { protected void Page_Load(object sender, EventArgs e) { HttpCookie ck = Request.Cookies["IsLoggedIn"]; if (ck == null || string.IsNullOrEmpty(ck.Value) || ck.Value != "1") { loggedin.Visible = false; not_loggedin.Visible = true; } else { loggedin.Visible = true; not_loggedin.Visible = false; HttpCookie ckUser = Context.Request.Cookies["UserName"]; if (ckUser == null || string.IsNullOrEmpty(ckUser.Value)) user.Text = "?"; else user.Text = ckUser.Value; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Tekphoria.Web.Server.Common { public static class Markup { public static string Div(this string content) { return string.Format("<div>{0}</div>"); } } }<file_sep> /** * HtmlHelper JavaScript Library v0.80 beta * * Copyright 2010, novaera * http://d.hatena.ne.jp/NovaEra/ * * MIT licenses. * * Date: 2010/03/28 */ (function () { var HtmlHelper = { /** * Documents */ // h1 - h6 h: function (contents, options) { return this._hNum(1, arguments); }, h1: function (a, b) { return this.h(a, b); }, hh: function (contents, options) { return this._hNum(2, arguments); }, h2: function (a, b) { return this.hh(a, b); }, hhh: function (contents, options) { return this._hNum(3, arguments); }, h3: function (a, b) { return this.hhh(a, b); }, hhhh: function (contents, options) { return this._hNum(4, arguments); }, h4: function (a, b) { return this.hhhh(a, b); }, hhhhh: function (contents, options) { return this._hNum(5, arguments); }, h5: function (a, b) { return this.hhhhh(a, b); }, hhhhhh: function (contents, options) { return this._hNum(6, arguments); }, h6: function (a, b) { return this.hhhhhh(a, b); }, _hNum: function (no, args) { return this._getHasChildElementStr("h" + no, args); }, // p p: function (contents, options) { return this._getHasChildElementStr("p", arguments); }, // img img: function (src, options) { options = options || {}; options["src"] = src; return this._getNoChildElementStr("img", options); }, // a a: function (href, contents, options) { options = options || {}; options["href"] = href; contents = contents || href; return this._getHasChildElementStr("a", [contents, options]); }, // pre pre: function (contents, options) { return this._getHasChildElementStr("pre", arguments); }, // code code: function (contents, options) { return this._getHasChildElementStr("code", arguments); }, // abbr abbr: function (title, contents, options) { options = options || {}; options["title"] = title; return this._getHasChildElementStr("abbr", [contents, options]); }, // acronym acronym: function (contents, options) { return this._getHasChildElementStr("acronym", arguments); }, // dfn dfn: function (contents, options) { return this._getHasChildElementStr("dfn", arguments); }, // cite cite: function (contents, options) { return this._getHasChildElementStr("cite", arguments); }, // kbd kbd: function (contents, options) { return this._getHasChildElementStr("kbd", arguments); }, // q q: function (contents, options) { return this._getHasChildElementStr("q", arguments); }, // blockquote bq: function (contents, options) { return this._getHasChildElementStr("blockquote", arguments); }, blockquote: function (a, b) { return this.bq(a, b); }, // samp samp: function (contents, options) { return this._getHasChildElementStr("samp", arguments); }, // var "var": function (contents, options) { return this._getHasChildElementStr("var", arguments); }, // bdo bdo: function (dir, contents, options) { options = options || {}; options["dir"] = dir; return this._getHasChildElementStr("bdo", [contents, options]); }, // div div: function (contents, options) { return this._getHasChildElementStr("div", arguments); }, // span span: function (contents, options) { return this._getHasChildElementStr("span", arguments); }, // em em: function (contents, options) { return this._getHasChildElementStr("em", arguments); }, // strong strong: function (contents, options) { return this._getHasChildElementStr("strong", arguments); }, // sub sub: function (options) { return this._getNoChildElementStr("sub", options); }, // sup sup: function (options) { return this._getNoChildElementStr("sup", options); }, // del del: function (contents, options) { return this._getHasChildElementStr("del", arguments); }, // ins ins: function (contents, options) { return this._getHasChildElementStr("ins", arguments); }, // ruby ruby: function (contents, options) { return this._getHasChildElementStr("ruby", arguments); }, // rb rb: function (contents, options) { return this._getHasChildElementStr("rb", arguments); }, // rbc rbc: function (contents, options) { return this._getHasChildElementStr("rbc", arguments); }, // rp rp: function (contents, options) { return this._getHasChildElementStr("rp", arguments); }, // rt rt: function (contents, options) { return this._getHasChildElementStr("rt", arguments); }, // rtc rtc: function (contents, options) { return this._getHasChildElementStr("rtc", arguments); }, // hr hr: function () { return "<hr />" }, // br br: function () { return "<br />" }, /** * Lists */ // ul ul: function (contents, options) { return this._getHasChildElementStr("ul", arguments); }, // ol ol: function (contents, options) { return this._getHasChildElementStr("ol", arguments); }, // li li: function (contents, options) { return this._getHasChildElementStr("li", arguments); }, // dl dl: function (contents, options) { return this._getHasChildElementStr("dl", arguments); }, // dt dt: function (contents, options) { return this._getHasChildElementStr("dt", arguments); }, // dd dd: function (contents, options) { return this._getHasChildElementStr("dd", arguments); }, /** * Tables */ // table table: function (contents, options) { return this._getHasChildElementStr("table", arguments); }, // caption cap: function (contents, options) { return this._getHasChildElementStr("caption", arguments); }, caption: function (a, b) { return this.cap(a, b); }, // col col: function (options) { return this._getNoChildElementStr("col", options); }, // colgroup colgroup: function (contents, options) { return this._getHasChildElementStr("colgroup", arguments); }, // thead thead: function (contents, options) { return this._getHasChildElementStr("thead", arguments); }, // tfoot tfoot: function (contents, options) { return this._getHasChildElementStr("tfoot", arguments); }, // tbody tbody: function (contents, options) { return this._getHasChildElementStr("tbody", arguments); }, // tr tr: function (contents, options) { return this._getHasChildElementStr("tr", arguments); }, // th th: function (contents, options) { return this._getHasChildElementStr("th", arguments); }, // td td: function (contents, options) { return this._getHasChildElementStr("td", arguments); }, /** * Form & Inputs */ // form post: function (action, contents, options) { return this._getHasChildElementStr("form", [contents, this._formOptions(action, "post", options)]); }, get: function (action, contents, options) { return this._getHasChildElementStr("form", [contents, this._formOptions(action, "get", options)]); }, multi: function (action, contents, options) { return this._getHasChildElementStr("form", [contents, this._formOptions(action, "multi", options)]); }, // textbox tbox: function (name, val, options) { return this._getNoChildElementStr("input", this._getInputOptions("text", name, val, options)); }, textbox: function (a, b, c) { return this.tbox(a, b, c); }, // password pass: function (name, val, options) { return this._getNoChildElementStr("input", this._getInputOptions("password", name, val, options)); }, password: function (a, b, c) { return this.pass(a, b, c); }, // file file: function (options) { options = options || {}; options["type"] = "file"; return this._getNoChildElementStr("input", options); }, // textarea tarea: function (contents, options) { return this._getHasChildElementStr("textarea", arguments); }, textarea: function (a, b) { return this.tarea(a, b); }, // hidden hide: function (name, val, options) { return this._getNoChildElementStr("input", this._getInputOptions("hidden", name, val, options)); }, hidden: function (a, b, c) { return this.hide(a, b, c); }, // radio button radio: function (name, val, options) { return this._getNoChildElementStr("input", this._getInputOptions("radio", name, val, options)); }, // checkbox chk: function (name, val, options) { options = options || {}; options["type"] = "checkbox"; options["name"] = name; options["value"] = val; return this._getNoChildElementStr("input", this._getInputOptions("checkbox", name, val, options)); }, check: function (a, b, c) { return this.chk(a, b, c) }, checkbox: function (a, b, c) { return this.chk(a, b, c) }, // selectbox select: function (name, contents, options) { options = options || {}; options["name"] = name; return this._getHasChildElementStr("select", [contents, options]); }, // option opt: function (val, contents, options) { options = options || {}; options["value"] = val; return this._getHasChildElementStr("option", [contents, options]); }, option: function (a, b, c) { return this.opt(a, b, c); }, // optgroup optgroup: function (label, contents, options) { options = options || {}; options["label"] = label; return this._getHasChildElementStr("optgroup", [contents, options]); }, // reset reset: function (val, options) { options = options || {}; options["type"] = "reset"; options["value"] = val; return this._getNoChildElementStr("input", options); }, // button button: function (val, options) { options = options || {}; options["type"] = "button"; options["value"] = val; return this._getNoChildElementStr("input", options); }, // submit submit: function (val, options) { options = options || {}; options["type"] = "submit"; options["value"] = val; return this._getNoChildElementStr("input", options); }, // input type="image" image: function (src, options) { options = options || {}; options["type"] = "image"; options["src"] = src; return this._getNoChildElementStr("input", options); }, // fieldset fset: function (contents, options) { return this._getHasChildElementStr("fieldset", arguments); }, fieldset: function (a, b) { return this.fset(a, b) }, // legend legend: function (contents, options) { return this._getHasChildElementStr("legend", arguments); }, // label label: function (target_id, contents, options) { options = options || {}; options["for"] = target_id; return this._getHasChildElementStr("label", [contents, options]); }, /** * js, css */ // outer script js: function (src, options) { options = options || {}; options["src"] = src; return this._getHasChildElementStr("script", ["", options]); }, // inner script script: function (contents, options) { return this._getHasChildElementStr("script", arguments); }, style: function (contents, options) { options = options || {}; options["type"] = "text/css"; return this._getHasChildElementStr("script", arguments); }, /** * others */ // meta meta: function (options) { return this._getNoChildElementStr("meta", options); }, // link link: function (contents, options) { return this._getHasChildElementStr("link", arguments); }, // object obj: function (contents, options) { return this._getHasChildElementStr("obj", arguments); }, object: function (a, b) { return this.obj(a, b); }, // param param: function (name, val, options) { return this._getHasChildElementStr("obj", this._getInputOptions("param", name, val, options)); }, /** * privates */ _getHasChildElementStr: function (tag_name, args) { var contents = args[0], options = args[1]; return ["<", tag_name, " ", this._getOptionsStr(options), ">", contents, "</", tag_name, ">"].join(""); }, _getNoChildElementStr: function (tag_name, options) { return ["<", tag_name, " ", this._getOptionsStr(options), " />"].join(""); }, _formOptions: function (action, type, options) { options = options || {}; options["method"] = (type == "get") ? "GET" : "POST"; if (type == "multi") options["enctype"] = "multipart/form-data"; options["action"] = action; return options; }, _getInputOptions: function (type, name, val, options) { val = val || ""; options = options || {}; options["type"] = type; options["name"] = name; options["value"] = val; return options; }, // extract options to string. _getOptionsStr: function (options) { var tmp_array = []; var quote = ""; var key; for (key in options) { quote = (options[key].match("'") == null) ? "'" : '"'; tmp_array.push([ ((key == "klass") ? "class" : key), "=", quote, "", options[key], quote, " " ].join("")); } return tmp_array.join(""); } }; if (typeof H == "undefined") H = HtmlHelper; window.HtmlHelper = HtmlHelper; })();<file_sep>/// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="App.Views.ts" /> /// <reference path="App.Common.ts" /> module App { export class AppStarter { private window: Window; private static hasSetEvents: boolean = false; public static start() { this.registerEvents(); this.registerRoutes(); } static registerRoutes() { window.routie({ '/prospect/:id/edit': (id) => App.View_EditProspect.init({ id: id }), '/prospect/:id/delete': (id) => App.View_DeleteProspect.init({ id: id }), //'/prospect/:id': (id) => App.View_Prospect.init({id:id}), '/prospects/:par1/:par2': (par1,par2) => App.View_Prospects.init({ par1:par1, par2:par2 }), '/prospects': () => App.View_Prospects.init({}), '/newprospect': () => App.View_NewProspect.init({}), '/': (id) => App.View_Prospects.init({}), '': () => App.View_Prospects.init({}) }); } private static registerEvents() { if (this.hasSetEvents === false) { //amplify.subscribe("SearchAddress_reply", (data) => App.View_ProspectsMap.render_map(data)); var client = new App.ProspectorServerClient() amplify.subscribe("UpdateProspectLocation", (data) => client.CallMethod("UpdateProspectLocation", data)); amplify.subscribe("UpdateProspectLocation_reply", () => alert("Updated")); amplify.subscribe("UserLoggedIn", (data) => { $("#login-part").html(data); }) amplify.subscribe("UserLoggedOut", (data) => { $("#login-part").html(data); }) this.hasSetEvents = true; } } } } <file_sep> class hyperlink { private id: string; private text: string; private href: string; private cssclass: string; }<file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var App; (function (App) { var AccountClient = (function (_super) { __extends(AccountClient, _super); function AccountClient() { _super.call(this, "account_server.ashx"); } return AccountClient; })(App.ServerClientBase); App.AccountClient = AccountClient; var Starter = (function () { function Starter() { } Starter.start = function () { this.registerEvents(); this.registerRoutes(); }; Starter.registerRoutes = function () { window["routie"]({ '/create': function (id) { return Account.CreateAccountView.init(); }, '/signin': function (id) { return Account.LoginView.init(); }, '/signout': function (id) { return Account.LoginView.signout(); }, '/': function (id) { return Account.LoginView.init(); }, '': function () { return Account.LoginView.init(); } }); }; Starter.registerEvents = function () { if (this.hasSetEvents === false) { this.hasSetEvents = true; } }; Starter.hasSetEvents = false; return Starter; })(); App.Starter = Starter; })(App || (App = {})); <file_sep>using System; using System.Collections.Concurrent; using System.Configuration; using System.Web; using System.Web.Configuration; namespace Tekphoria.Web.Server.Handlers { public class TestAssetHandler : IHttpHandler { private static readonly string _basedir = AppDomain.CurrentDomain.BaseDirectory; private static CompilationSection _configSection = (CompilationSection)ConfigurationManager.GetSection("system.web/compilation"); public static ConcurrentDictionary<string, string> Assets = new ConcurrentDictionary<string, string>(); public void ProcessRequest(HttpContext context) { try { context.Response.Expires = 60 * 24 * 30; context.Response.CacheControl = HttpCacheability.Public.ToString(); //context.Response.Cache.VaryByParams["load"] = true; var freshness = new TimeSpan(0, 0, 0, 15); DateTime now = DateTime.Now; context.Response.Cache.SetExpires(now.Add(freshness)); // Sets the Expires HTTP header to an absolute date and time. context.Response.Cache.SetMaxAge(freshness); context.Response.Cache.SetCacheability(HttpCacheability.Server); context.Response.Cache.SetValidUntilExpires(true); context.Response.Cache.SetAllowResponseInBrowserHistory(true); context.Response.Write(DateTime.Now.ToString()); context.Response.Write("TestAssetHandler"); } catch (Exception) { throw; } } public bool IsReusable { get; private set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.UI; namespace Tekphoria.Web.linkr { public partial class Linklist : UserControl { public Linklist() { Size = 10; } public String HeadText { set { linklist_header.Text = value; } } public IEnumerable<object> Links { set { linklist_links.DataSource = value.Take(Size); linklist_links.DataBind(); } } public int Size { get; set; } protected void Page_Load(object sender, EventArgs e) {} } } <file_sep>/// <reference path="../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../global_js/App.ViewEngine.ts" /> /// <reference path="../global_js/App.GlobalCommon.ts" /> /// <reference path="../components/googlemaps/Component.GoogleMaps.ts" /> module geotools { export class app { constructor() { this.start() } private search = $("#searchterm") private mapCanvas = $("#map-canvas") private submitButton = $("#btnSubmit") private form = $("#form1") private coordsDegrees = $("#coordsDegrees") private coordsDecimal = $("#coordsDecimal") private top = $("#top") private bottom = $("#bottom") private bottomleft = $("#bottom #left") private bottomright = $("#bottom #right") private detailsTable = $("table .details") // Yahoo start() { this.search.val("bs1 5tr") this.form.submit(e => this.handleSubmitForm(e)) $(window).height(); // returns height of browser viewport $(document).height(); // returns height of HTML document $(window).width(); // returns width of browser viewport $(document).width(); // returns width of HTML document var width = $(document).width(); } // this.bottomright.css({ // width: width * 0.45 + "px" // }) // this.mapCanvas.css({ // width: (width * 0.45) - 9 + "px", // height: 400 // }) // this.detailsTable.css({ // }).addClass("") // $("table").addClass("table table-bordered").css({width:width * 0.45 + "px"}) //} private handleSubmitForm(e) { e.preventDefault() var term = $("#searchterm").val(); if (!term) { alert("No search term") return; } this.codeAddress(term) } private codeAddress(address: string) { var google = window["google"]; var geocoder = new google.maps.Geocoder(); var map = new google.maps.Map(document.getElementById('map-canvas'), { zoom: 18, mapTypeId: google.maps.MapTypeId.SATELLITE }); geocoder.geocode({ 'address': address }, (results, status) => { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); var lon = +results[0].geometry.location.lng().toFixed(8); var lat = +results[0].geometry.location.lat().toFixed(8); var degs = geotools.app.degToMinutes(lat, "lon", "google") + " " + geotools.app.degToMinutes(lon, "lat", "google") this.coordsDecimal.text(lon + ", " + lat); this.coordsDegrees.text(degs); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } public static CHAR_DEG = "\u00B0" public static CHAR_MIN = "\u0027" public static CHAR_SEC = "\u0022" public static CHAR_SEP = "\u0020" // http://en.wikipedia.org/wiki/Decimal_degrees public static degToMinutes(decimal: number, orientation: string, format?: string) { var fmtDefault = "{compass} {deg} {min} {sec}"; if (format === 'google') fmtDefault = "{deg}\u00B0{min}\u0027{sec}\u0022{compass}"; var orientationDefault = orientation || "lat"; var latPosCompass, lonPosCompass, compass = "" if (orientationDefault === 'lat') { latPosCompass = decimal >= 0 ? "E" : "W" } if (orientationDefault === 'lon') { lonPosCompass = decimal >= 0 ? "N" : "S" } if (orientation === 'lat') compass = latPosCompass if (orientation === 'lon') compass = lonPosCompass if (!decimal) { return ""; } if (decimal.toString().indexOf(".") < 0) { return ""; } //var deg = decimal.toString().split(".")[0].toString().replace("-", "") var deg = Math.abs(+decimal.toString().split(".")[0]).toString() //var mins = ((decimal * 60) % 60).toString().split(".")[0].toString().replace("-", "") var mins = Math.abs(+((decimal * 60) % 60).toString().split(".")[0]).toString().replace("-", "") //var seconds = ((decimal * 3600) % 60).toFixed(4).toString().replace("-", "") var seconds = Math.abs(+((decimal * 3600) % 60).toFixed(2)).toString() return fmtDefault.replace("{compass}", compass) .replace("{deg}", deg.toString()) .replace("{min}", mins.toString()) .replace("{sec}", seconds.toString()) } } export class homeview { public render() { } //Degrees, minutes and seconds (DMS): 41° 24' 12.1674", 2° 10' 26.508" //Degrees and decimal minutes (DMM): 41 24.2028, 2 10.4418 //Decimal degrees (DDD): 41.40338, 2.17403 // 51.492148, -2.646708 //51°29'31.7"N 2°38'48.1"W // bs1 5tr // Google // 51°27'10.1"N 2°36'07.2"W // 51.452797, -2.601998 // ME //51.401409, -1.323114 //51°24'5.0724"N -1°19'23.2104"W private GetLocation(location) { var lon = +location.coords.longitude var lat = +location.coords.latitude var point = new window["GeoPoint"](lon, lat); $("#details").remove() $("form").append("<div id='details'></div>") $("#details").append("<br> " + lat + ", " + lon) //$("#details").append("<br>Google " + geotools.app.degToMinutes(lat, "lat", "") + " " + geotools.app.degToMinutes(lon, "lon")) $("#details").append("<br>GOOGLE " + geotools.app.degToMinutes(lat, "lon", "google") + " " + geotools.app.degToMinutes(lon, "lat", "google")) //$("#details").append("<br> " + point.getLatDeg() + " | " + point.getLonDeg()) } private template() { var lines = [] var searchterm = App.GlobalCommon.inputstring("searchterm", "searchterm", "", "Please enter the search term", "100") lines.push(App.GlobalCommon.form("Search", searchterm, "btnSearch", "form1", "form1")) lines.push("<div id=map-canvas></div>") return lines.join("") } } }<file_sep>/// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../components/googlemaps/Component.GoogleMaps.ts" /> /// <reference path="App.ViewEngine.ts" /> /// <reference path="App.ViewParts.ts" /> /// <reference path="App.AppStarter.ts" /> /// <reference path="App.Common.ts" /> module App { export class View_EditProspect { public static init(data) { var client = new App.ProspectorServerClient() var prospectdata = client.CallMethod("EditProspect", data) $.when(prospectdata).then((data) => this.render(data), null) } public static render(data) { data.user_id = amplify.store('UserId'); var images = []; Enumerable.From(data.files).Where((f) => f.file_type === 'IMAGE').ForEach((f) => { var image: any = {}; image.thumb = f.filename.replace("]_", "]_t_"); image.filename = f.filename; images.push(image); }) data.files = Enumerable.From(data.files).Where((f) => f.file_type !== 'IMAGE').ToArray(); data.images = images; App.ViewEngine.renderview(this.getTemplate(data), data); $("#location-map").append(View_ProspectsMap.getHtml(data)); View_ProspectsMap.setEvents(data); $("#sale_type_id option[value=" + data.prospect.sale_type_id + "]").first().prop("selected", true); $("#source_type_id option[value=" + data.prospect.source_type_id + "]").first().prop("selected", true); $("#status_id option[value=" + data.prospect.status_id + "]").first().prop("selected", true); $("#detailed_planning_permission").attr('checked', data.prospect.detailed_planning_permission === 1) $("#outline_planning").attr('checked', data.prospect.outline_planning === 1) //$("ul#sections.nav a").off("click").on("click", e => { // e.preventDefault(); // var content_selector = e.currentTarget.id.replace("-link", "-content"); // $(".tab-content").hide(); // var content = $("#" + content_selector).html(); // $("#tab-panel").hide().html(content).fadeIn(); //}) var touch = 'ontouchend' in document; if (touch) { $("#uploadtouch").show(); $("#uploadnontouch").hide(); } else { $("#uploadtouch").hide(); $("#uploadnontouch").show(); $('#file_upload').uploadify({ 'swf': '/components/uploadify/uploadify.swf', 'uploader': '/components/uploadify/uploadify.ashx', 'buttonText': 'select and upload', 'buttonClass': 'btn btn-small', 'formData': { prospect_id: data.prospect.id }, 'multi': true }); } // Save the updated data $("#btn_save_prospect").on("click", (e) => { e.preventDefault(); App.ViewPart.info_hide(); var form = App.GlobalCommon.getFormInputs($("#prospect_form")) var client = new ProspectorServerClient(); var resp = client.CallMethod("UpdateProspect", form); $.when(resp).then(data => { if (data.validationResult.IsValid) { App.ViewPart.info("Success", "The prospect has been updated."); } else { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } } , null); }); } public static getTemplate(data) { var tab_panel = "<div id='tab-panel'></div>" var tabs = '<ul id=sections class=" nav nav-tabs">' + '<li class="active"><a id="location-link">Location</a></li>' + '<li class="active"><a id="finance-link">Finance</a></li>' + '<li class="active"><a id="attachments-link">Attachments</a></li>' + '<li class="active"><a id="images-link">Images</a></li>' + '<li class="active"><a id="planning-link">Planning</a></li>' + '<li class="active"><a id="other-link">Other</a></li>' + '</ul> ' var address1 = App.GlobalCommon.textarea('address1', 'address1', '{{prospect.address1}}', 'The Address1', 'text') var prefix = "prospect"; var postcode = App.GlobalCommon.input_data_string('postcode', 'The Postcode', "prospect") var price_low = App.GlobalCommon.input_data_string('price_low', 'The Low Price', "prospect") var price_high = App.GlobalCommon.input_data_string('price_high', 'The High Price', "prospect") var price_sell = App.GlobalCommon.input_data_string('price_sell', 'The Estimated Sale Price', "prospect") var source_types = App.GlobalCommon.dropdown('The source type', 'source_type_id', 'source_type_id', data.source_types, ''); var sale_types = App.GlobalCommon.dropdown('The sale type', 'sale_type_id', 'sale_type_id', data.sale_types, ''); var status = App.GlobalCommon.dropdown('The Status type', 'status_id', 'status_id', data.statuses, ''); var detailed_planning_permission = App.GlobalCommon.checkbox('detailed_planning_permission', 'detailed_planning_permission', 'Detailed planning permission', '0') var outline_planning = App.GlobalCommon.checkbox('outline_planning', 'outline_planning', 'Outline planning', '0') var upload = App.GlobalCommon.uploadify("Select file[s]"); upload = '<div id="queue"></div><input id="file_upload" name="file_upload" type="file" multiple="true">' var id = App.GlobalCommon.inputstring("prospect_id", "prospect_id", "{{prospect.id}}", "", "hidden"); var location_info = address1 + postcode; var location_map = "<div id='control-group'><div id='location-map'/></div>" // var location = "<h5>Location</h5>" + App.Common.div("location","location-info row", location_info + location_map); var location = App.GlobalCommon.div("location-content", "tab-content", "<h5 id=location>Location</h5>" + location_info + location_map); var other = App.GlobalCommon.div("other-content", "tab-content", "<h5 id=other>Other</h5>" + sale_types + source_types + status) var finance = App.GlobalCommon.div("finance-content", "tab-content", "<h5 id=finance>Financial</h5>" + price_low + price_high + price_sell) var planning = App.GlobalCommon.div("planning-content", "tab-content", "<h5 id=planning>Planning</h5>" + detailed_planning_permission + outline_planning) var attachments = App.GlobalCommon.div("attachments-content", "tab-content", "<h5 id=attachments>Attachments</h5> " + upload + "<div class='attachments row row-fluid well offset2'>" + "<ul class='files'>{{#files}}<li><div class='file'><a href='/uskerfiles/files/{{filename}}'>{{filename}}</a></div></li>{{/files}}</ul>" + "</div>") var images = App.GlobalCommon.div("images-content", "tab-content", "<h5 id=images>Images</h5><div class='images row row-fluid well offset2'>{{#images}} <a href='/userfiles/files/{{filename}}'><img src='/userfiles/files/{{thumb}}'/></a>{{/images}}</div>") var fields = tab_panel + location + images + attachments + other + finance + planning + id; var form = App.GlobalCommon.form('<h3>{{prospect.address1}} {{prospect.postcode}}</h3>' + tabs, fields, 'btn_save_prospect', 'prospect_form'); return form; } } export class View_Prospects { static frame() { var tmp = "" tmp += "<div class='row-fluid'>" tmp += "<div class='sidebar well-small span2'>" tmp += "<a class='' href='#/newprospect'>New Prospect</a><hr>" tmp += "<div>Filter</div>" tmp += "<ul class='nav nav-list'>" tmp += "<li><a class='filter latest' href='#/prospects'>All / Latest</a></li>" tmp += "<li><a class='filter open' href='#/prospects/status/open'>Open</a></li>" tmp += "<li><a class='filter closed' href='#/prospects/status/closed'>Closed</a></li>" tmp += "</ul>" tmp += "</div>" tmp += "<div class='prospect_list span9'>{content}</div>" tmp += "</div>" return tmp; } static getTemplate() { var rows = "{{#prospects}}" + "<tr data-id='{{id}}'>" + "<td>#{{id}}</td>" + "<td class='status-{{status}}'>&bull; {{status}}</td>" + "<td class=address1>{{address1}}<br></td><td><small>{{postcode}}</small></td><td>created {{fuzzyCreated}}</td>" + "</tr>{{/prospects}}" var tmp = "" tmp += "<ul class='nav nav-tabs'><li class='active'><a href='#/prospects'>Prospects</a></li></ul>" tmp += "<table id=prospects class='table table-condensed table-hover'>" tmp += rows tmp += "</table>" return this.frame().replace("{content}", tmp); } public static init(data) { var client = new App.ProspectorServerClient() var viewdata = client.CallMethod("GetProspects", data) var cardTemplate = $.get("tmpl/ProspectCardView.html"); $.when(viewdata, cardTemplate) .then((data, tmpl) => this.render(data[0], tmpl[0]), null) } private static setData(data) { Enumerable.From(data.prospects).ForEach((item) => { item.fuzzyCreated = moment.utc(item.date_created).fromNow() }) return data; } public static render(data, tmpl) { this.setData(data) if (!tmpl) { tmpl = this.getTemplate(); } var html = App.ViewEngine.renderview(this.frame().replace("{content}", tmpl), data); $(".prospect-card").click((e) => { e.preventDefault(); var id = $(e.currentTarget).attr("data-id"); window.location.href = "#/prospect/" + id + "/edit"; }) return html; } } export class View_DeleteProspect { public static init(data) { this.render(data); } public static render(data) { var html = App.ViewEngine.renderview(this.getTemplate(), { id: data.id }) //events $("#deleteok").click((e) => { e.preventDefault() var client = new App.ProspectorServerClient() var serverdelete = client.CallMethod("DeleteProspect", data); $.when(serverdelete).then((data) => { ViewEngine.ClearScreen(); App.ViewPart.info("Success", "The prospect has been deleted") }, null) }) $("#deletecancel").click((e) => { e.preventDefault() window.history.go(-1) }) return html; } public static getTemplate() { var tmp = "<div class='well span3'>" tmp += "Delete Prospect {{prospect}} <br><br><a class='btn' id='deleteok' href='#/prospect/4/deleteok'>Yes</a> <a class='btn' id='deletecancel' href='#/prospect/4/deleteok'>No</a> " tmp += "</div>" return tmp; } } export class View_ProspectsMap { static getTemplate() { var title = '' var help = '<div class="control-label" for="map-canvas">You can move the pin here to acurately set the location of the property. Enter address and click search to view map.</div>' var searchbuton = '<div class="controls"><div><input class="input span3" id="query" type="text" placeholder="Enter a search eg postcode" value=""/><button id="btn_map_search" class="btn" type="button">Search</button></div><br>' var tmp = "<div id='latitude' style='display:none'></div>" tmp += "<div id='longitude' style='display:none'></div>" tmp += "<div id='prospect_id' style='display:none'></div>" tmp += "<div id='map-canvas' style='height: 400px;width: 400px;'>Waiting for search term</div></div>" return App.GlobalCommon.control(title + help + searchbuton + tmp) } public static getHtml(data) { this.setData(data) var html = App.ViewEngine.getHtml(this.getTemplate(), data); return html; } public static setData(data) { data.hasLocation = !(!data.prospect.latitude || !data.prospect.longitude) return data; } public static setEvents(data) { $("#prospect_id").text(data.prospect.id); if (data.hasLocation) { Component.GoogleMaps.show_location({ latitude: data.prospect.latitude, longitude: data.prospect.longitude }); } $("#btn_map_search").on("click", (e) => { e.preventDefault(); var query = $("#query").val(); if (query && query.length > 2) { Component.GoogleMaps.search_address_2(query); } }); amplify.subscribe("SearchAddress_reply", (data) => { Component.GoogleMaps.show_location({ latitude: data[0].geometry.location.lat(), longitude: data[0].geometry.location.lng() }); }); } public static render(data) { this.setData(data); var html = App.ViewEngine.getHtml(this.getTemplate(), data); App.ViewEngine.setAppHtml(html); this.setEvents(data); return html; } public static render_map(data) { var google: any = window["google"]; var mapOptions = { center: data[0].geometry.location, zoom: 18, mapTypeId: google.maps.MapTypeId.SATELLITE, }; Component.GoogleMaps.show_map(mapOptions, data); } public static search_address(address: string) { Component.GoogleMaps.search_address_2(address); } } export class View_NewProspect { public static init(data) { var client = new ProspectorServerClient(); var newserverdata = client.CallMethod("NewProspect", data) $.when(newserverdata).then((respData) => { this.render(respData); }, null) } public static render(data) { if (data.validationResult && data.validationResult.IsValid === false) { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } else { App.ViewEngine.renderview(this.getTemplate(data), {}) $("#price_low").val("0"); $("#price_high").val("0"); $("#btn_save_prospect").on("click", (e) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#prospect_form")); var client = new App.ProspectorServerClient() var addprospect = client.CallMethod("AddProspect", data) $.when(addprospect).then((data) => { if (data.validationResult.IsValid) { App.ViewPart.info("Success", "The prospect has added."); } else { App.GlobalCommon.apply_validation(data.validationResult, $("#prospect_form")); } }, null); }) } } public static div(id: string, cssclass: string, content: string) { var tmp = "<div id='{id}' class='{class}'>{content}</div>" if (!cssclass) { cssclass = ''; } if (!id) { id = ''; } return tmp.replace('{id}', id).replace('{class}', cssclass).replace('{content}', content) } public static getTemplate(data) { var address1 = App.GlobalCommon.textarea('address1', 'address1', '', 'The Address1', 'text') var postcode = App.GlobalCommon.inputstring('postcode', 'postcode', '', 'The Postcode', 'text') var price_low = App.GlobalCommon.inputstring('price_low', 'price_low', '', 'The Low Price', 'text') var price_high = App.GlobalCommon.inputstring('price_high', 'price_high', '', 'The High Price', 'text') var sale_types = App.GlobalCommon.dropdown('The sale type', 'sale_type_id', 'sale_type_id', data.sale_types, ''); var source_types = App.GlobalCommon.dropdown('The source type', 'source_type_id', 'source_type_id', data.source_types, ''); var detailed_planning_permission = App.GlobalCommon.checkbox('detailed_planning_permission', 'detailed_planning_permission', 'Detailed planning permission', '0') var outline_planning = App.GlobalCommon.checkbox('outline_planning', 'outline_planning', 'Outline planning', '0') var upload = App.GlobalCommon.upload('Please enter a file to upload'); var fields = address1 + postcode + price_low + price_high + sale_types + source_types + detailed_planning_permission + outline_planning; var form = App.GlobalCommon.form('<h4>Add prospect</h4>', fields, 'btn_save_prospect', 'prospect_form'); return form; } } }<file_sep>using System; using System.Web; namespace Tekphoria.Web.linkr { public partial class Goto : LinkrPage { protected void Page_Init(object sender, EventArgs e) { string url = HttpContext.Current.Request.QueryString.Get("h") ?? string.Empty; string id = HttpContext.Current.Request.QueryString.Get("id") ?? string.Empty; if (string.IsNullOrEmpty(url) || (string.IsNullOrEmpty(id))) Response.Redirect("index.aspx"); try { svr.Increment(new { id }); } finally { svr.CloseConnections(); } Response.Redirect(url); } } } <file_sep>using System; using System.Web.UI; using System.Web.UI.WebControls; namespace Tekphoria.Web.global_pages { public partial class MessagePanelCollection : UserControl { //public ErrorPanel Error_Panel { get; set; } //public SuccessPanel Success_Panel { get; set; } //public InfoPanel Info_Panel { get; set; } public MessagePanelCollection() { //Error_Panel = ErrorPnl; //Success_Panel = SuccessPnl; //Info_Panel = InfoPnl; } protected void Page_Load(object sender, EventArgs e) { } public void HideAll() { ErrorPnl.Visible = SuccessPnl.Visible = InfoPnl.Visible = false; } } } <file_sep>interface Amplify { // Pub sub subscribe(topic: string, callback: Function); subscribe(topic: string, context: any, callback: () => any); subscribe(topic: string, callback: () => any, priority: number); subscribe(topic: string, context: any, callback: () => any, priority: number); unsubscribe(topic: string, callback: () => any); publish(topic: string); publish(topic: string, ...params: any[]); publish(topic: string, data: any); //publish(topic: string, data: WB.Event); // Store store(key: string, value: any, options?: any); store(key: string); } declare var amplify: Amplify;<file_sep>using System; using System.Web.UI; using System.Web.UI.WebControls; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Account; namespace Tekphoria.Web.account { public partial class CreateAccount : Page { protected void Page_Load(object sender, EventArgs e) { error_panel.Controls.Clear(); error_panel.Visible = false; success_panel.Visible = false; if (!IsPostBack) { new_display_name.Text = ""; new_password.Text = ""; new_email.Text = ""; } else { var ob = new JObject(); new_email.Text = new_email.Text.Trim(); new_display_name.Text = new_display_name.Text.Trim(); new_password.Text = <PASSWORD>.Trim(); ob.Add("email", new JValue(new_email.Text)); ob.Add("display_name", new JValue(new_display_name.Text)); ob.Add("password", new JValue(new_password.Text)); var accountserver = new AccountServer(); dynamic result = accountserver.UserAdd(ob); var validationResult = (ValidationResult)result.validationResult; if (validationResult.Errors.Count > 0) { error_panel.Visible = true; success_panel.Visible = false; foreach (ValidationFailure er in validationResult.Errors) { error_panel.Controls.Add(new Literal { Text = string.Concat("<p>", er.ErrorMessage, "</p>") }); } } else { accountserver.LogOut(); accountserver.UserSignInTry(ob); error_panel.Visible = false; success_panel.Visible = true; input_panel.Visible = false; } } } } } <file_sep>/// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../account/Account.ts" /> /// <reference path='WB.Common.ts'/> /// <reference path='WB.BoardClasses.ts'/> /// <reference path='WB.StoryClasses.ts'/> /// <reference path='WB.TaskClasses.ts'/> /// <reference path='WB.MiscController.ts'/> /// <reference path="wb.userclasses.ts" /> module WB { export class AppStart { private window: Window; private static hasSetEvents: boolean = false; public static IsLoggedIn: boolean = false; public static UserId: number = 0; public static Email: string = ""; public static start() { var html = Account.LoginBarView.getHtml(); $("#user_bar").html(html); this.registerEvents(); this.registerRoutes(); this.gotoBoardIfExists(); } public static showSignedInBits() { var html = Account.LoginBarView.getHtml(); $("#user_bar").html(html); } public static hideSignedInBits() { $("#user_bar").html(""); } static registerRoutes() { window.routie({ 'user/:id': (data) => UserController.USER_GET(data), 'boards': () => BoardController.BOARDS_LIST(), 'boards/addshared': (data) => BoardController.USER_ADD_SHARED_BOARD(data), 'boards/add': () => BoardController.BOARD_ADD(), 'board/:hash/config': (hash) => BoardController.BOARD_GET_CONFIGURATION(hash), 'board/:hash/delete': (hash) => BoardController.BOARD_DELETE(hash), 'board/:hash/addstory': (hash) => StoryController.STORY_ADD_TO_BOARD(hash), 'board/:hash/archive': (hash) => BoardController.BOARD_GET_ARCHIVE(hash), 'board/:hash': (hash) => BoardController.BOARD_GET(hash), 'task/addtostory/:id/:hash': (id, hash) => TaskController.TASK_ADD_TO_STORY(id, hash), 'task/:id': (id) => TaskController.TASK_GET(id), 'task/delete/:id': (id) => TaskController.TASK_DELETE(id), 'story/:id/delete': (id) => StoryController.STORY_DELETE(id), 'story/:id': (id) => StoryController.STORY_GET(id), // OK '/': (id) => BoardController.BOARDS_LIST(), '': () => BoardController.BOARDS_LIST() }); } private static registerEvents() { if (!this.hasSetEvents) { amplify.subscribe("getLoginView", data => this.showSignedInBits()); this.hasSetEvents = true; } } private static gotoBoardIfExists() { var lastBoard = amplify.store("last_board_hash") if (lastBoard) { window.routie("board/" + lastBoard) } } } } WB.AppStart.start();<file_sep>/// <reference path="printerServerClient.ts" /> /// <reference path="../global_js/app.globalcommon.ts" /> /// <reference path="../global_js/jquery-1.9.1.d.ts" /> module printer { export class app { public static init() { } } export class PrinterFormView { //static action = ''; static timerid = 0; private static timeoutFunc(data) { var client = new PrinterServerClient() var act = client.CallMethod("GetStatus", data) $.when(act).then(resp=> { if (resp.res) { clearTimeout(this.timerid); if (resp.file.substr(-4) === ".pdf") { window.location.href = '/userfiles/' + resp.file } else { $("form").after("<br><img class=snap src='/userfiles/" + resp.file + "'/>") } } else { $(".log").last().after("<div class='log'> > waiting</div>") } }) } constructor() { var urlparms = App.GlobalCommon.getUrlParams(); var inputs : any = $.extend({}, App.GlobalCommon.getUrlParams()) if (inputs.url) { inputs.url = inputs.url.replace("http://", "").replace("https://", "") inputs.url = "http://" + inputs.url; if (inputs.url) { inputs.url = inputs.url.replace("http://", "").replace("https://", ""); inputs.url = "http://" + inputs.url; $("input[type='radio'][name='format'][value='pdf']").prop("checked", true) // $("#submitbutton").click(); } } if (inputs) { for (var propertyName in inputs) { $("input[name=" + propertyName + "]").first().val(inputs[propertyName]); //$("input[type=radio][name=" + propertyName + "][value=" + inputs[propertyName] +"]").first().prop("checked", true); } } $("form").submit((e) => PrinterFormView.formSubmit(e)) } private static formSubmit(e) { e.preventDefault(); App.GlobalCommon.clearErrors() $(":submit").attr("disabled", true); $(".snap, .log").remove() $("form").after("<div class=log> > requesting</div>") var url = $("#url").val() var client = new PrinterServerClient() var data = { format: $("input[type='radio'][name='format']:checked").val(), url: encodeURIComponent(url), renderTime: $("input[type='radio'][name='renderTime']:checked").val() } //PrinterFormView.timeoutFunc(data) this.timerid = setInterval(() => PrinterFormView.timeoutFunc(data), 5000); var act = client.CallMethod("Print", data) $.when(act).then(resp=> { if (resp.validationResult.IsValid === false) { App.GlobalCommon.apply_validation(resp.validationResult, $("form")); } else { //this.action = 'stop' $(":submit").attr("disabled", false); // setTimeout(()=> $(".log").remove(), 3000); } }) } } }<file_sep>var __extends = this.__extends || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __(); }; var chess; (function (chess) { var program = (function () { function program() { } program.prototype.run = function () { this.registerEvents(); var controller = new gamecontroller(); controller.home(); }; program.prototype.registerEvents = function () { amplify.subscribe("new_game_fired", function (data) { }); }; return program; })(); chess.program = program; (function (gamestate) { gamestate[gamestate["playing"] = 0] = "playing"; gamestate[gamestate["waiting"] = 1] = "waiting"; gamestate[gamestate["settingup"] = 2] = "settingup"; gamestate[gamestate["none"] = 3] = "none"; })(chess.gamestate || (chess.gamestate = {})); var gamestate = chess.gamestate; var gamecontroller = (function () { function gamecontroller() { } gamecontroller.prototype.home = function () { var view = new views.home(); var board = new chess.board(); var game = new chess.game(); game.board = board; view.render({ data: game }); }; gamecontroller.prototype.addwhiteplayer = function (player) { var client = new ChessServerClient(); client.CallMethod("AddPlayer", { player: player }); }; gamecontroller.prototype.addblackplayer = function (player) { var client = new ChessServerClient(); client.CallMethod("AddPlayer", { player: player }); }; return gamecontroller; })(); chess.gamecontroller = gamecontroller; var game = (function () { function game() { this.gamestate = gamestate.none; } return game; })(); chess.game = game; var player = (function () { function player(name) { this.name = name; } return player; })(); chess.player = player; var ChessServerClient = (function (_super) { __extends(ChessServerClient, _super); function ChessServerClient() { _super.call(this, "chess_server.ashx"); } return ChessServerClient; })(App.ServerClientBase); chess.ChessServerClient = ChessServerClient; var board = (function () { function board() { this._squares = []; this._graveyard = []; this.init(); } board.prototype.squares = function () { return this._squares; }; board.prototype.graveyard = function () { return this._graveyard; }; board.prototype.init = function () { this._squares = [ ['br1', 'bk1', 'bb1', 'bkg1', 'bq', 'bb2', 'bk2', 'br2'], ['bp1', 'bp2', 'bp3', 'bp4', 'bp5', 'bp6', 'bp7', 'bp8'], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['', '', '', '', '', '', '', ''], ['wp1', 'wp2', 'wp3', 'wp4', 'wp5', 'wp6', 'wp7', 'wp8'], ['wr1', 'wk1', 'wb1', 'wkg1', 'wq', 'wb2', 'wk2', 'wr2'] ]; this._graveyard = []; }; return board; })(); chess.board = board; })(chess || (chess = {})); <file_sep>var App; (function (App) { var invoice = (function () { function invoice() { } invoice.init = function () { var _this = this; var inputs = amplify.store("invoice_inputs"); if (inputs) { for (var propertyName in inputs) { $("[name=" + propertyName + "]").first().val(inputs[propertyName]); } } $("#generate-button").off("click").on("click", function (e) { e.preventDefault(); _this.processInputs(); }); KeyboardJS.on('ctrl > s', function (e) { e.preventDefault(); _this.processInputs(); }); KeyboardJS.on('ctrl > f', function (e) { e.preventDefault(); var form = $("#input-form"); if (form.is(':visible')) { form.hide(); } else { form.show(); } }); KeyboardJS.on('ctrl > p', function (e) { e.preventDefault(); $("#input-form").hide(); $("#email").hide(); window.print(); }); this.processInputs(); }; invoice.getLastMonthDate = function () { var date = moment().subtract('months', 1).calendar(); return moment(date).format("MMM YYYY"); }; invoice.getReference = function (companycode, counter) { return "Invoice-" + companycode + moment().format("YYMM") + "-" + counter; }; invoice.processInputs = function () { var inputs = App.GlobalCommon.getFormInputs($("body")); amplify.store("invoice_inputs", inputs); var results = {}; results.days = inputs.inputdaysworked; results.net = inputs.inputdayrate * inputs.inputdaysworked; results.dayrate = inputs.inputdayrate; results.nettotal = results.net; results.vat = (inputs.inputvatrate / 100) * results.net; results.payable = results.net + results.vat; results.reference = this.getReference(inputs.inputcompanycode, inputs.inputcounter); results.invoicedate = moment().format("D MMMM YYYY"); var lastmonth = moment().subtract('month', 1).calendar(); results.lastmonth = moment(lastmonth).format("MMMM YYYY"); results.emaildatesubject = results.lastmonth; results.emaildatebody = results.lastmonth; var accounting = window["accounting"]; results.net = results.nettotal = accounting.formatMoney(results.net, "£"); results.vat = accounting.formatMoney(results.vat, "£"); results.payable = accounting.formatMoney(results.payable, "£"); results.dayrate = accounting.formatMoney(results.dayrate, "£"); for (var propertyName in results) { $("#" + propertyName).text(results[propertyName]); } var required = $("body").find("[data-required=true]"); $.each(required, function (x, item) { var frag = $(item); var text = frag.text(); if (!text.length) { alert("Error: " + frag.attr("id")); } }); $("title").text(results.reference); $("body").fadeIn().fadeOut().fadeIn(); }; invoice.accounting = window["accounting"]; return invoice; })(); App.invoice = invoice; })(App || (App = {})); <file_sep>/// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/jqueryui-1.9.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="wb.storage.ts" /> /// <reference path="wb.logclasses.ts" /> /// <reference path="wb.taskclasses.ts" /> /// <reference path="wb.interfaces.ts" /> /// <reference path="wb.errorclasses.ts" /> /// <reference path="WB.StoryClasses.ts" /> module WB { export class Board { constructor( public id: string, public nameof: string, public columns?: string[], public stories?: Story[], public tasks?: Task[] ) { } } export class BoardSummary { constructor( public id: number, public nameof: string ) { } } export class BoardController { public static BOARDS_LIST() { var boards: Board[] = []; var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardsList", {}) $.when(action).then(resp => BoardsView.render(resp)); } public static BOARD_ADD() { BoardAddView.render(); } public static BOARD_DELETE(hash: string) { DeleteBoardView.render(hash); } public static BOARD_GET(hash: string) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetByHash", { hash: hash }) $.when(action).then(resp => this.HandleBoardResponse(resp) ); } public static HandleBoardResponse(resp) { if (resp.board) { BoardView2.render(resp); } else { window.routie("boards"); } } public static BOARD_DELETE_REPLY() { } public static BOARD_GET_CONFIGURATION(hash) { var client = new WB.ScrumboServerClient(); var action = client.CallMethod("BoardGetConfiguration", { hash: hash }) $.when(action).then(resp => BoardConfigView.render(resp)) } public static BOARD_GET_ARCHIVE(hash) { var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardGetArchiveByHash", { hash: hash }) $.when(act).then(resp => BoardArchiveView.render(resp)) } public static USER_ADD_SHARED_BOARD(data) { AddSharedBoardView.render() } } /* ========================================================================================= */ export class BoardView2 { public static render(data: any): void { amplify.store("last_board_hash", data.board.hash) if (data.board.extra_status_2) data.columns.splice(2, 0, data.board.extra_status_2); if (data.board.extra_status_1) data.columns.splice(2, 0, data.board.extra_status_1); var rows: string = ""; Enumerable.From(data.stories).OrderBy((s: Story) => s.sort_order).ForEach((story: Story) => { rows += "<tr data-storyid=" + story.id + ">" rows += "<td valign=top align=center>" + StoryView.munged(story, data.board.hash) + "</td>" Enumerable.From(data.columns).ForEach((col, idx) => { rows += "<td valign=middle align=center><div class='tasks' data-storyid='" + story.id + "' data-status='" + col + "'>" Enumerable.From(data.tasks).OrderBy((t: Task) => t.sort_order).ForEach((t: Task) => { if (t.story_id === story.id && t.status === col) { t.display_name = Enumerable.From(data.users).FirstOrDefault(u => t.user_id === u.id).display_name rows += WB.TaskView.getHtml(t); } }); rows += "</div></td>"; }) rows += "</tr>" }); // add empty rows if (data.stories.length < 6) { Enumerable.RangeTo(data.stories.length, 5).ForEach(i => { rows += "<tr>" Enumerable.RangeTo(0, data.columns.length).ForEach(i => { rows += "<td></td>" }) rows += "</tr>" }) } data.rowsHtml = rows; var toolbar = App.ViewEngine.getHtml(this.getToolBarTemplate(), data); var takmoreView = WB.TaskMoreBarView.getHtml({id:0}) WB.TaskMoreBarView.setEvents() App.ViewEngine.renderview(this.getTemplate(), data); $("#board").append(toolbar) $("#board").before(takmoreView) this.makeTasksSortable() this.makeStoriesSortable() } static makeTasksSortable() { var tasklists = $(".tasks"); tasklists.sortable({ connectWith: ".tasks", cursor: "move", placeholder: 'hover', distance: 1, tolerance: "pointer", start: (event, ui) => { var id = $(ui.item).attr("data-id"); var tasks = $(ui.item).parent(); var story_id = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var start_index = ui.item.index(); var start_data = '' + story_id + status + start_index; // create a key to determin current state so as not to update unecessarily tasks.attr('data-start_data', start_data); }, stop: (event, ui) => { var tasks = $(ui.item).parent(); var board_id = $("#board_id").val(); var tasks_all = tasks.find(".task"); var story_id = tasks.attr("data-storyid"); var status = tasks.attr("data-status"); var id = $(ui.item).attr("data-id"); var new_index = ui.item.index(); // read start data to determin id a server method needs to be sent var start_data = tasks.attr('data-start_data'); var new_data = '' + story_id + status + new_index; if (new_data === start_data) { return; } else { if (status === 'archive') { TaskController.TASK_UPDATE_STATUS({ id: id, status: 'archive' }); return; } var task_ordering = Enumerable.From(tasks_all).Select((t: Task) => { return +$(t).attr("data-id"); }).ToArray(); TaskController.TASK_MOVE({ board_id: board_id, story_id: story_id, id: id, status: status, task_ordering: task_ordering }); } } }).disableSelection(); } static makeStoriesSortable() { var touch = 'ontouchend' in document; if (!('ontouchend' in document)) { $("#board tbody").sortable({ placeholder: 'hover', cursor: "move", stop: (event, ui) => { var stories = $(ui.item).parent(); var stories_all = stories.find(".story"); var id = $(ui.item).attr("data-storyid"); var story_order = Enumerable.From(stories_all).Select((s: Story) => { return +$(s).attr("data-id"); }) .ToArray(); var data = { id: id, story_order: story_order } var client = new WB.ScrumboServerClient(); client.CallMethod("BoardSortStory", data) } }); } } public static getTemplate() { return "" + "<table width=100%>" + "<tr>" + "<td>" + "<div class='board-name pagination-left'>{{board.nameof}}</div>" + "<div class='board-moreinfo'>{{&board.more_info}}</div>" + "</td>" + "<td align=right>" + "<div class=''>" + "<a href='#boards'>All Boards</a>" + " <a href='#board/{{board.hash}}/config'>Configure</a> " + " <a href='#board/{{board.hash}}/archive'>Archive</a> " + " <a href='#board/{{board.slug}}/{{board.hash}}'>Link</a>" + "</div>" + "</td>" + "</tr>" + "</table>" + "<table id='board' class='table' align=center data-id={{board.hash}}>" + "<thead>" + "<th>Story <a class='btn btn-mini info' href='#board/{{board.hash}}/addstory'>add</a></th>" + "{{#columns}}<th>{{.}}</th>{{/columns}}" + "</tr>" + "</thead>" + "<tbody>" + "{{&rowsHtml}}" + "</tbody>" + "</table>" + "{{&board.taskMoreBarViewHtml}}" + "<input type=hidden id=board_id value='{{board.hash}}'></input>" } static getToolBarTemplate() { return "<div>" //+ " <a href='#board/{{board.hash}}/config'>Configure</a> " //+ " <a href='#board/{{board.hash}}/archive'>Archive</a> " //+ " <a href='#board/{{board.slug}}/{{board.hash}}'>Link</a>" + "</div>"; } } /* ========================================================================================= */ export class BoardConfigView { public static render(boardConfigData: any) { App.ViewEngine.renderview(this.getTemplate(), boardConfigData); $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var formdata = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardSetConfiguration", formdata); $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), window.history.back(1))) }); } static getTemplate(): string { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '{{board.nameof}}', 'The name of the board', 'text') // var top = App.GlobalCommon.inputstring('top_status', 'top_status', '{{board.top_status}}', 'Status for the top section', 'text') var info = App.GlobalCommon.textarea('more_info', 'more_info', '{{board.more_info}}', 'Extra infomation to be displayed.', '5') var status1 = App.GlobalCommon.inputstring('extra_status_1', 'extra_status_1', '{{board.extra_status_1}}', 'Status Column 1 after between inprogress and done.', 'text') var status2 = App.GlobalCommon.inputstring('extra_status_2', 'extra_status_2', '{{board.extra_status_2}}', 'Status Column 2 after between inprogress and done.', 'text') var hash = App.GlobalCommon.inputstring('hash', 'hash', '{{board.hash}}', '', 'hidden') return App.GlobalCommon.form('Configure board', nameof + info + status1 + status2 + hash) } } /* ========================================================================================= */ export class BoardTrashView { public static render() { this.registerEvents(); App.ViewEngine.renderview(this.getTemplate(), {}) } public static getHtml() { return this.getTemplate(); } static registerEvents() { } static getTemplate() { this.registerEvents(); return "<div class='trash'><img src='/img/trash.png'/></div>"; } } /* ========================================================================================= */ export class BoardAddView { private static getFormInputsAsObject(): any { var form: JQuery = $("#form1"); return App.GlobalCommon.getFormInputs(form); } public static render(): void { App.ViewEngine.renderview(this.getTemplate(), {}) //events var submitbtn = $("#btnsubmit"); var hash = $("#hash"); submitbtn.on("click", (e: any) => { e.preventDefault(); hash.val(App.GlobalCommon.createUUID(12, 36)); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardAdd", data) $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window.history.back(1))) }); } public static getTemplate(): string { var nameof = App.GlobalCommon.inputstring('nameof', 'nameof', '', 'The name of the board', 'text') var hash = App.GlobalCommon.inputstring('hash', 'hash', App.GlobalCommon.createUUID(12, 36), '', 'hidden') return App.GlobalCommon.form('Add a board', nameof + hash) } } /* ========================================================================================= */ export class BoardsView { public static render(boards: any): void { App.ViewEngine.renderview(this.getTemplate(), boards) } static getTemplate(): string { return "<div class=container><strong>Boards</strong><br>" + "<div class='pull-right'><a class='' href='#boards/addshared'>Add Shared Board</a> <a class='btn' href='#boards/add'>New Board</a></div>" + "<table class='table'><br><br>{{#BoardSummaries}}<tr><td><a class='' href='#board/{{hash}}'><strong>{{nameof}}</strong></a> </td>" + "<td><a class='' href='#board/{{hash}}/addstory'>+story</a></td><td><span class=muted>key: {{hash}}</span></td>" + "</tr>{{/BoardSummaries}}</table></div>" } } /* ========================================================================================= */ export class DeleteBoardView { public static render(hash): void { App.ViewEngine.renderview(this.getViewTemplate(), { "hash": hash }); $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("BoardDelete", data); $.when(act) .then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window["routie"]("boards"))) }); } static getViewTemplate(): string { return App.GlobalCommon.form('<div class="alert alert-danger">DANGER ZONE! Actions taken will delete a board</div>', 'To Cancel use the back button or press submit to delete the board' + App.GlobalCommon.inputstring('hash', 'hash', '{{hash}}', '', 'hidden') ) } } /* ========================================================================================= */ export class BoardArchiveView { public static render(data): void { var tasksHtml = ''; Enumerable.From(data.tasks).ForEach((t: Task) => { tasksHtml += TaskView.getHtml(t); }); data.tasksHtml = tasksHtml; var taskMoreBarViewHtml = TaskMoreBarView.render(data); App.ViewEngine.renderview(this.getViewTemplate() + taskMoreBarViewHtml, data); $('#archivedtasks').masonry({ itemSelector: '.task', }); } static getViewTemplate(): string { return '<div class="well clearfix board_archive"><strong>Board Archive</strong><hr><div id="archivedtasks" >{{&tasksHtml}}</div></div>'; } } export class AddSharedBoardView { public static render() { App.ViewEngine.renderview(this.getTemplate(), {}) $("#btnsubmit").off("click").on("click", (e: any) => { e.preventDefault(); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var act = client.CallMethod("UserAddSharedBoard", data); $.when(act) .then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), () => window["routie"]("boards"))) }); } static getTemplate(): string { var hash = App.GlobalCommon.inputstring('hash', 'hash', '', 'The shared boards hash', 'text') // var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden') return App.GlobalCommon.form('Link shared board', hash) } } } <file_sep>namespace Tekphoria.Web.Server.Handlers { public class EmailArgs { public string To { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool IsHtml { get; set; } } }<file_sep>/// <reference path="main.ts" /> "use strict"; module app { export class starter { public static start() { require(["jquery", "mustache", "stache!linklist"], (jquery, mustache, tmpl) => { var data = { head: "Recent", foot: "more.." }; $("#app").html(tmpl(data)); }); } } }<file_sep>/// <reference path="App.GlobalCommon.ts" /> module App { export class Payload { constructor(public methodName: string, public data: any) { } } export class ServerClientBase { private _endpoint: string = ""; constructor(endpoint: string) { if (!endpoint) { throw Error("No endpoint") return; } this._endpoint = endpoint; } private translate(input: string) { var res = ""; for (var i = 0; i < input.length; i++) { res += String.fromCharCode(1083756 ^ input.charCodeAt(i)); } return res; } private sendPayload(payload: Payload, next: Function) { if (!payload) { throw Error("No payload") } return $.ajax({ type: "POST", url: this._endpoint, headers: { "UserId": App.GlobalCommon.readCookie("UserId"), "Auth": App.GlobalCommon.readCookie("Auth") }, dataType: 'JSON', cache: false, //contentType: "application/json; charset=utf-8", //data: this.translate(JSON.stringify(payload)), data: JSON.stringify(payload), success: (data, b, c)=> { if (data && data.code && data.code === 401) { window.location.href = '/login' return } // alert("Hello") // payload.methodName = ""; next(data) //var t = c.responseText; //var u = this.translate(t); //next(JSON.parse(u)); }, error: ()=> { }, statusCode: { // 401: () => window.location.href = '/login', 404: (resp) => this.SetError(resp), 403: () => window.location.href = '/login', 500: (resp) => this.SetError(resp) } }) } private SetError(resp) { $(".navbar-fixed-bottom").empty(); $("#user_bar").empty(); App.ViewEngine.setAppHtml(resp.responseText); } public CallMethod(methodName: string, data: any) { var payload = new Payload(methodName, data); return this.sendPayload(payload, (data) => { amplify.publish(methodName + "_reply", data); }); } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text.RegularExpressions; using FluentValidation.Results; using Tekphoria.Server.Common; namespace Tekphoria.Server.Prospect { public class ProcessorActions { } }<file_sep>using System; using System.Data; using Newtonsoft.Json.Linq; namespace Tekphoria.Web.linkr { public partial class DeleteLink : LinkrPage { protected void Page_Load(object sender, EventArgs e) { ErrorPanel.Visible = InfoPanel.Visible = SuccessPanel.Visible = false; if (IsPostBack) { try { string id = Context.Request.QueryString["id"] ?? ""; if (string.IsNullOrWhiteSpace(id)) throw new DataException("Data is missing."); //if (!confirm.Checked) // throw new ArgumentOutOfRangeException(); var data = new JObject(); data.Add("id", id); data.Add("user_id", GetNonEmptyCookie("UserId")); svr.DeleteLink(data); SuccessPanel.Msg = "Link deleted"; } catch (ArgumentOutOfRangeException) { ErrorPanel.Msg = "The confirm checkbox was not checked. Please check the confirm checkbox to delete the link."; } catch (Exception ex) { ErrorPanel.Msg = "Error deleting Link " + ex.Message; } finally { svr.CloseConnections(); } Response.Redirect("/linkr/links"); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; namespace Tekphoria.Web.linkr { public partial class AllLinks : LinkrPage { protected void Page_Load(object sender, EventArgs e) { try { string userid = GetNonEmptyCookie("UserId"); int h; Int32.TryParse(Request["h"], out h); IEnumerable<LinkDB> links = svr.GetLinks(userid, h == 1).ToArray(); LinksAll.Links = links.OrderBy(l => l.textof).ToArray(); } finally { svr.CloseConnections(); } } } } <file_sep>/* Demo: jQuery Deck Shuffle Author: <NAME> Author URL: http://www.ianlunn.co.uk/ Demo URL: http://www.ianlunn.co.uk/demos/jquery-deck-shuffle/ Tutorial URL: http://www.ianlunn.co.uk/blog/code-tutorials/jquery-deck-shuffle/ License: http://creativecommons.org/licenses/by-sa/3.0/ (Attribution Share Alike). Please attribute work to Ian Lunn simply by leaving these comments in the source code or if you'd prefer and be so kind, place a link on your website to http://www.ianlunn.co.uk/. Dual licensed under the MIT and GPL licenses: http://www.opensource.org/licenses/mit-license.php http://www.gnu.org/licenses/gpl.html */ //global variables to be setup for later use var previous; var active; //moves the top layer to the middle and ammends the size of all child elements function moveMiddle(el){ $(el).animate({'left': '100px', 'height': '288px', 'width': '224px', 'top': '52px'}, {duration: 200,queue: false}); //moves the layer to the middle $(el).children('h2, p, ul').animate({'font-size': '80%'}, {duration: 200,queue: false}); //makes all text elements smaller $(el).children('.order').animate({'width': '80%'}, {duration: 200,queue: false}); //makes the order button smaller $(el).css({'z-index': '2'}); //moves the layer back one (to sit behind the top layer) } //moves the middle layer to the bottom and ammends the size of all child elements function moveBottom(el){ $(el).animate({'left': '185px', 'height': '216px', 'width': '168px', 'top': '95px'}, {duration: 200,queue: false}); //moves the layer to the bottom $(el).children('h2, p, ul').animate({'font-size': '60%'}, {duration: 200,queue: false}); //makes all text elements smaller $(el).children('.order').animate({'width': '60%'}, {duration: 200,queue: false}); //makes the order button smaller $(el).css({'z-index': '1'}); //moves the layer back one (to sit at the bottom, behind all layers) } //moves the selected layer to the top of the deck function moveTop(el){ //the animation is active (we store this to make sure the animation doesn't try to run again whilst it's in progress) active = true; //move element out of the deck $(el).animate({'left': '310px', 'height': '360px', 'width': '280px', 'top': '0px'}, 200, function(){ $(el).css("z-index", 3); //move element to the top of the deck if(zindex == 2){ //if the user has selected the middle layer moveMiddle('.top'); //move the top layer to the middle $('.top').attr("class", "middle"); //top becomes middle $(el).attr("class", "top"); //hovered element becomes top }else if(zindex == 1){ //if the user has selected the bottom layer moveMiddle('.top'); //move the top layer to the middle moveBottom('.middle'); //move the middle layer to the bottom $('.middle').attr("class", "bottom"); //middle becomes bottom $('.top').attr("class", "middle"); //top becomes middle $(el).attr("class", "top"); //hovered element becomes top } $(el).animate({'left': '0px'}, 200, function(){ //move element back into the deck active = false; //the animation has finished }); }); $(el).children('p, ul, h2').animate({'font-size': '100%'}); //make the text elements full size $(el).children('.order').animate({'width': '100%'}); //make the order button full size } function swap(){ //the function called when we want to swap the cards zindex = $(this).css('z-index'); //get the z-index of the layer the cursor is over if(previous != zindex && zindex != 3 && active != true){ //if this isn't the previously moved layer, isn't the top layer and the animation is not currently running... moveTop(this); //move the layer to the top } previous = zindex; //store the last layer that was moved } function out(){ //required for .hoverIntent() to work } $(document).ready(function(){ //when the page has loaded and is ready to go... $('#container').mouseleave(function(){ //when the cursor leaves the deck... previous = null; }); $('#one, #two, #three').hoverIntent(swap, out); //if the user hovers over any card, activate the hoverIntent function... });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using Tekphoria.Web.Server.Sitemap; namespace Tekphoria.Web.Server.Handlers { public class SitemapTxtHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { // text/plain context.Response.ContentType = "text/plain"; context.Response.ContentEncoding = new UTF8Encoding(); context.Response.Write(GetContent()); } private StringBuilder GetContent() { var sb= new StringBuilder(); SitemapData.Items.ForEach(u => sb.AppendFormat("{0}{1}", u, Environment.NewLine)); return sb; } public bool IsReusable { get; private set; } } }<file_sep>module WB { export class MiscController{ constructor () { } public static show404() { alert("not found"); } } }<file_sep>var WB; (function (WB) { var TaskController = (function () { function TaskController() { } TaskController.TASK_ADD_TO_STORY = function (id, hash) { var _this = this; TaskAddView.render({ id: id, hash: hash }); $("#btnsubmit").on("click", function (e) { e.preventDefault(); $(e.target).attr("disabled", "disabled"); _this.submitForm(); }); }; TaskController.submitForm = function () { var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskAddToStory", form); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(-1); }); }); }; TaskController.TASK_MOVE = function (data) { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskMove", data); }; TaskController.TASK_UPDATE_STATUS = function (data) { var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data); }; TaskController.TASK_DELETE = function (deleteData) { TaskDeleteView.render(deleteData); }; TaskController.TASK_GET = function (id) { var client = new WB.ScrumboServerClient(); var serverData = client.CallMethod("TaskGet", { id: id }); $.when(serverData).then(function (resp) { return TaskEditView.render(resp); }); }; TaskController.validate = function (data) { if (data.IsValid !== 'undefined' && data.IsValid === false) { App.GlobalCommon.apply_validation(data, $("#form1")); } else { window.history.back(-1); } }; TaskController.TASK_DELETE_REPLY = function (data) { window.history.back(-1); }; return TaskController; })(); WB.TaskController = TaskController; var TaskMenuView = (function () { function TaskMenuView() { } TaskMenuView.getHtml = function (task) { return App.ViewEngine.getHtml(this.getTemplate(), task); }; TaskMenuView.getTemplate = function () { return "<div class='taskmenu' data-id={{id}}>" + "<a href='#' class='act'>Edit</a>" + "<a href='#' class='act'>Add Log</a>" + "<a href='#' class='act'>Add File</a>" + "<a href='#' class='act'>Archive</a>" + "<a href='#' class='act'>Delete</a>" + "</div>"; }; TaskMenuView.render = function (task) { App.ViewEngine.renderview(this.getTemplate(), task); }; return TaskMenuView; })(); WB.TaskMenuView = TaskMenuView; var TaskView = (function () { function TaskView() { } TaskView.adjustModel = function (task) { if (!task.css_class) task.css_class = 'task'; task.isEditable = task.status === "TODO"; task.showUser = (task.user_id > 0); task.fuzzyModified = moment.utc(task.date_modified).fromNow(); task.textof = App.GlobalCommon.uiify(task.textof); return task; }; TaskView.render = function (task) { this.adjustModel(task); App.ViewEngine.renderview(this.getTemplate(task), task); }; TaskView.getHtml = function (task) { this.adjustModel(task); return App.ViewEngine.getHtml(this.getTemplate(task), task); }; TaskView.getTemplate = function (task) { var done = task.status !== 'DONE' ? "" : " <a class='btntaskarchive' alt='archive' href='#' data-id='{{id}}'>archive</a>"; var archive = task.status !== 'ARCHIVE' ? "" : " <a class='btntaskdone' alt='archive' href='#' data-id='{{id}}'>set done</a>"; return "<div class='task {{css_class}} clearfix' data-id='{{id}}' data-status='{{status}}'>" + "<div class=ttext> {{&textof}}" + "<div class='task-foot clearfix'>" + "<span class=''>#{{id}}</span> changed <span>{{fuzzyModified}} by {{display_name}}</span>" + " <a data-id={{id}} class='taskmore' alt='view taskbar' href='#task/{{id}}'>edit</a>" + done + archive + " </div>" + "</div>" + "</div>"; }; return TaskView; })(); WB.TaskView = TaskView; var TaskDeleteView = (function () { function TaskDeleteView() { } TaskDeleteView.render = function (id) { App.ViewEngine.renderview(this.getTemplate(), { id: id }); $("#btnsubmit").on("click", function (e) { e.preventDefault(); var form = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskDelete", form); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(-1); }); }); }); }; TaskDeleteView.getTemplate = function () { var id = App.GlobalCommon.inputstring('id', 'id', "{{id}}", '', 'hidden'); return App.GlobalCommon.form('Delete Task ?', id + "Pressing Submit will delete the task and any associated objects permenantly."); }; return TaskDeleteView; })(); WB.TaskDeleteView = TaskDeleteView; var TaskAddLogView = (function () { function TaskAddLogView() { } TaskAddLogView.render = function (data) { return App.ViewEngine.renderview(this.getTemplate(), data); }; TaskAddLogView.getData = function (data) { data.board_hash = amplify.store("last_board_hash"); return data; }; TaskAddLogView.getHtml = function (data) { return App.ViewEngine.getHtml(this.getTemplate(), data); }; TaskAddLogView.getTemplate = function () { var log = App.GlobalCommon.textarea('textof', 'textof', '', 'Enter the log text.', ''); var id = App.GlobalCommon.inputstring('task_id', 'task_id', "{{id}}", '', 'hidden'); var form = App.GlobalCommon.form('Add Log item', log, 'btnaddlog', "formAddLog"); return form; }; return TaskAddLogView; })(); WB.TaskAddLogView = TaskAddLogView; var TaskAddView = (function () { function TaskAddView() { } TaskAddView.render = function (taskViewData) { App.ViewEngine.renderview(this.getTemplate(), taskViewData); }; TaskAddView.getTemplate = function () { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{textof}}', '', "7"); var id = App.GlobalCommon.inputstring('story_id', 'story_id', "{{id}}", '', 'hidden'); var css = ""; css += App.GlobalCommon.radio('css_class', 'task', 'Yellow', 'taskmini yellow', true); css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'taskmini green', false); css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'taskmini orange', false); css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'taskmini pink', false); css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'taskmini blue', false); css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'taskmini purple', false); var shortcut = "<div class='label'>shift + n to save</div>"; var hash = App.GlobalCommon.inputstring('hash', 'hash', "{{hash}}", '', 'hidden'); return App.GlobalCommon.form('New Task ' + shortcut, textof + id + css + hash); }; return TaskAddView; })(); WB.TaskAddView = TaskAddView; var TaskEditView = (function () { function TaskEditView() { } TaskEditView.prototype.render = function (data) { }; TaskEditView.prototype.registerEvents = function () { }; TaskEditView.prototype.getHtml = function () { return ""; }; TaskEditView.render = function (taskViewData) { var html = App.ViewEngine.renderview(this.getTemplate(taskViewData), taskViewData); $("input:radio[value=" + taskViewData.css_class + "]").first().attr('checked', "checked"); $("#btnsubmit").on("click", function (e) { e.preventDefault(); $(e.target).attr("disabled", "disabled"); var data = App.GlobalCommon.getFormInputs($("#form1")); var client = new WB.ScrumboServerClient(); var servertask = client.CallMethod("TaskUpdateText", data); $.when(servertask).then(function (resp) { App.GlobalCommon.processPostBack(resp, $("#form1"), function () { return window.history.back(-1); }); }); }); $("#btnaddlog").on("click", function (e) { e.preventDefault(); }); return html; }; TaskEditView.getTemplate = function (data) { var textof = App.GlobalCommon.textarea('textof', 'textof', '{{&textof}}', '', "7"); var css = ""; css += App.GlobalCommon.radio('css_class', 'task', 'Yellow', 'taskmini yellow', true); css += App.GlobalCommon.radio('css_class', 'taskgreen', 'Green', 'taskmini green', false); css += App.GlobalCommon.radio('css_class', 'taskorange', 'Orange', 'taskmini orange', false); css += App.GlobalCommon.radio('css_class', 'taskpink', 'Pink', 'taskmini pink', false); css += App.GlobalCommon.radio('css_class', 'taskblue', 'Blue', 'taskmini blue', false); css += App.GlobalCommon.radio('css_class', 'taskpurple', 'Purple', 'taskmini purple', false); var id = "<input class='form-editing' type='hidden' id='id' name='id' value='{{id}}' maxlength='50'>"; var form = App.GlobalCommon.form('Edit Task #{{id}}', textof + css + TaskSetStatusView.getHtml(data) + id); return form; }; return TaskEditView; })(); WB.TaskEditView = TaskEditView; var TaskSetStatusView = (function () { function TaskSetStatusView() { } TaskSetStatusView.getHtml = function (data) { this.init(data); return App.ViewEngine.getHtml(this.getTemplate(), data); }; TaskSetStatusView.init = function (data) { $("body").on("click", ".btn_status", function (e) { e.preventDefault(); var status = $(e.target).attr('data-status'); var id = $(e.target).attr('data-id'); var data = { status: status, id: id }; var client = new WB.ScrumboServerClient(); client.CallMethod("TaskUpdateStatus", data); window.history.back(-1); }); }; TaskSetStatusView.render = function (data) { this.init(data); return App.ViewEngine.renderview(this.getTemplate(), data); }; TaskSetStatusView.getTemplate = function () { var tmp = "<br><div class=''>Status</div><div class='btn-group'>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='INPROGRESS'>In progress</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='TODO'>To do</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='DONE'>Done</a>" + "<a class='btn btn-small btn_status' href='#' data-id='{{id}}' data-status='ARCHIVE'>Archive</a>" + "</div>"; return tmp; }; return TaskSetStatusView; })(); WB.TaskSetStatusView = TaskSetStatusView; var TaskMoreBarView = (function () { function TaskMoreBarView() { } TaskMoreBarView.setData = function (data) { data.trashview = WB.BoardTrashView.getHtml(); return data; }; TaskMoreBarView.render = function (data) { this.setData(data); this.setEvents(); return App.ViewEngine.renderview(this.getTemplate(), this.setData(data)); }; TaskMoreBarView.getHtml = function (data) { this.setData(data); this.setEvents(); return this.render(data); }; TaskMoreBarView.setEvents = function () { }; TaskMoreBarView.getTemplate = function () { return "<div data-id=0 id='TaskMoreBarView' class='taskmoreviewbar'><strong>Task Bar</strong>" + " <a class = 'btntaskedit' alt='view and edit details' href='#'><i class='icon-edit'></i> edit</a>" + " <a class = 'btntaskaddlog' alt='add log' href='#'><i class='icon-th-list'></i> add log</a>" + " <a class = 'btntaskarchive' alt='archive of the board' href='#'><i class='icon-folder-close'></i> archive</a>" + " <a class = 'btntaskclose' alt='close this' href='#' ><i class='icon-remove'></i> close </a>" + " <a class = 'btntaskdelete' alt='delete' href='#'><i class='icon-trash'></i> delete</a>" + " </div >"; }; return TaskMoreBarView; })(); WB.TaskMoreBarView = TaskMoreBarView; var Task = (function () { function Task(id, nameof, textof, story_id, status, sort_order, isEditable, css_class, user_id, showUser, fuzzyModified, display_name, date_modified) { this.id = id; this.nameof = nameof; this.textof = textof; this.story_id = story_id; this.status = status; this.sort_order = sort_order; this.isEditable = isEditable; this.css_class = css_class; this.user_id = user_id; this.showUser = showUser; this.fuzzyModified = fuzzyModified; this.display_name = display_name; this.date_modified = date_modified; } return Task; })(); WB.Task = Task; })(WB || (WB = {})); <file_sep>using System; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Web; using FluentValidation; using MySql.Data.MySqlClient; using Newtonsoft.Json; namespace Tekphoria.Server.Common { public abstract class JsonServer { public bool IsReusable { get { return false; } } public string Translate(string input) { var key = 1083756; var inSb = new StringBuilder(input); var outSb = new StringBuilder(input.Length); char c; for (int i = 0; i < input.Length; i++) { c = inSb[i]; c = (char)(c ^ key); outSb.Append(c); } return outSb.ToString(); } public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.ContentEncoding = Encoding.UTF8; string body; using (TextReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8)) body = reader.ReadToEnd(); //body = Translate(body); if (string.IsNullOrWhiteSpace(body)) throw new DataException("Payload is empty."); var payload = JsonConvert.DeserializeObject<Payload2>(body); payload.Data.user_id = context.Request.Headers["UserId"] ?? "0"; HttpContext.Current.Items["UserId"] = payload.Data.user_id; MethodInfo methodInfo = GetType().GetMethod(payload.MethodName); object[] attributes = methodInfo.GetCustomAttributes(typeof(ValidationAttribute), false); if (attributes.Length > 0) { var validationAttribute = attributes[0] as ValidationAttribute; } ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure; object result = methodInfo.Invoke(this, new object[] { payload.Data }); //context.Response.Write(Translate(JsonConvert.SerializeObject(result))); context.Response.Write(JsonConvert.SerializeObject(result)); } public static void HandleError(Exception ex) { HttpContext.Current.Response.StatusCode = 500; dynamic error = new { error = GetException(ex).Message }; HttpContext.Current.Response.Write(JsonConvert.SerializeObject(error)); } private static Exception GetException(Exception ex) { if (ex != null && ex.InnerException != null) { return ex.InnerException; } return ex; } private static string GetInnerExceptionMessage(Exception ex) { return string.Empty; var result = string.Empty; if (ex != null && ex.InnerException != null){ if (!string.IsNullOrWhiteSpace(ex.InnerException.Message)){ result = ex.InnerException.Message; } } return result; } public static IDbConnection GetOpenConnection(string connectionString) { IDbConnection dbConnection = new MySqlConnection(connectionString); dbConnection.Open(); return dbConnection; } public static void CloseConnection(IDbConnection con) { if (con != null) { con.Close(); con.Dispose(); } } public static void CloseConnection(Lazy<IDbConnection> con) { if (con != null && con.IsValueCreated && con.Value != null){ con.Value.Close(); con.Value.Dispose(); } } } }<file_sep>using System; namespace Tekphoria.Web.linkr { public class LinkDB { public int id { get; set; } public int user_id { get; set; } public DateTime date_created { get; set; } public string category { get; set; } public string href { get; set; } public string textof { get; set; } public string descof { get; set; } public int hits { get; set; } public int ishidden { get; set; } public DateTime date_accessed { get; set; } public DateTime date_stale { get; set; } public decimal average_hits { get; set; } public string history { get; set; } public decimal recent_average { get; set; } } public class LinkDB2 { public DateTime date_created { get; set; } public string history { get; set; } public string hits { get; set; } } public class LinkHistory { public int id { get; set; } public DateTime created { get; set; } public int user_id { get; set; } public int link_id { get; set; } } } <file_sep>/// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/mustache-0.7.d.ts" /> /// <reference path="../../global_js/routie.d.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="widgets.ts" /> /// <reference path="../../global_js/Things.ts" /> module App2 { export class starter { public static start() { $.when($.get("/tekphoria/2/templates.html")).then(resp=> { App.ViewEngine.parseTemplateHtml(resp) this.registerRoutes(); }) } static registerRoutes() { window.routie({ 'start': ()=> new htmlPages.homePage(), '/': ()=> new htmlPages.homePage(), '': ()=> new htmlPages.homePage() }); } } export module htmlPages { export class homePage { private setheader() { var model = new things.htmlPageModel(); $("title").html(model.title); $("meta[name=description]").attr("content", model.description); } constructor() { var person = new things.person("<NAME>", "/global_img/allan-brunskill.jpg", "<NAME>", "Softare Developer") var address = new things.address("93 Sylvan way", "Bristol", "United Kingdom", "BS9 2LY") var articles = [ new widgets.articleWidget(new things.article("Articel1", "something else", "I went shopping", "today")) , new widgets.articleWidget(new things.article("Articel2", "something else", "I went shopping", "today")) , new widgets.articleWidget(new things.article("Articel3", "something else", "I went shopping", "today")) ] var model = { person: new widgets.personWidget(person).toHtml(), address: new widgets.addressWidget(address).toHtml(), header: new widgets.headerWidget().toHtml(), footer: new widgets.footerWidget().toHtml(), articles: articles.map(a => a.toHtml()).join(""), logomain: new widgets.logoMainWidget().toHtml() } App.ViewEngine.renderview(App.ViewEngine.tmpl["mainpage"], model); this.setheader(); } } } }<file_sep>/// <reference path="App.GlobalCommon.ts" /> /// <reference path="linq-2.2.d.ts" /> /// <reference path="amplify.d.ts" /> /// <reference path='jquery-1.9.1.d.ts'/> /// <reference path="mustache-0.7.d.ts" /> module App { export class ViewCommon { public static FormInput(id: string, inputtype: string, label: string, classes: string, placeholder: string) { var tmp = '<div class = "control-group">' tmp += '<label class="control-label" for="' + id + '">' + label + '</label>' tmp += '<div class = "controls" >' tmp += '<input type="' + inputtype + '" id="' + id + '" class="' + classes + '" placeholder="' + placeholder + '"></input>' tmp += '</div>' tmp += '</div>' } } export class View { public static test() { return 1; } // utitlity public static getFormInputs(form: JQuery): any { var input = {}; form.find("input[type=text]").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('value'); }); form.find("input[type=password]").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('value'); }); form.find("input[type=hidden]").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('value'); }); form.find("textarea").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('value'); }); form.find("select").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("input[type=radio]:checked").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('value'); }); form.find("input[type=checkbox]").each((idx, item) => { var jitem = $(item); input[jitem.attr('name')] = jitem.attr('checked') === 'checked' ? 1 : 0; }); return input; } public static control(content) { return this.div("", "control-group", content) } public static upload(title: string) { var help = "<label class='control-label' for='file_upload'>{title}</label>".replace("{title}", title); var q = "<div class='controls'><div id='queue'></div>"; var in2 = '<input id="file_upload" name="file_upload" type="file" multiple="multiple"></input>' var click = "&nbsp;&nbsp;&nbsp;<a href=" + "javascript:$('#file_upload').uploadifive('upload')" + ">start</a></div>"; return this.control(help + q + in2 + click); } public static dropdown(title: string, id: string, nameof: string, data: any[], selectedvalue: string) { var help = "<label class='control-label' for='{id}'>{title}</label>".replace("{title}", title).replace("{id}", id); //var option = "<option value='{id}' {selected}>{valueof}</option>" var select = "<div class='controls'><select name='{nameof}' id='{id}'>{options}</select></div>".replace("{nameof}", nameof).replace("{id}", id) var selected = '', options = ''; options += "<option value='-1'>...</option>" Enumerable.From(data).ForEach((item) => { if (selectedvalue === item) { selected = 'selected'; } options += option.replace("{id}", item.id).replace("{valueof}", item.valueof).replace("{selected}", selected) }) return this.control(help + select.replace("{options}", options)) } // utitlity public static form(title: string, fields: string, buttonId?: string, formid?: string): string { var tmp = "<div class='span12'><form class='form-horizontal' id='{formid}'>{0}<fieldset>{fields}<div id='errors'/><hr><button id={buttonId} class='btn clearfix'>Submit</button></fieldset></form></div>" .replace("{0}", title) .replace("{fields}", fields) if (formid) { tmp = tmp.replace("{formid}", formid) } else { tmp = tmp.replace("{formid}", "form1") } if (buttonId) { tmp = tmp.replace("{buttonId}", buttonId); } else { tmp = tmp.replace("{buttonId}", "btnsubmit"); } return tmp; } public static input_data_string(nameof: string, label, prefix: string) { return this.inputstring(nameof, nameof, "{{" + prefix + "." + nameof + "}}", label, "text"); } public static datadiv(nameof: string, label: string, prefix: string) { var label = this.div(nameof, nameof + " span2 datalabel", label); var data = this.div(nameof, nameof + " span3 ", "<strong>{{" + prefix + "." + nameof + "}}</strong>") return this.div("", "row", label + data); } public static div(id: string, cssclass: string, content: string) { var tmp = "<div id='{id}' class='{class}'>{content}</div>" if (!cssclass) { cssclass = ''; } if (!id) { id = ''; } return tmp.replace('{id}', id).replace('{class}', cssclass).replace('{content}', content) } public static textarea(id: string, name: string, text: string, help: string, rows: string): string { var tmp = "<label class='control-label' for='{5}'>{3}</label>" tmp += "<div class='controls'>" tmp += "<textarea id='{0}' name={1} rows={4}>{2}</textarea>" tmp += "</div>" tmp = tmp.replace("{0}", id) .replace("{1}", name) .replace("{2}", text) .replace("{3}", help) .replace("{4}", rows); return this.control(tmp); } // utitlity public static inputstring(id: string, name: string, value: string, help: string, type: string): string { var tmp = "<label class='control-label' for='{5}'>{3}</label>" tmp += "<div class='controls'>" tmp += "<input type={4} id='{0}' name='{1}' value='{2}' maxlength=50 ></input>" tmp += "</div>" //"<div class='control-group'><div class='controls'><span class='control-label' for='{5}' >{3}</span><input type={4} id='{0}' placeholder='' name='{1}' value='{2}' maxlength=50 ></input></div></div>" tmp = tmp.replace("{0}", id) .replace("{1}", name) .replace("{2}", value) .replace("{3}", help) .replace("{4}", type) .replace("{5}", id) .replace("{6}", help) return this.control(tmp); } public static checkbox(id: string, name: string, help: string, selected: string) { var tmp = this.inputstring(id, name, '', help, "checkbox"); if (selected === '1') { tmp.replace("></input>", "checked></input>") } return tmp; } public static radio(name: string, value: string, text: string, wrapclass: string, selected: boolean): string { var tmp = "<label class='{3}'><input type='radio' name='{0}' value='{1}' {4}/> {2}</label>" .replace("{0}", name) .replace("{1}", value) .replace("{2}", text) .replace("{3}", wrapclass) .replace("{4}", selected ? "checked" : ""); return tmp; } // utitlity : applies error messages to their respective elements public static apply_validation(validationResponse: ValidationReponse, form: JQuery): void { $(".text-error, .alert").remove(); var first: JQuery; Enumerable.From(validationResponse.Errors).ForEach((v: ValidationError, idx) => { var el: JQuery = $("#" + v.PropertyName); if (idx === 0) first = el; el.fadeOut().fadeIn().before("<div class='text-error'>" + v.ErrorMessage + "</div>"); }); first.focus(); } public static Message(type: string, text: string): string { return "<div class='alert {0}'>{1}</div>".replace("{0}", type).replace("{1}", text); } } //export class ValidationReponse { // constructor( // public Errors: ValidationError[] = [], // public IsValid: boolean = false // ) { } //} //export class ValidationError { // constructor(public AttemptedValue: string, // public CustomState: any, // public ErrorMessage: string, // public PropertyName: string // ) { } //} }<file_sep>var App; (function (App) { var AppStarter = (function () { function AppStarter() { } AppStarter.start = function () { this.registerEvents(); this.registerRoutes(); }; AppStarter.registerRoutes = function () { window.routie({ '/prospect/:id/edit': function (id) { return App.View_EditProspect.init({ id: id }); }, '/prospect/:id/delete': function (id) { return App.View_DeleteProspect.init({ id: id }); }, '/prospects/:par1/:par2': function (par1, par2) { return App.View_Prospects.init({ par1: par1, par2: par2 }); }, '/prospects': function () { return App.View_Prospects.init({}); }, '/newprospect': function () { return App.View_NewProspect.init({}); }, '/': function (id) { return App.View_Prospects.init({}); }, '': function () { return App.View_Prospects.init({}); } }); }; AppStarter.registerEvents = function () { if (this.hasSetEvents === false) { var client = new App.ProspectorServerClient(); amplify.subscribe("UpdateProspectLocation", function (data) { return client.CallMethod("UpdateProspectLocation", data); }); amplify.subscribe("UpdateProspectLocation_reply", function () { return alert("Updated"); }); amplify.subscribe("UserLoggedIn", function (data) { $("#login-part").html(data); }); amplify.subscribe("UserLoggedOut", function (data) { $("#login-part").html(data); }); this.hasSetEvents = true; } }; AppStarter.hasSetEvents = false; return AppStarter; })(); App.AppStarter = AppStarter; })(App || (App = {})); <file_sep>/// <reference path="address.ts" /> //import address = require("address") //export class person { // public nameof: string; // public age: string; // public address: address.address; // public getDetails() { // return "hello " + this.address.city; // } //}<file_sep>var App; (function (App) { var days = (function () { function days() { } days.init = function () { }; days.getDaysContent = function () { var html = ""; var now = moment(); for (var i; i <= now.daysInMonth(); i++) { DIV({ class: "day" }); } now.daysInMonth(); return ""; }; return days; })(); App.days = days; var Header = (function () { function Header() { } Header.init = function () { }; return Header; })(); App.Header = Header; })(App || (App = {})); <file_sep>/// <reference path="../../global_js/App.GlobalCommon.ts" /> module App { export class ProspectorServerClient extends ServerClientBase { constructor() { super("prospector_server2.ashx") } } } <file_sep>using System; using System.IO; using System.Text; using System.Web.UI; namespace Tekphoria.Web.linkr { public partial class Xor : UserControl { public string TargetId { get; set; } public string TargetFileFullPathBeginingWithBackSlash { get; set; } protected void Page_Load(object sender, EventArgs e) { const string csname1 = "translator"; Type cstype = GetType(); ClientScriptManager cs = Page.ClientScript; if (!cs.IsStartupScriptRegistered(cstype, csname1)) { string jsFile = AppDomain.CurrentDomain.BaseDirectory + TargetFileFullPathBeginingWithBackSlash; var js = new StringBuilder(File.ReadAllText(jsFile)); js.Replace("xxxxx", TargetId); //var js = "function translate(input) { var res = ''; for (var i = 0; i < input.length; i++) { res += String.fromCharCode(1083756 ^ input.charCodeAt(i)); } return res;}"; //js += string.Format("var el = document.getElementById('{0}');el.value = translate(el.value)", TargetId); cs.RegisterStartupScript(cstype, csname1, string.Concat("<script type='text/javascript'>", js, "</script>")); } } private string getJs() { return "function translate(input) { var res = '';for (var i = 0; i < input.length; i++) {res += String.fromCharCode(1083756 ^ input.charCodeAt(i));"; } } } <file_sep>using System; using System.Diagnostics; using System.Net.Mail; using System.Web; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.Server.Handlers { public class EmailHandler : JsonServer, IHttpHandler { public dynamic SendMailTest(EmailArgs args) { try { using (var mailMessage = new MailMessage(Config.EmailAddress, new MailAddress(args.To))) using (var smtp = new SmtpClient(Config.EmailServer)) { mailMessage.Subject = args.Subject; mailMessage.Body = args.Body; mailMessage.IsBodyHtml = args.IsHtml; smtp.Credentials = Config.EmailCredentials; smtp.Send(mailMessage); } } catch (Exception ex) { Debug.Write(ex); } return new { exception = "none", message = "OK" }; } public new void ProcessRequest(HttpContext context) { try { base.ProcessRequest(context); } catch (Exception ex) { HandleError(ex); } } public bool IsReusable { get; private set; } } }<file_sep>/// <reference path="chess.ts" /> /// <reference path="../global_js/App.ViewEngine.ts" /> /// <reference path="../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../global_js/linq-2.2.d.ts" /> /// <reference path="../global_js/amplify.d.ts" /> /// <reference path='../global_js/jquery-1.9.1.d.ts'/> /// <reference path="../global_js/mustache-0.7.d.ts" /> module views { export class menu { public static getHtml() { var h = templates.menu; this.events() return h } static events() { $("body").on("click", "#allgames", e=> this.allgames_fired(e)) $("body").on("click","#newgame", e=> this.newgame_fired(e)) } static allgames_fired(e) { e.preventDefault() $(".main").first().html(games.getHtml()) } static newgame_fired(e) { e.preventDefault() $(".main").first().html(newgame.getHtml()) } } export class board { public static getHtml() { var html = App.ViewEngine.getHtml(templates.frame(), {}); return html; } } export class games { public static getHtml() { var client = new chess.ChessServerClient() var act = client.CallMethod("Games", {}) $.when(act).then(resp => { return App.ViewEngine.getHtml(templates.games(), resp) }) } } export class newgame { public static getHtml() { this.events() return App.ViewEngine.getHtml(templates.setupgame(), {}) } static events() { $("body").on("click", "#btnsubmit", e => { e.preventDefault() var client = new chess.ChessServerClient() var form = App.GlobalCommon.getFormInputs($("#form1")) var resp = client.CallMethod("NewGame", form); $.when(resp).then(resp => this.handleSetupResponse(resp)) }) } static handleSetupResponse(resp) { if (resp.result.IsValid === undefined) { var html = views.board.getHtml() $(".main").first().html(html); } else { App.GlobalCommon.apply_validation(resp.result, $("#form1")) } } } export class home { public render(data: any) { var html = App.ViewEngine.renderview( templates.frame(), { menu: menu.getHtml(), main: templates.main }) return html; } } export class templates { static frame(): string { return "" + "<div" + " <div class='top'><h1>TS Chess</h1>by <NAME></div>" + "</div>" + "<div>" + " <div class='menu cell'>{{&menu}}</div>" + " <div class='main cell'>{{&main}}</div>" + "</div>" } static menu(): string { return "" + "<h3>Menu</h3>" + "<input type='button' name=allgames id=allgames value='All Games' />" + "<br><br><br><input type='button' name=newgame id=newgame value='New Game' />" } static main(): string { return "" + "<h3>Main Game</h3>" } static board(): string { var tmp = "" tmp += "<div class=board>" var rownum = 0; var color = "white" Enumerable.Range(0, 8).ForEach(r=> { tmp += " <div class=boardrow>" if (r === 0 || r % 2 === 0) { color = "white" } else { color = "black" } Enumerable.Range(0, 8).ForEach(s=> { tmp += "<div id=square class='cell " + color + "'>row" + r + " cell" + s + "</div>" if (color === "black") { color = "white" } else { color = "black" } }) tmp += " </div>" }) return tmp; } static messages(): string { return "" + "<div>" + "<h3>Messages</div>" + "{{#messages}}{{>message}}{{/messages}}" + "</div>" } static message(): string { return "" + "<br>at {{time}}, {{name}} said '{{message}}'" } static setupgame() { var title = "<h3>New Game</h3>" var black = App.GlobalCommon.inputstring("blackplayer", "blackplayer", "", "The black players name", "text", "200") var white = App.GlobalCommon.inputstring("whiteplayer", "whiteplayer", "", "The white players name", "text", "200") return title + App.GlobalCommon.form("Enter the player names", black + white, "btnsubmit", "form1") } static game(): string { var tmp = "" tmp += "<div class=game>Game {{id}} between {{blackplayer}} and {{whiteplayer}}</div>" return tmp } static games():string { var tmp = "" tmp += "<h3>All Games<h3>" tmp += "{{#games}}" tmp += "{{>game}}" tmp += "{{/games}}" return tmp } } } <file_sep>/// <reference path="phaser.d.ts" /> module app { enum state { UNKNOWN, RUNNING, STOPPED } export class global { public static nameof: string = 'Tappit'; public static version: string = '0.1'; public static auther: string = 'x'; public static levelframes: number = 100; public static score: number = 0; public static level: number = 1; public static stateof: number = state.STOPPED; public static framerate: number = 1; public static board_data: any = [] public static rnd: number = 0; public static currentFrame: number = 0; public static font1 = { font: "40px Arial", fill: "#FFCC00", stroke: "#333", strokeThickness: 5, align: "center", } } export class mainMenuState { game : Phaser.Game = null; constructor() { var game = new Phaser.Game(320, 640, Phaser.AUTO, '', { preload: this.preload, create: this.create, update: this.update }); this.game = game; } preload() { } create() { } update() {} } export class tappit { game : Phaser.Game = null; constructor() { var game = new Phaser.Game(320, 640, Phaser.AUTO, '', { preload: this.preload, create: this.create, update: this.update }); this.game = game; } preload() { } create() { this.game.physics.startSystem(Phaser.Physics.ARCADE); this.game.physics.arcade.gravity.y = 200; this.game.add.text(10, 10, global.nameof + " " + global.version + ".\nBy " + global.auther + ".", global.font1); } update() {} } //export class game { //static start() { // var tappit = new app.tappit() //} //} }<file_sep>using System.Text.RegularExpressions; using FluentValidation; using Newtonsoft.Json.Linq; namespace Tekphoria.Web.Server.Prospect { public class EmptyValidator : AbstractValidator<JObject> { } public class AddProspectDetailValidator : AbstractValidator<JObject> { public AddProspectDetailValidator() { RuleFor(x => (string)x.GetValue("address1")).NotEmpty().WithName("address1").WithMessage("Address is required."); RuleFor(x => (string)x.GetValue("postcode")).NotEmpty().WithName("postcode").WithMessage("Postcode is required."); // RuleFor(x => (string)x.GetValue("postcode")).Must(CommonValidators.IsPostCode).WithName("postcode").WithMessage("Postcode is not in the correct format."); RuleFor(x => (int)x.GetValue("sale_type_id")).GreaterThan(0).WithName("sale_type_id").WithMessage("Sale type is required."); RuleFor(x => (int)x.GetValue("source_type_id")).GreaterThan(0).WithName("source_type_id").WithMessage("Source type is required."); RuleFor(x => (int)x.GetValue("price_low")).GreaterThan(-1).WithName("price_low").WithMessage("The low price is required."); RuleFor(x => (int)x.GetValue("price_high")).GreaterThan(-1).WithName("price_high").WithMessage("The high price is required."); RuleFor(x => (int)x.GetValue("price_high")).GreaterThanOrEqualTo(x => (int)x.GetValue("price_low")).WithName("price_high").WithMessage("The high price should be higher than the low price."); } } public class UpdateProspectValidator : AbstractValidator<JObject> { public UpdateProspectValidator() { RuleFor(x => (string)x.GetValue("latitude")).NotEmpty().WithName("latitude").WithMessage("Latitude is required."); RuleFor(x => (string)x.GetValue("longitude")).NotEmpty().WithName("longitude").WithMessage("Longitude is required."); } } public static class CommonValidators { public static bool IsPostCode(string code) { return Regex.IsMatch(code, "(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})"); } } } <file_sep>using System; using System.Collections.Generic; using System.Net; using System.Web; using Clarks.MCR.WebSite.Sitemaps; namespace Tekphoria.Web.Server.Sitemap { public static class SitemapData { private static string _host = new Uri(new UriBuilder("http", HttpContext.Current.Request.Url.Host).Uri.ToString()).ToString(); private const tChangeFreq CHANGE_FREQUENCY = tChangeFreq.daily; public static List<string> Items { get { var list = new List<string> { _host, _host + "tekphoria/allan-brunskill-cv.html" }; return list; } } } }<file_sep>/// <reference path="printerServerClient.ts" /> /// <reference path="../global_js/app.globalcommon.ts" /> /// <reference path="../global_js/jquery-1.9.1.d.ts" /> module tekphoria { export class printer { private submitButton: JQuery = $("#submitButton") private url: JQuery = $("#url") constructor() { var urlparms: any = App.GlobalCommon.getUrlParams(); if (urlparms.url) { this.url.val(urlparms.url) } } startPrinting(url: string) { } status(id: string) { } stop(): void { } } //(function poll() { // setTimeout(function () { // $.ajax({ // url: "printer_server.ashx", success: function (data) { // console.log("Polling") // }, dataType: "json", complete: poll // }); // }, 5000); //})(); }<file_sep>/// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> module App { export class ViewPart { public static info(title: string, message: string) { var info = App.GlobalCommon.div("info__", "alert alert-success", "<strong>" + title + "</strong>"+ "<br>" + message); $("#info__").fadeOut().remove(); $("#app").prepend(info).hide().fadeIn(); return info; } public static info_hide() { $("#info__").remove(); } } }<file_sep>/// <reference path="app.ts" /> require.config({ stache: { path: '/linkr/templates/' }, paths: { //plugin : '/global_js/require-plugins/', jquery: '/global_js/jquery-1.9.1', app: '/linkr/app', mustache: '/global_js/moustache', text: '/global_js/require-plugins/text', stache: '/global_js/require-plugins/stache' } //baseUrl: '/linkr', //paths: { // // app // app: '/linkr/app', // //main libraries // routie: '/global_js/routie', // jquery: '/global_js/jquery-1.9.1', // moustache: '/global_js/moustache.js', // //shortcut paths // templates: '/tmpl', // data: '/data', // global: '/global_js/', // //require plugins // text: '/global_js/require-plugins/text', // domReady: '/global_js/require-plugins/domReady', // json: '/global_js/require-plugins/json', // hgn: '/global_js/require-plugins/hgn', // hogan: '/global_js/require-plugins/hogan', // stache: { path: '/templates/'} //}, }); requirejs(["jquery", "mustache", "app"], (jquery, app) => { this.app.starter.start(); });<file_sep>using System; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Reflection; using System.Web; using Tekphoria.Web.Server.Common.Routing; using Tekphoria.Web.Server.Scrumbo; namespace Tekphoria.Web { public class Global : HttpApplication { private static Router router; protected void Application_Start(Object sender, EventArgs e) { if (!HttpRuntime.UsingIntegratedPipeline) { throw new ApplicationException( "This application is not using integrated mode. Please change to an App Pool that uses integrated mode."); } string userfiles = AppDomain.CurrentDomain.BaseDirectory + "\\userfiles\\shared"; if (!Directory.Exists(userfiles)) Directory.CreateDirectory(userfiles); var setup = new ScrumboServerSetup(); setup.Run(); router = new Router(); router.Add(new RouteInfo("about", () => GetFile("/tekphoria/about.aspx", getAboutPage()))); router.Add(new RouteInfo("contact", () => GetFile("/tekphoria/contact.aspx"))); router.Add(new RouteInfo("services", () => GetFile("/tekphoria/services.aspx"))); router.Add(new RouteInfo("experience", () => GetFile("/tekphoria/experience.aspx"))); router.Add(new RouteInfo("projects", () => GetFile("/tekphoria/projects.aspx"))); router.Add(new RouteInfo("blog", () => GetFile("/tekphoria/blog.aspx"))); router.Add(new RouteInfo("today", () => GetFile("/tekphoria/today.aspx", new { city = "bristol", colors = new List<string> { "yello", "greeeen", "blu" } }))); router.Add(new RouteInfo("home", () => GetFile("/tekphoria/2/index.aspx"))); router.Add(new RouteInfo("linkr/links", () => GetFile("/linkr/Links.aspx"))); router.Add(new RouteInfo("linkr/links/all", () => GetFile("/linkr/AllLinks.aspx"))); router.Add(new RouteInfo("linkr/new", () => GetFile("/linkr/NewLink.aspx"))); router.Add(new RouteInfo("linkr/edit", () => GetFile("/linkr/EditLink.aspx"))); router.Add(new RouteInfo("linkr/delete", () => GetFile("/linkr/DeleteLink.aspx"))); router.Add(new RouteInfo("linkr", () => GetFile("/linkr/default.aspx"))); router.Add(new RouteInfo("linkr/goto", () => GetFile("/linkr/Goto.aspx"))); router.Add(new RouteInfo("login", () => GetFile("/account/Login.aspx"))); router.Add(new RouteInfo("logout", () => GetFile("/account/Logout.aspx"))); router.Add(new RouteInfo("account/new", () => GetFile("/account/CreateAccount.aspx"))); router.Add(new RouteInfo("account/verify", () => GetFile("/account/Verify.aspx"))); router.Add(new RouteInfo("account/changepwd", () => GetFile("/account/ChangePassword.aspx"))); router.Add(new RouteInfo("account", () => GetFile("/account/Index.aspx"))); } private dynamic getHomePage() { return new PageModel { Title = "Home Page", BreadCrumbs = new List<string> { "Home" } }; } private object getAboutPage() { return new PageModel { Title = "About", BreadCrumbs = new List<string> { "Home", "About" } }; } private void GetFile(string virtualpath, object data = null) { if (!virtualpath.EndsWith("aspx")) GetStaticFile(virtualpath); else { HttpContext ctx = HttpContext.Current; var viewdata = new ExpandoObject() as IDictionary<string, object>; if (data != null) { foreach (PropertyInfo propertyInfo in data.GetType().GetProperties()) viewdata.Add(propertyInfo.Name, propertyInfo.GetValue(data, null)); } ctx.Items["data"] = viewdata; ctx.Server.Transfer(virtualpath); ctx.Response.Flush(); } } private void GetStaticFile(string virtualpath) { HttpContext ctx = HttpContext.Current; //var path = ctx.Server.MapPath(virtualpath); //var content = File.ReadAllText(path); //ctx.Response.Write(content); ctx.Response.Write(File.ReadAllText(ctx.Server.MapPath(virtualpath))); ctx.Response.Flush(); } private void Application_BeginRequest(object sender, EventArgs e) { string path = HttpContext.Current.Request.Url.AbsolutePath; if (path.IndexOf("404", StringComparison.Ordinal) != -1) return; if (path.IndexOf("500", StringComparison.Ordinal) != -1) return; IRouteInfo route = router.FindRoute(HttpContext.Current.Request.Url.AbsolutePath); if (route != null) route.Execute(); } public class PageModel { public string Title { get; set; } public List<string> BreadCrumbs { get; set; } public string Content { get; set; } } } }<file_sep>/// <reference path="../../global_js/linq-2.2.d.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/keyboardjs.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> var App; (function (App) { var invoice = (function () { function invoice() { } invoice.init = function () { var _this = this; var inputs = amplify.store("invoice_inputs"); var items = amplify.store("invoice_items"); if (inputs) { for (var propertyName in inputs) { $("[name=" + propertyName + "]").first().val(inputs[propertyName]); } } if (items) { $(".invoiceitems").first().html(items); } $("#inputitemqty").off("keydown").on("keydown", function (e) { if (_this.isDeleteOrBackSpace(e)) { return true; } if ((e.keyCode < 48 || e.keyCode > 57)) { return false; } }); $("#inputincvat").off("keyup").on("keyup", function () { var inc = $("#inputincvat").val(); var rate = $("#inputvatrate").val(); var divder = 1 + (+rate / 100); var excl = +inc / divder; $("#inputexcvat").val(accounting.formatNumber(excl, 2)); }); $("#inputitemprice").off("keydown").on("keydown", function (e) { if (_this.isDeleteOrBackSpace(e)) { return true; } var val = "" + $(e.target).val(); if (_this.isFullStop(e)) { if (_this.hasFullStop(val)) { return false; } else { return true; } } var chars = val.split("."); if (chars.length <= 1) { } else { if (chars.length === 2 && chars[1].length < 2) { } else { return false; } } if (_this.isNotNumberKey(e)) { return false; } }); $("body").on("click", ".removeItem", function (e) { e.preventDefault(); var row = $(e.target).closest("tr").remove(); _this.recalculate(); }); $("#additem").off("click").on("click", function (e) { return _this.addInvoiceItem(); }); $("#generate-button").off("click").on("click", function (e) { e.preventDefault(); _this.recalculate(); }); KeyboardJS.on('ctrl > s', function (e) { e.preventDefault(); _this.recalculate(); _this.processInputs(); }); KeyboardJS.on('ctrl > f', function (e) { e.preventDefault(); var form = $("#input-form"); if (form.is(':visible')) { form.hide(); } else { form.show(); } }); KeyboardJS.on('ctrl > p', function (e) { e.preventDefault(); $("#input-form").hide(); $("#input-items").hide(); $("#email").hide(); $(".removeItem").hide(); window.print(); }); $("#invoicedate").text(moment().format("DD MMMM YYYY")); this.processInputs(); }; invoice.isNotNumberKey = function (e) { if ((e.keyCode < 48 || e.keyCode > 57)) { return true; } }; invoice.hasFullStop = function (val) { return val.indexOf(".") !== -1; }; invoice.isFullStop = function (e) { return e.keyCode === 190; }; invoice.isDeleteOrBackSpace = function (e) { return e.keyCode === 8 || e.keyCode === 46; }; invoice.addInvoiceItem = function () { var inputs = App.GlobalCommon.getFormInputs($("body")); var tmpl = $("#itemrowtemplate"); if ($(".invoiceitems .invoiceitem").length === 0) { $(".invoiceitems tr").first().before(tmpl.html()); } else { $(".invoiceitems .invoiceitem").last().after(tmpl.html()); } $(".itemdesc").last().text(inputs.inputitemdesc.toLocaleUpperCase()); $(".itemqty").last().text(inputs.inputitemqty); $(".itemprice").last().text(accounting.formatNumber(inputs.inputitemprice, 2)); this.recalculate(); }; invoice.recalculate = function () { var inputs = App.GlobalCommon.getFormInputs($("body")); var invoiceItems = $(".invoiceitem"); var summary = { net: 0, vatrate: inputs.inputvatrate / 100 }; Enumerable.From(invoiceItems).ForEach(function (row) { var row = $(row); var qty = row.find(".itemqty").text(); var price = row.find(".itemprice").text(); var total = +qty * +price; row.find(".itemtotal").text(accounting.formatNumber(total, 2)); summary.net += total; }); $("#nettotal").text(accounting.formatNumber(summary.net, 2)); $("#vat").text(accounting.formatNumber(summary.net * summary.vatrate, 2)); $("#payable").text(accounting.formatMoney(summary.net + (summary.net * summary.vatrate), "£")); }; invoice.getLastMonthDate = function () { var date = moment().subtract('months', 1).calendar(); return moment(date).format("MMM YYYY"); }; invoice.getReference = function (companycode, counter) { //Invoice-WESTEK1108-01.odt return "Invoice-" + companycode + moment().format("YYMM") + "-" + counter; }; invoice.processInputs = function () { var inputs = App.GlobalCommon.getFormInputs($("body")); amplify.store("invoice_inputs", inputs); amplify.store("invoice_items", $(".invoiceitems").html()); // calculate var results = {}; // format results.address = inputs.inputaddress; results.reference = this.getReference(inputs.inputcompanycode, inputs.inputcounter); for (var propertyName in results) { var txt = results[propertyName]; $("#" + propertyName).text(txt); $("#address").html(App.GlobalCommon.uiify(results.address).toLocaleUpperCase()); } // make sure it has stuff in it var required = $("body").find("[data-required=true]"); $.each(required, function (x, item) { var frag = $(item); var text = frag.text(); if (!text.length) { alert("Error: " + frag.attr("id")); } }); $("title").text(results.reference); $("body").fadeIn().fadeOut().fadeIn(); }; invoice.accounting = window["accounting"]; return invoice; })(); App.invoice = invoice; })(App || (App = {})); <file_sep>using System; using System.Drawing; using System.IO; using System.Web; using ImageResizer; namespace Tekphoria.Web.Server.Handlers { public class UploadHandler3 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; if (context.Request.Files.Count == 0) { context.Response.Write("Waiting for file."); } else { try { HttpPostedFile file = context.Request.Files[0]; var path = AppDomain.CurrentDomain.BaseDirectory + "\\userfiles\\" + file.FileName; if(File.Exists(path)) File.Delete(path); Bitmap b = ImageBuilder.Current.Build( file.InputStream, new ResizeSettings { MaxHeight = 1024, MaxWidth = 1024 }); b.Save(path); context.Response.Write("OK"); } catch (Exception ex) { context.Response.Write(ex); } } context.Response.End(); } public bool IsReusable { get { return false; } } } }<file_sep>using System; using FluentAssertions; using NUnit.Framework; using Tekphoria.Web.Server.Common.Routing; namespace Tests.Routing { [TestFixture] public class RouterTests { [TestCase("games/kids", "games/kids", 1)] [TestCase("/books/1", "books/{id}", 1)] [TestCase("/books/1/author/2", "books/{id}/author/{authorid}", 3)] [TestCase("/books/1/author", "books/{id}/author/{authorid}", 2)] [TestCase("/stuff/9/10", "stuff/{a}/{b}", 19)] [TestCase("/say", "say/{?words}", "I said hello there")] [TestCase("/say/blerg", "say/{?words}", "I said blerg")] [TestCase("/about", "about", "void")] public void MatchRoute(string incoming, string matched, object result) { var router = new Router(); router.Add(new RouteInfo("/say/{?words}", SayWords, new { words = "hello there" })); router.Add(new RouteInfo("/games/kids", args => 1)); router.Add(new RouteInfo("/books/{id}/author/{authorid}", args => args.id + args.authorid, new {authorid = 1})); router.Add(new RouteInfo("/books/{id}", args => args.id)); router.Add(new RouteInfo("/stuff/{a}/{b}", GetListOfStuff)); router.Add(new RouteInfo("/about", () => Console.WriteLine("hello"))); IRouteInfo route = router.FindRoute(incoming); route.Template.Should().Be(matched); var answer = route.Execute(); Assert.IsTrue(answer.ToString() == result.ToString()); } public dynamic SayWords(dynamic args) { var result = "I said " + (string) args.words; return result; } public dynamic GetListOfStuff(dynamic args) { var result = (int) args.a + (int) args.b; return result; } [TestCase("/{test}/say/something","saysomething")] public void CleanUrl(string url,string expected) { url.CleanForComparision().Should().Be(expected); } public void can_use_Action() { } } }<file_sep>///// <reference path="../../global_js/linq-2.2.d.ts" /> ///// <reference path="../../global_js/jquery-1.9.1.d.ts" /> //declare module WB { ///* //========================================================================================= //*/ // export class Config { // public static RootPath: string = "/node/app2"; // public static AppName: string = "Application 2"; // public static AppEl: JQuery = $("#app"); // public static ToolBarEl: JQuery = $("#toolbar_buttons"); // } ///* //========================================================================================= //*/ // export class Common { // public static getnewGuid(): string { // return UUID.create(12, 36); // } // // utitlity // public static getFormInputs(form: JQuery): any { // var input = {}; // form.find("input[type=text]").each((idx, item) => { // var jitem = $(item); // input[jitem.attr('name')] = jitem.attr('value'); // }); // form.find("input[type=password]").each((idx, item) => { // var jitem = $(item); // input[jitem.attr('name')] = jitem.attr('value'); // }); // form.find("input[type=hidden]").each((idx, item) => { // var jitem = $(item); // input[jitem.attr('name')] = jitem.attr('value'); // }); // form.find("textarea").each((idx, item) => { // var jitem = $(item); // input[jitem.attr('name')] = jitem.attr('value'); // }); // form.find("input[type=radio]:checked").each((idx, item) => { // var jitem = $(item); // input[jitem.attr('name')] = jitem.attr('value'); // }); // return input; // } // // utitlity // // utitlity // public static form(title: string, fields: string, buttonId? : string, formid? : string): string { // var tmp = "<div class='well span4'><form id='{formid}'><strong>{0}</strong><br><br><fieldset>{fields}<div id='errors'/><hr><button id={buttonId} class='btn clearfix'>Submit</button></fieldset></form></div>" // .replace("{0}", title) // .replace("{fields}", fields) // if (formid) { // tmp = tmp.replace("{formid}", formid) // } // else { // tmp = tmp.replace("{formid}", "form1") // } // if (buttonId) { // tmp = tmp.replace("{buttonId}", buttonId); // } // else { // tmp = tmp.replace("{buttonId}", "btnsubmit"); // } // return tmp; // } // public static textarea(id: string, name: string, text: string, help: string, rows: string) :string { // return "<span class='help-block'>{3}</span><textarea id='{0}' name={1} rows={4}>{2}</textarea>" // .replace("{0}",id) // .replace("{1}",name) // .replace("{2}",text) // .replace("{3}",help) // .replace("{4}",rows); // } // // utitlity // public static inputstring(id: string, name: string, value: string, help: string, type: string): string { // var tmp = // "<span class='help-block'>{3}</span><input type={4} id='{0}' name='{1}' value='{2}' maxlength=50 ></input>" // .replace("{0}", id) // .replace("{1}", name) // .replace("{2}", value) // .replace("{3}", help) // .replace("{4}", type) // return tmp; // } // public static radio(name: string, value: string, text: string, wrapclass: string, selected: boolean): string { // var tmp = "<label class='{3}'><input type='radio' name='{0}' value='{1}' {4}/> {2}</label>" // .replace("{0}", name) // .replace("{1}", value) // .replace("{2}", text) // .replace("{3}", wrapclass) // .replace("{4}", selected ? "checked" : ""); // return tmp; // } // // utitlity : applies error messages to their respective elements // public static apply_validation(validationResponse: ValidationReponse, form: JQuery): void { // $(".text-error, .alert").remove(); // var first: JQuery; // Enumerable.From(validationResponse.Errors).Reverse().ForEach((v: ValidationError, idx) => { // var el : JQuery = $("#" + v.PropertyName); // if (idx === 0) first = el; // el.fadeOut().fadeIn().after("<div class='text-error'>" + v.ErrorMessage + "</div>"); // }); // first.focus(); // } // public static Message(type: string, text: string): string { // return "<div class='alert {0}'>{1}</div>".replace("{0}", type).replace("{1}", text); // } // // Takes an ISO time and returns a string representing how // // long ago the date represents. // public static prettyDate(time) { // var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")), // diff = (((new Date()).getTime() - date.getTime()) / 1000), // day_diff = Math.floor(diff / 86400); // if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) // return "just now"; // var res = day_diff == 0 && ( // diff < 60 && "just now" || // diff < 120 && "1 minute ago" || // diff < 3600 && Math.floor(diff / 60) + " minutes ago" || // diff < 7200 && "1 hour ago" || // diff < 86400 && Math.floor(diff / 3600) + " hours ago") || // day_diff == 1 && "Yesterday" || // day_diff < 7 && day_diff + " days ago" || // day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago"; // return res; // } // public static truncate(input: string, n: number) { // var res = input.substr(0, n - 1) + (input.length > n ? '...' : ''); // return res; // } // public static uiify(input: string) { // var res = input; // //res = res.replace(/(\r\n|\n|\r)/gm, '<br>') // //res = res.replace(/(http:\/\/[^\s]+)/gi, (match) => { // // return '<a href="' + match + '">' + this.truncate(match, 40) + '</a>' ; // //}) // return res; // } // } // export class ValidationReponse { // constructor( // public Errors: ValidationError[] = [], // public IsValid: boolean = false // ) { } // } // export class ValidationError { // constructor(public AttemptedValue: string, // public CustomState: any, // public ErrorMessage: string, // public PropertyName: string // ) { } // } // export class Event { // constructor(public sender: any, public payload: any) { } // } // export class StorageConstants { // public static Boardlabel: string = "BOARD-{0}"; // public static TaskLabel: string = "TASK-{0}"; // public static Storylabel: string = "STORY-{0}"; // public static Userlabel: string = "USER-{0}"; // public static Boards: string = "BOARDS"; // } // export class Status { // public static Preparing: number = 1; // public static Todo: number = 2; // public static Done: number = 3; // public static InProgress: number = 4; // public static Blocked: number = 5; // } // //http://www.broofa.com/Tools/Math.uuid.js // export class UUID { // private static Chars: string[] = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ'.split(''); // public static create(len: number, radix: number): string { // var chars = this.Chars, uuid = [], i; // radix = radix || chars.length; // if (len) { // // Compact form // for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]; // } else { // // rfc4122, version 4 form // var r; // // rfc4122 requires these characters // uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; // uuid[14] = '4'; // // Fill in random data. At i==19 set the high bits of clock sequence as // // per rfc4122, sec. 4.1.5 // for (i = 0; i < 36; i++) { // if (!uuid[i]) { // r = 0 | Math.random() * 16; // uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; // } // } // } // return uuid.join(''); // } // } //}<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using Dapper; using FluentValidation; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Web.linkr; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.Server.Linkr { public class LinkrServer : JsonServer, IHttpHandler { //private readonly Lazy<IDbConnection> ScrumboDb = new Lazy<IDbConnection>(() => GetOpenConnection(Config.GetScrumboConnectionString.Value)); private readonly IDbConnection _scrumboDbConnection; public new void ProcessRequest(HttpContext context) { try { base.ProcessRequest(context); } catch (Exception ex) { HandleError(ex); } finally { CloseConnection(_scrumboDbConnection); } } private IDbConnection GetScrumboConnection() { if (_scrumboDbConnection == null || _scrumboDbConnection.State != ConnectionState.Open) CloseConnection(_scrumboDbConnection); return GetOpenConnection(Config.GetScrumboConnectionString.Value); } public void CloseConnections() { CloseConnection(_scrumboDbConnection); } //public dynamic GetLinks(dynamic data) //{ // string sql = // "select id,LEFT(textof,10),href,date_created,date_accessed,hits,GREATEST(recent_average, average_hits) from links where isHidden=@showhidden and user_id=@user_id;"; // dynamic links = GetScrumboConnection().Query(sql, new // { // data.user_id // }); // return new // { // links // }; //} public dynamic GetLink(dynamic data) { const string sql = "select id,textof,descof,href,date_created,date_accessed,hits,ishidden from links where id=@id and user_id=@user_id;"; dynamic link = GetScrumboConnection().Query(sql, new { data.id, data.user_id }).FirstOrDefault(); return new { link }; } public dynamic UpdateLinkDetail(dynamic data) { var validator = new UpdateLinkValidator(); ValidationResult result = validator.Validate(data); if (result.IsValid) { const string sql = "update links set href=@href,textof=@textof,descof=@descof,ishidden=@ishidden,hits=@hits where id=@link_id and user_id=@user_id;"; bool ishidden = data.ishidden; GetScrumboConnection().Execute(sql, new { data.href, data.textof, data.descof, data.link_id, data.user_id, data.hits, ishidden }); } return new { result }; } public dynamic InsertLink(dynamic data) { var validator = new InsertLinkValidator(); ValidationResult result = validator.Validate(data); if (result.IsValid) { const string sql = "insert into links (date_accessed,date_created,href,textof,descof,user_id,date_stale,average_hits,ishidden) values (date_add(UTC_TIMESTAMP(), INTERVAL -1 DAY),date_add(UTC_TIMESTAMP(), INTERVAL -1 DAY),@href,@textof,@descof,@user_id,date_add(UTC_TIMESTAMP(), INTERVAL 90 DAY),1,@ishidden);"; bool ishidden = data.ishidden; GetScrumboConnection().Execute(sql, new { data.href, data.textof, data.descof, data.user_id, ishidden }); } return new { result }; } public void Increment(dynamic data) { LinkDB link = GetScrumboConnection() .Query<LinkDB>("select user_id,hits,date_created from links where id = @id", new { data.id }) .FirstOrDefault(); var recent_days = 90; decimal linkHistoryCount = GetScrumboConnection() .Query( "select count(id) as countof from link_history where date_created > DATE_SUB(UTC_TIMESTAMP(), INTERVAL @days DAY) and link_id = @id", new { data.id, days = recent_days }) .First().countof; if (link != null) { decimal recent_average = linkHistoryCount == 0 ? 1 : linkHistoryCount / recent_days; decimal createdForDays = (DateTime.UtcNow - link.date_created).Days; decimal average_hits = link.hits/createdForDays; var linksSql = "update links set hits = hits + 1, date_accessed=UTC_TIMESTAMP(), date_stale=DATE_ADD(UTC_TIMESTAMP(), INTERVAL @recent_days DAY), history='-',average_hits=@average_hits, recent_average=@recent_average where id=@id;"; GetScrumboConnection().Execute( linksSql, new { data.id, recent_average, recent_days, average_hits }); GetScrumboConnection().Execute( "insert into link_history (date_created, user_id, link_id) values (UTC_TIMESTAMP(),@user_id, @id);", new { data.id, link.user_id }); } } public void Increment_obselete(dynamic data) { LinkDB q1 = GetScrumboConnection() .Query<LinkDB>("select hits,date_created,history from links where id = @id", new { data.id }) .FirstOrDefault(); if (q1 != null) { const int storedhistory_days_capacity = 53; const decimal recentdays = 10m; var recent_average = 0m; var date_stale = DateTime.UtcNow.AddDays(90); var history = string.Empty; // get history q1.history = q1.history ?? string.Empty; var list = new Queue<string>(q1.history.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); var createdDaysago = (decimal)DateTime.UtcNow.Subtract(q1.date_created).TotalDays; list.Enqueue(Math.Ceiling(createdDaysago).ToString("0")); history = list.Count > storedhistory_days_capacity ? String.Join(",", list.Skip(1).Take(storedhistory_days_capacity)) : String.Join(",", list); decimal recentLower = createdDaysago - recentdays; int inrangeCount = list.Select(s => Convert.ToInt32(s)).Count(s => s >= recentLower); if (inrangeCount > 0) recent_average = inrangeCount / recentdays; var updateRow = new LinkDB { id = Convert.ToInt32(data.id), history = history, recent_average = recent_average, date_stale = date_stale, average_hits = q1.hits / createdDaysago }; GetScrumboConnection() .Execute( "update links set hits = hits + 1, date_accessed=UTC_TIMESTAMP(), date_stale=@date_stale, average_hits=@average_hits, history=@history, recent_average=@recent_average where id=@id;", updateRow); } } public IEnumerable<LinkDB> GetLinks(string user_id, bool ishidden) { string sql = "select id,textof,href,date_created,date_accessed,date_stale,hits,TRUNCATE(GREATEST(average_hits, recent_average),2) as average_hits from links where isHidden=@ishidden and user_id=@user_id and id <> 37;"; return GetScrumboConnection().Query<LinkDB>(sql, new { user_id, ishidden }); } public IEnumerable<LinkDB> GetLinks_obselete(string user_id, bool ishidden) { string sql = "select id,textof,href,date_created,date_accessed,date_stale,hits,TRUNCATE(GREATEST(average_hits, recent_average),2) as average_hits from links where isHidden=@ishidden and user_id=@user_id and id <> 37;"; return GetScrumboConnection().Query<LinkDB>(sql, new { user_id, ishidden }); } public void DeleteLink(dynamic data) { GetScrumboConnection() .Execute( "delete from links where id=@id and user_id=@user_id;", new { data.id, data.user_id }); } public class InsertLinkValidator : AbstractValidator<JObject> { public InsertLinkValidator() { RuleFor(x => x.GetValue("href").ToString()) .Length(2, 256) .WithMessage("Link address is not valid.") .WithName("href"); RuleFor(x => x.GetValue("textof").ToString()) .Length(2, 100) .WithMessage("Title text is not valid.") .WithName("textof"); } } public class UpdateLinkValidator : InsertLinkValidator { } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Authentication; using System.Text; using System.Threading; using System.Web; using Dapper; using FluentValidation; using ImageResizer.Caching; using MySql.Data.MySqlClient; using Newtonsoft.Json; namespace Tekphoria.Web.Server.Common { public abstract class JsonServer : IHttpHandler { public bool IsReusable { get { return false; } } public string Translate(string input) { int key = 1083756; var inSb = new StringBuilder(input); var outSb = new StringBuilder(input.Length); char c; for (int i = 0; i < input.Length; i++) { c = inSb[i]; c = (char) (c ^ key); outSb.Append(c); } return outSb.ToString(); } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; context.Response.ContentEncoding = Encoding.UTF8; try { Authorise(context); } catch (Exception) { var resp = new { code = 401 }; context.Response.Write(JsonConvert.SerializeObject(resp)); return; } string body; using (TextReader reader = new StreamReader(context.Request.InputStream, Encoding.UTF8)) body = reader.ReadToEnd(); //body = Translate(body); if (string.IsNullOrWhiteSpace(body)) throw new DataException("Payload is empty."); var payload = JsonConvert.DeserializeObject<Payload2>(body); string user_id = context.Request.Headers["UserId"] ?? "0"; HttpContext.Current.Items["UserId"] = user_id; payload.Data.user_id = user_id; MethodInfo methodInfo = GetType().GetMethod(payload.MethodName); object[] attributes = methodInfo.GetCustomAttributes(typeof (ValidationAttribute), false); if (attributes.Length > 0) { var validationAttribute = attributes[0] as ValidationAttribute; } ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure; object result = methodInfo.Invoke(this, new object[] {payload.Data}); //context.Response.Write(Translate(JsonConvert.SerializeObject(result))); context.Response.Write(JsonConvert.SerializeObject(result)); } public void SetCookie(string name, string value) { var ck = new HttpCookie(name, value); ck.Expires = DateTime.Now.AddDays(30); HttpContext.Current.Response.Cookies.Add(ck); } public string GetCookieValue(HttpContext ctx, string name) { if (string.IsNullOrWhiteSpace(name)) return null; HttpCookie ck = ctx.Request.Cookies[name]; if (ck == null || string.IsNullOrWhiteSpace(ck.Value)) return null; return ck.Value; } public void Authorise(HttpContext ctx) { IDbConnection commonDbConnection = null; try { string ticket = GetCookieOrHeader(ctx, "Auth"); if (string.IsNullOrWhiteSpace(ticket)) { throw new AuthenticationException("Ticket is invalid"); } string user_id = GetCookieOrHeader(ctx, "UserId") ?? "0"; commonDbConnection = GetOpenConnection(Config.GetCommonDbConnectionString.Value); List<dynamic> res = commonDbConnection.Query( "SELECT access_id FROM tickets INNER JOIN users ON users.id = tickets.user_id WHERE tickets.access_id = @access_id AND tickets.date_expires > UTC_TIMESTAMP() LIMIT 1", new {access_id = ticket, user_id, nowutc = DateTime.UtcNow}).ToList(); if (!res.Any()) throw new AuthenticationException("Ticket is not found"); } catch (Exception ex) { throw; } finally { CloseConnection(commonDbConnection); } } public string GetHeaderValue(HttpContext ctx, string name) { var headers = ctx.Request.Headers; var val = headers.AllKeys.FirstOrDefault(x => x == name); if (!string.IsNullOrWhiteSpace(val)) return headers[name].Trim(); return null; } private string GetCookieOrHeader(HttpContext ctx, string name) { return GetHeaderValue(ctx, name) ?? GetCookieValue(ctx, name); } public static void HandleError(Exception ex) { HttpContext.Current.Response.StatusCode = 500; dynamic error = new { error = GetException(ex).Message }; HttpContext.Current.Response.Write(JsonConvert.SerializeObject(error)); } private static Exception GetException(Exception ex) { if (ex != null && ex.InnerException != null) return ex.InnerException; return ex; } private static string GetInnerExceptionMessage(Exception ex) { return string.Empty; string result = string.Empty; if (ex != null && ex.InnerException != null) { if (!string.IsNullOrWhiteSpace(ex.InnerException.Message)) { result = ex.InnerException.Message; } } return result; } public static IDbConnection GetOpenConnection(string connectionString) { IDbConnection dbConnection = new MySqlConnection(connectionString); dbConnection.Open(); return dbConnection; } public static void CloseConnection(IDbConnection con) { if (con != null) { con.Close(); con.Dispose(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Web; using Dapper; using FluentValidation; using Tekphoria.Web.Server.Account; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.locate { public class Locate : JsonServer, IHttpHandler { private IDbConnection _scrumboConnection; private HttpRequest req; public new void ProcessRequest(HttpContext context) { req = context.Request; if (req.HttpMethod == "GET") ProcessGet(context); if (req.HttpMethod == "POST") base.ProcessRequest(context); } private void ProcessGet(HttpContext context) { try { _scrumboConnection = GetOpenConnection(Config.GetScrumboConnectionString.Value); string user_id = req["u"] ?? ""; string lat = req["l"] ?? ""; string lng = req["n"] ?? ""; var args = new LocationArgs { user_id = user_id, lat = lat, lng = lng }; var validator = new LocationArgsValidatior(); validator.ValidateAndThrow(args); List<dynamic> res = _scrumboConnection.Query("select 1 from location where user_id=@user_id;", args).ToList(); _scrumboConnection.Execute( res.Any() ? "update location set lat=@lat,lng=@lng,date_modified=UTC_TIMESTAMP() where user_id=@user_id;" : "insert into location (user_id,lat,lng,date_created) values (@user_id,@lat,@lng,UTC_TIMESTAMP());", args); } finally { CloseConnection(_scrumboConnection); } } public dynamic GetLocations(dynamic data) { try { AccountServer accountServer = new AccountServer(); var user = accountServer.GetVerifiedUserById(data); _scrumboConnection = GetOpenConnection(Config.GetScrumboConnectionString.Value); List<dynamic> res = _scrumboConnection.Query( "SELECT lat,lng FROM location where user_id=@user_id;", new { data.user_id}) .ToList(); return new { locs = res, user, }; } catch (Exception ex) { Debug.Write(ex); throw; } finally { CloseConnection(_scrumboConnection); } } public new bool IsReusable { get { return false; } } } } <file_sep>/// <reference path="../../global_js/App.ViewEngine.ts" /> module WB { export class Error { constructor(public title: string, public message: string, public exception: any) { } } export class ErrorController{ public static Show(error: Error){ ErrorView.render(error); } } export class ErrorView { public static render(error: Error) : void { var munge = this.getErrorView(error.title, error.message) $("#errors").html(munge) } static getErrorView(title: string, message: string) { var tmp = this.getTemplate(); return tmp .replace('{0}', title) .replace('{1}', message) } static getTemplate(){ return "<div class=row><div class='span4 alert alert-error'><strong>{0}</strong> {1}</div></div>" } } }<file_sep>/// <reference path="../../global_js/moment.d.ts" /> /// <reference path="../../account/Account.ts" /> /// <reference path="../../global_js/App.ViewEngine.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/amplify.d.ts" /> /// <reference path="../../global_js/keyboardjs.d.ts" /> /// <reference path="../../global_js/App.GlobalCommon.ts" /> /// <reference path="../../global_js/jquery-1.9.1.d.ts" /> /// <reference path="../../global_js/moment.d.ts" /> module App { export class account_server_client extends App.ServerClientBase { constructor() { super("account_server.ashx") } } export class ledger { private Accounting: any = window["accounting"]; public init() { var client = new account_server_client(); var act = client.CallMethod("GetAccountsList", {}) $.when(act).then(resp => this.render(resp)); } private render(resp) { App.ViewEngine.renderview(this.getTemplate(resp), {}) $("#amount").css({ "text-align": "right" }) $("#btnsubmit").off("click").on("click", e => this.onFormSubmit(e)) $("body").on("keypress", e=> this.handleAmountKey(e)) } private handleAmountKey(e) { //e.preventDefault() var n = String.fromCharCode(e.charCode); if (App.GlobalCommon.isNumber(n) && e.target.id === "amount") { setTimeout(() => { var curr = $("#amount").val() //var newval = "" + curr + n; var formatted = this.Accounting.toFixed(+curr, 2); //var formatted = this.Accounting.formatNumber(+curr, {precision : 2, thousand:","}); $("#amount").val(formatted) }, 3000) } } private getTemplate(resp) { var items = [{ id: 1, valueof: "CAT" }, { id: 2, valueof: "DOG" }] var account = App.GlobalCommon.input_data_string("amount", "Amount", "") var amount = App.GlobalCommon.dropdown("Account", "account", "", resp.accounts, "One"); var descof = App.GlobalCommon.input_data_string("Description", "descof", "") var form = App.GlobalCommon.form("New Account Record", account + amount + descof, "btnsubmit", "form1"); return form; } onFormSubmit(e) { e.preventDefault() var formdata = App.GlobalCommon.getFormInputs($("#form1")) var client = new account_server_client() var act = client.CallMethod("SaveNewLedger", formdata) $.when(act).then(resp => App.GlobalCommon.processPostBack(resp, $("#form1"), function () { })) } } }<file_sep>/* * Minimal file upload button * * @author <NAME> <<EMAIL>> * */ !function ($) { var Upload = function (element, options) { this.options = $.extend({}, $.fn.Upload.defaults, options); this.el = $(element); var width = this.el.outerWidth(); var height = this.el.outerHeight(); var wrapper = $("<div style='position: relative; display: inline-block;'></div>"); var container = $("<div></div>"); container.css({ position: "absolute", overflow: "hidden", opacity: 0, top: 0, left: 0 }); this.fileInput = $("<input type='file'/>"); this.fileInput.attr("name", this.options.name); // This is the only way to make the button wider this.fileInput.css("font-size", "20px"); // Create the file upload input and get its width container.append(this.fileInput); this.el.wrap(wrapper); this.el.before(container); var iWidth = container.width(); container.width(width); container.height(height); this.fileInput.css({ "margin-left": -(iWidth - width - 13) + "px", "margin-top": "-3px", "height": (height * 2) + "px" }); this.listen(); }; Upload.prototype = { listen: function () { this.fileInput.change($.proxy(this.onselect, this)); }, onselect: function (e) { this.file = e.currentTarget.files[0]; if (this.options.onSelect) { this.options.onSelect.call(this); return; } this.sendFile(); }, sendFile: function (data) { if (!this.file) return; var fd = new FormData(); fd.append(this.options.name, this.file); if (data) { for (var i in data) fd.append(i, data[i]); } this.start = (new Date()).getTime(); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", $.proxy(this.update, this), false); xhr.addEventListener("load", $.proxy(this.complete, this), false); xhr.addEventListener("error", $.proxy(this.failed, this), false); xhr.addEventListener("abort", $.proxy(this.cancelled, this), false); xhr.open("POST", this.options.url); xhr.send(fd); this.xhr = xhr; this.progress = { lastBytes: 0, total: this.file.size, loaded: 0, speed: 0 } if (this.options.onUpdate) { this.intervalUpdate = $.proxy(this.options.onUpdate, this); this.timer = setInterval(this.intervalUpdate, this.options.updateInterval); } }, getPercentage: function () { return Math.round(this.progress.loaded * 100 / this.progress.total); }, getThroughput: function () { return this.progress.throughput; }, getSpeed: function () { return this.progress.speed; }, cancel: function () { this.xhr.abort(); }, inProgress: function () { return !!this.xhr; }, update: function (e) { if (!e.lengthComputable) return; this.progress.total = e.total; this.progress.loaded = e.loaded; this.progress.throughput = Math.round(this.progress.loaded - this.progress.lastBytes); this.progress.lastBytes = this.progress.loaded; var elapsed = (new Date()).getTime() - this.start; this.progress.speed = Math.round(1000 * this.progress.loaded / elapsed); }, complete: function (e) { clearInterval(this.timer); this.progress.loaded = this.progress.total; this.intervalUpdate(); if (this.options.onComplete) { var data = this.options.parseResponse ? jQuery.parseJSON(this.xhr.responseText) : undefined; this.options.onComplete.call(this, data); } this.xhr = null; }, failed: function (e) { clearInterval(this.timer); if (this.options.onError) { this.options.onError.call(this, this.xhr); } this.xhr = null; }, cancelled: function (e) { clearInterval(this.timer); if (this.options.onCancel) { this.options.onCancel.call(this); } this.xhr = null; } }; $.fn.Upload = function (option, arg) { var $this = $(this), data = $this.data('Upload'), options = typeof option == 'object' && option; if (!data) $this.data('Upload', (data = new Upload(this, options))); if (typeof option == 'string') { return data[option](arg); } return data; }; $.fn.Upload.defaults = { updateInterval: 500, parseResponse: true, name: "file" } }(window.jQuery);<file_sep>/// <reference path="App.ViewEngine.ts" /> /// <reference path="../account/Account.ts" /> /// <reference path="linq-2.2.d.ts" /> /// <reference path="amplify.d.ts" /> /// <reference path="jquery-1.9.1.d.ts" /> module App { export class ValidationReponse { constructor( public Errors: ValidationError[]= [], public IsValid: boolean = false ) { } } export class ValidationError { constructor(public AttemptedValue: string, public CustomState: any, public ErrorMessage: string, public PropertyName: string ) { } } export class GlobalCommon { public static processPostBack(resp, form: JQuery, after) { if (resp.IsValid !== 'undefined' && resp.IsValid === false) { this.apply_validation(resp, form); } else { after(); } } public static getFormInputs(form: JQuery): any { var input = { }; form.find("input[type=text]").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("input[type=password]").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("input[type=hidden]").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("textarea").each(function (idx, item) { var jitem = $(item); var txt = jitem.val() //txt = txt.replace(/</gi, '&lt;'); //txt = txt.replace(/>/gi, '&gt;'); input[jitem.attr('name')] = txt; //input[jitem.attr('name')] = jitem.val(); }); form.find("select").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("input[type=radio]:checked").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.val(); }); form.find("input[type=checkbox]").each(function (idx, item) { var jitem = $(item); input[jitem.attr('name')] = jitem.is(':checked') ? 1 : 0; }); return input; } // utitlity : applies error messages to their respective elements public static apply_validation(validationResponse: ValidationReponse, form: JQuery): void { $(".text-error, .alert").remove(); var first: JQuery; $.each(validationResponse.Errors, (idx, v) => { var el: JQuery = $("#" + v.PropertyName); if (idx === 0) first = el; var message = $("<div class='alert alert-error'>" + v.ErrorMessage + "</div>").hide() el.before(message.fadeIn().fadeOut().fadeIn()); }) first.focus(); } public static uiify(input: string) { var res = input; res = res.replace(/</gi, '&lt;'); res = res.replace(/>/gi, '&gt;'); res = res.replace(/(\r\n|\n|\r)/gm, '<br>') //var links = $("<div>" + input + "</div>").find("a"); //for (var i = 0; i < links.length; i++) { // var link = links[i] // var href = $(link).attr("href"); //} //res = res.replace(/(http:\/\/[^\s]+)/gi, (match) => { // // return '<a href="' + match + '">' + this.truncate(match, 40) + '</a>'; // return '<a href="' + match + '" target="_blank">Open</a>'+ match; //}) return res; } public static uploadify(title: string) { var help = "<label class='control-label' for='file_upload_1'>{title}</label>".replace("{title}", title); var input = '<div class="controls"><input type="file" name="file_upload_1" id="file_upload_1"></input></div>' return this.control(help + input); } public static upload(title: string) { var help = "<label class='control-label' for='file_upload'>{title}</label>".replace("{title}", title); var q = "<div class='controls'><div id='queue'></div>"; var in2 = '<input id="file_upload" name="file_upload" type="file" multiple="multiple"></input>' var click = "&nbsp;&nbsp;&nbsp;<a href=" + "javascript:$('#file_upload').uploadifive('upload')" + ">start</a></div>"; return this.control(help + q + in2 + click); } public static dropdown(title: string, id: string, nameof: string, data: any[], selectedvalue: string) { var help = "<label class='control-label' for='{id}'>{title}</label>".replace("{title}", title).replace("{id}", id); var option = "<option value='{id}' {selected}>{valueof}</option>" var select = "<div class='controls'><select name='{nameof}' id='{id}'>{options}</select></div>".replace("{nameof}", nameof).replace("{id}", id) var selected = '', options = ''; options += "<option value='-1'>...</option>" Enumerable.From(data).ForEach((item) => { if (selectedvalue === item) { selected = 'selected'; } options += option.replace("{id}", item.id).replace("{valueof}", item.valueof).replace("{selected}", selected) }) return this.control(help + select.replace("{options}", options)) } public static input_data_string(nameof: string, label, prefix: string) { return this.inputstring(nameof, nameof, "{{" + prefix + "." + nameof + "}}", label, "text"); } public static isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } public static form(title: string, fields: string, buttonId?: string, formid?: string): string { var tmp = "<div class='form'><form class='form-vertical' id='{formid}'><div><strong>{0}</strong></div><fieldset>{fields}<div id='errors'/><hr><button id={buttonId} class='btn btn-primary clearfix'>Submit</button></fieldset></form></div>" .replace("{0}", title) .replace("{fields}", fields) if (formid) { tmp = tmp.replace("{formid}", formid) } else { tmp = tmp.replace("{formid}", "form1") } if (buttonId) { tmp = tmp.replace("{buttonId}", buttonId); } else { tmp = tmp.replace("{buttonId}", "btnsubmit"); } return tmp; } public static textarea(id: string, name: string, text: string, help: string, rows: string): string { var tmp = "<label class='control-label' for='{5}'>{3}</label>" tmp += "<div class='controls'>" // "ckeditor" cols="80" id="editor1" name="editor1" tmp += "<textarea class='form-editing' id='{0}' name='{1}' rows='{4}'>{2}</textarea>" tmp += "<div class='form-viewing'>{6}</div>" tmp += "</div>" tmp = tmp.replace("{0}", id) .replace("{1}", name) .replace("{2}", text.replace(/<br>/gi, "\n")) .replace("{3}", help) .replace("{4}", rows) .replace("{5}", name) .replace("{6}", text) return this.control(tmp); } public static control(content) { return this.div("", "control-group", content) } public static div(id: string, cssclass: string, content: string) { var tmp = "<div id='{id}' class='{class}'>{content}</div>" if (!cssclass) { cssclass = ''; } if (!id) { id = ''; } return tmp.replace('{id}', id).replace('{class}', cssclass).replace('{content}', content) } public static checkbox(id: string, name: string, help: string, selected: string) { var tmp = this.inputstring(id, name, '', help, "checkbox"); if (selected === '1') { tmp.replace("></input>", "checked></input>") } return tmp; } public static radio(name: string, value: string, text: string, wrapclass: string, selected: boolean): string { var tmp = "<label class='{3}'><input type='radio' name='{0}' value='{1}' {4}/> {2}</label>" .replace("{0}", name) .replace("{1}", value) .replace("{2}", text) .replace("{3}", wrapclass) .replace("{4}", selected ? "checked" : ""); return tmp; } // utitlity public static inputstring(id: string, name: string, value: string, help: string, type: string, maxlength?: string): string { var tmp = "<label class='control-label' for='{5}'>{3}</label>" tmp += "<div class='controls'>" tmp += "<input class='form-editing' type={4} id='{0}' name='{1}' value='{2}' maxlength={7} ></input>" tmp += "<div class='form-viewing'>{8}</div>" tmp += "</div>" if (!maxlength) maxlength = "50"; //"<div class='control-group'><div class='controls'><span class='control-label' for='{5}' >{3}</span><input type={4} id='{0}' placeholder='' name='{1}' value='{2}' maxlength=50 ></input></div></div>" tmp = tmp.replace("{0}", id) .replace("{1}", name) .replace("{2}", value) .replace("{3}", help) .replace("{4}", type) .replace("{5}", id) .replace("{6}", help) .replace("{7}", maxlength) .replace("{8}", value) return this.control(tmp); } private static Chars: string[] = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZ'.split(''); public static truncate(input: string, n: number) { var res = input.substr(0, n - 1) + (input.length > n ? '...' : ''); return res; } public static createUUID(len: number, radix: number): string { var chars = this.Chars, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random() * 16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); } } }<file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Data; using System.Linq; using Dapper; using FluentValidation; using FluentValidation.Results; using Newtonsoft.Json.Linq; using Tekphoria.Web.Server.Common; namespace Tekphoria.Web.Server.Account { public class SignInValidator : AbstractValidator<User> { private readonly IDbConnection _accountsDb; private User user; public SignInValidator(IDbConnection accountsDb) { _accountsDb = accountsDb; Custom(user => { User db_user = _accountsDb.Query<User>( "select id,date_created,password,pwd,status from users where email=@email;", new { user.email }).FirstOrDefault(); if (db_user == null) return new ValidationFailure("email", "email not found."); if (string.CompareOrdinal(db_user.status, "VERIFIED") != 0) return new ValidationFailure("account", "Account not verified."); if (string.IsNullOrWhiteSpace(db_user.pwd)) { // upgrade the password string enc_password = Crypto.EncryptStringAes(db_user.password, Config.ID); _accountsDb.Execute("update users set password='v2', pwd=@pwd where id=@id;", new { pwd = <PASSWORD>, db_user.id }); db_user.pwd = <PASSWORD>; } if (string.CompareOrdinal(db_user.password, "v2") != 0 && string.CompareOrdinal(user.password, db_user.password) != 0) return new ValidationFailure("password", "The password is is not valid (v1)"); string enc_pwd = db_user.pwd.ToString(); string decrypted_password = Crypto.DecryptStringAES(enc_pwd, Config.ID); if (string.CompareOrdinal(user.password, decrypted_password) != 0) return new ValidationFailure("password", "The password is is not valid (v2)"); if (db_user.date_created.AddHours(4) < DateTime.UtcNow && string.CompareOrdinal(db_user.status, "VERIFIED") != 0) return new ValidationFailure("account", "Grace period expired."); return null; }); } } }
2535240d79f50f7a7a84042110a19e98a7864bf3
[ "Markdown", "C#", "TypeScript", "JavaScript" ]
174
TypeScript
brunskillage/Tekphoria-Web
0f56bbc0e4da5ca865f0bf3f6a22b439a492b2b5
d870f2028409c298f71a835e97227f30329cea1d
refs/heads/main
<repo_name>dannfirefight322/password-generator<file_sep>/README.md # password-generator ### This is my password generator. ### [This is the link](https://dannfirefight322.github.io/password-generator/) ![Screenshot](passwordGenerator.png)<file_sep>/script.js // Assignment Code var generateBtn = document.querySelector("#generate"); // Write password to the #password input function writePassword() { var password = generatePassword(); var passwordText = document.querySelector("#password"); passwordText.value = password; } // Add event listener to generate button generateBtn.addEventListener("click", writePassword); function generatePassword() { var passwordLength = prompt("Enter the number of characters you want for you new password. More than 12 but less than 128."); var numbers = confirm("Do you want numbers in your password?"); var lower = confirm("Do you want lowercases in your password?"); var upper = confirm("Do you want uppercases in your password?"); var minimumCount = 0; var minimumNumbers = ""; var minimumLower = ""; var minimumUpper = ""; var functionArray = { getNumbers: function() { return String.fromCharCode(Math.floor(Math.random() * 10 + 48)); }, getLower: function() { return String.fromCharCode(Math.floor(Math.random() * 26 + 97)); }, getUpper: function() { return String.fromCharCode(Math.floor(Math.random() * 26 + 65)); }, }; if (numbers === true) { minimumNumbers = functionArray.getNumbers(); minimumCount++; } if (lower === true) { minimumLower = functionArray.getLower(); minimumCount++; } if (upper === true) { minimumUpper = functionArray.getUpper(); minimumCount++; } var randomPasswordGenerated = ""; for (let i = 0; i < (parseInt(passwordLength) - minimumCount); i++) { var randomNumberPicked = Math.floor(Math.random() * 4); randomPasswordGenerated += randomNumberPicked; } randomPasswordGenerated += minimumNumbers; randomPasswordGenerated += minimumLower; randomPasswordGenerated += minimumUpper; return randomPasswordGenerated; }
fe039a9bb2ee68865901a1061e076c4b1a7750ea
[ "Markdown", "JavaScript" ]
2
Markdown
dannfirefight322/password-generator
4bc40b27f07d5c10d61c90b8d6656970d35725cd
733e6a015116d41af3eb449a0fae6e056afb692e
refs/heads/master
<repo_name>MibinGit/Algorithms-Assignments<file_sep>/README.md # Algorithms-Assignments Northeastern University - INFO6205 - Program Structure &amp; Algorithms <file_sep>/QUIZ/Sec2_Quiz2/Sec2_Quiz2_Coding.java public class Solution { public int binarySearch(int array[], int key) { //TODO:: implement binary search // Corner case: if(array == null || array.length == 0) { return -1; } int left = 0; int right = array.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(array[mid] > key) { left = mid + 1; } else if(array[mid] < key) { right = mid - 1; } else { return mid; } } return -1; } }
5281de5fef841c60b4e9cee1e9cda9ebfc415306
[ "Markdown", "Java" ]
2
Markdown
MibinGit/Algorithms-Assignments
e824e70e851286278c95125eafb48bd22694806c
4ea4f95afe4875a0abf0c187b455e14aaa3bc670
refs/heads/main
<repo_name>Rconat/code-quiz<file_sep>/script.js // DOM elements var startQuiz = document.getElementById('startQuizBtn') var countdownTimer = document.getElementById('countdownTimer') var restartQuiz = document.getElementById('restartQuizBtn') var answerResult = document.getElementById('answerResult') var count = 75; var currentQuestion = 0 // Quiz Questions and answers // Sourced Questions from "https://www.codeconquest.com/coding-quizzes/" var quizQuestions = [ { question: 'What is a JavaScript element that represents either TRUE or FALSE values?', choices: ['Event', 'RegExp', 'Condition', 'Boolean'], answer: 'Boolean' }, { question: 'What is the element called that can continue to execute a block of code as long as the specified condition remains TRUE?', choices: ['Debugger', 'Repeater', 'Clone', 'Loop'], answer: 'Loop' }, { question: 'in Javascript, what is a block of code called that is used to perform a specific task?', choices: ['Function', 'Declaration', 'Variable', 'String'], answer: 'Function' }, { question: 'What is the element called that is used to describe the set of variables, objects, and functions you explicitly have access to?', choices: ['Restriction', 'Range', 'Scope', 'Output Level'], answer: 'Range' }, { question: 'What is the element used – and hidden – in code that explains things and makes the content more readable?', choices: ['Comparisons', 'Quotations', 'Notes', 'Comments'], answer: 'Comments' }, { question: 'What is the name of the statement that is used to exit or end a loop?', choices: ['Break Statement', 'Close Statement', 'Falter Statement', 'Condition Statement'], answer: 'Condition Statement' }, { question: 'What is the default behavior called that is used to move declarations to the top of the current scope?', choices: ['Jumping', 'Arranging', 'Sorting', 'Hoisting'], answer: 'Hoisting' }, { question: 'What is the object called that lets you work with both dates and time-related data?', choices: ['Clock', 'Time Field', 'Time-warp', 'Dates'], answer: 'Clock' }, { question: 'Where is the JavaScript placed inside an HTML document or page?', choices: ['In the <body> and <head> sections', 'In the <footer> section', 'In the <title> section', 'In the <meta> section'], answer: 'In the <meta> section' }, ] // Score variables var currentScore = 0; var finalScore = 0 startQuiz.addEventListener('click', startQuizFunction); // function runs on startQuiz click function startQuizFunction() { // clear the quiz setup information and display quiz clearQuizTitle() showQuizQuestions() // Timer starting time countdownTimer.innerText = count + ' seconds left' // Create a running timer that counts down when agree to take the quiz setInterval(function() { count-=1 countdownTimer.innerText = count + ' seconds left' console.log(count + ' seconds left') // When timer runs out if (count <= 0) { // console.log ("inside") finalScore = currentScore // Display final score alert("Quiz Complete: Your final score is " + finalScore) // Display Scoreboard } }, 1000) // Ask quiz questions if (currentQuestion < quizQuestions.length) { var questionNumberDisplay = document.getElementById('questionNumber') questionNumberDisplay.innerText = (currentQuestion + 1) var questionTextDisplay = document.getElementById('questionText') questionTextDisplay.innerText = quizQuestions[currentQuestion].question // create buttons generateBtns() // on click // For each correct answer if ("clicked button".innerText === quizQuestions[currentQuestion].answer) { answerResult.innerText = 'Correct answer' // add 1 to the score currentScore++ // move to next question currentQuestion++ } // For each wrong answer subtract time from the countdown timer else { answerResult.innerText = 'Wrong answer' // decrease countdown by 5 sec count=count-5 // move to next question currentQuestion++ } } else { alert ("Quiz Complete: Your final score is " + finalScore) } } function generateBtns() { for (var i =0; i < quizQuestions[currentQuestion].choices.length; i++) { var options = document.createElement("buttons") document.body.appendChild(options); options.innerHTML = quizQuestions[currentQuestion].choices[i] } } // View Highscores button // Restart Quiz Button restartQuiz.addEventListener('click', restartQuizFunction); // function runs on restartQuiz click function restartQuizFunction() { restartCnfr = confirm("Would you like to restart the quiz?") if (restartCnfr) { clearInterval() count = 75; startQuizFunction() } } // function to hide the challenge information function clearQuizTitle() { document.querySelector('.quizIntro').classList.add('hidden'); } //function to show the quiz questions function showQuizQuestions() { document.querySelector('.quizQuestions').classList.toggle('hidden'); }
9ef63113928db1589e365026800323d8fa973b46
[ "JavaScript" ]
1
JavaScript
Rconat/code-quiz
2d17ba45b0942a5f012bf936e55186e4dffaedd8
bbb461928341fcd0b0cb090b5089d3637fe75ab8
refs/heads/master
<file_sep>package com.jojoldu.book.springboot.lol.api; import com.jojoldu.book.springboot.lol.config.ApiKey; import com.jojoldu.book.springboot.lol.dto.SummonerDto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @RequiredArgsConstructor @Service public class SummonerApiClient { private final RestTemplate restTemplate = new RestTemplate(); SummonerDto summonerDto; private final String SummonerInfoUrl = "https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/"; public SummonerDto requestSummonerInfo(String summonerName) { summonerDto = restTemplate.getForObject(SummonerInfoUrl+summonerName+"?api_key="+ApiKey.API_KEY,SummonerDto.class); return summonerDto; } } <file_sep>package com.jojoldu.book.springboot.lol; import com.jojoldu.book.springboot.lol.config.ApiKey; import com.jojoldu.book.springboot.lol.dto.SummonerDto; 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.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class SummonerSearchTest { @Autowired private TestRestTemplate restTemplate; private SummonerDto userDB; private final String SummonerInfoUrl = "https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/"; @Test public void SummonerSearch() { String summonerName = "블리츠그랩꾸드빵"; userDB = restTemplate.getForObject(SummonerInfoUrl+summonerName+"?api_key="+ApiKey.API_KEY,SummonerDto.class); System.out.println(userDB); } } <file_sep>package com.jojoldu.book.springboot.lol.dto; import lombok.Data; import lombok.Getter; @Data @Getter public class SummonerDto { private String accountId; private int profileIconId; private long revisionDate; private String name; private String id; private String puuid; private long summonerLevel; } <file_sep>package com.jojoldu.book.springboot.lol.web; import com.jojoldu.book.springboot.lol.dto.SummonerDto; import com.jojoldu.book.springboot.lol.service.SummonerService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RequiredArgsConstructor @RestController public class SummonerController { private final SummonerService summonerService; @GetMapping("/api/v1/user/lol/{summoner}") public SummonerDto get(@PathVariable String summoner) { return summonerService.searchSummoner(summoner); } } <file_sep># 웹 프로젝트 '태이존' '태이존'은 간단한 CRUD부터 무중단 배포까지 실제 서비스를 하고 있는 프로젝트로, 기능을 점점 더 추가하여 최종적으로는 op.gg같은 같은 웹서비스를 목표로 하고있습니다. # 프로젝트 진행 21.07.14 웹프로젝트 시작 21.08.31 AWS 서버 환경 구축 완료 - putty를 사용하여 EC2 서버 설정 완료 21.09.01 AWS RDS 마리아DB 생성 완료 21.09.03 EC2와 RDS 연동 완료, putty에서 ec2서버에 프로젝트 배포 시작하는데 오류남 21.09.03 ~ 21.09.06 오류 고침. 21.09.09 H2로 구동되던 DB를 RDS로 옮겼음 21.09.09 RDS 연결 오류 잡는중 21.09.23 s3 putty에 다운중 21.09.29 NGINX 오류로 홈페이지 제대로 작동하지 않음 해결중 21.09.30 NGINX 설정 - 서버 - location / 부분에 코드 추가 및 수정해주니 해결됨 21.10.01 네이버 로그인 오류 : Callback URL 오류 21.10.09 기능 추가가 안됨. 21.10.12 복습 : RestfulAPI, MVC패턴 21.10.13 복습 : 폼, JPA를 이용한 Dto 21.10.14 복습 : DB (h2) 21.10.16 복습 : 롬복, 리팩토링 21.10.17 복습 : 프로젝트 복습 ( ~ PostsRepositoryTest) 21.10.18 복습 : 프로젝트 복습 ( PostsRepositoryTest ~ 수정/조회test) 21.10.20 복습 : 프로젝트 복습 ( JPA Auditing ~ 프로젝트 끝까지) 21.10.20 기능 추가 오류 해결( RestTemplate ) 21.10.22 피파온라인 감독 정보 가져오기 + 감독 정보 단위테스트 성공 / 내장was 문제 21.10.23 롤 api 가져올 준비로 Controller, Service, Cto, ApiController, 뷰 구현 21.10.24 롤 유저 정보 저장 및 가져오기, 단위테스트 성공 21.10.25 피파 유저 정보 DB 구현 후 프로젝트 분리 21.11.04 글등록 버튼 무반응 오류 해결 <file_sep>package com.jojoldu.book.springboot.domain.posts; import com.jojoldu.book.springboot.domain.BaseTimeEntity; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; @Getter @NoArgsConstructor //기본 생성자 자동추가 (public Post(){} 과 같은 효과) / 파라미터가 없는 생성자를 자동추가함 @Entity // 테이블과 링크될 클래스임을 나타냄. Entity클래스에는 절대 Setter 메소드를 만들지 않을것. 대신 해당 필드의ㅣ 값 변경이 필요함녀 명확히 그 목적을 나타낼 수 있는 메소드를 추가해야한다. public class Posts extends BaseTimeEntity { // 실제 DB와 매칭될 클래스. // Entity클래스에서는 절대 Setter 메소드를 만들지말것. 만들어야하면 목적과 의도를 명확히나타낼수있는 메소드 추가할것. @Id // 기본키(PK) @GeneratedValue(strategy = GenerationType.IDENTITY) //PK의 생성 규칙을 나타냄. 괄호 안에 있는거 써야 auto_increment가 됨 private Long id; // 웬만하면 Entity의 PK는 Long타입의 Auto_increment를 추천함. 주민번호와 같이 비즈니스상 유니크 키나 여러 키를 조합한 복합키를 PK를 잡을 경우 난감한 상황 발생 가능. @Column(length = 500, nullable = false) // 굳이 선언하지 않아도 해당 클래스의 필드는 모두 칼럼이 됨. 사용 이유 : 사이즈를 500으로 늘리고싶거나 타입을 TEXT로 변경하고싶거나(content) private String title; @Column(columnDefinition = "TEXT", nullable = false) private String content; private String author; @Builder //해당 클래스의 빌더 패턴 클래스를 생성. 생성자 상단에 선언 시 생성자에 포함된 필드만 빌더에 포함 public Posts(String title, String content, String author){ this.title = title; this.content = content; this.author = author; } public void update(String title, String content){ this.title=title; this.content=content; } } <file_sep>buildscript { ext { //ext는 build.gradle에서 사용하는 전역함수 설정 springBootVersion = '2.1.7.RELEASE' } repositories { mavenCentral() jcenter() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } //아래 4개의 플러그인은 자바와 스프링부트를 사용하기 위한 필수 플러그인으로 항상 추가해야한다 apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' // 이 플러그인은 스프링 부트의 의존성들을 관리해주는 플러그인이라 필수추가 group 'com.jujuldu.book' version '1.0.1-SNAPSHOT-' +new Date().format("yyyyMMddHHmmss") sourceCompatibility = 1.8 //repositories는 각종 의존성(라이브러리)들을 어떤 원격 저장소에서 받을지를 정함. 기본적으론 메이븐, 최근엔 제이센터도 많이사용 repositories { mavenCentral() // 본인이 만든 라이브러리를 업로드할때 많은 과정과 설정 필요 jcenter() //위의 단점을 간단하게함. 또한 여기에 업로드하면 자동으로 메이븐에 업로드되게 자동화할수잇음 } //개발에 필요한 의존성(라이브러리)들을 선언하는 곳 dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.projectlombok:lombok') // perferences에서 annotation processor에 enable annotation processing을 매 플젝마다 해줘야됨 //JPA 시작하면서 등록한 의존성 compile('org.springframework.boot:spring-boot-starter-data-jpa') //스프링부트용 spring data jpa 추상화 라이브러리. 스프링부트 버전에 맞춰 자동으로 jap관련 라이브러리 버전 관리 compile('com.h2database:h2') // 인메모리 관계형DB. 별도의 설치없이 프로젝트 의존성만으로 관리가능. 메모리에서 실행되기 때문에 애플리케이션을 재시작할 때마다 초기화된다는 점을 이용하여 테스트용도로 많이 사용 //머스테치 ( 뷰 만들기 ) compile('org.springframework.boot:spring-boot-starter-mustache') //구글 로그인 compile('org.springframework.boot:spring-boot-starter-oauth2-client') // 소셜로그인 등 클라이언트 입장에서 소셜 기능 구현시 필요한 의존성이다 //데이터베이스 (세션을 저장하기 위한 저장소) compile('org.springframework.session:spring-session-jdbc') //테스트 환경을 위한 임의로 인증된 사용자를 추가 testCompile("org.springframework.security:spring-security-test") testCompile('org.springframework.boot:spring-boot-starter-test') //마리아DB 드라이버( 현재 H2 드라이버만 있는 상태여서 RDS로 바꾸는중) compile("org.mariadb.jdbc:mariadb-java-client") }<file_sep> #!/usr/bin/env bash ABSPATH=$(readlink -f $0) ABSDIR=$(dirname $ABSPATH) source ${ABSDIR}/profile.sh function switch_proxy() { IDLE_PORT=$(find_idle_port) echo "> 전환할 Port: $IDLE_PORT" echo "> Port 전환" echo "set \$service_url http://127.0.0.1:${IDLE_PORT};" | sudo tee /etc/nginx/conf.d/service-url.inc # 하나의 문장을 만들어 파이프라인으로 넘겨주기 위해 echo 사용함. # 엔진엑스가 변경할 프록시 주소를 생성합니다 # 쌍따옴표를 사용해야함. 안그러면 $service_url 인식못하고 변수를 찾게됨 # sudo부터의 코드 : 앞에서 넘겨준 문장을 service-url.inc에 덮어쓴다 echo "> 엔진엑스 Reload" sudo service nginx reload # 엔진엑스 설정을 다시 불러옴. restart와는 다르다. restart는 잠시 끊기지만 reload는 끊김없이 다시 불러옴 # 다만 중요한 설정들은 반영되지 않으므로 restart를 사용해야함. 여기선 외부의 설정파일인 service-url을 다시 불러오는 거라 reload로 가능함 } <file_sep>package com.jojoldu.book.springboot.web; import com.jojoldu.book.springboot.config.auth.SecurityConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.CoreMatchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) // 스프링부트test와 Junit 사이에 연결자 역할. Junit에 내장된 실행자 외 다른 실행자 실행시키는데 여기서는 SpringRunner라는 스프링 실행자를 사용 @WebMvcTest(controllers = HelloController.class, // 여러 스프링 테스트 어노테이션 중 Web(Spring MVC)에 집중할 수 있는 어노테이션 excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class) } ) public class HelloControllerTest { @Autowired // 스프링이 관리하는 빈(Bean)을 주입받음 private MockMvc mvc; // 웹 API를 테스트할 때 사용, 스프링MVC테스트의 시작점, 이 클래스를 통해 HTTP GET, POST 등에 대한 API 테스트 가능 // Mock : 실제 사용하는 모듈이 아닌, 실제 모듈을 흉내내는 테스트용 모듈 -> 테스트 효율성 증가 @WithMockUser(roles = "USER") @Test public void hello가_리턴된다() throws Exception { String hello = "hello"; mvc.perform(get("/hello")) //MockMvc를 통해 /hello 주소로 HTTP GET 요청을 함. 체이닝이 지원되어 아래에 이어서 선언 가능 .andExpect(status().isOk()) //mvc.perform의 결과를 검증한다. HTTP Header의 Status를 검증한다. / 우리가 흔히 알고있는 200,404,500 등의 상태 검증. 여기선 OK 즉, 200인지 검증 .andExpect(content().string(hello)); // mvc.pergorm의 결과를 검증. 응답 본문의 내용을 검증. Controoler에서 "hello"를 리턴하기 때문에 이 값이 맞는지 검증 } @WithMockUser(roles = "USER") @Test public void helloDto가_리턴된다() throws Exception { String name = "hello"; int amount = 1000; mvc.perform(get("/hello/dto") .param("name", name) .param("amount", String.valueOf(amount))) //값은 String만 허용돼서 이렇게 바꿔줘야함 .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value(equalTo(name))) //교재대로 안되어서 구글링해서 바꾸니까 됨 .andExpect(jsonPath("$.amount").value(equalTo(amount))); } }<file_sep>package com.jojoldu.book.springboot.web; import com.jojoldu.book.springboot.config.auth.LoginUser; import com.jojoldu.book.springboot.config.auth.dto.SessionUser; import com.jojoldu.book.springboot.service.posts.PostsService; import com.jojoldu.book.springboot.web.Dto.PostsResponseDto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @RequiredArgsConstructor // 선언된 모든 final 필드가 포함 된 생성자 생성 @Controller //머스테치에 url을 매핑하기 위한 코드 / 이게 컨트롤러다 라는 뜻 public class IndexController { private final PostsService postsService; //Repository 를 통해 데이터베이스에 접근 해 데이터를 가져오고, Service 를 통해 Repository 의 메소드를 이용하게 했으니 //이제 Controller 가 Service 메소드를 이용 할 시간이다. @GetMapping("/") public String index(Model model, @LoginUser SessionUser user){ // Model은 서버 템플릿 엔진에서 사용할 수 있는 객체를 저장할 수 있다/ postsService.findAllDesc()로 가져온 결과를 posts로 index.mustache에 전달 model.addAttribute("posts",postsService.findAllDesc()); // index.mustache에서 userName을 사용할수 있게 userName을 model에 저장하는 코드 추가 // 삭제한 코드 : SessionUser user = (SessionUser) httpSession.getAttribute("user"); // CustomOAuth2UserService에서 로그인 성공 시 세션에 SessionUser를 저장하도록 구성. 즉, 로그인 성공시 "user"값 가져올수있다 if(user!=null){ model.addAttribute("userName",user.getName()); // 세션에 저장된 값이 있을때만 model에 userName으로 등록, 세션에 저장된 값이 없으면 model에 아무런 값이 없으니 로그인 버튼이 보임 } return "index"; // 머스테치 스타터 덕분에 컨트롤러에서 문자열을 반환할 때 앞의 경로와 뒤의 파일 확장자는 자동으로 지정된다. // 그래서 결국엔 src/main/resources/templates/index.mustache로 전환되어 View Resolver가 처리하게 된다. } @GetMapping("/posts/save") public String postsSave(){ return "posts-save"; } @GetMapping("/posts/update/{id}") //글제목을 눌렀을 때 get요청을 받아서 보내주는 역할의 클래스 public String postsUpdate(@PathVariable Long id, Model model){ // @PathVariable : URL 경로에 변수를 넣어줌 PostsResponseDto dto = postsService.findById(id); model.addAttribute("post",dto); // 뷰에 전달할 데이터를 키,값 으로 전달함 return "posts-update"; } } <file_sep>package com.jojoldu.book.springboot.lol.service; import com.jojoldu.book.springboot.lol.api.SummonerApiClient; import com.jojoldu.book.springboot.lol.dto.SummonerDto; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @RequiredArgsConstructor @Service public class SummonerService { @Autowired private final SummonerApiClient SummonerApiClient; @Transactional(readOnly = true) public SummonerDto searchSummoner(String summoner) { return SummonerApiClient.requestSummonerInfo(summoner); } }<file_sep>package com.jojoldu.book.springboot.domain.posts; //다른곳에서 DAO라고 불리는 DB Layer접근자. JPA에서는 Repository라고 부름. //@Repository를 추가할 필요없음. Entity클래스와 Repository는 함께 위치해야함 import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import java.util.List; //Posts클래스로 Database를 접근하게 해줄 JpaRepository public interface PostsRepository extends JpaRepository<Posts, Long> { // JpaRepository<엔티티 클래스, PK타입>을 상속하기만 하면 기본적인 CRUD 메소드가 자동생성됨 @Query("SELECT p FROM Posts p ORDER BY p.id DESC") List<Posts> findAllDesc(); } <file_sep>package com.jojoldu.book.springboot.config.auth; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) // 이 어노테이션이 생설될 수 있는 위치를 지정한다 RARAMETER로 지정했으니 메소드의 파라미터로 선언된 객체에서만 사용할수있다. @Retention(RetentionPolicy.RUNTIME) //@Retention 어노테이션으로 어느 시점까지 어노테이션의 메모리를 가져갈 지 설정하고, @Target 어노테이션으로 필드, 메소드, 클래스, 파라미터 등 선언할 수 있는 타입을 설정하면 대부분 커스텀 어노테이션은 쉽게 생성할 수 있습니다. 여기서 속성부분만 설정해주면요 public @interface LoginUser { }
54030403b0f2403f7c90e400e68e0e0b60a7fae3
[ "Markdown", "Java", "Shell", "Gradle" ]
13
Java
93TEI/freelec-springboot2-webservice
0c50c30decd494370be2c732d8224ef33aa40fba
80cd454211e02eaedb0351e8ca309ab93c885277
refs/heads/main
<repo_name>eng-EslamEzzat/simpleTodoApp<file_sep>/App.js import React, {Component} from 'react'; import {Alert, FlatList, StyleSheet, Text, View,TouchableWithoutFeedback, Keyboard, Button} from 'react-native'; import AddTodo from './components/addTodo'; import Header from './components/header' import TodoItem from './components/todo-item' class app extends Component { state={ todos: [ { text: 'buy coffee', key: '1' }, { text: 'create an app', key: '2' }, { text: 'play on the switch', key: '3' } ], } pressHandler = key => { const todos = this.state.todos.filter(item=>(item.key != key)) this.setState({ todos }) } submitHandler = (text)=>{ text?this.setState({ todos:[ {text:text,key:Math.random.toString}, ...this.state.todos ] }):Alert.alert('error!!','Please enter invalid data',[{ text:'understood',onPress:()=>{console.log('alert is closeds')} }]) } render(){ return( <TouchableWithoutFeedback onPress={Keyboard.dismiss} > <View style={styles.container}> <Header/> <View style={styles.content}> <AddTodo submitHandler={this.submitHandler}/> <View style={styles.button} > <Button title='Delete All' color='#b00' onPress={()=>this.setState({todos:[]})} /> </View> <View style={styles.list}> <FlatList data={this.state.todos} renderItem={({ item })=>( <TodoItem item={item} pressHandler={this.pressHandler} /> )} /> </View> </View> </View> </TouchableWithoutFeedback> ) } }; const styles = StyleSheet.create({ container:{ flex: 1, backgroundColor: '#ccc', // alignItems: 'center', // justifyContent: 'center' }, content: { padding: 40, // backgroundColor: 'grey', flex: 1, }, list:{ marginTop:0, // backgroundColor: '#aaa', flex:1, }, button:{ marginTop:20, marginBottom:0, alignItems:'flex-end', }, }) export default app;<file_sep>/components/header.js import React from 'react'; import {StyleSheet, Text, View} from 'react-native' export default function Header() { return( <View style={styles.header}> <Text style={styles.text}>My Todo App</Text> </View> ) } const styles = StyleSheet.create({ header:{ height:90, paddingTop:40, backgroundColor:'black', }, text:{ color:'#ccc', textAlign:'center', fontSize:20, fontWeight:'bold', } })
4196b93e07c7f0ac13b487908386e5f79c7bc79e
[ "JavaScript" ]
2
JavaScript
eng-EslamEzzat/simpleTodoApp
bbf7292e33bb0bfcbfe543d33caa406059a14aea
e90e507bd919bbc00aa4ebf30fd4ddc5d2f83925
refs/heads/master
<repo_name>ParkerNGore/-Assignment-Arrays-Filter-Map-Reduce<file_sep>/src/index.js import Senators from "./data/senators"; export const republicans = () => { const republicans = Senators.filter((senator) => { if (senator.party === "Republican") { return true; } }); return republicans; }; export const democrats = () => { const democrats = Senators.filter((senator) => { if (senator.party === "Democrat") { return true; } }); return democrats; }; export const independents = () => { const independent = Senators.filter((senator) => { if (senator.party === "Independent") { return true; } }); return independent; }; export const males = () => { const males = Senators.filter((senator) => { if (senator.person.gender === "male") { return true; } }); return males; }; export const females = () => { const females = Senators.filter((senator) => { if (senator.person.gender === "female") { return true; } }); return females; }; export const byState = (state = "UT") => { const byState = Senators.filter((senator) => { if (senator.state === "UT") { return true; } }); return byState; }; export const mapping = () => { const result = Senators.map(({ party, person }) => { return { firstName: person.firstname, lastName: person.lastname, party: party, gender: person.gender, }; }); return result; }; export const reducedCount = () => { const partyCounts = Senators.reduce( (accum, senator) => { if (senator.party === "Republican") { accum.republican++; } else if (senator.party === "Democrat") { accum.democrat++; } else { accum.independent++; } return accum; }, { republican: 0, democrat: 0, independent: 0, } ); return partyCounts; };
8cc11cd175bd48c60e2704e5177ce8671d53c115
[ "JavaScript" ]
1
JavaScript
ParkerNGore/-Assignment-Arrays-Filter-Map-Reduce
c7bbe0cc4ea71ac7654ecc5b66748ca7f2325495
f1548c578f9fa293482ba5694935a113a1519614
refs/heads/main
<file_sep>import Link from "next/link"; import Image from "next/dist/client/image"; // import { useRouter } from "next/dist/client/router"; import { useState, Fragment } from "react"; const Navbar = () => { // const router = useRouter(); const [colorChange, setColorchange] = useState(false); const changeNavbarColor = () => { if (window.scrollY >= 80) { setColorchange(true); } else { setColorchange(false); } }; if (typeof window !== "undefined") { window.addEventListener("scroll", changeNavbarColor); } return ( <Fragment> <nav> <div className="navbar-wrapper fixed top-0 left-0 right-0 w-full z-10 bg-white"> <div className={`navbar-container flex justify-between items-center mx-6 md:mx-16 2xl:mx-40 h-20 ${ colorChange ? "bg-white border-b-2 border-white" : "bg-white border-b-2 border-green-500" }`} > <div className="logo-container self-end mb-4"> <div className="logo"> <Link href="/" passHref> <Image src={ colorChange ? "/MD_logo/MD_logo_courier_prime_green.svg" : "/MD_logo/MD_logo_courier_prime_black.svg" } alt="logo" width={40} height={40} /> {/* <Image src="/MD_logo_courier.svg" alt="" width={30} height={30} /> */} </Link> </div> </div> <div className="navlinks self-end mb-3"> <Link href="/#projects" passHref> <a className={`${colorChange ? "text-green-500 hover:text-black" : "text-black hover:text-green-500"}`}>Projects</a> </Link> <Link href="/#about" passHref> <a className={`${colorChange ? "text-green-500 hover:text-black" : "text-black hover:text-green-500"}`}>About</a> </Link> </div> </div> </div> </nav> </Fragment> ); }; export default Navbar; <file_sep> const ProjectsHome = () => { return ( <h1>subpage home</h1> ); } export default ProjectsHome; <file_sep>import Link from "next/link"; import Image from "next/dist/client/image"; import { useEffect } from "react"; import { useRouter } from "next/dist/client/router"; const NotFound = () => { const router = useRouter(); useEffect(() => { setTimeout(() => { router.push("/"); }, 3000); }, []); return ( <div className="not-found flex flex-col justify-center items-center h-screen"> <div className="404-logo"> <Image src="/MD_logo/MD_logo_courier_prime_green.svg" alt="logo" width={40} height={40} /> </div> <h1 className="text-xl mb-1 text-green-500">Seems you took a wrong turn</h1> <h2>This page can't be found</h2> <p> Go back to the{" "} <Link href="/"> <a>Homepage</a> </Link> </p> </div> ); }; export default NotFound; <file_sep>import Image from "next/dist/client/image"; const About = () => { return ( <> <div id="about" className="about-anchor"></div> <section className="about-container bg-gray-100 p-6 md:p-16 2xl:px-40"> {/* <div className="grid grid-cols-1 md:grid-cols-8 gap-6 mx-6 md:mx-16 2xl:mx-40 pt-6 md:pt-16 2xl:pt-32"> <h1 className="header-title leading-normal text-4xl text-green-600"> About </h1> </div> */} <div className="grid grid-cols-1 md:grid-cols-8 gap-6"> <div className="about-text md:col-span-8 xl:col-span-5 xl:row-span-2 2xl:col-span-5"> <h1 className="header-title leading-normal text-4xl text-black mb-4"> About </h1> <p className="text-xl leading-relaxed"> Hi, I'm Mick, an experienced graphic designer, knowledgeable dtp-operator, and aspiring web developer from Antwerp. Nice to meet you, welcome to my portfolio. <br></br> <br></br> On this website you can find some of the projects made with new skills I gained during a seven-month full-time Junior Web Developer training at BeCode Antwerp. They represent the first steps I have been taking in my ambition of becoming a full stack developer with an emphasis on front-end. More projects can be found on my <a href="https://github.com/MickDellaert" target="_blank">Github</a> profile. <br></br> <br></br> Up until now I have been working in the graphic design industry, mainly for printed output. During my <a href="https://www.linkedin.com/in/mick-dellaert" target="_blank">career</a> I have worked on a broad range of projects: making layouts for books, magazines, advertisements, and newspapers; designing packaging, POS materials, logos, exhibition stands, interactive magazines, websites, and illustrations. <br></br> <br></br> Currently, I would love to add a more dynamic and interactive dimension to my skills and enter the world of web development with its endless possibilities and exciting prospects. At the moment I am actively looking for an internship, hoping to contribute and complete my new knowledge in a fresh position and continue my journey. If I sparked your interest, don't hesitate to <a href = "mailto: <EMAIL>">contact</a> me. </p> </div> <div className="portrait mt-6 xl:mt-0 md:col-span-3 xl:col-span-2 xl:col-start-7 md:mt-6 2xl:col-span-2 2xl:col-start-7"> <Image layout="responsive" objectFit="cover" src={"/portret/portret-rgb.jpg"} alt={"mick"} width={200} height={200} className={"image"} /> </div> <div className="contact font-bold text-green-500 text-xl my-6 md:mb-0 md:col-span-4 xl:col-span-2 xl:col-start-7 2xl:col-span-2 2xl:col-start-7 self-end"> <h1 className="leading-normal text-4xl text-black mb-4"> Contact </h1> <a className="contact-link leading-relaxed" href="https://www.linkedin.com/in/mick-dellaert" target="_blank">LinkedIn</a> <a className="contact-link leading-relaxed" href="https://github.com/MickDellaert" target="_blank">Github</a> <p className="contact-link leading-relaxed">0488 244 705</p> <a className="contact-link leading-relaxed" href = "mailto: <EMAIL>">mickdellaert<EMAIL></a> </div> </div> </section> </> ); }; export default About; <file_sep>import Hero from "../components/Hero"; import About from "../components/About"; import Project from "../components/Project"; import Header from "../components/Header"; import Footer from "../components/Footer"; import { projects } from "../data"; export const getStaticProps = async () => { return { props: { projectsLists: projects, }, }; }; export default ({ projectsLists }) => ( <> {" "} <Header /> <main> <div id="projects" className="projects-anchor"></div> <section id="" className="pics grid md:grid-cols-2 2xl:grid-cols-4 gap-6 mx-6 md:mx-16 2xl:mx-40 mb-6 md:mb-16 2xl:mb-32 xl:pt-16 bg-white relative"> {projectsLists.map((projectsList) => ( <Project key={projectsList.id} {...projectsList} /> ))} </section> <About /> </main> <Footer/> </> ); <file_sep>import Link from "next/link"; import Image from "next/image"; const Project = ({ id, name, description, mainImage }) => ( <> <Link href={`/projects/[id]`} as={`/projects/${id}`}> <div className={"grid-image-container"}> <Image layout="responsive" objectFit="cover" src={mainImage} alt={name} width={200} height={200} className={"image"} /> <div className="grid-overlay"> <div className="grid-title">{name}</div> </div> </div> </Link> </> ); export default Project; <file_sep>import Navbar from "./Navbar"; import Hero from "./Hero"; const Header = () => { return ( <header className="header-container w-full flex flex-col justify-center"> <Navbar /> <Hero /> </header> ); }; export default Header;
715d97323399c5327974b0b78e284765a3fc347a
[ "JavaScript" ]
7
JavaScript
MickDellaert/portfolio2021
cff68da58f8af83353400a10097ce5fa15e02222
60ad5eaa56a0adba2e79e60ac5370baab8377c85
refs/heads/master
<file_sep>import { configure, addDecorator } from '@kadira/storybook'; import React from 'react'; import styled from 'styled-components'; const req = require.context('../src/stories', true, /.js$/); function loadStories() { req.keys().forEach(filename => req(filename)); } const Wrapper = styled.div` height: 100vh; display: flex; justify-content: center; align-items: center; `; addDecorator(story => ( <Wrapper> {story()} </Wrapper> )); configure(loadStories, module); <file_sep>import { storiesOf } from '@kadira/storybook'; import React from 'react'; import styled from 'styled-components'; import { withLoader } from '../index'; const Demo = styled.div` display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; border: 4px dashed steelblue; color: cornflowerblue; font-size: 20px; font-weight: bold; `; const EnhancedDemo = withLoader(Demo); storiesOf('👋 Demo Placeload', module) .add('loading ', () => <EnhancedDemo loading>Hello Placeload</EnhancedDemo>) .add('not loading', () => <EnhancedDemo>Hello Placeload</EnhancedDemo>); <file_sep>import { storiesOf } from '@kadira/storybook'; import React from 'react'; import styled from 'styled-components'; import { withLoader } from '../index'; const LoremParagraph = styled.p` color: rgb(290,190,209); `; const EnhancedParagraph = withLoader(LoremParagraph); storiesOf('✍️ Paragraph Placeload', module) .add('with loading', () => ( <EnhancedParagraph loading> Cupcake ipsum dolor sit amet macaroon cookie. Topping pastry carrot cake tart jujubes cheesecake jelly-o. Danish icing cheesecake cake chocolate bar bear claw cake cookie sweet. Jujubes cake sweet lemon drops jujubes bear claw. Gummi bears pastry jelly beans dessert ice cream chocolate bar. Pudding chocolate cake tootsie roll sugar plum cake chocolate cake bonbon. </EnhancedParagraph> )) .add('without loading', () => ( <EnhancedParagraph> Cupcake ipsum dolor sit amet macaroon cookie. Topping pastry carrot cake tart jujubes cheesecake jelly-o. Danish icing cheesecake cake chocolate bar bear claw cake cookie sweet. Jujubes cake sweet lemon drops jujubes bear claw. Gummi bears pastry jelly beans dessert ice cream chocolate bar. Pudding chocolate cake tootsie roll sugar plum cake chocolate cake bonbon. </EnhancedParagraph> )); <file_sep># react-placeload Inspired by the awesome [Placeload.js](https://github.com/victorvoid/placeload.js) :octocat: [Check the demo on Storybook](https://xavcz.github.io/react-placeload/)
8babe1ad438713178ddcf923415697b5c2423439
[ "JavaScript", "Markdown" ]
4
JavaScript
victorvoid/styled-placeload
72912c35c52e524f5693e3eaa5c445e4981809ba
946664c3e8ed08ba9d61a4fab34ff335fdd91250
refs/heads/master
<file_sep>package test; import org.apache.logging.log4j.core.config.Configurator; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LoggerTest { @Test public void log4j() { Configurator.initialize("Log4j2", "classpath:log4j2.xml"); Logger logger = LoggerFactory.getLogger(LoggerTest.class); try { int num = 0; while (!Thread.currentThread().isInterrupted()) { logger.info("TEST_中文_" + num++); Thread.sleep(1000); } } catch (Throwable e) { e.printStackTrace(); } } }<file_sep># 项目介绍 log4j2写入kafka,独立线程写logger,不影响业务线程运行 # appender class ms.shanghai.log.KafkaLog4j2Appender # 使用方式 pom.xml ```xml <dependency> <groupId>ms.shanghai.log</groupId> <artifactId>kafka-log4j2-appender</artifactId> <version>1.0-SNAPSHOT</version> </dependency> ``` log4j.xml ```xml <?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <!-- appender console: test --> <Console name="console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %level %logger{1.}(%F:%L) - %msg%n" /> </Console> <!-- appender kafka --> <!-- topic 主题 --> <Kafka name="kafka" topic="TopicName"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %level %logger{1.}(%F:%L) - %msg" /> <!-- kafka地址 --> <Property name="bootstrap.servers">127.0.0.1:9092</Property> <!-- 主节点通知 --> <Property name="acks">1</Property> <!-- 压缩方式 --> <Property name="compression.type">gzip</Property> </Kafka> </Appenders> <Loggers> <!-- 屏蔽kafka日志 --> <logger name="org.apache.kafka" level="OFF" /> <Root level="INFO"> <AppenderRef ref="console" /> <AppenderRef ref="kafka" /> </Root> </Loggers> </Configuration> ```
d2701f33bbd6278e27524706c7e36ebf7aaafc26
[ "Markdown", "Java" ]
2
Java
lycwukang/KafkaLog4j2Appender
78c101d837d4e8237aad83196e4e0da1ae52e6a3
0ca7b94fe5ff76b052e6639a9724272f77f8369e
refs/heads/master
<repo_name>ognjen987/rakija<file_sep>/lib/js/app.js $(document).ready(function(){ $("#racunaj").on("tap",function(){ // $(this).hide(); var litaraRakije = $("#rakijaLitara").val(); var trenutnoStepeni = $("#trenutnoIzmerenoStepeni").val(); var zeljenoStepeni = $("#kolikoZeliStepeni").val(); var kolicinaDestilovaneVode = litaraRakije * (trenutnoStepeni - zeljenoStepeni) / zeljenoStepeni; var fin = kolicinaDestilovaneVode.toFixed(2); $("#kolVode").html("Dodati " + fin + "L destilovane vode."); if (litaraRakije == "" || trenutnoStepeni == "" || zeljenoStepeni == ""){ $("#kolVode").html("Popunite sva polja!"); } }); });
7ee5bec2eec06a1952938d408c4b0e0c77f536ef
[ "JavaScript" ]
1
JavaScript
ognjen987/rakija
5961639920930b97f705f6ca48acd7eda43b3c0f
ac98d54b5e694e88a44d9d90fe06db6603dea435
refs/heads/main
<repo_name>rubenlm25/todo-list<file_sep>/src/app/components/task-item/task-item.component.ts import { Task } from '../../Task'; import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-task-item', templateUrl: './task-item.component.html', styleUrls: ['./task-item.component.scss'] }) export class TaskItemComponent implements OnInit { @Input() task: Task; @Output() onDeleteTask: EventEmitter<Task> = new EventEmitter(); @Output() onToogleReminder: EventEmitter<Task> = new EventEmitter(); constructor() { } status:string = 'disable' ngOnInit(): void { } onDelete(task){ this.onDeleteTask.emit(task); } onToogle(task){ this.onToogleReminder.emit(task); } onMode(){ let body=document.getElementById("bcg"); let mode = body.className; return mode; } } <file_sep>/src/app/mock-task.ts import { Task } from "./Task"; export const TASKS: Task[] = [ { id: 1, text:'Complete online Javascript course', reminder: false, }, { id: 2, text:'Jog around the park 3x', reminder: false, }, { id: 3, text:'10 minutes meditation', reminder: false, }, { id: 4, text:'Read for 1 hour', reminder: false, }, { id: 5, text:'Pick up groceries', reminder: false, }, { id: 6, text:'Complete Todo App on Frontend Mentor', reminder: false, } ];<file_sep>/src/app/components/task-option/task-option.component.ts import { TaskService } from './../../services/task.service'; import { Component, Input, OnInit, Output,EventEmitter } from '@angular/core'; @Component({ selector: 'app-task-option', templateUrl: './task-option.component.html', styleUrls: ['./task-option.component.scss'] }) export class TaskOptionComponent implements OnInit { @Input() itemLeft = ''; @Output() filterArg = new EventEmitter(); @Output() clearTask = new EventEmitter(); filterTodo :string = 'all'; variableClear :boolean = true constructor(private taskService: TaskService) { } ngOnInit(): void { } onChangeFilter(params){ this.filterArg.emit(params); } filterChange(params){ this.filterTodo = params; this.onChangeFilter(params); } onClearTask(variableClear){ variableClear=!variableClear; this.clearTask.emit(variableClear); } } <file_sep>/src/app/components/tasks/tasks.component.ts import { element } from 'protractor'; import { TaskService } from '../../services/task.service'; import { Component, OnInit } from '@angular/core'; import { Task } from 'src/app/Task'; @Component({ selector: 'app-tasks', templateUrl: './tasks.component.html', styleUrls: ['./tasks.component.scss'] }) export class TasksComponent implements OnInit { tasks: Task[] = []; tasksFiltered: Task[] = []; itemLeft: number; filter: string = 'all'; constructor(private taskService: TaskService) { } ngOnInit(): void { this.taskService.getTasks().subscribe((tasks) => this.tasks = tasks); this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks); } deleteTask(task: Task){ this.taskService .deleteTask(task) .subscribe( () => (this.tasksFiltered = this.tasksFiltered.filter((t) => t.id !== task.id)) ); } toogleReminder(task: Task){ task.reminder = !task.reminder; this.taskService.updateTaskReminder(task).subscribe(); setTimeout(()=>{this.onTest(this.filter); },50) } addTask(task: Task){ this.taskService.addTask(task).subscribe((task)=>(this.tasksFiltered.push(task))); } onCount(tasks: Task[]){ let count; let taskFiltered; if(this.filter=='completed'){ taskFiltered = this.tasks.filter(tasks =>tasks.reminder == false); } else{ taskFiltered= tasks.filter(tasks =>tasks.reminder == false); } count = taskFiltered.length; this.itemLeft= count; return count; } onTest(params){ console.log('passer ici'); switch(params){ case 'all': this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks); break; case 'active' : this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks.filter(task => task.reminder == false)); break; case 'completed' : this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks.filter(task => task.reminder == true)); this.taskService.getTasks().subscribe((tasks) => this.tasks = tasks); break; default: this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks); } this.filter=params; } onClear(params){ this.taskService.getTasks().subscribe((tasks) => this.tasksFiltered = tasks); // console.log(this.tasks); let testo = this.tasksFiltered.length; // let taille = cleartask.length // console.log(taille); for(let i = 0;i<testo;i++){ if(this.tasksFiltered[i].reminder == true){ this.taskService .deleteTask(this.tasksFiltered[i]) .subscribe( () => (this.tasksFiltered = this.tasksFiltered.filter((t) => t.id !== this.tasksFiltered[i].id)) ); } } this.onTest(this.filter); console.log('done'); } } <file_sep>/src/app/components/header/header.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'] }) export class HeaderComponent implements OnInit { constructor() { } ngOnInit(): void { } modeSetup(){ if(document.getElementById("toogle").classList.contains("light")){ document.getElementsByClassName("add-form")[0].classList.replace("light","dark"); let taskItem=document.getElementsByClassName("task"); for(var i=0; i< taskItem.length; i++){ document.getElementsByClassName("task")[i].classList.replace("light","dark"); } document.getElementsByClassName("header")[0].classList.replace("light","dark"); document.getElementById("toogle").classList.replace("light","dark"); document.getElementById("bcg").classList.replace("light","dark"); document.getElementsByClassName("task-option")[0].classList.replace("light","dark"); document.getElementsByClassName("list")[0].classList.replace("light","dark"); } else if(document.getElementById("toogle").classList.contains("dark")){ document.getElementsByClassName("add-form")[0].classList.replace("dark","light"); let taskItem=document.getElementsByClassName("task"); for(var i=0; i< taskItem.length; i++){ document.getElementsByClassName("task")[i].classList.replace("dark","light"); } document.getElementsByClassName("header")[0].classList.replace("dark","light"); document.getElementById("toogle").classList.replace("dark","light"); document.getElementById("bcg").classList.replace("dark","light"); document.getElementsByClassName("task-option")[0].classList.replace("dark","light"); document.getElementsByClassName("list")[0].classList.replace("dark","light"); } } }
0d95eeb10b29165ce61de7c3667aa872c7ab6257
[ "TypeScript" ]
5
TypeScript
rubenlm25/todo-list
66bdc200815673030e43635eacdd8afd7a391376
f9b201f405381f9f9c132db0c1fbec235a6afa03
refs/heads/master
<file_sep>export const toggleStep = (id) => ({ type: 'TOGGLE_STEP', id, completed: false }) <file_sep>const TargetsApi = { learningObjectives : [ { id : 1, text: 'Write an introduction', stepsToSuccess : ['Describe characters', 'Describe setting', 'Hook in the reader'] }, { id : 2, text: 'Write a build up', stepsToSuccess : ['Build tension', 'Describe the action', 'Write in the past'] } ], all : function() { return this.learningObjectives }, get : function(num) { const isLo = lO => lO.id === num; return this.learningObjectives.find(isLo); } } export default TargetsApi<file_sep> import React from 'react'; import { Route, Link, Switch } from 'react-router-dom' import Home from '../home' import LearningObjectives from '../learningObjectives/LearningObjectives' const App = () => ( <div> <header> <Link to="/">Home</Link> <Link to="/learning-objectives">Learning Objectives</Link> </header> <main> <Switch> <Route exact path='/' component={Home} /> <Route path='/learning-objectives' component={LearningObjectives} /> </Switch> </main> </div> ) export default App<file_sep>import React from 'react' import {Switch, Route} from 'react-router-dom' import AllLearningObjectives from './index' import Lo from './Lo' const LearningObjectives = () => { return ( <Switch> <Route exact path='/learning-objectives' component={AllLearningObjectives} /> <Route path='/learning-objectives/:id' component={Lo} /> </Switch> ) } export default LearningObjectives<file_sep>import React from 'react' import {Link} from 'react-router-dom' import TargetsApi from '../../targetsApi' const AllLearningObjectives = () => { return ( <div> <ul> { TargetsApi.all().map(lO => ( <li key={lO.id}> <Link to={`/learning-objectives/${lO.id}`}>{lO.text}</Link> </li> ) ) } </ul> </div> ) } export default AllLearningObjectives
bd5145ff934998b11069ad2e52a951c7347281a5
[ "JavaScript" ]
5
JavaScript
steps-to-success/writing
0dc0c3afff90c9313aca6b314ea0073784422aa3
fb2a75c9f239985cb49cb16c77c1c19ea51e656e
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Broadway430 { class Program { static string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Broadway_43;" + "Integrated Security=true"; static void Main(string[] args) { var result = "y"; do { //Console.WriteLine("Enter the table name:"); //string tableName = Console.ReadLine(); Console.WriteLine("Enter the Choice\n1: Display the record\n2: Create the reordd\n3: Update the record\n4: Delete the reccord\n"); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); var choice = Console.ReadLine(); switch (choice) { case "1": ReadFromTable(connection); break; case "2": InsertToTable(connection); break; case "3": UpdateToTable(connection); break; case "4": DeleteFromTable(connection); break; default: break; } connection.Close(); } Console.WriteLine("Want to try more (y/n)?"); result = Console.ReadLine(); } while (result == "y" || result == "Y"); Console.ReadLine(); } private static void ReadFromTable(SqlConnection connection) { // Provide the query string with a parameter placeholder. string queryString = "select * from Student"; // Create the Command and Parameter objects.// SqlCommand command = new SqlCommand(queryString, connection); try { SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { var readers = new string[] { reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString() }; Console.WriteLine(string.Join(",", readers)); } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } private static void InsertToTable(SqlConnection connection) { Console.WriteLine("Enter Name"); var name = Console.ReadLine(); Console.WriteLine("Enter Email"); var email = Console.ReadLine(); Console.WriteLine("Enter Age"); var age = Console.ReadLine(); string queryString = $"Insert into Student (Name, Email,Age) values ('{name}','{email}','{age}')"; // Create the Command and Parameter objects. SqlCommand command = new SqlCommand(queryString, connection); try { var res = command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } private static void UpdateToTable(SqlConnection connection) { Console.WriteLine("Enter the id of the record to update"); var id = Console.ReadLine(); Console.WriteLine("Enter name:"); var name = Console.ReadLine(); Console.WriteLine("Enter email:"); var email = Console.ReadLine(); Console.WriteLine("Enter Age:"); var Age = Console.ReadLine(); string queryString = $"update Student set name=('{name}'),email=('{email}'),Age=('{Age}') where id=('{id}') "; SqlCommand command = new SqlCommand(queryString, connection); try { var res = command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } private static void DeleteFromTable(SqlConnection connection) { Console.WriteLine("Enter the id of the record to be deleted"); var id = Console.ReadLine(); string queryString = $"delete from Student where id=('{id}')"; SqlCommand command = new SqlCommand(queryString, connection); try { var res = command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadLine(); } } } <file_sep>using MongoDB.Driver.Core.Configuration; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Broadways.Desktop { public partial class Form1 : Form { private string ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Broadway_43;" + "Integrated Security=true"; public Form1() { InitializeComponent(); ReloadData(); } private void ReadFromTable(SqlConnection connection) { // Provide the query string with a parameter placeholder. string queryString = "select * from Student"; // Create the Command and Parameter objects.// SqlCommand command = new SqlCommand(queryString, connection); try { SqlDataReader reader = command.ExecuteReader(); List<Student> students = new List<Student>(); while (reader.Read()) { // var readers = new string[] { reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString() }; //todo: need to update this students.Add(new Student { id = (int)reader[0], name = reader[1].ToString(), email = reader[2].ToString(), Age=(int)reader[3] }) ; // Console.WriteLine(string.Join(",", readers)); } reader.Close(); dataGridView1.DataSource =students ; dataGridView1.Refresh(); } catch (Exception ex) { Console.WriteLine(ex.Message); } // Console.ReadLine(); } private void InsertToTable(SqlConnection connection) { var name = textBox1.Text; var email =textBox2.Text; var age = textBox3.Text; string queryString = $"Insert into Student (Name, Email,Age) values ('{name}','{email}','{age}')"; // Create the Command and Parameter objects. SqlCommand command = new SqlCommand(queryString, connection); try { var res = command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Console.ReadLine(); } private void UpdateToTable(SqlConnection connection) { var name = textBox1.Text; var email = textBox2.Text; var Age = textBox3.Text; string queryString = $"update Student set email=('{email}'),Age=('{Age}') where name=('{name}') "; SqlCommand command = new SqlCommand(queryString, connection); try { var res = command.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } // Console.ReadLine(); } private void deletefromtable(SqlConnection connection) { if (selectedId==0) { MessageBox.Show("Id is 0, unable to find the record"); return; } //var name= textBox1.Text; string querystring = $"delete from student where id=('{selectedId}')"; SqlCommand command = new SqlCommand(querystring, connection); try { var res = command.ExecuteNonQuery(); ReloadData(); } catch (Exception ex) { Console.WriteLine(ex.Message); } // console.readline(); } private void button1_Click(object sender, EventArgs e) { ReloadData(); } void ReloadData() { using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); ReadFromTable(connection); connection.Close(); } } private void button2_Click(object sender, EventArgs e) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); InsertToTable(connection); connection.Close(); ReloadData(); } } private void button3_Click(object sender, EventArgs e) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); UpdateToTable(connection); connection.Close(); ReloadData(); } } int selectedId = 0; private void button4_Click(object sender, EventArgs e) { using (SqlConnection connection = new SqlConnection(ConnectionString)) { connection.Open(); deletefromtable(connection); connection.Close(); ReloadData(); } } private void dataGridView1_DoubleClick(object sender, EventArgs e) { var selected =dataGridView1.SelectedRows; selectedId = (int)selected[0].Cells[0].Value; textBox1.Text= (string)selected[0].Cells[1].Value; } } //Creating models public class Student { public int id { get; set; } public string name { get; set; } public string email { get; set; } public int Age { get; set; } } }
96c714e9bc56266a4e8a1a17d3a029479897f033
[ "C#" ]
2
C#
anchallama/insertupdatedelete
43862cde7207464ecd48278b1f57c60c316788ff
8bb879bccdb9ed09a3b53cd087333f237c144ef1
refs/heads/master
<repo_name>nvenkov1/lanczos-restart-strategies<file_sep>/lanczos.py import numpy as np import scipy.sparse as sparse import scipy.sparse.linalg def lanczos(A, npairs, m=50, q1=None, reortho=None, eigvals=None): # Implementation #1 : Algo. 7.1 (Demmel, 1997); # ( we use this ) Algo. 10.1.1 (Golub, 2012) # (implementation) Sec. 10.3.1 (Golub, 2012)---verison w. lighter storage # # Implementation #2 : Sec. 13.1 (Parlett, 1980); # (greater stability) Algo. 6.5 (Saad, 2011); # # Links between variants : A({1,2},{6,7}) (Paige, 1972) # Algo. 36.1 (Trefethen and Bau, 1997) # # Preferred references : Chap. 13.{1,2,7} (Parlett, 1980) # 10.3.1 (Golub, 2012) # alpha = np.zeros(m) # (al_1, ..., al_m) beta = np.zeros(m+1) # (be_0, ..., be_m), be_0 := 0 # T_j = sparse.diags(([be_1, ..., be_{j-1}], # (j-by-j) [al_1, ..., al_{j}] # [be_1, ..., be_{j-1}]), (-1,0,1)) n = A.shape[0] Q = np.zeros((n, m+1)) # Initialize first Lanczos vector if not isinstance(q1, np.ndarray): q1 = np.random.rand(n) q1 /= np.linalg.norm(q1) Q[:,0] = q1 if isinstance(eigvals, np.ndarray): data = {"approx_eigvecs":[], "approx_eigvals":[], "iterated_error_bound":[]} for j in range(m): u = A.dot(Q[:,j]) alpha[j] = Q[:,j].dot(u) u -= alpha[j]*Q[:,j] if (j > 0): u -= beta[j]*Q[:,j-1] if (reortho != None) & (j > 1): if (reortho == "full"): for _ in range(2): for k in range(j): u -= u.dot(Q[:,k])*Q[:,k] elif (reortho == "selective"): for k in range(j): if (beta[j]*abs(S[j-1,k]) < tol): u -= u.dot(Y[:,k])*Y[:,k] beta[j+1] = np.linalg.norm(u) Q[:,j+1] = u/beta[j+1] # Get eigenpairs from tridiagonal if (j > 0): # For T_2, ..., T_m theta, S = scipy.linalg.eigh_tridiagonal(alpha[:j+1], beta[1:j+1], select="a") # theta[0] <= ... <= theta[j] if (reortho == "selective"): Tnorm = theta[j]/theta[0] tol = np.finfo(float).eps**.5*Tnorm Y = Q[:,:j+1].dot(S) data["approx_eigvecs"] += [Y[:,-1::-1]] data["approx_eigvals"] += [theta[-1::-1]] data["iterated_error_bound"] += [np.abs(beta[j+1]*S[j,-1::-1])] if not isinstance(eigvals, np.ndarray): return approx_eigvecs, approx_eigvals, iterated_error_bound else: return data<file_sep>/examples/example01_lanczos.py import sys; sys.path += ["../"] from lanczos import lanczos import numpy as np import time from example01_lanczos_plot import * n = 1000 A = np.random.rand(n, n) A = A.dot(A.T) m = 50 npairs = 10 #eigvals = np.linalg.eigvalsh(A)[-1::-1] eigvals, eigvecs = np.linalg.eigh(A) eigvals = eigvals[-1::-1] eigvecs = eigvecs[:,-1::-1] q1 = None#eigvecs[:,4]+np.random.rand(n)*.005 t0 = time.time() data = lanczos(A, npairs, q1=q1, m=m, eigvals=eigvals) print("No reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() data_full = lanczos(A, npairs, q1=q1, m=m, reortho="full", eigvals=eigvals) print("Full reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() data_selective = lanczos(A, npairs, q1=q1, m=m, reortho="selective", eigvals=eigvals) print("Selective reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() approx_eigvals, approx_eigvals_full, approx_eigvals_selective = [], [], [] iterated_error_bound, iterated_error_bound_full, iterated_error_bound_selective = [], [], [] for i in range(m): approx_eigvals += [i*[None]+[d[i] for d in data["approx_eigvals"][i:]]] approx_eigvals_full += [i*[None]+[d[i] for d in data_full["approx_eigvals"][i:]]] approx_eigvals_selective += [i*[None]+[d[i] for d in data_selective["approx_eigvals"][i:]]] iterated_error_bound += [i*[None]+[d[i] for d in data["iterated_error_bound"][i:]]] iterated_error_bound_full += [i*[None]+[d[i] for d in data_full["iterated_error_bound"][i:]]] iterated_error_bound_selective += [i*[None]+[d[i] for d in data_selective["iterated_error_bound"][i:]]] approx_eigvals = np.array(approx_eigvals) approx_eigvals_full = np.array(approx_eigvals_full) approx_eigvals_selective = np.array(approx_eigvals_selective) iterated_error_bound = np.array(iterated_error_bound) iterated_error_bound_full = np.array(iterated_error_bound_full) iterated_error_bound_selective = np.array(iterated_error_bound_selective) plot(m, eigvals, approx_eigvals, approx_eigvals_full, approx_eigvals_selective, iterated_error_bound, iterated_error_bound_full, iterated_error_bound_selective) # TO DO: # T1: MAKE IT AS FAST AS POSSIBLE! # T2: ALLOW for npairs <= m # T3: Implement restart strategies. # Q1: HOW TO PICK m for a given npairs? # You can not know this, see p. 239-240 of Dongara et al.'s book. # m is fixed by the memory available. # after tridiagolnalization is completed for some m, only some values are converged, which ones? # how do you restart to obtain other approximate values?<file_sep>/README.tex.md # lanczos-restart-strategies #### Enables testing and applications of restarting strategies for Lanczos tridiagonalizations used in solving sequences of eigenvalue problems. Author: <NAME> email: [<EMAIL>](mailto:<EMAIL>) _TeX expressions rendered by [TeXify](https://github.com/apps/texify)._ ### Dependencies: - *Python* (2.x >= 2.6) - *SciPy* (>= 0.11) - *NumPy* (>= 1.6) ### Files' content: Files: _lanczos.py_. Classes: `lanczos`. - _lanczos.py_ : Signature : `lanczos`(`m`) Public methods : `method`(`self`). ### Usage: Examples: - _example01_lanczos.py_ : Use of the `lanczos` class to investigate the effect of full and selective reorthogonalization on the evolution of approximate eigenvalues. #### Example #1: example01_lanczos.py Investigates the effect of full and selective reorthogonalization on the evolution of approximate eigenvalues. ```python import sys; sys.path += ["../"] from lanczos import lanczos import numpy as np import time from example01_lanczos_plot import * n = 1000 A = np.random.rand(n, n) A = A.dot(A.T) m = 50 npairs = 10 eigvals = np.linalg.eigvalsh(A)[-1::-1] t0 = time.time() data = lanczos(A, npairs, m=m, eigvals=eigvals) print("No reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() data_full = lanczos(A, npairs, m=m, reortho="full", eigvals=eigvals) print("Full reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() data_selective = lanczos(A, npairs, m=m, reortho="selective", eigvals=eigvals) print("Selective reorthogonalization : %g" %(time.time()-t0)); t0 = time.time() approx_eigvals, approx_eigvals_full, approx_eigvals_selective = [], [], [] iterated_error_bound, iterated_error_bound_full, iterated_error_bound_selective = [], [], [] for i in range(m): approx_eigvals += [i*[None]+[d[i] for d in data["approx_eigvals"][i:]]] approx_eigvals_full += [i*[None]+[d[i] for d in data_full["approx_eigvals"][i:]]] approx_eigvals_selective += [i*[None]+[d[i] for d in data_selective["approx_eigvals"][i:]]] iterated_error_bound += [i*[None]+[d[i] for d in data["iterated_error_bound"][i:]]] iterated_error_bound_full += [i*[None]+[d[i] for d in data_full["iterated_error_bound"][i:]]] iterated_error_bound_selective += [i*[None]+[d[i] for d in data_selective["iterated_error_bound"][i:]]] approx_eigvals = np.array(approx_eigvals) approx_eigvals_full = np.array(approx_eigvals_full) approx_eigvals_selective = np.array(approx_eigvals_selective) iterated_error_bound = np.array(iterated_error_bound) iterated_error_bound_full = np.array(iterated_error_bound_full) iterated_error_bound_selective = np.array(iterated_error_bound_selective) plot(m, eigvals, approx_eigvals, approx_eigvals_full, approx_eigvals_selective, iterated_error_bound, iterated_error_bound_full, iterated_error_bound_selective) ``` Output : ![example01_lanczos_a](./figures/example01_lanczos_a.png) ![example01_lanczos_b](./figures/example01_lanczos_b.png) ![example01_lanczos_c](./figures/example01_lanczos_c.png) Observations : Ghost (repeating) eigenvalues appear when no reorthogonalization is applied. Memory requirements increase with $m$. Restart becomes necessary. <file_sep>/examples/example01_lanczos_plot.py import sys; sys.path += ["../"] from lanczos import lanczos import numpy as np import pylab as pl pl.rcParams['text.usetex'] = True params={'text.latex.preamble':[r'\usepackage{amssymb}',r'\usepackage{amsmath}']} figures_path = '../figures/' def plot(m, eigvals, approx_eigvals, approx_eigvals_full, approx_eigvals_selective, iterated_error_bound, iterated_error_bound_full, iterated_error_bound_selective): fig, ax = pl.subplots(1, 3, figsize=(11,3.4), sharey="row") lw = .8 ax[0].set_title("No reorthogonalization") for i in range(m): ax[0].semilogy(range(1,m), approx_eigvals[i,:], "+") for i in range(m): ax[0].semilogy(range(1,m), approx_eigvals[i,:], "-", lw=lw) ax[0].semilogy(eigvals.shape[0]*[m+3], eigvals, "k_", lw=0) ax[1].set_title("Full reorthogonalization") for i in range(m): ax[1].semilogy(range(1,m), approx_eigvals_full[i,:], "+") for i in range(m): ax[1].semilogy(range(1,m), approx_eigvals_full[i,:], "-", lw=lw) ax[1].semilogy(eigvals.shape[0]*[m+3], eigvals, "k_", lw=0) ax[2].set_title("Selective reorthogonalization") for i in range(m): ax[2].semilogy(range(1,m), approx_eigvals_selective[i,:], "+") for i in range(m): ax[2].semilogy(range(1,m), approx_eigvals_selective[i,:], "-", lw=lw) for j in range(3): ax[j].grid() ax[2].semilogy(eigvals.shape[0]*[m+3], eigvals, "k_", lw=0) ax[1].set_ylim(ax[0].get_ylim()); ax[2].set_ylim(ax[0].get_ylim()) ax[0].set_ylabel("Approximate eigenvalues") fig.suptitle("Approximate eigenvalues, "+r"$\{\lambda_i(T_m)\}_{i=1}^m$") ax[0].set_xlabel("m"); ax[1].set_xlabel("m"); ax[2].set_xlabel("m") pl.savefig(figures_path+"example01_lanczos_a.png", bbox_inches='tight') #pl.show() fig, ax = pl.subplots(1, 3, figsize=(11,3.4), sharey="row") lw = .8 ax[0].set_title("No reorthogonalization") for i in range(m): ind = (iterated_error_bound[i,:]==None).sum() ax[0].semilogy(range(1,m), np.concatenate((iterated_error_bound[i,:ind],iterated_error_bound[i,ind:]/approx_eigvals[i,ind:])), "-", lw=lw) ax[1].set_title("Full reorthogonalization") for i in range(m): ind = (iterated_error_bound_full[i,:]==None).sum() ax[1].semilogy(range(1,m), np.concatenate((iterated_error_bound_full[i,:ind],iterated_error_bound_full[i,ind:]/approx_eigvals_full[i,ind:])), "-", lw=lw) ax[2].set_title("Selective reorthogonalization") for i in range(m): ind = (iterated_error_bound_selective[i,:]==None).sum() ax[2].semilogy(range(1,m), np.concatenate((iterated_error_bound_selective[i,:ind],iterated_error_bound_selective[i,ind:]/approx_eigvals_selective[i,ind:])), "-", lw=lw) ax[1].set_ylim(ax[0].get_ylim()); ax[2].set_ylim(ax[0].get_ylim()) ax[0].set_ylim(1e-16,1e2) ax[0].set_ylabel("Iterated relative error bound") fig.suptitle("Iterated relative error bound, "+r"$\{|\beta_mS_{mi}/\lambda_i(T_m)|\}_{i=1}^m$") for j in range(3): ax[j].set_xlabel("m") ax[j].grid() pl.savefig(figures_path+"example01_lanczos_b.png", bbox_inches='tight') #pl.show() fig, ax = pl.subplots(1, 3, figsize=(11,3.4), sharey="row") lw = .8 ax[0].set_title("No reorthogonalization") for i in range(m): ind = (approx_eigvals[i,:]==None).sum() ax[0].semilogy(range(1,m), np.concatenate((approx_eigvals[i,:ind],np.abs((approx_eigvals[i,ind:]-eigvals[i])/eigvals[i]))), "-", lw=lw) ax[1].set_title("Full reorthogonalization") for i in range(m): ind = (approx_eigvals_full[i,:]==None).sum() ax[1].semilogy(range(1,m), np.concatenate((approx_eigvals_full[i,:ind],np.abs((approx_eigvals_full[i,ind:]-eigvals[i])/eigvals[i]))), "-", lw=lw) ax[2].set_title("Selective reorthogonalization") for i in range(m): ind = (approx_eigvals_selective[i,:]==None).sum() ax[2].semilogy(range(1,m), np.concatenate((approx_eigvals_selective[i,:ind],np.abs((approx_eigvals_selective[i,ind:]-eigvals[i])/eigvals[i]))), "-", lw=lw) ax[0].set_ylabel("Global error") fig.suptitle("Global error, "+r"$\{|\lambda_i(T_m)-\lambda_i(A)|/|\lambda_i(A)|\}_{i=1}^m$") for j in range(3): ax[j].set_xlabel("m") ax[j].grid() pl.savefig(figures_path+"example01_lanczos_c.png", bbox_inches='tight') #pl.show()
add55778c1d3c0107eb4e1ed6991d05f6aca25fd
[ "Markdown", "Python" ]
4
Python
nvenkov1/lanczos-restart-strategies
9aec8e9c614d9fb1509c1c814d6372a116d7fa67
6cb9492dff8561d2cd09d1db73e844fec8e6b1bc
refs/heads/master
<repo_name>josephtinsley/SimplePHPFramework<file_sep>/index.php <?PHP require_once 'application/config/config.php'; require_once 'application/route.php'; function __autoload($class_name) { require_once 'application/config/'.$class_name.'.php'; } route::getRoute(); <file_sep>/application/controllers/index_controllers.php <?PHP Class index_controllers extends BaseController{ public function __construct() { parent::__construct(); } public function index(){ BaseController::$view->_sitename = SITE_NAME; BaseController::$view->_title = 'Home Page'; BaseController::$view->_meta_description = 'Meta Description goes here'; BaseController::$view->_meta_keywords = 'Page Keywords goes here'; BaseController::$view->_greeting = 'Hello World! Welcome to our home page'; BaseController::$view->display('index/index'); } }//END CLASS <file_sep>/application/controllers/about_controllers.php <?PHP Class about_controllers extends BaseController{ public function __construct() { parent::__construct(); } public function index(){ BaseController::$view->_sitename = SITE_NAME; BaseController::$view->_title = 'About Page'; BaseController::$view->_meta_description = 'Meta Description goes here'; BaseController::$view->_meta_keywords = 'Page Keywords goes here'; BaseController::$view->_greeting = 'Hello World! Welcome to our about page'; BaseController::$view->_profile_names = $this->show_profile_names(); BaseController::$view->_sample_form = $this->show_sample_form(); BaseController::$view->display('about/index'); } private function show_profile_names() { BaseController::Model('about'); $retVal = about_models::get_profile_names(); $html ='<ul>'."\n"; for ($x = 0; $x < count($retVal); $x++) { $html .='<li>'.$retVal[$x]['f_name'] .':'.$retVal[$x]['l_name'].'</li>'."\n"; } $html .='</ul>'."\n"; return $html; } private function show_sample_form() { require_once CLASSES.'ClassSampleForm.php'; return SampleForm::form(); } }//END CLASS<file_sep>/application/models/about_models.php <?php class about_models extends BaseModel { public function index(){ return false; } public static function get_profile_names(){ $results = db::conn()->sql_query("SELECT", "SELECT f_name, l_name FROM profile"); $rows = db::conn()->query_rows($results); return ( count($rows) >0 )? $rows: false; } }//END CLASS <file_sep>/application/route.php <?PHP Class route { private static $default_request = 'index'; private static $request; public static $route; /* MAY HAVE TO USE $_SERVER['ORIG_PATH_INFO'] INSTEAD OF $_SERVER['PATH_INFO'] */ private static function setRequest() { self::$request = ( isset($_SERVER['PATH_INFO']) )? trim($_SERVER['PATH_INFO'],'/'): self::$default_request; } public static function getRoute() { global $params, $controller_class_name, $controller; self::setRequest(); if( self::$request === self::$default_request ) { self::$request = self::$default_request; } if( self::$request[0] == '_' ) { self::$request = str_replace('/','_',self::$request); } $params = explode('/',self::$request); if( file_exists( CONTROLLER. $params[0] . '_controllers.php' ) ) { require_once CONTROLLER. $params[0] . '_controllers.php'; $controller_class_name = $params[0]."_controllers"; }else { require_once CONTROLLER. 'error_controllers.php'; $controller_class_name = "error_controllers"; } /* CALL CONTROLLER CLASS */ $controller = new $controller_class_name; $controller->index(); self::$route = str_replace('/', '_',self::$request); } }//END CLASS<file_sep>/application/config/BaseView.php <?php class BaseView { public function display($name) { require_once 'application/views/'.$name.'.php'; } } ?> <file_sep>/application/config/config.php <?PHP // GLOBALLY REQUIRED ITEMS. define('ROOT', $_SERVER["DOCUMENT_ROOT"] . DIRECTORY_SEPARATOR.'SimplePHPFramework/'); define('SITE_NAME','SimplePHPFramework'); define('URL','http://localhost/SimplePHPFramework/'); define('DOMAIN','SimplePHPFramework.com'); define('MODEL', ROOT.'application/models/'); define('VIEW', ROOT.'application/views/'); define('CONTROLLER', ROOT.'application/controllers/'); define('CLASSES', ROOT.'application/classes/'); define('CSS', URL.'public/css/'); define('IMG', URL.'public/image/'); define('JS', URL.'public/js/');<file_sep>/application/views/error/index.php <!DOCTYPE html> <html> <head> <title><?php echo $this->_title;?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" content="<?php echo $this->_meta_description;?>"> <meta name="Keywords" content="<?php echo $this->_meta_keywords;?>"> <link href="public/css/reset.css" rel="stylesheet" type="text/css"> <link href="public/css/style.css" rel="stylesheet" type="text/css"> <script src="public/js/script.js"></script> </head> <body> <div class="header"> <div class="site-name"><?php echo $this->_sitename;?></div> </div> <div class="nav"> <div class="nav-links"> <a href="./">Home</a> <a href="./about">About</a> <a href="./contact">Contact</a> </div> </div> <div class="content curve-border5 center"> <h1 class="font32"><?PHP echo $this->_h1;?></h1> <p><?PHP echo $this->_content;?></p> </div> </body> </html> <file_sep>/application/classes/ClassSampleForm.php <?PHP Class SampleForm { public static function form() { $html='<table class="sample-form">'."\n"; $html.='<tr><td class="font18">First Name:</td> <td><input type="text" /></td> </tr>'."\n"; $html.='<tr><td class="font18">Last Name:</td> <td><input type="text" /></td> </tr>'."\n"; $html.='<tr><td>&nbsp;</td><td><button class="curve-border5 submit-button">Fake Button</button></td></tr>'."\n"; $html.='</table><!-- End Form -->'; return $html; } }//END CLASS<file_sep>/public/js/scripts.js function goURL(theUrl) { document.location.href = theUrl; } <file_sep>/application/config/db.php <?PHP Class DB { /* MAC CONFIG */ const Server = 'localhost'; const dbUser = "root"; const dbPass = "<PASSWORD>"; const dbName = "spf"; const SALT = 'supercalifragilisticexpialidocious'; private static $instance; private function __construct() { } public static function conn() { global $conne; if( !isset(self::$instance) ){ $conne = mysql_connect(self::Server, self::dbUser, self::dbPass) or die("Could not connect to localhost"); mysql_select_db(self::dbName, $conne) or die("Could not select database"); self::$instance = new db(); } return self::$instance; } public function sql_query($sql_type, $sql) { switch (strtolower($sql_type)) { case "delete" : $results = mysql_query($sql) or $this->_log_error( "Delete Error: ".mysql_error() ." SQL:->$sql" ); return $results; break; case "update" : $results = mysql_query($sql) or $this->_log_error( "Update Error: ".mysql_error() ." SQL:->$sql" ); return $results; break; case "insert" : $results = mysql_query($sql) or $this->_log_error( "Insert Error: ".mysql_error() ." SQL:->$sql" ); return $results; break; case "select" : $results = mysql_query($sql) or $this->_log_error( "Select Error: ".mysql_error() ." SQL:->$sql" ); return $results; break; } } public function query_rows($results) { $this->rows = null; // CLEARING OBJECT HERE. while ($row = mysql_fetch_array($results)) { $this->rows[] = $row; } return $this->rows; } public function close_conn() { mysql_close(); } public function mysql_free_result($results) { mysql_free_result($results); } public function _log_error($str) { $timeStamp = date("Ydmhis"); $fd = fopen(ROOT."_mysql_err_{$timeStamp}.txt", 'w'); $out = print_r($str , true); fwrite($fd, $out); } } //END CLASS<file_sep>/application/models/contact_models.php <?PHP class contact_models extends BaseModel { public function index(){ return false; } }//END CLASS <file_sep>/application/controllers/contact_controllers.php <?PHP Class contact_controllers extends BaseController{ public function __construct() { parent::__construct(); } public function index(){ BaseController::$view->_sitename = SITE_NAME; BaseController::$view->_title = 'Contact Page'; BaseController::$view->_meta_description = 'Meta Description goes here'; BaseController::$view->_meta_keywords = 'Page Keywords goes here'; BaseController::$view->_greeting = 'Hello World! Welcome to our contact page'; BaseController::$view->display('contact/index'); } }//END CLASS <file_sep>/application/config/BaseController.php <?php Class BaseController { CONST path = 'application/models/'; Protected static $view; Protected static $Model; public function __construct() { self::$view = new BaseView(); } public static function Model($name) { $file_name = self::path . $name.'_models.php'; if (file_exists($file_name)) { require_once "$file_name"; $model_class_name = $name . '_models'; self::$Model = new $model_class_name; return false; } else{ return false; } } }//END CLASS ?><file_sep>/application/config/BaseModel.php <?php class BaseModel { function __construct() { db::conn(); //MYSQL DATABASE } } ?><file_sep>/application/controllers/error_controllers.php <?PHP Class error_controllers extends BaseController{ public function __construct() { parent::__construct(); } public function index(){ BaseController::Model('error'); BaseController::$view->_sitename = SITE_NAME; BaseController::$view->_title = 'Error Page'; BaseController::$view->_meta_description = 'Meta Description goes here'; BaseController::$view->_meta_keywords = 'Page Keywords goes here'; BaseController::$view->_h1 = 'Error Page'; BaseController::$view->_content = 'This is the error page'; BaseController::$view->display('error/index'); } }//END CLASS
055bfb5c861a200a66c5fea16061e667aea645ea
[ "JavaScript", "PHP" ]
16
PHP
josephtinsley/SimplePHPFramework
0480e022153f339d28bf594b994a2bba971a45bb
ffa5462a3cc556e1bb3c4e176a848d4f3127b13e
refs/heads/master
<repo_name>tonny0531/VoiceAlert_Source<file_sep>/src/app/app.component.ts import { Component, ElementRef, ViewChild } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { audio = new Audio(); title = 'alert-voice'; sub: Subscription; source = interval(3000); ngOnInit(): void { this.audio.src = 'assets/babubabu.mp3'; this.audio.load(); } play(): void { this.audio.play(); this.sub = this.source.subscribe(v => { console.log('log'); this.audio.play(); }); } stop(): void { console.log('stop'); if (this.sub){ this.sub.unsubscribe(); } } }
296873171dddbf7d69fa373f8dd1227b11bfdb70
[ "TypeScript" ]
1
TypeScript
tonny0531/VoiceAlert_Source
f16df991a0e1d24148d6d3b189020b01e3d5ad06
bcb650a53d826bae62879a23f6a096ce6e62d42e
refs/heads/master
<repo_name>UCL-EO/QA4ECV_ATBD<file_sep>/notebooks/defaults.py import sys import os # where is the python directory? one of these probably for pp in ['.','python','../python','../../python']: try: ppp = os.path.abspath(pp) sys.path.insert(1,ppp) except: pass # add the python directory import pylab as plt import numpy as np from glob import glob import pandas as pd import netCDF4 from netCDF4 import Dataset import urllib2 from HTMLParser import HTMLParser import os import pickle import kernels import datetime from datetime import date,timedelta import scipy.sparse import scipy.stats def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) def save_obj(obj, name ): with open(name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL) def load_obj(name ): with open(name + '.pkl', 'rb') as f: return pickle.load(f) scale = 1.0 datadir = os.path.abspath('../data') print 'data directory',datadir ''' Codes to pull netcdf files from the server ''' # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): # see https://docs.python.org/2/library/htmlparser.html def handle_starttag(self, tag, attrs): pass; #print "Encountered a start tag:", tag def handle_endtag(self, tag): pass #print "Encountered an end tag :", tag def handle_data(self, data): data = data.strip() if len(data) and data[-1] == '/': # is it a directory? try: self.datadirs.append(data) except: self.datadirs = [data] if len(data) and data.split('.')[-1] == 'nc': # is it a nc file? try: self.ncfiles.append(data) except: self.ncfiles = [data] def getdirs(db): # get directories from url response = urllib2.urlopen(db,None,120) parser = MyHTMLParser() html = response.read() del response parser.feed(html) return parser def nc_urls(db): ''' obtain full list of data urls of nc files ''' ncfiles = {} parser = getdirs(db) for sensor in parser.datadirs: ncfiles[sensor] = [] parser2 = getdirs(db+sensor) if hasattr(parser2, 'datadirs'): for sub0 in parser2.datadirs: parser3 = getdirs(db+sensor+sub0) if hasattr(parser3, 'datadirs'): for sub1 in parser3.datadirs: parser4 = getdirs(db+sensor+sub0+sub1) if hasattr(parser4, 'datadirs'): print 'deepest level checked' if hasattr(parser4, 'ncfiles'): for nc in parser4.ncfiles: ncfiles[sensor].append(db+sensor+sub0+sub1+nc) if hasattr(parser3, 'ncfiles'): for nc in parser3.ncfiles: ncfiles[sensor].append(db+sensor+sub0+nc) if hasattr(parser2, 'ncfiles'): for nc in parser2.ncfiles: ncfiles[sensor].append(db+sensor+nc) return ncfiles def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) def obtain_data(db,doit=True): print 'connecting to',db ncfiles = nc_urls(db) print 'got urls' nclocals = {} datakeys = ncfiles.keys() for k in datakeys: print k ensure_dir(k) nclocals[k] = [] for ncfile in ncfiles[k]: print '.', if doit: data = urllib2.urlopen(ncfile).read() local = ncfile.split('/')[-1] nclocals[k].append(local) # write if doit: f = open(k+local,'wb') f.write(data) f.close() for k in nclocals.keys(): if k[-1] == '/': nclocals[k.strip('/')] = nclocals[k] del nclocals[k] return nclocals <file_sep>/README.md # QA4ECV Algorithm Theoretical Basis Document P.Lewis UCL/NCEO # Contents - [Download and sort data](https://github.com/UCL-EO/QA4ECV_ATBD/tree/master/notebooks/Get%20data.ipynb) In this section, we download the test dataset from the server as a set of `netcdf` files and harmonise most of the labelling across datasets. We also perform narrow to broadband conversion on the MODIS datasets, apply QA masks and do any scaling. The result of this is set of `pickle` (storage) `s1.0` (i.e. 'stage 1.0' of processing, which is really just a dump from the netcdf files for a single pixel in time) files containing the original data: notebooks/obj/bbdr.flags_s1.0_.pkl notebooks/obj/bbdr.meris_s1.0_.pkl notebooks/obj/bbdr.vgt_s1.0_.pkl notebooks/obj/ga.brdf.merge_s1.0_.pkl notebooks/obj/ga.brdf.nosnow_s1.0_.pkl notebooks/obj/ga.brdf.snow_s1.0_.pkl notebooks/obj/mod09_s1.0_.pkl notebooks/obj/myd09_s1.0_.pkl notebooks/obj/prior.v2.nosnow_s1.0_.pkl notebooks/obj/prior.v2.snow_s1.0_.pkl notebooks/obj/prior.v2.snownosnow_s1.0_.pkl and a set of `s2.0` files containing the masked and organised datasets. notebooks/obj/bbdr.flags_s2.0_.pkl notebooks/obj/bbdr.meris_s2.0_.pkl notebooks/obj/bbdr.vgt_s2.0_.pkl notebooks/obj/ga.brdf.merge_s2.0_.pkl notebooks/obj/ga.brdf.nosnow_s2.0_.pkl notebooks/obj/ga.brdf.snow_s2.0_.pkl notebooks/obj/mod09_s2.0_.pkl notebooks/obj/myd09_s2.0_.pkl notebooks/obj/prior.v2.nosnow_s2.0_.pkl notebooks/obj/prior.v2.snow_s2.0_.pkl notebooks/obj/prior.v2.snownosnow_s2.0_.pkl - [Load data and and prepare constraint matrices](https://github.com/UCL-EO/QA4ECV_ATBD/tree/master/notebooks/Load%20data.ipynb) This section reads the data from the `s2.0` files and organises into `s3.0` files, with the data organised as matrices: notebooks/obj/bbdr.meris_s3.0_.pkl notebooks/obj/bbdr.vgt_s3.0_.pkl notebooks/obj/mod09_s3.0_.pkl notebooks/obj/myd09_s3.0_.pkl The `s3.0` files are slimmed down sources of processed information. You can do all of the modelling and inversion with these files alone (other than e.g. comparison with original reflectance data for e.g. outlier detection). They contain *only* the following keys: ['kernels', 'weight', 'idoy', 'doy', 'refl', 'year', 'date'] which is the critical information for modelling organised appropriately. In this section, we also prepare matrices for other constraints we might want and the `A` and `b` matrices (full size, sparse representations). At present, these (`Ab` files) are: notebooks/obj/D1_Ab_.pkl notebooks/obj/D365_Ab_.pkl notebooks/obj/bbdr.meris_Ab_.pkl notebooks/obj/bbdr.vgt_Ab_.pkl notebooks/obj/myd09_Ab_.pkl notebooks/obj/mod09_Ab_.pkl notebooks/obj/prior.v2.nosnow_Ab_.pkl notebooks/obj/prior.v2.snow_Ab_.pkl The files `D1_Ab` and `D365_Ab` contain differential constraint (sparse) matrices for imposing smoothness in time. <file_sep>/python/grab_kernels.py import numpy as np import matplotlib.pyplot as plt from kernels import Kernels years = [ 2005 ] months = np.arange(1,13) QA_OK = np.array([8, 72, 136, 200, 1032, 1288, 2056, 2120, 2184, 2248]) for year in years: nsamples = 0 for month in months: fname = "MODIS_BRDF/hainich_%04d_%02d.txt" % ( year, month ) reflt = np.loadtxt ( fname, delimiter=";", usecols=np.arange(15,22) )/10000. nsamples += reflt.shape[0] doys = np.empty ( nsamples ) qa = np.empty ( nsamples ) qa_pass = np.empty ( nsamples ) refl = np.empty ( (nsamples,7) ) angs = np.empty ( (nsamples,4) ) istart = 0 for month in months: print "->%d, %d<-" % ( year, month ) fname = "MODIS_BRDF/hainich_%04d_%02d.txt" % ( year, month ) doyt = np.loadtxt ( fname, delimiter=";", usecols=[2] ) - year*1000 n = len(doyt) doys[istart:(istart+n)] = doyt reflt = np.loadtxt ( fname, delimiter=";", usecols=np.arange(15,22) )/10000. refl[istart:(istart+n),:] = reflt angst = np.loadtxt ( fname, delimiter=";", usecols=np.arange (11,15))/100. angs[istart:(istart+n), :] = angst #angs are sza,vza,saa,vaa qa1kt = np.loadtxt ( fname, delimiter=";", usecols=[10] ) qa[istart:(istart+n)] = qa1kt qa_passt = np.logical_or.reduce([qa1kt == x for x in QA_OK ]) qa_passt = qa_passt.astype(np.int8) qa_pass[istart:(istart+n)] = qa_passt istart = istart + n #K_obs = Kernels( angs[:,1], angs[:,0], angs[:,2] - angs[:,3], \ #LiType='Sparse', doIntegrals=False, \ #normalise=1, RecipFlag=True, RossHS=False, MODISSPARSE=True, \ #RossType='Thick' ) qa_pass = qa_pass.astype ( np.bool ) K_obs = Kernels(angs[:,1], angs[:,0], angs[:,2] - angs[:,3], \ LiType='Sparse', doIntegrals=False, \ normalise=1, RecipFlag=True, RossHS=False, MODISSPARSE=True, \ RossType='Thick' ) kern = np.ones (( doys.shape[0], 3 )) # Store the kernels in an array kern[ :, 1 ] = K_obs.Ross kern[ :, 2 ] = K_obs.Li for doy_win in np.arange ( 0,366,16 ): doy_pass = np.logical_and ( doys >= doy_win, doys < ( doy_win + 16 ) ) doy_pass = doy_pass * qa_pass if doy_pass.sum() < 7: print "Skipping period starting in %d" % doy_win continue K = kern[ doy_pass, :] for band in xrange (7): obs = refl[ doy_pass, band] (f, rmse, rank, svals ) = np.linalg.lstsq( K, obs ) print "\t%d Period starting %d. Kernels:" % (band, doy_win), f, "RMSE: %f" % rmse break<file_sep>/python/N2B.py from math import sqrt # Convert narrow to braodband based on specific coefficients for every narrow band +/- a constant def NarrowToBroadband(coefficients, NarrowBandReflectances, BroadbandAlbedo): for band_number in range(1, 8): BroadbandAlbedo[:,:] = BroadbandAlbedo[:,:] + \ (coefficients[band_number] * NarrowBandReflectances[:,:,band_number-1]) BroadbandAlbedo[:,:] = BroadbandAlbedo[:,:] + coefficients['c'] return BroadbandAlbedo def GetUncertaintyNarrowToBroadbandConversion(coefficients, RSE_from_BB_conversion): #Land surface reflectance one standard deviation noise estimates #From <NAME>., <NAME>., <NAME>., <NAME>. (2005) # Prototyping a global algorithm for systematic fire-affected # area mapping using MODIS time series data # Remote Sensing of Environment 97 (2005) 137-162 surface_reflectance_SD_noise_estimates = {1:0.004, 2:0.015, 3:0.003, 4:0.004, 5:0.013, 6:0.010, 7:0.006 } denominator = 0.0 uncertainty = RSE_from_BB_conversion ** 2 for band_number in range(1, 8): uncertainty = uncertainty + \ ( coefficients[band_number] * surface_reflectance_SD_noise_estimates[band_number]**2 ) denominator = denominator + coefficients[band_number] uncertainty = sqrt(uncertainty / denominator) return uncertainty #---------------------Shortwave--------------------# rse_bb_short = 0.0078 bb_short = numpy.zeros((ymax, xmax), numpy.float32 ) #short = 0.160*b1 + 0.291*b2 + 0.243*b3 + 0.116*b4 + 0.112*b5 + 0.081*b7 - 0.0015 coeff_bb_short = {1:0.160, 2:0.291, 3:0.243, 4:0.116, 5:0.112, 6:0.0, 7:0.081, 'c':-0.0015} bb_short = NarrowToBroadband(coeff_bb_short, reflectance, bb_short) uncertainty_bb_short = numpy.zeros((ymax, xmax), numpy.float32 ) uncertainty_bb_short[:,:] = GetUncertaintyNarrowToBroadbandConversion(coeff_bb_short, rse_bb_short) #--------------------- Visible ----------------------# rse_bb_visible = 0.0017 bb_visible = numpy.zeros((ymax, xmax), numpy.float32 ) #visible = 0.331*b1 + 0.424*b3 + 0.246*b4 coeff_bb_visible = {1:0.331, 2:0.0, 3:0.424, 4:0.246, 5:0.0, 6:0.0, 7:0.0, 'c':0.0} bb_visible = NarrowToBroadband(coeff_bb_visible, reflectance, bb_visible) uncertainty_bb_visible = numpy.zeros((ymax, xmax), numpy.float32 ) uncertainty_bb_visible[:,:] = GetUncertaintyNarrowToBroadbandConversion(coeff_bb_visible, rse_bb_visible) rse_bb_diffuse_visible = 0.0052 bb_diffuse_visible = numpy.zeros((ymax, xmax), numpy.float32 ) #diffuse_visible = 0.246*b1 + 0.528*b3 + 0.226*b4 - 0.0013 coeff_bb_diffuse_visible = {1:0.246, 2:0.0, 3:0.528, 4:0.226, 5:0.0, 6:0.0, 7:0.0, 'c':-0.0013} bb_diffuse_visible = NarrowToBroadband(coeff_bb_diffuse_visible, reflectance, bb_diffuse_visible) rse_bb_direct_visible = 0.0028 bb_direct_visible = numpy.zeros((ymax, xmax), numpy.float32 ) #direct_visible = 0.369*b1 + 0.374*b3 + 0.257*b4 coeff_bb_direct_visible = {1:0.369, 2:0.0, 3:0.374, 4:0.257, 5:0.0, 6:0.0, 7:0.0, 'c':0.0} bb_direct_visible = NarrowToBroadband(coeff_bb_direct_visible, reflectance, bb_direct_visible) # --------------------- NIR ---------------------# rse_bb_NIR = 0.005 bb_NIR = numpy.zeros((ymax, xmax), numpy.float32 ) #NIR = 0.039*b1 + 0.504*b2 - 0.071*b3 + 0.105*b4 + 0.252*b5 + 0.069*b6 + 0.101*b7 coeff_bb_NIR = {1:0.039, 2:0.504, 3:-0.071, 4:0.105, 5:0.252, 6:0.069, 7:0.101, 'c':0.0} bb_NIR = NarrowToBroadband(coeff_bb_NIR, reflectance, bb_NIR) uncertainty_bb_NIR = numpy.zeros((ymax, xmax), numpy.float32 ) uncertainty_bb_NIR[:,:] = GetUncertaintyNarrowToBroadbandConversion(coeff_bb_NIR, rse_bb_NIR) rse_bb_diffuse_NIR = 0.008 bb_diffuse_NIR = numpy.zeros((ymax, xmax), numpy.float32 ) #bb_diffuse_NIR = 0.085*b1 + 0.693*b2 - 0.146*b3 + 0.176*b4 + 0.146*b5 + 0.043*b7 - 0.0021 coeff_bb_diffuse_NIR = {1:0.085, 2:0.693, 3:-0.146, 4:0.176, 5:0.146, 6:0.0, 7:0.043, 'c':-0.0021} bb_diffuse_NIR = NarrowToBroadband(coeff_bb_diffuse_NIR, reflectance, bb_diffuse_NIR) rse_bb_direct_NIR = 0.0062 bb_direct_NIR = numpy.zeros((ymax, xmax), numpy.float32 ) #bb_direct_NIR = 0.037*b1 + 0.479*b2 - 0.068*b3 + 0.0976*b4 + 0.266*b5 + 0.0757*b6 + 0.107*b7 coeff_bb_direct_NIR = {1:0.037, 2:0.479, 3:-0.068, 4:0.0976, 5:0.266, 6:0.0757, 7:0.107, 'c':0.0} bb_direct_NIR = NarrowToBroadband(coeff_bb_direct_NIR, reflectance, bb_direct_NIR) <file_sep>/python/convertMe.py #!/usr/bin/env python import numpy as np import scipy import pylab as plt import numpy.ma as ma import datetime import glob from netCDF4 import Dataset import os # easy_install spectral import spectral.io.envi as envi def ensure_dir(f): # maybe its a filename try: fd = os.path.dirname(f) if not os.path.exists(fd): os.makedirs(fd) return True except: pass try: if not os.path.exists(f): os.makedirs(f) return True except: return False def doy2date(doys,baseyear=1998): # convert doys list to date field year = baseyear return np.array([datetime.datetime(year, 1, 1) + datetime.timedelta(doy - 1) \ for doy in doys]) def date2doy(dates,baseyear=1998): # convert date field to doys list base = datetime.datetime(baseyear, 1, 1) try: return (dates-base).days except: return np.array([(datef-base).days \ for datef in dates]) def readwriteFile(f_file,\ ofile='/tmp/test.nc',baseyear=1998,sensor='none',\ verbose=False,dtype=None,ofile_type='envi'): ''' Sort formatting of file ''' if not ensure_dir(ofile): return None,None fileroot = '.'.join(ofile.split('.')[:-1]) if ofile_type == 'envi': ofile = fileroot + '.hdr' ofile2 = fileroot + '.img' else: ofile2 = ofile if verbose: print f_file,'\n\t--->>>',ofile rootgrp = Dataset(f_file,'r') datasets = rootgrp.variables.keys() nx = len(rootgrp.dimensions['x']) ny = len(rootgrp.dimensions['y']) nt = len(datasets) if dtype is not None: # need to check if already done if os.path.isfile(ofile2): statinfo = os.stat(ofile2) if statinfo.st_size == 4 * nx * ny * nt: return # try to delete file first (some issue with the library) try: os.remove(ofile) if ofile_type == 'envi': os.remove(ofile2) except: pass time = np.zeros(nt) # time field for i in xrange(len(datasets)): field = datasets[i].split('_')[-2] try: year = int(field[:4]) doy = int(field[4:]) thisdate = datetime.datetime(year, 1, 1) + datetime.timedelta(doy - 1) except: year = baseyear doy = int(field[4:]) thisdate = datetime.datetime(year, 1, 1) + datetime.timedelta(doy - 1) # days from base year Jan 1 # time field time[i] = date2doy(thisdate) if ofile_type == 'nc': ncfile = Dataset(ofile,mode='w',clobber=True,diskless=False,persist=False,format='NETCDF4') ncfile.createDimension('time',nt) ncfile.createDimension('x',nx) ncfile.createDimension('y',ny) timer = ncfile.createVariable('time',np.dtype('float32').char,('time',)) x = ncfile.createVariable('x',np.dtype('float32').char,('x',)) y = ncfile.createVariable('y',np.dtype('float32').char,('y',)) x.units = '1 km' y.units = '1 km' timer.units = 'days from 1 1 %d' % baseyear timer[:] = time[:] result = ncfile.createVariable('data',np.dtype('float32').char,('time','x','y')) for i in xrange(len(datasets)): if dtype is None: result[i,:,:] = rootgrp.variables[datasets[i]][:] elif dtype == 'sd': sd = rootgrp.variables[datasets[i]][:] mask = ~(sd == 0) weight = np.zeros_like(sd) weight[mask] = 1./(sd[mask]*sd[mask]) result[i,:,:] = weight elif dtype == 'var': var = rootgrp.variables[datasets[i]][:] mask = ~(var == 0) weight = np.zeros_like(var) weight[mask] = 1./(var[mask]) result[i,:,:] = weight else: meta = {'lines':ny,'samples':nx,'bands':nt,'time':time,'baseyear':baseyear,'sensor':sensor} # flat binary file - envi format img = envi.create_image(ofile,metadata=meta,dtype='float32',interleave='bip') result = img.open_memmap(writable=True) resultip = np.zeros(result.shape) for i in xrange(len(datasets)): if dtype is None: resultip[:,:,i] = rootgrp.variables[datasets[i]][:] elif dtype == 'sd': sd = rootgrp.variables[datasets[i]][:] mask = ~(sd == 0) weight = np.zeros_like(sd) weight[mask] = 1./(sd[mask]*sd[mask]) resultip[:,:,i] = weight elif dtype == 'var': var = rootgrp.variables[datasets[i]][:] mask = ~(var == 0) weight = np.zeros_like(var) weight[mask] = 1./(var[mask]) resultip[:,:,i] = weight if verbose:print '\tcopying data ...' result[:] = resultip[:] if ofile_type == 'nc': ncfile.close() rootgrp.close() else: if verbose:print '\tclosing file ...' del img,result,resultip def trysd(f_file,\ ofile_type='envi',\ ofile='/tmp/test.nc', baseyear=1998,\ verbose=False, sensor='none'): ''' Check to see if file is sd or var and if so, convert to a weigfht file ''' # check filename for sd in ['sig_','SD:']: #import pdb;pdb.set_trace() if f_file.count(sd): readwriteFile(f_file,\ sensor=sensor,\ ofile=ofile.replace(sd,'weight'+sd[-1]),\ baseyear=baseyear,verbose=verbose,\ dtype='sd',ofile_type=ofile_type) elif f_file.count('VAR'): readwriteFile(f_file,\ sensor=sensor,\ ofile=ofile.replace('VAR','weight'),\ baseyear=baseyear,verbose=verbose,\ dtype='var',ofile_type=ofile_type) # make output directory odir = 'inputs' ensure_dir(odir) ofile_type = 'envi' # convert all files tiles = ['h18v04', 'h19v08', 'h22v02', 'h25v06'] tiles = ['h18v03'] for sensor in ['meris', 'vgt']: for tile in tiles: # MvL: the list iterated on the following line may need modifying depending on... # ...the actual format of files supplied. E.g. 'sig_BB' may need to be 'weight' for dd in ['BB_','Kvol_BRDF','Kgeo_BRDF','sig_BB','snow_mask']: print dd for f in glob.glob('data/bbdr.{sensor}/{tile}*/{dd}*/*.nc'\ .format(dd=dd,tile=tile,sensor=sensor)): print f filename = os.path.basename(f).split('.') print dd,f if filename[0] == 'bbdr': sensor = filename[1] else: sensor = filename[0] fn = os.path.join(odir,os.path.basename(f)) done = False if ofile_type == 'envi': fn = '.'.join(fn.split('.')[:-1]) + '.img' try: if os.path.isfile(fn): statinfo = os.stat(fn) if statinfo.st_size > 0: done = True print 'Done:',f,'\n\t-->',fn except: pass if not done: try: readwriteFile(f,sensor=sensor,ofile=fn,ofile_type=ofile_type,baseyear=1998,verbose=True) except: print 'Fail:',f,'\n\t-->',fn # convert sd and VAR to weight trysd(f,ofile=fn,sensor=sensor,ofile_type=ofile_type,baseyear=1998,verbose=True) #os.remove(f) # a second round for ga.brdf odir = 'inputs' ensure_dir(odir) ofile_type = 'envi' for sensor in ['ga.brdf']: for sensorsub in ['ga.brdf.Snow', 'ga.brdf.NoSnow', 'ga.brdf.merge']: print "***", sensorsub for tile in ['h18v04', 'h19v08', 'h22v02', 'h25v06']: for dd in ['mean_', 'VAR_', 'lat', 'lon', 'Entropy', 'Goodness_of_Fit', 'Relative_Entropy', 'Time_to_the_Closest_Sample', 'Weighted_Number_of_Samples']: for f in glob.glob('data/{sensor}/{sensorsub}/{tile}*/{dd}*/*.nc'\ .format(dd=dd, tile=tile, sensor=sensor, sensorsub=sensorsub)): filename = os.path.basename(f).split('.') print '@', sensor, sensorsub, tile, dd,f fn = os.path.join(odir,os.path.basename(f)) done = False if ofile_type == 'envi': fn = '.'.join(fn.split('.')[:-1]) + '.img' try: if os.path.isfile(fn): statinfo = os.stat(fn) if statinfo.st_size > 0: done = True print 'Done:',f,'\n\t-->',fn except: pass print done if not done: try: print '**Doing:', f readwriteFile(f,sensor=sensor,ofile=fn,ofile_type=ofile_type,baseyear=1998,verbose=True) except: print 'Fail:',f,'\n\t-->',fn # convert sd and VAR to weight trysd(f,ofile=fn,sensor=sensor,ofile_type=ofile_type,baseyear=1998,verbose=True) #os.remove(f) # a third round for prior odir = 'inputs' ensure_dir(odir) ofile_type = 'envi' for sensor in ['prior']: for sensorsub in ['prior.v2.snow', 'prior.v2.nosnow', 'prior.v2.snownosnow']: for tile in ['h18v03']: for dd in ['MEAN', 'SD', 'Weighted_number_of_samples', 'land_mask']: for f in glob.glob('data/{sensor}/{sensorsub}/{tile}*/{dd}*/*.nc'\ .format(dd=dd, tile=tile, sensor=sensor, sensorsub=sensorsub)): filename = os.path.basename(f).split('.') print sensor, sensorsub, tile, dd,f fn = os.path.join(odir,os.path.basename(f)) done = False if ofile_type == 'envi': fn = '.'.join(fn.split('.')[:-1]) + '.img' try: if os.path.isfile(fn): statinfo = os.stat(fn) if statinfo.st_size > 0: done = True print 'Done:',f,'\n\t-->',fn except: pass if not done: try: readwriteFile(f,sensor=sensor,ofile=fn,ofile_type=ofile_type,baseyear=1998,verbose=True) except: print 'Fail:',f,'\n\t-->',fn # convert sd and VAR to weight trysd(f,ofile=fn,sensor=sensor,ofile_type=ofile_type,baseyear=1998,verbose=True) #os.remove(f)
15186f7cd1521a741180d3b714ebf05191ca7f78
[ "Markdown", "Python" ]
5
Python
UCL-EO/QA4ECV_ATBD
3dbe86572286e3a3474de67ca2ac5a7fcffb44a2
f192bdfd461753f40e0d58cb941b793e9e3f301d
refs/heads/main
<file_sep>#GROUP 49 #<NAME> #<NAME> #<NAME> (Group Leader) # In[134]: #libraries required import numpy as np #for fast mathematical computations and handling vectorizations import pandas as pd # for handling raw data read from file. from sklearn.preprocessing import StandardScaler # Scale data to Standard dist from sklearn.linear_model import LogisticRegression # Logistic Regression implementation from sci-kit learn from keras.models import Sequential # Model used for stacking layers of neurons to generate a neural network from keras.layers import Dense # a layer of neurons in the neural network import random # Python's random library to generate random numbers # In[2]: print('Data Preprocessing...') #importing training data and test data CSVs into the program using the pandas read_csv fn train_data = pd.read_csv('input/train_data.csv') test_data = pd.read_csv('input/test_data.csv') # In[3]: #converting training set into file with only sequences train_data.Sequence.to_csv('input/sequence_data.csv', index= False) # In[4]: #converting train data to amino acid features using Pfeatures and then importing it sequence_data = pd.read_csv('input/final_amino_acid_result.csv') # In[5]: #importing library for oversampling from imblearn.combine import SMOTETomek # In[6]: x_train = sequence_data.values # taking out values from dataframe x_train = x_train[:, 1:] #dropping sequence number x_train = x_train.astype(np.float64) # converting from object type to float # In[7]: #using label as out attribute to predict y_train = train_data['label'].values # In[8]: ''' oversampling data to have equal number of training samples and test samples since the provided training dataset was unbalanced. 1801 interacting and 35090 non interacting samples. fit_resample method of SMOTETomek returns equal number of data points for both labels ''' smk = SMOTETomek(random_state=41) x_res, y_res = smk.fit_resample(x_train, y_train) # In[9]: # shape of data after oversampling print(x_res.shape, y_res.shape) # In[11]: #exporting sequence data to be used for conversion by pfeature test_data.Sequence.to_csv('input/test_sequence.csv', index=False, header=None) # In[10]: #converting testing sequence to amino acid using Pfeatures and then importing it x_test = pd.read_csv('input/final_test_result.csv').values[:, 1:] # In[21]: #importing sample dataset (submission format) sample_data = pd.read_csv('input/sample.csv') #Data Preprocessing complete! Begin with testing out models # # Logistic Regression Model # In[13]: print('Logistic Regression Model...') # training using Logistic Regression Model clf = LogisticRegression(random_state=0) clf.fit(x_res, y_res) # fitting the oversampled data into the LR model # In[14]: # Testing Model preds = clf.predict(x_test) #generating predictions against the test data # In[15]: #counting 1's in preds print("Count of interacting samples in LR Model : ", preds.tolist().count(1)) # In[40]: #importing sample data sample_data = pd.read_csv('input/sample.csv') #importing submission file sample_data.Label = preds # assigning Label column to generated predictions sample_data.to_csv('output/lr_output.csv', index=False) # exporting the file to be submitted print('Predictions stored at output/lr_output.csv') print('Neural Network Model...') # # Deep learning Keras Ensemble # # In[136]: import tensorflow as tf #the tensorflow library which includes deeplearning functions # In[130]: #normalizing the data set sc = StandardScaler() # initializing the scaling function pfeature_data = np.column_stack((sc.fit_transform(x_train), y_train)) # stacking columns inorder to get an array with both x's and y's. This repreesents the training data pdata = pd.DataFrame(pfeature_data) #converting into dataframe object to run comparison queries and segragating 0 and 1 values ones_data = (pdata[pdata[20] == 1].values) #extracting interacting sequences (with label 1) from the defined dataframe object zeros_data = (pdata[pdata[20] == 0].values) #extracting non-interacting sequence (label 0 ) from the defined dataframe object ones_data = ones_data[:, :-1].astype(np.float32) #taking input values of interacting seq and converting dtype from object to float zeros_data = zeros_data[:, :-1].astype(np.float32) #taking input values of non-interacting seq and converting dtype from object to float # In[137]: #Ensembling models and generating 11 predictions out_preds = [] # array which stores all the 11 model predictions for i in range(11): model = Sequential() # initializing a neural network model model.add(Dense(16,input_dim= ones_data.shape[1], activation='relu')) #adding a input Dense layer of 16 neurons model.add(Dense(4, activation='relu')) # adding a hidden Dense layer of 4 neurons model.add(Dense(1, activation='sigmoid'))# adding a output Dense layer of 1 neuron # taking a random number to choose 1801 random samples from zeros_data for training i = random.randint(0, zeros_data.shape[0] - ones_data.shape[0]-1) sample_zero = zeros_data[i: i+ ones_data.shape[0]] #taking 1801 random samples from zeros_data x_data = np.row_stack((sample_zero, ones_data)) # generating the sample training input data # generating the sample training output data: y_data = np.row_stack((np.zeros(ones_data.shape[0]), np.ones(ones_data.shape[0]))).reshape(-1,) #defining early_stopping to stop the training when change (delta) becomes insignificant. Also maintaining the best weights early_stopping = tf.keras.callbacks.EarlyStopping( patience=10, restore_best_weights=True, min_delta=0.0005, ) # defining loss, optimizer and metrics paramaeters. Compiling the model: model.compile(loss = 'binary_crossentropy', optimizer='adam', metrics=['accuracy']) # fitting the model with the given input data: history = model.fit(sc.fit_transform(x_data), y_data, epochs= 256, verbose=1,callbacks=[early_stopping]) # appending the current model predictions to an output array out_preds.append(model.predict(sc.fit_transform(x_test))) # In[152]: # final_preds = np.array(out_preds).round().sum(axis=0) #generating final predictions by reshaping to required size and summing all predictions final_preds = np.array(out_preds).reshape((11,9582,)).sum(axis = 0) #applying majority voting in order to obtain final predicted values: for i in range(len(final_preds)):# putting values in array according to threshold if final_preds[i] > 5: #when more than half of the models predict it as interacting final_preds[i] = 1 else: # when more than half of the models predict it as non interacting final_preds[i] = 0 final_preds.tolist().count(1)#counting no of 1's in our model # In[156]: sample_data.Label = final_preds.astype(np.int64) # converting from floating point data to integers sample_data.to_csv('output/NN_ensemble.csv', index=False)#csv file output of NN_ensemble print('Predictions stored at output/NN_ensemble.csv') # In[ ]: #converting sequence to ASCII value def seq_to_ascii(x): o = [] #initialize an output array storing ascii vectors of all sequences for i in range(x.shape[0]): out = [] # ascii vector for a sequence for c in x[i]: #ASCII conversion of every sequence character #converting every sequence char into a integer representing its corresponding ASCII value. Appending its relative location from 'A' to ascii vector out.append(ord(c) - ord('A')) o.append(out) #adding the final ascii vector into the o array return np.array(o) #convert and return the numpy array of o vector # print('Categorical Naive Bayes...') # # Categorical Naive bayes with ensemble Learning # # In[122]: #converting the sequence to ascii values ones_data = seq_to_ascii(train_data[train_data['label'] == 1]['Sequence'].values)#converting where label=1 zeros_data = seq_to_ascii(train_data[train_data['label'] == 0]['Sequence'].values)#converting where label=0 test_x = seq_to_ascii(test_data.Sequence.values) # generating ascii features for every sequence # In[123]: ones_data.shape # In[124]: x_data = np.row_stack((zeros_data[1: 1 + ones_data.shape[0]], ones_data))# generating the sample training input data # generating the sample training output data: y_data = np.row_stack((np.zeros(ones_data.shape[0]), np.ones(ones_data.shape[0]))).reshape(-1,) # In[125]: from sklearn.naive_bayes import CategoricalNB # sklearn implementation for Categorical Naive Bayes out_preds = [] # represents a vector to store predictions of each of the 11 models for i in range(11): model = CategoricalNB()#applying the naive bayes model i = random.randint(0, zeros_data.shape[0] - ones_data.shape[0]-1) sample_zero = zeros_data[i: i+ ones_data.shape[0]] x_data = np.row_stack((sample_zero, ones_data))# generating the sample training input data # generating the sample training output data: y_data = np.row_stack((np.zeros(ones_data.shape[0]), np.ones(ones_data.shape[0]))).reshape(-1,) model.fit(x_data, y_data)#fitting given sample data into the NB model out_preds.append(model.predict(test_x))#generating predictions and appending to out_preds # In[126]: # adding all predictions across the rows to get a sum of predictions for every test data final_preds = np.array(out_preds).sum(axis=0) for i in range(len(final_preds)): #Majority voting if final_preds[i] > 5: # if more than half models predicts interacting then assign label 1 final_preds[i] = 1 else: # else assign label 0 final_preds[i] = 0 final_preds.tolist().count(1) # In[127]: sample_data.Label = final_preds.astype(np.int64) # convverting from float to input sample_data.to_csv('output/CategoricalNaiveBayesEnsemble.csv', index=False)#final output as csv file print('Predictions stored at output/CategoricalNaiveBayesEnsemble.csv') <file_sep># Machine-Learning Machine Learning in Bioinformatics to predict the accuracy of interacting and non-interacting sequences. Converting sequence into its ASCII value and implementing Classification like Logictic regression, Decision tree etc. we are first training the model on training dataset and then predicting values for the test dataset.
1bce0fbe8c46f1b84a7ad403f5685a45c2604090
[ "Markdown", "Python" ]
2
Python
javachip8786/Machine-Learning
9072b60a9bd2a2c87907925bcd21055320d11914
3e986866cc569f4a7ba6a98e9d4539d02ae45d35
refs/heads/master
<repo_name>shengwenbai/nodebackend<file_sep>/README.md # nodebackend https://sleepy-reaches-77167.herokuapp.com/<file_sep>/build/precache-manifest.652bebd70f4c3b370641f010dea63d33.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "711d7d735a1bf6977339cbb7a9ce35dc", "url": "/index.html" }, { "revision": "6183d257eb2ff3d6664b", "url": "/static/js/2.2ff3e96c.chunk.js" }, { "revision": "140b7baa50c8a3cef654", "url": "/static/js/main.c813d0e2.chunk.js" }, { "revision": "4e646f0e581801a589fc", "url": "/static/js/runtime-main.7767e197.js" } ]);
74daccb25354f5d0ce50cdc9a7ac921e4e9153c2
[ "Markdown", "JavaScript" ]
2
Markdown
shengwenbai/nodebackend
64f4a81b2898c15175cf43823b2b8a6bd541dd73
207158c3799b7553de94df965e000a052a8a0da0
refs/heads/master
<file_sep>#!/bin/bash #SBATCH --job-name=cds2_single_cpu #SBATCH --nodes=8 #SBATCH --ntasks-per-node=2 #SBATCH --cpus-per-task=60 #SBATCH --output=cds2_eight_node.o%j.%N #DOMAIN INFORMATION export NUMTHE=375 export NUMRHO=1024 export PIXSIZE=1 #SOLVER DATA export NUMITER=30 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=8 export BACKBUFF=8 #I/O FILES export THEFILE=./MemXCT_datasets/CDS2_theta.bin export SINFILE=./MemXCT_datasets/CDS2_sinogram.bin export OUTFILE=./recon_CDS2.bin export OMP_NUM_THREADS=60 MPI_OPTS="-np 15" MPI_OPTS+=" --map-by socket:PE=60" mpirun $MPI_OPTS ./memxct <file_sep>#!/bin/bash #SBATCH --job-name=cds1_single_gpu #SBATCH --nodes=4 #SBATCH --ntasks-per-node=4 ######SBATCH --cpus-per-task=4 #SBATCH --output=cds1_gpu_4node.o%j.%N #DOMAIN INFORMATION export NUMTHE=750 export NUMRHO=512 export PIXSIZE=1 #SOLVER DATA export NUMITER=24 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=128 export SPECSIZE=128 #BLOCK SIZE export PROJBLOCK=512 export BACKBLOCK=512 #BUFFER SIZE export PROJBUFF=96 export BACKBUFF=96 #I/O FILES export THEFILE=./MemXCT_datasets/CDS1_theta.bin export SINFILE=./MemXCT_datasets/CDS1_sinogram.bin export OUTFILE=./recon_CDS1.bin export PATH=$PATH:/usr/local/cuda-11.0/bin MPI_OPT="-np 16" mpirun $MPI_OPTS ./memxct <file_sep>#!/bin/bash #SBATCH --job-name=cds2_single_cpu #SBATCH --nodes=1 #SBATCH --ntasks-per-node=15 #SBATCH --cpus-per-task=4 #SBATCH --output=cds2_single_cpu.o%j.%N #DOMAIN INFORMATION export NUMTHE=375 export NUMRHO=1024 export PIXSIZE=1 #SOLVER DATA export NUMITER=24 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=8 export BACKBUFF=8 #I/O FILES export THEFILE=./MemXCT_datasets/CDS2_theta.bin export SINFILE=./MemXCT_datasets/CDS2_sinogram.bin export OUTFILE=./recon_CDS2.bin export OMP_NUM_THREADS=4 MPI_OPTS="-np 15" MPI_OPTS+=" --map-by l3cache:PE=4" mpirun $MPI_OPTS ./memxct <file_sep>#!/bin/bash #SBATCH --job-name=cds1_single_cpu #SBATCH --nodes=1 #SBATCH --ntasks-per-node=15 #SBATCH --cpus-per-task=4 #SBATCH --output=cds1_single_cpu.o%j.%N #DOMAIN INFORMATION export NUMTHE=750 export NUMRHO=512 export PIXSIZE=1 #SOLVER DATA export NUMITER=24 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=8 export BACKBUFF=8 #I/O FILES export THEFILE=./MemXCT_datasets/CDS1_theta.bin export SINFILE=./MemXCT_datasets/CDS1_sinogram.bin export OUTFILE=./recon_CDS1.bin export OMP_NUM_THREADS=4 MPI_OPTS="-np 15" MPI_OPTS+=" --map-by l3cache:PE=4" mpirun $MPI_OPTS ./memxct <file_sep>#!/bin/bash #SBATCH --job-name=cds1_single_cpu #SBATCH --nodes=8 #SBATCH --ntasks-per-node=2 #SBATCH --cpus-per-task=60 #SBATCH --output=cds1_eight_node.o%j.%N #DOMAIN INFORMATION export NUMTHE=750 export NUMRHO=512 export PIXSIZE=1 #SOLVER DATA export NUMITER=30 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=8 export BACKBUFF=8 #I/O FILES export THEFILE=./MemXCT_datasets/CDS1_theta.bin export SINFILE=./MemXCT_datasets/CDS1_sinogram.bin export OUTFILE=./recon_CDS1.bin export OMP_NUM_THREADS=60 export BLIS_IC_NT=$OMP_NUM_THREADS MPI_OPTS="-np 16" MPI_OPTS+=" --map-by socket:PE=60" mpirun $MPI_OPTS ./memxct <file_sep># ----- Make Macros ----- CXX = mpicxx CXXFLAGS = -std=c++11 -fopenmp OPT = -O3 -march=znver2 LD_FLAGS = -fopenmp TARGETS = memxct OBJECTS = main.o raytrace.o kernels.o # ----- Make Rules ----- all: $(TARGETS) %.o: %.cpp vars.h @echo "a" ${CXX} ${CXXFLAGS} ${OPT} $^ -c -o $@ memxct: $(OBJECTS) @echo "b" $(CXX) -o $@ $(OBJECTS) $(LD_FLAGS) clean: rm -f $(TARGETS) *.o *.o.* *.txt *.bin core <file_sep>#!/bin/bash #SBATCH --job-name=cds1_single_cpu #SBATCH --nodes=1 #SBATCH --ntasks-per-node=2 #SBATCH --cpus-per-task=60 #SBATCH --output=cds1_one_node.o%j.%N #DOMAIN INFORMATION export NUMTHE=750 export NUMRHO=512 export PIXSIZE=1 #SOLVER DATA export NUMITER=30 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=8 export BACKBUFF=8 #I/O FILES export THEFILE=./MemXCT_datasets/CDS1_theta.bin export SINFILE=./MemXCT_datasets/CDS1_sinogram.bin export OUTFILE=./recon_CDS1.bin ##export OMP_PLACES="{0:59},{60:119}" ##export OMP_DISPLAY_ENV=TRUE export OMP_NUM_THREADS=60 export BLIS_IC_NT=$OMP_NUM_THREADS MPI_OPTS="-np 2" ##MPI_OPTS+=" --map-by hwthread:PE=60" MPI_OPTS+=" --map-by socket:PE=60" ##MPI_OPTS+=" --report-bindings" # ##MPI_OPTS=" --report-binding" mpirun $MPI_OPTS ./memxct <file_sep>#!/bin/bash #SBATCH --job-name=cds2_single_cpu #SBATCH --nodes=4 #SBATCH --ntasks-per-node=4 ######SBATCH --cpus-per-task=4 #SBATCH --output=cds2_gpu_4node.o%j.%N #DOMAIN INFORMATION export NUMTHE=375 export NUMRHO=1024 export PIXSIZE=1 #SOLVER DATA export NUMITER=24 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=64 export SPECSIZE=64 #BLOCK SIZE export PROJBLOCK=512 export BACKBLOCK=512 #BUFFER SIZE export PROJBUFF=96 export BACKBUFF=96 #I/O FILES export THEFILE=./MemXCT_datasets/CDS2_theta.bin export SINFILE=./MemXCT_datasets/CDS2_sinogram.bin export OUTFILE=./recon_CDS2.bin MPI_OPTS="-np 16" mpirun $MPI_OPTS ./memxct <file_sep># ----- Make Macros ----- CXX = mpicxx CXXFLAGS = -std=c++11 -fopenmp OPTFLAGS = -O3 -march=znver2 ## -fopt-info-vec-optimized -fopt-info-vec-missed LD_FLAGS = -fopenmp TARGETS = memxct OBJECTS = src/main.o src/raytrace.o src/kernels.o # ----- Make Rules ----- all: $(TARGETS) %.o: %.cpp ${CXX} ${CXXFLAGS} ${OPTFLAGS} $^ -c -o $@ memxct: $(OBJECTS) $(CXX) -o $@ $(OBJECTS) $(LD_FLAGS) clean: rm -f $(TARGETS) src/*.o src/*.o.* *.txt *.bin core <file_sep>#!/bin/bash #SBATCH --job-name=cds3_single_cpu #SBATCH --nodes=1 #SBATCH --ntasks-per-node=15 #SBATCH --cpus-per-task=4 #SBATCH --output=cds3_single_cpu.o%j.%N #DOMAIN INFORMATION export NUMTHE=1501 export NUMRHO=2048 export PIXSIZE=1 #SOLVER DATA export NUMITER=24 #TILE SIZE (MUST BE POWER OF TWO) export SPATSIZE=32 export SPECSIZE=32 #BLOCK SIZE export PROJBLOCK=128 export BACKBLOCK=128 #BUFFER SIZE export PROJBUFF=16 export BACKBUFF=16 #I/O FILES export THEFILE=./MemXCT_datasets/CDS3_theta.bin export SINFILE=./MemXCT_datasets/CDS3_sinogram.bin export OUTFILE=./recon_CDS3.bin export OMP_NUM_THREADS=4 MPI_OPTS="-np 15" MPI_OPTS+=" --map-by l3cache:PE=4" mpirun $MPI_OPTS ./memxct
5bce7f33ea0748130d6d7acada3cb3f6d3262e32
[ "Makefile", "Shell" ]
10
Shell
SeuperHakkerJa/vscc20-memxct
2f7ff4c81fd1d2dd5c04a54c2a6297544572f6e3
74a0a22f334a15c2383c4d240899a45c199ddf8c
refs/heads/main
<repo_name>Akan2096/DDOS-Attack<file_sep>/README.md # DDOS-Attack DDOS Attack Detection and Geographical Location tracking using python special libraries DPKT, PyGeoIP and Gmplot. Detection of DDOS attack by deep packet inspection and plotting the suspected attacker’s IP on Google Map. <file_sep>/ddosAttackProject.py import pygeoip import gmplot import webbrowser import dpkt import socket gip=pygeoip.GeoIP('GeoLiteCity.dat') from dpkt.compat import compat_ord def mac_addr(address): return ':'.join('%02x' % compat_ord(b) for b in address) def inet_to_str(inet): try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet) def print_packets(pcap): t=0 mylist=[] for timestamp, buf in pcap: t=t+1 if t==200000: break eth = dpkt.ethernet.Ethernet(buf) if not isinstance(eth.data, dpkt.ip.IP): continue ip = eth.data c=inet_to_str(ip.src) mylist.append(c) d=set(mylist) d1=list(d) latitude_list=[] longitude_list=[] sum1=0; sum2=0; n=0; for j in d1: y=j r=mylist.count(y) if(r>50000): print(y) res=gip.record_by_addr(y); n=n+1 sum1=sum1+float(res['latitude']) sum2=sum2+float(res['longitude']) latitude_list.append(res['latitude']) longitude_list.append(res['longitude']) sum1=sum1/n sum2=sum2/n gmap3 = gmplot.GoogleMapPlotter(sum1, sum2, 13) gmap3.scatter( latitude_list, longitude_list, '# FF0000', size = 40, marker = False ) gmap3.heatmap(latitude_list, longitude_list) gmap3.draw( "C:\\Users\\Lenovo\\Desktop\\map13.html" ) url = "C:\\Users\\Lenovo\\Desktop\\map13.html" webbrowser.open(url, new=2) def main(): filename=('maccdc2012_00016.pcap') f=open(filename,"rb", buffering=0); pcap=dpkt.pcap.Reader(f) print_packets(pcap)
8bc283c4e49e332e12d1d5851beb9e9cd9be4548
[ "Markdown", "Python" ]
2
Markdown
Akan2096/DDOS-Attack
18ff51801ceafc6617813d1ced86eda93de0d974
f5126cb257848e93ae267747e2a780e76a87c8f9
refs/heads/master
<file_sep># Parallel-Graph-Pattern-Searching Refer report for more details about concept, working, compiling and running instructions. <file_sep>#include<iostream> #include<cstdlib> #include<cmath> #include<pthread.h> #include<fstream> using namespace std; long int num_threads = 2; //Number of threads long int pattern_nodes,target_nodes,i,j,k; //This holds the data that each thread requires: struct thread_params{ int part; //which part to multiply int M,N; long int **A; long int **B; }; long int **mul; long int **newP; long int **H; long int **targetMatrix; long int **patternMatrix; long int **Htranspose; long int **X; long int Test1(); float multiply_with_threads(long int** ,long int** ,int ,int); void* matrix_multiply(void* params); class AdjacencyMatrix { private: long int n,p; bool *visited; public: long int matrixCount; long int **adj; AdjacencyMatrix(long int n) { this->n = n; visited = new bool[n]; adj = new long int* [n]; for(long int i=0; i<n; i++) { adj[i] = new long int[n]; for(long int j=0; j<n; j++) { adj[i][j]=0; } } } //******************************* Function definition: void add_edge() *************************************// void add_edge(long int origin,long int destin) { if(origin>n || destin>n || origin<0 || origin<0) { cout<<"invalid edge"<<endl; } else { adj[origin][destin] = 1; } }//end of void add_edge //******************************* Function definition: void display() *************************************// void display(long int t,long int p,long int **dispMatrix) { for(long int i=0;i<p;i++) { for(long int j=0;j<t;j++) cout<<dispMatrix[i][j]<<""; cout<<endl; } }//end of void desplay //******************************* Function definition: void homoSearch() *************************************// long int homoSearch(long int **H,long int **targetMatrix,long int **patternMatrix,long int target_nodes,long int pattern_nodes) { long int rowIndex, colIndex; // rowIndex = i, columnIndex = j long int x = pow(target_nodes, pattern_nodes); long int breakCount=1; //To come outof loop if match is not found! if(matrixCount == 1) rowIndex = -1; //Build first leaf else rowIndex = pattern_nodes-1; //H is already a leaf, build next leaf do { if(breakCount == x) { break; } if(rowIndex<(pattern_nodes-1)) { rowIndex = rowIndex + 1; for(colIndex=0; colIndex<target_nodes; colIndex++) if(colIndex == 0) H[rowIndex][colIndex] = 1; else H[rowIndex][colIndex] = 0; } else { while(rowIndex>=0 && H[rowIndex][target_nodes-1]) { for(colIndex = 0; colIndex<target_nodes; colIndex++) H[rowIndex][colIndex] = 1; //true {restore i-th row} rowIndex = rowIndex - 1; }//end of while if (rowIndex == -1) //Matrix 'H' is null matrix { for(long int i=0; i<pattern_nodes; i++) { for(long int j=0; j<target_nodes; j++) H[i][j]=0; } } else{ colIndex = 0; while(!H[rowIndex][colIndex]) { colIndex = colIndex + 1; } H[rowIndex][colIndex] = 0; //false //{unmap nodes i to node j} H[rowIndex][colIndex+1] = 1; //true //{map node i to node j+!} breakCount++; }//end of else }//End of else }while(rowIndex!=(pattern_nodes-1) || !Test1() && rowIndex!=-1); if(breakCount == x) { cout<<"Pattern Not Found!!"<<endl; } else { cout<<"Pattern matrix found!!"<<endl; cout<<"Hence, The Homomorphism Matrix is:"<<endl; display(target_nodes,pattern_nodes,H); } }//End of homoSearch function }; //Test1 function: long int Test1() { AdjacencyMatrix adj(target_nodes); //Make mul matrix null before doing any multiplication. for(i=0; i<pattern_nodes; i++) { for(j=0; j<target_nodes; j++) { mul[i][j]=0; adj.matrixCount = 1; } } for(long int i=0; i<pattern_nodes; i++) for(long int j=0; j<target_nodes; j++) Htranspose[j][i] = H[i][j]; //***************** Find H.T.Ht ***************// multiply_with_threads(H,targetMatrix,target_nodes,target_nodes); for(long int i=0; i<pattern_nodes; i++) for(long int j=0; j<target_nodes; j++) X[i][j] = mul[i][j]; for(i=0; i<pattern_nodes; i++) { for(j=0; j<target_nodes; j++) { mul[i][j]=0; adj.matrixCount = 1; } } multiply_with_threads(X,Htranspose,pattern_nodes,target_nodes); //****************Check if newP is equal to old P**************// int flag = 0; for(i=0; i<pattern_nodes; i++) { for(j=0; j<pattern_nodes; j++) { if(mul[i][j] != patternMatrix[i][j]) { flag = 2; break; } flag = 1; } if(flag == 2) break; } if(flag == 1) return 1; else return 0; }//end of Test1 //function: multiply_with_threads // Multiplies first and second using num_threads threads and puts the result in mat. float multiply_with_threads(long int **A,long int **B, int P, int Q) { int i,j,k; pthread_t* threads; // pointer to a group of threads AdjacencyMatrix adj(target_nodes); threads = (pthread_t*) malloc(sizeof(pthread_t) * num_threads); // Create the threads for (i = 1; i < num_threads; i++) { //Reason for creating heap like below(line 305): //Local variables(here tparam is local to the thread) can go outof scope before thread starts executing. //hence create a heap and pass it to the thread! //Do same thing for tparam->part =0; struct thread_params *tparam = (struct thread_params *) malloc(sizeof(struct thread_params)); tparam->part = i; tparam->M = P; tparam->N = Q; tparam->A = A; tparam->B = B; if (pthread_create (&threads[i], NULL, matrix_multiply, tparam) != 0 ) { cout<<"Error:pthread create error"<<endl; free(threads); exit(-1); } } struct thread_params *tparam = (struct thread_params *) malloc(sizeof(struct thread_params)); tparam->part = 0; tparam->M = P; tparam->N = Q; tparam->A = A; tparam->B = B; matrix_multiply(tparam); // wait for all the threads to end for (i = 1; i < num_threads; i++) pthread_join (threads[i], NULL); free(threads); }//multiply_with_threads // A matrix is divided into 'part' equal partitions // This is called by the thread with the 'part' number. void* matrix_multiply(void* params) { AdjacencyMatrix adj(target_nodes); // Read the parameters struct thread_params *read_params; read_params = (thread_params*) params; int p = read_params->part; // get the part number int M = read_params->M; int N = read_params->N; long int **A = read_params->A; long int **B = read_params->B; int begin = (p * pattern_nodes)/num_threads; // get the index for the beginning of this part int end = ((p+1) * pattern_nodes)/num_threads; // get the index for end of this part for(i=begin; i<end; i++) for(j=0; j<M; j++) for(k=0; k<N; k++) mul[i][j] = mul[i][j] || (A[i][k]*B[k][j]); free(read_params); return 0; }//end of matrix_multiply1 int main() { long int i,j,t,max_edges, max_edges1, origin, destin,ex; char arr[20]; ifstream myfile1; myfile1.open("example.txt"); myfile1>>ex; cout<<"Enter number of examples:"<<ex<<endl; for(t=0; t<ex; t++) { cout<<endl; myfile1>>arr; cout<<arr<<endl;; myfile1>>target_nodes; cout<<"Enter number of target nodes:"<<target_nodes<<endl; //**************************************Target Graph Creation***********************************// targetMatrix = new long int* [target_nodes]; for(i=0; i<target_nodes; i++) { targetMatrix[i] = new long int[target_nodes]; for(j=0; j<target_nodes; j++) { targetMatrix[i][j]=0; } } AdjacencyMatrix am(target_nodes); max_edges = target_nodes*target_nodes; for(i=0;i<max_edges;i++) { myfile1>>origin>>destin; cout<<"Enter Edge:"<<origin<<" "<<destin<<endl; if((origin == -1) && (destin == -1)) break; am.add_edge(origin-1,destin-1); }//end of for for(i=0;i<target_nodes;i++) for(j=0;j<target_nodes;j++) targetMatrix[i][j] = am.adj[i][j]; cout<<"Target Matrix is:"<<endl; am.display(target_nodes,target_nodes,targetMatrix); //***************************Pattern Graph Creation******************************// myfile1>>pattern_nodes; cout<<"Enter number of pattern nodes:"<<pattern_nodes<<endl; patternMatrix = new long int* [pattern_nodes]; for(i=0; i<pattern_nodes; i++) { patternMatrix[i] = new long int[pattern_nodes]; for(j=0; j<pattern_nodes; j++) { patternMatrix[i][j]=0; } } //---mul, newP, Htranspose matrices initialization---// mul = new long int* [pattern_nodes]; for(long int i=0; i<pattern_nodes; i++) mul[i] = new long int[target_nodes]; X = new long int* [pattern_nodes]; for(long int i=0; i<pattern_nodes; i++) X[i] = new long int[target_nodes]; newP = new long int* [pattern_nodes]; for(long i=0; i<pattern_nodes; i++) newP[i] = new long int[pattern_nodes]; Htranspose = new long int* [target_nodes]; for(long int i=0; i<target_nodes; i++) Htranspose[i] = new long int[pattern_nodes]; struct thread_params tp; tp.A = new long int* [pattern_nodes]; for(long int i=0; i<pattern_nodes; i++) tp.A[i] = new long int[target_nodes]; tp.B = new long int* [target_nodes]; for(long int i=0; i<target_nodes; i++) tp.B[i] = new long int[target_nodes]; AdjacencyMatrix am1(pattern_nodes); max_edges = pattern_nodes*(pattern_nodes-1); max_edges1 = pattern_nodes*pattern_nodes; for(i=0;i<max_edges1;i++) { myfile1>>origin>>destin; cout<<"Enter Edge:"<<origin<<" "<<destin<<endl; if((origin == -1) && (destin == -1)) break; am1.add_edge(origin-1,destin-1); }//end of for for(i=0;i<pattern_nodes;i++) for(j=0;j<pattern_nodes;j++) patternMatrix[i][j] = am1.adj[i][j]; cout<<"Pattern Matrix is:"<<endl; am1.display(pattern_nodes,pattern_nodes,patternMatrix); //*************************************Initial Homomorphism Matrix setup*************************/ H = new long int* [pattern_nodes]; for(i=0; i<pattern_nodes; i++) { H[i] = new long int[target_nodes]; for(j=0; j<target_nodes; j++) { H[i][j]=1; am1.matrixCount = 1; } } am1.homoSearch(H, targetMatrix, patternMatrix, target_nodes, pattern_nodes); cout<<endl; }//End of for myfile1.close(); return 0; }//End of main
929a00af68ffa16dff5e4033229b5f0416993585
[ "Markdown", "C++" ]
2
Markdown
tanaya13693/Parallel-Graph-Pattern-Searching
e5bed2871194b4502d561ea7967e842c81d021ed
dfd03bb11cb10f08a5e0e3b51c6bc7096a187775
refs/heads/master
<file_sep>package name.valery1707.java.kazakh.spi.util; import java.util.Currency; import java.util.Locale; import java.util.spi.CurrencyNameProvider; import static name.valery1707.java.kazakh.constants.KazakhLocales.*; import static name.valery1707.java.kazakh.constants.KazakhStrings.CURRENCY_ID; import static name.valery1707.java.kazakh.constants.KazakhStrings.CURRENCY_SYMBOL; public final class KazakhCurrencyNameProvider extends CurrencyNameProvider { public KazakhCurrencyNameProvider() { super(); } @Override public String getSymbol(final String currencyCode, final Locale locale) { checkLocale(locale); if (CURRENCY_ID.equals(currencyCode)) { return CURRENCY_SYMBOL; } return Currency.getInstance(currencyCode).getSymbol(SOURCE_LOCALE); } @Override public Locale[] getAvailableLocales() { return LOCALES_ARRAY; } } <file_sep>package name.valery1707.java.kazakh.text; import name.valery1707.java.kazakh.constants.KazakhLocales; import java.text.DecimalFormatSymbols; import java.util.Currency; import static name.valery1707.java.kazakh.constants.KazakhStrings.CURRENCY_ID; import static name.valery1707.java.kazakh.constants.KazakhStrings.CURRENCY_SYMBOL; public final class KazakhDecimalFormatSymbols extends DecimalFormatSymbols { public KazakhDecimalFormatSymbols() { super(KazakhLocales.SOURCE_LOCALE); setCurrency(Currency.getInstance(CURRENCY_ID)); setCurrencySymbol(CURRENCY_SYMBOL); } } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>name.valery1707.java</groupId> <artifactId>locale-kazakh</artifactId> <version>1.0.2-SNAPSHOT</version> <packaging>jar</packaging> <name>locale-kazakh</name> <description> The Java Kazakh Locale is an implementation of Java localization SPIs which will allow the Java VM to use the Kazakh Language (locales "kk" and "kk_KZ"), official languages of Kazakhstan, which is not included in Oracle's JVM distribution. Some source was found on The JAVAGALICIAN project (https://github.com/javagalician/javagalician-java6) </description> <url>https://github.com/valery1707/java-locale-kazakh</url> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <scm> <url>https://github.com/valery1707/java-locale-kazakh</url> <connection>scm:git:https://github.com/valery1707/java-locale-kazakh.git</connection> <developerConnection>scm:git:git@github.com:valery1707/java-locale-kazakh.git</developerConnection> <tag>HEAD</tag> </scm> <inceptionYear>2015</inceptionYear> <developers> <developer> <id>Valeriy.Vyrva</id> <name><NAME></name> <email><EMAIL></email> <url>https://github.com/valery1707</url> <roles> <role>developer</role> </roles> <timezone>+6</timezone> </developer> </developers> <properties> <project.encoding>UTF-8</project.encoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.6</maven.compiler.source> <maven.compiler.target>1.6</maven.compiler.target> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>${maven.compiler.source}</source> <target>${maven.compiler.target}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.1</version> <configuration> <autoVersionSubmodules>true</autoVersionSubmodules> <tagNameFormat>v@{project.version}</tagNameFormat> <useReleaseProfile>false</useReleaseProfile> <releaseProfiles>release</releaseProfiles> <goals>install</goals> <localCheckout>true</localCheckout> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>release</id> <build> <plugins> <plugin> <groupId>de.jutzig</groupId> <artifactId>github-release-plugin</artifactId> <version>1.1.1</version> <executions> <execution> <id>github-upload</id> <phase>install</phase> <goals> <goal>release</goal> </goals> <inherited>false</inherited> <configuration> <serverId>github-locale-kazakh</serverId> <releaseName>v${project.version}</releaseName> <tag>v${project.version}</tag> <artifact>${project.build.directory}/${project.artifactId}-${project.version}.${project.packaging}</artifact> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> </project> <file_sep>package name.valery1707.java.kazakh.spi.util; import java.text.DateFormatSymbols; import java.util.Locale; import java.util.TimeZone; import java.util.spi.TimeZoneNameProvider; import static name.valery1707.java.kazakh.constants.KazakhLocales.*; public final class KazakhTimeZoneNameProvider extends TimeZoneNameProvider { public KazakhTimeZoneNameProvider() { super(); } private static boolean isStyleValid(final int style) { return (style == TimeZone.SHORT || style == TimeZone.LONG); } private static void checkStyle(final int style) { if (!isStyleValid(style)) { throw new IllegalArgumentException("Style \"" + style + "\" is not valid"); } } @Override public String getDisplayName(final String ID, final boolean daylight, final int style, final Locale locale) { if (ID == null) { throw new NullPointerException(); } checkLocale(locale); checkStyle(style); final DateFormatSymbols symbols = DateFormatSymbols.getInstance(KAZAKH_KZ); final String[][] zoneStrings = symbols.getZoneStrings(); /* * First, try to retrieve a name using the specified ID as the main timezone ID */ for (String[] zoneString : zoneStrings) { if (ID.equalsIgnoreCase(zoneString[0])) { return getDisplayName(zoneString, daylight, style); } } /* * Then try to retrieve a name using the specified ID as a short name * (first, non-daylight saving - then, daylight-saving). */ for (String[] zoneString : zoneStrings) { String name = daylight ? zoneString[4] : zoneString[2]; if (ID.equalsIgnoreCase(name)) { return getDisplayName(zoneString, daylight, style); } } /* * If we don't have a name yet, default to source locale */ final TimeZone timeZone = TimeZone.getTimeZone(ID); return timeZone.getDisplayName(SOURCE_LOCALE); } private static String getDisplayName(final String[] zoneStrings, final boolean daylight, final int style) { switch (style) { case TimeZone.LONG: return (daylight ? zoneStrings[3] : zoneStrings[1]); case TimeZone.SHORT: return (daylight ? zoneStrings[4] : zoneStrings[2]); } return null; } @Override public Locale[] getAvailableLocales() { return LOCALES_ARRAY; } } <file_sep>package name.valery1707.java.kazakh.spi.text; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.spi.DateFormatProvider; import java.util.Locale; import static name.valery1707.java.kazakh.constants.KazakhLocales.LOCALES_ARRAY; import static name.valery1707.java.kazakh.constants.KazakhLocales.checkLocale; public final class KazakhDateFormatProvider extends DateFormatProvider { public static final String PATTERN_DATE_SHORT = "dd'.'MM'.'yy"; public static final String PATTERN_DATE_MEDIUM = "dd MMM yyyy 'ж.'"; public static final String PATTERN_DATE_LONG = "dd MMMM yyyy 'жыл'"; public static final String PATTERN_DATE_FULL = "EEEE d MMMM yyyy 'жыл'"; public static final String PATTERN_TIME_SHORT = "HH':'mm"; public static final String PATTERN_TIME_MEDIUM = "HH':'mm':'ss"; public static final String PATTERN_TIME_LONG = "HH':'mm':'ss z"; public static final String PATTERN_TIME_FULL = "HH':'mm':'ss z"; public KazakhDateFormatProvider() { super(); } private static boolean isStyleValid(final int style) { return (style == DateFormat.SHORT || style == DateFormat.MEDIUM || style == DateFormat.LONG || style == DateFormat.FULL); } private static void checkStyle(final int style) { if (!isStyleValid(style)) { throw new IllegalArgumentException("Style \"" + style + "\" is not valid"); } } @Override public DateFormat getDateInstance(final int style, final Locale locale) { checkLocale(locale); checkStyle(style); switch (style) { case DateFormat.FULL: return new SimpleDateFormat(PATTERN_DATE_FULL, locale); case DateFormat.LONG: return new SimpleDateFormat(PATTERN_DATE_LONG, locale); case DateFormat.MEDIUM: return new SimpleDateFormat(PATTERN_DATE_MEDIUM, locale); case DateFormat.SHORT: default: return new SimpleDateFormat(PATTERN_DATE_SHORT, locale); } } @Override public DateFormat getDateTimeInstance(final int dateStyle, final int timeStyle, final Locale locale) { checkLocale(locale); checkStyle(dateStyle); checkStyle(timeStyle); final StringBuilder pattern = new StringBuilder(); switch (dateStyle) { case DateFormat.FULL: pattern.append(PATTERN_DATE_FULL); break; case DateFormat.LONG: pattern.append(PATTERN_DATE_LONG); break; case DateFormat.MEDIUM: pattern.append(PATTERN_DATE_MEDIUM); break; case DateFormat.SHORT: default: pattern.append(PATTERN_DATE_SHORT); break; } pattern.append(" "); switch (timeStyle) { case DateFormat.FULL: pattern.append(PATTERN_TIME_FULL); break; case DateFormat.LONG: pattern.append(PATTERN_TIME_LONG); break; case DateFormat.MEDIUM: pattern.append(PATTERN_TIME_MEDIUM); break; case DateFormat.SHORT: default: pattern.append(PATTERN_TIME_SHORT); break; } return new SimpleDateFormat(pattern.toString(), locale); } @Override public DateFormat getTimeInstance(final int style, final Locale locale) { checkLocale(locale); checkStyle(style); switch (style) { case DateFormat.FULL: return new SimpleDateFormat(PATTERN_TIME_FULL, locale); case DateFormat.LONG: return new SimpleDateFormat(PATTERN_TIME_LONG, locale); case DateFormat.MEDIUM: return new SimpleDateFormat(PATTERN_TIME_MEDIUM, locale); case DateFormat.SHORT: default: return new SimpleDateFormat(PATTERN_TIME_SHORT, locale); } } @Override public Locale[] getAvailableLocales() { return LOCALES_ARRAY; } } <file_sep>package name.valery1707.java.kazakh.spi.text; import name.valery1707.java.kazakh.text.KazakhDecimalFormatSymbols; import java.text.DecimalFormatSymbols; import java.text.spi.DecimalFormatSymbolsProvider; import java.util.Locale; import static name.valery1707.java.kazakh.constants.KazakhLocales.LOCALES_ARRAY; import static name.valery1707.java.kazakh.constants.KazakhLocales.checkLocale; public final class KazakhDecimalFormatSymbolsProvider extends DecimalFormatSymbolsProvider { public KazakhDecimalFormatSymbolsProvider() { super(); } @Override public DecimalFormatSymbols getInstance(final Locale locale) { checkLocale(locale); return new KazakhDecimalFormatSymbols(); } @Override public Locale[] getAvailableLocales() { return LOCALES_ARRAY; } } <file_sep>package name.valery1707.java.kazakh.constants; public final class KazakhStrings { public static final String[] MONTH_LONG_STANDALONE = {"Қаңтар", "Ақпан", "Наурыз", "Сәуір", "Мамыр", "Маусым", "Шілде", "Тамыз", "Қыркүйек", "Қазан", "Қараша", "Желтоқсан"}; public static final String[] MONTH_LONG_FORMAT = MONTH_LONG_STANDALONE; public static final String[] MONTH_SHORT_STANDALONE = MONTH_LONG_STANDALONE; public static final String[] MONTH_SHORT_FORMAT = MONTH_SHORT_STANDALONE; public static final String[] MONTH_NARROW_STANDALONE = MONTH_SHORT_STANDALONE; public static final String[] MONTH_NARROW_FORMAT = MONTH_NARROW_STANDALONE; public static final String[] WEEKDAYS_LONG_STANDALONE = {"", "Дүйсенбі", "Сейсенбі", "Сәрсенбі", "Бейсенбі", "Жұма", "Сенбі", "Жексенбі"}; public static final String[] WEEKDAYS_LONG_FORMAT = WEEKDAYS_LONG_STANDALONE; public static final String[] WEEKDAYS_SHORT_STANDALONE = {"", "Дүй", "Сей", "Сәр", "Бей", "Жұм", "Сен", "Жек"}; public static final String[] WEEKDAYS_SHORT_FORMAT = WEEKDAYS_SHORT_STANDALONE; public static final String[] WEEKDAYS_NARROW_STANDALONE = WEEKDAYS_SHORT_STANDALONE; public static final String[] WEEKDAYS_NARROW_FORMAT = WEEKDAYS_NARROW_STANDALONE; public static final String CURRENCY_ID = "KZT"; public static final String CURRENCY_LONG = "Теңге"; public static final String CURRENCY_SHORT = "тңг"; public static final String CURRENCY_SYMBOL = "₸"; private KazakhStrings() { } } <file_sep>Java locale Kazakh is an extension for the Java Virtual Machine which adds support for the Kazakh locale (kk, kk_KZ). # INSTALLATION REQUIREMENTS: Java SE 6 or higher. ## 1. Installing ### 1.1. Installing permanently into your JVM Download latest release from [GitHub Releases](https://github.com/valery1707/java-locale-kazakh/releases). For installing Kazakh locale, just copy the `locale-kazakh-{version}.jar` file into your Java virtual machine's extension folder: * For a Java JDK: $JAVA_HOME/jre/lib/ext * For a Java JRE: $JAVA_HOME/lib/ext * For an Apple Java JDK/JRE in Mac OS X: /Library/Java/Extensions ### 1.2. Specifying as parameter on VM start If you prefer not to install the Kazakh locale file into your VM's folder, you can copy it into any other folder and specify it as a VM parameter: ```bash $ java -Djava.ext.dirs=$MY_EXTENSIONS_DIR ... ``` ## 2. Checking installation For checking installation Kazakh locale to JVM you may use project [Locale Kazakh Check](https://github.com/valery1707/java-locale-kazakh-check). <file_sep>Some information for developers. # Release ## Configure [GitHub release plugin](https://github.com/jutzig/github-release-plugin) 1. Go to [GitHub Applications](https://github.com/settings/applications) and create new personal access tokens with atleast this rights: * public_repo 2. Open Maven `settings.xml` and create new section: ```xml <server> <id>github-locale-kazakh</id> <privateKey>0000000000000000000000000000000000000000</privateKey> </server> ``` ## Create release Run command `mvn release:prepare release:perform` and maven make this actions: 1. Update project version from snapshot to release 1. Build project with goals 'clean verify' 1. Commit and push migration to release version 1. Create tag 1. Update project version to new snapshot version 1. Commit and push migration to snapshot version 1. Perform local checkout project sources 1. Build project with goal 'install' and enabled profile 'release' 1. After phase 'install' will be triggered execution 'github-upload', which create release on GitHub and upload to this release project artifact <file_sep>package name.valery1707.java.kazakh.constants; import java.util.Arrays; import java.util.List; import java.util.Locale; public final class KazakhLocales { public static final Locale KAZAKH = new Locale("kk"); public static final Locale KAZAKH_KZ = new Locale("kk", "KZ"); public static final Locale[] LOCALES_ARRAY = new Locale[]{KAZAKH, KAZAKH_KZ}; public static final List<Locale> LOCALES_LIST = Arrays.asList(LOCALES_ARRAY); public static final Locale SOURCE_LOCALE = new Locale("ru", "RU"); private KazakhLocales() { } public static void checkLocale(Locale locale) { if (locale == null) { throw new NullPointerException(); } if (!LOCALES_LIST.contains(locale)) { throw notSupportedLocale(locale); } } public static IllegalArgumentException notSupportedLocale(Locale locale) { return new IllegalArgumentException("Locale \"" + locale + "\" " + "is not one of the supported locales (" + LOCALES_LIST + ")"); } }
d1ec7b5dc523bb08f08373dfcba8859ea75d46fc
[ "Markdown", "Java", "Maven POM" ]
10
Java
valery1707/java-locale-kazakh
01dde7b90c55582a1897f4521de77d63c2b5d4e5
cf11783a98b28d89276e765ca700ab9f31bce950
refs/heads/master
<file_sep>package com.tomorrow.mitty.locationindoor; import android.app.Application; import com.baidu.mapapi.SDKInitializer; public class sdkApplication extends Application { @Override public void onCreate(){ super.onCreate(); //在使用SDK各组之前初始化context信息,传入ApplicationContext SDKInitializer.initialize(this); } }
afd27754add79b1f16bc040be8bbcbd3f9f76984
[ "Java" ]
1
Java
MittyShao/LocationIndoor
88ce9467e98687ee78e16f9b7a50061244152867
abf70de51217c6377d75f131def3a4e1fe026fc8
refs/heads/master
<file_sep>#!/usr/bin/env python3 import pygame, random from player import Player from food import Food class Board: """Used to organize and handle the gist of the game""" def __init__(self, width, height): self.score = 0 self.width = width self.height = height self._initEntities() def _initEntities(self): self.player = Player(self) self.entities = [ self.player, Food.randomFood(self), Food.randomFood(self), ] def _drawHud(self, display): font = pygame.font.Font(None, 24) text = font.render("Score: %d" % self.score, 1, (255, 255, 255)) textpos = text.get_rect() display.blit(text, textpos) if self.isGameOver(): self._drawGameOverHud(display) def _drawGameOverHud(self, display): font = pygame.font.Font(None, 64) text = font.render("GAME OVER", 1, (255, 0, 0)) textpos = text.get_rect() textpos.centerx = display.get_rect().centerx textpos.centery = display.get_rect().centery display.blit(text, textpos) font = pygame.font.Font(None, 24) text = font.render("(Press Space to Play Again)", 1, (255, 255, 255)) textpos = text.get_rect() textpos.centerx = display.get_rect().centerx textpos.centery = display.get_rect().centery + 32 display.blit(text, textpos) def _generateXYTupleFarAwayFromPlayer(self, size): quadrant_width = self.width / 2 quadrant_height = self.height / 2 if self.player.getRect().x < quadrant_width: x = random.randint(quadrant_width + 50, self.width - size) else: x = random.randint(0, quadrant_width - size - 50) if self.player.getRect().y < quadrant_height: y = random.randint(quadrant_height + 50, self.height - size) else: y = random.randint(0, quadrant_height - size - 50) return (x, y) def move(self, elapsedTime): for entity in self.entities: if entity != self.player: if self.player.getRect().colliderect(entity.getRect()): entity.hitPlayer(self) for entity in self.entities: entity.move(self, elapsedTime) def draw(self, display): self._drawHud(display) for entity in self.entities: entity.draw(display) def isGameOver(self): return self.player.isDead() def addScore(self, amount): self.score += amount def getScore(self): return self.score def getHeight(self): return self.height def getWidth(self): return self.width def addBadguy(self, badguy): self.entities.append(badguy) x, y = self._generateXYTupleFarAwayFromPlayer(badguy.getSize()) badguy.x, badguy.y = (x, y) def shuffleFood(self, food): self.entities.insert(0, Food.randomFood(self)) self.entities.remove(food) def randomXYTuple(self, size): x = random.randint(0, self.width - size) y = random.randint(0, self.height - size) return (x, y) <file_sep>#!/usr/bin/env python3 import pygame from pygame.locals import * from entity import Entity class Player(Entity): """Responsible for the main character square.""" def __init__(self, board): size = 15 x = board.getWidth()/2 - size/2 y = board.getHeight()/2 - size/2 Entity.__init__(self, x, y, size) self.speed = 100 self.dead = False def draw(self, display): pygame.draw.rect(display, pygame.Color(255, 255, 0), self.getRect()) def move(self, board, elapsedTime): if self.isDead(): return self._respondToKeyEvents(elapsedTime) self._ensureWithinScreenBounds(board) def _respondToKeyEvents(self, elapsedTime): if pygame.key.get_pressed()[pygame.K_UP]: self.y -= self.speed * elapsedTime if pygame.key.get_pressed()[pygame.K_DOWN]: self.y += self.speed * elapsedTime if pygame.key.get_pressed()[pygame.K_LEFT]: self.x -= self.speed * elapsedTime if pygame.key.get_pressed()[pygame.K_RIGHT]: self.x += self.speed * elapsedTime def _ensureWithinScreenBounds(self, board): self.x = min(max(0, self.x), board.getWidth() - self.size) self.y = min(max(0, self.y), board.getHeight() - self.size) def grow(self, amount): self.size += amount self.x -= amount/2 self.y -= amount/2 def shrink(self, amount): minimumSize = 5 if self.size > minimumSize: self.size = max(minimumSize, self.size - amount) self.x += amount/2 self.y += amount/2 def increaseSpeed(self, amount): self.speed += amount def decreaseSpeed(self, amount): minimumSpeed = 30 self.speed = max(self.speed - 10, minimumSpeed) def die(self): self.dead = True def isDead(self): return self.dead <file_sep>#!/usr/bin/env python3 import pygame, random, math from pygame.locals import * from entity import Entity class Badguy(Entity): """Parent bad guy class. When the player hits this entity, it will die!""" def __init__(self, color): Entity.__init__(self, 0, 0, size=10) self.color = color self.timeAlive = 0 self.SPAWN_TIME = 0.5 def move(self, board, elapsedTime): self.timeAlive += elapsedTime if self.timeAlive > self.SPAWN_TIME: self._step(board, elapsedTime) def draw(self, display): """Handles the spawn animation of the badguy, as well as stepping it. To control the movement of the badguy, use the _step method. """ if self.timeAlive < self.SPAWN_TIME: size = (self.timeAlive / self.SPAWN_TIME) * self.size deltaSize = self.size - size rect = (self.x + deltaSize/2, self.y + deltaSize/2, size, size) else: rect = self.getRect() pygame.draw.rect(display, self.color, rect) def hitPlayer(self, board): board.player.die() def _step(self, board, elapsedTime): """Should be used in sub classes instead of the 'move' method""" pass class SimpleBadguy(Badguy): """Simple badguy that keeps a constant velocity""" def __init__(self, board): Badguy.__init__(self, pygame.Color(255, 255, 255)) self.xVelocity = self._randomVelocity() self.yVelocity = self._randomVelocity() def _randomVelocity(self): """Random velocity as an integer - Between 10-50 pixels per second""" return random.choice([-1, 1]) * random.randint(10, 50) def _bounceOffWalls(self, board, elapsedTime): newX = self.x + self.xVelocity * elapsedTime if newX > board.getWidth() - self.size or newX < 0: self.xVelocity = -self.xVelocity newY = self.y + self.yVelocity * elapsedTime if newY > board.getHeight() - self.size or newY < 0: self.yVelocity = -self.yVelocity def _step(self, board, elapsedTime): self._bounceOffWalls(board, elapsedTime) self.x += elapsedTime * self.xVelocity self.y += elapsedTime * self.yVelocity class RandomBadguy(SimpleBadguy): """A badguy that will randomly change direction""" def __init__(self, board): SimpleBadguy.__init__(self, board) self.color = pygame.Color(255, 127, 127) self._lastDirectionChange = 0 def _randomizeVelocity(self, elapsedTime): self._lastDirectionChange += elapsedTime # Only change directions at most once per second. if self._lastDirectionChange > 1: self._lastDirectionChange = 0 chanceEachSecond = 3 if random.randint(0, chanceEachSecond) == 0: self.xVelocity = self._randomVelocity() if random.randint(0, chanceEachSecond) == 0: self.yVelocity = self._randomVelocity() def _step(self, board, elapsedTime): self._randomizeVelocity(elapsedTime) SimpleBadguy._step(self, board, elapsedTime) class SmartBadguy(Badguy): """A badguy that will chase the player""" def __init__(self, board): Badguy.__init__(self, pygame.Color(127, 255, 127)) self.speed = 30 def _step(self, board, elapsedTime): player = board.player if player.isDead(): return deltaX = abs(player.x - self.x) deltaY = abs(player.y - self.y) angle = math.atan(deltaY / deltaX) # Determine the quadrant and adjust the angle relative to self if player.y < self.y: if player.x < self.x: # Second quadrant angle = math.pi - angle #else: First quadrant, so do nothing. else: if player.x < self.x: # Third quadrant angle = math.pi + angle else: # Fourth quadrant angle = -angle # The Y axis (unlike on a normal cartesian plane) is negative as it goes up. self.y -= elapsedTime * self.speed * math.sin(angle) self.x += elapsedTime * self.speed * math.cos(angle) <file_sep>#!/usr/bin/env python3 import pygame, random from entity import Entity from badguy import * class Food(Entity): """The class to handle getting points ( coins, food, etc :] )""" def randomFood(board): """Factory method for creates a new random food type If you create new types of food, add them to this list. """ return random.choice([ GrowFood(board), ShrinkFood(board), FastFood(board), SlowFood(board), ]) def __init__(self, board): self.size = 10 self.x, self.y = board.randomXYTuple(self.size) def draw(self, display): radius = int(self.size / 2) x = self.x + radius y = self.y + radius pygame.draw.circle(display, self.color, (x, y), radius) def _initNewBadguy(self, board): score = board.getScore() if score == 1: return SmartBadguy(board) elif score % 10 == 0: return RandomBadguy(board) else: return SimpleBadguy(board) def hitPlayer(self, board): board.addScore(1) badguy = self._initNewBadguy(board) board.addBadguy(badguy) board.shuffleFood(self) class GrowFood(Food): def __init__(self, board): Food.__init__(self, board) self.color = pygame.Color(0, 255, 0) def hitPlayer(self, board): Food.hitPlayer(self, board) board.player.grow(2) class ShrinkFood(Food): def __init__(self, board): Food.__init__(self, board) self.color = pygame.Color(0, 0, 255) def hitPlayer(self, board): Food.hitPlayer(self, board) board.player.shrink(2) class FastFood(Food): def __init__(self, board): Food.__init__(self, board) self.color = pygame.Color(255, 0, 255) def hitPlayer(self, board): Food.hitPlayer(self, board) board.player.increaseSpeed(10) class SlowFood(Food): def __init__(self, board): Food.__init__(self, board) self.color = pygame.Color(255, 0, 0) def hitPlayer(self, board): Food.hitPlayer(self, board) board.player.decreaseSpeed(10) <file_sep>#!/usr/bin/env python3 import pygame class Entity: """Used to set standards to how game entities are designed""" def __init__(self, x : int, y : int, size : int): self.x = x self.y = y self.size = size def move(self, board, elapsedTime : float): """Used to move the entity based on the elapsedTime (in seconds)""" pass def getRect(self): return pygame.Rect(self.x, self.y, self.size, self.size) def getSize(self): return self.size def draw(self, display): """Draw the entity - Typically as a square""" pass def hitPlayer(self, board): """This method will be invoked on the object if hit by the player""" pass <file_sep>Squarez ======= This is just a little game I made for a programming class. Fork, and hack away! Dependencies ------------ PyGame for Python 3 <file_sep>#!/usr/bin/env python3 import pygame, sys from pygame.locals import * from board import Board if __name__ == '__main__': screen_width = 640 screen_height = 480 pygame.init() display = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Squarez') fpsClock = pygame.time.Clock() board = Board(screen_width, screen_height) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if board.isGameOver() and event.type == KEYUP and event.key == K_SPACE: board = Board(screen_width, screen_height) board.move(fpsClock.get_time() / 1000) display.fill((0, 0, 0)) board.draw(display) pygame.display.update() fpsClock.tick(60)
a7690ed84d9f8a0d2646a7c45a121732d4f9152e
[ "Markdown", "Python" ]
7
Python
elimirks/squarez
ad9af9808ce82205265dc9d24a1c29b3ff136f11
60bb2ee49775399ca95b3446aa65c9b95ddf22dc
refs/heads/master
<repo_name>appcelerator-modules/ti.pageflip<file_sep>/ios/example/views.js var win = Ti.UI.currentWindow; var PageFlip = require('ti.pageflip'); function createPage(number) { return Ti.UI.createLabel({ text: 'p' + number, textAlign: 'center', font: { fontSize: 150, fontWeight: 'bold' }, backgroundColor: '#fff' }); } var pages = [], count; for (count = 1; count <= 4; count++) { pages.push(createPage(count)); } var pageflip = PageFlip.createView({ /* All Options: TRANSITION_FLIP [default], TRANSITION_SLIDE, TRANSITION_FADE, TRANSITION_CURL */ transition: PageFlip.TRANSITION_CURL, transitionDuration: 0.3, landscapeShowsTwoPages: true, pages: pages }); win.add(pageflip); function updateWindowTitle() { win.title = 'Views, 1 < ' + (pageflip.currentPage + 1) + ' > ' + pageflip.pageCount; } updateWindowTitle(); pageflip.addEventListener('change', function (evt) { // evt.currentPage updateWindowTitle(); }); pageflip.addEventListener('tap', function (evt) { // evt.currentPage Ti.API.info('User tapped inside the paging margins! Maybe we should show them an overlay menu?'); }); pageflip.addEventListener('flipStarted', function (evt) { Ti.API.info('flip started!'); }); var previous = Ti.UI.createButton({ title: '<', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); previous.addEventListener('click', function () { var offsetLandscape = pageflip.landscapeShowsTwoPages && win.size.width > win.size.height; var previousPage = pageflip.currentPage - (offsetLandscape ? 2 : 1); if (offsetLandscape && previousPage < 0 && pageflip.currentPage == 1) { // We can already see both pages; don't change the page. return; } pageflip.changeCurrentPage(previousPage, true); updateWindowTitle(); }); var insert = Ti.UI.createButton({ title: 'Insrt', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); insert.addEventListener('click', function () { pageflip.insertPageBefore(0, createPage(++count)); updateWindowTitle(); }); var append = Ti.UI.createButton({ title: 'Apnd', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); append.addEventListener('click', function () { pageflip.appendPage(createPage(++count)); updateWindowTitle(); }); var remove = Ti.UI.createButton({ title: 'Del', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); remove.addEventListener('click', function () { pageflip.deletePage(Math.max(0, pageflip.currentPage)); updateWindowTitle(); }); var gestures = Ti.UI.createButton({ title: 'Gstrs', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); gestures.addEventListener('click', function () { pageflip.enableBuiltInGestures = !pageflip.enableBuiltInGestures; }); var next = Ti.UI.createButton({ title: '>', style: Ti.UI.iPhone.SystemButtonStyle.BORDERED }); next.addEventListener('click', function () { var offsetLandscape = pageflip.landscapeShowsTwoPages && win.size.width > win.size.height; var nextPage = pageflip.currentPage + (offsetLandscape ? 2 : 1); if (offsetLandscape && pageflip.pageCount % 2 == 0 && nextPage >= pageflip.pageCount && pageflip.currentPage == pageflip.pageCount - 2) { // We can already see both pages; don't change the page. return; } pageflip.changeCurrentPage(Math.min(nextPage, pageflip.pageCount - 1), true); updateWindowTitle(); }); var flexSpace = Ti.UI.createButton({ systemButton: Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE }); win.toolbar = [ previous, flexSpace, gestures, insert, append, remove, flexSpace, next ];<file_sep>/ios/documentation/index.md # Ti.PageFlip Module ## Description Display pages of data to your users. Comes stock with easy to turn pages, multiple transition effects (fade, flip, and slide), a quick PDF mode, and a view-based mode. ## Getting Started View the [Using Titanium Modules](http://docs.appcelerator.com/titanium/latest/#!/guide/Using_Titanium_Modules) document for instructions on getting started with using this module in your application. ## Accessing the Ti.PageFlip Module To access this module from JavaScript, you would do the following: var PageFlip = require('ti.pageflip'); ## Methods ### Ti.PageFlip.createView({...}) Creates a [Ti.PageFlip.View][]. #### Arguments Takes one argument, a dictionary with any of the properties from [Ti.PageFlip.View][]. ## Properties ### Ti.PageFlip.TRANSITION\_FLIP [readonly, int] When transitioning between pages, the page will "flip" from their spine. ### Ti.PageFlip.TRANSITION\_SLIDE [readonly, int] When transitioning between pages, the page will slide on and off the screen. ### Ti.PageFlip.TRANSITION\_FADE [readonly, int] When transitioning between pages, the pages will fade between each other. ### Ti.PageFlip.TRANSITION\_CURL [readonly, int, iOS 5 only] When transitioning between pages, the pages will curl between each other from their spine. ## Usage See example. ## Author <NAME> ## Module History View the [change log](changelog.html) for this module. ## Feedback and Support Please direct all questions, feedback, and concerns to [<EMAIL>](mailto:<EMAIL>?subject=iOS%20PageFlip%20Module). ## License Copyright(c) 2011-2013 by Appcelerator, Inc. All Rights Reserved. Please see the LICENSE file included in the distribution for further details. [Ti.PageFlip.View]: view.html<file_sep>/ios/documentation/view.md # Ti.PageFlip.View ## Description Displays flippable pages to the user. The user can turn pages by sliding their finger across the screen, or by taping on the far left or right to go back or advance, respectively. ## Properties ### pdf [string] A URL to a PDF document. If this property is specified, the module will automatically determine the page counts and views. If you want more control over what is visible, utilize the "pageCount" and "loadPage" properties. ### transition [int] Controls how the pages look when they flip. Defaults to _TRANSITION\_FLIP_ Use the TRANSITION_ constants in _[Ti.PageFlip][]_. ### transitionDuration [float] The number of seconds a complete transition should take. Defaults to 0.5. Note that the CURL transition does NOT support this property. ### pagingMarginWidth [int] The width of the area around the edge where the user can change pages. This includes both tap-to-advance and grabbing the edge of the page. Defaults to 10%. To disable this feature, set it to 0. Note that the CURL transition does NOT support this property. ### landscapeShowsTwoPages [bool] Indicates if two pages should be shown when the device is in its landscape orientation. Note that this does not influence the page numbering or counts. ### enableBuiltInGestures [bool] Controls whether or not the built in gestures are enabled (tap, pan, or swipe to change pages). ### pages [array] Contains all of the views that you want the user to be able to flip through. Can be any combination of visible elements, such as Ti.UI.View or Ti.UI.Label, etc. ### currentPage [int, readonly] The currently visible page. Use the "changeCurrentPage" method to move the user to another page. This uses a 0-based index. ### pageCount [int, readonly] Returns the total number of pages. ## Methods ### changeCurrentPage(index, animate) Moves the user to the specified page at the 0-based index, optionally animating them there. * index [int] The index to the page. * animate [bool, optional] Whether or not to animate the transition. ### insertPageBefore(index, page) Inserts a page in to the view hierarchy before the specified 0-based index. The pages after this index will be renumbered to make room for the new page. * index [int] The index _before_ which the page should be inserted. * page [view] Any combination of visible elements, such as Ti.UI.View or Ti.UI.Label, etc. ### insertPageAfter(index, page) Inserts a page in to the view hierarchy after the specified 0-based index. The pages after this index will be renumbered to make room for the new page. * index [int] The index _before_ which the page should be inserted. * page [view] Any combination of visible elements, such as Ti.UI.View or Ti.UI.Label, etc. ### appendPage(page) Appends a page to the end of the pages. * page [view] Any combination of visible elements, such as Ti.UI.View or Ti.UI.Label, etc. ### deletePage(index) Removes the page at the specified 0-based index. The pages after the specified index will be renumbered to take up the space left by the removed page. * index [int] The index _before_ which the page should be inserted. ## Events ### change Fired when the user moves to another page or the device reorients. Handlers will receive one dictionary as their first argument. The following properties will be available: * currentPage [int]: The 0-based index of the visible page. * pageCount [int]: The total number of pages. ### flipStarted Fired when a user starts to move to another page. ### tap Fired when the user taps inside of the pagingMarginWidth. This does not prevent other views inside the page flip from receiving touches. * currentPage [int]: The 0-based index of the clicked page. [Ti.PageFlip]: index.html
706757d587eafa61b12599ab564ccf957a6730b5
[ "JavaScript", "Markdown" ]
3
JavaScript
appcelerator-modules/ti.pageflip
271a09b4e8d5768d8354ad996410fb648e5213fb
a80ff0fbae73ddb8ea1d9a8f15fd2c1ba5db3865
refs/heads/main
<repo_name>skylarsmtih1269/Micro_II.Lab1<file_sep>/MICROLAB1_Revised.ino //Group Members: <NAME>, <NAME>, <NAME> int red = 10; int yellow = 9; int green = 8; int buzzer = 13; int button_Input = 7; void setup() { pinMode(red, OUTPUT); pinMode(yellow, OUTPUT); pinMode(green, OUTPUT); pinMode(button_Input, INPUT); pinMode(buzzer, OUTPUT); } void loop() { while(digitalRead(button_Input) == LOW) { digitalWrite(red, HIGH); delay(1000); digitalWrite(red, LOW); delay(1000); } if(digitalRead(button_Input) == HIGH) { changeLights(); } } void changeLights() { //Functions called to change the traffic light while(true) { green_on(); delay(20000); buzzerRG(); yellow_on(); delay(3000); buzzerY(); red_on(); delay(20000); buzzerRG(); } } void green_on() { digitalWrite(green, HIGH); digitalWrite(red, LOW); digitalWrite(yellow, LOW); } void yellow_on() { digitalWrite(yellow, HIGH); digitalWrite(red, LOW); digitalWrite(green, LOW); } void red_on() { digitalWrite(red,HIGH); digitalWrite(yellow, LOW); digitalWrite(green, LOW); } void buzzerRG() { digitalWrite(buzzer, LOW); delay(17000); digitalWrite(buzzer, HIGH); delay(3000); digitalWrite(buzzer, LOW); } void buzzerY() { digitalWrite(buzzer, HIGH); delay(3000); digitalWrite(buzzer, LOW); }
174349c2c0f4152f59435bd69c44a574c9bacff9
[ "C++" ]
1
C++
skylarsmtih1269/Micro_II.Lab1
87ca8e137b26eb9416283f5a9c20c6b1dc9b6455
96088a8ef80122aff5ff5d5431f52ef8b3b2015e
refs/heads/master
<file_sep>/* * XplainedRTOS.c * * Created: 2013-05-25 1:14:28 PM * Author: nrqm */ #include <util/delay.h> #include <avr/io.h> #include "os.h" enum { A=1, B, C, D, E, F, G }; const unsigned char PPP[] = {A, 20, B, 20, IDLE, 40, C, 20, D, 20, IDLE, 40}; const unsigned int PT = sizeof(PPP)/2; EVENT* e; //const unsigned char PPP[] = {}; //const unsigned int PT = 0; void periodic_task(void) { //uint8_t i; uint8_t arg = 0; arg = Task_GetArg(); uint8_t v = 0b10000000; if (arg == A) v = _BV(PB0); else if (arg == B) v = _BV(PB1); else if (arg == C) v = _BV(PB2); else if (arg == D) v = _BV(PB3); //Event_Wait(e); // periodic events can't wait! for(;;) { PORTB &= ~v; if (arg == A) _delay_ms(25); else if (arg == B) _delay_ms(75); else if (arg == C) _delay_ms(25); else if (arg == D) _delay_ms(75); PORTB |= v; Task_Next(); } } void rr_task() { for (;;) { Task_Next(); } } int r_main(void) { DDRB = 0xFF; PORTB = 0xFF; e = Event_Init(); // Task_Create params: function, parameter, level, name Task_Create(periodic_task, A, PERIODIC, A); Task_Create(periodic_task, B, PERIODIC, B); Task_Create(periodic_task, C, PERIODIC, C); Task_Create(periodic_task, D, PERIODIC, D); Task_Create(rr_task, 0, RR, 50); return 0; }<file_sep>rtos2 ===== Our real time operating system - project 2
dda73aaead2b12e663989eacc0c576c4e075aa02
[ "Markdown", "C" ]
2
C
sovay/rtos2
61350c33135151e71fc4fedcd5cc856f6139e367
b48d8c931217816f88e94e837f83080522e718a2
refs/heads/main
<file_sep><?php header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Headers: *"); header('Access-Control-Allow-Methods: POST, PUT, GET, DELETE, OPTIONS'); // local // $cn = mysqli_connect("localhost","root","","ubigeo"); // DATABASE HEROKU VARIABLES // heroku $cn = mysqli_connect("us-cdbr-east-04.cleardb.com","bbf959296dd944","e22a805b","heroku_0674d50a72a731f"); $cn->set_charset("utf8"); ?> <file_sep><?php //Include required PHPMailer files require 'includes/PHPMailer.php'; require 'includes/SMTP.php'; require 'includes/Exception.php'; //Define name spaces use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; function enviar_mensaje($correo_receptor='') { //Create instance of PHPMailer $mail = new PHPMailer(); //Set mailer to use smtp $mail->isSMTP(); //Define smtp host $mail->Host = "smtp.gmail.com"; //Enable smtp authentication $mail->SMTPAuth = true; //Set smtp encryption type (ssl/tls) $mail->SMTPSecure = "tls"; //Port to connect smtp $mail->Port = "587"; //Set gmail username $mail->Username = "<EMAIL>"; //Set gmail password $mail->Password = "<PASSWORD>"; //Email subject $mail->Subject = "MI EMPRESA - LIBRO DE RECLAMACION"; //Set sender email $mail->setFrom('<EMAIL>', 'TU_USUARIO'); //Enable HTML $mail->isHTML(true); //Attachment // $mail->addAttachment('img/attachment.png'); //Email body $mail->Body = "<h1>DOCUMENTO RECIBIDO CON EXITO</h1></br> <p>Gracias.</p> "; //Add recipient $mail->addAddress($correo_receptor); //Finally send email if ( $mail->send() ) { // echo "Email Sent..!"; return true; }else{ // echo "Message could not be sent. Mailer Error: "{$mail->ErrorInfo}; // echo "Message could not be sent. Mailer Error"; return false; } //Closing smtp connection $mail->smtpClose(); }<file_sep><?php require_once("./config/config.php"); mysqli_report(MYSQLI_REPORT_STRICT | MYSQLI_REPORT_OFF); $datos = []; if (isset($_GET['departamentos'])) { // seteamos departamentos $resultado = mysqli_query($cn,"SELECT * FROM departamento"); } else if (isset($_GET['provincias']) && isset($_GET['id_departamento'])) { // seteamos provincias $resultado = mysqli_query($cn,"SELECT * FROM provincia WHERE idDepa = {$_GET['id_departamento']}"); } else if (isset($_GET['distritos']) && isset($_GET['id_provincia'])) { // seteamos provincias $resultado = mysqli_query($cn,"SELECT * FROM distrito WHERE idProv = {$_GET['id_provincia']}"); } if (mysqli_num_rows($resultado) > 0) { while ($row = $resultado->fetch_assoc()) { $datos[] = $row; } } echo json_encode(["data" => $datos]); mysqli_close($cn); <file_sep>const MAIN_URL = "http://localhost/libroReclamos/api/"; // const MAIN_URL = "https://www.jair.educationhost.cloud/libro_reclamos/api/" const btnEnviar = document.querySelector("#btnEnviar"); btnEnviar.addEventListener('click', fetch_main); Date.prototype.toDateInputValue = (function() { var local = new Date(this); local.setMinutes(this.getMinutes() - this.getTimezoneOffset()); return local.toJSON().slice(0,10); }); $("#fecha_reclamo_queja").val(new Date().toDateInputValue()); async function fetch_main(){ limpiarErrores(); let data = { nombres : $("#nombres").val(), ap_paterno : $("#ap_paterno").val(), ap_materno : $("#ap_materno").val(), doc_identidad : $("#doc_identidad").val(), numero_doc : $("#numero_doc").val(), telefono : $("#telefono").val(), correo : $("#correo").val(), direccion : $("#direccion").val(), urbanizacion : $("#urbanizacion").val(), departamento : $("#departamento option:selected").text(), provincia : $("#provincia option:selected").text(), distrito : $("#distrito option:selected").text(), departamento_id : $("#departamento").val(), provincia_id : $("#provincia").val(), distrito_id : $("#distrito").val(), menor_edad: $("#menor_edad_si").is(":checked") ? 'SI' : 'NO', tienda : $("#tienda").val(), tipo : $("#tipo").val(), relacionado : $("#relacionado").val(), numero_pedido : $("#numero_pedido").val(), // fecha de hoy - setear automatico fecha_reclamo_queja : $("#fecha_reclamo_queja").val(), descripcion_bien_contratado : $("#descripcion_bien_contratado").val(), proveedor : $("#proveedor").val(), fecha_compra : $("#fecha_compra").val(), fecha_consumo : $("#fecha_consumo").val(), fecha_vencimiento : $("#fecha_vencimiento").val(), numero_lote : $("#numero_lote").val(), codigo_no_indespensable : $("#codigo_no_indespensable").val(), detalle_reclamo_queja : $("#detalle_reclamo_queja").val(), detalle_pedido_cliente : $("#detalle_pedido_cliente").val(), detalle_pedido_cliente : $("#detalle_pedido_cliente").val(), acciones_tomadas_empresa : $("#acciones_tomadas_empresa").val(), monto_reclamo : $("#monto_reclamo").val(), check_declaracion_titular : $("#check_declaracion_titular").is(':checked') ? true : false, check_terminos_condiciones : $("#check_terminos_condiciones").is(':checked') ? true : false } console.log(data) const request = await fetch(MAIN_URL+"libro_reclamo.php", { method: "POST", body: JSON.stringify(data), }); // const resp = await request.json().then((e) => e); let hasError = false; if (request.status == 201) { alert("Registrado Correctamente"); Swal.fire({ title: `Mensaje`, html: 'Creado Correctamente', icon: "success", }).then((result) => { //Relojeamos para evaluar el estado window.location.reload() }) } else { // ERROR hasError = true; await request.json().then((e) => { Swal.fire({ icon: 'error', title: 'Error', text: e.message }) mostrarErrores(e.errors) }); } } function mostrarErrores(errores){ console.log(errores) for (const key in errores) { $(`#${key}__error`).text(errores[key]); } } function limpiarErrores(){ $(".msg_error").text(""); } <file_sep><?php function jsonToCSV($jfilename, $cfilename) { if (($json = file_get_contents($jfilename)) == false) die('Error reading json file...'); $data = json_decode($json, true); $fp = fopen($cfilename, 'w'); $header = false; foreach ($data as $row) { if (empty($header)) { $header = array_keys($row); fputcsv($fp, $header); $header = array_flip($header); } fputcsv($fp, array_merge($header, $row)); } fclose($fp); // return; } $json_filename = __DIR__.'./data/data.json'; $csv_filename = __DIR__.'/data/data.csv'; jsonToCSV($json_filename, $csv_filename); ?><file_sep><?php $data['nombres'] = isset($_POST['nombres']) ? $_POST['nombres'] : ''; $data['ap_paterno'] = isset($_POST['ap_paterno']) ? $_POST['ap_paterno'] : ''; $data['ap_materno'] = isset($_POST['ap_materno']) ? $_POST['ap_materno'] : ''; $data['doc_identidad'] = isset($_POST['doc_identidad']) ? $_POST['doc_identidad'] : 'DNI'; $data['numero_doc'] = isset($_POST['numero_doc']) ? $_POST['numero_doc'] : ''; $data['telefono'] = isset($_POST['telefono']) ? $_POST['telefono'] : ''; $data['correo'] = isset($_POST['correo']) ? $_POST['correo'] : ''; $data['direccion'] = isset($_POST['direccion']) ? $_POST['direccion'] : ''; $data['urbanizacion'] = isset($_POST['urbanizacion']) ? $_POST['urbanizacion'] : ''; $list_docIdentidad = [ "DNI" => "DNI", "PASAPORTE" => "PASAPORTE", "CARNET_EXTRANJERIA" => "CARNET EXTRANJERIA", "RUC" => "RUC" ] ?> <!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.0"> <!-- bootstrap 5 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <!-- bootstrap 5 - ICONS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.5.0/font/bootstrap-icons.min.css" rel="stylesheet" type="text/css"> <!-- Main Css --> <link href="./resources/css/main.css" rel="stylesheet" type="text/css"> <title>Document</title> </head> <body> <!-- nav - logo --> <nav class="header"> <img class="header_logo" src="./resources/img/logo.png" alt="logo"> </nav> <!-- Seccion título --> <section class="title"> <h1 class=""><strong>Libro de Reclamaciones Empresa</strong></h1> <h5 class="my-4"><strong>RUC 123456789123</strong></h5> </section> <!-- Seccion INFO --> <section class="info"> <p class="text-danger"><strong>T129 - Wong.pe</strong></p> <p>Calle Augusto Angulo No 130 - Miraflores</p> <p>Teléfono: 613-8888 Opción 1 y luego opción 1</p> </section> <!-- Seccion Formulario --> <section class="container-md"> <!-- USUARIO DATOS --> <div class="card mt-4"> <div class="card-header d-flex"> <h4><i class="bi bi-person-circle text-danger"></i>  <strong>Identificación del Consumidor Reclamante</strong></h4> <span class="text-danger txt_obligatorio"><i><strong>    Datos Obligatorios *</i></strong></span> </div> <div class="card-body row p-5"> <div class="form group col-sm-12 col-md-6"> <label>Nombres<span class="text-danger"> *</span></label> <input type="text" name="nombres" class="form-control" value="<?= $data['nombres'] ?>"> <span class="text-danger msg_error" id="nombres__error"> <?= isset($data['errores']['nombres']) ? $data['errores']['nombres'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-3"> <label>Apellido Parno<span class="text-danger"> *</span></label> <input type="text" name="ap_paterno" class="form-control" value="<?= $data['ap_paterno'] ?>"> <span class="text-danger msg_error" id="ap_paterno__error"> <?= isset($data['errores']['ap_paterno']) ? $data['errores']['ap_paterno'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-3"> <label>Apellido Materno<span class="text-danger"> *</span></label> <input type="text" name="ap_materno" class="form-control" value="<?= $data['ap_materno'] ?>"> <span class="text-danger msg_error" id="ap_materno__error"> <?= isset($data['errores']['ap_materno']) ? $data['errores']['ap_materno'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Doc. Identidad<span class="text-danger"> *</span></label> <select id="doc_identidad" name="doc_identidad" class="form-control select2"> <?php foreach ($list_docIdentidad as $key => $value) { ?> <option <?= $key == $data['doc_identidad'] ? 'selected ="selected"' : '' ?> value="<?= $key ?>"><?= $value ?></option>; <?php } ?> </select> <span class="text-danger msg_error" id="doc_identidad__error"> <?= isset($data['errores']['doc_identidad']) ? $data['errores']['doc_identidad'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Numero Doc.<span class="text-danger"> *</span></label> <input type="text" name="numero_doc" class="form-control" value="<?= $data['numero_doc'] ?>"> <span class="text-danger msg_error" id="numero_doc__error"> <?= isset($data['errores']['numero_doc']) ? $data['errores']['numero_doc'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Teléfono / Celular<span class="text-danger"> *</span></label> <input type="number" name="telefono" class="form-control" value="<?= $data['telefono'] ?>" maxlength="12" oninput="if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" style="text-transform:uppercase;"> <span class="text-danger msg_error" id="telefono__error"> <?= isset($data['errores']['telefono']) ? $data['errores']['telefono'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-6"> <label>Correo Electrónico<span class="text-danger"> *</span></label> <input type="text" name="correo" class="form-control" value="<?= $data['correo'] ?>"> <span class="text-danger msg_error" id="correo__error"> <?= isset($data['errores']['correo']) ? $data['errores']['correo'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-3"> <label>Dirección<span class="text-danger"> *</span></label> <input type="text" name="direccion" class="form-control" value="<?= $data['direccion'] ?>"> <span class="text-danger msg_error" id="direccion__error"> <?= isset($data['errores']['direccion']) ? $data['errores']['direccion'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-3"> <label>Urbanización</label> <input type="text" name="urbanizacion" class="form-control" value="<?= $data['urbanizacion'] ?>"> <span class="text-danger msg_error" id="urbanizacion__error"> <?= isset($data['errores']['urbanizacion']) ? $data['errores']['urbanizacion'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Departamento<span class="text-danger"> *</span></label> <select id="departamento" name="departamento" class="form-control select2"> <option value="">Seleccione</option> </select> <span class="text-danger msg_error" id="departamento__error"> <?= isset($data['errores']['departamento']) ? $data['errores']['departamento'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Provincia<span class="text-danger"> *</span></label> <select id="provincia" name="provincia" class="form-control select2"> <option value="">Seleccione</option> </select> <span class="text-danger msg_error" id="provincia__error"> <?= isset($data['errores']['provincia']) ? $data['errores']['provincia'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-4"> <label>Distrito<span class="text-danger"> *</span></label> <select id="distrito" name="distrito" class="form-control select2"> <option value="">Seleccione</option> </select> <span class="text-danger msg_error" id="distrito__error"> <?= isset($data['errores']['distrito']) ? $data['errores']['distrito'] : ''; ?> </span><br> </div> <div class="form group mt-2 w-75 d-flex justify-content-around m-auto" style="max-width: 400px;"> <label>Eres Menor de Edad?</label> <div class="form-check" style="padding-right: 20px;"> <input id="radio_todos" class="form-check-input" value="SI" type="radio" name="radios_buttons" checked> <label class="form-check-label" for="radio_todos">SI</label> </div> <div class="form-check" style="padding-right: 20px;"> <input id="radio_entrada" class="form-check-input" value="NO" type="radio" name="radios_buttons"> <label class="form-check-label" for="radio_entrada">NO</label> </div> </div> </div> </div> <!-- DATOS DETALLE RECLAMACION--> <div class="card mt-4"> <div class="card-header d-flex"> <h4><i class="bi bi-person-circle text-danger"></i>  <strong>Detalle de la Reclamación y Pedido del Consumidor</strong></h4> <span class="text-danger txt_obligatorio"><i><strong>    Datos Obligatorios *</i></strong></span> </div> <div class="card-body row p-5"> <div class="form group col-sm-12 col-md-6"> <label>Tienda<span class="text-danger"> *</span></label> <select id="tienda" name="tienda" class="form-control select2"> <option value="">Seleccione</option> </select> <span class="text-danger msg_error" id="tienda__error"> <?= isset($data['errores']['tienda']) ? $data['errores']['tienda'] : ''; ?> </span><br> </div> <div class="form group col-sm-12 col-md-6"> </div> <!-- TIPOS --> <div class="form group col-sm-12 col-md-4"> <label>Seleccione Tipo<span class="text-danger"> *</span></label> <select id="tipo" name="tipo" class="form-control select2"> <option value="RECLAMO">Reclamo</option> <option value="QUEJA">Queja</option> </select> <span class="text-danger msg_error" id="tipo__error"> <?= isset($data['errores']['tipo']) ? $data['errores']['tipo'] : ''; ?> </span><br> </div> <!-- RELACIONADO --> <div class="form group col-sm-12 col-md-4"> <label>Seleccione Relacionado a <span class="text-danger"> *</span></label> <select id="relacionado" name="relacionado" class="form-control select2"> <option value="PRODUCTO">Producto</option> <option value="SERVICIO">Servicio</option> </select> <span class="text-danger msg_error" id="relacionado__error"> <?= isset($data['errores']['relacionado']) ? $data['errores']['relacionado'] : ''; ?> </span><br> </div> <!-- NRO PEDIDO --> <div class="form group col-sm-12 col-md-4"> <label>Nro° Pedido</label> <input type="text" name="numero_pedido" class="form-control"> <span class="text-danger msg_error" id="numero_pedido__error"> </span><br> </div> <!--FECHA RECLAMO / QUEJA --> <div class="form group col-sm-12 col-md-4"> <label>Fecha de reclamo / queja <span class="text-danger"> *</span></label> <input readonly type="text" name="fecha_reclamo_queja" class="form-control"> <span class="text-danger msg_error" id="fecha_reclamo_queja__error"> </span><br> </div> <!-- DESCRIPCION PRODUCTO / SERVICIO --> <div class="form group col-sm-12 col-md-8"> <label>Identificación del bien contratado: Descripción del producto o servicio <span class="text-danger"> *</span></label> <textarea rows="1" id="fecha_reclamo_queja" name="fecha_reclamo_queja" class="form-control"></textarea> <span class="text-danger msg_error" id="fecha_reclamo_queja__error"> </span><br> </div> <!--PROVEEDOR--> <div class="form group col-sm-12 col-md-3"> <label>Proveedor</label> <input type="text" name="proveedor" class="form-control"> <span class="text-danger msg_error" id="proveedor__error"> </span><br> </div> <!--FECHA COMPRA--> <div class="form group col-sm-12 col-md-3"> <label>Fecha de Compra</label> <input type="text" name="fecha_compra" class="form-control"> <span class="text-danger msg_error" id="fecha_compra__error"> </span><br> </div> <!--FECHA CONSUMO--> <div class="form group col-sm-12 col-md-3"> <label>Fecha de Consumo</label> <input type="text" name="fecha_consumo" class="form-control"> <span class="text-danger msg_error" id="fecha_consumo__error"> </span><br> </div> <!--FECHA COMPRA--> <div class="form group col-sm-12 col-md-3"> <label>Fecha de Vencimiento</label> <input type="text" name="fecha_vencimiento" class="form-control"> <span class="text-danger msg_error" id="fecha_vencimiento__error"> </span><br> </div> <!--NUMERO LOTE--> <div class="form group col-sm-12 col-md-6"> <label>Nr° Lote</label> <input type="text" name="numero_lote" class="form-control"> <span class="text-danger msg_error" id="numero_lote__error"> </span><br> </div> <!-- CODIGO --> <div class="form group col-sm-12 col-md-6"> <label>Código (no indespensable)</label> <input type="text" name="codigo_no_indesp" class="form-control"> <span class="text-danger msg_error" id="codigo_no_indesp__error"> </span><br> </div> <!-- DESCRIPCION PRODUCTO / SERVICIO --> <div class="form group col-sm-12 col-md-8"> <label>Detalle del Reclamo / Queja, según indica el cliente <span class="text-danger"> *</span></label> <textarea rows="3" id="detalle_reclamo_queja" name="detalle_reclamo_queja" class="form-control"></textarea> <span class="text-danger msg_error" id="detalle_reclamo_queja__error"> </span><br> </div> <!-- PEDIDO CLIENTE --> <div class="form group col-sm-12 col-md-4"> <label>Pedido del Cliente <span class="text-danger"> *</span></label> <textarea rows="3" id="detalle_pedido_cliente" name="detalle_pedido_cliente" class="form-control"></textarea> <span class="text-danger msg_error" id="detalle_pedido_cliente__error"> </span><br> </div> <!-- MONTO RECLAMADO --> <div class="form group col-sm-12 col-md-6"> <label>Monto Reclamado (S/.)</label> <input type="number" id="monto_reclamo" name="monto_reclamo" class="form-control"> <span class="text-danger msg_error" id="monto_reclamo__error"> </span><br> </div> <div class="form group col-sm-12 col-md-6"></div> <!-- ACCIONES TOMADA POR LA EMPRESA --> <div class="form group col-sm-12 col-md-6"> <label>Acciones tomadas por la empresa (Para ser llenado por el establecimiento) </label> <textarea rows="3" id="acciones_tomadas_empresa" name="acciones_tomadas_empresa" class="form-control"></textarea> <span class="text-danger msg_error" id="acciones_tomadas_empresa__error"> </span><br> </div> <div class="form group col-sm-12"> <p class="descripciones"><i><strong class="text-danger">(1) Reclamo:</strong> <span>Disconformidad relacionada a los productos y/o servicios.</span></i></p> <p class="descripciones"><i><strong class="text-danger">(2) Queja:</strong> <span>Disconformidad no relacionada a los productos y/o servicios; o, malestar o descontento a la atención al público.</span></i></p> </div> </div> </div> <!-- SECCION FINAL --> <div class="card mt-4"> <div class="card-body row p-5"> <div class="col-12"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="check_declaracion_titular"> <label class="form-check-label" for="declaracion_titular"> Declaro ser el titular del servicio y acepto el contenido del presente formulario manifestando bajo Declaración Jurada la veracidad de los hechos descritos. </label> <ul class="mt-2"> <li>La formulación del reclamo no impide acudir a otras vías de solución de controversias ni es requisito previo para interponer una denuncia ante Indecopi.</li> <li>El proveedor deberá dar respuesta al reclamo en un plazo no mayor a treinta (30) días calendario, pudiendo ampliar el plazo hasta por treinta días.</li> <li>Mediante la suscripción del presente documento el cliente autoriza a que lo contacten luego de atendido el reclamo a fin de evaluar la calidad y satisfacción con el proceso de atención de reclamos.</li> </ul> </div> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="check_terminos_condiciones"> <label class="form-check-label" for="terminos_condiciones"> He Leído y acepto la Política de Privacidad y Seguridad y la Política de Cookies" </label> </div> </div> <div class="col-12 d-flex justify-content-center"> <button class="mt-4 btn btn-dark" style="width: 150px;">ENVIAR</button> </div> </div> </div> </section> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep><?php require_once("./config/config.php"); date_default_timezone_set('America/Lima'); include __DIR__."./enviar_correo.php"; if($_SERVER['REQUEST_METHOD'] == 'POST'){ $errors = []; $_POST = json_decode(file_get_contents('php://input'), true); if(!isset($_POST["nombres"]) || strlen($_POST["nombres"]) <= 0 ) $errors['nombres'] = "Ingrese Nombres"; if(!isset($_POST["ap_paterno"]) || strlen($_POST["ap_paterno"]) <= 0 ) $errors['ap_paterno'] = "Ingrese Apellido Paterno"; if(!isset($_POST["ap_materno"]) || strlen($_POST["ap_materno"]) <= 0 ) $errors['ap_materno'] = "Ingrese Apellido Materno"; if(!isset($_POST["doc_identidad"]) || strlen($_POST["doc_identidad"]) <= 0 ) $errors['doc_identidad'] = "Ingrese Doc. Identidad"; if(!isset($_POST["numero_doc"]) || strlen($_POST["numero_doc"]) <= 0 ) $errors['numero_doc'] = "Ingrese Nr° Doc."; if(!isset($_POST["telefono"]) ) $_POST["telefono"] = ''; // ### CAN BE NULL if(!isset($_POST["correo"]) || strlen($_POST["correo"]) <= 0 ){ $errors['correo'] = "Ingrese Correo Electrónico"; }else{ if (!filter_var($_POST["correo"], FILTER_VALIDATE_EMAIL)) { $errors['correo'] = "Formato de Correo Electrónico inválido"; } } if(!isset($_POST["direccion"]) || strlen($_POST["direccion"]) <= 0 ) $errors['direccion'] = "Ingrese Direccion"; if(!isset($_POST["urbanizacion"]) ) $_POST["urbanizacion"] = ''; // ### CAN BE NULL if(!isset($_POST["departamento"]) || strlen($_POST["departamento"]) <= 0 ) $errors['departamento'] = "Ingrese Departamento"; if(!isset($_POST["provincia"]) || strlen($_POST["provincia"]) <= 0 ) $errors['provincia'] = "Ingrese Provincia"; if(!isset($_POST["distrito"]) || strlen($_POST["distrito"]) <= 0 ) $errors['distrito'] = "Ingrese Distrito"; if(!isset($_POST["departamento_id"]) || strlen($_POST["departamento_id"]) <= 0 ) { $_POST['departamento'] = ""; $errors['departamento_id'] = "Ingrese departamento"; } if(!isset($_POST["provincia_id"]) || strlen($_POST["provincia_id"]) <= 0 ){ $_POST['provincia'] = ""; $errors['provincia_id'] = "Ingrese provincia"; } if(!isset($_POST["distrito_id"]) || strlen($_POST["distrito_id"]) <= 0 ){ $_POST['distrito'] = ""; $errors['distrito_id'] = "Ingrese distrito"; } if(!isset($_POST["menor_edad"]) || strlen($_POST["menor_edad"]) <= 0 ) $errors['menor_edad'] = "Seleccione Consulta Edad"; if(!isset($_POST["tienda"]) || strlen($_POST["tienda"]) <= 0 ) $errors['tienda'] = "Seleccione Tienda"; if(!isset($_POST["tipo"]) || strlen($_POST["tipo"]) <= 0 ) $errors['tipo'] = "Seleccione Tipo "; if(!isset($_POST["relacionado"]) || strlen($_POST["relacionado"]) <= 0 ) $errors['relacionado'] = "Seleccione Relacionado a."; if(!isset($_POST["numero_pedido"]) ) $_POST["numero_pedido"] = ''; // ### CAN BE NULL if(!isset($_POST["fecha_reclamo_queja"]) || strlen($_POST["fecha_reclamo_queja"]) <= 0 ) $errors['fecha_reclamo_queja'] = "Ingrese fecha_reclamo_queja"; if(!isset($_POST["descripcion_bien_contratado"]) || strlen($_POST["descripcion_bien_contratado"]) <= 0 ) $errors['descripcion_bien_contratado'] = "Ingrese Identificacion del bien Contratado"; if(!isset($_POST["proveedor"]) ) $_POST["proveedor"] = ''; // ### CAN BE NULL if(!isset($_POST["fecha_compra"]) ) $_POST["fecha_compra"] = ''; // ### CAN BE NULL if(!isset($_POST["fecha_consumo"]) ) $_POST["fecha_consumo"] = ''; // ### CAN BE NULL if(!isset($_POST["fecha_vencimiento"]) ) $_POST["fecha_vencimiento"] = ''; // ### CAN BE NULL if(!isset($_POST["numero_lote"]) ) $_POST["numero_lote"] = ''; // ### CAN BE NULL if(!isset($_POST["codigo_no_indespensable"]) ) $_POST["codigo_no_indespensable"] = ''; // ### CAN BE NULL if(!isset($_POST["detalle_reclamo_queja"]) || strlen($_POST["detalle_reclamo_queja"]) <= 0 ) $errors['detalle_reclamo_queja'] = "Ingrese Detalle reclamo / queja"; if(!isset($_POST["detalle_pedido_cliente"]) || strlen($_POST["detalle_pedido_cliente"]) <= 0 ) $errors['detalle_pedido_cliente'] = "Ingrese Detalle del Pedido del cliemte"; if(!isset($_POST["monto_reclamo"]) ) $_POST["monto_reclamo"] = ''; // ### CAN BE NULL if(!isset($_POST["acciones_tomadas_empresa"]) ) $_POST["acciones_tomadas_empresa"] = ''; // ### CAN BE NULL if(!isset($_POST["check_declaracion_titular"]) || strlen($_POST["check_declaracion_titular"]) <= 0 ) $errors['check_declaracion_titular'] = "Acepte la Declaración titular del Servicio."; if(!isset($_POST["check_terminos_condiciones"]) || strlen($_POST["check_terminos_condiciones"]) <= 0 || $_POST["check_terminos_condiciones"] == false) $errors['check_terminos_condiciones'] = "Acepte las Políticas y Condiciones."; if (count($errors) > 0) { http_response_code(404); echo json_encode(["message" => "Corregir los errores.", "errors" => $errors]); die(); } $today = new DateTime(); $dayTime = date_format($today, 'Y-m-d H:i:s'); $day = date_format($today, 'Y-m-d'); $time = date_format($today, 'H:i:s'); $_POST["z_sistema_fecha_hora_creada"] = $dayTime; $_POST["z_sistema_fecha_creada"] = $day; $_POST["z_sistema_hora_creada"] = $time; $ruta_dataJson = __DIR__.'./data/data.json'; // Guardamos la data if (true) { // // obtenemos datajson en texto $dataJSON_TEXT = file_get_contents($ruta_dataJson); // // convertir texto to json $dataJSON_DECODE = json_decode($dataJSON_TEXT, true); // //contar y sumar más 1 por el ID $nuevaData = new ArrayObject(); $nuevaData["id"] = count($dataJSON_DECODE)+1; // seteamos nuevo arrayObject para colocar el id en la primera posición foreach($_POST as $k=>$v) $nuevaData[$k] = $v; // // setiar la nueva data al json array_Push($dataJSON_DECODE, $nuevaData); // // convertir nuevamente a texto el json $dataJSON_ENCODE = json_encode($dataJSON_DECODE, JSON_UNESCAPED_UNICODE); // // guardar la data en el archivo csv file_put_contents($ruta_dataJson, $dataJSON_ENCODE); // // actualizamos el archivo csv require_once(__DIR__.'./data_csv.php'); // enviamos el mensaje al usuario require_once(__DIR__.'./enviar_correo.php'); $error_email = ''; if(enviar_mensaje($_POST["correo"])) { $error_email = "Message sent!"; }else { $error_email = "Message NOT sent!"; } http_response_code(201); echo json_encode(["message" => "Registrado correctamente.", "email_enviado"=>$error_email]); } else { http_response_code(404); echo json_encode(["message" =>"Error en el servicio, Contacte a Sistemas."]); } die(); }
170b0ad85f23ed508f01b4cc58ec34bc059e840f
[ "JavaScript", "PHP" ]
7
PHP
22jair/libroReclamos
2dae91cf7618db6c418c8f0ab6e538a70875e6d1
9d3ca5022113effdf1bae49d5ece06b1e422756f
refs/heads/master
<repo_name>lidani/tictactoe<file_sep>/js/velha.js var main = new Vue({ el: '#app', data: { campos: [ " ", " ", " ", " ", " ", " ", " ", " ", " "], jogador: "X", ganhador: null }, methods: { jogar: function(i){ event.preventDefault(); if (this.campos[i] == " " && !this.verifica()){ if (this.jogador == "X"){ this.campos[i] = this.jogador; if (this.verifica()){ this.ganhador = "Parabéns, " + this.jogador + " ganhou."; } else { this.jogador = "O"; } } else { this.campos[i] = this.jogador; if (this.verifica()){ this.ganhador = "Parabéns, " + this.jogador + " ganhou."; } else { this.jogador = "X"; } } } else { if (this.verifica()){ // } else { console.log("Voce já jogou nessa casa."); } } }, verifica: function(){ if (this.ganhou(this.campos, "X") || this.ganhou(this.campos, "O")){ return true; } return false; }, ganhou: function(campos, jogador){ if (campos[0] == jogador && campos[1] == jogador && campos[2] == jogador){ return true; } if (campos[3] == jogador && campos[4] == jogador && campos[5] == jogador){ return true; } if (campos[6] == jogador && campos[7] == jogador && campos[8] == jogador){ return true; } if (campos[0] == jogador && campos[3] == jogador && campos[6] == jogador){ return true; } if (campos[1] == jogador && campos[4] == jogador && campos[7] == jogador){ return true; } if (campos[2] == jogador && campos[5] == jogador && campos[8] == jogador){ return true; } if (campos[0] == jogador && campos[4] == jogador && campos[8] == jogador){ return true; } if (campos[2] == jogador && campos[4] == jogador && campos[6] == jogador){ return true; } else { var arr = []; for (var j = 0; j < this.campos.length; j++) { if (this.campos[j] != " "){ arr.push(campos[j]); } } if (arr.length == 9){ this.ganhador = "Velha"; } else { arr = []; } } return false; } } });<file_sep>/README.md # tictactoe Tic Tac Toe for browser
eb88fe993b6f64578ef937963b18fc9efa641284
[ "JavaScript", "Markdown" ]
2
JavaScript
lidani/tictactoe
23578f73bb2fe9a6273810927fcf661d0cf6b618
df55ea543fbb8d7ba1b8e88c5a94140aab6b2b82
refs/heads/master
<file_sep>package com.example.receptionmedia; import java.util.ArrayList; import java.util.Set; import android.app.Activity; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; public class BluetoothActivity extends ListActivity{ private ProgressBar pg; private BluetoothAdapter bluetoothAdaptateur; private boolean D=false; private static final String TAG = "ClasseBluetooth"; private Button btn_scan; private ArrayAdapter<String> btArrayAdapter; Set<BluetoothDevice> pairedDevices; public static ArrayList<BluetoothDevice> foundDevices = new ArrayList<BluetoothDevice>(); String mode_de_connection = "Bluetooth"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bluetooth); pg = (ProgressBar) findViewById(R.id.progressBarDetectBlu); bluetoothAdaptateur = BluetoothAdapter.getDefaultAdapter(); btArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1); btn_scan = (Button)findViewById(R.id.btn_scan_blu); btn_scan.setOnClickListener(new OnClickListener(){ public void onClick(View v) { Attente at = new Attente(); at.execute(); bluetoothAdaptateur.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(discoveryResult, filter); pairedDevices = bluetoothAdaptateur.getBondedDevices(); btArrayAdapter.clear(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { String deviceBTName = device.getName(); foundDevices.add(device); btArrayAdapter.add(deviceBTName); } } setListAdapter(btArrayAdapter); } }); } BroadcastReceiver discoveryResult = new BroadcastReceiver() { public void onReceive(Context context, Intent intent){ String remoteDeviceName = intent.getStringExtra( BluetoothDevice.EXTRA_NAME); BluetoothDevice remoteDevice = intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE); Log.e(TAG,"jy suisssssssssssssssssssssssss 7"); btArrayAdapter.add(remoteDevice.getName()); foundDevices.add(remoteDevice); btArrayAdapter.notifyDataSetChanged(); } }; @Override protected void onListItemClick(ListView l, View v, int position, long id) { String value = (String)btArrayAdapter.getItem(position); Log.e("BluetoothActivity", value); Intent intent = new Intent(BluetoothActivity.this, RecuperationDonnees.class); intent.putExtra("modeComm", mode_de_connection); intent.putExtra("nameBluetoot", value); startActivity(intent); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); } public class Attente extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // TODO Auto-generated method stub try { Thread.sleep(12000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { // TODO Auto-generated method stub super.onPostExecute(result); pg.setVisibility(View.INVISIBLE); } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); pg.setVisibility(View.VISIBLE); } } } <file_sep>package com.example.receptionmedia; import android.app.Activity; import android.content.Intent; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class CreditsActivity extends Activity { TextView contact; //Button mail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_credits); contact = (TextView) findViewById(R.id.contact); contact.setPaintFlags(contact.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); contact.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent emailintent = new Intent(android.content.Intent.ACTION_SEND); emailintent.setType("plain/text"); emailintent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] {"<EMAIL>" }); startActivity(Intent.createChooser(emailintent, "Send mail...")); } }); } } <file_sep>package com.example.receptionmedia; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.Socket; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; public class RecuperationDonnees extends Activity{ private String adresseIP; private Socket socket; private ProgressBar pg; private ListView lv; private BufferedReader inFromServer; private List <String> bufferReception; private ArrayAdapter <String> array_reception; private HashMap<String, String> fichierATelecharger = new HashMap<String, String>(); private HashMap<String, String> site_internet = new HashMap<String, String>(); private static int cpt_promotion = 0; private static int cpt_site_ent = 0; private static int cpt_site_pro = 0; private String Promotion = "TÚlÚcharger promotion "; private String entete_dl = "DL :"; private String entete_site_ent = "SITE ENT :"; private String entete_site_pro = "SITE PRO :"; private String site_ent = "Site de l'entreprise "; private String site_pro = "Site du produit "; private String mode_de_communication; private String deviceBluetoothChoiceName; private static final String TAG = "Classe Recuperation Donnees"; private ArrayList<BluetoothDevice> foundDevices = new ArrayList<BluetoothDevice>(); private BluetoothDevice deviceSelected; private ClientBluetooth cb; private boolean premierLancement; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recuperation_donnees); lv = (ListView)findViewById(R.id.listViewComm); array_reception = new ArrayAdapter <String> (this, android.R.layout.simple_list_item_1); pg = (ProgressBar)findViewById(R.id.progressBarComm); premierLancement = true; } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart(); Bundle b = getIntent().getExtras(); mode_de_communication = b.getString("modeComm"); lv.setAdapter(array_reception); lv.setOnItemClickListener(Net); if(premierLancement) { premierLancement = false; if(mode_de_communication.equals("Wifi")) { adresseIP = b.getString("IP"); Log.e("RecuperationDonnees", "adresse IPPPPPPPPPPPPPPPP " + adresseIP); if (!adresseIP.equals("")) { CommClient commClient=new CommClient(); commClient.execute(); } } if(mode_de_communication.equals("Bluetooth")) { deviceBluetoothChoiceName = b.getString("nameBluetoot"); if(!deviceBluetoothChoiceName.equals("")) { Log.e(TAG,deviceBluetoothChoiceName); foundDevices = BluetoothActivity.foundDevices; for(BluetoothDevice bt : foundDevices) { if(bt.getName().equals(deviceBluetoothChoiceName)) deviceSelected = bt; } cb = new ClientBluetooth(deviceSelected); try { cb.connectServer(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } cb.start(); CommClient commClient=new CommClient(); commClient.execute(); } } } } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); } private OnItemClickListener Net = new OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { String value = (String)array_reception.getItem(arg2); System.out.println("VALUE : " + value); String fichier = null; if(value.contains("Site")) { for (Map.Entry<String, String> entry : site_internet.entrySet()) { if(entry.getKey().equals(value)) { fichier = entry.getValue(); System.out.println("fichier : " + fichier); } } if(mode_de_communication.equals("Wifi")) { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); if(wifiManager.isWifiEnabled()) wifiManager.setWifiEnabled(false); } startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(fichier))); } else { try { for (Map.Entry<String, String> entry : fichierATelecharger.entrySet()) { if(entry.getKey().equals(value)) { fichier = entry.getValue(); System.out.println("fichier : " + fichier); if(!fichier.contains("http")) { if(mode_de_communication.equals("Wifi")) { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); if(!wifiManager.isWifiEnabled()) { Toast.makeText(getApplicationContext(), " Attendez la reconnection du Wifi", Toast.LENGTH_LONG).show(); } wifiManager.setWifiEnabled(true); } if(mode_de_communication.equals("Bluetooth")) { } } } } getFile(fichier, "."); //String a ="\\Phone\\Download\\Autefage1-article.pdf"; //File f = getFile(a,"."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; public void getFile(String urlStr, String destFilePath) throws IOException, URISyntaxException { /*int current; if (urlStr == null) { Log.d("getFile", "null"); return null; } URL url = null; url = new URL(urlStr); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setUseCaches(true); InputStream is = con.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 8192); File streamFile = new File(destFilePath); if (!streamFile.exists()) { FileOutputStream fw = new FileOutputStream(streamFile); byte[] buffer = new byte[1024]; int bytes_read; while ((bytes_read = is.read(buffer)) != -1) { fw.write(buffer, 0, bytes_read); } fw.flush(); fw.close(); } else { return streamFile; } return streamFile;*/ File file = new File(".\\Phone"); if (file.exists()) { Uri path = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(path, "application/pdf"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(RecuperationDonnees.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show(); } } else { System.out.println("probleme le fichier n'existe pas"); } } private class CommClient extends AsyncTask<Void, Void, Void> { private String message; private BluetoothSocket socketBluetooth = null; @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(getApplicationContext(), "Recherche de documents provenant du drone", Toast.LENGTH_LONG).show(); } @Override protected Void doInBackground(Void... arg0) { try { if(mode_de_communication.equals("Wifi")) { Log.e("RecuperationDonnees", "je passsssssssssssssssssssse ici"); InetAddress serverAddr = InetAddress.getByName("192.168.1.27"/*adresseIP*/); Log.e("RecuperationDonnees", "je passsssssssssssssssssssse laaaaaaaaaaaaaa"); socket = new Socket(serverAddr, 8080); Log.e("RecuperationDonnees", "je passsssssssssssssssssssse hhhhhhhhhhhhhhhhhhhh"); inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); } if(mode_de_communication.equals("Bluetooth")) { while(!cb.isConnected()) System.out.println("pas connecte");; socketBluetooth = cb.getSocket(); System.out.println("socket bluetooth : " + socketBluetooth.toString()); inFromServer = new BufferedReader(new InputStreamReader(socketBluetooth.getInputStream())); } while (!(message = inFromServer.readLine()).equals("FIN")) { System.out.println("message : " + message); if((message.startsWith(entete_dl))) { final String cf; System.out.println( "dans le if : " + message); if(cpt_promotion != 0) cf = Promotion.concat(String.valueOf(cpt_promotion)); else cf = Promotion; cpt_promotion++; System.out.println("la clef est : " + cf); String tmp = message.substring(entete_dl.length(), message.length()); System.out.println("tmp : " + tmp); fichierATelecharger.put(cf, tmp); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub array_reception.add(cf); } }); } if((message.startsWith(entete_site_ent))) { final String cf; System.out.println("dans entete_site_entreprise"); String tmp = message.substring(entete_site_ent.length(), message.length()); if(cpt_site_ent !=0) cf = site_ent.concat(String.valueOf(cpt_site_ent)); else cf = site_ent; cpt_site_ent++; site_internet.put(cf, tmp); runOnUiThread( new Runnable() { public void run() { System.out.println("plop"); array_reception.add(cf); System.out.println("plop"); } }); System.out.println( "dans le else : " + message); } if((message.startsWith(entete_site_pro))) { final String cf; String tmp = message.substring(entete_site_pro.length(), message.length()); if(cpt_site_pro !=0) cf = site_pro.concat(String.valueOf(cpt_site_pro)); else cf = site_pro; cpt_site_pro++; site_internet.put(cf, tmp); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub array_reception.add(cf); } }); System.out.println( "dans le else : " + message); } } } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { if(mode_de_communication.equals("Wifi")) { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifiManager.setWifiEnabled(false); } pg.setVisibility(View.INVISIBLE); } } }
2190f1d60855efc83866b754f77bb666692dcaab
[ "Java" ]
3
Java
fcastagn/receptionMedia
c85b2600eb562c5b2324ac0e4fb01c7606c116c0
3fb1b00865e4785e7fc653503519496437d2dc19
refs/heads/master
<file_sep>package com.jen.sen; import com.jen.sen.untils.MD5Util; import com.jen.sen.untils.SysDateTimeUtil; import com.jen.sen.untils.Util; public class TestMd5 { public static void main(String[] args) { System.out.println("aaaaaaaaa:"+MD5Util.MD5("123456")); System.out.println("bbbbbbbbb:"+MD5Util.SHA256("123456")); System.out.println("ccccccccc:"+SysDateTimeUtil.getTimeStrBySeconds(30000)); ; } } <file_sep>/** * 初始化日期范围选择控件 */ function initdaterangepicker(daterangebtn,day){ $(daterangebtn).daterangepicker({ showDropdowns : true, format : "YYYY-MM-DD", dateLimit : { days : day }, //autoUpdateInput: false, locale : { cancelLabel : "清空" }, startDate : moment(), endDate : moment() }); $(daterangebtn).on('cancel.daterangepicker', function(ev,picker){ $(this).val(""); }); } /***************************************************************** jQuery Ajax封装通用类 (jenson.wang) *****************************************************************/ $(function(){ /** * ajax封装,正常和错误信息返回通用model * url 发送请求的地址 * data 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1} * async 空默认值: true。默认设置下,所有请求均为异步请求,要同步请将此选项设置为 false。 * 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。 * type 空认为 "post" * dataType 预期服务器返回的数据类型,,默认json */ jQuery.jenajax = function(url,data,async,type,dataType){ async = (async == null || async == "" || typeof (async) == "undefined") ? "true" : async; type = (type == null || type == "" || typeof (type) == "undefined") ? "post" : type; dataType = (dataType == null || dataType == "" || typeof (dataType) == "undefined") ? "json" : dataType; data = (data == null || data == "" || typeof (data) == "undefined") ? { "date" : new Date().getTime() } : data; $.ajax({ type : type, async : async, data : data, url : url, dataType : dataType, success : function(msg){ top.bootbox.alert({ title : "提示:", animate:false, message : msg.msg }); }, error : function(e){ top.bootbox.alert({ title : "错误提示:", animate:false, message : e.responseText }); } }); }; }); //绑定ajax内容到指定的Select控件 function BindSelect(ctrlName, url) { var control = $('#' + ctrlName); //设置Select2的处理 control.select2({ allowClear: true, formatResult: formatResult, formatSelection: formatSelection, escapeMarkup: function (m) { return m; } }); //绑定Ajax的内容 $.getJSON(url, function (data) { control.empty();//清空下拉框 $.each(data, function (i, item) { control.append("<option value='" + item.Value + "'>&nbsp;" + item.Text + "</option>"); }); }); } /** * 清空 */ function clearbtn(daterangebtn){ $(daterangebtn).value = ""; } /** * 判断是否为空 * * @param value * @returns {Boolean} */ function isNullorEmpty(value){ if (value == null || value == "" || typeof (value) == "undefined" || value == "null"){ return true; } return false; } /** * 包含某字符 * @param str * @param substr * @returns {Boolean} */ function isContains(str,substr){ return str.indexOf(substr) >= 0; } /** * 得到选中的复选框value的值,并以逗号相间隔 * * @author taoFangjin * @param checkName: * 一组复选框名称(name) * @returns {String ids} */ function getSelectedCheckList(checkName){ var ids = ""; $("input[name=" + checkName + "][type=checkbox]").each(function(){ var $input = $(this); if ($input.prop("checked") == true){ ids += (this.value + ","); } }); if (ids != ""){ ids = ids.substring(0, ids.length - 1); } return ids; }; /** * 得到下拉框(select)的value的值,并以逗号相间隔 * * @author taoFangjin * @param checkName: * 一组复选框名称(name) * @returns {String ids} */ function getSelectedList(selectName){ var ids = ""; $(selectName+" :selected").each(function(){ ids += (this.value + ","); }); if (ids != ""){ ids = ids.substring(0, ids.length - 1); } return ids; }; //字符串去掉首尾空格 function lrTrim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } //字符串去掉所有空格 function Trim(str) { return str.replace(/\s/g,""); } //数组对象转换,以,分开对象某个属性的字符串,如:[{id:"1",name:"asd"},{id:"2",name:"sdf"}] function ArryObtoStr(sNodes,node) { var choose = ""; for (var i=0;i<sNodes.length;i++) { var str=sNodes[i][node]; if(!isNullorEmpty(str)) { choose+= (i == (sNodes.length-1))?str:str+","; } } return choose; } //数组转换成以,分开的字符串 如["asd","sdf","dfg"] function ArrytoStr(array){ return array.join(); }<file_sep>package com.jen.sen.exception; public class AjaxException extends RuntimeException { private static final long serialVersionUID = 1L; private String errCode; private String errMsg; public AjaxException (String errCode,String errMsg){ this.errCode=errCode; this.errMsg=errMsg; } public AjaxException() { } public String getErrCode() { return errCode; } public void setErrCode(String errCode) { this.errCode = errCode; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public static AjaxException create(String errCode, String errMsg){ return new AjaxException(errCode, errMsg); } } <file_sep>package com.jen.sen.web.component; import java.io.Serializable; import java.util.List; /** * 菜单vo * filename MenuTreeComponent.java * company jen * @author jenson * @email <EMAIL> */ public class MenuTreeComponent implements Serializable { private static final long serialVersionUID = -1523002859550851821L; /** 单菜ID */ private Long rightId; /** 父菜单ID */ private Long rightParentId; /** 子菜单列表 */ private List<MenuTreeComponent> subMenus; /** 菜单级别 */ private Integer rightLevel; /** 菜单排序值 */ private Integer rightOrder; /** 菜单编号 */ private String rightCode; /** 菜单名称 */ private String rightName; /** 菜单图标 font awesome*/ private String rightImg; /** 菜单访问URL */ private String rightUrl; /** 菜单访问授权 */ private String perms; public Long getRightId() { return rightId; } public void setRightId(Long rightId) { this.rightId = rightId; } public Long getRightParentId() { return rightParentId; } public void setRightParentId(Long rightParentId) { this.rightParentId = rightParentId; } public List<MenuTreeComponent> getSubMenus() { return subMenus; } public void setSubMenus(List<MenuTreeComponent> subMenus) { this.subMenus = subMenus; } public Integer getRightLevel() { return rightLevel; } public void setRightLevel(Integer rightLevel) { this.rightLevel = rightLevel; } public Integer getRightOrder() { return rightOrder; } public void setRightOrder(Integer rightOrder) { this.rightOrder = rightOrder; } public String getRightCode() { return rightCode; } public void setRightCode(String rightCode) { this.rightCode = rightCode; } public String getRightName() { return rightName; } public void setRightName(String rightName) { this.rightName = rightName; } public String getRightUrl() { return rightUrl; } public void setRightUrl(String rightUrl) { this.rightUrl = rightUrl; } public String getRightImg() { return rightImg; } public void setRightImg(String rightImg) { this.rightImg = rightImg; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } } <file_sep>package com.jen.sen.service.system.role; import java.util.List; import java.util.Map; import com.jen.sen.exception.AjaxException; import com.jen.sen.persistence.core.dao.tools.PageDT; import com.jen.sen.persistence.pojo.system.TRoles; import com.jen.sen.web.vo.system.RoleVo; public interface IRoleService { public RoleVo findRole(Long Roleid) throws AjaxException; public List<RoleVo> findRoleByUserId(Long UserId) throws AjaxException; public List<RoleVo> findRole() throws AjaxException; public List<RoleVo> findRolePage(Map<String, Object> parms, PageDT page) throws AjaxException; public int findRolePageCount(Map<String, Object> parms) throws AjaxException; public void updateRoleState(String ids) throws AjaxException; public void saveOrupdateRole(RoleVo vo) throws Exception; public void saveOrupdateRoleAndRight(String rightids,RoleVo vo) throws Exception; public void saveOrupdateRoleByUserId(Long userid,String ids) throws Exception; public List<Map<String, Object>> findRightTree() throws AjaxException; public List<Map<String, Object>> findRightTreeByID(Long roleID) throws AjaxException; } <file_sep>package unit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4jTest { private static final Logger logger = LogManager.getLogger(Log4jTest.class); public static void main(String[] args) { logger.info("This is an info log111."); logger.warn("This is a warn log.111"); logger.error("This is a error log.111"); // } }<file_sep>package com.jen.sen.commons; /** * 声明所有需要声明名字的Spring bean的名字, 声明的规则为接口类名,并且类名的第一个字母为小写。 * filename BeanConstant.java * company jen * @author jenson * @email <EMAIL> */ public class BeanConstant { /* =========== DAO 声明实例名称========================================= */ /* ============ 1.系统管理Dao============ */ /** 用户管理Dao */ public static final String I_USER_DAO = "iUserDao"; public static final String I_ROLE_DAO = "iRoleDao"; public static final String I_SYSTEM_DAO = "iSystemDao"; /* =========== Service 声明实例名称========================================= */ /** 用户管理Service */ public static final String I_USER_SERVICE = "iUserService"; public static final String I_Role_SERVICE = "iRoleService"; public static final String I_SYSTEM_SERVICE = "iSystemService"; /* =========== 1.系统管理Service============ */ } <file_sep>package com.jen.sen.persistence.dao.system; import java.util.List; import java.util.Map; import java.util.Set; /** * * @author jenson * @Date 2016-5-17 */ import com.jen.sen.persistence.core.dao.FrameCenterDao; import com.jen.sen.persistence.pojo.system.TUser; public interface ISystemDao extends FrameCenterDao<TUser> { public List<Map<String, Object>> findMenuTreeByUser(Long userId); public List<Map<String, Object>> findMenuTreeAll(); public TUser findByUserName(String userName) ; public Set<String> findAllPerms(); public Set<String> findPermsByUserId(Long Userid); } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jen.sen</groupId> <artifactId>JEN-PARENT</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version.source>1.8</java.version.source> <java.version.target>1.8</java.version.target> <junit.version>4.10</junit.version> <springframework.version>4.2.7.RELEASE</springframework.version> <hibernate.version>4.3.11.Final</hibernate.version> <ehcache.version>4.3.11.Final</ehcache.version> <log4j.version>2.5</log4j.version> <mysql.connectorJ.version>5.1.38</mysql.connectorJ.version> <servlet-api.version>3.1.0</servlet-api.version> <jsp-api.version>2.2</jsp-api.version> <jstl.version>1.2</jstl.version> <com.jen.sen.version>${project.version}</com.jen.sen.version> <fastjson.version>1.2.11</fastjson.version> <jackson.version>2.8.2</jackson.version> <commons-lang3.version>3.4</commons-lang3.version> <xmemcached.version>2.0.1</xmemcached.version> <springmemcached.version>3.6.1</springmemcached.version> <xmemcachedprovider.version>3.6.1</xmemcachedprovider.version> <joda.version>2.9.4</joda.version> <httpclient.version>4.5.2</httpclient.version> <httpcore.version>4.4.5</httpcore.version> <shiro.version>1.3.2</shiro.version> <kaptcha.version>0.0.9</kaptcha.version> <jedis.version>2.9.0</jedis.version> <sdredis.version>1.8.1.RELEASE</sdredis.version> </properties> <modules> <module>../JEN-DAO</module> <module>../JEN-COMMON</module> <module>../JENWEB</module> </modules> <dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- the followings should be provided by container --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- spring4.2.5 configuration --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-context-support --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${springframework.version}</version> </dependency> <!-- hibernate configuration --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>${hibernate.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>${log4j.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>${log4j.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j.version}</version> </dependency> <!-- mysql configuration --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connectorJ.version}</version> </dependency> <!-- fastjson configuration --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${ehcache.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.googlecode.xmemcached</groupId> <artifactId>xmemcached</artifactId> <version>${xmemcached.version}</version> </dependency> <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>simple-spring-memcached</artifactId> <version>${springmemcached.version}</version> </dependency> <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>xmemcached-provider</artifactId> <version>${xmemcachedprovider.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/joda-time/joda-time --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${joda.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>${httpcore.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>${kaptcha.version}</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>${jedis.version}</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${sdredis.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>3.0.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.7</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.4</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> </plugin> </plugins> </pluginManagement> </build> </project> <file_sep>package com.jen.sen.web.controller.system.role; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jen.sen.commons.Constant; import com.jen.sen.exception.AjaxException; import com.jen.sen.persistence.core.dao.tools.PageDT; import com.jen.sen.service.system.role.IRoleService; import com.jen.sen.untils.DateUtils; import com.jen.sen.untils.Util; import com.jen.sen.web.component.ajaxComponent; import com.jen.sen.web.vo.system.RoleVo; /** * * filename roleController.java * company jen * @author jenson * @email <EMAIL> */ @Controller @RequestMapping(value = "system/role") public class roleController { @Resource private IRoleService iRoleService; private final static String JSP_DIR = "system/role/"; @RequestMapping(value = "/roleEdit") public ModelAndView roleEditPage(HttpServletRequest request,ModelAndView mv) { String id=Util.getParameterString(request,"id"); String rdonly=Util.getParameterString(request,"rdonly"); mv.addObject("roleId", id); mv.addObject("rdonly", rdonly); mv.setViewName(JSP_DIR+"roleEdit"); return mv; } @RequestMapping(value = "/roleManage") @RequiresPermissions("sys:role") public ModelAndView roleManagePage(HttpServletRequest request,ModelAndView mv) { mv.setViewName(JSP_DIR+"roleManage"); return mv; } @ResponseBody @RequestMapping(value ="/findRole") public ajaxComponent<RoleVo> findRole(HttpServletRequest request) throws AjaxException{ ajaxComponent<RoleVo> ajaxComponent = new ajaxComponent<RoleVo>(); String roleName = Util.getParameterString(request,"qyroleName"); String roleStatus = Util.getParameterString(request,"qystatus"); Map<String, Object> parms= new HashMap<String, Object>(); parms.put("roleName", roleName); parms.put("roleStatus", roleStatus); int draw = Util.getParameterInt(request,"draw"); int start = Util.getParameterInt(request,"start"); int count=0; PageDT pd = new PageDT(draw,start); count = iRoleService.findRolePageCount(parms); pd.setRecordsFiltered(count); List<RoleVo> roleVoList = iRoleService.findRolePage(parms, pd); ajaxComponent.setData(roleVoList); ajaxComponent.setDraw(draw); ajaxComponent.setRecordsTotal(pd.getRecordsFiltered()); ajaxComponent.setRecordsFiltered(pd.getRecordsFiltered()); return ajaxComponent; } @ResponseBody @RequestMapping(value ="/findSelectRole") public ajaxComponent<RoleVo> findAllRole(HttpServletRequest request) throws AjaxException{ ajaxComponent<RoleVo> ajaxComponent = new ajaxComponent<RoleVo>(); Long UserId = Util.getParameterLong(request,"userid"); if(UserId<1){ throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } List<RoleVo> roleVoList1 = iRoleService.findRole(); List<RoleVo> roleVoList2 = iRoleService.findRoleByUserId(UserId); ajaxComponent.setData(roleVoList1); ajaxComponent.setDataSec(roleVoList2); return ajaxComponent; } @SuppressWarnings("rawtypes") @ResponseBody @RequestMapping(value ="/updatestate",method = RequestMethod.POST) public ajaxComponent updateroleState(HttpServletRequest request) { String ids = Util.getParameterString(request,"Ids"); try { iRoleService.updateRoleState(ids); } catch (Exception e) { throw new AjaxException(); } return new ajaxComponent(); } @ResponseBody @RequestMapping(value = "/saveOrUpdateRole",method=RequestMethod.POST) public ajaxComponent<RoleVo> saveOrUpdateRole(HttpServletRequest request) { ajaxComponent<RoleVo> ajaxComponent = new ajaxComponent<RoleVo>(); RoleVo uv = new RoleVo(); try { Long id =Util.getParameterLong(request,"id"); String rightids=Util.getParameterString(request,"rightIDS"); if(id>0){ uv=iRoleService.findRole(id); }else{ uv.setCreateTime(DateUtils.now()); } uv.setRoleName(Util.getParameterString(request,"iptname")); uv.setStatus(new Short(request.getParameter("iptstatus"))); uv.setRemark(Util.getParameterString(request,"iptremark")); uv.setUpdateTime(DateUtils.now()); iRoleService.saveOrupdateRoleAndRight(rightids,uv); ajaxComponent.setVoObject(uv); } catch (Exception e) { throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } return ajaxComponent; } @ResponseBody @RequestMapping(value = "/queryRole") public ajaxComponent<RoleVo> queryRolebyID(HttpServletRequest request) { Long id = Util.getParameterLong(request,"id"); if(id<1){ throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } ajaxComponent<RoleVo> ajaxComponent = new ajaxComponent<RoleVo>(); RoleVo uv = new RoleVo(); uv=iRoleService.findRole(id); ajaxComponent.setVoObject(uv); return ajaxComponent; } @ResponseBody @RequestMapping(value = "/queryRoleByuserId") public ajaxComponent<RoleVo> queryRolebyUserID(HttpServletRequest request) { Long id = Util.getParameterLong(request,"userid"); if(id<1){ throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } ajaxComponent<RoleVo> ajaxComponent = new ajaxComponent<RoleVo>(); List<RoleVo> roleVoList=iRoleService.findRoleByUserId(id); ajaxComponent.setData(roleVoList); return ajaxComponent; } @SuppressWarnings("rawtypes") @ResponseBody @RequestMapping(value = "/updateRoleByID",method=RequestMethod.POST) public ajaxComponent updateRoleByUserId(HttpServletRequest request) { ajaxComponent ajaxComponent = new ajaxComponent(); try { Long userId = Util.getParameterLong(request,"userId"); String roleids = Util.getParameterString(request,"ids"); if(userId>0){ iRoleService.saveOrupdateRoleByUserId(userId, roleids); } ajaxComponent.setMsg(Constant.SYSTEM_SUCCESS_INFO); } catch (Exception e) { throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } return ajaxComponent; } @SuppressWarnings("rawtypes") @ResponseBody @RequestMapping(value = "/treeData",method=RequestMethod.POST) public ajaxComponent Treedate(HttpServletRequest request) { ajaxComponent<?> ajaxComponent = new ajaxComponent(); try { Long roleId =Util.getParameterLong(request,"roleId"); List<Map<String, Object>> lsm1= iRoleService.findRightTree(); List<Map<String, Object>> lsm2= iRoleService.findRightTreeByID(roleId); //设置角色对应的权限为选中状态(树形菜单) for(Map<String, Object> map2:lsm2){ for(Map<String, Object> map1:lsm1){ if(map2.get("right_id").equals(map1.get("right_id"))){ map1.put("checked", true); break; } } } ajaxComponent.setMap(lsm1); ajaxComponent.setMapSec(lsm2); ajaxComponent.setMsg(Constant.SYSTEM_SUCCESS_INFO); } catch (Exception e) { throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } return ajaxComponent; } } <file_sep>package com.jen.sen.web.controller.system.user; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.jen.sen.commons.Constant; import com.jen.sen.exception.AjaxException; import com.jen.sen.persistence.core.dao.tools.PageDT; import com.jen.sen.service.system.admin.ISystemService; import com.jen.sen.service.system.user.IUserService; import com.jen.sen.shiro.ShiroUtils; import com.jen.sen.untils.DateUtils; import com.jen.sen.untils.Util; import com.jen.sen.web.component.ajaxComponent; import com.jen.sen.web.vo.system.UserVo; /** * * filename UserController.java * company jen * @author jenson * @email <EMAIL> */ @Controller @RequestMapping(value = "system/user") public class UserController { @Resource private IUserService iUserService; @Resource private ISystemService iSystemService; private final static String JSP_DIR = "system/user/"; @RequestMapping(value = "/addUser") public ModelAndView userEditPage(HttpServletRequest request,ModelAndView mv) { mv.setViewName(JSP_DIR+"userEdit"); return mv; } @RequestMapping(value = "/userManage") @RequiresPermissions("sys:user") public ModelAndView userManagePage(HttpServletRequest request,ModelAndView mv) { mv.setViewName(JSP_DIR+"userManage"); return mv; } @ResponseBody @RequestMapping(value ="/findUser") public ajaxComponent<UserVo> findUser(HttpServletRequest request) throws AjaxException{ ajaxComponent<UserVo> ajaxComponent = new ajaxComponent<UserVo>(); String userAccount = Util.getParameterString(request,"qyuserAccount"); String userName = Util.getParameterString(request,"qyuserName"); String userStatus = Util.getParameterString(request,"qystatus"); String screatetime = Util.getParameterString(request,"screateTime"); String ecreatetime = Util.getParameterString(request,"ecreatesTime"); Map<String, Object> parms= new HashMap<String, Object>(); parms.put("userAccount", userAccount); parms.put("userName", userName); parms.put("userStatus", userStatus); parms.put("screatetime", screatetime); parms.put("ecreatetime", ecreatetime); int draw =Util.getParameterInt(request,"draw"); int start = Util.getParameterInt(request,"start"); int count=0; PageDT pd = new PageDT(draw,start); count = iUserService.findUserPageCount(parms); pd.setRecordsFiltered(count); List<UserVo> userVoList = iUserService.findUserPage(parms, pd); ajaxComponent.setData(userVoList); ajaxComponent.setDraw(draw); ajaxComponent.setRecordsTotal(pd.getRecordsFiltered()); ajaxComponent.setRecordsFiltered(pd.getRecordsFiltered()); return ajaxComponent; } @SuppressWarnings("rawtypes") @ResponseBody @RequestMapping(value ="/updatestate",method = RequestMethod.POST) public ajaxComponent updateUserState(HttpServletRequest request) { String ids = Util.getParameterString(request,"userIds"); try { iUserService.updateUserState(ids); } catch (Exception e) { throw new AjaxException(); } return new ajaxComponent(); } @ResponseBody @RequestMapping(value = "/saveOrUpdateUser",method=RequestMethod.POST) public ajaxComponent<UserVo> saveOrUpdateUser(HttpServletRequest request) { ajaxComponent<UserVo> ajaxComponent = new ajaxComponent<UserVo>(); UserVo uv = new UserVo(); try { Long id = Util.getParameterLong(request, "id"); //Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id")); if(id>0){ uv = iUserService.findUser(id); }else{ uv.setCreateTime(DateUtils.now()); } uv.setUserAccount(Util.getParameterString(request,"iptaccount")); uv.setUserName(Util.getParameterString(request,"iptname")); uv.setUserSex(Short.parseShort(request.getParameter("rsex")==null?"1":request.getParameter("rsex"))); uv.setUserIphone(Util.getParameterString(request,"iptphone")); uv.setUserBirthday(DateUtils.strToDateWithFormat(request.getParameter("iptborn"),"yyyy-MM-dd")); uv.setUserEmail(Util.getParameterString(request,"iptemail")); uv.setUserAddress(Util.getParameterString(request,"iptaddress")); uv.setRemark(Util.getParameterString(request,"iptremark")); uv.setStatus((short)1); uv.setUserPassword(<PASSWORD>("<PASSWORD>")); uv.setUpdateTime(DateUtils.now()); iUserService.saveOrupdateUser(uv); ajaxComponent.setVoObject(uv); } catch (Exception e) { throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } return ajaxComponent; } @ResponseBody @RequestMapping(value = "/queryUser") public ajaxComponent<UserVo> queryUserbyID(HttpServletRequest request) { Long id = Util.getParameterLong(request,"id"); if(id<1){ throw AjaxException.create(Constant.SYSTEM_AJAX_Code, Constant.SYSTEM_ERROR_INFO); } ajaxComponent<UserVo> ajaxComponent = new ajaxComponent<UserVo>(); UserVo uv = new UserVo(); uv=iUserService.findUser(id); ajaxComponent.setVoObject(uv); return ajaxComponent; } } <file_sep>package com.jen.sen.web.controller.system.admin; import java.awt.image.BufferedImage; import java.io.IOException; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import com.jen.sen.shiro.ShiroUtils; import com.jen.sen.untils.Util; import com.jen.sen.web.component.ajaxComponent; @Controller @RequestMapping(value = "system") public class loginController { private final static String JSP_DIR = "system"; @Resource private Producer KaptchaProducer; @RequestMapping("captcha.jpg") public void captcha(HttpServletResponse response) throws ServletException, IOException { response.setDateHeader("Expires", 0);// 禁止服务器端缓存 // 设置标准的 HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache");// 设置标准 HTTP/1.0 不缓存图片 response.setContentType("image/jpeg"); // 生成文字验证码 String text = KaptchaProducer.createText(); // 生成图片验证码 BufferedImage image = KaptchaProducer.createImage(text); // 保存到shiro session ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); } /** * //清除 shiro授权缓存,废弃,使用redis缓存,以spring缓存注解方式处理 * * @RequestMapping(value = "/clsCache", method = RequestMethod.GET) public * void ClsCache(HttpServletRequest request, * ModelAndView mv) { UserShiroRealm usr= * (UserShiroRealm)SpringBeanTools.getBean("userRealm" * ); usr.clearCachedAuthorizationInfo(ShiroUtils. * getSubject().getPrincipal()); } */ @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView showLoginPage(HttpServletRequest request, ModelAndView mv) { mv.setViewName(JSP_DIR + "/sysLogin"); return mv; } @RequestMapping(value = "/main") public ModelAndView loginSuccessPage(HttpServletRequest request, ModelAndView mv) { mv.setViewName(JSP_DIR + "/sysMain"); return mv; } @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST) public ajaxComponent<?> loginForm(HttpServletRequest request, ModelAndView mv) { ajaxComponent<?> ajaxComponent = new ajaxComponent<>(); String error = null; String account = Util.getParameterString(request,"account"); String pwd = Util.getParameterString(request,"password"); String captcha = Util.getParameterString(request,"captcha"); String captchasession = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY); if (!captcha.equalsIgnoreCase(captchasession)) { error = "验证码不正确"; ajaxComponent.setMsg(error); return ajaxComponent; } // 加密密码 String password = <PASSWORD>(pwd); Subject subject = ShiroUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(account, password); try { subject.login(token); } catch (UnknownAccountException e) { error = e.getMessage(); } catch (IncorrectCredentialsException e) { error = e.getMessage(); } catch (LockedAccountException e) { error = e.getMessage(); } catch (AuthenticationException e) { // 其他错误,比如锁定,如果想单独处理请单独catch处理 error = "账户验证失败:" + e.getMessage(); } ajaxComponent.setMsg(error); return ajaxComponent; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public ModelAndView logout(HttpServletRequest request, ModelAndView mv) { // 使用权限管理工具进行用户的退出,跳出登录,给出提示信息 SecurityUtils.getSubject().logout(); mv.setViewName(JSP_DIR + "/sysLogin"); return mv; } } <file_sep>jQuery.extend(jQuery.validator.messages, { required: "必选字段", remote: "请修正该字段", email: "请输入正确格式的电子邮件", url: "请输入合法的网址", date: "请输入合法的日期", dateISO: "请输入合法的日期 (格式yyyy-mm-dd).", number: "请输入合法的数字", digits: "只能输入整数", creditcard: "请输入合法的信用卡号", equalTo: "请再次输入相同的值", accept: "请输入拥有合法后缀名的字符串", maxlength: jQuery.validator.format("请输入一个 长度最多是 {0} 的字符串"), minlength: jQuery.validator.format("请输入一个 长度最少是 {0} 的字符串"), rangelength: jQuery.validator.format("请输入 一个长度介于 {0} 和 {1} 之间的字符串"), range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"), max: jQuery.validator.format("请输入一个最大为{0} 的值"), min: jQuery.validator.format("请输入一个最小为{0} 的值") }); jQuery.validator.addMethod("isnumAndLetters",function(value,element){ return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value); },$.validator.format("请输入字母或数字") ); jQuery.validator.addMethod("isloginname", function(value, element) { var char = /^[a-zA-Z0-9\u4e00-\u9fa5-_]+$/; return this.optional(element) || char.test(value); }, $.validator.format("登录名只能包含中文、英文、数字、下划线")); jQuery.validator.addMethod("isidcard",function(value,element){ return this.optional(element) || /^(\d{14}|\d{17})(\d|[xX])$/.test(value); },$.validator.format("请输入合法身份证号")); //电话号码验证 jQuery.validator.addMethod("isTel", function(value, element) { var tel = /^\d{3,4}-?\d{7,9}$/; //电话号码格式010-12345678 return this.optional(element) || (tel.test(value)); }, "请正确填写您的电话号码"); jQuery.validator.addMethod("isMobile", function(value, element) { var length = value.length; var mobile = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/; return this.optional(element) || (length == 11 && mobile.test(value)); }, "手机格式不正确"); //联系电话(手机/电话皆可)验证 jQuery.validator.addMethod("isPhone", function(value,element) { var length = value.length; var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/; var tel = /^\d{3,4}-?\d{7,9}$/; return this.optional(element) || (tel.test(value) || mobile.test(value)); }, "请正确填写您的联系电话"); jQuery.validator.addMethod("isIp", function(value, element) { var chrnum = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/; return this.optional(element) || chrnum.test(value); }, "ip格式不正确");<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>com.jen.sen</groupId> <artifactId>JEN-PARENT</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>JENWEB</artifactId> <packaging>war</packaging> <dependencies> <dependency> <groupId>com.jen.sen</groupId> <artifactId>JEN-DAO</artifactId> <version>${com.jen.sen.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- the followings should be provided by container --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- spring4.2.5 configuration --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <scope>test</scope> </dependency> <!-- hibernate configuration --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> </dependency> <!-- http://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> </dependency> <!-- mysql configuration --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> <dependency> <groupId>com.googlecode.xmemcached</groupId> <artifactId>xmemcached</artifactId> </dependency> <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>simple-spring-memcached</artifactId> </dependency> <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>xmemcached-provider</artifactId> </dependency> <!-- <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> </dependency> <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> </dependency> </dependencies> </project> <file_sep>package baset; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //,"/applicationContext-memcache.xml" @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/applicationContext.xml","/applicationContext-dbSource.xml","/dispatcherServletContext.xml" }) public class BaseTest { @BeforeClass public static void testbf() { System.out.println("test begin========"); } @AfterClass public static void testaf() { System.out.println("test end========"); } } <file_sep>package hibernate; // Generated 2016-12-27 17:26:25 by Hibernate Tools 4.3.1.Final import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * TRoleRight generated by hbm2java */ @Entity @Table(name = "t_role_right", catalog = "sendb") public class TRoleRight implements java.io.Serializable { private Long roriId; private TRight TRight; private TRoles TRoles; private Long createUserid; private Date createTime; private Long updateUserid; private Date updateTime; public TRoleRight() { } public TRoleRight(TRight TRight, TRoles TRoles) { this.TRight = TRight; this.TRoles = TRoles; } public TRoleRight(TRight TRight, TRoles TRoles, Long createUserid, Date createTime, Long updateUserid, Date updateTime) { this.TRight = TRight; this.TRoles = TRoles; this.createUserid = createUserid; this.createTime = createTime; this.updateUserid = updateUserid; this.updateTime = updateTime; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "rori_id", unique = true, nullable = false) public Long getRoriId() { return this.roriId; } public void setRoriId(Long roriId) { this.roriId = roriId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "right_id", nullable = false) public TRight getTRight() { return this.TRight; } public void setTRight(TRight TRight) { this.TRight = TRight; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "role_id", nullable = false) public TRoles getTRoles() { return this.TRoles; } public void setTRoles(TRoles TRoles) { this.TRoles = TRoles; } @Column(name = "create_userid") public Long getCreateUserid() { return this.createUserid; } public void setCreateUserid(Long createUserid) { this.createUserid = createUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_time", length = 19) public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Column(name = "update_userid") public Long getUpdateUserid() { return this.updateUserid; } public void setUpdateUserid(Long updateUserid) { this.updateUserid = updateUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_time", length = 19) public Date getUpdateTime() { return this.updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } } <file_sep>package com.jen.sen.untils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigDecimal; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.springframework.util.Assert; /** * 工具类 * filename Util.java * company jen * @author jenson * @email <EMAIL> */ public class Util { /** * 字符串是否为空或null值。 * isNullOrEmpty(null)返回 true; * isNullOrEmpty("")返回 true; * isNullOrEmpty(" ")返回 true; * @author jenson * @param str * @return boolean */ public static boolean isNullOrEmpty(String str) { return isNull(str) || isEmpty(str); } /** * 字符串为空或null值返回0。 * isNullOrEmpty(null)返回 0; * isNullOrEmpty("")返回 0; * isNullOrEmpty(" ")返回 0; * @author jenson * @param str * @return Integer */ public static Integer isNullOrEmptyToInteger(String str) { if (isNull(str) || isEmpty(str)) { return Integer.valueOf(0); } else { return Integer.valueOf(str.trim()); } } /** * 将10进制数转换成二进制字符串。 * * @author jenson * @param num * @return */ public static char[] tenTOTwo(int num) { String binNum = ""; while (num >= 2) { binNum += (num % 2) + ""; num = (int) (num / 2); } binNum += num % 2; char[] binChar = binNum.toCharArray(); char temp; for (int i = 0; i < Math.ceil(binChar.length / 2); i++) { temp = binChar[i]; binChar[i] = binChar[(binChar.length - 1) - i]; binChar[binChar.length - 1] = temp; } return binChar; } /** * 获取bit值位置值。 * * @author jenson * @param bits * @param num * @return boolean */ public static boolean getBitValue(char[] bits, int num) { if (!isNull(bits) && bits.length >= num) { String bit = String.valueOf(bits); int chr_index = Math.abs(num - bits.length + 1); char chr = bit.charAt(chr_index); String str = String.valueOf(chr); if (str.equals("0")) { return false; } else { return true; } } return false; } /** * 字符串为空或null值返回0。 * isNullOrEmpty(null)返回 0; * isNullOrEmpty("")返回 0; * isNullOrEmpty(" ")返回 0; * @author jenson * @param str * @return Long */ public static Long isNullOrEmptyToLong(String str) { if (isNull(str) || isEmpty(str)) { return Long.valueOf(0); } else { return Long.valueOf(str.trim()); } } /** * 字符串为空或null值返回0。 * isNullOrEmpty(null)返回 0; * isNullOrEmpty("")返回 0; * isNullOrEmpty(" ")返回 0; * @author jenson * @param str * @return Short */ public static Short isNullOrEmptyToShort(String str) { if (isNull(str) || isEmpty(str)) { return Short.valueOf((short) 0); } else { return Short.valueOf(str.trim()); } } /** * 判断对象是否为null。 * isNullOrEmpty(null)返回 true; * isNullOrEmpty("")返回true; * isNullOrEmpty(" ")返回 true; * @author jenson * @param obj * @return boolean */ public static boolean isNullOrEmpty(Object obj) { if (obj == null || obj.toString().trim().equals("")) { return true; } return false; } /** * 判断对象是否为null。 * * @author jenson * @param obj * @return boolean */ public static boolean isNull(Object obj) { return obj == null || obj.equals("null"); } /** * 字符串是否为空。 * isEmpty("")返回 true * isEmpty(" ")返回 true * @author jenson * @param str * @return boolean */ public static boolean isEmpty(String str) { return str != null && str.trim().equals(""); } /** * 将字符类型的值为null的转换为空的字符串("")。 * * @author jenson * @param str * @return String */ public static String isNullToEmptyStr(String str) { if (str == null) { return ""; } else { return str; } } public static BigDecimal isNullToZero(BigDecimal b) { if (isNullOrEmpty(b)) { return BigDecimal.ZERO; } else { return b; } } public static String isNullToStrZero(String b) { if (isNullOrEmpty(b)) { return "0"; } else { return b; } } /** * 获得字符串中某个关键词第一次出现的位置。 * @author jenson * @param str 字符串 * @param keyWordRegex 关键词的正则表达式 * @return int 关键词第一次出现位置的索引 */ public static int getKeyWordsFirstPosition(String str, String keyWordRegex) { Assert.hasText(str); Assert.hasText(keyWordRegex); int index = 0; Pattern pattern = Pattern.compile(keyWordRegex, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(str); while (matcher.find()) { index = matcher.start(); return index; } return index; } /** * 根据指定偏移量和指定长度,截取字符串。 * * @author jenson * @param str * @param offset * @param len * @return */ public static String getSubString(String str, int offset, int len) { if (str.length() <= len) { len = str.length(); } if ((len + offset) < str.length()) { return str.substring(offset, (len + offset)); } else { return str.substring(offset, str.length() - offset); } } /** * 根据指定偏移量,截取字符串。 * * @author jenson * @param str * @param offset * @return * @since 1.0_2016-10-24 */ public static String getSubString(String str, int offset) { if (offset < str.length()) { return str.substring(offset, str.length()); } else { return ""; } } /** * 获取某个子串在字符串中出现的次数。 * * @author jenson * @param sourceStr * 字符串 * @param subStr * 子串 * @return * @since 0.1_2016-12-21 */ public static int getAppearCountByStr(String sourceStr, String subStr) { int index = 0; int count = 0; while ((index = sourceStr.indexOf(subStr, index)) != -1) { count++; index += subStr.length(); } return count; } public static boolean isMobileNO(String mobiles) { boolean flag = false; try { Pattern p = Pattern.compile("^((1[3-9][0-9]))\\d{8}$"); Matcher m = p.matcher(mobiles); flag = m.matches(); } catch (Exception e) { flag = false; } return flag; } /** * String转换为object数组,如Str=1,2,3,4,5 * * @author jenson.wang * */ public static Object[] String2Object(String str) { String[] strr = str.split(","); Object array[] = new Object[strr.length]; for (int i = 0; i < strr.length; i++) { array[i] = Long.parseLong(strr[i]); } return array; } // 序列化,对象转化为byte数组 public static byte[] serialize(Object o) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutputStream outo = new ObjectOutputStream(out); outo.writeObject(o); } catch (IOException e) { e.printStackTrace(); } return out.toByteArray(); } // 反序列化,byte数组转化为对象 public static Object deserialize(byte[] b) { ObjectInputStream oin; try { oin = new ObjectInputStream(new ByteArrayInputStream(b)); try { return oin.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } catch (IOException e) { e.printStackTrace(); return null; } } /** * tontroller中获取request里的字符类型参数 * * @param req * @param strParaName * @return String */ public static String getParameterString(HttpServletRequest req, String strParaName) { String str = req.getParameter(strParaName); if (isNullOrEmpty(str)) { str = ""; } return str.trim(); } /** * tontroller中获取request里的Long类型参数,空为-1 * * @param req * @param strParaName * @return Long */ public static Long getParameterLong(HttpServletRequest req, String strParaName) { String str = req.getParameter(strParaName); Long i = -1L; if (!isNullOrEmpty(str)) { i = Long.parseLong(str); } return i; } /** * tontroller中获取request里的int类型参数,空为-1 * @param @param req * @param @param strParaName * @param @return * @return int */ public static int getParameterInt(HttpServletRequest req, String strParaName) { String str = req.getParameter(strParaName); int i = -1; if (!isNullOrEmpty(str)) { i = Integer.parseInt(str); } return i; } } <file_sep>package com.jen.sen.shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.crypto.hash.SimpleHash; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.SimpleByteSource; import com.jen.sen.commons.Constant; import com.jen.sen.web.vo.system.UserVo; /** * Shiro工具类,获取session,Subjec,UserVo等 * filename ShiroUtils.java * company jen * @author jenson * @email <EMAIL> */ public class ShiroUtils { public static Session getSession() { return SecurityUtils.getSubject().getSession(); } public static Subject getSubject() { return SecurityUtils.getSubject(); } public static UserVo getUserVo() { return (UserVo)SecurityUtils.getSubject().getPrincipal(); } public static Long getUserId() { return getUserVo().getUserId(); } public static void setSessionAttribute(Object key, Object value) { getSession().setAttribute(key, value); } public static Object getSessionAttribute(Object key) { return getSession().getAttribute(key); } public static boolean isLogin() { return SecurityUtils.getSubject().getPrincipal() != null; } public static void logout() { SecurityUtils.getSubject().logout(); } /***验证码***/ public static String getKaptcha(String key) { String kaptcha = getSessionAttribute(key).toString(); getSession().removeAttribute(key); return kaptcha; } /** * shiro加密算法,与appli***-shiro**.xml中加密算法一致,保证登录验证密码和加密方式一致,solt为jenson * @param str * @return * jenson.wang */ public static String getpwdShiro(String str) { //String salt=new SecureRandomNumberGenerator().nextBytes().toHex(); return new SimpleHash("SHA-256",str,new SimpleByteSource(Constant.I_SHIRO_SALT),2).toHex(); } } <file_sep>package com.jen.sen.persistence.pojo.system; // Generated 2016-5-25 16:02:32 by Hibernate Tools 4.3.1.Final import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * TRight generated by hbm2java */ @Entity @Table(name = "t_right", catalog = "sendb") public class TRight implements java.io.Serializable { private static final long serialVersionUID = 1L; private Long rightId; private String rightCode; private Long rightParentId; private Short rightOrder; private Short rightLevel; private String rightName; private String rightImg; private String rightUrl; private String perms; private Short status; private String remark; private Long createUserid; private Date createTime; private Long updateUserid; private Date updateTime; private Set<TRoleRight> TRoleRights = new HashSet<TRoleRight>(0); public TRight() { } public TRight(Short status) { this.status = status; } public TRight(String rightCode, Long rightParentId, Short rightOrder,Short rightLevel, String rightName, String rightUrl,String rightImg, Short status, String remark, Long createUserid, Date createTime, Long updateUserid, Date updateTime, Set<TRoleRight> TRoleRights) { this.rightCode = rightCode; this.rightParentId = rightParentId; this.rightOrder = rightOrder; this.rightLevel = rightLevel; this.rightName = rightName; this.rightUrl = rightUrl; this.rightImg= rightImg; this.status = status; this.remark = remark; this.createUserid = createUserid; this.createTime = createTime; this.updateUserid = updateUserid; this.updateTime = updateTime; this.TRoleRights = TRoleRights; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "right_id", unique = true, nullable = false) public Long getRightId() { return this.rightId; } public void setRightId(Long rightId) { this.rightId = rightId; } @Column(name = "right_code", length = 50) public String getRightCode() { return this.rightCode; } public void setRightCode(String rightCode) { this.rightCode = rightCode; } @Column(name = "right_parent_id") public Long getRightParentId() { return this.rightParentId; } public void setRightParentId(Long rightParentId) { this.rightParentId = rightParentId; } @Column(name = "right_order") public Short getRightOrder() { return this.rightOrder; } public void setRightOrder(Short rightOrder) { this.rightOrder = rightOrder; } @Column(name = "right_level") public Short getRightLevel() { return this.rightLevel; } public void setRightLevel(Short rightLevel) { this.rightLevel = rightLevel; } @Column(name = "right_name", length = 50) public String getRightName() { return this.rightName; } public void setRightName(String rightName) { this.rightName = rightName; } @Column(name = "right_url") public String getRightUrl() { return this.rightUrl; } public void setRightUrl(String rightUrl) { this.rightUrl = rightUrl; } @Column(name = "right_img") public String getRightImg() { return this.rightImg; } public void setRightImg(String rightImg) { this.rightImg = rightImg; } @Column(name = "status", nullable = false) public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } @Column(name = "remark", length = 300) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "create_userid") public Long getCreateUserid() { return this.createUserid; } public void setCreateUserid(Long createUserid) { this.createUserid = createUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_time", length = 19) public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Column(name = "update_userid") public Long getUpdateUserid() { return this.updateUserid; } public void setUpdateUserid(Long updateUserid) { this.updateUserid = updateUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_time", length = 19) public Date getUpdateTime() { return this.updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "TRight") public Set<TRoleRight> getTRoleRights() { return this.TRoleRights; } public void setTRoleRights(Set<TRoleRight> TRoleRights) { this.TRoleRights = TRoleRights; } public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } } <file_sep>package unit; import java.util.Date; import com.jen.sen.untils.DateUtils; import com.jen.sen.untils.Util; import com.jen.sen.web.vo.system.UserVo; public class TestDate { public static void main(String[] args) { UserVo uv = new UserVo(); System.out.println("fvvvvvvvvv:"+uv); System.out.println("bbbbbbbbbb:"+uv.toString().trim()); } } <file_sep>package com.jen.sen.persistence.core.dao.impl; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.transform.Transformers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import com.jen.sen.persistence.core.dao.FrameCenterDao; import com.jen.sen.persistence.core.dao.tools.PageDT; import com.jen.sen.persistence.pojo.system.TUser; /** * 数据库DAO公共类实现。 * filename FrameCenterDaoImpl.java * company jen * @author jenson * @email <EMAIL> */ public class FrameCenterDaoImpl<T> extends HibernateDaoSupport implements FrameCenterDao<T> { /** log工具实例 */ private static final Logger log = LogManager.getLogger(FrameCenterDaoImpl.class); @Resource public void setMySessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } public void save(T domain) { log.trace("saving " + domain.getClass().getName() + " instance"); getHibernateTemplate().save(domain); log.trace("saving sucessfull" + domain.getClass().getName() + " instance"); }; public void saveOrUpdate(T domain) { log.trace("saveOrUpdating " + domain.getClass().getName() + " instance"); getHibernateTemplate().saveOrUpdate(domain); log.trace("saveOrUpdating sucessfull " + domain.getClass().getName() + " instance"); }; public void update(T domain) { log.trace("updating " + domain.getClass().getName() + " instance"); getHibernateTemplate().update(domain); log.trace("updating sucessfull " + domain.getClass().getName() + " instance"); }; public void delete(T domain) { log.trace("deleting " + getClass().getName() + " instance"); getHibernateTemplate().delete(domain); log.trace("deleting sucessfull " + getClass().getName() + " instance"); } @SuppressWarnings({ "unchecked", "rawtypes" }) public T get(Class classType, Long id) { log.trace("getting " + classType.getName() + " instance"); T t = (T) getHibernateTemplate().get(classType, id); log.trace("getting sucessfull " + classType.getName() + " instance"); return t; }; /** * page 翻页类,page.getStart() 开始记录数,page.getLength()每页记录数 * 前提是记录数要先查出来,Start,RecordsFiltered要先赋值 */ @SuppressWarnings("unchecked") public List<T> queryPage(Class<T> clas, String sql, Object[] paras, PageDT page) { SQLQuery query = this.getCurrentSession().createSQLQuery(sql).addEntity(clas); if (paras != null && paras.length > 0) { int i = 0; for (Object tempPara : paras) { query.setParameter(i++, tempPara); } } if (page != null) { if (page.getLength() <= -1) { query.setFirstResult(0); query.setMaxResults(page.getRecordsFiltered() - 1); } else { query.setFirstResult(page.getStart()); if ((page.getRecordsFiltered() - page.getStart()) < page.getLength() && (page.getRecordsFiltered() - page.getStart() > -1)) { query.setMaxResults(page.getRecordsFiltered() - page.getStart()); } else { query.setMaxResults(page.getLength()); } } } return query.list(); } @SuppressWarnings("unchecked") public List<T> query(Class<T> clas, String sql, Object[] paras) { SQLQuery query = this.getCurrentSession().createSQLQuery(sql).addEntity(clas); if (paras != null && paras.length > 0) { int i = 0; for (Object tempPara : paras) { query.setParameter(i++, tempPara); } } return query.list(); } @SuppressWarnings({ "unchecked" }) public T load(@SuppressWarnings("rawtypes") Class classType, Long id) { return ((T) getCurrentSession().load(classType, id)); } @Override public <T> T findById(Class<T> entityClass, Long id) { return (T) getHibernateTemplate().get(entityClass, id); } public void exeHql(String hql, Object[] objects) { Query query = this.getCurrentSession().createQuery(hql); for (int i = 0; i < objects.length; i++) { query.setParameter(i, objects[i]); } query.executeUpdate(); } /** * 按sql语句执行update */ public void exeSql(String sql, Object[] paras) { SQLQuery query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(sql); if (paras != null && paras.length > 0) { int i = 0; for (Object tempPara : paras) { query.setParameter(i++, tempPara); } } query.executeUpdate(); } /** * 按条件查询sql的记录数 */ public Integer queryPageCountParas(String sql, Object[] paras) { log.trace("countListByHqlAndParas " + getClass().getName()); SQLQuery query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(sql); if (paras != null && paras.length > 0) { int i = 0; for (Object tempPara : paras) { query.setParameter(i++, tempPara); } } log.trace("countListByHqlAndParas sucessfull " + getClass().getName()); return Integer.parseInt(query.uniqueResult().toString()); } /** * 按条件查询sql的记录数 */ @SuppressWarnings({ "unchecked", "hiding" }) @Override public <T> List<T> findAll(Class<T> entityClass) { return getCurrentSession().createCriteria(entityClass).list(); } /**sql查询 * 返回值,List<Map<String, Object>> * * @author jenson * */ @SuppressWarnings("unchecked") public List<Map<String, Object>> findSqllistMap(String sql, Object[] objects){ SQLQuery query =this.getCurrentSession().createSQLQuery(sql); if (objects != null && objects.length > 0) { int i = 0; for (Object tempPara : objects) { query.setParameter(i++, tempPara); } } query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); return query.list(); } @SuppressWarnings({ "unchecked" }) public T getbysql(Class<T> clas,String sql) { SQLQuery query =this.getCurrentSession().createSQLQuery(sql); return (T) query.addEntity(clas).uniqueResult(); }; protected Session getCurrentSession() { return super.getHibernateTemplate().getSessionFactory().getCurrentSession(); } } <file_sep>package spring; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.jen.sen.persistence.dao.system.IUserDao; import com.jen.sen.persistence.pojo.system.TUser; import baset.BaseTest; public class TestDao extends BaseTest { @Autowired private IUserDao iUserDao; @Test public void testUser() { TUser tu = iUserDao.findById(TUser.class, 1L); TUser tu1 = iUserDao.findById(TUser.class, 1L); TUser tu2 = iUserDao.findById(TUser.class, 1L); System.out.println("user"+tu.getUserAccount()+"--"+tu.getUserName()); System.out.println("user"+tu1.getUserAccount()+"--"+tu1.getUserName()); System.out.println("user"+tu2.getUserAccount()+"--"+tu2.getUserName()); } } <file_sep>JENWEB === JENWEB is a ***J2EE*** project framework,it used ***spring MVC,hibernate,shiro,redis*** etc. it develop on ***jdk1.8,tomcat8***,maven. you can use it for free. build and running --- <br> <table> <tr> <td></td> <td>version</td> </tr> <tr> <td>spring</td> <td>4.2.7</td> </tr> <tr> <td>hibernate</td> <td>4.3.11</td> </tr> <tr> <td>shiro</td> <td>1.3.2</td> </tr> <tr> <td>mysql</td> <td>5.7</td> </tr> <tr> <td>redis</td> <td>3.2.X</td> </tr> </table> example --- ![image](https://github.com/jenson2000/JENWEB/blob/master/JEN-STATIC/WebContent/staticinfo/images/git002.jpg) File Hierarchy of the Source Code Package --- JENWEN used maven to manage third-party components. it has five project > JEN-STATIC <br> >> JEN-PARENT >>> JEN-COMMON <br> >>> JEN-DAO <br> >>> JENWEB <br> 1. JEN-STATIC is a static project. it includes static recourses, such as css,images,js,etc. 2. JEN-PARENT is maven parent project. 3. JEN-COMMON is tools package project.include some constant bean,tools bean,etc. 4. JEN-DAO is DAO project. include pojo,DAO etc. depends on JEN-COMMON 5. JENWEB is web project,depends on JEN-DAO,JEN-COMMON Getting Started --- /jenweb/doc/sendb.sql is sql scripts, you can use it to create database.<br> <file_sep>package com.jen.sen.persistence.pojo.system; // Generated 2016-5-25 16:02:32 by Hibernate Tools 4.3.1.Final import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * TUser generated by hbm2java */ @Entity @Table(name = "t_user", catalog = "sendb") public class TUser implements java.io.Serializable { private static final long serialVersionUID = 1L; private Long userId; private String userAccount; private String userPassword; private String userName; private Short userSex; private String userIphone; private Date userBirthday; private String userEmail; private String userAddress; private Short status; private String remark; private Long createUserid; private Date createTime; private Long updateUserid; private Date updateTime; private Set<TUserRoles> TUserRoleses = new HashSet<TUserRoles>(0); public TUser() { } public TUser(String userAccount, String userPassword, Short status) { this.userAccount = userAccount; this.userPassword = <PASSWORD>; this.status = status; } public TUser(String userAccount, String userPassword, String userName, Short userSex, String userIphone, Date userBirthday, String userEmail, String userAddress, Short status, String remark, Long createUserid, Date createTime, Long updateUserid, Date updateTime, Set<TUserRoles> TUserRoleses) { this.userAccount = userAccount; this.userPassword = <PASSWORD>Password; this.userName = userName; this.userSex = userSex; this.userIphone = userIphone; this.userBirthday = userBirthday; this.userEmail = userEmail; this.userAddress = userAddress; this.status = status; this.remark = remark; this.createUserid = createUserid; this.createTime = createTime; this.updateUserid = updateUserid; this.updateTime = updateTime; this.TUserRoleses = TUserRoleses; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "user_id", unique = true, nullable = false) public Long getUserId() { return this.userId; } public void setUserId(Long userId) { this.userId = userId; } @Column(name = "user_account", nullable = false, length = 50) public String getUserAccount() { return this.userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } @Column(name = "user_password", nullable = false, length = 150) public String getUserPassword() { return this.userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } @Column(name = "user_name", length = 20) public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name = "user_sex") public Short getUserSex() { return this.userSex; } public void setUserSex(Short userSex) { this.userSex = userSex; } @Column(name = "user_iphone", length = 30) public String getUserIphone() { return this.userIphone; } public void setUserIphone(String userIphone) { this.userIphone = userIphone; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "user_birthday", length = 19) public Date getUserBirthday() { return this.userBirthday; } public void setUserBirthday(Date userBirthday) { this.userBirthday = userBirthday; } @Column(name = "user_email", length = 100) public String getUserEmail() { return this.userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } @Column(name = "user_address", length = 200) public String getUserAddress() { return this.userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } @Column(name = "status", nullable = false) public Short getStatus() { return this.status; } public void setStatus(Short status) { this.status = status; } @Column(name = "remark", length = 300) public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } @Column(name = "create_userid") public Long getCreateUserid() { return this.createUserid; } public void setCreateUserid(Long createUserid) { this.createUserid = createUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "create_time", length = 19) public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Column(name = "update_userid") public Long getUpdateUserid() { return this.updateUserid; } public void setUpdateUserid(Long updateUserid) { this.updateUserid = updateUserid; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "update_time", length = 19) public Date getUpdateTime() { return this.updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "TUser") public Set<TUserRoles> getTUserRoleses() { return this.TUserRoleses; } public void setTUserRoleses(Set<TUserRoles> TUserRoleses) { this.TUserRoleses = TUserRoleses; } } <file_sep>/*=======================建库、用户脚本=======================================*/ CREATE DATABASE sendb DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; grant all privileges on sendb.* to jensen @'%' identified by 'jenson180#jenson' with grant option; FLUSH PRIVILEGES; -- ---------------------------- -- Table structure for t_right -- ---------------------------- DROP TABLE IF EXISTS `t_right`; CREATE TABLE `t_right` ( `right_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '权限ID', `right_code` varchar(50) DEFAULT NULL, `right_parent_id` bigint(20) DEFAULT NULL, `right_order` smallint(6) DEFAULT NULL, `right_level` smallint(6) DEFAULT NULL, `right_name` varchar(50) DEFAULT NULL, `right_img` varchar(255) NOT NULL, `right_url` varchar(255) DEFAULT NULL, `perms` varchar(255) DEFAULT NULL COMMENT '授权码', `status` smallint(6) NOT NULL DEFAULT '1' COMMENT '1:有效\r\n 0:无效', `remark` varchar(300) DEFAULT NULL, `create_userid` bigint(20) DEFAULT '0', `create_time` datetime DEFAULT NULL, `update_userid` bigint(20) DEFAULT '0', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`right_id`), KEY `ind_t_right_perms` (`perms`(191)) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_right -- ---------------------------- INSERT INTO `t_right` VALUES ('1', '001', null, '1', '1', '系统管理', 'fa fa-server', null, null, '1', null, '-1', '2017-01-12 16:11:15', '-1', '2017-01-12 16:11:26'); INSERT INTO `t_right` VALUES ('2', '001001', '1', '1', '2', '用户管理', 'fa fa-user', 'system/user/userManage', 'sys:user', '1', null, '-1', '2017-01-12 16:12:28', '0', '2017-01-12 16:12:33'); INSERT INTO `t_right` VALUES ('3', '001002', '1', '2', '2', '角色管理', 'fa fa-group', 'system/role/roleManage', 'sys:role', '1', '', '-1', '2017-01-12 16:12:28', '0', '2017-01-12 16:12:33'); INSERT INTO `t_right` VALUES ('4', '002', null, '2', '1', '1菜单', 'fa fa-star', null, null, '1', null, '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('5', '002001', '4', '1', '2', '1-1级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('6', '002002', '4', '2', '2', '1-2级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('7', '002003', '4', '3', '2', '1-3级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('8', '003', null, '3', '1', '2菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('9', '003001', '8', '1', '2', '2-1级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('10', '003002', '8', '2', '2', '2-2级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('11', '003003', '8', '3', '2', '2-3级菜单', 'fa fa-star', '', null, '1', '', '0', '2017-01-23 10:05:56', '0', '2017-01-23 10:06:00'); INSERT INTO `t_right` VALUES ('12', '001001001', '2', '3', '3', '用户管理-1', 'fa fa-star', 'system/user/userManage.do', null, '1', '', '-1', '2017-01-12 16:12:28', '0', '2017-01-12 16:12:33'); -- ---------------------------- -- Table structure for t_roles -- ---------------------------- DROP TABLE IF EXISTS `t_roles`; CREATE TABLE `t_roles` ( `role_id` bigint(20) NOT NULL AUTO_INCREMENT, `role_code` varchar(20) DEFAULT NULL, `role_name` varchar(50) DEFAULT NULL, `role_order` int(5) DEFAULT NULL COMMENT '排序', `status` smallint(6) NOT NULL DEFAULT '1' COMMENT '1:有效\r\n 0:无效', `remark` varchar(300) DEFAULT NULL, `create_userid` bigint(20) DEFAULT '0', `create_time` datetime DEFAULT NULL, `update_userid` bigint(20) DEFAULT '0', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`role_id`) ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_roles -- ---------------------------- INSERT INTO `t_roles` VALUES ('12', null, '角色1(test)', null, '1', 'test', null, '2017-01-01 14:48:42', null, '2017-04-01 11:32:20'); INSERT INTO `t_roles` VALUES ('13', null, '角色2(test)', null, '1', 'test', null, '2017-01-03 16:08:54', null, '2017-03-21 16:09:00'); INSERT INTO `t_roles` VALUES ('14', null, '角色3(test)', null, '1', 'test', null, '2017-01-03 16:09:16', null, '2017-01-03 16:09:16'); INSERT INTO `t_roles` VALUES ('15', '', '角色4(test)', null, '1', 'test', null, '2017-01-03 16:08:54', null, '2017-01-04 18:00:01'); INSERT INTO `t_roles` VALUES ('16', '', '角色5(test)', null, '1', 'test', null, '2017-01-03 16:08:54', null, '2017-01-04 18:00:20'); INSERT INTO `t_roles` VALUES ('17', '', '角色6(test)', null, '1', 'test', null, '2017-01-03 16:08:54', null, '2017-04-01 11:35:11'); -- ---------------------------- -- Table structure for t_role_right -- ---------------------------- DROP TABLE IF EXISTS `t_role_right`; CREATE TABLE `t_role_right` ( `rori_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键', `role_id` bigint(20) NOT NULL COMMENT '角色ID', `right_id` bigint(20) NOT NULL COMMENT '权限ID', `create_userid` bigint(20) DEFAULT '0', `create_time` datetime DEFAULT NULL, `update_userid` bigint(20) DEFAULT '0', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`rori_id`), KEY `FK_roleright_roles_roleid` (`role_id`), KEY `FK_roleright_right_rightid` (`right_id`), CONSTRAINT `FK_roleright_right_rightid` FOREIGN KEY (`right_id`) REFERENCES `t_right` (`right_id`), CONSTRAINT `FK_roleright_roles_roleid` FOREIGN KEY (`role_id`) REFERENCES `t_roles` (`role_id`) ) ENGINE=InnoDB AUTO_INCREMENT=45 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_role_right -- ---------------------------- INSERT INTO `t_role_right` VALUES ('26', '13', '1', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('27', '13', '2', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('28', '13', '3', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('29', '13', '8', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('30', '13', '9', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('31', '13', '10', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('32', '13', '11', null, '2017-03-21 16:09:00', null, '2017-03-21 16:09:00'); INSERT INTO `t_role_right` VALUES ('33', '12', '1', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('34', '12', '2', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('35', '12', '3', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('36', '12', '4', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('37', '12', '5', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('38', '12', '6', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('39', '12', '8', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('40', '12', '9', null, '2017-04-01 11:32:20', null, '2017-04-01 11:32:20'); INSERT INTO `t_role_right` VALUES ('41', '17', '1', null, '2017-04-01 11:35:11', null, '2017-04-01 11:35:11'); INSERT INTO `t_role_right` VALUES ('42', '17', '2', null, '2017-04-01 11:35:11', null, '2017-04-01 11:35:11'); INSERT INTO `t_role_right` VALUES ('43', '17', '12', null, '2017-04-01 11:35:11', null, '2017-04-01 11:35:11'); INSERT INTO `t_role_right` VALUES ('44', '17', '3', null, '2017-04-01 11:35:11', null, '2017-04-01 11:35:11'); -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `user_id` bigint(20) NOT NULL AUTO_INCREMENT, `user_account` varchar(60) NOT NULL, `user_password` varchar(100) NOT NULL, `user_name` varchar(20) DEFAULT NULL, `user_sex` smallint(6) DEFAULT NULL, `user_iphone` varchar(30) DEFAULT NULL, `user_birthday` date DEFAULT NULL, `user_email` varchar(100) DEFAULT NULL, `user_address` varchar(200) DEFAULT NULL, `status` smallint(6) NOT NULL DEFAULT '1' COMMENT '1:有效\r\n 0:无效', `remark` varchar(300) DEFAULT NULL, `create_userid` bigint(20) unsigned DEFAULT '0', `create_time` datetime DEFAULT NULL, `update_userid` bigint(20) unsigned DEFAULT '0', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=438 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_user -- ---------------------------- INSERT INTO `t_user` VALUES ('1', 'admin', '<PASSWORD>', 'admin', '1', '', '2017-02-28', '', '阿斯蒂芬asd1', '1', 'asdf的萨芬告诉对方', '0', '2017-02-28 18:04:27', '0', '2017-02-28 18:04:37'); INSERT INTO `t_user` VALUES ('381', 'abo111', '<PASSWORD>', '用户一', '2', '13928176252', '1992-09-01', '<EMAIL>', '阿斯蒂芬asd1', '1', 'asdf的萨芬告诉对方1123阿萨德89ff33', '0', '2017-01-20 14:19:20', '0', '2017-03-31 13:38:10'); INSERT INTO `t_user` VALUES ('382', 'abo2阿萨德1', '4<PASSWORD>', '用户二', '2', '13928176255', '1992-08-31', '<EMAIL>', '阿斯蒂芬asd', '1', 'asdf的萨芬告诉对方', '0', '2017-01-04 17:49:02', '0', '2017-03-31 13:38:19'); INSERT INTO `t_user` VALUES ('383', 'test_abo3', '<PASSWORD>', '用户三', '2', '13928176255', '1992-08-31', '<EMAIL>', '阿斯蒂芬asd', '0', 'asdf的萨芬告诉对方', '0', '2016-09-28 15:56:38', '0', '2017-03-31 13:39:43'); INSERT INTO `t_user` VALUES ('433', 'asdasdasd', '<PASSWORD>', 'dsagsadf', '2', '13636521123', '1923-02-13', '<EMAIL>', 'adsfasdfsadf', '0', '读书噶大哥哥sad分儿童斯蒂芬', null, '2017-03-31 16:50:20', null, '2017-03-31 16:50:45'); INSERT INTO `t_user` VALUES ('434', 'test_user1', '<PASSWORD>', 'asdsdf', '1', '13637298122', null, '', '', '1', '', null, '2017-04-01 10:48:34', null, '2017-04-01 10:48:34'); INSERT INTO `t_user` VALUES ('436', 'test_user2', '<PASSWORD>', 'adsf', '1', '13838729211', null, '<EMAIL>', '大木桥路238好2201', '1', '', null, '2017-04-01 11:29:13', null, '2017-04-01 11:29:13'); INSERT INTO `t_user` VALUES ('437', 'test_user3', '<PASSWORD>', 'adsf', '1', '', null, '', '', '1', '', null, '2017-04-01 11:31:54', null, '2017-04-01 11:31:54'); -- ---------------------------- -- Table structure for t_user_roles -- ---------------------------- DROP TABLE IF EXISTS `t_user_roles`; CREATE TABLE `t_user_roles` ( `usro_id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL COMMENT '用户ID', `role_id` bigint(20) NOT NULL COMMENT '角色ID', `create_userid` bigint(20) DEFAULT '0', `create_time` datetime DEFAULT NULL, `update_userid` bigint(20) DEFAULT '0', `update_time` datetime DEFAULT NULL, PRIMARY KEY (`usro_id`), KEY `FK_userroles_user_userid` (`user_id`), KEY `FK_userroles_roles_roleid` (`role_id`), CONSTRAINT `FK_userroles_roles_roleid` FOREIGN KEY (`role_id`) REFERENCES `t_roles` (`role_id`), CONSTRAINT `FK_userroles_user_userid` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of t_user_roles -- ---------------------------- INSERT INTO `t_user_roles` VALUES ('4', '382', '14', '0', '2017-01-04 16:30:12', '0', '2017-01-04 16:30:12'); INSERT INTO `t_user_roles` VALUES ('5', '382', '15', '0', '2017-01-04 16:30:12', '0', '2017-01-04 16:30:12'); INSERT INTO `t_user_roles` VALUES ('6', '382', '13', '0', '2017-01-04 16:30:12', '0', '2017-01-04 16:30:12'); INSERT INTO `t_user_roles` VALUES ('29', '381', '12', '-1', '2017-01-17 16:05:34', '-1', '2017-01-17 16:05:34'); INSERT INTO `t_user_roles` VALUES ('30', '381', '13', '-1', '2017-01-17 16:05:34', '-1', '2017-01-17 16:05:34'); INSERT INTO `t_user_roles` VALUES ('31', '381', '15', '-1', '2017-01-17 16:05:34', '-1', '2017-01-17 16:05:34'); INSERT INTO `t_user_roles` VALUES ('32', '381', '16', '-1', '2017-01-17 16:05:34', '-1', '2017-01-17 16:05:34'); INSERT INTO `t_user_roles` VALUES ('33', '381', '17', '-1', '2017-01-17 16:05:34', '-1', '2017-01-17 16:05:34'); INSERT INTO `t_user_roles` VALUES ('34', '437', '12', '-1', '2017-04-01 11:32:05', '-1', '2017-04-01 11:32:05'); INSERT INTO `t_user_roles` VALUES ('35', '437', '13', '-1', '2017-04-01 11:32:05', '-1', '2017-04-01 11:32:05');
2f2fd6c8d98d5c078bba8b5428cc4bb93d2ef5f1
[ "SQL", "JavaScript", "Markdown", "Maven POM", "Java" ]
25
Java
jenson2000/JENWEB
3bbfe622bc18642f175e01f1a0872566ffef389b
4811132f1242d1be2044f1a012f505b477bca903
refs/heads/master
<repo_name>TrungDucMai/QuadraticEquation<file_sep>/src/com/company/QuadraticEquation.java package com.company; public class QuadraticEquation { private double a, b, c; public QuadraticEquation() { } ; public QuadraticEquation(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double getA() { return this.a; } public double getB() { return this.b; } public double getC() { return this.c; } public double getDiscrimnant(double a, double b, double c) { return this.b * this.b - 4 * this.a * this.c; } public double getRoot1(double a, double b, double Delta) { return (-b + Math.pow(Delta, 0.5)) / (2 * a); } public double getRoot2(double a, double b, double Delta) { return (-b - Math.pow(Delta, 0.5)) / (2 * a); } } <file_sep>/src/com/company/Main.java package com.company; import java.sql.SQLOutput; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("nhap gia tri a,b,c"); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); QuadraticEquation quadraticEquation = new QuadraticEquation(a, b, c); double Delta = quadraticEquation.getDiscrimnant(a, b, c); double R1 = quadraticEquation.getRoot1(a, b, Delta); double R2 = quadraticEquation.getRoot2(a, b, Delta); if (Delta < 0) { System.out.println("phuong trinh vo nhiem"); } else if (Delta == 0) { System.out.println("phuong trinh co nghiem la : " + R1); } else { System.out.println("phuong trinh co 2 nghiem la: R1 = " + R1 + "R2 = " +R2); } } }
5ea65d4b13c2abc2c161373b06b68f878abca398
[ "Java" ]
2
Java
TrungDucMai/QuadraticEquation
a66b91352f499e79478538910cc8e608f1dcf68b
a4e783bcbc88f42eec058faefb1274d0d8e84872
refs/heads/master
<file_sep> import numpy as np import pandas as pd import matplotlib.pyplot as plt import plot_lib as pl from collections import OrderedDict import plotly.plotly as py import plotly.graph_objs as go import co_func as cf def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): """file_name1 = ('../outputs/zout_' +topo_type.lower()+'_'+ task_type.lower() + '_' + x_var.lower() + '_trace'+trace_type+'.csv') file_name2 = ('../outputs/zout_' +topo_type.lower()+'_'+ task_type.lower() + '_' + x_var.lower() + '_chern_trace'+trace_type+'.csv')""" file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=p) return file_name1, file_name2 def read_csv(file_name, file_type=0, topo_type='CLASSIFICATION', is_epsilon=False): global ACAP if file_type == 0: return pd.read_csv(file_name) else: print('here') names=['#flows', 'time', 'epsilon', 'r_threshold', 'is_correlated', 'key', '#pres'] + ['a' + str(i) for i in range(ACAP)] if is_epsilon: names=['#flows', 'time', 'epsilon', 'r_threshold','is_correlated', 'key'] + ['a' + str(i) for i in range(ACAP)] return pd.read_csv(file_name, skiprows=[0], names=names) def q1(x): return x.quantile(0.25) def q2(x): return x.quantile(0.75) def retieveData(infile_name1, group_fields, agg_fields, accuracys, errors, times, div=False, task_type="CLASSIFICATION", file_type=0, q_75s=[], q_25s=[], xss=[] ): df1 = read_csv(infile_name1, file_type) df1 = df1.replace([2, '2.0', 2.0, '2'], 1) df1 = df1[df1['#flows'] > 10] flow_nums = df1['#flows'].unique() if div == True: if task_type == "CLASSIFICATION": case_num = df1['#all_cases'].loc[0] else: case_num = df1['#correlated_detect'].max() else: case_num = 1 df1 = df1[df1['is_correlated'] == 1] agg_dict = OrderedDict({}) for agg_field in agg_fields: agg_dict[agg_field] = ['mean', 'std', q1, q2, 'median'] """time_df = (df1 .groupby(group_fields) .agg({'time':['mean']}) ) times.append(time_df['time']['mean']) print 'times', times""" df1 = (df1 .groupby(group_fields) .agg(agg_dict) ) data = df1[agg_fields[0]]['mean'].divide(case_num) error = df1[agg_fields[1]]['std'].divide(case_num) #time = df1[agg_fields[2]]['mean'].divide(case_num) quantile_25 = df1[agg_fields[1]]['q1'].divide(case_num) quantile_75 = df1[agg_fields[1]]['q2'].divide(case_num) accuracys.append(data) errors.append(error) #times.append(time) q_75s.append([data-quantile_25, quantile_75-data]) q_25s.append(quantile_25) xss.append(list(flow_nums)) #[x[0] for x in df1.index.values] return flow_nums, case_num def ranking_num(row): global ACAP num = 0 for i in range(ACAP): if isinstance(row['a'+str(i)], str) and 'end' in row['a'+str(i)]: num = i/2 break if num == 0: print row print('ranking_num:num==0') eeeee return num def getTime(infile_name, times, group_fields=[], key_field='', file_type=0, topo_type='CLASSIFICATION', case_num=1, xss=[]): df1 = read_csv(infile_name, file_type, topo_type=topo_type) df1 = df1.sort(columns=['#flows']) #df1 = df1[df1['#flows'] > 20] #df1 = df1[df1['#flows'] < 80] flow_nums = df1['#flows'].unique() xss.append(list(flow_nums)) #df1 = df1[df1['#flows'] < 90] time_df = (df1 .groupby(group_fields) .agg({'time':['mean']}) ) times.append(list(time_df['time']['mean'].divide(case_num))) print 'times++++++++++++', times def rankingPair(infile_name, cherns, flow_seq, pair_seq, file_type=0, topo_type='CLASSIFICATION', cut=None ): # d: key: ranking[] df1 = read_csv(infile_name, file_type, topo_type=topo_type) df1 = df1.replace([2, '2.0', 2.0, '2'], 1) df1 = df1.fillna(value='end') d = {} print df1['key'].unique() print df1 for flow_num in df1['#flows'].unique(): for key in df1['key'].unique(): print 'flow_num, key', flow_num, key if (str(flow_num)+key) not in d: d[str(flow_num)+key] = {} for index, row in df1.iterrows(): num = ranking_num(row) key = str(row['#flows'])+row['key'] for i in range(num): if row['a'+str(num+i)] not in d[key]: d[key][row['a'+str(num+i)]] = [0, 0] d[key][row['a'+str(num+i)]][0] += float(row['a'+str(i)]) d[key][row['a'+str(num+i)]][1] += 1 d1 = {} for key1 in d: d1[key1] = [] for key2 in d[key1]: d[key1][key2][0] /= d[key1][key2][1] d1[key1].append((d[key1][key2][0], key2)) d1[key1] = sorted(d1[key1], key=lambda tup: tup[0]) pair = str(df1['#flows'].unique()[flow_seq])+df1['key'].unique()[pair_seq] print pair print d1[pair] if cut == None: cherns.append([x[0]for x in d1[pair]]) x = [x[1] for x in d1[pair]] else: cherns.append([x[0]for x in d1[pair][:cut]]) x = [x[1] for x in d1[pair][:cut]] xss.append(x) return x def accuracyPlot(topo_types, task_types, trace_types, pair_seq=0): accuracys, errors, times, x = [], [], [], None cherns, chern_errors, time_chern, chern_x = [], [], [], None for trace_type in trace_types: topo_type = topo_types[0] task_type = task_types[1] infile_name1, infile_name2 = init_files( trace_type, task_type, topo_type, x_var='TTESTFLOWNUM', p=0.01 ) group_fields = ['#flows','is_correlated'] agg_fields = ['#correlated_detect', '#non-uniform_detect'] x, case_num = retieveData( infile_name1, group_fields, agg_fields, accuracys, errors, times, div=True ) print x, case_num group_fields = ['#flows','is_correlated', 'key'] agg_fields = ['count_chern', 'byte_chern', 'time'] chern_x = retieveData( infile_name2, group_fields, agg_fields, cherns, chern_errors, time_chern, div=False ) acc_legend = ['Database', 'Web', 'Hadoop', 'e1', 'e5', 'e10', 'e50', 'e100'] xlabel, ylabel = 'The number of flows', 'Average accuracy' pl.plot(accuracys, x=x, k=2, errors=errors, xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('.')[0], xlog=False, ylog=False, acc_legend=acc_legend[0:3] ) """xlabel, ylabel = 'The number of flows', 'Average p-value' chern_x_pair = chern_x[0][0::case_num] cherns_per_pair = [] cherns_error_pair = [] for j in range(len(cherns)): for i in range(pair_seq,pair_seq+1): key = cherns[j].index.values[i][2] cherns_per_pair.append(cherns[j][i::case_num]) cherns_error_pair.append(chern_errors[j][i::case_num]) print cherns_per_pair, chern_x_pair pl.plot(cherns_per_pair, x=chern_x_pair, k=2, errors=[], xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('.')[0]+'pair-key'+str(pair_seq), xlog=False, ylog=True, acc_legend=acc_legend, legend_y=0.85 )""" def rankingPlot(topo_types, task_types, trace_types, pair_seq=0): global ACAP accuracys, errors, x, q_75s, q_25s, times = [], [], None, [], [], [] cherns, chern_errors, chern_x, time_chern = [], [], None, [] xss = [] xss1 = [] for topo_type in topo_types[0:3]: trace_type = trace_types[0] task_type = task_types[1] cut = 5 if topo_type == topo_types[2]: ACAP = 256 cut = 10 if topo_type == topo_types[0]: pair_num = 4 elif topo_type == topo_types[1]: pair_num = 8 elif topo_type == topo_types[2]: pair_num = 14 infile_name1, infile_name2 = init_files( trace_type, task_type, topo_type, x_var='CHERNFLOWNUM', p=0.01 ) infile_name3, infile_name4 = init_files( trace_type, task_type, topo_type, x_var='TTESTFLOWNUM', p=0.01 ) key_field = '#flows' group_fields = ['#flows','is_correlated'] agg_fields = ['#correlated_detect', '#correlated_detect'] x, case_num = retieveData( infile_name1, group_fields, agg_fields, accuracys, errors, times, div=True, task_type='RANKING', q_75s=q_75s, q_25s=q_25s, xss=xss ) x, case_num = retieveData( infile_name3, group_fields, agg_fields, accuracys, errors, time_chern, div=True, task_type='RANKING', q_75s=q_75s, q_25s=q_25s, xss=xss ) getTime(infile_name2, times, group_fields=group_fields, key_field=key_field, file_type=1, topo_type=topo_type, case_num=pair_num, xss=xss1) getTime(infile_name4, times, group_fields=group_fields, key_field=key_field, file_type=1, topo_type=topo_type, case_num=pair_num, xss=xss1) print(len(x)) group_fields = ['#flows','is_correlated', 'key'] agg_fields = ['a'+str(i) for i in range(ACAP)] #print(agg_fields) """chern_x = rankingPair( infile_name2, cherns, 2, pair_seq, file_type=1, topo_type=topo_type, cut=cut )""" acc_legend = ['B4-Chernoff', 'B4-t-test', 'Tree-Chernoff', 'Tree-t-test', 'Jupiter-Chernoff', 'Jupiter-t-test', 'e1', 'e5', 'e10', 'e50', 'e100'] xlabel, ylabel = 'The number of flows', 'Average accuracy' pl.plot(accuracys, x=xss, k=2, errors=[], xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('/outputs')[1].split('.csv')[0].replace('.', '_'), xlog=False, ylog=False, acc_legend=acc_legend[:len(accuracys)], legend_x=0.45 ) x = [20, 30, 40, 50, 60, 70] xss = [x]*len(times) print times, len(times[0]) pl.plot(times, x=xss1, k=2, errors=[], xlabel=xlabel, ylabel='Execution time (seconds)', title=infile_name1.split('/outputs')[1].split('.csv')[0].replace('.', '_')+'_time', xlog=False, ylog=False, acc_legend=acc_legend, legend_y=0.85, legend_x = 0.0 ) xlabel, ylabel = 'Previous hop', 'Average p-value' print chern_x xticks = [] if chern_x != None: xticks = chern_x """pl.plot(cherns, x=[], k=len(cherns), errors=[], xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('/outputs')[1].split('.csv')[0]+'pair-key'+str(pair_seq), xlog=False, ylog=True, acc_legend=acc_legend, xticks=chern_x, figure_width=4.3307*1.25 )""" if __name__ == "__main__": global ACAP ACAP = 50 topo_types = ['B4', 'TREE', 'JUPITER'] task_types = ['CLASSIFICATION', 'RANKING', 'APPLICATION'] trace_types = ['A', 'B', 'C', 'e1', 'e5', 'e10', 'e50', 'e100'] pair_seq = 2 print trace_types[:3] #accuracyPlot(topo_types, task_types, trace_types[:3], pair_seq=pair_seq) rankingPlot(topo_types, task_types, trace_types[:3], pair_seq=pair_seq) plt.show() <file_sep>import networkx as nx import matplotlib.pyplot as plt from crc8 import crc8 from co_func import append_path import random from path_matrix import path_matrix import mesh_detection as mdt import mark_flows as mf from crc32 import crc32 import struct def get_seeds_table(router_nodes): """ Assign seed and polinmial to node. """ poly_list = ( [0x31, 0x2f, 0x39, 0xd5, 0x4d, 0x8d, 0x9b, 0x7a, 0x07, 0x49, 0x1d, 0x2d, 0x3d, 0x8b, 0x7b] ) np = len(poly_list) seeds = {} polys = {} i = 0 for node in router_nodes: seeds[node] = i*7 if i < np: polys[node] = poly_list[i] else: k = random.randint(0, np-1) polys[node] = poly_list[k] i += 1 polys = ({'s3': 0x31, 's4': 0x2f, 's5': 0x39, 's6': 0xd5, 's7': 0x4d, 's8': 0x8d, 's10': 0x9b, 's11': 0x7a, 's1': 0x07, 's2': 0x07, 's9': 0x07, 's12': 0x07} ) return seeds, polys def set_correlation(r1, r2, polys): poly_r2 = polys[r2] polys[r2] = polys[r1] return poly_r2 def reset_correlation(r2, polys, poly): polys[r2] = poly def build_graph(): G = nx.MultiGraph() edges = ([('s1', 's2', dict(route=0)), ('s1', 's5', dict(route=0)), ('s2', 's3', dict(route=0)), ('s3', 's4', dict(route=0)), ('s3', 's6', dict(route=0)), ('s4', 's5', dict(route=0)), ('s4', 's7', dict(route=0)), ('s4', 's8', dict(route=0)), ('s5', 's6', dict(route=0)), ('s6', 's7', dict(route=0)), ('s6', 's8', dict(route=0)), ('s7', 's8', dict(route=0)), ('s7', 's11', dict(route=0)), ('s8', 's10', dict(route=0)), ('s9', 's10', dict(route=0)), ('s9', 's11', dict(route=0)), ('s10', 's11', dict(route=0)), ('s10', 's12', dict(route=0)), ('s11', 's12', dict(route=0)), ] ) host_switch = ([('s1', 'h1', dict(route=0)), ('s2', 'h2', dict(route=0)), ('s3', 'h3', dict(route=0)), ('s4', 'h4', dict(route=0)), ('s5', 'h5', dict(route=0)), ('s6', 'h6', dict(route=0)), ('s7', 'h7', dict(route=0)), ('s8', 'h8', dict(route=0)), ('s9', 'h9', dict(route=0)), ('s10', 'h10', dict(route=0)), ('s11', 'h11', dict(route=0)), ('s12', 'h12', dict(route=0)) ] ) G.add_edges_from(edges) G.add_edges_from(host_switch) return G def routing(s, d, table): paths = list(nx.all_shortest_paths(G, s, d)) for path in paths: for i, node in enumerate(path): if i < len(path) - 1: if d not in table[node]: table[node][d] = [] if path[i+1] not in table[node][d]: table[node][d].append(path[i+1]) def all_routing(G, switch_nodes): # Routing table table = {} for s in G.nodes(): if 's' in s: table[s] = {} for s in switch_nodes: for d in switch_nodes: if s != d: routing(s, d, table) return table # No marking packets def next_hop(cur_hop, pre_hop, s, d, hash_str, table, seeds, polys, flow_paths ): print('cur_hop, pre_hop', cur_hop, pre_hop) if cur_hop == d: hash_str0 = hash_str hash_str = hash_str0[0:14] marker = hash_str0[14:] if marker != 'None': append_path(hash_str, pre_hop, cur_hop, flow_paths) return n = len(hash_str) # Header = 4+4+2+2+1 bytes hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] if marker == cur_hop: append_path(hash_str, pre_hop, cur_hop, flow_paths) nhop = table[cur_hop][d][0] n = len(table[cur_hop][d]) if n > 1: ni = crc8(seeds[cur_hop], hash_str, polys[cur_hop])%n nhop = table[cur_hop][d][ni] next_hop(nhop, cur_hop, s, d, hash_str0, table, seeds, polys, flow_paths) def map_addr_int(s, d): """ Map the current source and dest address to the ones in the topo """ s_out, d_out = crc32(s), crc32(d) return s_out, d_out def map_addr(s, d): """ Map the current source and dest address to the ones in the topo """ s_out, d_out = crc8(0, s, 0x31)%11 + 1, crc8(0, d, 0x1d)%11 + 1 count = 0 while s_out == d_out and count < 5: s_out, d_out = crc8(0, s, 0x31)%11 + 1, crc8(0, d, 0x1d)%11 + 1 count += 1 s_out, d_out = 's' + str(s_out), 's' + str(d_out) return s_out, d_out def map_addr_tree(s, d, tors): """ Map the current source and dest address to the ones in the topo """ n = len(tors) s_out, d_out = crc8(0, s, 0x31)%n + 1, crc8(0, d, 0x1d)%n + 1 count = 0 while s_out == d_out and count < 5: s_out, d_out = crc8(0, s, 0x31)%n + 1, crc8(0, d, 0x1d)%n + 1 count += 1 s_out, d_out = tors[s_out], tors[d_out] return s_out, d_out def map_port(sp, dp): s_out, d_out = crc32(sp) & 0x0000ffff, crc32(dp) & 0x0000ffff return s_out, d_out def hashStr(data): """ Return the packet header """ s, d = map_addr_int(data[2], data[3]) sp, dp = map_port(data[4], data[5]) data[2], data[3] = struct.pack('>I', s), struct.pack('>I', d) data[4], data[5] = struct.pack('>I', sp)[2:], struct.pack('>I', dp)[2:] data[6] = struct.pack('>I', int(data[6]))[-1] hash_str = (data[2] + data[3] + data[4] + data[5] + data[6] ) return hash_str def flow_routing(file_name, seeds, polys, flow_paths, switch_nodes, table): mark_group = mf.mark_group_dest(table) count = 0; start_time = 0; is_update = True flow_dict = {} with open((file_name), 'r') as f: for line in f: count += 1 if(count < 25000): data = line.split() # Update start time if(is_update): start_time = float((data[0])) is_update = False # Monitor every second #if (float(data[0]) - start_time) > 1: #is_update = True #print('Greater than 1.') #break s, d = map_addr(data[2], data[3]) hash_str = hashStr(data) flow_dict[hash_str] = 1 count_dict, threshold = {}, 100000 switch_id = mf.marknum( hash_str, count_dict, threshold, mark_group[d] ) hash_str += switch_id next_hop( s, 'h1', s, d, hash_str, table, seeds, polys, flow_paths ) else: print('time', (float(data[0]) - start_time)) print('Flow num:', len(flow_dict)) print('pkt count:', count) break return def single(r1, r2, pairs, switch_nodes, trues, ests, table): poly = set_correlation(r1, r2, polys) flow_paths = {} flow_routing(file_name, seeds, polys, flow_paths, switch_nodes, table) print(flow_paths) eeee rm = path_matrix(flow_paths, switch_nodes) print((rm)) eee cherns = {} dss = [] for s in switch_nodes: cherns[s], ds = mdt.hash_biased(s, rm, switch_nodes, table[s]) dss.append(ds) print('cherns', cherns) epsilon = 0.001 for s in switch_nodes: if cherns[s] < epsilon: trues += 1 print('++++++++++, s, chern, r1, r2', s, cherns[s], r1, r2) pairs.append([r1, r2, cherns[s]]) ranking = locate_corr(s, rm, switch_nodes, table) print('ranking', ranking) if len(ranking) != 0: if ranking[0][0] == r1 or ranking[0][0] == r2: ests += 1 reset_correlation(r2, polys, poly) return trues, ests def locate_corr(s, rm, switch_nodes, table): # pre_hops = [x for x in switch_nodes if x != s] print('pre_hops', pre_hops) cherns = mdt.corr_group(pre_hops, s, rm, switch_nodes, table) return cherns if __name__ == "__main__": # Build a graph G = build_graph() switch_nodes = ['s' + str(i) for i in range(1, 13)] # Get the routing path of all nodes table = all_routing(G, switch_nodes) seeds, polys = get_seeds_table(switch_nodes) file_name = ("/home/yunhong/Research_4/distributions/outputs/" + "split_flows_150s_web_sort_host" ) file_name = '/home/yunhong/Research_4/caida_trace/outputs/results' single_nodes = ['s1', 's2', 's9', 's12'] multi_nodes = [x for x in switch_nodes if x not in single_nodes] pairs = [] trues, ests = 0, 0 for r1 in multi_nodes: for r2 in multi_nodes: if r1 != r2: a = 0 trues, ests = single( r1, r2, pairs, switch_nodes, trues, ests, table ) print('pairs', pairs) #trues, ests = single('s4', 's3', pairs, switch_nodes, trues, ests) print('trues, ests', trues, ests) #mdt.corr_group(['s4'], 's3', rm, switch_nodes, table) #mdt.corr_group(['s3'], 's4', rm, switch_nodes, table) <file_sep>import random """ Mark packets in a flow Options: Mark every packet Mark some packet (This is resonable) """ def mark_group_dest(routing_table): """ How to mark packets according to destination only mark thoes with multi-path """ mark_group = {} for s_d in routing_table: for d in routing_table[s_d]: #if len(routing_table[s_d][d]) > 1: if d not in mark_group: mark_group[d] = [] mark_group[d] += routing_table[s_d][d] mark_group[d] = list(set(mark_group[d])) for key in mark_group: mark_group[key] += [key] return mark_group def marknum(hash_str, count_dict, mark_dict, threshold, mark_group): """ Determine how many packets to mark such that we can get a complete path """ if hash_str not in count_dict: count_dict[hash_str] = 2 mark_dict[hash_str] = {} switch_id = mark(mark_group, count_dict[hash_str]) count_dict[hash_str] += 1 if switch_id not in mark_dict[hash_str]: mark_dict[hash_str][switch_id] = 0 mark_dict[hash_str][switch_id] += 1 #if count_dict[(hash_str, switch_id)] > threshold: #return 'None' return switch_id def mark(mark_group, count): """ Return a switch ID it may be tranversing Currently, all switch IDs are in considering """ n = len(mark_group) pos = random.randint(0, n-1) #count % n # return mark_group[pos] def mark_random(p=0.1): r = random.random() if r < p: return "1" return "0" <file_sep>from collections import OrderedDict import bound as bd import numpy as np from crc32 import crc32 import random def collect_flows(hash_str, pre_hop, cur_hop, size, cflow_dict, app_link_dict, app_link_flow_dict, next_hops='', d='tor1' ): # hash_str: 4+4+2+2 # Per link. Per app, if (pre_hop, cur_hop) not in cflow_dict: cflow_dict[(pre_hop, cur_hop)] = {} dst_port = hash_str[10:12] dst_tor = int(int(d[3:])/129) key = dst_tor if key not in cflow_dict[(pre_hop, cur_hop)]: cflow_dict[(pre_hop, cur_hop)][key] = 0 cflow_dict[(pre_hop, cur_hop)][key] += size # Per link, Per app, flow count if (pre_hop, cur_hop) not in app_link_dict: app_link_dict[(pre_hop, cur_hop)] = {} app_link_flow_dict[(pre_hop, cur_hop)] = {} dst_port = hash_str[10:12] dst_tor = int(int(d[3:])/129) key = dst_tor if key not in app_link_dict[(pre_hop, cur_hop)]: app_link_dict[(pre_hop, cur_hop)][key] = 0 app_link_flow_dict[(pre_hop, cur_hop)][key] = {} if hash_str not in app_link_flow_dict[(pre_hop, cur_hop)][key]: app_link_flow_dict[(pre_hop, cur_hop)][key][hash_str] = 0 app_link_dict[(pre_hop, cur_hop)][key] += 1 def append_path(hash_str, pre_hop, cur_hop, d, paths, size=1): if (hash_str, d) not in paths: paths[(hash_str, d)] = OrderedDict({}) if (pre_hop, cur_hop) not in paths[(hash_str, d)]: paths[(hash_str, d)][(pre_hop, cur_hop)] = 0 paths[(hash_str, d)][(pre_hop, cur_hop)] += size #int(max(1, size/500)) def min_bound(next_counts, flow_indicator=1): n = len(next_counts) min_bound = 1.1 min_pos = -1 if flow_indicator == 1: sum_HHes = np.float64(((sum(next_counts)))) else: next_counts_cut = [[1]*len(x) for x in next_counts] sum_HHes = np.float64(sum([x for sub in next_counts_cut for x in sub])) for i in range(n): if flow_indicator == 1: o_fi = float((next_counts[i]))/sum_HHes else: o_fi = float(sum(next_counts[i]))/np.float64(sum([x for sub in next_counts for x in sub])) next_counts = [[1]*len(x) for x in next_counts] ratio = 1.0/len(next_counts) if o_fi <= 1:#ratio: if flow_indicator == 1: flow_fractions = [float(1.0)/sum_HHes]*int(sum_HHes) else: flow_fractions = ([x/sum_HHes for sub in next_counts for x in sub] ) theta, chern_bound = bd.chernoff_min( flow_fractions, o_fi, ratio=ratio ) if chern_bound < min_bound: min_bound = chern_bound min_pos = i # print(' %%min_bound', min_bound) return min_bound class singleNode(object): def __init__(self, val): self.val = val self.pre = None self.next = None def makelist(points): d = {} p = None count = 0 while(count < 2): count += 1 for point in points: if point[0] not in d: snode0 = singleNode(point[0]) d[point[0]] = snode0 else: snode0 = d[point[0]] if point[1] not in d: snode1 = singleNode(point[1]) d[point[1]] = snode1 else: snode1 = d[point[1]] snode0.next = snode1 snode1.pre = snode0 p = snode0 while(p.pre != None): p = p.pre nodes = [] while(p != None): nodes.append(p.val) p = p.next return nodes def get_seeds_table(router_nodes): """ Assign seed and polinmial to node. """ poly_list = ( [0x31, 0x2f, 0x39, 0xd5, 0x4d, 0x8d, 0x9b, 0x7a, 0x07, 0x49, 0x1d, 0x2d, 0x3d, 0x8b, 0x7b] ) np = len(poly_list) seeds = {} polys = {} i = 0 for node in router_nodes: seeds[node] = crc32(node)%256 if i < np: polys[node] = poly_list[i] else: k = random.randint(0, np-1) polys[node] = poly_list[k] i += 1 polys = ({'s3': 0x31, 's4': 0x2f, 's5': 0x39, 's6': 0xd5, 's7': 0x4d, 's8': 0x8d, 's10': 0x9b, 's11': 0x7a, 's1': 0x07, 's2': 0x07, 's9': 0x07, 's12': 0x07} ) return seeds, polys def get_seeds_table_tree(router_nodes): """ Assign seed and polinmial to node. """ poly_list = ( [0x31, 0x2f, 0x39, 0xd5, 0x4d, 0x8d, 0x9b, 0x7a, 0x07, 0x49, 0x1d, 0x2d, 0x3d, 0x8b, 0x7b, 0xff, 0xef, 0xdf, 0xcf, 0xbf, 0xaf, 0x9f, 0x8f, 0x7f, 0x6f, 0x5f, 0x4f, 0x3f, 0x1f, 0xde, 0xce, 0xbe, 0xae, 0x9e, 0x8e, 0x7e, 0x6e, 0x5e, 0x4e, 0x3e, 0x2e] ) np = len(poly_list) seeds = {} polys = {} i = 0 for node in router_nodes: seeds[node] = crc32(node)%256 if i < np: polys[node] = poly_list[i] else: k = random.randint(0, np-1) polys[node] = poly_list[k] i += 1 return seeds, polys def get_seeds_table_jupiter(router_nodes): """ Assign seed and polinmial to node. """ poly_list = ( [0x31, 0x2f, 0x39, 0xd5, 0x4d, 0x8d, 0x9b, 0x7a, 0x07, 0x49, 0x1d, 0x2d, 0x3d, 0x8b, 0x7b, 0xff, 0xef, 0xdf, 0xcf, 0xbf, 0xaf, 0x9f, 0x8f, 0x7f, 0x6f, 0x5f, 0x4f, 0x3f, 0x1f, 0xde, 0xce, 0xbe, 0xae, 0x9e, 0x8e, 0x7e, 0x6e, 0x5e, 0x4e, 0x3e, 0x2e] ) np = len(poly_list) seeds = {} polys = {} i = 0 d = {'tor': 0x31, 'al': 0x2f, 'ah': 0x39, 'sl': 0xd5, 'sh': 0x4d, 'e': 0x8d} for node in router_nodes: seeds[node] = crc32(node)%256 for key in d: if key in node: polys[node] = d[key] i += 1 return seeds, polys def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): file_name1 = ('../outputs/zout_' +topo_type.lower()+'_'+ task_type.lower() + '_' + x_var.lower() + '_trace'+trace_type+'_p'+str(p)+'.csv') file_name2 = ('../outputs/zout_' +topo_type.lower()+'_'+ task_type.lower() + '_' + x_var.lower() + '_chern_trace'+trace_type+'_p'+str(p)+'.csv') return file_name1, file_name2 <file_sep>import math from scipy.stats import entropy def getEntropy(data): """ Compute entropy """ data_sum = sum(data) print('data_sum', data_sum) if data_sum == 0: return 0 p = [x/data_sum for x in data] return entropy(p) print(getEntropy([1.0/4, 1.0/4, 1.0/4, 1.0/4])) <file_sep>from crc8 import crc8 from collections import OrderedDict from co_func import append_path def host(pre_hop, cur_hop, ev, hash_str, size, byte_cnt, link_byte_cnt, paths): byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size def tor_sw(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size # Generate random port port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] host(cur_hop, next_hop, ev, hash_str, size, byte_cnt, link_byte_cnt, paths) def aggr_sw(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size # Generate random port port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] tor_sw( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def spine_sw(cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): byte_cnt[cur_hop] += size port_num = 4 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] aggr_sw( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def host_up(cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): #append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size next_hop = port_list[cur_hop] tor_sw_up( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def tor_sw_up(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size port_num = 4 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] aggr_sw_up_0( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def aggr_sw_up_0(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] aggr_sw_up_1( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def aggr_sw_up_1(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] spine_sw_up_0( cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths ) def spine_sw_up_0(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop])%port_num next_hop = port_list[cur_hop].split()[port] spine_sw_up_1( cur_hop, next_hop, ev, hash_str, size, byte_cnt, link_byte_cnt, paths ) def spine_sw_up_1(pre_hop, cur_hop, ev, hash_str, size, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop+' '+cur_hop] += size <file_sep>from scipy import stats import pandas as pd import numpy as np def independentCluster(table, p_t): """ * Split the table to several tables """ apps = list(table.columns.values) n0 = len(apps) nn = 0 count = 0 while(nn != n0): n0 = len(apps) apps_compliment = [] while len(apps) != 0: a1 = [apps[0]] if isinstance(apps[0], str) else apps[0] max_p, max_a, max_ai = 0, [], None apps = apps[1:] for i, a2 in enumerate(apps): if isinstance(a2, str): a2 = [a2] table1 = table[a1+a2] ret = stats.chi2_contingency(observed=table1) p = ret[1] if max_p < p: max_p, max_a, max_ai = p, a2, i tmp = a1 if max_p > p_t: tmp += max_a if max_ai != None: apps.remove(apps[max_ai]) apps_compliment.append(tmp) count += 1 #if count == 5: #eee apps = apps_compliment nn = len(apps_compliment) app_imrs = [] for app in apps: inner_max, inner_min, inner_mean, inner_p = 0, 0, 0, 0 for a in app: inner_max += table[a].max() inner_min += table[a].min() inner_mean += table[a].mean() inner_imr = float(inner_max-inner_min)/inner_max if len(app) > 1: table1 = table[app] ret = stats.chi2_contingency(observed=table1) inner_p = ret[1] else: inner_p = 1.0 app_imrs.append((app, inner_p, inner_imr)) return app_imrs """d = {'a1': [1, 2, 5, 6], 'a2': [3, 4, 7, 8], 'a3': [1, 2, 5, 6], 'a4': [3, 4, 7, 8]} d = ({'a1': [9,3,31,38,24,4,27,6], 'a2': [307,345,1020,972,1020,349,1034,347], 'a3': [10,10,35,39,43,15,48,9], 'a4': [170,180,556,505,566,202,524,187], 'a5': [19,24,66,56,70,17,62,20]}) d = ({'a1': [19,17,18,15,24,21,14,14], 'a2': [307,345,1020,972,1020,349,1034,347], 'a3': [30,33,12,29,35,21,26,23], 'a4': [350,365,364,354,377,381,379,320], 'a5': [50,45,35,34,50,56,38,26] }) table = pd.DataFrame(data=d) independentCluster(table, 0.01)""" <file_sep>import numpy as np import bound as bd def crc_test(): HHes = [1]*10 + [0]*10 print HHes o_f = 0.5 theta, bound = bd.chernoff_min(HHes, o_f, ratio = 0.5) print(theta, bound) <file_sep>import networkx as nx import matplotlib.pyplot as plt from crc8 import crc8 import co_func as cf from co_func import append_path, collect_flows import random from path_matrix import path_matrix import mesh_detection_flow_table as mdt import mark_flows as mf from crc32 import crc32 import struct import application as ap import pandas as pd import operator import topo as tp import json import os.path from collections import Counter, OrderedDict import sys import time def set_correlation(r1, r2, polys): """ Make the two switches use the same hash polinomials """ poly_r2 = polys[r2] polys[r2] = polys[r1] return poly_r2 def reset_correlation(r2, polys, poly): """ Recover the polynomial on the switch """ polys[r2] = poly def build_graph(edges): """ Build the graph by the given topology """ G = nx.MultiGraph() G.add_edges_from(edges) return G def routing(G, s, d, table): """ Build routing table based on shortest path for the s,d pair """ try: paths = list(nx.all_shortest_paths(G, s, d)) except: print('s, d', s, d) paths = [] print('nx.has_path(G, s, d)', nx.has_path(G, s, d)) eee #print('len(paths)', len(paths)) for path in paths: for i, node in enumerate(path): if i < len(path) - 1: if node not in table: table[node] = OrderedDict({}) if d not in table[node]: table[node][d] = [] if path[i+1] not in table[node][d]: table[node][d].append(path[i+1]) def all_routing(G, switch_nodes, table_file_name): """ Build routing table for all the s,d pairs """ table = OrderedDict({}) for s in switch_nodes: for d in switch_nodes: if s != d: routing(G, s, d, table) with open(table_file_name, 'w') as file: file.write(json.dumps(table)) return table def all_routing_tree(G, tors, table_file_name): """ Build routing table for all the s, d pairs from Tors to Tors """ table = OrderedDict({}) for s in G.nodes(): table[s] = OrderedDict({}) for s in tors: for d in tors: if s != d: routing(G, s, d, table) with open(table_file_name, 'w') as file: file.write(json.dumps(table)) return table def all_routing_tree_2(G, tors1, tors2, table_file_name): """ Build routing table for all the s, d pairs from Tors to Tors """ table = OrderedDict({}) for s in G.nodes(): table[s] = OrderedDict({}) for s in tors1: for d in tors2: if s != d: routing(G, s, d, table) for d in tors1: for s in tors2: if s != d: routing(G, s, d, table) with open(table_file_name, 'w') as file: file.write(json.dumps(table)) return table # No marking packets def next_hop(cur_hop, pre_hop, s, d, hash_str, size, table, seeds, polys, flow_paths, cflow_dict, app_link_dict, select_dict=OrderedDict({}) ): if cur_hop == d: hash_str0 = hash_str hash_str = hash_str0[0:14] marker = hash_str0[14:] if marker == cur_hop: append_path(hash_str, pre_hop, cur_hop, d, flow_paths) select_dict[hash_str] = 1 return n = len(hash_str) # Header = 4+4+2+2+1 bytes hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] collect_flows(hash_str, pre_hop, cur_hop, size, cflow_dict) if marker == cur_hop: append_path(hash_str, pre_hop, cur_hop, d, flow_paths) select_dict[hash_str] = 1 nhop = table[cur_hop][d][0] n = len(table[cur_hop][d]) if n > 1: ni = crc8(seeds[cur_hop], hash_str, polys[cur_hop])%n nhop = table[cur_hop][d][ni] next_hop( nhop, cur_hop, s, d, hash_str0, size, table, seeds, polys, flow_paths, cflow_dict, app_link_dict, select_dict ) # No marking packets def next_hop_rand_mark(cur_hop, pre_hop, s, d, hash_str, size, table, seeds, polys, min_len, flow_paths, cflow_dict, app_link_dict, app_link_flow_dict, select_dict=OrderedDict({}), drop_id=0, r_threshold=0.0, black_hole='sh41', test_hop='', add_byte_dict = OrderedDict({}), w_key=0.0 ): if cur_hop == d: hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] if marker == "1": append_path(hash_str, pre_hop, cur_hop, d, flow_paths, size=size) #select_dict[hash_str] = 1 return min_len # Header = 4+4+2+2+1 bytes hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] next_hops = '' if pre_hop in table: next_hops = ','.join(sorted(table[pre_hop][d])) if black_hole != None: collect_flows( hash_str, pre_hop, cur_hop, size, cflow_dict, app_link_dict, app_link_flow_dict, next_hops, d=s ) nhop = table[cur_hop][d][0] n = len(table[cur_hop][d]) if n > 1: ni = crc8(seeds[cur_hop], hash_str, polys[cur_hop])%n nhop = table[cur_hop][d][ni] if cur_hop in test_hop: if cur_hop not in select_dict: select_dict[cur_hop] = OrderedDict({}) if hash_str not in select_dict[cur_hop]: select_dict[cur_hop][hash_str] = 1 min_len = min([len(select_dict[x]) for x in test_hop if x in select_dict]) #print min_len # Drop some packets from a particular link """if black_hole == nhop and int(int(s[3:])/129) == drop_id: r = random.random() if r < r_threshold: return""" """if test_hop not in add_byte_dict: add_byte_dict[test_hop] = 0.0 add_byte_dict[test_hop] += size """ # Randomly choosen a flow and add extra byte to it if cur_hop in test_hop and cur_hop not in add_byte_dict: add_byte_dict[cur_hop] = OrderedDict({}) if drop_id > 0 and n > 1 and cur_hop in test_hop and nhop == table[cur_hop][d][0] and len(add_byte_dict[cur_hop]) < 2: w_key1 = str(flow_cap) + ',' + cur_hop + ',' + topo_type w_key_size = w_key[w_key1] add_byte_dict[hash_str] = 1000*size size = (w_key_size)*r_threshold/(1-r_threshold*2) #print 'haha', size if marker == "1": append_path(hash_str, pre_hop, cur_hop, d, flow_paths, size=size) min_len = next_hop_rand_mark( nhop, cur_hop, s, d, hash_str0, size, table, seeds, polys, min_len, flow_paths, cflow_dict, app_link_dict, app_link_flow_dict, select_dict, drop_id=drop_id, r_threshold=r_threshold, black_hole=black_hole, test_hop=test_hop, add_byte_dict=add_byte_dict, w_key=w_key ) return min_len # Using hash set to get the paths of the flows def next_hop_hash_set(cur_hop, pre_hop, s, d, hash_str, table, seeds, polys, flow_paths, select_dict=OrderedDict({}), test_hop = '' ): select_range = 1 << 28 if cur_hop == d: hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] hash_mid = crc32(hash_str) if hash_mid < select_range: append_path(hash_str, pre_hop, cur_hop, d, flow_paths) if cur_hop == test_hop: select_dict[hash_str] = 1 return n = len(hash_str) # Header = 4+4+2+2+1 bytes hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] hash_mid = crc32(hash_str) if hash_mid < select_range: append_path(hash_str, pre_hop, cur_hop, d, flow_paths) if cur_hop == test_hop: select_dict[hash_str] = 1 nhop = table[cur_hop][d][0] n = len(table[cur_hop][d]) if n > 1: ni = crc8(seeds[cur_hop], hash_str, polys[cur_hop])%n nhop = table[cur_hop][d][ni] next_hop_hash_set( nhop, cur_hop, s, d, hash_str0, table, seeds, polys, flow_paths, select_dict, test_hop=test_hop ) def map_addr_int(s, d): """ Map the current source and dest address to the ones in the topo """ s_out, d_out = crc32(s), crc32(d) return s_out, d_out def map_addr(s, d): """ Map the current source and dest address to the ones in the topo """ s_out, d_out = crc8(0, s, 0x31)%11 + 1, crc8(0, d, 0x1d)%11 + 1 count = 0 while s_out == d_out and count < 5: s_out, d_out = crc8(0, s, 0x31)%11 + 1, crc8(0, d, 0x1d)%11 + 1 count += 1 s_out, d_out = 's' + str(s_out), 's' + str(d_out) return s_out, d_out def map_addr_tree(s, d, tors): """ Map the current source and dest address to the ones in the topo """ if len(tors) < 2: print('map_addr_tree: Error: len(tors) < 2') eee tors1 = tors[:] n = len(tors) #s_out = crc8(0, s, 0x31)%n + 1 s_out = random.randint(0, n-1) + 1 s_out = tors[s_out-1] tors1.remove(s_out) #d_out = crc8(0, d, 0x1d)%(n-1) + 1 d_out = random.randint(0, n-2) + 1 d_out = tors1[d_out-1] return s_out, d_out def map_addr_tree_app(s, d, tors): """ Map the current source and dest address to the ones in the topo """ if len(tors) < 2: print('map_addr_tree: Error: len(tors) < 2') eee tors1 = tors[:] n = len(tors) s_out = random.randint(0, n-1) + 1 s_out = tors[s_out-1] tors1.remove(s_out) d_out = 'e1' return s_out, d_out def map_addr_tree_2(s, d, tors1, tors2): """ Map the current source and dest address to the ones in the topo """ s_d = crc8(0, s, 0x31)%2 if s_d == 1: tors1, tors2 = tors2, tors1 n1 = len(tors1) n2 = len(tors2) #s_out, d_out = crc8(0, s, 0x31)%n1 + 1, crc8(0, d, 0x1d)%n2 + 1 s_out, d_out = random.randint(0, n1-1) + 1, random.randint(0, n2-1) + 1 s_out, d_out = tors1[s_out-1], tors2[d_out-1] return s_out, d_out def map_addr_tree_3(s, d, tors, block=4): """ Map the current source and dest address to the ones in the topo """ block_id = crc8(0, s, 0x31)%block s_d = crc8(0, s, 0x31)%2 n1 = 128 if block_id == 0: n2 = 128*3 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[s_out], tors[128 + d_out] elif block_id == 3: n2 = 128*3 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[d_out] elif block_id == 1: out_block = random.randint(0, 2) if out_block == 0: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[d_out] elif out_block == 1: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[128*(block_id+1) + d_out] else: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[128*(block_id+2) + d_out] elif block_id == 2: out_block = random.randint(0, 2) if out_block == 0: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[d_out] elif out_block == 1: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[128*(1+1) + d_out] else: n2 = 128 s_out, d_out = random.randint(0, n1-1), random.randint(0, n2-1) s_out, d_out = tors[128*block_id + s_out], tors[128*(block_id+1) + d_out] return s_out, d_out def map_port(sp, dp): s_out, d_out = crc32(sp) & 0x0000ffff, crc32(dp) & 0x0000ffff return s_out, d_out def hashStr(data): """ Return the packet header """ s, d = map_addr_int(data[2], data[3]) sp, dp = map_port(data[4], data[5]) data[2], data[3] = struct.pack('>I', s), struct.pack('>I', d) data[4], data[5] = struct.pack('>I', sp)[2:], struct.pack('>I', dp)[2:] data[6] = struct.pack('>I', int(data[6]))[-1] hash_str = (data[2] + data[3] + data[4] + data[5] + data[6] ) return hash_str def send_packet(hash_str, size, s, d, count_dict, count_dict1, mark_dict, threshold, mark_group, seeds, polys, min_len, flow_paths, cflow_dict, app_link_dict, app_link_flow_dict, switch_nodes, table, select_dict, drop_id=0, r_threshold=0.0, black_hole='sh41', test_hop='', add_byte_dict=OrderedDict({}), w_key=''): """switch_id = mf.marknum( hash_str, count_dict, count_dict1, threshold, mark_group[d] )""" pkt_mark = "0" if len(select_dict) < 1000000: pkt_mark = mf.mark_random(p=1.0) hash_str += pkt_mark if hash_str not in mark_dict: mark_dict[hash_str] = 0 mark_dict[hash_str] += 1 min_len = next_hop_rand_mark( s, 'h1', s, d, hash_str, size, table, seeds, polys, min_len, flow_paths, cflow_dict, app_link_dict, app_link_flow_dict, select_dict, drop_id=drop_id, r_threshold=r_threshold, black_hole=black_hole, test_hop=test_hop, add_byte_dict=add_byte_dict, w_key=w_key ) return min_len def flow_routing(file_name, seeds, polys, min_len, flow_paths, switch_nodes, table, flow_cap=1000, topo_type='B4', task_type='CLASSIFICATION', key='', class_dict=OrderedDict({}), imr_threshold=0.1, k=3, drop_id=0, r_threshold=0.0, black_hole='sh41', links=[], test_hop='', exc_time=0.0): mark_group = [] #mark_group = mf.mark_group_dest(table) count = 0; start_time = 0; start_time0 = 0; is_update = True flow_dict = OrderedDict({}) count_dict, threshold = OrderedDict({}), 100000 mark_dict = OrderedDict({}) count_dict1 = OrderedDict({}) select_dict = OrderedDict({}) cflow_dict = OrderedDict({}) app_link_dict = OrderedDict({}) app_link_flow_dict = OrderedDict({}) perlink_df = pd.DataFrame() add_byte_dict=OrderedDict({}) byte_dict_from_file = OrderedDict({}) with open(("../inputs/total_bytes"), 'a+') as f: for line in f: data = line.split(',') key = ','.join(data[:-1]) byte_dict_from_file[key] = float(data[-1]) with open((file_name), 'r') as f: for line in f: if(len(flow_dict) < 1824763): data = line.split() # Update start time if(is_update): start_time = float(data[0]) start_time0 = float(data[0]) is_update = False if task_type != 'APPLICATION': #if len(select_dict) >= flow_cap: #20000: if min_len >= flow_cap: """with open(("../inputs/total_bytes"), 'a') as f: for key in add_byte_dict: w_key = str(flow_cap) + ',' + key + ',' + topo_type print w_key, byte_dict_from_file.keys() if w_key not in byte_dict_from_file: f.write(w_key + ',' + str(add_byte_dict[key]) + '\n') byte_dict_from_file[w_key] = add_byte_dict[key]""" break if (float(data[0]) - start_time0) > 150: is_update = True print('Greater than 5.') break # Dominant applications and hash bias detection if task_type == 'APPLICATION': if (float(data[0]) - start_time) > 1.0: #if len(select_dict) >= flow_cap: start_time = time.time() is_update = True ap.appLinkCorrelation( data, perlink_df, app_link_dict, cflow_dict, key=key, class_dict=class_dict, imr_threshold=imr_threshold, k=k, topo_type=topo_type, links=links ) exc_time += time.time() - start_time return min_len break if topo_type == 'JUPITER1': #'JUPITER': s, d = map_addr_tree_3( data[2], data[3], switch_nodes ) #switch_nodes[:len(switch_nodes)/2], #switch_nodes[len(switch_nodes)/2:] if task_type == 'APPLICATION': idx = int(data[7]) s, d = map_addr_tree_app( data[2], data[3], switch_nodes[idx*128:(idx+1)*128] ) else: s, d = map_addr_tree( data[2], data[3], switch_nodes ) #d = 'e1' hash_str = hashStr(data) flow_dict[hash_str] = 1 data_size = float(data[1]) while(data_size > 0): count += 1 per_size = data_size #w_key = str(flow_cap) + ',' + test_hop + ',' + topo_type #if w_key not in byte_dict_from_file: #byte_dict_from_file[w_key] = 0 min_len = send_packet( hash_str, min(data_size, per_size), s, d, count_dict, count_dict1, mark_dict, threshold, mark_group, seeds, polys, min_len, flow_paths, cflow_dict, app_link_dict, app_link_flow_dict, switch_nodes, table, select_dict, drop_id=drop_id, r_threshold=r_threshold, black_hole=black_hole, test_hop=test_hop, add_byte_dict=add_byte_dict, w_key=byte_dict_from_file ) data_size -= per_size else: print( ' -- time', (float(data[0]) - start_time0), 'pkt count:', count, 'Flow num:', len(flow_dict) ) break return min_len def write_list_file(data): """ Write to file """ with open(("../outputs/tmp"), 'a') as f: for row in data: f.write(str(row) + '\n') def subFlows(flow_paths, test_node): sub_flows = [] for flow in flow_paths: if test_node in [y for x in flow[0].keys() for y in x]: sub_flows.append(flow) return sub_flows def classification(cherns, chern_byte, d_min, p, s, sub_flows, table, trues, ests, true_byte_dict, est_byte_dict, pairs, epsilon=0.001, metric_type='CHERN'): cherns[s], chern_byte[s], ds, d_min[s], p[s], true_class = mdt.hash_biased( s, sub_flows, table[s], metric_type=metric_type ) if s in [r1, r2]: key = '-'.join(sorted([r1, r2])) if key not in true_byte_dict: true_byte_dict[key] = [cherns[s], chern_byte[s], -1] true_byte_dict[key][0] = min(true_byte_dict[key][0], cherns[s]) true_byte_dict[key][1] = min(true_byte_dict[key][1], chern_byte[s]) if cherns[s] < epsilon: if s not in [r1, r2]: print( ' ++ s not in [r1, r2], d_min', s, [r1, r2], d_min[s] ) eeee key = ''.join(sorted([r1, r2])) if key not in trues: trues[key] = cherns[s] trues[key] = min(trues[key], cherns[s]) pairs.append([r1, r2, cherns[s], d_min[s], p[s]]) return true_class def classification_alg(true_byte_dict, epsilon=0.01, epsilon_pb=0.1): for key in true_byte_dict: if true_byte_dict[key][0] < epsilon: true_byte_dict[key][2] = 1 if (true_byte_dict[key][0] >= epsilon and true_byte_dict[key][1] < epsilon_pb ): true_byte_dict[key][2] = 0 def single(r1, r2, pairs, est_pairs, switch_nodes, trues, ests, true_byte_dict, est_byte_dict, table, test_nodes, flow_cap=1000, is_correlated=True, topo_type='B4', task_type="CLASSIFICATION", key='', class_dict=OrderedDict({}), imr_threshold=0.1, epsilon=0.001, drop_id=0, r_threshold=0.0, black_hole='sh41', links=[], metric_type='CHERN', exc_time=0.0, app_exc_time=0.0, flow_paths={}): print '**** correlation pair', r1, r2 true_class = -1 if is_correlated: poly = set_correlation(r1, r2, polys) true_class = 1 # Get the paths with at least two packets """ flow_paths = ([(f[0].keys(), f[1]) for f in flow_paths for key in f[0] if f[0][key] > 1]) print(flow_paths) eeeee """ cherns, chern_byte = OrderedDict({}), OrderedDict({}) d_min = OrderedDict({}) p = OrderedDict({}) if task_type != 'APPLICATION': for s in test_nodes: print ' **** testing node', s start_time = time.time() flow_path_list = ([(flow_paths[key], key[1], flow_paths[key].values()[-1]) for key in flow_paths] ) #print '**** Len(flow_paths)', len(flow_paths) #print flow_paths[0] sub_flows = subFlows(flow_path_list, s) if task_type == "CLASSIFICATION": byte_true_class = classification(cherns, chern_byte, d_min, p, s, sub_flows, table, trues, ests, true_byte_dict, est_byte_dict, pairs, epsilon, metric_type=metric_type) if true_class == -1: true_class = byte_true_class # Correlation ranking if task_type == "RANKING": ranking = locate_corr(s, sub_flows, table, epsilon) #print ' -- ranking', ranking if len(ranking) != 0: if (ranking[0][0] == r1 or ranking[0][0] == r2 or (topo_type == 'JUPITER' and(('al' in s and 'ah' in ranking[0][0]) or ('ah' in s and 'al' in ranking[0][0]) ) ) ): key = '-'.join(sorted([r1, r2])) if key not in ests: ests[key] = ranking if ranking[0][1] < ests[key][0][1]: ests[key] = ranking est_pairs.append((r1, r2)) exc_time += time.time() - start_time if is_correlated: reset_correlation(r2, polys, poly) return trues, ests, est_pairs, true_class, exc_time, app_exc_time def locate_corr(s, flow_paths, table, threshould=0.01, metric_type='CHERN'): cherns = mdt.corr_group( s, flow_paths, table, threshould, metric_type=metric_type) return cherns def testPairs(G, aggr_nodes, prefix1='2_0', prefix2='2_1', table=None): """ Return the pairs that may be correlated with each other """ aggr1 = [x for x in aggr_nodes[1:80:8] if prefix1 in x] aggr2 = [x for x in aggr_nodes[0:80:8] if prefix2 in x] n = len(aggr1) test_pairs = [] for i in range(0, n): for j in range(0, n): if (aggr1[i] in table and aggr2[j] in table and (aggr1[i], aggr2[j]) in G.edges() ): test_pairs.append((aggr1[i], aggr2[j])) return test_pairs def jupiteNetwork(): """ Load jupiter network and build a graph """ # Build a graph for large clos topo tor_cut, aggr_cut, spine_cut = 512, 256, 256 #2048, 4096, 4096 #32*4*2, 64*2, 16*2 switches, edges = tp.jupiter_topo( tor_cut=tor_cut, aggr_cut=aggr_cut, spine_cut=spine_cut ) G = build_graph(edges) external_edges = [] for node in G.nodes(): if 'sh' in node: G.add_edge(node, 'e1') """ paths = list(nx.all_shortest_paths(G, 'tor385', 'tor1')) #print(paths) #eee paths = list(nx.all_shortest_paths(G, 'tor129', 'tor257')) #print(paths) paths = list(nx.all_shortest_paths(G, 'tor257', 'tor385')) #print(paths) #eee """ switch_nodes, hnodes, tors, anodes, snodes = tp.getJupiternNodes( tors_num=tor_cut, aggr_num=aggr_cut, spine_num=spine_cut ) print('**** is_connected(G)', nx.is_connected(G)) print('**** number of components', nx.number_connected_components(G)) tors = tors[0:512] + ['e1'] # Get the routing path of all nodes table_file_name = '../outputs/jupiter_routing_table_anodes_cut4.txt' if((os.path.isfile(table_file_name)) == False): table = all_routing(G, tors, table_file_name) else: json_data = open(table_file_name).read() table = json.loads(json_data) seeds, polys = cf.get_seeds_table_jupiter(switch_nodes + ['e1']) # return G, tors, edges, table, seeds, polys, anodes def smallClosNetwork(): """ Load small clos network and build a graph based on it """ # Build a graph for Jupiter topo switch_nodes, edges = tp.tree_topo() G = build_graph(edges) nodes, host_nodes, tors, anodes, snodes = tp.getnodes() print('**** is_connected(G)', nx.is_connected(G)) # Get the routing path of all nodes table_file_name = '../outputs/tree_routing_table.txt' if((os.path.isfile(table_file_name)) == False): table = all_routing(G, tors+['e1'], table_file_name) else: json_data = open(table_file_name).read() table = json.loads(json_data) print('**** Got routing table!') seeds, polys = cf.get_seeds_table_tree(switch_nodes) # return G, tors, edges, table, seeds, polys def b4Wan(): """ Load a B4 Wan network and build a graph based on it """ tors, edges = tp.mesh_topo() G = build_graph(edges) # Get the routing path of all nodes table_file_name = '../outputs/mesh_routing_table.txt' table = all_routing(G, tors, table_file_name) if((os.path.isfile(table_file_name)) == False): table = all_routing(G, tors, table_file_name) else: json_data = open(table_file_name).read() table = json.loads(json_data) seeds, polys = cf.get_seeds_table(tors) # return G, tors, edges, table, seeds, polys if __name__ == "__main__": # Inputs as argv # Topo type: B4, TREE, JUPITER if len(sys.argv) >= 2: topo_type = sys.argv[1] else: topo_type = 'B4' # Variables if len(sys.argv) >= 3: flow_cap = int(sys.argv[2]) else: flow_cap = 1000 # Correlation or not: 1 and 0 if len(sys.argv) >= 4: is_correlated = bool(int(sys.argv[3])) else: is_correlated = True # trace_type: A, B, C... if len(sys.argv) >= 5: trace_type = (sys.argv[4]) else: trace_type = '' # Task type: CLASSIFICATION, RANKING, APPLICATION if len(sys.argv) >= 6: task_type = (sys.argv[5]) else: task_type = 'CLASSIFICATION' # X variable tyepe if len(sys.argv) >= 7: x_var = (sys.argv[6]) else: x_var = 'FLOWNUM' # P-value threshold if len(sys.argv) >= 8: epsilon = float(sys.argv[7]) else: epsilon = 0.01 # r_threshold if len(sys.argv) >= 9: r_threshold = float(sys.argv[8]) else: r_threshold = 0.0 # drop_id if len(sys.argv) >= 10: drop_id = int(sys.argv[9]) else: drop_id = 0 if len(sys.argv) >= 11: imr_threshold = float(sys.argv[10]) else: imr_threshold = 0.1 # Get network topo if topo_type == 'JUPITER': G, tors, edges, table, seeds, polys, anodes = jupiteNetwork() if topo_type == 'B4': G, tors, edges, table, seeds, polys = b4Wan() if topo_type == 'TREE': G, tors, edges, table, seeds, polys = smallClosNetwork() if trace_type == 'A': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_600s_clusterA_asort') elif trace_type == 'B': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_150s_web_sort_host') elif trace_type == 'C': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_600s_clusterC_asort') elif trace_type == 'e1': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_web_sort_host_elephant_1flows') elif trace_type == 'e5': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_web_sort_host_elephant_5flows') elif trace_type == 'e10': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_web_sort_host_elephant_10flows') elif trace_type == 'e50': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_web_sort_host_elephant_50flows') elif trace_type == 'e100': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_web_sort_host_elephant_100flows') elif trace_type == 'ABC': file_name = ("/home/yunhong/Research_4/distributions/outputs/" + 'split_flows_10s_clusterABC_asort') if topo_type == 'B4': test_pairs = ([('s3', 's4'), ('s4', 's3'), ('s3', 's6'), ('s6', 's3'), ('s4', 's5'), ('s5', 's4'), ('s5', 's6'), ('s6', 's5')] ) if task_type == 'APPLICATION': test_pairs = [('s4', 's3')] if topo_type == 'TREE': test_pairs = ([('2_0_0_0', '2_1_0_0'), ('2_0_0_1', '2_1_0_1'), ('2_0_0_2', '2_1_0_2'), ('2_0_0_3', '2_1_0_3'), ('2_0_1_0', '2_1_1_0'), ('2_0_1_1', '2_1_1_1'), ('2_0_1_2', '2_1_1_2'), ('2_0_1_3', '2_1_1_3')]) if task_type == 'APPLICATION': test_pairs = [('2_0_0_0', '2_1_0_0')] #test_pairs = [('2_0_0_0', '2_1_0_0'), ('2_0_0_0', '3_0_0_0')] """test_pairs = testPairs( G, anodes[0:80], prefix1='ah', prefix2='al', table=table )""" if topo_type == 'JUPITER': test_pairs = [] for i in range(1, 1+32*8, 32): # 1, 65, 129, 193 if i != 129: test_pairs.append(('al'+str(i), 'ah'+str(i))) test_pairs.append(('al'+str(i), 'ah'+str(i+1))) #test_pairs.append(('ah'+str(i), 'sl'+str(i))) #test_pairs = [('al1', 'sl81')] if task_type == 'APPLICATION': links = list(nx.all_shortest_paths(G, 'tor1', 'e1')) test_pairs = sorted( list(set([(x[2], x[3]) for x in links])), key=lambda x:x[0])[0:16] pairs, est_pairs = [], [] trues, ests = OrderedDict({}), OrderedDict({}) true_byte_dict, est_byte_dict, true_class_dict = OrderedDict({}), OrderedDict({}), OrderedDict({}) class_dict = OrderedDict({}) exc_time, app_exc_time = 0.0, 0.0 min_len = 1**10 test_hops = [x for y in test_pairs for x in y] flow_paths = OrderedDict({}) if is_correlated: for (r1, r2) in test_pairs: poly = set_correlation(r1, r2, polys) true_class = 1 min_len = flow_routing( file_name, seeds, polys, min_len, flow_paths, tors, table, flow_cap, topo_type, key='', class_dict=class_dict, imr_threshold=imr_threshold, task_type=task_type, drop_id=drop_id, r_threshold=r_threshold, black_hole=None, links=[], test_hop=test_hops, exc_time=0 ) for (r1, r2) in test_pairs: if task_type == 'APPLICATION': black_hole = [x for x in G[r2] if 'sh' in x][0] #elif task_type == 'CLASSIFICATION' #black_hole = [x for x in G[r2] if 'sh' in x][0] else: black_hole = None links = sorted( [(r2, x) for x in G[r2] if 'sh' in x], key=lambda x: x[1]) if r1 != r2: key = '-'.join(sorted([r1, r2])) trues, ests, est_pairs, true_class_dict[key], exc_time, app_exc_time = single( r1, r2, pairs, est_pairs, tors, trues, ests, true_byte_dict, est_byte_dict, table, [r1, r2], flow_cap, is_correlated, topo_type, task_type=task_type, key=key, class_dict=class_dict, imr_threshold=imr_threshold, epsilon=0.005, drop_id=drop_id, r_threshold=r_threshold, black_hole=black_hole, links=links, metric_type=x_var, exc_time=exc_time, app_exc_time=app_exc_time, flow_paths=flow_paths ) print( 'trues, ests, select_len, est_pairs, exc_time, app_exc_time', len(trues), len(ests), min_len, est_pairs, exc_time, app_exc_time ) classification_alg(true_byte_dict, epsilon=0.005, epsilon_pb=epsilon) # Write to fsile select_len = min_len file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=0.01) f1 = open(file_name1, 'a') f2 = open(file_name2, 'a') if task_type == "CLASSIFICATION": for key in true_byte_dict: true_class = is_correlated if drop_id <= 0: true_class = -1 is_correlated = -1 f2.write( str(select_len) + ',' + str(exc_time) + ',' + str(epsilon) + ',' + str(r_threshold) + ',' + str(int(is_correlated)) + ',' + key + ',' + str(true_byte_dict[key][0]) + ',' + str(true_byte_dict[key][1]) + ',' + str(true_byte_dict[key][2]) + ',' + str(int(true_class)) + '\n' #true_class_dict[key] ) f1.write( ','.join([str(x) for x in [select_len, epsilon, r_threshold, int(is_correlated), len([x for x in true_byte_dict.values() if x[2] == 1]), len([x for x in true_byte_dict.values() if x[2] == 0]), len(true_byte_dict)]] ) + '\n' ) if task_type == "RANKING": # Ranking result for key in ests: f2.write( str(select_len) + ',' + str(exc_time) + ',' + str(epsilon) + ',' + str(r_threshold) + ',' + str(int(is_correlated)) + ',' + key + ',' + str(len(ests)) + ',' + str([(x[2]) for x in ests[key]][0]) + ',' + ','.join([str(x[1]) for x in ests[key]]) + ',' + ','.join([str(x[0]) for x in ests[key]]) + '\n' ) f1.write( ','.join([str(x) for x in [select_len, epsilon, r_threshold, int(is_correlated), len(ests)]] ) + '\n' ) if task_type == "APPLICATION": # Ranking result true_num = 0 for key in class_dict: true_class = 0 true_class = 1 if is_correlated else 2 if r_threshold>0 else 0 f2.write( str(select_len) + ',' + str(app_exc_time) + ',' + str(r_threshold) + ',' + str(imr_threshold) + ',' + str(int(is_correlated)) + ',' + str(int(drop_id)) + ',' + key + ',' + str(class_dict[key]) + ',' + str(true_class) + '\n' ) if true_class == class_dict[key]: true_num += 1 f1.write( ','.join([str(x) for x in [select_len, r_threshold, imr_threshold, int(is_correlated), true_num, len(class_dict)]] ) + '\n' ) <file_sep>import numpy as np import bound as bd from co_func import min_bound def common_flows(r1, r2, rm, router_nodes, port_list): rm = np.array(rm, dtype=bool) rm = np.array(rm, dtype=int) r1_pos = router_nodes.index(r1) r2_pos = router_nodes.index(r2) r2_next_hops = port_list[r2].split() next_counts = [] for r2_next_hop in r2_next_hops: next_pos = router_nodes.index(r2_next_hop) m_r1_r2 = np.bitwise_and( rm[:, r1_pos], rm[:, r2_pos]) next_flows = np.bitwise_and( m_r1_r2, rm[:, next_pos]) next_count = sum(next_flows) next_counts.append(next_count) print(r1, r2, next_counts) return next_counts def corr_detection(r1, r2, rm, router_nodes, port_list): # input: # list[str]: n*1 # routing_matrix: # r1, r2: two routers, r1 is the ancester of r2 next_counts = common_flows(r1, r2, rm, router_nodes, port_list) return min_bound(next_counts) def corr_group(r1s, r2, rm, router_nodes, port_list): # input: # list[str]: n*1 # routing_matrix: # r1s, r2: ancesters of r2: r1 and router r2 min_bounds = [] for r1 in r1s: min_bound = corr_detection(r1, r2, rm, router_nodes, port_list) min_bounds.append(min_bound) return min_bounds <file_sep>import os import numpy as np import co_func as cf def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=p) f1 = open(file_name1, 'w') if task_type =='APPLICATION': f1.write(("#flows,iteration,r_threshold,is_correlated,#case_detect\n")) else: if task_type =='CLASSIFICATION': f1.write(("#flows,iteration,epsilon,r_threshold,is_correlated,#correlated_detect,#non-uniform_detect,#all_cases\n")) elif task_type =='RANKING': f1.write(("#flows,iteration,epsilon,r_threshold,is_correlated,#correlated_detect\n")) else: f1.write(("#flows,iteration,r_threshold,imr_threshold,is_correlated,#correlated_detect,#non-uniform_detect,#all_cases\n")) f2 = open(file_name2, 'w') if task_type =='CLASSIFICATION': f2.write('#flows,iteration,time,epsilon,r_threshold,' + 'is_correlated,' + 'key,count_chern,byte_chern,pred,true\n' ) elif task_type =='RANKING': f2.write('#flows,iteration,time,epsilon,r_threshold,' + 'is_correlated,' + 'key,#pres,o_f,count_chern[0]\n' ) elif task_type =='APPLICATION': f2.write('#flows,iteration,time,r_threshold,' + 'is_correlated,' + 'drop_id,key,pred,true\n' ) print(file_name1, '\n', file_name2) f1.close() f2.close() def run_single(topo_type, task_type, trace_type, iter_start=0, iter_end=10, x_var='FLOWNUM'): # B4 if topo_type == "B4": if task_type == 'CLASSIFICATION': flow_nums = np.arange(100, 810, 100)#np.arange(50, 310, 50)#np.arange(50, 410, 25) #np.arange(675, 860, 50)#np.arange(225, 660, 50)#np.arange(50, 210, 25) flow_nums = [500] epsilons = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.4] if task_type == "RANKING": flow_nums = np.arange(10, 110, 10) #flow_nums = [80, 90, 100] epsilons = np.arange(0.01, 0.12, 0.02) if task_type == "APPLICATION": flow_nums = [4500] epsilons = [0.01] # Tree if topo_type == "TREE": if task_type == 'CLASSIFICATION': flow_nums = np.arange(100, 810, 100)#np.arange(50, 310, 50)#np.arange(50, 410, 25)#np.arange(225, 660, 50)#np.arange(50, 210, 25)#np.arange(50, 250, 50) #np.arange(200, 2100, 300) epsilons = [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.4] if task_type == "RANKING": flow_nums = np.arange(10, 110, 10) #np.arange(100, 610, 50) #flow_nums = [80, 90, 100] epsilons = [0.005] if task_type == "APPLICATION": flow_nums = [2100] epsilons = [0.01] # Jupiter if topo_type == "JUPITER": if task_type == 'CLASSIFICATION': flow_nums = np.arange(100, 810, 100) #np.arange(50, 260, 25)#np.arange(5000, 36000, 2500) # 5000, 30000 epsilons = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.4] #np.arange(0.01, 0.22, 0.04) if task_type == "RANKING": flow_nums = np.arange(10, 110, 10) #np.arange(400, 1700, 200) epsilons = [0.005] #np.arange(0.01, 0.22, 0.04) if task_type == "APPLICATION": flow_nums = [2000] epsilons = [0.01] if x_var == 'BIAS' or 'RTHRESHOLD' in x_var: r_thresholds = [0.05, 0.1, 0.2, 0.3, 0.4] r_thresholds = [0.002, 0.004, 0.006, 0.008, 0.01, 0.012] if topo_type == 'JUPITER': r_thresholds = [x/5.0 for x in r_thresholds] imr_thresholds = [0.1] else: r_thresholds = [0.3] imr_thresholds = [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] drop_ids = [0] if 'FLOWNUM' in x_var or 'PVALUE' in x_var: r_thresholds = [0.01] imr_thresholds = [0.1] if 'PVALUE' in x_var or 'RTHRESHOLD' in x_var: flow_nums = [100] #flow_nums[len(flow_nums)-1:] if topo_type == "JUPITER": flow_nums = [800] if 'FLOWNUM' in x_var or 'RTHRESHOLD' in x_var: epsilons = [0.001] if topo_type == 'JUPITER': if 'CHERN' in x_var: epsilons = [0.01] else: epsilons = [0.0001] print '@flow_nums', flow_nums print '@epsilons', epsilons print '@r_thresholds', r_thresholds print '@imr_thresholds', imr_thresholds for iteration in range(iter_start, iter_end): if iteration == 0: init_files(trace_type, task_type, topo_type, x_var=x_var, p=0.01) for flow_num in flow_nums: for epsilon in epsilons: for r_threshold in r_thresholds: for imr_threshold in imr_thresholds: is_correlated, drop_id = 1, 0 #r_threshold = 0.1 drop_id = 0 if task_type == 'RANKING': drop_id = 0 print '\n@CORRELATED ', '@epsilon', '@flownum, @iteration', epsilon, flow_num, iteration command = ('python mesh_topo_ranking.py ' + topo_type + ' ' + str(flow_num) + ' ' + str(is_correlated) + ' ' + trace_type + ' ' + task_type + ' ' + x_var + ' ' + str(epsilon) + ' ' + str(r_threshold) + ' ' + str(drop_id) + ' ' + str(imr_threshold) + ' ' + str(iteration) ) os.system(command) """if task_type == "CLASSIFICATION": print '\n@NOT CORRELATED', '@epsilon, @flownum, @iteration', epsilon, flow_num, iteration is_correlated, drop_id = 0, 0 #r_threshold = 0.1 drop_id = 1 command = ('python mesh_topo_ranking.py ' + topo_type + ' ' + str(flow_num) + ' ' + str(is_correlated) + ' ' + trace_type + ' ' + task_type + ' ' + x_var + ' ' + str(epsilon) + ' ' + str(r_threshold) + ' ' + str(drop_id) + ' ' + str(imr_threshold) + ' ' + str(iteration) ) os.system(command) if task_type == "CLASSIFICATION": print '\n@NOT CORRELATED', '@epsilon, @flownum, @iteration', epsilon, flow_num, iteration is_correlated, drop_id = 0, 0 #r_threshold_1 = 0 drop_id = 0 command = ('python mesh_topo_ranking.py ' + topo_type + ' ' + str(flow_num) + ' ' + str(is_correlated) + ' ' + trace_type + ' ' + task_type + ' ' + x_var + ' ' + str(epsilon) + ' ' + str(r_threshold) + ' ' + str(drop_id) + ' ' + str(imr_threshold) + ' ' + str(iteration) ) os.system(command) if task_type == "APPLICATION": for drop_id in drop_ids: print('NOT CORRELATED') is_correlated = 0 command = ('python mesh_topo_ranking.py ' + topo_type + ' ' + str(flow_num) + ' ' + str(is_correlated) + ' ' + trace_type + ' ' + task_type + ' ' + x_var + ' ' + str(epsilon) + ' ' + str(r_threshold) + ' ' + str(drop_id) + ' ' + str(imr_threshold) + ' ' + str(iteration) ) os.system(command)""" if __name__ == '__main__': task_types = ['CLASSIFICATION', 'RANKING', 'APPLICATION'] trace_types = ['A', 'B', 'C', 'e1', 'e5', 'e10', 'e50', 'e100', 'ABC'] topo_types = ['B4', 'TREE', 'JUPITER'] x_vars = ['TTESTFLOWNUM', 'TTESTPVALUE', 'TTESTPVALUEBYTE', 'TTESTRTHRESHOLD', 'TTESTRANKINGPVALUEFLOWNUM', 'BIAS', 'IMR'] x_vars1 = ['CHERNFLOWNUM','CHERNPVALUE', 'CHERNPVALUEBYTE', 'CHERNRTHRESHOLD', 'CHERNRANKINGPVALUEFLOWNUM'] iter_start, iter_end = 0, 10 topo_type = topo_types[1] x_var = 'TTESTRANKINGPVALUEFLOWNUM'#x_vars[0] #check x_var caution init_file for task_type in task_types[1:2]: for trace_type in trace_types[0:1]: run_single(topo_type, task_type, trace_type, iter_start=iter_start, iter_end=iter_end, x_var=x_var) <file_sep>import binascii import zlib import netaddr import socket, sys import numpy as np import crcmod import pandas as pd import os import md5 import math import random import matplotlib.pyplot as plt from itertools import chain import bound from crc8 import crc8 from crc32 import crc32 import connection as con import topo import sketch as sk from path_matrix import path_matrix import detection as dt def get_seeds_table(): """ Assign seed and polinmial to node. """ nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = topo.getnodes() poly_list = ( [0x31, 0x2f, 0x39, 0xd5, 0x4d, 0x8d, 0x9b, 0x7a, 0x07, 0x49, 0x1d] ) seeds = {} polys = {} i = 0 router_nodes = tor_nodes + aggr_nodes + spine_nodes for node in router_nodes: if(node != '3_1_0_0' and node != '3_1_0_1'and node != '3_1_1_0' and node != '3_1_1_1'): seeds[node] = i*7 layer = int(node[0]) + int(node[2]) - 1 if(node[0] == '3'): layer = int(node[0]) + int(node[2]) polys[node] = poly_list[layer] i += 1 count = len(poly_list) - 1 polys['2_0_0_0'] = poly_list[count] count -= 1 polys['2_1_0_0'] = poly_list[count] count -= 1 polys['3_0_0_0'] = polys['2_0_0_0'] return seeds, polys def routing(file_name, seeds, polys, port_list, link_loads, node_loads, paths): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = topo.getnodes() count = 0; start_time = 0; is_update = True with open((file_name), 'r') as f: for line in f: count += 1 if(count < 10000000): data = line.split() # Update start time if(is_update): start_time = float((data[0])) is_update = False # Monitor every second if (float(data[0]) - start_time) > 1: is_update = True print('Greater than 1.') break hash_str = (data[2] + '\t' + data[3] + '\t' + data[4] + '\t' + data[5] + '\t' + data[6] ) ev = crc32(hash_str) size = int(float(data[1])) port = int(data[7]) next_hop = host_nodes[port] con.host_up( next_hop, ev, hash_str, size, seeds, polys, port_list, link_loads, node_loads, paths ) else: break def link_load_init(port_list): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = topo.getnodes() link_byte_cnt = {} for node in nodes: next_hops = port_list[node].split() for next_hop in next_hops: link_byte_cnt[node + ' '+next_hop] = 0 return link_byte_cnt def node_load_init(): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = topo.getnodes() byte_cnt = {} for node in nodes: byte_cnt[node] = 0 return byte_cnt if __name__ == '__main__': if(len(sys.argv) == 1): sys.argv.append('1') is_byte = bool(int(sys.argv[1])) nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = topo.getnodes() port_list = topo.get_nexthos_up() seeds, polys = get_seeds_table() link_loads = link_load_init(port_list) node_loads = node_load_init() file_name = ("/home/yunhong/Research_4/distributions/outputs/" + "split_flows_1s_web_sort_host_alpha_1.25" ) flow_packs = {} paths = {} routing(file_name, seeds, polys, port_list, node_loads, link_loads, paths) router_nodes = tor_nodes + aggr_nodes + spine_nodes rm = path_matrix(paths, router_nodes) r1s = ['2_0_0_0', '2_0_0_1', '2_0_1_0', '2_0_1_1', '2_1_0_0', '2_1_1_0'] r1 = '2_0_0_0' r1 = '2_1_0_0' r2 = '3_0_0_0' min_bounds = dt.corr_group(r1s, r2, rm, router_nodes, port_list) print('min_bounds', min_bounds) print(node_loads) <file_sep>import matplotlib.pyplot as plt import pandas as pd flow_num = [5000*i for i in range(1, 6)] df = pd.read_csv('../outputs/chern_values.csv', names=['a'+str(i) for i in range(5)]) print df.iloc[0:5] # Plot fig = plt.figure(figsize=(4.3307, 3.346)) ax = plt.subplot(111) types = ['o-', '^-', '*-', '<-', '>-', '+-'] colors = ['b', 'r', 'g', 'm', 'c', 'k'] for i in range(6): plt.plot(flow_num, df['a4'].iloc[i*5:(i+1)*5], types[i], color=colors[i]) #plt.plot(flow_num, mark_first_web_acc, '^-', color='red') #plt.plot(flow_num, mark_first_hadoop_acc, '*-', color='green') plt.ylabel('Chernoff value (C_b)') plt.xlabel('The number of flows') plt.grid(True) box = ax.get_position() ax.set_position([box.x0+0.02, box.y0+0.15, box.width * 0.75, box.height*0.75]) plt.xticks(flow_num) # Put a legend to the right of the current axis acc_legend = ['Web', '100', '500', '1000', '5%', '10%'] ax.legend(acc_legend, loc='center left', bbox_to_anchor=(0.96, 0.3), numpoints=1) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.savefig( '/home/yunhong/Research_4/trunk/figures/chern_values' + '.png', dpi = 300) plt.show() <file_sep>import numpy as np import bound as bd import co_func as cf from co_func import min_bound from t_test import t_test, t_test_byte def common_flows_with_next(r2, r2_next_hops, d, flow_paths, routing_table ): next_counts = {} next_bytes = {} for nhop in r2_next_hops: next_counts[nhop] = 0 next_bytes[nhop] = [] x = {} for f_path in flow_paths: dst = f_path[1] if dst in d: for edge in f_path[0]: if edge[0] == r2: if edge[1] in r2_next_hops: next_counts[edge[1]] += 1 next_bytes[edge[1]].append(f_path[2]) if (dst, edge[1]) not in x: x[(dst, edge[1])] = 0 x[(dst, edge[1])] += 1 #print 'next_counts', next_counts return next_counts.values(), next_bytes.values(), x def getIndex(qlist, value): idx = -1 try: idx = qlist.index(value, idx + 1) except ValueError: return idx return idx def common_flows_with_pre(prehop, r2, r2_next_hops, d, d_pre, flow_paths, routing_table ): next_counts = {} next_bytes = {} for nhop in r2_next_hops: next_counts[nhop] = 0 next_bytes[nhop] = [] # r2 is the previous hop of next hops for f_path in flow_paths: dst = f_path[1] ps = cf.makelist(f_path[0]) idx_pre = getIndex(ps, prehop) idx_cur = getIndex(ps, r2) if (idx_pre >= 0 and idx_cur >= 0 and idx_cur > idx_pre and dst in d and dst in d_pre ): for nhop in r2_next_hops: if (r2, nhop) in f_path[0]: next_counts[nhop] += 1 next_bytes[nhop].append(f_path[2]) break #print(' ^^ common_flows_with_pre:next_counts', next_counts) return next_counts.values(), next_bytes.values() def dest_group_by_nhops(routing_table): # ds with the same next hops # [[d1, d2], [], [], []] # key is the next hops, value is the dest ds = {} dests = routing_table.keys() d_n = len(dests) visited = [False for i in range(d_n)] for i, d in enumerate(dests): if len(routing_table[d]) > 1 and visited[i] == False: nhops = sorted(routing_table[d]) tmp = [d] for j in range(i+1, d_n): d_j = dests[j] if sorted(routing_table[d_j]) == nhops: visited[j] = True tmp.append(d_j) ds['\t'.join(nhops)] = tmp return ds def hash_biased(r1, flow_paths, routing_table_r1, threshould=0.01, metric_type='CHERN' ): """ routing_table is the table of r1 """ ds = dest_group_by_nhops(routing_table_r1) min_chern = 2.0 min_chern_byte = 2.0 d_min = None p_min, p_byte_min = 2.0, 2.0 true_class = -1 if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') next_counts, next_bytes, x = common_flows_with_next( r1, nhops, ds[key], flow_paths, routing_table_r1 ) chern_bound = 0 if max(next_counts) > 5: chern_bound = min_bound(next_counts) if min_chern > chern_bound: d_min = (key, ds[key], x) min_chern = min(min_chern, chern_bound) next_bytes_sorted = next_bytes sum_next_bytes = map(sum, next_bytes_sorted) chern_byte = min_bound(next_bytes, flow_indicator=0) min_chern_byte = min(min_chern_byte, chern_byte) t, p = t_test(next_counts, 0.5) t_byte, p_byte = t_test_byte(next_bytes, 0.5) p_byte_min = min(p_byte_min, p_byte) if max([y for x in next_bytes_sorted for y in x[-3:]])/sum(sum_next_bytes) > 0.1: true_class = 0 if p_min > p: # and max(next_counts) > 50: p_min = p d_min = (key, ds[key], x, next_counts) if 'TTEST' in metric_type: min_chern = p_min min_chern_byte = p_byte_min elif 'CHERNTT' in metric_type: min_chern_byte = p_byte_min elif 'TTCHERN' in metric_type: min_chern = p_min return min_chern, min_chern_byte, [r1, ds], d_min, p_min, true_class def corr_detection(r1_pre, r1, flow_paths, routing_table_pre, routing_table_r1, metric_type='CHERN' ): d_pres = dest_group_by_nhops(routing_table_pre) d_pre_list = [x for d_pre in d_pres.values() for x in d_pre] ds = dest_group_by_nhops(routing_table_r1) min_chern = 2.0 min_chern_byte = 2.0 p_min = 2.0 o_f = 0.5 if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') if len(set(d_pre_list).intersection(ds[key])) == 0: continue next_counts, next_bytes = common_flows_with_pre( r1_pre, r1, nhops, d_pre_list, ds[key], flow_paths, routing_table_r1 ) if sum(next_counts) > 10: t, p = t_test(next_counts, 0.5) chern_bound = 0 if sum(next_counts) > 10: # and max(next_counts) > 50: chern_bound = min_bound(next_counts) if min_chern > chern_bound: o_f = min(next_counts)/sum(next_counts) min_chern = min(min_chern, chern_bound) p_min = min(p_min, p) chern_byte = min_bound(next_bytes, flow_indicator=0) min_chern_byte = min(min_chern_byte, chern_byte) if 'TTEST' in metric_type: min_chern = p_min print 'TTEST HERE' elif 'CHERNTT' in metric_type: min_chern_byte = p_byte_min """print( ' ^^min_chern, p, min_chern_byte', min_chern, p_min, min_chern_byte )""" return min_chern, p_min, o_f def corr_group(r2, flow_paths, routing_table, threshould=0.01, metric_type='CHERN'): """ input: list[str]: n*1 routing_matrix: r1s, r2: ancesters of r2: r1 and router r2 """ r1s = pre_hop_group(r2, flow_paths, routing_table[r2]) min_bounds = [] for r1 in r1s: min_bound, p, o_f = corr_detection( r1, r2, flow_paths, routing_table[r1], routing_table[r2], metric_type=metric_type ) #if p != 0: #min_bound = min(min_bound, p) #if min_bound < threshould: min_bounds.append((r1, min_bound, o_f)) min_bounds = sorted(min_bounds, key=lambda x: x[1]) return min_bounds def pre_hop_group(r1, flow_paths, routing_table_r1): ds = dest_group_by_nhops(routing_table_r1) all_pres = [] if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') pres = pre_hops( r1, nhops, ds[key], flow_paths ) all_pres.append(pres) all_pres = list(set([x for pre in all_pres for x in pre])) return all_pres def pre_hops(r2, r2_next_hops, d, flow_paths): """ The pre hops of r1 based on the splitting, (2, 1) (4, 3) (5, 6) (3, 5) (1, 4) (2, 1) (1, 4) (4, 3) (3, 5) (5, 6) """ # r2 is the previous hop of next hops pres = [] for f_path in flow_paths: dst = f_path[1] if dst in d: ps = cf.makelist(f_path[0]) nodes = [] if r2 in ps: for p in ps: if r2 == p: break if 'h' not in p: nodes.append(p) pres += nodes return list(set(pres)) def other_hops(r2, flow_paths): """ Other hops in the path """ # r2 is the previous hop of next hops out_nodes = [] for f_path in flow_paths: nodes = list(set([x for y in f_path[0] for x in y if 'h' not in x])) print('f_path', f_path) if r2 in nodes: nodes.remove(r2) for node in nodes: if (r2, node) in f_path[0]: nodes.remove(node) out_nodes += nodes #print(' ^^ other_hops:nodes', list(set(out_nodes))) return list(set(out_nodes)) <file_sep> def getnodes(): nodes = [] # Host name host_nodes = [] for i in xrange(0,8): for j in xrange(0,2): name = str(0)+'_'+str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) host_nodes.append(name) # ToR name tor_nodes = [] for i in xrange(0,8): for j in xrange(0,2): name = str(1)+'_'+str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) tor_nodes.append(name) # Aggr name aggr_nodes = [] for i in xrange(0,4): for j in xrange(0,2): for k in xrange(0,2): name = str(2)+'_' +str(k)+'_' + str(j)+'_' +str(i) nodes.append(name) aggr_nodes.append(name) # Spine name spine_nodes = [] for i in xrange(0,4): for j in xrange(0,2): name = str(3)+'_' +str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) spine_nodes.append(name) for i in xrange(0,2): for j in xrange(0,2): name = str(3)+'_' +str(1)+'_' + str(j)+'_' +str(i) nodes.append(name) spine_nodes.append(name) return nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes def get_nexthos_up(): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes= getnodes() port_list = {} # Host for node in host_nodes: node_split = node.split('_') for j in xrange(0,1): next_hop = (str(1) + '_' + node_split[1] + '_' + node_split[2] + '_' +node_split[3]) if j == 0: next_hop_str = next_hop else: next_hop_str += ' '+next_hop port_list[node] = next_hop_str # Tor for node in tor_nodes: node_split = node.split('_') for j in xrange(0,4): next_hop = (str(2) + '_' + node_split[1] + '_' + node_split[2] + '_' +str(j)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' '+next_hop port_list[node] = next_hop_str # Aggr for node in aggr_nodes: node_split = node.split('_') if(node_split[1] == '0'): for j in xrange(0,2): next_hop = (str(2) + '_' + str(1) + '_' + node_split[2] + '_' + str(j+int(node_split[3])/2*2)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop if(node_split[1] == '1'): for j in xrange(0,2): next_hop = (str(3) + '_' + str(0) + '_' + str(int(node_split[3])%2) + '_' + str(j+int(node_split[3])/2*2)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop port_list[node] = next_hop_str # Spine for node in spine_nodes: node_split = node.split('_') if(node_split[1] == '0'): for j in xrange(0,2): next_hop = (str(3) + '_' + str(1) + '_' + node_split[2] + '_' + str(j)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop port_list[node] = next_hop_str return port_list def tree_topo(): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = getnodes() next_hop_up = get_nexthos_up() switch_nodes = [x for x in nodes if x not in host_nodes] + ['e1'] edges = [] for key in next_hop_up.keys(): if key not in host_nodes: nhops = next_hop_up[key].split() for nhop in nhops: edges.append((key, nhop)) print(len(edges)) external_edges = ([('3_1_0_0', 'e1'), ('3_1_0_1', 'e1'), ('3_1_1_0', 'e1'), ('3_1_1_1', 'e1')] ) edges += external_edges return switch_nodes, edges <file_sep>from random import randint from collections import Counter import numpy as np import pandas as pd import independent_set as iset import application as appl import os import numpy as np import co_func as cf def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=p) f1 = open(file_name1, 'w') if task_type =='APPLICATION': f1.write(("#flows,iteration,r_threshold,imr_threshold,p_t,topk,is_correlated,#case_detect,len(class_dict)\n")) else: if task_type =='CLASSIFICATION': f1.write(("#flows,iteration,epsilon,r_threshold,is_correlated,#correlated_detect,#non-uniform_detect,#all_cases\n")) elif task_type =='RANKING': f1.write(("#flows,iteration,epsilon,r_threshold,is_correlated,#correlated_detect\n")) else: f1.write(("#flows,iteration,r_threshold,imr_threshold,is_correlated,#correlated_detect,#non-uniform_detect,#all_cases\n")) f2 = open(file_name2, 'w') if task_type =='CLASSIFICATION': f2.write('#flows,iteration,time,epsilon,r_threshold,' + 'is_correlated,' + 'key,count_chern,byte_chern,pred,true\n' ) elif task_type =='RANKING': f2.write('#flows,iteration,time,epsilon,r_threshold,' + 'is_correlated,' + 'key,#pres,o_f,count_chern[0]\n' ) elif task_type =='APPLICATION': f2.write('#flows,iteration,time,r_threshold,imr_threshold,p_t,topk,' + 'is_correlated,' + 'drop_id,key,pred,true,imr0,imr1,imr2\n' ) print(file_name1, '\n', file_name2) f1.close() f2.close() def app_classification(app_flows1, app_flows2, app_flows3, x_var='', key='', iteration=0, is_correlated=0, imr_threshold=0.1, select_len=1, app_exc_time=0, r_threshold=0.1, x_type=1, p_t=0.01, topk=1): app1 = sorted(Counter([randint(0,8) for p in range(0,app_flows1)]).values()) app2 = sorted(Counter([randint(0,8) for p in range(0,app_flows2)]).values()) app3 = sorted(Counter([randint(0,8) for p in range(0,app_flows3)]).values()) #print 'r_threshold', r_threshold drop_id = 3 if is_correlated == 0 and x_type == 2: drop_link_id = randint(0, 8) app_x = app3 app_x[drop_link_id] = int(app_x[drop_link_id]*(1-r_threshold)) app_x = sorted(app_x) app3 = app_x elif is_correlated == 1 and x_type == 1: for i in range(4): app1[i], app2[i], app3[i] = 0.1, 0.1, 0.1 topk = topk app_top1 = app1[0:topk] + app1[-topk:] app_top2 = app2[0:topk] + app2[-topk:] app_top3 = app3[0:topk] + app3[-topk:] app_link_table = [] app_link_table.append(app_top1) app_link_table.append(app_top2) app_link_table.append(app_top3) app_link_table = np.transpose(np.array(app_link_table)) top_apps = [1,2,3] app_df = pd.DataFrame( app_link_table, columns=['a' + str(x) for x in top_apps]) app_imrs = iset.independentCluster(app_df, p_t) class_dict = {} appl.appClassification( len(app_imrs), app_imrs[0][2], key=key, imr_threshold=0.1, class_dict=class_dict) imrs = [x[2] for x in app_imrs] file_name1, file_name2 = cf.init_files(trace_type='ABC', task_type='APPLICATION', topo_type='JUPITER', x_var=x_var, p=0.01) f1 = open(file_name1, 'a') f2 = open(file_name2, 'a') if task_type == "APPLICATION": # Ranking result true_num = 0 for key in class_dict: true_class = 0 true_class = x_type f2.write( str(select_len) + ',' + str(iteration) + ',' + str(app_exc_time) + ',' + str(r_threshold) + ',' + str(imr_threshold) + ',' + str(p_t) + ',' + str(topk) + ',' + str(int(is_correlated)) + ',' + str(int(drop_id)) + ',' + key + ',' + str(class_dict[key]) + ',' + str(true_class) + ',' + ','.join([str(x) for x in imrs]) + '\n' ) if true_class == class_dict[key]: true_num += 1 f1.write( ','.join([str(x) for x in [select_len, iteration, r_threshold, imr_threshold, p_t, topk, int(is_correlated), true_num, len(class_dict)]] ) + '\n' ) app_flows10 = sum([1054, 1073, 1074, 1081, 1109, 1111, 1117, 1139]) app_flows20 = sum([97, 109, 124, 131, 136, 138, 144, 155]) - 34 app_flows30 = sum([255, 257, 269, 270, 274, 279, 280, 287]) iter_start, iter_end = 10, 20 x_vars = ['CHERNFLOWNUM', 'CHERNRTHRESHOLD', 'CHERNPAVLUE', 'TOPKONE', 'TOPKONEFIVE', 'TOPKTWO'] trace_type, task_type, topo_type, x_var = 'ABC', 'APPLICATION', 'JUPITER', 'TOPKTWO' imr_threshold = 0.1 if x_var == 'CHERNFLOWNUM': flow_nums =np.arange(0.5, 4.5, 0.5) r_thresholds = [0.2] topks = [2] p_ts = [0.1] if x_var == 'CHERNRTHRESHOLD': flow_nums = [4] r_thresholds = np.arange(0.125, 0.32, 0.025) topks = [2] p_ts = [0.1] if x_var == 'CHERNPAVLUE': flow_nums = [4] r_thresholds = [0.2] topks = [2] p_ts = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.4] if 'TOPK' in x_var: flow_nums = [4] r_thresholds = [0.2] topks = [1,2,3,4] p_ts = [0.1] if x_var == 'TOPKONE': r_thresholds = [0.1] if x_var == 'TOPKONEFIVE': r_thresholds = [0.15] print 'flow_nums, r_thresholds,topks, p_ts', flow_nums, r_thresholds,topks, p_ts for iteration in range(iter_start, iter_end): print 'iteration', iteration if iteration == 0: init_files(trace_type, task_type, topo_type, x_var=x_var, p=0.01) for r_threshold in r_thresholds: for p_t in p_ts: for topk in topks: #[1,2,3,4]: [4]:# for flow_multi in flow_nums:#np.arange(0.5, 4, 0.5): app_flows1 = int(app_flows10*flow_multi) app_flows2 = int(app_flows20*flow_multi) app_flows3 = int(app_flows30*flow_multi) print app_flows2 select_len = app_flows2 for key in np.arange(0, 16): print 'key', key app_classification(app_flows1, app_flows2, app_flows3, x_var=x_var, key=str(key), iteration=iteration, is_correlated=0, imr_threshold=imr_threshold, select_len=select_len, r_threshold=r_threshold, x_type=2, p_t=p_t, topk=topk) app_classification(app_flows1, app_flows2, app_flows3, x_var=x_var, key=str(key), iteration=iteration, is_correlated=1, imr_threshold=imr_threshold, select_len=select_len, r_threshold=r_threshold, x_type=1, p_t=p_t, topk=topk) app_classification(app_flows1, app_flows2, app_flows3, x_var=x_var, key=str(key), iteration=iteration, is_correlated=0, imr_threshold=imr_threshold, select_len=select_len, r_threshold=r_threshold, x_type=0, p_t=p_t, topk=topk) <file_sep> import numpy as np import pandas as pd import matplotlib.pyplot as plt import plot_lib as pl from collections import OrderedDict from sklearn.metrics import accuracy_score import co_func as cf def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=p) return file_name1, file_name2 def read_csv(file_name, file_type=0, topo_type='CLASSIFICATION', is_epsilon=False): global ACAP if file_type == 0: return pd.read_csv(file_name) else: print('here') names=['#flows', 'is_correlated', 'key'] + ['a' + str(i) for i in range(ACAP)] if is_epsilon: names=['#flows', 'time','epsilon', 'r_threshold', 'is_correlated', 'key'] + ['a' + str(i) for i in range(ACAP)] return pd.read_csv(file_name, skiprows=[0], names=names) def retieveData(infile_name1, group_fields, agg_fields, accuracys, errors, div=False, task_type="CLASSIFICATION", file_type=0, iteration=30, pair_num=4, key_field='epsilon', q_75ss=[], topo_type='', xss=[] ): print infile_name1 df1 = read_csv(infile_name1, file_type) #df1 = df1.replace([2, '2.0', 2.0, '2'], 1) #print df1 #df1['true'] = df1['is_correlated'].replace([0], -1) df1['colFromIndex'] = df1.index df1 = df1.sort(columns=[key_field, 'iteration', 'colFromIndex']) #df1 = df1[df1['is_correlated'] != 1] #df1 = df1[df1['r_threshold'] != 0.00] print df1.groupby([key_field]).count() df1 = df1.reset_index() pvalue_num = df1[key_field].unique().shape[0] group_num = pair_num acc_dict = OrderedDict({}) for i in range(iteration*pvalue_num): s_index = i*group_num*3 e_index = (i+1)*group_num*3 - 1 print 'index', s_index, e_index, len(df1), group_num, iteration*pvalue_num if e_index <= len(df1)+1: if df1[key_field].loc[s_index] != df1[key_field].loc[e_index]: print df1.loc[s_index], df1.loc[e_index] eeee key = df1[key_field].loc[e_index] y_pred = df1['pred'].loc[s_index:e_index+1] #y_pred = y_pred.append(df1_part2['pred'].loc[s_index:e_index]) y_true = df1['true'].loc[s_index:e_index+1] #y_true = y_true.append(df1_part2['true'].loc[s_index:e_index]) acc = accuracy_score(y_true, y_pred) if key not in acc_dict: acc_dict[key] = [] acc_dict[key].append(acc) print len(acc_dict) accuracy = [] error = [] q_25s = [] q_75s = [] for key in acc_dict: df = pd.DataFrame(acc_dict[key], columns=['key']) x= df['key'].mean() #if topo_type == 'B4': #x= df['key'].mean() accuracy.append(x) q_25 = df['key'].quantile(0.25) q_75 = df['key'].quantile(0.75) error.append(np.std(acc_dict[key])) q_25s.append(x-q_25) q_75s.append(q_75-x) accuracys.append(accuracy) errors.append(error) q_75ss.append([q_25s, q_75s]) if topo_type == 'JUPITER': xss.append([x*2 for x in list(df1[key_field].unique())]) else: xss.append(list(df1[key_field].unique())) return df1[key_field].unique(), pvalue_num, acc_dict def accuracyPlot(topo_types, task_types, trace_types, pair_seq=0): accuracys, errors, x = [], [], None cherns, chern_errors, chern_x = [], [], None acc_boxplot_data = [] q_75ss, xss = [], [] for topo_type in topo_types[2:3]: trace_type = 'ABC' task_type = task_types[2] if topo_type == topo_types[0]: pair_num = 4 elif topo_type == topo_types[1]: pair_num = 8 elif topo_type == topo_types[2]: pair_num = 16 infile_name1, infile_name2 = init_files( trace_type, task_type, topo_type, x_var = 'CHERNFLOWNUM' #CHERNPVALUE ) key_field = '#flows' group_fields = [key_field,'is_correlated', 'key'] agg_fields = ['count_chern', 'byte_chern'] chern_x, case_num, acc_dict = retieveData( infile_name2, group_fields, agg_fields, accuracys, errors, div=False, pair_num=pair_num, q_75ss=q_75ss, key_field=key_field, topo_type=topo_type, xss=xss ) acc_boxplot_data.append(acc_dict.values()) acc_legend = ['B4-Chernoff', 'B4-t-test','Tree-Chernoff', 'Tree-t-test', 'Jupiter-Chernoff', 'Jupiter-t-test'] xlabel, ylabel = 'the number of flows', 'Average accuracy' #'Relative elephant flow size''Packet dropping rate' print 'accuracys, chern_x', len(accuracys[0]), len(chern_x) print accuracys, xss pl.plot(accuracys, x=xss, k=2, errors=[], xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('/outputs')[1].split('.csv')[0].replace('.', '_'), xlog=True, ylog=False, acc_legend=[], legend_x=0.0, legend_y=0.3 ) print acc_boxplot_data pl.box_plot([acc_boxplot_data[0]], x=chern_x, k=2, errors=errors, xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('/outputs')[1].split('.csv')[0].replace('.', '_'), xlog=False, ylog=False, acc_legend=[], legend_y=0.85, xticks=[str(i) for i in chern_x]) if __name__ == "__main__": global ACAP ACAP = 50 topo_types = ['B4', 'TREE', 'JUPITER'] task_types = ['CLASSIFICATION', 'RANKING', 'APPLICATION'] trace_types = ['A', 'B', 'C'] pair_seq = 13 accuracyPlot(topo_types, task_types, trace_types, pair_seq=pair_seq) plt.show() <file_sep>class singleNode(object): def __init__(self, val): self.val = val self.pre = None self.next = None def makelist(points): d = {} p = None count = 0 while(count < 2): count += 1 for point in points: if point[0] not in d: snode0 = singleNode(point[0]) d[point[0]] = snode0 else: snode0 = d[point[0]] if point[1] not in d: snode1 = singleNode(point[1]) d[point[1]] = snode1 else: snode1 = d[point[1]] snode0.next = snode1 snode1.pre = snode0 print('point[0]', point[0], snode0.pre) print('len(d)', len(d)) print('d', d) p = snode0 while(p.pre != None): p = p.pre nodes = [] while(p != None): nodes.append(p.val) p = p.next print(nodes) return nodes """ (2, 1) (4, 3) (5, 6) (3, 5) (1, 4) (1, 4) (2, 1) (3, 5) (4, 3) (5, 6) (2, 1) (1, 4) (4, 3) (3, 5) (5, 6) """ points = [(2, 1), (4, 3), (5, 6), (3, 5), (1, 4)] makelist(points) <file_sep>import matplotlib.pyplot as plt import numpy as np flow_num = [200*i for i in range(2, 7)] mark_first_hadoop = [0, 0, 2, 4, 4] mark_first_cache = [0, 1, 3, 4, 4] mark_first_web = [0,1,1,3,4] mark_first_web_acc = [float(x)/4.0 for x in mark_first_web] mark_first_hadoop_acc = [float(x)/4.0 for x in mark_first_hadoop] mark_first_cache_acc = [float(x)/4.0 for x in mark_first_cache] # Plot fig = plt.figure(figsize=(4.3307, 3.346)) ax = plt.subplot(111) plt.plot(flow_num, mark_first_cache_acc, 'o-', color='blue') plt.plot(flow_num, mark_first_web_acc, '^-', color='red') plt.plot(flow_num, mark_first_hadoop_acc, '*-', color='green') plt.ylabel('Detection accuracy') plt.xlabel('The number of flows') plt.grid(True) box = ax.get_position() ax.set_position([box.x0+0.04, box.y0+0.15, box.width * 0.8, box.height*0.8]) plt.xticks(flow_num) # Put a legend to the right of the current axis acc_legend = ['Database', 'Web', 'Hadoop'] ax.legend(acc_legend, loc='center left', bbox_to_anchor=(0.6, 0.3), numpoints=1) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.savefig( '/home/yunhong/Research_4/trunk/figures/corr_acc' + '.png', dpi = 300) #plt.show() # Plot tree acc flow_num = [100*i for i in range(1, 6)] tree_cases_web = [0, 1, 6, 8, 8] tree_cases_cache = [0, 1, 4, 8, 8] tree_cases_hadoop = [0, 1, 4, 8, 8] mark_first_web_acc = [float(x)/8.0 for x in tree_cases_web] mark_first_cache_acc = [float(x)/8.0 for x in tree_cases_cache] mark_first_hadoop_acc = [float(x)/8.0 for x in tree_cases_hadoop] # Plot fig = plt.figure(figsize=(4.3307, 3.346)) ax = plt.subplot(111) plt.plot(flow_num, mark_first_cache_acc, 'o-', color='blue') plt.plot(flow_num, mark_first_web_acc, '^-', color='red') plt.plot(flow_num, mark_first_hadoop_acc, '*-', color='green') plt.ylabel('Detection accuracy') plt.xlabel('The number of flows') plt.grid(True) box = ax.get_position() ax.set_position([box.x0+0.04, box.y0+0.15, box.width * 0.8, box.height*0.8]) plt.xticks(flow_num) # Put a legend to the right of the current axis acc_legend = ['Database', 'Web', 'Hadoop'] ax.legend(acc_legend, loc='center left', bbox_to_anchor=(0.6, 0.3), numpoints=1) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.savefig( '/home/yunhong/Research_4/trunk/figures/tree_corr_acc' + '.png', dpi = 300) # Plot ranking for tree 20000 ranks = ([[8.56E-196,4.07E-21,1.41E-17,2.70E-16,4.61E-16,4.28E-11,5.70E-10, 7.16E-09, 6.4662618874286124e-07], [2.68E-197,5.68E-17,6.97E-15,1.10E-13,1.17E-10,3.72E-10,2.11E-09,2.42E-09, 0.00014743633533658324], [1.16E-215,1.88E-20,9.47E-19,8.18E-15,1.40E-13,8.32E-12,8.07E-10,1.12E-09, 5.5678461553995376e-09], [1.31E-200,9.25E-16,1.47E-15,2.46E-15,1.34E-12,3.34E-11,2.77E-09,1.48E-08, 7.8877317345062453e-06]] ) fig = plt.figure(figsize=(4.3307, 3.346)) ax = plt.subplot(111) plot_styles = ['o-', '^-', '*-', '+-'] colors = ['b', 'r', 'g', 'm'] k = 0 for rank in ranks: plt.plot(np.arange(len(rank)), rank, plot_styles[k], color=colors[k]) k = k+1 plt.yscale('log') plt.ylabel('p-value') plt.xlabel('Ranking') plt.grid(True) box = ax.get_position() ax.set_position([box.x0+0.06, box.y0+0.15, box.width * 0.8, box.height*0.8]) # Put a legend to the right of the current axis acc_legend = ['corr pair-'+str(i) for i in range(4)] ax.legend(acc_legend, loc='center left', bbox_to_anchor=(0.6, 0.3), numpoints=1) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.savefig( '/home/yunhong/Research_4/trunk/figures/tree_ranking' + '.png', dpi = 300) # Plot ranking for tree 1500 flow ranks = ([[ 3.552713678800501e-15,0.00013625614917754875], [2.2737367544323206e-13,0.0011431050868040661,0.0060710487499900405,0.0091164274466782567], [4.440892098500626e-16,0.00013625614917754875], [1.1102230246251565e-16,0.00040252981812451821,0.0031104283103858535]] ) fig = plt.figure(figsize=(4.3307, 3.346)) ax = plt.subplot(111) plot_styles = ['o-', '^-', '*-', '+-'] colors = ['b', 'r', 'g', 'm'] k = 0 for rank in ranks: plt.plot(np.arange(len(rank)), rank, plot_styles[k], color=colors[k]) k = k+1 plt.yscale('log') plt.ylabel('p-value') plt.xlabel('Ranking') plt.grid(True) box = ax.get_position() ax.set_position([box.x0+0.06, box.y0+0.15, box.width * 0.8, box.height*0.8]) # Put a legend to the right of the current axis acc_legend = ['corr pair-'+str(i) for i in range(4)] ax.legend(acc_legend, loc='center left', bbox_to_anchor=(0.6, 0.3), numpoints=1) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.savefig( '/home/yunhong/Research_4/trunk/figures/tree_ranking_1500flow' + '.png', dpi = 300) plt.show() <file_sep>from array import array poly = 0xEDB88320 defaulttable = array('L') for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ poly else: crc >>= 1 byte >>= 1 defaulttable.append(crc) def crc_table(poly = 0xEDB88320): table = array('L') for byte in range(256): crc = 0 for bit in range(8): if (byte ^ crc) & 1: crc = (crc >> 1) ^ poly else: crc >>= 1 byte >>= 1 table.append(crc) return table def crc32(string, table=defaulttable): value = 0xffffffffL for ch in string: value = table[(ord(ch) ^ value) & 0x000000ffL] ^ (value >> 8) return value^0xffffffffL #%1048576 <file_sep> def path_matrix(paths, nodes): # paths: dict{dict} # nodes: list[str] # Return matrix: len(paths)*len(nodes) matrix = [] for path in paths: tmp = [0] * len(nodes) seq = 1 for p in paths[path]: pos = nodes.index(p) tmp[pos] = seq seq += 1 matrix.append(tmp) return matrix <file_sep> import numpy as np import pandas as pd import matplotlib.pyplot as plt import plot_lib as pl from collections import OrderedDict import co_func as cf from collections import OrderedDict def init_files(trace_type = ' ', task_type='CLASSIFICATION', topo_type='b4', x_var = 'FLOWNUM', p=0.01 ): file_name1, file_name2 = cf.init_files(trace_type=trace_type, task_type=task_type, topo_type=topo_type, x_var=x_var, p=p) return file_name1, file_name2 def read_csv(file_name, file_type=0, topo_type='CLASSIFICATION', is_epsilon=False): global ACAP if file_type == 0: return pd.read_csv(file_name) else: print('here') names=['#flows', 'iteration', 'time', 'epsilon', 'r_threshold', 'is_correlated', 'key', '#pres', 'o_f'] + ['a' + str(i) for i in range(ACAP)] if is_epsilon: names=['#flows', 'iteration', 'time', 'epsilon', 'r_threshold','is_correlated', 'key', '#pres', 'o_f'] + ['a' + str(i) for i in range(ACAP)] return pd.read_csv(file_name, skiprows=[0], names=names) def q1(x): return x.quantile(0.25) def q2(x): return x.quantile(0.75) def ranking_num(row): global ACAP num = 0 for i in range(ACAP): if isinstance(row['a'+str(i)], str) and 'end' in row['a'+str(i)]: num = i/2 break if num == 0: print row print('ranking_num:num==0') eeeee return num def rankingPair(infile_name, cherns, flow_seq, pair_seqs, file_type=0, topo_type='CLASSIFICATION', cut=None, q_25s=[], q_75s=[] ): # d: key: ranking[] df1 = read_csv(infile_name, file_type, topo_type=topo_type) df1 = df1.replace([2, '2.0', 2.0, '2'], 1) df1 = df1.fillna(value='end') d = OrderedDict({}) print df1['key'].unique() print df1 pvalues_d = OrderedDict({}) for flow_num in df1['#flows'].unique(): for key in df1['key'].unique(): if (str(flow_num)+key) not in d: d[str(flow_num)+key] = OrderedDict({}) pvalues_d[str(flow_num)+key] = OrderedDict({}) for index, row in df1.iterrows(): num = ranking_num(row) key = str(row['#flows'])+row['key'] for i in range(num): if row['a'+str(num+i)] not in d[key]: d[key][row['a'+str(num+i)]] = [0, 0] pvalues_d[key][row['a'+str(num+i)]] = [] d[key][row['a'+str(num+i)]][0] += float(row['a'+str(i)]) d[key][row['a'+str(num+i)]][1] += 1 pvalues_d[key][row['a'+str(num+i)]].append(float(row['a'+str(i)])) d1 = OrderedDict({}) pvaluess = OrderedDict({}) for key1 in d: d1[key1] = [] pvaluess[key1] = [] for key2 in d[key1]: d[key1][key2][0] /= d[key1][key2][1] d1[key1].append((d[key1][key2][0], key2)) print pvalues_d[key].keys(), key2 x = np.mean(pvalues_d[key][key2]) q_25 = np.percentile(x-pvalues_d[key][key2], 0.25) q_75 = np.percentile(pvalues_d[key][key2]-x, 0.75) pvaluess[key1].append((x, q_25, q_75)) d1[key1] = sorted(d1[key1], key=lambda tup: tup[0]) for pair_seq in pair_seqs: pair = str(df1['#flows'].unique()[flow_seq])+df1['key'].unique()[pair_seq] if cut == None: cherns.append([x[0]for x in d1[pair]]) x = [x[1] for x in d1[pair]] else: cherns.append([x[0]for x in d1[pair][:cut]]) q_25s.append([x[1] for x in pvaluess[pair][:cut]]) q_75s.append([x[2] for x in pvaluess[pair][:cut]]) x = [x[1] for x in d1[pair][:cut]] return x def rankingPlot(topo_types, task_types, trace_types, pair_seq=0): global ACAP accuracys, errors, x, q_75s, q_25s = [], [], None, [], [] cherns, chern_errors, chern_x = [], [], None for topo_type in topo_types[1:2]: trace_type = trace_types[0] task_type = task_types[1] cut = 4 if topo_type == topo_types[2]: ACAP = 256 cut = 10 infile_name1, infile_name2 = init_files( trace_type, task_type, topo_type, x_var = 'CHERNRANKINGPVALUEFLOWNUM' ) infile_name3, infile_name4 = init_files( trace_type, task_type, topo_type, x_var = 'TTESTRANKINGPVALUEFLOWNUM' ) group_fields = ['#flows','is_correlated', 'key'] agg_fields = ['a'+str(i) for i in range(ACAP)] chern_x = rankingPair( infile_name2, cherns, 0, [0, 1], file_type=1, topo_type=topo_type, cut=cut, q_25s=q_25s, q_75s=q_75s ) chern_x = rankingPair( infile_name4, cherns, 0, [0, 1], file_type=1, topo_type=topo_type, cut=cut, q_25s=q_25s, q_75s=q_75s ) xlabel, ylabel = 'Rank', 'Average p-value' xticks = [] if chern_x != None: xticks = chern_x print chern_x, cherns, print 'q****', q_25s, q_75s pl.plot(cherns, x=[], k=2, errors=[] , xlabel=xlabel, ylabel=ylabel, title=infile_name1.split('/outputs')[1].split('.csv')[0]+'pair-key'+str(pair_seq), xlog=False, ylog=True, acc_legend=['0-hop-Chernoff', '1-hop-Chernoff', '0-hop-t-test', '1-hop-t-test'], xticks=np.arange(1, cut+1), figure_width=4.3307, figure_height=3.346, x_shift=0.06, y_shift=0.05, legend_x=0.3 ) #[q_25s, q_75s] if __name__ == "__main__": global ACAP ACAP = 50 topo_types = ['B4', 'TREE', 'JUPITER'] task_types = ['CLASSIFICATION', 'RANKING', 'APPLICATION'] trace_types = ['A', 'B', 'C', 'e1', 'e5', 'e10', 'e50', 'e100'] pair_seq = 1 print trace_types[:3] #accuracyPlot(topo_types, task_types, trace_types[:3], pair_seq=pair_seq) rankingPlot(topo_types, task_types, trace_types[:3], pair_seq=pair_seq) plt.show() <file_sep> from crc8 import crc8 def crcHash(d): <file_sep> def crc8(crc, data, poly): data_len = len(data) for x in data: extract = ord(x) for i in range(0, 8): sum_value = (crc^extract) & 0x01 crc >>= 1 if(sum_value): crc ^= poly extract >>= 1 return crc <file_sep>import pandas as pd import os.path import json def getnodes(): nodes = [] # Host name host_nodes = [] for i in xrange(0,8): for j in xrange(0,2): name = str(0)+'_'+str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) host_nodes.append(name) # ToR name tor_nodes = [] for i in xrange(0,8): for j in xrange(0,2): name = str(1)+'_'+str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) tor_nodes.append(name) # Aggr name aggr_nodes = [] for i in xrange(0,4): for j in xrange(0,2): for k in xrange(0,2): name = str(2)+'_' +str(k)+'_' + str(j)+'_' +str(i) nodes.append(name) aggr_nodes.append(name) # Spine name spine_nodes = [] for i in xrange(0,4): for j in xrange(0,2): name = str(3)+'_' +str(0)+'_' + str(j)+'_' +str(i) nodes.append(name) spine_nodes.append(name) for i in xrange(0,2): for j in xrange(0,2): name = str(3)+'_' +str(1)+'_' + str(j)+'_' +str(i) nodes.append(name) spine_nodes.append(name) return nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes def get_nexthos_up(): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes= getnodes() port_list = {} # Host for node in host_nodes: node_split = node.split('_') for j in xrange(0,1): next_hop = (str(1) + '_' + node_split[1] + '_' + node_split[2] + '_' +node_split[3]) if j == 0: next_hop_str = next_hop else: next_hop_str += ' '+next_hop port_list[node] = next_hop_str # Tor for node in tor_nodes: node_split = node.split('_') for j in xrange(0,4): next_hop = (str(2) + '_' + node_split[1] + '_' + node_split[2] + '_' +str(j)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' '+next_hop port_list[node] = next_hop_str # Aggr for node in aggr_nodes: node_split = node.split('_') if(node_split[1] == '0'): for j in xrange(0,2): next_hop = (str(2) + '_' + str(1) + '_' + node_split[2] + '_' + str(j+int(node_split[3])/2*2)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop if(node_split[1] == '1'): for j in xrange(0,2): next_hop = (str(3) + '_' + str(0) + '_' + str(int(node_split[3])%2) + '_' + str(j+int(node_split[3])/2*2)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop port_list[node] = next_hop_str # Spine for node in spine_nodes: node_split = node.split('_') if(node_split[1] == '0'): for j in xrange(0,2): next_hop = (str(3) + '_' + str(1) + '_' + node_split[2] + '_' + str(j)) if j == 0: next_hop_str = next_hop else: next_hop_str += ' ' + next_hop port_list[node] = next_hop_str return port_list def tree_topo(): nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes = getnodes() next_hop_up = get_nexthos_up() switch_nodes = [x for x in nodes if x not in host_nodes] edges = [] for key in next_hop_up.keys(): if key not in host_nodes: nhops = next_hop_up[key].split() for nhop in nhops: edges.append((key, nhop)) print(len(edges)) external_edges = ([('3_1_0_0', 'e1'), ('3_1_0_1', 'e1'), ('3_1_1_0', 'e1'), ('3_1_1_1', 'e1')] ) edges += external_edges return switch_nodes, edges def mesh_topo(): edges = ([('s1', 's2'), ('s1', 's5'), ('s2', 's3'), ('s3', 's4'), ('s3', 's6'), ('s4', 's5'), ('s4', 's7'), ('s4', 's8'), ('s5', 's6'), ('s6', 's7'), ('s6', 's8'), ('s7', 's8'), ('s7', 's11'), ('s8', 's10'), ('s9', 's10'), ('s9', 's11'), ('s10', 's11'), ('s10', 's12'), ('s11', 's12'), ] ) host_switch = ([('s1', 'h1'), ('s2', 'h2'), ('s3', 'h3'), ('s4', 'h4'), ('s5', 'h5'), ('s6', 'h6'), ('s7', 'h7'), ('s8', 'h8'), ('s9', 'h9'), ('s10', 'h10'), ('s11', 'h11'), ('s12', 'h12') ] ) edges += host_switch switches = ['s' + str(i) for i in range(1, 13)] return switches, edges def blockToBlock(input_name, block_num, a0_inc, ai_inc, a0_cut=None, ai_cut=None, file_name=None, r=9): if file_name != None: if((os.path.isfile(file_name)) == True): json_data = open(file_name).read() edges = json.loads(json_data) print('len(edges)', len(edges)) return edges # Read switches and edges from the file df0 = pd.read_csv(input_name, names=['a' + str(i) for i in range(r)]) df = df0.copy() print df0 # Generate switches and edges according to the rule: # a0+a0_inc, a_i + ai_inc for i in range(block_num): df1 = df0.copy() df1['a0'] = df1['a0'] + a0_inc #16 for j in range(1, r): df1['a' + str(j)] = df1['a' + str(j)] + ai_inc #8 df = df.append(df1, ignore_index=True) df0 = df1.copy() print(df) if a0_cut != None: df = df[df['a0'] <= a0_cut] if ai_cut != None: for j in range(1, r): df['a' + str(j)] = df['a' + str(j)][df['a' + str(j)] <= ai_cut] df = df.reset_index() edges = [] for j in range(1, r): for i in range(df.shape[0]): if pd.isnull(df['a' + str(j)].loc[i]) == False: edges.append((int(df['a0'].loc[i]), int(df['a' + str(j)].loc[i]))) print('len(edges)', len(edges)) if file_name != None: with open(file_name, 'w') as file: file.write(json.dumps(edges)) return edges def renameSwitch(edges, prefix1, prefix2): """ Rename the switch by some rules """ edges_renamed = [] for edge in edges: edges_renamed.append((prefix1+str(edge[0]), prefix2+str(edge[1]))) return edges_renamed def jupiter_topo(spine_cut=None, aggr_cut=None, tor_cut=None): """ Build the topology with 256 spine blocks and 64 aggregation blocks, that is, 64*8 = 512 MBs, all links: 256*16(switches)*8(links) = 512*8(switches)*8(links) Spine to Aggregation: all to all logically Each spine: 16(switches)*8(links) = 128 links Each aggregation: 8(MBs)*8(switches)*8(links) = 512 links Spine to Spine a0: low ai: top Spine to aggr a0: aggr_top ai: spine Aggr to Aggr a0: low ai: top Aggr to tor a0: aggr_low ai: tor """ # Spine to Spine 4096*8 input_name = "../inputs/spine_spine_connections.csv" block_num, a0_inc, ai_inc = 255, 16, 8 file_name = '../outputs/spine_spine_edge_cut.txt' spine_spine_edges = blockToBlock( input_name, block_num, a0_inc, ai_inc, a0_cut=spine_cut, ai_cut=spine_cut/2, file_name=file_name ) prefix1, prefix2 = 'sl', 'sh' edges_renamed = renameSwitch(spine_spine_edges, prefix1, prefix2) # Spine to aggr 4096*8 input_name = "../inputs/connection.csv" block_num, a0_inc, ai_inc = 31, 1, 128 file_name = '../outputs/spine_aggr_edge_cut.txt' spine_aggr_edges = blockToBlock( input_name, block_num, a0_inc, ai_inc, a0_cut=aggr_cut, ai_cut=spine_cut, file_name=file_name ) prefix1, prefix2 = 'ah', 'sl' edges = renameSwitch(spine_aggr_edges, prefix1, prefix2) edges_renamed += edges print([x for x in spine_aggr_edges if x[1] == 1]) # Aggr to Aggr 4096*8 input_name = "../inputs/aggr_aggr_connections.csv" block_num, a0_inc, ai_inc = 64*8-1, 8, 8 file_name = '../outputs/aggr_aggr_edge_cut.txt' aggr_aggr_edges = blockToBlock( input_name, block_num, a0_inc, ai_inc, a0_cut=aggr_cut, ai_cut=aggr_cut, file_name=file_name ) prefix1, prefix2 = 'al', 'ah' edges_renamed += renameSwitch(aggr_aggr_edges, prefix1, prefix2) # Aggr to tor input_name = "../inputs/aggr_tor_connections.csv" block_num, a0_inc, ai_inc = 64-1, 64, 128 file_name = '../outputs/aggr_tor_edge_cut.txt' aggr_tor_edges = blockToBlock( input_name, block_num, a0_inc, ai_inc, a0_cut=aggr_cut, ai_cut=tor_cut, file_name=file_name, r=17 ) prefix1, prefix2 = 'al', 'tor' edges_renamed += renameSwitch(aggr_tor_edges, prefix1, prefix2) # print edges_renamed switches = [] return switches, edges_renamed def getJupiternNodes(tors_num=8192, aggr_num=4096, spine_num=4096): nodes = [] host_nodes, tor_nodes, aggr_nodes, spine_nodes = [], [], [], [] # Tors for i in range(1, tors_num+1): tor_nodes.append('tor' + str(i)) # Aggrs for i in range(1, aggr_num+1): aggr_nodes.append('al' + str(i)) aggr_nodes.append('ah' + str(i)) # Spines for i in range(1, spine_num/2+1): spine_nodes.append('sh' + str(i)) for i in range(1, spine_num+1): spine_nodes.append('sl' + str(i)) nodes += tor_nodes + aggr_nodes + spine_nodes return nodes, host_nodes, tor_nodes, aggr_nodes, spine_nodes #switches, edges = jupiter_topo(tor_cut=32*4*2, aggr_cut=64*2, spine_cut=16*2) <file_sep>from collections import OrderedDict import bound as bd import numpy as np def append_path(hash_str, pre_hop, cur_hop, paths): if hash_str not in paths: paths[hash_str] = OrderedDict({}) if cur_hop not in paths[hash_str]: paths[hash_str][(pre_hop, cur_hop)] = 1 def min_bound(next_counts): n = len(next_counts) min_bound = 1.1 min_pos = -1 sum_HHes = np.float64(sum(next_counts)) for i in range(n): o_fi = float(next_counts[i])/sum(next_counts) ratio = 1.0/len(next_counts) if o_fi <= ratio: flow_fractions = [float(1.0)/sum_HHes]*sum_HHes theta, chern_bound = bd.chernoff_min( flow_fractions, o_fi, ratio=ratio ) if chern_bound < min_bound: min_bound = chern_bound min_pos = i print( 'chern_bound, o_fi, ratio, min_bound', chern_bound, o_fi, ratio, min_bound ) return min_bound <file_sep>import heapq import pandas as pd import numpy as np import operator import struct from collections import Counter import independent_set as iset def dominantApp(flow_dict_per_link): """ Return max key and value from the dictionary """ return max(flow_dict_per_link.iteritems(), key=operator.itemgetter(1)) def appRatioPerLink(flow_dict_per_link, k): """ k is the number of heavy hitters df column is the dst port df index is time """ k_keys_sorted = heapq.nlargest( k, flow_dict_per_link.items(), key=operator.itemgetter(1) ) #df_entry = pd.DataFrame( #data={struct.unpack('>I', '\x00\x00'+ x[0]):[x[1]] for x in k_keys_sorted}) df_entry = pd.DataFrame(data={x[0]:[x[1]] for x in k_keys_sorted}) #df_entry = df_entry.div(df_entry.sum(axis=1), axis=0) return df_entry def linkRatioPerApp(flow_dict_all_link, input_node): """ input_node is the number """ df = pd.DataFrame(data=flow_dict_all_link).fillna(value=0) return def appClassification(num_cluster, inner_imr, key='', imr_threshold=0.1, class_dict={}): # Bias if num_cluster > 1: class_dict[key] = 2 elif num_cluster == 1 and inner_imr > imr_threshold: # Correlated class_dict[key] = 1 else: class_dict[key] = 0 def appLinkCorrelation(data, perlink_df, app_link_dict, cflow_dict, key='', class_dict={}, imr_threshold=0.1, k=5, topo_type='B4', links=[] ): k = 3 if(perlink_df.shape[0] == 1): perlink_df.plot(x=perlink_df.index.values) return if topo_type == 'TREE': links = ([('2_1_0_0', '3_0_0_0'), ('2_1_0_0', '3_0_0_1')] ) if topo_type == 'B4': links = ([('s4', 's7'), ('s4', 's8')]) """ next_hops = '3_0_0_0,3_0_0_1' next_hops = 's7,s8 '""" #domi_app = ap.dominantApp(cflow_dict[link1]) #print(' --domi_app', domi_app) x = app_link_dict # The top k app on switch df_entry = None for link in links: if link not in x: x[link] = {} if df_entry == None: df_entry = Counter(x[link]) else: df_entry += Counter(x[link]) df_entry = appRatioPerLink( df_entry, k ) top_apps = list(df_entry.columns.values) app_link_table = [] link_topk = 1 link_bottomk = 1 for app in top_apps: #app = struct.pack('>I', app)[2:] tmp = [] for link in links: if app in x[link]: print x[link][app], tmp.append(x[link][app]) else: x[link][app] = 0.1 print 0, tmp.append(0.1) print '\n' tmp = sorted(tmp) print 'tmp', tmp app_link_table.append(tmp[0:link_topk]+tmp[-link_bottomk:]) app_link_table = np.transpose(np.array(app_link_table)) app_df = pd.DataFrame( app_link_table, columns=['a' + str(x) for x in top_apps]) print app_df app_imrs = iset.independentCluster(app_df, 0.01) perlink_df = perlink_df.append( df_entry, ignore_index=True).fillna(value=0 ) appClassification( len(app_imrs), app_imrs[0][2], key=key, imr_threshold=imr_threshold, class_dict=class_dict) inner_imr = app_imrs[0][2] print(' --df_entry', df_entry) return [x[2] for x in app_imrs] <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt def plot(data, x=None, k=1, errors=[], xlabel='x', ylabel='y', title='title', xlog=False, ylog=False, acc_legend=[], xticks=[], figure_width=4.3307*1.25, figure_height=3.346*1.25, legend_y=0.3, x_shift=0.02, y_shift=0.02, legend_x=0.6 ): fig = plt.figure(figsize=(figure_width, figure_height)) ax = plt.subplot(111) types = ['o-', '^-.', '*--', 'd-.', 'p:', '>:', '<-', '8-', 's-', 'p-', '1-', '2-', '3-', '4-', 'h-'] colors = ['b', 'r', 'g', 'm', 'c', 'k', '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'] if ylog: ax.set_yscale('log') if xlog: ax.set_xscale('log') if k == 1: if len(x) == 0: x_values = np.arange(len(data)) plt.plot(x_values, data, 'o-', color='blue', markersize=8) if len(errors) != 0: plt.errorbar(x_values, data, errors, linestyle='None',color="r") else: for i in range(len(data)): if len(x) == 0: x_values = np.arange(len(data[i])) else: x_values = x if len(x) !=0 and isinstance(x[0], (list,)): x_values = x[i] print 'x_values, data[i]',x_values, data[i] plt.plot( x_values, data[i], types[i], color=colors[i], linewidth=2.0, markersize=10) if len(errors) != 0: plt.errorbar( x_values, data[i], yerr=errors[i], linestyle='None', color=colors[i%16], linewidth=1.5, capthick=3 ) plt.ylabel(ylabel) plt.xlabel(xlabel) if len(xticks) > 0: plt.xticks(x_values, xticks) plt.grid(True) box = ax.get_position() ax.set_position( [box.x0+x_shift, box.y0+y_shift, box.width*1, box.height*1]) #plt.xticks(flow_num) # Put a legend to the right of the current axis if len(acc_legend) != 0: ax.legend( acc_legend, loc='center left', bbox_to_anchor=(legend_x, legend_y), numpoints=1 ) #plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') print '../figures/' + title + '.png' fig.savefig('../figures/' + title + '.png', dpi = 300) def box_plot(data, x=None, k=1, errors=[], xlabel='x', ylabel='y', title='title', xlog=False, ylog=False, acc_legend=[], xticks=[], figure_width=4.3307*1.25, legend_y=0.3 ): fig = plt.figure(figsize=(figure_width, 3.346*1.25)) ax = plt.subplot(111) types = ['o-', '^-.', '*--', 'd-.', 'p:', '>:', '<-', '8-', 's-', 'p-', '1-', '2-', '3-', '4-', 'h-'] colors = ['b', 'r', 'g', 'm', 'c', 'k', '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5'] if ylog: ax.set_yscale('log') if xlog: ax.set_xscale('log') bplots = [] colors = ['pink', 'lightblue', 'lightgreen'] for i in range(len(data)): x_values = np.arange(len(data[i])) bplot1 = plt.boxplot( data[i], widths=0.3, patch_artist=True) for patch in bplot1['boxes']: patch.set_facecolor(colors[i]) bplots.append(bplot1) """for bplot in bplots: for patch in bplot['boxes']: patch.set_facecolor(colors[0])""" plt.ylabel(ylabel) plt.xlabel(xlabel) if len(xticks) > 0: plt.xticks(np.arange(1, len(data[0])+1), xticks) plt.grid(True) box = ax.get_position() ax.set_position( [box.x0+0.04, box.y0+0.02, box.width, box.height]) fig.savefig('../figures/' + title + 'boxplot.png', dpi = 300) <file_sep>import random """ Mark packets in a flow Options: Mark every packet Mark some packet (This is resonable) """ def mark_group_dest(routing_table): """ How to mark packets according to destination only mark thoes with multi-path """ mark_group = {} for s_d in routing_table: for d in routing_table[s_d]: if len(routing_table[s_d][d]) > 1: if d not in mark_group: mark_group[d] = [] mark_group[d] += routing_table[s_d][d] mark_group[d] = list(set(mark_group[d])) return mark_group def marknum(hash_str, count_dict, threshold, mark_group): """ Determine how many packets to mark such that we can get a complete path """ if hash_str not in count_dict: count_dict[hash_str] = 0 count_dict[hash_str] += 1 if count_dict[hash_str] > threshold: return 'None' switch_id = mark(mark_group) return switch_id def mark(mark_group): """ Return a switch ID it may be tranversing Currently, all switch IDs are in considering """ n = len(mark_group) pos = random.randint(0, n-1) return mark_group[pos] <file_sep>import numpy as np import bound as bd from co_func import min_bound from t_test import t_test def common_flows_with_next(r2, r2_next_hops, d, rm, router_nodes, routing_table ): r2_pos = router_nodes.index(r2) rm_r2_nhops = [] # r2 is the previous hop of next hops for f in rm: for npos in r2_next_hops: next_pos = router_nodes.index(npos) dst = router_nodes[f.index(max(f))] if (f[r2_pos] != 0 and f[next_pos] != 0 and f[r2_pos] < f[next_pos] and dst in d ): rm_r2_nhops.append(f) rm = rm_r2_nhops if len(rm) == 0: return [0 for i in range(len(r2_next_hops))] rm = np.array(rm, dtype=bool) rm = np.array(rm, dtype=int) next_counts = [] for r2_next_hop in r2_next_hops: next_pos = router_nodes.index(r2_next_hop) next_flows = np.bitwise_and( rm[:, r2_pos], rm[:, next_pos]) next_count = sum(next_flows) next_counts.append(next_count) print('len(rm)', len(rm), r2, next_counts) return next_counts def common_flows_with_pre(prehop, r2, r2_next_hops, d, d_pre, rm, router_nodes, routing_table ): r2_pos = router_nodes.index(r2) rm_r2_nhops = [] # r2 is the previous hop of next hops for f in rm: for npos in r2_next_hops: pre_pos = router_nodes.index(prehop) next_pos = router_nodes.index(npos) dst = router_nodes[f.index(max(f))] if (f[pre_pos] != 0 and f[r2_pos] != 0 and f[next_pos] != 0 and f[pre_pos] < f[r2_pos] and f[r2_pos] < f[next_pos] and dst in d and dst in d_pre ): rm_r2_nhops.append(f) rm = rm_r2_nhops if len(rm) == 0: print("**** rm is empty!") return [0 for i in range(len(r2_next_hops))] rm = np.array(rm, dtype=bool) rm = np.array(rm, dtype=int) next_counts = [] for r2_next_hop in r2_next_hops: next_pos = router_nodes.index(r2_next_hop) next_flows = np.bitwise_and( rm[:, r2_pos], rm[:, next_pos]) next_count = sum(next_flows) next_counts.append(next_count) print('len(rm)', len(rm), r2, next_counts) return next_counts def dest_group_by_nhops(routing_table): # ds with the same next hops # [[d1, d2], [], [], []] # key is the next hops, value is the dest ds = {} dests = routing_table.keys() d_n = len(dests) visited = [False for i in range(d_n)] for i, d in enumerate(dests): if len(routing_table[d]) > 1 and visited[i] == False: nhops = sorted(routing_table[d]) tmp = [d] for j in range(i+1, d_n): d_j = dests[j] if sorted(routing_table[d_j]) == nhops: visited[j] = True tmp.append(d_j) ds['\t'.join(nhops)] = tmp return ds def hash_biased(r1, rm, router_nodes, routing_table_r1, threshould=0.001): """ routing_table is the table of r1 """ ds = dest_group_by_nhops(routing_table_r1) print('ds', r1, ds) min_chern = 2.0 if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') next_counts = common_flows_with_next( r1, nhops, ds[key], rm, router_nodes, routing_table_r1 ) t, p = t_test(next_counts, 0.5) chern_bound = 0 if sum(next_counts) > 0: chern_bound = min_bound(next_counts) min_chern = min(min_chern, chern_bound) if min_chern < threshould: break return min_chern, [r1, ds], p def corr_detection(r1_pre, r1, rm, router_nodes, routing_table_pre, routing_table_r1 ): d_pres = dest_group_by_nhops(routing_table_pre) d_pre_list = [x for d_pre in d_pres.values() for x in d_pre] ds = dest_group_by_nhops(routing_table_r1) print('r1, ds, d_pre_list', r1, ds, d_pre_list) min_chern = 2.0 if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') next_counts = common_flows_with_pre( r1_pre, r1, nhops, d_pre_list, ds[key], rm, router_nodes, routing_table_r1 ) t, p = t_test(next_counts, 0.5) chern_bound = 0 if sum(next_counts) > 0: chern_bound = min_bound(next_counts) min_chern = min(min_chern, chern_bound) return min_chern, p def corr_group(r2, rm, router_nodes, routing_table): # input: # list[str]: n*1 # routing_matrix: # r1s, r2: ancesters of r2: r1 and router r2 r1s = pre_hop_group(r2, rm, router_nodes, routing_table[r2]) min_bounds = [] ps = [] for r1 in r1s: min_bound, p = corr_detection( r1, r2, rm, router_nodes, routing_table[r1], routing_table[r2] ) min_bounds.append((r1, min_bound)) ps.append((r1, p)) min_bounds = sorted(min_bounds, key=lambda x: x[1]) return min_bounds def pre_hop_group(r1, rm, router_nodes, routing_table_r1): ds = dest_group_by_nhops(routing_table_r1) all_pres = [] if len(ds) != 0: for key in ds.keys(): nhops = key.split('\t') pres = pre_hops( r1, nhops, ds[key], rm, router_nodes, routing_table_r1 ) print('pres', pres) all_pres.append(pres) all_pres = list(set([x for pre in all_pres for x in pre])) return all_pres def pre_hops(r2, r2_next_hops, d, rm, router_nodes, routing_table): """ The pre hops of r1 based on the splitting, """ r2_pos = router_nodes.index(r2) rm_r2_nhops = [] # r2 is the previous hop of next hops for f in rm: for npos in r2_next_hops: next_pos = router_nodes.index(npos) dst = router_nodes[f.index(max(f))] if (f[r2_pos] != 0 and f[next_pos] != 0 and f[r2_pos] < f[next_pos] and dst in d ): rm_r2_nhops.append(f) rm = rm_r2_nhops if len(rm) == 0: print('++++ pre_hops, rm is empty, r2, r2_next_hops', r2, r2_next_hops) return [] print('rm', rm) pres = {} for f in rm: for x in f: if x < f[r2_pos] and x != 0: pre = router_nodes[f.index(x)] pres[pre] = 1 print('pres', r2, pres) return pres.keys() <file_sep>from countminsketch import CountMinSketch def node_countminsketch(): sketch = CountMinSketch(6000, 10) return sketch def host_init(host_nodes): host_sketches = {} for host_node in host_nodes: host_sketches[host_node] = node_countminsketch() return host_sketches def node_sketch_init(): global host_nodes, nodes node_sketches = {} for node in nodes: node_sketches[node] = node_countminsketch() return node_sketches def sort_sketch(sketch): sketch_elt_list = [] for table in sketch.tables: for mi in xrange(0, sketch.m): sketch_elt_list.append(table[mi]) sketch_elt_list.sort(reverse=True) return sketch_elt_list def clear_sketch(sketch): for table in sketch.tables: for mi in xrange(0, sketch.m): table[mi] = 0 return sketch <file_sep>import pandas as pd import numpy as np import math from scipy import optimize def hoefding_HHes(HHes, x, alpha): sum_HHes = np.float64(sum(HHes)) flow_fractions = [np.float64(f)/np.float64(sum_HHes) for f in HHes] return hoefding(flow_fractions, x, alpha) def hoefding(flow_fractions, x, alpha): x = x - alpha f_sum = 0 for fi in flow_fractions: f_sum += math.pow(fi,2.0) return math.exp(-math.pow(x,2.0)/f_sum) def chernoff_fun(theta): global flow_fractions, x, alpha comp1 = math.exp(-theta*x) e_proc = 1.0 for fi in flow_fractions: try: ans = math.exp(theta*fi) except OverflowError: ans = float('inf') e_proc *= (ans*alpha+1-alpha) return math.exp(-theta*x)*e_proc def chernoff_min(HHes, o_f, ratio = 0.5): global flow_fractions, x, alpha x = o_f alpha = ratio #sum_HHes = np.float64(sum(HHes)) flow_fractions = HHes #[np.float64(f)/sum_HHes for f in HHes] theta = optimize.fmin(chernoff_fun, 1, disp=False) ch_bound = chernoff_fun(theta[0]) return theta[0], ch_bound def chernoff_min_theta(HHes, o_f, ratio = 0.5): global flow_fractions, x, alpha if len(HHes) == 0 or o_f == 1: return 0, 0 x = o_f alpha = ratio flow_fractions = HHes f1 = flow_fractions[0] theta = ((np.float64(1.0) / np.float64(f1)) * math.log(o_f * (1.0 - alpha) / (alpha * (1 - o_f)), math.exp(1) ) ) ch_bound = chernoff_fun(theta) return theta, ch_bound
de77865d79a70c8e5c8f024340c198eea45c6c68
[ "Python" ]
32
Python
yunhong111/hashCorrelation
f82463ee7665aedf9a9e508008a9d7d2ff8e7123
ea265f6204382e81439cf13ce7db3da8c9ccb16a
refs/heads/master
<file_sep>/** * @constructor * @param {mozContact.Data} [data] */ function mozContact(data) {} /** * @const * @type {string} */ mozContact.prototype.id = ''; /** * @const * @type {Date} */ mozContact.prototype.published = null; /** * @const * @type {Date} */ mozContact.prototype.updated = null; /** * @type {string[]} */ mozContact.prototype.name = []; /** * @type {string[]} */ mozContact.prototype.honorificPrefix = []; /** * @type {string[]} */ mozContact.prototype.givenName = []; /** * @type {string[]} */ mozContact.prototype.additionalName = []; /** * @type {string[]} */ mozContact.prototype.familyName = []; /** * @type {string[]} */ mozContact.prototype.honorificSuffix = []; /** * @type {string[]} */ mozContact.prototype.nickname = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.email = []; /** * @type {Blob[]} */ mozContact.prototype.photo = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.url = []; /** * @type {string[]} */ mozContact.prototype.category = []; /** * @type {mozContact.AddressField[]} */ mozContact.prototype.adr = []; /** * @type {mozContact.TelField[]} */ mozContact.prototype.tel = []; /** * @type {string[]} */ mozContact.prototype.org = []; /** * @type {string[]} */ mozContact.prototype.jobTitle = []; /** * @type {Date} */ mozContact.prototype.bday = null; /** * @type {string[]} */ mozContact.prototype.note = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.impp = []; /** * @type {Date} */ mozContact.prototype.anniversary = null; /** * @type {string} */ mozContact.prototype.sex = ''; /** * @type {string} */ mozContact.prototype.genderIdentity = ''; /** * @type {string[]} */ mozContact.prototype.key = []; /** * @param {mozContact.Data} param * @deprecated since v1.3 */ mozContact.prototype.init = function (param) {}; /** * @typedef {*} mozContact.Data * @property {string} [name] * @property {string} [honorificPrefix] * @property {string} [givenName] * @property {string} [additionalName] * @property {string} [familyName] * @property {string} [honorificSuffix] * @property {string} [nickname] * @property {mozContact.ContactField} [email] * @property {Blob} [photo] * @property {mozContact.ContactField} [url] * @property {string} [category] * @property {mozContact.AddressField} [adr] * @property {mozContact.TelField} [tel] * @property {string} [org] * @property {string} [jobTitle] * @property {Date} [dbay] * @property {string} [note] * @property {mozContact.ContactField} [impp] * @property {Date} [anniversary] * @property {string} [sex] * @property {string} [genderIdentity] * @property {string} [key] */ /** * @typedef {*} mozContact.ContactField * @property {string[]} type * @property {string} value * @property {boolean} pref */ /** * @typedef {*} mozContact.AddressField * @property {string[]} type * @property {boolean} pref * @property {string} streetAddress * @property {string} locality * @property {string} region * @property {string} postalCode * @property {string} countryName */ /** * @typedef {*} mozContact.TelField * @property {string[]} type * @property {boolean} pref * @property {string} value * @property {string} carrier */ <file_sep>/** * @interface */ function ContactManager() {} /** * @type {function(MozContactChangeEvent)} */ ContactManager.prototype.oncontactchange = null; /** * @returns {DOMRequest} */ ContactManager.prototype.clear = function () {}; /** * filterOp: equals|startsWith|match * * @param {{filterBy: string[], filterValue: *, filterOp: string, * filterLimit: number}} options * @returns {DOMRequest} * @property {mozContact[]} result */ ContactManager.prototype.find = function (options) {}; /** * sortBy: givenName|familyName * sortOrder: descending|ascending * filterOp: equals|startsWith|match * * @param {{sortBy: string, sortOrder: string, filterBy: string[], * filterValue: *, filterOp: string, filterLimit: number}} options * @returns {DOMRequest} * @property {mozContact[]} result */ ContactManager.prototype.getAll = function (options) {}; /** * @returns {DOMRequest} * @property {number} result */ ContactManager.prototype.getCount = function () {}; /** * @returns {DOMRequest} * @property {number} result */ ContactManager.prototype.getRevision = function () {}; /** * @param {mozContact} contact * @returns {DOMRequest} */ ContactManager.prototype.remove = function (contact) {}; /** * @param {mozContact} contact * @returns {DOMRequest} */ ContactManager.prototype.save = function (contact) {}; /** * @interface * @extends Event */ function DeviceStorageChangeEvent() {} /** * @type {string} */ DeviceStorageChangeEvent.prototype.path = ''; /** * created|modified|deleted * * @type {string} */ DeviceStorageChangeEvent.prototype.reason = ''; /** * @interface * @extends EventTarget */ function DeviceStorage() {} /** * apps|music|pictures|sdcard|videos * * @const * @type {string} */ DeviceStorage.prototype.storageName = ''; /** * @const * @type {boolean} */ DeviceStorage.prototype.default = false; /** * @type {function(DeviceStorageChangeEvent)} */ DeviceStorage.prototype.onchange = null; /** * @param {Blob} file * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.add = function (file) {}; /** * @param {Blob} file * @param {string} name * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.addNamed = function (file, name) {}; /** * @returns {DOMRequest} * @property {string} result available|unavailable|shared */ DeviceStorage.prototype.available = function () {}; /** * @param {string} fileName * @returns {DOMRequest} */ DeviceStorage.prototype.delete = function (fileName) {}; /** * @param {string} path * @param {{since: Date}} [options] * @returns {DOMCursor} * @property {File} result */ DeviceStorage.prototype.enumerate = function (path, options) {}; /** * @param {string} path * @param {{since: Date}} [options] * @returns {DOMCursor} * @property {FileHandle} result */ DeviceStorage.prototype.enumerateEditable = function (path, options) {}; /** * @returns {DOMRequest} * @property {number} result */ DeviceStorage.prototype.freeSpace = function () {}; /** * @param {string} fileName * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.get = function (fileName) {}; /** * @param {string} fileName * @returns {DOMRequest} * @property {FileHandle} result */ DeviceStorage.prototype.getEditable = function (fileName) {}; /** * @returns {DOMRequest} * @property {number} result */ DeviceStorage.prototype.usedSpace = function () {}; /** * @interface * @extends DOMRequest */ function DOMCursor() {} /** * @type {boolean} */ DOMCursor.prototype.done = false; /** * @type {function()} */ DOMCursor.prototype.continue = function () {}; /** * @interface */ function DOMRequest() {} /** * @type {function(Event)} */ DOMRequest.prototype.onsuccess = null; /** * @type {function(Event)} */ DOMRequest.prototype.onerror = null; /** * done|pending * * @type {string} */ DOMRequest.prototype.readyState = ''; /** * @type {*} */ DOMRequest.prototype.result = null; /** * @type {DOMError} */ DOMRequest.prototype.error = null; /** * @interface */ function FileHandle() {} /** * @const * @type {string} */ FileHandle.prototype.name = ''; /** * @const * @type {string} */ FileHandle.prototype.type = ''; /** * @type {function(Event)} */ FileHandle.prototype.onabort = null; /** * @type {function(Event)} */ FileHandle.prototype.onerror = null; /** * @param {string} mode readonly|readwrite * @returns {LockedFile} */ FileHandle.prototype.open = function (mode) {}; /** * @returns {DOMRequest} * @property {File} result */ FileHandle.prototype.getFile = function () {}; /** * @interface * @extends DOMRequest */ function FileRequest() {} /** * @const * @type {LockedFile} */ FileRequest.prototype.lockedFile = null; /** * @type {function({loaded: number, total: number})} */ FileRequest.prototype.onprogress = null; /** * @interface */ function LockedFile() {} /** * @const * @type {FileHandle} */ LockedFile.prototype.fileHandle = null; /** * readonly|readwrite * * @const * @type {string} */ LockedFile.prototype.mode = ''; /** * @const * @type {boolean} */ LockedFile.prototype.active = false; /** * @type {number|null} */ LockedFile.prototype.location = 0; /** * @type {function(Event)} */ LockedFile.prototype.oncomplete = null; /** * @type {function(Event)} */ LockedFile.prototype.onabort = null; /** * @type {function(Event)} */ LockedFile.prototype.onerror = null; /** * @param {{size: boolean, lastModified: boolean}} param * @returns {FileRequest} * @property {{size: number, lastModified: Date}} result */ LockedFile.prototype.getMetadata = function (param) {}; /** * @param {number} size * @returns {FileRequest} * @property {ArrayBuffer} result */ LockedFile.prototype.readAsArrayBuffer = function (size) {}; /** * @param {number} size * @param {string} [encoding] * @returns {FileRequest} * @property {string} result */ LockedFile.prototype.readAsText = function (size, encoding) {}; /** * @param {string|ArrayBuffer} data * @returns {FileRequest} */ LockedFile.prototype.write = function (data) {}; /** * @param {string|ArrayBuffer} data * @returns {FileRequest} * @property {null} location */ LockedFile.prototype.append = function (data) {}; /** * @param {number} [start] * @returns {FileRequest} */ LockedFile.prototype.truncate = function (start) {}; /** * @returns {FileRequest} */ LockedFile.prototype.flush = function () {}; /** * @returns {FileRequest} */ LockedFile.prototype.abort = function () {}; /** * @constructor * @param {MozActivityOptions} options * @extends DOMRequest */ function MozActivity(options) {} /** * @typedef {{}} MozActivityOptions * @property {string} name * @property {{}} [data] */ /** * @interface */ function MozActivityRequestHandler() {} /** * @const * @type {MozActivityOptions} */ MozActivityRequestHandler.prototype.source = null; /** * @param {*} answer */ MozActivityRequestHandler.prototype.postResult = function (answer) {}; /** * @param {string} message */ MozActivityRequestHandler.prototype.postError = function (message) {}; /** * @interface * @extends Event */ function MozContactChangeEvent() {} /** * @type {string} */ MozContactChangeEvent.prototype.contactID = ''; /** * update|create|remove * * @type {string} */ MozContactChangeEvent.prototype.reason = ''; /** * @constructor * @param {mozContact.Data} [data] */ function mozContact(data) {} /** * @const * @type {string} */ mozContact.prototype.id = ''; /** * @const * @type {Date} */ mozContact.prototype.published = null; /** * @const * @type {Date} */ mozContact.prototype.updated = null; /** * @type {string[]} */ mozContact.prototype.name = []; /** * @type {string[]} */ mozContact.prototype.honorificPrefix = []; /** * @type {string[]} */ mozContact.prototype.givenName = []; /** * @type {string[]} */ mozContact.prototype.additionalName = []; /** * @type {string[]} */ mozContact.prototype.familyName = []; /** * @type {string[]} */ mozContact.prototype.honorificSuffix = []; /** * @type {string[]} */ mozContact.prototype.nickname = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.email = []; /** * @type {Blob[]} */ mozContact.prototype.photo = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.url = []; /** * @type {string[]} */ mozContact.prototype.category = []; /** * @type {mozContact.AddressField[]} */ mozContact.prototype.adr = []; /** * @type {mozContact.TelField[]} */ mozContact.prototype.tel = []; /** * @type {string[]} */ mozContact.prototype.org = []; /** * @type {string[]} */ mozContact.prototype.jobTitle = []; /** * @type {Date} */ mozContact.prototype.bday = null; /** * @type {string[]} */ mozContact.prototype.note = []; /** * @type {mozContact.ContactField[]} */ mozContact.prototype.impp = []; /** * @type {Date} */ mozContact.prototype.anniversary = null; /** * @type {string} */ mozContact.prototype.sex = ''; /** * @type {string} */ mozContact.prototype.genderIdentity = ''; /** * @type {string[]} */ mozContact.prototype.key = []; /** * @param {mozContact.Data} param * @deprecated since v1.3 */ mozContact.prototype.init = function (param) {}; /** * @typedef {*} mozContact.Data * @property {string} [name] * @property {string} [honorificPrefix] * @property {string} [givenName] * @property {string} [additionalName] * @property {string} [familyName] * @property {string} [honorificSuffix] * @property {string} [nickname] * @property {mozContact.ContactField} [email] * @property {Blob} [photo] * @property {mozContact.ContactField} [url] * @property {string} [category] * @property {mozContact.AddressField} [adr] * @property {mozContact.TelField} [tel] * @property {string} [org] * @property {string} [jobTitle] * @property {Date} [dbay] * @property {string} [note] * @property {mozContact.ContactField} [impp] * @property {Date} [anniversary] * @property {string} [sex] * @property {string} [genderIdentity] * @property {string} [key] */ /** * @typedef {*} mozContact.ContactField * @property {string[]} type * @property {string} value * @property {boolean} pref */ /** * @typedef {*} mozContact.AddressField * @property {string[]} type * @property {boolean} pref * @property {string} streetAddress * @property {string} locality * @property {string} region * @property {string} postalCode * @property {string} countryName */ /** * @typedef {*} mozContact.TelField * @property {string[]} type * @property {boolean} pref * @property {string} value * @property {string} carrier */ /** * @interface */ function Navigator() {} /** * @type {navigator} */ Navigator.prototype = navigator; /** * @param {string} storageName apps|music|pictures|sdcard|videos * @returns {DeviceStorage} */ Navigator.prototype.getDeviceStorage = function (storageName) {}; /** * @param {string} storageName apps|music|pictures|sdcard|videos * @returns {DeviceStorage[]} */ Navigator.prototype.getDeviceStorages = function (storageName) {}; /** * @param {string} type activity|* * @param {function(MozActivityRequestHandler|*)} handler */ Navigator.prototype.mozSetMessageHandler = function (type, handler) {}; /** * @type {ContactManager} */ Navigator.prototype.mozContacts = null; /** * @type {TCPSocket} */ Navigator.prototype.mozTCPSocket = null; /** * @interface */ function TCPServerSocket() {} /** * @const * @type {number} */ TCPServerSocket.prototype.localPort = 0; /** * @type {function(TCPSocket)} */ TCPServerSocket.prototype.onconnect = null; /** * @type {function(Event)} */ TCPServerSocket.prototype.onerror = null; /** * @type {function()} */ TCPServerSocket.prototype.close = function () {}; /** * @interface * @extends Event */ function TCPSocketEvent() {} /** * @type {TCPSocket} */ TCPSocketEvent.prototype.target = null; /** * open|error|data|drain|close * * @type {string} */ TCPSocketEvent.prototype.type = ''; /** * @type {string|ArrayBuffer|null} */ TCPSocketEvent.prototype.data = null; /** * @interface */ function TCPSocket() {} /** * @const * @type {string} */ TCPSocket.prototype.host = ''; /** * @const * @type {number} */ TCPSocket.prototype.port = 0; /** * @const * @type {boolean} */ TCPSocket.prototype.ssl = false; /** * @const * @type {number} */ TCPSocket.prototype.bufferedAmount = 0; /** * arraybuffer|string * * @const * @type {string} */ TCPSocket.prototype.binaryType = ''; /** * connecting|open|closing|closed * * @const * @type {string} */ TCPSocket.prototype.readyState = ''; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onopen = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.ondrain = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onerror = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.ondata = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onclose = null; /** * @type {function()} */ TCPSocket.prototype.close = function () {}; /** * @param {string} host * @param {number} port * @param {{useSecureTransport?: boolean, binaryType?: string}} [options] * @returns {TCPSocket} */ TCPSocket.prototype.open = function (host, port, options) {}; /** * @param {number} port * @param {{binaryType: string}} [options] * @param {number} [backlog] * @returns {TCPServerSocket} * @since v1.2 */ TCPSocket.prototype.listen = function (port, options, backlog) {}; /** * @type {function()} */ TCPSocket.prototype.resume = function () {}; /** * @param {string|ArrayBuffer} data * @param {number} [byteOffset] * @param {number} [byteLength] * @returns {boolean} */ TCPSocket.prototype.send = function (data, byteOffset, byteLength) {}; /** * @type {function()} */ TCPSocket.prototype.suspend = function () {}; /** * @type {function()} */ TCPSocket.prototype.upgradeToSecure = function () {}; <file_sep>/** * @interface */ function TCPSocket() {} /** * @const * @type {string} */ TCPSocket.prototype.host = ''; /** * @const * @type {number} */ TCPSocket.prototype.port = 0; /** * @const * @type {boolean} */ TCPSocket.prototype.ssl = false; /** * @const * @type {number} */ TCPSocket.prototype.bufferedAmount = 0; /** * arraybuffer|string * * @const * @type {string} */ TCPSocket.prototype.binaryType = ''; /** * connecting|open|closing|closed * * @const * @type {string} */ TCPSocket.prototype.readyState = ''; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onopen = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.ondrain = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onerror = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.ondata = null; /** * @type {function(TCPSocketEvent)} */ TCPSocket.prototype.onclose = null; /** * @type {function()} */ TCPSocket.prototype.close = function () {}; /** * @param {string} host * @param {number} port * @param {{useSecureTransport?: boolean, binaryType?: string}} [options] * @returns {TCPSocket} */ TCPSocket.prototype.open = function (host, port, options) {}; /** * @param {number} port * @param {{binaryType: string}} [options] * @param {number} [backlog] * @returns {TCPServerSocket} * @since v1.2 */ TCPSocket.prototype.listen = function (port, options, backlog) {}; /** * @type {function()} */ TCPSocket.prototype.resume = function () {}; /** * @param {string|ArrayBuffer} data * @param {number} [byteOffset] * @param {number} [byteLength] * @returns {boolean} */ TCPSocket.prototype.send = function (data, byteOffset, byteLength) {}; /** * @type {function()} */ TCPSocket.prototype.suspend = function () {}; /** * @type {function()} */ TCPSocket.prototype.upgradeToSecure = function () {}; <file_sep># Firefox OS IDE helper Some JavaScript interfaces implementation for Firefox OS WebAPIs, helpful for code completion and type hinting. ## About All of us know Firefox OS is a relatively new and revolutionary mobile operating system, that's why making use of the WebAPIs the OS uses can be a problem if we want our IDE to do the job we should. Most editors and/or IDEs are missing of that interfaces. This repository contains some of the relevant (I mean, most used) definitions in JavaScript code (a TypeScript version is planned), so you get code completion, parameter info, argument and return type hinting, wrong type assignment check, and other goodies the IDE of your choice supports. ## Contents Currently, the repository has the following contents: * Base types: `DOMRequest` and `DOMCursor`. * Device storage types: `navigator.getDeviceStorage` and related interfaces. * Web activities types: `MozActivity` class, `navigator.mozSetMessageHandler`. * Web contacts types: `mozContact` class, `navigator.mozContacts`. * TCP sockets types: `navigator.mozTCPSocket` and related interfaces/events. ## Usage Clone/download this repository or just the `fxos-ide-helper.js` file, then tell your editor/IDE to treat that file (or the entire repository) as a library. ## Notes * The interfaces are fetched from Mozilla Developer Network (MDN) JavaScript documentation, specifically from [this](http://goo.gl/C6y2XC) link. * This repository doesn't contain *enum* definitions. JSDoc still don't supports documentation for allowed values (WebStorm's implementation does, but not all the world uses this IDE). * The definitions were well tested and working in WebStorm 9, 10 and PhpStorm 8. If something didn't worked for your editor/IDE, feel free to open a issue and I'll try to add support for that. * Support for [Adobe Brackets](http://brackets.io) was, for the moment, left in *nothing*. Is there any plugin that reads JSDoc and helps with code completion for that IDE? * Started support for [Adobe Brackets](http://brackets.io), now `navigator.*` works, but return types isn't being analyzed yet. ## License MIT. <file_sep>/** * @interface */ function LockedFile() {} /** * @const * @type {FileHandle} */ LockedFile.prototype.fileHandle = null; /** * readonly|readwrite * * @const * @type {string} */ LockedFile.prototype.mode = ''; /** * @const * @type {boolean} */ LockedFile.prototype.active = false; /** * @type {number|null} */ LockedFile.prototype.location = 0; /** * @type {function(Event)} */ LockedFile.prototype.oncomplete = null; /** * @type {function(Event)} */ LockedFile.prototype.onabort = null; /** * @type {function(Event)} */ LockedFile.prototype.onerror = null; /** * @param {{size: boolean, lastModified: boolean}} param * @returns {FileRequest} * @property {{size: number, lastModified: Date}} result */ LockedFile.prototype.getMetadata = function (param) {}; /** * @param {number} size * @returns {FileRequest} * @property {ArrayBuffer} result */ LockedFile.prototype.readAsArrayBuffer = function (size) {}; /** * @param {number} size * @param {string} [encoding] * @returns {FileRequest} * @property {string} result */ LockedFile.prototype.readAsText = function (size, encoding) {}; /** * @param {string|ArrayBuffer} data * @returns {FileRequest} */ LockedFile.prototype.write = function (data) {}; /** * @param {string|ArrayBuffer} data * @returns {FileRequest} * @property {null} location */ LockedFile.prototype.append = function (data) {}; /** * @param {number} [start] * @returns {FileRequest} */ LockedFile.prototype.truncate = function (start) {}; /** * @returns {FileRequest} */ LockedFile.prototype.flush = function () {}; /** * @returns {FileRequest} */ LockedFile.prototype.abort = function () {}; <file_sep>MAKEFLAGS += -s E = S = $(E) $(E) default: echo > n cat $(subst $(S), n ,$(wildcard IDL/*.js)) > fxos-ide-helper.js rm n <file_sep>/** * @typedef {{}} MozActivityOptions * @property {string} name * @property {{}} [data] */ <file_sep>/** * @interface */ function TCPServerSocket() {} /** * @const * @type {number} */ TCPServerSocket.prototype.localPort = 0; /** * @type {function(TCPSocket)} */ TCPServerSocket.prototype.onconnect = null; /** * @type {function(Event)} */ TCPServerSocket.prototype.onerror = null; /** * @type {function()} */ TCPServerSocket.prototype.close = function () {}; <file_sep>/** * @interface * @extends Event */ function TCPSocketEvent() {} /** * @type {TCPSocket} */ TCPSocketEvent.prototype.target = null; /** * open|error|data|drain|close * * @type {string} */ TCPSocketEvent.prototype.type = ''; /** * @type {string|ArrayBuffer|null} */ TCPSocketEvent.prototype.data = null; <file_sep>/** * @interface * @extends EventTarget */ function DeviceStorage() {} /** * apps|music|pictures|sdcard|videos * * @const * @type {string} */ DeviceStorage.prototype.storageName = ''; /** * @const * @type {boolean} */ DeviceStorage.prototype.default = false; /** * @type {function(DeviceStorageChangeEvent)} */ DeviceStorage.prototype.onchange = null; /** * @param {Blob} file * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.add = function (file) {}; /** * @param {Blob} file * @param {string} name * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.addNamed = function (file, name) {}; /** * @returns {DOMRequest} * @property {string} result available|unavailable|shared */ DeviceStorage.prototype.available = function () {}; /** * @param {string} fileName * @returns {DOMRequest} */ DeviceStorage.prototype.delete = function (fileName) {}; /** * @param {string} path * @param {{since: Date}} [options] * @returns {DOMCursor} * @property {File} result */ DeviceStorage.prototype.enumerate = function (path, options) {}; /** * @param {string} path * @param {{since: Date}} [options] * @returns {DOMCursor} * @property {FileHandle} result */ DeviceStorage.prototype.enumerateEditable = function (path, options) {}; /** * @returns {DOMRequest} * @property {number} result */ DeviceStorage.prototype.freeSpace = function () {}; /** * @param {string} fileName * @returns {DOMRequest} * @property {File} result */ DeviceStorage.prototype.get = function (fileName) {}; /** * @param {string} fileName * @returns {DOMRequest} * @property {FileHandle} result */ DeviceStorage.prototype.getEditable = function (fileName) {}; /** * @returns {DOMRequest} * @property {number} result */ DeviceStorage.prototype.usedSpace = function () {}; <file_sep>/** * @interface * @extends Event */ function MozContactChangeEvent() {} /** * @type {string} */ MozContactChangeEvent.prototype.contactID = ''; /** * update|create|remove * * @type {string} */ MozContactChangeEvent.prototype.reason = ''; <file_sep>/** * @interface * @extends DOMRequest */ function DOMCursor() {} /** * @type {boolean} */ DOMCursor.prototype.done = false; /** * @type {function()} */ DOMCursor.prototype.continue = function () {}; <file_sep>/** * @interface */ function DOMRequest() {} /** * @type {function(Event)} */ DOMRequest.prototype.onsuccess = null; /** * @type {function(Event)} */ DOMRequest.prototype.onerror = null; /** * done|pending * * @type {string} */ DOMRequest.prototype.readyState = ''; /** * @type {*} */ DOMRequest.prototype.result = null; /** * @type {DOMError} */ DOMRequest.prototype.error = null; <file_sep>/** * @interface */ function FileHandle() {} /** * @const * @type {string} */ FileHandle.prototype.name = ''; /** * @const * @type {string} */ FileHandle.prototype.type = ''; /** * @type {function(Event)} */ FileHandle.prototype.onabort = null; /** * @type {function(Event)} */ FileHandle.prototype.onerror = null; /** * @param {string} mode readonly|readwrite * @returns {LockedFile} */ FileHandle.prototype.open = function (mode) {}; /** * @returns {DOMRequest} * @property {File} result */ FileHandle.prototype.getFile = function () {}; <file_sep>/** * @interface */ function ContactManager() {} /** * @type {function(MozContactChangeEvent)} */ ContactManager.prototype.oncontactchange = null; /** * @returns {DOMRequest} */ ContactManager.prototype.clear = function () {}; /** * filterOp: equals|startsWith|match * * @param {{filterBy: string[], filterValue: *, filterOp: string, * filterLimit: number}} options * @returns {DOMRequest} * @property {mozContact[]} result */ ContactManager.prototype.find = function (options) {}; /** * sortBy: givenName|familyName * sortOrder: descending|ascending * filterOp: equals|startsWith|match * * @param {{sortBy: string, sortOrder: string, filterBy: string[], * filterValue: *, filterOp: string, filterLimit: number}} options * @returns {DOMRequest} * @property {mozContact[]} result */ ContactManager.prototype.getAll = function (options) {}; /** * @returns {DOMRequest} * @property {number} result */ ContactManager.prototype.getCount = function () {}; /** * @returns {DOMRequest} * @property {number} result */ ContactManager.prototype.getRevision = function () {}; /** * @param {mozContact} contact * @returns {DOMRequest} */ ContactManager.prototype.remove = function (contact) {}; /** * @param {mozContact} contact * @returns {DOMRequest} */ ContactManager.prototype.save = function (contact) {};
88959054f6d5d2a5ea42c2753a70846c708bcadc
[ "JavaScript", "Makefile", "Markdown" ]
15
JavaScript
w2k31984/fxos-ide-helper
001f01c20a688a7eb63b7d29f188e667b932c87a
12862bed8fd6364af1fa526d2795d3f291af8f56
refs/heads/master
<repo_name>floering/mogli<file_sep>/lib/mogli/location.rb module Mogli class Location < Model define_properties :latitude, :longitude, :street, :city, :state, :country, :zip end end <file_sep>/lib/mogli/place.rb module Mogli class Place < Page set_search_type define_properties :phone, :is_community_page, :website, :description # define_properties :id, :name, :location, :category # has_association :checkins, "Checkin" end end <file_sep>/lib/mogli/insight.rb module Mogli class Insight < Model define_properties :id, :name end end<file_sep>/Todo.txt *) move all model related tests to model_spec.rb *) handle picture attributes *) allow embedding into other classes, example: class User < ActiveRecord::Base acts_as_ogli :id=>:facebook_id,:class=>Ogli::User end allows user.facebook.activities or user.facebook_unpopulated.activities 2) Start working on update handling<file_sep>/lib/mogli/checkin.rb module Mogli class Checkin < Model define_properties :id, :message, :created_time, :coordinates, :place creation_properties :message, :place, :coordinates hash_populating_accessor :from, "User" hash_populating_accessor :tags, "User" hash_populating_accessor :place, "Place" hash_populating_accessor :application, "Page" end end
962d16c0153e219bd6c789105bd28002750f94cd
[ "Text", "Ruby" ]
5
Ruby
floering/mogli
2382d65285371d8197c8edf938995650f075b9b9
0de740e8de7becaa82451c92687f9113673223b5
refs/heads/master
<file_sep># JDll java调用dll示例 # 注意 1.示例中身份证读卡器调用的是32位的dll,所以jdk需要安装32位jdk <file_sep>package com.sheliming.dll.idcard; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; public class IDCardReader { public static Map<String,String> getInfos(int type){ return getInfos(null,type); } /** * @Author henry * @Description 读取身份证 * @Date 2019-03-22 9:52 * @Param saveDir 图片存储路径 * @Param type 类型 1:身份证 2:ic卡 * @return java.util.Map<java.lang.String,java.lang.String> */ public static Map<String, String> getInfos(String saveDir, int type){ Map<String, String> paramMap = new HashMap<String, String>(); int ret; int iPort=1001; //USB PORT ret= IDCardDll.INSTANCE.InitComm(iPort); if(ret!=1){ paramMap.put("msg","没有找到读卡器!"); }else{ System.out.println("读卡器连接成功!"); if (type == 1){ paramMap = getCardInfos(ret,paramMap,saveDir); }else{ paramMap = getIcCardNo(paramMap); } } ret= IDCardDll.INSTANCE.CloseComm(); if(ret!=1){ System.out.println("读卡器关闭连接错误!"); }else{ System.out.println("读卡器关闭连接成功!"); } return paramMap; } /** * @Author henry * @Description 获取IC卡 卡号 * @Date 2019-03-22 9:52 * @Param * @return */ private static Map<String,String> getIcCardNo(Map<String,String> paramMap){ try { byte[] sn = new byte[1024]; int res = IDCardDll.INSTANCE.Routon_IC_HL_ReadCardSN(sn); if (res > 0){ IDCardDll.INSTANCE.HID_BeepLED(true,true,200); // 开启蜂鸣 paramMap.put("sn", new String(sn, "GBK").trim()); }else{ paramMap.put("msg","读卡失败!请将卡重新放读卡器上!"); } }catch (UnsupportedEncodingException ex){ ex.printStackTrace(); } return paramMap; } /** * @Author henry * @Description 读取身份证信息 * @Date 2019-03-22 10:06 * @Param * @return */ private static Map<String,String> getCardInfos(int ret, Map<String,String> paramMap, String saveDir){ ret= IDCardDll.INSTANCE.Authenticate(); if(ret!=1){ paramMap.put("msg","读卡失败!请将身份证重新放读卡器上!"); }else{ byte[] Name = new byte[31]; byte[] Gender = new byte[3]; byte[] Folk = new byte[10]; byte[] BirthDay = new byte[9]; byte[] Code = new byte[19]; byte[] Address = new byte[71]; byte[] Agency = new byte[31]; byte[] ExpireStart = new byte[9]; byte[] ExpireEnd = new byte[9]; byte[] directory; //设置照片存放目录 if (saveDir == null || "".equals(saveDir)){ directory = new byte[200]; }else{ directory = saveDir.getBytes(); } ret= IDCardDll.INSTANCE.ReadBaseInfosPhoto(Name, Gender, Folk, BirthDay, Code, Address, Agency, ExpireStart, ExpireEnd, directory); if(ret>0){ System.out.println("信息读取成功!"); try { System.out.println("-----------------------------------------------"); paramMap.put("Name", new String(Name, "GBK").trim()); paramMap.put("Gender", new String(Gender, "GBK").trim()); paramMap.put("Folk", new String(Folk, "GBK").trim()); paramMap.put("BirthDay", new String(BirthDay, "GBK").trim()); paramMap.put("Code", new String(Code, "GBK").trim()); paramMap.put("Address", new String(Address, "GBK").trim()); paramMap.put("Agency", new String(Agency, "GBK").trim()); paramMap.put("ExpireStart", new String(ExpireStart, "GBK").trim()); paramMap.put("ExpireEnd", new String(ExpireEnd, "GBK").trim()); paramMap.put("directory", new String(directory, "GBK").trim()); System.out.println("-----------------------------------------------"); } catch (UnsupportedEncodingException e) { paramMap.put("msg","卡信息异常!"); e.printStackTrace(); } } } return paramMap; } public static void main(String[] args) { System.out.println(getInfos(1).toString()); } }
a881df2ad68624e917c9ad0ec6968cecad01d887
[ "Markdown", "Java" ]
2
Markdown
shelimingming/JDll
16b4642b23bcb0e92f68f36c82670f106950857c
e71d7fe4bc26cc54cc6080edcdb4561cb1a186b4
refs/heads/main
<file_sep>import re import getpass def password_check(passwd): val = True # Get last character of string i.e. char at index position -1 last_char = passwd[len(passwd) - 1] while val: # This is the condition that checks the first character is a capital letter if passwd and not passwd[0].isalpha(): val = False print('First character must always be letter') elif not last_char.isdigit() and not last_char.isalpha(): print("the last digit should always be letter") break elif len(passwd)<1 or len(passwd)>20: print("the password did not meet the required length") #^[a-zA-Z]{3}[0-9]{1,2}$ elif not passwd.isalpha() and not passwd.isdigit(): #elif not passwd.isdigit() or not passwd.isdigit(): print("password can only consist of Latin letters, numbers, dot and minuses") break else: print("The Input string Given Matches the Password Rules") break else: print("the password is not Valid") my_str = getpass.getpass("Enter a password: ") print("The password you entered is" , my_str) password_check(my_str) <file_sep>from itertools import zip_longest #function to take two list def two_list(lst1,lst2): d1=zip_longest(lst1,lst2) #Output:<itertools.zip_longest object at 0x00993C08> # Converting zip object to dict using dict() contructor. return dict(d1) x = list(map(int, input("Enter the values of first list: ").split())) y = list(map(int, input("Enter the values of second list: ").split())) print(two_list(x,y)) <file_sep>#function to take the filename def CalculateIPHits(filename): # Make a dictionary to store IP addresses and their hit counts # and read the contents of the log file line by line IP_LIST = {} Contents = open(filename, "r").readlines( ) # Loop through each line of the logfile for line in Contents: # Split the string to isolate the IP address Ip = line.split(" ")[0] # To Ensure the length of IP Adress if 6 < len(Ip) <= 15: # Increase by 1 if IP exists; else set hit count = 1 IP_LIST[Ip] = IP_LIST.get(Ip, 0) + 1 # sorted function will sort IP in descending and then take first 10 res = sorted(IP_LIST, key=IP_LIST.get, reverse=True)[:10] return res filepath="C:/Users/Harry/PycharmProjects/hacker_Earth/access.log" HitsDictionary = CalculateIPHits(filepath) print (HitsDictionary)
4ded5aa37040a4e5aaad1a73d1975bca4a53d634
[ "Python" ]
3
Python
hdsouza06/python_test_results
88b643d2ec79a56e4a8be26cf4e014a4be9d01aa
9ce3e94c48bd8e87d3f9ae29a3319777f22d7753
refs/heads/master
<file_sep>import React, { Component } from 'react' import classnames from 'classnames' // 仿饿了么头部展示部分 class Header extends Component { constructor(props) { super(props); this.state = { keyWord_arr: ["炸鸡", "面", "奶茶", "披萨", "沙拉", "冒菜", "粥", "米粉", "麻辣烫", "星巴克"] } } render() { const addressName = classnames('addressName', 'textEllipsis'); return ( <div> <div className="header_ele" > <div className="cityAddress"> <i className="address_icon"></i> <span className={addressName}>黄浦区上海市委(人民大道北)</span> </div> <aside className="weatherDay"> <div className="weatherTips"> <h2>26°</h2> <p>多云天</p> </div> <img src="./src/assets/images/weather.png" alt=""/> </aside> </div> <div className="search"> <a href="javascript:;" className="content"> <i className="search_icon"></i> <span>搜索商家、商品名称</span> </a> </div> <div className="keyWord"> <div className="keyWord_value"> { this.state.keyWord_arr.map(function (item) { return <a href="javascript:;">{item}</a> }) } </div> </div> </div> ) } } export default Header;<file_sep>import React, { Component } from 'react' // 高阶组件 const TopComponent = (ComposedComponent, title) => class extends Component { constructor(props) { super(props); this.historyBack = this.historyBack.bind(this); } historyBack() { window.history.back() } render() { return ( <div> <div className="eleHeader_wrapper"> <i className="goBack" onClick={ this.historyBack }><img src="../src/assets/images/goBack.png" alt=""/></i> <h3>{title}</h3> </div> <ComposedComponent></ComposedComponent> </div> ) } } export default TopComponent;<file_sep>const initialState = { swiperItem: [], shopList: [], partsList: { '1': [], '2': [] }, shoppingOnSaleList: { list: [] }, gifsSuggestList: { list: [] }, guessLikesList: { list: [] }, orderList: [{ 'img': 'https://fuss10.elemecdn.com/c/68/94b2bd123225deb521408d8a6ac7djpeg.jpeg?imageMogr/format/webp/thumbnail/!64x64r/gravity/Center/crop/64x64/', 'name': '油焖大虾', 'statue': 1, 'datetime': '2017-08-20 20:42', 'productName': '油焖大虾-精品', 'productNum': 1, 'price': 130.00 }, { 'img': 'https://fuss10.elemecdn.com/a/c1/6e92545fa052027f4f26f9b75c05cjpeg.jpeg?imageMogr/format/webp/thumbnail/!64x64r/gravity/Center/crop/64x64/', 'name': '咸骨煲仔粥爽滑饺子王', 'statue': 1, 'datetime': '2017-08-26 12:03', 'productName': '咸骨粥', 'productNum': 2, 'price': 99.00 }, { 'img': 'https://fuss10.elemecdn.com/f/8d/f29dbf20be425fc12426c0b1f90b7jpeg.jpeg?imageMogr/format/webp/thumbnail/!130x130r/gravity/Center/crop/64x64/', 'name': 'CoCo都可(前门店', 'statue': 0, 'datetime': '2017-08-12 10:02', 'productName': '鲜百香双响炮/大杯', 'productNum': 2, 'price': 180.00 } ] } const home = (state = initialState, action) => { switch (action.type) { case 'ENTRIES': return Object.assign({}, state, action) case 'GETSHOPLIST': return Object.assign({}, state, action) case 'DISCOVERPARTS': return Object.assign({}, state, action) case 'SHOPPINGONSALE': const data = { shoppingOnSaleList: { 'page_title': '天天特价', 'sub_title': '特价商品,一网打尽', 'list': [] } } action.shoppingOnSaleList.query_list.forEach(function (item, index) { if (index > 2) return; const arr = {}; arr['name'] = item['foods'][0].name; arr['image'] = item['foods'][0].image_path; arr['price'] = item['foods'][0].price; arr['delPrice'] = item['foods'][0].original_price; data.shoppingOnSaleList.list.push(arr); }); return Object.assign({}, state, data) case 'GIFSSUGGEST': const gifs_data = { gifsSuggestList: { 'page_title': '限时好礼', 'sub_title': '小积分换豪礼', 'list': [] } } action.gifsSuggestList.forEach(function (item, index) { const arr = {}; arr['name'] = item.title; arr['image'] = item.image_hash; arr['price'] = item.points_required; arr['delPrice'] = item.original_price; gifs_data.gifsSuggestList.list.push(arr); }); return Object.assign({}, state, gifs_data) case 'GUESSLIKES': const guess_data = { guessLikesList: { 'page_title': '美食热推', 'sub_title': '你的口味,我都懂得', 'list': [] } } action.guessLikesList.forEach(function (item, index) { const arr = {}; const items = item['foods'][0]; arr['name'] = items.name; arr['image'] = items.image_hash; arr['price'] = items.price; arr['delPrice'] = ''; guess_data.guessLikesList.list.push(arr); }); return Object.assign({}, state, guess_data) default: return state } } export default home;<file_sep>import React, { Component } from 'react' import '../assets/css/swiper.min.css' import Swiper from '../assets/js/swiper.min.js' // 仿饿了么左右滑动选择 class Iswiper extends Component { constructor(props) { super(props); } componentDidMount() { new Swiper('.swiper-container', { pagination: '.swiper-pagination' }); } render() { const _this = this; const { swiperItem } = this.props; return ( <div className="swiper-container"> <div className="swiper-wrapper"> <SwiperItem swiperItem = {swiperItem} swiperIndex = "1"></SwiperItem> <SwiperItem swiperItem = {swiperItem} swiperIndex = "2"></SwiperItem> </div> <div className="swiper-pagination"></div> </div> ) } }; // 创建滑动区块的小模块 class SwiperItem extends Component { constructor(props) { super(props); } formatImgUrl(imageHash) { let imgUrl = 'https://fuss10.elemecdn.com/'; let imgSize = '.jpeg?imageMogr/format/webp/thumbnail/!90x90r/gravity/Center/crop/90x90/'; imgUrl += imageHash.substr(0, 1) + '/' + imageHash.substr(1, 2) + '/' + imageHash.substr(3) + imgSize; return imgUrl } render() { const _this = this; const { swiperItem, swiperIndex } = this.props; return ( <div className="swiper-slide">{ swiperItem.map(function(item, index){ let itemUi = ''; let limitIndex = swiperIndex == '1' ? index < 8 : index > 7; if(limitIndex){ const itemUiImage = _this.formatImgUrl(item.image_hash); itemUi = <a href={item.link.replace(/eleme:\/\/restaurants\?/g, 'https://h5.ele.me/msite/food/#geohash=wx4g0bmjetr7&#')} className="swiper_item"> <div className="item_content"><img src={itemUiImage} alt=""/></div> <span className="item_title">{item.name}</span> </a> return itemUi; } }) }</div> ) } } export default Iswiper;<file_sep>var express = require('express'); var request = require('request'); var router = express.Router(); // 获取饿了么推荐商家 router.get('/restaurants', function (req, res, next) { request('https://restapi.ele.me/shopping/restaurants?latitude=39.90469&longitude=116.407173&offset=20&limit=20&extras[]=activities&terminal=h5', function (error, response, body) { res.send(body); }) }); module.exports = router;<file_sep>import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux'; import { Provider, connect } from 'react-redux'; import thunk from 'redux-thunk'; import reducer from './src/redux/reducers' import { Router, Route, hashHistory, IndexRoute, HashRouter, BrowserRouter } from 'react-router-dom' import AppRouter from './src/routes/router' import './src/assets/css/base.scss' const store = createStore(reducer, applyMiddleware(thunk)); ReactDOM.render( <Provider store= {store}> <HashRouter> <AppRouter /> </HashRouter> </Provider>, document.getElementById('app') )<file_sep>var express = require('express'); var request = require('request'); var router = express.Router(); // 获取饿了么推荐商家 router.get('/guessLikes', function (req, res, next) { request('https://restapi.ele.me/hotfood/v1/guess/likes?latitude=39.90469&longitude=116.407173&offset=0&limit=3&request_id=93b342b9-3091-4526-bccb-d84cfeeec5ef&tag_id=-1&columns=1', function (error, response, body) { res.send(body); }) }); module.exports = router;<file_sep>import React, { Component } from 'react' import { connect } from 'react-redux'; import { getShopAction, getEntriesAction } from '../redux/actions' import axios from 'axios' import Header from '../components/header' import Swiper from '../components/swiper' import SectionCard from '../components/sectionCard' import '../assets/css/index.scss' // 仿饿了么首页 class Index extends Component { constructor(props) { super(props); } componentWillMount() { const { getShopList, getEntries } = this.props; getShopList(); getEntries(); } render() { const { shopList, swiperItem } = this.props; return ( <div> <Header></Header> <Swiper swiperItem = {swiperItem}></Swiper> <div className="index-title">推荐商家</div> <div className="shoplist">{ shopList.map(function(item, index){ return <SectionCard item={item}></SectionCard> }) } </div> </div> ) } }; function mapStateToProps(state) { return { shopList: state.home.shopList, swiperItem: state.home.swiperItem }; } function mapDispatchToProps(dispatch) { return { getShopList: () => dispatch(getShopAction()), getEntries: () => dispatch(getEntriesAction()) }; } export default connect(mapStateToProps, mapDispatchToProps)(Index);<file_sep>import React, { Component } from 'react' import TopComponent from './topComponent' import { connect } from 'react-redux'; import '../assets/css/discover.scss' // 仿饿了么订单页 class Order extends Component { constructor(props) { super(props); } render() { const { orderList } = this.props; return ( <div className="orderList offsetTop50">{ orderList.map(function(item, index){ return <OrderList data={item} index= {index}></OrderList> }) } </div> ) } }; class OrderList extends Component { constructor(props) { super(props); } render() { const { data, index } = this.props; return ( <a href="javascript:;" className="ordercard"> <div className="ordercard-body"> <div className="ordercard-avatar"> <img src={data.img} alt=""/> </div> <div className="ordercard-content"> <div className="ordercard-head"> <div className="title"> <p className="name">{data.name}<span className="rightIcon"></span></p> <p className="statue">{data.statue == 1 ? '订单已完成' : '未完成'}</p> </div> <p className="datetime">{data.datetime}</p> </div> <div className="ordercard-detail"> <p className="detail"> <span className="productname">{data.productName}</span> <span>等{data.productNum}件商品</span> </p> <p className="price">¥{data.price}</p> </div> </div> </div> { index == 0 ? <div className="ordercard-bottom"><button className="cardbutton">再来一单</button></div> : '' } </a> ) } } function mapStateToProps(state) { return { orderList: state.home.orderList } } export default TopComponent(connect(mapStateToProps)(Order), '订单');<file_sep>import React, { Component } from 'react' import { connect } from 'react-redux'; import TopComponent from './topComponent' import DiscoverRecommend from '../components/discoverRecommend' import { getDiscoverPartsAction, getShoppingOnSaleAction, getGifsSuggestAction, getGuessLikesAction } from '../redux/actions' import '../assets/css/discover.scss' // 仿饿了么发现页 class Discover extends Component { constructor(props) { super(props); } componentWillMount() { const { getDiscoverParts, getShoppingOnSale, getGifsSuggest, getGuessLikes } = this.props; getDiscoverParts(); getShoppingOnSale(); getGifsSuggest(); getGuessLikes(); } render() { const { partsList, shoppingOnSaleList, gifsSuggestList, guessLikesList } = this.props; return ( <div className="Discover offsetTop50"> <section> <DiscoverActivePart list = {partsList['1']} partType = "list"></DiscoverActivePart> <DiscoverActivePart list = {partsList['2']} partType = "subPic"></DiscoverActivePart> </section> <DiscoverRecommend data = {guessLikesList}></DiscoverRecommend> <DiscoverRecommend data = {shoppingOnSaleList}></DiscoverRecommend> <DiscoverRecommend data = {gifsSuggestList}></DiscoverRecommend> </div> ) } }; // 饿了么发现页的活动区块 class DiscoverActivePart extends Component { constructor(props) { super(props); } formatImgUrl(imageHash) { let imgUrl = 'https://fuss10.elemecdn.com/'; let imgSize = '?imageMogr/format/webp/'; let reg = /jpeg$/g; reg.test(imageHash) ? imgSize = '.jpeg' + imgSize : imgSize = '.png' + imgSize; imgUrl += imageHash.substr(0, 1) + '/' + imageHash.substr(1, 2) + '/' + imageHash.substr(3) + imgSize; return imgUrl } render() { const _this = this; const { list, partType } = this.props; const partTypeClass = partType == 'list' ? 'entry list1' : 'entry list2'; return ( <div className={partTypeClass}>{ list.map(function(item,index){ return <a href={item.content_url}> <div className="content_wrapper"> <p className="title" style={{'color': item.title_color}}>{item.title}</p> <p className="tips">{item.subtitle}</p> </div> <img src={_this.formatImgUrl(partType == 'list' ? item.main_pic_hash : item.sub_pic_hash)} alt=""/> </a> }) }</div> ) } } function mapStateToProps(state) { return { partsList: state.home.partsList, shoppingOnSaleList: state.home.shoppingOnSaleList, gifsSuggestList: state.home.gifsSuggestList, guessLikesList: state.home.guessLikesList } } function mapDispatchToProps(dispatch) { return { getDiscoverParts: () => dispatch(getDiscoverPartsAction()), getShoppingOnSale: () => dispatch(getShoppingOnSaleAction()), getGifsSuggest: () => dispatch(getGifsSuggestAction()), getGuessLikes: () => dispatch(getGuessLikesAction()) } } export default TopComponent(connect(mapStateToProps, mapDispatchToProps)(Discover), '发现');<file_sep>import React, { Component } from 'react' import TopComponent from './topComponent' import { connect } from 'react-redux'; import '../assets/css/discover.scss' // 仿饿了么我的 class Profile extends Component { constructor(props) { super(props); } render() { return ( <div className="userOrderList offsetTop50"> <div className="profile-wrpper"> <span className="profile-img"> <img src="../src/assets/images/userHead.png" alt=""/> </span> <div className="profile-name"> <p className="userName">啦啦啦</p> <p className="userPhone"><img src="../src/assets/images/phone.png" alt=""/>135****5000</p> </div> <span className="rightIcon"> <img src="../src/assets/images/arrowRight2.png" alt=""/> </span> </div> <div className="discountsIntegral"> <a href="javascript:;" className="discounts_Wrapper"> <p> <span className="textWeight" style={{color: 'rgb(255, 95, 62)'}}>2</span> <span style={{color: 'rgb(255, 95, 62)'}}>个</span> </p> <p>优惠</p> </a> <a href="javascript:;" className="integral_wrapper"> <p> <span className="textWeight" style={{color: 'rgb(106, 194, 11)'}}>1616</span> <span style={{color: 'rgb(106, 194, 11)'}}>分</span> </p> <p>积分</p> </a> </div> <a href="javascript:;" className="link_item"> <span className="item_icon"><img src="../src/assets/images/address.png" alt=""/></span> <div className="item_value">我的地址<span className="rightIcon"></span></div> </a> <a href="javascript:;" className="link_item"> <span className="item_icon"><img src="../src/assets/images/giftbag.png" alt=""/></span> <div className="item_value">积分商城<span className="rightIcon"></span></div> </a> <a href="javascript:;" className="link_item noBorderBottom"> <span className="item_icon"><img src="../src/assets/images/flower.png" alt=""/></span> <div className="item_value">服务中心<span className="rightIcon"></span></div> </a> <a href="javascript:;" className="link_item noBorderTop mt0"> <span className="item_icon"><img src="../src/assets/images/elm.png" alt=""/></span> <div className="item_value">下载饿了么APP<span className="rightIcon"></span></div> </a> </div> ) } }; export default TopComponent(Profile, '我的');<file_sep>var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var proxy = require('http-proxy-middleware') var NODE_ENV = process.env.NODE_ENV; var plugins = [ new ExtractTextPlugin("css/[name].css"), new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]; var entry = { 'app': [ path.resolve(__dirname, 'app.js') ] } if (NODE_ENV == 'dev') { plugins.push(new webpack.HotModuleReplacementPlugin()); for (var item in entry) { entry[item].unshift('webpack/hot/dev-server'); entry[item].unshift('webpack-dev-server/client?http://127.0.0.1:8080'); } } module.exports = { entry: entry, output: { path: path.resolve(__dirname, 'build'), filename: '[name].js', publicPath: NODE_ENV == 'dev' ? 'http://127.0.0.1:8080/build' : '/build' }, module: { rules: [{ test: /\.js?$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', query: { name: 'assets/[name]-[hash:5].[ext]' } }, { test: /\.scss$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'sass-loader'] }) },{ test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/ }] }, resolve: { extensions: ['.js', '.jsx'], alias: { css: './src/css' } }, plugins: plugins, devtool: NODE_ENV == 'dev' ? 'eval-source-map' : false, devServer: { proxy: { '/api': { target: 'http://localhost:3009/api', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }<file_sep>## 技术栈 react + react-router + react-redux + axios + scss + ES6/7 + webpack + node ## 项目运行 这个项目使用了node提供后端接口,webpack中使用了代理本地3009接口获取数据,而server中,通过访问这个路由时去爬取饿了么h5端的数据,开启项目之前要先启动本地服务 ``` git clone https://github.com/qiuyuquan/React-Elm.git cd React-Elm cd server npm install npm run start (开启本地服务) cd ../ npm install npm run dev 访问 http://localhost:8088 ``` ## 说明 > 这个项目主要是理解react的基本开发,以及react+redux的结合基本使用 > 由于项目不是实际开发,所以项目有一些数据使用固定数据,这个项目主要是用于react、redux入门系列,引导对于一些不熟悉react的入门。 > 如果npm install 下载某些依赖包失败的话,推荐使用淘宝的注册源 ``` npm install -g cnpm --registry=https://registry.npm.taobao.org ``` 然后直接使用淘宝源就可以了 ``` cnpm install ``` ## 项目截图 <div align="center"> <img src="https://github.com/qiuyuquan/React-Elm/blob/master/screenShot/WX20171011-150138%402x.png" width="320" height="568"/> <img src="https://github.com/qiuyuquan/React-Elm/blob/master/screenShot/WX20171011-150211%402x.png" width="320" height="568"/> </div> <div align="center"> <img src="https://github.com/qiuyuquan/React-Elm/blob/master/screenShot/WX20171011-150244%402x.png" width="320" height="568"/> <img src="https://github.com/qiuyuquan/React-Elm/blob/master/screenShot/WX20171011-150304%402x.png" width="320" height="568"/> </div> ## 项目总结 > 组件中如果多个重复使用的方法或者是组件有多个类似的ui功能,但是又不能拆分时,我们可以用react组件的高价组件,说的明白一点就是在exoprt时,把exoprt的这个组件通过传参的形式,植入到另一个组件中再返回一个新的组件对象 > redux中reducers中,数据不能单独的赋值返回,这样react检测不到你这个数据变化,必需得是返回一整个state对象,我们可以类似这样使用,返回一个全新的state ``` return Object.assign({}, state, data) ``` ## 学习推荐大神链接 [react-pxq](https://github.com/bailicangdu/react-pxq) <file_sep>var home = require('./home'); var restaurants = require('./restaurants'); var discover = require('./discover'); var shoppingOnSale = require('./shoppingOnSale'); var gifsSuggest = require('./gifsSuggest'); var guessLikes = require('./guessLikes'); module.exports = function (app) { app.use('/api', require('./home')); app.use('/api', require('./restaurants')); app.use('/api', require('./discover')); app.use('/api', require('./shoppingOnSale')); app.use('/api', require('./gifsSuggest')); app.use('/api', require('./guessLikes')); }<file_sep>import React, { Component } from 'react' // 发现页推荐模块 class DiscoverRecommend extends Component { constructor(props) { super(props); } formatImgUrl(imageHash) { let imgUrl = 'https://fuss10.elemecdn.com/'; let imgSize = '?imageMogr/format/webp/'; let reg = /jpeg$/g; reg.test(imageHash) ? imgSize = '.jpeg' + imgSize : imgSize = '.png' + imgSize; imgUrl += imageHash.substr(0, 1) + '/' + imageHash.substr(1, 2) + '/' + imageHash.substr(3) + imgSize; return imgUrl } render() { const _this = this; const { data } = this.props; return ( <section> <div className="activity-header"> <span className="line left"></span>{data.page_title}<span className="line right"></span> </div> <p className="activity-sub-title">{data.sub_title}</p> <div className="activity-body">{ data.list.map(function(item, index){ return <a href="javascript:;"> <img src={_this.formatImgUrl(item.image)} alt=""/> <div> <div className="food-info clearfix"> <div className="food-price"> <span className="price ui-ellipsis"><span className="yuan">¥</span>{item.price}</span> <del className="original-price ui-ellipsis">{item.delPrice ? '¥'+item.delPrice : item.delPrice}</del> </div> </div> </div> </a> }) } </div> <p className="activity-more">查看更多</p> </section> ) } } export default DiscoverRecommend;<file_sep>import React, { Component } from 'react'; import { Switch, Router, Route, hashHistory, IndexRoute, HashRouter, Link, NavLink } from 'react-router-dom' import Nav from '../components/nav' import Index from '../view/index' import Discover from '../view/discover' import Order from '../view/order' import Profile from '../view/profile' export default () => ( <div> <Switch> <Route exact path="/" component={Index} /> <Route path="/index" component={Index} /> <Route path="/discover" component={Discover} /> <Route path="/order" component={Order} /> <Route path="/profile" component={Profile} /> </Switch> <Nav></Nav> </div> );<file_sep>import React, { Component } from 'react' import { Switch, Router, Route, hashHistory, IndexRoute, HashRouter, NavLink } from 'react-router-dom' // 仿饿了么底部导航 class Nav extends Component { constructor(props) { super(props); this.state = { nav: [ { 'id': 'index', 'value': '外卖', 'icon': './src/assets/images/ele_icon.png', '_icon': './src/assets/images/_ele_icon.png' }, { 'id': 'discover', 'value': '发现', 'icon': './src/assets/images/discover.png', '_icon': './src/assets/images/_discover.png' }, { 'id': 'order', 'value': '订单', 'icon': './src/assets/images/order.png', '_icon': './src/assets/images/_order.png' }, { 'id': 'profile', 'value': '我的', 'icon': './src/assets/images/user.png', '_icon': './src/assets/images/_user.png' }, ] } } render() { return ( <div className="nav_wrap"> { this.state.nav.map(function (item) { return <NavLink to={'/'+item.id} activeClassName="active" activeStyle={{'color':'#5DA6F1'}}> <i className="defaut_status" style={{'backgroundImage': 'url('+item.icon+')'}}></i> <i className="active_status" style={{'backgroundImage': 'url('+item._icon+')'}}></i> <span>{item.value}</span> </NavLink> }) } </div> ) } }; export default Nav;
92f2123081231ba65c84fb56b9b1777d0d41f08b
[ "JavaScript", "Markdown" ]
17
JavaScript
qiuyuquan/React-Elm
c29986d4f4a0ca2fc5ba8f179665bf52d7a48bb6
99a7facd481eecad7008171eb44aa4d7fe9091d5
refs/heads/master
<repo_name>IUBLibTech/mock_storage_proxy<file_sep>/config.ru require 'bundler' require 'rufus-scheduler' Bundler.require require './storage_proxy' run StorageProxy <file_sep>/storage_proxy.rb class StorageProxy < Sinatra::Base require 'rufus-scheduler' configure :development do register Sinatra::Reloader end # This scheduler's job is to move files from ./storage/queue to ./storage/cache to simulate slow file retrieval. # A file is put into the queue when staged - it's just a renamed copy of a stub file from ./storage/archive. scheduler = Rufus::Scheduler.new scheduler.every '10s' do # Move all files found in the queue to the cache move_to_cache end # Endpoint definitions get '/' do "Some default response goes here" end get '/status/:id' do locate_file(params['id']) end get '/stage/:id' do stage(params['id']) end get '/unstage/:id' do unstage(params['id']) end get '/fixity/:id' do # TODO end get '/some_other_example_endpoint/:id' do "Response for some_other_example_endpoint/#{params['id']} goes here" end private def locate_file(identifier) # TODO # Check for a string in identifier (like foo) mocking a file unknown condition, return error status. # Else check cache in ./storage/cache, return staged status if exists. # Else check queue in ./storage/queue, return staging status if exists. # Else, return a status indicating it isn't staged but is a valid file that can be. [response: "Some response status for #{identifier} goes here"].to_json end def stage(identifier) # TODO # Copy ./storage/archive/stub to ./storage/queue/identifier [response: "Some response indicating stage request received for #{identifier} goes here"].to_json end def self.move_to_cache puts 'Checking staging queue for files' # Sleep so that we don't move new files as soon as they were created - guarantees an asynchronous wait sleep 10 # TODO # Move ./storage/queue/* to ./storage/cache end def unstage(identifier) # TODO # Remove ./storage/cache/identifier [response: "Some response indicating unstage request received for #{identifier} goes here"].to_json end end <file_sep>/Gemfile source 'https://rubygems.org' gem 'sinatra', require: 'sinatra/base' gem 'sinatra-contrib', require: 'sinatra/reloader' gem 'rufus-scheduler' gem 'thin' gem 'json'<file_sep>/README.md # mock_storage_proxy `bundle install` In a dedicated terminal: `rackup -p 4567` Test: ``` curl localhost:4567/ Some default response goes here curl localhost:4567/status/id [{"response":"Some response status for id goes here"}] curl localhost:4567/stage/id [{"response":"Some response indicating stage request received for id goes here"}] curl localhost:4567/unstage/id [{"response":"Some response indicating unstage request received for id goes here"}] ```
db950ff6a813ff21381436c2b6d8ed492ab808c5
[ "Markdown", "Ruby" ]
4
Ruby
IUBLibTech/mock_storage_proxy
d4d7c579b5789ea4ef8c245d5c1b86abb41f40b4
05981df720ad2bfcd95a9c88c1b19b2c2d022c8b
refs/heads/master
<repo_name>idan288/Web-Based-Multiplayer-Battleship-Game<file_sep>/source files/web/js/statistics.js // Constants: const SHIPSIGN = 'O'; const EMPTY = ' '; const HITINGSIGN = 'X'; const MISSSIGN = '-'; const MINESIGN = '*'; const HITMINE = '@'; const roomsURL = 'rooms'; const gameURL = 'game'; // Global vars: let roomName; let userName; $(document).ready(function () { roomName = CookieUtil.GetCookie('roomName'); userName = CookieUtil.GetCookie('userName'); ajaxGetStatisticsGame(); }); function updateGlobalStatistics(statistic) { $('#roomName').text(roomName); $('#totalTurns').text(statistic[0]); $('#gameType').text(statistic[1]); updateTable('#winPShips', statistic[2]); updateTable('#losePShips', statistic[3]); $('#time').text(statistic[4]); } function updateWinPlayerStatistics(statistic) { $('#winPName').text(statistic[0]); $('#winPScore').text(statistic[1]); $('#winPHits').text(statistic[2]); $('#winPMiss').text(statistic[3]); $('#winPAvgAttack').text(statistic[4]); updateBoard('#winPShipsBoard', statistic[5].board); updateBoard('#winPHitsBoard', statistic[6].board); } function updateLoosePlayerStatistics(statistic) { $('#losePName').text(statistic[0]); $('#losePScore').text(statistic[1]); $('#losePHits').text(statistic[2]); $('#losePMiss').text(statistic[3]); $('#losePAvgAttack').text(statistic[4]); updateBoard('#losePShipsBoard', statistic[5].board); updateBoard('#losePHitsBoard', statistic[6].board); } function ajaxGetStatisticsGame() { $.ajax({ data: { requestType: "statistics", roomName: roomName, }, url: gameURL, success: function (statistics) { updateGlobalStatistics(statistics[2]); updateWinPlayerStatistics(statistics[0]); updateLoosePlayerStatistics(statistics[1]); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { console.log("Timeout", "No connection", true); } else if (XMLHttpRequest.readyState === 0) { console.log("Lost connection with server"); } }, timeout: 10000 }); } function updateTable(tableName, arr) { let row; $(tableName).empty(); if (arr != null) { for (let i = 0; i < arr.length; i++) { row = '<tr class="center aligned">' + '<td>' + arr[i].length + '</td>' + '<td>' + arr[i].type + '</td>'; $(row).appendTo($(tableName)); } } } function updateBoard(boardType, board) { let row; let simpleFinish = '></div></td>'; let begin; let ch; $(boardType).empty(); for (let i = 0; i < board.length; i++) { row = '<tr>'; for (let j = 0; j < board.length; j++) { ch = board[i][j]; begin = '<td><div class="boardCell '; switch (ch) { case EMPTY: begin += 'empty" '; break; case SHIPSIGN: begin += 'ship" '; break; case MISSSIGN: begin += 'miss" '; break; case HITINGSIGN: begin += 'hit" '; break; case MINESIGN: begin += 'mine" '; break; case HITMINE: begin += 'hitMine" '; break; default: } row += (begin + simpleFinish); } row += '</tr>'; $(row).appendTo($(boardType)); } } function leaveStatsticsPage() { $.ajax({ data: { requestType: "returnToRooms", }, url: gameURL, success: function (responseJson) { if (typeof responseJson.redirect !== "undefined") { document.location.href = responseJson.redirect; } else if (typeof responseJson.error !== "undefined") { console.log(responseJson.error); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { console.log("Timeout", "No connection", true); } else if (XMLHttpRequest.readyState === 0) { console.log("Lost connection with server"); } }, timeout: 10000 }); } function logout() { $.ajax({ data: { requestType: "logout", userName: userName, }, url: roomsURL, success: function (url) { window.location = url; }, error: function () { console.log("bad thing happend"); } }); } function storageChange(event) { if(event.key === 'logged_in') { logout(); } } window.addEventListener('storage', storageChange, false); <file_sep>/source files/src/GameLogic/XMLReader.java package GameLogic; import javafx.concurrent.Task; import jaxb.schema.generated.BattleShipGame; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.ArrayList; public class XMLReader extends Task<Void> { private static final String JAXB_XML_GAME_PACKAGE_NAME = "jaxb.schema.generated"; private final int PLAYERSNUMBER = 2; private final int MINBOARDSIZE = 5; private final int MAXBOARDSIZE = 20; private static final Integer SLEEP_TIME = 500; // private final int COLUMNROWSHIPLENGTH = 3; private final char SHIPSIGN = 'O'; private final char EMPTY = ' '; private final char TESTEDSHIPSIGN = '@'; private String pathFile; private String[] gameType; private ArrayList<ArrayList<Character>> player1Board; private ArrayList<ArrayList<Character>> player2Board; private ArrayList<BattleShip> battleShipsPlayer1; private ArrayList<BattleShip> battleShipsPlayer2; private int[] mineAmount; private enum BasicDiretionsType { ROW, COLUMN } private enum AdvanceDirectionType { ROW, COLUMN, RIGHT_UP, RIGHT_DOWN, UP_RIGHT, DOWN_RIGHT, } private enum DirectionsPositions { LEFTROW, RIGHTROW, UPCOLUMN, DOWNCOLUMN, } /* public XMLReader(String pathFile, ArrayList<ArrayList<Character>> player1Board, ArrayList<ArrayList<Character>> player2Board, String[] gameType, ArrayList<BattleShip> battleShipsPlayer1, ArrayList<BattleShip> battleShipsPlayer2, int[] mineAmount) { this.pathFile = pathFile; this.gameType = gameType; this.battleShipsPlayer1 = battleShipsPlayer1; this.battleShipsPlayer2 = battleShipsPlayer2; this.player1Board = player1Board; this.player2Board = player2Board; this.mineAmount = mineAmount; } */ @Override protected Void call() throws Exception { loadXML(this.pathFile, this.player1Board, this.player2Board, this.gameType, this.battleShipsPlayer1, this.battleShipsPlayer2, this.mineAmount); return null; } public void loadXML(String pathFile, ArrayList<ArrayList<Character>> player1Board, ArrayList<ArrayList<Character>> player2Board, String[] gameType, ArrayList<BattleShip> battleShipsPlayer1, ArrayList<BattleShip> battleShipsPlayer2, int[] mineAmount) throws InterruptedException { InputStream inputStream; updateMessage("Fetching file"); updateProgress(0, 7); Thread.sleep(SLEEP_TIME); updateMessage("Checking if file exist"); updateProgress(1, 7); try { inputStream = new FileInputStream(pathFile); } catch (FileNotFoundException e) { throw new IllegalArgumentException("File does not exist."); } Thread.sleep(SLEEP_TIME); updateMessage("Checking file extension"); updateProgress(2, 7); String extensionOfFile = getFileExtension(pathFile); if (!extensionOfFile.equals("xml")) { throw new IllegalArgumentException("The extension of file must be .xml"); } try { Thread.sleep(SLEEP_TIME); updateMessage("Checking board size"); updateProgress(3, 7); BattleShipGame battleShipGame = deserializeFrom(inputStream); int boardSize = battleShipGame.getBoardSize(); if (boardSize < MINBOARDSIZE || boardSize > MAXBOARDSIZE) { throw new XMLFileParsingException("board size must be between 5 to 20."); } Thread.sleep(SLEEP_TIME); updateMessage("Checking game type"); updateProgress(4, 7); gameType[0] = battleShipGame.getGameType(); gameType[0] = gameType[0].toUpperCase(); if (!gameType[0].equals("BASIC") && !gameType[0].equals("ADVANCE")) { throw new XMLFileParsingException("game type must be BASIC or ADVANCE."); } List<BattleShipGame.ShipTypes.ShipType> shipTypes = battleShipGame.getShipTypes().getShipType(); Thread.sleep(SLEEP_TIME); updateMessage("Checking ship types"); updateProgress(4, 7); checkShipTypes(shipTypes, gameType[0], boardSize); List<BattleShipGame.Boards.Board> boards = battleShipGame.getBoards().getBoard(); checkBoards(boards, shipTypes, boardSize, gameType[0], player1Board, player2Board, battleShipsPlayer1, battleShipsPlayer2); if (battleShipGame.getMine() != null) { mineAmount[0] = battleShipGame.getMine().getAmount(); } else { mineAmount[0] = 0; } } catch (JAXBException e) { e.printStackTrace(); } } public void loadXML(InputStream inputStream, ArrayList<ArrayList<Character>> player1Board, ArrayList<ArrayList<Character>> player2Board, String[] gameType, ArrayList<BattleShip> battleShipsPlayer1, ArrayList<BattleShip> battleShipsPlayer2, int[] mineAmount) throws Exception { if (inputStream.available() == 0) { throw new XMLFileParsingException("file is empty"); } try { // updateMessage("Checking board size"); // updateProgress(3, 7); BattleShipGame battleShipGame = deserializeFrom(inputStream); int boardSize = battleShipGame.getBoardSize(); if (boardSize < MINBOARDSIZE || boardSize > MAXBOARDSIZE) { throw new XMLFileParsingException("board size must be between 5 to 20."); } // updateMessage("Checking game type"); // updateProgress(4, 7); gameType[0] = battleShipGame.getGameType(); gameType[0] = gameType[0].toUpperCase(); if (!gameType[0].equals("BASIC") && !gameType[0].equals("ADVANCE")) { throw new XMLFileParsingException("game type must be BASIC or ADVANCE."); } List<BattleShipGame.ShipTypes.ShipType> shipTypes = battleShipGame.getShipTypes().getShipType(); // updateMessage("Checking ship types"); // updateProgress(4, 7); checkShipTypes(shipTypes, gameType[0], boardSize); List<BattleShipGame.Boards.Board> boards = battleShipGame.getBoards().getBoard(); checkBoards(boards, shipTypes, boardSize, gameType[0], player1Board, player2Board, battleShipsPlayer1, battleShipsPlayer2); if (battleShipGame.getMine() != null) { mineAmount[0] = battleShipGame.getMine().getAmount(); } else { mineAmount[0] = 0; } } catch (JAXBException e) { throw new XMLFileParsingException("Bad XML File"); } } private void checkBoards(List<BattleShipGame.Boards.Board> boards, List<BattleShipGame.ShipTypes.ShipType> ships, int boadrdsize, String gameType, ArrayList<ArrayList<Character>> player1Board, ArrayList<ArrayList<Character>> player2Board, ArrayList<BattleShip> battleShipsPlayer1, ArrayList<BattleShip> battleShipsPlayer2) throws InterruptedException { int curShipAmount; List<BattleShipGame.Boards.Board.Ship> boardships; if (boards.size() != PLAYERSNUMBER) { throw new XMLFileParsingException("need to be exactly tow game boards."); } // check board ships for the correct amount ships. for (BattleShipGame.ShipTypes.ShipType ship : ships) { for (BattleShipGame.Boards.Board board : boards) { boardships = board.getShip(); curShipAmount = 0; for (BattleShipGame.Boards.Board.Ship boardShip : boardships) { if (boardShip.getShipTypeId().equals(ship.getId())) { curShipAmount++; } } if (curShipAmount != ship.getAmount()) { throw new XMLFileParsingException( String.format("there is %d amount of %s in shipsTypes and in the board ships there is %d", ship.getAmount(), ship.getId(), curShipAmount)); } } } // Thread.sleep(SLEEP_TIME); // updateMessage("Checking player1 board"); // updateProgress(5, 7); checkShipsPositions(boards.get(0).getShip(), boadrdsize, gameType, 1, player1Board, battleShipsPlayer1, ships); // Thread.sleep(SLEEP_TIME); // updateMessage("Checking player2 board"); // updateProgress(6, 7); checkShipsPositions(boards.get(1).getShip(), boadrdsize, gameType, 2, player2Board, battleShipsPlayer2, ships); // Thread.sleep(SLEEP_TIME); // updateMessage("XML load successfully"); // updateProgress(7, 7); } private void checkShipsPositions(List<BattleShipGame.Boards.Board.Ship> shipsBoard, int boardSize, String gameType, int boardIndex, ArrayList<ArrayList<Character>> playerBoard, ArrayList<BattleShip> battleShips, List<BattleShipGame.ShipTypes.ShipType> ships) { // need to check for the board ships. // if the this is Basic => direction = ROW , COLUMN. // if ADVANCE => direction = RIGHT_DOWN, DOWN_RIGHT, UP_RIGHT,RIGHT_UP, ROW , COLUMN int shipIndex = 1; for (BattleShipGame.Boards.Board.Ship ship : shipsBoard) { if (gameType.equals("BASIC")) { try { BasicDiretionsType.valueOf(ship.getDirection()); } catch (IllegalArgumentException e) { throw new XMLFileParsingException(String.format ("the direction of the ship number %d on board %d is unsupported for this BASIC game type", shipIndex, boardIndex)); } } if (gameType.equals("ADVANCE")) { try { AdvanceDirectionType.valueOf(ship.getDirection()); } catch (IllegalArgumentException e) { throw new XMLFileParsingException(String.format ("the direction of the ship number %d on board %d is unsupported for this ADVANCE game type", shipIndex, boardIndex)); } } shipIndex++; } // create empty board. char[][] board = new char[boardSize][boardSize]; for (int i = 0; i < boardSize; i++) { for (int j = 0; j < boardSize; j++) { board[i][j] = EMPTY; } } BattleShipGame.ShipTypes.ShipType shipType; shipIndex = 1; String dir; AdvanceDirectionType type; BattleShipGame.Boards.Board.Ship.Position resPos = new BattleShipGame.Boards.Board.Ship.Position(); ArrayList<BattleShipGame.Boards.Board.Ship.Position> positions; // boolean valid = true; for (BattleShipGame.Boards.Board.Ship ship : shipsBoard) { dir = ship.getDirection().toUpperCase(); type = AdvanceDirectionType.valueOf(dir); shipType = getShipTypeById(ship.getShipTypeId(), ships); positions = getShipPossitionArr(type, ship.getPosition(), shipType.getLength()); switch (type) { case ROW: checkValidROWPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; case COLUMN: checkValidCOLUMNPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; case RIGHT_UP: checkValidRIGHT_UPPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; case UP_RIGHT: checkValidUP_RIGHTPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; case DOWN_RIGHT: checkValidDOWN_RIGHTTPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; case RIGHT_DOWN: checkValidRIGHT_DOWNTPosition(board, boardSize, ship.getPosition(), boardIndex, shipIndex, shipType.getLength()); break; } battleShips.add(new BattleShip(shipIndex, ship.getDirection(), shipType.getLength(), shipType.getScore(), positions)); shipIndex++; } copyToPlayerBoard(board, boardSize, playerBoard); } private ArrayList<BattleShipGame.Boards.Board.Ship.Position> getShipPossitionArr(AdvanceDirectionType type, BattleShipGame.Boards.Board.Ship.Position pos, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; ArrayList<BattleShipGame.Boards.Board.Ship.Position> positions = new ArrayList<>(); BattleShipGame.Boards.Board.Ship.Position mypos = new BattleShipGame.Boards.Board.Ship.Position(); mypos.setY(pos.getY()); mypos.setX(pos.getX()); switch (type) { case ROW: getPositionsOneSquence(positions, DirectionsPositions.LEFTROW, mypos, length); break; case COLUMN: getPositionsOneSquence(positions, DirectionsPositions.DOWNCOLUMN, mypos, length); break; case UP_RIGHT: getPositionsOneSquence(positions, DirectionsPositions.LEFTROW, mypos, length); mypos.setX(mypos.getX() + 1); getPositionsOneSquence(positions, DirectionsPositions.DOWNCOLUMN, mypos, length - 1); break; case DOWN_RIGHT: getPositionsOneSquence(positions, DirectionsPositions.LEFTROW, mypos, length); mypos.setX(x); getPositionsOneSquence(positions, DirectionsPositions.UPCOLUMN, mypos, length - 1); break; case RIGHT_DOWN: getPositionsOneSquence(positions, DirectionsPositions.DOWNCOLUMN, mypos, length); mypos.setY(y); getPositionsOneSquence(positions, DirectionsPositions.RIGHTROW, mypos, length - 1); break; case RIGHT_UP: getPositionsOneSquence(positions, DirectionsPositions.UPCOLUMN, mypos, length); mypos.setY(y); getPositionsOneSquence(positions, DirectionsPositions.RIGHTROW, mypos, length - 1); break; } return positions; } private void getPositionsOneSquence(ArrayList<BattleShipGame.Boards.Board.Ship.Position> positions , DirectionsPositions type, BattleShipGame.Boards.Board.Ship.Position pos, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; switch (type) { case LEFTROW: for (int i = 0; i < length; i++) { BattleShipGame.Boards.Board.Ship.Position p = new BattleShipGame.Boards.Board.Ship.Position(); p.setX(x); p.setY(y + i); positions.add(p); } break; case RIGHTROW: for (int i = 0; i < length; i++) { BattleShipGame.Boards.Board.Ship.Position p = new BattleShipGame.Boards.Board.Ship.Position(); p.setX(x); p.setY(y - i); positions.add(p); } break; case DOWNCOLUMN: for (int i = 0; i < length; i++) { BattleShipGame.Boards.Board.Ship.Position p = new BattleShipGame.Boards.Board.Ship.Position(); p.setX(x + i); p.setY(y); positions.add(p); } break; case UPCOLUMN: for (int i = 0; i < length; i++) { BattleShipGame.Boards.Board.Ship.Position p = new BattleShipGame.Boards.Board.Ship.Position(); p.setX(x - i); p.setY(y); positions.add(p); } break; } } private BattleShipGame.ShipTypes.ShipType getShipTypeById(String shipID, List<BattleShipGame.ShipTypes.ShipType> ships) { for (BattleShipGame.ShipTypes.ShipType ship : ships) { if (ship.getId().equals(shipID)) { return ship; } } return null; } private void copyToPlayerBoard(char[][] board, int boardSize, ArrayList<ArrayList<Character>> playerBoard) { for (int i = 0; i < boardSize; i++) { playerBoard.add(new ArrayList<>(boardSize)); for (int j = 0; j < boardSize; j++) { playerBoard.get(i).add(j, board[i][j]); } } } private void checkValidRIGHT_UPPosition(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; BattleShipGame.Boards.Board.Ship.Position mypos = new BattleShipGame.Boards.Board.Ship.Position(); mypos.setY(pos.getY()); mypos.setX(pos.getX()); chechCOLUMNFROMDOWN(board, boardSize, mypos, boardIndex, shipIndex, length); mypos.setY(y); checkROWFROMRIGHT(board, boardSize, mypos, boardIndex, shipIndex, length - 1); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x - i][y] = SHIPSIGN; } // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x][y - i] = SHIPSIGN; } } private void checkValidROWPosition(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { //check ship one each other. // check ship for out of bound. int x = pos.getX() - 1; int y = pos.getY() - 1; checkROW(board, boardSize, pos, boardIndex, shipIndex, length); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x][y + i] = SHIPSIGN; } } private boolean checkPositionSurrounding(char[][] board, int boardSize, int x, int y, BattleShipGame.Boards.Board.Ship.Position resPos) { // check for up if (x - 1 > -1 && board[x - 1][y] == SHIPSIGN) { resPos.setY(y); resPos.setX(x - 1); return false; } //down if (x + 1 < boardSize && board[x + 1][y] == SHIPSIGN) { resPos.setY(y); resPos.setX(x + 1); return false; } //left if (y - 1 > -1 && board[x][y - 1] == SHIPSIGN) { resPos.setY(y - 1); resPos.setX(x); return false; } // right if (y + 1 < boardSize && board[x][y + 1] == SHIPSIGN) { resPos.setY(y + 1); resPos.setX(x); return false; } // up left if (x - 1 > -1 && y - 1 > -1 && board[x - 1][y - 1] == SHIPSIGN) { resPos.setY(y - 1); resPos.setX(x - 1); return false; } // down left if (x + 1 < boardSize && y - 1 > -1 && board[x + 1][y - 1] == SHIPSIGN) { resPos.setY(y - 1); resPos.setX(x + 1); return false; } // up right if (x - 1 > -1 && y + 1 < boardSize && board[x - 1][y + 1] == SHIPSIGN) { resPos.setY(y + 1); resPos.setX(x - 1); return false; } // down right if (x + 1 < boardSize && y + 1 < boardSize && board[x + 1][y + 1] == SHIPSIGN) { resPos.setY(y + 1); resPos.setX(x + 1); return false; } return true; } private void checkROWFROMRIGHT(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; //check th Row part of the ship for (int i = 0; i < length; i++) { if (x < 0 || x >= boardSize || y - i < 0 || y - i >= boardSize) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d beyond the scope of the board the first problematic position in row = %d col = %d", boardIndex, shipIndex, pos.getX(), pos.getY() - i)); } if (board[x][y - i] != EMPTY) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d has conflict position in row = %d col = %d with another ship", boardIndex, shipIndex, pos.getX(), pos.getY() - i)); } else { board[x][y - i] = TESTEDSHIPSIGN; } } boolean valid; BattleShipGame.Boards.Board.Ship.Position resPos = new BattleShipGame.Boards.Board.Ship.Position(); // check of none one space between ships. for (int i = 0; i < length; i++) { valid = checkPositionSurrounding(board, boardSize, x, y - i, resPos); if (!valid) { throw new XMLFileParsingException(String.format( "on board %d the ship number %d has linking with other ship on position row = %d col = %d", boardIndex, shipIndex, resPos.getX() + 1, resPos.getY() + 1)); } } } private void chechCOLUMNFROMDOWN(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; for (int i = 0; i < length; i++) { if (x - i < 0 || x - i > boardSize || y < 0 || y > boardSize) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d beyond the scope of the board the first problematic position in row = %d col = %d", boardIndex, shipIndex, pos.getX() - i, pos.getY())); } if (board[x - i][y] != EMPTY) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d has conflict position in row = %d col = %d with another ship", boardIndex, shipIndex, pos.getX() - i, pos.getY())); } else { board[x - i][y] = TESTEDSHIPSIGN; } } boolean valid; BattleShipGame.Boards.Board.Ship.Position resPos = new BattleShipGame.Boards.Board.Ship.Position(); // check of none one space between ships. for (int i = 0; i < length; i++) { valid = checkPositionSurrounding(board, boardSize, x - i, y, resPos); if (!valid) { throw new XMLFileParsingException(String.format( "on board %d the ship number %d has linking with other ship on position row = %d col = %d", boardIndex, shipIndex, resPos.getX() + 1, resPos.getY() + 1)); } } } private void checkValidDOWN_RIGHTTPosition(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; BattleShipGame.Boards.Board.Ship.Position mypos = new BattleShipGame.Boards.Board.Ship.Position(); mypos.setY(pos.getY()); mypos.setX(pos.getX()); checkROW(board, boardSize, mypos, boardIndex, shipIndex, length); mypos.setX(x); chechCOLUMNFROMDOWN(board, boardSize, mypos, boardIndex, shipIndex, length - 1); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x - i][y] = SHIPSIGN; } // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x][y + i] = SHIPSIGN; } } private void checkValidRIGHT_DOWNTPosition(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; BattleShipGame.Boards.Board.Ship.Position mypos = new BattleShipGame.Boards.Board.Ship.Position(); mypos.setY(pos.getY()); mypos.setX(pos.getX()); //check th Column part of the ship checkCOLUMN(board, boardSize, mypos, boardIndex, shipIndex, length); mypos.setY(y); checkROWFROMRIGHT(board, boardSize, mypos, boardIndex, shipIndex, length - 1); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x + i][y] = SHIPSIGN; } // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x][y - i] = SHIPSIGN; } } private void checkValidUP_RIGHTPosition(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; BattleShipGame.Boards.Board.Ship.Position mypos = new BattleShipGame.Boards.Board.Ship.Position(); mypos.setY(pos.getY()); mypos.setX(pos.getX()); //check th Column part of the ship checkCOLUMN(board, boardSize, mypos, boardIndex, shipIndex, length); mypos.setY(y + 2); //check th Row part of the ship checkROW(board, boardSize, mypos, boardIndex, shipIndex, length - 1); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x + i][y] = SHIPSIGN; } // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x][y + i] = SHIPSIGN; } } private void checkROW(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; for (int i = 0; i < length; i++) { if (x < 0 || x >= boardSize || y + i < 0 || y + i >= boardSize) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d beyond the scope of the board the first problematic position in row = %d col = %d", boardIndex, shipIndex, pos.getX(), pos.getY() + i)); } if (board[x][y + i] != EMPTY) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d has conflict position in row = %d col = %d with another ship", boardIndex, shipIndex, pos.getX(), pos.getY() + i)); } else { board[x][y + i] = TESTEDSHIPSIGN; } } boolean valid; BattleShipGame.Boards.Board.Ship.Position resPos = new BattleShipGame.Boards.Board.Ship.Position(); // check of none one space between ships. for (int i = 0; i < length; i++) { valid = checkPositionSurrounding(board, boardSize, x, y + i, resPos); if (!valid) { throw new XMLFileParsingException(String.format( "on board %d the ship number %d has linking with other ship on position row = %d col = %d", boardIndex, shipIndex, resPos.getX() + 1, resPos.getY() + 1)); } } } private void checkCOLUMN(char[][] board, int boardSize, BattleShipGame.Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { int x = pos.getX() - 1; int y = pos.getY() - 1; // check first column part of the ship for (int i = 0; i < length; i++) { if (x + i < 0 || x + i > boardSize || y < 0 || y > boardSize) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d beyond the scope of the board the first problematic position in row = %d col = %d", boardIndex, shipIndex, pos.getX() + i, pos.getY())); } if (board[x + i][y] != EMPTY) { throw new XMLFileParsingException(String.format ("on board %d the ship number %d has conflict position in row = %d col = %d with another ship", boardIndex, shipIndex, pos.getX() + i, pos.getY())); } else { board[x + i][y] = TESTEDSHIPSIGN; } } boolean valid; BattleShipGame.Boards.Board.Ship.Position resPos = new BattleShipGame.Boards.Board.Ship.Position(); // check of none one space between ships. for (int i = 0; i < length; i++) { valid = checkPositionSurrounding(board, boardSize, x + i, y, resPos); if (!valid) { throw new XMLFileParsingException(String.format( "on board %d the ship number %d has linking with other ship on position row = %d col = %d", boardIndex, shipIndex, resPos.getX() + 1, resPos.getY() + 1)); } } } private void checkValidCOLUMNPosition(char[][] board, int boardSize, BattleShipGame. Boards.Board.Ship.Position pos, int boardIndex, int shipIndex, int length) { //check ship one each other. int x = pos.getX() - 1; int y = pos.getY() - 1; checkCOLUMN(board, boardSize, pos, boardIndex, shipIndex, length); // all good so change the TESTEDSIGN to SHIPSIGN. for (int i = 0; i < length; i++) { board[x + i][y] = SHIPSIGN; } } private void checkShipTypes(List<BattleShipGame.ShipTypes.ShipType> ships, String gameType, int boardSize) { if (ships.isEmpty()) { throw new XMLFileParsingException("there is no ships, game must contains at least one ship."); } for (BattleShipGame.ShipTypes.ShipType ship : ships) { if (ship.getAmount() == 0) { throw new XMLFileParsingException("there is ship with Amount = 0"); } if (gameType.equals("BASIC") && !ship.getCategory().toUpperCase().equals("REGULAR")) { throw new XMLFileParsingException("there is unmatched ship category to the game type, category should be REGULAR"); } if (gameType.equals("ADVANCE") && !ship.getCategory().toUpperCase().equals("REGULAR") && !ship.getCategory().toUpperCase().equals("L_SHAPE")) { throw new XMLFileParsingException("there is unmatched ship category to the game type, category should be REGULAR or L_SHAPE"); } } // check if there is just one of ShipId each ship in shipsType. String shipId; int amoutOfShipId; for (BattleShipGame.ShipTypes.ShipType checkedShip : ships) { shipId = checkedShip.getId(); amoutOfShipId = 0; for (BattleShipGame.ShipTypes.ShipType ship : ships) { if (shipId.equals(ship.getId())) { amoutOfShipId++; } } if (amoutOfShipId != 1) { throw new XMLFileParsingException(String.format("there is duplicates ships type id on the type id: %s", shipId)); } } // check if the all the length is bigger then 0 and less then BoardSize. for (BattleShipGame.ShipTypes.ShipType ship : ships) { if (ship.getLength() < 1 || ship.getLength() > boardSize) { throw new XMLFileParsingException(String.format ("the ship id %s has wrong length, the length need to be 1 up to %d, and the ship length is: %d", ship.getId(), boardSize)); } } } public String getFileExtension(String pathFile) { if (pathFile.lastIndexOf(".") != -1 && pathFile.lastIndexOf(".") != 0) return pathFile.substring(pathFile.lastIndexOf(".") + 1); else return ""; } private BattleShipGame deserializeFrom(InputStream in) throws JAXBException { JAXBContext context = JAXBContext.newInstance(JAXB_XML_GAME_PACKAGE_NAME); Unmarshaller unmarshaller = context.createUnmarshaller(); return (BattleShipGame) unmarshaller.unmarshal(in); } } <file_sep>/source files/src/servlets/GameServlet.java package servlets; import GameLogic.BattleShip; import com.google.gson.Gson; import constants.Constants; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @WebServlet(name = "GameServlet", urlPatterns = "/game") public class GameServlet extends HttpServlet { private final Gson gson = new Gson(); private RoomsManager roomsManager; private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); String requestType = request.getParameter("requestType"); switch (requestType) { case Constants.CHECK_GAME_START: handleCheckGameStart(request, response); break; case Constants.GET_BOARD: handleGetBoard(request, response); break; case Constants.GET_PLAYER_DETAILS: handlePlayerDetails(request, response); break; case Constants.CLICK_ON_BOARD: handelClickOnboard(request, response); break; case Constants.MINE_PLACE: handelMinePlace(request, response); break; case Constants.GET_GAME_STATUS: handleGetGameStatus(request, response); break; case Constants.GET_PLAYERS_LIST: handleGetPlayerList(request, response); break; case Constants.GET_SHIPS_LIST: handleGetShips(request, response); break; case Constants.MINE_MOVE: handleMineMove(request, response); break; case Constants.GET_STATISTICS: handleStatistics(request, response); break; case Constants.GET_GAMEFINISH: handleGameFinish(request, response); break; case Constants.LEAVE: handleLeave(request, response); break; case Constants.RETURNROOMS: handleExitStatisticsPage(request, response); break; } } private void handleExitStatisticsPage(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, String> result = new HashMap<>(); result.put("redirect", "rooms.html"); String json = gson.toJson(result); response.getWriter().write(json); } private void handleLeave(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); String avgAttackTime = request.getParameter("avgTime"); roomsManager.updateAvgAttack(roomName, userName, avgAttackTime); roomsManager.userWantToLeave(userName, roomName); handleExitStatisticsPage(request, response); } private void handleGameFinish(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); String avgAttackTime = request.getParameter("avgTime"); roomsManager.updateAvgAttack(roomName, userName, avgAttackTime); roomsManager.removeUserFromRoom(roomName, userName); Map<String, String> result = new HashMap<>(); result.put("redirect", "statistics.html"); Cookie roomNameCookie = new Cookie("roomName", roomName); Cookie userNameCookie = new Cookie("userName", userName); roomNameCookie.setPath("/"); userNameCookie.setPath("/"); response.addCookie(roomNameCookie); // so the client side will remember his room id after redirect response.addCookie(userNameCookie); String json = gson.toJson(result); response.getWriter().write(json); } private void handleStatistics(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); ArrayList<ArrayList<Object>> result = roomsManager.getRoomStatistics(roomName); response.getWriter().println(gson.toJson(result)); response.getWriter().flush(); } private void handleMineMove(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); int row = Integer.parseInt(request.getParameter("row")); int col = Integer.parseInt(request.getParameter("col")); Boolean res = roomsManager.makeMineMove(roomName, userName, row, col); response.getWriter().println(gson.toJson(res)); response.getWriter().flush(); } private void handleGetShips(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); ArrayList<ArrayList<BattleShip>> result = new ArrayList<>(2); roomsManager.getShips(result, roomName, userName); response.getWriter().println(gson.toJson(result)); response.getWriter().flush(); } private void handleGetPlayerList(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String res = gson.toJson(roomsManager.getPlayerLists(roomName)); response.getWriter().println(res); response.getWriter().flush(); } private void handleGetGameStatus(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); String res = gson.toJson(roomsManager.getGameStatus(roomName, userName)); response.getWriter().println(res); response.getWriter().flush(); } private void handelMinePlace(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); int row = Integer.parseInt(request.getParameter("row")); int col = Integer.parseInt(request.getParameter("col")); String res = gson.toJson(roomsManager.isMineLegal(roomName, userName, row, col)); response.getWriter().println(res); response.getWriter().flush(); } private void handelClickOnboard(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); int row = Integer.parseInt(request.getParameter("row")); int col = Integer.parseInt(request.getParameter("col")); String res = gson.toJson(roomsManager.clickOnBoard(roomName, userName, row, col)); response.getWriter().println(res); response.getWriter().flush(); } private void handleGetBoard(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); String boardType = request.getParameter("boardType"); String board = gson.toJson(roomsManager.getBoard(roomName, userName, boardType)); response.getWriter().println(board); response.getWriter().flush(); } private void handlePlayerDetails(HttpServletRequest request, HttpServletResponse response) throws IOException { String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); String playerDetails = gson.toJson(roomsManager.getPlayerDetails(roomName, userName)); response.getWriter().println(playerDetails); response.getWriter().flush(); } private void handleCheckGameStart(HttpServletRequest request, HttpServletResponse response) throws IOException { if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } String roomName = request.getParameter("roomName"); String userName = request.getParameter("userName"); ArrayList<Object> result = new ArrayList<>(3); if (roomsManager.startGameRoom(roomName)) { // the game can start. // result = new Pair<>(true, roomsManager.getPlayerLists(roomName)); result.add(true); result.add(roomsManager.getPlayerLists(roomName)); result.add(roomsManager.thisIsPlayerTurn(roomName, userName)); result.add(roomsManager.getOppPlayerName(roomName, userName)); } else { // missing player. result.add(false); result.add(roomsManager.getPlayerLists(roomName)); result.add(roomsManager.thisIsPlayerTurn(roomName, userName)); } response.getWriter().println(gson.toJson(result)); response.getWriter().flush(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }<file_sep>/source files/src/GameLogic/XMLFileParsingException.java package GameLogic; public class XMLFileParsingException extends RuntimeException { public XMLFileParsingException() { } public XMLFileParsingException(String message) { super(message); } public XMLFileParsingException(Throwable cause) { super(cause); } public XMLFileParsingException(String message, Throwable cause) { super(message, cause); } @Override public String getMessage() { return super.getMessage(); } }<file_sep>/source files/src/GameLogic/BattleShip.java package GameLogic; import jaxb.schema.generated.BattleShipGame; import java.util.ArrayList; public class BattleShip { private String type; private int length; private int score; private int serialNumber; private ArrayList<BattleShipGame.Boards.Board.Ship.Position> shipPosition; public BattleShip() { } public BattleShip(int serialNum, String type, int length, int score, ArrayList<BattleShipGame.Boards.Board.Ship.Position> positions) { serialNumber = serialNum; this.type = type; this.length = length; this.score = score; shipPosition = positions; } public int getScore() { return score; } public int getSerialNumber() { return serialNumber; } public ArrayList<BattleShipGame.Boards.Board.Ship.Position> getShipPosition() { return shipPosition; } public int getLength() { return length; } public ArrayList<BattleShipGame.Boards.Board.Ship.Position> getshipPostion() { return shipPosition; } public String getType() { return type; } } <file_sep>/source files/web/js/room.js const roomsURL = "rooms"; let userName = ""; let selectedRoomDetails = []; let refreshRate = 1000; //miliseconds function refreshUsersList(users) { let trString; //clear all current users $("#usersList").empty(); $.each(users || [], function (index, element) { if (element === userName) { trString = '<tr style="background-color: #99eb94">'; } else { trString = '<tr>'; } $(trString + '<td>' + '<i class="user icon"></i>' + element + '</td>' + '</tr>').appendTo($("#usersList")); }); } function ajaxUsersList() { $.ajax({ data: {requestType: "userList"}, url: roomsURL, success: function (users) { refreshUsersList(users); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showRoomMsg('Timeout, No connection'); } else if (XMLHttpRequest.readyState === 0) { showRoomMsg('Lost connection with server'); } }, timeout: 10000 }); } function refreshRoomsList(rooms) { $("#roomsList").empty(); let trStr; let classType; let style; $.each(rooms || [], function (index, element) { if (selectedRoomDetails[0] === element.roomName) { classType = 'active'; } else { classType = ''; } if (element.numofPlayerInRoom == 2) { style = 'style="background-color: #a3ffba"'; } else { style = ''; } trStr = '<tr class="' + classType + '" onclick="getdata(this)" ' + style + '>'; $(trStr + '<td>' + element.roomName + '</td>' + '<td>' + element.createdBy + '</td>' + '<td>' + element.boardSize + '</td>' + '<td>' + element.gameType + '</td>' + '<td>' + element.numofPlayerInRoom + '</td>' + '</tr>').appendTo($("#roomsList")); }); } function ajaxGetMyUserName() { $.ajax({ data: {requestType: "userName"}, url: roomsURL, success: function (name) { userName = name; }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showRoomMsg('Timeout, No connection'); } else if (XMLHttpRequest.readyState == 0) { showRoomMsg('Lost connection with server'); } } , timeout: 10000 }) ; } function ajaxRoomsList() { $.ajax({ data: {requestType: "roomList"}, url: roomsURL, success: function (rooms) { refreshRoomsList(rooms); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showRoomMsg('Timeout, No connection'); } else if (XMLHttpRequest.readyState == 0) { showRoomMsg('Lost connection with server'); } }, timeout: 10000 }); } function refreshPageData() { ajaxUsersList(); ajaxRoomsList(); } $("#roomsList").hover(function () { $(this).css('cursor', 'pointer'); }, function () { $(this).css('cursor', 'auto'); }); //activate the timer calls after the page is loaded $(document).ready(function () { setInterval(refreshPageData, refreshRate); ajaxGetMyUserName(); }); function logout() { $.ajax({ data: { requestType: "logout", userName: userName, }, url: roomsURL, success: function (url) { let item; item = window.localStorage.getItem('logged_in'); if (item != null) { item = !item; } else { item = true; } window.localStorage.setItem('logged_in', item); window.location = url; }, error: function () { console.log("bad thing happend"); } }); } function getdata(element) { selectedRoomDetails = []; if ($(element).attr('class') === 'active') { $(element).removeClass('active'); } else { let rows = document.getElementById("roomTable").rows; let x = rows.length; for (let i = 0; i < x; i++) { $(rows[i]).removeClass('active'); } $(element).find('td').each(function () { selectedRoomDetails.push($(this).text()); }); $(element).addClass('active'); } } function showAddRoomModel() { $('.ui.modal.createRoom').modal('setting', 'transition', 'fade').modal('setting', 'closable', false).modal('show').modal('refresh'); $('#gameName').val(""); } function addRoom() { if (document.getElementById("file").files[0]) { //if a file was chosen hideErrMsg(); let formData = new FormData(); formData.append("XMLFile", document.getElementById("file").files[0]); formData.append("requestType", "fileUpload"); formData.append("userName", userName); formData.append("roomName", $('#gameName').val()); formData.append("fileName", $('#file').val()); let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { let msgClassName; if (xhr.readyState === xhr.DONE) { { if ("Room added successfully" === xhr.responseText.trim()) { //if there's something, it's an error msgClassName = 'ui success message'; } else { msgClassName = 'ui negative message'; } $('#errMsg').attr('class', msgClassName).transition('bounce in').text(xhr.responseText); } } }; xhr.open("POST", roomsURL, true); xhr.send(formData); } else { $('#errMsg').transition('bounce in').text("Please choose a file"); } } // click button to enter a room $(document).on("click", "#enterRoom", function (e) { if (selectedRoomDetails[0] != null) { $.ajax({ data: { userName: userName, requestType: "enterRoom", roomName: selectedRoomDetails[0], }, url: roomsURL, success: function (responseJson) { //change to board page if (typeof responseJson.redirect !== "undefined") { document.location.href = responseJson.redirect; } else if (typeof responseJson.error !== "undefined") { showRoomMsg(responseJson.error); } } }); } }); // form in start modal, input user name, and check invalid parameters. $('.ui.form.createRoom').form({ on: 'blur', inline: true, onValid: function () { $('#addbtn').removeClass('disabled'); }, onInvalid: function () { $('#addbtn').addClass('disabled'); }, fields: { name: { identifier: 'name', rules: [ { type: 'regExp[^[a-zA-Z\u0590-\u05FF ]+$]', prompt: "Please enter legal game name.", }, ], }, }, }); function hideErrMsg() { $('#errMsg').attr('class', 'ui negative message').transition('hide'); } function deleteRoom() { if (selectedRoomDetails[0] != null) { $.ajax({ data: { requestType: "deleteRoom", userName: userName, roomName: selectedRoomDetails[0], }, url: roomsURL, success: function (res) { if (res[0]) { selectedRoomDetails = []; } showRoomMsg(res[1]); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showRoomMsg("Timeout", "No connection"); } else if (XMLHttpRequest.readyState === 0) { showRoomMsg("Lost connection with server"); } }, timeout: 10000 }); } } function showRoomMsg(msg) { $('#roomMsg').transition('show').transition('bounce in') .text(msg); setTimeout(function () { $('#roomMsg').transition('fade'); }, 3000); } hideErrMsg(); function storageChange(event) { if (event.key === 'logged_in') { logout(); } } window.addEventListener('storage', storageChange, false); <file_sep>/source files/src/servlets/Room.java package servlets; import GameLogic.*; import jaxb.schema.generated.BattleShipGame; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Room { private String roomName; private ArrayList<PlayerInfo> players = new ArrayList<>(2); private GameLogic gameLogic; private boolean isGameBegin = false; private int mineAmount; private int numofPlayerInRoom = 0; private String createdBy; private String gameType; private int boardSize; private int curPlayerTurn = 0; private String gameStatus = "waiting"; private String gameFinishTime; public Room(String roomName, String gameType, String createdBy, GameLogic gameLogic, int mineAmount) { this.roomName = roomName; this.gameLogic = gameLogic; this.mineAmount = mineAmount; this.createdBy = createdBy; this.gameType = gameType; this.boardSize = gameLogic.getBoardSize(); } public void removeUser(String userName) { removePlayerByName(userName); numofPlayerInRoom--; } private void removePlayerByName(String userName) { for (PlayerInfo p : players) { if (p.getName().equals(userName)) { players.remove(p); break; } } } public void setPlayer(String playerName) { players.add(new PlayerInfo(playerName, 0, players.size())); numofPlayerInRoom++; } public void userWantToLeave(String userName) { removePlayerByName(userName); numofPlayerInRoom--; gameStatus = "leave"; } public Boolean makeMineMove(String userName, int row, int col) { int curUserInd = getIndexOfPlayer(userName); BattleShipGame.Boards.Board.Ship.Position pos = new BattleShipGame.Boards.Board.Ship.Position(); pos.setX(row); pos.setY(col); if (gameLogic.addMine(pos, curUserInd)) { curPlayerTurn = (curPlayerTurn + 1) % 2; return true; } return false; } public void getShips(ArrayList<ArrayList<BattleShip>> ships, String userName) { int oppInd = (getIndexOfPlayer(userName) + 1) % 2; Player p = getPlayer(userName); ships.add(p.getBattleShips()); p = gameLogic.getPlayer(oppInd); ships.add(p.getBattleShips()); } public ArrayList<ArrayList<Character>> getBoard(String userName, String boardType) { Player player = getPlayer(userName); ArrayList<ArrayList<Character>> board; if (boardType.equals("shipsBoard")) { board = player.getBattleShipBoard().getBoard(); } else { board = player.getHitingBoard().getBoard(); } return board; } public Player getWinPlayer() { return gameLogic.getPlayer(curPlayerTurn); } public Player getLosePlayer() { return gameLogic.getPlayer((curPlayerTurn + 1) % 2); } public Boolean isMinePlaceLegal(String userName, int row, int col) { int playerIndex = getIndexOfPlayer(userName); return gameLogic.isValidMinePlace(row, col, playerIndex); } public int getCurPlayerTurn() { return curPlayerTurn; } public String handleClickOnBoard(String userName, int row, int col) { int indexCurPlayer = getIndexOfPlayer(userName); int oppPlayerIndex = (indexCurPlayer + 1) % 2; BattleShipGame.Boards.Board.Ship.Position pos = new BattleShipGame.Boards.Board.Ship.Position(); pos.setX(row); pos.setY(col); GameLogic.GameStatus status = gameLogic.UserMove(pos, indexCurPlayer); players.get(indexCurPlayer).setScore(gameLogic.getPlayer(indexCurPlayer).getScore()); players.get(oppPlayerIndex).setScore(gameLogic.getPlayer(oppPlayerIndex).getScore()); return getStringOfGameStatus(status); } public String getGameStatus(String userName) { String res = gameStatus; switch (gameStatus) { case "run": res = curPlayerTurn == getIndexOfPlayer(userName) ? "myTurn" : "oppTurn"; break; } return res; } private String getStringOfGameStatus(GameLogic.GameStatus status) { switch (status) { case BadChoose: curPlayerTurn = (curPlayerTurn + 1) % 2; return "bad"; case Miss: curPlayerTurn = (curPlayerTurn + 1) % 2; return "miss"; case Win: gameFinishTime = gameLogic.getElpesedTime(); gameStatus = "win"; return "win"; case Hit: return "hit"; case Mine: curPlayerTurn = (curPlayerTurn + 1) % 2; return "hitMine"; } curPlayerTurn = (curPlayerTurn + 1) % 2; return "bad"; } public String getGameFinishTime() { return gameFinishTime; } public Player getPlayer(String name) { return gameLogic.getPlayer(getIndexOfPlayer(name)); } public int getIndexOfPlayer(String name) { for (PlayerInfo p : players) { if (p.getName().equals(name)) { return p.getPlayerIndex(); } } return -1; } public List<PlayerInfo> getPlayerLists() { return players; } public void startGame() { gameLogic.resetGame(); gameLogic.getPlayer(0).setName(players.get(0).getName()); gameLogic.getPlayer(1).setName(players.get(1).getName()); curPlayerTurn = 0; gameStatus = "run"; } public boolean isGameBegin() { return isGameBegin; } public String getGameType() { return gameType; } public int numofPlayerInRoom() { return numofPlayerInRoom; } public int getMineAmount() { return mineAmount; } public GameLogic getGameLogic() { return gameLogic; } public int getBoardSize() { return boardSize; } public String getRoomName() { return roomName; } public String getCreatedBy() { return createdBy; } public boolean isUserNameExists(String userName) { for (PlayerInfo p : players) { if (p.getName().equals(userName)) { return true; } } return false; } } <file_sep>/README.md # Battleship-Game A Web-Based-Multiplayer Battleship game in HTML/JavaScript, with Client-Server coordination.</br> Server side code was written in Java using Tomcat server.</br> > **Notice that you can run the project just with Ex3_war file using Tomcat.** ## Project demonstration ### Login screen : - #### Can't login with same username that already login to the system. - #### Can't login with empty username. ![Login screen](Screenshots/1.png) - #### If the user exceeds the rules, a corresponding error message is displayed. ![Login screen-err1](Screenshots/2.png) ![Login screen-err2](Screenshots/3.png) ### Rooms screen: 1. In this screen are displayed all the online users, when the line of the user himself marked in green. 2. Can be see all the avilabel rooms.</br> In case the room is marked in light green it's mean that this room is full, and the user can't join. 3. Player can upload new game by click on **Create room** button. </br> In case the upload game does not meet the rules, a orresponding error message is displayed that explain the problem. 4. In order to join a room, need to choose one room from the rooms table, the line will marked in grey and then click on</br> **Enter room** button, if the room is not full the user will move to the game page. #### Room screen example. ![Rooms screen](Screenshots/4.png) ![Rooms screen](Screenshots/5.png) ### Game screen: 1. The game automatic began when all the players connect to the game. 2. There is a message box in the center of the screen that show to the user messages about the game staus. - #### The possible messages is: a) Hit, Miss, Plant of mines.</br> b) Who the active player now.</br> c) Server communication error.</br> d) Lose or Win message. #### Game screen example. ![Game screen](Screenshots/6.jpg) ### Board marks: 1. empty square : ![empty square](Screenshots/7.png) 2. ship square : ![ship square](Screenshots/8.png) 3. miss square : ![miss square](Screenshots/9.png) 4. hit square : ![hit square](Screenshots/10.png) 5. mine hit square : ![mine hit square](Screenshots/11.png) 6. mine square : ![mine square](Screenshots/12.png) ### Summary screen: This screen appears when the game is finish. #### Summary screen example. ![Summary screen](Screenshots/13.png) ![Summary screen](Screenshots/14.png) <file_sep>/source files/src/servlets/RoomServlet.java package servlets; import GameLogic.*; import com.google.gson.Gson; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.util.*; @MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5) @WebServlet(name = "RoomsServlet", urlPatterns = {"/rooms"}) public class RoomServlet extends HttpServlet { private RoomsManager roomsManager; private final XMLReader xmlReader = new XMLReader(); private final Gson gson = new Gson(); private void processPostRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); String requestType = request.getParameter("requestType"); if (Objects.equals(requestType, "fileUpload")) { handleXMLFile(request, response); } } private void processGetRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); String requestType = request.getParameter("requestType"); switch (requestType) { case "userName": handleUserName(request, response); break; case "userList": handleUserList(request, response); break; case "roomList": handleRoomList(request, response); break; case "enterRoom": handleEnterRoom(request, response); break; case "logout": handleLogout(request, response); break; case "deleteRoom": handleDeleteRoom(request, response); break; } } private void handleDeleteRoom(HttpServletRequest request, HttpServletResponse response) throws IOException { String username = request.getParameter("userName"); String roomName = request.getParameter("roomName"); ArrayList<Object> res = new ArrayList<>(); Boolean isDeleted; String msg; if (roomsManager.isRoomCreatedBy(roomName, username)) { if (!roomsManager.hasLoginPlayers(roomName)) { roomsManager.deleteRoom(roomName); isDeleted = true; msg = "The room " + roomName + " has deleted."; } else { isDeleted = false; msg = "The room can't being deleted because he have a login players."; } } else { isDeleted = false; msg = "The room can't delete because isn't create by you."; } res.add(isDeleted); res.add(msg); response.getWriter().println(gson.toJson(res)); response.getWriter().flush(); } private void handleEnterRoom(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //user want to enter the room. //check if there is less then 2 player in the room. // so we can add another player. if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } String roomName = request.getParameter("roomName"); String username = request.getParameter("userName"); Map<String, String> result = new HashMap<>(); //user doesn't exist so register them if (roomsManager.checkIfPlayerCanIn(roomName, username)) { // room isn't full roomsManager.addPlayerToRoom(roomName, username); result.put("redirect", "game.html"); Cookie roomNameCookie = new Cookie("roomName", roomName); Cookie userNameCookie = new Cookie("userName", username); Cookie gameTypeCookie = new Cookie("gameType", roomsManager.getGameType(roomName)); roomNameCookie.setPath("/"); userNameCookie.setPath("/"); gameTypeCookie.setPath("/"); response.addCookie(roomNameCookie); // so the client side will remember his room id after redirect response.addCookie(userNameCookie); response.addCookie(gameTypeCookie); } else if (roomsManager.isGameRun(roomName)) { result.put("error", "Game is already running"); } else if (roomsManager.isUserAlreadyExist(roomName, username)) { result.put("error", "You can't play with yourself."); } else { // room is full result.put("error", "Room is full"); } String json = gson.toJson(result); response.getWriter().write(json); } private void handleRoomList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } String roomsList = gson.toJson(roomsManager.getRoomList()); out.println(roomsList); out.flush(); } private void handleLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } roomsManager.removePlayer(request.getParameter("userName")); Utils.SessionUtils.clearSession(request); String json = gson.toJson("index.html"); response.getWriter().write(json); } private void handleUserName(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); String userName = gson.toJson(Utils.SessionUtils.getUsername(request)); out.println(userName); out.flush(); } private void handleUserList(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } String playerListJson = gson.toJson(roomsManager.getPlayerList()); out.println(playerListJson); out.flush(); } private void handleXMLFile(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (roomsManager == null) { roomsManager = Utils.ServletUtils.getRoomsManager(getServletContext()); } Part file = request.getPart("XMLFile"); String fileName = request.getParameter("fileName"); String responseMSG; String roomName = request.getParameter("roomName"); if (roomsManager.isRoomNameExist(roomName)) { responseMSG = "The room name already exist."; } else { if (xmlReader.getFileExtension(fileName).equals("xml")) { try { ArrayList<ArrayList<Character>> player1Board = new ArrayList<>(); ArrayList<ArrayList<Character>> player2Board = new ArrayList<>(); ArrayList<BattleShip> battleShipsPlayer1 = new ArrayList<BattleShip>(); ArrayList<BattleShip> battleShipsPlayer2 = new ArrayList<BattleShip>(); int[] mineAmount = new int[1]; String[] gameType = new String[1]; xmlReader.loadXML(file.getInputStream(), player1Board, player2Board, gameType, battleShipsPlayer1, battleShipsPlayer2, mineAmount); GameLogic gameLogic = new GameLogic(gameType[0], player1Board, player2Board, battleShipsPlayer1, battleShipsPlayer2, "", "", mineAmount[0]); Room room = new Room(roomName, gameType[0], request.getParameter("userName"), gameLogic, mineAmount[0]); roomsManager.addNewRoom(room); responseMSG = "Room added successfully"; } catch (Exception e) { responseMSG = e.getMessage(); } } else { responseMSG = "The extension of file must be .xml"; } } response.getWriter().println(responseMSG); response.getWriter().flush(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processPostRequest(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processGetRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> } <file_sep>/source files/src/servlets/RoomsManager.java package servlets; import GameLogic.BattleShip; import GameLogic.Player; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.util.*; public class RoomsManager implements ServletContextListener { private final ArrayList<String> onlinePlayers = new ArrayList<>(); private final Map<String, Room> roomList = new HashMap<>(); public Boolean makeMineMove(String roomName, String userName, int row, int col) { return roomList.get(roomName).makeMineMove(userName, row, col); } public void userWantToLeave(String userName, String roomName) { roomList.get(roomName).userWantToLeave(userName); } public void removeUserFromRoom(String roomName, String userName) { roomList.get(roomName).removeUser(userName); } public Boolean isPlayerNameExist(String playerName) { for (String pname : onlinePlayers) { if (pname.equals(playerName)) { return true; } } return false; } public String getGameType(String roomName) { Room room = roomList.get(roomName); return room.getGameType(); } public ArrayList<ArrayList<Object>> getRoomStatistics(String roomName) { Room room = roomList.get(roomName); ArrayList<ArrayList<Object>> res = new ArrayList<>(3); // win Player statistics ArrayList<Object> winPStatistics = new ArrayList<>(7); Player winPlayer = room.getWinPlayer(); winPStatistics.add(winPlayer.getName()); winPStatistics.add(winPlayer.getScore()); winPStatistics.add(winPlayer.getNumOfHitting()); winPStatistics.add(winPlayer.getNumOfMisses()); winPStatistics.add(winPlayer.getAverageTime()); winPStatistics.add(winPlayer.getBattleShipBoard()); winPStatistics.add(winPlayer.getHitingBoard()); res.add(winPStatistics); // lose Player statistics ArrayList<Object> losePStatistics = new ArrayList<>(7); Player losePlayer = room.getLosePlayer(); losePStatistics.add(losePlayer.getName()); losePStatistics.add(losePlayer.getScore()); losePStatistics.add(losePlayer.getNumOfHitting()); losePStatistics.add(losePlayer.getNumOfMisses()); losePStatistics.add(losePlayer.getAverageTime()); losePStatistics.add(losePlayer.getBattleShipBoard()); losePStatistics.add(losePlayer.getHitingBoard()); res.add(losePStatistics); // global Statistics ArrayList<Object> global = new ArrayList<>(5); global.add(room.getGameLogic().getTotalTurns()); global.add(room.getGameType()); global.add(winPlayer.getBattleShips()); global.add(losePlayer.getBattleShips()); global.add(room.getGameFinishTime()); res.add(global); return res; } public void getShips(ArrayList<ArrayList<BattleShip>> ships, String roomName, String userName) { roomList.get(roomName).getShips(ships, userName); } public Boolean isMineLegal(String roomName, String userName, int row, int col) { Room room = roomList.get(roomName); return room.isMinePlaceLegal(userName, row, col); } public String getGameStatus(String roomName, String userName) { return roomList.get(roomName).getGameStatus(userName); } public int getMineAmount(String roomName) { Room room = roomList.get(roomName); return room.getMineAmount(); } public String getOppPlayerName(String roomName, String myName) { Room room = roomList.get(roomName); int index = room.getIndexOfPlayer(myName); PlayerInfo p = room.getPlayerLists().get((index + 1) % 2); return p.getName(); } public void addNewOnlinePlayer(String pName) { onlinePlayers.add(pName); } public List<PlayerInfo> getPlayerLists(String roomName) { Room room = roomList.get(roomName); return room.getPlayerLists(); } public Boolean thisIsPlayerTurn(String roomName, String userName) { Room room = roomList.get(roomName); return room.getIndexOfPlayer(userName) == room.getCurPlayerTurn(); } public void removePlayer(String name) { for (String pname : onlinePlayers) { if (pname.equals(name)) { onlinePlayers.remove(pname); return; } } } public boolean checkIfPlayerCanIn(String roomName, String userName) { Room room = roomList.get(roomName); if (room.numofPlayerInRoom() > 1) { return false; } else if (room.isUserNameExists(userName)) { return false; } return true; } public void addPlayerToRoom(String roomName, String playerName) { Room room = roomList.get(roomName); room.setPlayer(playerName); } public ArrayList<String> getPlayerDetails(String roomName, String userName) { ArrayList<String> pDetails = new ArrayList<>(); Room room = roomList.get(roomName); Player p = room.getPlayer(userName); pDetails.add(Integer.toString(p.getMinesAmount())); pDetails.add(Integer.toString(room.getGameLogic().getTotalTurns())); pDetails.add(Integer.toString(p.getNumOfMisses())); pDetails.add(Integer.toString(p.getNumOfHitting())); pDetails.add("00:00:00"); pDetails.add(Integer.toString(room.getIndexOfPlayer(userName))); return pDetails; } public ArrayList<ArrayList<Character>> getBoard(String roomName, String userName, String boardType) { Room room = roomList.get(roomName); return room.getBoard(userName, boardType); } public String clickOnBoard(String roomName, String userName, int row, int col) { Room room = roomList.get(roomName); return room.handleClickOnBoard(userName, row, col); } public Boolean isRoomNameExist(String name) { return roomList.containsKey(name); } public List<String> getPlayerList() { return onlinePlayers; } public List<Room> getRoomList() { return new ArrayList<Room>(roomList.values()); } public void addNewRoom(Room room) { roomList.put(room.getRoomName(), room); } public boolean isGameRun(String roomName) { Room room = roomList.get(roomName); return room.isGameBegin(); } public boolean startGameRoom(String roomName) { Room room = roomList.get(roomName); if (room.numofPlayerInRoom() == 2) { room.startGame(); return true; } return false; } @Override public void contextInitialized(ServletContextEvent servletContextEvent) { servletContextEvent.getServletContext().setAttribute("RoomsManager", this); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } public boolean isRoomCreatedBy(String roomName, String username) { return roomList.get(roomName).getCreatedBy().equals(username); } public void deleteRoom(String roomName) { for (String room : roomList.keySet()) { if (room.equals(roomName)) { roomList.remove(room); break; } } } public boolean hasLoginPlayers(String roomName) { return roomList.get(roomName).numofPlayerInRoom() > 0; } public boolean isUserAlreadyExist(String roomName, String userName) { return roomList.get(roomName).isUserNameExists(userName); } public void updateAvgAttack(String roomName, String userName, String avgAttackTime) { int ind = roomList.get(roomName).getIndexOfPlayer(userName); if (ind != -1) { roomList.get(roomName).getPlayer(userName).updateAverageTime(Long.parseLong(avgAttackTime)); } } } <file_sep>/source files/web/js/game.js // constants: const SHIPSIGN = 'O'; const EMPTY = ' '; const HITINGSIGN = 'X'; const MISSSIGN = '-'; const MINESIGN = '*'; const HITMINE = '@'; const gameURL = 'game'; const roomsURL = 'rooms'; // Global vars let sec = 0; let mineAmount = 0; let roomName; let refreshRate = 1000; let checkGameStartInterval; let checkOppPlayerLeaveInterval; let userName; let oppName; let firstTime = true; let isMyTurnNow = false; let inDisabledMode = false; let turnSec = 0; let avgTime = 0; let numMiss = 0; let numHits = 0; function pad(val) { return val > 9 ? val : "0" + val; } let timer = setInterval(function () { document.getElementById("seconds").innerHTML = pad(++sec % 60); document.getElementById("minutes").innerHTML = pad(parseInt((sec / 60) % 60, 10)); document.getElementById("hours").innerHTML = pad(parseInt(sec / 3600, 10)); }, refreshRate); function allowDrop(ev, row, col, element) { ev.preventDefault(); $.ajax({ data: { requestType: "minePlace", roomName: roomName, userName: userName, row: row, col: col, }, url: gameURL, success: function (isMinePlaceLegal) { if (!isMinePlaceLegal) { $(element).attr('ondrop', ''); $(element).attr('ondragover', ''); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev, row, col, element) { if (mineAmount > 0) { ev.preventDefault(); let data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); $.ajax({ data: { requestType: "mineMove", roomName: roomName, userName: userName, row: row, col: col, }, url: gameURL, success: function (allGood) { if (allGood) { mineAmount--; $('#mine').html('<i id="1" class="bomb icon" draggable="true" ondragstart="drag(event)"></i> Mines amount: ' + mineAmount); if (mineAmount == 0) { $('#mine').html('<i id="1" class="bomb icon"></i> Mines amount: ' + mineAmount); } } else { $(element).attr('class', 'boardCell empty'); $(element).attr('id', row.toString() + col.toString()); $(element).attr('ondrop', 'drop(event,' + row + ',' + col + ',' + 'this)'); $(element).attr('ondragover', 'allowDrop(event,' + row + ',' + col + ',' + 'this)'); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } } , timeout: 10000 }); } } //activate the timer calls after the page is loaded $(document).ready(function () { //The users list is refreshed automatically roomName = CookieUtil.GetCookie('roomName'); userName = CookieUtil.GetCookie('userName'); $('#gameType').text(CookieUtil.GetCookie('gameType')); checkGameStartInterval = setInterval(checkIfGameStarted, refreshRate); }); function checkIfGameStarted() { $.ajax({ data: { requestType: "checkGameStart", roomName: roomName, userName: userName, }, url: gameURL, success: function (response) { updatePlayerList(response[1]); if (response[0]) { //if started showHideMSG("gameIsStart"); clearInterval(checkGameStartInterval); ajaxupdatePlayerGameDetails(); ajaxGetBoard('shipsBoard'); ajaxGetBoard('hitsBoard'); turnSec = parseInt(sec); oppName = response[3]; if (response[2]) { setTimeout(function () { showHideMSG('myTurn'); }, 1000); } checkOppPlayerLeaveInterval = setInterval(checkGameStatusAndUpdateBoards, refreshRate); } else { showHideMSG('gameNotStartYet'); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function dissableElemetsOnTurn() { disableElements('hitsBoard'); disableElements('shipsBoard'); if (mineAmount > 0) { $('#mine').html('<i id="1" class="bomb icon"></i> Mines amount: ' + mineAmount); } $('#leaveBtn').attr('onclick', ''); inDisabledMode = true; } function disableElements(type) { let board = document.getElementById(type).getElementsByClassName('boardCell'); for (let i = 0; i < board.length; i++) { $(board[i]).attr('ondrop', ''); $(board[i]).attr('ondragover', ''); $(board[i]).attr('onclick', ''); } } function enableElements() { ajaxGetBoard('shipsBoard'); ajaxGetBoard('hitsBoard'); if (mineAmount > 0) { $('#mine').html('<i id="1" class="bomb icon" draggable="true" ondragstart="drag(event)"></i> Mines amount: ' + mineAmount); } $('#leaveBtn').attr('onclick', 'leaveGame()'); inDisabledMode = false; } const msg = { gameNotStartYet: "Please wait to other player join the room.", myTurn: "Your turn now make your move!", oppTurn: " Make is move now please wait.", gameIsStart: "Game started.", miss: "Miss!!", hit: "Hit!!", win: "So So Excitement!! You are the Winner!", lose: "You lose the game!", leave: " leave the game!", lostConnection: "Lost connection with server", timeout: "Timeout No connection", }; function showHideMSG(type, content) { let curMsg; curMsg = msg[type]; if (type === 'oppTurn' || type === 'leave') { curMsg = oppName + curMsg; } else if (type === 'error') { curMsg = content; } $('#msgText').text(curMsg); } function ajaxGetBoard(boardType) { $.ajax({ data: { requestType: "getBoard", roomName: roomName, userName: userName, boardType: boardType, }, url: gameURL, success: function (board) { updateBoard(board, boardType); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function updateBoard(board, boardType) { let row; let finishOfShipsBoard; let finishOfHitBoard; let simpleFinish = '></div></td>'; let begin; let id; boardType = '#' + boardType; $(boardType).empty(); let ch; for (let i = 0; i < board.length; i++) { row = '<tr>'; for (let j = 0; j < board.length; j++) { ch = board[i][j]; begin = '<td><div class="boardCell '; switch (ch) { case EMPTY: begin += 'empty" '; break; case SHIPSIGN: begin += 'ship" '; break; case MISSSIGN: begin += 'miss" '; break; case HITINGSIGN: begin += 'hit" '; break; case MINESIGN: begin += 'mine" '; break; case HITMINE: begin += 'hitMine" '; break; default: } if (ch == EMPTY) { if (boardType == '#shipsBoard') { id = i.toString() + j.toString(); finishOfShipsBoard = 'ondrop="drop(event,' + i + ',' + j + ',this)" ondragover="allowDrop(event,' + i + ',' + j + ',this)" ' + 'id="' + id + '"></div></td>'; row += ( begin + finishOfShipsBoard); } else { finishOfHitBoard = 'onclick="clickOnHitsCellBoard(' + i + ',' + j + ',' + 'this' + ')"></div></td>'; row += (begin + finishOfHitBoard); } } else { row += (begin + simpleFinish) } } row += '</tr>'; $(row).appendTo($(boardType)); } } function getAvg() { let avgInt = parseInt(avgTime); let misAndHitsInt = parseInt(numMiss) + parseInt(numHits); if (avgInt !== 0 && (misAndHitsInt) !== 0) { return parseInt(avgInt / misAndHitsInt); } return 0; } function updateAvgSec() { console.log("sec = " + sec); console.log("turnSec = " + turnSec); avgTime += (sec - turnSec); console.log("avg = " + avgTime); } function getAvgStr() { let time = getAvg(); let hours = pad(parseInt(time / 3600)); let minutes = pad(parseInt((time / 60) % 60)); let seconds = pad(parseInt(time % 60)); return hours + ':' + minutes + ':' + seconds; } function clickOnHitsCellBoard(row, col, element) { updateAvgSec(); $.ajax({ data: { requestType: "clickOnBoard", roomName: roomName, userName: userName, row: row, col: col, }, url: gameURL, success: function (result) { let hitResClass; switch (result) { case "hit": hitResClass = 'hit'; turnSec = parseInt(sec); $('#msg').transition('jiggle'); $('#msg').css('background-image', "url('img/hit.gif')"); showHideMSG("hit"); setTimeout(function () { $('#msg').css('background-image', ""); showHideMSG("myTurn"); }, 2000); break; case "miss": hitResClass = 'miss'; itsFirstTime = true; dissableElemetsOnTurn(); $('#msg').transition('jiggle'); showHideMSG("miss"); setTimeout(function () { showHideMSG("oppTurn"); }, 2000); isMyTurnNow = false; break; case "hitMine": hitResClass = 'hitMine'; break; case "win": hitResClass = 'hit'; userWinActions(); break; } $(element).attr('class', 'boardCell ' + hitResClass).attr('onclick', ''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function ajaxGameFinish() { $.ajax({ data: { requestType: "gameFinish", roomName: roomName, userName: userName, avgTime: avgTime, }, url: gameURL, success: function (responseJson) { if (typeof responseJson.redirect !== "undefined") { document.location.href = responseJson.redirect; } else if (typeof responseJson.error !== "undefined") { showHideMSG('error', responseJson.error); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function updateShipTable(table, ships) { let row; $(table).empty(); if (ships != null) { for (let i = 0; i < ships.length; i++) { row = '<tr class="center aligned">' + '<td>' + ships[i].length + '</td>' + '<td>' + ships[i].type + '</td>'; $(row).appendTo($(table)); } } } function ajaxGetShips() { $.ajax({ data: { requestType: "getShips", roomName: roomName, userName: userName, }, url: gameURL, success: function (ships) { updateShipTable('#myShips', ships[0]); updateShipTable('#oppShips', ships[1]); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function checkGameStatusAndUpdateBoards() { ajaxupdatePlayerGameDetails(); if (!isMyTurnNow) { ajaxGetBoard('shipsBoard'); } ajaxGetPlayersList(); ajaxGetGameStatus(); ajaxGetShips(); } function ajaxGetGameStatus() { $.ajax({ data: { requestType: "gameStatus", roomName: roomName, userName: userName, }, url: gameURL, success: function (res) { switch (res) { case 'oppTurn': isMyTurnNow = false; if (!inDisabledMode) { dissableElemetsOnTurn(); showHideMSG("oppTurn"); } break; case 'leave': clearInterval(checkOppPlayerLeaveInterval); $('#msg').transition('jiggle'); showHideMSG('leave'); setTimeout(function () { userWinActions(); }, 2000); break; case 'win': //the status is win, and this is not me => in lose. clearInterval(checkOppPlayerLeaveInterval); userLoseActions(); break; case 'myTurn': isMyTurnNow = true; if (inDisabledMode) { turnSec = parseInt(sec); enableElements(); showHideMSG('myTurn'); } break; } }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus == "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function userLoseActions() { clearInterval(checkOppPlayerLeaveInterval); $('#msg').transition('jiggle'); // $('#msg').css('background-image', "url('img/win.gif')"); showHideMSG("lose"); setTimeout(function () { ajaxGameFinish(); }, 2000); } function userWinActions() { clearInterval(checkOppPlayerLeaveInterval); $('#msg').css('color', 'white'); $('#msg').transition('jiggle'); $('#msg').css('background-image', "url('img/win.gif')"); showHideMSG("win"); setTimeout(function () { ajaxGameFinish(); }, 2000); } function ajaxGetPlayersList() { $.ajax({ data: { requestType: "getPlayersList", roomName: roomName, }, url: gameURL, success: function (playerList) { updatePlayerList(playerList); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function updatePlayerGameDetails(details) { $('#roomName').text(roomName); if (firstTime) { mineAmount = details[0]; } $('#mineAmount').text('Mines amount: ' + mineAmount); $('#totalTurns').text(details[1]); numMiss = details[2]; $('#miss').text(details[2]); numHits = details[3]; $('#hits').text(details[3]); $('#avgAttack').text(getAvgStr()); if (firstTime) { firstTime = false; if (details[5] == 0) { setTimeout(function () { sec = 0; turnSec = 0; }, 900); } else { sec = 0; turnSec = 0; } } } function ajaxupdatePlayerGameDetails() { $.ajax({ data: { requestType: "playerGameDetails", roomName: roomName, userName: userName, }, url: gameURL, success: function (details) { updatePlayerGameDetails(details); }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (textStatus === "timeout") { showHideMSG('timeout'); } else if (XMLHttpRequest.readyState === 0) { showHideMSG("lostConnection"); } }, timeout: 10000 }); } function updatePlayerList(playersList) { $('#playerLists').empty(); if (playersList != null) { for (let i = 0; i < playersList.length; i++) { if (playersList[i].name == userName) { trString = '<tr class="center aligned" style="background-color: #99eb94">'; } else { trString = '<tr class="center aligned">'; } $(trString + '<td>' + playersList[i].name + '</td>' + '<td>' + playersList[i].score + '</td>' + '</tr>' ).appendTo($('#playerLists')); } } } function leaveGame(wantToLogOut) { $.ajax({ data: { requestType: "leave", userName: userName, roomName: roomName, avgTime: avgTime, }, url: gameURL, success: function (responseJson) { if (wantToLogOut === true) { logout(); } else if (typeof responseJson.redirect !== "undefined") { document.location.href = responseJson.redirect; } else if (typeof responseJson.error !== "undefined") { showHideMSG('error', responseJson.error); } }, error: function () { console.log("bad thing happend"); } }); } function logout() { $.ajax({ data: { requestType: "logout", userName: userName, }, url: roomsURL, success: function (url) { window.location = url; }, error: function () { console.log("bad thing happend"); } }); } function storageChange(event) { if (event.key === 'logged_in') { leaveGame(true); } } window.addEventListener('storage', storageChange, false); <file_sep>/source files/web/js/CookieUtil.js const DEFAULTEXP = 30; class CookieUtil { static GetCookie(cname) { let name = cname + '='; let decodedCookie = decodeURIComponent(document.cookie); let cookieArr = decodedCookie.split(';'); for (let i = 0; i < cookieArr.length; i++) { let ch = cookieArr[i]; while (ch.charAt(0) === ' ') { ch = ch.substring(1); } if (ch.indexOf(name) === 0) { return ch.substring(name.length, ch.length); } } return ''; } static SetCookie(cname, cvalue, exdays) { let d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); let expires = 'expires=' + d.toGMTString(); document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/'; } static CheckCookie(cookieName, val) { let name = this.GetCookie(cookieName); if (name !== '' && name !== 'undefined') { return name; // there is a cookieName cookie. } // no cookie, create. this.SetCookie(cookieName, val, DEFAULTEXP); return val; } static SetCookieOnChange(cookieName, value) { let name = this.GetCookie(cookieName); if (name !== value) { this.SetCookie(cookieName, value, DEFAULTEXP); } } }
9ac9016e8af80f2764e8b7f4bdf0905910ece0a8
[ "JavaScript", "Java", "Markdown" ]
12
JavaScript
idan288/Web-Based-Multiplayer-Battleship-Game
26735c8f2867a1d4b3d7311f8da8802440c51eac
26a5dd05344bf448e995e4916bdaf7e4239bd4a1
refs/heads/master
<repo_name>vonweb/quick-mock-middleware<file_sep>/src/index.ts import { join } from 'path' import chokidar from 'chokidar' import matchMock from './matchMock' import getMockData from './getMockData' import { RequestHandler } from 'express' const debug = require('debug')('quick-mock:createMiddleware') export default function createMiddleware(options: Options = {} as any): RequestHandler { const { cwd = process.cwd(), watch = true } = options let mockData = null const paths = [join(cwd, 'mock')] function fetchMockData() { mockData = getMockData({ cwd, // config, // onError(e) { // errors.push(e) // }, }) } function cleanRequireCache() { Object.keys(require.cache).forEach(file => { if ( paths.some(path => { return file.indexOf(path) > -1 }) ) { delete require.cache[file] } }) } fetchMockData() if (watch) { const watcher = chokidar.watch(paths, { ignoreInitial: true, }) watcher.on('all', (event, file) => { debug(`[${event}] ${file}, reload mock data`) cleanRequireCache() fetchMockData() }) } return function mockMiddleware(req, res, next) { // debug('req', req && req.path, debug.enabled, debug.namespace, process.env.DEBUG) const match = mockData && matchMock(req, mockData) if (match) { debug(`mock matched: [${match.method}] ${match.path}`) return match.handler(req, res, next) } else { return next() } } } interface Options { cwd?: string watch?: boolean } <file_sep>/src/getMockData.ts import { existsSync } from 'fs' import bodyParser from 'body-parser' import assert from 'assert' import pathToRegexp from 'path-to-regexp' // import multer from 'multer' import { join } from 'path' import glob from 'glob' import { RequestHandler } from 'express' const debug = require('debug')('quick-mock:getMockData') const VALID_METHODS = ['get', 'post', 'put', 'patch', 'delete'] const BODY_PARSED_METHODS = ['post', 'put', 'patch', 'delete'] function createHandler(method: string, path: string, handler: any): RequestHandler { return function(req, res, next) { if (BODY_PARSED_METHODS.includes(method)) { bodyParser.json({ limit: '5mb', strict: false })(req, res, () => { bodyParser.urlencoded({ limit: '5mb', extended: true })(req, res, () => { sendData() }) }) } else { sendData() } function sendData() { if (typeof handler === 'function') { handler(req, res, next) } else { res.json(handler) } } } } function parseKey(key: string) { let method = 'get' let path = key if (/\s+/.test(key)) { const splited = key.split(/\s+/) method = splited[0].toLowerCase() path = splited[1] // eslint-disable-line } assert( VALID_METHODS.includes(method), `Invalid method ${method} for path ${path}, please check your mock files.` ) return { method, path, } } function normalizeConfig(config: MockConfig) { return Object.keys(config).reduce<MockData[]>((memo, key) => { const handler = config[key] const type = typeof handler assert( type === 'function' || type === 'object', `mock value of ${key} should be function or object, but got ${type}` ) const { method, path } = parseKey(key) const keys = [] const re = pathToRegexp(path, keys) memo.push({ method, path, re, keys, handler: createHandler(method, path, handler), }) return memo }, []) } export function getMockConfigFromFiles(files: string[]): MockConfig { return files.reduce<MockConfig>((memo, mockFile) => { try { const m = require(mockFile) // eslint-disable-line memo = { ...memo, ...(m.default || m), } return memo } catch (e) { throw new Error(e.stack) } }, {}) } function getMockFiles(opts: Options) { const { cwd } = opts const mockFiles = glob .sync('mock/**/*.[jt]s', { cwd, }) .map(p => join(cwd, p)) debug(`load mock data from mock folder, including files ${JSON.stringify(mockFiles)}`) return mockFiles } function getMockConfig(opts): MockConfig { const files = getMockFiles(opts) debug(`mock files: ${files.join(', ')}`) return getMockConfigFromFiles(files) } export default function(opts: Options) { try { return normalizeConfig(getMockConfig(opts)) } catch (e) { console.error('Mock files parse failed') } } interface Options { cwd: string } interface MockConfig { [method_path: string]: any } export interface MockData { method: string path: string re: RegExp keys: pathToRegexp.Key[] handler: RequestHandler } <file_sep>/examples/express.ts import express from 'express' // import mockMiddleware from '../src/index' import mockMiddleware from '../lib/bundle' import path from 'path' const app = express() // const pwd = path.resolve(__dirname) app.use( mockMiddleware({ cwd: path.resolve(__dirname), }) ) app.use((req, res) => { res.send(req.path + '# hhh ') }) app.listen(3333) <file_sep>/README.md # quick-mock-middleware ## 项目介绍 quick-mock-middleware 从[umi-mock](https://github.com/umijs/umi/tree/master/packages/umi-mock)中间件中抽出的,可用于兼容 express、webpack-dev-server 等 ## 安装 ``` yarn add quick-mock-middleware -D ``` ## 使用 ### 参数 | 参数名 | 描述 | | ------ | ------------------------------- | | cwd | 当前目录(默认当前执行目录) | | watch | 是否监控 mock 目录(默认 true) | ### express ```js const app = express() // const pwd = path.resolve(__dirname) app.use(mockMiddleware({ cwd: path.resolve(__dirname) })) ``` ### webpack-dev-server ```js module.exports = { devServer: { before: app => { app.use(mockMiddleware({ cwd: path.resolve(__dirname) })) }, }, } ```
5b70d1db94313ef379667a38f468236f87a26253
[ "Markdown", "TypeScript" ]
4
TypeScript
vonweb/quick-mock-middleware
46bf698461916578b794e042f8bb93e80786a3c9
9d9f1f653ff6938b056f3fd8e725a7182d6bbf01
refs/heads/master
<file_sep># CatvsNoncat-predictor Classifies images as either containing a cat or not using logistic regression. Allows users to upload their own files to test against the algorithm.\ The **catvsnoncat_full_analysis** contains the full analysis of the algorithm. It uses different values of learning rate and compares the reduction in cost function that results from each of them by plotting a graph.\ The **code(log_reg).py** file contains the code to classify images as cat or non-cat. Here specify the name of your image in line 104 of the code and path to the image in line 105. <file_sep>import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage train_dataset = h5py.File('train_catvnoncat.h5',"r") test_dataset = h5py.File('test_catvnoncat.h5',"r") train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features train_set_y = np.array(train_dataset["train_set_y"][:]).reshape((1,209)) # your train set labels test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features test_set_y = np.array(test_dataset["test_set_y"][:]).reshape((1,50)) # your test set labels classes = np.array(test_dataset["list_classes"][:]) m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] x_train_flatten = train_set_x_orig.reshape(m_train,-1).T x_test_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0],-1).T test_set_x = x_test_flatten/255 train_set_x = x_train_flatten/255 def sigmoid(z): return 1/(1+np.exp(-z)) print ("sigmoid(0) = " + str(sigmoid(0))) print ("sigmoid(9.2) = " + str(sigmoid(9.2))) def initialize_with_zeros(dim): w = np.zeros((dim,1)) b = 0 assert(w.shape == (dim,1)) return w,b def propagate(w,x,y,b): m = x.shape[0] z = np.dot(w.T,x) + b a = sigmoid(z) J = -np.sum(y * np.log(a) + ((1-y) * np.log(1-a)))/m db = np.sum(a-y)/m dw = np.dot(x,(a-y).T)/m assert(dw.shape == w.shape) assert(db.dtype == float) cost = np.squeeze(J) assert(cost.shape == ()) grads = {"dw":dw,"db":db} return grads, cost def optimize(w,b,x,y,num_iter,alpha): costs = [] for i in range(num_iter): grads,cost = propagate(w,x,y,b) w = w - grads["dw"]*alpha b = b - grads["db"]*alpha if i%100 == 0: costs.append(cost) params = {"w":w,"b":b} grad = {"w":grads["dw"],"b":grads["db"]} return params, grad, costs def predict(w,x,b): z_cap = np.dot(w.T,x) + b y_cap = sigmoid(z_cap) y_pred = np.zeros((1,x.shape[1])) for i in range(y_cap.shape[1]): if y_cap[0,i]>0.5: y_pred[0][i]=1 else: y_pred[0,i]=0 assert(y_pred.shape == (1,x.shape[1])) return y_pred def model(x_train,y_train,x_test,y_test,num_iters=2000,alpha=0.5): w = np.zeros((x_train.shape[0],1)) b = 0 params,grads,costs = optimize(w,b,x_train,y_train,num_iters,alpha) w = params["w"] b = params["b"] y_pred_test = predict(w,x_test,b) y_pred_train = predict(w,x_train,b) print("train accuracy: {} %".format(100 - np.mean(np.abs(y_pred_train - y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(y_pred_test - y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": y_pred_test, "Y_prediction_train" : y_pred_train, "w" : w, "b" : b, "learning_rate" : alpha, "num_iterations": num_iters} return d d = model(train_set_x,train_set_y,test_set_x,test_set_y) my_image = "cat.jpg" #name of the image you want to test fname = "/home/destroyer/MLimages/" + my_image # here enter the path to your image image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T my_predicted_image = predict(d["w"], my_image,d["w"]) plt.imshow(image) print("y = " + str(np.squeeze(my_predicted_image)) + ", the algorithm predicts a \"" + classes[int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
ab5d94816ee1838dc452885b466039c95567b20f
[ "Markdown", "Python" ]
2
Markdown
sartkap/CatvsNoncat-predictor
343df3ef421932eebda61c6cc679d4c184381d44
b3fad89691ba8b8c1a1051e530a6e16512133ab1
refs/heads/master
<file_sep>var expect = require('chai').expect; describe('default', function () { it('processes CSS with default plugins', function () { var css = require('!raw-loader!../!./support/cases/style.css'); expect(css).to.eql('a { color: blue }\n'); }); it('processes CSS in safe mode', function () { var css = require('!raw-loader!' + '../?parser=postcss-safe-parser!' + './support/cases/broken.css'); expect(css).to.eql('a { color:\n}'); }); it('lets other plugins alter the used plugins', function () { var css = require('!raw-loader!../?rewrite=true!' + './support/cases/style.css'); expect(css).to.eql('a { color: black }\n'); }); it('processes CSS-in-JS', function () { var css = require('!raw-loader!' + '../?parser=postcss-js!' + './support/cases/style.js'); expect(css).to.eql('a {\n color: blue\n}'); }); it('processes CSS with exec', function () { var css = require('!raw-loader!' + '../?exec!' + './support/cases/exec.js'); expect(css).to.eql('a {\n color: green\n}'); }); it('inlines map', function () { var css = require('!raw-loader!../?sourceMap=inline!' + './support/cases/style.css'); expect(css).to.include('/*# sourceMappingURL='); }); });
e346eb4f1caf86cce8049fab43f215767b1c045a
[ "JavaScript" ]
1
JavaScript
paleite/postcss-loader
ec2b13ecd16d4f1b8b5032020cfbe39502cb90f4
b5721fa922c421088f69c902749e1df99d9018ed
refs/heads/master
<repo_name>jansipke/aurora-android<file_sep>/src/nl/jansipke/aurora/android/utils/AuroraDate.java package nl.jansipke.aurora.android.utils; import java.text.ParseException; import java.util.Calendar; public class AuroraDate { private static String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private int year; private int month; private int day; public AuroraDate(int calendarPart, int ago) { Calendar date = Calendar.getInstance(); date.add(calendarPart, -ago); this.year = date.get(Calendar.YEAR); this.month = date.get(Calendar.MONTH) + 1; this.day = date.get(Calendar.DAY_OF_MONTH); } public AuroraDate(int year, int month, int day) throws ParseException { this.year = year; this.month = month; this.day = day; } public AuroraDate(String timestamp) throws ParseException { if (timestamp == null || timestamp.length() != 10) { throw new ParseException("Timestamp needs to be 10 characters long, but is [" + timestamp + "]", 0); } this.year = new Integer(timestamp.substring(0, 4)).intValue(); this.month = new Integer(timestamp.substring(5, 7)).intValue(); this.day = new Integer(timestamp.substring(8, 10)).intValue(); } public int getYear() { return year; } public int getMonth() { return month; } public int getDay() { return day; } public String getMonthString() { return months[month - 1]; } public String getMonthYearString() { return months[month - 1] + " " + year; } public String getYearMonthString() { StringBuffer sb = new StringBuffer(year + "-"); if (month < 10) { sb.append("0"); } sb.append(month); return sb.toString(); } public boolean isWeekend() { Calendar date = Calendar.getInstance(); date.set(year, month - 1, day); return (date.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) || (date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY); } @Override public String toString() { StringBuffer sb = new StringBuffer(year + "-"); if (month < 10) { sb.append("0"); } sb.append(month + "-"); if (day < 10) { sb.append("0"); } sb.append(day); return sb.toString(); } } <file_sep>/src/nl/jansipke/aurora/android/GraphActivity.java package nl.jansipke.aurora.android; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import nl.jansipke.aurora.android.csv.CSVHandler; import nl.jansipke.aurora.android.utils.AuroraDate; import nl.jansipke.aurora.android.utils.AuroraGraph; import nl.jansipke.aurora.android.utils.AuroraHttp; import nl.jansipke.aurora.android.utils.AuroraSerie; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView.LegendAlign; import com.jjoe64.graphview.LineGraphView; public abstract class GraphActivity extends Activity { private int daysAgo = 0; private String graphData = ""; private ProgressDialog progressDialog= null; protected List<AuroraSerie> auroraSeries = null; protected double minYValue = 0; protected double maxYValue = 1; private void drawGraph() { try { AuroraDate auroraDate = new AuroraDate(Calendar.DAY_OF_YEAR, daysAgo); CSVHandler graphCsv = new CSVHandler(graphData); final String[] timestamps = graphCsv.getColumn("timestamp"); GraphView graphView = new LineGraphView(this, auroraDate.toString()) { @Override protected String formatLabel(double value, boolean isValueX) { if (isValueX) { if (value == timestamps.length) { value--; } int index = (int) value; return getHourMin(timestamps[index]); } else { return super.formatLabel(value, isValueX); } } private String getHourMin(String timestamp) { Date date = new Date(Long.parseLong(timestamp) * 1000); SimpleDateFormat format = new SimpleDateFormat("HH:mm"); return format.format(date); } }; for (AuroraSerie auroraSerie : auroraSeries) { String legendName = auroraSerie.getLegendName(); String valueName = auroraSerie.getValueName(); int color = auroraSerie.getColor(); Double[] values = graphCsv.getDoubleColumn(valueName); graphView.addSeries(AuroraGraph.getGraphViewSeries(legendName, color, values)); } graphView.setShowLegend(true); graphView.setLegendAlign(LegendAlign.TOP); graphView.setScalable(true); graphView.setScrollable(true); graphView.setManualYAxisBounds(maxYValue, minYValue); graphView.setViewPort(0, timestamps.length); LinearLayout layout = (LinearLayout) findViewById(R.id.graph); layout.removeAllViews(); layout.addView(graphView); } catch (Exception e) { } } private void getHttpData() { Calendar calendarStart = new GregorianCalendar(); calendarStart.add(Calendar.DATE, -daysAgo); int yearStart = calendarStart.get(Calendar.YEAR); int monthStart = calendarStart.get(Calendar.MONTH); int dayStart = calendarStart.get(Calendar.DAY_OF_MONTH); Calendar calendarEnd = new GregorianCalendar(); calendarEnd.add(Calendar.DATE, 1 - daysAgo); int yearEnd = calendarEnd.get(Calendar.YEAR); int monthEnd = calendarEnd.get(Calendar.MONTH); int dayEnd = calendarEnd.get(Calendar.DAY_OF_MONTH); long start = new GregorianCalendar(yearStart, monthStart, dayStart, 0, 0).getTimeInMillis() / 1000; long end = new GregorianCalendar(yearEnd, monthEnd, dayEnd, 0, 1).getTimeInMillis() / 1000; try { graphData = AuroraHttp.getHttpContent("http://www.tjalk8.nl/pv/get_measurements.php?start=" + start + "&end=" + end); } catch (Exception e) { } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.graph); Button prevButton = (Button) findViewById(R.id.button_prev); prevButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { daysAgo++; updateScreen(); } }); Button nextButton = (Button) findViewById(R.id.button_next); nextButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (daysAgo > 0) { daysAgo--; updateScreen(); } } }); Button thisButton = (Button) findViewById(R.id.button_today); thisButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (daysAgo != 0) { daysAgo = 0; updateScreen(); } } }); updateScreen(); } private void setButtonState() { Button prevButton = (Button) findViewById(R.id.button_prev); Button nextButton = (Button) findViewById(R.id.button_next); Button todayButton = (Button) findViewById(R.id.button_today); if (daysAgo == 0) { prevButton.setEnabled(true); nextButton.setEnabled(false); todayButton.setEnabled(false); } else { prevButton.setEnabled(true); nextButton.setEnabled(true); todayButton.setEnabled(true); } } private void updateScreen() { progressDialog = ProgressDialog.show(this, "", "Loading data...", true); final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { setButtonState(); drawGraph(); progressDialog.dismiss(); } }; new Thread(new Runnable() { public void run() { getHttpData(); handler.sendEmptyMessage(0); } }).start(); } } <file_sep>/README.md # aurora-android Android app for displaying Aurora PV inverter data. This project is a couple of years old and as-is requires a server that feeds the app with certain data. The server and a description of the structure of this data is unavailable. Use this project as a starting point to create an app to display PV inverter data. <file_sep>/src/nl/jansipke/aurora/android/activities/CurrentActivity.java package nl.jansipke.aurora.android.activities; import java.util.ArrayList; import nl.jansipke.aurora.android.GraphActivity; import nl.jansipke.aurora.android.utils.AuroraSerie; import android.graphics.Color; public class CurrentActivity extends GraphActivity { public CurrentActivity() { auroraSeries = new ArrayList<AuroraSerie>(); auroraSeries.add(new AuroraSerie("input1_current", "Input 1", Color.BLUE)); minYValue = 0; maxYValue = 14; } }
cd45c6471eb0205d7e0bf6483c5a90c8cb4a77a6
[ "Markdown", "Java" ]
4
Java
jansipke/aurora-android
c8c1bdc2117f449043190fc9403b8c876a4b3255
aff5e5fe63ab1631c911e6d2f362b1b59706c500
refs/heads/master
<file_sep>from flask import render_template, url_for, redirect, flash, request from flask_login.utils import logout_user from flaskblog.form import RegistrationForm, LoginForm from flaskblog.bootstrap import app, db, bcrypt from flaskblog.models import User, Post from flask_login import login_user, current_user, logout_user, login_required posts = [] @app.get('/home') @app.get('/') def home(): # app.logger.info('%s failed to log in', request) return render_template('home.html', posts=posts, title="First Blog") @app.get('/about') def about(): # app.logger.info('%s failed to log in', request) return render_template('about.html', posts=posts, title="About") @app.route('/register', methods=["GET", "POST"]) def register(): if current_user.is_authenticated: return redirect(url_for('home')) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash( form.password.data).decode('utf-8') user = User(username=form.username.data, email=form.email.data, password=<PASSWORD>) db.session.add(user) db.session.commit() flash(f'Your account has been created! You are able to login', category='success') return redirect(url_for('login')) else: app.logger.info('%s failed to register', request) return render_template('register.html', title='Register', form=form) @app.route('/login', methods=["GET", "POST"]) def login(): if current_user.is_authenticated: return redirect(url_for('home')) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user, remember=form.remember.data) next_page = request.args.get('next') if next_page: return redirect(url_for(next_page)) return redirect(url_for('home')) flash(f'Login unsuccessful . Please check email & password', category='danger') return render_template('login.html', title='Login', form=form) @app.route("/logout") def logout(): logout_user() return redirect(url_for('home')) @app.route("/account") @login_required def account(): return render_template('account.html', title="Account") <file_sep># Flask-blog Blogs are great way to share information. I am taking this project as my learning in Flask & also for my personal hobby of writing blogs ## db queries on terminal - from server import db, User, Post - db.create_all() - db.drop_all() - user1 = User(username = "ak00029" , email="<EMAIL>", password="<PASSWORD>") - db.session.add(user1) - db.session.commit() - User.query.all() - User.query.first() - User.query.get(id) - User.query.filter_by(username='ak00029') - User.query.first().posts <file_sep>from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask import Flask from flask_bcrypt import Bcrypt app = Flask(__name__) bcrypt = Bcrypt(app) login_manager = LoginManager(app) login_manager.login_view = 'login' login_manager.login_message_category = 'info' app.config['SECRET_KEY'] = '64c7f09d88e0edd7a4230c2181f40811' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db' db = SQLAlchemy(app) <file_sep>from flaskblog.bootstrap import app, db from flaskblog.models import User, Post from flaskblog import routes
874f50c19cd9516c598b135751b44a8f5d58b6a6
[ "Markdown", "Python" ]
4
Python
AmitSureshChandra/Flask-blog
915e4dc3665a8d1a576a1f0a73c79a5d8dfc96a5
73522fe4b632310e78970bca856f16a091018d67
refs/heads/master
<file_sep>function MapCtrl ($scope, $http, GeolocationService) { //////////////////////////////// // Variables & Initialisation // //////////////////////////////// $scope.Math = Math; $scope.panneau = 0; $scope.loader = false; var map, curPos = null, curPosMarker = null, curPosCircleAccuracy = null var directionsDisplay, directionsService = new google.maps.DirectionsService(); var startPos, // 45,50281 -73,61756 UnivMtl destPos // 45,50397 -73,57136 McGill var destMarker, markers=[]; var watchId, tracking=false; ///////////////////////////////////////////// // Fonction principale appelée en premier // ///////////////////////////////////////////// $scope.geolocate = function(){ $scope.loader = true; GeolocationService.getCurrentPosition(function(position){ $scope.panneau = 1; var mapOptions = { zoom: 16, streetViewControl: false, mapTypeControl: false, }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); initCurLocMarker(position.coords); startPos = curPos; map.setCenter(startPos); google.maps.event.addListener(map, "click", leftclick); $scope.loader = false; }, function(error){ $scope.loader = false; alert('Impossible de recuperer votre position.'); }); } ////////////////////////////////////////////////////////// // Fonctions pour s'occuper du choix de la destination // ////////////////////////////////////////////////////////// /** * quand on clique sur la carte, on récupère les informations sur le point choisi * @param event objet de la carte qui contient nottement latLng. */ leftclick = function(event){ stopTracking(); destPos = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng()); deleteMarkers(); initializeDirection(); calcRoute(); startTracking(); } /** On réinitialise les trajets en effacant au besoin les précédents */ function initializeDirection() { if (directionsDisplay != null){ directionsDisplay.setMap(null); } directionsDisplay = new google.maps.DirectionsRenderer(); directionsDisplay.setMap(map); } /** On calcule la nouvelle route vers la nouvelle destination */ function calcRoute() { var request = { origin:startPos, destination:destPos, travelMode: google.maps.TravelMode.TRANSIT }; directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); var leg = result.routes[0].legs[0]; for (var i = leg.steps.length- 1; i >= 0; i--) { if(leg.steps[i].travel_mode == google.maps.TravelMode.TRANSIT){ var transit_info=leg.steps[i].transit; var dep_point=transit_info.departure_stop.location; var texte = 'Departure from ' + transit_info.departure_stop.name + ' stop at ' +transit_info.departure_time.text + ' with line '+transit_info.line.short_name +', ' + transit_info.line.name +' <br> '+ transit_info.num_stops + ' stops to destination' ; texte = '<span style="color:#000000"> ' + texte + '</span>'; addInfoWindow(dep_point,texte); } }; } }); } /////////////////////////////////////////////////////////////////// // Fonctions pour gèrer le Tracking de l'appareil en temps réel // /////////////////////////////////////////////////////////////////// /** Lancer le tracking et la MAJ en temps réel de la localisation de l'appareil */ function startTracking(){ tracking=true; watchID = GeolocationService.watchPosition(successGeoCB, errorGeoCB, { timeout: 30000 }); } /** * Si on réussi bien à récupérer la position, on mettre à jour celle-ci, et vérifier si l'on est dans un trajet si l'on est proche de l'arrivée * @param position GPS qui comprend nottement l'objet coords */ function successGeoCB(position) { updateCurLocMarker(position.coords); if(google.maps.geometry.spherical.computeDistanceBetween(curPos,destPos) < 100) alert('Vous êtes bientôt arrivé !'); deleteMarkers(); // On cache les markers que l'on avait peut être de présent sur la carte lors du choix de la destination } /** * onError Callback receives a PositionError object * @param PositionError object */ function errorGeoCB(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } /** On arrête le traking */ function stopTracking(){ if(tracking){ deleteMarkers(); GeolocationService.clearWatch(watchID); watchID=null; } tracking=false; } //////////////////////////////////////////////////////////////////// // Fonctions pour interagir avec le Marker localisation courante // //////////////////////////////////////////////////////////////////// /** * Initialisation du Marker localisation courante * @param position.coords coords */ function initCurLocMarker(coords) { curPos = new google.maps.LatLng(coords.latitude,coords.longitude); curPosMarker = new google.maps.Marker({ position: curPos, map: map, icon: { url: 'img/maps/curLoc24.png', size: new google.maps.Size(24, 24), origin: new google.maps.Point(0,0), anchor: new google.maps.Point(12, 12)// The anchor for this image is the base of the flagpole at 0,32. } }); // Draw a circle around the user position to have an idea of the current localization accuracy curPosCircleAccuracy = new google.maps.Circle({ center: curPos, radius: coords.accuracy, map: map, fillColor: '#B3D3F4', fillOpacity: 0.4, strokeColor: '#8cbae2', strokeOpacity: 0, strokeWidth:0 }); } /** * Mise à jour du Marker localisation courante * @param position.coords coords */ function updateCurLocMarker(coords) { if (!curPosMarker || !curPosCircleAccuracy) { initCurLocMarker(coords); }else{ curPos = new google.maps.LatLng(coords.latitude,coords.longitude); curPosMarker.setPosition(curPos); curPosCircleAccuracy.setCenter(curPos); curPosCircleAccuracy.setRadius(coords.accuracy); }; } /** Cacher de la carte le Marker localisation courante */ function hideCurLocMarker() { if (curPosMarker) {curPosMarker.setMap(null)}; if (curPosCircleAccuracy) {curPosCircleAccuracy.setMap(null)}; } /** Réafficher sur la carte le Marker localisation courante */ function showCurLocMarker() { if (curPosMarker) {curPosMarker.setMap(map)}; if (curPosCircleAccuracy) {curPosCircleAccuracy.setMap(map)}; } $scope.focusCurLoc = function(){ if (curPosCircleAccuracy) { map.fitBounds(curPosCircleAccuracy.getBounds()); }else{ map.setCenter(curPos); }; } //////////////////////////////////////////////////////////////////// // Jeu de fonction pour ajouter des Markers sur la carte // // Ces Marker sont enregistrés dans un tableau On pourra // // les retirer tous d'un coup sans perturber les autres markers. // //////////////////////////////////////////////////////////////////// /** * Add a marker to the map and push to the markers array. * @param google.maps.LatLng location */ function addMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); markers.push(marker); } /** * Add a marker to the map and push to the array. * @param google.maps.LatLng location * @param String Texte à afficher */ function addInfoWindow(location,Texte) { var marker = new google.maps.InfoWindow({ position: location, map: map, content: Texte }); markers.push(marker); } /** * Affecter à tous nos points une carte donnée * @param google.maps.Map GoogleMap sur laquelle on veut placer nos points */ function setAllMap(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } } /** Removes the markers from the map, but keeps them in the array. */ function clearMarkers() { setAllMap(null); } /** Shows any markers currently in the array. */ function showMarkers() { setAllMap(map); } /** Deletes all markers in the array by removing references to them. */ function deleteMarkers() { clearMarkers(); markers = []; } }<file_sep><?php function getEvangileDuJourContent($type,$date=null,$lang="FR",$content="GSP"){ if (empty($date) || !is_numeric($date)) { $date = date('Ymd'); } $url = "http://feed.evangelizo.org/v2/reader.php?date=".$date."&type=".$type."&lang=".$lang."&content=GSP"; $h = fopen($url,"r"); $str = ''; while (!feof($h)) { $str .= fgets($h); } return $str; } ?> <html lang="fr"><head> <meta charset="utf-8"> <meta content="IE=edge" http-equiv="X-UA-Compatible"> <meta content="width=device-width, initial-scale=1" name="viewport"> <meta content="Page de Maintenance du site internet du BdSpi de l'Icam" name="description"> <meta content="<NAME> 115" name="author"> <link href="favicon.png" rel="shortcut icon"> <title>Maintenance site internet BdSpi Icam</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="css/bootstrap.min.css"> <!-- Custom styles for this template --> <link rel="stylesheet" href="css/maintenance.css"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <style id="holderjs-style" type="text/css"></style> </head> <body> <div class="site-wrapper"> <div class="site-wrapper-inner"> <div class="cover-container"> <div class="masthead clearfix"> <div class="inner clearfix text-center"> <img src="logo_bdspi.png" alt="BdSpi Icam" title="BdSpi Icam" height="140"> </div> </div> <div class="inner cover"> <h1 class="cover-heading">Maintenance du site.</h1> <p class="lead"> Le site du BdSpi est actuellement en création, Il vous sera bientôt présenté.<br> Votre équipe du BdSpi de l'Icam Lille, pour tous les BdSpi Icam </p> <h3>Saint du jour :</h3> <p> <?= getEvangileDuJourContent('saint') ?> </p> </div> <div class="masthead clearfix"> <div class="inner clearfix text-center"> <img src="icam_at_rn_cge_paris_2014.jpg" alt="L'Icam à la RN CGE de Paris 2014" title="L'Icam à la RN CGE de Paris 2014 - <NAME>" height="300"> </div> </div> <div class="inner cover"> <h3>Evangile du jour <small>(<?= getEvangileDuJourContent('liturgic_t') ?>)</small></h3> <p> <?= getEvangileDuJourContent('all') ?> </p> </div> </div> </div> </div> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery.js"></script> <script src="js/bootstrap.min.js"></script> </body></html><file_sep>BdSpi Icam ========== Voici le début du site internet pour les BdSpi de tous les Sites Icam qui le voudront. Nous sommes une équipe de Lillois à lancer le projet ! N'hésitez pas à me contacter, *<NAME> en 115* pour plus d'informations
65b86e0dcc14fdf535848e0f2fc7679a6ef2040e
[ "JavaScript", "Markdown", "PHP" ]
3
JavaScript
BdSpi-Icam/site-bdspi
c58d1784b33e77c86caba4a6251f280dc62e1b5a
83e887e814e93657b54aa0d6c316e49cbaf8cc0b
refs/heads/master
<file_sep>import Vue from "vue"; import Router from "vue-router"; Vue.use(Router); import Content from "@/pages/content/Content"; import Editor from "@/pages/editor/Editor"; export default new Router({ mode: "history", base: process.env.BASE_URL, routes: [ { path: "/content/:id", component: Content }, { path: "/editor/:id", component: Editor } ] }); <file_sep>import * as fs from 'fs'; import { homedir } from 'os'; import { INoteConfig } from '@/types'; export function getNoteConfig(): INoteConfig { let config!: INoteConfig; const basePath = `${ homedir() }/electron-note`; const docPath = basePath + '/doc'; const imagesPath = basePath + '/image'; const configPath = basePath + '/config.json'; if (!fs.existsSync(basePath)) { fs.mkdirSync(docPath, { recursive: true, }); fs.mkdirSync(imagesPath); config = { 'doc': docPath, img: imagesPath }; fs.writeFileSync(configPath, JSON.stringify(config)); } else { config = JSON.parse(fs.readFileSync(configPath).toString()); } return config; } <file_sep>import Vue from 'vue'; import { INoteConfig } from '@/types/index'; declare module 'vue/types/vue' { interface Vue { $config: INoteConfig } } <file_sep>import Vue from 'vue'; import { getNoteConfig } from './boot'; import App from './App'; import router from './router'; import store from './store'; import 'ant-design-vue/dist/antd.min.css'; import '@/assets/style/style.less'; Vue.config.productionTip = false; Vue.prototype.$config = getNoteConfig(); new Vue({ router, store, render: h => h(App), }).$mount('#app'); <file_sep>import Vue from "vue"; import Vuex from "vuex"; import { IVuexState, IMenuItem } from '@/types'; Vue.use(Vuex); export default new Vuex.Store<IVuexState>({ state: { selectMenu: undefined }, getters: { GET_SELECT_MENU(state: IVuexState) { return state.selectMenu; } }, mutations: { SET_SELECT_MENU(state: IVuexState, data: IMenuItem) { state.selectMenu = data; } }, actions: {} }); <file_sep>import { basename } from 'path'; import marked from 'marked'; export const isEmpty = (data: any | any[]) => Array.isArray(data) ? data.length < 1 : data === '' || data === null || data === undefined; export const addExt = (p: string, ext: string = '.md') => { return p.includes(ext) ? p : p + ext; }; export const removeExt = (p: string, ext: string = '.md') => { return basename(p, ext); }; export const transMDToHtml = (m: string) => { return marked(m); }; <file_sep>export interface INoteConfig { doc: string; img: string; } export interface IVuexState { selectMenu?: IMenuItem; } export interface IMenuItem { path: string; title: string; } export enum EModalType { ADD = 1, EDIT = 2, } <file_sep>module.exports = { lintOnSave: false, pluginOptions: { electronBuilder: { chainWebpackMainProcess: (config) => { }, chainWebpackRendererProcess: (config) => { }, mainProcessWatch: [], mainProcessArgs: [], builderOptions: { productName: 'ENote', appId: 'com.ENote', mac: { icon: 'public/static/images/icons/icon.icns', }, }, }, }, };
f482d8b9cebc7e228ce6ef30aa4a03f7922e26e8
[ "JavaScript", "TypeScript" ]
8
TypeScript
yuezm/electron-note
9676e272023b0e560c02e4f7a1de1e012d6e0766
73ea98694991c9c4d45985f21517ac54841060c8
refs/heads/master
<repo_name>greenlightjohnny/restauth<file_sep>/index.js const express = require("express"); const app = express(); const mongoose = require("mongoose"); require("dotenv").config(); ////Import Routes const authRoute = require("./routes/auth"); const postRoute = require("./routes/posts"); console.log(postRoute); ///Connect to database with Mongoose mongoose.connect( `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PWORD}@cluster<EMAIL>.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true }, () => console.log("Connected to the MongoDB") ); ///Middleware app.use(express.json()); ///Route Middlewares app.use("/api/user", authRoute); app.use("/api/posts", postRoute); app.listen(3000, () => console.log("Server is UP!"));
cb851d2fd2337eedc6493cb5df2621b326493ca8
[ "JavaScript" ]
1
JavaScript
greenlightjohnny/restauth
f4e6e95cec5714d96602dd644422262173db1567
4867ac11278060649311315ad1b02697123b8bc6
refs/heads/master
<repo_name>epfromer/JSTest101<file_sep>/gulpfile.js var gulp = require('gulp'); var browserSync = require('browser-sync').create(); var plumber = require('gulp-plumber'); var srcDir = './app/**/*.*'; var buildDir = './build/'; // reload browsers as watch task after changes made gulp.task('watch', ['build'], function(done) { browserSync.reload(); done(); }); // process changed app files and put into build dir gulp.task('build', function () { return gulp .src(srcDir) .pipe(plumber()) .pipe(gulp.dest(buildDir)); }); // default task to launch build and watch for changes gulp.task('default', ['build'], function() { // create static server to serve build dir browserSync.init({ server: { baseDir: buildDir, index: "jasmine/SpecRunner.html" // index: "qunit/tests.html" } }); // reload browsers gulp.watch(srcDir, ['watch']); }); <file_sep>/app/mocha/mochaTest1.js var assert = require('assert'); var expect = require('chai').expect; var should = require('chai').should(); var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); chai.should(); /* Basic tests showing differences between assert, expect and should. */ describe('Array', function () { describe('#indexOf()', function () { it('should return -1 when the value is not present', function () { assert.equal(-1, [1, 2, 3].indexOf(4)); }); }); }); describe('test object equality', function () { it('should have equal objects', function () { var obj = {name: 'ed', gender: 'male'}; var objB = obj; expect(obj).to.equal(objB); }) it('should have equal objects', function () { var obj = {name: 'ed', gender: 'male'}; var objB = obj; obj.should.equal(objB); }) it('should have equal objects', function () { var obj = {name: 'ed', gender: 'male'}; var objB = {name: 'ed', gender: 'male'}; obj.should.deep.equal(objB); }) it('should have equal objects', function () { var obj = {name: 'ed', gender: 'male'}; var objB = {name: 'ed', gender: 'male'}; obj.should.deep.equal(objB); }) }); describe('test nulls', function () { it('should allow nulls', function () { var iAmNull = null; should.not.exist(iAmNull); }) }); describe('basic mocha test', function () { /* xit('should throw errors', function () { assert.equal(2, 3); }); */ //it('test to be defined'); /* it('test showing asserts are just exceptions', function () { try { assert.equal(2, 3); } catch (e) { //console.log(e); } }) */ }); <file_sep>/app/spy.js // define top class var MyClass = function () { }; MyClass.prototype.method1 = function () { console.log('method1'); return true; }; // and subclass var MySubclass = function () { }; MySubclass.prototype = new MyClass(); MySubclass.prototype.method2 = function () { console.log('method2'); return 'something'; }; // set up spies /* function SpyOn(classToSpyOn) { for (var key in classToSpyOn) { classToSpyOn[key] = CreateSpy(key); }; }; */ function SpyOn(classToSpyOn) { for (var key in classToSpyOn) { classToSpyOn[key] = CreateSpyPassthrough(key, classToSpyOn, classToSpyOn[key]); }; }; function CreateSpy(key) { return function () { console.log('i am a spy for ' + key); }; }; function CreateSpyPassthrough(key, context, origfunc) { var passthroughSpy = function () { console.log('i am a passthrough spy for ' + key); return origfunc.apply(context, arguments); }; return passthroughSpy; }; // get a subclass and spy on it var mysubsclass = new MySubclass(); SpyOn(mysubsclass); // show that we're spying on these methods mysubsclass.method1(); mysubsclass.method2();<file_sep>/README.md # JSTest101 tinker with JS testing frameworks - qunit is old-old-school - jasmine is old-school - mocha is modern <file_sep>/app/qunit/tests.js QUnit.module("module 1"); QUnit.test( "hello test 1", function( assert ) { assert.ok( 1 == "1", "Passed!" ); }); QUnit.module("module 2", { setup: function () { }, teardown: function () { } }); QUnit.test( "hello test 2", function( assert ) { assert.ok( 1 == "1", "Passed!" ); }); QUnit.module("async tests"); /* QUnit.test( "broken async timing test", function( assert ) { setTimeout(function () { QUnit.ok(true); }, 100); }); */ QUnit.asyncTasks()
4769b60d56fd0813314a948d92f21fdb3067f7d7
[ "JavaScript", "Markdown" ]
5
JavaScript
epfromer/JSTest101
dc244b9bd5a492dfcc63ba3b8f774fe27e92b11e
7de0bef6df6e5eb7d684a4a9dd08f492fbea1c42
refs/heads/master
<file_sep>/** @file model.c @author <NAME> (jruisi) A program that creates Model objects and transforms them based on user input. */ #include <stdio.h> #include <stdlib.h> #include <string.h> /** Loads a model from a given file, adding all the points of the line segments to the model's point list. @param fname the file name @return m the model loaded */ Model *loadModel( char const *fname ) { #define START 100 int count = 0; int idx = 0 FILE *f = fopen( fname, "r"); if (!f) { fprintf( stderr, "Can't open file"); } Model *m = (Model *)malloc(sizeof(Model*)); m->pList = (double(*)[2])malloc( START * sizeof(m->pList)); m->fname = fname; char *str[21]; for (int i = 0; i < strlen(fname); i++) { if (fname[i] = '.') { break; } str[i] = fname[i]; } m->name = str; double x, y; while(fscanf(f, "%lf %lf", &x, &y) != EOF) { double p[2] = {x, y}; memcpy(pList[idx], &p, sizeof(p)); idx++; count += 2; } m->pCount = count; return m; } /** Creates more space for the program by freeing a model whenever it needs to be deleted. @param m the model to free */ void freeModel( Model *m ) { free(m); } /** Called from the applyToScene function, this method applys a specific command to a specific function in the scene. @param m the model to issue the command to @param f the function to user @param pt the x and y coordinates @param a the x coordinate @param b the y coordinate @param a variable to transform model by @param b variable to transform model by */ void applyToModel( Model *m, void (*f)( double pt[ 2 ], double a, double b ), double a, double b ) { } /** Translates a given model a given distance up, right, down, or up. @param m the model to be translated @param x the x distance to be moved @param y the y distance to be moved */ void translate( Model *m, double x, double y) { } /** Scales a given model by a scale factor @param m the model to be scaled @param scale the scale factor */ void scale( Model *m, double scale) { } /** Rotates a given model by a given degree @param m the model to be rotated @param deg the amount of rotation */ void rotate( Model *m, double deg) { } <file_sep>/** @file drawing.c @author <NAME> (jruisi) A program that creates drawings from files of different graphical models that is input by the user. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "model.h" #include "scene.h" /** The main function reads in the user input and decides what command the user is trying to run. The main function then sends that data to scene.c and model.c to handle the commands. */ int main() { int count = 1; printf("cmd %d> ", count); Scene *s = makeScene(); char cmd[21]; while (scanf("%s", cmd) != EOF) { //Gets the load command if (strcmp(cmd, "load") == 0) { char name[21], file[21]; scanf("%s %s", name, file); //load printf("cmd %d> ", ++count); //Gets the save command } else if (strcmp(cmd, "save") == 0) { char file[21]; scanf("%s", file); //save printf("cmd %d> ", ++count); //Gets the delete command } else if (strcmp(cmd, "delete") == 0) { char name[21]; scanf("%s", name); applyToScene(s, name, ); printf("cmd %d> ", ++count); //Gets the list command } else if (strcmp(cmd, "list") == 0) { //list printf("cmd %d> ", ++count); //Gets the translate command } else if (strcmp(cmd, "translate") == 0) { char name[21]; double x, y; scanf("%s %lf %lf", name, &x, &y); applyToScene(s, name, ); printf("cmd %d> ", ++count); //Gets the scale command } else if (strcmp(cmd, "scale") == 0) { char name[21]; double val; scanf("%s %lf", name, &val); applyToScene(s, name, ); printf("cmd %d> ", ++count); //Gets the rotate command } else if (strcmp(cmd, "rotate") == 0) { char name[21]; double val; scanf("%s %lf", name, &val); applyToScene(s, name, ); printf("cmd %d> ", ++count); //Gets the quit command } else if (strcmp(cmd, "quit") == 0) { freeScene(s); exit(0); //Invalid command } else { fprintf(stderr, "Command %d invalid\n", count); printf("cmd %d> ", ++count); } } exit(0); } <file_sep>/** @file scene.c @author <NAME> (jruisi) A program that creates Scene objects and transforms them based on user input. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include "model.h" /** Initializes a scene @return s the initialized scene */ Scene *makeScene() { Scene *s = (Scene *)malloc(sizeof(Scene)); s->mCount = 0; s->mCap = 100; s->mList = (Model**)malloc(s->mCap * sizeof(Model*)); return s; } /** Frees the given scene from memory @param s the scene to be freed */ void freeScene( Scene *s ) { free(s); } /** Checks to see if a given model name is present in the scene. If it is, apply the given transformation to the model. */ bool applyToScene( Scene *s, char const *name, void (*f)( double pt[ 2 ], double a, double b ), double a, double b ) { for (int i = 0; i < 100; i++) { Model *m = s->mList[i]; char *one = name; char *two = m->name; if (strcmp(one, two) == 0) { //apply to model return true; } } return false; } <file_sep>#ifndef _MODEL_H_ #define _MODEL_H_ #include <stdio.h> /** Maximum length of name and filename strings. */ #define NAME_LIMIT 20 /** Representation for a model, a collection of line segments. */ typedef struct { /** Name of the model. */ char name[ NAME_LIMIT + 1 ]; /** File name it was loaded from. */ char fname[ NAME_LIMIT + 1 ]; /** Number of points in the model. It has half this many line segments. */ int pCount; /** List of points in the model, twice as long as the number of segments, since each segment has two points */ double (*pList)[ 2 ]; } Model; #endif <file_sep>#ifndef _SCENE_H_ #define _SCENE_H_ #include "model.h" #include <stdbool.h> /** Representation for a whole scene, a collection of models. */ typedef struct { /** Number of models in the scene. */ int mCount; /** Capacity of the model list. */ int mCap; /** List of pointers to models. */ Model **mList; } Scene; #endif
179b095fda1f6a8b09bc7a7e77bd5c6c77c4d57e
[ "C" ]
5
C
jruisi/hw-ruby-intro
5effb0615e8b38f74af7440b0c95376f7208a56a
6de949733809031c4c49120b46f999eff5988359
refs/heads/master
<file_sep>require 'rubygems' require 'bundler' Bundler.setup Bundler.require require "rspec/core/rake_task" desc 'Default: run specs.' task :default => :spec desc 'Run the specs' RSpec::Core::RakeTask.new(:spec) do |spec| end YARD::Rake::YardocTask.new(:doc) do |t| t.files = ['lib/**/*.rb', '-', 'HISTORY.md'] t.options = ['--no-private', '--title', 'Reportable Documentation'] end <file_sep>class ReportableRenameModelName < ActiveRecord::Migration def self.up rename_column :reportable_cache, :model_name, :model_class_name end def self.down rename_column :reportable_cache, :model_class_name, :model_name end end <file_sep>class ReportableRaphaelAssetsGenerator < Rails::Generators::Base include Rails::Generators::Actions source_root File.expand_path('../templates/', __FILE__) def create_raphael_file empty_directory('public/javascripts') copy_file( File.join(File.dirname(__FILE__), 'templates', 'raphael.min.js'), 'public/javascripts/raphael.min.js' ) copy_file( File.join(File.dirname(__FILE__), 'templates', 'g.raphael.min.js'), 'public/javascripts/g.raphael.min.js' ) copy_file( File.join(File.dirname(__FILE__), 'templates', 'g.line.min.js'), 'public/javascripts/g.line.min.js' ) readme(File.join(File.dirname(__FILE__), 'templates', 'NOTES')) end end <file_sep>ENV['RAILS_ENV'] = 'test' require 'rubygems' require 'bundler/setup' require 'active_record' require 'active_record/version' require 'active_support' begin require 'ruby-debug' # Debugger.start # Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) rescue LoadError # ruby-debug wasn't available so neither can the debugging be end ROOT = Pathname(File.expand_path(File.join(File.dirname(__FILE__), '..'))) $LOAD_PATH << File.join(ROOT, 'lib') $LOAD_PATH << File.join(ROOT, 'lib/saulabs') require File.join(ROOT, 'lib', 'saulabs', 'reportable.rb') # Rails::Initializer.run(:set_load_path) # Rails::Initializer.run(:set_autoload_paths) # Rails::Initializer.run(:initialize_time_zone) do |config| # config.time_zone = 'Pacific Time (US & Canada)' # end # FileUtils.mkdir_p File.join(File.dirname(__FILE__), 'log') # ActiveRecord::Base.logger = ActiveSupport::BufferedLogger.new(File.dirname(__FILE__) + "/log/spec.log") RSpec.configure do |config| config.filter_run :focus => true config.run_all_when_everything_filtered = true end ActiveRecord::Base.default_timezone = :local databases = YAML::load(IO.read(File.join(File.dirname(__FILE__), 'db', 'database.yml'))) ActiveRecord::Base.establish_connection(databases[ENV['DB'] || 'sqlite3']) load(File.join(File.dirname(__FILE__), 'db', 'schema.rb')) class User < ActiveRecord::Base; end class YieldMatchException < Exception; end <file_sep>class ReportableJqueryFlotAssetsGenerator < Rails::Generators::Base include Rails::Generators::Actions source_root File.expand_path('../templates/', __FILE__) def create_jquery_flot_file empty_directory('public/javascripts') copy_file( File.join(File.dirname(__FILE__), 'templates', 'jquery.flot.min.js'), 'public/javascripts/jquery.flot.min.js' ) copy_file( File.join(File.dirname(__FILE__), 'templates', 'excanvas.min.js'), 'public/javascripts/excanvas.min.js' ) readme(File.join(File.dirname(__FILE__), 'templates', 'NOTES')) end end <file_sep>source "http://rubygems.org" gem 'rails', '~> 5.0.1' gem 'protected_attributes' gem 'sqlite3' # gem 'mysql', '>= 2.8.0' gem 'pg' gem 'rspec', '~> 2.8.0' gem 'simplecov' gem 'excellent', '>= 1.5.4' gem 'yard', '>= 0.4.0' gem 'yard-rspec', '>= 0.1.0' gem 'bluecloth', '>= 2.0.5'
64a5b8e9bdcee3ce2b055c638c290908dbb95f3c
[ "Ruby" ]
6
Ruby
octanner/reportable
f2ed1e276281a6eb7ce6f9863ede0b138127ccc1
48e927aef8b39146b9d0c8e575037da77e385fad
refs/heads/master
<file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddLevelAndWeightFieldToPosts extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function($table){ $table->integer('level')->unsigned()->nullable(); $table->integer('weight')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function($table){ $table->dropColumn('level'); $table->dropColumn('weight'); }); } } <file_sep><?php namespace tutoweb\Events; abstract class Event { // } <file_sep>## fbm tut ### License This repository is not opensource <file_sep><?php namespace tutoweb\Http\Requests; use Illuminate\Foundation\Http\FormRequest; abstract class Request extends FormRequest { // }
700e9fc7f82c1823ba9c56fba5cd4fd6ae05b2b7
[ "Markdown", "PHP" ]
4
PHP
fbmfbm/fbmtut
4a17bcd6b5fb9d8a4a59a2905899c007d6026b5e
cb4b7a8142650d67ed05efcbf7c4c17e554c7151
refs/heads/master
<repo_name>baker1797/django-learn<file_sep>/novemberSite/basketball/admin.py from django.contrib import admin from basketball.models import Team, Player #, Stats class PlayerInLine(admin.TabularInline): model = Player #extra = 3 #extra is 3 by default class TeamAdmin(admin.ModelAdmin): fieldsets = [ ('Team', {'fields': ['city', 'name']}), #('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}) ] inlines = [PlayerInLine] list_display = ('name', 'city') # Register your models here. admin.site.register(Team, TeamAdmin) admin.site.register(Player)<file_sep>/novemberSite/novemberSite/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', #ex: /polls/ url(r'^polls/', include('polls.urls', namespace="polls")), #ex: /admin/ url(r'^admin/', include(admin.site.urls)), #ex: /basketball/ url(r'^basketball/', include('basketball.urls', namespace='basketball')), ) <file_sep>/novemberSite/basketball/views.py from django.shortcuts import render from basketball.models import Team, Player def index(request): context = { 'teams': Team.objects.order_by('city'), 'players': Player.objects.all(), } return render(request, 'basketball/index.html', context) def player_card(request, player_id): context = { 'player': Player.objects.get(id=player_id) } return render(request, 'basketball/player_card.html', context) <file_sep>/novemberSite/polls/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from django.views import generic from polls.models import Choice, Poll class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_poll_list' def get_queryset(self): """Return the last five published polls""" return Poll.objects.order_by('-pub_date')[:5] def anotherPage(request): return HttpResponse("Hello, world. You're at more.") class DetailView(generic.DetailView): model = Poll template_name = 'polls/detail.html' #def detail(request, poll_id): # poll = get_object_or_404(Poll, pk=poll_id) # return render(request, 'polls/detail.html', {'poll': poll}) # def results(request, poll_id): "Display the poll's results after processing the data" poll = get_object_or_404(Poll, pk=poll_id) for choice in poll.choice_set.all(): choice.setPercentage(poll.total_votes) return render(request, 'polls/results.html', {'poll': poll, 'total_votes': poll.total_votes}) def vote(request, poll_id): "Handle the vote submission after a user completes a poll" p = get_object_or_404(Poll, pk=poll_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except(KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'poll': p, 'error_message': "You didn't select a choice", }) else: selected_choice.votes += 1 selected_choice.save() p.total_votes += 1 p.save() return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))<file_sep>/novemberSite/novemberSite/playerPos/PointGuard.py class PointGuard: "Point guard class" abbrev = "PG" positionCount = 0 #def __init__(self, n = "New Player", v = 0): def __init__(self, name, value): self.name = name self.position = "PG" self.value = value self.__salary = 10000 #hidden to public, visible using miami1._PointGuard__salary PointGuard.positionCount += 1 def __str__(self): return "Pos | Val | Name\n %s | %d | %s" \ %(self.position, self.value, self.name) def setName(self, name): self.name = name def shootBall(): print "Shoot the ball!"<file_sep>/novemberSite/novemberSite/testPage.py #Module Setup import time import calendar import testFunctions import playerPos miami1 = playerPos.PointGuard("<NAME>", 40) miami2 = playerPos.PointGuard("<NAME>", 60) print miami1 print miami2 ##Variable Setup #x = 3 #y = 3 #strVar = "My String" #listVar = [1,2,3,"Four","Five","Six"] #dictVar = {'key1': '1', 'keyTwo': 2, 'third': 'Three'} # # #print time.asctime(time.localtime(time.time())) #print calendar.month(2013,10) # ##Printing Number variables #print "\n==Printing Numbers==" #if (x == 3 and 3 != 5 and x in listVar and x is y): # print "good" #else: # print "bad" # ##Printing String variables #print "\n==Printing Strings==" # #print "string:\t\t" + strVar #print "string [4]:\t" + strVar[4] #print "string [3:]:\t" + strVar[3:] #print "string [3:6]:\t" + strVar[3:6] # ##Printing List variables #print "\n==Printing Lists==" # #print listVar #print listVar[:4] #print listVar[2:3] # ##Printing Dictionary variables #print "\n==Printing Dictionary==" # #print dictVar['keyTwo'] #print dictVar.keys() #print dictVar.values() #print str(dictVar) #print dictVar.items() # ##Printing imported Function #print "\n==Printing Function==" # #def importTestFunction(): # print "success" # #testFunctions.firstFunction([1,2,3]) <file_sep>/novemberSite/novemberSite/testFunctions.py myList = [1,2,3] def firstFunction(myList, age = 12): "First Function Testing" print "first function" print myList myList.append([4,5,6]); print myList myList = [7,8,9] print myList print age return def defaultValFunction(): firstFunction(myList) #uses default value firstFunction(myList, 32) print myList def anonFunction(): sumAnon = lambda var1, var2: var1 + var2 print sumAnon(2,8) def dirList(): import novemberSite print dir(novemberSite)<file_sep>/novemberSite/polls/urls.py from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', #url(r'^more/$',views.anotherPage, name='anotherPage'), url(r'^$',views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), #ex: /polls/4324 (?P<poll_id>\d+) --> poll_id='4324' url(r'^(?P<poll_id>\d+)/results/$', views.results, name='results'), #ex: /polls/4324/results/ url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote') #ex: /polls/4324/vote/ )<file_sep>/novemberSite/basketball/models.py from django.db import models # Create your models here. class Team(models.Model): name = models.CharField(max_length = 20) city = models.CharField(max_length = 30) roster_size = models.IntegerField(default = 0) def __unicode__(self): return self.name #def adjust_roster_size(self, ): # pass class Player(models.Model): team = models.ForeignKey(Team) #defined by p.player_set.create() first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) #jersey = models.IntegerField() def __unicode__(self): return self.last_name + ", " + self.first_name #class Stats(models.Model): # threes = models.IntegerField(default = 0) # rebounds = models.IntegerField(default = 0) # assists = models.IntegerField(default = 0) # steals = models.IntegerField(default = 0) # blocks = models.IntegerField(default = 0) # points = models.IntegerField(default = 0) # # def __unicode__(self): # return self.player <file_sep>/novemberSite/novemberSite/playerPos/__init__.py from PointGuard import PointGuard from SmallForward import SmallForward<file_sep>/novemberSite/novemberSite/playerPos/SmallForward.py def SmallForward(n = "<NAME>", p = "SF", v = 0): "Small Forward class" name = n position = p value = v def printObj(): print name + " " + position + " " + value
05ada30b72bf51e43f054e465f45b509437def0d
[ "Python" ]
11
Python
baker1797/django-learn
71c45a32459f9686cc2a21a22718a48febc3b5e5
b3d9219a5af28155f52e60a30a9aeaaa4ae5fece
refs/heads/master
<file_sep>\name{QuaProc} \alias{Quantifying_processes} \title{Quantifying_processes2} \usage{ betaNTI(com,cophenetic(tree)) } \description{ com: community tree:phylogenetic tree } \examples{ betaNTI(com,cophenetic(tree)) } <file_sep># Hello, world! # # This is an example function named 'hello' # which prints 'Hello, world!'. # # You can learn more about package authoring with RStudio at: # # http://r-pkgs.had.co.nz/ # # Some useful keyboard shortcuts for package authoring: # # Build and Reload Package: 'Ctrl + Shift + B' # Check Package: 'Ctrl + Shift + E' # Test Package: 'Ctrl + Shift + T' hello <- function() { print("Hello, world!") } ########################################################################################################### ###cophenetic for big tree ########################################################################################################### ############################################################## ####以下代码需要在服务器跑,个人电脑可能带不动!!!!######## ############################################################## bigtree_cophenetic <- function(rooted_tree, subsize = 9000){ t0=Sys.time() library(picante) #tree <- read.tree(file = "rooted-tree.nwk") tree <- rooted_tree tips_list <- tree$tip.label ##设置每个子集大小,要小于2万,即sub_size小于10000。 sub_size <- subsize n <- ceiling(length(tips_list)/sub_size) if (n < 3) { cop_all <- cophenetic(tree) } if (n > 2) { sub_tiplist <- list() for (i in 1:(n-1)) { sub_tmp <- tips_list[(1+(i-1)*sub_size) : (i*sub_size)] sub_tiplist[[i]] <- sub_tmp } sub_tiplist[[n]] <- tips_list[(1+(n-1)*sub_size) : length(tips_list)] cop_all <- matrix(0,nrow = length(tips_list),ncol = length(tips_list)) cop_all <- as.data.frame(cop_all) rownames(cop_all) <- tips_list colnames(cop_all) <- tips_list for (i in 1:n) { for (j in i:n) { if (j>i) { a <- sub_tiplist[[i]] b <- sub_tiplist[[j]] ab <- c(a,b) print(paste(i,j)) print(length(ab)) c <- setdiff(tips_list ,ab) tree1<-drop.tip(tree,c) cop <- cophenetic(tree1) cop_all[rownames(cop),colnames(cop)] <- cop[rownames(cop),colnames(cop)] } } } } print(paste0("Big tree distance finished time: ",Sys.time())) print(Sys.time()-t0) return(cop_all) } ########################################################################################################### ###betaNTI ########################################################################################################### betaNTI <- function(com, cophenetic_dis, beta.reps = 999, filename="all_sample", nocore=2, nbin=5, mth_snowfall=F){ print(paste0("Process begin: ",Sys.time())) print(paste0("This com table is a ",nrow(com)," x ",ncol(com)," matrix.")) t_start=Sys.time() if(mth_snowfall){ library(snowfall) print("Use Snowfall package") } else { library(parallel) print("Use Parallel package") } library(picante) #library(abind) library(bigmemory) #library(tidyr) com <- com[,colSums(com)>0] cophenetic_dis <- cophenetic_dis[colnames(com),colnames(com)] ##实际betaMNTD print(paste0("Begin betaMNTD: ",Sys.time())) t0=Sys.time() bmntd.weighted.ob = picante::comdistnt(com,cophenetic_dis,abundance.weighted=T) bmntd.weighted.ob = as.matrix(bmntd.weighted.ob) bmntd.weighted.ob[upper.tri(bmntd.weighted.ob)] <- NA diag(bmntd.weighted.ob) <- NA bmntd.weighted.ob <- as.data.frame(bmntd.weighted.ob) bmntd.weighted.ob$id2 <- rownames(bmntd.weighted.ob) bmntd.weighted.ob <- tidyr::gather(bmntd.weighted.ob,key = "id1", value = "disval",na.rm = T,-id2) write.table(bmntd.weighted.ob,file = paste(filename,"betaMNTD.txt",sep = "_"),quote = F,row.names = F,col.names = T,sep = "\t") print(paste0("betaMNTD time:",format(Sys.time()-t0))) ##基于的betaMNTD #rand.weighted.bMNTD.comp = array(c(-999),dim=c(nrow(com),nrow(com),beta.reps)) #for (rep in 1:beta.reps) { # rand.weighted.bMNTD.comp[,,rep] = as.matrix(picante::comdistnt(com,taxaShuffle(cophenetic_dis),abundance.weighted=T,exclude.conspecifics = F)) # print(c(date(),rep)) #} func <- function(n,comm,cop) { library(picante) #library(tidyr) ma <- as.matrix(picante::comdistnt(comm,taxaShuffle(cop),abundance.weighted=T,exclude.conspecifics = F)) ma[upper.tri(ma)] <- NA diag(ma) <- NA #print(n) colnames(ma) <- rownames(ma) <- 1:nrow(ma) ma <- as.data.frame(ma) ma$id2 <- rownames(ma) ma <- tidyr::gather(ma,key = "id1", value = "disval",na.rm = T,-id2) gc() return(ma) } print(paste0("Begin null model: ",Sys.time())) nr=nrow(com)*(nrow(com)-1)/2 if(mth_snowfall){ sfInit(parallel = TRUE, cpus = nocore) sfLibrary(picante) sfLibrary(tidyr) sfExport("com","cophenetic_dis") } else { cl <- makeCluster(nocore) } if(nbin == 1){ t0=Sys.time() if(mth_snowfall){ results <- sfLapply(1:beta.reps,func,comm <- com,cop<-cophenetic_dis) } else { results <- parLapply(cl,1:beta.reps,func,comm <- com,cop<-cophenetic_dis) } rand.weighted.bMNTD.comp <- abind::abind(results,along = 1) rm(results) gc() print(paste0("null model time:",format(Sys.time()-t0))) } else { subn <- round(beta.reps/nbin,digits = 0) rand.weighted.bMNTD.comp <- big.matrix(nrow=beta.reps*nr, ncol=3, init=-999, backingfile=paste0('parall_bnti_',filename,'_null_model_res.bin'), descriptorfile=paste0('parall_bnti_',filename,'_null_model_res.desc')) for(i in 1:nbin){ print(paste0("start bin",i)) t0=Sys.time() if(i != nbin){ print(paste0((i-1)*subn+1,"-",(i*subn))) if(mth_snowfall){ results <- sfLapply(((i-1)*subn+1):(i*subn),func,comm <- com,cop<-cophenetic_dis) } else { results <- parLapply(cl,((i-1)*subn+1):(i*subn),func,comm <- com,cop<-cophenetic_dis) } rand.weighted.bMNTD.comp[(nr*(i-1)*subn+1):(nr*i*subn),] <- abind::abind(results,along = 1) } else { print(paste0((i-1)*subn+1,"-",beta.reps)) if(mth_snowfall){ results <- sfLapply(((i-1)*subn+1):beta.reps,func,comm <- com,cop<-cophenetic_dis) } else { results <- parLapply(cl,((i-1)*subn+1):beta.reps,func,comm <- com,cop<-cophenetic_dis) } rand.weighted.bMNTD.comp[(nr*(i-1)*subn+1):(nr*beta.reps),] <- abind::abind(results,along = 1) } print(paste0("bin",i,"null model time:",format(Sys.time()-t0))) rm(results) gc() } } if(mth_snowfall){ sfStop() } else { stopCluster(cl) } print("Parallel process fishned") rm(cophenetic_dis) gc() print(paste0("Begin loops: ",Sys.time())) weighted.bNTI = bmntd.weighted.ob weighted.bNTI[,3] <- -999 t0=Sys.time() for (id1 in 1:(nrow(com)-1)) { for (id2 in (id1+1):nrow(com)) { rand.vals = as.numeric(rand.weighted.bMNTD.comp[rand.weighted.bMNTD.comp[,2]==id1 & rand.weighted.bMNTD.comp[,1]==id2,3]) weighted.bNTI[weighted.bNTI[,"id1"]==rownames(com)[id1] & weighted.bNTI[,"id2"]==rownames(com)[id2],3] <- (bmntd.weighted.ob[weighted.bNTI[,"id1"]==rownames(com)[id1] & weighted.bNTI[,"id2"]==rownames(com)[id2],3] - mean(rand.vals)) / sd(rand.vals) } } colnames(weighted.bNTI) <- c("Sample1","Sample2","betaNTI") print(paste0("loops time:",format(Sys.time()-t0))) write.table(weighted.bNTI,file = paste(filename,"betaNTI.txt",sep = "_"),quote = F,row.names = F,col.names = T,sep = "\t") #return(weighted.bNTI) print(paste0("Total time:",format(Sys.time()-t_start))) } ########################################################################################################### ###RCbray ########################################################################################################### raup_crick_modified=function(comm, nocore=2, reps=9999, filename="all_sample", nbin=5, mth_snowfall=F){ ##comm: a species by site matrix, with row names for plots. ##Note that the choice of how many plots (rows) to include has a real impact on the metric, as species and their occurrence frequencies across the set of plots is used to determine gamma and the frequency with which each species is drawn from the null model print(paste0("RCbray begin: ",Sys.time())) print(paste0("This com table is a ",nrow(comm)," x ",ncol(comm)," matrix.")) t_start = Sys.time() if(mth_snowfall){ library(snowfall) print("Use Snowfall package") } else { library(parallel) print("Use Parallel package") } #library(vegan) #library(tidyr) library(bigmemory) #对物种求和 com_sum <- colSums(comm) ## count number of sites and total species richness across all plots,提取物种名称 (gamma) n_sites <-nrow(comm) n_sp <- ncol(comm) gamma <- colnames(comm) ##make the comm matrix into a pres/abs. (overwrites initial comm matrix): comm_standard <- vegan::decostand(comm,"pa") ##create an occurrence vector- used to give more weight to widely distributed species in the null model: occur <- colSums(comm_standard) ## determine how many unique species richness values are in the dataset ##this is used to limit the number of null communities that have to be calculated alpha_levels<-sort(unique(rowSums(comm_standard))) #generate the matrix for the input of func_subRC function mtr <- matrix(0,length(alpha_levels),length(alpha_levels)) rownames(mtr) <- colnames(mtr) <- 1:length(alpha_levels) mtr[upper.tri(mtr)] <- NA mtr <- as.data.frame(mtr) mtr$id2 <- rownames(mtr) long_bray <- tidyr::gather(mtr,key = "id1", value = "repsno",na.rm = T,-id2) #a1 <- rep(long_bray$id1,reps) #a2 <- rep(long_bray$id2,reps) #repsno <- rep(1:reps, each = nrow(long_bray)) #vfsmmy <- data.frame(a1,a2,repsno) vfsmmy <- matrix(c(rep(long_bray$id1,reps),rep(long_bray$id2,reps),rep(1:reps, each = nrow(long_bray))),reps*nrow(long_bray),3) rm(long_bray,mtr) gc() #构建用于并行函数 #vf: containing 3 factors needed for cycle func_subRC <- function(nl,vfsmmy,comm,alpha_levels,occur){ #library(snowfall) #library(vegan) a1 <- as.numeric(vfsmmy[nl,1]) a2 <- as.numeric(vfsmmy[nl,2]) #n <- vfsmmy[nl,3] n_sp <- ncol(comm) gamma <- colnames(comm) com_sum <- colSums(comm) ##two empty null communities of size gamma: com1 <- com2 <- rep(0,n_sp) names(com1) <- names(com2) <- gamma ##add alpha1 number of species to com1, weighting by species occurrence frequencies: com1[sample(gamma, alpha_levels[a1], replace=FALSE, prob=occur)]<-1 ##same for com2: com2[sample(gamma, alpha_levels[a2], replace=FALSE, prob=occur)]<-1 ##how many species are shared in common? #null_dist[i]<-sum((com1+com2)>1) ##有两种方法,测试证明,两者结果相似,mantel test结果R为99.1%,p为0.001.这里选择方法2。 ###方法一:用所有样品平均多度作为概率抽取物种多度(会出现一部分物种多度为0) #allreads1 <- sum(comm[a1,]) #com1list <- which(com1==1) #com1_pro <- com_sum[com1list] #ind1 <- as.factor(sample(com1list,allreads1,replace=TRUE, prob=com1_pro)) #ind1_summary <- t(as.matrix(table(ind1))) #allreads2 <- sum(comm[a2,]) #com2list <- which(com2==1) #com2_pro <- com_sum[com2list] #ind2 <- as.factor(sample(com2list,allreads2,replace=TRUE, prob=com2_pro)) #ind2_summary <- t(as.matrix(table(ind2))) #pairma <- matrix(0,nrow=2,ncol=n_sp) #colnames(pairma) <- 1:n_sp #pairma[1,colnames(ind1_summary)] <- ind1_summary #pairma[2,colnames(ind2_summary)] <- ind2_summary #dis1 <- vegan::vegdist(pairma,method="bray") ###方法二:以所有样品平均多度为比例,计算物种多度(保证了所有样品多度不为0) allreadcount <- sum(comm[1,]) com1list <- which(com1==1) com1_pro <- com_sum[com1list] com1_pro <- allreadcount*com1_pro/sum(com1_pro) com2list <- which(com2==1) com2_pro <- com_sum[com2list] com2_pro <- allreadcount*com2_pro/sum(com2_pro) pairma <- matrix(0,nrow=2,ncol=n_sp) colnames(pairma) <- gamma pairma[1,names(com1_pro)] <- com1_pro pairma[2,names(com2_pro)] <- com2_pro dis2 <- vegan::vegdist(pairma,method="bray") output <- c(alpha_levels[a1],alpha_levels[a2],dis2) return(output) } ##make_null: print(paste0("RCbray null model begin: ",Sys.time())) if(mth_snowfall){ sfInit(parallel = TRUE, cpus = nocore) sfLibrary(vegan) sfExport("vfsmmy","comm", "alpha_levels", "occur") } else { cl <- makeCluster(nocore) } ttl_reps <- nrow(vfsmmy) if(nbin == 1) { t0=Sys.time() if(mth_snowfall){ results <- sfLapply(1:ttl_reps,func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } else { results <- parLapply(cl,1:ttl_reps,func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } null_dist <- matrix(unlist(results), nrow=3) rm(results) gc() print(paste0("null model time:",format(Sys.time()-t0,digits=4))) } else { subn <- round(ttl_reps/nbin,digits = 0) print(paste0("Need ",nbin, " loops. Each loop has ",subn," reps." )) null_dist <- big.matrix(nrow=3, ncol=ttl_reps, init=-999, backingfile=paste0('parall_rcbray_',filename,'_null_model_res.bin'), descriptorfile=paste0('parall_rcbray_',filename,'_null_model_res.desc')) for(i in 1:nbin){ print(paste0("start bin",i)) t0=Sys.time() if(i != nbin){ if(mth_snowfall){ results <- sfLapply(((i-1)*subn+1):(i*subn),func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } else { results <- parLapply(cl,((i-1)*subn+1):(i*subn),func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } null_dist[,((i-1)*subn+1):(i*subn)] <- matrix(unlist(results), nrow=3) } else { if(mth_snowfall){ results <- sfLapply(((i-1)*subn+1):ttl_reps,func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } else { results <- parLapply(cl,((i-1)*subn+1):ttl_reps,func_subRC,vfsmmy <- vfsmmy, comm <- comm,alpha_levels<-alpha_levels,occur <- occur) } null_dist[,((i-1)*subn+1):ttl_reps] <- matrix(unlist(results), nrow=3) } print(paste0("bin",i," null model time:",format(Sys.time()-t0,digits=4))) rm(results) gc() } } #sfStop() print("Parallel null model processes finished") ##build a site by site matrix for the results, with the names of the sites in the row and col names: disbray <- as.matrix(vegan::vegdist(comm,method="bray")) print("a1") disbray[upper.tri(disbray)] <- NA diag(disbray) <- NA disbray <- as.data.frame(disbray) disbray$id1 <- rownames(disbray) disbray <- tidyr::gather(disbray,key = "id2", value = "rn",na.rm = T,-id1) print("a2") rm(occur, comm,vfsmmy) gc() func_mtr <- function(nlm, disbray, reps, comm_standard,null_dist){ #require(bigmemory) ##how many species are shared between the two sites: n_shared_obs <- disbray[nlm,3] ## what was the observed richness of each site? obs_a1<-sum(comm_standard[disbray[nlm,1],]) obs_a2<-sum(comm_standard[disbray[nlm,2],]) ##place these alphas into an object to match against alpha_table (sort so smaller alpha is first) obs_a_pair<-sort(c(obs_a1, obs_a2)) nullrc <- null_dist[3,null_dist[1,]==obs_a_pair[1] & null_dist[2,]==obs_a_pair[2]] ##how many null observations is the observed value tied with? num_exact_matching_in_null<-sum(nullrc==n_shared_obs) ##how many null values are bigger than the observed value? num_greater_in_null<-sum(nullrc>n_shared_obs) rc <- ((num_greater_in_null+(num_exact_matching_in_null)/2)/reps) ##our modification of raup crick standardizes the metric to range from -1 to 1 instead of 0 to 1 rc <- (rc - 0.5)*2 ## at this point rc represents an index of dissimilarity- multiply by -1 to convert to a similarity as specified in the original 1979 Raup Crick paper rc<- -1*rc return(c(disbray[nlm,1],disbray[nlm,2],round(rc, digits=3))) } print("a3") #null_dist <- as.matrix(null_dist) null_dist1 <- matrix(-999,nrow=3, ncol=ttl_reps) class(null_dist1) null_dist1 <- null_dist[1:3,] class(null_dist1) print("a4") if(mth_snowfall){ #sfInit(parallel = TRUE, cpus = nocore) sfExport("disbray","reps", "comm_standard", "null_dist1") rcres <- sfLapply(1:nrow(disbray),func_mtr, disbray <- disbray, reps <- reps, comm_standard<-comm_standard, null_dist <- null_dist1) sfStop() } else { rcres <- parLapply(cl,1:nrow(disbray),func_mtr, disbray <- disbray, reps <- reps, comm_standard<-comm_standard, null_dist <- null_dist1) stopCluster(cl) } print("a5") longRC <- t(matrix(unlist(rcres), nrow=3)) colnames(longRC) <- c("Sample1","Sample2","RCbray") write.table(longRC,file = paste(filename,"RCbray.txt",sep = "_"),quote = F,row.names = F,col.names = T,sep = "\t") print(paste0("Total time:",format(Sys.time()-t_start,,digits=4))) } <file_sep>library(vegan) ########################################################################## ###########统计百分比,第一步:NTI######################################### ########################################################################## NTI_Summ <- as.data.frame(matrix(NA,nrow = 6,ncol = 7)) colnames(NTI_Summ) <- c("Total","No_nonselection","No_homogeneous_selection","No_variable_selection","No_Dispersal_Limitation","No_Homogenizing_Dispersal","NO_Drift") tmpn <- "02bNTI_parallel_from_pkusever/AWF_betaNTI.txt" bNTI_AWF <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "02bNTI_parallel_from_pkusever/AWP_betaNTI.txt" bNTI_AWP <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "02bNTI_parallel_from_pkusever/AS_betaNTI.txt" bNTI_AS <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "02bNTI_parallel_from_pkusever/SWF_betaNTI.txt" bNTI_SWF <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "02bNTI_parallel_from_pkusever/SWP_betaNTI.txt" bNTI_SWP <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "02bNTI_parallel_from_pkusever/SS_betaNTI.txt" bNTI_SS <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) n=1 for (i in c("SWF","SWP","SS","AWF","AWP","AS")) { ntitmp <- as.dist(get(paste('bNTI_',i,sep = ''))) No_total <- length(ntitmp) No_less_exp <- length(which(ntitmp < -2)) No_more_exp <- length(which(ntitmp > 2)) No_same_exp <- (No_total - No_less_exp - No_more_exp ) NTI_Summ[n,1:4] <- c(No_total,No_same_exp,No_less_exp,No_more_exp) rownames(NTI_Summ)[n] <- i n <- n+1 } #write.table(NTI_Summ,file = 'Summary_betaNTI.txt',quote = F,row.names = T,col.names = T,sep = "\t") ########################################################################## ###########统计百分比,第二步:RCbray###################################### ########################################################################## tmpn <- "03RCbray/SWF_RCbray.txt" RCb_SWF <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "03RCbray/SWP_RCbray.txt" RCb_SWP <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "99_RCbray_result_from_pkusever/SS_RCbray.txt" RCb_SS <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "03RCbray/AWF_RCbray.txt" RCb_AWF <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "03RCbray/AWP_RCbray.txt" RCb_AWP <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) tmpn <- "99_RCbray_result_from_pkusever/AS_RCbray.txt" RCb_AS <- read.table(tmpn,header = T,row.names = 1, sep='\t',check.name = F) for (i in c("AWP","AWF","AS","SWP","SWF","SS")) { RCtmp <- get(paste('RCb_',i,sep = ''))#RCb_AWP ntitmp <- get(paste('bNTI_',i,sep = ''))#bNTI_AWP1 RCtmp[ntitmp > 2] <- 0 RCtmp[ntitmp < -2] <- 0 RCtmp <- as.dist(RCtmp) #rc_total <- length(which(RCtmp1 != "NTI")) No_DL <- length(which(RCtmp > 0.95)) No_HD <- length(which(RCtmp < -0.95)) No_drift <- NTI_Summ[i,2] - No_DL - No_HD NTI_Summ[i,5:7] <- c(No_DL,No_HD,No_drift) } psumm <- NTI_Summ[,3:7] psumm <- decostand(psumm,method = "total") colnames(psumm) <- c("p_homogeneous_selection","p_variable_selection","p_Dispersal_Limitation","p_Homogenizing_Dispersal","p_Drift") NTI_Summ <- cbind(NTI_Summ,psumm) write.table(NTI_Summ,file = 'Quantifying_processes.txt',quote = F,row.names = T,col.names = T,sep = "\t")
e4b3f8a70e01811cae3d76a538c3ca6e10aee043
[ "R" ]
3
R
mol529/Rdiversity
c537e9fb78fbc8dacaf95c3540a4985f79a5ba5a
c82d70366cbdc302f61424944f24d5b674d23213
refs/heads/master
<file_sep># Java-Threaded-Binary-Search-Tree ## Brief Description A Java [Swing](https://en.wikipedia.org/wiki/Swing_(Java)) application which implements a [Threaded BST (Binary Search Tree)](https://en.wikipedia.org/wiki/Threaded_binary_tree) and an interactive GUI to manipulate it. The BST in this application manages a dictionary of key-value pairs of student id's (keys) and their names (values). ![tree](https://upload.wikimedia.org/wikipedia/commons/thumb/7/7a/Threaded_tree.svg/330px-Threaded_tree.svg.png) ## Features - Optional display of the **threads** in the tree, which could be either displayed (in red) or hidden: ![Application Screenshots Gif](Screenshots/Enabling-Display-of-Wired-Threads-in-Red.png) - **Dictionary Operations** :key:: - Insert - Find - Remove - **Queries** :mag_right:: - Maximum - Minimum - Median - Successor - Predecessor - **Tree Traversals** :palm_tree: : - Preorder - Inorder - Postorder - BFS (Breadth-First-Search) ## Usage - Inorder to run application just clone or download the files and run the batch script file "**runApplication.bat**". - All Interaction is done through the GUI, and all output is shown on cmd & on the status bar on the app's footer, besides the BFS Travese output which is shown only on the cmd due it's length. - Instead of manipulating each operation separatly directly via the graphical user interface, you could alternatively upload a script input file :page_facing_up:. The format the script file is a separate line for each command. See [Input File Example](InputFileExample.txt) for a demo input file. The command interpreter is case in-sensitive so you could for example type either *Preorder* or *preorder*. Some commands accept no arguments, other only one argument and other two arguments, here is the entire list of commands which are allowed in a script input file, associated with their arguments (argument type & whether the argument is mandatory or not): | Command | Argument1 | Argument2 | |----------------|-------------------------|-------------------------| | Insert | ID (Numeric, mandatory) | Name (String, optional) | | Delete | ID (Numeric, mandatory) | | | Search | ID (Numeric, mandatory) | | | Minimum | | | | Maximum | | | | Median | | | | Successor | ID (Numeric, mandatory) | | | Predecessor | ID (Numeric, mandatory) | | | Preorder | | | | Inorder | | | | Postorder | | | ## Demo Screenshots ![Application Screenshots Gif](Screenshots/screenshots.gif) ## Log Output Sample ![Cmd output](Screenshots/CLI-Output-Log.png) ## UML Class Diagram ![UML Class Diagram](UML.png) <file_sep>package student; /** * * @author <NAME> * * Student - class representing student with an ID and name. */ public class Student implements Comparable<Student> { // Instance variables private Integer id; private String name; /** Constructor */ public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return id.toString(); // only id is relevant for the tree } /**CompareTo: Compare between 2 students by their Identification number property. * This is simply done by using the java standard Integer class comparison. * @param otherStudent student to be compared to. * @return 0, negative number or positive number, if this student id is accordingly * equal, less than or larger than the other students id. */ @Override public int compareTo(Student otherStudent) { return this.id.compareTo(otherStudent.id); } /** checks student equality: returns true if both have same id, false otherwise. */ @Override public boolean equals(Object obj) { if(obj instanceof Student) { return this.id.equals(((Student) obj).id); } else return false; } //basic Getters: public Integer getId() {return id;} public String getName(){return name;} } // end of class <file_sep>package treeGUI; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.security.SecureRandom; import javax.management.openmbean.KeyAlreadyExistsException; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import binaryTree.BSTNode; import ioHandler.IOHandler; import student.Student; import wiredBinarySearchTree.WiredBST; /** * @author <NAME>. * * This class is responsible for supplying a GUI interactive application * which supports the wired binary search tree operations & queries. * It also supports a printout visualization of the existing tree. * and support importing an input file with the following commands as noted below: * ------------|-------------------|-------------| * command |arg1 |arg2 | * ------------|-------------------|-------------| * insert <numeric id> <string name>| * delete <numeric id> | * search <numeric id> | * minimum | * maximum | * median | * predecessor <numeric id> | * successor <numeric id> | * inorder | * preorder | * postorder | * ----------------------------------------------| * Commands aren't case sensitive (i.e, you could type Delete or delete). * @See "inputFileExample.txt" for some examples. */ @SuppressWarnings("serial") public class GUIApplication extends JFrame implements ActionListener { // Data Instance variables: WiredBST<Student> tree; // the tree IOHandler ioHandler; // I/O handler for file import BSTNode<Student> node; String message; /* GUI instance variables: */ // Panels private final JPanel northPanel; private final JPanel southPanel; private final JPanel eastPanel; private final JPanel westPanel; private final JPanel centerPanel; private final JPanel controllsPanel; private final JPanel inputFieldsPanel; private final JPanel dictionaryOperationsPanel; private final JPanel queriesPanel; private final JPanel treeWalksPanel; private final JPanel extraFeaturesPanel; private final TreePrinter<Student> canvasPanel; private final JScrollPane canvasScrollPane; // Buttons & Controls: private JButton insertButton; private JButton deleteButton; private JButton searchButton; private JButton successorButton; private JButton predecessorButton; private JButton minimumButton; private JButton maximumButton; private JButton medianButton; private JButton inOrderButton; private JButton preOrderButton; private JButton postOrderButton; private JButton printBFSButton; private JButton clearButton; private JButton importFileButton; private final JTextField studentIDField; private final JTextField studentNameField; private final JCheckBox displayWiresCheckBox; // Labels: private final JLabel applicationHeaderLabel; private final JLabel studentIDLabel; private final JLabel studentNameLabel; private final JLabel statusBar; // Icons: private final Icon insertIcon; private final Icon deleteIcon; private final Icon searchIcon; private final Icon importIcon; private final Icon clearIcon; // Fonts: private static final Font defaultFont = new Font("Tahoma", 0, 14); // Colors: private static Color green1 = new Color(152, 251, 152); private static Color green2 = new Color(0, 255, 152); private static Color green3 = new Color(0, 255, 127); private static Color green4 = new Color(154, 205, 20); /** * Constructor - Initialize all GUI components: * @param tree - the wired binary tree to manipulate and display: */ public GUIApplication(WiredBST<Student> tree) { super("Wired Binary Search Tree Application"); this.tree = tree; this.ioHandler = new IOHandler(); this.setSize(1000, 700); this.setFont(defaultFont); // Create panels northPanel = new JPanel(new BorderLayout()); southPanel = new JPanel(new BorderLayout()); eastPanel = new JPanel(new BorderLayout()); westPanel = new JPanel(new BorderLayout()); centerPanel = new JPanel(new BorderLayout()); canvasPanel = new TreePrinter<Student>(tree); controllsPanel = new JPanel(new GridLayout(5,0,5,5)); inputFieldsPanel = new JPanel(new GridLayout(1,0,5,5)); dictionaryOperationsPanel = new JPanel(new GridLayout(1,0,5,5)); queriesPanel = new JPanel(new GridLayout(1,0,5,5)); treeWalksPanel = new JPanel(new GridLayout(1,3,5,5)); extraFeaturesPanel = new JPanel(new GridLayout(1,0,5,5)); northPanel.setBorder(BorderFactory.createLineBorder(Color.black)); centerPanel.setBorder(BorderFactory.createLineBorder(Color.black)); southPanel.setBorder(BorderFactory.createLineBorder(Color.black)); canvasPanel.setBorder(BorderFactory.createLineBorder(Color.black)); inputFieldsPanel.setBorder(BorderFactory.createLineBorder(Color.black)); dictionaryOperationsPanel.setBorder(BorderFactory.createLineBorder(Color.black)); queriesPanel.setBorder(BorderFactory.createLineBorder(Color.black)); treeWalksPanel.setBorder(BorderFactory.createLineBorder(Color.black)); extraFeaturesPanel.setBorder(BorderFactory.createLineBorder(Color.black)); // Set main panels locations: this.add(northPanel, BorderLayout.NORTH); this.add(southPanel, BorderLayout.SOUTH); this.add(centerPanel, BorderLayout.CENTER); this.add(eastPanel, BorderLayout.EAST); this.add(westPanel, BorderLayout.WEST); // Application Title applicationHeaderLabel = new JLabel("Wired Binary Search Tree GUI application", SwingConstants.LEFT); applicationHeaderLabel.setBackground(new Color (200,255,175)); applicationHeaderLabel.setOpaque(true); northPanel.add(applicationHeaderLabel, BorderLayout.PAGE_START); // Canvas panel display area section: canvasScrollPane = new JScrollPane(canvasPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); centerPanel.add(canvasScrollPane); // Input fields panel: studentIDLabel = new JLabel("Student ID (key): "); studentIDLabel.setFont(defaultFont); studentIDField = new JTextField("100", 8); studentIDField.setBackground(new Color(250, 250, 210)); studentIDField.setFont(defaultFont); studentIDField.addActionListener(this); studentIDField.setToolTipText("Enter Students uniqe identification number"); studentNameLabel = new JLabel("Student Name (optional): "); studentNameLabel.setFont(defaultFont); studentNameField = new JTextField("<NAME>", 16); studentNameField.setFont(defaultFont); studentNameField.addActionListener(this); studentNameField.setToolTipText("Enter students name, or blank"); studentNameField.setBackground(new Color(250, 250, 210)); inputFieldsPanel.add(studentIDLabel); inputFieldsPanel.add(studentIDField); inputFieldsPanel.add(studentNameLabel); inputFieldsPanel.add(studentNameField); studentIDLabel.setBorder(BorderFactory.createLineBorder(Color.black)); studentNameLabel.setBorder(BorderFactory.createLineBorder(Color.black)); studentIDField.setBorder(BorderFactory.createLineBorder(Color.black)); studentNameField.setBorder(BorderFactory.createLineBorder(Color.black)); // Dictionary operations panel: insertIcon = new ImageIcon(getClass().getResource("icons\\insert.png")); insertButton = new JButton("Insert", insertIcon); insertButton.setToolTipText("Insert new student to tree"); insertButton.setBackground(green1); insertButton.addActionListener(this); deleteIcon = new ImageIcon(getClass().getResource("icons\\delete.png")); deleteButton = new JButton("Delete", deleteIcon); deleteButton.setToolTipText("Delete student from tree"); deleteButton.setBackground(green1); deleteButton.addActionListener(this); searchIcon = new ImageIcon(getClass().getResource("icons\\search.png")); searchButton = new JButton("Search", searchIcon); searchButton.setBackground(green1); searchButton.setToolTipText("Search for student in tree by it's id"); searchButton.addActionListener(this); dictionaryOperationsPanel.add(insertButton); dictionaryOperationsPanel.add(deleteButton); dictionaryOperationsPanel.add(searchButton); // Queries panel: minimumButton = new JButton("Minimum"); maximumButton = new JButton("Maximum"); medianButton = new JButton("Median"); predecessorButton = new JButton("Predecessor"); successorButton = new JButton("Successor"); minimumButton.setBackground(green2); maximumButton.setBackground(green2); medianButton.setBackground(green2); predecessorButton.setBackground(green2); successorButton.setBackground(green2); minimumButton.addActionListener(this); maximumButton.addActionListener(this); medianButton.addActionListener(this); predecessorButton.addActionListener(this); successorButton.addActionListener(this); queriesPanel.add(minimumButton); queriesPanel.add(maximumButton); queriesPanel.add(medianButton); queriesPanel.add(predecessorButton); queriesPanel.add(successorButton); // Tree walk traversals panel: inOrderButton = new JButton("Inorder tree walk"); preOrderButton = new JButton("Preorder tree walk"); postOrderButton = new JButton("Postorder tree walk"); inOrderButton.setBackground(green3); preOrderButton.setBackground(green3); postOrderButton.setBackground(green3); inOrderButton.addActionListener(this); preOrderButton.addActionListener(this); postOrderButton.addActionListener(this); treeWalksPanel.add(inOrderButton); treeWalksPanel.add(preOrderButton); treeWalksPanel.add(postOrderButton); // Extra Features Panel: importIcon = new ImageIcon(getClass().getResource("icons\\import.png")); importFileButton = new JButton("Import input File", importIcon); printBFSButton = new JButton("BFS print"); clearIcon = new ImageIcon(getClass().getResource("icons\\clear.png")); clearButton = new JButton("Clear Tree", clearIcon); importFileButton.addActionListener(this); printBFSButton.addActionListener(this); clearButton.addActionListener(this); displayWiresCheckBox = new JCheckBox("Display Tree Wires"); displayWiresCheckBox.setToolTipText("if this is checked, non null wires would be displayed in red"); displayWiresCheckBox.setBackground(Color.YELLOW); displayWiresCheckBox.addActionListener(this); importFileButton.setBackground(green4); printBFSButton.setBackground(green4); clearButton.setBackground(green4); extraFeaturesPanel.add(importFileButton); extraFeaturesPanel.add(printBFSButton); extraFeaturesPanel.add(clearButton); extraFeaturesPanel.add(displayWiresCheckBox); // Controls panel setup: controllsPanel.add(inputFieldsPanel); controllsPanel.add(dictionaryOperationsPanel); controllsPanel.add(queriesPanel); controllsPanel.add(treeWalksPanel); controllsPanel.add(extraFeaturesPanel); southPanel.add(controllsPanel, BorderLayout.NORTH); // Status bar section: statusBar = new JLabel("@Chanan Welt: 20407 Maman16"); statusBar.setFont(new Font("Tahoma", Font.BOLD, 17)); statusBar.setOpaque(true); statusBar.setBackground(Color.LIGHT_GRAY); southPanel.add(statusBar, BorderLayout.SOUTH); statusBar.setBorder(BorderFactory.createLineBorder(Color.black)); } /** * GUI event handler: handles all push buttons and check box: */ public void actionPerformed(ActionEvent event) { //clear status bar from previous status: clearStatusBar(); // validate input: if(!inputIsValid(event)) return; //get input fields values: int inputID; if (!studentIDField.getText().isEmpty()) inputID = Integer.parseInt(studentIDField.getText()); else inputID = 0; String inputName = studentNameField.getText(); // check which object fired the event and treat it accordingly: Object triggeringObject = event.getSource(); // INSERT: if(triggeringObject == insertButton) { try { node = tree.insert(new Student(inputID, inputName)); } catch (KeyAlreadyExistsException exception) { message = "Insert faild:" + exception.getMessage() + "key must be uniqe!"; displayMessage(message, JOptionPane.ERROR_MESSAGE); return; } if (node != null) { message = String.format("Student <%s> inserted successfully", (inputID + " " + inputName)); displayMessage(message, JOptionPane.INFORMATION_MESSAGE); } repaint(); return; } // DELETE else if (triggeringObject == deleteButton) { node = tree.delete(tree.search(tree.getRoot(), new Student(inputID, null))); if (node == null) displayMessage(("Deleteion failed: ID " + inputID + " does not exist on tree"), JOptionPane.ERROR_MESSAGE); else { message = String.format("Student <%s> deleted successfully", (node.getData())); displayMessage(message, JOptionPane.INFORMATION_MESSAGE); } repaint(); return; } // SEARCH else if (triggeringObject == searchButton) { Student studentKey = new Student(inputID, null); node = tree.search(tree.getRoot(), studentKey); if (node == null) displayMessage(("Search failed: ID " + inputID + " does not exist on this tree"), JOptionPane.INFORMATION_MESSAGE); else { message = String.format("Student <%s> found", (node.toString())); displayMessage(message, JOptionPane.INFORMATION_MESSAGE); } return; } // MAXIMUM: else if (triggeringObject == maximumButton) { node = tree.getMaximum(tree.getRoot()); if (node == null) displayMessage(("No maximum, tree is empty "), JOptionPane.ERROR_MESSAGE); else displayMessage((String.format("Maximum found: <%s>", node)), JOptionPane.INFORMATION_MESSAGE); return; } // MINIMUM else if (triggeringObject == minimumButton) { node = tree.getMinimum(tree.getRoot()); if (node == null) displayMessage(("No minimum, tree is empty "), JOptionPane.ERROR_MESSAGE); else displayMessage((String.format("Minimum found: <%s>", node)), JOptionPane.INFORMATION_MESSAGE); return; } // MEDIAN else if (triggeringObject == medianButton) { node = tree.getMedian(); if (node == null) displayMessage(("No median, tree is empty "), JOptionPane.ERROR_MESSAGE); else displayMessage((String.format("Median found: <%s>", node)), JOptionPane.INFORMATION_MESSAGE); return; } // SUCCESSOR else if (triggeringObject == successorButton) { Student studentKey = new Student(inputID, null); node = tree.search(tree.getRoot(), studentKey); if (node == null) displayMessage(("successor not found: key "+inputID+" does not exist"), JOptionPane.INFORMATION_MESSAGE); else { node = tree.getSuccessor(node); if (node != null) displayMessage((String.format("Successor of <%d> is <%s>", inputID, node.getData())), JOptionPane.INFORMATION_MESSAGE); else displayMessage((String.format("<%d> is the max node. it has no successor.", inputID)), JOptionPane.INFORMATION_MESSAGE); } return; } // PREDECESSOR else if (triggeringObject == predecessorButton) { Student studentKey = new Student(inputID, null); node = tree.search(tree.getRoot(), studentKey); if (node == null) displayMessage(("predecessor not found: key "+inputID+" does not exist"), JOptionPane.INFORMATION_MESSAGE); else { node = tree.getPredecessor(node); if (node != null) displayMessage((String.format("Predecessor of <%d> is <%s>", inputID, node.getData())), JOptionPane.INFORMATION_MESSAGE); else displayMessage((String.format("<%d> is the minimum node. it has no predecessor.", inputID)), JOptionPane.INFORMATION_MESSAGE); } return; } // IN-ORDER TREE TRAVESERAL: else if (triggeringObject == inOrderButton) { message = tree.inorderTreeWalk(tree.getRoot()); System.out.println(message); setStatusBar(message); return; } // PRE-ORDER TREE TRAVESERAL: else if (triggeringObject == preOrderButton) { message = tree.preorderTreeWalk(tree.getRoot()); System.out.println(message); setStatusBar(message); return; } // POST-ORDER TREE TRAVESERAL: else if (triggeringObject == postOrderButton) { message = tree.postorderTreeWalk(tree.getRoot()); System.out.println(message); setStatusBar(message); return; } // BREADTH-DEPTH-FIRST TREE TRAVESERAL: else if (triggeringObject == printBFSButton) { System.out.println(tree); setStatusBar("Breadth-Search-Scan Printout was sent to standart output"); return; } // CLEAR CURRENT TREE: else if (triggeringObject == clearButton) { int dialogResult = JOptionPane.showConfirmDialog(this, "clear entire tree?"); if (dialogResult == JOptionPane.OK_OPTION) { this.tree = new WiredBST<Student>(); setStatusBar("Tree was cleared, The tree is now empty."); canvasPanel.setTree(tree); repaint(); return; } } // TOGGLE DISPLAY MODE FOR WIRES: else if (triggeringObject == displayWiresCheckBox) { if(displayWiresCheckBox.isSelected()) canvasPanel.setDisplayWires(true); else canvasPanel.setDisplayWires(false); repaint(); return; } // IMPORT INPUT FILE: else if (triggeringObject == this.importFileButton) { // let the user select the desired input file: JFileChooser fileChooser = new JFileChooser(); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int result = fileChooser.showOpenDialog(this); // if user clicked Cancel button or exited dialog, return: if (result != JFileChooser.APPROVE_OPTION) return; // pass file to ioHandler for further processing: try { File inputFile = fileChooser.getSelectedFile(); ioHandler.processInputFile(tree, inputFile); repaint(); return; } catch (Exception e) { displayMessage(("Error opening file" + e.getMessage()), JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } } /** Utility initialization method for setting GUI first time:*/ public void initGui() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } /* Display Message on GUI and\or standard error output */ private void displayMessage(String message, int messageType) { if (messageType == JOptionPane.ERROR_MESSAGE) { JOptionPane.showMessageDialog(this, message, "Wired BST Application", JOptionPane.ERROR_MESSAGE); System.err.println(message); } else { setStatusBar(message); System.out.println(message); } } /* Display messages on GUI status bar */ private void setStatusBar(String message) { SecureRandom randomNumbers = new SecureRandom(); int randomRedColor = randomNumbers.nextInt(256); int randomBlueColor = randomNumbers.nextInt(256); statusBar.setOpaque(true); statusBar.setText(message); statusBar.setBackground(new Color(randomRedColor, 255, randomBlueColor)); } /* Clear status bar from previous status */ public void clearStatusBar() { statusBar.setText(null); statusBar.setBackground(Color.LIGHT_GRAY); } /* Input validation tests */ private boolean inputIsValid(ActionEvent event) { // validate student id input is a natural number: String inputID = studentIDField.getText(); // make sure all mandatory input fields have input: if (inputID.isEmpty()) { Object triggeringObject = event.getSource(); if ((triggeringObject == insertButton) || (triggeringObject == deleteButton) || (triggeringObject == searchButton) || (triggeringObject == predecessorButton) || ((triggeringObject == predecessorButton))) { displayMessage(String.format("Student ID is a mandatory field for this operation"), JOptionPane.ERROR_MESSAGE); return false; } } else // make sure student id is a positive integer: { try { int value = Integer.parseInt(inputID); if (value <= 0) { message = String.format("Invalid student id input: \"%s\", ID must be a positive number", inputID); displayMessage(message, JOptionPane.ERROR_MESSAGE); return false; } } catch (NumberFormatException e) { message = String.format("Invalid student id input: \"%s\", ID must be numeric", inputID); displayMessage(message, JOptionPane.ERROR_MESSAGE); return false; } } return true; } } // end of class
13ebec842b46ad67c34c399e2a11ab002bf842bc
[ "Markdown", "Java" ]
3
Markdown
kalash34/Java-Threaded-Binary-Search-Tree-Visualization
60dfc842cb320c52a908a4748b538b47fc506f1f
341d6cb0b5c37fa75007378167538d6651900ca4
refs/heads/master
<repo_name>anand-raj/gatsby-materialui<file_sep>/src/components/AppBar.js import React from 'react'; import PropTypes from 'prop-types'; import { navigate } from 'gatsby'; import { withStyles } from '@material-ui/core/styles'; import {AppBar, Toolbar, Typography, Button} from '@material-ui/core'; const styles = { root: { flexGrow: 1, }, grow: { flexGrow: 1, }, menuButton: { marginLeft: -12, marginRight: 20, }, }; function ButtonAppBar(props) { const { classes } = props; return ( <div className={classes.root}> <AppBar color="default" position="static"> <Toolbar> <Typography variant="h5" color="error" className={classes.grow} style={{fontWeight: "bold"}}> <span color="inherit" onClick={() => navigate("/")}>GATSBY</span> </Typography> <Button color="inherit" onClick={() => navigate("/articles")}>Literature</Button> <Button color="inherit">News</Button> <Button color="inherit">Organisation</Button> </Toolbar> </AppBar> </div> ); } ButtonAppBar.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ButtonAppBar); <file_sep>/src/components/ArticleList.js import React from 'react'; import { StaticQuery, graphql } from 'gatsby'; import Cards from './Cards'; export default () => ( <StaticQuery query = { graphql `query { allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}) { totalCount edges { node { fields { slug } id frontmatter { title image keywords date(formatString: "MMMM YYYY") } excerpt } } } }` } render = { data => { console.log(data.allMarkdownRemark.edges) return(<Cards cards={data.allMarkdownRemark.edges} />) } } />);<file_sep>/src/components/Layout.js import React from 'react'; import CssBaseline from '@material-ui/core/CssBaseline'; import { withStyles } from '@material-ui/core/styles'; import AppBar from './AppBar'; import Footer from './Footer.js'; const styles = theme => ({ layout: { width: 'auto', marginLeft: theme.spacing.unit * 3, marginRight: theme.spacing.unit * 3, [theme.breakpoints.up(1100 + theme.spacing.unit * 3 * 2)]: { width: 1100, marginLeft: 'auto', marginRight: 'auto', }, } }); const Layout = ({ children, classes }) => ( <React.Fragment> <CssBaseline /> <AppBar /> <br /> <div className={classes.layout}> {children} </div> <Footer /> </React.Fragment> ) export default withStyles(styles)(Layout); <file_sep>/src/markdown/history-aikkms.md --- title: "History of AIKKMS" date: "2019-01-03" image: "https://source.unsplash.com/150x150/?protest,movement" keywords: "javascript" --- ##History of AIKKMS The share croppers in Bengal launched a heroic movement in nineteen fortysix called Tebhaga movement ( two third share of the yield for the share croppers). But the revisionist leadership of CPI betrayed the cause of the mmovement. Comrade <NAME> with his meagre resources took the responsibility to give the movement a proper direction and organised the share croppers in Sundarban area in south twentyfour pargsnas of west bengal.As a result Krishak Khet mazur Federation formed.In Nineteen eightyfour first All india conference of the organisation was held and All India Kishan Khetmajdoor Sangathan--AIKKMS took its birth.In two thousand sixteen its second all india conference was held in Bhubaneswar,Odisha.Now the organisation is working in fourteen states in our country having more than ten lakh members. From its inception the organisation is trying its best to organise peasants movement on the basis of the teaching of great Marxist thinker of this era com.Shibdas Ghosh.It organised movement against the village kulaks,and anti peasant policy of the central and state govts.of various shades.In these struggles hundreds of workers and cadres sacrificed their lives,faced brutal torture from the reactionary classes, but still they are fighting jubilantly against the oppressive measures of capitalism imperialism.aikkms is fighting and will fight t liberate the<file_sep>/src/templates/Post.js import React from 'react'; import { graphql } from 'gatsby'; import { Typography } from '@material-ui/core'; import { withStyles } from '@material-ui/core/styles'; import TurndownService from 'turndown'; import Layout from '../components/Layout'; import Markdown from './Markdown'; const turndownService = new TurndownService(); const styles = theme => ({ markdown: { padding: `${theme.spacing.unit * 3}px 0`, } }); const Post = ({ data, classes }) => { const post = data.markdownRemark console.log(post.html.toString()) return ( <Layout> <Typography gutterBottom variant="h4">{post.frontmatter.title}</Typography> <div style={{ width: '100%', height: '200px', backgroundColor: '#fafafa', backgroundImage: 'Url(https://source.unsplash.com/960x200/?' + post.frontmatter.keywords + ')', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', marginBottom: '30px' }}></div> <Markdown className={classes.markdown}> {turndownService.turndown(post.html)} </Markdown> </Layout> ) } export default withStyles(styles)(Post); export const query = graphql` query($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title keywords } } } `<file_sep>/src/components/Carousel.js import React from 'react'; import "react-responsive-carousel/lib/styles/carousel.min.css"; import { Carousel } from 'react-responsive-carousel'; import { Typography } from '@material-ui/core'; export default () => { return ( <div align="center"> <Carousel showStatus={false} transitionTime={1000} showThumbs={false} autoPlay interval={5000} infiniteLoop> <div> <img src="https://source.unsplash.com/1110x400/?landscape" alt="landscape" /> <div className="legend"> <Typography style={{ color: "white" }}> Legend 1 </Typography></div> </div> <div> <img src="https://source.unsplash.com/1110x400/?nature" alt="landscape" /> <div className="legend"> <Typography style={{ color: "white" }}> Legend 2 </Typography></div> </div> <div> <img src="https://source.unsplash.com/1110x400/?nightsky" alt="landscape" /> <div className="legend"> <Typography style={{ color: "white" }}> Legend 3 </Typography></div> </div> </Carousel> </div> ); }
5f67de1298df4db0c659ad5747599b98742ac02c
[ "JavaScript", "Markdown" ]
6
JavaScript
anand-raj/gatsby-materialui
78915804ebeb5697f0061e7bbb58845f18e80c7f
e83c6625a39e7830ed0d2e24a78e4c5584354d9b
refs/heads/master
<repo_name>Hydrapain/fire<file_sep>/js/app.js // Your web app's Firebase configuration var config = { apiKey: "<KEY>", authDomain: "usuarios-6830f.firebaseapp.com", databaseURL: "https://usuarios-6830f.firebaseio.com", projectId: "usuarios-6830f", storageBucket: "usuarios-6830f.appspot.com", messagingSenderId: "863158451087", appId: "1:863158451087:web:88904063f580df19" }; // Initialize Firebase firebase.initializeApp(config); // Initialize Cloud Firestore through Firebase var db = firebase.firestore(); // Definción de eventos para botones de registro y conexión var re = document.getElementById("registrar"); re.addEventListener("click", registrar, false); var co = document.getElementById("conectar"); co.addEventListener("click", conectar, false); function registrar() { var email = document.getElementById("email1").value; var password = document.getElementById("<PASSWORD>1").value; firebase.auth().createUserWithEmailAndPassword(email, password) .then(function () { confirmar(); $("#botones").css("visibility", "hidden"); $("#cerrarconexion").css("display", "inline"); $("#modalRegistro").modal('hide'); }) .catch(function (error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; alert("Error: " + errorCode + ". " + errorMessage); }); } function conectar() { var email = document.getElementById("email2").value; var password = document.getElementById("password2").value; firebase.auth().signInWithEmailAndPassword(email, password) .then(function () { $("#botones").css("visibility", "hidden"); $("#cerrarconexion").css("display", "inline"); }) .catch(function (error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; alert("Error: " + errorCode + ". " + errorMessage); }); } function observador() { firebase.auth().onAuthStateChanged(function (user) { if (user) { console.log("Existe usuario activo."); contenidosUsuarioRegistrado(user); var displayName = user.displayName; var email = user.email; var emailVerified = user.emailVerified; var photoURL = user.photoURL; var isAnonymous = user.isAnonymous; var uid = user.uid; var providerData = user.providerData; console.log('Usuario verificado: ' + emailVerified); // ... } else { // User is signed out. console.log("No existe ningún usuario activo."); } }); } function contenidosUsuarioRegistrado(usuario) { var contenido = document.getElementById("contenido"); if (usuario.emailVerified) { contenido.innerHTML = ` <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"> <h4 class="alert-heading">¡Bienvenido ${usuario.email}!</h4> <p>Siéntete a gusto en nuestro portal.</p> <hr> <p class="mb-0">Tenemos muchos contenidos exclusivos solo para usuarios registrados como tú.</p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <h2>Agregar usuarios</h2> <div class="form-inline"> <label for="tipo" class="col-sm-2 col-form-label">Tipo territorio: </label> <input type="number" id="tipo" placeholder="Introduce tipo de territorio" class="form-control my-3 col-sm-4" > </div> <div class="form-inline"> <label for="territorio" class="col-sm-2 col-form-label">Territorio: </label> <input type="number" id="territorio" placeholder="Introduce un territorio" class="form-control my-3 col-sm-4" maxlenght="50" pattern="[A-Za-zÑñÁÉÍÓúáéíóúÇç\s]"> </div> <div class="form-inline"> <label for="inicial" class="col-sm-2 col-form-label">Fecha Inicial: </label> <input type="text" id="inicial" placeholder="Introduce fecha inicial" class="form-control my-3 col-sm-1" maxlenght="4" pattern="\d{4}"> </div> <div class="form-inline"> <label for="final" class="col-sm-2 col-form-label">Fecha Final: </label> <input type="text" id="final" placeholder="Introduce fecha final" class="form-control my-3 col-sm-4" > </div> <div class="form-inline"> <label for="cuando" class="col-sm-2 col-form-label">Cuándo se trabaja: </label> <input type="text" id="cuando" placeholder="Cuando se trabaja" class="form-control my-3 col-sm-4" maxlenght="50" pattern="[A-Za-zÑñÁÉÍÓúáéíóúÇç\s]"> </div> <div class="form-inline"> <label for="quien" class="col-sm-2 col-form-label">Quien trabaja: </label> <input type="number" id="quien" placeholder="Quien trabaja" class="form-control my-3 col-sm-1" maxlenght="4" pattern="\d{4}"> </div> <button class="btn btn-info my-3" id="guardar">Guardar</button> <table class="table"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Tipo</th> <th scope="col">Territorio</th> <th scope="col">Inicial</th> <th scope="col">Final</th> <th scope="col">Apellido</th> <th scope="col">Cuando</th> <th scope="col">Quien</th> <th scope="col">Eliminar</th> </tr> </thead> <tbody id="tabla"> </tbody> </table> `; cargarTabla(); $("#cerrarconexion").html(`<button id="cerrar" class="btn btn-danger btn-sm ml-2">Cerrar sesión</button>`); var ce = document.getElementById("cerrar"); ce.addEventListener("click", cerrar, false); var gu = document.getElementById("guardar"); gu.addEventListener("click", guardar, false); } else { contenido.innerHTML = ` <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"> <h4 class="alert-heading">¡Bienvenido ${usuario.email}!</h4> <p>Activa tu cuenta para ver nuestros contenidos para usuarios registrados.</p> <hr> <p class="mb-0">Revisa tu correo electrónico</p> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> `; } } function cerrar() { firebase.auth().signOut() .then(function () { console.log("Saliendo..."); $("#botones").css("visibility", "visible"); $("#cerrarconexion").css("display", "none"); contenido.innerHTML = ` <div class="alert alert-warning alert-dismissible fade show mt-3" role="alert"> <strong>¡Cáspitas!</strong> Esperamos verte pronto otra vez por nuestro portal. <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> `; cerrarconexion.innerHTML = ""; }) .catch(function (error) { console.log(error); }); } function confirmar() { var user = firebase.auth().currentUser; user.sendEmailVerification().then(function () { // Email sent. console.log("Enviando correo..."); }).catch(function (error) { // An error happened. console.log(error); }); } function guardar() { var usuario = { tipo: document.getElementById("tipo").value, territorio: document.getElementById("territorio").value, inicial: document.getElementById("inicial").value final: document.getElementById("final").value, cuando: document.getElementById("cuando").value, quien: document.getElementById("quien").value }; db.collection("usuarios").add(usuario) .then(function (docRef) { console.log("Documento escrito con ID: ", docRef.id); document.getElementById("tipo").value = ""; document.getElementById("territorio").value = ""; document.getElementById("inicial").value = ""; document.getElementById("final").value = ""; document.getElementById("cuando").value = ""; document.getElementById("quien").value = ""; }) .catch(function (error) { console.error("Error añadiendo el documento: ", error); }); } // Lectura de los documentos function cargarTabla() { db.collection("usuarios").onSnapshot(function (querySnapshot) { var tabla = document.getElementById("tabla"); tabla.innerHTML = ""; querySnapshot.forEach(function (doc) { tabla.innerHTML += ` <tr> <th scope="row">${doc.id}</th> <td>${doc.data().tipo}</td> <td>${doc.data().territorio}</td> <td>${doc.data().inicial}</td> <td>${doc.data().final}</td> <td>${doc.data().cuando}</td> <td>${doc.data().quien}</td> <td><button class="btn btn-success" onclick="editarDatos('${doc.id}');">Editar</button></td> <td><button class="btn btn-danger" onclick="borrarDatos('${doc.id}');">Eliminar</button></td> </tr> `; }); }); } // Borrar datos de documentos function borrarDatos(parId) { db.collection("usuarios").doc(parId).delete() .then(function () { console.log("Usuario borrado correctamente."); }).catch(function (error) { console.error("Error borrando el usuario: ", error); }); } // Editar datos de documentos function editarDatos(parId) { } observador();
d5ffa932c8217de1ca483140963c59969742b4a7
[ "JavaScript" ]
1
JavaScript
Hydrapain/fire
f18f76bcff3fea90bef245ef72e3d4b81009083a
87fa246c13e883db9167fca7e2273ed39cf58944
refs/heads/master
<repo_name>Akhmed78111/svyaznoy<file_sep>/ConsoleApplication2/Model/Credit.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2.Model { class Credit { public int CreditID { get; set; } public string Name { get; set; } public int OneCount { get; set; } public int TwoCount { get; set; } public int FiveCount { get; set; } public int TenCount { get; set; } } } <file_sep>/ConsoleApplication2/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; using ConsoleApplication2.Model; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { int ID; EAContext db = new EAContext(); var CU = db.Credits .Where(c => c.CreditID == 2) .FirstOrDefault(); CU.TenCount = 10; CU.FiveCount = 5; CU.TwoCount = 10; CU.OneCount = 5; int credit = 0; label1: db.SaveChanges(); db = new EAContext(); var Products = from o in db.Products where o.Count > 0 select o; var credUser = db.Credits .Where(c => c.CreditID == 2) .FirstOrDefault(); Console.WriteLine("Количество монет в ваших руках:"); Console.WriteLine("Рубль\tДва\tПять\tДесять"); Console.WriteLine("{0}\t{1}\t{2}\t{3}", credUser.OneCount, credUser.TwoCount, credUser.FiveCount, credUser.TenCount); Console.WriteLine("\nНа счету: {0} руб.\n", credit); Console.WriteLine("ID\tName\tPrice\tCount"); foreach (var b in Products) { Console.WriteLine("{0}\t{1}\t{2}\t{3}", b.ProductID, b.Name, b.Price, b.Count); } Console.WriteLine("\n!pay/n - внести n руб.;\n!buy/ID - купить ID товар;\n!get/ - забрать сдачу;"); string s = Console.ReadLine(); string p; int n = 0; for(int i = 0; i < s.Length; i++) { if (s[i] == '/') break; n++; } p = s.Remove(n, s.Length - n); switch (p.ToLower()) { case "!buy": try { ID = Convert.ToInt32(s.Remove(0, n + 1)); int i = 0; foreach (var b in db.Products) { if ((b.ProductID == ID) && (b.Count > 0) && (credit >= b.Price)) { i++; b.Count--; Console.Clear(); Console.WriteLine("\nСпасибо за покупку!\n"); credit = credit - b.Price; goto label1; } else if ((b.ProductID == ID) && (b.Count > 0) && (credit < b.Price)) { i++; Console.Clear(); Console.WriteLine("\nНе хватает денег для покупки этого товара. \n"); goto label1; } } if (i == 0) { Console.Clear(); Console.WriteLine("К сожалению, такого товара нет.\n"); goto label1; } } catch { Console.Clear(); Console.WriteLine("Ошибка! После команды !buy/ введие ID товара.\n"); goto label1; } break; case "!pay": try { int t = Convert.ToInt32(s.Remove(0, n + 1)); Console.Clear(); PaymentClass pay = new PaymentClass(); pay.Payment(t); credit = credit + pay.Credit(); goto label1; } catch { Console.Clear(); Console.WriteLine("Ошибка! После команды !pay/ введие .\n"); goto label1; } case "!get": Console.Clear(); PaymentClass get = new PaymentClass(); get.GetMoney(credit); if (get.Credit() > 0) Console.WriteLine("Из - за отсутствия сдачи, аппарат вернул вам {0} руб.\n", credit- get.Credit()); else Console.WriteLine("Вы получили {0} руб. сдачи.\n", credit - get.Credit()); credit = get.Credit(); goto label1; default: Console.Clear(); Console.WriteLine("Ошибка! Неправильная команда.\n"); goto label1; } } } class PaymentClass { int sum; public int Credit() { return sum; } public void GetMoney(int cred) { EAContext db = new EAContext(); var credAuto = db.Credits .Where(c => c.CreditID == 1) .FirstOrDefault(); var credUser = db.Credits .Where(c => c.CreditID == 2) .FirstOrDefault(); int[,] arrAuto = new int[2, 4] { {10,5,2,1}, { credAuto.TenCount,credAuto.FiveCount,credAuto.TwoCount,credAuto.OneCount} }; int[] arr = new int[4]; for(int i = 0; i < 4; i++) /*Алгоритм для выдачи сдачи минимальным количеством монет*/ { if (cred == 0) break; do { if (arrAuto[1,i] == 0) break; if (cred - arrAuto[0, i] >= 0) { cred = cred - arrAuto[0, i]; arrAuto[1, i]--; } else break; } while (cred > 0); } /*Конец!*/ credUser.TenCount = credUser.TenCount + credAuto.TenCount - arrAuto[1, 0]; credUser.FiveCount = credUser.FiveCount + credAuto.FiveCount - arrAuto[1, 1]; credUser.TwoCount = credUser.TwoCount + credAuto.TwoCount - arrAuto[1, 2]; credUser.OneCount = credUser.OneCount + credAuto.OneCount - arrAuto[1, 3]; db.SaveChanges(); sum = cred; } public void Payment(int cred) { EAContext db = new EAContext(); var credUser = db.Credits .Where(c => c.CreditID == 2) .FirstOrDefault(); var credAuto = db.Credits .Where(c => c.CreditID == 1) .FirstOrDefault(); switch (cred) { case 1: if (credUser.OneCount > 0) { credUser.OneCount--; credAuto.OneCount++; sum = cred; Console.WriteLine("Вы внесли {0} руб.\n", cred); } else Console.WriteLine("Таких бабок у вас с роду не было!\n"); db.SaveChanges(); break; case 2: if (credUser.TwoCount > 0) { credUser.TwoCount--; credAuto.TwoCount++; sum = cred; Console.WriteLine("Вы внесли {0} руб.\n", cred); } else Console.WriteLine("Таких бабок у вас с роду не было!\n"); db.SaveChanges(); break; case 5: if (credUser.FiveCount > 0) { credUser.FiveCount--; credAuto.FiveCount++; sum = cred; Console.WriteLine("Вы внесли {0} руб.\n", cred); } else Console.WriteLine("Таких бабок у вас с роду не было!\n"); db.SaveChanges(); break; case 10: if (credUser.TenCount > 0) { credUser.TenCount--; credAuto.TenCount++; sum = cred; Console.WriteLine("Вы внесли {0} руб.\n", cred); } else Console.WriteLine("Таких бабок у вас с роду не было!\n"); db.SaveChanges(); break; default: Console.WriteLine("Таких бабок у вас с роду не было!\n"); break; } } } } <file_sep>/ConsoleApplication2/Model/EAContext.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Entity; namespace ConsoleApplication2.Model { class EAContext : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Credit> Credits { get; set; } } }
1707bad794a78d1f16d9d12acadb019d2b11d6cd
[ "C#" ]
3
C#
Akhmed78111/svyaznoy
5726192c99a41087d3fc08232b1967d4ff14f59a
69aa3d667b40fade67fcb0f89787383a59724ecd
refs/heads/master
<repo_name>department-g33k/hassio-config<file_sep>/readme.md [![Build Status](https://travis-ci.org/department-g33k/hassio-config.svg?branch=master)](https://travis-ci.org/department-g33k/hassio-config) <file_sep>/updatescript.sh #!/bin/bash FileYouWantToTest='/mnt/dar-dc-01/docker/Volumes/travis/scripts/update-hass.txt' echo -n "Verifying if $FileYouWantToTest exist..." if [ -f $FileYouWantToTest ] then rm -f $FileYouWantToTest # ./pull.sh cd /var/snap/docker/common/var-lib-docker/volumes/58f3283090e6f82058c64b2e8ab991d7a6d6952191f5febb8463485190dd2296/_data echo -n "Pulling from Git" git pull echo -n "Restarting docker" docker restart home-assistant fi exit 0 <file_sep>/todo.txt #todo.Text - AndroidIP Webcam integration (back yard) - Fix TravisCI automation X Fix Notification tone for doors - Add Bayesian to sense "is BEST here" to change rules - How can I sense if Joel's awake? - Automation to warn Luke, then turn off WiFi to devices. Google Home Hub/Home Mini as BLE Tracker "sources" "Kids Asleep - mute warnings" Button Timers for all the things AdGuard - like piHole but with content blocker OhmConnect Fix rooms where Google homes and lights are
9a3a7776f6bb1834eb6b5bd4c016137323a58e2c
[ "Markdown", "Text", "Shell" ]
3
Markdown
department-g33k/hassio-config
595125fee7c692b038857ef3fb562dadd14e7259
817c4fd9296664832f2e0e9a095928796da04780
refs/heads/master
<file_sep>// Verify that URL exists document.getElementById("submitBtn").addEventListener("click", function(){ console.log("Click registered"); window.location.href = '/processed'; }); <file_sep>beautifulsoup4==4.6.0 certifi==2018.4.16 chardet==3.0.4 click==6.7 cssselect==1.0.3 Flask==1.0.2 Flask-WTF==0.14.2 goose3==3.1.0 idna==2.6 itsdangerous==0.24 jieba==0.39 Jinja2==2.10 lxml==4.2.1 MarkupSafe==1.0 nltk==3.2.5 numpy==1.14.3 Pillow==5.1.0 requests==2.18.4 scikit-learn==0.19.1 scipy==1.0.1 six==1.11.0 sklearn==0.0 tqdm==4.23.2 urllib3==1.22 Werkzeug==0.14.1 WTForms==2.1 <file_sep>from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField from flask_wtf import FlaskForm from wtforms.validators import DataRequired class urlForm(FlaskForm): url = StringField('URL', validators=[DataRequired()]) submit = SubmitField('Submit') class formData(): def __init__(self): self.url = "" self.header = "" self.body = "" self.verdict = "" def set_url(self, url): self.url = url def set_header(self, head): self.header = head def set_body(self, body): self.body =body def set_verdict(self, judgement): self.verdict = judgement<file_sep>import flask APP = flask.Flask('frontend', static_folder=None) <file_sep>import flask from flask import render_template, url_for, request, flash, redirect from utils.form import urlForm, formData from utils.scrape import extractArticle APP = flask.Flask(__name__) articleInfo = formData() @APP.route('/', methods=['GET', 'POST']) def route(): form = urlForm() if form.validate_on_submit(): articleInfo.set_url(form.url.data) # implement in utils.scrape.extractArticle with goose or beautifulsoup downloadArticle = extractArticle(articleInfo.url) downloadArticle.article_contents() articleInfo.set_header(downloadArticle.header) articleInfo.set_body(downloadArticle.body) # analyse stance return render_template('/processed.html', article=articleInfo) return render_template('index.html', title='Submit article', form=form) @APP.route('/processed', methods=['GET', 'POST']) def processed(article=None): if request.method == "POST": return render_template('processed.html', article=article) if __name__ == '__main__': APP.secret_key = 'secret key' APP.config['SESSION_TYPE'] = 'filesystem' # APP.run(debug=True,port=5000) APP.run()<file_sep># import libraries import urllib2 from bs4 import BeautifulSoup # specify url quote_page = ‘https://www.nytimes.com/2018/05/05/business/dealbook/berkshire-hathaway-annual-meeting-stock.html?rref=collection%2Fsectioncollection%2Fbusiness&action=click&contentCollection=business&region=rank&module=package&version=highlights&contentPlacement=1&pgtype=sectionfront' # query the website and return the html to the variable ‘page’ page = urllib2.urlopen(quote_page) # parse the html using beautiful soup and store in variable `soup` soup = BeautifulSoup(page, ‘html.parser’) # Take out the <div> of name and get its value name_box = soup.find(‘h1’, attrs={‘class’: headline}) name = name_box.text.strip() # strip() is used to remove starting and trailing print name
11f0388132dc7eb25e3d44c749bf2970faf81237
[ "JavaScript", "Python", "Text" ]
6
JavaScript
qvandenberg/fnc-1-baseline
79b14083e31067f2caf23616f85ba6e6a6d97509
1beb558b0368a32853f262998b1eb3270d7c8791
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { LoadingController,NavController } from 'ionic-angular'; import { UserSettings } from '../../shared/shared'; import * as _ from 'lodash'; /* Generated class for the Favorites page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-favorites', templateUrl: 'favorites.html' }) export class FavoritesPage { favorites = []; constructor(public navCtrl: NavController, public loadingController: LoadingController, public userSettings: UserSettings) {} ionViewDidLoad() { this.userSettings.getAllFavorites().then(favs => this.favorites = favs); } ionViewDidEnter(){ //this.favorites = this.userSettings.getAllFavorites(); this.userSettings.getAllFavorites().then(favs => this.favorites = favs); } } <file_sep>import { Injectable } from '@angular/core'; import { Events } from 'ionic-angular'; import { Storage } from '@ionic/storage'; import { SQLite } from 'ionic-native'; import { SqlStorage } from './shared'; const win: any = window; @Injectable() export class UserSettings { //storage = new Storage(SqlStorage); public db: SQLite; public sql: SqlStorage; constructor(public events: Events, public storage: Storage) { if (win.sqlitePlugin) { this.sql = new SqlStorage(); } else { console.warn('SQLite plugin not installed. Falling back to regular Ionic Storage.'); } } favoriteTeam(pizza) { let item = { pizza:pizza}; if (this.sql){ this.sql.set(pizza.id.toString(), JSON.stringify(item)).then(data => { this.events.publish('favorites:changed'); }); } else { return new Promise(resolve => { this.storage.set(pizza.id.toString(), JSON.stringify(item)).then(() => { this.events.publish('favorites:changed'); resolve(); }); }); } } unfavoriteTeam(pizza) { if (this.sql){ this.sql.remove(pizza.id.toString()).then(data => { this.events.publish('favorites:changed'); }); } else { return new Promise(resolve => { this.storage.remove(pizza.id.toString()).then(() => { this.events.publish('favorites:changed'); resolve(); }); }); } } isFavoriteTeam(pizzaId) { if (this.sql){ return this.sql.get(pizzaId.toString()).then(value => value ? true : false); } else { return new Promise(resolve => resolve(this.storage.get(pizzaId.toString()).then(value => value ? true : false))); } } getAllFavorites(){ if (this.sql){ return this.sql.getAll(); } else { return new Promise(resolve => { let results = []; this.storage.forEach(data => { results.push(JSON.parse(data)); }); return resolve(results); }); } } initStorage(){ if (this.sql){ return this.sql.initializeDatabase(); } else { return new Promise(resolve => resolve()); } } } <file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; /* Generated class for the Fastfood page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-fastfood', templateUrl: 'fastfood.html' }) export class FastfoodPage { constructor(public navCtrl: NavController) {} ionViewDidLoad() { console.log('Hello FastfoodPage Page'); } } <file_sep>import { Component } from '@angular/core'; import { AlertController, NavController, NavParams, ToastController } from 'ionic-angular'; import { UserSettings } from '../../shared/shared'; /* Generated class for the Detail page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-detail', templateUrl: 'detail.html' }) export class DetailPage { pizza: any={}; isFollowing = false; constructor(public navCtrl: NavController, public navParams: NavParams, public alertController: AlertController, private toastController: ToastController, private userSettings: UserSettings) {} ionViewDidLoad() { this.pizza = this.navParams.data; this.userSettings.isFavoriteTeam(this.pizza.id).then(value => this.isFollowing = value); } toggleFollow(){ if (this.isFollowing) { let confirm = this.alertController.create({ title: 'Unfollow?', message: 'Are you sure you want to unfollow?', buttons: [ { text: 'Yes', handler: () => { this.isFollowing = false; this.userSettings.unfavoriteTeam(this.pizza); let toast = this.toastController.create({ message: 'You have unfollowed this team.', duration: 2000, position: 'bottom' }); toast.present(); } }, { text: 'No' } ] }); confirm.present(); } else { this.isFollowing = true; this.userSettings.favoriteTeam(this.pizza); } } } <file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { Home } from '../home/home'; /* Generated class for the Pizza page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-pizza', templateUrl: 'pizza.html' }) export class PizzaPage { pizza: any[]; pizzas = [ { name: 'HC Elite 7th', image: 'img/pizza.png', price: '18 RON' }, { name: 'HC Elite', image: 'img/pizza.png', price: '19 RON' } ]; constructor(public navCtrl: NavController) {} ionViewDidLoad() { console.log('Hello PizzaPage Page'); } } <file_sep>import { Component, ViewChild } from '@angular/core'; import { Events, Nav,LoadingController, Platform } from 'ionic-angular'; import { StatusBar, Splashscreen } from 'ionic-native'; import { UserSettings } from '../shared/shared'; import { Home } from '../pages/home/home'; import { FavoritesPage } from '../pages/favorites/favorites'; import { PizzaPage } from '../pages/pizza/pizza'; import { DetailPage } from '../pages/detail/detail'; import { InformationPage } from '../information/information'; import { enableProdMode } from '@angular/core'; enableProdMode(); @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; rootPage: any = Home; favoriteFoods: any[]; pages: Array<{title: string, component: any}>; constructor(public platform: Platform, public userSettings: UserSettings, public loadingController: LoadingController, public events: Events) { this.initializeApp(); // used for an example of ngFor and navigation this.pages = [ { title: 'Home', component: Home }, // { title: 'Favorites', component: FavoritesPage } ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. StatusBar.styleDefault(); Splashscreen.hide(); this.platform.registerBackButtonAction(function(event){ let nav=this.app.getComponent('nav'); if (nav.canGoBack()) {nav.pop();} else {this.confirmExitApp(nav);} },101); this.userSettings.initStorage().then(() => { this.rootPage = Home; this.refreshFavorites(); this.events.subscribe('favorites:changed', () => this.refreshFavorites()); }); }); } refreshFavorites(){ this.userSettings.getAllFavorites().then(favs => this.favoriteFoods = favs); //this.favoriteTeams = this.userSettings.getAllFavorites(); } goToFood(favorite){ let loader = this.loadingController.create({ content: 'Getting data...', dismissOnPageChange: true }); loader.present(); this.nav.push(DetailPage, favorite.pizza); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } } <file_sep>import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import {PizzaPage} from '../pizza/pizza'; import {InformationPage} from '../information/information'; declare var window; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class Home { PizzaTab = PizzaPage; pizza: any; constructor(public navCtrl: NavController) { } goToPizza(){ this.navCtrl.push(PizzaPage); } goHome(){ //this.nav.push(MyTeamsPage); this.navCtrl.popToRoot(); } goToInformation(){ this.navCtrl.push(InformationPage); } callIT(passedNumber){ //You can add some logic here window.location = passedNumber; } } <file_sep>import { Component } from '@angular/core'; import { NavController,LoadingController, NavParams } from 'ionic-angular'; import { Home } from '../home/home'; import { DetailPage } from '../detail/detail'; import * as _ from 'lodash'; /* Generated class for the Pizza page. See http://ionicframework.com/docs/v2/components/#navigation for more info on Ionic pages and navigation. */ @Component({ selector: 'page-pizza', templateUrl: 'pizza.html' }) export class PizzaPage { pizza: any={}; sizeFilter = '30'; size: any; allSize: any[]; pizzasFiltered: any[]; pizzas = [ { id: 1, name: '<NAME>', description: 'sos de rosii , mozzarella', weight: 'Cca 490 g', image: 'img/pizza.png', price: '15 RON', size: '30' }, { id: 2, name: '<NAME>', description: 'sos de rosii , mozzarella , carne de pui', weight: 'Cca 480 g', image: 'img/pizza.png', price: '18 RON', size: '50' }, { id: 3, name: '<NAME>', description: 'sos de rosii , mozzarella', weight: 'Cca 490 g', image: 'img/pizza.png', price: '15 RON', size: '30' }, { id: 4, name: '<NAME>', description: 'sos de rosii , mozzarella , carne de pui', weight: 'Cca 480 g', image: 'img/pizza.png', price: '18 RON', size: '50' }, { id: 5, name: '<NAME>', description: 'sos de rosii , mozzarella', weight: 'Cca 490 g', image: 'img/pizza.png', price: '15 RON', size: '30' }, { id: 6, name: '<NAME>', description: 'sos de rosii , mozzarella , carne de pui,sos de rosii , mozzarella , carne de pui', weight: 'Cca 480 g', image: 'img/pizza.png', price: '18 RON', size: '30' } ]; constructor(public navCtrl: NavController, public navParams: NavParams, public loadingController: LoadingController) {} ionViewDidLoad() { this.filterSize(); } ionViewWillEnter(){ this.refreshAll(this); } itemTapped($event, pizza){ let loader = this.loadingController.create({ content: 'Getting data...', dismissOnPageChange: true }); loader.present(); this.navCtrl.parent.parent.push(DetailPage, pizza); } filterSize(){ if(this.sizeFilter === '30'){ this.pizzasFiltered = _.filter(this.pizzas,{size:'30'}); } else { this.pizzasFiltered = _.filter(this.pizzas,{size:'50'}); } } refreshAll(refresher){ this.ionViewDidLoad(); } } <file_sep>import { NgModule, ErrorHandler } from '@angular/core'; import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; import { MyApp } from './app.component'; import { Storage } from '@ionic/storage'; import { UserSettings } from '../shared/shared'; import { Home } from '../pages/home/home'; import { FavoritesPage } from '../pages/favorites/favorites'; import { PizzaPage } from '../pages/pizza/pizza'; import { DetailPage } from '../pages/detail/detail'; import {InformationPage} from '../pages/information/information'; import { enableProdMode } from '@angular/core'; enableProdMode(); @NgModule({ declarations: [ MyApp, Home, FavoritesPage, PizzaPage, InformationPage, DetailPage, ], imports: [ IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, Home, FavoritesPage, PizzaPage, InformationPage, DetailPage ], providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},Storage,UserSettings] }) export class AppModule {} <file_sep>export * from './usersettings'; export * from './sqlstorage';
f8527a119c3658fa7164730dfbc621ba1c577e4c
[ "TypeScript" ]
10
TypeScript
stevedevelope17/Pizzerie
20240ee9bf098e66ad4f58716612821f1fa388d2
5d480bef6e6722e95f9e714aa6ff044dc77a9cf1
refs/heads/master
<repo_name>logandk/permalink_fu_hacks<file_sep>/lib/accents.rb module PermalinkFu class << self def escape_with_accents(string) result = string.to_s result.gsub!(/[\xE6]/, 'ae') result.gsub!(/[\xC6]/, 'Ae') result.gsub!(/[\xF8]/, 'oe') result.gsub!(/[\xD8]/, 'Oe') result.gsub!(/[\xE5]/, 'aa') result.gsub!(/[\xC5]/, 'Aa') escape_without_accents(result) end alias_method_chain :escape, :accents end end <file_sep>/README.markdown permalink_fu hack - SEO Friendly Danish Accents ================================================= This is a Ruby on Rails plugin, hacks the `permalink_fu` plugin to correctly replace danish accents. The purpose of using an [Evil Twin](http://errtheblog.com/posts/67-evil-twin-plugin) plugin is not to interfere with the `permalink_fu` plugin for people not requiring this specific functionality. The plugin makes sure that `permalink_fu` replaces the following accents: * æ => ae * ø => oe * å => aa * Æ => Ae * Ø => Oe * Å => Aa Installation ============ As a Rails Plugin ----------------- Use this to install as a plugin in a Ruby on Rails app: $ script/plugin install git://github.com/logandk/permalink_fu_hacks.git As a Rails Plugin (using git submodules) ---------------------------------------- Use this if you prefer the idea of being able to easily switch between using edge or a tagged version: $ git submodule add git://github.com/logandk/permalink_fu_hacks.git vendor/plugins/permalink_fu_hacks Usage ===== Besides installation, you don't have to do anything to use this plugin. It simply overrides the `escape` method of the `PermalinkFu` class, to escape danish accents. When you have installed the plugin using the instructions above, just use `permalink_fu` as you normally would. Credits ======= [permalink_fu](http://github.com/technoweenie/permalink_fu/tree/master) is developed by Technoweenie. Copyright (c) 2009 <NAME>, released under the MIT license
3ae77225bb1012049dc8b6ca8adf11f8e5e92573
[ "Markdown", "Ruby" ]
2
Ruby
logandk/permalink_fu_hacks
58946fd617fe8bdb9c42f8da1bde4582e5aaa89c
3ef185c70e3644832f0933e2a501b89ab8c49543
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_many :visits validates :user_name, presence: true, length: { maximum: 30 } validates :user_firstname, presence: true, length: { maximum: 30 } validates :user_lastname, presence: true, length: { maximum: 30 } scope :last_created, -> (x) { order(created_at: :desc).limit(x) } end <file_sep>require 'rails_helper' RSpec.describe LocationsController, :type => :controller do describe "finding index and show" do # it "renders index" do # get :index # expect(response).to render_template('index') # end # it "renders show" do # loc = Location.create # get :show, id:loc.id # expect(response).to render_template('show') # end # it "gets #show" do # loc = Location.create # get :show, id:loc.id # expect(assigns(:location)).to eq(loc) # end # it "returns ok if location with that id exists" do # loc = Location.create # get :show, id:loc.id # expect(response).to have_http_status(:ok) # end # it "returns 404 if location with that id does not exist" do # loc = Location.create # get :show, id:loc.id # expect(response).to have_http_status(404) # end end end <file_sep>require 'rails_helper' RSpec.describe Visit, :type => :model do describe "test validation of user_name" do it "must be present" do visit = Visit.new expect(visit.valid?).to eq (false) end it "must be less than 30 characters" do visit = Visit.new user_name: 'wwwwwooooorrrrrrfffffnnnnnssssssllllll' expect(visit.valid?).to eq (false) end it "must be only alphanumeric" do visit = Visit.new user_name: '123' expect(visit.valid?).to eq (false) end end describe "test validation of location_id" do it "must be present" do visit = Visit.new expect(visit.valid?).to eq (false) end it "must be only numeric" do visit = Visit.new location_id: 'abc' expect(visit.valid?).to eq (false) end end describe "test validation of from_date" do it "must be present" do visit = Visit.new expect(visit.valid?).to eq (false) end it "must be be in the future" do visit = Visit.new from_date: (Time.now - 1.day) expect(visit.valid?).to eq (false) end it "from_date must be earlier than to_date" do visit = Visit.new from_date: (Time.now + 1.day), to_date: Time.now expect(visit.valid?).to eq (false) end end describe "test validation of to_date" do it "must be present" do visit = Visit.create expect(visit.valid?).to eq (false) end end end <file_sep>class LocationsController < ApplicationController def index @locations = Location.last_created(10) render 'not_found', status:404 unless @locations end def show @location = Location.find_by(id: params[:id]) render 'not_found', status:404 unless @location end def new @location = Location.new render 'new' end def create @location = Location.new location_params #@visit.user = User.find(session[:user_id]) if @location.save flash[:notice] = "Location created" redirect_to action: 'index', controller: 'locations' else render 'new' end end def destroy @location = Location.find(params[:id]) @location.destroy flash[:notice] = "Location deleted" redirect_to action: 'index' end def update @location = Location.find(params[:id]) if @location.update_attributes location_params flash[:notice] = "Location updated" redirect_to action: 'show', controller: 'locations', id: @location.id else flash[:error] = "Location not updated" @errors = location.errors.full_messages render 'edit' end end def edit @location = Location.find(params[:id]) end private def location_params params.require(:location).permit(:name, :city, :country, :zip_code, :description) end end<file_sep>class Visit < ActiveRecord::Base #set up relationship between visits and locations belongs_to :location belongs_to :user #validation validates :from_date, presence: true validates :to_date, presence: true validates :user_id, presence: true validates :location_id, presence: true, numericality: { only_integer: true } validate :from_date_in_future validate :from_date_is_before_to_date def from_date_in_future if from_date < Time.now errors.add(:from_date, "cannot be in the past.") end end def from_date_is_before_to_date if from_date.to_i > to_date.to_i errors.add(:from_date, "cannot be after the 'to date'.") end end end <file_sep>require 'rails_helper' RSpec.describe Location, :type => :model do #pending "add some examples to (or delete) #{__FILE__}" describe "testing iron_find method" do Location.create(name: 'SpecTest', city: 'Nowhere') it "iron_find functions as .find" do expect(Location.iron_find(1)).to eq(Location.find(1)) end end describe "testing last_created method" do Location.create name: 'Dom', city: 'Koeln', country: 'Germany', zip_code: 50660, description: "Koeln Cathedral" Location.create name: 'Sants', city: 'Barcelona', country: 'Spain' Location.create name: '<NAME>el', city: 'Melbourne', country: 'Australia', zip_code: 3070, description: "Best pub in Melbourne" Location.create name: '<NAME>', city: 'Melbourne', country: 'Australia', zip_code: 3071, description: "Thornbury House" Location.create name: 'Pioch', city: 'Montpellier', country: 'France', zip_code: 34090, description: "Our flat in Monty P" Location.create name: 'Hbf', description: "Main Station" it "last_created functions as .order(created_at: :desc).limit(3)" do expect(Location.last_created(3)).to eq(Location.order(created_at: :desc).limit(3)) end end describe "testing in_spain? method" do Location.create name: 'MOB', city: 'Barcelona', country: 'Spain', description: "Barcelona Main Station" Location.create name: 'Sants', city: 'Barcelona', country: 'Spain' Location.create name: 'Tramway Hotel', city: 'Melbourne', country: 'Australia', zip_code: 3070, description: "Best pub in Melbourne" Location.create name: '<NAME>', city: 'Melbourne', country: 'Australia', zip_code: 3071, description: "Thornbury House" Location.create name: 'Pioch', city: 'Montpellier', country: 'France', zip_code: 34090, description: "Our flat in Monty P" Location.create name: 'Hbf', description: "Main Station" it "only shows locations with Country = Spain" do expect(Location.in_spain?).to eq(Location.where(country: 'Spain')) end end # describe "find visits for a location" do # it "returns a count of all the visits for a location for a month" do # loc10 = Location.create name: '<NAME>', city: 'Melbourne', country: 'Australia', zip_code: 3070, description: "Best pub in Melbourne" # Visit.create location_id: loc10.id, user_name: 'Cat', from_date: (DateTime.now - 3.hours), to_date: (DateTime.now) # Visit.create location_id: loc10.id, user_name: 'Tom', from_date: (DateTime.now - 3.hours), to_date: (DateTime.now) # Visit.create location_id: loc10.id, user_name: 'Dario', from_date: (DateTime.now - 8.hours), to_date: (DateTime.now - 7.hours) # expect(loc10.monthly_visits(7,2014).count).to eq(3) # end # end describe "test validation of name" do it "must be present" do location = Location.new expect(location.valid?).to eq (false) end it "must be less than 30 characters" do location = Location.new name: 'wwwwwooooorrrrrrfffffnnnnnssssssllllll' expect(location.valid?).to eq (false) end it "must be only alphanumeric" do location = Location.new name: '123' expect(location.valid?).to eq (false) end end describe "test validation of city" do it "must be present" do location = Location.new expect(location.valid?).to eq (false) end it "must be less than 30 characters" do location = Location.new city: 'wwwwwooooorrrrrrfffffnnnnnssssssllllll' expect(location.valid?).to eq (false) end it "must be only alphanumeric" do location = Location.new city: '123' expect(location.valid?).to eq (false) end end describe "test validation of country" do it "must be present" do location = Location.new expect(location.valid?).to eq (false) end it "must be less than 30 characters" do location = Location.new country: 'wwwwwooooorrrrrrfffffnnnnnssssssllllll' expect(location.valid?).to eq (false) end it "must be only alphanumeric" do location = Location.new country: '123' expect(location.valid?).to eq (false) end end describe "test validation of zip_code" do it "must be present" do location = Location.new expect(location.valid?).to eq (false) end it "must be less than 6 characters" do location = Location.new zip_code: '1234567' expect(location.valid?).to eq (false) end it "must be only numeric" do location = Location.new zip_code: 'abc' expect(location.valid?).to eq (false) end end describe "test validation of description" do it "must be present" do location = Location.new expect(location.valid?).to eq (false) end it "must be less than 256 characters" do location = Location.new description: '123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890abcdefghijklmnop...................................................' expect(location.valid?).to eq (false) end end end<file_sep>module ApplicationHelper def flash_message flash_message_format(:notice) ||flash_message_format(:error) end def flash_message_format(type) if flash[type] content_tag :div, class: "#{type} message" do content_tag :p do flash[type] end end end end def delete_button end end <file_sep>class HomeController < ApplicationController def welcome #as the method name is the same as the control, there is no need to render #render "welcome" end def contact #render "contact" end end <file_sep>class Location < ActiveRecord::Base #set up relationship between visits and locations has_many :visits has_many :users #initial validation validates :name, presence: true, length: { maximum: 30 } validates :city, presence: true, length: { maximum: 30 }, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } validates :country, presence: true, length: { maximum: 30 }, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } validates :zip_code, presence: true, length: { maximum: 5 }, numericality: { only_integer: true } validates :description, presence: true, length: { maximum: 255 } # because we created the class Locations, this command is not necessary #set_table_name 'locations' def self.iron_find(i) Location.where(id:i).first end # def self.last_created(x) # Location.order(created_at: :desc).limit(x) # end scope :last_created, -> (x) { order(created_at: :desc).limit(x) } def self.in_spain? Location.where(country: 'Spain') end def monthly_visits(m,y) #better query because it's not running through all visits then querying on locations self.visits.where('extract(year from from_date) = ?', y).where('extract(month from from_date) = ?', m) # Visit.where('extract(year from from_date) = ?', y).where('extract(month from from_date) = ?', m).where(location_id:self.id).count end end <file_sep>class VisitsController < ApplicationController def index @location = Location.find(params[:location_id]) @visits = @location.visits render 'not_found', status:404 unless @visits end def show @location = Location.find(params[:id]) @visit = Visit.find(params[:id]) @user = @visit.user.id render 'not_found', status:404 unless @visit end def new @location = Location.find(params[:location_id]) @visit = Visit.new render 'new' end def create @location = Location.find(params[:location_id]) @visit = @location.visits.new visit_params #@visit.user = User.find(session[:user_id]) if @visit.save flash[:notice] = "Visit created" redirect_to action: 'index', controller: 'visits', location_id: @location.id else render 'new' end end def destroy @location = Location.find(params[:location_id]) @visit = Visit.find(params[:id]) @visit.destroy flash[:notice] = "Visit deleted" redirect_to action: 'index', controller: 'visits', location_id: @location.id end def update @location = Location.find(params[:location_id]) @visit = @location.visits.find(params[:id]) if @visit.update_attributes visit_params flash[:notice] = "Visit updated" redirect_to action: 'index', controller: 'visits', location_id: @location.id else flash[:error] = "Visit not updated" @errors = visit.errors.full_messages render 'edit' end end def edit @location = Location.find(params[:location_id]) @visit = Visit.find(params[:id]) end private def visit_params params.require(:visit).permit(:user_id, :user_name, :from_date, :to_date) end end
52dd6dae634ab768961d226fcee9daca383f2efb
[ "Ruby" ]
10
Ruby
catburston/RoR-practice
5ec0d53e8492d426dda64cb0a82016d9fc76cc84
39f6377cee73f35fa902e0aca31f36d5114692bc
refs/heads/master
<repo_name>CharityBunyon/twiliopractice<file_sep>/twiliopractice/Program.cs using System; using System.Linq; using Twilio; using Twilio.Rest.Api.V2010.Account; namespace twiliopractice { class Program { static void Main(string[] args) { // Find your Account Sid and Token at twilio.com/console // DANGER! This is insecure. See http://twil.io/secure const string accountSid = "AC6072ff9abad24ebeece0827cc00664f5"; const string authToken = ""; TwilioClient.Init(accountSid, authToken); var mediaUrl = new[] { new Uri("https://pbs.twimg.com/profile_images/679818776670371840/h4PrZuJd.png") }.ToList(); // using Linq to convert it to a linq object var message = MessageResource.Create( body: "Sending an image.", from: new Twilio.Types.PhoneNumber("+12095800301"), mediaUrl: mediaUrl, to: new Twilio.Types.PhoneNumber("+16159676153") ); Console.WriteLine(message.Sid); } } }
f1b69234de6dd2adf549929f08c7f357bcf566ac
[ "C#" ]
1
C#
CharityBunyon/twiliopractice
43b2ca613b4a017b02032b7d57fdeeab2f8fa605
caaf3201c9dbaec4bcc66ebc44988c6cb255e8ea
refs/heads/master
<file_sep>/** * My API Sandbox * */ Sandbox.define('/rest/cellule/166', 'GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 152, "libelleFR": "lib_fr", "libelleEN": "lib_en", "pole": 151, "region": 101, "metier": 102, "coParent": 151, "niveau": "METIER", "pays": 1, "mailGenerique": "<EMAIL>", "langueMail": "FR", "personnesHabilites": [{ "uid": 123456, "nom": "Jean", "prenom": "Jean" }], "avisBusinessRequis": true, "avisBusinessObligatoire": false, "partageDeDossierAutorise": true, "saisieAutoriseNiveau1": false, "transfertDansSTAR": true, "themes": ["ARMEMENT"], "typeCo": "CG", "historique": { "creationDate": "2012-03-04", "creationUsername": "cr_username", "creationNom": "cr_nom", "creationPrenom": "cr_prenom", "modificationDate": "2013-03-04", "modificationUsername": "mod_username", "modificationNom": "mod_nom", "modificationPrenom": "mod_prenom", "suppresionDate": "2014-03-04", "suppresionUsername": "sup_username", "suppresionNom": "sup_nom", "suppresionPrenom": "sup_prenom", "dateDernierConnexion": "2014-03-03" } }); }) Sandbox.define('/rest/celluleactive', 'GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json([{ "id": 157, "libelleFR": "lib_fr", "libelleEN": "lib_en", "pole": 150, "region": 101, "metier": 102, "coParent": 151, "niveau": "POLE", "pays": 1, "mailGenerique": "<EMAIL>", "langueMail": "FR", "personnesHabilites": [{"uid": 123456, "nom": "Jean", "prenom": "Jean"}], "avisBusinessRequis": true, "avisBusinessObligatoire": false, "partageDeDossierAutorise": true, "saisieAutoriseNiveau1": false, "transfertDansSTAR": true, "themes": ["ARMEMENT"], "typeCo": "CG", "historique": { "creationDate": "2012-03-04", "creationUsername": "cr_username", "creationNom": "cr_nom", "creationPrenom" :"cr_prenom", "modificationDate": "2013-03-04", "modificationUsername": "mod_username", "modificationNom": "mod_nom", "modificationPrenom": "mod_prenom", "suppresionDate": "2014-03-04", "suppresionUsername": "sup_username", "suppresionNom": "sup_nom", "suppresionPrenom": "sup_prenom", "dateDernierConnexion": "2014-03-03" } }, {"id": 156, "libelleFR": "lib", "libelleEN": "lib_en", "pole": 150, "region": 101, "metier": 102, "coParent": 152, "niveau": "POLE", "pays": 1, "mailGenerique": "<EMAIL>", "langueMail": "FR", "personnesHabilites": [{"uid": 123456, "nom": "Jean", "prenom": "Jean"}], "avisBusinessRequis": true, "avisBusinessObligatoire": false, "partageDeDossierAutorise": true, "saisieAutoriseNiveau1": false, "transfertDansSTAR": true, "themes": ["ARMEMENT"], "typeCo": "CG", "historique": { "creationDate": "2012-03-04", "creationUsername": "username", "creationNom": "nom", "creationPrenom" :"prenom", "modificationDate": "2013-03-04", "modificationUsername": "username", "modificationNom": "nom", "modificationPrenom": "prenom", "suppresionDate": "2014-03-04", "suppresionUsername": "username", "suppresionNom": "nom", "suppresionPrenom": "prenom", "dateDernierConnexion": "2014-03-03" } } ]); }) Sandbox.define('/rest/cellule','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": "199" }); }) Sandbox.define('/rest/mesTaches','GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "taches": [{ "idDossier": 250, "poleEmettrice": 151, "coEmettrice": 152, "demandeur": "<NAME>", "pays": 2, "coDestinatrice": 152, "action": "CREER_DOSSIER", "theme": "ARMEMENT", "escalade": "AVIS", "dateReception": "2014-12-15", "dateRetour": "2014-12-15", "detailDemande": "<b>Detaile du demande</b> Detaile du demande Detaile du demande Detaile du demande <ul><li>wer</li><li>sss</li></ul>" }, { "idDossier": 250, "poleEmettrice": 151, "coEmettrice": 152, "demandeur": "<NAME>", "pays": 2, "coDestinatrice": 152, "action": "CREER_DOSSIER", "theme": "ARMEMENT", "escalade": "AVIS", "dateReception": "2014-12-15", "dateRetour": "2014-12-15", "detailDemande": "<b>Detaile du demande</b> Detaile du demande Detaile du demande Detaile du demande <ul><li>wer</li><li>sss</li></ul>" }], "nbDossiers": 2 }); }) Sandbox.define('/rest/suiviDossiers','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "dossiers": [{ "idDossier": 250, "pole": 151, "coEmettrice": 152, "demandeur": "<NAME>", "pays": 1, "traiterPar": 152, "action": "ACTION1", "theme": "ARMEMENT", "escalade": "AVIS", "dateReception": "2014-12-15", "dateRetour": "2014-12-16", "detailDemande": "<b>Detaile duddd demande</b> Detaile du demande Detaile du demande Detaile du demande", "statut": "AUCUN" }, { "idDossier": 250, "pole": 152, "coEmettrice": 152, "demandeur": "<NAME>", "pays": 1, "traiterPar": 152, "action": "ACTION1", "theme": "ARMEMENT", "escalade": "AVIS", "dateReception": "2014-12-16", "dateRetour": "2014-12-16", "detailDemande": "<b>Detaile du4444 demande</b> Detaile du demande Detaile du demande Detaile du demanade", "statut": "AUCUN" }], "nbTaches": 2 }); }) Sandbox.define('/rest/dossier/new','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "cgOnlyActiveCells": false, "poleCells": [150, 156], "cgCells": [150], "cellsForPole": { "150": [150, 152, 153, 154, 155], "156": [161, 156, 158, 159, 160] } }); }) Sandbox.define('/rest/dossier/250/reopen','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "cgOnlyActiveCells": false, "poleCells": [150, 156], "cgCells": [150], "cellsForPole": { "150": [153, 154, 155], "156": [158, 159] }, "typeEscalade": {"PPE":["ARBITRAGE", "AVIS"]} }); }) Sandbox.define('/rest/dossier/250/copy','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "cgOnlyActiveCells": false, "poleCells": [150, 156], "cgCells": [150], "cellsForPole": { "150": [150, 152], "156": [161, 156] }, "typeEscalade": {"PPE":["ARBITRAGE", "AVIS"]} }); }) Sandbox.define('/rest/dossier/250/escalade','GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "typeEscalade": [ "DECISION", "ARBITRAGE", "AVIS", "INFORMATION" ], "coDestinataireForTypeEscalade": { "ARBITRAGE": [151] }, "repondreRequired": false, "coDestinataire": [150, 151, 152], "documents": [{ "name": "Document attach? No.1", "date": "2014-02-04" }, { "name": "Document attach? No.2", "date": "2014-06-11" }] }); }) Sandbox.define('/rest/recherche/refog','GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "users": [{ "idAnnuaire": 123, "nom": "Nom1", "prenom": "Prenom1" }, { "idAnnuaire": 124, "nom": "Nom2", "prenom": "Prenom2" }, { "idAnnuaire": 123, "nom": "Nom1", "prenom": "Prenom1" }, { "idAnnuaire": 124, "nom": "Nom2", "prenom": "Prenom2" }] }); }) Sandbox.define('/rest/dossier/250/escalade/etapes','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "etapesEscalade": [{ "niveauDecis": "POLE", "pays": null, "coDestinatrice": 151, "nomEtPrenom": "TestPrenom TestNom", "dateDuJour": "2015-01-21", "commentaires": "<b>xxx</b>", "pole": 151, "typeEscalade": "DECISION" }, { "niveauDecis": "POLE", "pays": null, "coDestinatrice": 151, "nomEtPrenom": "TestPrenom TestNom", "dateDuJour": "2015-01-21", "commentaires": "<b>xxx</b>", "pole": 151, "typeEscalade": "AVIS" }, { "niveauDecis": "POLE", "pays": null, "coDestinatrice": 151, "nomEtPrenom": "TestPrenom TestNom", "dateDuJour": "2015-01-22", "commentaires": "<b>xxx</b>", "pole": 151, "typeEscalade": "ARBITRAGE" }, { "niveauDecis": "POLE", "pays": null, "coDestinatrice": 151, "nomEtPrenom": "TestPrenom TestNom", "dateDuJour": "2015-01-22", "commentaires": "<b>xxx</b>", "pole": 151, "typeEscalade": "INFORMATION" }] }); }) Sandbox.define('/rest/user','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "utilisateurs": [{ "id": 1, "fullName": "GIGI" }] }); }) Sandbox.define('/rest/dossier/250/escalade','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(201); // Send the response body. res.json({ "value": 250 }); }) Sandbox.define('/rest/dossier/250/information','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 111 }); }) Sandbox.define('/rest/dossier/250/avis','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 111 }); }) Sandbox.define('/rest/dossier/250/decision','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 111 }); }) Sandbox.define('/rest/dossier/250/arbitrage','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 111 }); }) Sandbox.define('/rest/dossier/250/lock','DELETE', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/keepalive','GET', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/document','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 152 }); }) Sandbox.define('/rest/reference','GET', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response.F res.status(200); // Send the response body. res.json({ "PARAMETERS": [{ "id": "THEME", "label": "THEME", "isEditable": false }, { "id": "CELLULE", "label": "CELLULE", "isEditable": true }], "LANGUAGE": [{ "id": "FR", "label": "FRANCAIS" }, { "id": "EN", "label": "ANGALIS" }], "DATE_FORMAT": [{ "id": "0", "label": "dd/MM/yyyy" }, { "id": "1", "label": "MM/dd/yyyy" }], "USER_SEARCH_STATUT": [{ "id": "ACTIF", "label": "ACTIF" }, { "id": "INACTIF", "label": "INACTIF" }], "USER": [{ "id": 1, "username": "216739", "nom": "Basset", "prenom": "Antoine", "cellules": [150], "active": true }, { "id": 2, "username": "191541", "nom": "Viez", "prenom": "Florence", "cellules": [1] }, { "id": 3, "username": "185012", "nom": "Perruchot", "prenom": "C?dric", "cellules": [1] }, { "id": 4, "username": "276512", "nom": "Martinez", "prenom": "Luis", "cellules": [2] }, { "id": 5, "username": "114395", "nom": "Robert ", "prenom": "S?verine", "cellules": [2] }, { "id": 6, "username": "140961", "nom": "Aucher", "prenom": "Nicole", "cellules": [2] }, { "id": 7, "username": "113224", "nom": "Terrier", "prenom": "Jean-Michel", "cellules": [4] }, { "id": 8, "username": "204259", "nom": "Callegari", "prenom": "Marie-Andr?e", "cellules": [5] }, { "id": 9, "username": "114386", "nom": "Michelin", "prenom": "Christophe", "cellules": [6] }, { "id": 10, "username": "829788", "nom": "Schwartz ", "prenom": "Shaheen", "cellules": [6] }, { "id": 11, "username": "417344", "nom": "Duranthon ", "prenom": "Caroline", "cellules": [6] }, { "id": 12, "username": "353821", "nom": "Emery ", "prenom": "Marie-Eve", "cellules": [6] }, { "id": 13, "username": "114830", "nom": "Ditisheim ", "prenom": "Philippe", "cellules": [7] }, { "id": 14, "username": "512489", "nom": "Marquer ", "prenom": "Ephraim", "cellules": [8] }, { "id": 15, "username": "113653", "nom": "Bourdel ", "prenom": "Stephane", "cellules": [9] }, { "id": 16, "username": "202862", "nom": "Baugier ", "prenom": "Pascal", "cellules": [9] }, { "id": 17, "username": "204260", "nom": "Chiffre ", "prenom": "Stephane", "cellules": [9] }, { "id": 18, "username": "153503", "nom": "Mathieu ", "prenom": "Bertrand", "cellules": [9] }, { "id": 19, "username": "114412", "nom": "Checri ", "prenom": "Marc", "cellules": [10] }, { "id": 20, "username": "133592", "nom": "Tartelin ", "prenom": "Philippe", "cellules": [10] }, { "id": 21, "username": null, "nom": "Ouoba ", "prenom": "Annie", "cellules": [11] }, { "id": 35, "username": "000000", "nom": "Rentea ", "prenom": "Victor", "cellules": [7] }, { "id": 31, "username": "978797", "nom": "Dura ", "prenom": "Claudia", "cellules": [12] }, { "id": 32, "username": "19519", "nom": "Gadiuta ", "prenom": "Dan", "cellules": [13] }, { "id": 33, "username": "978799", "nom": "Petre ", "prenom": "Alexandru", "cellules": [14] }, { "id": 34, "username": "996601", "nom": "Herbaut ", "prenom": "Fabienne", "cellules": [15] }, { "id": 36, "username": "a02245", "nom": "Dorobantu ", "prenom": "Bogdan", "cellules": [15] }, { "id": 37, "username": "346630", "nom": "Moevi ", "prenom": "Mathilde", "cellules": [100] }, { "id": 85, "username": "u32", "nom": "u32", "prenom": "John", "cellules": [501200, 100] }, { "id": 85, "username": "u32", "nom": "u32", "prenom": "John", "cellules": [501200, 100] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 53, "username": "u0", "nom": "u0", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 54, "username": "u1", "nom": "u1", "prenom": "John", "cellules": [165, 181, 197, 162, 165, 181, 197, 162] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 55, "username": "u2", "nom": "u2", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 56, "username": "u3", "nom": "u3", "prenom": "John", "cellules": [166, 182, 198, 163, 166, 182, 198, 163] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 57, "username": "u4", "nom": "u4", "prenom": "John", "cellules": [167, 183, 199, 164, 167, 183, 199, 164] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 58, "username": "u5", "nom": "u5", "prenom": "John", "cellules": [164, 167, 183, 199, 164, 167, 183, 199] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 59, "username": "u6", "nom": "u6", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 60, "username": "u7", "nom": "u7", "prenom": "John", "cellules": [168, 184, 200, 168, 184, 200] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 61, "username": "u8", "nom": "u8", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 62, "username": "u9", "nom": "u9", "prenom": "John", "cellules": [169, 185, 201, 169, 185, 201] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 63, "username": "u10", "nom": "u10", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 64, "username": "u11", "nom": "u11", "prenom": "John", "cellules": [170, 186, 202, 170, 186, 202] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 65, "username": "u12", "nom": "u12", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 66, "username": "u13", "nom": "u13", "prenom": "John", "cellules": [171, 187, 203, 171, 187, 203] }, { "id": 67, "username": "u14", "nom": "u14", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 67, "username": "u14", "nom": "u14", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 67, "username": "u14", "nom": "u14", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 67, "username": "u14", "nom": "u14", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 68, "username": "u15", "nom": "u15", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 68, "username": "u15", "nom": "u15", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 68, "username": "u15", "nom": "u15", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 68, "username": "u15", "nom": "u15", "prenom": "John", "cellules": [172, 188, 172, 188] }, { "id": 69, "username": "u16", "nom": "u16", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 69, "username": "u16", "nom": "u16", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 69, "username": "u16", "nom": "u16", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 69, "username": "u16", "nom": "u16", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 70, "username": "u17", "nom": "u17", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 70, "username": "u17", "nom": "u17", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 70, "username": "u17", "nom": "u17", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 70, "username": "u17", "nom": "u17", "prenom": "John", "cellules": [173, 189, 173, 189] }, { "id": 71, "username": "u18", "nom": "u18", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 71, "username": "u18", "nom": "u18", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 71, "username": "u18", "nom": "u18", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 71, "username": "u18", "nom": "u18", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 72, "username": "u19", "nom": "u19", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 72, "username": "u19", "nom": "u19", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 72, "username": "u19", "nom": "u19", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 72, "username": "u19", "nom": "u19", "prenom": "John", "cellules": [174, 190, 174, 190] }, { "id": 73, "username": "u20", "nom": "u20", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 73, "username": "u20", "nom": "u20", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 73, "username": "u20", "nom": "u20", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 73, "username": "u20", "nom": "u20", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 74, "username": "u21", "nom": "u21", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 74, "username": "u21", "nom": "u21", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 74, "username": "u21", "nom": "u21", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 74, "username": "u21", "nom": "u21", "prenom": "John", "cellules": [175, 191, 175, 191] }, { "id": 75, "username": "u22", "nom": "u22", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 75, "username": "u22", "nom": "u22", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 75, "username": "u22", "nom": "u22", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 75, "username": "u22", "nom": "u22", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 76, "username": "u23", "nom": "u23", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 76, "username": "u23", "nom": "u23", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 76, "username": "u23", "nom": "u23", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 76, "username": "u23", "nom": "u23", "prenom": "John", "cellules": [176, 192, 176, 192] }, { "id": 77, "username": "u24", "nom": "u24", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 77, "username": "u24", "nom": "u24", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 77, "username": "u24", "nom": "u24", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 77, "username": "u24", "nom": "u24", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 78, "username": "u25", "nom": "u25", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 78, "username": "u25", "nom": "u25", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 78, "username": "u25", "nom": "u25", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 78, "username": "u25", "nom": "u25", "prenom": "John", "cellules": [177, 193, 177, 193] }, { "id": 79, "username": "u26", "nom": "u26", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 79, "username": "u26", "nom": "u26", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 79, "username": "u26", "nom": "u26", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 79, "username": "u26", "nom": "u26", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 80, "username": "u27", "nom": "u27", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 80, "username": "u27", "nom": "u27", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 80, "username": "u27", "nom": "u27", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 80, "username": "u27", "nom": "u27", "prenom": "John", "cellules": [178, 194, 178, 194] }, { "id": 81, "username": "u28", "nom": "u28", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 81, "username": "u28", "nom": "u28", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 81, "username": "u28", "nom": "u28", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 81, "username": "u28", "nom": "u28", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 82, "username": "u29", "nom": "u29", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 82, "username": "u29", "nom": "u29", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 82, "username": "u29", "nom": "u29", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 82, "username": "u29", "nom": "u29", "prenom": "John", "cellules": [179, 195, 179, 195] }, { "id": 83, "username": "u30", "nom": "u30", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 83, "username": "u30", "nom": "u30", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 83, "username": "u30", "nom": "u30", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 83, "username": "u30", "nom": "u30", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 84, "username": "u31", "nom": "u31", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 84, "username": "u31", "nom": "u31", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 84, "username": "u31", "nom": "u31", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 84, "username": "u31", "nom": "u31", "prenom": "John", "cellules": [180, 196, 180, 196] }, { "id": 501151, "username": "1234", "nom": "Doe", "prenom": "John", "cellules": [150, 152] }, { "id": 501151, "username": "1234", "nom": "Doe", "prenom": "John", "cellules": [150, 152] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }, { "id": 501150, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "cellules": [151, 150, 152, 153, 154, 155] }], "RESULTAT": [{ "id": 2401, "label": "Neant", "active": true, "isAutre": false }, { "id": 2402, "label": "Autres", "active": true, "isAutre": true }, { "id": 119, "label": "Resultat Inactive", "active": false, "isAutre": false }], "REPONSE_AVIS": [{ "id": 30100, "label": "Favorable", "active": true, "isAutre": false }, { "id": 30200, "label": "Favorable avec r??serves", "active": true, "isAutre": false }, { "id": 30300, "label": "D??favorable", "active": true, "isAutre": false }, { "id": 117, "label": "ReponseAvis Inactive", "active": false, "isAutre": false }], "TYPE_RELATION": [{ "id": 2201, "label": "Client", "active": true, "isAutre": false }, { "id": 2202, "label": "Prospect", "active": true, "isAutre": false }, { "id": 2203, "label": "Interm??diaire", "active": true, "isAutre": false }, { "id": 2204, "label": "Collaborateur", "active": true, "isAutre": false }, { "id": 126, "label": "TypeRelation Inactive", "active": false, "isAutre": false }], "OUI_NON": [{ "id": true, "label": "Oui" }, { "id": false, "label": "Non" }], "ACTION_AUDIT": [{ "id": "NO_ACTION", "label": "Aucune action", "active": true }, { "id": "CREER_DOSSIER", "label": "Dossier cr?? ", "active": true }, { "id": "ESCALADER_DOSSIER", "label": "Escalad?", "active": true }, { "id": "REPONDRE_DEMANDE", "label": "D?cision enregistr?e", "active": true }, { "id": "CLORE_DOSSIER", "label": "Cl?tur?", "active": true }, { "id": "ESCALADER_CO", "label": "Dossier cr??", "active": true }, { "id": "RENVOYER_DOSSIER", "label": "Renvoy? sans traitement", "active": true }, { "id": "DEMANDER_CYCLE", "label": "Nouveau cycle de d?cision demand?", "active": true }, { "id": "PROPOSER_TRANSFERT", "label": "Transf?r? - En attente d'acceptation", "active": true }, { "id": "ACCEPTER_TRANSFERT", "label": "Transfert accept?", "active": true }, { "id": "REFUSER_TRANSFERT", "label": "Transfert refus?", "active": true }, { "id": "REPRESENTER_DOSSIER", "label": "Dossier repr?sent?", "active": true }, { "id": "POSER_QUESTION", "label": "Question pos?e", "active": true }, { "id": "MODIFIER_DOSSIER", "label": "Donn?es modifi?es", "active": true }, { "id": "SUSPENDRE_DOSSIER", "label": "En suspens", "active": true }, { "id": "DECALER_REVOIR", "label": "Suspens renouvel?", "active": true }, { "id": "LEVER_SUSPEND", "label": "Suspens lev?", "active": true }], "CARACT_ADAPTE_PROD": [{ "id": 2801, "label": "Connaissance du client", "active": true, "isAutre": false }, { "id": 2802, "label": "Cat??gorisation du client", "active": true, "isAutre": false }, { "id": 2803, "label": "Ad??quation de l???offre aux besoins du client", "active": true, "isAutre": false }, { "id": 2804, "label": "Obligation de mise en garde du client", "active": true, "isAutre": false }, { "id": 2805, "label": "Autre", "active": true, "isAutre": true }], "ESCALADE": [{ "id": "DECISION", "label": "D?cision", "active": true }, { "id": "ARBITRAGE", "label": "Arbitrage", "active": true }, { "id": "AVIS", "label": "Avis", "active": true }, { "id": "INFORMATION", "label": "Information", "active": true }], "REGION": [{ "id": 1, "label": "EMEA", "active": true, "isAutre": false }], "REGULATEUR": [{ "id": 1901, "label": "USA-OFAC", "active": true, "isAutre": false }, { "id": 1902, "label": "USA-Fin-CEN", "active": true, "isAutre": false }, { "id": 1903, "label": "France", "active": true, "isAutre": false }, { "id": 1904, "label": "Union Europ??enne", "active": true, "isAutre": false }, { "id": 1905, "label": "Autres", "active": true, "isAutre": true }, { "id": 115, "label": "Regulateur Inactive", "active": false, "isAutre": false }], "NIVEAU_SENSIBILITE_PAYS": [{ "id": 901, "label": "Peu sensible", "active": true, "isAutre": false }, { "id": 902, "label": "Moyennement sensible", "active": true, "isAutre": false }, { "id": 903, "label": "Fortement sensible", "active": true, "isAutre": false }, { "id": 904, "label": "Tr??s fortement sensible", "active": true, "isAutre": false }, { "id": 111, "label": "NiveauSensibilitePays Inactive", "active": false, "isAutre": false }], "SOURCE_ID_PPE": [{ "id": 1501, "label": "Entretien client", "active": true, "isAutre": false }, { "id": 1502, "label": "Lynx", "active": true, "isAutre": false }, { "id": 1503, "label": "WorldCheck", "active": true, "isAutre": false }, { "id": 1504, "label": "Autre", "active": true, "isAutre": true }, { "id": 122, "label": "SourceIdPPE Inactive", "active": false, "isAutre": false }], "ACTION": [{ "id": "NO_ACTION", "label": "Aucune action", "active": true }, { "id": "CREER_DOSSIER", "label": "Dossier ? compl?ter ", "active": true }, { "id": "ESCALADER_DOSSIER", "label": "En attente de traitement", "active": true }, { "id": "REPONDRE_DEMANDE", "label": "En attente de traitement", "active": true }, { "id": "CLORE_DOSSIER", "label": "Cl?tur?", "active": true }, { "id": "ESCALADER_CO", "label": "Demande CG - Dossier ? compl?ter", "active": true }, { "id": "RENVOYER_DOSSIER", "label": "Dossier retourn? - En attente de traitement", "active": true }, { "id": "DEMANDER_CYCLE", "label": "Nouveau cycle demand? - En attente de traitement", "active": true }, { "id": "PROPOSER_TRANSFERT", "label": "Accepter/Refuser le transfert", "active": true }, { "id": "ACCEPTER_TRANSFERT", "label": "Transfert accept?-En attente de traitement", "active": true }, { "id": "REFUSER_TRANSFERT", "label": "Transfert refus?-En attente de traitement", "active": true }, { "id": "REPRESENTER_DOSSIER", "label": "Dossier repr?sent?-En attente de traitement ", "active": true }, { "id": "POSER_QUESTION", "label": "R?pondre ? une question", "active": true }, { "id": "MODIFIER_DOSSIER", "label": "En attente de traitement ", "active": true }, { "id": "SUSPENDRE_DOSSIER", "label": "Lever/renouveler le suspens", "active": true }, { "id": "DECALER_REVOIR", "label": "Lever/renouveler le suspens", "active": true }, { "id": "LEVER_SUSPEND", "label": "Suspens lev?-En attente de traitement", "active": true }], "NIVEAU_RISQUE": [{ "id": 1701, "label": "Faible", "active": true, "isAutre": false }, { "id": 1702, "label": "Moyen", "active": true, "isAutre": false }, { "id": 1703, "label": "Elev??", "active": true, "isAutre": false }, { "id": 110, "label": "NiveauRisque Inactive", "active": false, "isAutre": false }], "DISPOSITIF_BIEN_VENDRE": [{ "id": 701, "label": "Processus de validation des nouveaux produits", "active": true, "isAutre": false }, { "id": 702, "label": "Qualification des vendeurs", "active": true, "isAutre": false }, { "id": 703, "label": "Convention producteurs ??? distributeurs", "active": true, "isAutre": false }, { "id": 704, "label": "Caract??re raisonnable du co??t pour le client", "active": true, "isAutre": false }, { "id": 705, "label": "Discrimination", "active": true, "isAutre": false }, { "id": 706, "label": "Inducement (vendeurs/distributeurs)", "active": true, "isAutre": false }, { "id": 707, "label": "Conflits d???int??r??ts", "active": true, "isAutre": false }, { "id": 708, "label": "Tra??abilit??", "active": true, "isAutre": false }, { "id": 709, "label": "Autre", "active": true, "isAutre": true }, { "id": 103, "label": "DispositifBienVendre Inactive", "active": false, "isAutre": false }], "DEVISE": [{ "id": 1, "label": "EUR - EURO", "active": true, "isAutre": false }, { "id": 2, "label": "USD - US DOLLAR", "active": true, "isAutre": false }, { "id": 3, "label": "CAD - DOLLAR CANADIEN", "active": true, "isAutre": false }], "TYPE_RELATION_PPE": [{ "id": 1601, "label": "Entr??e en relation", "active": true, "isAutre": false }, { "id": 1602, "label": "R??vision d???une relation d???affaire existante", "active": true, "isAutre": false }, { "id": 127, "label": "TypeRelationPPE Inactive", "active": false, "isAutre": false }], "SANCTION": [{ "id": 2701, "label": "DUMMY (SANCTION)", "active": true, "isAutre": false }, { "id": 2702, "label": "DUMMY2 (SANCTION)", "active": true, "isAutre": false }, { "id": 120, "label": "Sanction Inactive", "active": false, "isAutre": false }], "TYPE_PPE_REL_AFFAIRE": [{ "id": 1301, "label": "B??n??ficiaire effectif", "active": true, "isAutre": false }, { "id": 1302, "label": "Repr??sentant l??gal", "active": true, "isAutre": false }, { "id": 1303, "label": "Mandataire", "active": true, "isAutre": false }, { "id": 1304, "label": "Autre", "active": true, "isAutre": true }, { "id": 125, "label": "TypePPERelationAffaire Inactive", "active": false, "isAutre": false }], "EVAL_INFLUENCE_PPE": [{ "id": 1201, "label": "Significatif", "active": true, "isAutre": false }, { "id": 1202, "label": "Non significatif", "active": true, "isAutre": false }, { "id": 104, "label": "EvaluationInfluencePPE Inactive", "active": false, "isAutre": false }], "REPONSE_ARBITRAGE": [{ "id": 10100, "label": "Favorable", "active": true, "isAutre": false }, { "id": 10200, "label": "Favorable avec r??serves", "active": true, "isAutre": false }, { "id": 10300, "label": "D??favorable", "active": true, "isAutre": false }, { "id": 116, "label": "ReponseArbitrage Inactive", "active": false, "isAutre": false }], "EXECUTION_OP": [{ "id": 40100, "label": "Documentation contractuelle", "active": true, "isAutre": false }, { "id": 40200, "label": "Best execution", "active": true, "isAutre": false }, { "id": 40300, "label": "Valorisation du produit", "active": true, "isAutre": false }, { "id": 40400, "label": "Autre", "active": true, "isAutre": true }, { "id": 105, "label": "ExecutionOp Inactive", "active": false, "isAutre": false }], "THEME": [{ "id": "PPE", "label": "PPE", "active": true }, { "id": "ARMEMENT", "label": "Armement", "active": true }, { "id": "SANCTION_NOMINATIVE", "label": "Sanctions Nominatives", "active": true }, { "id": "EMBARGO", "label": "Embargo", "active": true }, { "id": "PIC", "label": "PIC", "active": true }, { "id": "AUTRES_CAS", "label": "Autre Cas", "active": true, "autre": true }], "PROGRAMME_SANCTION": [{ "id": 1801, "label": "UE-AFG", "active": true, "isAutre": false }, { "id": 1802, "label": "UE-BLR", "active": true, "isAutre": false }, { "id": 1804, "label": "Autre", "active": true, "isAutre": true }, { "id": 114, "label": "ProgrammeSanction Inactive", "active": false, "isAutre": false }], "METIER": [{ "id": 2601, "label": "DUMMY (METIER)", "active": true, "isAutre": false }, { "id": 107, "label": "Metier Inactive", "active": false, "isAutre": false }], "DESC_LIEN_PPE": [{ "id": 1401, "label": "Membre direct de la famille", "active": true, "isAutre": false }, { "id": 1402, "label": "Personne ??troitement associ??e", "active": true, "isAutre": false }, { "id": 102, "label": "DescriptionLienPPE Inactive", "active": false, "isAutre": false }], "CATEGORIE_CLIENTELE": [{ "id": "PERSONNE_PHYSIQUE", "label": "Personne physique", "active": true }, { "id": "PERSONNE_MORALE", "label": "Personne morale", "active": true }], "PRECISION_INFO_CLIENT": [{ "id": 50100, "label": "Information sur les risques", "active": true, "isAutre": false }, { "id": 50200, "label": "Information sur les co??ts", "active": true, "isAutre": false }, { "id": 112, "label": "PrecisionInfoClient Inactive", "active": false, "isAutre": false }], "PAYS": [{ "id": 1, "label": "FR - France", "active": true, "isAutre": false }, { "id": 2, "label": "GB - Grande-Bretagne", "active": false, "isAutre": false }, { "id": 3, "label": "IT - Italie", "active": true, "isAutre": false }], "INFO_CLIENT": [{ "id": 601, "label": "Caract??re clair", "active": true, "isAutre": false }, { "id": 602, "label": "Exact", "active": true, "isAutre": false }, { "id": 603, "label": "Non trompeur de l???information", "active": true, "isAutre": false }, { "id": 604, "label": "Adaptation de l???information au profil client", "active": true, "isAutre": false }, { "id": 106, "label": "InfoClient Inactive", "active": false, "isAutre": false }], "CELLULE": [ { "id" : 533050, "label" : "cell_test", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : 156, "niveau" : "REGION", "pays" : 82, "themes" : [ "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 533052, "label" : "name_test1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 181, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 535050, "label" : "Sorin's CO 1 [EN]", "active" : false, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 165, "niveau" : "PAYS", "pays" : 34, "themes" : [ "ARMEMENT", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 551051, "label" : "BIS FHE CO", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 544050, "niveau" : "ENTITE", "pays" : 64, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 551054, "label" : "5 FHE CO", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 551053, "niveau" : "ENTITE", "pays" : 44, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 551055, "label" : "FHE PEP", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 13, "niveau" : "PAYS", "pays" : 40, "themes" : [ "PPE" ], "isDeletable" : false }, { "id" : 551056, "label" : "CO 6 FHE Sanction", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 14, "niveau" : "PAYS", "pays" : 27, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 100, "label" : "CG ERROR", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ ], "isDeletable" : false }, { "id" : 1, "label" : "GFS Paris Investigation Unit", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PPE" ], "isDeletable" : false }, { "id" : 2, "label" : "GFS Paris Financial Sanctions Unit", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO" ], "isDeletable" : false }, { "id" : 3, "label" : "GFS US", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 101, "themes" : [ "EMBARGO" ], "isDeletable" : false }, { "id" : 4, "label" : "CG PIC", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PIC" ], "isDeletable" : false }, { "id" : 5, "label" : "GC Research department", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 6, "label" : "IS", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "PPE", "SANCTION_NOMINATIVE", "EMBARGO", "PIC" ], "isDeletable" : false }, { "id" : 7, "label" : "Compliance Investment partners", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 6, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "SANCTION_NOMINATIVE", "EMBARGO" ], "isDeletable" : false }, { "id" : 8, "label" : "PIC Investment partners", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 6, "niveau" : "METIER", "pays" : 82, "themes" : [ "PIC" ], "isDeletable" : false }, { "id" : 9, "label" : "IRB", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 9, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 10, "label" : "Compliance IRB MEO", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 9, "parent" : 9, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 11, "label" : "Compliance BICIAB", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 9, "parent" : 10, "niveau" : "ENTITE", "pays" : 83, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 12, "label" : "PIC Investment partners FR", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 8, "niveau" : "REGION", "pays" : 82, "themes" : [ "PIC" ], "isDeletable" : false }, { "id" : 13, "label" : "PEP FR", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 7, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE" ], "isDeletable" : false }, { "id" : 14, "label" : "Sanction FR", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 7, "niveau" : "REGION", "pays" : 82, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 15, "label" : "Embargo FR", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 7, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "EMBARGO" ], "isDeletable" : false }, { "id" : 16, "label" : "Embargo Paris", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 15, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "EMBARGO" ], "isDeletable" : false }, { "id" : 150, "label" : "PoleA", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "EMBARGO", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 151, "label" : "CGA", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PPE" ], "isDeletable" : false }, { "id" : 152, "label" : "MetierA", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : 150, "niveau" : "METIER", "pays" : 82, "themes" : [ "ARMEMENT" ], "isDeletable" : false }, { "id" : 153, "label" : "RegionA", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : 152, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 154, "label" : "PaysA", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : 153, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "EMBARGO" ], "isDeletable" : false }, { "id" : 155, "label" : "Entite", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 150, "parent" : 154, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 156, "label" : "Pole_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 157, "label" : "CG_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "EMBARGO", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 158, "label" : "Metier_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : 156, "niveau" : "METIER", "pays" : 82, "themes" : [ "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 159, "label" : "Region_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : 158, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "EMBARGO" ], "isDeletable" : false }, { "id" : 160, "label" : "Pays_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : 159, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 161, "label" : "Entite_Escalade", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 156, "parent" : 160, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 162, "label" : "CG_1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 163, "label" : "CG_2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 164, "label" : "CG_3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 165, "label" : "Pole_Test_A", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 166, "label" : "Metier_Test_A1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 165, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 167, "label" : "Metier_Test_A2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 165, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 168, "label" : "Region_Test_A1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 166, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 169, "label" : "Region_Test_A2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 167, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 170, "label" : "Region_Test_A3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 167, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 171, "label" : "Pays_Test_A1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 168, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 172, "label" : "Pays_Test_A2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 168, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 173, "label" : "Pays_Test_A3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 169, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 174, "label" : "Pays_Test_A4", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 170, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 175, "label" : "Entite_A1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 171, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 176, "label" : "Entite_A2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 172, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 177, "label" : "Entite_A3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 172, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 178, "label" : "Entite_A4", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 173, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 179, "label" : "Entite_A5", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 174, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 180, "label" : "Entite_A6", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 174, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 181, "label" : "Pole_Test_B", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : null, "niveau" : "POLE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 182, "label" : "Metier_Test_B1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 181, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 183, "label" : "Metier_Test_B2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 181, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 184, "label" : "Metier_Test_B3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 181, "niveau" : "METIER", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 185, "label" : "Region_Test_B1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 182, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 186, "label" : "Region_Test_B2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 183, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 187, "label" : "Region_Test_B3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 184, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 188, "label" : "Region_Test_B4", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 184, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 189, "label" : "Region_Test_B5", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 184, "niveau" : "REGION", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 190, "label" : "Pays_Test_B1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 185, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 191, "label" : "Pays_Test_B2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 185, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 192, "label" : "Pays_Test_B3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 186, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 193, "label" : "Pays_Test_B4", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 187, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 194, "label" : "Pays_Test_B5", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 188, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 195, "label" : "Pays_Test_B6", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 189, "niveau" : "PAYS", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 196, "label" : "Entite_B1", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 190, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 197, "label" : "Entite_B2", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 191, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 198, "label" : "Entite_B3", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 191, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 199, "label" : "Entite_B4", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 192, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 200, "label" : "Entite_B5", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 193, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 201, "label" : "Entite_B6", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 194, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 202, "label" : "Entite_B7", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 195, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 203, "label" : "Entite_B8", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 181, "parent" : 195, "niveau" : "ENTITE", "pays" : 82, "themes" : [ "PPE", "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 533051, "label" : "name", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 165, "parent" : 165, "niveau" : "PAYS", "pays" : 20, "themes" : [ "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 535051, "label" : "pole_cg", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "POLE", "pays" : 45, "themes" : [ "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "AUTRES_CAS" ], "isDeletable" : false }, { "id" : 535052, "label" : "cell_cg", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : null, "parent" : null, "niveau" : "CG", "pays" : 17, "themes" : [ "ARMEMENT", "SANCTION_NOMINATIVE", "EMBARGO", "PIC" ], "isDeletable" : false }, { "id" : 544050, "label" : "<NAME>", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 14, "niveau" : "PAYS", "pays" : 82, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 551050, "label" : "<NAME>", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 544050, "niveau" : "ENTITE", "pays" : 20, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 551052, "label" : "<NAME>", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 14, "niveau" : "PAYS", "pays" : 13, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false }, { "id" : 551053, "label" : "4 FHE CO", "active" : true, "isAutre" : false, "dateCreation" : null, "createur" : null, "dateSuppresion" : null, "destructeur" : null, "pole" : 6, "parent" : 14, "niveau" : "PAYS", "pays" : 34, "themes" : [ "SANCTION_NOMINATIVE" ], "isDeletable" : false } ], "TYPE_LISTE_DONNEES_GEN": [{ "id": 2001, "label": "Liste des sanctions nominatives", "active": true, "isAutre": false }, { "id": 2002, "label": "Liste des pays sous embargos", "active": true, "isAutre": false }, { "id": 2003, "label": "Listes de surveillance", "active": true, "isAutre": false }, { "id": 124, "label": "TypeListeDonneesGenerales Inactive", "active": false, "isAutre": false }], "TYPE_CONTROLE": [{ "id": 1001, "label": "Transaction", "active": true, "isAutre": false }, { "id": 1002, "label": "Autre cas", "active": true, "isAutre": false }, { "id": 123, "label": "TypeControle Inactive", "active": false, "isAutre": false }], "REPONSE_DECISION": [{ "id": 20100, "label": "Accord", "active": true, "isAutre": false }, { "id": 20200, "label": "Accord avec r??serves", "active": true, "isAutre": false }, { "id": 20300, "label": "Refus", "active": true, "isAutre": false }, { "id": 118, "label": "ReponseDecision Inactive", "active": false, "isAutre": false }], "CARACT_LIEN_PPE": [{ "id": 2501, "label": "DUMMY (CARACT_LIEN_PPE)", "active": true, "isAutre": false }, { "id": 100, "label": "CaractereLienPPE Inactive", "active": false, "isAutre": false }], "NIVEAU": [{ "id": "CG", "label": "Conformit? Groupe", "active": true }, { "id": "POLE", "label": "P?les", "active": true }, { "id": "METIER", "label": "M?tiers", "active": true }, { "id": "REGION", "label": "R?gions", "active": true }, { "id": "PAYS", "label": "Pays", "active": true }, { "id": "ENTITE", "label": "Entit?s", "active": true }], "SENS_MESSAGE": [{ "id": 2301, "label": "Entrant", "active": true, "isAutre": false }, { "id": 2302, "label": "Sortant", "active": true, "isAutre": false }, { "id": 121, "label": "SensMessage Inactive", "active": false, "isAutre": false }], "NATURE_RELATION_DEMANDE": [{ "id": 2101, "label": "B??n??ficiaire effectif", "active": true, "isAutre": false }, { "id": 2102, "label": "Mandataire", "active": true, "isAutre": false }, { "id": 2103, "label": "Repr??sentant l??gal", "active": true, "isAutre": false }, { "id": 2104, "label": "Co-titulaire", "active": true, "isAutre": false }, { "id": 2105, "label": "Autre", "active": true, "isAutre": true }, { "id": 109, "label": "NatureRelationDemande Inactive", "active": false, "isAutre": false }], "PRODUIT_SERVICE": [{ "id": 801, "label": "Moyen de paiement / CB / Virement", "active": true, "isAutre": false }, { "id": 802, "label": "Compte courant / ? terme / ??pargne", "active": true, "isAutre": false }, { "id": 803, "label": "Compte titres", "active": true, "isAutre": false }, { "id": 804, "label": "Produits d??riv??s", "active": true, "isAutre": false }, { "id": 805, "label": "Ing??nierie patrimoniale / Mandat de gestion", "active": true, "isAutre": false }, { "id": 806, "label": "Cr??dit immobilier", "active": true, "isAutre": false }, { "id": 807, "label": "Cr??dit consommation", "active": true, "isAutre": false }, { "id": 808, "label": "Assurance vie", "active": true, "isAutre": false }, { "id": 809, "label": "Assurance emprunteur", "active": true, "isAutre": false }, { "id": 810, "label": "Autre", "active": true, "isAutre": true }, { "id": 113, "label": "ProduitService Inactive", "active": false, "isAutre": false }], "STATUT_DOSSIER": [{ "id": "AUCUN", "label": "Aucun", "active": true }, { "id": "EN_COURS_CREATION", "label": "En cours de creation", "active": true }, { "id": "ESCALADE", "label": "Escalade", "active": true }, { "id": "REPONDUE", "label": "Repondue", "active": true }, { "id": "CLOSE", "label": "Cloture", "active": true }, { "id": "RENVOYE", "label": "Renvoye", "active": true }, { "id": "NOUVEAU_CYCLE", "label": "Nouveau cycle", "active": true }, { "id": "ATTENTE_TRANSFERT", "label": "Attente transfert", "active": true }, { "id": "REPRESENTE", "label": "Represente", "active": true }, { "id": "EN_ATTENTE_REPONSE", "label": "En attente response", "active": true }, { "id": "EN_SUSPENS_MANUEL", "label": "En suspenssion manuel", "active": true }], "NATURE_INTERROGATION": [{ "id": 1101, "label": "Homonymie", "active": true, "isAutre": false }, { "id": 1102, "label": "Personnes li??es ? un nom list??", "active": true, "isAutre": false }, { "id": 108, "label": "NatureInterrogation Inactive", "active": false, "isAutre": false }] }); }) Sandbox.define('/rest/dossier','POST', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(201); // Send the response body. res.json({ "value": 250 }); }) Sandbox.define('/rest/dossier/250','PUT', function(req, res) { // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(201); // Send the response body. res.json({ "value": 250 }); }) Sandbox.define('/rest/dossier/search/new','GET', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "poles": [150, 156], "metiers": [2601] }); }) Sandbox.define('/rest/dossier/search', 'POST', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json( [{ "dossierId": 250, "theme": "PPE", "typeEscalade": "ARBITRAGE", "detailDemande": "cc", "nomClient": "ccc", "statut": "cc", "pole": 150, "cellule": 151, "metier": 152, "dateCreation": "2014-12-12", "niveauDecision": "cc", "dateDerniereDecision": "2014-12-12" }, { "dossierId": 250, "theme": "PPE", "typeEscalade": "INFORMATION", "detailDemande": "cc", "nomClient": "ccc", "statut": "cc", "pole": 150, "cellule": 151, "metier": 152, "dateCreation": "2014-12-12", "niveauDecision": "cc", "dateDerniereDecision": "2014-12-12" }] ); }) Sandbox.define('/rest/user/current','GET', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 33, "idAnnuaire": 978799, "fullName": "<NAME>", "language": "FR", "email": "<EMAIL>", "isAdmin": false, "dateFormat": "1" }); }) Sandbox.define('/rest/dossier/250/close','GET', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ coDestinataires: [161, 162, 163, 164] }); }) Sandbox.define('/rest/dossier/250/infoDefavorable/new','GET', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "motif": null, "dateSaisie": 1425031892024, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "coRattachement": 154, "pole": 152 }); }) Sandbox.define('/rest/dossier/250/infoDefavorable', 'POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/dossier/250/commentairesCG', 'POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/dossier/250/close','POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/dossier/250','GET', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 250, "readOnly": false, "lockAcquired": true, "actionEscalade": false, "validActions": ["ATTACH_DOCUMENTS", "ESCALADER", "ANNULER", "ENREGISTRER", "CLOTURER", "VALIDER_DEMANDE"], "dossierLieeId": 123, "initialResponseRequired": false, "reference": "34.236", "coEnCharge": 156, "pays": 1, "metier": 2601, "coEmettrice": 151, "viewingAsCgLevel": true, "entiteEmettrice": "entite emetrice", "dateCreation": "2015-01-20", "dateRetour": "2015-01-25", "dateTransfert": "2015-01-20", "statut": "EN_COURS_CREATION", "theme": "PIC", "escalade": "ARBITRAGE", "detailDemande": "Detaile du demande for Mes Taches #3 <b>123</b><ul><li>111.</li></ul>", "relation": [2202], "categorieClientele": "PERSONNE_MORALE", "ficheClient": { "idRmpm": "rmpm", "raisonSociale": "raison sociale", "paysSiegeSocial": null, "numeroImmatriculation": "inmatr", "dateImmatriculation": "2015-01-15", "secteurActivite": "secteur", "partAuPorteur": true, "adresseFiscaleLine1": "fisc_distrib", "adresseFiscaleLine2": "y", "adresseFiscaleLine3": "z", "adresseFiscaleCptLcl": "x", "adresseFiscalePays": 1, "adresseResidenceLine1": "rd", "adresseResidenceLine2": "rd", "adresseResidenceLine3": "rv", "adresseResidenceCptLcl": "rx", "adresseResidencePays": 1, "paysActivitePrincipale": 1, "idClient": 355, "nom": null, "prenom": null, "dateNaissance": null, "paysNaissance": null, "paysNationalite": null, "profession": null, "nomEmployeur": null }, "paysRattache": [{ "pays": 1, "pourcentageActivite": 20.1, "natureLien": "Nature lien" }], "personneLiee": [{ "nom": "nom", "prenom": "prenom", "dateNaissance": "2015-01-26", "paysNaissance": 1, "relationPersonneLiee": 2102 }], "hitVigilance": true, "typeListe": 2002, "emetteur": 1904, "programmeSanction": [1801], "justificationAppartenanceAListe": "A valid reason explanation", "kycDateDerniereMAJ": "2015-02-09", "kycComplet": true, "kycElementManquant": "Nothing", "objetRelationAffaire": "affair to object relation", "niveauRisque": 1701, "dateEntreeRelation": "2015-02-09", "compteContrat": "Compt contrat", "avis": "Un Avis", "autreEntiteBNPP": "another BNPP", "dateCloture": "2015-01-30", "dateProchainCAC": "2015-01-30", "pole": 151, "lienPaysSousSanction": true, "sanctions": { "natureInterrogation": null, "referenceListeVigilance": null, "navire": null, "nom": null, "noImo": null, "type": null, "pavillon": null, "tonnageEtJaugeBrute": null, "nomPrenomRaisonSociale": null, "nationalitaePaysSiegeSocial": null, "paysResidenceImplantation": null, "montantEngagementSurLivresBNPP": "xxx", "informationComplementaires": [] }, "embargo": { "typeControle": null, "sensMessage": null, "pays": null, "lienReglementationUS": "lienReglementationUS", "lienReglementationUE": "lienReglementationUE", "lienReglementationFrance": "lienReglementationFrance", "autres": "autres", "intervenantsVerifiesResultat": 2402, "intervenantsAutreResultat": "intervenantsAutreResultat", "objetEconomiqueResultat": 2401, "objetEconomiqueAutreResultat": "objetEconomiqueAutreResultat", "nonNucleaireResultat": 2401, "nonNucleaireAutreResultat": null, "objetCommercialNatureMarchandise": "objetCommercialNatureMarchandise", "donneurOrdre": "donneurOrdre", "donneurOrdrePays": 1, "donneurOrdreVille": "donneurOrdreVille", "donneurOrdrePrecisionsComplementaires": "donneurOrdrePrecisionsComplementaires", "donneurOrdreBanqueEmettrice": "donneurOrdreBanqueEmettrice", "donneurOrdreBanqueEmettricePays": 1, "donneurOrdreBanqueEmettriceVille": "donneurOrdreBanqueEmettriceVille", "donneurOrdreBanqueCorrespondante": "donneurOrdreBanqueCorrespondante", "donneurOrdreBanqueCorrespondantePays": 1, "donneurOrdreBanqueCorrespondanteVille": "donneurOrdreBanqueCorrespondanteVille", "banqueIntermediare": "banqueIntermediare", "banqueIntermediarePays": 1, "banqueIntermediareVille": "withBanqueIntermediareVille", "beneficiaire": "beneficiaire", "beneficiairePays": 1, "beneficiaireVille": "beneficiaireVille", "beneficiairePrecisionsComplementaires": "beneficiairePrecisionsComplementaires", "beneficiaireBanqueCorrespondante": "beneficiaireBanqueCorrespondante", "beneficiaireBanqueCorrespondantePays": 1, "beneficiaireBanqueCorrespondanteVille": "beneficiaireBanqueCorrespondanteVille", "beneficiaireBanque": "beneficiaireBanque", "beneficiaireBanquePays": 1, "beneficiaireBanqueVille": "beneficiaireBanqueVille", "transportParNavire": "transportParNavire", "natureOperationBancaire": "natureOperationBancaire", "montant": 12, "devise": null, "detailTransactionEtListePiecesJointes": "detailTransactionEtListePiecesJointes" }, "armement": { "paysImportation": null, "paysExportation": null, "cotationSensibilitePaysImportation": null, "nomPrenomRaisonSocialeAcheteur": null, "acheteurEnLienAvecEtat": null, "nomPrenomRaisonSocialeIntermediaire": null, "kycCompletIntermediaire": null, "natureBienService": null, "avisRse": null, "risqueReputationIdentifie": null, "montant": null, "devise": null }, "listePpe": [{ "relation": null, "modeEntreeEnRelation": "modeEntreeEnRelation", "dateDernierEntretienAvecRelationAffaire": "2015-01-22", "sourceIdentificationStatutPPE": 1504, "autreSourceIdentificationStatutPPE": "autreSourceIdentificationStatutPPE", "ppeAHautRisque": true, "classificationPPESpecifiqueRetenueParMetier": "classificationPPESpecifiqueRetenueParMetier", "enqueteExterne": "enqueteExterne", "autresRecherche": "autresRecherche", "fonctionProspect": "fonctionProspect", "dateEntreeEnFonctionProspect": null, "dateCessationDeLaFonctionProspect": "2015-01-21", "paysExerciceProspect": 1, "autresFonctionsPolitiquementExposeesProspect": "autresFonctionsPolitiquementExposeesProspect", "detailFonctionsOccupeesDansSocieteProspect": "detailFonctionsOccupeesDansSocieteProspect", "relationProspectPersonnelPolitiquementExposee": 1401, "natureRelationProspectPersonnePolitiquementExposee": "natureRelationProspectPersonnePolitiquementExposee", "societeDePersonnePolitiquementExposee": 1304, "autreSocieteDePersonnePolitiquementExposee": "autreSocieteDePersonnePolitiquementExposee", "evaluationInfluencePersonnePolitiquementExposee": 1201, "motifEvaluationInfluencePersonnePolitiquementExposee": "motifEvaluationInfluencePersonnePolitiquementExposee", "nom": "gigi", "dateNaissance": "2015-01-28", "prenom": "prenom", "paysNaissance": 1, "nationalite": null, "paysResidence": 1, "fonctionInfo": "fonctionInfo", "dateEntreeEnFonctionInformation": "2015-01-23", "dateCessationDeLaFonctionInformation": "2015-01-19", "paysExerciceInformation": 1, "autresFonctionsPolitiquementExposeesInformation": "autresFonctionsPolitiquementExposeesInformation", "detailFonctionsOccupeesDansSocieteInformation": "detailFonctionsOccupeesDansSocieteInformation", "montantAnnuelRevenus": null, "compositionEvaluationPatrimoine": "compositionEvaluationPatrimoine", "origineEconomiquePatrimoine": "origineEconomiquePatrimoine", "origineEconomiqueFondsRecuARecevoir": "origineEconomiqueFondsRecuARecevoir", "montantEngagementSurLivreBNPP": null, "produitsEtService": [{ "nature": "nature", "montantActuel": 12, "montantAttendu": 14 }], "profilTransactionnelAnnuel": [{ "nature": "nature", "montant": 12, "nombre": 8, "provenance": 1, "destination": 1 }], "fonctionnementConformeAuProfilTransactionnel": null }], "autreCas": { "descriptionDemande": "A <strong>bold</strong> value." }, "protectionInteretsClients": { "produitsServices": [801], "characteristiquesProduitService": null, "profilClientConcerne": null, "dispositifBienVendre": [701, 702, 703], "autreDispositifBienVendre": "autreDispositifBienVendre", "caractereAdapteProduit": [2801], "autreCaractereAdapteProduit": null, "informationClient": [601], "precisionInformationClient": [50100], "executionOperation": [40100], "autreExecutionOperation": null, "resumeProblematique": null, "casADonneLieuAReclamation": null, "casADonneLieuAProcedureContentieuse": null, "procedureClassAction": null, "nombreAutreClients": null, "casReferenceDansForecast": null, "referenceIncidentForecast": null, "impactIncidentPourLeGroup": null, "dysfonctionementsObserves": null, "mesuresCorrectives": null, "avisDemande": null }, "region": 1, "dateDernierCAC": "2015-01-10", "informationsAction": { "etapesEscalade": [{ "typeEscalade": "ARBITRAGE", "niveauDecis": "PAYS", "pays": 1, "coDestinatrice": 150, "commentaires": "test comment", "dateCreation": "2015-01-12", "nomEtPrenom": "<NAME>", "avis": 30100, "dateReponse": "2015-01-30", "commentairesMgmt": "test comment 2", "nomEtPrenomMgmt": "<NAME>", "avisMgmt": 30200, "dateReponseMgmt": "2015-01-30", "afficherAvisMgmt": true, "controlerAvisMgmt": false, "pole": 151, "saisiPar": "<NAME>" }, { "typeEscalade": "AVIS", "niveauDecis": "PAYS", "pays": 3, "coDestinatrice": 150, "commentaires": "test comment", "dateCreation": "2015-01-12", "nomEtPrenom": "<NAME>", "avis": 30300, "dateReponse": "2015-01-30", "pole": 151, "saisiPar": "<NAME>" }, { "typeEscalade": "DECISION", "niveauDecis": "PAYS", "pays": 1, "coDestinatrice": 150, "commentaires": "test comment", "dateCreation": "2015-01-12", "nomEtPrenom": "<NAME>", "avis": 30200, "dateReponse": "2015-01-30", "pole": 151, "saisiPar": "<NAME>" }, { "typeEscalade": "INFORMATION", "niveauDecis": "PAYS", "pays": 2, "coDestinatrice": 150, "commentaires": "test comment", "dateCreation": "2015-01-12", "pole": 151, "saisiPar": "<NAME>", "files": [{ "id": 100, "titre": "xxx", "filename": "filename", "dateRattachement": "2014-12-12", "nomCreateur": "nmom", "prenomCreateur": "precxszf", "co": 150, "pole": 151 }] }], "actionARealiser": [{ "typeEscalade": "ARBITRAGE", "niveauDecis": "PAYS", "pays": 1, "coDestinatrice": 2, "commentaires": "test comment", "dateCreation": "2015-01-12", "nomEtPrenom": "<NAME>", "avis": 10100, "dateReponse": "2015-01-30", "commentairesMgmt": "test comment 2", "nomEtPrenomMgmt": "<NAME>", "avisMgmt": 10200, "dateReponseMgmt": "2015-01-30", "afficherAvisMgmt": true, "controlerAvisMgmt": false, "pole": 1, "saisiPar": "<NAME>", "reponseDemande": { "files": [{ "filename": "gigi", "titre": "gigit", "id": 1231 }] } }] }, "audit": [{ "actionRealisee": "REPONDRE_DEMANDE", "typeEscalade": "ARBITRAGE", "parPole": 151, "parCO": 152, "parUtilisateur": "TestPrenom TestNom", "parDate": "2015-01-26", "destinationPole": 151, "destinationCO": 151, "destinationUtilisateur": "TestPrenom TestNom", "commentairesMgmt": "12431c1234 14234 21 1234 1324 1243 1234 1234 ", "files": [{ "titreDocument": "file2", "nomFichier": "gigi", "dateAttachement": "2014-12-12", "nom": "Moraru", "prenom": "Vali", "co": 151, "pole": 152 }] }], "infoDefavorable": [], "files": [{ "filename": "file2", "nomFichier": "gigi", "dateAttachement": "2014-12-12", "nom": "Moraru", "prenom": "Vali", "co": 151, "pole": 152 }], "commentairesCG": [{ "commentaireCG": "un commentaire", "co": 151, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "dateSaisie": "2015-03-04" }, { "commentaireCG": "un commentaire2", "co": 151, "username": "test", "nom": "TestNom", "prenom": "TestPrenom", "dateSaisie": "2015-06-04" }], "droits": [{ "celluleId": 151, "isManuel": true }, { "celluleId": 152, "isManuel": true }, { "celluleId": 153, "isManuel": true }, { "celluleId": 154, "isManuel": true }, { "celluleId": 155, "isManuel": true }, { "celluleId": 159, "isManuel": true }] }); }) Sandbox.define('/rest/user/search', 'POST', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "users": [{ "id": 1, "username": "216739", "nom": "Basset", "prenom": "Antoine", "fullName": "Antoine overview ", "email": "PARIS CG EP overview", "isAdmin": false }, { "id": 2, "username": "191541", "nom": "Viez", "prenom": "Florence", "fullName": "Florence overview ", "email": "PARIS CG EP SUPPORT", "isAdmin": false }] }); }) Sandbox.define('/rest/dossier/search/fiche','POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json( [{ "idRmpm": "idRmpm", "raisonSociale": "raisonSociale", "paysSiegeSocial": 1, "numeroImmatriculation": "numeroImmatriculation", "dateImmatriculation": 1, "secteurActivite": "secteurActivite", "partAuPorteur": true, "adresseFiscaleLine1": "adresseFiscaleLine1", "adresseFiscaleLine2": "adresseFiscaleLine2", "adresseFiscaleLine3": "adresseFiscaleLine3", "adresseFiscaleCptLcl": "adresseFiscaleCptLcl", "adresseFiscalePays": 1, "adresseResidenceLine1": "adresseResidenceLine1", "adresseResidenceLine2": "adresseResidenceLine2", "adresseResidenceLine3": "adresseResidenceLine3", "adresseResidenceCptLcl": "adresseResidenceCptLcl", "adresseResidencePays": 1, "adresseImplantationLine1": "adresseImplantationLine1", "adresseImplantationLine2": "adresseImplantationLine2", "adresseImplantationLine3": "adresseImplantationLine3", "adresseImplantationCptLcl": "adresseImplantationCptLcl", "adresseImplantationPays": 1, "paysActivitePrincipale": 1, "idClient": 1, "nom": "nom", "prenom": "prenom", "dateNaissance": 1, "paysNaissance": 1, "paysNationalite": 1, "profession": "profession", "nomEmployeur": "nomEmployeur", "categorieClientele": "PERSONNE_MORALE", "dossierId": 123, "detailDemande": "detailDemande detailDemande detailDemande detailDemande detailDemande detailDemande detailDemande", "statut": "ACTIF", "theme": "PPE", "escalade": "escalade" }, { "idRmpm": "idRmpm", "raisonSociale": "raisonSociale", "paysSiegeSocial": 1, "numeroImmatriculation": "numeroImmatriculation", "dateImmatriculation": 1, "secteurActivite": "secteurActivite", "partAuPorteur": true, "adresseFiscaleLine1": "adresseFiscaleLine1", "adresseFiscaleLine2": "adresseFiscaleLine2", "adresseFiscaleLine3": "adresseFiscaleLine3", "adresseFiscaleCptLcl": "adresseFiscaleCptLcl", "adresseFiscalePays": 1, "adresseResidenceLine1": "adresseResidenceLine1", "adresseResidenceLine2": "adresseResidenceLine2", "adresseResidenceLine3": "adresseResidenceLine3", "adresseResidenceCptLcl": "adresseResidenceCptLcl", "adresseResidencePays": 1, "adresseImplantationLine1": "adresseImplantationLine1", "adresseImplantationLine2": "adresseImplantationLine2", "adresseImplantationLine3": "adresseImplantationLine3", "adresseImplantationCptLcl": "adresseImplantationCptLcl", "adresseImplantationPays": 1, "paysActivitePrincipale": 1, "idClient": 1, "nom": "nom", "prenom": "prenom", "dateNaissance": 1, "paysNaissance": 1, "paysNationalite": 1, "profession": "profession", "nomEmployeur": "nomEmployeur", "categorieClientele": "PERSONNE_MORALE", "dossierId": 123, "detailDemande": "detailDemande", "statut": "ACTIF", "theme": "PPE", "escalade": "escalade" }] ); }) Sandbox.define('/rest/cellule/12/deletable', 'GET', function(req, res){ // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "value": true }); }) Sandbox.define('/rest/cellule/12', 'DELETE', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/user/1','GET', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "id": 1, "username": "216739", "nom": "Bassettt", "prenom": "Antoine", "email": "", "admin": false, "formatdate": "asd", "statut": "ACTIF", "cellules": [], "coUser": [{ "pole": 151, "pays": 1, "coRattachment": 151, "coRattachmentLibelle": "PoleABC", "parent": 152, "statut": "ACTIF", "dateRattachment": "2015-01-22", "usernameAdminRattachment": "123", "dateDetachement": "2015-01-22", "usernameAdminDetachement": "1234" }, { "pole": 151, "pays": 1, "coRattachment": 151, "coRattachmentLibelle": "PoleABC", "parent": 152, "statut": "INACTIF", "dateRattachment": "2015-01-22", "usernameAdminRattachment": "123", "dateDetachement": "2015-01-22", "usernameAdminDetachement": "1234" }] } ); }) Sandbox.define('/rest/contact','GET', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/reference/THEME', 'PUT', function(req, res){ // Check the request, make sure it is a compatible type // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/user/current/preferences','PUT', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/user','POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/dossier/searchPPE','POST', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json( [{ "dossierId": 250, "theme": "PPE", "typeEscalade": "ARBITRAGE", "detailDemande": "cc", "nomClient": "ccc", "statut": "cc", "pole": 150, "cellule": 151, "metier": 152, "dateCreation": "2014-12-12", "niveauDecision": "cc", "dateDerniereDecision": "2014-12-12" }, { "dossierId": 250, "theme": "PPE", "typeEscalade": "INFORMATION", "detailDemande": "cc", "nomClient": "ccc", "statut": "cc", "pole": 150, "cellule": 151, "metier": 152, "dateCreation": "2014-12-12", "niveauDecision": "cc", "dateDerniereDecision": "2014-12-12" }] ); }) Sandbox.define('/rest/user/1','PUT', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/dossier/250/upload','PUT', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); }) Sandbox.define('/rest/user/current/language','PUT', function(req, res) { // Set the type of response, sets the Content-Type header. res.type('application/json'); // Set the status code of the response. res.status(200); // Send the response body. res.json({ "status": "ok" }); })
9d1bb63d68009867f243d0c358fb967c01524c4c
[ "JavaScript" ]
1
JavaScript
moraruetc/ep-sandbox
3bcd343ad1800a3b73e27e69dba710b1f6a0a596
04470038277d0f0529639381ac7ee43bbd44e48e
refs/heads/master
<file_sep>import os import hashlib import sys print("============== Select Menu ==============") print("(1) Hash Calculation (2) Hashset (3) Exit") menu = int(input("Select >>> ")) if menu == 1: filename = input('FileName >>> ') f1 = open(filename, 'rb') data = f1.read() f1.close() md5 = hashlib.md5(data).hexdigest() sha1 = hashlib.sha1(data).hexdigest() sha256 = hashlib.sha256(data).hexdigest() print("============== Hash Result ==============") print("MD5: " + md5) print("SHA-1: " + sha1) print("SHA-256: " + sha256) if menu == 2: print("Default Searching Path is C:\\Users\\parj2\\Downloads") hashset = input("MD5 HashSet >>> ") path_dir = "C:/Users/parj2/Downloads/" file_list = os.listdir(path_dir) print(file_list) dic = {} for i in file_list: print(i) f2 = open(path_dir+i,'rb') realdata = f2.read() f2.close() md5 = hashlib.md5(realdata).hexdigest() dic[i] = md5 print("MD5: " + md5, end="\n\n") print("C:\\Users\\parj2\\Downloads ALL File MD5 Result Save!!") print(dic) for key, value in dic.items(): if value == hashset: print("============== Success ==============") print("Detection: "+ path_dir +key) break # else: # print("============== Fail ==============") # print("No matching MD5 HashSet~~") # sys.exit() if menu == 3: print("What The Fuxx!!") sys.exit()
b7878514dcae3e3efdbeae43be1a9701629f0548
[ "Python" ]
1
Python
fxploit/hash-result
0c0f70a6d6f2f0c74c792b3f46a39f59dde4ce9a
9b7cfbef63e4c288f7260f721d3bedb30b091c34
refs/heads/master
<repo_name>lichangao1826/flask-es<file_sep>/export.py from library.elasticsearch.manager import ElasticSearchManager import pandas as pd es_client = ElasticSearchManager() body = { "query": { "function_score": { "functions": [ { "script_score": { "script": "doc['rhyme_score'].value + doc['antithesis_score'].value" } } ], "query": { "bool": { "must": [ { "match": { "status_2_new": True } }, { "match": { "status_8_new": True } } ] } }, "score_mode": "first" } } } num = 0 content_list = [] total_score = [] is_symmetry = [] is_lyrics = [] song_name = [] story_ne_score = [] story_pos_score = [] story_sum_score = [] rhyme_text_list = [] antithesis_text_list = [] new_score = [] doc_list = es_client.search_by_scroll("sentence_nlp", body) for doc in doc_list: if num == 5000: break status = False for i in range(len(doc['_source']["text_list"]) - 1): if doc['_source']["text_list"][i] == doc['_source']["text_list"][i + 1]: status = True break if status: continue song_map = { "drew": "画心", "mydream": "我的梦 (Live)", "another": "另一个天堂", "we": "我们说好的", "wolf": "饿狼传说", "missyou": "想你,零点零一分", "loves": "爱的供养", "if": "如果爱下去", "final": "终于等到你", "only_one": "无双" } data = doc['_source'] content_list.append(data["sentence"].strip()) # total_score.append(data["symmetry_count"] + data["lyrics_count"]) # is_symmetry.append(1 if data["symmetry_count"] > 0 else 0) # is_lyrics.append(1 if data["lyrics_count"] > 0 else 0) song_name.append(song_map[data["song"]]) # story_ne_score.append(data["story_ne_score"]) # story_pos_score.append(data["story_pos_score"]) # story_sum_score.append(data["story_sum_score"]) current_rhyme_text_list = [] for text_list in data["rhyme_text_list"]: current_rhyme_text_list.append(",".join(text_list)) rhyme_text_list.append("|".join(current_rhyme_text_list)) current_antithesis_text_list = [] for text_list in data["antithesis_text_list"]: current_antithesis_text_list.append(",".join(text_list)) antithesis_text_list.append("|".join(current_antithesis_text_list)) new_score.append(data["rhyme_score"] + data["antithesis_score"]) num += 1 print(num) dataframe = pd.DataFrame({ '评论': content_list, "对仗句": antithesis_text_list, "押韵句": rhyme_text_list, "分数": new_score, "歌名": song_name }) dataframe.to_csv("nlp_new_v3.csv", index=False, sep=',') # 字典中的key值即为csv中列名 # dataframe = pd.DataFrame({ # '内容': content_list, # '总分': total_score, # "是否对仗": is_symmetry, # "是否押韵": is_lyrics, # "歌名": song_name # }) # 将DataFrame存储为csv,index表示是否显示行名,default=True # dataframe.to_csv("sentence.csv", index=False, sep=',') <file_sep>/main.py from flask import Flask, jsonify from library.elasticsearch.manager import ElasticSearchManager import requests import json app = Flask(__name__) es_client = ElasticSearchManager() @app.route('/') def hello_world(): return 'Hello World!' @app.route('/comment_story_<index_type>/<keyword>/<page>', methods=['GET']) def search_story_comment_old(index_type, keyword, page): score = 0 if index_type == "old": index = "ai_doc_wangyiyun_comment" score = 150 elif index_type == "new": index = "ai_doc_wangyiyun_comment_story_test_without_event" elif index_type == "new_with_event": index = "ai_doc_wangyiyun_comment_story_test" elif index_type == "new_probability_with_event": index = "ai_doc_wangyiyun_comment_story_test_probability" score = 500 elif index_type == "new_probability": index = "ai_doc_wangyiyun_comment_story_test_probability_without_event" elif index_type == "new_douban": index = "ai_doc_douban_v2_story" score = 100 elif index_type == "old_douban": index = "ai_doc_douban" score = 100 else: return "请输入正确的 index_type:old、new、new_with_event、new_probability、new_douban" body = { "query": { "bool": { "must": [ # { # "term": { # "document_type": { # "value": "wangyiyun_comment" # } # } # }, { "match_phrase": { "content": keyword } }, { "bool": { "should": [ { "nested": { "path": "score", "query": { "range": { "score.concentration_score": { "gt": score } } } } } ] } } ] } }, "sort": [ { "score.concentration_score": { "order": "desc", "nested_path": "score", "nested_filter": { "range": { "score.concentration_score": { "gt": score } } } } } ] } result = [] per_page = 100 doc_from = per_page * (int(page) - 1) doc_list = es_client.search_by_scroll(index, body) for i, doc in enumerate(doc_list): if i >= doc_from: result.append({ "hash_id": doc["_source"]["hash_id"], "story_score": doc["_source"]["score"]["concentration_score"], "content": doc["_source"]["content"] }) if len(result) >= per_page: break return jsonify(result) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) <file_sep>/requirements.txt elasticsearch==5.5.3 elasticsearch-dsl==5.4.0 flask==1.1.1 requests==2.22.0 <file_sep>/library/elasticsearch/manager.py from elasticsearch_dsl.connections import connections from elasticsearch import helpers ES_SERVER = { 'default': { 'host': ['192.168.0.253:9200'], } } class ElasticSearchManager(object): def __init__(self, group='default', timeout=60): if 'auth' in ES_SERVER[group]: self.__client = connections.create_connection( hosts=ES_SERVER[group]['host'], http_auth=ES_SERVER[group]['auth'], timeout=timeout) else: self.__client = connections.create_connection(hosts=ES_SERVER[group]['host'], timeout=timeout) def insert(self, index_name, data, doc_type=None): if not isinstance(data, dict) or 'hash_id' not in data: return '-1' if not doc_type: doc_type = index_name result = self.__client.index(index=index_name, doc_type=doc_type, id=data['hash_id'], body=data) return result['_id'] if '_id' in result else '-1' def get(self, index_name, auto_id, doc_type=None): if not doc_type: doc_type = index_name result = self.__client.get(index=index_name, doc_type=doc_type, id=auto_id) return result['_source'] if '_source' in result else {} def delete(self, index_name, auto_id, doc_type=None): if not doc_type: doc_type = index_name return self.__client.delete(index=index_name, doc_type=doc_type, id=auto_id, ignore=[400, 404]) def update(self, index_name, auto_id, data, doc_type=None): if not isinstance(data, dict): return '-1' if not doc_type: doc_type = index_name result = self.__client.index(index=index_name, doc_type=doc_type, id=auto_id, body=data) return result['_id'] if '_id' in result else '-1' def count(self, index_name, doc_type=None): if not doc_type: doc_type = index_name result = self.__client.count(index=index_name, doc_type=doc_type) return result['count'] if 'count' in result else 0 def get_mapping(self, index_name): result = self.__client.indices.get_mapping(index_name) return result def set_mapping(self, index_name, mapping, doc_type=None): if not doc_type: doc_type = index_name self.__client.indices.create(index=index_name, ignore=400) result = self.__client.indices.put_mapping(index=index_name, doc_type=doc_type, body=mapping) return result def search_by_scroll(self, index_name, body): return helpers.scan( client=self.__client, index=index_name, scroll='10080m', size=10, query=body, preserve_order=True )
144f65c41a7bb1fc34c6473339b3699bf61fb09c
[ "Python", "Text" ]
4
Python
lichangao1826/flask-es
79e0509b503c37bb838999ac45b64a563445e909
5e1af7d14a1135ce64e951072764c88d2e65f423
refs/heads/master
<file_sep> function myMap() { myCenter=new google.maps.LatLng(41.878114, -87.629798); var mapOptions= { center:myCenter, zoom:12, scrollwheel: false, draggable: false, mapTypeId:google.maps.MapTypeId.ROADMAP }; var map=new google.maps.Map(document.getElementById("googleMap"),mapOptions); var marker = new google.maps.Marker({ position: myCenter, }); marker.setMap(map); } // Modal Image Gallery function onClick(element) { document.getElementById("img01").src = element.src; document.getElementById("modal01").style.display = "block"; var captionText = document.getElementById("caption"); captionText.innerHTML = element.alt; } // Change style of navbar on scroll window.onscroll = function() {myFunction()}; function myFunction() { var navbar = document.getElementById("myNavbar"); if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) { navbar.className = "w3-bar" + " w3-card" + " w3-animate-top" + " w3-white"; } else { navbar.className = navbar.className.replace(" w3-card w3-animate-top w3-white", ""); } } function toggleFunction() { var x = document.getElementById("navDemo"); if (x.className.indexOf("w3-show") == -1) { x.className += " w3-show"; } else { x.className = x.className.replace(" w3-show", ""); } } // Initialize Firebase var config = { apiKey: "<KEY>", authDomain: "camp-days.firebaseapp.com", databaseURL: "https://camp-days.firebaseio.com", projectId: "camp-days", storageBucket: "", messagingSenderId: "1015701760329" }; firebase.initializeApp(config); // Get the modal document.getElementById("form").addEventListener("submit",submitForm); function submitForm(e){ e.preventDefault(); // Get values var name = getInputVal('name'); var email = getInputVal('email'); var message = getInputVal('message'); saveMessage(name,email,message); document.getElementById('form').reset(); } // References the messages collection var messagesRef = firebase.database().ref('contact'); function getInputVal(id){ return document.getElementById(id).value; } // Save message to firebase function saveMessage(name,email,message){ var newMessageRef = messagesRef.push(); newMessageRef.set({ name : name, email : email, message:message, }); }
da8868d0cf2e7bfbbf482fac859fc76ce651355a
[ "JavaScript" ]
1
JavaScript
ChaimaMazigh/Test
ae6de84b72279e4bc8fc99a252fec94a36335cda
49f1413028bcf0e47b9f2cc7239d469db382e66f
refs/heads/master
<file_sep>FileManager exercise. Briefing: A DAO factory is in charge of the instantiation of the different DAO's to be used in the persistence process. The files with the extension .txt will be persisted through the StudentDAOTxt, the .xml through StudentDAOXml and the .json thorugh StudentDAOJson. The persisted files can be found inside the Debug folder in the WinSite folder. A UML diagram is provided as a FileManager.dia file.<file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using FileManager.Common.Models; using Newtonsoft.Json; namespace FileManager.DataAccess.DAO { public class StudentDAOJson : IAbstractStudentDAO { private JsonSerializerSettings settings = null; private const string emptyJsonArray = "[]"; public string FilePath { get; private set; } public StudentDAOJson() { string solutionFolderPath = System.AppDomain.CurrentDomain.BaseDirectory; string fileName = ConfigurationManager.AppSettings["persistence_file_json"]; FilePath = solutionFolderPath + fileName; settings = new JsonSerializerSettings { DateFormatString = "dd'/'MM'/'yyyy", Formatting = Formatting.Indented }; } public Student Add(Student student) { WriteStudent(student); Student readStudent = FindById(student.StudentId); return readStudent; } private void WriteStudent(Student student) { if (!File.Exists(FilePath)) { InitializeJsonFile(); } string jsonString = ReadJsonFile(); List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonString, settings); students.Add(student); jsonString = JsonConvert.SerializeObject(students, settings); WriteJsonFile(jsonString); } private void InitializeJsonFile() { WriteJsonFile(emptyJsonArray); } private void WriteJsonFile(string jsonString) { StreamWriter writer = null; try { writer = new StreamWriter(FilePath, false); writer.Write(jsonString); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { writer.Dispose(); } } private string ReadJsonFile() { string jsonString = String.Empty; StreamReader reader = null; try { reader = new StreamReader(FilePath); jsonString = reader.ReadToEnd(); return jsonString; } catch (Exception ex) { Console.WriteLine(ex.Message); return String.Empty; } finally { reader.Close(); } } public Student FindById(int id) { string jsonString = ReadJsonFile(); List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonString, settings); foreach (Student student in students) { if (id == student.StudentId) { return student; } } return null; } public Student Update(int id, Student updatedStudent) { string jsonString = ReadJsonFile(); List<Student> students = JsonConvert.DeserializeObject<List<Student>>(jsonString, settings); int index = students.FindIndex(student => student.StudentId == id); if(index == -1) { throw new Exception(String.Format("No student in the file with id {0}", id)); } students[index].Name = updatedStudent.Name; students[index].Surname = updatedStudent.Surname; students[index].DateOfBirth = updatedStudent.DateOfBirth; jsonString = JsonConvert.SerializeObject(students, settings); WriteJsonFile(jsonString); return updatedStudent; } } } <file_sep>using FileManager.Common.Models; using FileManager.DataAccess.DAO.Singletons; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Resources; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace FileManager.Presentation.WinSite { public partial class Vuelos : Form { private static VuelosSingleton vuelosSingleton = null; public string language = Properties.Settings.Default.Language; public Vuelos() { Thread.CurrentThread.CurrentUICulture = new CultureInfo(language); InitializeComponent(); } private void originCbo_SelectedIndexChanged(object sender, EventArgs e) { string selectedCity = originCbo.SelectedItem.ToString(); InitializeDestinationCombobox(selectedCity); } private void destinationCbo_SelectedIndexChanged(object sender, EventArgs e) { //nothing to do atm. } private void Vuelos_Load(object sender, EventArgs e) { vuelosSingleton = VuelosSingleton.Instance; InitializeOriginComboBox(); string selectedCity = originCbo.SelectedItem.ToString(); InitializeDestinationCombobox(selectedCity); } private void InitializeOriginComboBox() { int size = VuelosSingleton.FlightsDictionary.Keys.Count; string[] items = new string[size]; for(int i = 0; i < size; ++i) { items[i] = VuelosSingleton.FlightsDictionary.Keys.ElementAt(i).Name; } originCbo.DataSource = items; originCbo.SelectedIndex = 0; } private void InitializeDestinationCombobox(string cityName) { List<Airport> airports; bool found = VuelosSingleton.FlightsDictionary.TryGetValue(new Airport(cityName), out airports); if (!found) { throw new Exception("No airports"); } string[] airportNames = new string[airports.Count]; for(int i = 0; i < airportNames.Length; ++i) { airportNames[i] = airports[i].Name; } destinationCbo.DataSource = airportNames; destinationCbo.SelectedItem = 0; } private void ChangeLanguage(string lang) { foreach(Control c in this.Controls) { ComponentResourceManager resources = new ComponentResourceManager(typeof(Vuelos)); resources.ApplyResources(c, c.Name, new CultureInfo(lang)); } } private void EnglishToolStripMenuItem_Click(object sender, EventArgs e) { ChangeLanguage("en-GB"); this.Text = "Flights"; Properties.Settings.Default.Language = "en-GB"; //TODO: remove literal strings } private void SpanishToolStripMenuItem_Click(object sender, EventArgs e) { ChangeLanguage("es-ES"); this.Text = "Vuelos"; Properties.Settings.Default.Language = "es-ES"; //TODO: remove literal strings } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using FileManager.Common.Models; using FileManager.Utilities; namespace FileManager.DataAccess.DAO { public class StudentDAOTxt : IAbstractStudentDAO { public string FilePath { get; private set; } public StudentDAOTxt() { string solutionFolderPath = System.AppDomain.CurrentDomain.BaseDirectory; string fileName = ConfigurationManager.AppSettings["persistence_file_txt"]; FilePath = solutionFolderPath + fileName; } public Student Add(Student student) { WriteStudent(student); Student readStudent = FindById(student.StudentId); return readStudent; } private void WriteStudent(Student student) { string line = student.StudentId + "," + student.Name + "," + student.Surname + "," + student.DateOfBirth.Day.ToString() + "/" + student.DateOfBirth.Month.ToString() + "/" + student.DateOfBirth.Year.ToString(); StreamWriter outputFile = null; WriteLine(outputFile, line); } private void WriteLine(StreamWriter outputFile, string line) { try { outputFile = new StreamWriter(FilePath, true); outputFile.WriteLine(line); } catch (IOException ex) { Console.WriteLine(ex.Message); } finally { outputFile.Dispose(); } } public Student FindById(int id) { List<string> lines = File.ReadLines(FilePath).ToList<string>(); foreach(string line in lines) { string[] splitLine = line.Split(new char[] { ',' }); int parsedId = ParseString(splitLine[0]); if(parsedId == id) { string name = splitLine[1]; string surname = splitLine[2]; string dateString = splitLine[3]; DateTime dateOfBirth = ConvertFromString(dateString); return new Student(id, name, surname, dateOfBirth); } } return null; } private int ParseString(string idString) { try { return Int32.Parse(idString); } catch(Exception ex) { Console.Write(ex.Message); throw; } } private DateTime ConvertFromString(string dateString) { try { return Convert.ToDateTime(dateString); } catch (Exception ex) { Console.Write(ex.Message); throw; } } public Student Update(int id, Student updatedStudent) { List<Student> readStudents = ReadAllStudents(); Student studentToUpdate = FindById(id); int studentIndex = readStudents.IndexOf(studentToUpdate); if (studentIndex != -1) { readStudents[studentIndex].Name = updatedStudent.Name; readStudents[studentIndex].Surname = updatedStudent.Surname; readStudents[studentIndex].DateOfBirth = updatedStudent.DateOfBirth; //sobreescribo el archivo StreamWriter streamWriter = GetWriter(); string studentsString = string.Empty; foreach (Student student in readStudents) { studentsString += student.ToString(); } streamWriter.Write(studentsString); streamWriter.Dispose(); return updatedStudent; } return null; } private List<Student> ReadAllStudents() { StreamReader streamReader = GetReader(); string line = null; List<Student> readStudents = new List<Student>(); //leo todos los students while (streamReader.Peek() >= 0) { line = streamReader.ReadLine(); string[] split = line.Split(new char[] { ',' }); Student student = new Student(Int32.Parse(split[0]), split[1], split[2], Convert.ToDateTime(split[3])); readStudents.Add(student); } streamReader.Dispose(); return readStudents; } private StreamReader GetReader() { StreamReader streamReader = null; try { streamReader = new StreamReader(FilePath); } catch (Exception ex) { Console.Write(ex.Message); streamReader.Dispose(); throw; } return streamReader; } private StreamWriter GetWriter() { StreamWriter streamWriter = null; try { streamWriter = new StreamWriter(FilePath, false); } catch(Exception ex) { Console.Write(ex.Message); streamWriter.Dispose(); throw; } return streamWriter; } } } <file_sep>using FileManager.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.Common.Models { public class Student { public Student() { } public Student(int id, string name, string surname, DateTime dateOfBirth) { StudentId = id; Name = name; Surname = surname; DateOfBirth = dateOfBirth; } public int StudentId { get; set; } public string Name { get; set; } public string Surname { get; set; } public DateTime DateOfBirth { get; set; } public override bool Equals(object obj) { if (obj == null) return false; Student otherStudent = (Student)obj; return this.Name == otherStudent.Name && this.Surname == otherStudent.Surname && this.DateOfBirth == otherStudent.DateOfBirth; } public override int GetHashCode() { string nameSurnameBirth = Name + Surname + DateOfBirth.Day.ToString(); return nameSurnameBirth.GetHashCode(); } public override string ToString() { return StudentId + "," + Name + "," + Surname + "," + DateUtilities.DateTimeToStringES(DateOfBirth) + "\n"; } } } <file_sep>using FileManager.Common.Models; using FileManager.DataAccess.DAO; using FileManager.DataAccess.DAO.DAOFactoriesImpl; using FileManager.Utilities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace FileManager.Presentation.WinSite { public partial class Form1 : Form { public string language = Properties.Settings.Default.Language; private IAbstractStudentDAOFactory studentDAOFactory = null; private IAbstractStudentDAO studentDAOTxt = null; private IAbstractStudentDAO studentDAOXml = null; private IAbstractStudentDAO studentDAOJson = null; public Form1() { Thread.CurrentThread.CurrentUICulture = new CultureInfo(language); InitializeComponent(); InitializeDAOFactory(); InitializeStudentDAOs(); } private void InitializeDAOFactory() { studentDAOFactory = new StudentDAOFactory(); } private void InitializeStudentDAOs() { studentDAOTxt = studentDAOFactory.CreateStudentDAOTxt(); studentDAOXml = studentDAOFactory.CreateStudentDAOXml(); studentDAOJson = studentDAOFactory.CreateStudentDAOJson(); } private void BtnSaveTxt_Click(object sender, EventArgs e) { BtnSave(studentDAOTxt); } private Student CreateStudentFromFields() { int studentId = Int32.Parse(txtStudentId.Text); DateTime dateOfBirth = DateUtilities.StringToDateTimeES(txtDateOfBirth.Text); return new Student(studentId, txtName.Text, txtSurname.Text, dateOfBirth); } private void ClearFormFields() { foreach (Control control in this.Controls) { if (control is TextBox) { control.ResetText(); } } } private void ShowPopUp(string message) { Form popup = new Popup(message); popup.ShowDialog(); popup.Dispose(); } private void BtnSaveXML_Click(object sender, EventArgs e) { BtnSave(studentDAOXml); } private void BtnSaveJSON_Click(object sender, EventArgs e) { BtnSave(studentDAOJson); } private void EnglishToolStripMenuItem1_Click(object sender, EventArgs e) { ChangeLanguage("en-GB"); Properties.Settings.Default.Language = "en-GB"; } private void SpanishToolStripMenuItem_Click(object sender, EventArgs e) { ChangeLanguage("es-ES"); Properties.Settings.Default.Language = "es-ES"; } private void ChangeLanguage(string language) { foreach(Control c in this.Controls) { ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1)); resources.ApplyResources(c, c.Name, new CultureInfo(language)); } } private void BtnUpdateTxt_Click(object sender, EventArgs e) { BtnUpdate(studentDAOTxt); } private void BtnFindStudent_Click(object sender, EventArgs e) { BtnFind(studentDAOTxt); } private void BtnBuscarXml_Click(object sender, EventArgs e) { BtnFind(studentDAOXml); } private void BtnUpdateXml_Click(object sender, EventArgs e) { BtnUpdate(studentDAOXml); } private void BtnSave(IAbstractStudentDAO dao) { Student student = CreateStudentFromFields(); dao.Add(student); //TODO: Check if the save operation is OK, otherwise show error and keep form data. ClearFormFields(); ShowPopUp("Estudiante añadido"); } private void BtnFind(IAbstractStudentDAO dao) { int studentId = Int32.Parse(txtStudentId.Text); Student foundStudent = dao.FindById(studentId); if (foundStudent != null) { txtStudentId.Text = foundStudent.StudentId.ToString(); txtName.Text = foundStudent.Name; txtSurname.Text = foundStudent.Surname; txtDateOfBirth.Text = DateUtilities.DateTimeToStringES(foundStudent.DateOfBirth); } } private void BtnUpdate(IAbstractStudentDAO dao) { Student student = CreateStudentFromFields(); dao.Update(student.StudentId, student); //TODO: Check if the save operation is OK, otherwise show error and keep form data. ClearFormFields(); ShowPopUp("Estudiante actualizado"); } private void BtnFindJson_Click(object sender, EventArgs e) { BtnFind(studentDAOJson); } private void BtnUpdateJson_Click(object sender, EventArgs e) { BtnUpdate(studentDAOJson); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.DataAccess.DAO.DAOFactoriesImpl { public class StudentDAOFactory : IAbstractStudentDAOFactory { public IAbstractStudentDAO CreateStudentDAOJson() { return new StudentDAOJson(); } public IAbstractStudentDAO CreateStudentDAOTxt() { return new StudentDAOTxt(); } public IAbstractStudentDAO CreateStudentDAOXml() { return new StudentDAOXml(); } } } <file_sep>using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.Utilities { public class DateUtilities { public static DateTime StringToDateTimeES(string date) { CultureInfo cultureInfo = new CultureInfo("es-ES"); try { return DateTime.Parse(date, cultureInfo); } catch (Exception ex) { Console.Write(ex.Message); return new DateTime(0, 0, 0); } } public static string DateTimeToStringES(DateTime dateTime) { string dateString = dateTime.Day.ToString() + "/" + dateTime.Month.ToString() + "/" + dateTime.Year.ToString(); return dateString; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.Common.Models { public class Airport { public string Name { get; set; } public Airport(){} public Airport(string name) { Name = name; } public override bool Equals(object obj) { return obj is Airport airport; } public override int GetHashCode() { var hashCode = 1174183988; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Name); return hashCode; } public override string ToString() { return Name; } } } <file_sep>using FileManager.Common.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FileManager.DataAccess.DAO.Singletons { public class VuelosSingletonWithStaticConstructor { public static VuelosSingletonWithStaticConstructor Instance { get; } = new VuelosSingletonWithStaticConstructor(); public static string FilePath { get; private set; } public Guid Id { get; set; } public static Dictionary<Airport, List<Airport>> FlightsDictionary { get; private set; } static VuelosSingletonWithStaticConstructor() { string solutionFolderPath = System.AppDomain.CurrentDomain.BaseDirectory; string fileName = ConfigurationManager.AppSettings["flights_file_xml"]; FilePath = solutionFolderPath + fileName; FlightsDictionary = new Dictionary<Airport, List<Airport>>(); } private VuelosSingletonWithStaticConstructor() { Id = Guid.NewGuid(); LoadFlights(FilePath); } private static void LoadFlights(string FilePath) { XDocument document = XDocument.Load(FilePath); XElement root = document.Element("airports"); var airports = from element in root.Elements() select element; foreach (XElement connection in airports) { string name = connection.Attribute("origin").Value; var connections = connection.Elements("connection"); List<Airport> airportConnections = new List<Airport>(); foreach (XElement con in connections) { airportConnections.Add(new Airport(con.Value)); } FlightsDictionary.Add(new Airport(name), airportConnections); } } } } <file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting; using FileManager.DataAccess.DAO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FileManager.DataAccess.DAO.DAOFactoriesImpl; using FileManager.Common.Models; using FileManager.Utilities; namespace FileManager.DataAccess.DAO.Tests { [TestClass()] public class StudentDAOXmlTests { IAbstractStudentDAOFactory daoFactory = null; IAbstractStudentDAO studentDaoXml = null; [TestMethod()] public void StudentDAOXmlTest() { Assert.IsTrue(true); } [TestMethod()] [DataRow(0, "CarlosTest", "López", "01", "02", "2000")] public void AddTest(int id, string name, string surname, string day, string month, string year) { daoFactory = new StudentDAOFactory(); studentDaoXml = daoFactory.CreateStudentDAOXml(); string dateString = day + "/" + month + "/" + year; Student student = new Student(id, name, surname, DateUtilities.StringToDateTimeES(dateString)); Student insertedStudent = studentDaoXml.Add(student); Assert.IsTrue(student.Equals(insertedStudent)); } [TestMethod()] [DataRow(0)] public void FindByIdTest(int studentId) { daoFactory = new StudentDAOFactory(); studentDaoXml = daoFactory.CreateStudentDAOTxt(); Student found = studentDaoXml.FindById(studentId); Assert.IsNotNull(found); } [TestMethod()] public void UpdateTest() { Assert.Fail(); } } }<file_sep>using FileManager.Common.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FileManager.DataAccess.DAO.Singletons { public class VuelosSingleton { private static VuelosSingleton instance = null; private static readonly object padlock = new object(); public static string FilePath { get; private set; } public Guid Id { get; set; } public static Dictionary<Airport, List<Airport>> FlightsDictionary { get; private set; } private VuelosSingleton() { Id = Guid.NewGuid(); string solutionFolderPath = System.AppDomain.CurrentDomain.BaseDirectory; string fileName = ConfigurationManager.AppSettings["flights_file_xml"]; FilePath = solutionFolderPath + fileName; FlightsDictionary = new Dictionary<Airport, List<Airport>>(); LoadFlights(FilePath); } public static VuelosSingleton Instance { get { lock (padlock) if(instance == null) { instance = new VuelosSingleton(); } return instance; } } private static void LoadFlights(string FilePath) { XDocument document= XDocument.Load(FilePath); XElement root = document.Element("airports"); var airports = from element in root.Elements() select element; foreach(XElement connection in airports) { string name = connection.Attribute("origin").Value; var connections = connection.Elements("connection"); List<Airport> airportConnections = new List<Airport>(); foreach(XElement con in connections) { airportConnections.Add(new Airport(con.Value)); } FlightsDictionary.Add(new Airport(name), airportConnections); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileManager.DataAccess.DAO { public interface IAbstractStudentDAOFactory { IAbstractStudentDAO CreateStudentDAOTxt(); IAbstractStudentDAO CreateStudentDAOXml(); IAbstractStudentDAO CreateStudentDAOJson(); } } <file_sep>using System; using FileManager.DataAccess.DAO.Singletons; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FileManager.DataAccess.DAO.Integration.Test { [TestClass] public class UnitTest1 { [TestMethod] public void TestVuelosSingleton() { VuelosSingleton vuelosSingletonsFirst = VuelosSingleton.Instance; VuelosSingleton vuelosSingletonsSecond = VuelosSingleton.Instance; Assert.IsTrue(vuelosSingletonsFirst.Id.ToString() == vuelosSingletonsSecond.Id.ToString()); } [TestMethod] public void TestVuelosSingletonWithStaticConstuctors() { //TODO: this static constructor singleton is not working. Fix this VuelosSingletonWithStaticConstructor vuelosSingletonsFirst = VuelosSingletonWithStaticConstructor.Instance; VuelosSingletonWithStaticConstructor vuelosSingletonsSecond = VuelosSingletonWithStaticConstructor.Instance; Assert.IsTrue(vuelosSingletonsFirst.Id.ToString() == vuelosSingletonsSecond.Id.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using FileManager.Common.Models; using FileManager.Utilities; namespace FileManager.DataAccess.DAO { public class StudentDAOXml : IAbstractStudentDAO { private XDocument xDocument = null; public string FilePath { get; private set; } public StudentDAOXml() { string solutionFolderPath = System.AppDomain.CurrentDomain.BaseDirectory; string fileName = ConfigurationManager.AppSettings["persistence_file_xml"]; FilePath = solutionFolderPath + fileName; } public Student Add(Student student) { WriteStudent(student); Student readStudent = FindById(student.StudentId); return readStudent; } private void WriteStudent(Student student) { if (!File.Exists(FilePath)) { xDocument = CreateNewDocument(); } xDocument = XDocument.Load(FilePath); XElement root = xDocument.Element("students"); XElement studentElement = CreateStudentElement(student); root.Add(studentElement); xDocument.Save(FilePath); } private XDocument CreateNewDocument() { XDocument xDocument = new XDocument(new XElement("students", "")); xDocument.Save(FilePath); return xDocument; } private XElement CreateStudentElement(Student student) { XElement studentElement = new XElement("student", ""); studentElement.Add( new XElement("id", student.StudentId), new XElement("name", student.Name), new XElement("surname", student.Surname), new XElement("dateOfBirth", DateUtilities.DateTimeToStringES(student.DateOfBirth))); return studentElement; } public Student FindById(int id) { if (!File.Exists(FilePath)) { throw new Exception("No file found:" + FilePath); } xDocument = XDocument.Load(FilePath); var student = from element in xDocument.Element("students").Elements() where element.Element("id").Value.Equals(id.ToString()) select element; if (student == null) { return null; } XElement found = GetFirstElement(student); string name = found.Element("name").Value; string surname = found.Element("surname").Value; DateTime dateOfBirth = Convert.ToDateTime(found.Element("dateOfBirth").Value); return new Student(id, name, surname, dateOfBirth); } private XElement GetFirstElement(IEnumerable<XElement> elements) { try { return elements.First(); } catch (Exception ex) { Console.Write(ex.Message); throw; } } public Student Update(int id, Student updatedStudent) { if(!File.Exists(FilePath)) { throw new Exception("No file found " + FilePath); } xDocument = XDocument.Load(FilePath); var studentToUpdate = from student in xDocument.Elements("students").Elements() where student.Element("id").Value.Equals(id.ToString()) select student; GetFirstElement(studentToUpdate).Element("name").Value = updatedStudent.Name; GetFirstElement(studentToUpdate).Element("surname").Value = updatedStudent.Surname; GetFirstElement(studentToUpdate).Element("dateOfBirth").Value = DateUtilities.DateTimeToStringES(updatedStudent.DateOfBirth); xDocument.Save(FilePath); return updatedStudent; } } }
3a999c753d6de6fd23aa36756a2f80c5df6f38df
[ "Markdown", "C#" ]
15
Markdown
danielPerPar2/FileManager
f34c44bdc7139a9e61fee26bd42d91fcf4f242f1
9bf20d12a7e31723dad6756aaa2c7df61a4c731b
refs/heads/master
<repo_name>Sampath1893/EmployeeOps<file_sep>/src/app/services/authentication.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DatePipe } from '@angular/common'; import { DailyLoginService } from '../services/daily-login.service'; import {MatSnackBar} from '@angular/material'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { constructor(public snackBar: MatSnackBar,private http: HttpClient,private dailyLogin:DailyLoginService) { } openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } private _loginUrl="http://localhost:3000/api/login"; login(userData) { return this.http.post<any>(this._loginUrl,userData) }; logout() { const pipe = new DatePipe('en-US'); const logoutTime= new Date; let uploadObj={ date: pipe.transform(logoutTime,'shortDate'), // @ts-ignore employeeID: localStorage.getItem('currentUser'), outTime: pipe.transform(logoutTime,'mediumTime') } this.dailyLogin.updateDailyLogin(uploadObj) .subscribe( res => { /*if(res.date=="SessionTimedOut"){ this.openSnackBar("Logout Session Timed Out!","Close"); }*/ localStorage.removeItem('currentUser')}, err => console.log(err) ) } } <file_sep>/src/app/services/daily-login.service.spec.ts import { TestBed, inject } from '@angular/core/testing'; import { DailyLoginService } from './daily-login.service'; describe('DailyLoginService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [DailyLoginService] }); }); it('should be created', inject([DailyLoginService], (service: DailyLoginService) => { expect(service).toBeTruthy(); })); }); <file_sep>/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import {MatSnackBar} from '@angular/material'; import { AuthenticationService } from '../services/authentication.service'; import { Router, ActivatedRoute } from '@angular/router'; import { DailyLoginService } from '../services/daily-login.service'; import { DatePipe } from '@angular/common'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { hide : boolean = true; returnUrl: string; userData = {} constructor(public snackBar: MatSnackBar, private authenticationService: AuthenticationService, private route: ActivatedRoute, private router: Router, private dailyLogin:DailyLoginService) {} openSnackBar(message: string, action: string) { this.snackBar.open(message, action, { duration: 2000, }); } checkLogin(){ this.authenticationService.login(this.userData) .subscribe( res => { this.openSnackBar("Welcome "+res[0].name,"Close"); localStorage.setItem('currentUser', res[0].employeeID); this.router.navigate([this.returnUrl]); this.updateDailyLogin(); }, err => this.openSnackBar(err.error,"close") ) } updateDailyLogin(){ const pipe = new DatePipe('en-US'); const loginTime= new Date; let uploadObj={ date: pipe.transform(loginTime,'shortDate'), // @ts-ignore employeeID: this.userData.userID, inTime: pipe.transform(loginTime,'mediumTime') } this.dailyLogin.updateDailyLogin(uploadObj) .subscribe( res => console.log(res), err => console.log(err) ) } ngOnInit() { // reset login status this.authenticationService.logout(); // get return url from route parameters or default to '/' this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/'; } } <file_sep>/server/routes/api.js const express = require('express') const router = express.Router() const User = require('../models/user') const dailyData = require ('../models/dailyLogin') const mongoose = require('mongoose') const db="mongodb://sampath:<EMAIL>:31711/employeeops" mongoose.set('useFindAndModify', false) mongoose.connect(db, { useNewUrlParser: true },err =>{ if(err){ console.error('Error'+err) }else{ console.log('Connected to mongodb') } }) router.get('/',(req, res)=>{ res.send('From API route') }) router.post('/login',(req,res)=>{ let userData = req.body // console.log(userData) User.find({employeeID: userData.userID},(error,user)=>{ // console.log(user) if(error){ console.log(error) } else{ if(user.length<=0){ res.status(401).send('Invalid UserID') } else{ //console.log(user.password) // console.log(userData.password) if(user[0].password !== userData.password){ res.status(401).send('Invalid Passsword') } else{ res.status(200).send(user) } } } }) }) router.post('/dailyLogin',(req,res)=>{ let loginData=req.body dailyData.find({date: loginData.date,employeeID:loginData.employeeID},(error,userloginData)=>{ if(error){ console.log(error) } else{ if(userloginData.length>0 ){ if(loginData.outTime){ dailyData.findOneAndUpdate({date: loginData.date,employeeID:loginData.employeeID},{$set:req.body},{new:false},(error,userUpdatedData)=>{ if(error){ res.status(401).send('Internal Error Occured') } else{ res.status(200).send(userUpdatedData) } }) } } else{ if(loginData.outTime){ loginData.date='SessionTimedOut'; res.status(200).send(loginData) } else{ let dayData=new dailyData(loginData) dayData.save((error,updatedData)=>{ if(error){ res.status(401).send('Internal Error Occured') } else{ res.status(200).send(updatedData) } }) } } } }) }) module.exports = router
5c1d54ed0bb6dbc2d5e1334585f674b1fb8676ce
[ "JavaScript", "TypeScript" ]
4
TypeScript
Sampath1893/EmployeeOps
601caff8633a5ef06c98a071e6cebff4c67e994a
47d5bcdeb1d1eb248ca66347f5656c28add484ca
refs/heads/master
<file_sep>#ifndef RLL_COLORSET_H #define RLL_COLORSET_H #include "Color.hpp" #include <vector> namespace rll { class ColorSet { public: ColorSet() { colorMap.push_back(Color(0, 0, 255)); colorMap.push_back(Color(0, 255, 0)); colorMap.push_back(Color(255, 0, 0)); colorMap.push_back(Color(0, 255, 255)); colorMap.push_back(Color(255, 255, 0)); colorMap.push_back(Color(0, 127, 255)); colorMap.push_back(Color(255, 127, 0)); colorMap.push_back(Color(0, 255, 127)); colorMap.push_back(Color(127, 255, 0)); } const Color getColorByIndex(int id) const { return colorMap.at(id); } private: std::vector< Color > colorMap; }; } // rll #endif //RLL_COLORSET_H <file_sep>cmake_minimum_required(VERSION 3.3) project(Fellton) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(PATH_TO_LIBTCOD /home/andrew/lib/libtcod) set(LIBTCOD_HEADERS ${PATH_TO_LIBTCOD}/headers) set(LIBTCOD_LIBRARY ${PATH_TO_LIBTCOD}/) include_directories(${LIBTCOD_HEADERS}) link_directories(${LIBTCOD_LIBRARY}) include_directories(src/) set(SOURCE_FILES main.cpp) add_executable(Fellton ${SOURCE_FILES}) target_link_libraries(Fellton -ltcodxx -ltcod) execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_SOURCE_DIR}/res/tileset.png ${CMAKE_BINARY_DIR}/terminal.png ) <file_sep>#ifndef RLL_AREA_HPP #define RLL_AREA_HPP #include "TPoint.hpp" #include <vector> namespace rll { template< typename T > class TArea { protected: typedef int CoordinateT; public: TArea() : xSize(0), ySize(0) { } TArea(const Point& p) : TArea(p.x(), p.y()) { } TArea(const Point& p, const T& initValue) : TArea(p.x(), p.y(), initValue) { } TArea(CoordinateT x, CoordinateT y) : TArea(x, y, T()) { } TArea(CoordinateT x, CoordinateT y, const T& initValue) : field(y, std::vector< T >(x, initValue)) { xSize = computeXSize(); ySize = computeYSize(); } TArea(const TArea& a) : field(a.field), xSize(a.xSize), ySize(a.ySize) { } virtual ~TArea() = default; int getYSize() const { return ySize; } int getXSize() const { return xSize; } Point getSize() const { return Point::makePoint(getXSize(), getYSize()); } int getElementCount() const { return getYSize() * getXSize(); } T& at(const Point& p) { return at(p.x(), p.y()); } T& at(CoordinateT x, CoordinateT y) { return field/*[y][x]*/.at(y).at(x); } T& at(CoordinateT id) { return at(id%getXSize(), id/getXSize()); } T& operator [] (CoordinateT id) { return at(id); } T& operator [] (const Point& p) { return at(p); } T getElement(const Point& p) const { return getElement(p.x(), p.y()); } T getElement(CoordinateT x, CoordinateT y) const { return field/*[y][x]*/.at(y).at(x); } void setElement(const Point& p, const T& element) { setElement(p.x(), p.y(), element); } void setElement(CoordinateT x, CoordinateT y, const T& element) { at(x, y) = element; } bool borders(const Point& p) const { return borders(p.x(), p.y()); } bool borders(CoordinateT x, CoordinateT y) const { return (x>=0 && x < getXSize()) && (y>=0 && y < getYSize()); } void resize(const Point& size) { resize(size.x(), size.y()); } void resize(CoordinateT x, CoordinateT y) { field.resize(y); for(CoordinateT c = 0; c < y; c++) { field[c].resize(x); } xSize = computeXSize(); ySize = computeYSize(); } void fill(const T& fillingValue) { std::fill(field.begin(), field.end(), std::vector< T >(getXSize(), fillingValue)); } bool isEmpty() const { return getYSize() == 0; } protected: std::vector< std::vector< T > > field; int xSize, ySize; private: int computeYSize() const { return (int)field.size(); } int computeXSize() const { return (int)field.size() ? (int)field.front().size() : 0; } }; typedef TArea< int > Area; } // rll #endif //RLL_AREA_HPP <file_sep>#ifndef RLL_POINT_HPP #define RLL_POINT_HPP namespace rll { template < typename T > class TPoint { public: TPoint() : TPoint(T(), T(), T()) { } TPoint(const TPoint& p) : _x(p.x()), _y(p.y()), _z(p.z()) { } TPoint(const T& x, const T& y, const T& z = T()) : _x(x), _y(y), _z(z) { } T x() const { return _x; } T y() const { return _y; } T z() const { return _z; } T& x() { return _x; } T& y() { return _y; } T& z() { return _z; } TPoint shift(const T& x, const T& y, const T& z = 0) const { return TPoint(_x + x, _y + y, _z + z); } TPoint shift(const TPoint& p) const { return shift(p.x(), p.y(), p.z()); } bool operator == (const TPoint& p) const { return x()==p.x() and y()==p.y() and z()==p.z(); } bool operator != (const TPoint& p) const { return not (*this == p); } bool operator < (TPoint const& rhs) const { return x() < rhs.x() or (x() == rhs.x() and y() < rhs.y() or(y() == rhs.y() and z() < rhs.z())); } virtual ~TPoint() = default; static TPoint makePoint(const T& x, const T& y, const T& z = 0) { return TPoint(x, y, z); } private: T _x, _y, _z; }; typedef TPoint< int > Point; } // rll #endif //RLL_POINT_HPP <file_sep>////////////////////////////////////////////////////////////////////////// // Map generators ////////////////////////////////////////////////////////////////////////// #pragma once #ifndef RL_MAPGENERATORS_H #define RL_MAPGENERATORS_H #include "mapgenerators/standarddungeon.h" #include "mapgenerators/maze.h" #include "mapgenerators/antnest.h" #include "mapgenerators/mines.h" #include "mapgenerators/caves.h" #include "mapgenerators/spaceshuttle.h" #include "mapgenerators/simplecity.h" #endif <file_sep>#ifndef RLL_CONNECTEDREGIONSEARCHER_HPP #define RLL_CONNECTEDREGIONSEARCHER_HPP #include <algorithm> #include "NeighborhoodSearcher.hpp" namespace rll { template< typename T > class ConnectedRegionSearcher { public: ConnectedRegionSearcher() : regionMaxId(0) { }; TArea< T > search(const TArea< T >& field); int regionCount() { return regionMaxId; } private: void searchRecursive(const TArea< T > &field, TArea< T >& regions, int x, int y, int id); int regionMaxId; }; template< typename T > TArea< T > ConnectedRegionSearcher<T>::search(const TArea< T > &field) { TArea< T > result(field.getXSize(), field.getYSize(), -1); for(int y = 0; y < field.getYSize(); y++) { for (int x = 0; x < field.getXSize(); x++) { if(result.getElement(x, y) == -1) { searchRecursive(field, result, x, y, regionMaxId++); } } } return result; } template< typename T > void ConnectedRegionSearcher<T>::searchRecursive( const TArea< T > &field, TArea< T >& regions, int x, int y, int id ) { NeighborhoodSearcher< T > searcher(field); typename NeighborhoodSearcher< T >::neighborSetT neighbors; regions.setElement(x, y, id); neighbors = searcher.FindNeumann({ x, y }); T originElement = field.getElement(x, y); for(int i = 0; i < neighbors.size(); i++) { if(neighbors[i]._data == originElement && regions.getElement(neighbors[i]) == -1) { searchRecursive(field, regions, neighbors[i].x(), neighbors[i].y(), id); } } } } // rll #endif //RLL_CONNECTEDREGIONSEARCHER_HPP <file_sep>// permissive-fov.cc /* Copyright (c) 2007, <NAME>. Licensed under the BSD license. See LICENSE.txt for details. */ #include <list> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include "permissive-fov.h" using std::list; using std::max; using std::min; using std::string; namespace { struct offsetT { public: offsetT(short newX = 0, short newY = 0) : x(newX) , y(newY) { } public: short x; short y; }; std::ostream & operator<<(std::ostream & stream, offsetT const & right) { stream << "(" << right.x << ", " << right.y << ")"; return stream; } struct fovStateT { offsetT source; permissiveMaskT * mask; isBlockedFunction isBlocked; visitFunction visit; void * context; offsetT quadrant; offsetT extent; }; struct lineT { lineT(offsetT newNear=offsetT(), offsetT newFar=offsetT()) : near(newNear) , far(newFar) { } bool isBelow(offsetT const & point) { return relativeSlope(point) > 0; } bool isBelowOrContains(offsetT const & point) { return relativeSlope(point) >= 0; } bool isAbove(offsetT const & point) { return relativeSlope(point) < 0; } bool isAboveOrContains(offsetT const & point) { return relativeSlope(point) <= 0; } bool doesContain(offsetT const & point) { return relativeSlope(point) == 0; } // negative if the line is above the point. // positive if the line is below the point. // 0 if the line is on the point. int relativeSlope(offsetT const & point) { return (far.y - near.y)*(far.x - point.x) - (far.y - point.y)*(far.x - near.x); } offsetT near; offsetT far; }; struct bumpT { bumpT() : parent(NULL) {} offsetT location; bumpT * parent; }; struct fieldT { fieldT() : steepBump(NULL), shallowBump(NULL) {} lineT steep; lineT shallow; bumpT * steepBump; bumpT * shallowBump; }; void visitSquare(fovStateT const * state, offsetT const & dest, list<fieldT>::iterator & currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps, list<fieldT> & activeFields); list<fieldT>::iterator checkField(list<fieldT>::iterator currentField, list<fieldT> & activeFields); void addShallowBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps); void addSteepBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps); bool actIsBlocked(fovStateT const * state, offsetT const & pos); void calculateFovQuadrant(fovStateT const * state) { list<bumpT> steepBumps; list<bumpT> shallowBumps; // activeFields is sorted from shallow-to-steep. list<fieldT> activeFields; activeFields.push_back(fieldT()); activeFields.back().shallow.near = offsetT(0, 1); activeFields.back().shallow.far = offsetT(state->extent.x, 0); activeFields.back().steep.near = offsetT(1, 0); activeFields.back().steep.far = offsetT(0, state->extent.y); offsetT dest(0, 0); // Visit the source square exactly once (in quadrant 1). if (state->quadrant.x == 1 && state->quadrant.y == 1) { actIsBlocked(state, dest); } list<fieldT>::iterator currentField = activeFields.begin(); short i = 0; short j = 0; int maxI = state->extent.x + state->extent.y; // For each square outline for (i = 1; i <= maxI && ! activeFields.empty(); ++i) { int startJ = max(0, i - state->extent.x); int maxJ = min(i, state->extent.y); // Visit the nodes in the outline for (j = startJ; j <= maxJ && currentField != activeFields.end(); ++j) { dest.x = i-j; dest.y = j; visitSquare(state, dest, currentField, steepBumps, shallowBumps, activeFields); } currentField = activeFields.begin(); } } void visitSquare(fovStateT const * state, offsetT const & dest, list<fieldT>::iterator & currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps, list<fieldT> & activeFields) { // The top-left and bottom-right corners of the destination square. offsetT topLeft(dest.x, dest.y + 1); offsetT bottomRight(dest.x + 1, dest.y); while (currentField != activeFields.end() && currentField->steep.isBelowOrContains(bottomRight)) { // case ABOVE // The square is in case 'above'. This means that it is ignored // for the currentField. But the steeper fields might need it. ++currentField; } if (currentField == activeFields.end()) { // The square was in case 'above' for all fields. This means that // we no longer care about it or any squares in its diagonal rank. return; } // Now we check for other cases. if (currentField->shallow.isAboveOrContains(topLeft)) { // case BELOW // The shallow line is above the extremity of the square, so that // square is ignored. return; } // The square is between the lines in some way. This means that we // need to visit it and determine whether it is blocked. bool isBlocked = actIsBlocked(state, dest); if (!isBlocked) { // We don't care what case might be left, because this square does // not obstruct. return; } if (currentField->shallow.isAbove(bottomRight) && currentField->steep.isBelow(topLeft)) { // case BLOCKING // Both lines intersect the square. This current field has ended. currentField = activeFields.erase(currentField); } else if (currentField->shallow.isAbove(bottomRight)) { // case SHALLOW BUMP // The square intersects only the shallow line. addShallowBump(topLeft, currentField, steepBumps, shallowBumps); currentField = checkField(currentField, activeFields); } else if (currentField->steep.isBelow(topLeft)) { // case STEEP BUMP // The square intersects only the steep line. addSteepBump(bottomRight, currentField, steepBumps, shallowBumps); currentField = checkField(currentField, activeFields); } else { // case BETWEEN // The square intersects neither line. We need to split into two fields. list<fieldT>::iterator steeperField = currentField; list<fieldT>::iterator shallowerField = activeFields.insert(currentField, *currentField); addSteepBump(bottomRight, shallowerField, steepBumps, shallowBumps); checkField(shallowerField, activeFields); addShallowBump(topLeft, steeperField, steepBumps, shallowBumps); currentField = checkField(steeperField, activeFields); } } list<fieldT>::iterator checkField(list<fieldT>::iterator currentField, list<fieldT> & activeFields) { list<fieldT>::iterator result = currentField; // If the two slopes are colinear, and if they pass through either // extremity, remove the field of view. if (currentField->shallow.doesContain(currentField->steep.near) && currentField->shallow.doesContain(currentField->steep.far) && (currentField->shallow.doesContain(offsetT(0, 1)) || currentField->shallow.doesContain(offsetT(1, 0)))) { result = activeFields.erase(currentField); } return result; } void addShallowBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps) { // First, the far point of shallow is set to the new point. currentField->shallow.far = point; // Second, we need to add the new bump to the shallow bump list for // future steep bump handling. shallowBumps.push_back(bumpT()); shallowBumps.back().location = point; shallowBumps.back().parent = currentField->shallowBump; currentField->shallowBump = & shallowBumps.back(); // Now we have too look through the list of steep bumps and see if // any of them are below the line. // If there are, we need to replace near point too. bumpT * currentBump = currentField->steepBump; while (currentBump != NULL) { if (currentField->shallow.isAbove(currentBump->location)) { currentField->shallow.near = currentBump->location; } currentBump = currentBump->parent; } } void addSteepBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps) { currentField->steep.far = point; steepBumps.push_back(bumpT()); steepBumps.back().location = point; steepBumps.back().parent = currentField->steepBump; currentField->steepBump = & steepBumps.back(); // Now look through the list of shallow bumps and see if any of them // are below the line. bumpT * currentBump = currentField->shallowBump; while (currentBump != NULL) { if (currentField->steep.isBelow(currentBump->location)) { currentField->steep.near = currentBump->location; } currentBump = currentBump->parent; } } bool actIsBlocked(fovStateT const * state, offsetT const & pos) { offsetT adjustedPos(pos.x*state->quadrant.x + state->source.x, pos.y*state->quadrant.y + state->source.y); bool result = state->isBlocked(adjustedPos.x, adjustedPos.y, state->context) == 1; if ((state->quadrant.x * state->quadrant.y == 1 && pos.x == 0 && pos.y != 0) || (state->quadrant.x * state->quadrant.y == -1 && pos.y == 0 && pos.x != 0) || doesPermissiveVisit(state->mask, pos.x*state->quadrant.x, pos.y*state->quadrant.y) == 0) { return result; } else { state->visit(adjustedPos.x, adjustedPos.y, state->context); return result; } } } void permissiveSquareFov(short sourceX, short sourceY, int inRadius, isBlockedFunction isBlocked, visitFunction visit, void * context) { int radius = max(inRadius, 0); permissiveMaskT mask; mask.north = radius; mask.south = radius; mask.east = radius; mask.west = radius; mask.width = 2*radius + 1; mask.height = 2*radius + 1; mask.mask = NULL; permissiveFov(sourceX, sourceY, &mask, isBlocked, visit, context); } void permissiveFov(short sourceX, short sourceY, permissiveMaskT * mask, isBlockedFunction isBlocked, visitFunction visit, void * context) { fovStateT state; state.source = offsetT(sourceX, sourceY); state.mask = mask; state.isBlocked = isBlocked; state.visit = visit; state.context = context; static const int quadrantCount = 4; static const offsetT quadrants[quadrantCount] = {offsetT(1, 1), offsetT(-1, 1), offsetT(-1, -1), offsetT(1, -1)}; offsetT extents[quadrantCount] = {offsetT(mask->east, mask->north), offsetT(mask->west, mask->north), offsetT(mask->west, mask->south), offsetT(mask->east, mask->south)}; int quadrantIndex = 0; for (; quadrantIndex < quadrantCount; ++quadrantIndex) { state.quadrant = quadrants[quadrantIndex]; state.extent = extents[quadrantIndex]; calculateFovQuadrant(&state); } } namespace { static const int BITS_PER_INT = sizeof(int)*8; #define GET_INT(x,y) (((x)+(y)*mask->width)/BITS_PER_INT) #define GET_BIT(x,y) (((x)+(y)*mask->width)%BITS_PER_INT) unsigned int * allocateMask(int width, int height) { int cellCount = width * height; int intCount = cellCount / BITS_PER_INT; if (cellCount % BITS_PER_INT != 0) { ++intCount; } return new unsigned int[intCount]; } } permissiveErrorT initPermissiveMask(permissiveMaskT * mask, int north, int south, int east, int west) { permissiveErrorT result = PERMISSIVE_NO_FAILURE; mask->north = max(north, 0); mask->south = max(south, 0); mask->east = max(east, 0); mask->west = max(west, 0); mask->width = mask->west + 1 + mask->east; mask->height = mask->south + 1 + mask->north; mask->mask = allocateMask(mask->width, mask->height); if (mask->mask == NULL) { result = PERMISSIVE_OUT_OF_MEMORY; } return result; } permissiveErrorT loadPermissiveMask(permissiveMaskT * mask, char const * fileName) { list<string> input; size_t maxLineSize = 1; std::ifstream file(fileName, std::ios::in); if (!file) { return PERMISSIVE_FAILED_TO_OPEN_FILE; } permissiveErrorT result = PERMISSIVE_NO_FAILURE; string line; getline(file, line); while (file) { maxLineSize = max(maxLineSize, line.size()); input.push_front(line); getline(file, line); } mask->width = static_cast<int>(maxLineSize); mask->height = static_cast<int>(input.size()); mask->mask = allocateMask(mask->width, mask->height); // TODO: Out of memory list<string>::iterator inputPos = input.begin(); unsigned int * intPos = mask->mask; int bitPos = 0; for (int i = 0; i < mask->height; ++i, ++inputPos) { for (int j = 0; j < mask->width; ++j) { char current = '#'; if (j < static_cast<int>(inputPos->size())) { current = (*inputPos)[j]; } int bit = 1; // TODO: Enforce input restrictions. switch (current) { case '#': bit = 0; break; case '!': bit = 0; // Deliberate fall-through. case '@': // Bit is already set properly. mask->south = i; mask->west = j; mask->north = mask->height - 1 - mask->south; mask->east = mask->width - 1 - mask->west; break; case '.': default: // bit is already 1 break; } if (bit == 1) { *intPos |= 0x1 << bitPos; } else { *intPos &= ~(0x1 << bitPos); } ++bitPos; if (bitPos == BITS_PER_INT) { bitPos = 0; ++intPos; } } } return result; } void cleanupPermissiveMask(permissiveMaskT * mask) { delete [] mask->mask; mask->mask = NULL; } permissiveErrorT savePermissiveMask(permissiveMaskT * mask, char const * fileName) { permissiveErrorT result = PERMISSIVE_NO_FAILURE; std::ofstream file(fileName, std::ios::out | std::ios::trunc); if (!file) { result = PERMISSIVE_FAILED_TO_OPEN_FILE; } else { for (int y = - mask->south; y <= mask->north && file; ++y) { for (int x = - mask->west; x <= mask->east && file; ++x) { if (x == 0 && y == 0) { if (doesPermissiveVisit(mask, x, y)) { file << '@'; } else { file << '!'; } } else { if (doesPermissiveVisit(mask, x, y)) { file << '.'; } else { file << '#'; } } } file << '\n'; } if (!file) { result = PERMISSIVE_SAVE_WRITE_FAILED; } } return result; } void setPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask != NULL) { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); mask->mask[index] |= 0x1 << shift; } } void clearPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask != NULL) { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); mask->mask[index] &= ~(0x1 << shift); } } int doesPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask == NULL) { return 1; } else { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); return (mask->mask[index] >> shift) & 0x1; } } <file_sep>#ifndef RLL_NEIGHBORHOODSEARCHER_HPP #define RLL_NEIGHBORHOODSEARCHER_HPP #include <vector> #include "TArea.hpp" namespace rll { template < typename T > struct Neighbor : public Point { Neighbor(const T data, const Point& p) : Point(p.x(), p.y(), p.z()), _data(data) { } Neighbor(const T data, int x, int y, int z = 0) : Point(x, y, z), _data(data) { } const T _data; bool operator == (const T& rhs) { return _data == rhs; } }; template < typename T > class NeighborhoodSearcher { public: typedef std::vector< Neighbor< T > > neighborSetT; public: NeighborhoodSearcher(const TArea< T >& field) : _field(field) { } neighborSetT FindNeumann(const Point& source); neighborSetT FindMoore(const Point& source); private: const TArea< T >& _field; }; template< typename T > typename NeighborhoodSearcher<T>::neighborSetT NeighborhoodSearcher<T>::FindNeumann(const Point& source) { neighborSetT neighbors; if(_field.borders(source.shift(-1, 0))) { neighbors.push_back( {_field.getElement(source.shift(-1, 0)), source.shift(-1, 0)} ); } if(_field.borders(source.shift( 0,-1))) { neighbors.push_back( {_field.getElement(source.shift( 0,-1)), source.shift( 0,-1)} ); } if(_field.borders(source.shift( 0, 1))) { neighbors.push_back( {_field.getElement(source.shift( 0, 1)), source.shift( 0, 1)} ); } if(_field.borders(source.shift( 1, 0))) { neighbors.push_back( {_field.getElement(source.shift( 1, 0)), source.shift( 1, 0)} ); } return neighbors; } template< typename T > typename NeighborhoodSearcher<T>::neighborSetT NeighborhoodSearcher< T >::FindMoore(const Point& source) { neighborSetT neighbors = FindNeumann(source); if(_field.borders(source.shift(-1, -1))) { neighbors.push_back( {_field.getElement(source.shift(-1, -1)), source.shift(-1, -1)} ); } if(_field.borders(source.shift(-1, 1))) { neighbors.push_back( {_field.getElement(source.shift(-1, 1)), source.shift(-1, 1)} ); } if(_field.borders(source.shift( 1, -1))) { neighbors.push_back( {_field.getElement(source.shift( 1, -1)), source.shift( 1, -1)} ); } if(_field.borders(source.shift( 1, 1))) { neighbors.push_back( {_field.getElement(source.shift( 1, 1)), source.shift( 1, 1)} ); } return neighbors; } } //rll #endif // RLL_NEIGHBORHOODSEARCHER_HPP <file_sep>#ifndef RLL_BORDERDRAFTER_HPP #define RLL_BORDERDRAFTER_HPP #include "libtcod.hpp" namespace rll { const TCODColor defaultActiveBorderColor(200,160,30); class BorderDrafter { public: BorderDrafter() : _activeBorderColor(defaultActiveBorderColor) { } void SetActiveBorderColor(TCODColor color) { _activeBorderColor = color; } void DrawActiveBorder (int startX, int endX, int startY, int endY, TCODConsole* console); void DrawPassiveBorder(TCODConsole* console); void DrawPassiveBorder(int startX, int endX, int startY, int endY, TCODConsole* console); private: TCODColor _activeBorderColor; private: static const int rightUpCorner = TCOD_CHAR_DNE; static const int leftUpCorner = TCOD_CHAR_DNW; static const int rightDownCorner = TCOD_CHAR_DSE; static const int leftDownCorner = TCOD_CHAR_DSW; static const int horizontalLine = TCOD_CHAR_DHLINE; static const int verticalLine = TCOD_CHAR_DVLINE; }; void BorderDrafter::DrawActiveBorder (int startX, int endX, int startY, int endY, TCODConsole* console) { console->setDefaultBackground(_activeBorderColor); for(int i = startX; i < endX; i++) { console->putChar(i, startY, ' ', TCOD_BKGND_SET); console->putChar(i, endY - 1, ' ', TCOD_BKGND_SET); } for(int i = startY; i < endY; i++) { console->putChar(startX, i, ' ', TCOD_BKGND_SET); console->putChar(endX - 1, i, ' ', TCOD_BKGND_SET); } } void BorderDrafter::DrawPassiveBorder(TCODConsole* console) { DrawPassiveBorder(0, console->getWidth(), 0, console->getHeight(), console); } void BorderDrafter::DrawPassiveBorder(int startX, int endX, int startY, int endY, TCODConsole* console) { console->setDefaultBackground(TCODColor::black); console->putChar(startX, startY, leftUpCorner, TCOD_BKGND_SET); console->putChar(endX - 1, startY, rightUpCorner, TCOD_BKGND_SET); console->putChar(startX, endY - 1, leftDownCorner, TCOD_BKGND_SET); console->putChar(endX - 1, endY - 1, rightDownCorner, TCOD_BKGND_SET); for(int i = startX + 1; i < endX - 1; i++) { console->putChar(i, startY, horizontalLine, TCOD_BKGND_SET); console->putChar(i, endY - 1, horizontalLine, TCOD_BKGND_SET); } for(int i = startY + 1; i < endY - 1; i++) { console->putChar(startX, i, verticalLine, TCOD_BKGND_SET); console->putChar(endX - 1, i, verticalLine, TCOD_BKGND_SET); } } } //rll #endif // RLL_BORDERDRAFTER_HPP <file_sep>#ifndef RLL_PATHSEARCHER_HPP #define RLL_PATHSEARCHER_HPP #include "libtcod.hpp" #include <vector> #include "TPoint.hpp" #include <iostream> using std::cout; using std::endl; using std::vector; namespace rll { template <typename T > class PathSearcher { public: typedef bool (*isWalkable) ( const T& cell ); public: PathSearcher(const TArea< T >& field, isWalkable func, bool diagonallyMoving, float diagonallyCost); ~PathSearcher(); vector< Point > computePath(int sx, int sy, int ex, int ey); private: const TArea< T >& _field; isWalkable f; TCODMap* map; TCODPath* aStar; }; template <typename T > PathSearcher<T>::PathSearcher(const TArea< T >& field, isWalkable func, bool diagonallyMoving = false, float diagonallyCost = 1.41) :_field(field), f(func) { map = new TCODMap(field.getXSize(), field.getYSize()); for(int y = 0; y < field.getYSize(); ++y) { for(int x = 0; x < field.getXSize(); ++x) { if(f(field.getElement(x, y))) { map->setProperties(x, y, true, true); } else { map->setProperties(x, y, true, false); } } } if(diagonallyMoving) { aStar = new TCODPath(map, diagonallyCost); } else { aStar = new TCODPath(map, 0); } } template <typename T > PathSearcher<T>::~PathSearcher() { delete aStar; delete map; } template <typename T > vector< Point > PathSearcher<T>::computePath(int sx, int sy, int ex, int ey) { vector< Point > result; aStar->compute(sx, sy, ex, ey); int xPos, yPos; int pathSize = aStar->size(); for(int i = 0; i < pathSize; i++) { aStar->get(i, &xPos, &yPos); result.push_back({xPos, yPos}); } return result; } } // rll #endif //RLL_PATHSEARCHER_HPP <file_sep>#include <iostream> #include <algorithm> #include "libtcod.hpp" #include "rll/TArea.hpp" #include "rll/PathSearcher.hpp" #include "src/roguelikelib/mapgenerators.h" using namespace std; using namespace RL; using namespace rll; const int freeCell = 0; const int wallCell = 1; const int levelXSize = 100; const int levelYSize = 75; int main() { RL::InitRandomness(); Area a(levelXSize, levelYSize, freeCell); // for(int y = 0; y < a.getYSize(); y++) { // for(int x = 0; x < a.getXSize(); x++) { // if(x==0 || x == a.getXSize()-1 || y==0 || y==a.getYSize()-1) { // a.setElement(x, y, wallCell); // } else { // int rnd = rand()%10; // a.setElement(x, y, rnd==0 ? wallCell : freeCell); // } // } // } CMap level; level.Resize(levelXSize, levelYSize); CreateAntNest(level, true); CreateCaves(level); CreateMaze(level); //CreateMines(level, 30); CreateSimpleCity(level, 5); CreateSpaceShuttle(level, 30); //CreateStandardDunegon(level, 30); for(int y = 0; y < a.getYSize(); y++) { for(int x = 0; x < a.getXSize(); x++) { if(level.GetCell(x, y) == LevelElementWall) { a.setElement(x, y, wallCell); } } } PathSearcher< int > ps(a, [](const int& w) -> bool { return w != wallCell; }); TCODConsole::root->setCustomFont("terminal.png"); TCODConsole::initRoot(a.getXSize(), a.getYSize(), "FellTon"); const TCODColor darkGroundColor(50,50,150); const TCODColor wallColor(130,110,50); const TCODColor groundColor(200,180,50); int rootX, rootY; for(int y = 0; y < a.getYSize(); y++) { for(int x = 0; x < a.getXSize(); x++) { if(a.getElement(x, y) != wallCell) { rootX = x; rootY = y; } } } int mouseX, mouseY; vector< rll::Point > path; while(!TCODConsole::isWindowClosed()) { TCOD_key_t key; TCOD_mouse_t mouse; TCODSystem::checkForEvent(TCOD_EVENT_ANY, &key, &mouse); if(key.vk != TCODK_NONE && key.pressed) { switch (key.vk) { case TCODK_LEFT : rootX--; break; case TCODK_RIGHT : rootX++; break; case TCODK_UP : rootY--; break; case TCODK_DOWN : rootY++; break; } } mouseX = mouse.cx; mouseY = mouse.cy; path = ps.computePath(rootX, rootY, mouseX, mouseY); int tile; TCODColor color; TCODColor background; for(int y = 0; y < a.getYSize(); y++) { for(int x = 0; x < a.getXSize(); x++) { switch (a.getElement(x, y)) { case freeCell : tile = '.'; color = darkGroundColor; break; case wallCell : tile = '#'; color = wallColor; break; } if(x == rootX && y == rootY) { tile = '@'; } background = TCODColor::black; if(find(path.begin(), path.end(), rll::Point(x,y)) != path.end()) { background = groundColor; } TCODConsole::root->putCharEx(x, y, tile, color, background); } } TCODConsole::flush(); } return 0; }<file_sep>#ifndef RLL_COLOR_HPP #define RLL_COLOR_HPP namespace rll { class Color { public: typedef unsigned char channelT; Color() : Color(0, 0, 0) { } Color(channelT r, channelT g, channelT b) : _r(r), _g(g), _b(b) { } channelT& r() { return _r; } channelT& g() { return _g; } channelT& b() { return _b; } private: channelT _r, _g, _b; }; } // rll #endif //RLL_COLOR_HPP <file_sep>////////////////////////////////////////////////////////////////////////// // Randomness ////////////////////////////////////////////////////////////////////////// #pragma once #ifndef RL_RANDOMNESS_H #define RL_RANDOMNESS_H #include "extern/mt19937int.h" #include <time.h> namespace RL { inline void InitRandomness(void) { init_genrand((unsigned int) time(0)); }; inline int Random(int value) { int random_value; if (value==0) return 0; random_value= (int) (((float)genrand_int32() / (float)0xFFFFFFFF)*(value)); return random_value; }; inline bool RandomLowerThatLimit(int limit, int value) { if (value==0) return false; if (Random(value)<limit) return true; return false; } inline bool CoinToss() { return Random(2)!=0; }; } #endif
7619c6b692094766cf9d32c86d11e9eee1468296
[ "C", "CMake", "C++" ]
13
C++
Hatber/Fellton
a1d248ee017056bb05ce176fb3cb7f721f67e0a2
0d56eb891d76fde066ecc1fd02508a80b4986f84
refs/heads/master
<repo_name>Ade00/Connecto_Quatro<file_sep>/connect4.py import pygame, random, colours from pygame.locals import * from colours import * pygame.init() #Constants W = 100 ROWS = 6 COLS = 7 WINDOWHEIGHT = W * ROWS WINDOWWIDTH = W * COLS CAPTION = 'Connect 4' DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) MARGIN = 0.8 GAP = W*(1-MARGIN)/2 BOXSIZE = W * MARGIN pygame.Surface.fill(DISPLAYSURF, YELLOW) def DrawRectangle(row, column, colour): pygame.draw.rect(DISPLAYSURF,colour,(W * column + GAP, W * row + GAP, BOXSIZE, BOXSIZE)) pygame.display.update() def DrawBoard(): for row in range(ROWS): for column in range(COLS): DrawRectangle(row, column, WHITE) pygame.display.update() def setup(): DrawBoard() def match_r_diag(match, grid): match = [] for row in range(ROWS): for col in range(COLS): diag_list = [] for c in range(ROWS): diag_list.append(grid[c][col]) diag_str = '' diag_str = diag_str.join(diag_list) try: row = diag_str.index(match_str) except ValueError: row = -1 if (row != -1): match.append(row) match.append(col) return tuple(match) def match_hor(match_str, grid): match = [] for row in range(ROWS): row_str = '' row_str = row_str.join(grid[row]) try: col = row_str.index(match_str) except ValueError: col = -1 if (col != -1): match.append(row) match.append(col) return tuple(match) def match_ver(match_str, grid): match = [] for col in range(COLS): col_list = [] for c in range(ROWS): col_list.append(grid[c][col]) col_str = '' col_str = col_str.join(col_list) try: row = col_str.index(match_str) except ValueError: row = -1 if (row != -1): match.append(row) match.append(col) return tuple(match) def match_all(mat, grid): move = [] for sp in range(4): match_base = [mat]*4 match_str = '' match_base[sp] = ' ' match_str = match_str.join(match_base) # Form the string to MATCH match = match_hor(match_str,grid) if match != (): move.append((match[0],match[1]+sp)) match = match_ver(match_str,grid) if match != (): move.append((match[0]+sp,match[1])) return move def playerTurn(column, grid): for row in range(ROWS): # Search the Column for the 1st SPACE if grid[row][column] == ' ': break grid[row][column] = 'P' DrawRectangle(ROWS-1-row,column, ORANGE) return grid def computerTurn(grid, IBEF_grid): plays = {} # Plays with different IBEF weights plays_all = [] # Find all available moves for column in range(COLS): # Determine available moves by for row in range (ROWS): # searching all columns for 1st SPACE if grid[row][column] == ' ': # Assemble a dictionary of moves and Weightings plays[IBEF_grid[row][column]] = (row, column) plays_all.append((row,column)) break # Can the Computer win in this turn? move = () mv = match_all('C', grid) print(mv) for m in mv: for play in range(len(plays_all)): if plays_all[play] == m: move = m if move == (): # Can the Player win in this turn? mv = match_all('P', grid) print(mv) for m in mv: for play in range(len(plays_all)): if plays_all[play] == m: move = m if move == (): # Nobody can win. IBEF = [] for play in plays: IBEF.append(play) move = plays[max(IBEF)] print(IBEF) print(plays_all) print(move) grid[move[0]][move[1]] = 'C' DrawRectangle(ROWS-1-move[0],move[1], GREEN) return grid #Game code setup() turn = 'player' # Initialise Grids grid = [] for x in range(ROWS): grid.append([' '] * COLS) IBEF_grid = [[3, 4, 5, 7, 5, 4, 3], [4, 6, 8,10, 8, 6, 4], [5, 8,11,13,11, 8, 5], [5, 8,11,13,11, 8, 5], [4, 6, 8,10, 8, 6, 4], [3, 4, 5, 7, 5, 4, 3]] #Main loop Play = True grid = computerTurn(grid, IBEF_grid) # Computer Turn while Play: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == MOUSEBUTTONUP: pos = pygame.mouse.get_pos() column = int(pos[0] / W) row = int(pos[1] / W) grid = playerTurn(column, grid) # Player Turn if (match_hor('PPPP', grid) != () or match_ver('PPPP', grid) != ()): print('PLAYER WINS !!') Play = False grid = computerTurn(grid, IBEF_grid) # Computer Turn if (match_hor('CCCC', grid) != () or match_ver('CCCC', grid) != ()): print('COMPUTER WINS !!') Play = False
15b0d2f2b7045bb2b3c58b3cb1a05c270c1e9f42
[ "Python" ]
1
Python
Ade00/Connecto_Quatro
b3ba5fe2fb862f405547c6246f1d02ac7bef99a4
805d00f0cdd42c586b40cc4dab58098195fc15f9
refs/heads/master
<repo_name>petethomas94/go-api<file_sep>/repository/repository.go package repository import ( "errors" . "go-api/types" ) var workouts = make([]Workout, 0) var exercises = make([]Exercise, 0) var programs = make([]Program, 0) var workoutSessions = make(map[int]WorkoutSession) func GetWorkout(ID int) (*Workout, error) { if len(workouts) == 0 { populateWorkouts() } for _, workout := range workouts { if workout.ID == ID { return &workout, nil } } return nil, errors.New("Workout not found") } func GetExercise(ID int) (*Exercise, error) { if len(exercises) == 0 { populateExercises() } for _, exercise := range exercises { if exercise.ID == ID { return &exercise, nil } } return nil, errors.New("Exercise not found") } func GetProgram(ID int) (*Program, error) { if len(programs) == 0 { populatePrograms() } for _, program := range programs { if program.ID == ID { return &program, nil } } return nil, errors.New("Program not found") } func SaveWorkoutSession(workoutSession *WorkoutSession) (int, error) { var ID = len(workoutSessions) + 1 workoutSessions[ID] = *workoutSession return ID, nil } func GetWorkoutSession(ID int) (*WorkoutSession, error) { workoutSession, ok := workoutSessions[ID] if ok { return &workoutSession, nil } return nil, errors.New("Workout session not found") } func populateWorkouts() { workouts = append(workouts, exampleWorkout) } func populatePrograms() { programs = append(programs, greyskull) } func populateExercises() { exercises = append(exercises, exampleExercises...) } var exampleExercises = []Exercise{ Exercise{ID: 1, Name: "Deadlift"}, Exercise{ID: 2, Name: "Squat"}, Exercise{ID: 3, Name: "Overhead Press"}, Exercise{ID: 4, Name: "Bench Press"}} var greyskull = Program{ID: 1, Name: "Greyskull", Workouts: []int{1, 2, 3, 4, 5, 6}} var exampleWorkout = Workout{ ID: 2, Exercises: []ExerciseGroup{ ExerciseGroup{ ExerciseID: 2, Sets: []Set{ Set{Amrap: false, Reps: 5}, Set{Amrap: false, Reps: 5}, Set{Amrap: true, Reps: 5}}}, ExerciseGroup{ ExerciseID: 3, Sets: []Set{ Set{Amrap: false, Reps: 5}, Set{Amrap: false, Reps: 5}, Set{Amrap: true, Reps: 5}}}, ExerciseGroup{ ExerciseID: 4, Sets: []Set{ Set{Amrap: false, Reps: 5}, Set{Amrap: false, Reps: 5}, Set{Amrap: true, Reps: 5}}}}} <file_sep>/main.go package main import ( "go-api/handlers" "net/http" "github.com/gorilla/mux" ) func main() { r := mux.NewRouter() r.Handle("/api/workout/{workoutId}", handlers.WorkoutHandler).Methods("GET") r.Handle("/api/workout", handlers.WorkoutHandler).Methods("GET") r.Handle("/api/exercise/{exerciseId}", handlers.ExerciseHandler).Methods("GET") r.Handle("/api/exercise", handlers.ExerciseHandler).Methods("GET") r.Handle("/api/program/{programId}", handlers.ProgramHandler).Methods("GET") r.Handle("/api/workoutsession", handlers.WorkoutSessionPostHandler).Methods("POST") r.Handle("/api/workoutsession/{workoutSessionId}", handlers.WorkoutSessionGetHandler).Methods("GET") http.ListenAndServe(":3000", r) } <file_sep>/handlers/handler.go package handlers import ( "encoding/json" "go-api/repository" . "go-api/types" "io/ioutil" "net/http" "strconv" "github.com/gorilla/mux" ) var WorkoutHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) if workoutID, err := strconv.Atoi(parameters["workoutId"]); err == nil { if workout, err := repository.GetWorkout(workoutID); err == nil { payload, _ := json.Marshal(workout) writeResponse(w, payload) } else { writeError(w, err) } } }) var ExerciseHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) if exerciseID, err := strconv.Atoi(parameters["exerciseId"]); err == nil { if exercise, err := repository.GetExercise(exerciseID); err == nil { payload, _ := json.Marshal(exercise) writeResponse(w, payload) } else { writeError(w, err) } } }) var ProgramHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) if programID, err := strconv.Atoi(parameters["programId"]); err == nil { if program, err := repository.GetProgram(programID); err == nil { payload, _ := json.Marshal(program) writeResponse(w, payload) } else { writeError(w, err) } } }) var WorkoutSessionGetHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { parameters := mux.Vars(r) if workoutSessionID, err := strconv.Atoi(parameters["workoutSessionId"]); err == nil { if workoutSession, err := repository.GetWorkoutSession(workoutSessionID); err == nil { payload, _ := json.Marshal(workoutSession) writeResponse(w, payload) } else { writeError(w, err) } } }) var WorkoutSessionPostHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } workoutSession := new(WorkoutSession) err = json.Unmarshal(body, workoutSession) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } repository.SaveWorkoutSession(workoutSession) w.Header().Set("Location", r.URL.Path+"/") w.WriteHeader(http.StatusCreated) }) func writeError(w http.ResponseWriter, err error) { http.Error(w, err.Error(), http.StatusNotFound) } func writeResponse(w http.ResponseWriter, payload []byte) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(payload)) } <file_sep>/types/types.go package types type Program struct { ID int Name string Workouts []int } type Workout struct { ID int Exercises []ExerciseGroup } type ExerciseGroup struct { ExerciseID int Sets []Set } type Set struct { Amrap bool Reps int } type Exercise struct { ID int Name string } type WorkoutSession struct { Workout Workout UserID int }
8d56c9e7277048b7d5be642521a37366f13f1b71
[ "Go" ]
4
Go
petethomas94/go-api
7cd53770dd470cf3da8d63b6417758dbe1cb12c8
f57e9073dfc949891b5c1785d97d991b5e6908a9
refs/heads/master
<file_sep> // ================ Estilos Iniciais ================== //Declaração de variáveis let bodY = document.body; let bwhite = document.getElementsByClassName("bwhite"); //Estilizando Var com JS bodY.style.backgroundColor = "rgb(188, 195, 246)"; //bodY.style.fontFamily = "" //Função anonima que se alto invoca e deixa fundo dos blocos brancos (function () { let i; for (i = 0; i < bwhite.length; i++) { bwhite[i].style.backgroundColor = "white"; //bwhite[i].className += " rounded"; bwhite[i].style.borderRadius = "8px"; //bwhite[i].style.padding } })(); bwhite[0].style.borderTop = "blue 12px solid"; // =============== Validações Formulário ==================== var blocoErros = document.getElementById("warning"); var listaErros = document.getElementById("warninglist"); var contadorErros = 0; function alreadyexists(id){ let i; for(i = 0; i < listaErros.childNodes.length; i++) { if(listaErros.childNodes[i].id == id) { return true; } } return false; } function inRed(campo, texto, id, preenchido) { let jaExiste = alreadyexists(id); if (preenchido == false && jaExiste == false) { contadorErros++; campo.style.border = "5px solid red"; let aviso = document.createElement("li"); aviso.id = id; aviso.innerHTML = texto; listaErros.appendChild(aviso); } if (contadorErros > 0) blocoErros.style.display = "block"; else blocoErros.style.display = "none"; } function inWhite(idLI, idBloco) { let jaExiste = alreadyexists(idLI); if(contadorErros > 0 && jaExiste == true){ let bloco = document.getElementById(idBloco); let li = document.getElementById(idLI); console.log(li); //console.log(contadorErros); listaErros.removeChild(li); bloco.style.border = "none"; contadorErros--; } if (contadorErros > 0) blocoErros.style.display = "block"; else blocoErros.style.display = "none"; } function validateName() { var nameField = document.forms["formname"]["nome"].value; if (nameField == "" || nameField == null) //(nameField.trim() !== "" && isNaN(nameField)) { inRed(document.getElementById("nomecampo"), "Campo nome não preenchido", "nomeAviso", false); return false; } else { //inRed(document.getElementById("nomecampo"), "Campo nome não preenchido", "nomeAviso", true); inWhite("nomeAviso","nomecampo"); } return true; } function validateRadios(nameRadio, campoID, texto, id) { let radio = document.getElementsByName(nameRadio); let blocoNotificado = document.getElementById(campoID); let i = 0; while (i < radio.length) { if (radio[i].checked) { inRed(blocoNotificado, texto, id, true); inWhite(id,campoID); return true; } i++; } inRed(blocoNotificado, texto, id, false); return false; } function validateForm() { let nameBool = validateName(); let ageBool = validateRadios("age", "idadecampo", "Campo Idade não preenchido", "idadeAviso"); let genBool = validateRadios("gender", "generocampo", "Campo Gênero não selecionado", "generoAviso"); let albBool = validateRadios("album", "albumcampo", "Campo Álbum do ano não selecionado", "albumAviso"); let artbool = validateRadios("art", "artistacampo", "Campo Artista do ano não selecionado", "artistaAviso"); let mscbool = validateRadios("msc", "musicacampo", "Campo Música do ano não selecionado", "musicaAviso"); let vidbool = validateRadios("video", "videocampo", "Campo Clipe do ano não selecionado", "videoAviso"); var formValid; console.log("Nome: " + nameBool + " Age: " + ageBool + " Genero: " + genBool); if (nameBool == true && ageBool == true && genBool == true && albBool == true && artbool == true && mscbool == true && vidbool == true) { return true; } else { return false; } //return formValid; } // =================== Cards configuração ================== var cards = document.getElementsByClassName("card"); var radiosAlbum = document.getElementsByName("album"); (function (){ cards[0].addEventListener("click", function(){ radiosAlbum[0].checked = true; }); cards[1].addEventListener("click", function(){ radiosAlbum[1].checked = true; }); cards[2].addEventListener("click", function(){ radiosAlbum[2].checked = true; }); cards[3].addEventListener("click", function(){ radiosAlbum[3].checked = true; }); cards[4].addEventListener("click", function(){ radiosAlbum[3].checked = true; }); })(); <file_sep>Página única de um formulário Como usar: Baixe os arquivos, abra a página "index.html" e navegue. Single page of a form How to use: Download the files, open the "index.html" page and browse.
2ff1bf18b74cf44be887e51b3a98f27539cab179
[ "JavaScript", "Markdown" ]
2
JavaScript
WKFilipeDavi/FormularioMusicAwards
4a9c61b5e37e2e2c6df209100aed477d7cdb2ae6
b91eb305bd0e3f1236efd16903cc016e67cc8f4f
refs/heads/main
<repo_name>Thmyris/goruntu-isleme<file_sep>/README.md # goruntu-isleme COMU Goruntu Isleme ders notlari <file_sep>/eski imzalar/convert.py import matplotlib.pyplot as plt import numpy as np import os from skimage.transform import resize def crop_and_return_min_mn_for_a_folder(folder_name): # for resize min_m_for_all,min_n_for_all=0,0 files=get_all_files_in_folder(folder_name) i=0 for file in files: full_file_name=folder_name+"/"+file print(file,end=" " ) print(full_file_name) try: im_rgb=plt.imread(full_file_name) im_bw=convert_rgb_to_bw(im_rgb) mbr=get_MBR_from_a_bwImage(im_bw) im_bw_cropped=crop_an_image_by_new_mn(im_bw,mbr) if(i==0): min_m_for_all,min_n_for_all=im_bw_cropped.shape else: if (min_m_for_all>im_bw_cropped.shape[0]): min_m_for_all=im_bw_cropped.shape[0] if (min_n_for_all>im_bw_cropped.shape[1]): min_n_for_all=im_bw_cropped.shape[1] new_file_name=file[0:-4] + "_cropped" + file[-4:] print("_cropped") full_file_name=new_path+"/"+new_file_name plt.imsave(full_file_name,im_bw_cropped,cmap='gray') # print(new_file_name) except: print("error in "+file) print(" finished ...") return min_m_for_all,min_n_for_all def convert_rgb_to_bw(im_rbg): try : im_rbg=im_rbg/np.max(im_rbg) m=im_rbg.shape[0] n=im_rbg.shape[1] my_new_image=np.zeros((m,n),dtype=int) for row in range(m): for column in range(n): s=im_rbg[row,column,0]/3+im_rbg[row,column,1]/3+im_rbg[row,column,2]/3 img_avg=np.mean(im_rbg) img_std=np.std(im_rgb) # diff_to_0=s-0 # diff_to_1=np.abs(1-diff_to_0) if s<img_std: my_new_image[row,column]=0 else: my_new_image[row,column]=1 return my_new_image except: print(" convert_rgb_to_bw da hata oluştu ....") def get_all_folders_in_path(path_=""): my_folders=[folder for folder in os.listdir(path_) if os.path.isdir(path_ + '/'+str(folder))] return my_folders def get_all_files_in_folder(path_=""): my_files=[file for file in os.listdir(path_) if os.path.isfile(path_ + '/'+str(file))] return my_files def get_my_files(data_folder_1): #data_folder_1=r"C:\\Users\\ikahraman\\lab_files_for_courses_synch_with_github\\data_signature\\987654321\\" files=get_all_files_in_folder(data_folder_1) return files def get_MBR_from_a_bwImage(im_bw): # for smallest biggest m m,n=im_bw.shape[0],im_bw.shape[1] smallest_m=m biggest_m=0 for i in range(m): for j in range(n): intensity=im_bw[i,j] if (intensity==0 and i<smallest_m): smallest_m=i if (intensity==0 and i>biggest_m): biggest_m=i # for smallest biggest n smallest_n=n biggest_n=0 for i in range(m): for j in range(n): intensity=im_bw[i,j] if (intensity==0 and j<smallest_n): smallest_n=j if (intensity==0 and j>biggest_n): biggest_n=j smallest_n,biggest_n smallest_m,biggest_m m1,m2,n1,n2=smallest_m,biggest_m,smallest_n,biggest_n return m1,m2,n1,n2 def crop_an_image_by_new_mn(im_bw,mbr): m1,m2,n1,n2=mbr[0],mbr[1],mbr[2],mbr[3] m,n=m2-m1,n2-n1 my_new_image=np.zeros((m,n),dtype=int) my_new_image=im_bw[m1:m2+1,n1:n2+1] return my_new_image def my_cropp_process(): data_folder_1=r"/home/thmyris/Desktop/tes/170401001" print("took address") files=get_my_files(data_folder_1) print("got files", files) for file in files: full_file_name=data_folder_1+"/"+file im_1=plt.imread(full_file_name) im_2=convert_rgb_to_bw(im_1) # (im_1.ndim,im_1.shape),(im_2.ndim,im_2.shape) mbr=get_MBR_from_a_bwImage(im_2) im_3=crop_an_image_by_new_mn(im_2,mbr) size=(200,200) im_4=resize(im_3,size) # (im_3.ndim,im_3.shape) # plt.subplot(1,3,1),plt.imshow(im_1) # plt.subplot(1,3,2),plt.imshow(im_2,cmap='gray') # plt.subplot(1,3,3),plt.imshow(im_3,cmap='gray') # plt.show() a=file #a="1234567890.png" i=len(a)-4 b=a[0:-4]+"_cropped_"+a[i:] print(a) print(b) full_file_name=data_folder_1+"/"+b full_file_name plt.imsave(full_file_name,im_4,cmap='gray') def convert_rgb_to_bw(im_rbg): im_rbg=im_rbg/np.max(im_rbg) # m,n,k=im_rbg.shape m=im_rbg.shape[0] n=im_rbg.shape[1] my_new_image=np.zeros((m,n),dtype=int) my_new_image=my_new_image+1 for row in range(m): for column in range(n): s=im_rbg[row,column,0]/3+im_rbg[row,column,1]/3+im_rbg[row,column,2]/3 diff_to_0=s-0 diff_to_1=np.abs(1-diff_to_0) if diff_to_0<diff_to_1: my_new_image[row,column]=0 else: my_new_image[row,column]=1 return my_new_image my_cropp_process()
ac2ab9b7ca873534e8bcbbd637115760f773ccff
[ "Markdown", "Python" ]
2
Markdown
Thmyris/goruntu-isleme
562745dba5a413638dbc0c6cfc724edb2b5ef3d2
ad1a529d42296cd66d6e6069bf30de69eff02419
refs/heads/main
<repo_name>Anagaret/animalerie_api<file_sep>/api/API/router/router.php <?php $path = $_SERVER["PATH_INFO"]; define("SERVER", $_SERVER["HTTP_HOST"]."/"); $uri = explode("/", $path); $entity = ucfirst($uri[1]); $controller = "App\Controller\\".$entity."Controller"; $cont = new $controller(); $rMethod = $_SERVER["REQUEST_METHOD"]; if ($rMethod === "GET") { if (isset($uri[2]) && preg_match("[\d]", $uri[2]) && !isset($uri[3])) { $cont->single($uri[2]); } elseif (!isset($uri[2])) { $cont->list(); } else { $cont->badRequestJsonResponse(); } } elseif ($rMethod === "POST") { if (isset($uri[2]) && $uri[2] === "create") { $cont->create($_POST); } else { $cont->badRequestJsonResponse("Page not found please try ".SERVER.$uri[1]."/create with method POST."); } } elseif ($rMethod === "PUT" || $rMethod === "PATCH") { if (isset($uri[2]) && preg_match("[\d]", $uri[2])) { if (isset($uri[3]) && $uri[3] === "update") { $_PUT = array(); parse_str(file_get_contents("php://input"), $_PUT); $cont->update($uri[2], $_PUT); } else { $cont->badRequestJsonResponse("Page not found please try ".SERVER.$uri[1]."/{id}/update with method PUT."); } } else { $cont->badRequestJsonResponse("$entity not found please try with another id."); } } elseif ($rMethod === "DELETE") { if (isset($uri[2]) && preg_match("[\d]", $uri[2])) { if (isset($uri[3]) && $uri[3] === "delete") { $cont->delete($uri[2]); } else { $cont->badRequestJsonResponse("Page not found please try ".SERVER .$uri[1]."/{id}/delete with method DELETE."); } } else { $cont->badRequestJsonResponse("$entity not found please try with another id."); } } <file_sep>/api/API/swagger/swagger.php <?php use OpenApi\Annotations as OA; /** * @OA\Info( * title="Api de blog du cours Api", * version="0.0.1" * ) * @OA\Server( * url="http://localhost:8000", * description="sandbox-server" * ) */<file_sep>/api/API/app/Controller/UserController.php <?php namespace App\Controller; use App\Model\UserModel; use Core\Controller\DefaultController; use Firebase\JWT\JWT; class UserController extends DefaultController{ public function __construct() { $this->model = new UserModel; } /** * List all users * @OA\Get( * path="/user", * summary="List all users", * @OA\Parameter( * name="limit", * in="query", * description="limit permettant la pagination", * required=false, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response = "200", * description="List all users", * @OA\JsonContent( * type="array", * description="User[]", * @OA\Items( * ref="#/components/schemas/User" * ), * ), * @OA\XmlContent( * type="string" * ) * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @return void */ public function list () { $this->jsonResponse($this->model->findAll()); } /** * return an user * @OA\Get( * path="/user/{id}", * summary="return an user", * @OA\Parameter( * name="id", * in="path", * description="id du user à récupérer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response ="200", * description="return an user", * @OA\JsonContent(ref="#/components/schemas/User") * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @param integer $id * @return void */ public function single ($id) { $this->jsonResponse($this->model->find($id)); } /** * Save user in DB * * @OA\Post( * path="/user/create", * summary="Create a user", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="User enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="User à enregistrer", * required=true, * @OA\JsonContent( * @OA\Property( * property="mail", * type="string", * example="<EMAIL>" * ), * @OA\Property( * property="password", * type="string", * example="<PASSWORD>" * ), * @OA\Property( * property="pseudo", * type="string", * example="monPseudo" * ), * ) * ) * ) * * @param array $data * @return void */ public function create ($data) { $save = $this->model->create($data); if ($save === true) { $this->saveJsonResponse("User bien enregistrée"); } else { $this->BadRequestJsonResponse($save); } } /** * Update user in Db * * @OA\Put( * path="/user/{id}/update", * summary="Update user", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Parameter( * name="id", * in="path", * description="id de user à mettre à jour", * required=true, * @OA\Schema(type="integer") * ), * @OA\Response( * response="200", * description="User enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Nouvelles données du user", * required=true, * @OA\JsonContent( * @OA\Property( * property="mail", * type="string", * example="<EMAIL>" * ), * @OA\Property( * property="password", * type="string", * example="<PASSWORD>" * ), * @OA\Property( * property="pseudo", * type="string", * example="monPseudo" * ), * ) * ) * ) * * @param int $id * @param array $data * @return void */ public function update (int $id, array $data) { $this->jsonResponse($this->model->update($id, $data)); } /** * Delete user in Db * @OA\Delete( * path="/user/{id}/delete", * summary="Delete user", * @OA\Parameter( * name="id", * in="path", * description="id du user à supprimer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Suppression validée", * @OA\JsonContent( * type="string", * example="User supprimé" * ) * ) * ) * * @param string $id * @return void */ public function delete (string $id) { $this->jsonResponse($this->model->delete($id)); } public function login (array $currentUser) { $user = $this->model->getUserByEmail($currentUser["email"]); if (password_verify($currentUser["password"], $user->getPassword())) { $date = new \DateTime(); $date->add(new \DateInterval('P1D')); $ts = $date->getTimestamp(); $key = "toto"; $payload = [ "id" => $user->getId(), "email" => $user->getEmail(), "pseudo" => $user->getPseudo(), "roles" => $user->getRole(), "exp" => $ts ]; $jwt = JWT::encode($payload, $key); $this->jsonResponse($jwt); } else { $this->unauthorizedResponse("Erreur identifiants"); } } } <file_sep>/createAnnonce.php <?php require_once('annonce.php'); if(isset(($_POST['nom']))){ createAnnounce( $_POST['nom'], $_POST['race'], (int) $_POST['age'], (double)$_POST['poids'], (double)$_POST['taille'], $_POST['couleur'] ); header('Location: listAnnounce.php?userId='.$_POST['creatorId']); } ?> <a href='listAnnounce.php?userId=<?php echo $_GET['userId'];?>'>Accueil</a> <h1>Créer une annonce</h1> <form method='POST' action='createAnnonce.php'> nom : <input type='text' name='nom'/> race : <input type='text' name='race'/> age : <input type='int' name='age'/> poids :<input type='double' name='poids'/> taille :<input type='double' name='taille'/> couleur :<input type='text' name='couleur'/> <input type = 'submit' value = 'Créer une annonce'> </form> <file_sep>/api/API/Core/Database.php <?php namespace Core; class Database { private $pdo; public function __construct() { $this->pdo = new \PDO("mysql:host=localhost:3306;dbname=animalerie", "root", "", [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ]); $this->pdo->exec("SET NAMES UTF8"); } public function query(string $statement, string $className ,bool $one=false) { try { $query = $this->pdo->query($statement, \PDO::FETCH_CLASS, $className); $data = null; if ($one) { $data = $query->fetch(); } else { $data = $query->fetchAll(); } return $data; } catch (\Throwable $th) { return "Une erreur s'est produite lors de la récupération des informations"; } } public function prepare(string $statement, array $data = array()) { try { $prepare = $this->pdo->prepare($statement); $prepare->execute($data); return true; } catch (\Exception $e) { return $e->getMessage(); } } }<file_sep>/README.md # animalerie_api [API] | PHP | Dans le cadre de la formation IPSSI, il nous est demandé de créer le site d'une association d'animaux. Les fichiers ont été mis dans le dossier Xampp. Pour pouvoir faire des appels à l'API, il faut donc commencer les appels par localhost/api/API/index.php/ La documentation de l'API sur Postman est https://documenter.getpostman.com/view/13594324/TzkzrfC9 <file_sep>/listAnnounce.php <?php require_once('annonce.php'); $announces = getAllAnnounces(); ?> <a href='createAnnonce.php?userId=<?php echo $_GET['userId'];?>'>Créer une annonce</a> <h1>Liste des Annonces</h1> <?php foreach ($announces as $announce) { echo '<a href= \'announceDetails.php?announceId='.$announce['id'].'&userId='.$_GET['userId'].'\'>'.$announce['titre'].'</a><br>'; } ?><file_sep>/api/API/app/Entity/User.php <?php namespace App\Entity; class User { /** * @OA\Property( * type="integer", * nullable=false, * ) * @var int */ public $id; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $pseudo; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $mail; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $password; /** * @OA\Property( * type="boolean", * nullable=false, * ) * @var boolean */ public $admin = null; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of pseudo */ public function getPseudo() { return $this->pseudo; } /** * Set the value of pseudo */ public function setPseudo($pseudo): self { $this->pseudo = $pseudo; return $this; } /** * Get the value of mail */ public function getMail() { return $this->mail; } /** * Set the value of mail */ public function setMail($mail): self { $this->mail = $mail; return $this; } /** * Get the value of password */ public function getPassword() { return $this->password; } /** * Set the value of password */ public function setPassword($password): self { $this->password = $password; return $this; } /** * Set the value of admin */ public function setAdmin($admin): self { $this->admin = $admin; return $this; } }<file_sep>/api/API/app/Controller/ProduitController.php <?php namespace App\Controller; use App\Model\ProduitModel; use Core\Controller\DefaultController; class ProduitController extends DefaultController{ public function __construct() { $this->model = new ProduitModel; } /** * List all products * @OA\Get( * path="/produit", * summary="List all products", * @OA\Parameter( * name="limit", * in="query", * description="limit permettant la pagination", * required=false, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response = "200", * description="List all products", * @OA\JsonContent( * type="array", * description="Produit[]", * @OA\Items( * ref="#/components/schemas/Produit" * ), * ), * @OA\XmlContent( * type="string" * ) * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @return void */ public function list () { $this->jsonResponse($this->model->findAll()); } /** * return a product * @OA\Get( * path="/produit/{id}", * summary="return a produiuct", * @OA\Parameter( * name="id", * in="path", * description="id du produit à récupérer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response ="200", * description="return a product", * @OA\JsonContent(ref="#/components/schemas/Produit") * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @param integer $id * @return void */ public function single (int $id) { $this->jsonResponse($this->model->find($id)); } /** * Save product in DB * * @OA\Post( * path="/produit/create", * summary="Create a product", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Produit enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Produit à enregistrer", * required=true, * @OA\JsonContent( * @OA\Property( * property="nom", * type="string", * example="<NAME>" * ), * @OA\Property( * property="cible", * type="string", * example="Chiens" * ), * @OA\Property( * property="type", * type="string", * example="Accessoires" * ), * @OA\Property( * property="prix", * type="number", * example=5.5 * ), * @OA\Property( * property="description", * type="string", * example="Collier rouge largeur 2 cm" * ), * @OA\Property( * property="image", * type="string", * example="https://www.wanimo.com/images/collier_laisse_et_harnais/A/SM/ASMS040/500x500/01/collier-basic-en-cuir-rouge-martin-sellier.jpg" * ), * ) * ) * ) * * @param array $data * @return void */ public function create ($data) { $save = $this->model->create($data); if ($save === true) { $this->saveJsonResponse("Produit bien enregistré"); } else { $this->BadRequestJsonResponse($save); } } /** * Update product in Db * * @OA\Put( * path="/produit/{id}/update", * summary="Update product", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Parameter( * name="id", * in="path", * description="id du produit à mettre à jour", * required=true, * @OA\Schema(type="integer") * ), * @OA\Response( * response="200", * description="Produit enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Nouvelles données du produit", * required=true, * @OA\JsonContent( * @OA\Property( * property="nom", * type="string", * example="<NAME>" * ), * @OA\Property( * property="cible", * type="string", * example="Chiens" * ), * @OA\Property( * property="type", * type="string", * example="Accessoire" * ), * @OA\Property( * property="prix", * type="double", * example=5.5 * ), * @OA\Property( * property="description", * type="string", * example="Collier rouge largeur 2 cm" * ), * @OA\Property( * property="image", * type="string", * example="https://www.wanimo.com/images/collier_laisse_et_harnais/A/SM/ASMS040/500x500/01/collier-basic-en-cuir-rouge-martin-sellier.jpg" * ), * ) * * ) * ) * * @param int $id * @param array $data * @return void */ public function update ($id, $data) { $this->jsonResponse($this->model->update($id, $data)); } /** * Delete product in Db * @OA\Delete( * path="/produit/{id}/delete", * summary="Delete product", * @OA\Parameter( * name="id", * in="path", * description="id du produit à supprimer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Suppression validée", * @OA\JsonContent( * type="string", * example="Produit supprimé" * ) * ) * ) * * @param string $id * @return void */ public function delete (string $id) { $this->jsonResponse($this->model->delete($id)); } }<file_sep>/api/API/app/Controller/BlogController.php <?php namespace App\Controller; use App\Model\BlogModel; use Core\Controller\DefaultController; class BlogController extends DefaultController{ public function __construct() { $this->model = new BlogModel; } /** * List all blog messages * @OA\Get( * path="/blog", * summary="List all blog messages", * @OA\Parameter( * name="limit", * in="query", * description="limit permettant la pagination", * required=false, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response = "200", * description="List all blog messages", * @OA\JsonContent( * type="array", * description="Blog[]", * @OA\Items( * ref="#/components/schemas/Blog" * ), * ), * @OA\XmlContent( * type="string" * ) * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @return void */ public function list () { $this->jsonResponse($this->model->findAll()); } /** * return a blog message * @OA\Get( * path="/blog/{id}", * summary="return a blog message", * @OA\Parameter( * name="id", * in="path", * description="id du message de blog à récupérer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response ="200", * description="return a blog message", * @OA\JsonContent(ref="#/components/schemas/Blog") * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @param integer $id * @return void */ public function single ($id) { $this->jsonResponse($this->model->find($id)); } /** * Save a blog message in DB * * @OA\Post( * path="/blog/create", * summary="Create a blog message", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Message de blog enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Message à enregistrer", * required=true, * @OA\JsonContent( * @OA\Property( * property="pseudo", * type="integer", * example=1 * ), * @OA\Property( * property="message", * type="string", * example="Voici un message" * ), * @OA\Property( * property="titre", * type="string", * example="Bonjour" * ), * ) * ) * ) * * @param array $data * @return void */ public function create ($data) { $save = $this->model->create($data); if ($save === true) { $this->saveJsonResponse("Message de blog bien enregistrée"); } else { $this->BadRequestJsonResponse($save); } } /** * Update blog in Db * * @OA\Put( * path="/blog/{id}/update", * summary="Update blog", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Parameter( * name="id", * in="path", * description="id du message de blog à mettre à jour", * required=true, * @OA\Schema(type="integer") * ), * @OA\Response( * response="200", * description="Message enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Nouvelles données du message de blog", * required=true, * @OA\JsonContent( * @OA\Property( * property="pseudo", * type="integer", * example=1 * ), * @OA\Property( * property="message", * type="string", * example="Voici un message" * ), * @OA\Property( * property="titre", * type="string", * example="Bonjour" * ), * ) * * ) * ) * * @param int $id * @param array $data * @return void */ public function update (int $id, array $data) { $this->jsonResponse($this->model->update($id, $data)); } /** * Delete blog in Db * @OA\Delete( * path="/blog/{id}/delete", * summary="Delete blog", * @OA\Parameter( * name="id", * in="path", * description="id du blog à supprimer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Suppression validée", * @OA\JsonContent( * type="string", * example="Blog message supprimé" * ) * ) * ) * * @param string $id * @return void */ public function delete (string $id) { $this->jsonResponse($this->model->delete($id)); } }<file_sep>/api/API/app/Entity/Blog.php <?php namespace App\Entity; class Blog { /** * @OA\Property( * type="integer", * nullable=false, * ) * @var int */ public $id; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $pseudo; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $titre; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $date; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $message; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of pseudo */ public function getPseudo() { return $this->pseudo; } /** * Set the value of pseudo */ public function setPseudo($pseudo): self { $this->pseudo = $pseudo; return $this; } /** * Get the value of titre */ public function getTitre() { return $this->titre; } /** * Set the value of titre */ public function setTitre($titre): self { $this->titre = $titre; return $this; } /** * Get the value of date */ public function getDate() { return $this->date; } /** * Set the value of date */ public function setDate($date): self { $this->date = $date; return $this; } /** * Get the value of message */ public function getMessage() { return $this->message; } /** * Set the value of message */ public function setMessage($message): self { $this->message = $message; return $this; } }<file_sep>/api/API/app/Controller/AnimalController.php <?php namespace App\Controller; use App\Model\AnimalModel; use Core\Controller\DefaultController; class AnimalController extends DefaultController{ public function __construct() { $this->model = new AnimalModel; } /** * List all animals * @OA\Get( * path="/animal", * summary="List all animals", * @OA\Parameter( * name="limit", * in="query", * description="limit permettant la pagination", * required=false, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response = "200", * description="List all animals", * @OA\JsonContent( * type="array", * description="Animal[]", * @OA\Items( * ref="#/components/schemas/Animal" * ), * ), * @OA\XmlContent( * type="string" * ) * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @return void */ public function list () { $this->jsonResponse($this->model->findAll()); } /** * return an animal * @OA\Get( * path="/animal/{id}", * summary="return an animal", * @OA\Parameter( * name="id", * in="path", * description="id de l'animal à récupérer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response ="200", * description="return an animal", * @OA\JsonContent(ref="#/components/schemas/Animal") * ), * @OA\Response( * response="401", * description="apiKey missing", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ), * @OA\Response( * response="500", * description="internal server error", * @OA\JsonContent( * type="string", * description="apikey manquante" * ) * ) * ) * * @param integer $id * @return void */ public function single (int $id) { $this->jsonResponse($this->model->find($id)); } /** * Save animal in DB * * @OA\Post( * path="/animal/create", * summary="Create an animal", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Animal enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Animal à enregistrer", * required=true, * @OA\JsonContent( * @OA\Property( * property="nom", * type="string", * example="Charlie" * ), * @OA\Property( * property="espece", * type="string", * example="Chiens" * ), * @OA\Property( * property="couleur", * type="string", * example="Blanc et marron" * ), * @OA\Property( * property="race", * type="string", * example="Welsh Corgi Pembroke" * ), * @OA\Property( * property="age", * type="integer", * example=2 * ), * @OA\Property( * property="taille", * type="double", * example=0.5 * ), * @OA\Property( * property="poids", * type="double", * example=10 * ), * @OA\Property( * property="sexe", * type="bit", * example=0 * ), * @OA\Property( * property="description", * type="string", * example="Très joueur" * ), * @OA\Property( * property="image", * type="string", * example="https://www.centrale-canine.fr/sites/default/files/2019-02/Big%20Woods%20Thomas%20O%27Malley%20%28Johana%20Flink%29.jpg" * ), * ) * ) * ) * * @param array $data * @return void */ public function create ($data) { $save = $this->model->create($data); if ($save === true) { $this->saveJsonResponse("Animal bien enregistré"); } else { $this->BadRequestJsonResponse($save); } } /** * Update animal in Db * * @OA\Put( * path="/animal/{id}/update", * summary="Update animal", * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Parameter( * name="id", * in="path", * description="id de l'animal à mettre à jour", * required=true, * @OA\Schema(type="integer") * ), * @OA\Response( * response="200", * description="Animal enregistré", * @OA\JsonContent( * type="string" * ) * ), * @OA\RequestBody( * description="Nouvelles données de l'animal", * required=true, * @OA\JsonContent( * @OA\Property( * property="nom", * type="string", * example="Charlie" * ), * @OA\Property( * property="espece", * type="string", * example="Chiens" * ), * @OA\Property( * property="couleur", * type="string", * example="Blanc et marron" * ), * @OA\Property( * property="race", * type="string", * example="Welsh Corgi Pembroke" * ), * @OA\Property( * property="age", * type="integer", * example=2 * ), * @OA\Property( * property="taille", * type="double", * example=0.5 * ), * @OA\Property( * property="poids", * type="double", * example=12 * ), * @OA\Property( * property="sexe", * type="bit", * example=0 * ), * @OA\Property( * property="description", * type="string", * example="Très joueur" * ), * @OA\Property( * property="image", * type="string", * example="https://www.centrale-canine.fr/sites/default/files/2019-02/Big%20Woods%20Thomas%20O%27Malley%20%28Johana%20Flink%29.jpg" * ), * ) * * ) * ) * * @param int $id * @param array $data * @return void */ public function update ($id, $data) { $this->jsonResponse($this->model->update($id, $data)); } /** * Delete animal in Db * @OA\Delete( * path="/animal/{id}/delete", * summary="Delete animal", * @OA\Parameter( * name="id", * in="path", * description="id de l'animal à supprimer", * required=true, * @OA\Schema(type="integer") * ), * @OA\Parameter( * name="apikey", * in="query", * description="apikey permettant de valider l'application", * required=true, * @OA\Schema(type="string") * ), * @OA\Response( * response="200", * description="Suppression validée", * @OA\JsonContent( * type="string", * example="Animal supprimé" * ) * ) * ) * * @param string $id * @return void */ public function delete (string $id) { $this->jsonResponse($this->model->delete($id)); } }<file_sep>/api/front/src_js/ProductsList.js import React from 'react' import Product from './Product' const ProductsList = ({ products,handleChangeAdd }) => { return( <div id="products"> {products.map(product => <Product key={product.id} title={product.title} price={product.price} description={product.description} category={product.category} image={product.image} handleChangeAdd={handleChangeAdd} /> )} </div> ) } export default ProductsList<file_sep>/api/API/app/Model/ProduitModel.php <?php namespace App\Model; use App\Entity\Produit; use Core\Database; class ProduitModel { private $className = "App\Entity\Produit"; public function __construct() { $this->db = new Database; } /** * return list of Produits * * @return Produit[] */ public function findAll() :array { $statement = "SELECT * FROM `produits`"; $test= $this->db->query($statement, $this->className); return $test; } /** * Return an Produit * * @param int $id * @return Produit */ public function find(int $id) :Produit { $statement = "SELECT * FROM produits WHERE id = $id"; return $this->db->query($statement, $this->className, true); } public function create(array $data) { $statement = "INSERT INTO produits (nom, type, cible, description, image, prix) VALUES (:nom, :type, :cible, :description, :image, :prix)"; return $this->db->prepare($statement, $data); } public function update(int $id, array $data) { $statement = "UPDATE produits SET nom = :nom, type = :type, cible = :cible, description = :description, image = :image, prix = :prix where id = $id "; return $this->db->prepare($statement, $data); } public function delete(int $id) { $statement = "DELETE FROM produits WHERE id = $id"; return $this->db->prepare($statement, array()); } }<file_sep>/api/API/app/Model/UserModel.php <?php namespace App\Model; use App\Entity\User; use Core\Database; class UserModel { private $className = "App\Entity\User"; public function __construct() { $this->db = new Database; } /** * return list of Users * * @return User[] */ public function findAll() :array { $statement = "SELECT * FROM user"; return $this->db->query($statement, $this->className); } /** * Return an User * * @param int $id * @return User */ public function find(int $id) :user { $statement = "SELECT * FROM user WHERE id = $id"; return $this->db->query($statement, $this->className, true); } public function create(array $data) { $statement = "INSERT INTO user (pseudo, mail, password) VALUES (:pseudo, :mail, :password)"; return $this->db->prepare($statement, $data); } public function update(int $id, array $data) { $statement = "UPDATE user SET pseudo = :pseudo, mail = :mail, password = :<PASSWORD> WHERE id = $id "; return $this->db->prepare($statement, $data); } public function delete(int $id) { $statement = "DELETE FROM user WHERE id = $id"; return $this->db->prepare($statement, array()); } }<file_sep>/api/API/app/Entity/Produit.php <?php namespace App\Entity; class Produit { /** * @OA\Property( * type="integer", * nullable=false, * ) * @var int */ public $id; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $nom; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $type; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $cible; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $description; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $image; /** * @OA\Property( * type="number", * nullable=false, * ) * @var double */ public $prix; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of article */ public function getNom() { return $this->nom; } /** * Set the value of article */ public function setNom($nom): self { $this->nom = $nom; return $this; } /** * Get the value of type */ public function getType() { return $this->type; } /** * Set the value of type */ public function setType($type): self { $this->type = $type; return $this; } /** * Get the value of cible */ public function getCible() { return $this->cible; } /** * Set the value of cible */ public function setCible($cible): self { $this->cible = $cible; return $this; } /** * Get the value of description */ public function getDescription() { return $this->description; } /** * Set the value of description */ public function setDescription($description): self { $this->description = $description; return $this; } /** * Get the value of image */ public function getImage() { return $this->image; } /** * Set the value of image */ public function setImage($image): self { $this->image = $image; return $this; } /** * Get the value of prix */ public function getPrix() { return $this->prix; } /** * Set the value of prix */ public function setPrix($prix): self { $this->prix = $prix; return $this; } }<file_sep>/api/API/Core/Controller/DefaultController.php <?php namespace Core\Controller; class DefaultController { public function jsonResponse ($data, $message = "Récupération ok") { header("content-type: Application/json"); header("cache-control: public, max-age=86400"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 200'); $response = [ "statusCode" => 200, "message" => $message, "data" => $data ]; echo json_encode($response); } public function saveJsonResponse($message = "Enregistrement ok") { header("content-type: Application/json"); header("cache-control: no-cache"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 201'); $response = [ "statusCode" => 201, "message" => $message ]; echo json_encode($response); } public function unauthorizedResponse($message = "Unauthorized") { header("content-type: Application/json"); header("cache-control: no-cache"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 401'); $response = [ "statusCode" => 401, "message" => $message ]; echo json_encode($response); } public function badRequestJsonResponse($message = "Page not found") { header("content-type: Application/json"); header("cache-control: no-cache"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 404'); $response = [ "statusCode" => 404, "message" => $message ]; echo json_encode($response); } public function notAllowedResponse($message = "Method not allowed") { header("content-type: Application/json"); header("cache-control: no-cache"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 405'); $response = [ "statusCode" => 405, "message" => $message ]; echo json_encode($response); } public function internalErrorResponse ($message = "Internal server error") { header("content-type: Application/json"); header("cache-control: no-cache"); header("Access-Control-Allow-Origin: *"); header('HTTP/1.0 500'); $response = [ "statusCode" => 500, "message" => $message ]; echo json_encode($response); } public function optionResponse($message) { header("content-type: Application/json"); header("cache-control: public, max-age=86400"); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: *"); header("Access-Control-Allow-Headers: *"); header("Access-Control-Allow-Credentials: true"); header('HTTP/1.1 200'); $response = [ "statusCode" => 200, "message" => $message ]; echo json_encode($response); } }<file_sep>/api/front/src_js/GetProducts.js import { useState,useEffect } from "react"; const Products = () =>{ const url = 'http://localhost/api/API/index.php/produit?apikey=<KEY>' const useFetch = (url) => { const [state,setState] = useState({ items: [], loading: true, }) useEffect(() => { if(state.loading){ (async () => { const res = await fetch(url) const data = await res.json() if (res.ok) { setState({ items: data, loading: false, }) } else { console.log(JSON.stringify(data)) setState({ items: [], loading: false, }) } })() } }) return [ state.loading, state.items, ] } return(useFetch(url)) } export default Products<file_sep>/api/API/app/Entity/Don.php <?php namespace App\Entity; class Don { /** * @OA\Property( * type="integer", * nullable=false, * ) * @var int */ public $id; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $pseudo; /** * @OA\Property( * type="number", * nullable=false, * ) * @var double */ public $montant; /** * @OA\Property( * type="string", * nullable=false, * ) * @var string */ public $date; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of pseudo */ public function getPseudo() { return $this->pseudo; } /** * Set the value of pseudo */ public function setPseudo($pseudo): self { $this->pseudo = $pseudo; return $this; } /** * Get the value of montant */ public function getMontant() { return $this->montant; } /** * Set the value of montant */ public function setMontant($montant): self { $this->montant = $montant; return $this; } /** * Get the value of date */ public function getDate() { return $this->date; } /** * Set the value of date */ public function setDate($date): self { $this->date = $date; return $this; } }<file_sep>/animalerie.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Hôte : 127.0.0.1:3306 -- Généré le : jeu. 01 juil. 2021 à 15:02 -- Version du serveur : 8.0.21 -- Version de PHP : 7.3.21 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `animalerie` -- CREATE DATABASE IF NOT EXISTS animalerie; USE animalerie; -- -------------------------------------------------------- -- -- Structure de la table `animaux` -- DROP TABLE IF EXISTS `animaux`; CREATE TABLE IF NOT EXISTS `animaux` ( `id` int NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, `espece` varchar(255) NOT NULL, `race` varchar(255) NOT NULL, `age` int UNSIGNED NOT NULL, `poids` double UNSIGNED NOT NULL, `taille` double UNSIGNED NOT NULL, `image` varchar(255) NOT NULL, `description` text NOT NULL, `couleur` varchar(255) NOT NULL, `adopted` tinyint(1) NOT NULL DEFAULT '0', `adoptionDate` timestamp NULL DEFAULT NULL, `sexe` tinyint(1) NOT NULL, `sterile` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ); -- -- Déchargement des données de la table `animaux` -- INSERT INTO `animaux` (`id`, `nom`, `espece`, `race`, `age`, `poids`, `taille`, `image`, `description`, `couleur`, `adopted`, `adoptionDate`, `sexe`, `sterile`) VALUES (1, 'Cookie', 'Chiens', 'Welsh Corgi Pembroke', 23, 10, 28, 'https://media.os.fressnapf.com/cms/2020/07/ratgeber_hund_rasse_portraits_welsh-corgi-pembroke_1200x527.jpg', 'Cookie aime la nature.', 'Roux et blanc.', 0, NULL, 1, 0), (2, 'Edgard', 'Oiseaux', 'Youyou du sénégal', 20, 120, 30, 'https://www.woopets.fr/assets/races/000/420/big-portrait/youyou-du-senegal.jpg', 'Edgard aime s\'amuser.', 'Gris, vert et jaune.', 0, NULL, 0, 0), (4, 'Felix', 'Chats', 'Sphynx', 35, 35.3, 40.5, 'https://jardinage.lemonde.fr/images/dossiers/2017-07/sphynx-1-131510.jpg', 'Felix est peureux.', 'Rose et gris', 0, NULL, 0, 0), (5, 'Jane', 'Poissons', 'Scalaire', 53, 10, 20, 'https://lemagdesanimaux.ouest-france.fr/images/dossiers/2019-08/scalaire-2-093615.jpg', 'Jane aime nager.', 'blanc, jaune et noire.', 0, NULL, 1, 0), (6, 'Coco', 'Oiseaux', 'Youyou du sénégal', 36, 36.2, 30, 'https://i.pinimg.com/236x/97/d9/b7/97d9b712d741439524357f2504d8333a--colorful-birds-exotic-birds.jpg', 'Coco aime manger des graines.', 'Gris, jaune, vert.', 0, NULL, 0, 0), (7, 'Pedro', 'Tortue', '<NAME>', 120, 20, 30, 'https://lemagdesanimaux.ouest-france.fr/images/dossiers/2019-08/tortue-hermann-1-095212.jpg', 'Pedro aime la salade.', 'Noire', 0, NULL, 0, 0), (8, 'Blanche', 'Lapin', '<NAME>', 1, 10.5, 5, 'https://static.wamiz.com/images/news/facebook/petit-lapin-nain-fb-5d248ec90f4bd.jpg', 'Blanche aime gambader dans l\'herbe.', 'Blanc', 0, NULL, 1, 0), (9, 'Écaille', 'Serpent', 'Couleuvre', 2, 10, 28.6, 'https://lemagdesanimaux.ouest-france.fr/images/dossiers/2020-01/couleuvre-073457.jpg', 'Écaille se repose souvent au soleil.', 'Vert', 0, NULL, 0, 0), (10, 'Jade', 'Lézard', '<NAME>', 6, 5, 23, 'https://www.bestioles.ca/reptiles/images/anolis-vert-2.jpg', 'Aime manger.', 'Vert.', 0, NULL, 1, 0); -- -------------------------------------------------------- -- -- Structure de la table `blog` -- DROP TABLE IF EXISTS `blog`; CREATE TABLE IF NOT EXISTS `blog` ( `id` int NOT NULL AUTO_INCREMENT, `pseudo` int NOT NULL, `titre` varchar(255) NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `message` text NOT NULL, PRIMARY KEY (`id`), KEY `fk_id_pseudo` (`pseudo`) ); -- -- Déchargement des données de la table `blog` -- INSERT INTO `blog` (`id`, `pseudo`, `titre`, `date`, `message`) VALUES (1, 1, 'Test.', '2021-06-29 14:43:54', 'Test du blog avec un message.'), (2, 2, 'Un message de bob!', '2021-06-29 14:43:54', 'Bonjour! Je suis bob un utilisateur régulier.'); -- -------------------------------------------------------- -- -- Structure de la table `dons` -- DROP TABLE IF EXISTS `dons`; CREATE TABLE IF NOT EXISTS `dons` ( `id` int NOT NULL AUTO_INCREMENT, `pseudo` int NOT NULL, `montant` float UNSIGNED NOT NULL, `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `fk_id_pseudo` (`pseudo`) ); -- -- Déchargement des données de la table `dons` -- INSERT INTO `dons` (`id`, `pseudo`, `montant`, `date`) VALUES (1, 2, 10.5, '2021-06-29 13:04:00'), (2, 2, 5, '2021-06-29 13:04:37'), (3, 1, 16.3, '2021-06-29 13:05:46'); -- -------------------------------------------------------- -- -- Structure de la table `produits` -- DROP TABLE IF EXISTS `produits`; CREATE TABLE IF NOT EXISTS `produits` ( `id` int NOT NULL AUTO_INCREMENT, `nom` varchar(255) NOT NULL, `type` varchar(255) NOT NULL, `cible` varchar(255) NOT NULL, `description` text NOT NULL, `image` varchar(255) NOT NULL, `prix` float UNSIGNED NOT NULL, PRIMARY KEY (`id`) ); -- -- Déchargement des données de la table `produits` -- INSERT INTO `produits` (`id`, `nom`, `type`, `cible`, `description`, `image`, `prix`) VALUES (1, '<NAME>', 'Alimentation', 'Chiens', 'Croquettes pour chien à l\'Agneau - 100% Viande.', 'https://static.kleps.com/3561-thickbox_default/croquettes-agneau-adulte.jpg', 10.5), (2, 'Os pour chien en caoutchouc SPOT®', 'Jouet', 'Chiens', 'Spécialement conçu pour les chiens qui aiment jouer dur, ce jouet flottant est fait de caoutchouc ultra résistant, pratiquement indestructible.', 'https://cdn.shopify.com/s/files/1/2018/3907/products/Jouet_chien_garantie_1_800x.jpg?v=1499041989', 15.95), (3, 'Nature Mix Mélange de graines', 'Alimentation', 'Oiseaux', 'Mélange de graine', 'https://www.cdiscount.com/pdt2/3/8/3/1/700x700/auc3281011002383/rw/nature-mix-melange-de-graines-pour-oiseau-de-la.jpg', 18.21), (4, 'Jouet laser interactif pour chat', 'Jouet', 'Chats', 'Le jouet laser interactif pour chat (Bolt Frolicat) PetSafeest est un jouet qui vous promet des heures d\'amusement, à vous et à votre chat.', 'https://ezoo-shop.com/wp-content/uploads/2019/05/pty17-14245-Jouet-laser-interactif-pour-chat-Bolt-Frolicat-PetSafe-4.jpg', 49), (5, 'Jouet pour oiseau avec pièces de bois et cordes', 'Jouet', 'Oiseaux', 'Jouet en bois avec cordes.', 'https://static.zoomalia.com/prod_img/22194/lm_129d1f491a404d6854880943e5c3cd9ca251403170608.jpg', 5.99), (6, 'Super vivarium', 'Vivarium', 'Reptiles', 'Petit vivarium.', 'https://serpents.info/wp-content/uploads/2018/11/t%C3%A9l%C3%A9chargement-16.jpg', 50), (7, 'Collier rouge', 'Accessoire', 'Chiens', 'Collier rouge pour chien.', 'https://shop-cdn-m.mediazs.com/bilder/collier/bobby/safe/rouge/pour/chien/5/400/104055_pla_canifrance_bobby_dog_halsband_rot_hs_01_5.jpg', 6.99), (8, 'Laisse rouge', 'Accessoire', 'Chiens', 'Une laisse rouge pour chiens.', 'https://www.wanimo.com/images/collier_laisse_et_harnais/A/7F/A7FAC01/500x500/01/laisse-club-rouge-ferplast.jpg', 6.45), (9, 'Tetra AniMin Colore Nourriture pour Poissons Rouges 250 ML', 'Alimentation', 'Poissons', 'Aliment complet en flocons pour renforcer l\'éclat des couleurs – Convient à tous les poissons rouges et d\'eau froide.', 'https://images-na.ssl-images-amazon.com/images/I/81HgtqXiIrL._AC_SY879_.jpg', 10.25), (10, 'FRISKIES Croquettes à la viande et aux légumes', 'Alimentation', 'Chats', 'Croquettes a base de viande et de légume.', 'https://www.cdiscount.com/pdt2/4/1/4/1/700x700/fri7613034180414/rw/friskies-croquettes-a-la-viande-et-aux-legumes-p.jpg', 6.99); -- -------------------------------------------------------- -- -- Structure de la table `user` -- DROP TABLE IF EXISTS `user`; CREATE TABLE IF NOT EXISTS `user` ( `id` int NOT NULL AUTO_INCREMENT, `pseudo` varchar(255) NOT NULL, `mail` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `admin` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ); -- -- Déchargement des données de la table `user` -- INSERT INTO `user` (`id`, `pseudo`, `mail`, `password`, `admin`) VALUES (1, 'admin', '<EMAIL>', 'admin', 1), (2, 'bob', '<EMAIL>', '<PASSWORD>', 0); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/api/API/app/Model/BlogModel.php <?php namespace App\Model; use Core\Database; use App\Entity\Blog; class BlogModel { private $className = "App\Entity\Blog"; public function __construct() { $this->db = new Database; } /** * return list of blog messages * * @return Blog[] */ public function findAll() :array { $statement = "SELECT * FROM blog"; return $this->db->query($statement, $this->className); } /** * Return an Blog * * @param int $id * @return Blog */ public function find(int $id) :Blog { $statement = "SELECT * FROM blog WHERE id = $id"; return $this->db->query($statement, $this->className, true); } public function create(array $data) { $statement = "INSERT INTO blog (pseudo, titre, message) VALUES (:pseudo, :titre, :message)"; return $this->db->prepare($statement, $data); } public function update(int $id, array $data) { $statement = "UPDATE blog SET pseudo = :pseudo , titre = :titre, message = :message WHERE id = $id"; return $this->db->prepare($statement, $data); } public function delete(int $id) { $statement = "DELETE FROM blog WHERE id = $id"; return $this->db->prepare($statement, array()); } }<file_sep>/api/API/vendor/composer/installed.php <?php return array( 'root' => array( 'pretty_version' => '1.0.0+no-version-set', 'version' => '1.0.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'reference' => NULL, 'name' => '__root__', 'dev' => true, ), 'versions' => array( '__root__' => array( 'pretty_version' => '1.0.0+no-version-set', 'version' => '1.0.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'reference' => NULL, 'dev_requirement' => false, ), 'doctrine/annotations' => array( 'pretty_version' => '1.13.1', 'version' => '1.13.1.0', 'type' => 'library', 'install_path' => __DIR__ . '/../doctrine/annotations', 'aliases' => array(), 'reference' => 'e6e7b7d5b45a2f2abc5460cc6396480b2b1d321f', 'dev_requirement' => false, ), 'doctrine/lexer' => array( 'pretty_version' => '1.2.1', 'version' => '1.2.1.0', 'type' => 'library', 'install_path' => __DIR__ . '/../doctrine/lexer', 'aliases' => array(), 'reference' => 'e864bbf5904cb8f5bb334f99209b48018522f042', 'dev_requirement' => false, ), 'psr/cache' => array( 'pretty_version' => '1.0.1', 'version' => '1.0.1.0', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/cache', 'aliases' => array(), 'reference' => 'd11b50ad223250cf17b86e38383413f5a6764bf8', 'dev_requirement' => false, ), 'symfony/deprecation-contracts' => array( 'pretty_version' => 'v2.4.0', 'version' => '2.4.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', 'aliases' => array(), 'reference' => '5f38c8804a9e97d23e0c8d63341088cd8a22d627', 'dev_requirement' => false, ), 'symfony/finder' => array( 'pretty_version' => 'v5.3.0', 'version' => '5.3.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/finder', 'aliases' => array(), 'reference' => '0ae3f047bed4edff6fd35b26a9a6bfdc92c953c6', 'dev_requirement' => false, ), 'symfony/polyfill-ctype' => array( 'pretty_version' => 'v1.23.0', 'version' => '1.23.0.0', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-ctype', 'aliases' => array(), 'reference' => '46cd95797e9df938fdd2b03693b5fca5e64b01ce', 'dev_requirement' => false, ), 'symfony/yaml' => array( 'pretty_version' => 'v5.3.3', 'version' => '5.3.3.0', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/yaml', 'aliases' => array(), 'reference' => '485c83a2fb5893e2ff21bf4bfc7fdf48b4967229', 'dev_requirement' => false, ), 'zircote/swagger-php' => array( 'pretty_version' => '3.2.3', 'version' => '3.2.3.0', 'type' => 'library', 'install_path' => __DIR__ . '/../zircote/swagger-php', 'aliases' => array(), 'reference' => '41ed0eb1dacebe2c365623b3f9ab13d1531a03da', 'dev_requirement' => false, ), ), ); <file_sep>/api/API/app/Model/DonModel.php <?php namespace App\Model; use Core\Database; use App\Entity\Don; class DonModel { private $className = "App\Entity\Don"; public function __construct() { $this->db = new Database; } /** * return list of dons * * @return Don[] */ public function findAll() :array { $statement = "SELECT * FROM dons"; return $this->db->query($statement, $this->className); } /** * Return an don * * @param int $id * @return Don */ public function find(int $id) :Don { $statement = "SELECT * FROM dons WHERE id = $id"; return $this->db->query($statement, $this->className, true); } public function create(array $data) { $statement = "INSERT INTO dons (pseudo, montant) VALUES (:pseudo, :montant)"; return $this->db->prepare($statement, $data); } public function update(int $id, array $data) { $statement = "UPDATE dons SET pseudo = :pseudo , montant = :montant WHERE id = $id"; return $this->db->prepare($statement, $data); } public function delete(int $id) { $statement = "DELETE FROM dons WHERE id = $id"; return $this->db->prepare($statement, array()); } }<file_sep>/api/API/index.php <?php use Core\Controller\DefaultController; use Firebase\JWT\JWT; require "vendor/autoload.php"; if (isset($_GET["apikey"]) && $_GET["apikey"] === "<KEY>") { $role = array("ROLE_USER"); if (isset($_COOKIE["jwToken"])) { $jwt = $_COOKIE["jwToken"]; $decoded = JWT::decode($jwt, "toto", array('HS256')); $role = array_merge($role, json_decode($decoded->roles)); } require "router/router.php"; } else { $controller = new DefaultController; $controller->unauthorizedResponse("Apikey manquante"); }<file_sep>/annonce.php <?php require_once('connection.php'); function getUser(String $login, String $password){ $connection = connect(); $query = $connection->prepare('SELECT id FROM user WHERE password= :password AND login = :login'); $query->execute(array('password' => $password, 'login'=> $login)); return $query->fetch(); } function createAnnounce( string $nom, string $race, int $age, double $poids, double $taille, string $couleur, boolean $is_adopted = null, string $adoption_date = false, string $image ){ if(isset($nom) && isset($race) && isset($age) && isset($poids) && isset($taille) && isset($couleur) && isset($image)){ $connection = new PDO( 'mysql:host=localhost;dbname=animalerie', 'root', '', [ PDO::ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ]); $query = $connection->prepare('INSERT INTO animaux(nom, race, age, poids, taille, couleur, is_adopted,adoption_date, image) VALUES (:nom, :race, :age, :poids, :taille, :couleur, :is_adopted, :adoption_date, :image)'); $query->execute(array( 'nom' => $nom, 'race' => $race, 'age' => $age, 'poids' => $poids, 'taille' => $taille, 'couleur' => $couleur, 'is_adopted' => $is_adopted, 'adoption_date' => $adoption_date, 'image' => $image)); $query->closeCursor(); } } function getAllAnnounces(){ $connection = new PDO( 'mysql:host=localhost;dbname=animalerie', 'root', '', [ PDO::ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ]); $query = $connection->prepare('SELECT * FROM animaux'); $query->execute(); return $query->fetchAll(PDO::FETCH_ASSOC); } function getAnnounce(int $unique_id){ $connection = new PDO( 'mysql:host=localhost;dbname=animalerie', 'root', '', [ PDO::ATTR_ERRMODE => PDO:: ERRMODE_EXCEPTION ]); $query = $connection->prepare('SELECT * FROM animaux WHERE unique_id = :unique_id'); $query->execute(array('unique_id' => $unique_id)); return $query->fetch(); }<file_sep>/api/API/app/Entity/Animal.php <?php namespace App\Entity; class Animal { /** * @OA\Property( * type="integer", * nullable=false, * ) * @var int */ public $id; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $nom; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $espece; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $race; /** * @OA\Property( * type="integer", * nullable=false * ) * @var int */ public $age; /** * @OA\Property( * type="number", * nullable=false * ) * @var number */ public $poids; /** * @OA\Property( * type="number", * nullable=false * ) * @var number */ public $taille; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $image; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $description; /** * @OA\Property( * type="string", * nullable=false * ) * @var string */ public $couleur; /** * @OA\Property( * type="boolean", * nullable=false * ) * @var boolean */ public $adopted ; /** * @OA\Property( * type="date", * nullable=false * ) * @var date */ public $adoptionDate ; /** * @OA\Property( * type="boolean", * nullable=true * ) * @var boolean */ public $sexe; /** * @OA\Property( * type="boolean", * nullable=false * ) * @var boolean */ public $sterile; /** * Get the value of id */ public function getId() { return $this->id; } /** * Get the value of nom */ public function getNom() { return $this->nom; } /** * Set the value of nom */ public function setNom($nom): self { $this->nom = $nom; return $this; } /** * Get the value of description */ public function getDescription() { return $this->description; } /** * Set the value of description */ public function setDescription($description): self { $this->description = $description; return $this; } /** * Get the value of espece */ public function getEspece() { return $this->espece; } /** * Set the value of espece */ public function setEspece($espece): self { $this->espece = $espece; return $this; } /** * Get the value of race */ public function getRace() { return $this->race; } /** * Set the value of race */ public function setRace($race): self { $this->race = $race; return $this; } /** * Get the value of age */ public function getAge() { return $this->age; } /** * Set the value of age */ public function setAge($age): self { $this->age = $age; return $this; } /** * Get the value of poids */ public function getPoids() { return $this->poids; } /** * Set the value of poids */ public function setPoids($poids): self { $this->poids = $poids; return $this; } /** * Get the value of taille */ public function getTaille() { return $this->taille; } /** * Set the value of taille */ public function setTaille($taille): self { $this->taille = $taille; return $this; } /** * Get the value of couleur */ public function getCouleur() { return $this->couleur; } /** * Set the value of couleur */ public function setCouleur($couleur): self { $this->couleur = $couleur; return $this; } /** * Get the value of adopted */ public function getIsAdopted() { return $this->adopted; } /** * Set the value of is_adopted */ public function setIsAdopted($adopted): self { $this->adopted = $adopted; return $this; } /** * Get the value of adoptionDate */ public function getAdoptionDate() { return $this->adoptionDate; } /** * Set the value of adoptionDate */ public function setAdoptionDate($adoptionDate): self { $this->adoptionDate = $adoptionDate; return $this; } /** * Get the value of image */ public function getImage() { return $this->image; } /** * Set the value of image */ public function setImage($image): self { $this->image = $image; return $this; } /** * Get the value of sexe */ public function getSexe() { return $this->sexe; } /** * Set the value of sexe */ public function setSexe($sexe): self { $this->sexe = $sexe; return $this; } /** * Get the value of sterile */ public function getSterile() { return $this->sterile; } /** * Set the value of sterile */ public function setSterile($sterile): self { $this->sterile = $sterile; return $this; } }<file_sep>/api/API/app/Model/AnimalModel.php <?php namespace App\Model; use App\Entity\Animal; use Core\Database; class AnimalModel { private $className = "App\Entity\Animal"; public function __construct() { $this->db = new Database; } /** * return list of Animals * * @return Animal[] */ public function findAll() :array { $statement = "SELECT * FROM animaux"; $test = $this->db->query($statement, $this->className); return $test; } /** * Return an Animal * * @param int $id * @return Animal */ public function find(int $id) :Animal { $statement = "SELECT * FROM animaux WHERE id = $id"; return $this->db->query($statement, $this->className, true); } public function create(array $data) { $statement = "INSERT INTO animaux (nom, espece, race, age, poids, taille, image, description, couleur, sexe) VALUES (:nom, :espece, :race, :age, :poids, :taille, :image, :description , :couleur, :sexe)"; return $this->db->prepare($statement, $data); } public function update(int $id, array $data) { $statement = "UPDATE animaux SET nom = :nom, espece = :espece, race = :race, age = :age, poids = :poids, taille = :taille, image = :image, description = :description, couleur = :couleur, sexe = :sexe where id = $id "; return $this->db->prepare($statement, $data); } public function delete(int $id) { $statement = "DELETE FROM animaux WHERE id = $id"; return $this->db->prepare($statement, array()); } }
1f27eff85db14a46b37e8f9554552a8f8472e7af
[ "Markdown", "SQL", "JavaScript", "PHP" ]
27
PHP
Anagaret/animalerie_api
8d5ce387fd49ec818b26fe9c2bdf258105501811
05f0576b7e3104d267512ef685b4c422decf3f16
refs/heads/master
<repo_name>gopicci/locallibrary<file_sep>/locallibrary-app/requirements.txt Django==3.0.6 gunicorn==20.0.4 psycopg2-binary==2.8.5<file_sep>/docker-compose.yml version: '3' services: web: build: ./locallibrary-app command: python manage.py runserver 0.0.0.0:8000 volumes: - ./locallibrary-app/:/usr/src/locallibrary/ ports: - 80:8000 env_file: - ./.env.dev <file_sep>/locallibrary-app/catalog/urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name='index'), # name is for reverse url mapping, ie <a href="{% url 'index' %}">Home</a>, more robust than direct linking in case of updates path('books/', views.BookListView.as_view(), name='books'), # calling view as class instead, less code, need to call .as_view() path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), # re_path(r'^book/(?P<pk>\d+)$', views.BookDetailView.as_view(), name='book-detail'), # could also use regular expressions. ?P returns strings # path('url/', views.my_reused_view, {'my_template_name': 'some_path'}, name='aurl'), # these to pas additional options as third unnamed arg, useful ie to use same view for multiple resources # path('anotherurl/', views.my_reused_view, {'my_template_name': 'another_path'}, name='anotherurl'), # don't use same var names as name path('authors/', views.AuthorListView.as_view(), name='authors'), re_path(r'^author/(?P<pk>\d+)$', views.AuthorDetailView.as_view(), name='author-detail'), path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'), path('borrowed/', views.LoanedBooksListView.as_view(), name='all-borrowed'), path('book/<uuid:pk>/renew/', views.renew_book_librarian, name='renew-book-librarian'), path('author/create/', views.AuthorCreate.as_view(), name='author_create'), path('author/<int:pk>/update/', views.AuthorUpdate.as_view(), name='author_update'), path('author/<int:pk>/delete/', views.AuthorDelete.as_view(), name='author_delete'), ]
dd55ae2681a49491a184634ccf350cda03ea7326
[ "Python", "Text", "YAML" ]
3
Text
gopicci/locallibrary
af8cd088488698e83cbf377f15a310b69e305efa
a719b6708c98feffb5ece9ae4b2950e92745717a
refs/heads/master
<repo_name>miriamfrank23/js-looping-and-iteration-filter-lab-nyc-web-082718<file_sep>/index.js function findMatching (drivers, name) { return drivers.filter(function (driver) { return driver.toLowerCase() === name.toLowerCase(); }); } function fuzzyMatch (drivers, name) { let length = name.length; return drivers.filter(function (driver) { return driver.slice(0, length) === name; }); } function matchName (drivers, name) { return drivers.filter(function (driver) { return driver.name.toLowerCase() === name.toLowerCase(); }); }
5a496a864345b97a84f97467fb6fb0572cda8a8e
[ "JavaScript" ]
1
JavaScript
miriamfrank23/js-looping-and-iteration-filter-lab-nyc-web-082718
566d39ff991f578b331878918ded9d017ada57aa
87a0083763fedd0ebf7684ab1d120909d45770dd
refs/heads/master
<file_sep>## Functions to calcualate the inverse of the matrix and cache the value. ## This avoids repeatedly running the matrix inversion because this ## is a costly computation. ## Returns a list of functions that the cacheSolve will use. makeCacheMatrix <- function(x = matrix()) { #sets m to null every time it's run m <- NULL #get function returns value of x get <- function() x #called by cachesolve, stores value using superassignment setinverse <- function(inverse) { m <<- inverse } # returns cached value of m to cacheSolve getinverse <- function() {m} # lists all functions list(get = get, setinverse = setinverse, getinverse = getinverse) } ## Function that returns the inverse of the matrix; inverse ## is calculated if not cached, or cached matrix is returned if alredy ## cached cacheSolve <- function(x, ...) { #Accesses the value of x from object m <- x$getinverse() #if already cached, returns cached object if(!is.null(m)) { message("getting cached data") return(m) } # if not cached, gets data data <- x$get() #inverts the matrix m <- solve(data, ...) #stores inverted matrix in cache x$setinverse(m) #returns inverted matrix m }
27ee76fb767772100d94bc3c83921da0a9b34fee
[ "R" ]
1
R
seanasdf/ProgrammingAssignment2
2c37b98df1b1c3edaf922c9011e77511278fa206
1ad8563cedfd73a8f155f0acd0f5698a3dac08e8
refs/heads/master
<file_sep># HackerRank-30-days-of-Code HackerRank 30 days Challenge to brush up coding skills Here You will get all solutions of HackerRank 30 days of Code <file_sep>''' Day 9: Recursion 3 Objective Today, we’re learning and practicing an algorithmic concept called Recursion. Check out the Tutorial tab for learning materials and an instructional video! Recursive Method for Calculating Factorial Task Write a factorial function that takes a positive integer, as a parameter and prints the result of ( factorial). Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of . Input Format A single integer, (the argument to pass to factorial). Constraints Your submission must contain a recursive function named factorial. Output Format Print a single integer denoting . Sample Input 3 Sample Output 6 ''' # Answer import math import os import random import re import sys def factorial(n): if n==0: return 1 else: return n * factorial(n-1) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) result = factorial(n) fptr.write(str(result) + '\n') fptr.close() <file_sep>''' Day 6: Let's Review Objective Today we’re expanding our knowledge of Strings and combining it with what we’ve already learned about loops. Check out the Tutorial tab for learning materials and an instructional video! Task Given a string, S, of length that is indexed from 0 to N-1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail). Note: 0 is considered to be an even index. Input Format The first line contains an integer, T (the number of test cases). Each line i of the T subsequent lines contain a String, S. Constraints 1<=T<=10 2<=length of S<=10000 Output Format For each String Sj (where 0<=j<=T-1 ), print Sj‘s even-indexed characters, followed by a space, followed by Sj‘s odd-indexed characters. Sample Input 2 Hacker Rank Sample Output Hce akr Rn ak ''' # Solution a=int(input()) for i in range(a): s=input() print(s[0::2]+' '+s[1::2]) <file_sep>''' Objective Today, we’re learning about Key-Value pair mappings using a Map or Dictionary data structure. Check out the Tutorial tab for learning materials and an instructional video! Task Given n names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not Found instead. Note: Your phone book should be a Dictionary/Map/HashMap data structure. Input Format The first line contains an integer, n, denoting the number of entries in the phone book. Each of the n subsequent lines describes an entry in the form of 2 space-separated values on a single line. The first value is a friend’s name, and the second value is an 8-digit phone number. After the n lines of phonebook entries, there are an unknown number of lines of queries. Each line (query) contains a name to look up, and you must continue reading lines until there is no more input. Note: Names consist of lowercase English alphabetic letters and are first names only. Constraints 1<= n <=10000 1<= queries <=10000 Output Format On a new line for each query, print Not Found if the name has no corresponding entry in the phone book; otherwise, print the full name and phone number in the format name=phoneNumber. Sample Input 3 sam 99912222 tom 11122222 harry 12299933 sam edward harry Sample Output sam=99912222 Not found harry=12299933 ''' # Answer n=int(input()) d={} for i in range(n): name,contact=map(str,input().split()) name=name.lower() d[name]=contact try: while(True): query=input().lower() if query in d: print(query+"="+d[query]) else: print('Not found') except(EOFError): pass <file_sep>''' #Day 3: Intro to Conditional Statements Objective In this challenge, we're getting started with conditional statements. Check out the Tutorial tab for learning materials and an instructional video! Task Given an integer, n , perform the following conditional actions: If n is odd, print Weird. If n is even and in the inclusive range of 2 to 5 , print Not Weird. If n is even and in the inclusive range of 6 to 20 , print Weird. If n is even and greater than 20 , print Not Weird. Complete the stub code provided in your editor to print whether or not n is weird. Input Format A single line containing a positive integer, n . Constraints 1 <= n <= 100 Output Format Print Weird if the number is weird; otherwise, print Not Weird. Sample Input 0 3 Sample Output 0 Weird Sample Input 1 24 Sample Output 1 Not Weird Explanation Sample Case 0: n = 3 n is odd and odd numbers are weird, so we print Weird. Sample Case 1: n = 24 n > 20 and n is even, so it isn't weird. Thus, we print Not Weird. ''' if __name__ == '__main__': N = int(input()) if N%2 != 0: print('Weird') else: if N%2==0: if N>=2 and N<=5: print('Not Weird') elif N>=6 and N<=20: print('Weird') elif N>20: print('Not Weird') <file_sep>''' Objective In this challenge, we’re going to use loops to help us do some simple math. Check out the Tutorial tab to learn more. Task Given an integer, n, print its first 10 multiples. Each multiple n*I (where 1<=i<=10 ) should be printed on a new line in the form: n x i = result. Input Format A single integer, n. Constraints 2<=n <=20 Output Format Print 10 lines of output; each line i (where 1<=i<=10 ) contains the result of n*i in the form: n x i = result. Sample Input 2 Sample Output 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10 2 x 6 = 12 2 x 7 = 14 2 x 8 = 16 2 x 9 = 18 2 x 10 = 20 ''' # Solution if __name__ == '__main__': n = int(input()) count=0 for i in range(1,11): count=i*n print(str(n) +' x '+ str(i) +" = "+ str(count)) <file_sep>''' Day 0: Hello, World. Objective In this challenge, we review some basic concepts that will get you started with this series. You will need to use the same (or similar) syntax to read input and write output in challenges throughout HackerRank. Check out the Tutorial tab for learning materials and an instructional video! Task To complete this challenge, you must save a line of input from stdin to a variable, print Hello, World. on a single line, and finally print the value of your variable on a second line. Input Format A single line of text denoting inputString (the variable whose contents must be printed). Output Format Print Hello, World. on the first line, and the contents of inputString on the second line. Sample Input Welcome to 30 Days of Code! Sample Output Hello, World. Welcome to 30 Days of Code! Explanation On the first line, we print the string literal Hello, World.. On the second line, we print the contents of the variable inputString which, for this sample case, happens to be Welcome to 30 Days of Code!. If you do not print the variable's contents to stdout, you will not pass the hidden test case. ''' #Solution # Read a full line of input from stdin and save it to our dynamically typed variable, input_string. input_string = input() # Print a string literal saying "Hello, World." to stdout. print('Hello, World.') print('Welcome to 30 Days of Code!') <file_sep>''' Day 4: Class vs. Instance Problem Objective In this challenge, we're going to learn about the difference between a class and an instance; because this is an Object Oriented concept, it's only enabled in certain languages. Check out the Tutorial tab for learning materials and an instructional video! Task Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter The constructor must assign initialAge argument to age after confirming the argument passed as initialAge is not negative if a negative is passed as initial Age,the constructor should set age to 0 and print Age is not valid, setting age to 0 and print Age is not valid, setting age to 0..In addition,you must write the following instance methods: 1. yearPasses() should increase the age instance variable by 1. 2. amIOld() should perform the following conditional actions: If age < 13 print You are young.. If age > 13 and age < 18, print You are a teenager.. Otherwise, print You are old.. To help you learn by example and complete this challenge, much of the code is provided for you, but you'll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don't worry if you don't understand it all quite yet! Note: Do not remove or alter the stub code in the editor Input Format Input is handled for you by the stub code in the editor.. The first line contains an integer, T (the number of test cases), and the T subsequent lines each contain an integer denoting the age of a Person instance. Constraints • 1<= T < =4 • -5 <=age<=30 Output Format Complete the method definitions provided in the editor so they meet the specifications outlined above, the code to test your editor. If your methods are implemented correctly, each test case will print 2 or 3 lines (depending on whether or not a valid initialAge was passed to the constructor). Sample Input 4 -1 10 16 18 Sample Output Age is not valid, setting age to 0. You are young. You are young. You are young. You are a teenager. You are a teenager. You are old. You are old. You are old. Explanation Test Case 0: initialAge =-1 Because initialAge<0, our code must set to and print the "Age is not valid..." message followed by the young message. Three years pass and age=3, so we print the young message again. Test Case 1: initialAge= 10 Because ,initialAge<13 our code should print that the person is young. Three years pass and age =13 , so we print that the person is now a teenager. Test Case 2: initialAge= 16 Because , 13<=initialAge<18our code should print that the person is a teenager. Three years pass and age=19, so we print that the person is old. Test Case 3: initialAge= 18 Because initialAge>=18, our code should print that the person is old. Three years pass and age=21 the person is still old at , so we print the old message again. The extra line at the end of the output is supposed to be there and is trimmed before being compared against the test case's expected output. If you're failing this challenge, check your logic and review your print statements for spelling errors. ''' class Person: def __init__(self,initialAge): # Add some more code to run some checks on initialAge self.age=0 if initialAge<0: print('Age is not valid, setting age to 0.') else: self.age=initialAge def amIOld(self): # Do some computations in here and print out the correct statement to the console if age<13: print('You are young.') elif age>=13 and age<18: print('You are a teenager.') else: print('You are old.') def yearPasses(self): # Increment the age of the person in here global age age+=1 t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")<file_sep>''' Day 1: Data Types Objective Today, we're discussing data types. Check out the Tutorial tab for learning materials and an instructional video! Task Complete the code in the editor below. The variables i, d, and s are already declared and initialized for you. You must: Declare variables: one of type int, one of type double, and one of type String. Read 3 lines of input from stdin (according to the sequence given in the Input Format section below) and initialize your 3 variables. Use the + operator to perform the following operations: Print the sum of plus your int variable on a new line. Print the sum of plus your double variable to a scale of one decimal place on a new line. Concatenate with the string you read as input and print the result on a new line. Note: If you are using a language that doesn't support using + for string concatenation (e.g.: C), you can just print one variable immediately following the other on the same line. The string provided in your editor must be printed first, immediately followed by the string you read as input. Input Format The first line contains an integer, i. The second line contains a double, d. The third line contains a string, s. Output Format Print the sum of both integers on the first line, the sum of both doubles (scaled to 1 decimal place) on the second line, and then the two concatenated strings on the third line. Sample Input 12 4.0 is the best place to learn and practice coding! Sample Output 16 8.0 HackerRank is the best place to learn and practice coding! Explanation When we sum the integers 4 and 12, we get the integer 16. When we sum the floating point numbers 4.0 and 4.0, we get 8.0. When we concatenate HackerRank with is the best place to learn and practice coding!, we get HackerRank is the best place to learn and practice coding!. You will not pass this challenge if you attempt to assign the Sample Case values to your variables instead of following the instructions above and reading input from stdin. ''' i = 4 d = 4.0 s = 'HackerRank ' # Declare second integer, double, and String variables. i2 = int(input()) d2 = float(input()) s2 = input() # Read and save an integer, double, and String to your variables. # Print the sum of both integer variables on a new line. print (i + i2) # Print the sum of the double variables on a new line. print (d + d2) # Concatenate and print the String variables on a new line # The 's' variable above should be printed first. print (s+s2) <file_sep>''' Day 7: Arrays Task Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers. Input Format The first line contains an integer, N (the size of our array). The second line contains N space-separated integers describing array A's elements. Constraints 1 <= N <= 1000 1 <= Ai <= 10000, where Ai is the ith integer in the array Output Format Print the elements of array A in reverse order as a single line of space-separated numbers. ''' if __name__ == '__main__': n = int(input()) arr = list(map(int, input().rstrip().split())) print(' '.join([str(i) for i in reversed(arr)]))
fca603f3ce68cc1da8597529507b41300b8dd0f4
[ "Markdown", "Python" ]
10
Markdown
kkapoor1394/HackerRank-30-days-of-Code
1e170e8acdfaafafda9499d4bb4995631c901cf2
9a2e4e93673b3ad6f4d0da4686e050a715e1cc0b
refs/heads/master
<repo_name>yellow-beard/deleter<file_sep>/models/image.php <?php require_once '../s3/sdk.class.php'; class Image { public $url; public $id; public $s3_id; function __construct($id, $s3_id, $url) { $this->id = $id; $this->s3_id = $s3_id; $this->url = $url; } public static function find_by_url($url) { $sql = "SELECT * FROM images WHERE url = '" . mysql_real_escape_string($url) . "'"; $res = get_res($sql); $data = mysql_fetch_assoc($res); if ($data) { return new Image($data['id'], $data['s3_id'], $data['url']); } else { return false; } } public static function find_or_create_by_url($url) { $i = Image::find_by_url($url); if ($i === false) { return Image::create_by_url($url); } return $i; } public static function create_by_url($url) { $sql = "INSERT INTO images (url) VALUES ('".mysql_real_escape_string($url)."')"; get_res($sql); $i = Image::find_by_url($url); $i->cross_out(); $i->save_s3(); return $i; } function cross_out() { $fh = fopen($this->url, "r"); $imagick = new Imagick(); $imagick->readImageFile($fh); $geometry = $imagick->getImageGeometry(); $x = $geometry['width']; $y = $geometry['height']; $max_side = max($x, $y); $min_side = min($x,$y); $cross_count = floor($max_side/$min_side); $draw = new ImagickDraw(); $draw->setStrokeColor(new ImagickPixel('#010101')); // black fixes stroke width to 1????? $line_width = ceil($min_side/30); $draw->setStrokeWidth($line_width); $gap = 0; $stroke_var = $max_side/$cross_count; if ($cross_count > 1) { $gap = $line_width*3; $stroke_var -= $gap; } for ($i=0; $i<=$cross_count; $i++) { if ($max_side == $x) { $draw->line($i*($stroke_var+$gap), 0, (($i+1)*$stroke_var)+($i*$gap), $y); // the \ strokes $draw->line((($i+1)*$stroke_var)+($i*$gap), 0, $i*($stroke_var+$gap), $y); // the / strokes } else { $draw->line(0, $i*($stroke_var+$gap), $x, (($i+1)*$stroke_var)+($i*$gap)); // the \ strokes $draw->line($x, $i*($stroke_var+$gap), 0, (($i+1)*$stroke_var)+($i*$gap)); // the / strokes } } $imagick->drawImage($draw); $this->imagick = $imagick; } function save_s3() { $this->save(); $this->imagick->writeImage('../public/images/'.$this->id); $s3 = new AmazonS3(); $s3->create_object(S3_BUCKET, $this->id, array( 'fileUpload' => '../public/images/'.$this->id, 'acl' => $s3::ACL_PUBLIC )); unlink('../public/images/'.$this->id); } function s3_url() { return 'http://s3.amazonaws.com/'.S3_BUCKET.'/'.$this->id; } function save() { } } <file_sep>/public/index.php <?php if($_SERVER['HTTP_HOST'] == 'cag.deletedmuseums.org') { header( 'Location: http://cag.deletedmuseums.org/page.php?u=http%3A%2F%2Fchristchurchartgallery.org.nz%2F'); } ?> <form action='/site.php' method='get' > Hello, enter a url to delete <input type='text' name='u' /> <input type='submit' /> </form> <br /><br /> Or have a look at <a href='page.php?u=http%3A%2F%2Fchristchurchartgallery.org.nz%2F'>Christchurch Art Gallery</a> <file_sep>/public/site_update.php <? require_once('../includes/includes.php'); $site = Site::find_by_id($_POST['site_id']); $site->css = $_POST['css']; $site->save(); header( 'Location: http://'.$_SERVER['SERVER_NAME'].'/site.php?u='.urlencode($site->url) ) ; ?> <file_sep>/readme.md setup: 1. `cp includes/config.php.default includes/config.php` open up includes/config.php and set up your s3 bucket and database. you'll need to create the bucket via the web interface or something like that. 2. `cp s3/config.inc.php.default s3/config.inc.php` and edit it to include your s3 key and secret. 3. fire up mysql. create your database. use it. source migration.sql to create the tables. load image_test.php for a tiny test. then try out the site :) requires php's curl lib web server must be able to write to public/images very slow... single process serial download, altering and upload of images :) :) :) <file_sep>/models/page.php <?php $page_base_url = ""; $page_url_path = ""; class Page { public $url; public $base_url; public $html; public $site; public $path; function __construct($url) { $this->url = $url; $ar = parse_url($url); $this->base_url = $ar['scheme'] . "://" . $ar['host']; $this->path = str_replace($this->base_url, "", $url); $this->site = Site::find_by_url($this->base_url); } function scrape() { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->base_url. $this->path); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $this->html = curl_exec($ch); curl_close($ch); } function display() { $this->scrape(); $this->apply_filters(); return $this->html; } function apply_filters() { $this->rewrite_css(); $this->rewrite_links(); $this->rewrite_js(); $this->rewrite_images(); $this->rewrite_forms(); $this->rewrite_mp3(); $this->add_css(); } function gather_css() { } function strip_css() { } function rewrite_js() { $this->html = preg_replace('/(<script.*?type="text\/javascript".*?src=(\'|"))(\/.*?)(\'|")/', "$1".$this->base_url."$3$4", $this->html); } function rewrite_mp3() { $this->html = preg_replace('/src="\/(.*?\.mp3")/', "src=\"".$this->base_url."/$1", $this->html); $this->html = str_replace('http://christchurchartgallery.org.nz/media/uploads/2011_09/Rita_Angus_-_Cass_High_Qual.mp3', 'https://s3.amazonaws.com/website_remixer_custom/Rita_Angus_-_Cass_High_Qual+edited.mp3', $this->html); } function rewrite_css() { $this->html = preg_replace('/(<link.*?rel="stylesheet".*?href=(\'|"))(.*?)(\'|")/', "$1".$this->base_url."$3$4", $this->html); } function rewrite_links() { //$this->html = '<a href="/search/" class="advanced">&rarr; Advanced Search</a>'; $GLOBALS['page_base_url'] = $this->base_url; $this->html = preg_replace_callback('/(<a.*?href=(\'|"))(.*?)(\'|")/', "rlcf", $this->html); } function rewrite_images() { // $this->html = '<img src="/media/cache/65/98/6598cb5dd8a078ffc28b076f126533a3.jpg" alt="The Christchurch Art Gallery Collection" width="880" height="300">'; $GLOBALS['page_base_url'] = $this->base_url; $this->html = preg_replace_callback('/(<img.*?src=(\'|"))(.*?)(\'|")/', "rlcf", $this->html); $this->html = preg_replace_callback('/poster="\/(.*?\.jpg)"/', "rlcf_poster", $this->html); $this->html = preg_replace_callback('/data-hover_src="\/(.*?\.jpg)"/', "rlcf_data_hover_src", $this->html); } function rewrite_forms() { $GLOBALS['page_base_url'] = $this->base_url; $GLOBALS['page_url_path'] = $this->path; $this->html = preg_replace_callback('/(<form.*?action=(\'|"))(.*?)(\'|")(.*?>)/', "rclf_form", $this->html); } function add_css() { $extra = " <style type=\"text/css\"> body > *{visibility:inherit} html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td, a, a.current, a:visited, a:link, header nav.side a, #crumbtrail p, #crumbtrail > a, #crumbtrail > span, input, nav.bold a, .toprow a, .toprow label, .toprow input.go { text-decoration: line-through; } body { background: url('https://s3.amazonaws.com/website_remixer_custom/crosses.png'); } #headerwrap header .title a { background-image: url('http://remixer.leecunliffe.com/page.php?u=http%3A%2F%2Fchristchurchartgallery.org.nz%2Fmedia%2Fi%2Fheader.png'); } </style>\n "; $this->html = str_replace("</head>", $extra."</head>", $this->html); } } function rlcf($matches) { if (substr($matches[3],0, 4) == "http") { return $matches[1]."http://".$_SERVER['SERVER_NAME']."/page.php?u=".urlencode($matches[3]).$matches[4]; } else { return $matches[1]."http://".$_SERVER['SERVER_NAME']."/page.php?u=".urlencode($GLOBALS['page_base_url'].$matches[3]).$matches[4]; } } function rlcf_poster($matches) { return "poster=\"http://".$_SERVER['SERVER_NAME']."/page.php?u=".urlencode($GLOBALS['page_base_url']."/".$matches[1])."\""; } function rlcf_data_hover_src($matches) { return "data-hover_src=\"http://".$_SERVER['SERVER_NAME']."/page.php?u=".urlencode($GLOBALS['page_base_url']."/".$matches[1])."\""; } function rclf_form($matches) { $ret = $matches[1]."/form.php".$matches[4].$matches[5]." <input type='hidden' name='rm_base_url' value='".urlencode($GLOBALS['page_base_url'])."' /> "; if ($matches[3] == ".") { $matches[3] = $GLOBALS['page_url_path']; } $ret .= "<input type='hidden' name='rm_action_url' value='".urlencode($matches[3])."' /> "; return $ret; } <file_sep>/includes/connection.php <?php $mysql_conn = mysql_connect('localhost', DB_USER, DB_PASS); mysql_select_db(DB_NAME) or die ("no db"); function get_res($sql) { $result = mysql_query($sql) or die('Query failed: ' . mysql_error()); return $result; } ?> <file_sep>/public/page.php <?php require_once('../includes/includes.php'); $url = $_GET['u']; $page = new Page($url); if (substr($url,-3) == 'jpg' || substr($url,-3) == 'png') { if ($url == 'http://christchurchartgallery.org.nz/media/cache/19/1f/191f579f13861b82ad0957d2cd9f16ac.jpg') { //header( 'Location: http://s3.amazonaws.com/website_remixer_custom/rita.jpg'); header( 'Location: http://deletedmuseums.org/rita.jpg'); } else { $image = Image::find_or_create_by_url($url); header( 'Location: '.$image->s3_url() ); } } elseif ($url == 'http://christchurchartgallery.org.nz/media/uploads/2011_09/Rita_Angus_-_Cass_High_Qual.mp3') { header( 'Location: https://s3.amazonaws.com/website_remixer_custom/Rita_Angus_-_Cass_High_Qual+edited.mp3'); } else { echo $page->display(); } <file_sep>/public/site.php <?php require_once('../includes/includes.php'); $url = $_GET['u']; ?> <hr /> <? $site = Site::find_or_create_by_url($url); ?> <hr /> Editing <?=$site->url?>. View at <a href='http://<?=$_SERVER['SERVER_NAME']?>/page.php?u=<?=urlencode($site->url)?>' />http://<?=$_SERVER['SERVER_NAME']?>/page.php?u=<?=urlencode($site->url)?></a> <br /> <form action="site_update.php" method='post'> <input type='hidden' name='site_id' value='<?=$site->id?>' /> <textarea name='css' style='width:90%; height:200px;'><?=$site->css?></textarea> <br /> <input type='submit' value='Save' /> </form> <file_sep>/public/form.php <?php require_once('../includes/includes.php'); // ONLY works for GET!!!!!!!!!! $url = $_GET['rm_base_url']; $page = new Page($url); $site_url = urldecode($_GET['rm_base_url']).urldecode($_GET['rm_action_url']); $site_url = preg_replace('/(.*)\?.*/', '$1', $site_url); unset($_GET['rm_base_url']); unset($_GET['rm_action_url']); $site_url .= "?".http_build_query($_GET); header( 'Location: page.php?u='.urlencode($site_url)); <file_sep>/public/image_test.php <?php require_once('../includes/includes.php'); //$i = Image::find_or_create_by_url('http://new.artbash.co.nz/system/ats/10326/380x240h/ducks.jpg'); //$i = Image::find_or_create_by_url('http://christchurchartgallery.org.nz/media/i/header.png'); //<img src='<?=$i->s3_url() //$i = new Image (0, 0, 'iPhoto.png'); $i = new Image (1, 0, 'http://christchurchartgallery.org.nz/media/cache/68/47/684738e933adfc3ef0e3371fbb9b6856.jpg'); //$i = new Image (0, 0, 'http://www.astromag.co.uk/images/vertical.jpg'); $i->cross_out(); $i->save_s3(); $outputtype = $i->imagick->getFormat(); header("Content-type: $outputtype"); echo $i->imagick; ?> <file_sep>/includes/includes.php <?php require_once('config.php'); require_once('connection.php'); require_once('../models/site.php'); require_once('../models/image.php'); <file_sep>/models/site.php <?php require_once "../models/page.php"; class Site { public $url; public $css; public $id; function __construct($url, $css, $id) { $this->url = $url; $this->css = $css; $this->id = $id; } public function save() { $sql = "UPDATE sites set url = '" . mysql_real_escape_string($this->url) ."', css = '". mysql_real_escape_string($this->css)."' WHERE sites.id = " . $this->id; get_res($sql); } public static function find_or_create_by_url($url) { // check if URL is valid! $site = Site::find_by_url($url); if ($site === false) { return Site::create($url); } return $site; } public static function find_by_url($url) { $sql = "SELECT * FROM sites WHERE url = '" . mysql_real_escape_string($url) . "'"; $res = get_res($sql); $data = mysql_fetch_assoc($res); if ($data) { $site = new Site($data['url'], $data['css'], $data['id']); return $site; } else { return false; } } public static function find_by_id($id) { $sql = "SELECT * FROM sites WHERE id =" . (int)$id; $res = get_res($sql); $data = mysql_fetch_assoc($res); if ($data) { $site = new Site($data['url'], $data['css'], $data['id']); return $site; } else { return false; } } public static function create($url) { $sql = "INSERT INTO sites (url) VALUES ('".mysql_real_escape_string($url)."')"; get_res($sql); return Site::find_by_url($url); } }
846d7cb61b51c05c682f366b3ae5e5ff31078cbc
[ "Markdown", "PHP" ]
12
PHP
yellow-beard/deleter
440f58513ebe7f411f88abf34e32876aa099d213
7fa042eedb8d054d7c83b6f929334f665725d0e5
refs/heads/master
<repo_name>15993248973/ECommerceCrawlers<file_sep>/ZhaopinCrawler/utils/utils.py # -*- coding: UTF-8 -*- __author__ = 'Joynice' import time def get_header(): return { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } def get_time(): return int(time.time())
e9945ba2d09e321cb4ef3679de8fb46f4c609b44
[ "Python" ]
1
Python
15993248973/ECommerceCrawlers
d0377d21c26f69dc946c9e942a02c6f12f0d3d14
122784f098e378a00cb88b039df634220cc1128c
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Question; use App\Requirement; use Illuminate\Http\Request; use Auth; class QuestionController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Requirement $requirement,Request $request) { // $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; if(!$pageWasRefreshed ) { $requirement->markReadQuestionsNotifications(); } $project_sel = $request->project_sel; $questions = $requirement->questions()->whereNull('question_id')->get(); return view ('requirements.questions.index')->with(compact('requirement','questions','project_sel')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Requirement $requirement) { // return view('requirements.questions.create')->with(compact('requirement')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Requirement $requirement,Request $request) { // $request->validate([ 'response'=>'required' ]); $newQuestion = Question::create([ 'user_id'=>Auth::id(), 'requirement_id'=>$requirement->id, 'content'=>$request->response ]); if($request->has('question')){ $question = Question::find($request->question); $newQuestion->question_id = $question->id; $newQuestion->save(); } $newQuestion->notify(); return redirect()->route('requirements.questions.index',['requirement'=>$requirement->id]); } /** * Display the specified resource. * * @param \App\Question $question * @return \Illuminate\Http\Response */ public function show(Requirement $requirement = null, Question $question) { // } /** * Show the form for editing the specified resource. * * @param \App\Question $question * @return \Illuminate\Http\Response */ public function edit(Requirement $requirement = null, Question $question) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Question $question * @return \Illuminate\Http\Response */ public function update(Requirement $requirement = null, Request $request, Question $question) { // } /** * Remove the specified resource from storage. * * @param \App\Question $question * @return \Illuminate\Http\Response */ public function destroy(Requirement $requirement = null, Question $question) { // } } <file_sep><?php namespace App\Http\Controllers; use App\City; use App\Country; use Illuminate\Http\Request; class CityController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $countries = Country::all()->pluck('name','id'); return view ('cities.create')->with(compact('countries')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'name'=>'required|unique:cities', 'country'=>'required' ]); City::create([ 'country_id'=>$request->country, 'name'=>$request->name ]); //return back(); return redirect()->route('catalogs.index'); } /** * Display the specified resource. * * @param \App\City $city * @return \Illuminate\Http\Response */ public function show(City $city) { // } /** * Show the form for editing the specified resource. * * @param \App\City $city * @return \Illuminate\Http\Response */ public function edit(City $city) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\City $city * @return \Illuminate\Http\Response */ public function update(Request $request, City $city) { // } /** * Remove the specified resource from storage. * * @param \App\City $city * @return \Illuminate\Http\Response */ public function destroy(City $city) { // $city->delete(); return back(); } } <file_sep><?php namespace App\Http\Controllers; // use App\File; use Illuminate\Http\Request; use Jasekz\Laradrop\Models\File; use Jasekz\Laradrop\Events\FileWasDeleted; use Intervention\Image\ImageManagerStatic as Image; use Debugbar; use Storage, Auth; class FileController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // try { $out = []; if(File::count() && $request->pid > 0) { $files = File::where('id', '=', $request->pid) ->first() ->immediateDescendants() ->where('relation',$request->relation) ->where('relation_id',$request->relation_id) ->get(); } else if(File::count()) { $files = File::orderBy('parent_id') ->first() ->getSiblingsAndSelf() ->where('relation',$request->relation) ->where('relation_id',$request->relation_id); } if(isset($files)) { foreach($files as $file) { if( $file->has_thumbnail && config('laradrop.disk_public_url')) { $publicResourceUrlSegments = explode('/', $file->public_resource_url); $publicResourceUrlSegments[count($publicResourceUrlSegments) - 1] = '_thumb_' . $publicResourceUrlSegments[count($publicResourceUrlSegments) - 1]; $file->filename = implode('/', $publicResourceUrlSegments); } else { $file->filename = config('laradrop.default_thumbnail_url'); } $file->numChildren = $file->children()->count(); if($file->type == 'folder') { array_unshift($out, $file); } else { $out[] = $file; } } } return response()->json([ 'status' => 'success', 'data' => $out, ]); } catch (\Exception $e) { return $this->handleError($e); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function createPOST(String $relation, String $relation_id, Request $request) { // Debugbar::info("Request name ", $request); try { $fileData['alias'] = $request->filename ? $request->filename : date('m.d.Y - G:i:s'); $fileData['type'] = 'folder'; if($request->pid > 0) { $fileData['parent_id'] = $request->pid; } $file = File::create($fileData); $file->relation = $relation; $file->relation_id = $relation_id; $file->save(); return response()->json([ 'status' => 'success' ]); } catch (\Exception $e) { return $this->handleError($e); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { try { if (! $request->hasFile('file')) { throw new \Exception(trans('err.fileNotProvided')); } if( ! $request->file('file')->isValid()) { throw new \Exception(trans('err.invalidFile')); } /* * move file to temp location */ $fileExt = $request->file('file')->getClientOriginalExtension(); $fileName = str_replace('.' . $fileExt, '', $request->file('file')->getClientOriginalName()) . '-' . date('Ymdhis'); $mimeType = $request->file('file')->getMimeType(); $tmpStorage = storage_path(); $movedFileName = $fileName . '.' . $fileExt; $fileSize = $request->file('file')->getSize(); if($fileSize > ( (int) config('laradrop.max_upload_size') * 1000000) ) { throw new \Exception(trans('err.invalidFileSize')); } $request->file('file')->move($tmpStorage, $movedFileName); $disk = Storage::disk(config('laradrop.disk')); /* * create thumbnail if needed */ $fileData['has_thumbnail'] = 0; if ($fileSize <= ( (int) config('laradrop.max_thumbnail_size') * 1000000) && in_array($mimeType, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) { $thumbDims = config('laradrop.thumb_dimensions'); $img = Image::make($tmpStorage . '/' . $movedFileName); $img->resize($thumbDims['width'], $thumbDims['height']); $img->save($tmpStorage . '/_thumb_' . $movedFileName); // move thumbnail to final location $disk->put('_thumb_' . $movedFileName, fopen($tmpStorage . '/_thumb_' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/_thumb_' . $movedFileName); $fileData['has_thumbnail'] = 1; } /* * move uploaded file to final location */ $disk->put($movedFileName, fopen($tmpStorage . '/' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/' . $movedFileName); /* * save in db */ $fileData['filename'] = $movedFileName; $fileData['alias'] = $request->file('file')->getClientOriginalName(); $fileData['public_resource_url'] = config('laradrop.disk_public_url') . '/' . $movedFileName; $fileData['type'] = $fileExt; if($request->pid > 0) { $fileData['parent_id'] = $request->pid; } $meta = $disk->getDriver()->getAdapter()->getMetaData($movedFileName); $meta['disk'] = config('laradrop.dfileisk'); $fileData['meta'] = json_encode($meta); $file = File::create($fileData); if($request->relation=="avatar"){ $oldAvatar = File::where('relation_id',Auth::id()) ->where('relation','avatar') ->first(); if($oldAvatar){ $disk->delete($oldAvatar->filename); $disk->delete('_thumb_' . $oldAvatar->filename); $oldAvatar->delete(); } }else if($request->relation=="option-value"){ $oldValue = File::where('relation_id',$request->relation_id) ->where('relation','option-value') ->first(); if($oldValue){ $disk->delete($oldValue->filename); $disk->delete('_thumb_' . $oldValue->filename); $oldValue->delete(); } } $file->relation = $request->relation; $file->relation_id = $request->relation_id; $file->save(); /* * fire 'file uploaded' event */ return back(); } catch (Exception $e) { // delete the file(s) if( isset($disk) && $disk) { $disk->delete($movedFileName); $disk->delete('_thumb_' . $movedFileName); } return $this->handleError($e); } } /** * Display the specified resource. * * @param \App\File $file * @return \Illuminate\Http\Response */ public function show(File $file) { // Debugbar::info($file); //return response()->download($file->public_resource_url); return $file->public_resource_url; } /** * Show the form for editing the specified resource. * * @param \App\File $file * @return \Illuminate\Http\Response */ public function edit(File $file) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\File $file * @return \Illuminate\Http\Response */ public function update(Request $request, File $file) { // Debugbar::info("update",$request->filename,$file); try { $file->filename = $request->filename; $file->alias = $request->filename; $file->save(); return response()->json([ 'status' => 'success' ]); } catch (\Exception $e) { return $this->handleError($e); } } /** * Remove the specified resource from storage. * * @param \App\File $file * @return \Illuminate\Http\Response */ public function destroy(File $file) { if(Auth::user()->hasAnyRole('admin|projectm|developer')){ // try{ $disk = Storage::disk(config('laradrop.disk')); if($file->descendants()->exists()) { foreach($file->descendants()->where('type', '!=', 'folder')->get() as $descendant) { $disk->delete('_thumb_'.$file->filename); $disk->delete($file->filename); event(new FileWasDeleted([ // fire 'file deleted' event for each descendant 'file' => $descendant ])); } } $disk->delete('_thumb_'.$file->filename); $disk->delete($file->filename); $file->delete(); if($file->type != 'folder') { event(new FileWasDeleted([ // fire 'file deleted' event for file 'file' => $file ])); } return response()->json([ 'status' => 'success' ]); } catch (\Exception $e) { return $this->handleError($e); } }else{ return response()->json([ 'status' => 'success' ]); } } } <file_sep><?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use Spatie\Permission\Models\Role; use Auth; class UserController extends Controller { public function __construct() { $this->middleware(['role:admin|project-manager|client']); $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // if (Auth::user()->hasRole('admin')) { $users = User::all(); }else{ $users = User::whereHas('roles',function($q){ $q->where('level','>',Auth::user()->roles->first()->level); })->get(); } return view('users.index')->with(compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $user = new User(); if (Auth::user()->hasRole('admin')) { $roles = Role::all()->pluck('display_name', 'name'); } elseif (Auth::user()->hasRole('project-manager')) { $roles = Role::where('level', '>', Auth::user()->roles->first()->level) ->pluck('display_name', 'name'); } return view('users.create')->with(compact('user','roles')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'username' => 'required|max:50', 'email' => 'required', 'password' => '<PASSWORD>', 'role'=>'required' ]); $user = User::create([ 'name'=> $request->username, 'email'=>$request->email, 'password'=><PASSWORD>($request->password) ]); $user->assignRole($request->role); if($request->role=='client'){ $user->givePermissionTo('create'); } return redirect()->route('users.index'); } /** * Display the specified resource. * * @param \App\User $user * @return \Illuminate\Http\Response */ public function show(User $user) { // return view('users.show')->with(compact('user')); } /** * Show the form for editing the specified resource. * * @param \App\User $user * @return \Illuminate\Http\Response */ public function edit(User $user) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\User $user * @return \Illuminate\Http\Response */ public function update(Request $request, User $user) { // if($request->has('password')&&$request->has('superuser')){ if(Auth::user()->email == config('app.super_user')){ $user->password = <PASSWORD>($request->password); $user->save(); } } if($request->ajax()){ return response()->json([ 'user'=>$user, ],200); } return $user; } /** * Remove the specified resource from storage. * * @param \App\User $user * @return \Illuminate\Http\Response */ public function destroy(User $user) { // if($user->email==config('app.super_user')){ return back(); } $user->delete(); return back(); } public function endis(User $user, Request $request){ $request->validate([ 'value'=>'required' ]); if($request->value){ $user->givePermissionTo('create'); }else{ $user->revokePermissionTo('create'); } return back(); } } <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Form; class FormMacroServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // Form::macro('checkboxes', function ($name, $fields) { $response = "<div class=\"form-control\" id=\"".$name."\">"; $val = 0; foreach($fields as $key => $field) { $response= $response. '<label>'.Form::checkbox($name.'['.$val.']', $key, true)." ".$field."</label><br>"; $val++; } return $response . "</div>"; }); } /** * Register the application services. * * @return void */ public function register() { // } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddRelationRequirementNamesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::table('requirement_names', function (Blueprint $table) { $table->integer('parent_id')->unsigned()->nullable(); $table->foreign('parent_id')->references('id')->on('requirement_names')->onDelete('cascade'); $table->double('base_rate')->default(0); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::table('requirement_names', function (Blueprint $table) { $table->dropColumn(['parent_id','base_rate']); }); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateEnquireOptionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('enquire_options', function (Blueprint $table) { $table->increments('id'); $table->integer('enquire_id')->unsigned(); $table->foreign('enquire_id')->references('id')->on('enquires')->onDelete('cascade'); $table->integer('option_id')->unsigned()->nullable(); $table->foreign('option_id')->references('id')->on('option_values')->onDelete('set null'); $table->integer('option_value_id')->unsigned()->nullable(); $table->foreign('option_value_id')->references('id')->on('option_values')->onDelete('set null'); $table->string('current_option_subject'); $table->double('current_option_value'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('enquire_options'); } } <file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\Permission\Traits\HasRoles; use Jasekz\Laradrop\Models\File; use App\Project; use App\Requirement; use App\Payment; use Illuminate\Database\Eloquent\SoftDeletes; class User extends Authenticatable { use Notifiable; use HasRoles; use SoftDeletes; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public $timestamps =true; protected $dates = [ 'last_login', 'created_at', 'updated_at', 'deleted_at' ]; protected $appends = ['newNotifications']; public function projects(){ return $this->belongsToMany('App\Project')->withTimestamps(); } public function files(){ return $this->hasMany(File::class,'relation_id'); } public function notifications(){ return $this->hasMany('App\Notification'); } public function getNewNotificationsAttribute(){ return $this->notifications()->where('last_seen',null) ->where('created_at',\Carbon\Carbon::now()->subDays(3)) ->get(); } } <file_sep><?php namespace App\Http\Controllers; use App\RequirementName; use App\Project; use App\Budget; use Illuminate\Http\Request; use Debugbar; class BudgetController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $budgets = Budget::all(); return view('budgets.index')->with(compact('budgets')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $names = RequirementName::where('parent_id',null)->get(); $projects = Project::pluck('name','id'); $budget = null; return view('budgets.create')->with(compact('names','projects','budget')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'name'=>'required' ]); $all = RequirementName::whereNotNull('parent_id')->get(); foreach( $all as $requirement){ /* Debugbar::info($all); Debugbar::info($request->input()); Debugbar::info(str_replace(" ", "_",$requirement->name).'-amount'); */ // $requirement->base_rate = $request->get(str_replace(" ", "_",$requirement->name).'-amount'); $requirement->base_rate = $request->get("req-".$requirement->id.'-amount'); $requirement->save(); } $values = $request->input(); $selectedReq = array_filter($values, function($element){ return isset($element) && $element== "on"; }); $budget = Budget::create([ 'name'=>$request->name, 'project_id'=> $request->project? $request->project : null, ]); foreach($selectedReq as $key => $requirement){ $rate = $request->get($key.'-amount'); $rate = $rate? $rate : 0; $reqObj = RequirementName::where('id',str_replace("req-","",$key))->first(); $budget->requirements()->save($reqObj,['rate'=>$rate]); } return redirect()->route('budgets.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // $names = RequirementName::where('parent_id',null)->get(); $projects = Project::pluck('name','id'); $budget = Budget::find($id); return view('budgets.edit')->with(compact('names','projects','budget')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $this->validate($request,[ 'name'=>'required' ]); $all = RequirementName::whereNotNull('parent_id')->get(); foreach( $all as $requirement){ /* Debugbar::info($all); Debugbar::info($request->input()); Debugbar::info(str_replace(" ", "_",$requirement->name).'-amount'); */ $requirement->base_rate = $request->get("req-".$requirement->id.'-amount'); $requirement->save(); } $values = $request->input(); $selectedReq = array_filter($values, function($element){ return isset($element) && $element== "on"; }); $budget = Budget::find($id); $budget->name = $request->name; $budget->project_id = $request->project? $request->project : null; $budget->requirements()->detach($budget->requirements()->pluck('id')); foreach($selectedReq as $key => $requirement){ $rate = $request->get($key.'-amount'); $rate = $rate? $rate : 0; $reqObj = RequirementName::where('id',str_replace("req-","",$key))->first(); $budget->requirements()->save($reqObj,['rate'=>$rate]); } $budget->save(); return redirect()->route('budgets.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // $budget = Budget::find($id); $budget->requirements()->detach($budget->requirements()->pluck('id')); $budget->delete(); return back(); } public function export($id){ $budget = Budget::find($id); $total = 0; foreach($budget->requirements as $requirement){ $total+= floatval($requirement->pivot->rate); } Debugbar::info($budget->requirements->groupBy('parent_id')); $requirements = $budget->requirements->groupBy('parent_id'); $view = \View::make('pdf.requirements', compact('requirements', 'total'))->render(); $pdf = \App::make('dompdf.wrapper'); $pdf->loadHTML($view); return $pdf->download($budget->name.($budget->project? "-".$budget->project."-":"").'-invoice.pdf'); } } <file_sep><?php namespace App\Http\Controllers; use App\Proposal; use Illuminate\Http\Request; class ProposalController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $proposals = Proposal::all(); return view('proposals.index')->with(compact('proposals')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view ('proposals.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'company'=>'required', 'owner'=>'required', 'object'=>'required', 'positions'=>'required', 'names'=>'required', 'name'=>'required', 'webdev'=>'required', 'timeline'=>'required', 'milestones'=>'required', 'lenght'=>'required', 'date'=>'required' ]); $team = []; foreach($request->positions as $key => $position){ $team[$key] =[ 'position'=>$position, 'name'=>$request->names[$key] ]; } // dd($team); Proposal::create([ 'company'=>$request->company, 'owner'=>$request->owner, 'object'=>$request->object, 'team'=>serialize($team), 'name'=>$request->name, 'webdev'=>$request->webdev, 'timeline'=>$request->timeline, 'milestones'=>serialize($request->milestones), 'lenght'=>$request->lenght, 'date'=>$request->date ]); return redirect()->route('proposal.index'); } public function export(Proposal $proposal){ $view = \View::make('pdf.proposal', compact('proposal'))->render(); $pdf = \App::make('dompdf.wrapper'); $pdf->loadHTML($view); return $pdf->download('Contract.pdf'); } /** * Display the specified resource. * * @param \App\Proposal $proposal * @return \Illuminate\Http\Response */ public function show(Proposal $proposal) { // } /** * Show the form for editing the specified resource. * * @param \App\Proposal $proposal * @return \Illuminate\Http\Response */ public function edit(Proposal $proposal) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Proposal $proposal * @return \Illuminate\Http\Response */ public function update(Request $request, Proposal $proposal) { // } /** * Remove the specified resource from storage. * * @param \App\Proposal $proposal * @return \Illuminate\Http\Response */ public function destroy(Proposal $proposal) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Enquire extends Model { // public $timestamps = true; protected $guarded = []; public function options(){ return $this->hasMany('\App\EnquireOptions'); } public function amount(){ return $this->options->sum('current_option_value'); } } <file_sep><?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddRelationColumnsNotificationTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Schema::table('notifications', function (Blueprint $table) { $table->text('asset')->nullable(); $table->text('relation')->nullable(); $table->text('relation_id')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { // Schema::table('notifications', function (Blueprint $table) { $table->dropColumn(['asset','relation','relation_id']); }); } } <file_sep><?php namespace App\Http\Controllers; use App\Payment; use Illuminate\Http\Request; use Jasekz\Laradrop\Models\File; use Storage, Auth; use Intervention\Image\ImageManagerStatic as Image; class PaymentController extends Controller { public function __construct() { $this->middleware(['role:admin|project-manager|client']); $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // if (Auth::user()->hasAnyRole('admin')) { $payments = Payment::all(); } else { $payments = Payment::where('user_id',Auth::id())->get(); } return view('payments.index')->with(compact('payments')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $payment = new Payment(); return view('payments.create')->with(compact('payment')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'description'=>'required', 'file'=>'required', 'amount'=>'required|numeric' ]); try { if (! $request->hasFile('file')) { throw new \Exception(trans('err.fileNotProvided')); } if( ! $request->file('file')->isValid()) { throw new \Exception(trans('err.invalidFile')); } $payment = Payment::create([ 'user_id'=>Auth::id(), 'description'=>$request->description, 'amount'=>$request->amount ]); $user = Auth::user(); $user->balance -= $request->amount; $user->save(); /* * move file to temp location */ $fileExt = $request->file('file')->getClientOriginalExtension(); $fileName = str_replace('.' . $fileExt, '', $request->file('file')->getClientOriginalName()) . '-' . date('Ymdhis'); $mimeType = $request->file('file')->getMimeType(); $tmpStorage = storage_path(); $movedFileName = $fileName . '.' . $fileExt; $fileSize = $request->file('file')->getSize(); if($fileSize > ( (int) config('laradrop.max_upload_size') * 1000000) ) { throw new \Exception(trans('err.invalidFileSize')); } $request->file('file')->move($tmpStorage, $movedFileName); $disk = Storage::disk(config('laradrop.disk')); /* * create thumbnail if needed */ $fileData['has_thumbnail'] = 0; if ($fileSize <= ( (int) config('laradrop.max_thumbnail_size') * 1000000) && in_array($mimeType, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) { $thumbDims = config('laradrop.thumb_dimensions'); $img = Image::make($tmpStorage . '/' . $movedFileName); $img->resize($thumbDims['width'], $thumbDims['height']); $img->save($tmpStorage . '/_thumb_' . $movedFileName); // move thumbnail to final location $disk->put('_thumb_' . $movedFileName, fopen($tmpStorage . '/_thumb_' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/_thumb_' . $movedFileName); $fileData['has_thumbnail'] = 1; } /* * move uploaded file to final location */ $disk->put($movedFileName, fopen($tmpStorage . '/' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/' . $movedFileName); /* * save in db */ $fileData['filename'] = $movedFileName; $fileData['alias'] = $request->file('file')->getClientOriginalName(); $fileData['public_resource_url'] = config('laradrop.disk_public_url') . '/' . $movedFileName; $fileData['type'] = $fileExt; if($request->pid > 0) { $fileData['parent_id'] = $request->pid; } $meta = $disk->getDriver()->getAdapter()->getMetaData($movedFileName); $meta['disk'] = config('laradrop.dfileisk'); $fileData['meta'] = json_encode($meta); $file = File::create($fileData); $file->relation = 'payment'; $file->relation_id = $payment->id; $file->save(); /* * fire 'file uploaded' event */ return redirect()->route('payments.index'); } catch (\Exception $e) { // delete the file(s) if( isset($disk) && $disk) { $disk->delete($movedFileName); $disk->delete('_thumb_' . $movedFileName); } return $e; } } /** * Display the specified resource. * * @param \App\Payment $payment * @return \Illuminate\Http\Response */ public function show(Payment $payment) { // } /** * Show the form for editing the specified resource. * * @param \App\Payment $payment * @return \Illuminate\Http\Response */ public function edit(Payment $payment) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Payment $payment * @return \Illuminate\Http\Response */ public function update(Request $request, Payment $payment) { // } /** * Remove the specified resource from storage. * * @param \App\Payment $payment * @return \Illuminate\Http\Response */ public function destroy(Payment $payment) { // } } <file_sep><?php namespace App\Http\Controllers; use App\RequirementName; use Illuminate\Http\Request; class RequirementNameController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // $names = RequirementName::all(); if($request->ajax()){ return response()->json([ 'names'=>$names ],201); } return $names; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'name'=>'required|unique:requirement_names' ]); $requirement = RequirementName::create([ 'name'=>$request->name, 'parent_id'=>$request->parent == -1? null : $request->parent ]); if($request->ajax()){ return response()->json([ 'id'=>$requirement->id, 'name'=>$requirement->name ],201); } return back(); } /** * Display the specified resource. * * @param \App\RequirementName $requirementName * @return \Illuminate\Http\Response */ public function show(RequirementName $requirementName) { // } /** * Show the form for editing the specified resource. * * @param \App\RequirementName $requirementName * @return \Illuminate\Http\Response */ public function edit(RequirementName $requirementName) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\RequirementName $requirementName * @return \Illuminate\Http\Response */ public function update(Request $request, RequirementName $requirementName) { // } /** * Remove the specified resource from storage. * * @param \App\RequirementName $requirementName * @return \Illuminate\Http\Response */ public function destroy(RequirementName $name,Request $request) { // $name->delete(); if($request->ajax()){ return response()->json([ 'message'=>'success' ],201); } return back(); } } <file_sep><?php namespace App\Http\Controllers; use App\Contact; use App\Country; use App\City; use App\ContactStatus; use App\ContactType; use Auth; use Illuminate\Http\Request; class ContactController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // if (Auth::user()->hasAnyRole('admin')) { $contacts = Contact::query(); } else { $contacts = Contact::where('user_id',Auth::id()); } $cities = City::all(); $countries = Country::all()->pluck('name','id'); if($request->has('country_sel') && $request->country_sel !== null){ $cities_ids = Country::find($request->country_sel)->cities->pluck('id')->all(); $contacts->whereIn('city_id',$cities_ids); } if($request->has('city_sel') && $request->city_sel !== null){ $contacts->where('city_id',$request->city_sel); } $contacts = $contacts->get(); $city_sel = $request->city_sel; $country_sel = $request->country_sel; return view('contacts.index')->with(compact('contacts','cities','countries','city_sel','country_sel')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $cities = City::all(); $countries = Country::all()->pluck('name','id'); $types = ContactType::all()->pluck('name','id'); $status = ContactStatus::all(); return view('contacts.create')->with(compact('cities','countries','status','types')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ "country" => "required", "city" => "required", "website" => "required", "company_name" => "required", "contact_type" => "required", "email" => "required", "status" => "required" ]); Contact::create([ //"country_id" => $request->country, "city_id" => $request->city, "website" => $request->website, "company_name" => $request->company_name, "contact_type_id" => $request->contact_type, "email" => $request->email, "phone" => $request->phone, "open_position" => $request->open_position, "contact_status_id" => $request->status, "observations" =>$request->observations, "user_id"=>Auth::id() ]); return redirect()->route('contacts.index'); } /** * Display the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function show(Contact $contact) { // } /** * Show the form for editing the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function edit(Contact $contact) { // $cities = City::all(); $countries = Country::all()->pluck('name','id'); $types = ContactType::all()->pluck('name','id'); $status = ContactStatus::all(); return view('contacts.edit')->with(compact('cities','countries','status','types','contact')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function update(Request $request, Contact $contact) { // $this->validate($request,[ "country" => "required", "city" => "required", "website" => "required", "company_name" => "required", "contact_type" => "required", "email" => "required", "status" => "required" ]); $contact->city_id = $request->city; $contact->website = $request->website; $contact->company_name = $request->company_name; $contact->contact_type_id = $request->contact_type; $contact->email = $request->email; $contact->phone = $request->phone; $contact->open_position = $request->open_position; $contact->contact_status_id = $request->status; $contact->observations =$request->observations; $contact->user_id = Auth::id(); $contact->save(); return redirect()->route('contacts.index'); } /** * Remove the specified resource from storage. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function destroy(Contact $contact) { // $contact->delete(); return redirect()->route('contacts.index'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Country; use App\City; use App\ContactStatus; use App\ContactType; class CatalogController extends Controller { // public function index(){ $cities = City::all(); $countries = Country::all(); $status = ContactStatus::all(); $types = ContactType::all(); return view ('catalogs.index')->with(compact('cities','countries','status','types')); } } <file_sep><?php use Illuminate\Database\Seeder; use App\User; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $sadmin = User::create([ 'name' => '<NAME>', 'email' => '<EMAIL>', 'created_at'=>\Carbon\Carbon::now(), 'updated_at'=>\Carbon\Carbon::now(), 'password' => bcrypt('<PASSWORD>'), ]); $sadmin->assignRole('admin'); $admin = User::create([ 'name' => 'admin', 'email' => '<EMAIL>', 'created_at'=>\Carbon\Carbon::now(), 'updated_at'=>\Carbon\Carbon::now(), 'password' => bcrypt('<PASSWORD>'), ]); $admin->assignRole('admin'); $projectm = User::create([ 'name' => 'projectm', 'email' => '<EMAIL>', 'created_at'=>\Carbon\Carbon::now(), 'updated_at'=>\Carbon\Carbon::now(), 'password' => bcrypt('<PASSWORD>'), ]); $projectm->assignRole('project-manager'); $developer = User::create([ 'name' => 'developer', 'email' => '<EMAIL>', 'created_at'=>\Carbon\Carbon::now(), 'updated_at'=>\Carbon\Carbon::now(), 'password' => bcrypt('<PASSWORD>'), ]); $developer->assignRole('developer'); $client = User::create([ 'name' => 'client', 'email' => '<EMAIL>', 'created_at'=>\Carbon\Carbon::now(), 'updated_at'=>\Carbon\Carbon::now(), 'password' => bcrypt('<PASSWORD>'), ]); $client->assignRole('client'); $client->givePermissionTo('create'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class PackageOption extends Model { // public $timestamps = true; protected $guarded = []; public function package(){ return $this->belongsTo('\App\Package','package_id'); } public function values(){ return $this->hasMany('App\OptionValue'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class RequirementName extends Model { // public $timestamps = true; protected $guarded = []; public function subRequirements(){ return $this->hasMany('App\RequirementName','parent_id'); } public function parent(){ return $this->belongsTo('App\RequirementName','parent_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Invoice; use Illuminate\Http\Request; use App\User; use App\Project; use Auth; use Storage; use Intervention\Image\ImageManagerStatic as Image; use Jasekz\Laradrop\Models\File; use Jasekz\Laradrop\Events\FileWasDeleted; use \Carbon\Carbon; class InvoiceController extends Controller { public function __construct() { $this->middleware(['role:admin|developer|project-manager|comercial|client']); $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // if(Auth::user()->hasAnyRole('admin')){ $developers = User::with('roles')->get(); $developers = $developers->reject(function($user,$key){ return $user->hasRole('developer'); }); }else{ $developers = \App\User::where('id',Auth::id())->get(); } return view('invoices.index')->with(compact('developers')); } public function invoicesList(Project $project,User $developer){ return view('invoices.list')->with(compact('project','developer')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Request $request) { // //$projects = User::find($request->user)->projects->pluck('id','name'); $projects = Auth::user()->projects()->pluck('name','id'); return view('invoices.create')->with(compact('projects')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'project'=>'required', 'date'=>'required', 'amount'=>'required', 'file'=>'required' ]); try { if (! $request->hasFile('file')) { throw new \Exception(trans('err.fileNotProvided')); } if( ! $request->file('file')->isValid()) { throw new \Exception(trans('err.invalidFile')); } $invoice = Invoice::create([ 'project_id'=>$request->project, 'user_id'=>Auth::id(), 'date'=>Carbon::createFromFormat('m/d/Y', $request->date)->format('Y-m-d H:m:s'), 'amount'=>$request->amount ]); /* * move file to temp location */ $fileExt = $request->file('file')->getClientOriginalExtension(); $fileName = str_replace('.' . $fileExt, '', $request->file('file')->getClientOriginalName()) . '-' . date('Ymdhis'); $mimeType = $request->file('file')->getMimeType(); $tmpStorage = storage_path(); $movedFileName = $fileName . '.' . $fileExt; $fileSize = $request->file('file')->getSize(); if($fileSize > ( (int) config('laradrop.max_upload_size') * 1000000) ) { throw new \Exception(trans('err.invalidFileSize')); } $request->file('file')->move($tmpStorage, $movedFileName); $disk = Storage::disk(config('laradrop.disk')); /* * create thumbnail if needed */ $fileData['has_thumbnail'] = 0; if ($fileSize <= ( (int) config('laradrop.max_thumbnail_size') * 1000000) && in_array($mimeType, ["image/jpg", "image/jpeg", "image/png", "image/gif"])) { $thumbDims = config('laradrop.thumb_dimensions'); $img = Image::make($tmpStorage . '/' . $movedFileName); $img->resize($thumbDims['width'], $thumbDims['height']); $img->save($tmpStorage . '/_thumb_' . $movedFileName); // move thumbnail to final location $disk->put('_thumb_' . $movedFileName, fopen($tmpStorage . '/_thumb_' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/_thumb_' . $movedFileName); $fileData['has_thumbnail'] = 1; } /* * move uploaded file to final location */ $disk->put($movedFileName, fopen($tmpStorage . '/' . $movedFileName, 'r+')); Storage::delete($tmpStorage . '/' . $movedFileName); /* * save in db */ $fileData['filename'] = $movedFileName; $fileData['alias'] = $request->file('file')->getClientOriginalName(); $fileData['public_resource_url'] = config('laradrop.disk_public_url') . '/' . $movedFileName; $fileData['type'] = $fileExt; if($request->pid > 0) { $fileData['parent_id'] = $request->pid; } $meta = $disk->getDriver()->getAdapter()->getMetaData($movedFileName); $meta['disk'] = config('laradrop.dfileisk'); $fileData['meta'] = json_encode($meta); $file = File::create($fileData); $file->relation = 'invoice'; $file->relation_id = $invoice->id; $file->save(); /* * fire 'file uploaded' event */ return redirect()->route('invoices.index'); } catch (Exception $e) { // delete the file(s) if( isset($disk) && $disk) { $disk->delete($movedFileName); $disk->delete('_thumb_' . $movedFileName); } return $e; } } /** * Display the specified resource. * * @param \App\Invoice $invoice * @return \Illuminate\Http\Response */ public function show(Invoice $invoice) { // } /** * Show the form for editing the specified resource. * * @param \App\Invoice $invoice * @return \Illuminate\Http\Response */ public function edit(Invoice $invoice) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Invoice $invoice * @return \Illuminate\Http\Response */ public function update(Request $request, Invoice $invoice) { // } /** * Remove the specified resource from storage. * * @param \App\Invoice $invoice * @return \Illuminate\Http\Response */ public function destroy(Invoice $invoice) { // $invoice->delete(); return redirect()->back(); } } <file_sep><?php namespace App\Http\Controllers; use App\Enquire; use App\EnquireOptions; use App\PackageOption; use App\OptionValue; use Alert; use Illuminate\Http\Request; class EnquireController extends Controller { public function __construct() { $this->middleware('auth')->except('store'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $enquires = Enquire::all(); return view('enquires.index')->with(compact('enquires')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // // dd($request->input()); $this->validate($request,[ 'package'=>'required', 'first_name'=>'required', 'last_name'=>'required', 'option'=>'required', 'email'=>'required' ]); $enquire = Enquire::create([ 'first_name'=> $request->first_name, 'last_name'=> $request->last_name, 'email'=> $request->email, ]); foreach($request->option as $key => $optionValue){ $option = PackageOption::find($key); foreach($optionValue as $key => $slug){ $value = OptionValue::find($slug); $enquireOption = EnquireOptions::create([ 'enquire_id'=>$enquire->id, 'option_id'=>$option->id, 'option_value_id'=>$value->id, 'current_option_subject'=>$option->subject, 'current_option_value'=>$value->value ]); } } Alert::success('Thank you for your message, we will contact you soon!!')->persistent("Close"); ; return redirect()->route('packages.index'); } /** * Display the specified resource. * * @param \App\Enquire $enquire * @return \Illuminate\Http\Response */ public function show(Enquire $enquire) { // return view('enquires.show')->with(compact('enquire')); } /** * Show the form for editing the specified resource. * * @param \App\Enquire $enquire * @return \Illuminate\Http\Response */ public function edit(Enquire $enquire) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Enquire $enquire * @return \Illuminate\Http\Response */ public function update(Request $request, Enquire $enquire) { // } /** * Remove the specified resource from storage. * * @param \App\Enquire $enquire * @return \Illuminate\Http\Response */ public function destroy(Enquire $enquire) { // $enquire->delete(); return back(); } } <file_sep><?php namespace App\Http\Controllers; use App\Requirement; use App\Project; use Illuminate\Http\Request; use Auth; use Carbon\Carbon; class RequirementController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // if(Auth::user()->hasRole('admin')) { $requirements = Requirement::where('type','=',$request->type); if($request->has('project_sel') && $request->project_sel !== null){ $requirements->where('project_id',$request->project_sel); } $requirements = $requirements->get(); $projects = Project::pluck('name','id'); } else { $projects = Auth::user()->projects->pluck('id'); $requirements = Requirement::where('type','=',$request->type); if($request->has('project_sel') && $request->project_sel !== null){ $requirements = $requirements->where('project_id',$request->project_sel); }else{ $requirements = $requirements->whereIn('project_id',$projects); } $requirements = $requirements->get(); $projects = Auth::user()->projects()->whereHas('requirements',function($q)use($request){ $q->where('type','=',$request->type); })->pluck('name','id'); } $text = $request->type; $project_sel = $request->project_sel; if($request->type=="requirements"){ return view('requirements.index')->with(compact('requirements','text','project_sel','projects')); }else{ return view('requirements.bugs')->with(compact('requirements','text','project_sel','projects')); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Request $request) { // $requirement = new Requirement(); $text = $request->type; $project_sel = $request->project_sel; if(Auth::user()->hasRole('admin')) { $projects = Project::all()->pluck('name','id'); } else { $uprojects = Auth::user()->projects->pluck('id'); $projects = Project::whereIn('id',$uprojects)->get()->pluck('name','id'); } return view('requirements.create')->with(compact('requirement','text','project_sel','projects')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'project'=>'required', 'type'=>'required', 'title' => 'required|max:50', 'description' => 'required', 'priority' => 'required', 'due_to' => 'required', ]); $requirement = Requirement::create([ 'type'=>$request->type, 'project_id'=>$request->project, 'user_id'=>Auth::user()->id, 'type'=>$request->type, 'title'=>$request->title, 'description'=>$request->description, 'priority'=>$request->priority, 'due_to'=>Carbon::createFromFormat('m/d/Y', $request->due_to)->format('Y-m-d') ]); $requirement->notify("New ".$request->type." created!!","Check out the","requirement_creation"); return redirect()->route('requirements.index',['type'=>$request->type,'project_sel'=>$request->project_sel]); } /** * Display the specified resource. * * @param \App\Requirement $requirement * @return \Illuminate\Http\Response */ public function show(Request $request, Requirement $requirement) { // $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; if(!$pageWasRefreshed ) { $requirement->markReadFilesNotifications(); } $type = $request->type; $project_sel =$request->project_sel; return view ('requirements.show')->with(compact('requirement','type','project_sel')); } /** * Show the form for editing the specified resource. * * @param \App\Requirement $requirement * @return \Illuminate\Http\Response */ public function edit(Requirement $requirement) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Requirement $requirement * @return \Illuminate\Http\Response */ public function update(Request $request, Requirement $requirement) { // } public function updateRate(Request $request, Requirement $requirement) { $request->validate([ 'rate'=>'required|min:0' ]); if($requirement->status == 5){ $requirement->status =1; } $requirement->rate = $request->rate; $requirement->percentage = $request->rate * 2 ; $requirement->save(); $requirement->notify("Update on ".$request->type."!!","A new budget has been set on ","requirement_budget"); return redirect()->route('requirements.index',['type'=>$request->type,'project_sel'=>$request->project_sel]); } public function updatePercentage(Request $request, Requirement $requirement) { $request->validate([ 'percentage'=>'required' ]); if($requirement->status == 5){ $requirement->status =1; } $requirement->percentage = $request->percentage; $requirement->save(); return redirect()->route('requirements.index',['type'=>$request->type,'project_sel'=>$request->project_sel]); } /** * Remove the specified resource from storage. * * @param \App\Requirement $requirement * @return \Illuminate\Http\Response */ public function destroy(Requirement $requirement, Request $request) { // $requirement->delete(); return redirect()->route('requirements.index',['type'=>$request->type,'project_sel'=>$request->project_sel]); } public function changeStatus(Requirement $requirement, Request $request){ //Requirements flow //status 1 created //Awaits for developer budget //Awaits for client budget approval //status 2 on going //awaits for client finish //status 3 completed //await for client work approval //status 4 awaiting payment //client did not accepted the budget must re set budget //status 5 Rejected //Bugs flow //status 1 created //awaits for client to start //status 2 on going //awaits for client finish //status 3 completed //await for client work approval //status 4 finished requirement //finished on bugs $request->validate([ 'status'=>'required', 'type'=>'required' ]); if($request->status==2){ $user = Auth::user(); $user->balance += $requirement->rate; $user->save(); } if($request->status==5){ $requirement->rate = null; $requirement->percentage = null; $requirement->save(); } $requirement->status = $request->status; $requirement->save(); if($request->has('type') && $request->type =="json"){ return response()->json([ 'status' => 'success', 'data'=>json_encode($requirement) ]); } return redirect()->route('requirements.index',['type'=>$request->type,'project_sel'=>$request->project_sel]); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Notification; use Auth; use Debugbar; use App\Invoice; class Project extends Model { // protected $fillable = ['name','description','budget','requirements']; public $timestamps = true; public function users(){ return $this->belongsToMany('App\User')->withTimestamps(); } public function requirements(){ return $this->hasMany('App\Requirement'); } public function milestones(){ return $this->hasMany('App\Milestone'); } public function notify($title , $message, $asset){ $id = Auth::id(); foreach ($this->users as $user){ if($user->id == $id){ continue; }if($user->id== 1){ continue; } Notification::create([ 'title'=>$title, 'message'=>$message." ".$this->name.".", 'priority'=>1, 'user_id'=>$user->id, 'asset'=>$asset, 'relation'=>'projects', 'relation_id'=>$this->id ]); } Notification::create([ 'title'=>$title, 'message'=>$message." ".$this->name.".", 'priority'=>1, 'user_id'=>1, 'asset'=>$asset, 'relation'=>'projects', 'relation_id'=>$this->id ]); } public function newFilesNotifications(\App\User $user = null){ return Notification::where('relation','projects') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->where('last_seen',null) ->get(); } public function markReadFilesNotifications(\App\User $user = null){ Notification::where('relation','projects') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->update([ 'last_seen' => \Carbon\Carbon::now() ]); } public function invoices(){ return $this->hasMany('\App\Invoice','project_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\Milestone; use App\Project; use Illuminate\Http\Request; use Carbon\Carbon; class MilestoneController extends Controller { public function __construct() { $this->middleware(['role:admin|project-manager']); $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Project $project) { // return view ('projects.milestones.index')->with(compact('project')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create(Project $project) { // $error_code = 5; return redirect()->back()->with('error_code', ['id'=>$project->id,'name'=>$project->name]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Project $project, Request $request) { // $request->validate([ 'dates'=>'required', 'percentages'=>'required' ]); $merged = array_combine($request->percentages, $request->dates); foreach($merged as $key => $value) { Milestone::create([ 'project_id'=>$project->id, 'percentage'=>(float)$key, 'due_to'=>Carbon::createFromFormat('m/d/Y', $value)->format('Y-m-d') ]); } $projects = Project::all(); return view('projects.index')->with(compact('projects')); } /** * Display the specified resource. * * @param \App\Milestone $milestone * @return \Illuminate\Http\Response */ public function show(Milestone $milestone) { // } /** * Show the form for editing the specified resource. * * @param \App\Milestone $milestone * @return \Illuminate\Http\Response */ public function edit(Milestone $milestone) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Milestone $milestone * @return \Illuminate\Http\Response */ public function update(Request $request, Milestone $milestone) { // } /** * Remove the specified resource from storage. * * @param \App\Milestone $milestone * @return \Illuminate\Http\Response */ public function destroy(Milestone $milestone) { // } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class EnquireOptions extends Model { // public $timestamps = true; protected $guarded = []; public function option(){ return $this->belongsTo('App\PackageOption','option_id'); } public function value(){ return $this->belongsTo('App\OptionValue','option_value_id'); } } <file_sep><?php namespace App\Listeners; use Jasekz\Laradrop\Events\FileWasUploaded; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Debugbar; use Jasekz\Laradrop\Models\File; use App\Requirement; use App\Project; class FileUploadSuccess { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param FileWasUploaded $event * @return void */ public function handle(FileWasUploaded $event) { // $file = $event->data["file"]; $object = json_decode($event->data["postData"]["customData"]); foreach($object->form as $input){ $file[$input->name] = $input->value; } $file->save(); switch($file['relation']){ case "projects": Project::find($file['relation_id'])->notify("New file added!!", "New file added on", "file"); Debugbar::info("notification projects"); break; case "requirement": Requirement::find($file['relation_id'])->notify("New file added!!", "New file added on", "file"); Debugbar::info("notification requirement"); break; } } } <file_sep><?php namespace App\Http\Controllers; use App\CalendarEvent; use Illuminate\Http\Request; use Auth; use Carbon\Carbon; class CalendarEventController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // // if(Auth::user()->hasAnyRole('admin')){ $tasks = CalendarEvent::all(); // }else{ // $tasks = CalendarEvent::where('user_id',Auth::id())->get(); // } return view('calendar.index')->with(compact('tasks')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $projects = Auth::user()->projects()->pluck('name','id'); return view('calendar.create')->with(compact('projects')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'description'=>'required', 'started_at'=>'required', 'ended_at'=>'required|after:started_at', ]); $timeEntry = CalendarEvent::create([ 'description'=>$request->description, 'started_at'=>Carbon::createFromFormat('m/d/Y H:i', $request->started_at), 'ended_at'=>Carbon::createFromFormat('m/d/Y H:i', $request->ended_at), 'user_id'=>Auth::id() ]); return redirect()->route('calendar.index'); } /** * Display the specified resource. * * @param \App\CalendarEvent $calendarEvent * @return \Illuminate\Http\Response */ public function show(CalendarEvent $calendarEvent) { // } /** * Show the form for editing the specified resource. * * @param \App\CalendarEvent $calendarEvent * @return \Illuminate\Http\Response */ public function edit(CalendarEvent $calendarEvent) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\CalendarEvent $calendarEvent * @return \Illuminate\Http\Response */ public function update(Request $request, CalendarEvent $calendarEvent) { // } /** * Remove the specified resource from storage. * * @param \App\CalendarEvent $calendarEvent * @return \Illuminate\Http\Response */ public function destroy(CalendarEvent $calendar) { // $calendar->delete(); return redirect()->back(); } } <file_sep><?php namespace App; use Jasekz\Laradrop\Models\File; use Illuminate\Database\Eloquent\Model; class Invoice extends Model { // protected $guarded = []; public function file(){ return File::where('relation_id',$this->id) ->where('relation','invoice') ->first(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Contact extends Model { // protected $guarded = []; public function city(){ return $this->belongsTo('\App\City','city_id'); } public function status(){ return $this->belongsTo('\App\ContactStatus','contact_status_id'); } public function contact_type(){ return $this->belongsTo('\App\ContactType','contact_type_id'); } } <file_sep><?php namespace App\Http\Controllers; use App\TimeEntry; use Illuminate\Http\Request; use Auth; use Carbon\Carbon; class TimeEntryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // if(Auth::user()->hasAnyRole('admin')){ $timeentries = TimeEntry::all(); }else{ $timeentries = TimeEntry::where('user_id',Auth::id())->get(); } return view('timeentries.index')->with(compact('timeentries')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $projects = Auth::user()->projects()->pluck('name','id'); return view('timeentries.create')->with(compact('projects')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'project_id'=>'required', 'hours'=>'required', 'minutes'=>'required', 'hourly_rate'=>'required' ]); $timeEntry = TimeEntry::create([ 'project_id'=>$request->project_id, 'hours'=>$request->hours + ($request->minutes /60), 'hourly_rate'=>$request->hourly_rate, 'user_id'=>Auth::id() ]); return redirect()->route('timetracking.index'); } /** * Display the specified resource. * * @param \App\TimeEntry $timeEntry * @return \Illuminate\Http\Response */ public function show(TimeEntry $timeEntry) { // } /** * Show the form for editing the specified resource. * * @param \App\TimeEntry $timeEntry * @return \Illuminate\Http\Response */ public function edit(TimeEntry $timeEntry) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\TimeEntry $timeEntry * @return \Illuminate\Http\Response */ public function update(Request $request, TimeEntry $timeEntry) { // } /** * Remove the specified resource from storage. * * @param \App\TimeEntry $timeEntry * @return \Illuminate\Http\Response */ public function destroy(TimeEntry $timetracking) { // $timetracking->delete(); return redirect()->back(); } } <file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); var browserSync = require('browser-sync').create(); var header = require('gulp-header'); var cleanCSS = require('gulp-clean-css'); var pug = require('gulp-pug'); var rename = require("gulp-rename"); var uglify = require('gulp-uglify'); var beautify = require('gulp-html-beautify'); var pkg = require('./package.json'); var gutil = require('gulp-util') var pngquant = require('imagemin-pngquant'); var $ = require('gulp-load-plugins')(); // Set the banner content var banner = ['/*!\n', ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n', ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n', ' * Licensed under <%= pkg.license %> (https://github.com/BlackrockDigital/<%= pkg.name %>/blob/master/LICENSE)\n', ' */\n', '' ].join(''); gulp.task('sass', function() { gulp.src('resources/assets/sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('public/css/')); }); // Minify compiled CSS gulp.task('minify-css', ['sass'], function() { return gulp.src('public/css/app.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('public/css')) }); // Minify custom JS gulp.task('minify-js', function() { return gulp.src(['resources/assets/js/**/*.js', '!resources/assets/js/**/*.min.js']) .pipe(uglify()) .on('error', function (err) { gutil.log(gutil.colors.red('[Error]'), err.toString()); }) .pipe(header(banner, { pkg: pkg })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('public/js')) }); // Copy vendor files from /node_modules into /vendor // NOTE: requires `npm install` before running! gulp.task('copy', function() { gulp.src([ 'node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map' ]) .pipe(gulp.dest('public/vendor/bootstrap')) gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js']) .pipe(gulp.dest('public/vendor/jquery')) gulp.src(['node_modules/popper.js/dist/umd/popper.js', 'node_modules/popper.js/dist/umd/popper.min.js']) .pipe(gulp.dest('public/vendor/popper')) gulp.src(['node_modules/jquery.easing/*.js']) .pipe(gulp.dest('public/vendor/jquery-easing')) gulp.src([ 'node_modules/font-awesome/**', '!node_modules/font-awesome/**/*.map', '!node_modules/font-awesome/.npmignore', '!node_modules/font-awesome/*.txt', '!node_modules/font-awesome/*.md', '!node_modules/font-awesome/*.json' ]) .pipe(gulp.dest('public/vendor/font-awesome')) gulp.src(['node_modules/chart.js/dist/*.js']) .pipe(gulp.dest('public/vendor/chart.js')) gulp.src([ 'node_modules/datatables.net/js/*.js', 'node_modules/datatables.net-bs4/js/*.js', 'node_modules/datatables.net-bs4/css/*.css' ]) .pipe(gulp.dest('public/vendor/datatables/')) gulp.src([ 'node_modules/sweetalert2/dist/*.js', 'node_modules/sweetalert2/dist/*.css', ]) .pipe(gulp.dest('public/vendor/sweetalert2/')) gulp.src([ 'node_modules/lightbox2/dist/css/*.js', 'node_modules/lightbox2/dist/js/*.css', ]) .pipe(gulp.dest('public/vendor/lightbox/')) }) // Compress images gulp.task('images', function () { return ( gulp .src('resources/assets/img/*') .pipe($.imagemin([ $.imagemin.jpegtran({progressive: true}), $.imagemin.optipng({use: [pngquant()]}), $.imagemin.svgo({plugins: [{removeViewBox: true}]}), ])) .pipe(gulp.dest('public/img')) ); }); // Default task gulp.task('default', ['copy', 'sass', 'minify-css', 'minify-js', 'images']); // Dev task with browserSync gulp.task('dev', ['sass', 'minify-css', 'minify-js'], function() { gulp.watch('scss/**/*', ['sass']); gulp.watch('public/css/*.css', ['minify-css']); gulp.watch('public/js/*.js', ['minify-js']); });<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! | */ Route::get('/home', 'HomeController@index')->name('home')->middleware('auth'); Auth::routes(); Route::get('/',[ 'uses'=> 'HomeController@index', 'as'=>'index' ])->name('packages'); Route::get('/projects/export',[ 'uses'=>'ProjectController@exportRequirements', 'as'=>'project.export' ]); Route::resource('projects','ProjectController'); Route::resource('projects.milestones','MilestoneController'); Route::post('requirements/updateRate/{requirement}',[ 'uses'=>'RequirementController@updateRate', 'as'=>'requirements.updateRate' ]); Route::post('requirements/updatePercentage/{requirement}',[ 'uses'=>'RequirementController@updatePercentage', 'as'=>'requirements.updatePercentage' ]); Route::post('requirements/status/{requirement}',[ 'uses'=>'RequirementController@changeStatus', 'as'=>'requirements.status' ]); Route::resource('requirements','RequirementController'); Route::resource('bugs','RequirementController'); Route::post('users/endis/{user}',[ 'uses'=>'UserController@endis', 'as'=>'users.endis' ]); Route::resource('users','UserController'); Route::resource('payments','PaymentController'); Route::get('notifications/display',[ 'uses'=>'NotificationController@display', 'as'=>'notifications.display' ]); Route::post('notifications/check',[ 'uses'=>'NotificationController@check', 'as'=>'notifications.check' ]); Route::get('notifications/list/{user}',[ 'uses'=>'NotificationController@listNotifications', 'as'=>'notifications.list' ]); Route::resource('notifications','NotificationController'); Route::resource('requirements.questions','QuestionController'); Route::group(['middleware' => config('laradrop.middleware') ? config('laradrop.middleware') : null], function () { Route::get('laradrop/containers', [ 'as' => 'laradrop.containers', 'uses' => '\Jasekz\Laradrop\Http\Controllers\LaradropController@getContainers' ]); Route::post('laradrop/move', [ 'as' => 'laradrop.move', 'uses' => '\Jasekz\Laradrop\Http\Controllers\LaradropController@move' ]); Route::post('laradrop/create', [ 'as' => 'laradrop.create', 'uses' => '\Jasekz\Laradrop\Http\Controllers\LaradropController@create' ]); Route::resource('laradrop', '\Jasekz\Laradrop\Http\Controllers\LaradropController'); }); Route::post('files/create/{relation}/{relation_id}',[ 'uses'=>'FileController@createPost', 'as'=>'files.createPost' ]); Route::get('files/show/{file}',[ 'uses'=>'FileController@show', 'as'=>'files.show' ]); Route::get('files/{relation}/{relation_id}',[ 'uses'=>'FileController@index', 'as'=>'files.index' ]); Route::post('files',[ 'uses'=>'FileController@store', 'as'=>'files.store' ]); Route::post('files/update/{file}',[ 'uses'=>'FileController@update', 'as'=>'files.update' ]); Route::delete('files/destroy/{file}',[ 'uses'=>'FileController@destroy', 'as'=>'files.destroy' ]); Route::resource('/requirement/names','RequirementNameController'); Route::get('/proposal/export/{proposal}',[ 'uses'=>'ProposalController@export', 'as'=>'proposal.export' ]); Route::resource('/proposal','ProposalController'); Route::get('/budgets/{budget}/export',[ 'uses'=>'BudgetController@export', 'as'=>'budgets.export' ]); Route::resource('/budgets','BudgetController'); Route::get('/customizer',[ 'uses'=>'PackageController@index', 'as'=>'customizer' ]); Route::resource('/packages','PackageController'); Route::resource('/options','PackageOptionController'); Route::resource('/values','OptionValueController'); Route::resource('/enquires','EnquireController'); Route::resource('/contacts','ContactController'); Route::resource('/catalogs','CatalogController'); Route::resource('/cities','CityController'); Route::resource('/countries','CountryController'); Route::resource('/contacts/status','ContactStatusController'); Route::resource('/contact/types','ContactTypeController'); Route::get('/invoices/list/{project}/{developer}',[ 'uses'=>'InvoiceController@invoicesList', 'as'=>'invoices.list' ]); Route::resource('/invoices','InvoiceController'); Route::resource('/timetracking','TimeEntryController'); Route::resource('/calendar','CalendarEventController');<file_sep><?php namespace App\Http\Controllers; use App\Package; use Illuminate\Http\Request; use Debugbar; class PackageController extends Controller { public function __construct() { $this->middleware('auth')->except('index','show'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $packages = Package::all(); return view('packages.index')->with(compact('packages')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $packages = Package::all(); return view('packages.create')->with(compact('packages')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'name'=>'required', 'description'=>'required' ]); $package = Package::create([ 'name'=>$request->name, 'description'=>$request->description ]); if($request->ajax()){ return response()->json([ 'id'=>$package->id, 'name'=>$package->name ],201); } return $package; } /** * Display the specified resource. * * @param \App\Package $package * @return \Illuminate\Http\Response */ public function show(Package $package) { // return view('packages.show')->with(compact('package')); } /** * Show the form for editing the specified resource. * * @param \App\Package $package * @return \Illuminate\Http\Response */ public function edit(Package $package) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Package $package * @return \Illuminate\Http\Response */ public function update(Request $request, Package $package) { // } /** * Remove the specified resource from storage. * * @param \App\Package $package * @return \Illuminate\Http\Response */ public function destroy(Package $package,Request $request) { // Debugbar::info($package); if($request->ajax() && $package->delete()){ return response()->json([ 'message'=>'success' ],201); }else{ $package->delete(); } return back(); } } <file_sep><?php namespace App\Http\Controllers; use App\ContactType; use Illuminate\Http\Request; class ContactTypeController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view ('types.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'name'=>'required|unique:contact_types' ]); ContactType::create([ 'name'=>$request->name ]); //return back(); return redirect()->route('catalogs.index'); } /** * Display the specified resource. * * @param \App\ContactType $contactType * @return \Illuminate\Http\Response */ public function show(ContactType $contactType) { // } /** * Show the form for editing the specified resource. * * @param \App\ContactType $contactType * @return \Illuminate\Http\Response */ public function edit(ContactType $contactType) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\ContactType $contactType * @return \Illuminate\Http\Response */ public function update(Request $request, ContactType $contactType) { // } /** * Remove the specified resource from storage. * * @param \App\ContactType $contactType * @return \Illuminate\Http\Response */ public function destroy(ContactType $type) { // $type->delete(); return back(); } } <file_sep><?php namespace App\Http\Controllers; use App\Notification; use App\User; use Illuminate\Http\Request; use Auth, Session; class NotificationController extends Controller { public function __construct() { /* $this->middleware(['role:admin|client']); */ $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $notifications = Notification::all(); return view('notifications.index')->with(compact('notifications')); } public function listNotifications(User $user){ $notifications = $user->notifications()->OrderBy('created_at','DESC')->get(); return view('notifications.list')->with(compact('notifications')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $users = User::role('client')->pluck('email','id'); return view('notifications.create')->with(compact('users')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $request->validate([ 'users'=>'required', 'title'=>'required|max:25', 'priority'=>'required', 'message'=>'required|max:50' ]); foreach($request->users as $userid){ Notification::create([ 'title'=>$request->title, 'message'=>$request->message, 'priority'=>$request->priority, 'user_id'=>$userid ]); } return redirect()->route('notifications.index'); } /** * Display the specified resource. * * @param \App\Notification $notification * @return \Illuminate\Http\Response */ public function show(Notification $notification) { // } /** * Show the form for editing the specified resource. * * @param \App\Notification $notification * @return \Illuminate\Http\Response */ public function edit(Notification $notification) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Notification $notification * @return \Illuminate\Http\Response */ public function update(Request $request, Notification $notification) { // } /** * Remove the specified resource from storage. * * @param \App\Notification $notification * @return \Illuminate\Http\Response */ public function destroy(Notification $notification) { // $notification->delete(); return back(); } public function check(Request $request){ $request->validate([ 'id'=>'required' ]); if(Auth::user()){ $notification = Notification::find($request->id); $notification->last_seen = \Carbon\Carbon::now(); $notification->save(); } } } <file_sep># task4it-manager Task4it Manager es un programa para administrar una agencia de freelancers, puede registrar proyectos, nuevos features y bugs. También puede registrar clientes para asignarles proyectos y usuarios para realizar una asignación de features y bugs a developers. ![alt text](https://github.com/Alejandroem/task4it-manager/blob/master/readme/task4it.png) ## SonarQube Análisis ### Overview del proyecto ![alt text](https://github.com/Alejandroem/task4it-manager/blob/master/readme/sonarcube-overview.png) ### Bugs detectados por sonarcube: El análisis de sonar cube no detectó una cantidad alarmante de bugs dentro del proyecto, los issues detectados están relacionados con código inalcanzable. ![alt text](https://github.com/Alejandroem/task4it-manager/blob/master/readme/sonarcube-bugs.png) ### KPI Code Mantainability: El KPI de Code Mantainability revela bastante información sobre una situación de la vida real relacionada al proyecto, a menudo que el proyecto iba creciendo el código se hacía más difícil de mantener, debido a que este fue un proyecto que no contaba con un proceso formal para desarrollar pruebas, el proyecto se desarolló como un pipeline de código y ver el KPI de sonarcube de mantenaibility ha reflejado lo que sucede en el proceso de desarrollo. ![alt text](https://github.com/Alejandroem/task4it-manager/blob/master/readme/sonarcube-maintainability.png) <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; class Question extends Model { // protected $guarded=[]; public function requirement(){ return $this->belongsTo('App\Requirement'); } public function questions(){ return $this->hasMany('App\Question'); } public function user(){ return $this->belongsTo('App\User'); } public function parent(){ return $this->belongsTO('App\Question'); } public function notify(){ $string = $this->requirement->type ==="bugs"? "bug": "requirement"; $id = Auth::id(); foreach ($this->requirement->project->users as $user){ if($user->id == $id){ continue; } Notification::create([ 'title'=>"New question added!!!", 'message'=>"New question added on ".$string." ".$this->requirement->title, 'priority'=>1, 'user_id'=>$user->id, 'asset'=>'question', 'relation'=>'requirement', 'relation_id'=>$this->requirement->id ]); } Notification::create([ 'title'=>"New question added!!!", 'message'=>"New question added on ".$string." ".$this->requirement->title, 'priority'=>1, 'user_id'=>1, 'asset'=>'question', 'relation'=>'requirement', 'relation_id'=>$this->requirement->id ]); /* foreach ($this->requirement->project->users as $user){ Notification::create([ 'title'=>"New question added on ".$string." ".$this->requirement->title, 'message'=>"1", 'priority'=>1, 'user_id'=>$user->id, 'asset'=>'question', 'relation'=>'questions', 'relation_id'=>$this->id ]); } Notification::create([ 'title'=>"New question added on ".$string." ".$this->requirement->title, 'message'=>"1", 'priority'=>1, 'user_id'=>1, 'asset'=>'question', 'relation'=>'questions', 'relation_id'=>$this->id ]); */ } } <file_sep><?php namespace App\Http\Controllers; use App\Project; use App\Requirement; use App\User; use Illuminate\Http\Request; use Auth, Purifier; use Spatie\Permission\Models\Role; use Debugbar; class ProjectController extends Controller { public function __construct() { $this->middleware(['role:admin|project-manager|client|developer']); $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // if (Auth::user()->hasAnyRole('admin')) { $projects = Project::all(); } else { $projects = Project::whereHas('users', function ($q) { $q->where('id', Auth::id()); })->get(); } return view('projects.index')->with(compact('projects')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // $project = new Project(); if (Auth::user()->hasRole('admin')) { $roles = Role::all()->pluck('display_name', 'name'); } elseif (Auth::user()->hasRole('project-manager')) { $roles = Role::where('level', '>', Auth::user()->roles->first()->level) ->pluck('display_name', 'name'); } if (Auth::user()->hasRole('admin')) { $users = User::all()->pluck('email','id'); }else{ $users = User::whereHas('roles',function($q){ $q->where('level','>',Auth::user()->roles->first()->level); })->get()->pluck('email','id'); } if (Auth::user()->hasRole('admin')) { $project_users = $project->users->pluck('email','id'); }else{ $project_users = $project->users()->whereHas('roles',function($q){ $q->where('level','>=',Auth::user()->roles->first()->level); })->get()->pluck('email','id'); } $clients = User::role('client')->pluck('email','id'); return view('projects.create')->with(compact('project', 'users', 'roles','project_users','clients')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // // dd($request->input()); $user = null; $request->validate([ 'name' => 'required|max:50', 'description' => 'required', 'budget'=>'required|numeric|min:0', 'charge_to'=>'required' ]); if ($request->toogle_user==='on') { $request->validate([ 'username' => 'required|max:50', 'email' => 'required', 'password' => '<PASSWORD>', 'role' => 'required', ]); $user = User::create([ 'name'=>$request->username, 'email'=>$request->email, 'password'=>$request->password ]); $user->assignRole($request->role); } else { $request->validate([ 'user' => 'required' ]); $user = User::find($request->user); } $project = Project::create([ 'name'=>$request->name, 'description'=>$request->description, 'budget'=>$request->budget, 'requirements'=>$request->has('requirements-list')?$request->get('requirements-list'):"" ]); $user->projects()->attach($project->id); $client = User::find($request->charge_to); $client->balance+=$project->budget; $client->save(); $project->users()->attach($request->users); $project->notify("New project created!!","You are asigned to project ","project_creation"); return redirect()->route('projects.index'); } /** * Display the specified resource. * * @param \App\Project $project * @return \Illuminate\Http\Response */ public function show(Project $project) { // $pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0'; if(!$pageWasRefreshed ) { $project->markReadFilesNotifications(); } return view ('projects.show')->with(compact('project')); } /** * Show the form for editing the specified resource. * * @param \App\Project $project * @return \Illuminate\Http\Response */ public function edit(Project $project) { // if (Auth::user()->hasRole('admin')) { $users = User::all()->pluck('email','id'); }else{ $users = User::whereHas('roles',function($q){ $q->where('level','>=',Auth::user()->roles->first()->level); })->get()->pluck('email','id'); } if (Auth::user()->hasRole('admin')) { $project_users = $project->users->pluck('email','id'); }else{ $project_users = $project->users()->whereHas('roles',function($q){ $q->where('level','>=',Auth::user()->roles->first()->level); })->get()->pluck('email','id'); } return view('projects.edit')->with(compact('project', 'users','project_users')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Project $project * @return \Illuminate\Http\Response */ public function update(Request $request, Project $project) { // $request->validate([ 'name'=>'required', 'description' => 'required', 'budget'=>'required|numeric|min:0' ]); $project->name = $request->name; $project->description=$request->description; $project->budget = $request->budget; $project->requirements = $request->has('requirements-list')?$request->get('requirements-list'):" "; $project->save(); $project->users()->sync($request->users); $project->users()->attach($request->newUsers); return redirect()->route('projects.index'); } public function exportRequirements(Request $request){ Debugbar::info($request->input()); $request->validate([ 'message'=>'required' ]); $requirements = json_decode($request->message); $total = 0; foreach($requirements as $requirement){ $total+= floatval($requirement->rate); } Debugbar::info($requirements); $view = \View::make('pdf.requirements', compact('requirements', 'total'))->render(); $pdf = \App::make('dompdf.wrapper'); $pdf->loadHTML($view); return $pdf->download('invoice'); } /** * Remove the specified resource from storage. * * @param \App\Project $project * @return \Illuminate\Http\Response */ public function destroy(Project $project) { // $project->delete(); return back(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Jasekz\Laradrop\Models\File; class OptionValue extends Model { // public $timestamps = true; protected $guarded = []; public function image(){ return File::where('relation_id',$this->id) ->where('relation','option-value') ->first(); } } <file_sep><?php namespace App; use App\Project; use App\User; use Illuminate\Database\Eloquent\Model; class TimeEntry extends Model { // protected $guarded = []; protected $dates = [ 'created_at', 'updated_at', 'started_at', 'ended_at' ]; public function project(){ return $this->belongsTo('\App\Project','project_id'); } public function user(){ return $this->belongsTo('\App\User','user_id'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Auth; class Requirement extends Model { // public $timestamps = true; protected $dates = ['due_to']; protected $fillable = ['type','project_id','user_id','title','description','priority','due_to']; protected $appends = ['total']; public function project(){ return $this->belongsTo('App\Project'); } public function questions(){ return $this->hasMany('App\Question'); } public function getTotalAttribute() { return $this->rate * ($this->percentage/100) + $this->rate; } public function notify($title , $message, $asset){ $string = $this->type ==="bugs"? "bug": "requirement"; $id = Auth::id(); foreach ($this->project->users as $user){ if($user->id == $id){ continue; }if($user->id== 1){ continue; } Notification::create([ 'title'=>$title, 'message'=>$message." " .$string . " " . $this->title, 'priority'=>1, 'user_id'=>$user->id, 'asset'=>$asset, 'relation'=>'requirement', 'relation_id'=>$this->id ]); } Notification::create([ 'title'=>$title, 'message'=>$message." " .$string . " " . $this->title, 'priority'=>1, 'user_id'=>1, 'asset'=>$asset, 'relation'=>'requirement', 'relation_id'=>$this->id ]); } public function newFilesNotifications(\App\User $user = null){ return Notification::where('relation','requirement') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->where('last_seen',null) ->get() ->count(); } public function markReadFilesNotifications(\App\User $user = null){ Notification::where('relation','requirement') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->update([ 'last_seen' => \Carbon\Carbon::now() ]); } public function newQuestionsNotifications(\App\User $user = null){ $questionsId = $this->questions()->pluck('id'); $count = Notification::where('relation','questions') ->whereIn('relation_id',$questionsId) ->where('user_id',isset($user)?$user->id : Auth::id()) ->where('last_seen',null) ->get() ->count(); $count += Notification::where('asset','question') ->where('relation','requirement') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->where('last_seen',null) ->get() ->count(); return $count; } public function markReadQuestionsNotifications(\App\User $user = null){ $questionsId = $this->questions()->pluck('id'); Notification::where('relation','questions') ->whereIn('relation_id',$questionsId) ->where('user_id',isset($user)?$user->id : Auth::id()) ->update([ 'last_seen' => \Carbon\Carbon::now() ]); Notification::where('asset','question') ->where('relation','requirement') ->where('relation_id',$this->id) ->where('user_id',isset($user)?$user->id : Auth::id()) ->update([ 'last_seen' => \Carbon\Carbon::now() ]); } } <file_sep><?php use Illuminate\Database\Seeder; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; class UserRolesPermissionSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // app()['cache']->forget('spatie.permission.cache'); Role::create(['name' => 'admin','display_name'=>'Administrator','level'=>1]); Role::create(['name' => 'project-manager','display_name'=>'Project Manager','level'=>2]); Role::create(['name' => 'developer','display_name'=>'Developer','level'=>3]); Role::create(['name' => 'client','display_name'=>'Client','level'=>4]); Permission::create(['name' => 'create']); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Requirement; use App\Project; use App\Question; class Notification extends Model { // public $timestamps = true; protected $guarded = []; protected $appends = ['type','url']; protected $dates = [ 'created_at', 'updated_at', 'last_seen' ]; public function user(){ return $this->belongsTo('App\User'); } public function getUrlAttribute(){ switch($this->relation){ case "requirement": $requirement = null; if($this->relation=="questions"){ $requirement = Question::find($this->relation_id)->requirement; }else if($this->relation=="requirement"){ $requirement = Requirement::find($this->relation_id); } if(!$requirement){ return ""; } if($this->asset=="file" || $this->asset=="requirement_creation" || $this->asset=="requirement_budget"){ return "".route('requirements.show',['requirement'=>$requirement->id,'type'=>$requirement->type,'project_sel'=>""]); }else if($this->asset=="question"){ return "".route('requirements.questions.index',['requirement'=>$requirement->id]); } return "".route('requirements.questions.index',['requirement'=>1]); case "projects": $project = Project::find($this->relation_id); if(!$project){ return ""; } if($this->asset=="file"){ return "".route('projects.show',['id'=>$project->id]); }else if($this->asset=="project_creation"){ return "".route('projects.show',['id'=>$project->id]); } } } public function getTypeAttribute(){ switch($this->priority){ case 0: return "alert-primary"; case 1: return "alert-success"; case 2: return "alert-danger"; case 3: return "alert-warning"; } } } <file_sep><?php namespace App\Http\Controllers; use App\PackageOption; use Illuminate\Http\Request; use Debugbar; class PackageOptionController extends Controller { public function __construct() { $this->middleware('auth'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // return "index"; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return "create"; } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ 'name'=>'required', 'parent'=> 'required' ]); $option = PackageOption ::create([ 'subject'=>$request->name, 'package_id'=>$request->parent ]); if($request->ajax()){ return response()->json([ 'id'=>$option->id, 'name'=>$option->subject ],201); } return $option; } /** * Display the specified resource. * * @param \App\PackageOption $packageOption * @return \Illuminate\Http\Response */ public function show(PackageOption $packageOption) { // return "show"; } /** * Show the form for editing the specified resource. * * @param \App\PackageOption $packageOption * @return \Illuminate\Http\Response */ public function edit(PackageOption $packageOption) { // return "edit"; } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\PackageOption $packageOption * @return \Illuminate\Http\Response */ public function update(Request $request, PackageOption $option) { // if($request->has('multiple')){ $option->multiple = $request->multiple; } if($request->ajax() && $option->save()){ return response()->json([ 'message'=>'success' ],201); }else{ $option->save(); } return back(); } /** * Remove the specified resource from storage. * * @param \App\PackageOption $packageOption * @return \Illuminate\Http\Response */ public function destroy(PackageOption $option,Request $request) { // Debugbar::info($option); if($request->ajax() && $option->delete()){ return response()->json([ 'message'=>'success' ],201); }else{ $option->delete(); } return $option; return back(); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Project; use App\Requirement; use Jasekz\Laradrop\Models\File; class Payment extends Model { // public $timestamps = true; protected $guarded = []; protected $appends = [/* 'assetName', */'attachment']; /* public function getAssetNameAttribute() { switch($this->asset){ case "project": return Project::where('id',$this->asset_id)->first()->name; break; case "requirement": case "bug": return Requirement::where('id',$this->asset_id)->where('type',$this->asset)->first()->title; break; } } */ public function user(){ return $this->belongsTo('App\User'); } public function getAttachmentAttribute(){ return File::where('relation','payment')->where('relation_id',$this->id)->first(); } }
e07fd8109a8226f52bb12a20050691fac963f34a
[ "JavaScript", "Markdown", "PHP" ]
45
PHP
Alejandroem/task4it-manager
913d5605ca163aba8ac52fdeabddb1846be8e0c8
c2f5f6f1acd5b1839cf3b4be86b8611a77f2ef76
refs/heads/master
<repo_name>Naxaes/simple-metronome-pygame<file_sep>/main.py import pygame SOUND_BUFFER_SIZE = 1024 SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 400, 400 FPS_CAP = 60 TITLE_FONT_SIZE = 16 TITLE_FONT_NAME = 'Courier New' # Who doesn't prefer monospace fonts?? COLOR_BLACK = (0, 0, 0) COLOR_WHITE = (255, 255, 255) COLOR_GREEN = (0, 255, 0) BACKGROUND_COLOR = COLOR_BLACK TEXT_COLOR = COLOR_WHITE DOT_COLOR = COLOR_GREEN # The buffer for the mixer is too large for my computer, which makes the latency to big. # This initializes the buffer to 1024 instead of 4096 (they've changed this default quite a lot). # The rest are the default values. # https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.pre_init pygame.mixer.pre_init(buffer=SOUND_BUFFER_SIZE) pygame.init() font = pygame.font.SysFont(TITLE_FONT_NAME, TITLE_FONT_SIZE) screen = pygame.display.set_mode(SCREEN_SIZE) dot_timer = 0 # Keeps track on how long the dot has been displayed. display_dot = False # Whether to display the dot or not. bpm = 120 clock = pygame.time.Clock() sound = pygame.mixer.Sound('bop.wav') time = 0 running = True while running: dt = clock.tick(FPS_CAP) time += dt for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: bpm -= 5 elif event.key == pygame.K_RIGHT: bpm += 5 # Calculate how long to wait based on the bpm. beats_per_ms = (bpm / 60) / 1000 ms_per_beat = 1 / beats_per_ms # How many milliseconds each beat takes. if time >= ms_per_beat: time -= ms_per_beat sound.play() display_dot = True dot_timer = ms_per_beat * 0.75 screen.fill(BACKGROUND_COLOR) text_surface = font.render('BPM {}'.format(bpm), True, TEXT_COLOR) screen.blit(text_surface, (160, 20)) if display_dot: dot_timer -= dt if dot_timer <= 0: display_dot = False pygame.draw.circle(screen, DOT_COLOR, (200, 200), 20) pygame.display.update() <file_sep>/README.md # Simple Metronome A simple metronome example made with Python3 and Pygame.
369297144479f0ce98e1ec65d5086e1aed0c16de
[ "Markdown", "Python" ]
2
Python
Naxaes/simple-metronome-pygame
e2c76822e5446cdbfc67c7e60caa247f6c2dd51d
adc65fad87459eeb93a0e65ff139599796ce982c
refs/heads/main
<repo_name>Themion/-Assignment<file_sep>/머신러닝/11주차 과제/CifarNet.py # -*- coding: utf-8 -*- """ Created on Sun May 31 20:38:03 2020 @author: RML """ import torch import torchvision.models as models def _cifarnet(pretrained = False, path = None): model = models.resnext101_32x8d() if pretrained: state_dict = torch.load(path) model.load_state_dict(state_dict) return model <file_sep>/컴퓨터 그래픽스 및 비전/190502/190502_test.py import numpy as np import cv2 def emptyFunction(x): pass def main(): ori = cv2.imread("number.jpg", 0) windowName = "Lines" cv2.namedWindow(windowName) cv2.createTrackbar('Thres1', windowName, 755, 2000, emptyFunction) cv2.createTrackbar('Thres2', windowName, 1000, 2000, emptyFunction) cv2.createTrackbar('THR', windowName, 100, 200, emptyFunction) cv2.createTrackbar('Length', windowName, 50, 100, emptyFunction) while(True): thres1 = cv2.getTrackbarPos('Thres1', windowName) thres2 = cv2.getTrackbarPos('Thres2', windowName) thr = cv2.getTrackbarPos('THR', windowName) lth = cv2.getTrackbarPos('Length', windowName) if(thres1 > thres2): thres1, thres2 = thres2, thres1 #흰색 번호판 추출 및 중간값 블러링 #salt & pepper 오류 제거 img = cv2.inRange(ori, 240, 255) img = cv2.medianBlur(img, 5) #Contour를 이용해 번호판 안쪽 공간을 모두 메운다 contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for i in range(0, len(contours)): cv2.drawContours(img, contours, i, 255, -1) #열기 기법으로 번호판이 아닌 큰 덩어리를 제거 kernel = np.ones((11, 11), np.uint8) img = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel) #캐니 에지 - 허프 라인으로 번호판의 에지 탐색 #필요하다면 HpoughLineP를 HoughLine으로 바꿈 img = cv2.Canny(img, thres1, thres2, None, 3) hough = cv2.HoughLinesP(img, 1, np.pi/180, thr, minLineLength = lth, maxLineGap=10) if hough is not None: for line in hough: for x1, y1, x2, y2 in line: cv2.line(img, (x1, y1), (x2, y2), 127, 3) #제대로 된 에지를 찾았을 경우 각 선분 간의 교점으로 네 점을 찾아야 함 cv2.imshow(windowName, img) if cv2.waitKey(1) & 0xFF == 27: cv2.destroyAllWindows() break if __name__ == "__main__": main() <file_sep>/컴퓨터 그래픽스 및 비전/190404/190404.py import cv2 import numpy as np import math def main(): size = 1 mode = 3 kernel = cv2.getGaussianKernel(size, (0.3*((size-1)*0.5 - 1) + 0.8)) def callback_size(x): nonlocal size nonlocal kernel size = x*2+1 kernel = cv2.getGaussianKernel(size, (0.3*((size-1)*0.5 - 1) + 0.8)) img_remake() def callback_mode(x): nonlocal mode mode = x img_remake() original = cv2.imread('L1.png') img = cv2.imread('L2.png') def img_remake(): nonlocal size nonlocal mode nonlocal kernel print (mode, size) filt = cv2.filter2D(img, -1, kernel) blur = cv2.blur(img, (size, size)) gau = cv2.GaussianBlur(img, (size, size), 0) med = cv2.medianBlur(img, size) err = [0, 0, 0, 0] err[0] = np.sum(abs(original - filt)) / (img.shape[0]*img.shape[1]) err[1] = np.sum(abs(original - blur)) / (img.shape[0]*img.shape[1]) err[2] = np.sum(abs(original - gau)) / (img.shape[0]*img.shape[1]) err[3] = np.sum(abs(original - med)) / (img.shape[0]*img.shape[1]) print(err) #Convolution if mode==0: cv2.imshow("image", np.hstack([original, img, filt])) #kernel: kernel array #Average elif mode==1: cv2.imshow("image", np.hstack([original, img, blur])) #(k, k): kernel shape #Gaussian elif mode==2: cv2.imshow("image", np.hstack([original, img, gau])) # 0: how to determine variance #Median else : cv2.imshow("image", np.hstack([original, img, med])) #print ((np.sum(original) - np.sum(blur))/(original.shape[0]*original.shape[1]*3)) #cv2.imshow('image', blur) cv2.namedWindow('image') cv2.createTrackbar('Size', 'image', 0, 5, callback_size) cv2.createTrackbar('Filter', 'image', mode, 3, callback_mode) cv2.imshow("image", np.hstack([original, img, img])) if __name__ == "__main__": main() <file_sep>/컴파일러/7주차 과제/과제 4 - Parser - 2016125052/Parser/Parser.java package Parser; import java.util.*; public class Parser { // Recursive descent parser that inputs a C++Lite program and // generates its abstract syntax. Each method corresponds to // a concrete syntax grammar rule, which appears as a comment // at the beginning of the method. Token token; // current token from the input stream Lexer lexer; static TreeNode root, handler; public Parser(Lexer ts) { // Open the C++Lite source program lexer = ts; // as a token stream, and token = lexer.next(); // retrieve its first Token } private String match (TokenType t) { // * return the string of a token if it matches with t * String value = token.value(); if (token.type().equals(t)) token = lexer.next(); else if(t == TokenType.Semicolon) { token = lexer.next(); match(t); } else error(t); return value; } private void error(TokenType tok) { error(tok.toString()); } private void error(String tok) { System.err.println("Syntax error: expecting: " + tok + "; saw: " + token); root.print(); System.exit(1); } public Program program() { // Program --> void main ( ) '{' Declarations Statements '}' TokenType[ ] header = {TokenType.Int, TokenType.Main, TokenType.LeftParen, TokenType.RightParen}; for (int i = 0; i<header.length; i++) // bypass "int main ( )" match(header[i]); root = new TreeNode("int main(): "); handler = root; match(TokenType.LeftBrace); Declarations ds = declarations(); Block ss = statements(); match(TokenType.RightBrace); return new Program(ds, ss); // student exercise } private Declarations declarations () { // Declarations --> { Declaration } Declarations ds = new Declarations(); TreeNode adder = new TreeNode("Declarations: "); handler.addChild(adder); handler = handler.get(handler.size() - 1); while(isType()) declaration(ds); handler = handler.getParent(); return ds; // student exercise } private void declaration (Declarations ds) { // Declaration --> Type Identifier { , Identifier } ; Type t = type(); while(token.type() != TokenType.Eof) { Variable v = new Variable(token.value()); match(TokenType.Identifier); TreeNode adder = new TreeNode("Declaration: "); adder.addChild("Type: " + t.toString()); ds.add(new Declaration(v, t)); adder.addChild("Variable: " + v.toString()); handler.addChild(adder); if(token.type() == TokenType.Comma) match(TokenType.Comma); else if(token.type() == TokenType.Semicolon){ match(TokenType.Semicolon); if(isType()) t = type(); else break; } } // student exercise } private Type type () { // Type --> int | bool | float | char Type t = null; if(token.type() == TokenType.Int) t = Type.INT; else if(token.type() == TokenType.Bool) t = Type.BOOL; else if(token.type() == TokenType.Float) t = Type.FLOAT; else if(token.type() == TokenType.Char) t = Type.CHAR; else error("Current token not type (current token: " + token + ")"); match(token.type()); // student exercise return t; } private Statement statement () { // Statement --> ; | Block | Assignment | IfStatement | WhileStatement Statement s = null; if(token.type() == TokenType.Semicolon) s = new Skip(); else if (token.type() == TokenType.If) s = ifStatement(); else if (token.type() == TokenType.While) s = whileStatement(); else if (token.type() == TokenType.LeftBrace) { match(TokenType.LeftBrace); Block bl = statements(); match(TokenType.RightBrace); s = bl; } else if(token.type() == TokenType.Identifier){ Variable name = new Variable(token.value()); match(TokenType.Identifier); s = assignment(name); } else error("Unknown statement type: " + token.value()); // student exercise return s; } private Block statements () { // Block --> '{' Statements '}' Block b = new Block(); TreeNode adder = new TreeNode("Statements: "); handler.addChild(adder); handler = handler.get(handler.size() - 1); while ((token.type() != TokenType.RightBrace) && (token.type() != TokenType.Eof)) b.members.add(statement()); handler = handler.getParent(); return b; // student exercise } private Assignment assignment (Variable i) { // Assignment --> Identifier = Expression ; TreeNode adder = new TreeNode("="); adder.addChild("Variable: " + i.toString()); adder.addChild("Value: "); handler.addChild(adder); handler = handler.get(handler.size() - 1).get(1); match(TokenType.Assign); Expression e = expression(); match(TokenType.Semicolon); handler = handler.getParent().getParent(); return new Assignment(i, e); // student exercise } private Conditional ifStatement () { // IfStatement --> if ( Expression ) Statement [ else Statement ] match(TokenType.If); TreeNode adder = new TreeNode("If: "); adder.addChild("Condition: "); adder.addChild("Then: "); handler.addChild(adder); handler = handler.get(handler.size() - 1).get(0); match(TokenType.LeftParen); Expression e = expression(); match(TokenType.RightParen); handler = handler.getParent().get(1); Statement s = statement(); Statement el = new Skip(); handler = handler.getParent(); if(token.type() == TokenType.Else) { token = lexer.next(); handler.addChild("Else: "); handler = handler.get(2); el = statement(); handler = handler.getParent(); } handler = handler.getParent(); return new Conditional(e, s, el); // student exercise } private Loop whileStatement () { // WhileStatement --> while ( Expression ) Statement match(TokenType.While); TreeNode adder = new TreeNode("While: "); adder.addChild("Condition: "); adder.addChild("Then: "); handler.addChild(adder); handler = handler.get(handler.size() - 1).get(0); match(TokenType.LeftParen); Expression e = expression(); match(TokenType.RightParen); handler = handler.getParent().get(1); Statement s = statement(); handler = handler.getParent().getParent(); return new Loop(e, s); // student exercise } private Expression expression () { // Expression --> Conjunction { || Conjunction } handler.addChild("Expression: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression e = conjunction(); while (isEqualityOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); match(TokenType.Or); Expression e2 = conjunction(); e = new Binary(op, e, e2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return e; // student exercise } private Expression conjunction () { // Conjunction --> Equality { && Equality } handler.addChild("Conjunction: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression c = equality(); while (isEqualityOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); match(TokenType.And); Expression c2 = equality(); c = new Binary(op, c, c2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return c; // student exercise } private Expression equality () { // Equality --> Relation [ EquOp Relation ] handler.addChild("Equality: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression e = relation(); if (isEqualityOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); Expression e2 = relation(); e = new Binary(op, e, e2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return e; // student exercise } private Expression relation (){ // Relation --> Addition [RelOp Addition] handler.addChild("Relation: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression r = addition(); if (isRelationalOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); Expression r2 = addition(); r = new Binary(op, r, r2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return r; // student exercise } private Expression addition () { // Addition --> Term { AddOp Term } handler.addChild("Addition: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression e = term(); while (isAddOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); Expression term2 = term(); e = new Binary(op, e, term2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return e; } private Expression term () { // Term --> Factor { MultiplyOp Factor } handler.addChild("Term: "); handler = handler.get(handler.size() - 1); TreeNode adder; Expression e = factor(); while (isMultiplyOp()) { Operator op = new Operator(match(token.type())); adder = new TreeNode(op.toString()); adder.addChild(handler.get(0)); handler.remove(handler.size() - 1); handler.addChild(adder); handler = handler.get(handler.size() - 1); Expression term2 = factor(); e = new Binary(op, e, term2); handler = handler.getParent(); } handler.popThis(); handler = handler.getParent(); return e; } private Expression factor() { // Factor --> [ UnaryOp ] Primary if (isUnaryOp()) { Operator op = new Operator(match(token.type())); handler.addChild(op.toString()); //handler가 리프 노드라고 가정 handler = handler.get(0); Expression term = primary(); handler = handler.getParent(); return new Unary(op, term); } else return primary(); } private Expression primary () { // Primary --> Identifier | Literal | ( Expression ) // | Type ( Expression ) Expression e = null; if (token.type().equals(TokenType.Identifier)) { e = new Variable(match(TokenType.Identifier)); handler.addChild("Identifier: " + e.toString()); } else if (isLiteral()) { e = literal(); handler.addChild("Literal: " + e.toString()); } else if (token.type().equals(TokenType.LeftParen)) { handler.addChild("Paren: "); handler = handler.get(handler.size() - 1); token = lexer.next(); e = expression(); match(TokenType.RightParen); handler = handler.getParent(); } else if (isType( )) { Operator op = new Operator(match(token.type())); handler.addChild("Typecast: " + op.toString()); handler = handler.get(handler.size() - 1); match(TokenType.LeftParen); Expression term = expression(); match(TokenType.RightParen); e = new Unary(op, term); handler = handler.getParent(); } else error("Identifier | Literal | ( | Type"); return e; } private Value literal( ) { try{ // int literal if (token.type() == TokenType.IntLiteral){ Value v = new IntValue(Integer.parseInt(token.value())); match(TokenType.IntLiteral); return v; // float literal }else if (token.type() == TokenType.FloatLiteral){ Value v = new FloatValue(Float.parseFloat(token.value())); match(TokenType.FloatLiteral); return v; } // char literal else if (token.type() == TokenType.CharLiteral){ Value v = new CharValue(token.value().charAt(0)); match(TokenType.CharLiteral); return v; } else error("unknown token type for literal! Token value: " + token.value()); } catch(NumberFormatException e){ error("Inavlid number format " + e.getLocalizedMessage()); } return null; // student exercise } private boolean isAddOp( ) { return token.type().equals(TokenType.Plus) || token.type().equals(TokenType.Minus); } private boolean isMultiplyOp( ) { return token.type().equals(TokenType.Multiply) || token.type().equals(TokenType.Divide); } private boolean isUnaryOp( ) { return token.type().equals(TokenType.Not) || token.type().equals(TokenType.Minus); } private boolean isEqualityOp( ) { return token.type().equals(TokenType.Equals) || token.type().equals(TokenType.NotEqual); } private boolean isRelationalOp( ) { return token.type().equals(TokenType.LessEqual) || token.type().equals(TokenType.Less) || token.type().equals(TokenType.GreaterEqual) || token.type().equals(TokenType.Greater); } private boolean isType( ) { return token.type().equals(TokenType.Int) || token.type().equals(TokenType.Bool) || token.type().equals(TokenType.Float) || token.type().equals(TokenType.Char); } private boolean isLiteral( ) { return token.type().equals(TokenType.IntLiteral) || isBooleanLiteral() || token.type().equals(TokenType.FloatLiteral) || token.type().equals(TokenType.CharLiteral); } private boolean isBooleanLiteral( ) { return token.type().equals(TokenType.True) || token.type().equals(TokenType.False); } public static void main(String args[]) { System.out.print("Enter your clite file path: "); Scanner scan = new Scanner(System.in); String s = scan.nextLine(); Parser parser = new Parser(new Lexer(s)); Program prog = parser.program(); root.print(); // display abstract syntax tree } //main } // Parser <file_sep>/컴퓨터 그래픽스 및 비전/190411/190411.py import cv2 import time import numpy as np def emptyFunction(x): pass def main(): windowName = "Test" cv2.namedWindow(windowName) cap = cv2.VideoCapture(0) prevTime = 0 if cap.isOpened(): ret, ori = cap.read() mix = ori cv2.createTrackbar('Alpha', windowName, 333, 1000, emptyFunction) cv2.createTrackbar('MaskSize', windowName, 0, 10, emptyFunction) cv2.createTrackbar('Blending', windowName, 0, 3, emptyFunction) while ret: ret, ori = cap.read() can = cv2.Canny(ori, 100, 150, L2gradient=False) can = cv2.cvtColor(can, cv2.COLOR_GRAY2BGR) alpha = cv2.getTrackbarPos('Alpha', windowName) / 1000 mix = cv2.addWeighted(ori, alpha, can, (1 - alpha), 0) #필터링 마스크 크기 size = cv2.getTrackbarPos('MaskSize',windowName) * 2 + 1 #필터링 타입 tp = cv2.getTrackbarPos('Blending', windowName) if(tp == 1): #일반 필터링 kernel = np.ones((size, size), dtype = np.float32) / (size**2) mix = cv2.filter2D(mix, -1, kernel) elif(tp == 2): #가우시안 필터링 mix = cv2.GaussianBlur(mix, (size, size), 0) elif(tp == 3): #블러 필터링 mix = blur = cv2.blur(mix, (size, size)) ### #현재 시간 가져오기 (초단위로 가져옴) curTime = time.time() #현재 시간에서 이전 시간을 빼면? #한번 돌아온 시간!! sec = curTime - prevTime #이전 시간을 현재시간으로 다시 저장시킴 prevTime = curTime # 프레임 계산 한바퀴 돌아온 시간을 1초로 나누면 된다. # 1 / time per frame fps = 1/(sec) # 프레임 수를 문자열에 저장 str = "FPS : %0.1f" % fps # 표시 cv2.putText(ori, str, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0)) ### cv2.imshow(windowName, np.hstack([ori, mix, can])) if cv2.waitKey(1) == 27: break cv2.destroyAllWindows() cap.release() else: ret = False if __name__ == "__main__": main() <file_sep>/컴퓨터 그래픽스 및 비전/190328/190328.py # skin color detection # created by SYO # 2018.03.26 import cv2 import numpy as np import math import winsound as ws img = cv2.imread("skin0.jpg") converted = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) w_lower = np.array([0, 48, 170], dtype = "uint8") w_upper = np.array([20, 255, 255], dtype = "uint8") w_skinMask = cv2.inRange(converted, w_lower, w_upper) b_lower = np.array([0, 48, 80], dtype = "uint8") b_upper = np.array([20, 255, 180], dtype = "uint8") b_skinMask = cv2.inRange(converted, b_lower, b_upper) mix_skinMask = cv2.bitwise_and(w_skinMask, b_skinMask) w_skin = cv2.bitwise_and(img, img, mask = w_skinMask) b_skin = cv2.bitwise_and(img, img, mask = b_skinMask) mix_skin = cv2.bitwise_or(w_skin, b_skin) for i in range(mix_skinMask.shape[0]): for j in range(mix_skinMask.shape[1]): if mix_skinMask[i][j]: mix_skin[i][j][0] = 0 mix_skin[i][j][1] = 0 mix_skin[i][j][2] = 255 cv2.imshow("images", np.vstack([np.hstack([img, b_skin]), np.hstack([w_skin, mix_skin])])) cv2.waitKey(0) cv2.destroyAllWindows() <file_sep>/머신러닝/7주차 과제/HW3_2016125052_이상헌.py import numpy as np import dataUtils import model_2016125052 as model import json from json import JSONEncoder import numpy np.random.seed(1) ''' TrainSet Accuracy with best NN: 83.691406% TestSet Accuracy with best NN: 78.191489% ''' class NumpyArrayEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray): return obj.tolist() return JSONEncoder.default(self, obj) # save weights of model from json file def saveParams(params, path): with open(path, "w") as make_file: json.dump(params, make_file, cls=NumpyArrayEncoder) print("Done writing serialized NumPy array into file") # load weights of model from json file def loadParams(path): with open(path, "r") as read_file: print("Converting JSON encoded data into Numpy array") decodedArray = json.load(read_file) return decodedArray def main(): epochs = 10000 test_rate = 100 batch_size = 2 ** 7 resume = False # path of model weights model_weights_path = 'weights.json' ### dataset loading 하기. dataPath = 'dataset/train' valPath = 'dataset/val' dataloader = dataUtils.Dataloader(dataPath, minibatch = batch_size) val_dataloader = dataUtils.Dataloader(valPath) # NeuralNetwork 생성 layerDims = [len(dataloader.getImage(0)), 10, 10, 1] #simpleNN = model.NeuralNetwork(layerDims, learning_rate = 1.5) simpleNN = model.NeuralNetwork(layerDims, learning_rate = 1.5, decay_rate = 0.2) if resume: simpleNN.parameters = loadParams(resume) for epoch in range (0, epochs, 1): training(dataloader, simpleNN, epoch) if epoch % test_rate == test_rate - 1: rate = validation(val_dataloader, simpleNN) print('\nTest Accuracy: %.6f%%\n' %(rate * float(100))) print('------------------------------\n') rate = validation(dataloader, simpleNN) print('TrainSet Accuracy with best NN: %.6f%%' %(rate * float(100))) rate = validation(val_dataloader, simpleNN) print('TestSet Accuracy with best NN: %.6f%%' %(rate * float(100))) print('\n------------------------------\n') saveParams(simpleNN.parameters, model_weights_path) def validation(dataloader, simpleNN): rate = 0 cnt = 0 for i, (images, targets) in enumerate(dataloader): p = simpleNN.predict(images) rate += simpleNN.hit_ratio(p, targets) cnt += 1 return rate / cnt def training(dataloader, simpleNN, epoch): min_cost = 10000000 max_cost = -1 min_rate = 101 max_rate = -1 for i, (images, targets) in enumerate(dataloader): train = simpleNN.forward(images) cost = simpleNN.compute_cost(train, targets) rate = simpleNN.hit_ratio(train, targets)[0] simpleNN.backward() simpleNN.update_params(epoch) if min_cost > cost: min_cost = cost if max_cost < cost: max_cost = cost if min_rate > rate: min_rate = rate if max_rate < rate: max_rate = rate print("Cost %7i| %.9f\t%.9f" %(epoch + 1, min_cost, max_cost)) print("Accuracy\t| " + format(float(min_rate) * 100., "5.3f") + '%\t' + format(float(max_rate) * 100., "5.3f") + '%') return simpleNN if __name__=='__main__': main()<file_sep>/머신러닝/7주차 과제/model_2016125052.py import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def relu(x): return np.maximum(x, 0) class NeuralNetwork: def __init__(self, layerDims, learning_rate = 1, decay_rate = 0.2, nSample = 0): ############ self.learning_rate = learning_rate self.decay_rate = decay_rate self.parameters = self.weightInit(layerDims) self.grads = {} self.cache = {} self.initialize_optimizer() def initialize_optimizer(self): size = self.parameters['size'] VdW = [0 for _ in range(size)] Vdb = [0 for _ in range(size)] self.grads.update(VdW = VdW, Vdb = Vdb) def weightInit(self, layerDims): np.random.seed(1) W = [0 for _ in range(len(layerDims))] b = [0 for _ in range(len(layerDims))] for l in range(1, len(layerDims)): W[l] = np.random.randn(layerDims[l], layerDims[l - 1]) * np.sqrt(2 / layerDims[l - 1]) b[l] = np.zeros((layerDims[l], 1)) return {"W": W, "b": b, "size": len(layerDims)} def forward(self, X, training = True): W, b, size = self.parameters.values() Z = [0 for _ in range(size)] A = [0 for _ in range(size)] A[0] = X for i in range(1, size): Z[i] = np.dot(W[i], A[i - 1]) + b[i] A[i] = relu(Z[i]) A[size - 1] = sigmoid(Z[size - 1]) if training is True: self.cache.update(X = X, Z = Z, A = A) return A[size - 1] def backward(self, lambd = 0.7): W, b, size = self.parameters.values() VdW, Vdb = self.grads.values() A = self.cache['A'] dZ = [0 for _ in range(size)] dW = [0 for _ in range(size)] db = [0 for _ in range(size)] m = float(A[0].shape[1]) size = size - 1 dZ[size] = A[size] - self.cache['Y'] dW[size] = (np.dot(dZ[size], A[size - 1].T) + lambd * W[size]) / m db[size] = 1./m * np.sum(dZ[size], axis=1, keepdims = True) for i in range(size - 1, 1, -1): dZ[i] = np.multiply(np.dot(W[i + 1].T, dZ[i + 1]), np.int64(A[i] > 0)) dW[i] = (np.dot(dZ[i], A[i - 1].T) + lambd * W[i]) / m db[i] = 1./m * np.sum(dZ[i], axis=1, keepdims = True) beta = 0.9 div = 1 for i in range(1, size): div *= beta VdW[i] = (beta * VdW[i - 1] + (1 - beta) * dW[i]) / (1 - div) Vdb[i] = (beta * Vdb[i - 1] + (1 - beta) * db[i]) / (1 - div) self.grads.update(VdW = VdW, Vdb = Vdb) return def compute_cost(self, X, Y): self.cache.update(Y = Y) lambd = 0.7 W = self.parameters['W'] sum_W = 0. for Wi in W: sum_W += np.sum(np.square(Wi)) L2_cost = lambd / (2 * len(Y)) * sum_W logprobs = np.multiply(np.log(X), Y) + np.multiply(np.log(1 - X), 1 - Y) cost = -np.sum(logprobs) * (1 / len(Y)) + L2_cost cost = float(np.squeeze(cost)) assert(isinstance(cost, float)) return cost def update_params(self, epoch_num): W, b, size = self.parameters.values() VdW, Vdb = self.grads.values() learning_rate = self.learning_rate / (1 + self.decay_rate * epoch_num) ''' backward의 결과로 dW[1], db[1]과 VdW[1], Vdb[1]은 모두 0이 나오지만 첫째, dW[1]과 dW[2]의 사이즈 차이로 VdW[2]를 계산하려 할 시에 에러가 발생함 둘째, db[1]을 계산한 결과 원인 모를 이유로 정확도개 개선되지 않음 따라서 VdW[2:]와 Vdb[2:]만을 사용한 결과 정확도가 개선됨을 확인하였으므로 VdW[2:]만을 사용하려 W를 계산하기로 하였다 ''' for i in range(1, size): W[i] = W[i] - (learning_rate) * VdW[i] b[i] = b[i] - (learning_rate) * Vdb[i] self.parameters.update(W = W, b = b) return def predict(self, X): return self.forward(X, training = False) > 0.5 def hit_ratio(self, Y_, Y): return (np.dot(Y, Y_.T) + np.dot(1 - Y, 1 - Y_.T)) / float(Y.size)<file_sep>/머신러닝/5주차 과제/untitled0.py import numpy as np import matplotlib.pyplot as plt from data_utils import decision_boundary, generate_dataset import sklearn import sklearn.datasets np.random.seed(1) def sigmoid(x): return 1 / (1 + np.exp(-x)) def relu(x): return np.maximum(x, 0) class NeuralNetwork: def __init__(self,layerDims, nSample): self.size = len(layerDims) ############ self.nSample = nSample self.parameters = self.weightInit(layerDims) self.grads = {} self.vel = {} self.s = {} self.cache = {} ##self.initialize_optimizer() def weightInit(self, layerDims): np.random.seed(1) W = [0 for _ in range(len(layerDims))] b = [0 for _ in range(len(layerDims))] for l in range(1, len(layerDims)): W[l] = np.random.randn(layerDims[l], layerDims[l - 1]) * 0.1 b[l] = np.zeros((layerDims[l], 1)) return {"W": W, "b": b} def forward(self, X): W, b = self.parameters.values() size = self.size Z = [0 for _ in range(size)] A = [0 for _ in range(size)] A[0] = X for i in range(1, size): Z[i] = np.dot(W[i], A[i - 1]) + b[i] A[i] = relu(Z[i]) A[size - 1] = sigmoid(Z[size - 1]) self.cache.update(X = X, Z = Z, A = A) return A[size - 1] def backward(self, lambd = 0.7): W, b = self.parameters.values() A = self.cache['A'] size = self.size - 1 dW = [0 for _ in range(self.size)] db = [0 for _ in range(self.size)] dZ = [0 for _ in range(self.size)] m = A[0].shape[1] dZ[size] = A[size] - self.cache['Y'] dW[size] = 1./m * np.dot(dZ[size], A[size - 1].T) + lambd / m * W[size] db[size] = 1./m * np.sum(dZ[size], axis=1, keepdims = True) for i in range(size - 1, 1, -1): dZ[i] = np.multiply(np.dot(W[i + 1].T, dZ[i + 1]), np.int64(A[i] > 0)) dW[i] = 1./m * np.dot(dZ[i], A[i - 1].T) + lambd / m * W[i] db[i] = 1./m * np.sum(dZ[i], axis=1, keepdims = True) self.grads.update(dW = dW, db = db) return def compute_cost(self, fw, Y): self.cache.update(Y = Y) lambd=0.7 size = self.size W = self.parameters['W'] sum_W = 0. for i in W: sum_W += np.sum(np.square(i)) L2_cost = lambd / (2 * Y.shape[1]) * sum_W logprobs = (np.multiply(np.log(fw), Y) + np.multiply(np.log(1 - fw), 1 - Y) ) cost = -np.sum(logprobs) * (1 / Y.shape[1]) + L2_cost cost = float(np.squeeze(cost)) assert(isinstance(cost, float)) return cost def update_params(self, learning_rate=1.2): W, b = self.parameters.values() dW, db = self.grads.values() for i in range(1, self.size): W[i] = W[i] - (learning_rate) * dW[i] b[i] = b[i] - (learning_rate) * db[i] self.parameters.update(W = W, b = b) return def predict(self, X): return self.forward(X) > 0.5 def main(): np.random.seed(1) num_iterations=12000 learning_rate =0.3 ### dataset loading 하기. X_train,Y_train, X_test, Y_test = generate_dataset() # plt.title("Data distribution") # plt.scatter(X_train[0, :], X_train[1, :], c=Y_train[0,:], s=20, cmap=plt.cm.RdBu) # plt.show() ## 코딩 시작 nSample = X_train.shape[1] layerDims = [X_train.shape[0], 20, 7, 1] ## 코딩 끝 simpleNN = NeuralNetwork(layerDims,nSample) training(X_train, Y_train, simpleNN, num_iterations, learning_rate) def training(X_train, Y_train, simpleNN, num_iterations, learning_rate): ## 코딩시작 # num_iterations 동안 training regularization이 없는 simple neural network를 학습하는 code를 작성하세요. # return 값으론, 학습된 모델을 출력하세요. print('Starting training') _, _, X_test, Y_test = generate_dataset() for i in range(0, num_iterations): A3 = simpleNN.forward(X_train) cost = simpleNN.compute_cost(A3, Y_train) simpleNN.backward() simpleNN.update_params() if i % 1000 ==0: print("Cost after iteration %i: %f" %(i,cost)) predictions = simpleNN.predict(X_train) print ('Train Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") predictions = simpleNN.predict(X_test) print ('Test Accuracy: %d' % float((np.dot(Y_test,predictions.T) + np.dot(1-Y_test,1-predictions.T))/float(Y_test.size)*100) + '%') print('--------------------------------------------') ##코딩 끝 # predictions = simpleNN.predict(X_train) # print ('Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') # decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") return simpleNN if __name__=='__main__': main() <file_sep>/컴퓨터 그래픽스 및 비전/190418/S class - 190418.py import numpy as np import cv2 def main(): def mouse_callback(event, x, y, flags, param): nonlocal count nonlocal stack if event == cv2.EVENT_LBUTTONDOWN: cv2.circle(img, (x, y), 5, (0, 0, 0), 1) cv2.circle(img, (x, y), 4, (255, 255, 255), -1) stack[count][0] = x; stack[count][1] = y count = count + 1 stack = np.float32([[0, 0], [0, 0], [0, 0], [0, 0]]) count = 0 img = cv2.imread("number2.jpg") ori = img.copy() cv2.namedWindow('image') cv2.setMouseCallback('image', mouse_callback) lower = np.array([230, 230, 230], dtype = "uint8") upper = np.array([255, 255, 255], dtype = "uint8") Mask = cv2.inRange(ori, lower, upper) Mask = cv2.GaussianBlur(Mask, (5, 5), 0) cv2.imshow("find", Mask) while(count < 4): cv2.imshow('image',img) if cv2.waitKey(1) & 0xFF == 27: cv2.destroyAllWindows() break h = stack[1][1] - stack[0][1] w = stack[2][0] - stack[0][0] stack2 = np.float32([[0, 0], [0, h], [w, 0], [w, h]]) print(stack) print(stack2) P = cv2.getPerspectiveTransform(stack, stack2) change = cv2.warpPerspective(ori, P, (w, h)) cv2.imshow('change', change) if __name__ == "__main__": main() <file_sep>/컴퓨터 그래픽스 및 비전/190314/190314.py # -*- coding: utf-8 -*- """ Created on Thu Mar 14 17:19:09 2019 @author: Kei """ import cv2 import numpy as np import winsound as ws from matplotlib import pyplot as plt def main(): imgpath = "C:\\Users\\Kei\\Desktop\\cg\\team\\1\\messi5.jpg" img = cv2.imread(imgpath) img_buf = img.copy() print(img) # event loop while(True): # display the image in the same window cv2.imshow('messi', img_buf) # 64bit os returns 32bits, mask out to get the ascii 8bits key = cv2.waitKey(0) & 0xFF print(key) if key == ord('q'): # esc: quit break # show the original image elif key == ord('c'): img_buf = img[:, :, :] elif key == ord('g'): img_buf = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) elif key == ord('m'): print("행을 나눌 칸 갯수를 입력하시오.") r = input() print("열을 나눌 칸 갯수를 입력하시오.") c = input() new = img.copy() new2 = img.copy() new3 = img.copy() print(img.shape[0], img.shape[1]) r = int(r) c = int(c) T = img.shape[0]/r S = img.shape[1]/c T = int (T) S = int (S) arsize = T*S print(T, S, "T, S") print("a.average b.median c.center") ikey = input() if ikey == ('a'): for k in range(r): for f in range(c): T2 = T*k S2 = S*f #print(k, f, T*(k), S*(f), "k f") temp1 = 0 temp2 = 0 temp3 = 0 for i in range(T): for j in range(S): #print(i, j) temp1 = temp1 + img[i+T2][j+S2][0] temp2 = temp2 + img[i+T2][j+S2][1] temp3 = temp3 + img[i+T2][j+S2][2] temp1 = int(temp1 / arsize) temp2 = int(temp2 / arsize) temp3 = int(temp3 / arsize) for i in range(T): for j in range(S): new[i+T2][j+S2][0] = temp1 new[i+T2][j+S2][1] = temp2 new[i+T2][j+S2][2] = temp3 if i == T-1 or j == S-1: new[i+T2][j+S2][0] = 0 #line Color new[i+T2][j+S2][1] = 0 new[i+T2][j+S2][2] = 0 img_buf = new plt.imshow(img_buf) for k in range(r): for f in range(c): T2 = T*k S2 = S*f plt.text(S2+int(S/2),T2+int(T/2),"({}, {})".format(f, k), color='white') plt.show() elif ikey == ('b'): for k in range(r): for f in range(c): T2 = T*k S2 = S*f list1 = [] list2 = [] list3 = [] for i in range(T): for j in range(S): list1.append(img[i+T2][j+S2][0]) list2.append(img[i+T2][j+S2][1]) list3.append(img[i+T2][j+S2][2]) list1.sort() list2.sort() list3.sort() temp1 = list1[int(arsize/2)] temp2 = list2[int(arsize/2)] temp3 = list3[int(arsize/2)] for i in range(T): for j in range(S): new2[i+T2][j+S2][0] = temp1 new2[i+T2][j+S2][1] = temp2 new2[i+T2][j+S2][2] = temp3 if i == T-1 or j == S-1: new2[i+T2][j+S2][0] = 0 new2[i+T2][j+S2][1] = 0 new2[i+T2][j+S2][2] = 0 img_buf = new2 plt.imshow(img_buf) for k in range(r): for f in range(c): T2 = T*k S2 = S*f plt.text(S2+int(S/2),T2+int(T/2),"({}, {})".format(f, k), color='white') plt.show() elif ikey == ('c'): for k in range(r): for f in range(c): T2 = T*k S2 = S*f #print(k, f, T*(k), S*(f), "k f") temp1 = img[T2+int(T/2)][S2+int(S/2)][0] temp2 = img[T2+int(T/2)][S2+int(S/2)][1] temp3 = img[T2+int(T/2)][S2+int(S/2)][2] for i in range(T): for j in range(S): new3[i+T2][j+S2][0] = temp1 new3[i+T2][j+S2][1] = temp2 new3[i+T2][j+S2][2] = temp3 if i == T-1 or j == S-1: new3[i+T2][j+S2][0] = 0 new3[i+T2][j+S2][1] = 0 new3[i+T2][j+S2][2] = 0 img_buf = new3 plt.imshow(img_buf) for k in range(r): for f in range(c): T2 = T*k S2 = S*f plt.text(S2+int(S/2),T2+int(T/2),"({}, {})".format(f, k), color='white') plt.show() else: print("Wrong input") break else: # defalut: warning ws.PlaySound("*", ws.SND_ALIAS) cv2.destroyAllWindows() if __name__ == "__main__": main() <file_sep>/컴퓨터 그래픽스 및 비전/190418/190418.py # -*- coding: utf-8 -*- import cv2 import numpy as np imgpath = "number2.jpg" original = cv2.imread(imgpath) pts1 = np.float32([[0, 0], [0, 0], [0, 0], [0, 0]]) count = 0 def searching(): global original converted = cv2.cvtColor(original, cv2.COLOR_BGR2HSV) lower = np.array([0, 0, 240], dtype = "uint8") upper = np.array([10, 10, 255], dtype = "uint8") Mask = cv2.inRange(converted, lower, upper) Mask = cv2.GaussianBlur(Mask, (5, 5), 0) cv2.imshow("find", Mask) def change(): global original, pts1 h = pts1[1][1] - pts1[0][1] w = pts1[2][0] - pts1[0][0] pts2 = np.float32([[0, 0], [0, h], [w, 0], [w, h]]) P = cv2.getPerspectiveTransform(pts1, pts2) changed = cv2.imread(imgpath) changed = cv2.warpPerspective(changed, P, (w, h)) cv2.imshow("Changed", changed) def CallBackFunc(event, x, y, flags, param): global original, pts1, count if event == cv2.EVENT_LBUTTONDOWN: pts1[count][0] = x pts1[count][1] = y cv2.circle(original, (x, y), 5, (0, 0, 0), 1) cv2.circle(original, (x, y), 4, (255, 255, 255), -1) count += 1 def CallBackVoid(event, x, y, flags, param): pass def main(): global original, pts1, count windowName = "Original" cv2.namedWindow(windowName) cv2.setMouseCallback(windowName, CallBackFunc) searching() while(True): cv2.imshow(windowName, original) if count >= 4: cv2.setMouseCallback(windowName, CallBackVoid) #에러 방지 change() k = cv2.waitKey(1) & 0xFF if k == 27: break cv2.destroyAllWindows() if __name__ == "__main__": main() <file_sep>/컴퓨터 그래픽스 및 비전/190502/cp.py import numpy as np import cv2 # Read the image file image = cv2.imread('num (1).jpg') image = cv2.resize(image, dsize=(360, 480), interpolation=cv2.INTER_AREA) img = image.copy() image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) image = cv2.Canny(image, 170, 200) cnts, _ = cv2.findContours(image.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:30] NumberPlateCnt = None count = 0 for c in cnts: peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.02 * peri, True) if len(approx) == 4: NumberPlateCnt = approx break stack = list() for i in range(4): stack.append([NumberPlateCnt[i][0][0], NumberPlateCnt[i][0][1]]) for i in range(3): if stack[i][0] > stack[i + 1][0]: stack[i], stack[i + 1] = stack[i + 1], stack[i] for i in range(3): if stack[i][0] > stack[i + 1][0]: stack[i], stack[i + 1] = stack[i + 1], stack[i] if(stack[0][1] > stack[1][1]): stack[0], stack[1] = stack[1], stack[0] if(stack[2][1] > stack[3][1]): stack[2], stack[3] = stack[3], stack[2] stack = np.float32([[stack[0][0], stack[0][1]], [stack[1][0], stack[1][1]], [stack[2][0], stack[2][1]], [stack[3][0], stack[3][1]]]) h = int(stack[1][1] - stack[0][1]) w = int(stack[2][0] - stack[0][0]) stack2 = np.float32([[0, 0], [0, h], [w, 0], [w, h]]) P = cv2.getPerspectiveTransform(stack, stack2) plate = cv2.warpPerspective(img, P, (w, h)) cv2.imshow('number Plate', plate) <file_sep>/컴퓨터 그래픽스 및 비전/190502/190502.py import numpy as np import cv2 def emptyFunction(x): pass def main(): ori = cv2.imread("number.jpg", 0) img = ori.copy() ### lower = np.array([240], dtype = "uint8") upper = np.array([250], dtype = "uint8") img = cv2.inRange(img, lower, upper) ### img = cv2.GaussianBlur(img, (9, 9), 0) kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) img = cv2.filter2D(img, -1, kernel) ### windowName = "Lines" cv2.namedWindow(windowName) cv2.createTrackbar('Thres1', windowName, 755, 2000, emptyFunction) cv2.createTrackbar('Thres2', windowName, 1000, 2000, emptyFunction) cv2.createTrackbar('THR', windowName, 100, 200, emptyFunction) while(True): thres1 = cv2.getTrackbarPos('Thres1', windowName) thres2 = cv2.getTrackbarPos('Thres2', windowName) thr = cv2.getTrackbarPos('THR', windowName) if(thres1 > thres2): thres1, thres2 = thres2, thres1 can = cv2.Canny(img, thres1, thres2, None, 3) show = cv2.cvtColor(can, cv2.COLOR_GRAY2BGR) hough = cv2.HoughLinesP(can, 1, np.pi/180, thr, maxLineGap=10) if hough is not None: for line in hough: for x1, y1, x2, y2 in line: cv2.line(show, (x1, y1), (x2, y2), [0, 0, 255], 3) cv2.imshow(windowName, show) if cv2.waitKey(1) & 0xFF == 27: cv2.destroyAllWindows() break if __name__ == "__main__": main() <file_sep>/머신러닝/5주차 과제/HW2_2016125052_이상헌.py import numpy as np import matplotlib.pyplot as plt from data_utils import decision_boundary, generate_dataset import sklearn import sklearn.datasets np.random.seed(1) def sigmoid(x): """ sigmoid 함수 Arguments: x: scalar 또는 numpy array Return: s: sigmoid(x) """ ## 코딩시작 s = 1 / (1 + np.exp(-x)) ## 코딩 끝 return s def relu(x): """ ReLU 함수 Arguments: x : scalar 또는 numpy array Return: s : relu(x) """ ## 코딩시작 s = np.maximum(x, 0) ## 코딩 끝 return s class NeuralNetwork: def __init__(self,layerDims, nSample): ''' 학습할 네트워크. Arguments: layerDims [array]: layerDims[i] 는 레이어 i의 hidden Unit의 개수 (layer0 = input layer) nSample: 데이터셋의 샘플 수 ''' self.nSample = nSample self.parameters = self.weightInit(layerDims) self.grads = {} self.cache = {} def weightInit(self, layerDims): """ network parameter 초기화 Arguments: layerDims [array] : Returns: parameters: network의 parameter를 dictionary 형태로 저장 key 값은 "W1", "b1", ..., "WL", "bL" Tips: 0.01..... 꼭.... """ np.random.seed(1) parameters = {} ## 코딩 시작 # parameter를 초기화 하세요. for l in range(1, len(layerDims)): parameters['W' + str(l)] = np.random.randn(layerDims[l], layerDims[l - 1]) * 0.1 parameters['b' + str(l)] = np.zeros((layerDims[l], 1)) ## 코딩 끝 return parameters def forward(self, X): ''' forward propagation Arguments: X: input data Return: A23: network output ''' ## 코딩시작 # parameter 값을 불러와서, Z1, A1, Z2, A2, Z3, A3 계산후 cache update W1, b1, W2, b2, W3, b3 = self.parameters.values() Z1 = np.dot(W1,X) + b1 A1 = relu(Z1) Z2 = np.dot(W2,A1) + b2 A2 = relu(Z2) Z3 = np.dot(W3,A2) + b3 A3 = sigmoid(Z3) self.cache.update(X=X, Z1=Z1, A1= A1, Z2=Z2, A2=A2, Z3=Z3, A3=A3) ## 코딩 끝 return A3 def backward(self): ''' backward propagation. gradients를 구한다. Arguments: Return: ''' ## 코딩 시작 # parameter와 cache를 이용해 gradients를 구한후 grads update한다. # dZ1, dZ2, dZ3, dW1, dW2, dW3, db1, db2, db3, dA1, dA2 를 각각 구하세요. W1, b1, W2, b2, W3, b3 = self.parameters.values() X = self.cache['X'] Y = self.cache['Y'] A1 = self.cache['A1'] A2 = self.cache['A2'] A3 = self.cache['A3'] m = X.shape[1] dZ3 = A3 - Y dW3 = np.dot(dZ3, A2.T) / m db3 = np.sum(dZ3, axis = 1,keepdims = True) / m dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) dW2 = np.dot(dZ2, A1.T) / m db2 = np.sum(dZ2, axis = 1,keepdims = True) / m dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = np.dot(dZ1, X.T) / m db1 = np.sum(dZ1, axis = 1,keepdims = True) / m self.grads.update(dW1=dW1, db1= db1, dW2=dW2, db2=db2, dW3=dW3, db3=db3) ## 코딩 끝 return def update_params(self, learning_rate=1.2): ''' backpropagation을 통해 얻은 gradients를 update한다. Arguments: learning_rate: 학습할 learning rate Return: ''' ## 코딩시작 # parameter와 grads를 이용해 gradients descents를 통해 새로운 weight를 구하고, parameters update W1, b1, W2, b2, W3, b3 = self.parameters.values() dW1, db1, dW2, db2, dW3, db3 = self.grads.values() W1 = W1 - learning_rate * dW1 b1 = b1 - learning_rate * db1 W2 = W2 - learning_rate * dW2 b2 = b2 - learning_rate * db2 W3 = W3 - learning_rate * dW3 b3 = b3 - learning_rate * db3 self.parameters.update(W1=W1, b1= b1, W2=W2, b2=b2, W3=W3, b3=b3) ## 코딩 끝 return def compute_cost(self, A3, Y): ''' cross-entropy loss를 이용하여 cost를 구한다. Arguments: A2 : network 결과값 Y : 정답 label(groud truth) Return: cost ''' self.cache.update(Y=Y) ## 코딩시작 logprobs = np.multiply(np.log(A3), Y) + np.multiply(np.log(1 - A3), 1 - Y) cost = -np.sum(logprobs) * (1 / Y.shape[1]) ### 코딩끝 cost = float(np.squeeze(cost)) assert(isinstance(cost, float)) return cost def compute_cost_with_regularization(self, A3, Y, lambd=0.7): ''' cross-entropy loss에 regularization term을 이용하여 cost를 구한다. Arguments: A3 : network 결과값 Y : 정답 label(groud truth) lambd : 람다 값. Return: cost ''' self.cache.update(Y=Y) W1, W2, W3 = self.parameters["W1"], self.parameters["W2"], self.parameters["W3"] ## 코딩시작 L2_cost = lambd / (2 * Y.shape[1]) * (np.sum(np.square(W1)) + np.sum(np.square(W2)) + np.sum(np.square(W3))) cost = self.compute_cost(A3, Y) + L2_cost ### 코딩끝 cost = float(np.squeeze(cost)) assert(isinstance(cost, float)) return cost def backward_with_regularization(self,lambd=0.7): ''' regularization term이 추가된 backward propagation. Arguments: lambd: Return: ''' ## 코딩 시작 # regularization term이 추가된 cost에서 back-propagation을 진행, grads update W1,b1,W2,b2, W3, b3 = self.parameters.values() X = self.cache['X'] Y = self.cache['Y'] A1 = self.cache['A1'] A2 = self.cache['A2'] A3 = self.cache['A3'] m = float(X.shape[1]) dZ3 = A3 - Y dW3 = (np.dot(dZ3, A2.T) + lambd * W3) / m db3 = np.sum(dZ3, axis=1, keepdims = True) / m dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(np.dot(W3.T, dZ3), np.int64(A2 > 0)) dW2 = (np.dot(dZ2, A1.T) + lambd * W2) / m db2 = np.sum(dZ2, axis=1, keepdims = True) / m dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = (np.dot(dZ1, X.T) + lambd * W1) / m db1 = np.sum(dZ1, axis=1, keepdims = True) / m self.grads.update(dW1=dW1, db1= db1, dW2=dW2, db2=db2, dW3=dW3, db3=db3) ## 코딩 return def predict(self,X): ''' 학습한 network가 잘 학습했는지, test set을 통해 확인한다. Arguments: X: input data Return: ''' ## 코딩시작 # network 출력이 0.5보다 크면 1 아니면 0, 결과를 predictions로 출력한다. A3 = self.forward(X) predictions = (A3 > 0.5) ## 코딩 끝 return predictions def main(): np.random.seed(1) num_iterations=12000 learning_rate =0.3 ### dataset loading 하기. X_train,Y_train, X_test, Y_test = generate_dataset() # plt.title("Data distribution") # plt.scatter(X_train[0, :], X_train[1, :], c=Y_train[0,:], s=20, cmap=plt.cm.RdBu) # plt.show() ## 코딩 시작 nSample = X_train.shape[1] layerDims = [X_train.shape[0], 20, 7, 1] ## 코딩 끝 #simpleNN = NeuralNetwork(layerDims,nSample) #training(X_train, Y_train, simpleNN, num_iterations, learning_rate) simpleNN_R = NeuralNetwork(layerDims,nSample) training_with_regularization(X_train, Y_train, simpleNN_R, num_iterations, learning_rate) ### print prediction # predictions = simpleNN.predict(X_train) # print ('Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') # decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") # predictions = simpleNN.predict(X_test) # print ('Accuracy: %d' % float((np.dot(Y_test,predictions.T) + np.dot(1-Y_test,1-predictions.T))/float(Y_test.size)*100) + '%') # decision_boundary(lambda x: simpleNN.predict(x.T), X_test, Y_test, name="test Dataset") # predictions = simpleNN_R.predict(X_train) # print ('Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') # decision_boundary(lambda x: simpleNN_R.predict(x.T), X_train, Y_train, name="Train Dataset") # predictions = simpleNN_R.predict(X_test) # print ('Accuracy: %d' % float((np.dot(Y_test,predictions.T) + np.dot(1-Y_test,1-predictions.T))/float(Y_test.size)*100) + '%') # decision_boundary(lambda x: simpleNN_R.predict(x.T), X_test, Y_test, name="test Dataset") def training(X_train, Y_train, simpleNN, num_iterations, learning_rate): ## 코딩시작 # num_iterations 동안 training regularization이 없는 simple neural network를 학습하는 code를 작성하세요. # return 값으론, 학습된 모델을 출력하세요. print('Starting training') _, _, X_test, Y_test = generate_dataset() for i in range(0, num_iterations): A3 = simpleNN.forward(X_train) cost = simpleNN.compute_cost(A3, Y_train) simpleNN.backward() simpleNN.update_params() if i % 1000 ==0: print("Cost after iteration %i: %f" %(i,cost)) predictions = simpleNN.predict(X_train) print ('Train Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") predictions = simpleNN.predict(X_test) print ('Test Accuracy: %d' % float((np.dot(Y_test,predictions.T) + np.dot(1-Y_test,1-predictions.T))/float(Y_test.size)*100) + '%') print('--------------------------------------------') ##코딩 끝 # predictions = simpleNN.predict(X_train) # print ('Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') # decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") return simpleNN def training_with_regularization(X_train, Y_train, simpleNN, num_iterations, learning_rate): ## 코딩시작 # num_iterations 동안 training regularization이 있는 simple neural network를 학습하는 code를 작성하세요. # return 값으론, 학습된 모델을 출력하세요. print('Starting training_with_regularization') _, _, X_test, Y_test = generate_dataset() for i in range(0, num_iterations): A3 = simpleNN.forward(X_train) cost = simpleNN.compute_cost_with_regularization(A3, Y_train) simpleNN.backward_with_regularization() simpleNN.update_params() if i % 1000 ==0: print("Cost after iteration %i: %f" %(i,cost)) predictions = simpleNN.predict(X_train) print ('Train Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") predictions = simpleNN.predict(X_test) print ('Test Accuracy: %d' % float((np.dot(Y_test,predictions.T) + np.dot(1-Y_test,1-predictions.T))/float(Y_test.size)*100) + '%') ##코딩 끝 # predictions = simpleNN.predict(X_train) # print ('Accuracy: %d' % float((np.dot(Y_train,predictions.T) + np.dot(1-Y_train,1-predictions.T))/float(Y_train.size)*100) + '%') # decision_boundary(lambda x: simpleNN.predict(x.T), X_train, Y_train, name="Train Dataset") return simpleNN if __name__=='__main__': main() <file_sep>/컴퓨터 그래픽스 및 비전/190523/190523.py import numpy as np import math import cv2 col, width, row, height = -1, -1, -1, -1 frame = None frame2 = None inputmode = False rectangle = False trackWindow = None sift = cv2.xfeatures2d.SIFT_create() #찾을 타겟 이미지의 코너를 탐색 def getimg(): global sift, kp1, des1, roi, h, w roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) h, w = roi.shape kp1, des1 = sift.detectAndCompute(roi, None) def imgMatch(img2): global sift, kp1, des1, roi, h, w #비슷한 코너가 10개 이상 존재한다면 매칭에 성공한 것으로 간주 MIN_MATCH_COUNT = 10 img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) # img2: trainImage, 동영상의 프레임 하나 #입력받은 프레임의 코너를 탐색하여 kd 트리를 이용해 코너를 매칭한다 kp2, des2 = sift.detectAndCompute(img2, None) FLANN_INDEX_KDTREE = 0 index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5) search_params = dict(checks = 50) flann = cv2.FlannBasedMatcher(index_params, search_params) matches = flann.knnMatch(des1, des2, k = 2) # store all the good matches as per Lowe's ratio test. good = [] dst = [] #각 매칭점의 마할라노비스 거리를 비교해 좋은 매칭점을 골라낸다 for m, n in matches: if m.distance < 1.0 * n.distance: good.append(m) #좋은 매칭점의 수가 MIN_MATCH_COUNT개보다 많거나 같다면 if len(good) >= MIN_MATCH_COUNT: #좋은 매칭점을 한 컨테이너에 모은 뒤, 매칭점의 타입을 실행할 함수의 인자에 맞게 변환한다 src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1, 1, 2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1, 1, 2) #RANSAC을 이용해 frame 속 타겟 이미지의 위치를 탐색한다 M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) matchesMask = mask.ravel().tolist() #타겟 이미지는 프레임에서 회전 혹은 변형 등의 왜곡이 있을 수 있으므로 #perspectiveTransform을 통해 타겟 이미지를 프레임 내의 타겟 이미지와 일치하게 변형 pts = np.float32([ [0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0] ]).reshape(-1, 1, 2) dst = cv2.perspectiveTransform(pts, M) #타겟 이미지를 표시할 원의 중심을 저장 dx = (dst[0][0][0] + dst[1][0][0] + dst[2][0][0] + dst[3][0][0]) / 4 dy = (dst[0][0][1] + dst[1][0][1] + dst[2][0][1] + dst[3][0][1]) / 4 #타겟 이미지의 위치와 원의 중심을 return한다 return dst, dx, dy #좋은 매칭점의 수가 MIN_MATCH_COUNT개보다 적다면 else: #좋은 매칭점의 수를 출력한다 print ("Not enough matches are found: %d/%d" % (len(good), MIN_MATCH_COUNT)) matchesMask = None #return값의 형식만 맞춰 쓸모없는 값을 return한다 return None, 0, 0 #타겟 이미지를 만들 사각형을 만든다 def onMouse(event, x, y, flags, param): global col, width, row, height, frame, frame2, inputmode global rectangle, roi, trackWindow, xx, yy if inputmode: if event == cv2.EVENT_LBUTTONDOWN: rectangle = True col, row = x, y elif event == cv2.EVENT_MOUSEMOVE: if rectangle: frame2 = frame.copy() cv2.rectangle(frame2, (col, row), (x, y), (0, 255, 0), 2) cv2.imshow('frame', frame2) elif event == cv2.EVENT_LBUTTONUP: inputmode = False rectangle = False frame2 = frame.copy() cv2.rectangle(frame2, (col, row), (x, y), (0, 255, 0), 2) height, width = abs(row - y), abs(col - x) trackWindow = (col, row, width, height) roi = frame[row : row + height, col : col + width] getimg() return def camShift(): global frame, frame2, inputmode, trackWindow, roi, out, width, height #속도 향상을 위해 타겟 이미지를 찾는 횟수를 제한한다 frameSkip = 0 #타겟 이미지를 표시할 원의 중심 dx, dy = 0, 0 #프레임 안에서의 타겟 이미지의 네 꼭지점 dst = np.float32([ [0, 0], [0, 0], [0, 0], [0, 0] ]).reshape(-1, 1, 2) #dst, dx, dy값을 백업한다 pdst, pdx, pdy = dst, dx, dy try: path ='video//1st_school_tour_studentcenter.avi' file = cv2.VideoCapture(path) except: print("Video Failed") return ret, frame = file.read() cv2.namedWindow('frame') cv2.setMouseCallback('frame', onMouse, param = (frame, frame2)) termination = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 100, 1) #동영상의 모든 프레임에 대해 while True: ret, frame = file.read() if not ret: break #처리 속도 향상을 위해 프레임의 사이즈를 조정한다 frame = cv2.resize(frame, (640, 360)) #원본 이미지와 출력할 이미지를 구분한다 frame2 = frame.copy() #타겟 이미지가 선택되었다면 if (trackWindow is not None): #현재 프레임이 이미지 매칭을 할 프레임이라면 if (frameSkip == 0): #이미지 매칭을 실행 dst, dx, dy = imgMatch(frame) #이미지 매칭에 성공하였다면 dst, dx, dy값을 백업 if(dst is None): dst = pdst dx = pdx dy = pdy #이미지 매칭에 실패하였다면 백업된 dst, dx, dy값을 복구 else: pdst = dst pdx = dx pdy = dy #다음 일정 프레임은 이미지 매칭을 실행하지 않는다 frameSkip += 1 #현재 프레임이 이미지 매칭을 할 프레임이 아니라면 else: #frameSkip의 값을 1 올려준다 frameSkip += 1 #frameSkip이 3의 배수가 된다면 frameSkip의 값을 0으로 초기화해 이미지 매칭을 재실행하게끔 한다 frameSkip = frameSkip % 3 #이미지 매칭의 결과값을 frame2에 표시 frame2 = cv2.polylines(frame2, [np.int32(dst)], True, (255, 255, 255), 2, cv2.LINE_AA) frame2 = cv2.circle(frame2, (math.floor(dx), math.floor(dy)), math.floor((width + height) / 4), (0, 255, 255), 2) #frame2를 출력 cv2.imshow('frame', frame2) #이미지 매칭을 실행할 타겟 이미지는 #동영상 재생 중에 i를 눌러 onMouse를 실행시킨 뒤 #이미지 매칭을 할 프레임을 초기화 k = cv2.waitKey(60) & 0xFF if k == 27: break if k == ord('i'): inputmode = True frameSkip = 0 while inputmode: cv2.imshow('frame', frame) cv2.waitKey(0) file.release() cv2.destroyAllWindows() camShift()
dbb639c56650b8c91db5b1e118951379c90acc04
[ "Java", "Python" ]
16
Python
Themion/-Assignment
6d20d0794c64ec6a657474fb3fcb485f0accb3c9
4db831c17b1b7f36e27e2cae9be497a0d6561438
refs/heads/master
<repo_name>programalex/.net<file_sep>/ConectarLINQ/ConectarLINQ/Controllers/UsuarioController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ConectarLINQ.Models; namespace ConectarLINQ.Controllers { public class UsuarioController : Controller { // GET: Usuario public UsuarioModel model = new UsuarioModel(); public ActionResult Index() { return View(model.ListarUsuario()); } public ActionResult Details(int id) { var consept = model.BuscarUsuario(id); return View(consept); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(consept c) { try { if (model.InsertarUsuario(c).Equals("ok")) { return RedirectToAction("Index"); } else { return RedirectToAction("Create"); } } catch { return View(); } } public ActionResult Edit(int id) { var consept = model.BuscarUsuario(id); return View(consept); } [HttpPost] public ActionResult Edit(int id, consept c) { try { consept consept = new consept(); consept.NumeroIdentificacion = id; consept.TipoDocumento = c.TipoDocumento; consept.Nombre = c.Nombre; consept.Fecha = c.Fecha; if (model.ActualizarUsuario(consept).Equals("ok")) { return RedirectToAction("Index"); } else { return RedirectToAction("Edit"); } } catch { return View(); } } public ActionResult Delete(int id) { var consept = model.EliminarUsuario(id); return RedirectToAction("Index"); } [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { if (model.EliminarUsuario(id).Equals("ok")) { return RedirectToAction("Index"); } else { return RedirectToAction("Delete"); } } catch { return View(); } } } }<file_sep>/Conectar/Entidades/UserBussiness.cs using Connection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class UserBussiness { public List<Usuario> GetAll() { using (var db = new ModelConnection()) { var Listausuarios = db.consept.ToList(); return Listausuarios.Select(x => new Usuario(x)).ToList(); } } } } <file_sep>/Conectar/DataConecction/ModelConecction.cs namespace DataConecction { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class ModelConecction : DbContext { public ModelConecction() : base("name=ModelConecction") { } public virtual DbSet<consept> consept { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { } } } <file_sep>/Conectar/Entidades/EntidadesUsuario.cs using Connection; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class EntidadesUsuario { } public class Usuario { public Usuario() { } public Usuario(consept concept) { this.TipoDocumento = concept.TipoDocumento; this.NumeroIdentificacion = concept.NumeroIdentificacion; this.Nombre = concept.Nombre; this.Fecha = concept.Fecha; } public int? TipoDocumento { get; set; } public int NumeroIdentificacion { get; set; } public string Nombre { get; set; } public DateTime? Fecha { get; set; } } } <file_sep>/ConectarLINQ/ConectarLINQ/Models/UsuarioModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ConectarLINQ.Models { public class UsuarioModel { DataUsuarioDataContext contexto = new DataUsuarioDataContext(); public List<consept> ListarUsuario() { List<consept> Lista = new List<consept>(); var consulta = contexto.consulta(); foreach (var consept in consulta) { consept c = new consept(); c.TipoDocumento = consept.TipoDocumento; c.NumeroIdentificacion = consept.NumeroIdentificacion; c.Nombre = consept.Nombre; c.Fecha = consept.Fecha; Lista.Add(c); } return Lista; } public consept BuscarUsuario(int NumeroIdentificacion) { consept c = new consept(); try { var consulta = contexto.crud_consulta(NumeroIdentificacion); foreach (var consept in consulta) { c.NumeroIdentificacion = consept.NumeroIdentificacion; c.TipoDocumento = consept.TipoDocumento; c.Nombre = consept.Nombre; c.Fecha = consept.Fecha; } } catch (Exception) { throw; } return c; } public string InsertarUsuario(consept c) { string resultado = String.Empty; try { contexto.insertar(c.NumeroIdentificacion, c.TipoDocumento, c.Nombre, c.Fecha); resultado = "ok"; } catch (Exception ex) { resultado = ex.Message; } return resultado; } public string ActualizarUsuario(consept c) { string resultado = String.Empty; try { contexto.crud_actualizar(c.NumeroIdentificacion, c.TipoDocumento, c.Nombre, c.Fecha); resultado = "ok"; } catch (Exception ex) { resultado = ex.Message; } return resultado; } public string EliminarUsuario(int NumeroIdentificacion) { string resultado = String.Empty; try { contexto.crud_eliminar(NumeroIdentificacion); resultado = "ok"; } catch (Exception ex) { resultado = ex.Message; } return resultado; } } } <file_sep>/Conectar/Conectar/Controllers/UsuarioController.cs using Entidades; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Connection; using System.Web.Mvc; namespace Conectar.Controllers { public class UsuarioController : Controller { // GET: Usuario public ActionResult Index() { var q = new UserBussiness(); return View(q.GetAll()); } } } <file_sep>/AngularMVC/AngularMVC/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AngularMVC.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public JsonResult GetProducts(){ var db = new ProsuctsDBEntities(); var products = db.Products.ToList(); return Json(products, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult AddProduct(string newProduct) { var db = new ProsuctsDBEntities(); db.Products.Add(new Product() { ProductName = newProduct }); db.SaveChanges(); var products = db.Products.ToList(); return Json(products, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult DeleteProduct(Product delProduct) { var db = new ProsuctsDBEntities(); var product = db.Products.Find(delProduct.Id); db.Products.Remove(product); db.SaveChanges(); var products = db.Products.ToList(); return Json(products, JsonRequestBehavior.AllowGet); } } }<file_sep>/Conectar/Conectar/Controllers/CrudUsuarioController.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 Connection; namespace Conectar.Controllers { public class CrudUsuarioController : Controller { private ModelConnection db = new ModelConnection(); // GET: CrudUsuario public ActionResult Index() { return View(db.consept.ToList()); } // GET: CrudUsuario/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } consept consept = db.consept.Find(id); if (consept == null) { return HttpNotFound(); } return View(consept); } // GET: CrudUsuario/Create public ActionResult Create() { return View(); } // POST: CrudUsuario/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "NumeroIdentificacion,TipoDocumento,Nombre,Fecha")] consept consept) { if (ModelState.IsValid) { db.consept.Add(consept); db.SaveChanges(); return RedirectToAction("Index"); } return View(consept); } // GET: CrudUsuario/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } consept consept = db.consept.Find(id); if (consept == null) { return HttpNotFound(); } return View(consept); } // POST: CrudUsuario/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "NumeroIdentificacion,TipoDocumento,Nombre,Fecha")] consept consept) { if (ModelState.IsValid) { db.Entry(consept).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(consept); } // GET: CrudUsuario/Delete/5 public ActionResult Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } consept consept = db.consept.Find(id); if (consept == null) { return HttpNotFound(); } return View(consept); } // POST: CrudUsuario/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { consept consept = db.consept.Find(id); db.consept.Remove(consept); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>/crudmvc/crudmvc/Scripts/App.js var myApp = angular.module('myApp', []); myApp.controller('mainController', function ($scope,$http) { $http.get('/home/GetDatos') .success(function (result) { $scope.datosr = result; }) .error(function (data) { console.log(data); }); $scope.newdatos = ""; $scope.addDato = function () { $http.post("/home/AddDatos/", { newdatos: $scope.newdatos }) .success(function (result) { $scope.datosr = result; $scope.newdatos = ""; }) .error(function (data) { console.log(data); }); } });<file_sep>/crudmvc/crudmvc/Controllers/HomeController.cs using crudmvc; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace crudmvc.Controllers { public class HomeController : Controller { // GET: Home public ActionResult Index() { return View(); } public JsonResult GetDatos(){ var db = new CrudDBmvcangularEntities(); var datosr = db.datos.ToList(); return Json(datosr, JsonRequestBehavior.AllowGet); } [HttpPost] public JsonResult AddDato(string newdatos) { var db = new CrudDBmvcangularEntities(); db.datos.Add(new dato() { Datos = newdatos }); db.SaveChanges(); var datosr = db.datos.ToList(); return Json(datosr, JsonRequestBehavior.AllowGet); } } }
4e0eb217af898b578ff0ff0c1fe71224a3949588
[ "JavaScript", "C#" ]
10
C#
programalex/.net
553ab7005440d6c58b2a11f8ca1750f3803130a8
f0d59902981f0455d7849810ed28c4bee9c4c1d7
refs/heads/master
<file_sep>#!/bin/sh # Dies ist ein Backup-Script zu einem externen ftp-Server. # der Lösch-Vorgang muss allerdings manuell vom Server aus passieren.! # # # Bereiche, welche gesichert werden sollen: # # /home/* # /root # /var/www # /etc # /var/log # /var/lib # mysql-Datenbanken # /usr/bin #Log erstellen DATE=`date +"%Y%m%d"` LOG=`echo "Backup beginnt als $USER um $DATE"` # Verzeichnisse sichern cd /backup DATE=`date +"%Y%m%d"` mkdir backup_$DATE cd /backup/backup_$DATE tar -cvjf root.tar.bz2 /root >>$LOG tar -cvjf home.tar.bz2 /home >>$LOG tar -cvjf www.tar.bz2 /var/www >>$LOG tar -cvjf etc.tar.bz2 /etc >>$LOG tar -cvjf log.tar.bz2 /var/log >>$LOG tar -cvjf lib.tar.bz2 /var/lib >>$LOG tar -cvjf usr-bin.tar.bz2 /usr/bin >>$LOG # Datenbanken TARGET=/var/backup/mysql IGNORE="phpmyadmin|mysql|information_schema|performance_schema|test" CONF=/etc/mysql/debian.cnf if [ ! -r $CONF ]; then echo "$0 - auf $CONF konnte nicht zugegriffen werden"; exit 1; fi DBS="$(/usr/bin/mysql --defaults-extra-file=$CONF -Bse 'show databases' | /bin/grep -Ev $IGNORE)">>$LOG NOW=$(date +"%Y-%m-%d") for DB in $DBS; do /usr/bin/mysqldump --defaults-extra-file=$CONF --skip-extended-insert --skip-comments $DB >> DB.sql done # Alle Backups komprimieren cd /backup tar -cvjf backup_$DATE.tar.bz2 /backup/backup_$DATE >>$LOG rm -r /backup/backup_$DATE echo "Transfer startet -- $NOW" >>$LOG # ÜBERTRAGUNG AUF EXTERNEN FTP-SERVER ftp -n thisismyhiddenftp.domain.tld <<End-Of-Session user thisismybackupuser "<PASSWORD>" binary put "backup_$DATE.tar.bz2" bye End-Of-Session echo "Ihr Backup ist erfolgreich erstellt" $LOG | mail -s "Backup: erfolgreich" <EMAIL><file_sep># FTP-backup Easy backup script for linux. I created a easy backup script for my linux server. Feel free to push improvements. Run this programm at your own risk!
3a9e28dd4875a7de5b5cb37f91b7d28c621281c3
[ "Markdown", "Shell" ]
2
Shell
plehr/FTP-Backup
ab002810cee46b4bfb285459eb447dd0226811c3
4f36285e002c30afe2b7208ebc267a2e5e61fdfa